index
int64 1
4.82k
| file_id
stringlengths 6
9
| content
stringlengths 240
14.6k
| repo
stringlengths 9
82
| path
stringlengths 8
129
| token_length
int64 72
3.85k
| original_comment
stringlengths 13
1.35k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | prompt
stringlengths 142
14.6k
| Excluded
bool 1
class | file-tokens-Qwen/Qwen2-7B
int64 64
3.93k
| comment-tokens-Qwen/Qwen2-7B
int64 4
476
| file-tokens-bigcode/starcoder2-7b
int64 74
3.98k
| comment-tokens-bigcode/starcoder2-7b
int64 4
458
| file-tokens-google/codegemma-7b
int64 56
3.99k
| comment-tokens-google/codegemma-7b
int64 4
472
| file-tokens-ibm-granite/granite-8b-code-base
int64 74
3.98k
| comment-tokens-ibm-granite/granite-8b-code-base
int64 4
458
| file-tokens-meta-llama/CodeLlama-7b-hf
int64 77
4.07k
| comment-tokens-meta-llama/CodeLlama-7b-hf
int64 4
496
| excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool 2
classes | excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool 2
classes | excluded-based-on-tokenizer-google/codegemma-7b
bool 2
classes | excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool 2
classes | excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool 2
classes | include-for-inference
bool 2
classes |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3,833 | 8390_2 | /*_x000D_
* Copyright (c) 2014, Netherlands Forensic Institute_x000D_
* All rights reserved._x000D_
*/_x000D_
package nl.minvenj.nfi.prnu;_x000D_
_x000D_
import java.awt.color.CMMException;_x000D_
import java.awt.image.BufferedImage;_x000D_
import java.awt.image.ColorModel;_x000D_
import java.io.BufferedInputStream;_x000D_
import java.io.BufferedOutputStream;_x000D_
import java.io.File;_x000D_
import java.io.FileInputStream;_x000D_
import java.io.FileOutputStream;_x000D_
import java.io.IOException;_x000D_
import java.io.InputStream;_x000D_
import java.io.ObjectInputStream;_x000D_
import java.io.ObjectOutputStream;_x000D_
import java.io.OutputStream;_x000D_
_x000D_
import javax.imageio.ImageIO;_x000D_
_x000D_
import nl.minvenj.nfi.prnu.filter.FastNoiseFilter;_x000D_
import nl.minvenj.nfi.prnu.filter.ImageFilter;_x000D_
import nl.minvenj.nfi.prnu.filter.WienerFilter;_x000D_
import nl.minvenj.nfi.prnu.filter.ZeroMeanTotalFilter;_x000D_
_x000D_
public final class PrnuExtract {_x000D_
static final File TESTDATA_FOLDER = new File("testdata");_x000D_
_x000D_
static final File INPUT_FOLDER = new File(TESTDATA_FOLDER, "input");_x000D_
// public static final File INPUT_FILE = new File(INPUT_FOLDER, "test.jpg");_x000D_
public static final File INPUT_FILE = new File("/var/scratch/bwn200/Dresden/2748x3664/Kodak_M1063_4_12664.JPG");_x000D_
static final File EXPECTED_PATTERN_FILE = new File(INPUT_FOLDER, "expected.pat");_x000D_
_x000D_
static final File OUTPUT_FOLDER = new File(TESTDATA_FOLDER, "output");_x000D_
static final File OUTPUT_FILE = new File(OUTPUT_FOLDER, "test.pat");_x000D_
_x000D_
public static void main(final String[] args) throws IOException {_x000D_
long start = System.currentTimeMillis();_x000D_
long end = 0;_x000D_
_x000D_
// Laad de input file in_x000D_
final BufferedImage image = readImage(INPUT_FILE);_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("Load image: " + (end-start) + " ms.");_x000D_
_x000D_
// Zet de input file om in 3 matrices (rood, groen, blauw)_x000D_
start = System.currentTimeMillis();_x000D_
final float[][][] rgbArrays = convertImageToFloatArrays(image);_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("Convert image:" + (end-start) + " ms.");_x000D_
_x000D_
// Bereken van elke matrix het PRNU patroon (extractie stap)_x000D_
start = System.currentTimeMillis();_x000D_
for (int i = 0; i < 3; i++) {_x000D_
extractImage(rgbArrays[i]);_x000D_
}_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("PRNU extracted: " + (end-start) + " ms.");_x000D_
_x000D_
// Schrijf het patroon weg als een Java object_x000D_
writeJavaObject(rgbArrays, OUTPUT_FILE);_x000D_
_x000D_
System.out.println("Pattern written");_x000D_
_x000D_
// Controleer nu het gemaakte bestand_x000D_
final float[][][] expectedPattern = (float[][][]) readJavaObject(EXPECTED_PATTERN_FILE);_x000D_
final float[][][] actualPattern = (float[][][]) readJavaObject(OUTPUT_FILE);_x000D_
for (int i = 0; i < 3; i++) {_x000D_
// Het patroon zoals dat uit PRNU Compare komt, bevat een extra matrix voor transparantie. Deze moeten we overslaan (+1)!_x000D_
compare2DArray(expectedPattern[i + 1], actualPattern[i], 0.0001f);_x000D_
}_x000D_
_x000D_
System.out.println("Validation completed");_x000D_
_x000D_
//This exit is inserted because the program will otherwise hang for a about a minute_x000D_
//most likely explanation for this is the fact that the FFT library spawns a couple_x000D_
//of threads which cannot be properly destroyed_x000D_
System.exit(0);_x000D_
}_x000D_
_x000D_
private static BufferedImage readImage(final File file) throws IOException {_x000D_
final InputStream fileInputStream = new FileInputStream(file);_x000D_
try {_x000D_
final BufferedImage image = ImageIO.read(new BufferedInputStream(fileInputStream));_x000D_
if ((image != null) && (image.getWidth() >= 0) && (image.getHeight() >= 0)) {_x000D_
return image;_x000D_
}_x000D_
}_x000D_
catch (final CMMException e) {_x000D_
// Image file is unsupported or corrupt_x000D_
}_x000D_
catch (final RuntimeException e) {_x000D_
// Internal error processing image file_x000D_
}_x000D_
catch (final IOException e) {_x000D_
// Error reading image from disk_x000D_
}_x000D_
finally {_x000D_
fileInputStream.close();_x000D_
}_x000D_
_x000D_
// Image unreadable or too smalld array_x000D_
return null;_x000D_
}_x000D_
_x000D_
private static float[][][] convertImageToFloatArrays(final BufferedImage image) {_x000D_
final int width = image.getWidth();_x000D_
final int height = image.getHeight();_x000D_
final float[][][] pixels = new float[3][height][width];_x000D_
_x000D_
final ColorModel colorModel = ColorModel.getRGBdefault();_x000D_
for (int y = 0; y < height; y++) {_x000D_
for (int x = 0; x < width; x++) {_x000D_
final int pixel = image.getRGB(x, y); // aa bb gg rr_x000D_
pixels[0][y][x] = colorModel.getRed(pixel);_x000D_
pixels[1][y][x] = colorModel.getGreen(pixel);_x000D_
pixels[2][y][x] = colorModel.getBlue(pixel);_x000D_
}_x000D_
}_x000D_
return pixels;_x000D_
}_x000D_
_x000D_
private static void extractImage(final float[][] pixels) {_x000D_
final int width = pixels[0].length;_x000D_
final int height = pixels.length;_x000D_
_x000D_
long start = System.currentTimeMillis();_x000D_
long end = 0;_x000D_
_x000D_
final ImageFilter fastNoiseFilter = new FastNoiseFilter(width, height);_x000D_
fastNoiseFilter.apply(pixels);_x000D_
_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("Fast Noise Filter: " + (end-start) + " ms.");_x000D_
_x000D_
start = System.currentTimeMillis();_x000D_
final ImageFilter zeroMeanTotalFilter = new ZeroMeanTotalFilter(width, height);_x000D_
zeroMeanTotalFilter.apply(pixels);_x000D_
_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("Zero Mean Filter: " + (end-start) + " ms.");_x000D_
_x000D_
start = System.currentTimeMillis();_x000D_
final ImageFilter wienerFilter = new WienerFilter(width, height);_x000D_
wienerFilter.apply(pixels);_x000D_
_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("Wiener Filter: " + (end-start) + " ms.");_x000D_
}_x000D_
_x000D_
public static Object readJavaObject(final File inputFile) throws IOException {_x000D_
final ObjectInputStream inputStream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(inputFile)));_x000D_
try {_x000D_
return inputStream.readObject();_x000D_
}_x000D_
catch (final ClassNotFoundException e) {_x000D_
throw new IOException("Cannot read pattern: " + inputFile.getAbsolutePath(), e);_x000D_
}_x000D_
finally {_x000D_
inputStream.close();_x000D_
}_x000D_
}_x000D_
_x000D_
private static void writeJavaObject(final Object object, final File outputFile) throws IOException {_x000D_
final OutputStream outputStream = new FileOutputStream(outputFile);_x000D_
try {_x000D_
final ObjectOutputStream objectOutputStream = new ObjectOutputStream(new BufferedOutputStream(outputStream));_x000D_
objectOutputStream.writeObject(object);_x000D_
objectOutputStream.close();_x000D_
}_x000D_
finally {_x000D_
outputStream.close();_x000D_
}_x000D_
}_x000D_
_x000D_
private static boolean compare2DArray(final float[][] expected, final float[][] actual, final float delta) {_x000D_
for (int i = 0; i < expected.length; i++) {_x000D_
for (int j = 0; j < expected[i].length; j++) {_x000D_
if (Math.abs(actual[i][j] - expected[i][j]) > delta) {_x000D_
System.err.println("de waarde op " + i + "," + j + " is " + actual[i][j] + " maar had moeten zijn " + expected[i][j]);_x000D_
return false;_x000D_
}_x000D_
}_x000D_
}_x000D_
return true;_x000D_
}_x000D_
_x000D_
}_x000D_
| nlesc-sherlock/cluster-analysis | prnuextract/src/nl/minvenj/nfi/prnu/PrnuExtract.java | 2,212 | // Laad de input file in_x000D_ | line_comment | nl | /*_x000D_
* Copyright (c) 2014, Netherlands Forensic Institute_x000D_
* All rights reserved._x000D_
*/_x000D_
package nl.minvenj.nfi.prnu;_x000D_
_x000D_
import java.awt.color.CMMException;_x000D_
import java.awt.image.BufferedImage;_x000D_
import java.awt.image.ColorModel;_x000D_
import java.io.BufferedInputStream;_x000D_
import java.io.BufferedOutputStream;_x000D_
import java.io.File;_x000D_
import java.io.FileInputStream;_x000D_
import java.io.FileOutputStream;_x000D_
import java.io.IOException;_x000D_
import java.io.InputStream;_x000D_
import java.io.ObjectInputStream;_x000D_
import java.io.ObjectOutputStream;_x000D_
import java.io.OutputStream;_x000D_
_x000D_
import javax.imageio.ImageIO;_x000D_
_x000D_
import nl.minvenj.nfi.prnu.filter.FastNoiseFilter;_x000D_
import nl.minvenj.nfi.prnu.filter.ImageFilter;_x000D_
import nl.minvenj.nfi.prnu.filter.WienerFilter;_x000D_
import nl.minvenj.nfi.prnu.filter.ZeroMeanTotalFilter;_x000D_
_x000D_
public final class PrnuExtract {_x000D_
static final File TESTDATA_FOLDER = new File("testdata");_x000D_
_x000D_
static final File INPUT_FOLDER = new File(TESTDATA_FOLDER, "input");_x000D_
// public static final File INPUT_FILE = new File(INPUT_FOLDER, "test.jpg");_x000D_
public static final File INPUT_FILE = new File("/var/scratch/bwn200/Dresden/2748x3664/Kodak_M1063_4_12664.JPG");_x000D_
static final File EXPECTED_PATTERN_FILE = new File(INPUT_FOLDER, "expected.pat");_x000D_
_x000D_
static final File OUTPUT_FOLDER = new File(TESTDATA_FOLDER, "output");_x000D_
static final File OUTPUT_FILE = new File(OUTPUT_FOLDER, "test.pat");_x000D_
_x000D_
public static void main(final String[] args) throws IOException {_x000D_
long start = System.currentTimeMillis();_x000D_
long end = 0;_x000D_
_x000D_
// Laad de<SUF>
final BufferedImage image = readImage(INPUT_FILE);_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("Load image: " + (end-start) + " ms.");_x000D_
_x000D_
// Zet de input file om in 3 matrices (rood, groen, blauw)_x000D_
start = System.currentTimeMillis();_x000D_
final float[][][] rgbArrays = convertImageToFloatArrays(image);_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("Convert image:" + (end-start) + " ms.");_x000D_
_x000D_
// Bereken van elke matrix het PRNU patroon (extractie stap)_x000D_
start = System.currentTimeMillis();_x000D_
for (int i = 0; i < 3; i++) {_x000D_
extractImage(rgbArrays[i]);_x000D_
}_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("PRNU extracted: " + (end-start) + " ms.");_x000D_
_x000D_
// Schrijf het patroon weg als een Java object_x000D_
writeJavaObject(rgbArrays, OUTPUT_FILE);_x000D_
_x000D_
System.out.println("Pattern written");_x000D_
_x000D_
// Controleer nu het gemaakte bestand_x000D_
final float[][][] expectedPattern = (float[][][]) readJavaObject(EXPECTED_PATTERN_FILE);_x000D_
final float[][][] actualPattern = (float[][][]) readJavaObject(OUTPUT_FILE);_x000D_
for (int i = 0; i < 3; i++) {_x000D_
// Het patroon zoals dat uit PRNU Compare komt, bevat een extra matrix voor transparantie. Deze moeten we overslaan (+1)!_x000D_
compare2DArray(expectedPattern[i + 1], actualPattern[i], 0.0001f);_x000D_
}_x000D_
_x000D_
System.out.println("Validation completed");_x000D_
_x000D_
//This exit is inserted because the program will otherwise hang for a about a minute_x000D_
//most likely explanation for this is the fact that the FFT library spawns a couple_x000D_
//of threads which cannot be properly destroyed_x000D_
System.exit(0);_x000D_
}_x000D_
_x000D_
private static BufferedImage readImage(final File file) throws IOException {_x000D_
final InputStream fileInputStream = new FileInputStream(file);_x000D_
try {_x000D_
final BufferedImage image = ImageIO.read(new BufferedInputStream(fileInputStream));_x000D_
if ((image != null) && (image.getWidth() >= 0) && (image.getHeight() >= 0)) {_x000D_
return image;_x000D_
}_x000D_
}_x000D_
catch (final CMMException e) {_x000D_
// Image file is unsupported or corrupt_x000D_
}_x000D_
catch (final RuntimeException e) {_x000D_
// Internal error processing image file_x000D_
}_x000D_
catch (final IOException e) {_x000D_
// Error reading image from disk_x000D_
}_x000D_
finally {_x000D_
fileInputStream.close();_x000D_
}_x000D_
_x000D_
// Image unreadable or too smalld array_x000D_
return null;_x000D_
}_x000D_
_x000D_
private static float[][][] convertImageToFloatArrays(final BufferedImage image) {_x000D_
final int width = image.getWidth();_x000D_
final int height = image.getHeight();_x000D_
final float[][][] pixels = new float[3][height][width];_x000D_
_x000D_
final ColorModel colorModel = ColorModel.getRGBdefault();_x000D_
for (int y = 0; y < height; y++) {_x000D_
for (int x = 0; x < width; x++) {_x000D_
final int pixel = image.getRGB(x, y); // aa bb gg rr_x000D_
pixels[0][y][x] = colorModel.getRed(pixel);_x000D_
pixels[1][y][x] = colorModel.getGreen(pixel);_x000D_
pixels[2][y][x] = colorModel.getBlue(pixel);_x000D_
}_x000D_
}_x000D_
return pixels;_x000D_
}_x000D_
_x000D_
private static void extractImage(final float[][] pixels) {_x000D_
final int width = pixels[0].length;_x000D_
final int height = pixels.length;_x000D_
_x000D_
long start = System.currentTimeMillis();_x000D_
long end = 0;_x000D_
_x000D_
final ImageFilter fastNoiseFilter = new FastNoiseFilter(width, height);_x000D_
fastNoiseFilter.apply(pixels);_x000D_
_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("Fast Noise Filter: " + (end-start) + " ms.");_x000D_
_x000D_
start = System.currentTimeMillis();_x000D_
final ImageFilter zeroMeanTotalFilter = new ZeroMeanTotalFilter(width, height);_x000D_
zeroMeanTotalFilter.apply(pixels);_x000D_
_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("Zero Mean Filter: " + (end-start) + " ms.");_x000D_
_x000D_
start = System.currentTimeMillis();_x000D_
final ImageFilter wienerFilter = new WienerFilter(width, height);_x000D_
wienerFilter.apply(pixels);_x000D_
_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("Wiener Filter: " + (end-start) + " ms.");_x000D_
}_x000D_
_x000D_
public static Object readJavaObject(final File inputFile) throws IOException {_x000D_
final ObjectInputStream inputStream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(inputFile)));_x000D_
try {_x000D_
return inputStream.readObject();_x000D_
}_x000D_
catch (final ClassNotFoundException e) {_x000D_
throw new IOException("Cannot read pattern: " + inputFile.getAbsolutePath(), e);_x000D_
}_x000D_
finally {_x000D_
inputStream.close();_x000D_
}_x000D_
}_x000D_
_x000D_
private static void writeJavaObject(final Object object, final File outputFile) throws IOException {_x000D_
final OutputStream outputStream = new FileOutputStream(outputFile);_x000D_
try {_x000D_
final ObjectOutputStream objectOutputStream = new ObjectOutputStream(new BufferedOutputStream(outputStream));_x000D_
objectOutputStream.writeObject(object);_x000D_
objectOutputStream.close();_x000D_
}_x000D_
finally {_x000D_
outputStream.close();_x000D_
}_x000D_
}_x000D_
_x000D_
private static boolean compare2DArray(final float[][] expected, final float[][] actual, final float delta) {_x000D_
for (int i = 0; i < expected.length; i++) {_x000D_
for (int j = 0; j < expected[i].length; j++) {_x000D_
if (Math.abs(actual[i][j] - expected[i][j]) > delta) {_x000D_
System.err.println("de waarde op " + i + "," + j + " is " + actual[i][j] + " maar had moeten zijn " + expected[i][j]);_x000D_
return false;_x000D_
}_x000D_
}_x000D_
}_x000D_
return true;_x000D_
}_x000D_
_x000D_
}_x000D_
| false | 2,837 | 13 | 3,105 | 14 | 3,214 | 14 | 3,105 | 14 | 3,450 | 14 | false | false | false | false | false | true |
1,004 | 110179_0 | package nl.han.ooad.classes;
public class Data {
public Vragenlijst getVragenlijst() {
String[] antwoorden1 = { "11", "elf" };
String[] antwoorden2 = { "Ottawa" };
String juisteAntwoord1 = "Queen";
String[] fouteAntwoorden1 = { "The Beatles", "Coldplay", "ABBA" };
String juisteAntwoord2 = "50";
String[] fouteAntwoorden2 = { "40", "48", "52" };
Vraag[] vragen = {
new OpenVraag("Hoeveel tijdzones zijn er in Rusland", antwoorden1),
new OpenVraag("Hoeveel tijdzones zijn er in Rusland", antwoorden2),
new MeerkeuzeVraag("Welke band staat het vaakst in de Top 2000 van 2022", juisteAntwoord1,
fouteAntwoorden1),
new MeerkeuzeVraag("Uit hoeveel staten bestaan de Verenigde Staten", juisteAntwoord2, fouteAntwoorden2)
};
return new Vragenlijst(vragen);
}
}
/*
*
* Open vragen:
* 1)
* Vraag: Hoeveel tijdzones zijn er in Rusland?
* Antwoord: 11
*
* 2)
* Vraag: Wat is de hoofdstad van Canada?
* Antwoord: Ottawa
*
* Meerkeuze vragen:
* 3)
* Vraag: Welke band staat het vaakst in de Top 2000 van 2022?
* A: The Beatles (fout)
* B: coldplay (fout)
* C: Queen (goed)
* D: ABBA (fout)
*
* 4)
* Vraag: Uit hoeveel staten bestaan de Verenigde Staten?
* A: 40 (fout)
* B: 48 (fout)
* C: 50 (goed)
* D: 52 (fout)
*/ | MAGerritsen/finch | finch/src/main/java/nl/han/ooad/classes/Data.java | 526 | /*
*
* Open vragen:
* 1)
* Vraag: Hoeveel tijdzones zijn er in Rusland?
* Antwoord: 11
*
* 2)
* Vraag: Wat is de hoofdstad van Canada?
* Antwoord: Ottawa
*
* Meerkeuze vragen:
* 3)
* Vraag: Welke band staat het vaakst in de Top 2000 van 2022?
* A: The Beatles (fout)
* B: coldplay (fout)
* C: Queen (goed)
* D: ABBA (fout)
*
* 4)
* Vraag: Uit hoeveel staten bestaan de Verenigde Staten?
* A: 40 (fout)
* B: 48 (fout)
* C: 50 (goed)
* D: 52 (fout)
*/ | block_comment | nl | package nl.han.ooad.classes;
public class Data {
public Vragenlijst getVragenlijst() {
String[] antwoorden1 = { "11", "elf" };
String[] antwoorden2 = { "Ottawa" };
String juisteAntwoord1 = "Queen";
String[] fouteAntwoorden1 = { "The Beatles", "Coldplay", "ABBA" };
String juisteAntwoord2 = "50";
String[] fouteAntwoorden2 = { "40", "48", "52" };
Vraag[] vragen = {
new OpenVraag("Hoeveel tijdzones zijn er in Rusland", antwoorden1),
new OpenVraag("Hoeveel tijdzones zijn er in Rusland", antwoorden2),
new MeerkeuzeVraag("Welke band staat het vaakst in de Top 2000 van 2022", juisteAntwoord1,
fouteAntwoorden1),
new MeerkeuzeVraag("Uit hoeveel staten bestaan de Verenigde Staten", juisteAntwoord2, fouteAntwoorden2)
};
return new Vragenlijst(vragen);
}
}
/*
*
* Open vragen:
<SUF>*/ | false | 485 | 200 | 582 | 248 | 466 | 205 | 582 | 248 | 586 | 236 | true | true | true | true | true | false |
1 | 18424_13 | package com.example.idek;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraX;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageAnalysisConfig;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureConfig;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.core.PreviewConfig;
import androidx.lifecycle.LifecycleOwner;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.util.Rational;
import android.util.Size;
import android.view.TextureView;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.nio.ByteBuffer;
//ik haat mijzelf dus daarom maak ik een camera ding met een api dat nog niet eens in de beta stage is
//en waarvan de tutorial in een taal is dat ik 0% begrijp
//saus: https://codelabs.developers.google.com/codelabs/camerax-getting-started/
public class MainActivity extends AppCompatActivity {
//private int REQUEST_CODE_PERMISSIONS = 10; //idek volgens tutorial is dit een arbitraire nummer zou helpen als je app meerdere toestimmingen vraagt
//private final String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA"}; //array met permissions vermeld in manifest
TextureView txView;
String result = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txView = findViewById(R.id.view_finder);
startCamera();
/*if(allPermissionsGranted()){
} else{
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}*/
}
private void startCamera() {//heel veel dingen gebeuren hier
//eerst zeker zijn dat de camera niet gebruikt wordt.
CameraX.unbindAll();
/* doe preview weergeven */
int aspRatioW = txView.getWidth(); //haalt breedte scherm op
int aspRatioH = txView.getHeight(); //haalt hoogte scherm op
Rational asp = new Rational (aspRatioW, aspRatioH); //helpt bij zetten aspect ratio
Size screen = new Size(aspRatioW, aspRatioH); //grootte scherm ofc
PreviewConfig pConfig = new PreviewConfig.Builder().setTargetAspectRatio(asp).setTargetResolution(screen).build();
Preview pview = new Preview(pConfig);
pview.setOnPreviewOutputUpdateListener(
new Preview.OnPreviewOutputUpdateListener() {
//eigenlijk maakt dit al een nieuwe texturesurface aan
//maar aangezien ik al eentje heb gemaakt aan het begin...
@Override
public void onUpdated(Preview.PreviewOutput output){
ViewGroup parent = (ViewGroup) txView.getParent();
parent.removeView(txView); //moeten wij hem eerst yeeten
parent.addView(txView, 0);
txView.setSurfaceTexture(output.getSurfaceTexture()); //dan weer toevoegen
//updateTransform(); //en dan updaten
}
});
/* image capture */
/*ImageCaptureConfig imgConfig = new ImageCaptureConfig.Builder().setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY).setTargetRotation(getWindowManager().getDefaultDisplay().getRotation()).build();
ImageCapture imgCap = new ImageCapture(imgConfig);*/
/* image analyser */
ImageAnalysisConfig imgAConfig = new ImageAnalysisConfig.Builder().setImageReaderMode(ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE).build();
final ImageAnalysis imgAsys = new ImageAnalysis(imgAConfig);
imgAsys.setAnalyzer(
new ImageAnalysis.Analyzer(){
@Override
public void analyze(ImageProxy image, int rotationDegrees){
try {
ByteBuffer bf = image.getPlanes()[0].getBuffer();
byte[] b = new byte[bf.capacity()];
bf.get(b);
Rect r = image.getCropRect();
int w = image.getWidth();
int h = image.getHeight();
PlanarYUVLuminanceSource sauce = new PlanarYUVLuminanceSource(b ,w, h, r.left, r.top, r.width(), r.height(),false);
BinaryBitmap bit = new BinaryBitmap(new HybridBinarizer(sauce));
result = new qrReader().decoded(bit);
System.out.println(result);
Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
Log.wtf("F: ", result);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
}
}
}
);
//bindt de shit hierboven aan de lifecycle:
CameraX.bindToLifecycle((LifecycleOwner)this, imgAsys, /*imgCap,*/ pview);
}
/*private void updateTransform(){
//compenseert veranderingen in orientatie voor viewfinder, aangezien de rest van de layout in portrait mode blijft.
//methinks :thonk:
Matrix mx = new Matrix();
float w = txView.getMeasuredWidth();
float h = txView.getMeasuredHeight();
//berekent het midden
float cX = w / 2f;
float cY = h / 2f;
int rotDgr; //voor de switch < propt in hoeveel graden shit is gekanteld
//Display a = txView.getDisplay(); //ok dan stoppen wij .getdisplay in z'n eigen shit.
int rtrn = (int)txView.getRotation(); //dan dit maar in een aparte int zetten want alles deed boem bij het opstarten
//omfg het komt omdat .getDisplay erin zit.
switch(rtrn){
case Surface.ROTATION_0:
rotDgr = 0;
break;
case Surface.ROTATION_90:
rotDgr = 90;
break;
case Surface.ROTATION_180:
rotDgr = 180;
break;
case Surface.ROTATION_270:
rotDgr = 270;
break;
default:
return;
}
mx.postRotate((float)rotDgr, cX, cY); //berekent preview out put aan de hand van hoe de toestel gedraaid is
float buffer = txView.getMeasuredHeight() / txView.getMeasuredWidth() ;
int scaleW;
int scaleH;
if(w > h){ //center-crop transformation
scaleH = (int)w;
scaleW = Math.round(w * buffer);
} else{
scaleH = (int)h;
scaleW = Math.round(h * buffer);
}
float x = scaleW / w; //doet schaal berekenen
float y = scaleH / h;
mx.preScale(x, y, cX, cY); //vult preview op
txView.setTransform(mx); //past dit op preview toe
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//als alle permissies zijn toegestaan start camera
if(requestCode == REQUEST_CODE_PERMISSIONS){
if(allPermissionsGranted()){
startCamera();
} else{
Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private boolean allPermissionsGranted(){
//kijken of alle permissies zijn toegestaan
for(String permission : REQUIRED_PERMISSIONS){
if(ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED){
return false;
}
}
return true;
}*/
}
| 0974201/code-bin | java/backup camerax proj.java | 2,322 | //maar aangezien ik al eentje heb gemaakt aan het begin... | line_comment | nl | package com.example.idek;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraX;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageAnalysisConfig;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureConfig;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.core.PreviewConfig;
import androidx.lifecycle.LifecycleOwner;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.util.Rational;
import android.util.Size;
import android.view.TextureView;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.nio.ByteBuffer;
//ik haat mijzelf dus daarom maak ik een camera ding met een api dat nog niet eens in de beta stage is
//en waarvan de tutorial in een taal is dat ik 0% begrijp
//saus: https://codelabs.developers.google.com/codelabs/camerax-getting-started/
public class MainActivity extends AppCompatActivity {
//private int REQUEST_CODE_PERMISSIONS = 10; //idek volgens tutorial is dit een arbitraire nummer zou helpen als je app meerdere toestimmingen vraagt
//private final String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA"}; //array met permissions vermeld in manifest
TextureView txView;
String result = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txView = findViewById(R.id.view_finder);
startCamera();
/*if(allPermissionsGranted()){
} else{
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}*/
}
private void startCamera() {//heel veel dingen gebeuren hier
//eerst zeker zijn dat de camera niet gebruikt wordt.
CameraX.unbindAll();
/* doe preview weergeven */
int aspRatioW = txView.getWidth(); //haalt breedte scherm op
int aspRatioH = txView.getHeight(); //haalt hoogte scherm op
Rational asp = new Rational (aspRatioW, aspRatioH); //helpt bij zetten aspect ratio
Size screen = new Size(aspRatioW, aspRatioH); //grootte scherm ofc
PreviewConfig pConfig = new PreviewConfig.Builder().setTargetAspectRatio(asp).setTargetResolution(screen).build();
Preview pview = new Preview(pConfig);
pview.setOnPreviewOutputUpdateListener(
new Preview.OnPreviewOutputUpdateListener() {
//eigenlijk maakt dit al een nieuwe texturesurface aan
//maar aangezien<SUF>
@Override
public void onUpdated(Preview.PreviewOutput output){
ViewGroup parent = (ViewGroup) txView.getParent();
parent.removeView(txView); //moeten wij hem eerst yeeten
parent.addView(txView, 0);
txView.setSurfaceTexture(output.getSurfaceTexture()); //dan weer toevoegen
//updateTransform(); //en dan updaten
}
});
/* image capture */
/*ImageCaptureConfig imgConfig = new ImageCaptureConfig.Builder().setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY).setTargetRotation(getWindowManager().getDefaultDisplay().getRotation()).build();
ImageCapture imgCap = new ImageCapture(imgConfig);*/
/* image analyser */
ImageAnalysisConfig imgAConfig = new ImageAnalysisConfig.Builder().setImageReaderMode(ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE).build();
final ImageAnalysis imgAsys = new ImageAnalysis(imgAConfig);
imgAsys.setAnalyzer(
new ImageAnalysis.Analyzer(){
@Override
public void analyze(ImageProxy image, int rotationDegrees){
try {
ByteBuffer bf = image.getPlanes()[0].getBuffer();
byte[] b = new byte[bf.capacity()];
bf.get(b);
Rect r = image.getCropRect();
int w = image.getWidth();
int h = image.getHeight();
PlanarYUVLuminanceSource sauce = new PlanarYUVLuminanceSource(b ,w, h, r.left, r.top, r.width(), r.height(),false);
BinaryBitmap bit = new BinaryBitmap(new HybridBinarizer(sauce));
result = new qrReader().decoded(bit);
System.out.println(result);
Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
Log.wtf("F: ", result);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
}
}
}
);
//bindt de shit hierboven aan de lifecycle:
CameraX.bindToLifecycle((LifecycleOwner)this, imgAsys, /*imgCap,*/ pview);
}
/*private void updateTransform(){
//compenseert veranderingen in orientatie voor viewfinder, aangezien de rest van de layout in portrait mode blijft.
//methinks :thonk:
Matrix mx = new Matrix();
float w = txView.getMeasuredWidth();
float h = txView.getMeasuredHeight();
//berekent het midden
float cX = w / 2f;
float cY = h / 2f;
int rotDgr; //voor de switch < propt in hoeveel graden shit is gekanteld
//Display a = txView.getDisplay(); //ok dan stoppen wij .getdisplay in z'n eigen shit.
int rtrn = (int)txView.getRotation(); //dan dit maar in een aparte int zetten want alles deed boem bij het opstarten
//omfg het komt omdat .getDisplay erin zit.
switch(rtrn){
case Surface.ROTATION_0:
rotDgr = 0;
break;
case Surface.ROTATION_90:
rotDgr = 90;
break;
case Surface.ROTATION_180:
rotDgr = 180;
break;
case Surface.ROTATION_270:
rotDgr = 270;
break;
default:
return;
}
mx.postRotate((float)rotDgr, cX, cY); //berekent preview out put aan de hand van hoe de toestel gedraaid is
float buffer = txView.getMeasuredHeight() / txView.getMeasuredWidth() ;
int scaleW;
int scaleH;
if(w > h){ //center-crop transformation
scaleH = (int)w;
scaleW = Math.round(w * buffer);
} else{
scaleH = (int)h;
scaleW = Math.round(h * buffer);
}
float x = scaleW / w; //doet schaal berekenen
float y = scaleH / h;
mx.preScale(x, y, cX, cY); //vult preview op
txView.setTransform(mx); //past dit op preview toe
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//als alle permissies zijn toegestaan start camera
if(requestCode == REQUEST_CODE_PERMISSIONS){
if(allPermissionsGranted()){
startCamera();
} else{
Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private boolean allPermissionsGranted(){
//kijken of alle permissies zijn toegestaan
for(String permission : REQUIRED_PERMISSIONS){
if(ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED){
return false;
}
}
return true;
}*/
}
| false | 1,724 | 19 | 1,945 | 21 | 1,962 | 15 | 1,941 | 21 | 2,321 | 20 | false | false | false | false | false | true |
4,243 | 26668_1 | public class Dossier {_x000D_
private String vluchtelingId;_x000D_
private boolean paspoortGetoond;_x000D_
private boolean asielAanvraagCompleet;_x000D_
private boolean rechterToegewezen;_x000D_
private boolean uitspraakRechter;_x000D_
private boolean toegelatenTotSamenleving;_x000D_
private boolean terugkeerNaarLandVanHerkomst;_x000D_
_x000D_
public Dossier(String vluchtelingId,boolean paspoortGetoond,boolean asielAanvraagCompleet ,boolean rechterToegewezen, boolean uitspraakRechter, boolean toegelatenTotSamenleving, boolean terugkeerNaarLandVanHerkomst) {_x000D_
// Standaard waarden instellen_x000D_
this.vluchtelingId= vluchtelingId;_x000D_
this.paspoortGetoond = false;_x000D_
this.asielAanvraagCompleet = false;_x000D_
this.rechterToegewezen = false;_x000D_
this.uitspraakRechter = false;_x000D_
this.toegelatenTotSamenleving = false;_x000D_
this.terugkeerNaarLandVanHerkomst = false;_x000D_
}_x000D_
_x000D_
_x000D_
// Getters en setters voor de variabelen_x000D_
public String getVluchtelingId(){_x000D_
return vluchtelingId;_x000D_
}_x000D_
public boolean isPaspoortGetoond() {_x000D_
return paspoortGetoond;_x000D_
}_x000D_
_x000D_
public void setPaspoortGetoond(boolean paspoortGetoond) {_x000D_
this.paspoortGetoond = paspoortGetoond;_x000D_
}_x000D_
_x000D_
public boolean isAsielAanvraagCompleet() {_x000D_
return asielAanvraagCompleet;_x000D_
}_x000D_
_x000D_
public void setAsielAanvraagCompleet(boolean asielAanvraagCompleet) {_x000D_
this.asielAanvraagCompleet = asielAanvraagCompleet;_x000D_
}_x000D_
_x000D_
public boolean isRechterToegewezen() {_x000D_
return rechterToegewezen;_x000D_
}_x000D_
_x000D_
public void setRechterToegewezen(boolean rechterToegewezen) {_x000D_
this.rechterToegewezen = rechterToegewezen;_x000D_
}_x000D_
_x000D_
public boolean isUitspraakRechter() {_x000D_
return uitspraakRechter;_x000D_
}_x000D_
_x000D_
public void setUitspraakRechter(boolean uitspraakRechter) {_x000D_
this.uitspraakRechter = uitspraakRechter;_x000D_
}_x000D_
_x000D_
public boolean isToegelatenTotSamenleving() {_x000D_
return toegelatenTotSamenleving;_x000D_
}_x000D_
_x000D_
public void setToegelatenTotSamenleving(boolean toegelatenTotSamenleving) {_x000D_
this.toegelatenTotSamenleving = toegelatenTotSamenleving;_x000D_
}_x000D_
_x000D_
public boolean isTerugkeerNaarLandVanHerkomst() {_x000D_
return terugkeerNaarLandVanHerkomst;_x000D_
}_x000D_
_x000D_
public void setTerugkeerNaarLandVanHerkomst(boolean terugkeerNaarLandVanHerkomst) {_x000D_
this.terugkeerNaarLandVanHerkomst = terugkeerNaarLandVanHerkomst;_x000D_
}_x000D_
_x000D_
@Override_x000D_
public String toString() {_x000D_
return String.format("Paspoort Getoond: %b, Asielaanvraag Compleet: %b, Rechter Toegewezen: %b, Uitspraak Rechter: %b, Toegelaten Tot Samenleving: %b, Terugkeer Naar Land Van Herkomst: %b, VluvhtelingID: %s",_x000D_
paspoortGetoond, asielAanvraagCompleet, rechterToegewezen, uitspraakRechter, toegelatenTotSamenleving, terugkeerNaarLandVanHerkomst, vluchtelingId);_x000D_
}_x000D_
}_x000D_
| samuel2597/Portefolio-2 | Dossier.java | 1,029 | // Getters en setters voor de variabelen_x000D_ | line_comment | nl | public class Dossier {_x000D_
private String vluchtelingId;_x000D_
private boolean paspoortGetoond;_x000D_
private boolean asielAanvraagCompleet;_x000D_
private boolean rechterToegewezen;_x000D_
private boolean uitspraakRechter;_x000D_
private boolean toegelatenTotSamenleving;_x000D_
private boolean terugkeerNaarLandVanHerkomst;_x000D_
_x000D_
public Dossier(String vluchtelingId,boolean paspoortGetoond,boolean asielAanvraagCompleet ,boolean rechterToegewezen, boolean uitspraakRechter, boolean toegelatenTotSamenleving, boolean terugkeerNaarLandVanHerkomst) {_x000D_
// Standaard waarden instellen_x000D_
this.vluchtelingId= vluchtelingId;_x000D_
this.paspoortGetoond = false;_x000D_
this.asielAanvraagCompleet = false;_x000D_
this.rechterToegewezen = false;_x000D_
this.uitspraakRechter = false;_x000D_
this.toegelatenTotSamenleving = false;_x000D_
this.terugkeerNaarLandVanHerkomst = false;_x000D_
}_x000D_
_x000D_
_x000D_
// Getters en<SUF>
public String getVluchtelingId(){_x000D_
return vluchtelingId;_x000D_
}_x000D_
public boolean isPaspoortGetoond() {_x000D_
return paspoortGetoond;_x000D_
}_x000D_
_x000D_
public void setPaspoortGetoond(boolean paspoortGetoond) {_x000D_
this.paspoortGetoond = paspoortGetoond;_x000D_
}_x000D_
_x000D_
public boolean isAsielAanvraagCompleet() {_x000D_
return asielAanvraagCompleet;_x000D_
}_x000D_
_x000D_
public void setAsielAanvraagCompleet(boolean asielAanvraagCompleet) {_x000D_
this.asielAanvraagCompleet = asielAanvraagCompleet;_x000D_
}_x000D_
_x000D_
public boolean isRechterToegewezen() {_x000D_
return rechterToegewezen;_x000D_
}_x000D_
_x000D_
public void setRechterToegewezen(boolean rechterToegewezen) {_x000D_
this.rechterToegewezen = rechterToegewezen;_x000D_
}_x000D_
_x000D_
public boolean isUitspraakRechter() {_x000D_
return uitspraakRechter;_x000D_
}_x000D_
_x000D_
public void setUitspraakRechter(boolean uitspraakRechter) {_x000D_
this.uitspraakRechter = uitspraakRechter;_x000D_
}_x000D_
_x000D_
public boolean isToegelatenTotSamenleving() {_x000D_
return toegelatenTotSamenleving;_x000D_
}_x000D_
_x000D_
public void setToegelatenTotSamenleving(boolean toegelatenTotSamenleving) {_x000D_
this.toegelatenTotSamenleving = toegelatenTotSamenleving;_x000D_
}_x000D_
_x000D_
public boolean isTerugkeerNaarLandVanHerkomst() {_x000D_
return terugkeerNaarLandVanHerkomst;_x000D_
}_x000D_
_x000D_
public void setTerugkeerNaarLandVanHerkomst(boolean terugkeerNaarLandVanHerkomst) {_x000D_
this.terugkeerNaarLandVanHerkomst = terugkeerNaarLandVanHerkomst;_x000D_
}_x000D_
_x000D_
@Override_x000D_
public String toString() {_x000D_
return String.format("Paspoort Getoond: %b, Asielaanvraag Compleet: %b, Rechter Toegewezen: %b, Uitspraak Rechter: %b, Toegelaten Tot Samenleving: %b, Terugkeer Naar Land Van Herkomst: %b, VluvhtelingID: %s",_x000D_
paspoortGetoond, asielAanvraagCompleet, rechterToegewezen, uitspraakRechter, toegelatenTotSamenleving, terugkeerNaarLandVanHerkomst, vluchtelingId);_x000D_
}_x000D_
}_x000D_
| false | 1,385 | 16 | 1,463 | 18 | 1,356 | 16 | 1,463 | 18 | 1,558 | 18 | false | false | false | false | false | true |
3,785 | 83494_1 | package be.thomasmore.party.controllers;
import be.thomasmore.party.model.Client;
import be.thomasmore.party.repositories.ClientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.time.LocalDateTime;
import java.util.Optional;
import static java.time.LocalDateTime.now;
@Controller
public class ClientController {
@Autowired
ClientRepository clientRepository;
@GetMapping("/clienthome")
public String home(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
}
return "clienthome";
}
@GetMapping("/clientgreeting")
public String clientGreeting(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
final Client client = clientFromDb.get();
String message = "%s %s%s%s".formatted(
getGreeting(),
getPrefix(client),
client.getName(),
getPostfix(client));
model.addAttribute("message", message);
}
return "clientgreeting";
}
@GetMapping("/clientdetails")
public String clientDetails(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
final Client client = clientFromDb.get();
model.addAttribute("client", client);
model.addAttribute("discount", calculateDiscount(client));
}
return "clientdetails";
}
private String getPrefix(Client client) {
if (client.getNrOfOrders() < 10) return "";
if (client.getNrOfOrders() < 50) return "beste ";
return "allerliefste ";
}
private String getGreeting() {
LocalDateTime now = now();
//LocalDateTime now = LocalDateTime.parse("2023-09-23T17:15"); //for test purposes
//NOTE: dit is de meest naieve manier om iets te testen. Volgend jaar zien we daar meer over.
if (now.getHour() < 6) return "Goedenacht";
if (now.getHour() < 12) return "Goedemorgen";
if (now.getHour() < 17) return "Goedemiddag";
if (now.getHour() < 22) return "Goedenavond";
return "Goedenacht";
}
private String getPostfix(Client client) {
if (client.getNrOfOrders() == 0) return ", en welkom!";
if (client.getNrOfOrders() >= 80) return ", jij bent een topper!";
return "";
}
private double calculateDiscount(Client client) {
if (client.getTotalAmount() < 50) return 0;
return client.getTotalAmount() / 200;
}
} | neeraj543/Toets-1 | src/main/java/be/thomasmore/party/controllers/ClientController.java | 806 | //NOTE: dit is de meest naieve manier om iets te testen. Volgend jaar zien we daar meer over. | line_comment | nl | package be.thomasmore.party.controllers;
import be.thomasmore.party.model.Client;
import be.thomasmore.party.repositories.ClientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.time.LocalDateTime;
import java.util.Optional;
import static java.time.LocalDateTime.now;
@Controller
public class ClientController {
@Autowired
ClientRepository clientRepository;
@GetMapping("/clienthome")
public String home(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
}
return "clienthome";
}
@GetMapping("/clientgreeting")
public String clientGreeting(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
final Client client = clientFromDb.get();
String message = "%s %s%s%s".formatted(
getGreeting(),
getPrefix(client),
client.getName(),
getPostfix(client));
model.addAttribute("message", message);
}
return "clientgreeting";
}
@GetMapping("/clientdetails")
public String clientDetails(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
final Client client = clientFromDb.get();
model.addAttribute("client", client);
model.addAttribute("discount", calculateDiscount(client));
}
return "clientdetails";
}
private String getPrefix(Client client) {
if (client.getNrOfOrders() < 10) return "";
if (client.getNrOfOrders() < 50) return "beste ";
return "allerliefste ";
}
private String getGreeting() {
LocalDateTime now = now();
//LocalDateTime now = LocalDateTime.parse("2023-09-23T17:15"); //for test purposes
//NOTE: dit<SUF>
if (now.getHour() < 6) return "Goedenacht";
if (now.getHour() < 12) return "Goedemorgen";
if (now.getHour() < 17) return "Goedemiddag";
if (now.getHour() < 22) return "Goedenavond";
return "Goedenacht";
}
private String getPostfix(Client client) {
if (client.getNrOfOrders() == 0) return ", en welkom!";
if (client.getNrOfOrders() >= 80) return ", jij bent een topper!";
return "";
}
private double calculateDiscount(Client client) {
if (client.getTotalAmount() < 50) return 0;
return client.getTotalAmount() / 200;
}
} | false | 628 | 27 | 717 | 32 | 750 | 24 | 717 | 32 | 839 | 31 | false | false | false | false | false | true |
1,563 | 162774_5 | package nl.vanlaar.bart.topid.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import nl.vanlaar.bart.topid.Model.Comment;
import nl.vanlaar.bart.topid.Model.Idee;
import nl.vanlaar.bart.topid.Model.IdeeënLijst;
import nl.vanlaar.bart.topid.R;
import nl.vanlaar.bart.topid.View.ReactiesAdapter;
/**
* De reageer activity laat de gebruiker een reactie plaatsen op een idee
*/
public class ReageerActivity extends AppCompatActivity {
private Button btPlaatsReactie;
private EditText etReactie;
private Comment comment = new Comment();
private ArrayList<Idee> ideeënLijst;
private Idee idee;
private ArrayList<Comment> commentList;
private ListView lv;
private ReactiesAdapter reactiesAdapter;
private ImageView backArrow;
private ListView commentListView;
private int ideePositieIdee;
private int ideePositieKlacht;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reageer);
//idee en ideeënlijst vullen
ideePositieIdee = getIntent().getIntExtra(ShowIdeeActivity.EXTRA_IDEE,-1);
ideePositieKlacht = getIntent().getIntExtra(ShowIdeeActivity.EXTRA_KLACHT,-1);
/*
laden van dummy data
*/
if(ideePositieIdee>-1){
ideeënLijst = IdeeënLijst.getInstance().getIdeeën();
idee = ideeënLijst.get(ideePositieIdee);
} else if (ideePositieKlacht > -1) {
ideeënLijst = IdeeënLijst.getInstance().getKlachten();
idee = ideeënLijst.get(ideePositieKlacht);
}
//commentlist vullen, sanity check voor als die list nog niet gemaakt is.
if(commentList != null) {
commentList = idee.getComments();
} else {
idee.createCommentList();
commentList = idee.getComments();
}
//kopellen aan views
btPlaatsReactie = (Button) findViewById(R.id.btPlaats_reactie);
etReactie = (EditText) findViewById(R.id.et_reageer_text);
backArrow = (ImageView) findViewById(R.id.iv_reageren_toolbar_backbutton);
commentListView = (ListView) findViewById(R.id.lvReacties_showIdee);
//adapter configuratie
reactiesAdapter = new ReactiesAdapter(this, commentList);
commentListView.setAdapter(reactiesAdapter);
//als de terug knop wordt ingedrukt ga dan naar de vorige activity
backArrow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
//onclicklisnter voor de post knop
btPlaatsReactie.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//als er nog velden leeg zijn laat dat aan de user zien
if (TextUtils.isEmpty(etReactie.getText())) {
Toast toast = Toast.makeText(getApplicationContext(), "U mag geen lege reactie plaatsen", Toast.LENGTH_SHORT);
toast.show();
return;
//maak een comment, vul hem met de velden en voeg hem toe aan een idee
} else {
comment = new Comment(MainActivity.LOGGED_IN_USER.getName(), etReactie.getText().toString(), MainActivity.LOGGED_IN_USER.getTempImage(), MainActivity.LOGGED_IN_USER);
commentList.add(comment);
reactiesAdapter.notifyDataSetChanged();
Toast toast = Toast.makeText(getApplicationContext(), "Uw Reactie is geplaatst", Toast.LENGTH_SHORT);
toast.show();
etReactie.setText("");
}
}
});
}
}
| SaxionHBO-ICT/topicus-ict-solutions-deventer | TopID/app/src/main/java/nl/vanlaar/bart/topid/Activity/ReageerActivity.java | 1,261 | //als de terug knop wordt ingedrukt ga dan naar de vorige activity | line_comment | nl | package nl.vanlaar.bart.topid.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import nl.vanlaar.bart.topid.Model.Comment;
import nl.vanlaar.bart.topid.Model.Idee;
import nl.vanlaar.bart.topid.Model.IdeeënLijst;
import nl.vanlaar.bart.topid.R;
import nl.vanlaar.bart.topid.View.ReactiesAdapter;
/**
* De reageer activity laat de gebruiker een reactie plaatsen op een idee
*/
public class ReageerActivity extends AppCompatActivity {
private Button btPlaatsReactie;
private EditText etReactie;
private Comment comment = new Comment();
private ArrayList<Idee> ideeënLijst;
private Idee idee;
private ArrayList<Comment> commentList;
private ListView lv;
private ReactiesAdapter reactiesAdapter;
private ImageView backArrow;
private ListView commentListView;
private int ideePositieIdee;
private int ideePositieKlacht;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reageer);
//idee en ideeënlijst vullen
ideePositieIdee = getIntent().getIntExtra(ShowIdeeActivity.EXTRA_IDEE,-1);
ideePositieKlacht = getIntent().getIntExtra(ShowIdeeActivity.EXTRA_KLACHT,-1);
/*
laden van dummy data
*/
if(ideePositieIdee>-1){
ideeënLijst = IdeeënLijst.getInstance().getIdeeën();
idee = ideeënLijst.get(ideePositieIdee);
} else if (ideePositieKlacht > -1) {
ideeënLijst = IdeeënLijst.getInstance().getKlachten();
idee = ideeënLijst.get(ideePositieKlacht);
}
//commentlist vullen, sanity check voor als die list nog niet gemaakt is.
if(commentList != null) {
commentList = idee.getComments();
} else {
idee.createCommentList();
commentList = idee.getComments();
}
//kopellen aan views
btPlaatsReactie = (Button) findViewById(R.id.btPlaats_reactie);
etReactie = (EditText) findViewById(R.id.et_reageer_text);
backArrow = (ImageView) findViewById(R.id.iv_reageren_toolbar_backbutton);
commentListView = (ListView) findViewById(R.id.lvReacties_showIdee);
//adapter configuratie
reactiesAdapter = new ReactiesAdapter(this, commentList);
commentListView.setAdapter(reactiesAdapter);
//als de<SUF>
backArrow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
//onclicklisnter voor de post knop
btPlaatsReactie.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//als er nog velden leeg zijn laat dat aan de user zien
if (TextUtils.isEmpty(etReactie.getText())) {
Toast toast = Toast.makeText(getApplicationContext(), "U mag geen lege reactie plaatsen", Toast.LENGTH_SHORT);
toast.show();
return;
//maak een comment, vul hem met de velden en voeg hem toe aan een idee
} else {
comment = new Comment(MainActivity.LOGGED_IN_USER.getName(), etReactie.getText().toString(), MainActivity.LOGGED_IN_USER.getTempImage(), MainActivity.LOGGED_IN_USER);
commentList.add(comment);
reactiesAdapter.notifyDataSetChanged();
Toast toast = Toast.makeText(getApplicationContext(), "Uw Reactie is geplaatst", Toast.LENGTH_SHORT);
toast.show();
etReactie.setText("");
}
}
});
}
}
| false | 913 | 19 | 1,066 | 20 | 1,044 | 15 | 1,066 | 20 | 1,203 | 18 | false | false | false | false | false | true |
880 | 156331_6 | /*_x000D_
* Copyright (c) 2014, Netherlands Forensic Institute_x000D_
* All rights reserved._x000D_
*/_x000D_
package nl.minvenj.nfi.common_source_identification;_x000D_
_x000D_
import java.awt.color.CMMException;_x000D_
import java.awt.image.BufferedImage;_x000D_
import java.awt.image.ColorModel;_x000D_
import java.io.BufferedInputStream;_x000D_
import java.io.BufferedOutputStream;_x000D_
import java.io.File;_x000D_
import java.io.FileInputStream;_x000D_
import java.io.FileOutputStream;_x000D_
import java.io.IOException;_x000D_
import java.io.InputStream;_x000D_
import java.io.ObjectInputStream;_x000D_
import java.io.ObjectOutputStream;_x000D_
import java.io.OutputStream;_x000D_
_x000D_
import javax.imageio.ImageIO;_x000D_
_x000D_
import nl.minvenj.nfi.common_source_identification.filter.FastNoiseFilter;_x000D_
import nl.minvenj.nfi.common_source_identification.filter.ImageFilter;_x000D_
import nl.minvenj.nfi.common_source_identification.filter.WienerFilter;_x000D_
import nl.minvenj.nfi.common_source_identification.filter.ZeroMeanTotalFilter;_x000D_
_x000D_
public final class CommonSourceIdentification {_x000D_
static final File TESTDATA_FOLDER = new File("testdata");_x000D_
_x000D_
static final File INPUT_FOLDER = new File(TESTDATA_FOLDER, "input");_x000D_
// public static final File INPUT_FILE = new File(INPUT_FOLDER, "test.jpg");_x000D_
public static final File INPUT_FILE = new File("/var/scratch/bwn200/Dresden/2748x3664/Kodak_M1063_4_12664.JPG");_x000D_
static final File EXPECTED_PATTERN_FILE = new File(INPUT_FOLDER, "expected.pat");_x000D_
_x000D_
static final File OUTPUT_FOLDER = new File(TESTDATA_FOLDER, "output");_x000D_
static final File OUTPUT_FILE = new File(OUTPUT_FOLDER, "test.pat");_x000D_
_x000D_
public static void main(final String[] args) throws IOException {_x000D_
long start = System.currentTimeMillis();_x000D_
long end = 0;_x000D_
_x000D_
// Laad de input file in_x000D_
final BufferedImage image = readImage(INPUT_FILE);_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("Load image: " + (end-start) + " ms.");_x000D_
_x000D_
// Zet de input file om in 3 matrices (rood, groen, blauw)_x000D_
start = System.currentTimeMillis();_x000D_
final float[][][] rgbArrays = convertImageToFloatArrays(image);_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("Convert image:" + (end-start) + " ms.");_x000D_
_x000D_
// Bereken van elke matrix het PRNU patroon (extractie stap)_x000D_
start = System.currentTimeMillis();_x000D_
for (int i = 0; i < 3; i++) {_x000D_
extractImage(rgbArrays[i]);_x000D_
}_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("PRNU extracted: " + (end-start) + " ms.");_x000D_
_x000D_
// Schrijf het patroon weg als een Java object_x000D_
writeJavaObject(rgbArrays, OUTPUT_FILE);_x000D_
_x000D_
System.out.println("Pattern written");_x000D_
_x000D_
// Controleer nu het gemaakte bestand_x000D_
final float[][][] expectedPattern = (float[][][]) readJavaObject(EXPECTED_PATTERN_FILE);_x000D_
final float[][][] actualPattern = (float[][][]) readJavaObject(OUTPUT_FILE);_x000D_
for (int i = 0; i < 3; i++) {_x000D_
// Het patroon zoals dat uit PRNU Compare komt, bevat een extra matrix voor transparantie. Deze moeten we overslaan (+1)!_x000D_
compare2DArray(expectedPattern[i + 1], actualPattern[i], 0.0001f);_x000D_
}_x000D_
_x000D_
System.out.println("Validation completed");_x000D_
_x000D_
//This exit is inserted because the program will otherwise hang for a about a minute_x000D_
//most likely explanation for this is the fact that the FFT library spawns a couple_x000D_
//of threads which cannot be properly destroyed_x000D_
System.exit(0);_x000D_
}_x000D_
_x000D_
private static BufferedImage readImage(final File file) throws IOException {_x000D_
final InputStream fileInputStream = new FileInputStream(file);_x000D_
try {_x000D_
final BufferedImage image = ImageIO.read(new BufferedInputStream(fileInputStream));_x000D_
if ((image != null) && (image.getWidth() >= 0) && (image.getHeight() >= 0)) {_x000D_
return image;_x000D_
}_x000D_
}_x000D_
catch (final CMMException e) {_x000D_
// Image file is unsupported or corrupt_x000D_
}_x000D_
catch (final RuntimeException e) {_x000D_
// Internal error processing image file_x000D_
}_x000D_
catch (final IOException e) {_x000D_
// Error reading image from disk_x000D_
}_x000D_
finally {_x000D_
fileInputStream.close();_x000D_
}_x000D_
_x000D_
// Image unreadable or too smalld array_x000D_
return null;_x000D_
}_x000D_
_x000D_
private static float[][][] convertImageToFloatArrays(final BufferedImage image) {_x000D_
final int width = image.getWidth();_x000D_
final int height = image.getHeight();_x000D_
final float[][][] pixels = new float[3][height][width];_x000D_
_x000D_
final ColorModel colorModel = ColorModel.getRGBdefault();_x000D_
for (int y = 0; y < height; y++) {_x000D_
for (int x = 0; x < width; x++) {_x000D_
final int pixel = image.getRGB(x, y); // aa bb gg rr_x000D_
pixels[0][y][x] = colorModel.getRed(pixel);_x000D_
pixels[1][y][x] = colorModel.getGreen(pixel);_x000D_
pixels[2][y][x] = colorModel.getBlue(pixel);_x000D_
}_x000D_
}_x000D_
return pixels;_x000D_
}_x000D_
_x000D_
private static void extractImage(final float[][] pixels) {_x000D_
final int width = pixels[0].length;_x000D_
final int height = pixels.length;_x000D_
_x000D_
long start = System.currentTimeMillis();_x000D_
long end = 0;_x000D_
_x000D_
final ImageFilter fastNoiseFilter = new FastNoiseFilter(width, height);_x000D_
fastNoiseFilter.apply(pixels);_x000D_
_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("Fast Noise Filter: " + (end-start) + " ms.");_x000D_
_x000D_
start = System.currentTimeMillis();_x000D_
final ImageFilter zeroMeanTotalFilter = new ZeroMeanTotalFilter(width, height);_x000D_
zeroMeanTotalFilter.apply(pixels);_x000D_
_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("Zero Mean Filter: " + (end-start) + " ms.");_x000D_
_x000D_
start = System.currentTimeMillis();_x000D_
final ImageFilter wienerFilter = new WienerFilter(width, height);_x000D_
wienerFilter.apply(pixels);_x000D_
_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("Wiener Filter: " + (end-start) + " ms.");_x000D_
}_x000D_
_x000D_
public static Object readJavaObject(final File inputFile) throws IOException {_x000D_
final ObjectInputStream inputStream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(inputFile)));_x000D_
try {_x000D_
return inputStream.readObject();_x000D_
}_x000D_
catch (final ClassNotFoundException e) {_x000D_
throw new IOException("Cannot read pattern: " + inputFile.getAbsolutePath(), e);_x000D_
}_x000D_
finally {_x000D_
inputStream.close();_x000D_
}_x000D_
}_x000D_
_x000D_
private static void writeJavaObject(final Object object, final File outputFile) throws IOException {_x000D_
final OutputStream outputStream = new FileOutputStream(outputFile);_x000D_
try {_x000D_
final ObjectOutputStream objectOutputStream = new ObjectOutputStream(new BufferedOutputStream(outputStream));_x000D_
objectOutputStream.writeObject(object);_x000D_
objectOutputStream.close();_x000D_
}_x000D_
finally {_x000D_
outputStream.close();_x000D_
}_x000D_
}_x000D_
_x000D_
private static boolean compare2DArray(final float[][] expected, final float[][] actual, final float delta) {_x000D_
for (int i = 0; i < expected.length; i++) {_x000D_
for (int j = 0; j < expected[i].length; j++) {_x000D_
if (Math.abs(actual[i][j] - expected[i][j]) > delta) {_x000D_
System.err.println("de waarde op " + i + "," + j + " is " + actual[i][j] + " maar had moeten zijn " + expected[i][j]);_x000D_
return false;_x000D_
}_x000D_
}_x000D_
}_x000D_
return true;_x000D_
}_x000D_
_x000D_
}_x000D_
| JungleComputing/common-source-identification-desktop | src/main/java/nl/minvenj/nfi/common_source_identification/CommonSourceIdentification.java | 2,232 | // Controleer nu het gemaakte bestand_x000D_ | line_comment | nl | /*_x000D_
* Copyright (c) 2014, Netherlands Forensic Institute_x000D_
* All rights reserved._x000D_
*/_x000D_
package nl.minvenj.nfi.common_source_identification;_x000D_
_x000D_
import java.awt.color.CMMException;_x000D_
import java.awt.image.BufferedImage;_x000D_
import java.awt.image.ColorModel;_x000D_
import java.io.BufferedInputStream;_x000D_
import java.io.BufferedOutputStream;_x000D_
import java.io.File;_x000D_
import java.io.FileInputStream;_x000D_
import java.io.FileOutputStream;_x000D_
import java.io.IOException;_x000D_
import java.io.InputStream;_x000D_
import java.io.ObjectInputStream;_x000D_
import java.io.ObjectOutputStream;_x000D_
import java.io.OutputStream;_x000D_
_x000D_
import javax.imageio.ImageIO;_x000D_
_x000D_
import nl.minvenj.nfi.common_source_identification.filter.FastNoiseFilter;_x000D_
import nl.minvenj.nfi.common_source_identification.filter.ImageFilter;_x000D_
import nl.minvenj.nfi.common_source_identification.filter.WienerFilter;_x000D_
import nl.minvenj.nfi.common_source_identification.filter.ZeroMeanTotalFilter;_x000D_
_x000D_
public final class CommonSourceIdentification {_x000D_
static final File TESTDATA_FOLDER = new File("testdata");_x000D_
_x000D_
static final File INPUT_FOLDER = new File(TESTDATA_FOLDER, "input");_x000D_
// public static final File INPUT_FILE = new File(INPUT_FOLDER, "test.jpg");_x000D_
public static final File INPUT_FILE = new File("/var/scratch/bwn200/Dresden/2748x3664/Kodak_M1063_4_12664.JPG");_x000D_
static final File EXPECTED_PATTERN_FILE = new File(INPUT_FOLDER, "expected.pat");_x000D_
_x000D_
static final File OUTPUT_FOLDER = new File(TESTDATA_FOLDER, "output");_x000D_
static final File OUTPUT_FILE = new File(OUTPUT_FOLDER, "test.pat");_x000D_
_x000D_
public static void main(final String[] args) throws IOException {_x000D_
long start = System.currentTimeMillis();_x000D_
long end = 0;_x000D_
_x000D_
// Laad de input file in_x000D_
final BufferedImage image = readImage(INPUT_FILE);_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("Load image: " + (end-start) + " ms.");_x000D_
_x000D_
// Zet de input file om in 3 matrices (rood, groen, blauw)_x000D_
start = System.currentTimeMillis();_x000D_
final float[][][] rgbArrays = convertImageToFloatArrays(image);_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("Convert image:" + (end-start) + " ms.");_x000D_
_x000D_
// Bereken van elke matrix het PRNU patroon (extractie stap)_x000D_
start = System.currentTimeMillis();_x000D_
for (int i = 0; i < 3; i++) {_x000D_
extractImage(rgbArrays[i]);_x000D_
}_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("PRNU extracted: " + (end-start) + " ms.");_x000D_
_x000D_
// Schrijf het patroon weg als een Java object_x000D_
writeJavaObject(rgbArrays, OUTPUT_FILE);_x000D_
_x000D_
System.out.println("Pattern written");_x000D_
_x000D_
// Controleer nu<SUF>
final float[][][] expectedPattern = (float[][][]) readJavaObject(EXPECTED_PATTERN_FILE);_x000D_
final float[][][] actualPattern = (float[][][]) readJavaObject(OUTPUT_FILE);_x000D_
for (int i = 0; i < 3; i++) {_x000D_
// Het patroon zoals dat uit PRNU Compare komt, bevat een extra matrix voor transparantie. Deze moeten we overslaan (+1)!_x000D_
compare2DArray(expectedPattern[i + 1], actualPattern[i], 0.0001f);_x000D_
}_x000D_
_x000D_
System.out.println("Validation completed");_x000D_
_x000D_
//This exit is inserted because the program will otherwise hang for a about a minute_x000D_
//most likely explanation for this is the fact that the FFT library spawns a couple_x000D_
//of threads which cannot be properly destroyed_x000D_
System.exit(0);_x000D_
}_x000D_
_x000D_
private static BufferedImage readImage(final File file) throws IOException {_x000D_
final InputStream fileInputStream = new FileInputStream(file);_x000D_
try {_x000D_
final BufferedImage image = ImageIO.read(new BufferedInputStream(fileInputStream));_x000D_
if ((image != null) && (image.getWidth() >= 0) && (image.getHeight() >= 0)) {_x000D_
return image;_x000D_
}_x000D_
}_x000D_
catch (final CMMException e) {_x000D_
// Image file is unsupported or corrupt_x000D_
}_x000D_
catch (final RuntimeException e) {_x000D_
// Internal error processing image file_x000D_
}_x000D_
catch (final IOException e) {_x000D_
// Error reading image from disk_x000D_
}_x000D_
finally {_x000D_
fileInputStream.close();_x000D_
}_x000D_
_x000D_
// Image unreadable or too smalld array_x000D_
return null;_x000D_
}_x000D_
_x000D_
private static float[][][] convertImageToFloatArrays(final BufferedImage image) {_x000D_
final int width = image.getWidth();_x000D_
final int height = image.getHeight();_x000D_
final float[][][] pixels = new float[3][height][width];_x000D_
_x000D_
final ColorModel colorModel = ColorModel.getRGBdefault();_x000D_
for (int y = 0; y < height; y++) {_x000D_
for (int x = 0; x < width; x++) {_x000D_
final int pixel = image.getRGB(x, y); // aa bb gg rr_x000D_
pixels[0][y][x] = colorModel.getRed(pixel);_x000D_
pixels[1][y][x] = colorModel.getGreen(pixel);_x000D_
pixels[2][y][x] = colorModel.getBlue(pixel);_x000D_
}_x000D_
}_x000D_
return pixels;_x000D_
}_x000D_
_x000D_
private static void extractImage(final float[][] pixels) {_x000D_
final int width = pixels[0].length;_x000D_
final int height = pixels.length;_x000D_
_x000D_
long start = System.currentTimeMillis();_x000D_
long end = 0;_x000D_
_x000D_
final ImageFilter fastNoiseFilter = new FastNoiseFilter(width, height);_x000D_
fastNoiseFilter.apply(pixels);_x000D_
_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("Fast Noise Filter: " + (end-start) + " ms.");_x000D_
_x000D_
start = System.currentTimeMillis();_x000D_
final ImageFilter zeroMeanTotalFilter = new ZeroMeanTotalFilter(width, height);_x000D_
zeroMeanTotalFilter.apply(pixels);_x000D_
_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("Zero Mean Filter: " + (end-start) + " ms.");_x000D_
_x000D_
start = System.currentTimeMillis();_x000D_
final ImageFilter wienerFilter = new WienerFilter(width, height);_x000D_
wienerFilter.apply(pixels);_x000D_
_x000D_
end = System.currentTimeMillis();_x000D_
System.out.println("Wiener Filter: " + (end-start) + " ms.");_x000D_
}_x000D_
_x000D_
public static Object readJavaObject(final File inputFile) throws IOException {_x000D_
final ObjectInputStream inputStream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(inputFile)));_x000D_
try {_x000D_
return inputStream.readObject();_x000D_
}_x000D_
catch (final ClassNotFoundException e) {_x000D_
throw new IOException("Cannot read pattern: " + inputFile.getAbsolutePath(), e);_x000D_
}_x000D_
finally {_x000D_
inputStream.close();_x000D_
}_x000D_
}_x000D_
_x000D_
private static void writeJavaObject(final Object object, final File outputFile) throws IOException {_x000D_
final OutputStream outputStream = new FileOutputStream(outputFile);_x000D_
try {_x000D_
final ObjectOutputStream objectOutputStream = new ObjectOutputStream(new BufferedOutputStream(outputStream));_x000D_
objectOutputStream.writeObject(object);_x000D_
objectOutputStream.close();_x000D_
}_x000D_
finally {_x000D_
outputStream.close();_x000D_
}_x000D_
}_x000D_
_x000D_
private static boolean compare2DArray(final float[][] expected, final float[][] actual, final float delta) {_x000D_
for (int i = 0; i < expected.length; i++) {_x000D_
for (int j = 0; j < expected[i].length; j++) {_x000D_
if (Math.abs(actual[i][j] - expected[i][j]) > delta) {_x000D_
System.err.println("de waarde op " + i + "," + j + " is " + actual[i][j] + " maar had moeten zijn " + expected[i][j]);_x000D_
return false;_x000D_
}_x000D_
}_x000D_
}_x000D_
return true;_x000D_
}_x000D_
_x000D_
}_x000D_
| false | 2,847 | 17 | 3,120 | 19 | 3,229 | 15 | 3,120 | 19 | 3,470 | 18 | false | false | false | false | false | true |
1,759 | 32522_0 | package nl.tomkemper.usessoap;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class ClientRunner implements CommandLineRunner {
private final CountryClient client;
public ClientRunner(CountryClient client){
this.client = client;
}
@Override
public void run(String... args) throws Exception {
Thread.sleep(1000); //lelijke hack om even te wachten tot de webservice wakker is:)
var resp = this.client.getCountry("Nederland");
System.out.println(resp.getCountry().getName());
}
}
| TomKemperNL/usessoap | client/src/main/java/nl/tomkemper/usessoap/ClientRunner.java | 168 | //lelijke hack om even te wachten tot de webservice wakker is:) | line_comment | nl | package nl.tomkemper.usessoap;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class ClientRunner implements CommandLineRunner {
private final CountryClient client;
public ClientRunner(CountryClient client){
this.client = client;
}
@Override
public void run(String... args) throws Exception {
Thread.sleep(1000); //lelijke hack<SUF>
var resp = this.client.getCountry("Nederland");
System.out.println(resp.getCountry().getName());
}
}
| false | 126 | 18 | 151 | 20 | 153 | 16 | 151 | 20 | 170 | 19 | false | false | false | false | false | true |
763 | 181882_0 | package me.kyllian.netflixstatistix.controllers;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import me.kyllian.netflixstatistix.NetflixStatistix;
import me.kyllian.netflixstatistix.models.PercentagePerEpisodeModel;
import me.kyllian.netflixstatistix.post.PostBuilder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
public class PercentagePerEpisodeController extends Controller implements Initializable {
//Voor een geselecteerde account en serie, geef per aflevering het gemiddeld
//bekeken percentage van de totale tijdsduur.
@FXML
private TableView<PercentagePerEpisodeModel> table;
@FXML
private TableColumn<PercentagePerEpisodeModel, String> tableSerie;
@FXML
private TableColumn<PercentagePerEpisodeModel, Integer> tableEpisode;
@FXML
private TableColumn<PercentagePerEpisodeModel, Integer> tableAverageTime;
@Override
public void initialize(URL location, ResourceBundle resources) {
tableSerie.setCellValueFactory(new PropertyValueFactory<>("Serie"));
tableEpisode.setCellValueFactory(new PropertyValueFactory<>("Episode"));
tableAverageTime.setCellValueFactory(new PropertyValueFactory<>("AverageTime"));
new PostBuilder()
.withIdentifier("averageTime")
.post(this);
}
@Override
public void handleResponse(String response) {
List<PercentagePerEpisodeModel> percentagePerEpisodeModels = new ArrayList<>();
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i != array.length(); i++) {
JSONObject data = array.getJSONObject(i);
percentagePerEpisodeModels.add(new PercentagePerEpisodeModel(data.getString("name_serie"), data.getInt("episode_id"), data.getInt("average")));
}
} catch (JSONException exception) {
System.out.println("Error reading JSON from server");
exception.printStackTrace();
}
table.setItems(FXCollections.observableArrayList(percentagePerEpisodeModels));
}
public void back() {
try {
Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("view/statistic.fxml"));
root.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm());
NetflixStatistix.parentWindow.getScene().setRoot(root);
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
| InstantlyMoist/NetflixStatistix | src/main/java/me/kyllian/netflixstatistix/controllers/PercentagePerEpisodeController.java | 834 | //Voor een geselecteerde account en serie, geef per aflevering het gemiddeld | line_comment | nl | package me.kyllian.netflixstatistix.controllers;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import me.kyllian.netflixstatistix.NetflixStatistix;
import me.kyllian.netflixstatistix.models.PercentagePerEpisodeModel;
import me.kyllian.netflixstatistix.post.PostBuilder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
public class PercentagePerEpisodeController extends Controller implements Initializable {
//Voor een<SUF>
//bekeken percentage van de totale tijdsduur.
@FXML
private TableView<PercentagePerEpisodeModel> table;
@FXML
private TableColumn<PercentagePerEpisodeModel, String> tableSerie;
@FXML
private TableColumn<PercentagePerEpisodeModel, Integer> tableEpisode;
@FXML
private TableColumn<PercentagePerEpisodeModel, Integer> tableAverageTime;
@Override
public void initialize(URL location, ResourceBundle resources) {
tableSerie.setCellValueFactory(new PropertyValueFactory<>("Serie"));
tableEpisode.setCellValueFactory(new PropertyValueFactory<>("Episode"));
tableAverageTime.setCellValueFactory(new PropertyValueFactory<>("AverageTime"));
new PostBuilder()
.withIdentifier("averageTime")
.post(this);
}
@Override
public void handleResponse(String response) {
List<PercentagePerEpisodeModel> percentagePerEpisodeModels = new ArrayList<>();
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i != array.length(); i++) {
JSONObject data = array.getJSONObject(i);
percentagePerEpisodeModels.add(new PercentagePerEpisodeModel(data.getString("name_serie"), data.getInt("episode_id"), data.getInt("average")));
}
} catch (JSONException exception) {
System.out.println("Error reading JSON from server");
exception.printStackTrace();
}
table.setItems(FXCollections.observableArrayList(percentagePerEpisodeModels));
}
public void back() {
try {
Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("view/statistic.fxml"));
root.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm());
NetflixStatistix.parentWindow.getScene().setRoot(root);
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
| false | 553 | 22 | 673 | 25 | 673 | 19 | 673 | 25 | 802 | 24 | false | false | false | false | false | true |
1,272 | 128157_1 | package nl.pdok;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
/**
*
* @author Raymond Kroon <[email protected]>
*/
public class BoyerMoorePatternMatcher {
public final static int NO_OF_CHARS = 256;
public final static int MAX_BUFFER_SIZE = 1024;
private InputStream src;
private HashMap<String, PatternCache> cache = new HashMap<>();
private boolean isAtMatch = false;
private int bufferSize = 0;
private byte[] buffer = new byte[MAX_BUFFER_SIZE];
private int bufferPosition = 0;
private String previousPatternId = null;
private int suggestedBufferPosition = 0;
public BoyerMoorePatternMatcher(InputStream src) {
this.src = src;
}
public boolean currentPositionIsMatch() {
return isAtMatch;
}
public byte[] flushToNextMatch(String patternId) throws IOException {
// een stukje buffer lezen, en de buffer aanvullen mits nodig
// fuck de copy pasta onzin....
if (previousPatternId != null && previousPatternId.equals(patternId)) {
bufferPosition = suggestedBufferPosition;
}
previousPatternId = patternId;
byte[] flushResult = new byte[0];
isAtMatch = false;
PatternCache pc = cache.get(patternId);
while (true) {
SearchResult result = search(buffer, bufferSize, pc.pattern, pc.patternLength, pc.badchars, bufferPosition);
bufferPosition = result.offset;
suggestedBufferPosition = result.suggestedNewOffset;
flushResult = concat(flushResult, flushBuffer());
if (result.matched) {
isAtMatch = true;
return flushResult;
} else {
if (!fillBuffer()) {
isAtMatch = false;
flushResult = concat(flushResult, flushBuffer());
return flushResult;
}
}
}
}
private byte[] flushBuffer() {
// System.out.println("buffer");
// System.out.println(new String(buffer));
// System.out.println("/buffer/" + bufferPosition);
byte[] flushed = Arrays.copyOfRange(buffer, 0, bufferPosition);
// move currentPosition to front;
buffer = Arrays.copyOfRange(buffer, bufferPosition, MAX_BUFFER_SIZE + bufferPosition);
bufferSize = bufferSize - bufferPosition;
suggestedBufferPosition = suggestedBufferPosition - bufferPosition;
bufferPosition = 0;
return flushed;
}
private boolean fillBuffer() throws IOException {
if (bufferSize < MAX_BUFFER_SIZE) {
int read = src.read(buffer, bufferSize, MAX_BUFFER_SIZE - bufferSize);
bufferSize += read;
return read > 0;
}
return true;
}
public byte[] concat(byte[] a, byte[] b) {
int aLen = a.length;
int bLen = b.length;
byte[] c = new byte[aLen + bLen];
System.arraycopy(a, 0, c, 0, aLen);
System.arraycopy(b, 0, c, aLen, bLen);
return c;
}
private class PatternCache {
public final byte[] pattern;
public final int patternLength;
public final int[] badchars;
public PatternCache(byte[] pattern) {
this.pattern = pattern;
this.patternLength = pattern.length;
this.badchars = badCharHeuristic(pattern);
}
}
public void setPattern(String id, byte[] pattern) {
cache.put(id, new PatternCache(pattern));
}
public static int[] badCharHeuristic(byte[] pattern) {
int[] result = new int[NO_OF_CHARS];
int patternSize = pattern.length;
// default = -1
Arrays.fill(result, -1);
for (int i = 0; i < patternSize; ++i) {
result[byteValue(pattern[i])] = i;
}
return result;
}
public static class SearchResult {
public final boolean matched;
public final int offset;
public final int suggestedNewOffset;
public SearchResult(boolean matched, int offset, int suggestedNewOffset) {
this.matched = matched;
this.offset = offset;
this.suggestedNewOffset = suggestedNewOffset;
}
}
public static SearchResult search(byte[] src, byte[] pattern, int offset) {
/* Fill the bad character array by calling the preprocessing
function badCharHeuristic() for given pattern */
return search(src, src.length, pattern, pattern.length, badCharHeuristic(pattern), offset);
}
/* A pattern searching function that uses Bad Character Heuristic of
Boyer Moore Algorithm */
public static SearchResult search(byte[] src, int srcLength, byte[] pattern, int patternLength, int[] badchars, int offset) {
int s = offset; // s is shift of the pattern with respect to text
while (s <= (srcLength - patternLength)) {
int j = patternLength - 1;
/* Keep reducing index j of pattern while characters of
pattern and text are matching at this shift s */
while (j >= 0 && pattern[j] == src[s + j]) {
j--;
}
/* If the pattern is present at current shift, then index j
will become -1 after the above loop */
if (j < 0) {
//System.out.println("pattern found at index = " + s);
/* Shift the pattern so that the next character in src
aligns with the last occurrence of it in pattern.
The condition s+m < n is necessary for the case when
pattern occurs at the end of text */
//s += (s+patternLength < srcLength) ? patternLength - badchars[src[s+patternLength]] : 1;
return new SearchResult(true, s, (s + patternLength < srcLength) ? s + patternLength - badchars[src[s + patternLength]] : s + 1);
} else {
/* Shift the pattern so that the bad character in src
aligns with the last occurrence of it in pattern. The
max function is used to make sure that we get a positive
shift. We may get a negative shift if the last occurrence
of bad character in pattern is on the right side of the
current character. */
s += Math.max(1, j - badchars[byteValue(src[s + j])]);
}
}
return new SearchResult(false, srcLength, s);
}
private static int byteValue(byte b) {
return (int) b & 0xFF;
}
}
| PDOK/xml-splitter | src/java/nl/pdok/BoyerMoorePatternMatcher.java | 1,748 | // een stukje buffer lezen, en de buffer aanvullen mits nodig | line_comment | nl | package nl.pdok;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
/**
*
* @author Raymond Kroon <[email protected]>
*/
public class BoyerMoorePatternMatcher {
public final static int NO_OF_CHARS = 256;
public final static int MAX_BUFFER_SIZE = 1024;
private InputStream src;
private HashMap<String, PatternCache> cache = new HashMap<>();
private boolean isAtMatch = false;
private int bufferSize = 0;
private byte[] buffer = new byte[MAX_BUFFER_SIZE];
private int bufferPosition = 0;
private String previousPatternId = null;
private int suggestedBufferPosition = 0;
public BoyerMoorePatternMatcher(InputStream src) {
this.src = src;
}
public boolean currentPositionIsMatch() {
return isAtMatch;
}
public byte[] flushToNextMatch(String patternId) throws IOException {
// een stukje<SUF>
// fuck de copy pasta onzin....
if (previousPatternId != null && previousPatternId.equals(patternId)) {
bufferPosition = suggestedBufferPosition;
}
previousPatternId = patternId;
byte[] flushResult = new byte[0];
isAtMatch = false;
PatternCache pc = cache.get(patternId);
while (true) {
SearchResult result = search(buffer, bufferSize, pc.pattern, pc.patternLength, pc.badchars, bufferPosition);
bufferPosition = result.offset;
suggestedBufferPosition = result.suggestedNewOffset;
flushResult = concat(flushResult, flushBuffer());
if (result.matched) {
isAtMatch = true;
return flushResult;
} else {
if (!fillBuffer()) {
isAtMatch = false;
flushResult = concat(flushResult, flushBuffer());
return flushResult;
}
}
}
}
private byte[] flushBuffer() {
// System.out.println("buffer");
// System.out.println(new String(buffer));
// System.out.println("/buffer/" + bufferPosition);
byte[] flushed = Arrays.copyOfRange(buffer, 0, bufferPosition);
// move currentPosition to front;
buffer = Arrays.copyOfRange(buffer, bufferPosition, MAX_BUFFER_SIZE + bufferPosition);
bufferSize = bufferSize - bufferPosition;
suggestedBufferPosition = suggestedBufferPosition - bufferPosition;
bufferPosition = 0;
return flushed;
}
private boolean fillBuffer() throws IOException {
if (bufferSize < MAX_BUFFER_SIZE) {
int read = src.read(buffer, bufferSize, MAX_BUFFER_SIZE - bufferSize);
bufferSize += read;
return read > 0;
}
return true;
}
public byte[] concat(byte[] a, byte[] b) {
int aLen = a.length;
int bLen = b.length;
byte[] c = new byte[aLen + bLen];
System.arraycopy(a, 0, c, 0, aLen);
System.arraycopy(b, 0, c, aLen, bLen);
return c;
}
private class PatternCache {
public final byte[] pattern;
public final int patternLength;
public final int[] badchars;
public PatternCache(byte[] pattern) {
this.pattern = pattern;
this.patternLength = pattern.length;
this.badchars = badCharHeuristic(pattern);
}
}
public void setPattern(String id, byte[] pattern) {
cache.put(id, new PatternCache(pattern));
}
public static int[] badCharHeuristic(byte[] pattern) {
int[] result = new int[NO_OF_CHARS];
int patternSize = pattern.length;
// default = -1
Arrays.fill(result, -1);
for (int i = 0; i < patternSize; ++i) {
result[byteValue(pattern[i])] = i;
}
return result;
}
public static class SearchResult {
public final boolean matched;
public final int offset;
public final int suggestedNewOffset;
public SearchResult(boolean matched, int offset, int suggestedNewOffset) {
this.matched = matched;
this.offset = offset;
this.suggestedNewOffset = suggestedNewOffset;
}
}
public static SearchResult search(byte[] src, byte[] pattern, int offset) {
/* Fill the bad character array by calling the preprocessing
function badCharHeuristic() for given pattern */
return search(src, src.length, pattern, pattern.length, badCharHeuristic(pattern), offset);
}
/* A pattern searching function that uses Bad Character Heuristic of
Boyer Moore Algorithm */
public static SearchResult search(byte[] src, int srcLength, byte[] pattern, int patternLength, int[] badchars, int offset) {
int s = offset; // s is shift of the pattern with respect to text
while (s <= (srcLength - patternLength)) {
int j = patternLength - 1;
/* Keep reducing index j of pattern while characters of
pattern and text are matching at this shift s */
while (j >= 0 && pattern[j] == src[s + j]) {
j--;
}
/* If the pattern is present at current shift, then index j
will become -1 after the above loop */
if (j < 0) {
//System.out.println("pattern found at index = " + s);
/* Shift the pattern so that the next character in src
aligns with the last occurrence of it in pattern.
The condition s+m < n is necessary for the case when
pattern occurs at the end of text */
//s += (s+patternLength < srcLength) ? patternLength - badchars[src[s+patternLength]] : 1;
return new SearchResult(true, s, (s + patternLength < srcLength) ? s + patternLength - badchars[src[s + patternLength]] : s + 1);
} else {
/* Shift the pattern so that the bad character in src
aligns with the last occurrence of it in pattern. The
max function is used to make sure that we get a positive
shift. We may get a negative shift if the last occurrence
of bad character in pattern is on the right side of the
current character. */
s += Math.max(1, j - badchars[byteValue(src[s + j])]);
}
}
return new SearchResult(false, srcLength, s);
}
private static int byteValue(byte b) {
return (int) b & 0xFF;
}
}
| false | 1,420 | 20 | 1,545 | 21 | 1,666 | 15 | 1,545 | 21 | 1,778 | 21 | false | false | false | false | false | true |
1,023 | 204127_4 | /**
* Oefening 1.11
* @author Matthew Smet
* @import importeren van nodige libraries
*/
import java.lang.*;
/**
* klasse Eersteprog gebaseerd op oefening 1.11 met 2 methoden
* Methode main met @param args array van strings met meegegeven parameters
* Methode drukaf met @param integer m
*/
public class Eersteprog
{
public static void main(String args[])
{
//Methode drukaf word opgeroepen met parameter 100
drukaf(100);
}
private static void(int m)
{
//Locale variablen wordt aangemaakt(a)
int a;
//herhaalt de lus 100x (meegegeven parameter)
for (a=0;a<m;a++)
{
//print het getal uit in de cmd
System.out.println(a);
}
}
} | MTA-Digital-Broadcast-2/C-Vdovlov-Evgeni-Smet-Matthew-Project-MHP | Matthew smet - Oefeningen Java + mhp/LaboJava/blz12/Eersteprog.java | 249 | //herhaalt de lus 100x (meegegeven parameter) | line_comment | nl | /**
* Oefening 1.11
* @author Matthew Smet
* @import importeren van nodige libraries
*/
import java.lang.*;
/**
* klasse Eersteprog gebaseerd op oefening 1.11 met 2 methoden
* Methode main met @param args array van strings met meegegeven parameters
* Methode drukaf met @param integer m
*/
public class Eersteprog
{
public static void main(String args[])
{
//Methode drukaf word opgeroepen met parameter 100
drukaf(100);
}
private static void(int m)
{
//Locale variablen wordt aangemaakt(a)
int a;
//herhaalt de<SUF>
for (a=0;a<m;a++)
{
//print het getal uit in de cmd
System.out.println(a);
}
}
} | false | 227 | 20 | 256 | 19 | 236 | 16 | 256 | 19 | 268 | 19 | false | false | false | false | false | true |
4,503 | 10426_10 | package model.datum;
import java.util.Date;
/**
*
* @author Isaak
*
*/
public class Datum {
private int dag;
private int maand;
private int jaar;
/**
* @throws Exception
*
*/
public Datum() throws Exception
{
HuidigeSysteemDatum();
}
/**
*
* @param Datum
* @throws Exception
*/
@SuppressWarnings("deprecation")
public Datum(Date datum) throws Exception
{
setDatum(datum.getDate(), datum.getMonth() + 1, datum.getYear() + 1900);
}
/**
*
* @param datum
* @throws Exception
*/
public Datum(Datum datum) throws Exception
{
setDatum(datum.getDag(), datum.getMaand(), datum.getJaar());
}
/**
*
* @param dag
* @param maand
* @param jaar
* @throws Exception
*/
public Datum(int dag, int maand, int jaar) throws Exception
{
setDatum(dag, maand, jaar);
}
/**
* Datum als string DDMMJJJJ
* @param datum
* @throws Exception
* @throws NumberFormatException
*/
public Datum(String datum) throws NumberFormatException, Exception
{
String[] datumDelen = datum.split("/");
if (datumDelen.length != 3 || datumDelen[0].length() < 1 ||
datumDelen[1].length() != 2 || datumDelen[2].length() != 4)
{
throw new IllegalArgumentException("De gegeven datum is onjuist. "
+ "Geldig formaat: (D)D/MM/YYYY");
}
setDatum(Integer.parseInt(datumDelen[0]), Integer.parseInt(datumDelen[1]), Integer.parseInt(datumDelen[2]));
}
/**
* Stel de datumvariabelen in. Doe ook de validatie en werp exceptions indien nodig
*
* @param dag
* @param maand
* @param jaar
* @return
* @throws Exception
*/
public boolean setDatum(int dag, int maand, int jaar) throws Exception
{
// Eerst de basale controle
if (dag < 1 || dag > 31)
{
throw new Exception("Ongeldige dag gegeven");
}
if (maand < 1 || maand > 12)
{
throw new Exception("Ongeldige numerieke maand gegeven");
}
if (jaar < 0)
{
throw new Exception("Ongeldig jaar gegeven");
}
// Nu een precieze controle
switch (maand)
{
case 2:
// 1) Als het geen schrikkeljaar is, heeft februari max 28 dagen
// 2) Wel een schrikkeljaar? Max 29 dagen
if ((!Maanden.isSchrikkeljaar(jaar) && dag >= 29) || (Maanden.isSchrikkeljaar(jaar) &&
dag > 29))
{
throw new Exception("De dag is niet juist voor de gegeven maand februari");
}
break;
case 4:
case 6:
case 9:
case 11:
if (dag > 30)
{
throw new Exception("De dag is niet juist voor de gegeven maand " + Maanden.get(maand));
}
break;
}
// Alles is goed verlopen
this.dag = dag;
this.maand = maand;
this.jaar = jaar;
return true;
}
/**
*
* @return
*/
public String getDatumInAmerikaansFormaat()
{
return String.format("%04d/%02d/%02d", jaar, maand, dag);
}
/**
*
* @return
*/
public String getDatumInEuropeesFormaat()
{
return String.format("%02d/%02d/%04d", dag, maand, jaar);
}
/**
* Haal de dag van het Datum object op
* @return
*/
public int getDag()
{
return dag;
}
/**
* Haal de maand van het Datum object op
* @return
*/
public int getMaand()
{
return maand;
}
/**
* Haal het jaar van het Datum object op
* @return
*/
public int getJaar()
{
return jaar;
}
/**
* Is de gegeven datum kleiner dan het huidid datum object?
*
* @param datum
* @return
*/
public boolean kleinerDan(Datum datum)
{
return compareTo(datum) > 0;
}
/**
*
* @param datum
* @return
* @throws Exception
*/
public int verschilInJaren(Datum datum) throws Exception
{
return new DatumVerschil(this, datum).getJaren();
}
/**
*
* @param datum
* @return
* @throws Exception
*/
public int verschilInMaanden(Datum datum) throws Exception
{
return new DatumVerschil(this, datum).getMaanden();
}
/**
*
* @param aantalDagen
* @return
* @throws Exception
*/
public Datum veranderDatum(int aantalDagen) throws Exception
{
if (aantalDagen > 0)
{
while (aantalDagen + dag > Maanden.get(maand).aantalDagen(jaar))
{
aantalDagen -= Maanden.get(maand).aantalDagen(jaar) - dag + 1;
// Jaar verhogen
jaar += (maand == 12 ? 1 : 0);
// Maand verhogen
maand = (maand == 12 ? 1 : ++maand);
// We hebben een nieuwe maand, dus terug van 1 beginnen
dag = 1;
}
}
// Negatieve waarde, dus terug in de tijd gaan
else
{
while (-dag >= aantalDagen)
{
// Verminder met aantal dagen in huidige maand.
aantalDagen += dag;
// Verminder jaartal?
jaar -= (maand == 1 ? 1 : 0);
// Verminder maand
maand = (maand == 1 ? 12 : --maand);
// Zet als laatste dag van (vorige) maand
dag = Maanden.get(maand).aantalDagen(jaar);
}
}
return new Datum(dag += aantalDagen, maand, jaar);
}
/**
*
*/
@Override
public boolean equals(Object obj)
{
// Is het exact hetzelfde object?
if (this == obj)
{
return true;
}
// Is het hetzelfde type?
if (obj == null || !(obj instanceof Datum))
{
return false;
}
// Nu zien of de inhoud dezelfde is
return compareTo((Datum) obj) == 0;
}
/**
* Ik snap er de ballen van
*/
@Override
public int hashCode()
{
final int prime = 37;
int hash = 1;
hash = prime * hash + dag;
hash = prime * hash + maand;
hash = prime * hash + jaar;
return hash;
}
/**
* Vergelijk de onze datum met de nieuwe
*/
public int compareTo(Datum datum2)
{
if (jaar > datum2.jaar)
{
return 1;
}
else if (jaar < datum2.jaar)
{
return -1;
}
if (maand > datum2.maand)
{
return 1;
}
else if (maand < datum2.maand)
{
return -1;
}
if (dag > datum2.dag)
{
return 1;
}
else if (dag < datum2.dag)
{
return -1;
}
return 0;
}
/**
* Geef een string representatie terug van de datum
* @return Datum in string formaat
*/
public String toString()
{
return dag + " " + Maanden.get(maand) + " " + jaar;
}
/**
* Return de huidige datum van het systeem
* @return Date
* @throws Exception
*/
@SuppressWarnings("deprecation")
private void HuidigeSysteemDatum() throws Exception
{
Date datum = new Date();
setDatum(datum.getDate(), datum.getMonth() + 1, datum.getYear() + 1900);
}
}
| thunder-tw/JavaPractOpdrachten | Opdracht 1/src/model/datum/Datum.java | 2,560 | // 2) Wel een schrikkeljaar? Max 29 dagen | line_comment | nl | package model.datum;
import java.util.Date;
/**
*
* @author Isaak
*
*/
public class Datum {
private int dag;
private int maand;
private int jaar;
/**
* @throws Exception
*
*/
public Datum() throws Exception
{
HuidigeSysteemDatum();
}
/**
*
* @param Datum
* @throws Exception
*/
@SuppressWarnings("deprecation")
public Datum(Date datum) throws Exception
{
setDatum(datum.getDate(), datum.getMonth() + 1, datum.getYear() + 1900);
}
/**
*
* @param datum
* @throws Exception
*/
public Datum(Datum datum) throws Exception
{
setDatum(datum.getDag(), datum.getMaand(), datum.getJaar());
}
/**
*
* @param dag
* @param maand
* @param jaar
* @throws Exception
*/
public Datum(int dag, int maand, int jaar) throws Exception
{
setDatum(dag, maand, jaar);
}
/**
* Datum als string DDMMJJJJ
* @param datum
* @throws Exception
* @throws NumberFormatException
*/
public Datum(String datum) throws NumberFormatException, Exception
{
String[] datumDelen = datum.split("/");
if (datumDelen.length != 3 || datumDelen[0].length() < 1 ||
datumDelen[1].length() != 2 || datumDelen[2].length() != 4)
{
throw new IllegalArgumentException("De gegeven datum is onjuist. "
+ "Geldig formaat: (D)D/MM/YYYY");
}
setDatum(Integer.parseInt(datumDelen[0]), Integer.parseInt(datumDelen[1]), Integer.parseInt(datumDelen[2]));
}
/**
* Stel de datumvariabelen in. Doe ook de validatie en werp exceptions indien nodig
*
* @param dag
* @param maand
* @param jaar
* @return
* @throws Exception
*/
public boolean setDatum(int dag, int maand, int jaar) throws Exception
{
// Eerst de basale controle
if (dag < 1 || dag > 31)
{
throw new Exception("Ongeldige dag gegeven");
}
if (maand < 1 || maand > 12)
{
throw new Exception("Ongeldige numerieke maand gegeven");
}
if (jaar < 0)
{
throw new Exception("Ongeldig jaar gegeven");
}
// Nu een precieze controle
switch (maand)
{
case 2:
// 1) Als het geen schrikkeljaar is, heeft februari max 28 dagen
// 2) Wel<SUF>
if ((!Maanden.isSchrikkeljaar(jaar) && dag >= 29) || (Maanden.isSchrikkeljaar(jaar) &&
dag > 29))
{
throw new Exception("De dag is niet juist voor de gegeven maand februari");
}
break;
case 4:
case 6:
case 9:
case 11:
if (dag > 30)
{
throw new Exception("De dag is niet juist voor de gegeven maand " + Maanden.get(maand));
}
break;
}
// Alles is goed verlopen
this.dag = dag;
this.maand = maand;
this.jaar = jaar;
return true;
}
/**
*
* @return
*/
public String getDatumInAmerikaansFormaat()
{
return String.format("%04d/%02d/%02d", jaar, maand, dag);
}
/**
*
* @return
*/
public String getDatumInEuropeesFormaat()
{
return String.format("%02d/%02d/%04d", dag, maand, jaar);
}
/**
* Haal de dag van het Datum object op
* @return
*/
public int getDag()
{
return dag;
}
/**
* Haal de maand van het Datum object op
* @return
*/
public int getMaand()
{
return maand;
}
/**
* Haal het jaar van het Datum object op
* @return
*/
public int getJaar()
{
return jaar;
}
/**
* Is de gegeven datum kleiner dan het huidid datum object?
*
* @param datum
* @return
*/
public boolean kleinerDan(Datum datum)
{
return compareTo(datum) > 0;
}
/**
*
* @param datum
* @return
* @throws Exception
*/
public int verschilInJaren(Datum datum) throws Exception
{
return new DatumVerschil(this, datum).getJaren();
}
/**
*
* @param datum
* @return
* @throws Exception
*/
public int verschilInMaanden(Datum datum) throws Exception
{
return new DatumVerschil(this, datum).getMaanden();
}
/**
*
* @param aantalDagen
* @return
* @throws Exception
*/
public Datum veranderDatum(int aantalDagen) throws Exception
{
if (aantalDagen > 0)
{
while (aantalDagen + dag > Maanden.get(maand).aantalDagen(jaar))
{
aantalDagen -= Maanden.get(maand).aantalDagen(jaar) - dag + 1;
// Jaar verhogen
jaar += (maand == 12 ? 1 : 0);
// Maand verhogen
maand = (maand == 12 ? 1 : ++maand);
// We hebben een nieuwe maand, dus terug van 1 beginnen
dag = 1;
}
}
// Negatieve waarde, dus terug in de tijd gaan
else
{
while (-dag >= aantalDagen)
{
// Verminder met aantal dagen in huidige maand.
aantalDagen += dag;
// Verminder jaartal?
jaar -= (maand == 1 ? 1 : 0);
// Verminder maand
maand = (maand == 1 ? 12 : --maand);
// Zet als laatste dag van (vorige) maand
dag = Maanden.get(maand).aantalDagen(jaar);
}
}
return new Datum(dag += aantalDagen, maand, jaar);
}
/**
*
*/
@Override
public boolean equals(Object obj)
{
// Is het exact hetzelfde object?
if (this == obj)
{
return true;
}
// Is het hetzelfde type?
if (obj == null || !(obj instanceof Datum))
{
return false;
}
// Nu zien of de inhoud dezelfde is
return compareTo((Datum) obj) == 0;
}
/**
* Ik snap er de ballen van
*/
@Override
public int hashCode()
{
final int prime = 37;
int hash = 1;
hash = prime * hash + dag;
hash = prime * hash + maand;
hash = prime * hash + jaar;
return hash;
}
/**
* Vergelijk de onze datum met de nieuwe
*/
public int compareTo(Datum datum2)
{
if (jaar > datum2.jaar)
{
return 1;
}
else if (jaar < datum2.jaar)
{
return -1;
}
if (maand > datum2.maand)
{
return 1;
}
else if (maand < datum2.maand)
{
return -1;
}
if (dag > datum2.dag)
{
return 1;
}
else if (dag < datum2.dag)
{
return -1;
}
return 0;
}
/**
* Geef een string representatie terug van de datum
* @return Datum in string formaat
*/
public String toString()
{
return dag + " " + Maanden.get(maand) + " " + jaar;
}
/**
* Return de huidige datum van het systeem
* @return Date
* @throws Exception
*/
@SuppressWarnings("deprecation")
private void HuidigeSysteemDatum() throws Exception
{
Date datum = new Date();
setDatum(datum.getDate(), datum.getMonth() + 1, datum.getYear() + 1900);
}
}
| false | 2,103 | 17 | 2,242 | 20 | 2,323 | 16 | 2,242 | 20 | 2,700 | 18 | false | false | false | false | false | true |
1,734 | 37768_8 | package com.KineFit.app.activities;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.KineFit.app.R;
import com.KineFit.app.adapters.TakenAdapter;
import com.KineFit.app.model.Taak;
import com.KineFit.app.model.enums.TaskStatus;
import com.KineFit.app.services.JSONParser;
import org.json.JSONArray;
import org.json.JSONObject;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
/**
* Activity voor het taken overzicht.
* Op deze activity kan de gebruiker taken bekijken en voltooien.
*
* Created by Thomas on 30/04/16.
* @author Thomas Vandenabeele
*/
public class TakenActivity extends BasisActivity {
//region DATAMEMBERS
/** pDialog voor de UI */
private ProgressDialog pDialog;
/** LinearLayout voor het filtermenu */
private LinearLayout filterTakenMenu;
/** ToggleButton voor filteren */
private ToggleButton tbFilter;
/** Switch voor gesloten taken */
private Switch sGeslotenTaken;
/** Switch voor gefaalde taken */
private Switch sGefaaldeTaken;
/** Boolean gesloten taken */
private boolean geslotenTaken;
/** Boolean gefaalde taken */
private boolean gefaaldeTaken;
/** ListView voor de taken */
private ListView lvTaken;
/** TextView voor melding geen taken */
private TextView txtGeenTaken;
/** TakenLijst */
private ArrayList<Taak> takenLijst;
/** SQL datum formatter */
private SimpleDateFormat sqlDatumFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/** Korte datum formatter */
private SimpleDateFormat korteDatum = new SimpleDateFormat("dd-MM-yyyy");
/** Korte tijd formatter */
private SimpleDateFormat korteTijd = new SimpleDateFormat("HH:mm");
//endregion
//region REST: TAGS & URL
/** JSONParser voor de REST client aan te spreken */
JSONParser jParser = new JSONParser();
/** Tag voor gebruikersnaam */
private static final String TAG_GEBRUIKERSNAAM = "username";
//-------------------------------------------------------------------------------------------------------------------------------//
/** URL om alle taken op te vragen */
private static String url_alle_taken = "http://thomasvandenabeele.no-ip.org/KineFit/get_all_tasks.php";
/** Tag voor succes */
private static final String TAG_SUCCES = "success";
/** Tag voor taken */
private static final String TAG_TAKEN = "tasks";
/** Tag voor taak id */
private static final String TAG_ID = "id";
/** Tag voor taak naam */
private static final String TAG_NAAM = "message";
/** Tag voor taak aanmaak datum */
private static final String TAG_AANMAAKDATUM = "created_at";
/** Tag voor taak status */
private static final String TAG_STATUS = "status";
//-------------------------------------------------------------------------------------------------------------------------------//
/** URL om het de status van een taak te updaten */
private static String url_update_taak_status = "http://thomasvandenabeele.no-ip.org/KineFit/update_status_task.php";
/** ID van de status */
private static final String TAG_STATUS_ID = "id";
/** Naam van de status */
private static final String TAG_STATUS_NAAM = "name";
//-------------------------------------------------------------------------------------------------------------------------------//
//endregion
/**
* Methode die opgeroepen wordt bij aanmaak activity.
* @param savedInstanceState
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.taken_lijst);
//region UI componenten toekennen
txtGeenTaken = (TextView) findViewById(R.id.txtGeenTaken);
filterTakenMenu = (LinearLayout)findViewById(R.id.filterMenuTaken);
tbFilter = (ToggleButton)findViewById(R.id.tbFilter);
sGeslotenTaken = (Switch)findViewById(R.id.sGeslotenTaken);
sGefaaldeTaken = (Switch)findViewById(R.id.sGefaaldeTaken);
lvTaken = (ListView)findViewById(R.id.lvTaken);
//endregion
// OnCheckedChangeListener voor togglebutton filteren
tbFilter.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
// Toon filter menu
filterTakenMenu.setVisibility(View.VISIBLE);
}
else{
// Verberg filter menu
filterTakenMenu.setVisibility(View.GONE);
}
}
});
// OnCheckedChangeListener voor sGeslotenTaken
sGeslotenTaken.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
geslotenTaken = isChecked;
// Herlaad de listView
new LaadAlleTaken().execute();
}
});
// OnCheckedChangeListener voor sGefaaldeTaken
sGefaaldeTaken.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
gefaaldeTaken = isChecked;
// Herlaad de listView
new LaadAlleTaken().execute();
}
});
// Instantiëren members
geslotenTaken = sGeslotenTaken.isChecked();
gefaaldeTaken = sGefaaldeTaken.isChecked();
takenLijst = new ArrayList<Taak>();
// Laad de listView
new LaadAlleTaken().execute();
// OnItemClickListener voor ListView
lvTaken.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Get de geselecteerde taak
Taak t = takenLijst.get(position);
// Volgende code enkel wanneer de status nieuw of open is:
if(t.getStatus().equals(TaskStatus.OPEN)||t.getStatus().equals(TaskStatus.NEW)){
final String pid = ((TextView) view.findViewById(R.id.task_pid)).getText().toString();
final ContentValues parameters = new ContentValues();
parameters.put(TAG_STATUS_ID, pid);
// Maak alert venster
new AlertDialog.Builder(TakenActivity.this)
.setTitle("Voltooi taak")
.setMessage("Is u in deze taak geslaagd?")
.setPositiveButton("Geslaagd",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
parameters.put(TAG_STATUS_NAAM, TaskStatus.DONE.toString());
new UpdateTaakStatus().execute(parameters);
// Sluit alert
dialog.cancel();
}
})
.setNeutralButton("Gefaald",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
parameters.put(TAG_STATUS_NAAM, TaskStatus.FAILED.toString());
new UpdateTaakStatus().execute(parameters);
// Sluit alert
dialog.cancel();
}
})
.setNegativeButton("Annuleren",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Sluit alert
dialog.cancel();
}
})
.setCancelable(false)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
});
}
/**
* Async Taak op achtergrond om het aantal ongelezen taken op te halen en weer te geven.
* Via HTTP Request naar REST client.
* */
class LaadAlleTaken extends AsyncTask<String, String, String> {
/**
* Methode die opgeroepen wordt voor uitvoeren van taak.
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TakenActivity.this);
pDialog.setMessage("Taken laden, gelieve even te wachten aub...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Deze methode wordt in de achtergrond uitgevoerd.
* @param params Strings niet relevant
* @return niet relevant
*/
protected String doInBackground(String... params) {
// Maakt de request en geeft het resultaat
ContentValues parameters = new ContentValues();
parameters.put(TAG_GEBRUIKERSNAAM, sessie.getUsername());
JSONObject json = jParser.makeHttpRequest(url_alle_taken, "GET", parameters);
Log.d("Alle taken: ", json.toString());
try {
if (json.getInt(TAG_SUCCES) == 1) {
// Taken ophalen
JSONArray tasks = json.getJSONArray(TAG_TAKEN);
takenLijst.clear();
// Omzetten in ArrayList<Taak>
for (int i = 0; i < tasks.length(); i++) {
JSONObject c = tasks.getJSONObject(i);
java.sql.Date aanmaakDatum = new java.sql.Date(sqlDatumFormatter.parse(c.getString(TAG_AANMAAKDATUM)).getTime());
Taak t = new Taak(c.getInt(TAG_ID),
c.getString(TAG_NAAM),
aanmaakDatum,
TaskStatus.valueOf(c.getString(TAG_STATUS)));
// Filtercriteria checken
boolean add = true;
switch (t.getStatus()){
case DONE:
if(!geslotenTaken) add = false;
break;
case FAILED:
if(!gefaaldeTaken) add = false;
break;
default:
add = true;
break;
}
// Toevoegen aan lijst
if(add) takenLijst.add(t);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Methode voor na uitvoering taak.
* Update de UI door ListView te vullen.
* **/
protected void onPostExecute(String file_url) {
// pDialog sluiten
pDialog.dismiss();
if(takenLijst.size()>0) {
// Geen melding
txtGeenTaken.setVisibility(View.GONE);
lvTaken.setVisibility(View.VISIBLE);
runOnUiThread(new Runnable() {
public void run() {
TakenAdapter ta = new TakenAdapter(TakenActivity.this, R.layout.task_list_item, takenLijst);
lvTaken.setAdapter(ta);
}
});
}
else {
// Toon melding
txtGeenTaken.setVisibility(View.VISIBLE);
lvTaken.setVisibility(View.GONE);
}
}
}
/**
* Async Taak op achtergrond om het aantal ongelezen taken op te halen en weer te geven.
* Via HTTP Request naar REST client.
* */
class UpdateTaakStatus extends AsyncTask<ContentValues, String, Integer> {
/**
* Methode die opgeroepen wordt voor uitvoeren van taak.
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TakenActivity.this);
pDialog.setMessage("Updating Taak ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Deze methode wordt in de achtergrond uitgevoerd.
* @param parameters Strings niet relevant
* @return int geslaagd
*/
protected Integer doInBackground(ContentValues... parameters) {
// Maakt de request en geeft het resultaat
JSONObject json = jParser.makeHttpRequest(url_update_taak_status, "POST", parameters[0]);
Log.d("Update taak status: ", json.toString());
try {
return json.getInt(TAG_SUCCES);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
* Methode voor na uitvoering taak.
* Update de UI door de ListView voor taken te herladen.
* **/
protected void onPostExecute(Integer success) {
// pDialog sluiten
pDialog.dismiss();
if (success == 1) {
new LaadAlleTaken().execute();
}
}
}
}
| ThomasVandenabeele/kinefit-android-app | src/main/java/com/KineFit/app/activities/TakenActivity.java | 3,851 | /** ListView voor de taken */ | block_comment | nl | package com.KineFit.app.activities;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.KineFit.app.R;
import com.KineFit.app.adapters.TakenAdapter;
import com.KineFit.app.model.Taak;
import com.KineFit.app.model.enums.TaskStatus;
import com.KineFit.app.services.JSONParser;
import org.json.JSONArray;
import org.json.JSONObject;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
/**
* Activity voor het taken overzicht.
* Op deze activity kan de gebruiker taken bekijken en voltooien.
*
* Created by Thomas on 30/04/16.
* @author Thomas Vandenabeele
*/
public class TakenActivity extends BasisActivity {
//region DATAMEMBERS
/** pDialog voor de UI */
private ProgressDialog pDialog;
/** LinearLayout voor het filtermenu */
private LinearLayout filterTakenMenu;
/** ToggleButton voor filteren */
private ToggleButton tbFilter;
/** Switch voor gesloten taken */
private Switch sGeslotenTaken;
/** Switch voor gefaalde taken */
private Switch sGefaaldeTaken;
/** Boolean gesloten taken */
private boolean geslotenTaken;
/** Boolean gefaalde taken */
private boolean gefaaldeTaken;
/** ListView voor de<SUF>*/
private ListView lvTaken;
/** TextView voor melding geen taken */
private TextView txtGeenTaken;
/** TakenLijst */
private ArrayList<Taak> takenLijst;
/** SQL datum formatter */
private SimpleDateFormat sqlDatumFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/** Korte datum formatter */
private SimpleDateFormat korteDatum = new SimpleDateFormat("dd-MM-yyyy");
/** Korte tijd formatter */
private SimpleDateFormat korteTijd = new SimpleDateFormat("HH:mm");
//endregion
//region REST: TAGS & URL
/** JSONParser voor de REST client aan te spreken */
JSONParser jParser = new JSONParser();
/** Tag voor gebruikersnaam */
private static final String TAG_GEBRUIKERSNAAM = "username";
//-------------------------------------------------------------------------------------------------------------------------------//
/** URL om alle taken op te vragen */
private static String url_alle_taken = "http://thomasvandenabeele.no-ip.org/KineFit/get_all_tasks.php";
/** Tag voor succes */
private static final String TAG_SUCCES = "success";
/** Tag voor taken */
private static final String TAG_TAKEN = "tasks";
/** Tag voor taak id */
private static final String TAG_ID = "id";
/** Tag voor taak naam */
private static final String TAG_NAAM = "message";
/** Tag voor taak aanmaak datum */
private static final String TAG_AANMAAKDATUM = "created_at";
/** Tag voor taak status */
private static final String TAG_STATUS = "status";
//-------------------------------------------------------------------------------------------------------------------------------//
/** URL om het de status van een taak te updaten */
private static String url_update_taak_status = "http://thomasvandenabeele.no-ip.org/KineFit/update_status_task.php";
/** ID van de status */
private static final String TAG_STATUS_ID = "id";
/** Naam van de status */
private static final String TAG_STATUS_NAAM = "name";
//-------------------------------------------------------------------------------------------------------------------------------//
//endregion
/**
* Methode die opgeroepen wordt bij aanmaak activity.
* @param savedInstanceState
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.taken_lijst);
//region UI componenten toekennen
txtGeenTaken = (TextView) findViewById(R.id.txtGeenTaken);
filterTakenMenu = (LinearLayout)findViewById(R.id.filterMenuTaken);
tbFilter = (ToggleButton)findViewById(R.id.tbFilter);
sGeslotenTaken = (Switch)findViewById(R.id.sGeslotenTaken);
sGefaaldeTaken = (Switch)findViewById(R.id.sGefaaldeTaken);
lvTaken = (ListView)findViewById(R.id.lvTaken);
//endregion
// OnCheckedChangeListener voor togglebutton filteren
tbFilter.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
// Toon filter menu
filterTakenMenu.setVisibility(View.VISIBLE);
}
else{
// Verberg filter menu
filterTakenMenu.setVisibility(View.GONE);
}
}
});
// OnCheckedChangeListener voor sGeslotenTaken
sGeslotenTaken.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
geslotenTaken = isChecked;
// Herlaad de listView
new LaadAlleTaken().execute();
}
});
// OnCheckedChangeListener voor sGefaaldeTaken
sGefaaldeTaken.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
gefaaldeTaken = isChecked;
// Herlaad de listView
new LaadAlleTaken().execute();
}
});
// Instantiëren members
geslotenTaken = sGeslotenTaken.isChecked();
gefaaldeTaken = sGefaaldeTaken.isChecked();
takenLijst = new ArrayList<Taak>();
// Laad de listView
new LaadAlleTaken().execute();
// OnItemClickListener voor ListView
lvTaken.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Get de geselecteerde taak
Taak t = takenLijst.get(position);
// Volgende code enkel wanneer de status nieuw of open is:
if(t.getStatus().equals(TaskStatus.OPEN)||t.getStatus().equals(TaskStatus.NEW)){
final String pid = ((TextView) view.findViewById(R.id.task_pid)).getText().toString();
final ContentValues parameters = new ContentValues();
parameters.put(TAG_STATUS_ID, pid);
// Maak alert venster
new AlertDialog.Builder(TakenActivity.this)
.setTitle("Voltooi taak")
.setMessage("Is u in deze taak geslaagd?")
.setPositiveButton("Geslaagd",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
parameters.put(TAG_STATUS_NAAM, TaskStatus.DONE.toString());
new UpdateTaakStatus().execute(parameters);
// Sluit alert
dialog.cancel();
}
})
.setNeutralButton("Gefaald",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
parameters.put(TAG_STATUS_NAAM, TaskStatus.FAILED.toString());
new UpdateTaakStatus().execute(parameters);
// Sluit alert
dialog.cancel();
}
})
.setNegativeButton("Annuleren",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Sluit alert
dialog.cancel();
}
})
.setCancelable(false)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
});
}
/**
* Async Taak op achtergrond om het aantal ongelezen taken op te halen en weer te geven.
* Via HTTP Request naar REST client.
* */
class LaadAlleTaken extends AsyncTask<String, String, String> {
/**
* Methode die opgeroepen wordt voor uitvoeren van taak.
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TakenActivity.this);
pDialog.setMessage("Taken laden, gelieve even te wachten aub...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Deze methode wordt in de achtergrond uitgevoerd.
* @param params Strings niet relevant
* @return niet relevant
*/
protected String doInBackground(String... params) {
// Maakt de request en geeft het resultaat
ContentValues parameters = new ContentValues();
parameters.put(TAG_GEBRUIKERSNAAM, sessie.getUsername());
JSONObject json = jParser.makeHttpRequest(url_alle_taken, "GET", parameters);
Log.d("Alle taken: ", json.toString());
try {
if (json.getInt(TAG_SUCCES) == 1) {
// Taken ophalen
JSONArray tasks = json.getJSONArray(TAG_TAKEN);
takenLijst.clear();
// Omzetten in ArrayList<Taak>
for (int i = 0; i < tasks.length(); i++) {
JSONObject c = tasks.getJSONObject(i);
java.sql.Date aanmaakDatum = new java.sql.Date(sqlDatumFormatter.parse(c.getString(TAG_AANMAAKDATUM)).getTime());
Taak t = new Taak(c.getInt(TAG_ID),
c.getString(TAG_NAAM),
aanmaakDatum,
TaskStatus.valueOf(c.getString(TAG_STATUS)));
// Filtercriteria checken
boolean add = true;
switch (t.getStatus()){
case DONE:
if(!geslotenTaken) add = false;
break;
case FAILED:
if(!gefaaldeTaken) add = false;
break;
default:
add = true;
break;
}
// Toevoegen aan lijst
if(add) takenLijst.add(t);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Methode voor na uitvoering taak.
* Update de UI door ListView te vullen.
* **/
protected void onPostExecute(String file_url) {
// pDialog sluiten
pDialog.dismiss();
if(takenLijst.size()>0) {
// Geen melding
txtGeenTaken.setVisibility(View.GONE);
lvTaken.setVisibility(View.VISIBLE);
runOnUiThread(new Runnable() {
public void run() {
TakenAdapter ta = new TakenAdapter(TakenActivity.this, R.layout.task_list_item, takenLijst);
lvTaken.setAdapter(ta);
}
});
}
else {
// Toon melding
txtGeenTaken.setVisibility(View.VISIBLE);
lvTaken.setVisibility(View.GONE);
}
}
}
/**
* Async Taak op achtergrond om het aantal ongelezen taken op te halen en weer te geven.
* Via HTTP Request naar REST client.
* */
class UpdateTaakStatus extends AsyncTask<ContentValues, String, Integer> {
/**
* Methode die opgeroepen wordt voor uitvoeren van taak.
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TakenActivity.this);
pDialog.setMessage("Updating Taak ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Deze methode wordt in de achtergrond uitgevoerd.
* @param parameters Strings niet relevant
* @return int geslaagd
*/
protected Integer doInBackground(ContentValues... parameters) {
// Maakt de request en geeft het resultaat
JSONObject json = jParser.makeHttpRequest(url_update_taak_status, "POST", parameters[0]);
Log.d("Update taak status: ", json.toString());
try {
return json.getInt(TAG_SUCCES);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
* Methode voor na uitvoering taak.
* Update de UI door de ListView voor taken te herladen.
* **/
protected void onPostExecute(Integer success) {
// pDialog sluiten
pDialog.dismiss();
if (success == 1) {
new LaadAlleTaken().execute();
}
}
}
}
| false | 2,670 | 6 | 3,048 | 6 | 3,150 | 6 | 3,048 | 6 | 3,752 | 6 | false | false | false | false | false | true |
4,422 | 177505_9 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import bean.CartBean;
import dao.OrderDAO;
import dao.OrderProductDAO;
import model.hibernate.Order;
import model.hibernate.OrderProduct;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
/**
*
* @author Stefan
*/
public class CartController extends HttpServlet {
CartBean cartBean = new CartBean();
HttpSession session;
/* HTTP GET request */
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
/* Call the session, or create it of it does not exist */
this.session = request.getSession(true);
// Check if there is already an instance of the cartBean in the session
if(this.session.getAttribute("cartBean") != null)
// And assign it if there is
cartBean = (CartBean) this.session.getAttribute("cartBean");
// Set an attribute containing the cart bean
request.setAttribute("cartBean", cartBean);
// Set a session attribute containing the cart bean
this.session.setAttribute("cartBean", cartBean);
// Stel de pagina in die bij deze controller hoort
String address = "cart.jsp";
// Doe een verzoek naar het adres
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
// Stuur door naar bovenstaande adres
dispatcher.forward(request, response);
}
/* HTTP POST request */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// Set a variable for the address to the JSP file that'll be shown at runtime
String address;
// Create an instance of the order/orderProduct DAO & Model
OrderDAO orderDao = new OrderDAO();
OrderProductDAO orderProductDao = new OrderProductDAO();
Order order;
OrderProduct orderProduct;
/* Call the session, or create it of it does not exist */
this.session = request.getSession(true);
// Check if there is already an instance of the cartBean in the session
if(this.session.getAttribute("cartBean") != null)
// And assign it if there is
cartBean = (CartBean) this.session.getAttribute("cartBean");
/*
* Check if a customer is logged in prior to placing the order, and make
* sure products are present in the cart.
*/
if(
cartBean.getProduct().size() > 0 &&
cartBean.getCustomer() != null
) {
order = new Order();
order.setCustomer(cartBean.getCustomer());
order.setOrderDate(new Date());
orderDao.create(order);
List orderProductList = new LinkedList();
for(int i = 0; i < cartBean.getProduct().size(); i++) {
orderProduct = new OrderProduct();
orderProduct.setOrder(order);
orderProduct.setProduct(cartBean.getProduct().get(i).getProduct());
orderProduct.setProductQuantity(cartBean.getProduct().get(i).getProductAmount());
orderProductDao.create(orderProduct);
orderProductList.add(orderProduct);
}
// Assign a new empty vector to the product vector
cartBean.setProduct(new Vector());
// Set the page that will be shown when the POST is made
address = "order_success.jsp";
} else {
// Set the page that will be shown when the POST is made
address = "order_failure.jsp";
}
// Set an attribute containing the cart bean
request.setAttribute("cartBean", cartBean);
// Set a session attribute containing the cart bean
this.session.setAttribute("cartBean", cartBean);
// Doe een verzoek naar het adres
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
// Stuur door naar bovenstaande adres
dispatcher.forward(request, response);
}
} | svbeusekom/WEBShop | src/java/controller/CartController.java | 1,080 | // Doe een verzoek naar het adres | line_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import bean.CartBean;
import dao.OrderDAO;
import dao.OrderProductDAO;
import model.hibernate.Order;
import model.hibernate.OrderProduct;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
/**
*
* @author Stefan
*/
public class CartController extends HttpServlet {
CartBean cartBean = new CartBean();
HttpSession session;
/* HTTP GET request */
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
/* Call the session, or create it of it does not exist */
this.session = request.getSession(true);
// Check if there is already an instance of the cartBean in the session
if(this.session.getAttribute("cartBean") != null)
// And assign it if there is
cartBean = (CartBean) this.session.getAttribute("cartBean");
// Set an attribute containing the cart bean
request.setAttribute("cartBean", cartBean);
// Set a session attribute containing the cart bean
this.session.setAttribute("cartBean", cartBean);
// Stel de pagina in die bij deze controller hoort
String address = "cart.jsp";
// Doe een<SUF>
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
// Stuur door naar bovenstaande adres
dispatcher.forward(request, response);
}
/* HTTP POST request */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// Set a variable for the address to the JSP file that'll be shown at runtime
String address;
// Create an instance of the order/orderProduct DAO & Model
OrderDAO orderDao = new OrderDAO();
OrderProductDAO orderProductDao = new OrderProductDAO();
Order order;
OrderProduct orderProduct;
/* Call the session, or create it of it does not exist */
this.session = request.getSession(true);
// Check if there is already an instance of the cartBean in the session
if(this.session.getAttribute("cartBean") != null)
// And assign it if there is
cartBean = (CartBean) this.session.getAttribute("cartBean");
/*
* Check if a customer is logged in prior to placing the order, and make
* sure products are present in the cart.
*/
if(
cartBean.getProduct().size() > 0 &&
cartBean.getCustomer() != null
) {
order = new Order();
order.setCustomer(cartBean.getCustomer());
order.setOrderDate(new Date());
orderDao.create(order);
List orderProductList = new LinkedList();
for(int i = 0; i < cartBean.getProduct().size(); i++) {
orderProduct = new OrderProduct();
orderProduct.setOrder(order);
orderProduct.setProduct(cartBean.getProduct().get(i).getProduct());
orderProduct.setProductQuantity(cartBean.getProduct().get(i).getProductAmount());
orderProductDao.create(orderProduct);
orderProductList.add(orderProduct);
}
// Assign a new empty vector to the product vector
cartBean.setProduct(new Vector());
// Set the page that will be shown when the POST is made
address = "order_success.jsp";
} else {
// Set the page that will be shown when the POST is made
address = "order_failure.jsp";
}
// Set an attribute containing the cart bean
request.setAttribute("cartBean", cartBean);
// Set a session attribute containing the cart bean
this.session.setAttribute("cartBean", cartBean);
// Doe een verzoek naar het adres
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
// Stuur door naar bovenstaande adres
dispatcher.forward(request, response);
}
} | false | 823 | 8 | 928 | 9 | 972 | 8 | 928 | 9 | 1,064 | 11 | false | false | false | false | false | true |
4,731 | 23373_7 | package nl.b3p.geotools.data.dxf.entities;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import nl.b3p.geotools.data.dxf.parser.DXFLineNumberReader;
import java.io.EOFException;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.regex.Pattern;
import nl.b3p.geotools.data.GeometryType;
import nl.b3p.geotools.data.dxf.parser.DXFUnivers;
import nl.b3p.geotools.data.dxf.header.DXFLayer;
import nl.b3p.geotools.data.dxf.header.DXFLineType;
import nl.b3p.geotools.data.dxf.header.DXFTables;
import nl.b3p.geotools.data.dxf.parser.DXFCodeValuePair;
import nl.b3p.geotools.data.dxf.parser.DXFGroupCode;
import nl.b3p.geotools.data.dxf.parser.DXFParseException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class DXFText extends DXFEntity {
private static final Log log = LogFactory.getLog(DXFText.class);
private Double x = null, y = null;
public DXFText(DXFText newText) {
this(newText.getColor(), newText.getRefLayer(), 0, newText.getLineType(), 0.0);
setStartingLineNumber(newText.getStartingLineNumber());
setType(newText.getType());
setUnivers(newText.getUnivers());
}
public DXFText(int c, DXFLayer l, int visibility, DXFLineType lineType, double thickness) {
super(c, l , visibility, lineType, thickness);
}
public Double getX() {
return x;
}
public void setX(Double x) {
this.x = x;
}
public Double getY() {
return y;
}
public void setY(Double y) {
this.y = y;
}
public static DXFText read(DXFLineNumberReader br, DXFUnivers univers, boolean isMText) throws IOException {
DXFText t = new DXFText(0, null, 0, null, DXFTables.defaultThickness);
t.setUnivers(univers);
t.setName(isMText ? "DXFMText" : "DXFText");
t.setTextrotation(0.0);
t.setStartingLineNumber(br.getLineNumber());
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
// MTEXT direction vector
Double directionX = null, directionY = null;
String textposhor = "left";
String textposver = "bottom";
boolean doLoop = true;
while (doLoop) {
cvp = new DXFCodeValuePair();
try {
gc = cvp.read(br);
} catch (DXFParseException ex) {
throw new IOException("DXF parse error" + ex.getLocalizedMessage());
} catch (EOFException e) {
doLoop = false;
break;
}
switch (gc) {
case TYPE:
// geldt voor alle waarden van type
br.reset();
doLoop = false;
break;
case X_1: //"10"
t.setX(cvp.getDoubleValue());
break;
case Y_1: //"20"
t.setY(cvp.getDoubleValue());
break;
case TEXT: //"1"
t.setText(processOrStripTextCodes(cvp.getStringValue()));
break;
case ANGLE_1: //"50"
t.setTextrotation(cvp.getDoubleValue());
break;
case X_2: // 11, X-axis direction vector
directionX = cvp.getDoubleValue();
break;
case Y_2: // 21, Y-axis direction vector
directionY = cvp.getDoubleValue();
break;
case THICKNESS: //"39"
t.setThickness(cvp.getDoubleValue());
break;
case DOUBLE_1: //"40"
t.setTextheight(cvp.getDoubleValue());
break;
case INT_2: // 71: MTEXT attachment point
switch(cvp.getShortValue()) {
case 1: textposver = "top"; textposhor = "left"; break;
case 2: textposver = "top"; textposhor = "center"; break;
case 3: textposver = "top"; textposhor = "right"; break;
case 4: textposver = "middle"; textposhor = "left"; break;
case 5: textposver = "middle"; textposhor = "center"; break;
case 6: textposver = "middle"; textposhor = "right"; break;
case 7: textposver = "bottom"; textposhor = "left"; break;
case 8: textposver = "bottom"; textposhor = "center"; break;
case 9: textposver = "bottom"; textposhor = "right"; break;
}
break;
case INT_3: // 72: TEXT horizontal text justification type
// komen niet helemaal overeen, maar maak voor TEXT en MTEXT hetzelfde
switch(cvp.getShortValue()) {
case 0: textposhor = "left"; break;
case 1: textposhor = "center"; break;
case 2: textposhor = "right"; break;
case 3: // aligned
case 4: // middle
case 5: // fit
// negeer, maar hier "center" van
textposhor = "center";
}
break;
case INT_4:
switch(cvp.getShortValue()) {
case 0: textposver = "bottom"; break; // eigenlijk baseline
case 1: textposver = "bottom"; break;
case 2: textposver = "middle"; break;
case 3: textposver = "top"; break;
}
break;
case LAYER_NAME: //"8"
t._refLayer = univers.findLayer(cvp.getStringValue());
break;
case COLOR: //"62"
t.setColor(cvp.getShortValue());
break;
case VISIBILITY: //"60"
t.setVisible(cvp.getShortValue() == 0);
break;
default:
break;
}
}
t.setTextposvertical(textposver);
t.setTextposhorizontal(textposhor);
if(isMText && directionX != null && directionY != null) {
t.setTextrotation(calculateRotationFromDirectionVector(directionX, directionY));
if(log.isDebugEnabled()) {
log.debug(MessageFormat.format("MTEXT entity at line number %d: text pos (%.4f,%.4f), direction vector (%.4f,%.4f), calculated text rotation %.2f degrees",
t.getStartingLineNumber(),
t.getX(), t.getY(),
directionX, directionY,
t.getTextrotation()));
}
}
t.setType(GeometryType.POINT);
return t;
}
private static String processOrStripTextCodes(String text) {
if(text == null) {
return null;
}
// http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%202010%20User%20Documentation/index.html?url=WS1a9193826455f5ffa23ce210c4a30acaf-63b9.htm,topicNumber=d0e123454
text = text.replaceAll("%%[cC]", "Ø");
text = text.replaceAll("\\\\[Pp]", "\r\n");
text = text.replaceAll("\\\\[Ll~]", "");
text = text.replaceAll(Pattern.quote("\\\\"), "\\");
text = text.replaceAll(Pattern.quote("\\{"), "{");
text = text.replaceAll(Pattern.quote("\\}"), "}");
text = text.replaceAll("\\\\[CcFfHhTtQqWwAa].*;", "");
return text;
}
private static double calculateRotationFromDirectionVector(double x, double y) {
double rotation;
// Hoek tussen vector (1,0) en de direction vector uit MText als theta:
// arccos (theta) = inproduct(A,B) / lengte(A).lengte(B)
// arccos (theta) = Bx / wortel(Bx^2 + By^2)
// indien hoek in kwadrant III of IV, dan theta = -(theta-2PI)
double length = Math.sqrt(x*x + y*y);
if(length == 0) {
rotation = 0;
} else {
double theta = Math.acos(x / length);
if((x <= 0 && y <= 0) || (x >= 0 && y <= 0)) {
theta = -(theta - 2*Math.PI);
}
// conversie van radialen naar graden
rotation = theta * (180/Math.PI);
if(Math.abs(360 - rotation) < 1e-4) {
rotation = 0;
}
}
return rotation;
}
@Override
public Geometry getGeometry() {
if (geometry == null) {
updateGeometry();
}
return geometry;
}
@Override
public void updateGeometry() {
if(x != null && y != null) {
Coordinate c = rotateAndPlace(new Coordinate(x, y));
setGeometry(getUnivers().getGeometryFactory().createPoint(c));
} else {
setGeometry(null);
}
}
@Override
public DXFEntity translate(double x, double y) {
this.x += x;
this.y += y;
return this;
}
@Override
public DXFEntity clone() {
return new DXFText(this);
//throw new UnsupportedOperationException();
}
}
| wscherphof/b3p-gt2-dxf | src/main/java/nl/b3p/geotools/data/dxf/entities/DXFText.java | 2,844 | // negeer, maar hier "center" van | line_comment | nl | package nl.b3p.geotools.data.dxf.entities;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import nl.b3p.geotools.data.dxf.parser.DXFLineNumberReader;
import java.io.EOFException;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.regex.Pattern;
import nl.b3p.geotools.data.GeometryType;
import nl.b3p.geotools.data.dxf.parser.DXFUnivers;
import nl.b3p.geotools.data.dxf.header.DXFLayer;
import nl.b3p.geotools.data.dxf.header.DXFLineType;
import nl.b3p.geotools.data.dxf.header.DXFTables;
import nl.b3p.geotools.data.dxf.parser.DXFCodeValuePair;
import nl.b3p.geotools.data.dxf.parser.DXFGroupCode;
import nl.b3p.geotools.data.dxf.parser.DXFParseException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class DXFText extends DXFEntity {
private static final Log log = LogFactory.getLog(DXFText.class);
private Double x = null, y = null;
public DXFText(DXFText newText) {
this(newText.getColor(), newText.getRefLayer(), 0, newText.getLineType(), 0.0);
setStartingLineNumber(newText.getStartingLineNumber());
setType(newText.getType());
setUnivers(newText.getUnivers());
}
public DXFText(int c, DXFLayer l, int visibility, DXFLineType lineType, double thickness) {
super(c, l , visibility, lineType, thickness);
}
public Double getX() {
return x;
}
public void setX(Double x) {
this.x = x;
}
public Double getY() {
return y;
}
public void setY(Double y) {
this.y = y;
}
public static DXFText read(DXFLineNumberReader br, DXFUnivers univers, boolean isMText) throws IOException {
DXFText t = new DXFText(0, null, 0, null, DXFTables.defaultThickness);
t.setUnivers(univers);
t.setName(isMText ? "DXFMText" : "DXFText");
t.setTextrotation(0.0);
t.setStartingLineNumber(br.getLineNumber());
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
// MTEXT direction vector
Double directionX = null, directionY = null;
String textposhor = "left";
String textposver = "bottom";
boolean doLoop = true;
while (doLoop) {
cvp = new DXFCodeValuePair();
try {
gc = cvp.read(br);
} catch (DXFParseException ex) {
throw new IOException("DXF parse error" + ex.getLocalizedMessage());
} catch (EOFException e) {
doLoop = false;
break;
}
switch (gc) {
case TYPE:
// geldt voor alle waarden van type
br.reset();
doLoop = false;
break;
case X_1: //"10"
t.setX(cvp.getDoubleValue());
break;
case Y_1: //"20"
t.setY(cvp.getDoubleValue());
break;
case TEXT: //"1"
t.setText(processOrStripTextCodes(cvp.getStringValue()));
break;
case ANGLE_1: //"50"
t.setTextrotation(cvp.getDoubleValue());
break;
case X_2: // 11, X-axis direction vector
directionX = cvp.getDoubleValue();
break;
case Y_2: // 21, Y-axis direction vector
directionY = cvp.getDoubleValue();
break;
case THICKNESS: //"39"
t.setThickness(cvp.getDoubleValue());
break;
case DOUBLE_1: //"40"
t.setTextheight(cvp.getDoubleValue());
break;
case INT_2: // 71: MTEXT attachment point
switch(cvp.getShortValue()) {
case 1: textposver = "top"; textposhor = "left"; break;
case 2: textposver = "top"; textposhor = "center"; break;
case 3: textposver = "top"; textposhor = "right"; break;
case 4: textposver = "middle"; textposhor = "left"; break;
case 5: textposver = "middle"; textposhor = "center"; break;
case 6: textposver = "middle"; textposhor = "right"; break;
case 7: textposver = "bottom"; textposhor = "left"; break;
case 8: textposver = "bottom"; textposhor = "center"; break;
case 9: textposver = "bottom"; textposhor = "right"; break;
}
break;
case INT_3: // 72: TEXT horizontal text justification type
// komen niet helemaal overeen, maar maak voor TEXT en MTEXT hetzelfde
switch(cvp.getShortValue()) {
case 0: textposhor = "left"; break;
case 1: textposhor = "center"; break;
case 2: textposhor = "right"; break;
case 3: // aligned
case 4: // middle
case 5: // fit
// negeer, maar<SUF>
textposhor = "center";
}
break;
case INT_4:
switch(cvp.getShortValue()) {
case 0: textposver = "bottom"; break; // eigenlijk baseline
case 1: textposver = "bottom"; break;
case 2: textposver = "middle"; break;
case 3: textposver = "top"; break;
}
break;
case LAYER_NAME: //"8"
t._refLayer = univers.findLayer(cvp.getStringValue());
break;
case COLOR: //"62"
t.setColor(cvp.getShortValue());
break;
case VISIBILITY: //"60"
t.setVisible(cvp.getShortValue() == 0);
break;
default:
break;
}
}
t.setTextposvertical(textposver);
t.setTextposhorizontal(textposhor);
if(isMText && directionX != null && directionY != null) {
t.setTextrotation(calculateRotationFromDirectionVector(directionX, directionY));
if(log.isDebugEnabled()) {
log.debug(MessageFormat.format("MTEXT entity at line number %d: text pos (%.4f,%.4f), direction vector (%.4f,%.4f), calculated text rotation %.2f degrees",
t.getStartingLineNumber(),
t.getX(), t.getY(),
directionX, directionY,
t.getTextrotation()));
}
}
t.setType(GeometryType.POINT);
return t;
}
private static String processOrStripTextCodes(String text) {
if(text == null) {
return null;
}
// http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%202010%20User%20Documentation/index.html?url=WS1a9193826455f5ffa23ce210c4a30acaf-63b9.htm,topicNumber=d0e123454
text = text.replaceAll("%%[cC]", "Ø");
text = text.replaceAll("\\\\[Pp]", "\r\n");
text = text.replaceAll("\\\\[Ll~]", "");
text = text.replaceAll(Pattern.quote("\\\\"), "\\");
text = text.replaceAll(Pattern.quote("\\{"), "{");
text = text.replaceAll(Pattern.quote("\\}"), "}");
text = text.replaceAll("\\\\[CcFfHhTtQqWwAa].*;", "");
return text;
}
private static double calculateRotationFromDirectionVector(double x, double y) {
double rotation;
// Hoek tussen vector (1,0) en de direction vector uit MText als theta:
// arccos (theta) = inproduct(A,B) / lengte(A).lengte(B)
// arccos (theta) = Bx / wortel(Bx^2 + By^2)
// indien hoek in kwadrant III of IV, dan theta = -(theta-2PI)
double length = Math.sqrt(x*x + y*y);
if(length == 0) {
rotation = 0;
} else {
double theta = Math.acos(x / length);
if((x <= 0 && y <= 0) || (x >= 0 && y <= 0)) {
theta = -(theta - 2*Math.PI);
}
// conversie van radialen naar graden
rotation = theta * (180/Math.PI);
if(Math.abs(360 - rotation) < 1e-4) {
rotation = 0;
}
}
return rotation;
}
@Override
public Geometry getGeometry() {
if (geometry == null) {
updateGeometry();
}
return geometry;
}
@Override
public void updateGeometry() {
if(x != null && y != null) {
Coordinate c = rotateAndPlace(new Coordinate(x, y));
setGeometry(getUnivers().getGeometryFactory().createPoint(c));
} else {
setGeometry(null);
}
}
@Override
public DXFEntity translate(double x, double y) {
this.x += x;
this.y += y;
return this;
}
@Override
public DXFEntity clone() {
return new DXFText(this);
//throw new UnsupportedOperationException();
}
}
| false | 2,175 | 11 | 2,416 | 12 | 2,560 | 10 | 2,416 | 12 | 2,890 | 11 | false | false | false | false | false | true |
1,458 | 62866_7 | package stamboom.domain;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.*;
import javafx.beans.property.LongProperty;
import javafx.beans.property.SimpleLongProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import stamboom.util.StringUtilities;
public class Gezin implements Serializable {
// *********datavelden*************************************
private final int nr;
private final Persoon ouder1;
private final Persoon ouder2;
private final List<Persoon> kinderen;
private transient ObservableList<Persoon> obsKinderen;
private String childnames = "";
/**
* kan onbekend zijn (dan is het een ongehuwd gezin):
*/
private Calendar huwelijksdatum ;
/**
* kan null zijn; als huwelijksdatum null is, dan zal scheidingsdatum ook null
* zijn; Als huwelijksdatum en scheidingsdatum bekend zijn, dan zal de
* scheidingsdatum na het huewelijk zijn.
*/
private Calendar scheidingsdatum ;
// *********constructoren***********************************
/**
* er wordt een (kinderloos) gezin met ouder1 en ouder2 als ouders
* geregistreerd; de huwelijks-(en scheidings)datum zijn onbekend (null);
* het gezin krijgt gezinsNr als nummer;
*
* @param ouder1 mag niet null zijn, moet al geboren zijn,
* en mag geen famillie van ouder2 zijn.
* @param ouder2 ongelijk aan ouder1, moet al geboren zijn,
* en mag geen familie van ouder1 zijn.
*/
Gezin(int gezinsNr, Persoon ouder1, Persoon ouder2) {
if (ouder1 == null) {
throw new RuntimeException("Eerste ouder mag niet null zijn");
}
if (ouder1 == ouder2) {
throw new RuntimeException("ouders hetzelfde");
}
if (ouder2 != null) {
if (ouder1.getOuderlijkGezin() != null
&& ouder1.getOuderlijkGezin().isFamilieVan(ouder2)) {
throw new RuntimeException("ouder 2 is familie van ouder 1");
}
if (ouder2.getOuderlijkGezin() != null
&& ouder2.getOuderlijkGezin().isFamilieVan(ouder1)) {
throw new RuntimeException("ouder 1 is familie van ouder 2");
}
}
if (ouder1.getGebDat().compareTo(Calendar.getInstance()) > 0){
throw new RuntimeException("ouder1 moet nog geboren worden");
}
if (ouder2 != null && ouder2.getGebDat().compareTo(Calendar.getInstance()) > 0)
{
throw new RuntimeException("ouder2 moet nog geboren worden");
}
this.nr = gezinsNr;
this.ouder1 = ouder1;
this.ouder2 = ouder2;
this.huwelijksdatum = null;
this.scheidingsdatum = null;
kinderen = new ArrayList<>();
obsKinderen = FXCollections.observableList(kinderen);
}
// ********methoden*****************************************
public ObservableList<Persoon> getKinderen() {
return (ObservableList<Persoon>) FXCollections.unmodifiableObservableList(obsKinderen);
}
/**
* @return alle kinderen uit dit gezin
*/
// public List<Persoon> getKinderen() {
// return (List<Persoon>) Collections.unmodifiableList(kinderen);
// }
/**
*
* @return het aantal kinderen in dit gezin
*/
public int aantalKinderen() {
return kinderen.size();
}
/**
*
* @return het nummer van dit gezin
*/
public int getNr() {
return nr;
}
/**
* @return de eerste ouder van dit gezin
*/
public Persoon getOuder1() {
return ouder1;
}
/**
* @return de tweede ouder van dit gezin (kan null zijn)
*/
public Persoon getOuder2() {
return ouder2;
}
/**
*
* @return het nr, de naam van de eerste ouder, gevolgd door de naam van de
* eventuele tweede ouder. Als dit gezin getrouwd is, wordt ook de huwelijksdatum
* vermeld.
*/
@Override
public String toString() {
StringBuilder s = new StringBuilder();
s.append(this.nr).append(" ");
s.append(ouder1.getNaam());
if (ouder2 != null) {
s.append(" met ");
s.append(ouder2.getNaam());
}
if (heeftGetrouwdeOudersOp(Calendar.getInstance())) {
s.append(" ").append(StringUtilities.datumString(huwelijksdatum));
}
return s.toString().trim();
}
/**
* @return de datum van het huwelijk (kan null zijn)
*/
public Calendar getHuwelijksdatum() {
return huwelijksdatum;
}
/**
* @return de datum van scheiding (kan null zijn)
*/
public Calendar getScheidingsdatum() {
return scheidingsdatum;
}
/**
* Als ouders zijn gehuwd, en er nog geen scheidingsdatum is dan wordt deze
* geregistreerd.
*
* @param datum moet na de huwelijksdatum zijn.
* @return true als scheiding kan worden voltrokken, anders false
*/
boolean setScheiding(Calendar datum) {
if (this.scheidingsdatum == null && huwelijksdatum != null
&& datum != null && datum.after(huwelijksdatum)) {
this.scheidingsdatum = datum;
return true;
} else {
return false;
}
}
/**
* registreert het huwelijk, mits dit gezin nog geen huwelijk is en beide
* ouders op deze datum mogen trouwen (pas op: het is mogelijk dat er al wel
* een huwelijk staat gepland, maar nog niet is voltrokken op deze datum)
* Mensen mogen niet trouwen voor hun achttiende.
*
* @param datum de huwelijksdatum
* @return false als huwelijk niet mocht worden voltrokken, anders true
*/
boolean setHuwelijk(Calendar datum) {
//todo opgave 1
Calendar today = Calendar.getInstance();
int ageOuder1 = today.get(Calendar.YEAR) - ouder1.getGebDat().get(Calendar.YEAR);
int ageOuder2 = today.get(Calendar.YEAR) - ouder2.getGebDat().get(Calendar.YEAR);
if(ageOuder1 < 18 || ageOuder2 < 18)
{
return false;
}
if(datum.before(huwelijksdatum)|| huwelijksdatum == null)
{
huwelijksdatum = datum;
return true;
}
else
{
return false;
}
}
/**
* @return het gezinsnummer, gevolgd door de namen van de ouder(s),
* de eventueel bekende huwelijksdatum, (als er kinderen zijn)
* de constante tekst '; kinderen:', en de voornamen van de
* kinderen uit deze relatie (per kind voorafgegaan door ' -')
*/
public String beschrijving() {
//todo opgave 1
String result = this.nr + " " + this.ouder1.getNaam() + " met " + this.ouder2.getNaam();
if (this.huwelijksdatum != null) {
result = result + " " + StringUtilities.datumString(huwelijksdatum);
}
if (this.kinderen != null && this.kinderen.size() >= 1) {
result = result + "; kinderen: ";
for (Persoon persoon : this.kinderen) {
result = result + "-" + persoon.getVoornamen() + " ";
}
}
return result.trim();
}
public String beschrijvingKinderen() {
//todo opgave 1
String result = "";
if (this.kinderen != null && this.kinderen.size() >= 1) {
for (Persoon persoon : this.kinderen) {
result = result + persoon.getVoornamen() + " ";
}
}
return result.trim();
}
/**
* Voegt kind toe aan dit gezin. Doet niets als dit kind al deel uitmaakt
* van deze familie.
*
* @param kind
*/
void breidUitMet(Persoon kind) {
if (!kinderen.contains(kind) && !this.isFamilieVan(kind)) {
kinderen.add(kind);
}
}
/**
* Controleert of deze familie niet al de gegeven persoon bevat.
*
* @param input
* @return true als deze familie de gegeven persoon bevat.
*/
boolean isFamilieVan(Persoon input) {
if (this.ouder1.getNr() == input.getNr()
|| (this.ouder2 != null && this.ouder2.getNr() == input.getNr())
|| kinderen.contains(input)) {
return true;
}
boolean output = this.ouder1.getOuderlijkGezin() != null
&& this.ouder1.getOuderlijkGezin().isFamilieVan(input);
if (!output && this.ouder2 != null) {
output = this.ouder2.getOuderlijkGezin() != null
&& this.ouder2.getOuderlijkGezin().isFamilieVan(input);
}
return output;
}
/**
*
* @param datum
* @return true als dit gezin op datum getrouwd en nog niet gescheiden is,
* anders false
*/
public boolean heeftGetrouwdeOudersOp(Calendar datum) {
return isHuwelijkOp(datum) && (scheidingsdatum == null || scheidingsdatum.after(datum));
}
/**
*
* @param datum
* @return true als dit gezin op of voor deze datum getrouwd is, ongeacht of
* de ouders hierna gingen/gaan scheiden.
*/
public boolean isHuwelijkOp(Calendar datum) {
//todo opgave 1
if(huwelijksdatum == null){
return false;
}
else if(huwelijksdatum.before(datum)){
return true;
}
return false;
}
/**
*
* @return true als de ouders van dit gezin niet getrouwd zijn, anders false
*/
public boolean isOngehuwd() {
if(huwelijksdatum == null){
return true;
}
return false;
}
/**
*
* @param datum
* @return true als dit een gescheiden huwelijk is op datum, anders false
*/
public boolean heeftGescheidenOudersOp(Calendar datum) {
//todo opgave 1
boolean isGescheiden = false;
if(ouder1.isGescheidenOp(datum))
{
isGescheiden = true;
}
if(ouder2.isGescheidenOp(datum))
{
isGescheiden = true;
}
return isGescheiden;
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject();
obsKinderen = FXCollections.observableList(kinderen);
}
}
| Requinard/C2j | src/stamboom/domain/Gezin.java | 3,221 | /**
*
* @return het nummer van dit gezin
*/ | block_comment | nl | package stamboom.domain;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.*;
import javafx.beans.property.LongProperty;
import javafx.beans.property.SimpleLongProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import stamboom.util.StringUtilities;
public class Gezin implements Serializable {
// *********datavelden*************************************
private final int nr;
private final Persoon ouder1;
private final Persoon ouder2;
private final List<Persoon> kinderen;
private transient ObservableList<Persoon> obsKinderen;
private String childnames = "";
/**
* kan onbekend zijn (dan is het een ongehuwd gezin):
*/
private Calendar huwelijksdatum ;
/**
* kan null zijn; als huwelijksdatum null is, dan zal scheidingsdatum ook null
* zijn; Als huwelijksdatum en scheidingsdatum bekend zijn, dan zal de
* scheidingsdatum na het huewelijk zijn.
*/
private Calendar scheidingsdatum ;
// *********constructoren***********************************
/**
* er wordt een (kinderloos) gezin met ouder1 en ouder2 als ouders
* geregistreerd; de huwelijks-(en scheidings)datum zijn onbekend (null);
* het gezin krijgt gezinsNr als nummer;
*
* @param ouder1 mag niet null zijn, moet al geboren zijn,
* en mag geen famillie van ouder2 zijn.
* @param ouder2 ongelijk aan ouder1, moet al geboren zijn,
* en mag geen familie van ouder1 zijn.
*/
Gezin(int gezinsNr, Persoon ouder1, Persoon ouder2) {
if (ouder1 == null) {
throw new RuntimeException("Eerste ouder mag niet null zijn");
}
if (ouder1 == ouder2) {
throw new RuntimeException("ouders hetzelfde");
}
if (ouder2 != null) {
if (ouder1.getOuderlijkGezin() != null
&& ouder1.getOuderlijkGezin().isFamilieVan(ouder2)) {
throw new RuntimeException("ouder 2 is familie van ouder 1");
}
if (ouder2.getOuderlijkGezin() != null
&& ouder2.getOuderlijkGezin().isFamilieVan(ouder1)) {
throw new RuntimeException("ouder 1 is familie van ouder 2");
}
}
if (ouder1.getGebDat().compareTo(Calendar.getInstance()) > 0){
throw new RuntimeException("ouder1 moet nog geboren worden");
}
if (ouder2 != null && ouder2.getGebDat().compareTo(Calendar.getInstance()) > 0)
{
throw new RuntimeException("ouder2 moet nog geboren worden");
}
this.nr = gezinsNr;
this.ouder1 = ouder1;
this.ouder2 = ouder2;
this.huwelijksdatum = null;
this.scheidingsdatum = null;
kinderen = new ArrayList<>();
obsKinderen = FXCollections.observableList(kinderen);
}
// ********methoden*****************************************
public ObservableList<Persoon> getKinderen() {
return (ObservableList<Persoon>) FXCollections.unmodifiableObservableList(obsKinderen);
}
/**
* @return alle kinderen uit dit gezin
*/
// public List<Persoon> getKinderen() {
// return (List<Persoon>) Collections.unmodifiableList(kinderen);
// }
/**
*
* @return het aantal kinderen in dit gezin
*/
public int aantalKinderen() {
return kinderen.size();
}
/**
*
* @return het nummer<SUF>*/
public int getNr() {
return nr;
}
/**
* @return de eerste ouder van dit gezin
*/
public Persoon getOuder1() {
return ouder1;
}
/**
* @return de tweede ouder van dit gezin (kan null zijn)
*/
public Persoon getOuder2() {
return ouder2;
}
/**
*
* @return het nr, de naam van de eerste ouder, gevolgd door de naam van de
* eventuele tweede ouder. Als dit gezin getrouwd is, wordt ook de huwelijksdatum
* vermeld.
*/
@Override
public String toString() {
StringBuilder s = new StringBuilder();
s.append(this.nr).append(" ");
s.append(ouder1.getNaam());
if (ouder2 != null) {
s.append(" met ");
s.append(ouder2.getNaam());
}
if (heeftGetrouwdeOudersOp(Calendar.getInstance())) {
s.append(" ").append(StringUtilities.datumString(huwelijksdatum));
}
return s.toString().trim();
}
/**
* @return de datum van het huwelijk (kan null zijn)
*/
public Calendar getHuwelijksdatum() {
return huwelijksdatum;
}
/**
* @return de datum van scheiding (kan null zijn)
*/
public Calendar getScheidingsdatum() {
return scheidingsdatum;
}
/**
* Als ouders zijn gehuwd, en er nog geen scheidingsdatum is dan wordt deze
* geregistreerd.
*
* @param datum moet na de huwelijksdatum zijn.
* @return true als scheiding kan worden voltrokken, anders false
*/
boolean setScheiding(Calendar datum) {
if (this.scheidingsdatum == null && huwelijksdatum != null
&& datum != null && datum.after(huwelijksdatum)) {
this.scheidingsdatum = datum;
return true;
} else {
return false;
}
}
/**
* registreert het huwelijk, mits dit gezin nog geen huwelijk is en beide
* ouders op deze datum mogen trouwen (pas op: het is mogelijk dat er al wel
* een huwelijk staat gepland, maar nog niet is voltrokken op deze datum)
* Mensen mogen niet trouwen voor hun achttiende.
*
* @param datum de huwelijksdatum
* @return false als huwelijk niet mocht worden voltrokken, anders true
*/
boolean setHuwelijk(Calendar datum) {
//todo opgave 1
Calendar today = Calendar.getInstance();
int ageOuder1 = today.get(Calendar.YEAR) - ouder1.getGebDat().get(Calendar.YEAR);
int ageOuder2 = today.get(Calendar.YEAR) - ouder2.getGebDat().get(Calendar.YEAR);
if(ageOuder1 < 18 || ageOuder2 < 18)
{
return false;
}
if(datum.before(huwelijksdatum)|| huwelijksdatum == null)
{
huwelijksdatum = datum;
return true;
}
else
{
return false;
}
}
/**
* @return het gezinsnummer, gevolgd door de namen van de ouder(s),
* de eventueel bekende huwelijksdatum, (als er kinderen zijn)
* de constante tekst '; kinderen:', en de voornamen van de
* kinderen uit deze relatie (per kind voorafgegaan door ' -')
*/
public String beschrijving() {
//todo opgave 1
String result = this.nr + " " + this.ouder1.getNaam() + " met " + this.ouder2.getNaam();
if (this.huwelijksdatum != null) {
result = result + " " + StringUtilities.datumString(huwelijksdatum);
}
if (this.kinderen != null && this.kinderen.size() >= 1) {
result = result + "; kinderen: ";
for (Persoon persoon : this.kinderen) {
result = result + "-" + persoon.getVoornamen() + " ";
}
}
return result.trim();
}
public String beschrijvingKinderen() {
//todo opgave 1
String result = "";
if (this.kinderen != null && this.kinderen.size() >= 1) {
for (Persoon persoon : this.kinderen) {
result = result + persoon.getVoornamen() + " ";
}
}
return result.trim();
}
/**
* Voegt kind toe aan dit gezin. Doet niets als dit kind al deel uitmaakt
* van deze familie.
*
* @param kind
*/
void breidUitMet(Persoon kind) {
if (!kinderen.contains(kind) && !this.isFamilieVan(kind)) {
kinderen.add(kind);
}
}
/**
* Controleert of deze familie niet al de gegeven persoon bevat.
*
* @param input
* @return true als deze familie de gegeven persoon bevat.
*/
boolean isFamilieVan(Persoon input) {
if (this.ouder1.getNr() == input.getNr()
|| (this.ouder2 != null && this.ouder2.getNr() == input.getNr())
|| kinderen.contains(input)) {
return true;
}
boolean output = this.ouder1.getOuderlijkGezin() != null
&& this.ouder1.getOuderlijkGezin().isFamilieVan(input);
if (!output && this.ouder2 != null) {
output = this.ouder2.getOuderlijkGezin() != null
&& this.ouder2.getOuderlijkGezin().isFamilieVan(input);
}
return output;
}
/**
*
* @param datum
* @return true als dit gezin op datum getrouwd en nog niet gescheiden is,
* anders false
*/
public boolean heeftGetrouwdeOudersOp(Calendar datum) {
return isHuwelijkOp(datum) && (scheidingsdatum == null || scheidingsdatum.after(datum));
}
/**
*
* @param datum
* @return true als dit gezin op of voor deze datum getrouwd is, ongeacht of
* de ouders hierna gingen/gaan scheiden.
*/
public boolean isHuwelijkOp(Calendar datum) {
//todo opgave 1
if(huwelijksdatum == null){
return false;
}
else if(huwelijksdatum.before(datum)){
return true;
}
return false;
}
/**
*
* @return true als de ouders van dit gezin niet getrouwd zijn, anders false
*/
public boolean isOngehuwd() {
if(huwelijksdatum == null){
return true;
}
return false;
}
/**
*
* @param datum
* @return true als dit een gescheiden huwelijk is op datum, anders false
*/
public boolean heeftGescheidenOudersOp(Calendar datum) {
//todo opgave 1
boolean isGescheiden = false;
if(ouder1.isGescheidenOp(datum))
{
isGescheiden = true;
}
if(ouder2.isGescheidenOp(datum))
{
isGescheiden = true;
}
return isGescheiden;
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject();
obsKinderen = FXCollections.observableList(kinderen);
}
}
| false | 2,695 | 17 | 2,941 | 17 | 2,828 | 17 | 2,941 | 17 | 3,236 | 19 | false | false | false | false | false | true |
587 | 19753_4 | /*_x000D_
* To change this template, choose Tools | Templates_x000D_
* and open the template in the editor._x000D_
*/_x000D_
// https://netbeans.org/kb/docs/web/hibernate-webapp.html_x000D_
package Hibernate;_x000D_
_x000D_
import java.util.List;_x000D_
import javax.faces.bean.ManagedBean;_x000D_
import javax.faces.bean.SessionScoped;_x000D_
import javax.faces.model.DataModel;_x000D_
import javax.faces.model.ListDataModel;_x000D_
_x000D_
/**_x000D_
*_x000D_
* @author Eusebius_x000D_
*/_x000D_
@ManagedBean_x000D_
@SessionScoped_x000D_
public class festivalManagedBean {_x000D_
_x000D_
/**_x000D_
* Creates a new instance of festivalManagedBean_x000D_
*/_x000D_
_x000D_
int startId;_x000D_
int endId;_x000D_
DataModel festivalNames;_x000D_
festivalHelper helper;_x000D_
private int recordCount = 2;_x000D_
private int pageSize = 10;_x000D_
_x000D_
private Festivals current;_x000D_
private int selectedItemIndex;_x000D_
_x000D_
public festivalManagedBean() {_x000D_
helper = new festivalHelper();_x000D_
startId = 1;_x000D_
endId = 10;_x000D_
}_x000D_
_x000D_
public festivalManagedBean(int startId, int endId) {_x000D_
helper = new festivalHelper();_x000D_
this.startId = startId;_x000D_
this.endId = endId;_x000D_
}_x000D_
_x000D_
public Festivals getSelected() {_x000D_
if (current == null) {_x000D_
current = new Festivals();_x000D_
selectedItemIndex = -1;_x000D_
}_x000D_
return current;_x000D_
}_x000D_
_x000D_
_x000D_
public DataModel getFestivalNames() {_x000D_
if (festivalNames == null) {_x000D_
festivalNames = new ListDataModel(helper.getFestivalNames(startId, endId));_x000D_
}_x000D_
return festivalNames;_x000D_
}_x000D_
_x000D_
void recreateModel() {_x000D_
festivalNames = null;_x000D_
}_x000D_
_x000D_
public boolean isHasNextPage() {_x000D_
if (endId + pageSize <= recordCount) {_x000D_
return true;_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
public boolean isHasPreviousPage() {_x000D_
if (startId-pageSize > 0) {_x000D_
return true;_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
public String next() {_x000D_
startId = endId+1;_x000D_
endId = endId + pageSize;_x000D_
recreateModel();_x000D_
return "index";_x000D_
}_x000D_
_x000D_
public String previous() {_x000D_
startId = startId - pageSize;_x000D_
endId = endId - pageSize;_x000D_
recreateModel();_x000D_
return "index";_x000D_
}_x000D_
_x000D_
public int getPageSize() {_x000D_
return pageSize;_x000D_
}_x000D_
_x000D_
public String prepareView(){_x000D_
current = (Festivals) getFestivalNames().getRowData();_x000D_
return "browse";_x000D_
}_x000D_
public String prepareList(){_x000D_
recreateModel();_x000D_
return "index";_x000D_
}_x000D_
// alle bands van een bepaald festival ophalen en achter elkaar zetten_x000D_
public String getBands() {_x000D_
List bands = helper.getBandsByID(current.getFestId());_x000D_
StringBuilder totalLineUp = new StringBuilder();_x000D_
for (int i = 0; i < bands.size(); i++) {_x000D_
Bands band = (Bands) bands.get(i);_x000D_
totalLineUp.append(band.getBandNaam());_x000D_
totalLineUp.append(" : ");_x000D_
totalLineUp.append(band.getBandSoortMuziek());_x000D_
totalLineUp.append("; ");_x000D_
}_x000D_
return totalLineUp.toString();_x000D_
}_x000D_
// alle tickets en hun prijs van een bepaald festival ophalen en achter elkaar zetten_x000D_
public String getTicketypes() {_x000D_
List tickets = helper.getTicketsByID(current.getFestId());_x000D_
StringBuilder totalTickets = new StringBuilder();_x000D_
for (int i = 0; i < tickets.size(); i++) {_x000D_
Tickettypes ticket = (Tickettypes) tickets.get(i);_x000D_
totalTickets.append(ticket.getTypOmschr());_x000D_
totalTickets.append(" : €");_x000D_
totalTickets.append(ticket.getTypPrijs().toString());_x000D_
totalTickets.append("; ");_x000D_
}_x000D_
return totalTickets.toString();_x000D_
}_x000D_
}_x000D_
| GeintegreerdProjectGroep16/ProjectDeel2 | src/java/Hibernate/festivalManagedBean.java | 1,089 | // alle tickets en hun prijs van een bepaald festival ophalen en achter elkaar zetten_x000D_ | line_comment | nl | /*_x000D_
* To change this template, choose Tools | Templates_x000D_
* and open the template in the editor._x000D_
*/_x000D_
// https://netbeans.org/kb/docs/web/hibernate-webapp.html_x000D_
package Hibernate;_x000D_
_x000D_
import java.util.List;_x000D_
import javax.faces.bean.ManagedBean;_x000D_
import javax.faces.bean.SessionScoped;_x000D_
import javax.faces.model.DataModel;_x000D_
import javax.faces.model.ListDataModel;_x000D_
_x000D_
/**_x000D_
*_x000D_
* @author Eusebius_x000D_
*/_x000D_
@ManagedBean_x000D_
@SessionScoped_x000D_
public class festivalManagedBean {_x000D_
_x000D_
/**_x000D_
* Creates a new instance of festivalManagedBean_x000D_
*/_x000D_
_x000D_
int startId;_x000D_
int endId;_x000D_
DataModel festivalNames;_x000D_
festivalHelper helper;_x000D_
private int recordCount = 2;_x000D_
private int pageSize = 10;_x000D_
_x000D_
private Festivals current;_x000D_
private int selectedItemIndex;_x000D_
_x000D_
public festivalManagedBean() {_x000D_
helper = new festivalHelper();_x000D_
startId = 1;_x000D_
endId = 10;_x000D_
}_x000D_
_x000D_
public festivalManagedBean(int startId, int endId) {_x000D_
helper = new festivalHelper();_x000D_
this.startId = startId;_x000D_
this.endId = endId;_x000D_
}_x000D_
_x000D_
public Festivals getSelected() {_x000D_
if (current == null) {_x000D_
current = new Festivals();_x000D_
selectedItemIndex = -1;_x000D_
}_x000D_
return current;_x000D_
}_x000D_
_x000D_
_x000D_
public DataModel getFestivalNames() {_x000D_
if (festivalNames == null) {_x000D_
festivalNames = new ListDataModel(helper.getFestivalNames(startId, endId));_x000D_
}_x000D_
return festivalNames;_x000D_
}_x000D_
_x000D_
void recreateModel() {_x000D_
festivalNames = null;_x000D_
}_x000D_
_x000D_
public boolean isHasNextPage() {_x000D_
if (endId + pageSize <= recordCount) {_x000D_
return true;_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
public boolean isHasPreviousPage() {_x000D_
if (startId-pageSize > 0) {_x000D_
return true;_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
public String next() {_x000D_
startId = endId+1;_x000D_
endId = endId + pageSize;_x000D_
recreateModel();_x000D_
return "index";_x000D_
}_x000D_
_x000D_
public String previous() {_x000D_
startId = startId - pageSize;_x000D_
endId = endId - pageSize;_x000D_
recreateModel();_x000D_
return "index";_x000D_
}_x000D_
_x000D_
public int getPageSize() {_x000D_
return pageSize;_x000D_
}_x000D_
_x000D_
public String prepareView(){_x000D_
current = (Festivals) getFestivalNames().getRowData();_x000D_
return "browse";_x000D_
}_x000D_
public String prepareList(){_x000D_
recreateModel();_x000D_
return "index";_x000D_
}_x000D_
// alle bands van een bepaald festival ophalen en achter elkaar zetten_x000D_
public String getBands() {_x000D_
List bands = helper.getBandsByID(current.getFestId());_x000D_
StringBuilder totalLineUp = new StringBuilder();_x000D_
for (int i = 0; i < bands.size(); i++) {_x000D_
Bands band = (Bands) bands.get(i);_x000D_
totalLineUp.append(band.getBandNaam());_x000D_
totalLineUp.append(" : ");_x000D_
totalLineUp.append(band.getBandSoortMuziek());_x000D_
totalLineUp.append("; ");_x000D_
}_x000D_
return totalLineUp.toString();_x000D_
}_x000D_
// alle tickets<SUF>
public String getTicketypes() {_x000D_
List tickets = helper.getTicketsByID(current.getFestId());_x000D_
StringBuilder totalTickets = new StringBuilder();_x000D_
for (int i = 0; i < tickets.size(); i++) {_x000D_
Tickettypes ticket = (Tickettypes) tickets.get(i);_x000D_
totalTickets.append(ticket.getTypOmschr());_x000D_
totalTickets.append(" : €");_x000D_
totalTickets.append(ticket.getTypPrijs().toString());_x000D_
totalTickets.append("; ");_x000D_
}_x000D_
return totalTickets.toString();_x000D_
}_x000D_
}_x000D_
| false | 1,686 | 27 | 1,791 | 35 | 1,835 | 23 | 1,791 | 35 | 1,973 | 31 | false | false | false | false | false | true |
3,988 | 30819_11 | package dynProg.solvers;_x000D_
_x000D_
import dynProg.Solver;_x000D_
_x000D_
public class BottomUpSolver implements Solver{_x000D_
_x000D_
private int[][] matrix;_x000D_
_x000D_
public BottomUpSolver(){ _x000D_
}_x000D_
_x000D_
public static void main(String[] args){_x000D_
BottomUpSolver s = new BottomUpSolver();_x000D_
s.solve(new int[]{3,5,7,9,11}, 17);_x000D_
}_x000D_
_x000D_
_x000D_
public boolean solve(int[] numbers, int sum){ _x000D_
matrix = new int[numbers.length][sum]; _x000D_
// Elke rij bijlangs gaan_x000D_
//M(i,j)_x000D_
//row == i_x000D_
//answer == j_x000D_
int totaal=0;_x000D_
for(int p=0;p<numbers.length;p++){_x000D_
totaal += numbers[p];_x000D_
}_x000D_
for(int i = 0; i<numbers.length; i++){ _x000D_
int somB = 0;_x000D_
for(int j = 0; j<=i; j++){ _x000D_
// Plaats de huidige_x000D_
// Als numbers j is 3 dan wordt er een 1 geplaatst op M(0,2)_x000D_
matrix[i][numbers[j]-1] = numbers[j];_x000D_
_x000D_
// De som uitvoeren_x000D_
// Zolang de som van B kleiner is dan 17 zal hij toegevoegd worden aan de matrix_x000D_
// Als {3,5} aan de beurt is wordt er dus 8 uitgerekend_x000D_
// Gekeken of het kleiner is dan 17_x000D_
// en vervolgens in dit geval op {1,7} geplaatst_x000D_
somB += numbers[j]; _x000D_
if(somB<=sum){ _x000D_
matrix[i][somB - 1] = somB;_x000D_
}_x000D_
_x000D_
// De som van de vorige_x000D_
// Totaal is gelijk aan de som van B - het getal voor de huidige_x000D_
// Dit moet eigenlijk vaker om alle antwoorden te krijgen maar is op dit moment niet nodig om te doen_x000D_
if (j > 0)_x000D_
{_x000D_
totaal = somB - numbers[j - 1];_x000D_
if(totaal-1<=sum){_x000D_
matrix[i][totaal - 1] = totaal;_x000D_
} _x000D_
} _x000D_
} _x000D_
} _x000D_
return solved(sum);_x000D_
}_x000D_
_x000D_
/**_x000D_
* _x000D_
* @param sum_x000D_
* @return_x000D_
*/_x000D_
private boolean solved(int sum){_x000D_
_x000D_
if(sum<= matrix[0].length){_x000D_
//Kijken of er een antwoord staat in de laatste kolom_x000D_
//Elke rij bijlangs gaan en kijken in de laatste kolom of er een antwoord staat_x000D_
for(int i = 0; i<matrix.length; i++){_x000D_
if(matrix[i][sum-1] != 0){ _x000D_
System.out.println("true");_x000D_
return true;_x000D_
}_x000D_
}_x000D_
}_x000D_
return false;_x000D_
}_x000D_
}_x000D_
_x000D_
| phoenixz0024/OGGG_2.3 | DynamicProgramming/src/dynProg/solvers/BottomUpSolver.java | 911 | // Totaal is gelijk aan de som van B - het getal voor de huidige_x000D_ | line_comment | nl | package dynProg.solvers;_x000D_
_x000D_
import dynProg.Solver;_x000D_
_x000D_
public class BottomUpSolver implements Solver{_x000D_
_x000D_
private int[][] matrix;_x000D_
_x000D_
public BottomUpSolver(){ _x000D_
}_x000D_
_x000D_
public static void main(String[] args){_x000D_
BottomUpSolver s = new BottomUpSolver();_x000D_
s.solve(new int[]{3,5,7,9,11}, 17);_x000D_
}_x000D_
_x000D_
_x000D_
public boolean solve(int[] numbers, int sum){ _x000D_
matrix = new int[numbers.length][sum]; _x000D_
// Elke rij bijlangs gaan_x000D_
//M(i,j)_x000D_
//row == i_x000D_
//answer == j_x000D_
int totaal=0;_x000D_
for(int p=0;p<numbers.length;p++){_x000D_
totaal += numbers[p];_x000D_
}_x000D_
for(int i = 0; i<numbers.length; i++){ _x000D_
int somB = 0;_x000D_
for(int j = 0; j<=i; j++){ _x000D_
// Plaats de huidige_x000D_
// Als numbers j is 3 dan wordt er een 1 geplaatst op M(0,2)_x000D_
matrix[i][numbers[j]-1] = numbers[j];_x000D_
_x000D_
// De som uitvoeren_x000D_
// Zolang de som van B kleiner is dan 17 zal hij toegevoegd worden aan de matrix_x000D_
// Als {3,5} aan de beurt is wordt er dus 8 uitgerekend_x000D_
// Gekeken of het kleiner is dan 17_x000D_
// en vervolgens in dit geval op {1,7} geplaatst_x000D_
somB += numbers[j]; _x000D_
if(somB<=sum){ _x000D_
matrix[i][somB - 1] = somB;_x000D_
}_x000D_
_x000D_
// De som van de vorige_x000D_
// Totaal is<SUF>
// Dit moet eigenlijk vaker om alle antwoorden te krijgen maar is op dit moment niet nodig om te doen_x000D_
if (j > 0)_x000D_
{_x000D_
totaal = somB - numbers[j - 1];_x000D_
if(totaal-1<=sum){_x000D_
matrix[i][totaal - 1] = totaal;_x000D_
} _x000D_
} _x000D_
} _x000D_
} _x000D_
return solved(sum);_x000D_
}_x000D_
_x000D_
/**_x000D_
* _x000D_
* @param sum_x000D_
* @return_x000D_
*/_x000D_
private boolean solved(int sum){_x000D_
_x000D_
if(sum<= matrix[0].length){_x000D_
//Kijken of er een antwoord staat in de laatste kolom_x000D_
//Elke rij bijlangs gaan en kijken in de laatste kolom of er een antwoord staat_x000D_
for(int i = 0; i<matrix.length; i++){_x000D_
if(matrix[i][sum-1] != 0){ _x000D_
System.out.println("true");_x000D_
return true;_x000D_
}_x000D_
}_x000D_
}_x000D_
return false;_x000D_
}_x000D_
}_x000D_
_x000D_
| false | 1,152 | 27 | 1,232 | 28 | 1,251 | 24 | 1,232 | 28 | 1,371 | 28 | false | false | false | false | false | true |
955 | 151820_11 | package inholland.nl.eindopdrachtjavafx.DAL;
import inholland.nl.eindopdrachtjavafx.Models.Item;
import inholland.nl.eindopdrachtjavafx.Models.Member;
import java.io.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class Database {
private List<Member> members;
private List<Item> items;
public Database() {
this.members = new ArrayList<>();
this.items = new ArrayList<>();
try {
loadDataForMembers();
loadDataForItems();
} catch (IOException e) {
// add users to collection
this.members.add(new Member(1, "Lars","Lars", "H", "Lars H", LocalDate.of(1990, 1, 1), "1234"));
this.members.add(new Member(2, "Test","Jane", "Doe", "Jane Doe", LocalDate.of(1994, 6, 15), "0000"));
this.members.add(new Member(3, "John","John", "Smith", "John Smith", LocalDate.of(1992, 3, 12), "1234"));
this.members.add(new Member(4, "Jane2","Jane", "Smith", "Jane Smith", LocalDate.of(1995, 8, 23), "5678"));
this.members.add(new Member(5, "John2","John", "Doe", "John Doe", LocalDate.of(1990, 1, 1), "2378"));
// add items to collection
this.items.add(new Item(1, true, "Harry Potter and the Philosopher's Stone", "J.K. Rowling", LocalDate.of(1997, 6, 26)));
this.items.add(new Item(2, true, "Harry Potter and the Chamber of Secrets", "J.K. Rowling", LocalDate.of(1998, 7, 2)));
this.items.add(new Item(3, true, "Harry Potter and the Prisoner of Azkaban", "J.K. Rowling", LocalDate.of(1999, 7, 8)));
this.items.add(new Item(4, true, "Harry Potter and the Goblet of Fire", "J.K. Rowling", LocalDate.of(2000, 7, 8)));
this.items.add(new Item(5, true, "Harry Potter and the Order of the Phoenix", "J.K. Rowling", LocalDate.of(2003, 6, 21)));
this.items.add(new Item(6, true, "Harry Potter and the Half-Blood Prince", "J.K. Rowling", LocalDate.of(2005, 7, 16)));
this.items.add(new Item(7, true, "Harry Potter and the Deathly Hallows", "J.K. Rowling", LocalDate.of(2007, 7, 21)));
}
}
// return collection of users
public List<Member> getMember() {
return members;
}
public List<Item> getAllItems() {
return items;
}
public List<Member> getAllMembers(){
return members;
}
public Item getItem(int itemCode) {
for (Item item : items) {
if (item.getItemCode() == itemCode) {
return item;
}
}
return null;
}
// make method to check if itemcode and member are in database
public boolean checkItemCodeAndMember(int itemCode, int memberID) {
// check if itemcode is in database
for (Item item : items) {
if (item.getItemCode() == itemCode) {
// check if member is in database
for (Member existingMember : members) {
if (existingMember.getMemberID() == memberID) {
return true;
}
}
}
}
return false;
}
// make method to check if itemcode is in database
public boolean checkItemCode(int itemCode) {
// check if itemcode is in database
for (Item item : items) {
if (item.getItemCode() == itemCode) {
return true;
}
}
return false;
}
// make method to calculate overdue days
public int calculateOverdueDays(int itemCode) {
// get lending date
LocalDate lendingDate = null;
for (Item item : items) {
if (item.getItemCode() == itemCode) {
lendingDate = item.getLendingDate();
}
}
// calculate overdue days
LocalDate today = LocalDate.now();
return today.getDayOfYear() - lendingDate.getDayOfYear();
}
public void lentItem (int itemCode, int memberID) {
if (checkItemCodeAndMember(itemCode, memberID)) {
for (Item item : items) {
if (item.getItemCode() == itemCode) {
item.setAvailability(false);
item.setLendingDate(LocalDate.now());
return;
}
}
}
}
public boolean receivedItem(int itemCode) {
if (checkItemCode(itemCode)) {
for (Item item : items) {
if (item.getItemCode() == itemCode) {
item.setAvailability(true);
/* item.setLendingDate(null);*/ // dit moet nog worden aangepast, als dat mogelijk is. Null veroorzaakt error.
return true;
}
}
}
return false;
}
//check if item is already lent
public boolean checkIfItemIsAlreadyLent(int itemCode) {
for (Item item : items) {
if (item.getItemCode() == itemCode && !item.getAvailability()) {
return true;
}
}
return false;
}
// check if item is already received
public boolean checkIfItemIsAlreadyReceived(int itemCode) {
for (Item item : items) {
if (item.getItemCode() == itemCode && item.getAvailability()) {
return true;
}
}
return false;
}
// add new item to database
public void addItem(Item item) {
item.setItemCode(this.generateItemCode());
items.add(item);
}
public void addMember(Member member) {
member.setMemberID(this.generateMemberID());
members.add(member);
}
public void editItem(Item item) {
for (Item existingItem : items) {
if (existingItem.getItemCode() == item.getItemCode()) {
existingItem.setTitle(item.getTitle());
existingItem.setAuthor(item.getAuthor());
}
}
}
public void editMember(Member member) {
for (Member existingMember : members) {
if (existingMember.getMemberID() == member.getMemberID()) {
existingMember.setFirstname(member.getFirstname());
existingMember.setLastname(member.getLastname());
existingMember.setDateOfBirth(member.getDateOfBirth());
}
}
}
// delete item from database
public void deleteItem(Item item) {
for (Item existingItem : items) {
if (existingItem.getItemCode() == item.getItemCode()) {
items.remove(existingItem);
return;
}
}
}
public void deleteMember(Member member) {
for (Member existingMember : members) {
if (existingMember.getMemberID() == member.getMemberID()) {
members.remove(existingMember);
return;
}
}
}
// auto generated itemcode
public int generateItemCode() {
int itemCode = 0;
for (Item item : items) {
if (item.getItemCode() > itemCode) {
itemCode = item.getItemCode();
}
}
return itemCode + 1;
//return items.size() + 1;
}
public int generateMemberID() {
int memberID = 0;
for (Member member : members) {
if (member.getMemberID() > memberID) {
memberID = member.getMemberID();
}
}
return memberID + 1;
}
// save data for items
private void saveDataForItems() {
try {
FileOutputStream fileOutputStream = new FileOutputStream("items.dat");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
// write loop for all items
for (Item item : items) {
objectOutputStream.writeObject(item);
}
objectOutputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// save data for members and serialize
private void saveDataForMembers() {
try {
FileOutputStream fileOutputStream = new FileOutputStream("members.dat");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
// write loop for all members
for (Member member : members) {
objectOutputStream.writeObject(member);
}
objectOutputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void saveData() {
saveDataForItems();
saveDataForMembers();
}
// load data for items
public void loadDataForItems() throws IOException{
try {
FileInputStream fileInputStream = new FileInputStream("items.dat");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
// read loop for all items
while (true) {
try {
Item item = (Item) objectInputStream.readObject();
items.add(item);
} catch (EOFException e) {
break;
}
}
objectInputStream.close();
fileInputStream.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
// load data for members
public void loadDataForMembers() throws IOException {
try {
FileInputStream fileInputStream = new FileInputStream("members.dat");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
// read loop for all members
while (true) {
try {
Member member = (Member) objectInputStream.readObject();
members.add(member);
} catch (EOFException e) {
break;
}
}
objectInputStream.close();
fileInputStream.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
| LarsHartendorp/JavaEindopdracht | eindOpdrachtJavaFX/src/main/java/inholland/nl/eindopdrachtjavafx/DAL/Database.java | 2,783 | // dit moet nog worden aangepast, als dat mogelijk is. Null veroorzaakt error. | line_comment | nl | package inholland.nl.eindopdrachtjavafx.DAL;
import inholland.nl.eindopdrachtjavafx.Models.Item;
import inholland.nl.eindopdrachtjavafx.Models.Member;
import java.io.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class Database {
private List<Member> members;
private List<Item> items;
public Database() {
this.members = new ArrayList<>();
this.items = new ArrayList<>();
try {
loadDataForMembers();
loadDataForItems();
} catch (IOException e) {
// add users to collection
this.members.add(new Member(1, "Lars","Lars", "H", "Lars H", LocalDate.of(1990, 1, 1), "1234"));
this.members.add(new Member(2, "Test","Jane", "Doe", "Jane Doe", LocalDate.of(1994, 6, 15), "0000"));
this.members.add(new Member(3, "John","John", "Smith", "John Smith", LocalDate.of(1992, 3, 12), "1234"));
this.members.add(new Member(4, "Jane2","Jane", "Smith", "Jane Smith", LocalDate.of(1995, 8, 23), "5678"));
this.members.add(new Member(5, "John2","John", "Doe", "John Doe", LocalDate.of(1990, 1, 1), "2378"));
// add items to collection
this.items.add(new Item(1, true, "Harry Potter and the Philosopher's Stone", "J.K. Rowling", LocalDate.of(1997, 6, 26)));
this.items.add(new Item(2, true, "Harry Potter and the Chamber of Secrets", "J.K. Rowling", LocalDate.of(1998, 7, 2)));
this.items.add(new Item(3, true, "Harry Potter and the Prisoner of Azkaban", "J.K. Rowling", LocalDate.of(1999, 7, 8)));
this.items.add(new Item(4, true, "Harry Potter and the Goblet of Fire", "J.K. Rowling", LocalDate.of(2000, 7, 8)));
this.items.add(new Item(5, true, "Harry Potter and the Order of the Phoenix", "J.K. Rowling", LocalDate.of(2003, 6, 21)));
this.items.add(new Item(6, true, "Harry Potter and the Half-Blood Prince", "J.K. Rowling", LocalDate.of(2005, 7, 16)));
this.items.add(new Item(7, true, "Harry Potter and the Deathly Hallows", "J.K. Rowling", LocalDate.of(2007, 7, 21)));
}
}
// return collection of users
public List<Member> getMember() {
return members;
}
public List<Item> getAllItems() {
return items;
}
public List<Member> getAllMembers(){
return members;
}
public Item getItem(int itemCode) {
for (Item item : items) {
if (item.getItemCode() == itemCode) {
return item;
}
}
return null;
}
// make method to check if itemcode and member are in database
public boolean checkItemCodeAndMember(int itemCode, int memberID) {
// check if itemcode is in database
for (Item item : items) {
if (item.getItemCode() == itemCode) {
// check if member is in database
for (Member existingMember : members) {
if (existingMember.getMemberID() == memberID) {
return true;
}
}
}
}
return false;
}
// make method to check if itemcode is in database
public boolean checkItemCode(int itemCode) {
// check if itemcode is in database
for (Item item : items) {
if (item.getItemCode() == itemCode) {
return true;
}
}
return false;
}
// make method to calculate overdue days
public int calculateOverdueDays(int itemCode) {
// get lending date
LocalDate lendingDate = null;
for (Item item : items) {
if (item.getItemCode() == itemCode) {
lendingDate = item.getLendingDate();
}
}
// calculate overdue days
LocalDate today = LocalDate.now();
return today.getDayOfYear() - lendingDate.getDayOfYear();
}
public void lentItem (int itemCode, int memberID) {
if (checkItemCodeAndMember(itemCode, memberID)) {
for (Item item : items) {
if (item.getItemCode() == itemCode) {
item.setAvailability(false);
item.setLendingDate(LocalDate.now());
return;
}
}
}
}
public boolean receivedItem(int itemCode) {
if (checkItemCode(itemCode)) {
for (Item item : items) {
if (item.getItemCode() == itemCode) {
item.setAvailability(true);
/* item.setLendingDate(null);*/ // dit moet<SUF>
return true;
}
}
}
return false;
}
//check if item is already lent
public boolean checkIfItemIsAlreadyLent(int itemCode) {
for (Item item : items) {
if (item.getItemCode() == itemCode && !item.getAvailability()) {
return true;
}
}
return false;
}
// check if item is already received
public boolean checkIfItemIsAlreadyReceived(int itemCode) {
for (Item item : items) {
if (item.getItemCode() == itemCode && item.getAvailability()) {
return true;
}
}
return false;
}
// add new item to database
public void addItem(Item item) {
item.setItemCode(this.generateItemCode());
items.add(item);
}
public void addMember(Member member) {
member.setMemberID(this.generateMemberID());
members.add(member);
}
public void editItem(Item item) {
for (Item existingItem : items) {
if (existingItem.getItemCode() == item.getItemCode()) {
existingItem.setTitle(item.getTitle());
existingItem.setAuthor(item.getAuthor());
}
}
}
public void editMember(Member member) {
for (Member existingMember : members) {
if (existingMember.getMemberID() == member.getMemberID()) {
existingMember.setFirstname(member.getFirstname());
existingMember.setLastname(member.getLastname());
existingMember.setDateOfBirth(member.getDateOfBirth());
}
}
}
// delete item from database
public void deleteItem(Item item) {
for (Item existingItem : items) {
if (existingItem.getItemCode() == item.getItemCode()) {
items.remove(existingItem);
return;
}
}
}
public void deleteMember(Member member) {
for (Member existingMember : members) {
if (existingMember.getMemberID() == member.getMemberID()) {
members.remove(existingMember);
return;
}
}
}
// auto generated itemcode
public int generateItemCode() {
int itemCode = 0;
for (Item item : items) {
if (item.getItemCode() > itemCode) {
itemCode = item.getItemCode();
}
}
return itemCode + 1;
//return items.size() + 1;
}
public int generateMemberID() {
int memberID = 0;
for (Member member : members) {
if (member.getMemberID() > memberID) {
memberID = member.getMemberID();
}
}
return memberID + 1;
}
// save data for items
private void saveDataForItems() {
try {
FileOutputStream fileOutputStream = new FileOutputStream("items.dat");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
// write loop for all items
for (Item item : items) {
objectOutputStream.writeObject(item);
}
objectOutputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// save data for members and serialize
private void saveDataForMembers() {
try {
FileOutputStream fileOutputStream = new FileOutputStream("members.dat");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
// write loop for all members
for (Member member : members) {
objectOutputStream.writeObject(member);
}
objectOutputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void saveData() {
saveDataForItems();
saveDataForMembers();
}
// load data for items
public void loadDataForItems() throws IOException{
try {
FileInputStream fileInputStream = new FileInputStream("items.dat");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
// read loop for all items
while (true) {
try {
Item item = (Item) objectInputStream.readObject();
items.add(item);
} catch (EOFException e) {
break;
}
}
objectInputStream.close();
fileInputStream.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
// load data for members
public void loadDataForMembers() throws IOException {
try {
FileInputStream fileInputStream = new FileInputStream("members.dat");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
// read loop for all members
while (true) {
try {
Member member = (Member) objectInputStream.readObject();
members.add(member);
} catch (EOFException e) {
break;
}
}
objectInputStream.close();
fileInputStream.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
| false | 2,188 | 21 | 2,437 | 25 | 2,613 | 19 | 2,437 | 25 | 2,810 | 24 | false | false | false | false | false | true |
2,430 | 13774_0 | package view.serie;
import datalayer.MovieDAO;
import datalayer.SerieDAO;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import models.Episode;
import models.Movie;
import models.Serie;
import java.util.ArrayList;
import java.util.List;
public class SerieControllerTableView implements EventHandler<ActionEvent>{
private TableView tableView;
private TextArea gemiddeldeKijkTijdSerie;
public SerieControllerTableView(TableView tableView, TextArea gemiddeldekijktijdSerie ){
this.tableView = tableView;
this.gemiddeldeKijkTijdSerie = gemiddeldekijktijdSerie; }
/**
* Deze controller pakt alle episodes van een serie geselecteerd in de choicebox.
* @param actionEvent
*/
@Override
public void handle(ActionEvent actionEvent) {
ChoiceBox btn = (ChoiceBox) actionEvent.getTarget();
Serie selectedSerie = (Serie) btn.getSelectionModel().getSelectedItem();
SerieDAO serieDAO = SerieDAO.getInstance();
this.tableView.getItems().clear();
List<Episode> episodes = serieDAO.getAllEpisodesBySerie(selectedSerie);
for(Episode item : episodes){
this.tableView.getItems().add(item);
}
this.tableView.getSelectionModel().selectFirst();
}
}
| coenribbens/Netflix-statistix | src/main/java/view/serie/SerieControllerTableView.java | 428 | /**
* Deze controller pakt alle episodes van een serie geselecteerd in de choicebox.
* @param actionEvent
*/ | block_comment | nl | package view.serie;
import datalayer.MovieDAO;
import datalayer.SerieDAO;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import models.Episode;
import models.Movie;
import models.Serie;
import java.util.ArrayList;
import java.util.List;
public class SerieControllerTableView implements EventHandler<ActionEvent>{
private TableView tableView;
private TextArea gemiddeldeKijkTijdSerie;
public SerieControllerTableView(TableView tableView, TextArea gemiddeldekijktijdSerie ){
this.tableView = tableView;
this.gemiddeldeKijkTijdSerie = gemiddeldekijktijdSerie; }
/**
* Deze controller pakt<SUF>*/
@Override
public void handle(ActionEvent actionEvent) {
ChoiceBox btn = (ChoiceBox) actionEvent.getTarget();
Serie selectedSerie = (Serie) btn.getSelectionModel().getSelectedItem();
SerieDAO serieDAO = SerieDAO.getInstance();
this.tableView.getItems().clear();
List<Episode> episodes = serieDAO.getAllEpisodesBySerie(selectedSerie);
for(Episode item : episodes){
this.tableView.getItems().add(item);
}
this.tableView.getSelectionModel().selectFirst();
}
}
| false | 299 | 30 | 369 | 32 | 350 | 32 | 369 | 32 | 403 | 32 | false | false | false | false | false | true |
2,801 | 10464_19 | package org.tensorflow.demo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.tensorflow.demo.env.ImageUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import cz.msebera.android.httpclient.Header;
/**
* Created by Gil on 26/11/2017.
*/
public class ServerInterface implements UploadInterface{
// json antwoord van server op img http post (bevat gedetecteerde keypoints)
private JSONObject keypointsResponse = null;
// keypoints van eerste persoon
private JSONArray keypoints_person1;
// beslissing van pose matching door server ( na findmatch() )
private String matchOrNot;
private double sp_score;
private double mp_score;
private double us_score;
//private HashMap<String, Bitmap> modelPoses = new HashMap<>();
private ArrayList<String> modelPoses = new ArrayList<>();
private ArrayList<Keypoint> keypointListPerson1 = new ArrayList<>();
// Activity parent; wordt gebruikt om terug te singallen als async http post klaar is
private UploadImageActivity parentCallback;
public ServerInterface(UploadImageActivity parent){
parentCallback = parent;
}
public ServerInterface(){};
// asynch http post call dus met callback werken -> voor wanneer server terug antwoord
public void findMatch(File imgToUpload, int modelId){
String Url = "http://1dr8.be/findmatch";
//If any auth is needed
String username = "username";
String password = "password";
// Bitmap compressedImage = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth(username, password);
client.addHeader("enctype", "multipart/form-data");
RequestParams params = new RequestParams();
try {
//params.put("pic", storeImage(imgToUpload));
params.put("file", imgToUpload);
params.put("id", modelId);
} catch (FileNotFoundException e) {
Log.d("MyApp", "File not found!!!" + imgToUpload.getAbsolutePath());
}
client.post(Url, params, new JsonHttpResponseHandler() {
@Override
public void onProgress(long bytesWritten, long totalSize) {
super.onProgress(bytesWritten, totalSize);
//Log.d(MainActivity.TAG, "PROGRESS: writen: " + bytesWritten + " totalsize: " + totalSize );
final long bytes = bytesWritten;
final long total = totalSize;
parentCallback.runOnUiThread(new Runnable() {
@Override
public void run() {
// werkt niet!!
((TextView) parentCallback.findViewById(R.id.txt_status)).setText("Uploading ... " + bytes/total + "% complete");
//Log.d(MainActivity.TAG, "###In UI Thread!" );
//parentCallback.signalImgUploadProgress(bytesWritten, totalSize);
}
});
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject responseBody) {
//Do what's needed
Log.d("APP ", "Gelukt!!!:");
Log.d("APP", "antwoord: " + responseBody.toString());
keypointsResponse = responseBody;
parseKeypointsJSON();
parseMatchJSON();
//signal parent activity upload is ready
parentCallback.signalImgUploadReady(true, "server");
}
@Override
public void onFailure(int statusCode, Header[] headers, String errorResponse, Throwable error) {
//Print error
Log.d("APP", errorResponse + " " + error.toString());
Log.d("APP", "----ERROORRRRRRRRRR");
}
});
}
public ArrayList<String> getAllModels(MainActivity parent){
String Url = "http://1dr8.be/getAllPoses";
//If any auth is needed
String username = "username";
String password = "password";
// Bitmap compressedImage = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth(username, password);
client.addHeader("enctype", "multipart/form-data");
modelPoses.clear();
client.get(Url, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray responseBody) {
//Do what's needed
Log.d("APP ", "Gelukt!!!:");
Log.d("APP", "antwoord: " + responseBody.toString());
String pic1 = "";
try {
//pic1 = responseBody.getJSONObject(0).getString("foto");
//pic1 = responseBody.getJSONObject(0);
for(int i=0; i<responseBody.length();i++){
pic1 = responseBody.getJSONObject(i).getString("foto");
final byte[] decodedBytes = Base64.decode(pic1.getBytes(), 0);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
modelPoses.add(responseBody.getJSONObject(i).getString("naam"));
String randomFileName = responseBody.getJSONObject(i).getString("naam") + ".jpg"; //+ randomNum;
ImageUtils.saveBitmap(decodedByte, randomFileName);
String path_recorded_img = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "tensorflow/"+ randomFileName;
Log.d("APP", "first pic: " + pic1);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, String errorResponse, Throwable error) {
//Print error
Log.d("APP", errorResponse + " " + error.toString());
Log.d("APP", "----ERROORRRRRRRRRR");
}
});
Log.d("APP", "refresh readyy !!!");
parent.displayFeedback("Models loaded");
return modelPoses;
}
private void parseMatchJSON() {
try {
//String match = keypointsResponse.getJSONObject("match").toString();
matchOrNot = String.valueOf(keypointsResponse.getBoolean("match"));
sp_score = (double) keypointsResponse.getJSONArray("SP").get(0);
mp_score = (double) Math.round(keypointsResponse.getDouble("MP")*100.0)/100.0;
us_score = keypointsResponse.getDouble("US");
Log.d("APP" , "----match result: " + matchOrNot);
} catch (JSONException e) {
e.printStackTrace();
}
}
// oude functie toen findMatch() nog niet bestond en server enkel keypoints terug gaf.
public void uploadNewModel(File imgToUpload, final MainActivity parent) {
String Url = "http://1dr8.be/uploadPose";
//If any auth is needed
String username = "username";
String password = "password";
// Bitmap compressedImage = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth(username, password);
client.addHeader("enctype", "multipart/form-data");
final RequestParams params = new RequestParams();
try {
//params.put("pic", storeImage(imgToUpload));
params.put("file", imgToUpload);
} catch (FileNotFoundException e) {
Log.d("MyApp", "File not found!!!" + imgToUpload.getAbsolutePath());
}
client.post(Url, params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject responseBody) {
//Do what's needed
Log.d("APP ", "Gelukt!!!:");
Log.d("APP", "antwoord: " + responseBody.toString());
try {
parent.displayFeedback("new model added with id " + String.valueOf(responseBody.getInt("id")));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, String errorResponse, Throwable error) {
//Print error
Log.d("APP", errorResponse + " " + error.toString());
Log.d("APP", "----ERROORRRRRRRRRR");
parent.displayFeedback(errorResponse.toString());
}
});
}
//parsen van keypoints
public void parseKeypointsJSON(){
try {
JSONArray ar_people = keypointsResponse.getJSONArray("people");
Log.d("APP", ar_people.toString());
//get body keypoints of first person
JSONArray ar_person1 = ar_people.getJSONObject(0).getJSONArray("pose_keypoints");
keypoints_person1 = ar_person1;
Log.d("APP", ar_person1.toString());
for(int kp = 0; kp<keypoints_person1.length(); kp = kp+3){
try {
double x = Double.parseDouble(keypoints_person1.get(kp).toString());
double y = Double.parseDouble(keypoints_person1.get(kp+1).toString());
keypointListPerson1.add(new Keypoint(x, y));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public JSONObject getKeypointsResponse() {
return keypointsResponse;
}
public void setKeypointsResponse(JSONObject keypointsResponse) {
this.keypointsResponse = keypointsResponse;
}
public JSONArray getKeypoints_person1() {
return keypoints_person1;
}
public void setKeypoints_person1(JSONArray keypoints_person1) {
this.keypoints_person1 = keypoints_person1;
}
public ArrayList<Keypoint> getKeypointListPerson1() {
return keypointListPerson1;
}
public void setKeypointListPerson1(ArrayList<Keypoint> keypointListPerson1) {
this.keypointListPerson1 = keypointListPerson1;
}
public String isMatchOrNot() {
return matchOrNot;
}
public double getSp_score() {
return sp_score;
}
public double getMp_score() {
return mp_score;
}
public double getUs_score() {
return us_score;
}
} | gilbeckers/PoseMatch_v3 | src/org/tensorflow/demo/ServerInterface.java | 3,017 | // oude functie toen findMatch() nog niet bestond en server enkel keypoints terug gaf. | line_comment | nl | package org.tensorflow.demo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.tensorflow.demo.env.ImageUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import cz.msebera.android.httpclient.Header;
/**
* Created by Gil on 26/11/2017.
*/
public class ServerInterface implements UploadInterface{
// json antwoord van server op img http post (bevat gedetecteerde keypoints)
private JSONObject keypointsResponse = null;
// keypoints van eerste persoon
private JSONArray keypoints_person1;
// beslissing van pose matching door server ( na findmatch() )
private String matchOrNot;
private double sp_score;
private double mp_score;
private double us_score;
//private HashMap<String, Bitmap> modelPoses = new HashMap<>();
private ArrayList<String> modelPoses = new ArrayList<>();
private ArrayList<Keypoint> keypointListPerson1 = new ArrayList<>();
// Activity parent; wordt gebruikt om terug te singallen als async http post klaar is
private UploadImageActivity parentCallback;
public ServerInterface(UploadImageActivity parent){
parentCallback = parent;
}
public ServerInterface(){};
// asynch http post call dus met callback werken -> voor wanneer server terug antwoord
public void findMatch(File imgToUpload, int modelId){
String Url = "http://1dr8.be/findmatch";
//If any auth is needed
String username = "username";
String password = "password";
// Bitmap compressedImage = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth(username, password);
client.addHeader("enctype", "multipart/form-data");
RequestParams params = new RequestParams();
try {
//params.put("pic", storeImage(imgToUpload));
params.put("file", imgToUpload);
params.put("id", modelId);
} catch (FileNotFoundException e) {
Log.d("MyApp", "File not found!!!" + imgToUpload.getAbsolutePath());
}
client.post(Url, params, new JsonHttpResponseHandler() {
@Override
public void onProgress(long bytesWritten, long totalSize) {
super.onProgress(bytesWritten, totalSize);
//Log.d(MainActivity.TAG, "PROGRESS: writen: " + bytesWritten + " totalsize: " + totalSize );
final long bytes = bytesWritten;
final long total = totalSize;
parentCallback.runOnUiThread(new Runnable() {
@Override
public void run() {
// werkt niet!!
((TextView) parentCallback.findViewById(R.id.txt_status)).setText("Uploading ... " + bytes/total + "% complete");
//Log.d(MainActivity.TAG, "###In UI Thread!" );
//parentCallback.signalImgUploadProgress(bytesWritten, totalSize);
}
});
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject responseBody) {
//Do what's needed
Log.d("APP ", "Gelukt!!!:");
Log.d("APP", "antwoord: " + responseBody.toString());
keypointsResponse = responseBody;
parseKeypointsJSON();
parseMatchJSON();
//signal parent activity upload is ready
parentCallback.signalImgUploadReady(true, "server");
}
@Override
public void onFailure(int statusCode, Header[] headers, String errorResponse, Throwable error) {
//Print error
Log.d("APP", errorResponse + " " + error.toString());
Log.d("APP", "----ERROORRRRRRRRRR");
}
});
}
public ArrayList<String> getAllModels(MainActivity parent){
String Url = "http://1dr8.be/getAllPoses";
//If any auth is needed
String username = "username";
String password = "password";
// Bitmap compressedImage = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth(username, password);
client.addHeader("enctype", "multipart/form-data");
modelPoses.clear();
client.get(Url, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray responseBody) {
//Do what's needed
Log.d("APP ", "Gelukt!!!:");
Log.d("APP", "antwoord: " + responseBody.toString());
String pic1 = "";
try {
//pic1 = responseBody.getJSONObject(0).getString("foto");
//pic1 = responseBody.getJSONObject(0);
for(int i=0; i<responseBody.length();i++){
pic1 = responseBody.getJSONObject(i).getString("foto");
final byte[] decodedBytes = Base64.decode(pic1.getBytes(), 0);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
modelPoses.add(responseBody.getJSONObject(i).getString("naam"));
String randomFileName = responseBody.getJSONObject(i).getString("naam") + ".jpg"; //+ randomNum;
ImageUtils.saveBitmap(decodedByte, randomFileName);
String path_recorded_img = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "tensorflow/"+ randomFileName;
Log.d("APP", "first pic: " + pic1);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, String errorResponse, Throwable error) {
//Print error
Log.d("APP", errorResponse + " " + error.toString());
Log.d("APP", "----ERROORRRRRRRRRR");
}
});
Log.d("APP", "refresh readyy !!!");
parent.displayFeedback("Models loaded");
return modelPoses;
}
private void parseMatchJSON() {
try {
//String match = keypointsResponse.getJSONObject("match").toString();
matchOrNot = String.valueOf(keypointsResponse.getBoolean("match"));
sp_score = (double) keypointsResponse.getJSONArray("SP").get(0);
mp_score = (double) Math.round(keypointsResponse.getDouble("MP")*100.0)/100.0;
us_score = keypointsResponse.getDouble("US");
Log.d("APP" , "----match result: " + matchOrNot);
} catch (JSONException e) {
e.printStackTrace();
}
}
// oude functie<SUF>
public void uploadNewModel(File imgToUpload, final MainActivity parent) {
String Url = "http://1dr8.be/uploadPose";
//If any auth is needed
String username = "username";
String password = "password";
// Bitmap compressedImage = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth(username, password);
client.addHeader("enctype", "multipart/form-data");
final RequestParams params = new RequestParams();
try {
//params.put("pic", storeImage(imgToUpload));
params.put("file", imgToUpload);
} catch (FileNotFoundException e) {
Log.d("MyApp", "File not found!!!" + imgToUpload.getAbsolutePath());
}
client.post(Url, params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject responseBody) {
//Do what's needed
Log.d("APP ", "Gelukt!!!:");
Log.d("APP", "antwoord: " + responseBody.toString());
try {
parent.displayFeedback("new model added with id " + String.valueOf(responseBody.getInt("id")));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, String errorResponse, Throwable error) {
//Print error
Log.d("APP", errorResponse + " " + error.toString());
Log.d("APP", "----ERROORRRRRRRRRR");
parent.displayFeedback(errorResponse.toString());
}
});
}
//parsen van keypoints
public void parseKeypointsJSON(){
try {
JSONArray ar_people = keypointsResponse.getJSONArray("people");
Log.d("APP", ar_people.toString());
//get body keypoints of first person
JSONArray ar_person1 = ar_people.getJSONObject(0).getJSONArray("pose_keypoints");
keypoints_person1 = ar_person1;
Log.d("APP", ar_person1.toString());
for(int kp = 0; kp<keypoints_person1.length(); kp = kp+3){
try {
double x = Double.parseDouble(keypoints_person1.get(kp).toString());
double y = Double.parseDouble(keypoints_person1.get(kp+1).toString());
keypointListPerson1.add(new Keypoint(x, y));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public JSONObject getKeypointsResponse() {
return keypointsResponse;
}
public void setKeypointsResponse(JSONObject keypointsResponse) {
this.keypointsResponse = keypointsResponse;
}
public JSONArray getKeypoints_person1() {
return keypoints_person1;
}
public void setKeypoints_person1(JSONArray keypoints_person1) {
this.keypoints_person1 = keypoints_person1;
}
public ArrayList<Keypoint> getKeypointListPerson1() {
return keypointListPerson1;
}
public void setKeypointListPerson1(ArrayList<Keypoint> keypointListPerson1) {
this.keypointListPerson1 = keypointListPerson1;
}
public String isMatchOrNot() {
return matchOrNot;
}
public double getSp_score() {
return sp_score;
}
public double getMp_score() {
return mp_score;
}
public double getUs_score() {
return us_score;
}
} | false | 2,219 | 22 | 2,510 | 26 | 2,660 | 19 | 2,510 | 26 | 2,985 | 24 | false | false | false | false | false | true |
3,071 | 31704_3 | import java.util.HashMap;
public class BasicHashMaps
{
/*first things first die maps word hier as static verklaar
*omdat ons die map in 'n static main method gaan gebruik
* so dis nie noodwendig altyd nodig om jou hashmap as
* static te verklaar nie.
*
* okay here we go :D
*/
//net 'n gewone hashMap waar integers (ints) gemap word
//---------------------------------------------------------
static HashMap<String, Integer> basic = new HashMap<String, Integer>();
//static HashMap<String, int> basic = new HashMap<String, int>(); gewone 'int' sou nie werk nie soek 'Integer'
//---------------------------------------------------------
//hashmap waar Human objects gemap word
//---------------------------------------------------------
static HashMap<String, Human> map = new HashMap<String, Human>();
//---------------------------------------------------------
/* Net hoe 'n HashMap werk.
* ------------------------
* Dit het 'n key en 'n value, HashMap<key, Value>
* (1) die value is gemap na die key, dws die key stel die value voor
*
* (2) die verskil tussen HashMap en Hash table ->
* HashMap - unsynchronized (concurrent) en laat 'null' values toe in die map
* Hastable - Synchronized en laat nie 'null' values toe in die table
* hulle werk basically dieselfde
* (ek sal vir jou verduidelik wat dit beteken, maar moet nie te veel daaroor worry nie)
*
* (3) as daar twee key values is wat dieselfde is, word die een override.
* dws net die nuutste een bestaan.
*
* Die maps word soos 'n array amper gebruik, baie dieselfde konsep
*
* */
public static void main(String[] args)
{
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
System.out.println("Using the 'basic' HashMap");
System.out.println("---------------------------");
basic.put("one", 1);
basic.put("two", 2);
basic.put("seven", 7);
System.out.println(basic); //wys vir jou wat als in jou map is. Human Objects display nie mooi nie
System.out.println(basic.keySet());//wys die keys
System.out.println(basic.values());// wys die values
if(basic.containsKey("three"))
{
Human use1 = map.get("three");
System.out.println(use1.getname() + " Exists"); //stuur 1 terug indien die persoon daar is, null andersins
}
else
{
System.out.println("bestaan nie in 'Basic' map");
}
int totV = 0;
for(int v : basic.values())
{
totV = totV+ v;
}
System.out.println("The total value of the basic Map is : "+totV);
System.out.println("\n\n\n\n");
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
System.out.println("Using the 'map' HashMap");
System.out.println("---------------------------");
//maak nuwe humans
Human p1 = new Human("Jan", "de Wet", 3);
Human p2 = new Human("sannie", "Pienaar", 20);
//plaas humans in die map
map.put("Person_1", p1);
map.put("Person_2", p2);
//kyk net hoe werk die funksies.
System.out.println(map); //wys vir jou wat als in jou map is. Human Objects display nie mooi nie
System.out.println(map.keySet());//wys die key
System.out.println(map.values());//wys die values
System.out.println();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//kyk net of die spesifieke human in die hashmap is.
if(map.containsKey("Person_1"))
{
Human use1 = map.get("Person_1"); // die get metode stuur 'n Human object terug
// hier wil ek maar net die Human klas se mothods kan gebruik.
System.out.println(use1.getname() + " Exists");
}
System.out.println();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
String ja = ""; //skep die variable waarin ek 'n string wil bou
for(Human names : map.values()) // omdat die map.values() die Values (wat objects van tiepe Human is) in die map aanstuur,
{ // stoor ek hulle in 'n names variable van tiepe Human.
ja = ja + names.getname()+" ";
//gebruik die Human variable (name) om die Human methods te gebruik, om 'n string te bou, wat al die name bevat
}
System.out.println(ja);// print die String
System.out.println();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Human use2 = map.get("Person_2"); //map.get() stuur die Human Object terug [amper net soos map.Valuas() in 'n for loop]
System.out.println(use2.getname() +" "+ use2.getSname()+" is "+ use2.getAge());
System.out.println(); // een manier hoe om die map values te gebruik
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Hier is net 'n bewys dat wanneer daar 'n key value geadd word, wat alreeds in die HashMap bestaan,
// dat dit heeltemal vervang word met die nuwe value.
// dws die key map(point) nou na 'n nuwe object.
Human p3 = new Human("koos ", "best", 50);
map.put("Person_2", p3);
Human use3 = map.get("Person_2");
System.out.println(use3.getname() +" "+ use3.getSname()+" is "+ use3.getAge());
//nou sien ons dat dit werklik gebeur het en dat die inskrywing (Sannie Pienaar, 20)
//nie meer bestaan in die HashMap nie.
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
}
}
| iggydv/Java-projects | BasicHashMaps.java | 1,805 | //hashmap waar Human objects gemap word | line_comment | nl | import java.util.HashMap;
public class BasicHashMaps
{
/*first things first die maps word hier as static verklaar
*omdat ons die map in 'n static main method gaan gebruik
* so dis nie noodwendig altyd nodig om jou hashmap as
* static te verklaar nie.
*
* okay here we go :D
*/
//net 'n gewone hashMap waar integers (ints) gemap word
//---------------------------------------------------------
static HashMap<String, Integer> basic = new HashMap<String, Integer>();
//static HashMap<String, int> basic = new HashMap<String, int>(); gewone 'int' sou nie werk nie soek 'Integer'
//---------------------------------------------------------
//hashmap waar<SUF>
//---------------------------------------------------------
static HashMap<String, Human> map = new HashMap<String, Human>();
//---------------------------------------------------------
/* Net hoe 'n HashMap werk.
* ------------------------
* Dit het 'n key en 'n value, HashMap<key, Value>
* (1) die value is gemap na die key, dws die key stel die value voor
*
* (2) die verskil tussen HashMap en Hash table ->
* HashMap - unsynchronized (concurrent) en laat 'null' values toe in die map
* Hastable - Synchronized en laat nie 'null' values toe in die table
* hulle werk basically dieselfde
* (ek sal vir jou verduidelik wat dit beteken, maar moet nie te veel daaroor worry nie)
*
* (3) as daar twee key values is wat dieselfde is, word die een override.
* dws net die nuutste een bestaan.
*
* Die maps word soos 'n array amper gebruik, baie dieselfde konsep
*
* */
public static void main(String[] args)
{
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
System.out.println("Using the 'basic' HashMap");
System.out.println("---------------------------");
basic.put("one", 1);
basic.put("two", 2);
basic.put("seven", 7);
System.out.println(basic); //wys vir jou wat als in jou map is. Human Objects display nie mooi nie
System.out.println(basic.keySet());//wys die keys
System.out.println(basic.values());// wys die values
if(basic.containsKey("three"))
{
Human use1 = map.get("three");
System.out.println(use1.getname() + " Exists"); //stuur 1 terug indien die persoon daar is, null andersins
}
else
{
System.out.println("bestaan nie in 'Basic' map");
}
int totV = 0;
for(int v : basic.values())
{
totV = totV+ v;
}
System.out.println("The total value of the basic Map is : "+totV);
System.out.println("\n\n\n\n");
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
System.out.println("Using the 'map' HashMap");
System.out.println("---------------------------");
//maak nuwe humans
Human p1 = new Human("Jan", "de Wet", 3);
Human p2 = new Human("sannie", "Pienaar", 20);
//plaas humans in die map
map.put("Person_1", p1);
map.put("Person_2", p2);
//kyk net hoe werk die funksies.
System.out.println(map); //wys vir jou wat als in jou map is. Human Objects display nie mooi nie
System.out.println(map.keySet());//wys die key
System.out.println(map.values());//wys die values
System.out.println();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//kyk net of die spesifieke human in die hashmap is.
if(map.containsKey("Person_1"))
{
Human use1 = map.get("Person_1"); // die get metode stuur 'n Human object terug
// hier wil ek maar net die Human klas se mothods kan gebruik.
System.out.println(use1.getname() + " Exists");
}
System.out.println();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
String ja = ""; //skep die variable waarin ek 'n string wil bou
for(Human names : map.values()) // omdat die map.values() die Values (wat objects van tiepe Human is) in die map aanstuur,
{ // stoor ek hulle in 'n names variable van tiepe Human.
ja = ja + names.getname()+" ";
//gebruik die Human variable (name) om die Human methods te gebruik, om 'n string te bou, wat al die name bevat
}
System.out.println(ja);// print die String
System.out.println();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Human use2 = map.get("Person_2"); //map.get() stuur die Human Object terug [amper net soos map.Valuas() in 'n for loop]
System.out.println(use2.getname() +" "+ use2.getSname()+" is "+ use2.getAge());
System.out.println(); // een manier hoe om die map values te gebruik
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Hier is net 'n bewys dat wanneer daar 'n key value geadd word, wat alreeds in die HashMap bestaan,
// dat dit heeltemal vervang word met die nuwe value.
// dws die key map(point) nou na 'n nuwe object.
Human p3 = new Human("koos ", "best", 50);
map.put("Person_2", p3);
Human use3 = map.get("Person_2");
System.out.println(use3.getname() +" "+ use3.getSname()+" is "+ use3.getAge());
//nou sien ons dat dit werklik gebeur het en dat die inskrywing (Sannie Pienaar, 20)
//nie meer bestaan in die HashMap nie.
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
}
}
| false | 1,365 | 9 | 1,509 | 9 | 1,633 | 9 | 1,509 | 9 | 1,769 | 9 | false | false | false | false | false | true |
2,204 | 33841_2 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package biometricstationjava;
/**
*
* @author Jelle
*/
public class ArduinoParser {
private static final int ARRAYSIZE = 5;
private int heartbeat = 0;
private double temperature = 0.0;
private double acc_X = 0.0;
private double acc_Y = 0.0;
private double acc_Z = 0.0;
public ArduinoParser() {
}
public SensorData parse(String dataString) {
String[] data = dataString.split(";");
if (!isValidStringArray(data)) {
System.out.println("check data, something wrong has happened!");
return null;
}
temperature = Double.parseDouble(data[0]);
heartbeat = Integer.parseInt(data[1]);
acc_X = Double.parseDouble(data[2]);
acc_Y = Double.parseDouble(data[3]);
acc_Z = Double.parseDouble(data[4]);
return new SensorData(temperature, heartbeat, acc_X, acc_Y, acc_Z);
}
public boolean isValidStringArray(String[] data) {
boolean valid = true;
for (int i = 0; i < data.length && valid == true; i++) {
if (data[i].isEmpty()) {
valid = false;
}
}
return valid && data.length == ARRAYSIZE; //Krijgt niet altijd de juiste data door.
}
}
| bbt-oop2-2018/biometric-station-java-service-jelledebuyzere_elisedesmet | BiometricStationJava/src/biometricstationjava/ArduinoParser.java | 416 | //Krijgt niet altijd de juiste data door. | line_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package biometricstationjava;
/**
*
* @author Jelle
*/
public class ArduinoParser {
private static final int ARRAYSIZE = 5;
private int heartbeat = 0;
private double temperature = 0.0;
private double acc_X = 0.0;
private double acc_Y = 0.0;
private double acc_Z = 0.0;
public ArduinoParser() {
}
public SensorData parse(String dataString) {
String[] data = dataString.split(";");
if (!isValidStringArray(data)) {
System.out.println("check data, something wrong has happened!");
return null;
}
temperature = Double.parseDouble(data[0]);
heartbeat = Integer.parseInt(data[1]);
acc_X = Double.parseDouble(data[2]);
acc_Y = Double.parseDouble(data[3]);
acc_Z = Double.parseDouble(data[4]);
return new SensorData(temperature, heartbeat, acc_X, acc_Y, acc_Z);
}
public boolean isValidStringArray(String[] data) {
boolean valid = true;
for (int i = 0; i < data.length && valid == true; i++) {
if (data[i].isEmpty()) {
valid = false;
}
}
return valid && data.length == ARRAYSIZE; //Krijgt niet<SUF>
}
}
| false | 325 | 12 | 366 | 14 | 391 | 11 | 366 | 14 | 423 | 13 | false | false | false | false | false | true |
126 | 76888_1 | import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Created by 11302014 on 4/05/2015.
*/
public class FServer implements Runnable {
private Key myPrivateKey = null;
private Key myPublicKey = null;
FDecryptor fDecryptor = null;
public FServer(Key myPrivateKey, Key myPublicKey) throws NoSuchAlgorithmException, NoSuchPaddingException {
this.myPrivateKey = myPrivateKey;
this.myPublicKey = myPublicKey;
this.fDecryptor = new FDecryptor();
}
public void start() {
Thread buf = new Thread(this);
buf.start();
}
@Override
public void run() {
try {
ServerSocket bigSocket = new ServerSocket(FClient.port);
while (true) {
Socket smallSocket = bigSocket.accept();
OutputStream output = smallSocket.getOutputStream();
InputStream input = smallSocket.getInputStream();
Key otherPublicKey = null;
byte[] buffer = new byte[1024*1024];
int bytesReceived = 0;
//versturen van public key
System.out.println("Server: start versturen publickey..." + myPublicKey.getEncoded().length);
output.write(myPublicKey.getEncoded());
output.flush();
//ontvangen van public key
System.out.println("Server: start ontvangen publickey...");
while((bytesReceived = input.read(buffer))>0) {
KeyFactory kf = KeyFactory.getInstance("RSA");
otherPublicKey = kf.generatePublic(new X509EncodedKeySpec(buffer));
System.out.println(bytesReceived);
break;
}
FileOutputStream out = new FileOutputStream("buf.enc");
//ontvangen van file
System.out.println("Server: start ontvangen file...");
while((bytesReceived = input.read(buffer))>0) {
out.write(buffer,0,bytesReceived);
System.out.println(bytesReceived);
break;
}
out.flush();
out.close();
input.close();
smallSocket.close();
//buf file lezen
System.out.println("Server: file lezen...");
FTotalPacket received = FTotalPacket.readEncBuf();
//file decrypteren
System.out.println("Server: file decrypteren...");
byte[] unencryptedFile = fDecryptor.decrypt(received, myPrivateKey, otherPublicKey);
//file weg schrijven
System.out.println("Server: gedecrypte file wegschrijven");
/// save file dialog waar de nieuwe file moet komen
FTotalPacket.writeFile(unencryptedFile, received.getName());
//als.zip decrypten
System.out.println("Server: Zipfile uitpakken...");
unzip(received.getName());
System.out.println("Server: Done!");
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
}
private void unzip (String zipFile) {
byte[] buffer = new byte[1024];
File folder = new File ("");
if (!folder.exists()) {
folder.mkdir();
}
try {
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry ze = zis.getNextEntry();
while (ze!=null) {
String fileName = ze.getName();
System.out.println(ze.getName());
File newFile = new File(fileName);
new File (newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile.getName());
int len;
while ((len = zis.read(buffer))>0) {
fos.write(buffer,0,len);
}
fos.close();
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| AppDev10/BasicSecurityAppDev10 | src/main/java/FServer.java | 1,388 | //versturen van public key | line_comment | nl | import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Created by 11302014 on 4/05/2015.
*/
public class FServer implements Runnable {
private Key myPrivateKey = null;
private Key myPublicKey = null;
FDecryptor fDecryptor = null;
public FServer(Key myPrivateKey, Key myPublicKey) throws NoSuchAlgorithmException, NoSuchPaddingException {
this.myPrivateKey = myPrivateKey;
this.myPublicKey = myPublicKey;
this.fDecryptor = new FDecryptor();
}
public void start() {
Thread buf = new Thread(this);
buf.start();
}
@Override
public void run() {
try {
ServerSocket bigSocket = new ServerSocket(FClient.port);
while (true) {
Socket smallSocket = bigSocket.accept();
OutputStream output = smallSocket.getOutputStream();
InputStream input = smallSocket.getInputStream();
Key otherPublicKey = null;
byte[] buffer = new byte[1024*1024];
int bytesReceived = 0;
//versturen van<SUF>
System.out.println("Server: start versturen publickey..." + myPublicKey.getEncoded().length);
output.write(myPublicKey.getEncoded());
output.flush();
//ontvangen van public key
System.out.println("Server: start ontvangen publickey...");
while((bytesReceived = input.read(buffer))>0) {
KeyFactory kf = KeyFactory.getInstance("RSA");
otherPublicKey = kf.generatePublic(new X509EncodedKeySpec(buffer));
System.out.println(bytesReceived);
break;
}
FileOutputStream out = new FileOutputStream("buf.enc");
//ontvangen van file
System.out.println("Server: start ontvangen file...");
while((bytesReceived = input.read(buffer))>0) {
out.write(buffer,0,bytesReceived);
System.out.println(bytesReceived);
break;
}
out.flush();
out.close();
input.close();
smallSocket.close();
//buf file lezen
System.out.println("Server: file lezen...");
FTotalPacket received = FTotalPacket.readEncBuf();
//file decrypteren
System.out.println("Server: file decrypteren...");
byte[] unencryptedFile = fDecryptor.decrypt(received, myPrivateKey, otherPublicKey);
//file weg schrijven
System.out.println("Server: gedecrypte file wegschrijven");
/// save file dialog waar de nieuwe file moet komen
FTotalPacket.writeFile(unencryptedFile, received.getName());
//als.zip decrypten
System.out.println("Server: Zipfile uitpakken...");
unzip(received.getName());
System.out.println("Server: Done!");
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
}
private void unzip (String zipFile) {
byte[] buffer = new byte[1024];
File folder = new File ("");
if (!folder.exists()) {
folder.mkdir();
}
try {
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry ze = zis.getNextEntry();
while (ze!=null) {
String fileName = ze.getName();
System.out.println(ze.getName());
File newFile = new File(fileName);
new File (newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile.getName());
int len;
while ((len = zis.read(buffer))>0) {
fos.write(buffer,0,len);
}
fos.close();
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| false | 970 | 7 | 1,121 | 7 | 1,196 | 7 | 1,121 | 7 | 1,366 | 7 | false | false | false | false | false | true |
1,971 | 84245_5 | import java.util.Map;
import java.util.HashMap;
import java.util.Scanner;
/**
* Practicum 3: BSA calculator
* Dit programma vertelt een gebruiker hun BSA aan de hand van ingevoerde cijfers.
*
* @author Aetheryx
*/
public class Main {
// Declareer alle vakken met het bijbehorend aantal studiepunten
private static final Map<String, Integer> /* <Vak, Studiepunten> */ VAKKEN = Map.of(
"Fasten Your Seatbelts", 12,
"Programming", 3,
"Databases", 3,
"Object Oriented Programming 1", 3,
"User Interaction", 3,
"Personal Skills", 2,
"Project Skills", 2
);
// Het maximaal aantal haalbare studiepunten (met opzet dynamisch berekend)
private static final int MAX_AANTAL_STUDIEPUNTEN = VAKKEN
.values()
.stream()
.mapToInt(Integer::intValue)
.sum();
// De barriere voor een positief BSA
private static final double BARRIERE_POSITIEF_BSA = (double) 5 / 6;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
HashMap<String, Double> behaaldeCijfers = new HashMap<String, Double>();
int totaalBehaaldeStudiepunten = 0;
System.out.println("Voer behaalde cijfers in:");
// Itereer over de vakken, vraag en sla het cijfer op
for (String vakNaam : VAKKEN.keySet()) {
System.out.print(vakNaam + ": ");
double behaaldCijfer = scanner.nextDouble();
behaaldeCijfers.put(vakNaam, behaaldCijfer);
}
// lege regel
System.out.println();
// Bereken voor elk vak het aantal studiepunten, tel het op bij het totaal, print de informatie uit
for (String vakNaam : VAKKEN.keySet()) {
double behaaldCijfer = behaaldeCijfers.get(vakNaam);
double behaaldeStudiepunten = behaaldCijfer >= 5.5
? VAKKEN.get(vakNaam)
: 0;
totaalBehaaldeStudiepunten += behaaldeStudiepunten;
System.out.printf(
"Vak/project: %-30s Cijfer: %-6.1f Behaalde punten: %.0f\n",
vakNaam,
behaaldCijfer,
behaaldeStudiepunten
);
}
System.out.printf("\nTotaal behaalde studiepunten: %d/%d\n", totaalBehaaldeStudiepunten, MAX_AANTAL_STUDIEPUNTEN);
// Het ratio van aantal behaalde studiepunten : maximaal haalbare studiepunten
double studiePuntenRatio = (double) totaalBehaaldeStudiepunten / MAX_AANTAL_STUDIEPUNTEN;
System.out.println(
studiePuntenRatio >= BARRIERE_POSITIEF_BSA
? "Je loopt op schema voor een positief BSA."
: "PAS OP: je ligt op schema voor een negatief BSA!"
);
}
}
| aetheryx/edu | software-engineering/programming/practicum/3: BSA Monitor/Main.java | 942 | // Bereken voor elk vak het aantal studiepunten, tel het op bij het totaal, print de informatie uit | line_comment | nl | import java.util.Map;
import java.util.HashMap;
import java.util.Scanner;
/**
* Practicum 3: BSA calculator
* Dit programma vertelt een gebruiker hun BSA aan de hand van ingevoerde cijfers.
*
* @author Aetheryx
*/
public class Main {
// Declareer alle vakken met het bijbehorend aantal studiepunten
private static final Map<String, Integer> /* <Vak, Studiepunten> */ VAKKEN = Map.of(
"Fasten Your Seatbelts", 12,
"Programming", 3,
"Databases", 3,
"Object Oriented Programming 1", 3,
"User Interaction", 3,
"Personal Skills", 2,
"Project Skills", 2
);
// Het maximaal aantal haalbare studiepunten (met opzet dynamisch berekend)
private static final int MAX_AANTAL_STUDIEPUNTEN = VAKKEN
.values()
.stream()
.mapToInt(Integer::intValue)
.sum();
// De barriere voor een positief BSA
private static final double BARRIERE_POSITIEF_BSA = (double) 5 / 6;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
HashMap<String, Double> behaaldeCijfers = new HashMap<String, Double>();
int totaalBehaaldeStudiepunten = 0;
System.out.println("Voer behaalde cijfers in:");
// Itereer over de vakken, vraag en sla het cijfer op
for (String vakNaam : VAKKEN.keySet()) {
System.out.print(vakNaam + ": ");
double behaaldCijfer = scanner.nextDouble();
behaaldeCijfers.put(vakNaam, behaaldCijfer);
}
// lege regel
System.out.println();
// Bereken voor<SUF>
for (String vakNaam : VAKKEN.keySet()) {
double behaaldCijfer = behaaldeCijfers.get(vakNaam);
double behaaldeStudiepunten = behaaldCijfer >= 5.5
? VAKKEN.get(vakNaam)
: 0;
totaalBehaaldeStudiepunten += behaaldeStudiepunten;
System.out.printf(
"Vak/project: %-30s Cijfer: %-6.1f Behaalde punten: %.0f\n",
vakNaam,
behaaldCijfer,
behaaldeStudiepunten
);
}
System.out.printf("\nTotaal behaalde studiepunten: %d/%d\n", totaalBehaaldeStudiepunten, MAX_AANTAL_STUDIEPUNTEN);
// Het ratio van aantal behaalde studiepunten : maximaal haalbare studiepunten
double studiePuntenRatio = (double) totaalBehaaldeStudiepunten / MAX_AANTAL_STUDIEPUNTEN;
System.out.println(
studiePuntenRatio >= BARRIERE_POSITIEF_BSA
? "Je loopt op schema voor een positief BSA."
: "PAS OP: je ligt op schema voor een negatief BSA!"
);
}
}
| false | 805 | 25 | 935 | 30 | 796 | 23 | 935 | 30 | 1,056 | 30 | false | false | false | false | false | true |
1,080 | 150386_2 | package be.kuleuven.candycrush;
import javafx.util.Pair;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CandycrushModel {
private String speler;
private Board<Candy> candyBoard;
private int score;
private boolean gestart;
private BoardSize boardSize;
public CandycrushModel(String speler, int width, int height){
this.speler = speler;
boardSize = new BoardSize(height, width);
candyBoard = new Board<>(boardSize);
score = 0;
gestart = false;
Function<Position, Candy> candyCreator = position -> randomCandy();
candyBoard.fill(candyCreator);
}
public CandycrushModel(String speler) {
this(speler, 10, 10);
}
public String getSpeler() {
return speler;
}
public BoardSize getBoardSize(){
return boardSize;
}
public Board<Candy> getSpeelbord() {
return candyBoard;
}
public void setCandyBoard(Board<Candy> board){
candyBoard = board;
}
public int getWidth() {
return boardSize.kolommen();
}
public int getHeight() {
return boardSize.rijen();
}
public int getScore(){
return this.score;
}
public boolean isGestart(){
return this.gestart;
}
public void start(){
this.gestart = true;
}
public void reset(){
this.score =0;
this.gestart = false;
Function<Position, Candy> candyCreator = position -> randomCandy();
candyBoard.fill(candyCreator);
}
public Candy randomCandy(){
Random random = new Random();
int randomGetal = random.nextInt(8);
return switch (randomGetal) {
case 4 -> new Erwt();
case 5 -> new Kropsla();
case 6 -> new Lente_ui();
case 7 -> new Tomaat();
default -> new NormalCandy(randomGetal);
};
}
public void candyWithIndexSelected(Position position){
Iterable<Position> Neighbours = getSameNeighbourPositions(position);
/*for(Position Neighbour : Neighbours){
candyBoard.replaceCellAt(Neighbour, randomCandy());
score = score + 2;
}
candyBoard.replaceCellAt(position, randomCandy());
score++;*/
candyBoard.replaceCellAt(position, new noCandy());
score++;
fallDownTo(position, candyBoard);
updateBoard(candyBoard);
System.out.println(getAllSwaps(candyBoard));
}
Iterable<Position> getSameNeighbourPositions(Position position){
Iterable<Position> neighbors = position.neighborPositions();
ArrayList<Position> result = new ArrayList<>();
for(Position neighbor : neighbors){
Candy candy = candyBoard.getCellAt(position);
Candy neighborCandy = candyBoard.getCellAt(neighbor);
if(candy.equals(neighborCandy)){
result.add(neighbor);
}
}
return result;
}
public boolean firstTwoHaveCandy(Candy candy, Stream<Position> positions, Board<Candy> board){
return positions
.limit(2)
.allMatch(p -> board.getCellAt(p).equals(candy));
}
public Stream<Position> horizontalStartingPositions(Board<Candy> board){
return boardSize.positions().stream()
.filter(p -> {
Stream<Position> buren = p.walkLeft();
return !firstTwoHaveCandy(board.getCellAt(p), buren, board);
});
}
public Stream<Position> verticalStartingPositions(Board<Candy> board){
return boardSize.positions().stream()
.filter(p -> {
Stream<Position> buren = p.walkUp();
return !firstTwoHaveCandy(board.getCellAt(p), buren, board);
});
}
public List<Position> longestMatchToRight(Position pos, Board<Candy> board){
Stream<Position> walked = pos.walkRight();
return walked
.takeWhile(p -> board.getCellAt(p).equals(board.getCellAt(pos))
&& !(board.getCellAt(p) instanceof noCandy) && !(board.getCellAt(pos) instanceof noCandy))
.toList();
}
public List<Position> longestMatchDown(Position pos, Board<Candy> board){
Stream<Position> walked = pos.walkDown();
return walked
.takeWhile(p -> board.getCellAt(p).equals(board.getCellAt(pos))
&& !(board.getCellAt(p) instanceof noCandy) && !(board.getCellAt(pos) instanceof noCandy))
.toList();
}
public Set<List<Position>> findAllMatches(Board<Candy> board){
List<List<Position>> allMatches = Stream.concat(horizontalStartingPositions(board), verticalStartingPositions(board))
.flatMap(p -> {
List<Position> horizontalMatch = longestMatchToRight(p, board);
List<Position> verticalMatch = longestMatchDown(p, board);
return Stream.of(horizontalMatch, verticalMatch);
})
.filter(m -> m.size() > 2)
.sorted((match1, match2) -> match2.size() - match1.size())
.toList();
return allMatches.stream()
.filter(match -> allMatches.stream()
.noneMatch(longerMatch -> longerMatch.size() > match.size() && new HashSet<>(longerMatch).containsAll(match)))
.collect(Collectors.toSet());
}
public void clearMatch(List<Position> match, Board<Candy> board){
List<Position> copy = new ArrayList<>(match); // Match is immutable dus maak een copy
if(copy.isEmpty()) return;
Position first = copy.getFirst();
board.replaceCellAt(first, new noCandy());
copy.removeFirst();
score++;
clearMatch(copy, board);
}
public void fallDownTo(List<Position> match, Board<Candy> board){
if(horizontalMatch(match)){
match.forEach(position -> fallDownTo(position, board));
} else {
match.stream()
.max(Comparator.comparingInt(Position::rij)).ifPresent(position -> fallDownTo(position, board));
}
}
public void fallDownTo(Position pos, Board<Candy> board){
try{
Position boven = new Position(pos.rij() - 1, pos.kolom(), boardSize);
if(board.getCellAt(pos) instanceof noCandy){
while (board.getCellAt(boven) instanceof noCandy){
boven = new Position(boven.rij() - 1, boven.kolom(), boardSize);
}
board.replaceCellAt(pos, board.getCellAt(boven));
board.replaceCellAt(boven, new noCandy());
fallDownTo(pos, board);
} else{
fallDownTo(boven, board);
}
} catch (IllegalArgumentException ignored){return;}
}
public boolean horizontalMatch(List<Position> match){
return match.getFirst().rij() == match.getLast().rij();
}
public boolean updateBoard(Board<Candy> board){
Set<List<Position>> matches = findAllMatches(board);
if (matches.isEmpty()) return false;
for(List<Position> match : matches){
clearMatch(match, board);
fallDownTo(match, board);
}
updateBoard(board);
return true;
}
public void swapCandies(Position pos1, Position pos2, Board<Candy> board){
if(!pos1.isNeighbor(pos2) || !matchAfterSwitch(pos1, pos2, board)){
return;
}
if(board.getCellAt(pos1) instanceof noCandy || board.getCellAt(pos2) instanceof noCandy){
return;
}
unsafeSwap(pos1, pos2, board);
updateBoard(board);
}
private void unsafeSwap(Position pos1, Position pos2, Board<Candy> board){
Candy candy1 = board.getCellAt(pos1);
Candy candy2 = board.getCellAt(pos2);
board.replaceCellAt(pos1, candy2);
board.replaceCellAt(pos2, candy1);
}
public boolean matchAfterSwitch(Position pos1, Position pos2, Board<Candy> board){
unsafeSwap(pos1, pos2, board);
Set<List<Position>> matches = findAllMatches(board);
unsafeSwap(pos1, pos2, board);
return !matches.isEmpty();
}
private Set<List<Position>> getAllSwaps(Board<Candy> board){
Set<List<Position>> swaps = new HashSet<>();
for (Position position : board.getBoardSize().positions()){
Iterable<Position> neighbours = position.neighborPositions();
for(Position neighbour : neighbours){
if(!matchAfterSwitch(neighbour, position, board)){
continue;
}
if(board.getCellAt(position) instanceof noCandy || board.getCellAt(neighbour) instanceof noCandy){
continue;
}
List<Position> swap = Arrays.asList(position, neighbour);
// Verwijderd duplicaten in de lijst, want
// r1c2-r1c3 == r1c3-r1c2
List<Position> reverseSwap = Arrays.asList(neighbour, position);
if(swaps.contains(swap) || swaps.contains(reverseSwap)){
continue;
}
swaps.add(swap);
}
}
return swaps;
}
public Solution maximizeScore(){
List<List<Position>> moves = new ArrayList<>();
Solution intialSolution = new Solution(0,candyBoard, moves);
return findOptimalSolution(intialSolution, null);
}
private Solution findOptimalSolution(Solution partialSolution, Solution bestSoFar){
Set<List<Position>> swaps = getAllSwaps(partialSolution.board());
if(swaps.isEmpty()){
System.out.println(partialSolution.score());
System.out.println(partialSolution.calculateScore());
System.out.println("*-*");
if (bestSoFar == null || partialSolution.isBetterThan(bestSoFar)) {
return partialSolution;
} else {
return bestSoFar;
}
}
if(bestSoFar != null && partialSolution.canImproveUpon(bestSoFar)){
return bestSoFar;
}
for(List<Position> swap : swaps){
Board<Candy> mutableBoard = new Board<>(partialSolution.board().getBoardSize());
partialSolution.board().copyTo(mutableBoard);
swapCandies(swap.getFirst(), swap.getLast(), mutableBoard);
List<List<Position>> newMoves = new ArrayList<>(partialSolution.moves());
newMoves.add(swap);
Solution solution = new Solution(0, mutableBoard, newMoves);
int score = solution.calculateScore();
bestSoFar = findOptimalSolution(new Solution(score, mutableBoard, newMoves), bestSoFar);
}
return bestSoFar;
}
public Collection<Solution> solveAll(){
List<List<Position>> moves = new ArrayList<>();
Solution intialSolution = new Solution(0,candyBoard, moves);
ArrayList<Solution> collection = new ArrayList<>();
return findAllSolutions(intialSolution, collection);
}
private Collection<Solution> findAllSolutions(Solution partialSolution, Collection<Solution> solutionsSoFar){
Set<List<Position>> swaps = getAllSwaps(partialSolution.board());
if(swaps.isEmpty()){
System.out.println("Oplossing gevonden B)");
int score = partialSolution.calculateScore();
Solution solution = new Solution(score, partialSolution.board(), partialSolution.moves());
solution.printSolution();
solutionsSoFar.add(solution);
return solutionsSoFar;
}
for(List<Position> swap : swaps){
Board<Candy> mutableBoard = new Board<>(partialSolution.board().getBoardSize());
partialSolution.board().copyTo(mutableBoard);
swapCandies(swap.getFirst(), swap.getLast(), mutableBoard);
List<List<Position>> newMoves = new ArrayList<>(partialSolution.moves());
newMoves.add(swap);
findAllSolutions(new Solution(0, mutableBoard, newMoves), solutionsSoFar);
}
return solutionsSoFar;
}
public Solution solveAny(){
Solution intialSolution = new Solution(0,candyBoard, null);
return findAnySolution(intialSolution);
}
private Solution findAnySolution(Solution partialSolution){
Set<List<Position>> swaps = getAllSwaps(partialSolution.board());
if(swaps.isEmpty()) return partialSolution; // Current.isComplete()
for (List<Position> swap : swaps){
// SWAP
// 1. copy board vanuit record
// 2. swapcandies en update
// 3. maak partialSolution
// 4. recursie
Board<Candy> mutableBoard = new Board<>(partialSolution.board().getBoardSize());
partialSolution.board().copyTo(mutableBoard);
swapCandies(swap.getFirst(), swap.getLast(), mutableBoard);
int score = this.getScore();
return findAnySolution(new Solution(score, mutableBoard, null));
}
return null;
}
} | MathiasHouwen/SES_CandyCrush | candycrush/src/main/java/be/kuleuven/candycrush/CandycrushModel.java | 3,789 | // Verwijderd duplicaten in de lijst, want | line_comment | nl | package be.kuleuven.candycrush;
import javafx.util.Pair;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CandycrushModel {
private String speler;
private Board<Candy> candyBoard;
private int score;
private boolean gestart;
private BoardSize boardSize;
public CandycrushModel(String speler, int width, int height){
this.speler = speler;
boardSize = new BoardSize(height, width);
candyBoard = new Board<>(boardSize);
score = 0;
gestart = false;
Function<Position, Candy> candyCreator = position -> randomCandy();
candyBoard.fill(candyCreator);
}
public CandycrushModel(String speler) {
this(speler, 10, 10);
}
public String getSpeler() {
return speler;
}
public BoardSize getBoardSize(){
return boardSize;
}
public Board<Candy> getSpeelbord() {
return candyBoard;
}
public void setCandyBoard(Board<Candy> board){
candyBoard = board;
}
public int getWidth() {
return boardSize.kolommen();
}
public int getHeight() {
return boardSize.rijen();
}
public int getScore(){
return this.score;
}
public boolean isGestart(){
return this.gestart;
}
public void start(){
this.gestart = true;
}
public void reset(){
this.score =0;
this.gestart = false;
Function<Position, Candy> candyCreator = position -> randomCandy();
candyBoard.fill(candyCreator);
}
public Candy randomCandy(){
Random random = new Random();
int randomGetal = random.nextInt(8);
return switch (randomGetal) {
case 4 -> new Erwt();
case 5 -> new Kropsla();
case 6 -> new Lente_ui();
case 7 -> new Tomaat();
default -> new NormalCandy(randomGetal);
};
}
public void candyWithIndexSelected(Position position){
Iterable<Position> Neighbours = getSameNeighbourPositions(position);
/*for(Position Neighbour : Neighbours){
candyBoard.replaceCellAt(Neighbour, randomCandy());
score = score + 2;
}
candyBoard.replaceCellAt(position, randomCandy());
score++;*/
candyBoard.replaceCellAt(position, new noCandy());
score++;
fallDownTo(position, candyBoard);
updateBoard(candyBoard);
System.out.println(getAllSwaps(candyBoard));
}
Iterable<Position> getSameNeighbourPositions(Position position){
Iterable<Position> neighbors = position.neighborPositions();
ArrayList<Position> result = new ArrayList<>();
for(Position neighbor : neighbors){
Candy candy = candyBoard.getCellAt(position);
Candy neighborCandy = candyBoard.getCellAt(neighbor);
if(candy.equals(neighborCandy)){
result.add(neighbor);
}
}
return result;
}
public boolean firstTwoHaveCandy(Candy candy, Stream<Position> positions, Board<Candy> board){
return positions
.limit(2)
.allMatch(p -> board.getCellAt(p).equals(candy));
}
public Stream<Position> horizontalStartingPositions(Board<Candy> board){
return boardSize.positions().stream()
.filter(p -> {
Stream<Position> buren = p.walkLeft();
return !firstTwoHaveCandy(board.getCellAt(p), buren, board);
});
}
public Stream<Position> verticalStartingPositions(Board<Candy> board){
return boardSize.positions().stream()
.filter(p -> {
Stream<Position> buren = p.walkUp();
return !firstTwoHaveCandy(board.getCellAt(p), buren, board);
});
}
public List<Position> longestMatchToRight(Position pos, Board<Candy> board){
Stream<Position> walked = pos.walkRight();
return walked
.takeWhile(p -> board.getCellAt(p).equals(board.getCellAt(pos))
&& !(board.getCellAt(p) instanceof noCandy) && !(board.getCellAt(pos) instanceof noCandy))
.toList();
}
public List<Position> longestMatchDown(Position pos, Board<Candy> board){
Stream<Position> walked = pos.walkDown();
return walked
.takeWhile(p -> board.getCellAt(p).equals(board.getCellAt(pos))
&& !(board.getCellAt(p) instanceof noCandy) && !(board.getCellAt(pos) instanceof noCandy))
.toList();
}
public Set<List<Position>> findAllMatches(Board<Candy> board){
List<List<Position>> allMatches = Stream.concat(horizontalStartingPositions(board), verticalStartingPositions(board))
.flatMap(p -> {
List<Position> horizontalMatch = longestMatchToRight(p, board);
List<Position> verticalMatch = longestMatchDown(p, board);
return Stream.of(horizontalMatch, verticalMatch);
})
.filter(m -> m.size() > 2)
.sorted((match1, match2) -> match2.size() - match1.size())
.toList();
return allMatches.stream()
.filter(match -> allMatches.stream()
.noneMatch(longerMatch -> longerMatch.size() > match.size() && new HashSet<>(longerMatch).containsAll(match)))
.collect(Collectors.toSet());
}
public void clearMatch(List<Position> match, Board<Candy> board){
List<Position> copy = new ArrayList<>(match); // Match is immutable dus maak een copy
if(copy.isEmpty()) return;
Position first = copy.getFirst();
board.replaceCellAt(first, new noCandy());
copy.removeFirst();
score++;
clearMatch(copy, board);
}
public void fallDownTo(List<Position> match, Board<Candy> board){
if(horizontalMatch(match)){
match.forEach(position -> fallDownTo(position, board));
} else {
match.stream()
.max(Comparator.comparingInt(Position::rij)).ifPresent(position -> fallDownTo(position, board));
}
}
public void fallDownTo(Position pos, Board<Candy> board){
try{
Position boven = new Position(pos.rij() - 1, pos.kolom(), boardSize);
if(board.getCellAt(pos) instanceof noCandy){
while (board.getCellAt(boven) instanceof noCandy){
boven = new Position(boven.rij() - 1, boven.kolom(), boardSize);
}
board.replaceCellAt(pos, board.getCellAt(boven));
board.replaceCellAt(boven, new noCandy());
fallDownTo(pos, board);
} else{
fallDownTo(boven, board);
}
} catch (IllegalArgumentException ignored){return;}
}
public boolean horizontalMatch(List<Position> match){
return match.getFirst().rij() == match.getLast().rij();
}
public boolean updateBoard(Board<Candy> board){
Set<List<Position>> matches = findAllMatches(board);
if (matches.isEmpty()) return false;
for(List<Position> match : matches){
clearMatch(match, board);
fallDownTo(match, board);
}
updateBoard(board);
return true;
}
public void swapCandies(Position pos1, Position pos2, Board<Candy> board){
if(!pos1.isNeighbor(pos2) || !matchAfterSwitch(pos1, pos2, board)){
return;
}
if(board.getCellAt(pos1) instanceof noCandy || board.getCellAt(pos2) instanceof noCandy){
return;
}
unsafeSwap(pos1, pos2, board);
updateBoard(board);
}
private void unsafeSwap(Position pos1, Position pos2, Board<Candy> board){
Candy candy1 = board.getCellAt(pos1);
Candy candy2 = board.getCellAt(pos2);
board.replaceCellAt(pos1, candy2);
board.replaceCellAt(pos2, candy1);
}
public boolean matchAfterSwitch(Position pos1, Position pos2, Board<Candy> board){
unsafeSwap(pos1, pos2, board);
Set<List<Position>> matches = findAllMatches(board);
unsafeSwap(pos1, pos2, board);
return !matches.isEmpty();
}
private Set<List<Position>> getAllSwaps(Board<Candy> board){
Set<List<Position>> swaps = new HashSet<>();
for (Position position : board.getBoardSize().positions()){
Iterable<Position> neighbours = position.neighborPositions();
for(Position neighbour : neighbours){
if(!matchAfterSwitch(neighbour, position, board)){
continue;
}
if(board.getCellAt(position) instanceof noCandy || board.getCellAt(neighbour) instanceof noCandy){
continue;
}
List<Position> swap = Arrays.asList(position, neighbour);
// Verwijderd duplicaten<SUF>
// r1c2-r1c3 == r1c3-r1c2
List<Position> reverseSwap = Arrays.asList(neighbour, position);
if(swaps.contains(swap) || swaps.contains(reverseSwap)){
continue;
}
swaps.add(swap);
}
}
return swaps;
}
public Solution maximizeScore(){
List<List<Position>> moves = new ArrayList<>();
Solution intialSolution = new Solution(0,candyBoard, moves);
return findOptimalSolution(intialSolution, null);
}
private Solution findOptimalSolution(Solution partialSolution, Solution bestSoFar){
Set<List<Position>> swaps = getAllSwaps(partialSolution.board());
if(swaps.isEmpty()){
System.out.println(partialSolution.score());
System.out.println(partialSolution.calculateScore());
System.out.println("*-*");
if (bestSoFar == null || partialSolution.isBetterThan(bestSoFar)) {
return partialSolution;
} else {
return bestSoFar;
}
}
if(bestSoFar != null && partialSolution.canImproveUpon(bestSoFar)){
return bestSoFar;
}
for(List<Position> swap : swaps){
Board<Candy> mutableBoard = new Board<>(partialSolution.board().getBoardSize());
partialSolution.board().copyTo(mutableBoard);
swapCandies(swap.getFirst(), swap.getLast(), mutableBoard);
List<List<Position>> newMoves = new ArrayList<>(partialSolution.moves());
newMoves.add(swap);
Solution solution = new Solution(0, mutableBoard, newMoves);
int score = solution.calculateScore();
bestSoFar = findOptimalSolution(new Solution(score, mutableBoard, newMoves), bestSoFar);
}
return bestSoFar;
}
public Collection<Solution> solveAll(){
List<List<Position>> moves = new ArrayList<>();
Solution intialSolution = new Solution(0,candyBoard, moves);
ArrayList<Solution> collection = new ArrayList<>();
return findAllSolutions(intialSolution, collection);
}
private Collection<Solution> findAllSolutions(Solution partialSolution, Collection<Solution> solutionsSoFar){
Set<List<Position>> swaps = getAllSwaps(partialSolution.board());
if(swaps.isEmpty()){
System.out.println("Oplossing gevonden B)");
int score = partialSolution.calculateScore();
Solution solution = new Solution(score, partialSolution.board(), partialSolution.moves());
solution.printSolution();
solutionsSoFar.add(solution);
return solutionsSoFar;
}
for(List<Position> swap : swaps){
Board<Candy> mutableBoard = new Board<>(partialSolution.board().getBoardSize());
partialSolution.board().copyTo(mutableBoard);
swapCandies(swap.getFirst(), swap.getLast(), mutableBoard);
List<List<Position>> newMoves = new ArrayList<>(partialSolution.moves());
newMoves.add(swap);
findAllSolutions(new Solution(0, mutableBoard, newMoves), solutionsSoFar);
}
return solutionsSoFar;
}
public Solution solveAny(){
Solution intialSolution = new Solution(0,candyBoard, null);
return findAnySolution(intialSolution);
}
private Solution findAnySolution(Solution partialSolution){
Set<List<Position>> swaps = getAllSwaps(partialSolution.board());
if(swaps.isEmpty()) return partialSolution; // Current.isComplete()
for (List<Position> swap : swaps){
// SWAP
// 1. copy board vanuit record
// 2. swapcandies en update
// 3. maak partialSolution
// 4. recursie
Board<Candy> mutableBoard = new Board<>(partialSolution.board().getBoardSize());
partialSolution.board().copyTo(mutableBoard);
swapCandies(swap.getFirst(), swap.getLast(), mutableBoard);
int score = this.getScore();
return findAnySolution(new Solution(score, mutableBoard, null));
}
return null;
}
} | false | 2,812 | 13 | 3,164 | 15 | 3,305 | 12 | 3,164 | 15 | 3,769 | 14 | false | false | false | false | false | true |
1,406 | 24337_1 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
public class crystalYellow extends Mover
/*
Dit zorgt er voor dat een Coin/collectable op z'n plek blijft staan als je het oppakt.
Je geeft de methode de waarde true aan in ScoreBoard.class zodat applyVelocity(); word toegepast.
*/
{
boolean alwaysOnScreen = false;
public crystalYellow()
{
}
public crystalYellow(boolean onScreen)
{
this.alwaysOnScreen = onScreen;
}
public void act()
{
if(alwaysOnScreen == false)
{
applyVelocity();
}
}
}
| ROCMondriaanTIN/project-greenfoot-game-Xardas22 | crystalYellow.java | 205 | /*
Dit zorgt er voor dat een Coin/collectable op z'n plek blijft staan als je het oppakt.
Je geeft de methode de waarde true aan in ScoreBoard.class zodat applyVelocity(); word toegepast.
*/ | block_comment | nl | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
public class crystalYellow extends Mover
/*
Dit zorgt er<SUF>*/
{
boolean alwaysOnScreen = false;
public crystalYellow()
{
}
public crystalYellow(boolean onScreen)
{
this.alwaysOnScreen = onScreen;
}
public void act()
{
if(alwaysOnScreen == false)
{
applyVelocity();
}
}
}
| false | 160 | 57 | 173 | 64 | 180 | 51 | 173 | 64 | 213 | 70 | false | false | false | false | false | true |
1,642 | 171915_1 | package model;
/**
* @author Stefan van Tilburg
* <p>
* Opdracht 3.3 BSA Monitor
* <p>
* Doel Class Vak. Opslag voor Vak gegevens (naam, punten en cesuur).
*/
public class Vak {
private String naam;
private int punten;
private double cesuur; // cesuur is beoordelingsgrens tussen geslaagd / niet geslaagd
public Vak(String naam, int punten, double cesuur) {
this.naam = naam;
this.punten = punten;
this.cesuur = cesuur;
}
public String getNaam() {
return naam;
}
public int getPunten() {
return punten;
}
public double getCesuur() {
return cesuur;
}
}
| StefanvanTilburg/BSAMonitorCh4 | src/model/Vak.java | 220 | // cesuur is beoordelingsgrens tussen geslaagd / niet geslaagd | line_comment | nl | package model;
/**
* @author Stefan van Tilburg
* <p>
* Opdracht 3.3 BSA Monitor
* <p>
* Doel Class Vak. Opslag voor Vak gegevens (naam, punten en cesuur).
*/
public class Vak {
private String naam;
private int punten;
private double cesuur; // cesuur is<SUF>
public Vak(String naam, int punten, double cesuur) {
this.naam = naam;
this.punten = punten;
this.cesuur = cesuur;
}
public String getNaam() {
return naam;
}
public int getPunten() {
return punten;
}
public double getCesuur() {
return cesuur;
}
}
| false | 193 | 21 | 225 | 26 | 197 | 18 | 225 | 26 | 230 | 22 | false | false | false | false | false | true |
2,581 | 133718_8 | package Oefentoetspraktijkantwoorden;
public class Water extends Drank
{
//formaat is private zoals in klassendiagram stond
private int formaat;
//1 van de constructors
public Water() { this.formaat = 2; }
//1 van de constructors
public Water(String formaat) {
// logica kan op meerdere manieren
//gebruik van equals is verplicht aangezien String een object is en niet een primitief type
if (formaat != null) {
if (formaat.equals("klein")) {
this.formaat = 1;
} else if (formaat.equals("normaal")) {
this.formaat = 2;
} else if (formaat.equals("groot")) {
this.formaat = 3;
} else {
this.formaat = 1;
System.out.println("Hebben wij niet!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
/*
if (formaat ==("klein")) {
this.formaat = 1;
} else if (formaat ==("normaal")) {
this.formaat = 2;
} else if (formaat == ("groot")) {
this.formaat = 3;
} else {
this.formaat = 1;
System.out.println("Hebben wij niet!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
*/
} else {
this.formaat = 1;
System.out.println("Hebben wij niet!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
}
public int getFormaatVoorGui() { return formaat; }
// verplichte methode getPrijs
public double getPrijs() { return 0; }
//verplichte methode getOmschrijving
public String getOmschrijving() {
String txt = null;
if(formaat == 1) { txt = "klein";}
else if(formaat == 2) { txt = "normaal";}
else if(formaat == 3) { txt = "groot";}
return "een " + txt + " glas water";
}
//---------------- code voor testen ------------------------------
public static void _DEMO_water() {
Water w = new Water("groot");
System.out.println(w);
System.out.println(w.getOmschrijving());
System.out.println(w.getPrijs());
System.out.println(new Water());
Water wXXL = new Water("XXL");
System.out.println(wXXL);
}
}
| donnyrsk/Huiswerk | src/Oefentoetspraktijkantwoorden/Water.java | 685 | //---------------- code voor testen ------------------------------ | line_comment | nl | package Oefentoetspraktijkantwoorden;
public class Water extends Drank
{
//formaat is private zoals in klassendiagram stond
private int formaat;
//1 van de constructors
public Water() { this.formaat = 2; }
//1 van de constructors
public Water(String formaat) {
// logica kan op meerdere manieren
//gebruik van equals is verplicht aangezien String een object is en niet een primitief type
if (formaat != null) {
if (formaat.equals("klein")) {
this.formaat = 1;
} else if (formaat.equals("normaal")) {
this.formaat = 2;
} else if (formaat.equals("groot")) {
this.formaat = 3;
} else {
this.formaat = 1;
System.out.println("Hebben wij niet!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
/*
if (formaat ==("klein")) {
this.formaat = 1;
} else if (formaat ==("normaal")) {
this.formaat = 2;
} else if (formaat == ("groot")) {
this.formaat = 3;
} else {
this.formaat = 1;
System.out.println("Hebben wij niet!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
*/
} else {
this.formaat = 1;
System.out.println("Hebben wij niet!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
}
public int getFormaatVoorGui() { return formaat; }
// verplichte methode getPrijs
public double getPrijs() { return 0; }
//verplichte methode getOmschrijving
public String getOmschrijving() {
String txt = null;
if(formaat == 1) { txt = "klein";}
else if(formaat == 2) { txt = "normaal";}
else if(formaat == 3) { txt = "groot";}
return "een " + txt + " glas water";
}
//---------------- code<SUF>
public static void _DEMO_water() {
Water w = new Water("groot");
System.out.println(w);
System.out.println(w.getOmschrijving());
System.out.println(w.getPrijs());
System.out.println(new Water());
Water wXXL = new Water("XXL");
System.out.println(wXXL);
}
}
| false | 567 | 7 | 657 | 8 | 616 | 8 | 657 | 8 | 807 | 10 | false | false | false | false | false | true |
1,928 | 24431_1 | import Commands.Calendar.AddSession;
import Commands.Calendar.Calendar;
import Commands.Calendar.RemoveSession;
import Commands.Command;
import Commands.Dice;
import Commands.Food.AddFood;
import Commands.Food.GetFood;
import Commands.Food.RemoveFood;
import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
import java.awt.*;
import java.util.*;
/**
* Luisteraar die luistert naar commando's
*/
public class CommandListener extends ListenerAdapter {
private Map<String, Command> dicecommands = Map.of(
"d4", new Dice(4),
"d6", new Dice(6),
"d8", new Dice(8),
"d10", new Dice(10),
"d12", new Dice(12),
"d20", new Dice(20),
"d100", new Dice(100)
);
private ArrayList<Command> commands = new ArrayList<>(Arrays.asList(new Calendar(), new AddSession(), new RemoveSession(), new AddFood(), new GetFood(), new RemoveFood()));
private ArrayList<Command> testcommands = new ArrayList<>(Arrays.asList(new DungeonMaster()));
/**
* Deze methode checkt of een bericht een geldig commanda is en als dit zo is checkt het of het een dicecommand is, een hulp command of een complex (aka 1tje van meerdere woroden) command.
* -> Dicecommand: Gooi de desbetreffende dice x keer
* -> Hulp command: Bouw de hulpboodschap op en toon deze
* -> Complex command: Check of er woord daaruit een commando is en voer deze dan uit.
* @param e Event die getrowed wordt iedere keer dat er een bericht verstuurd wordt
*/
@Override
public void onGuildMessageReceived(GuildMessageReceivedEvent e) {
String message = e.getMessage().getContentRaw();
String[] words = message.split(" ");
if (message.length() > 0 && words[0].charAt(0) == '/') {
String command = words[0].substring(1);
if (words.length <= 2 && dicecommands.keySet().contains(command.toLowerCase())) {
dicecommands.get(command).run(Arrays.copyOfRange(words, 1, words.length), e);
// Matches(regex) -> (?i) is voor case insensitive
} else if (words.length == 1 && command.matches("(?i)^(commands|help|h)$")) {
EmbedBuilder eb = new EmbedBuilder();
eb.setTitle("Sumarville Commands");
Map<String, StringBuilder> sbs = new HashMap<>();
for (Command c : commands) {
String cat = c.getCategory();
if (!sbs.containsKey(cat)) {
sbs.put(cat, new StringBuilder());
}
StringBuilder sb = sbs.get(cat);
sb.append(String.format("\n/%s[", c.getName()));
sb.append("\n/").append(c.getName()).append("[");
Arrays.stream(c.getAliases()).forEach(alias -> sb.append(alias).append(", "));
sb.delete(sb.length() - 2, sb.length()).append(String.format("]: %s", c.getDescription()));
}
eb.addField("Dice rolls", "/d4, /d6, /d8, /d10, /d12, /d20, /d100", true);
eb.setColor(Color.ORANGE);
sbs.keySet().forEach(s -> eb.addField(s, sbs.get(s).toString().trim(), false));
e.getChannel().sendMessage(eb.build()).queue();
} else {
int ctr = 0;
while (ctr < commands.size() && !commands.get(ctr).isCommandFor(command)) {
ctr++;
}
if (ctr < commands.size()) {
commands.get(ctr).run(Arrays.copyOfRange(words, 1, words.length), e);
} else {
for (Command c : testcommands) {
if (c.isCommandFor(command)) {
c.run(Arrays.copyOfRange(words, 1, words.length), e);
}
}
}
}
}
}
}
| Zelzahn/DnD_Discord_Bot | src/main/java/CommandListener.java | 1,230 | /**
* Deze methode checkt of een bericht een geldig commanda is en als dit zo is checkt het of het een dicecommand is, een hulp command of een complex (aka 1tje van meerdere woroden) command.
* -> Dicecommand: Gooi de desbetreffende dice x keer
* -> Hulp command: Bouw de hulpboodschap op en toon deze
* -> Complex command: Check of er woord daaruit een commando is en voer deze dan uit.
* @param e Event die getrowed wordt iedere keer dat er een bericht verstuurd wordt
*/ | block_comment | nl | import Commands.Calendar.AddSession;
import Commands.Calendar.Calendar;
import Commands.Calendar.RemoveSession;
import Commands.Command;
import Commands.Dice;
import Commands.Food.AddFood;
import Commands.Food.GetFood;
import Commands.Food.RemoveFood;
import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
import java.awt.*;
import java.util.*;
/**
* Luisteraar die luistert naar commando's
*/
public class CommandListener extends ListenerAdapter {
private Map<String, Command> dicecommands = Map.of(
"d4", new Dice(4),
"d6", new Dice(6),
"d8", new Dice(8),
"d10", new Dice(10),
"d12", new Dice(12),
"d20", new Dice(20),
"d100", new Dice(100)
);
private ArrayList<Command> commands = new ArrayList<>(Arrays.asList(new Calendar(), new AddSession(), new RemoveSession(), new AddFood(), new GetFood(), new RemoveFood()));
private ArrayList<Command> testcommands = new ArrayList<>(Arrays.asList(new DungeonMaster()));
/**
* Deze methode checkt<SUF>*/
@Override
public void onGuildMessageReceived(GuildMessageReceivedEvent e) {
String message = e.getMessage().getContentRaw();
String[] words = message.split(" ");
if (message.length() > 0 && words[0].charAt(0) == '/') {
String command = words[0].substring(1);
if (words.length <= 2 && dicecommands.keySet().contains(command.toLowerCase())) {
dicecommands.get(command).run(Arrays.copyOfRange(words, 1, words.length), e);
// Matches(regex) -> (?i) is voor case insensitive
} else if (words.length == 1 && command.matches("(?i)^(commands|help|h)$")) {
EmbedBuilder eb = new EmbedBuilder();
eb.setTitle("Sumarville Commands");
Map<String, StringBuilder> sbs = new HashMap<>();
for (Command c : commands) {
String cat = c.getCategory();
if (!sbs.containsKey(cat)) {
sbs.put(cat, new StringBuilder());
}
StringBuilder sb = sbs.get(cat);
sb.append(String.format("\n/%s[", c.getName()));
sb.append("\n/").append(c.getName()).append("[");
Arrays.stream(c.getAliases()).forEach(alias -> sb.append(alias).append(", "));
sb.delete(sb.length() - 2, sb.length()).append(String.format("]: %s", c.getDescription()));
}
eb.addField("Dice rolls", "/d4, /d6, /d8, /d10, /d12, /d20, /d100", true);
eb.setColor(Color.ORANGE);
sbs.keySet().forEach(s -> eb.addField(s, sbs.get(s).toString().trim(), false));
e.getChannel().sendMessage(eb.build()).queue();
} else {
int ctr = 0;
while (ctr < commands.size() && !commands.get(ctr).isCommandFor(command)) {
ctr++;
}
if (ctr < commands.size()) {
commands.get(ctr).run(Arrays.copyOfRange(words, 1, words.length), e);
} else {
for (Command c : testcommands) {
if (c.isCommandFor(command)) {
c.run(Arrays.copyOfRange(words, 1, words.length), e);
}
}
}
}
}
}
}
| false | 915 | 145 | 1,058 | 152 | 1,068 | 133 | 1,058 | 152 | 1,199 | 152 | false | false | false | false | false | true |
3,555 | 97790_2 | package nl.kadaster.brk.graphql.aantekening;
import com.fasterxml.jackson.annotation.JsonInclude;
import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL;
/**
* @author Marc van Andel
* @since 0.1
*/
@JsonInclude(NON_NULL)
public class KoopovereenkomstAantekening extends Aantekening {
/**
* Einddatum van de koopovereenkomst.
*/
public String einddatum;
/**
* Tijdstip waarop de aantekening komt te vervallen.
*/
public String tijdstipVervallen;
}
| marcvanandel/brk-graphql-example | src/main/java/nl/kadaster/brk/graphql/aantekening/KoopovereenkomstAantekening.java | 180 | /**
* Tijdstip waarop de aantekening komt te vervallen.
*/ | block_comment | nl | package nl.kadaster.brk.graphql.aantekening;
import com.fasterxml.jackson.annotation.JsonInclude;
import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL;
/**
* @author Marc van Andel
* @since 0.1
*/
@JsonInclude(NON_NULL)
public class KoopovereenkomstAantekening extends Aantekening {
/**
* Einddatum van de koopovereenkomst.
*/
public String einddatum;
/**
* Tijdstip waarop de<SUF>*/
public String tijdstipVervallen;
}
| false | 136 | 21 | 163 | 23 | 150 | 20 | 163 | 23 | 185 | 24 | false | false | false | false | false | true |
854 | 22443_1 | package model;
import model.article.Article;
import model.basket.Basket;
import model.log.Log;
import model.observer.Observer;
import model.shop.Shop;
import db.ArticleDbContext;
import java.io.IOException;
import java.util.*;
/**
* @author the team
*/
public class DomainFacade {
private final Shop shop;
private final Log log;
public DomainFacade() throws IOException {
Prop.load();
this.log = new Log();
this.shop = new Shop(log);
}
public Log getLog() {
return log;
}
public List<String> getLogItems() {
return log.getItems();
}
public void addLogObserver(Observer observer) {
log.addObserver(observer);
}
public Shop getShop() {
return shop;
}
public ArticleDbContext getArticleDb() {
return shop.getArticleDb();
}
public void putSaleOnHold() {
shop.putSaleOnHold();
}
public void continueHeldSale() {
shop.resumeSale();
}
public boolean saleIsOnHold() {
return shop.saleIsOnHold();
}
public void addShopObserver(Observer observer) { shop.addObserver(observer); }
public void removeShopObserver(Observer observer) { shop.removeObserver(observer); }
//region Basket
public Basket getBasket() {
return shop.getBasket();
}
public void updateDiscountContext() {
getBasket().updateDiscountContext();
}
public void addBasketObserver(Observer observer) {
getBasket().addObserver(observer);
}
public void removeBasketObserver(Observer observer) {
getBasket().removeObserver(observer);
}
public void closeBasket() {
getBasket().close();
}
public void payBasket() {
getBasket().pay();
}
public void cancelBasket() {
getBasket().cancel();
}
public void addBasketArticle(Article article) {
getBasket().add(article);
}
public Collection<Article> getAllUniqueBasketArticles() {
return getBasket().getAllUniqueArticles();
}
public Map<Article, Integer> getBasketArticleStacks() {
return getBasket().getArticleStacks();
}
public void removeBasketArticle(Article article) {
getBasket().remove(article);
}
public void removeBasketArticles(Map<Article, Integer> articleAmountsToRemove) {
getBasket().removeAll(articleAmountsToRemove);
}
public void removeBasketArticles(Collection<Article> articles) {
getBasket().removeAll(articles);
}
public void clearBasketArticles() {
getBasket().clear();
}
//Geeft prijs ZONDER toegepaste korting
public double getBasketTotalPrice() {
return getBasket().getTotalPrice();
}
//Geeft totale prijs MET korting toegepast
public double getBasketDiscountedPrice() {
return getBasket().getTotalDiscountedPrice();
}
//endregion
}
| JonasBerx/3_Berx_Draelants_Fiers_KassaApp_2019 | src/model/DomainFacade.java | 872 | //Geeft prijs ZONDER toegepaste korting | line_comment | nl | package model;
import model.article.Article;
import model.basket.Basket;
import model.log.Log;
import model.observer.Observer;
import model.shop.Shop;
import db.ArticleDbContext;
import java.io.IOException;
import java.util.*;
/**
* @author the team
*/
public class DomainFacade {
private final Shop shop;
private final Log log;
public DomainFacade() throws IOException {
Prop.load();
this.log = new Log();
this.shop = new Shop(log);
}
public Log getLog() {
return log;
}
public List<String> getLogItems() {
return log.getItems();
}
public void addLogObserver(Observer observer) {
log.addObserver(observer);
}
public Shop getShop() {
return shop;
}
public ArticleDbContext getArticleDb() {
return shop.getArticleDb();
}
public void putSaleOnHold() {
shop.putSaleOnHold();
}
public void continueHeldSale() {
shop.resumeSale();
}
public boolean saleIsOnHold() {
return shop.saleIsOnHold();
}
public void addShopObserver(Observer observer) { shop.addObserver(observer); }
public void removeShopObserver(Observer observer) { shop.removeObserver(observer); }
//region Basket
public Basket getBasket() {
return shop.getBasket();
}
public void updateDiscountContext() {
getBasket().updateDiscountContext();
}
public void addBasketObserver(Observer observer) {
getBasket().addObserver(observer);
}
public void removeBasketObserver(Observer observer) {
getBasket().removeObserver(observer);
}
public void closeBasket() {
getBasket().close();
}
public void payBasket() {
getBasket().pay();
}
public void cancelBasket() {
getBasket().cancel();
}
public void addBasketArticle(Article article) {
getBasket().add(article);
}
public Collection<Article> getAllUniqueBasketArticles() {
return getBasket().getAllUniqueArticles();
}
public Map<Article, Integer> getBasketArticleStacks() {
return getBasket().getArticleStacks();
}
public void removeBasketArticle(Article article) {
getBasket().remove(article);
}
public void removeBasketArticles(Map<Article, Integer> articleAmountsToRemove) {
getBasket().removeAll(articleAmountsToRemove);
}
public void removeBasketArticles(Collection<Article> articles) {
getBasket().removeAll(articles);
}
public void clearBasketArticles() {
getBasket().clear();
}
//Geeft prijs<SUF>
public double getBasketTotalPrice() {
return getBasket().getTotalPrice();
}
//Geeft totale prijs MET korting toegepast
public double getBasketDiscountedPrice() {
return getBasket().getTotalDiscountedPrice();
}
//endregion
}
| false | 627 | 14 | 680 | 15 | 743 | 10 | 680 | 15 | 888 | 16 | false | false | false | false | false | true |
643 | 37717_2 | package be.SabahLeanderSteven.endtermandroidproject.model;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.Query;
import java.util.List;
@Dao
public interface LocationDAO {
@Insert
void insert(Location location);
@Query("DELETE FROM locations")
void deleteAll();
//vermijd het zelf aanspreken van getters etc., sowieso al geobserveerd
//livedata werkt enkel met List, niet met ArrayList
//wordt geen list,
@Query("SELECT * from locations")
LiveData<List<Location>> getAllLocations();
@Query("SELECT * FROM locations WHERE id LIKE :id")
Location findLocationById(String id);
@Query("SELECT * FROM locations WHERE type LIKE :type")
LiveData<List<Location>> getAllLocationsOfType(String type);
}
| H3AR7B3A7/EndTermAndroidProject | app/src/main/java/be/SabahLeanderSteven/endtermandroidproject/model/LocationDAO.java | 241 | //wordt geen list, | line_comment | nl | package be.SabahLeanderSteven.endtermandroidproject.model;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.Query;
import java.util.List;
@Dao
public interface LocationDAO {
@Insert
void insert(Location location);
@Query("DELETE FROM locations")
void deleteAll();
//vermijd het zelf aanspreken van getters etc., sowieso al geobserveerd
//livedata werkt enkel met List, niet met ArrayList
//wordt geen<SUF>
@Query("SELECT * from locations")
LiveData<List<Location>> getAllLocations();
@Query("SELECT * FROM locations WHERE id LIKE :id")
Location findLocationById(String id);
@Query("SELECT * FROM locations WHERE type LIKE :type")
LiveData<List<Location>> getAllLocationsOfType(String type);
}
| false | 183 | 6 | 216 | 7 | 211 | 6 | 216 | 7 | 248 | 6 | false | false | false | false | false | true |
290 | 52977_0 | package nl.knaw.huygens.timbuctoo.core.dto;
import com.fasterxml.jackson.databind.JsonNode;
import javaslang.control.Try;
import nl.knaw.huygens.timbuctoo.core.dto.dataset.Collection;
import nl.knaw.huygens.timbuctoo.model.properties.ReadableProperty;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Optional;
import static nl.knaw.huygens.timbuctoo.logging.Logmarkers.databaseInvariant;
public class DisplayNameHelper {
private static final Logger LOG = LoggerFactory.getLogger(DisplayNameHelper.class);
public static Optional<String> getDisplayname(GraphTraversalSource traversalSource, Vertex vertex,
Collection targetCollection) {
ReadableProperty displayNameProperty = targetCollection.getDisplayName();
if (displayNameProperty != null) {
GraphTraversal<Vertex, Try<JsonNode>> displayNameGetter = traversalSource.V(vertex.id()).union(
targetCollection.getDisplayName().traversalJson()
);
if (displayNameGetter.hasNext()) {
Try<JsonNode> traversalResult = displayNameGetter.next();
if (!traversalResult.isSuccess()) {
LOG.debug(databaseInvariant, "Retrieving displayname failed", traversalResult.getCause());
} else {
if (traversalResult.get() == null) {
LOG.debug(databaseInvariant, "Displayname was null");
} else {
if (!traversalResult.get().isTextual()) {
LOG.debug(databaseInvariant, "Displayname was not a string but " + traversalResult.get().toString());
} else {
return Optional.of(traversalResult.get().asText());
}
}
}
} else {
LOG.debug(databaseInvariant, "Displayname traversal resulted in no results: " + displayNameGetter);
}
} else {
LOG.debug("No displayname configured for " + targetCollection.getEntityTypeName());
//FIXME: deze wordt gegooid tijdens de finish. da's raar
}
return Optional.empty();
}
}
| CLARIAH/timbuctoo | timbuctoo-instancev4/src/main/java/nl/knaw/huygens/timbuctoo/core/dto/DisplayNameHelper.java | 674 | //FIXME: deze wordt gegooid tijdens de finish. da's raar | line_comment | nl | package nl.knaw.huygens.timbuctoo.core.dto;
import com.fasterxml.jackson.databind.JsonNode;
import javaslang.control.Try;
import nl.knaw.huygens.timbuctoo.core.dto.dataset.Collection;
import nl.knaw.huygens.timbuctoo.model.properties.ReadableProperty;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Optional;
import static nl.knaw.huygens.timbuctoo.logging.Logmarkers.databaseInvariant;
public class DisplayNameHelper {
private static final Logger LOG = LoggerFactory.getLogger(DisplayNameHelper.class);
public static Optional<String> getDisplayname(GraphTraversalSource traversalSource, Vertex vertex,
Collection targetCollection) {
ReadableProperty displayNameProperty = targetCollection.getDisplayName();
if (displayNameProperty != null) {
GraphTraversal<Vertex, Try<JsonNode>> displayNameGetter = traversalSource.V(vertex.id()).union(
targetCollection.getDisplayName().traversalJson()
);
if (displayNameGetter.hasNext()) {
Try<JsonNode> traversalResult = displayNameGetter.next();
if (!traversalResult.isSuccess()) {
LOG.debug(databaseInvariant, "Retrieving displayname failed", traversalResult.getCause());
} else {
if (traversalResult.get() == null) {
LOG.debug(databaseInvariant, "Displayname was null");
} else {
if (!traversalResult.get().isTextual()) {
LOG.debug(databaseInvariant, "Displayname was not a string but " + traversalResult.get().toString());
} else {
return Optional.of(traversalResult.get().asText());
}
}
}
} else {
LOG.debug(databaseInvariant, "Displayname traversal resulted in no results: " + displayNameGetter);
}
} else {
LOG.debug("No displayname configured for " + targetCollection.getEntityTypeName());
//FIXME: deze<SUF>
}
return Optional.empty();
}
}
| false | 459 | 17 | 549 | 19 | 566 | 18 | 549 | 19 | 669 | 18 | false | false | false | false | false | true |
4,343 | 20898_3 | /*
Copyright 2013 Nationale-Nederlanden
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package nl.nn.adapterframework.webcontrol.action;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nl.nn.adapterframework.scheduler.SchedulerAdapter;
import nl.nn.adapterframework.scheduler.SchedulerHelper;
import nl.nn.adapterframework.unmanaged.DefaultIbisManager;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
/**
* @author Johan Verrips
*/
public class SchedulerHandler extends ActionBase {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// Extract attributes we will need
initAction(request);
String action = request.getParameter("action");
if (null == action)
action = mapping.getParameter();
String jobName = request.getParameter("jobName");
String groupName = request.getParameter("groupName");
if (ibisManager==null) {
error("Cannot find ibismanager",null);
return null;
}
// TODO Dit moet natuurlijk netter...
DefaultIbisManager manager = (DefaultIbisManager)ibisManager;
SchedulerHelper sh = manager.getSchedulerHelper();
SchedulerAdapter schedulerAdapter = new SchedulerAdapter();
Scheduler scheduler;
try {
scheduler = sh.getScheduler();
} catch (SchedulerException e) {
error("Cannot find scheduler",e);
return null;
}
try {
if (action.equalsIgnoreCase("startScheduler")) {
log.info("start scheduler:" + new Date() + getCommandIssuedBy(request));
scheduler.start();
} else
if (action.equalsIgnoreCase("pauseScheduler")) {
log.info("pause scheduler:" + new Date() + getCommandIssuedBy(request));
scheduler.pause();
} else
if (action.equalsIgnoreCase("deleteJob")) {
log.info("delete job jobName [" + jobName
+ "] groupName [" + groupName
+ "] " + getCommandIssuedBy(request));
scheduler.deleteJob(jobName, groupName);
} else
if (action.equalsIgnoreCase("triggerJob")) {
log.info("trigger job jobName [" + jobName
+ "] groupName [" + groupName
+ "] " + getCommandIssuedBy(request));
scheduler.triggerJob(jobName, groupName);
} else {
log.error("no valid argument for SchedulerHandler:" + action);
}
} catch (Exception e) {
error("",e);
}
// Report any errors
if (!errors.isEmpty()) {
saveErrors(request, errors);
}
// Remove the obsolete form bean
if (mapping.getAttribute() != null) {
if ("request".equals(mapping.getScope()))
request.removeAttribute(mapping.getAttribute());
else
session.removeAttribute(mapping.getAttribute());
}
// Forward control to the specified success URI
return (mapping.findForward("success"));
}
}
| smhoekstra/iaf-1 | core/src/main/java/nl/nn/adapterframework/webcontrol/action/SchedulerHandler.java | 1,115 | // TODO Dit moet natuurlijk netter... | line_comment | nl | /*
Copyright 2013 Nationale-Nederlanden
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package nl.nn.adapterframework.webcontrol.action;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nl.nn.adapterframework.scheduler.SchedulerAdapter;
import nl.nn.adapterframework.scheduler.SchedulerHelper;
import nl.nn.adapterframework.unmanaged.DefaultIbisManager;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
/**
* @author Johan Verrips
*/
public class SchedulerHandler extends ActionBase {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// Extract attributes we will need
initAction(request);
String action = request.getParameter("action");
if (null == action)
action = mapping.getParameter();
String jobName = request.getParameter("jobName");
String groupName = request.getParameter("groupName");
if (ibisManager==null) {
error("Cannot find ibismanager",null);
return null;
}
// TODO Dit<SUF>
DefaultIbisManager manager = (DefaultIbisManager)ibisManager;
SchedulerHelper sh = manager.getSchedulerHelper();
SchedulerAdapter schedulerAdapter = new SchedulerAdapter();
Scheduler scheduler;
try {
scheduler = sh.getScheduler();
} catch (SchedulerException e) {
error("Cannot find scheduler",e);
return null;
}
try {
if (action.equalsIgnoreCase("startScheduler")) {
log.info("start scheduler:" + new Date() + getCommandIssuedBy(request));
scheduler.start();
} else
if (action.equalsIgnoreCase("pauseScheduler")) {
log.info("pause scheduler:" + new Date() + getCommandIssuedBy(request));
scheduler.pause();
} else
if (action.equalsIgnoreCase("deleteJob")) {
log.info("delete job jobName [" + jobName
+ "] groupName [" + groupName
+ "] " + getCommandIssuedBy(request));
scheduler.deleteJob(jobName, groupName);
} else
if (action.equalsIgnoreCase("triggerJob")) {
log.info("trigger job jobName [" + jobName
+ "] groupName [" + groupName
+ "] " + getCommandIssuedBy(request));
scheduler.triggerJob(jobName, groupName);
} else {
log.error("no valid argument for SchedulerHandler:" + action);
}
} catch (Exception e) {
error("",e);
}
// Report any errors
if (!errors.isEmpty()) {
saveErrors(request, errors);
}
// Remove the obsolete form bean
if (mapping.getAttribute() != null) {
if ("request".equals(mapping.getScope()))
request.removeAttribute(mapping.getAttribute());
else
session.removeAttribute(mapping.getAttribute());
}
// Forward control to the specified success URI
return (mapping.findForward("success"));
}
}
| false | 771 | 9 | 878 | 12 | 974 | 8 | 878 | 12 | 1,140 | 11 | false | false | false | false | false | true |
2,908 | 125818_0 | package chris;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
public class Day13 {
private static AtomicBoolean smudge = new AtomicBoolean();
public static void main(String[] args) {
System.out.println(puzzel1());
System.out.println(puzzel2());
}
private static String puzzel1() {
try (BufferedReader bufferedReader = new BufferedReader(new FileReader("puzzel13.txt"))) {
List<List<Character>> field = new ArrayList<>();
String regel;
AtomicLong totaal =new AtomicLong();
while ((regel = bufferedReader.readLine()) != null) {
if(!regel.isEmpty()) {
List<Character> fill = new ArrayList<>();
for (int x = 0; x < regel.length(); x++) {
fill.add(regel.charAt(x));
}
field.add(fill);
} else {
// vind perfecte horizontale spiegels
int grootstePerfect = 0;
for(int x=0; x< field.size() -1;x++) {
boolean hMatch = getHMatch(field, x, x + 1);
if (hMatch) {
boolean perfect = true;
for (int i= x;i> 0; i--) {
if (x + (x-i) + 2 == field.size()) break;
if (!(getHMatch(field, i - 1, x + (x-i) + 2))) {
perfect = false;
break;
}
}
if(perfect) {
totaal.addAndGet(100 * (x + 1));
break;
}
}
}
// vind perfecte verticale spiegels
for(int y=0; y< field.get(0).size() -1;y++) {
boolean vMatch = getVMatch(field, y, y + 1);
if (vMatch) {
boolean perfect = true;
for (int i= y;i> 0; i--) {
if (y + (y-i) + 2 == field.get(0).size()) break;
if (!(getVMatch(field, i - 1, y + (y-i) + 2))) {
perfect = false;
break;
}
}
if(perfect) {
totaal.addAndGet(y + 1);
break;
}
}
}
field = new ArrayList<>();
}
}
return totaal.toString();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
private static String puzzel2() {
try (BufferedReader bufferedReader = new BufferedReader(new FileReader("puzzel13.txt"))) {
List<List<Character>> field = new ArrayList<>();
String regel;
AtomicLong totaal =new AtomicLong();
while ((regel = bufferedReader.readLine()) != null) {
if(!regel.isEmpty()) {
List<Character> fill = new ArrayList<>();
for (int x = 0; x < regel.length(); x++) {
fill.add(regel.charAt(x));
}
field.add(fill);
} else {
// vind perfecte horizontale spiegels
int grootstePerfect = 0;
for(int x=0; x< field.size() -1;x++) {
boolean hMatch = getHMatchS(field, x, x + 1);
if (hMatch) {
boolean perfect = true;
for (int i= x;i> 0; i--) {
if (x + (x-i) + 2 == field.size()) break;
if (!(getHMatchS(field, i - 1, x + (x-i) + 2))) {
perfect = false;
smudge.set(false);
break;
}
}
if(perfect && smudge.get()) {
smudge.set(false);
totaal.addAndGet(100 * (x + 1));
break;
}
} else {
smudge.set(false);
}
}
// vind perfecte verticale spiegels
for(int y=0; y< field.get(0).size() -1;y++) {
boolean vMatch = getVMatchS(field, y, y + 1);
if (vMatch) {
boolean perfect = true;
for (int i= y;i> 0; i--) {
if (y + (y-i) + 2 == field.get(0).size()) break;
if (!(getVMatchS(field, i - 1, y + (y-i) + 2))) {
perfect = false;
smudge.set(false);
break;
}
}
if(perfect && smudge.get()) {
smudge.set(false);
totaal.addAndGet(y + 1);
break;
}
} else {
smudge.set(false);
}
}
field = new ArrayList<>();
}
}
return totaal.toString();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
private static boolean getHMatch(List<List<Character>> field, int x, int x2) {
int match = 0;
for(int y=0;y<field.get(x).size();y++) {
if(field.get(x).get(y).equals(field.get(x2).get(y))) match++;
}
return match == field.get(x).size();
}
private static boolean getVMatch(List<List<Character>> field, int y, int y2) {
int match = 0;
for(int x=0;x<field.size();x++) {
if(field.get(x).get(y).equals(field.get(x).get(y2))) match++;
}
return match == field.size();
}
private static boolean getHMatchS(List<List<Character>> field, int x, int x2) {
int match = 0;
for(int y=0;y<field.get(x).size();y++) {
if(field.get(x).get(y).equals(field.get(x2).get(y))) match++;
}
if (match == field.get(x).size() - 1 && !smudge.get()) {
smudge.set(true);
return true;
}
return match == field.get(x).size();
}
private static boolean getVMatchS(List<List<Character>> field, int y, int y2) {
int match = 0;
for(int x=0;x<field.size();x++) {
if(field.get(x).get(y).equals(field.get(x).get(y2))) match++;
}
if (match == field.size() - 1 && !smudge.get()) {
smudge.set(true);
return true;
}
return match == field.size();
}
}
| hartenc/advent-of-code-2023 | src/java/chris/Day13.java | 2,088 | // vind perfecte horizontale spiegels | line_comment | nl | package chris;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
public class Day13 {
private static AtomicBoolean smudge = new AtomicBoolean();
public static void main(String[] args) {
System.out.println(puzzel1());
System.out.println(puzzel2());
}
private static String puzzel1() {
try (BufferedReader bufferedReader = new BufferedReader(new FileReader("puzzel13.txt"))) {
List<List<Character>> field = new ArrayList<>();
String regel;
AtomicLong totaal =new AtomicLong();
while ((regel = bufferedReader.readLine()) != null) {
if(!regel.isEmpty()) {
List<Character> fill = new ArrayList<>();
for (int x = 0; x < regel.length(); x++) {
fill.add(regel.charAt(x));
}
field.add(fill);
} else {
// vind perfecte<SUF>
int grootstePerfect = 0;
for(int x=0; x< field.size() -1;x++) {
boolean hMatch = getHMatch(field, x, x + 1);
if (hMatch) {
boolean perfect = true;
for (int i= x;i> 0; i--) {
if (x + (x-i) + 2 == field.size()) break;
if (!(getHMatch(field, i - 1, x + (x-i) + 2))) {
perfect = false;
break;
}
}
if(perfect) {
totaal.addAndGet(100 * (x + 1));
break;
}
}
}
// vind perfecte verticale spiegels
for(int y=0; y< field.get(0).size() -1;y++) {
boolean vMatch = getVMatch(field, y, y + 1);
if (vMatch) {
boolean perfect = true;
for (int i= y;i> 0; i--) {
if (y + (y-i) + 2 == field.get(0).size()) break;
if (!(getVMatch(field, i - 1, y + (y-i) + 2))) {
perfect = false;
break;
}
}
if(perfect) {
totaal.addAndGet(y + 1);
break;
}
}
}
field = new ArrayList<>();
}
}
return totaal.toString();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
private static String puzzel2() {
try (BufferedReader bufferedReader = new BufferedReader(new FileReader("puzzel13.txt"))) {
List<List<Character>> field = new ArrayList<>();
String regel;
AtomicLong totaal =new AtomicLong();
while ((regel = bufferedReader.readLine()) != null) {
if(!regel.isEmpty()) {
List<Character> fill = new ArrayList<>();
for (int x = 0; x < regel.length(); x++) {
fill.add(regel.charAt(x));
}
field.add(fill);
} else {
// vind perfecte horizontale spiegels
int grootstePerfect = 0;
for(int x=0; x< field.size() -1;x++) {
boolean hMatch = getHMatchS(field, x, x + 1);
if (hMatch) {
boolean perfect = true;
for (int i= x;i> 0; i--) {
if (x + (x-i) + 2 == field.size()) break;
if (!(getHMatchS(field, i - 1, x + (x-i) + 2))) {
perfect = false;
smudge.set(false);
break;
}
}
if(perfect && smudge.get()) {
smudge.set(false);
totaal.addAndGet(100 * (x + 1));
break;
}
} else {
smudge.set(false);
}
}
// vind perfecte verticale spiegels
for(int y=0; y< field.get(0).size() -1;y++) {
boolean vMatch = getVMatchS(field, y, y + 1);
if (vMatch) {
boolean perfect = true;
for (int i= y;i> 0; i--) {
if (y + (y-i) + 2 == field.get(0).size()) break;
if (!(getVMatchS(field, i - 1, y + (y-i) + 2))) {
perfect = false;
smudge.set(false);
break;
}
}
if(perfect && smudge.get()) {
smudge.set(false);
totaal.addAndGet(y + 1);
break;
}
} else {
smudge.set(false);
}
}
field = new ArrayList<>();
}
}
return totaal.toString();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
private static boolean getHMatch(List<List<Character>> field, int x, int x2) {
int match = 0;
for(int y=0;y<field.get(x).size();y++) {
if(field.get(x).get(y).equals(field.get(x2).get(y))) match++;
}
return match == field.get(x).size();
}
private static boolean getVMatch(List<List<Character>> field, int y, int y2) {
int match = 0;
for(int x=0;x<field.size();x++) {
if(field.get(x).get(y).equals(field.get(x).get(y2))) match++;
}
return match == field.size();
}
private static boolean getHMatchS(List<List<Character>> field, int x, int x2) {
int match = 0;
for(int y=0;y<field.get(x).size();y++) {
if(field.get(x).get(y).equals(field.get(x2).get(y))) match++;
}
if (match == field.get(x).size() - 1 && !smudge.get()) {
smudge.set(true);
return true;
}
return match == field.get(x).size();
}
private static boolean getVMatchS(List<List<Character>> field, int y, int y2) {
int match = 0;
for(int x=0;x<field.size();x++) {
if(field.get(x).get(y).equals(field.get(x).get(y2))) match++;
}
if (match == field.size() - 1 && !smudge.get()) {
smudge.set(true);
return true;
}
return match == field.size();
}
}
| false | 1,498 | 10 | 1,715 | 12 | 1,827 | 7 | 1,715 | 12 | 2,042 | 11 | false | false | false | false | false | true |
1,271 | 122914_4 | package nl.pdok.gml3.impl.gml3_1_1_2.convertors;
import jakarta.xml.bind.JAXBElement;
import java.util.ArrayList;
import java.util.List;
import net.opengis.gml.v_3_1_1.*;
import nl.pdok.gml3.exceptions.GeometryException;
import nl.pdok.gml3.exceptions.GeometryValidationErrorType;
import nl.pdok.gml3.exceptions.InvalidGeometryException;
import nl.pdok.gml3.exceptions.UnsupportedGeometrySpecificationException;
import org.locationtech.jts.algorithm.Orientation;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.MultiPolygon;
import org.locationtech.jts.geom.Polygon;
/**
* <p>
* GMLToSurfaceConvertor class.
* </p>
*
* @author GinkeM
* @version $Id: $Id
*/
public class GMLToSurfaceConvertor {
private final GeometryFactory geometryFactory;
private final GMLToLineConvertor gmlToLineConvertor;
/**
* <p>
* Constructor for GMLToSurfaceConvertor.
* </p>
*
* @param geometryFactory a {@link org.locationtech.jts.geom.GeometryFactory} object.
* @param gmlToLineConvertor a {@link nl.pdok.gml3.impl.gml3_1_1_2.convertors.GMLToLineConvertor}
* object.
*/
public GMLToSurfaceConvertor(GeometryFactory geometryFactory,
GMLToLineConvertor gmlToLineConvertor) {
this.geometryFactory = geometryFactory;
this.gmlToLineConvertor = gmlToLineConvertor;
}
/**
* <p>
* convertMultiSurface.
* </p>
*
* @param surfaces a {@link net.opengis.gml.v_3_1_1.MultiSurfaceType} object.
* @return a {@link org.locationtech.jts.geom.Geometry} object.
* @throws nl.pdok.gml3.exceptions.GeometryException if any.
*/
public Geometry convertMultiSurface(MultiSurfaceType surfaces) throws GeometryException {
List<Polygon> polygons = new ArrayList<Polygon>();
for (SurfacePropertyType surface : surfaces.getSurfaceMember()) {
JAXBElement<? extends AbstractSurfaceType> element = surface.getSurface();
Geometry result = convertElementContainingSurface(element);
addResultingPolygonsToList(result, polygons);
}
SurfaceArrayPropertyType array = surfaces.getSurfaceMembers();
if (array != null) {
List<JAXBElement<? extends AbstractSurfaceType>> arraySurfaceMembers = array.getSurface();
if (arraySurfaceMembers != null) {
for (JAXBElement<? extends AbstractSurfaceType> surfaceMember : arraySurfaceMembers) {
Geometry result = convertElementContainingSurface(surfaceMember);
addResultingPolygonsToList(result, polygons);
}
}
}
return convertPolygonListToMuliPolygonOrSinglePolygon(polygons);
}
private Geometry convertPolygonListToMuliPolygonOrSinglePolygon(List<Polygon> polygons)
throws GeometryException {
if (polygons.isEmpty()) {
throw new InvalidGeometryException(
GeometryValidationErrorType.MULTI_SURFACE_DID_NOT_CONTAIN_MEMBERS, null);
} else if (polygons.size() == 1) {
return polygons.get(0);
} else {
MultiPolygon multi = new MultiPolygon(polygons.toArray(new Polygon[] {}), geometryFactory);
return multi;
}
}
private Geometry convertElementContainingSurface(
JAXBElement<? extends AbstractSurfaceType> surface) throws GeometryException {
if (surface != null) {
AbstractSurfaceType abstractSurfaceType = surface.getValue();
if (abstractSurfaceType != null) {
return convertSurface(abstractSurfaceType);
}
}
return null;
}
private void addResultingPolygonsToList(Geometry geometry, List<Polygon> polygons) {
if (geometry != null) {
if (geometry instanceof MultiPolygon collection) {
for (int i = 0; i < collection.getNumGeometries(); i++) {
polygons.add((Polygon) collection.getGeometryN(i));
}
} else {
polygons.add((Polygon) geometry);
}
}
}
/**
* <p>
* convertSurface.
* </p>
*
* @param abstractSurface a {@link net.opengis.gml.v_3_1_1.AbstractSurfaceType} object.
* @return a {@link org.locationtech.jts.geom.Geometry} object.
* @throws nl.pdok.gml3.exceptions.GeometryException if any.
*/
public Geometry convertSurface(AbstractSurfaceType abstractSurface) throws GeometryException {
if (abstractSurface instanceof SurfaceType surface) {
List<Polygon> polygons = new ArrayList<>();
SurfacePatchArrayPropertyType patches = surface.getPatches().getValue();
// opmerking multipliciteit 2 of meer is afgevangen door xsd
for (int i = 0; i < patches.getSurfacePatch().size(); i++) {
AbstractSurfacePatchType abstractPatch = patches.getSurfacePatch().get(i).getValue();
if (abstractPatch instanceof PolygonPatchType polygonPatch) {
Polygon polygon = convertPolygonPatch(polygonPatch);
polygons.add(polygon);
} else {
throw new UnsupportedGeometrySpecificationException(
"Only polygon patch type is supported");
}
}
return convertPolygonListToMuliPolygonOrSinglePolygon(polygons);
} else if (abstractSurface instanceof PolygonType polygonType) {
if (polygonType.getExterior() == null) {
throw new InvalidGeometryException(GeometryValidationErrorType.POLYGON_HAS_NO_EXTERIOR,
null);
}
AbstractRingPropertyType abstractRing = polygonType.getExterior().getValue();
LinearRing shell = gmlToLineConvertor.translateAbstractRing(abstractRing);
LinearRing[] innerRings = new LinearRing[polygonType.getInterior().size()];
for (int i = 0; i < polygonType.getInterior().size(); i++) {
innerRings[i] =
gmlToLineConvertor.translateAbstractRing(polygonType.getInterior().get(i).getValue());
}
return geometryFactory.createPolygon(shell, innerRings);
} else {
throw new UnsupportedGeometrySpecificationException(
"Only Surface and Polygon are " + "supported as instances of _Surface");
}
}
/**
* <p>
* convertPolygonPatch.
* </p>
*
* @param polygonPatch a {@link net.opengis.gml.v_3_1_1.PolygonPatchType} object.
* @return a {@link org.locationtech.jts.geom.Polygon} object.
* @throws nl.pdok.gml3.exceptions.GeometryException if any.
*/
public Polygon convertPolygonPatch(PolygonPatchType polygonPatch) throws GeometryException {
if (polygonPatch.getExterior() == null) {
throw new InvalidGeometryException(GeometryValidationErrorType.POLYGON_HAS_NO_EXTERIOR, null);
}
AbstractRingPropertyType abstractRing = polygonPatch.getExterior().getValue();
LinearRing exteriorShell = gmlToLineConvertor.translateAbstractRing(abstractRing);
if (!Orientation.isCCW(exteriorShell.getCoordinates())) {
throw new InvalidGeometryException(GeometryValidationErrorType.OUTER_RING_IS_NOT_CCW, null);
}
LinearRing[] innerRings = new LinearRing[polygonPatch.getInterior().size()];
for (int i = 0; i < polygonPatch.getInterior().size(); i++) {
innerRings[i] =
gmlToLineConvertor.translateAbstractRing(polygonPatch.getInterior().get(i).getValue());
if (Orientation.isCCW(innerRings[i].getCoordinates())) {
throw new InvalidGeometryException(GeometryValidationErrorType.INNER_RING_IS_CCW, null);
}
}
return geometryFactory.createPolygon(exteriorShell, innerRings);
}
}
| PDOK/gml3-jts | src/main/java/nl/pdok/gml3/impl/gml3_1_1_2/convertors/GMLToSurfaceConvertor.java | 2,418 | // opmerking multipliciteit 2 of meer is afgevangen door xsd | line_comment | nl | package nl.pdok.gml3.impl.gml3_1_1_2.convertors;
import jakarta.xml.bind.JAXBElement;
import java.util.ArrayList;
import java.util.List;
import net.opengis.gml.v_3_1_1.*;
import nl.pdok.gml3.exceptions.GeometryException;
import nl.pdok.gml3.exceptions.GeometryValidationErrorType;
import nl.pdok.gml3.exceptions.InvalidGeometryException;
import nl.pdok.gml3.exceptions.UnsupportedGeometrySpecificationException;
import org.locationtech.jts.algorithm.Orientation;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.MultiPolygon;
import org.locationtech.jts.geom.Polygon;
/**
* <p>
* GMLToSurfaceConvertor class.
* </p>
*
* @author GinkeM
* @version $Id: $Id
*/
public class GMLToSurfaceConvertor {
private final GeometryFactory geometryFactory;
private final GMLToLineConvertor gmlToLineConvertor;
/**
* <p>
* Constructor for GMLToSurfaceConvertor.
* </p>
*
* @param geometryFactory a {@link org.locationtech.jts.geom.GeometryFactory} object.
* @param gmlToLineConvertor a {@link nl.pdok.gml3.impl.gml3_1_1_2.convertors.GMLToLineConvertor}
* object.
*/
public GMLToSurfaceConvertor(GeometryFactory geometryFactory,
GMLToLineConvertor gmlToLineConvertor) {
this.geometryFactory = geometryFactory;
this.gmlToLineConvertor = gmlToLineConvertor;
}
/**
* <p>
* convertMultiSurface.
* </p>
*
* @param surfaces a {@link net.opengis.gml.v_3_1_1.MultiSurfaceType} object.
* @return a {@link org.locationtech.jts.geom.Geometry} object.
* @throws nl.pdok.gml3.exceptions.GeometryException if any.
*/
public Geometry convertMultiSurface(MultiSurfaceType surfaces) throws GeometryException {
List<Polygon> polygons = new ArrayList<Polygon>();
for (SurfacePropertyType surface : surfaces.getSurfaceMember()) {
JAXBElement<? extends AbstractSurfaceType> element = surface.getSurface();
Geometry result = convertElementContainingSurface(element);
addResultingPolygonsToList(result, polygons);
}
SurfaceArrayPropertyType array = surfaces.getSurfaceMembers();
if (array != null) {
List<JAXBElement<? extends AbstractSurfaceType>> arraySurfaceMembers = array.getSurface();
if (arraySurfaceMembers != null) {
for (JAXBElement<? extends AbstractSurfaceType> surfaceMember : arraySurfaceMembers) {
Geometry result = convertElementContainingSurface(surfaceMember);
addResultingPolygonsToList(result, polygons);
}
}
}
return convertPolygonListToMuliPolygonOrSinglePolygon(polygons);
}
private Geometry convertPolygonListToMuliPolygonOrSinglePolygon(List<Polygon> polygons)
throws GeometryException {
if (polygons.isEmpty()) {
throw new InvalidGeometryException(
GeometryValidationErrorType.MULTI_SURFACE_DID_NOT_CONTAIN_MEMBERS, null);
} else if (polygons.size() == 1) {
return polygons.get(0);
} else {
MultiPolygon multi = new MultiPolygon(polygons.toArray(new Polygon[] {}), geometryFactory);
return multi;
}
}
private Geometry convertElementContainingSurface(
JAXBElement<? extends AbstractSurfaceType> surface) throws GeometryException {
if (surface != null) {
AbstractSurfaceType abstractSurfaceType = surface.getValue();
if (abstractSurfaceType != null) {
return convertSurface(abstractSurfaceType);
}
}
return null;
}
private void addResultingPolygonsToList(Geometry geometry, List<Polygon> polygons) {
if (geometry != null) {
if (geometry instanceof MultiPolygon collection) {
for (int i = 0; i < collection.getNumGeometries(); i++) {
polygons.add((Polygon) collection.getGeometryN(i));
}
} else {
polygons.add((Polygon) geometry);
}
}
}
/**
* <p>
* convertSurface.
* </p>
*
* @param abstractSurface a {@link net.opengis.gml.v_3_1_1.AbstractSurfaceType} object.
* @return a {@link org.locationtech.jts.geom.Geometry} object.
* @throws nl.pdok.gml3.exceptions.GeometryException if any.
*/
public Geometry convertSurface(AbstractSurfaceType abstractSurface) throws GeometryException {
if (abstractSurface instanceof SurfaceType surface) {
List<Polygon> polygons = new ArrayList<>();
SurfacePatchArrayPropertyType patches = surface.getPatches().getValue();
// opmerking multipliciteit<SUF>
for (int i = 0; i < patches.getSurfacePatch().size(); i++) {
AbstractSurfacePatchType abstractPatch = patches.getSurfacePatch().get(i).getValue();
if (abstractPatch instanceof PolygonPatchType polygonPatch) {
Polygon polygon = convertPolygonPatch(polygonPatch);
polygons.add(polygon);
} else {
throw new UnsupportedGeometrySpecificationException(
"Only polygon patch type is supported");
}
}
return convertPolygonListToMuliPolygonOrSinglePolygon(polygons);
} else if (abstractSurface instanceof PolygonType polygonType) {
if (polygonType.getExterior() == null) {
throw new InvalidGeometryException(GeometryValidationErrorType.POLYGON_HAS_NO_EXTERIOR,
null);
}
AbstractRingPropertyType abstractRing = polygonType.getExterior().getValue();
LinearRing shell = gmlToLineConvertor.translateAbstractRing(abstractRing);
LinearRing[] innerRings = new LinearRing[polygonType.getInterior().size()];
for (int i = 0; i < polygonType.getInterior().size(); i++) {
innerRings[i] =
gmlToLineConvertor.translateAbstractRing(polygonType.getInterior().get(i).getValue());
}
return geometryFactory.createPolygon(shell, innerRings);
} else {
throw new UnsupportedGeometrySpecificationException(
"Only Surface and Polygon are " + "supported as instances of _Surface");
}
}
/**
* <p>
* convertPolygonPatch.
* </p>
*
* @param polygonPatch a {@link net.opengis.gml.v_3_1_1.PolygonPatchType} object.
* @return a {@link org.locationtech.jts.geom.Polygon} object.
* @throws nl.pdok.gml3.exceptions.GeometryException if any.
*/
public Polygon convertPolygonPatch(PolygonPatchType polygonPatch) throws GeometryException {
if (polygonPatch.getExterior() == null) {
throw new InvalidGeometryException(GeometryValidationErrorType.POLYGON_HAS_NO_EXTERIOR, null);
}
AbstractRingPropertyType abstractRing = polygonPatch.getExterior().getValue();
LinearRing exteriorShell = gmlToLineConvertor.translateAbstractRing(abstractRing);
if (!Orientation.isCCW(exteriorShell.getCoordinates())) {
throw new InvalidGeometryException(GeometryValidationErrorType.OUTER_RING_IS_NOT_CCW, null);
}
LinearRing[] innerRings = new LinearRing[polygonPatch.getInterior().size()];
for (int i = 0; i < polygonPatch.getInterior().size(); i++) {
innerRings[i] =
gmlToLineConvertor.translateAbstractRing(polygonPatch.getInterior().get(i).getValue());
if (Orientation.isCCW(innerRings[i].getCoordinates())) {
throw new InvalidGeometryException(GeometryValidationErrorType.INNER_RING_IS_CCW, null);
}
}
return geometryFactory.createPolygon(exteriorShell, innerRings);
}
}
| false | 1,721 | 18 | 1,883 | 21 | 2,028 | 17 | 1,883 | 21 | 2,372 | 19 | false | false | false | false | false | true |
650 | 64553_1 | package Iterator;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Halil Teker on 6/24/2017.
*/
public class HogeschoolRotterdam implements Iterable {
private List<Student> studenten;
public HogeschoolRotterdam() {
// TODO Maak de studenten list, en voeg enkele studenten toe
studenten = new ArrayList<Student>();
studenten.add(new Student("Jan", "Janssen", "Rotterdam"));
studenten.add(new Student("Chukwuemeka", "Aziz", "Rotterdam"));
studenten.add(new Student("Ravindra", "Dushyant", "Rotterdam"));
}
public List<Student> getStudenten() {
return this.studenten;
}
@Override
public Iterator iterator() {
return new HogeschoolRotterdamIterator(studenten);
}
}
| HTeker/Dessign-Patterns-Implementation | Opdrachten/src/Iterator/HogeschoolRotterdam.java | 243 | // TODO Maak de studenten list, en voeg enkele studenten toe | line_comment | nl | package Iterator;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Halil Teker on 6/24/2017.
*/
public class HogeschoolRotterdam implements Iterable {
private List<Student> studenten;
public HogeschoolRotterdam() {
// TODO Maak<SUF>
studenten = new ArrayList<Student>();
studenten.add(new Student("Jan", "Janssen", "Rotterdam"));
studenten.add(new Student("Chukwuemeka", "Aziz", "Rotterdam"));
studenten.add(new Student("Ravindra", "Dushyant", "Rotterdam"));
}
public List<Student> getStudenten() {
return this.studenten;
}
@Override
public Iterator iterator() {
return new HogeschoolRotterdamIterator(studenten);
}
}
| false | 195 | 18 | 228 | 18 | 221 | 13 | 228 | 18 | 245 | 17 | false | false | false | false | false | true |
1,102 | 26153_1 | package nl.hu.dp;
import org.hibernate.annotations.Cascade;
import javax.persistence.*;
import java.sql.Date;
import java.util.*;
@Entity
@Table(name = "ov_chipkaart")
public class OVChipkaart {
@Id
@Column(name = "kaart_nummer", nullable = false)
private int id;
@Column(name = "geldig_tot")
private Date geldigTot;
private Integer klasse;
private Integer saldo;
@ManyToOne
@JoinColumn(name = "reiziger_id")
private Reiziger reiziger_id;
//https://javaee.github.io/javaee-spec/javadocs/javax/persistence/ManyToMany.html
//ovchipkaart is de owning side hier zitten joins om product en ovchipkaart samen te voegen
//deze joins zorgen dus voor de relationship die we nodig hebben
//zie @ManyToMany van klasse Product
@ManyToMany
@JoinTable(name = "ov_chipkaart_product", joinColumns = @JoinColumn(name = "kaart_nummer")
,inverseJoinColumns = @JoinColumn(name = "product_nummer"))
private List<Product> producten = new ArrayList<>();
public OVChipkaart() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public OVChipkaart(int id, Date geldigTot, Integer klasse, Integer saldo) {
this.id = id;
this.geldigTot = geldigTot;
this.klasse = klasse;
this.saldo = saldo;
}
public int getKaartId() {
return id;
}
public void setKaartId(int id) {
this.id=id;
}
public Reiziger getReiziger() {
return reiziger_id;
}
public void setReiziger(Reiziger reiziger) {
this.reiziger_id = reiziger;
}
public Date getGeldigTot() {
return geldigTot;
}
public void setGeldigTot(Date geldigTot) {
this.geldigTot = geldigTot;
}
public Integer getKlasse() {
return klasse;
}
public void setKlasse(Integer klasse) {
this.klasse = klasse;
}
public Integer getSaldo() {
return saldo;
}
public void setSaldo(Integer saldo) {
this.saldo = saldo;
}
public void voegProductToe(Product product) {
producten.add(product);
}
public void verwijderProduct(Product product) {
producten.remove(product);
}
public List<Product> getProducten() {
return producten;
}
public String toString() {
String product = "";
for (Product p : producten) {
product +=
"nummer #" + p.getProductNummer() +
" naam: " + p.getNaam() + " beschrijving: " + p.getBeschrijving() + " ";
}
if (reiziger_id != null && producten == null) {
return "{kaartnummer: #" + id + " geldigTot: " + geldigTot + " klasse: " + klasse + " saldo: " + saldo +
" {ReizigerID: " + "#" + reiziger_id.getId() + "}";
} else if (producten != null && reiziger_id != null) {
return "{kaartnummer: #" + id + " geldigTot: " + geldigTot + " klasse: " + klasse + " saldo: " + saldo +
"\n Producten{" + product + "}" + " Reiziger{"+reiziger_id.getNaam()+"}";
}
return "{kaartnummer: #" + id + " geldigTot: " + geldigTot + " klasse: " + klasse + " saldo: " + saldo + "}";
}
}
| Mertcan417/Data-Persistency_ovchipkaart-hibernate | src/main/java/nl/hu/dp/OVChipkaart.java | 1,106 | //deze joins zorgen dus voor de relationship die we nodig hebben | line_comment | nl | package nl.hu.dp;
import org.hibernate.annotations.Cascade;
import javax.persistence.*;
import java.sql.Date;
import java.util.*;
@Entity
@Table(name = "ov_chipkaart")
public class OVChipkaart {
@Id
@Column(name = "kaart_nummer", nullable = false)
private int id;
@Column(name = "geldig_tot")
private Date geldigTot;
private Integer klasse;
private Integer saldo;
@ManyToOne
@JoinColumn(name = "reiziger_id")
private Reiziger reiziger_id;
//https://javaee.github.io/javaee-spec/javadocs/javax/persistence/ManyToMany.html
//ovchipkaart is de owning side hier zitten joins om product en ovchipkaart samen te voegen
//deze joins<SUF>
//zie @ManyToMany van klasse Product
@ManyToMany
@JoinTable(name = "ov_chipkaart_product", joinColumns = @JoinColumn(name = "kaart_nummer")
,inverseJoinColumns = @JoinColumn(name = "product_nummer"))
private List<Product> producten = new ArrayList<>();
public OVChipkaart() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public OVChipkaart(int id, Date geldigTot, Integer klasse, Integer saldo) {
this.id = id;
this.geldigTot = geldigTot;
this.klasse = klasse;
this.saldo = saldo;
}
public int getKaartId() {
return id;
}
public void setKaartId(int id) {
this.id=id;
}
public Reiziger getReiziger() {
return reiziger_id;
}
public void setReiziger(Reiziger reiziger) {
this.reiziger_id = reiziger;
}
public Date getGeldigTot() {
return geldigTot;
}
public void setGeldigTot(Date geldigTot) {
this.geldigTot = geldigTot;
}
public Integer getKlasse() {
return klasse;
}
public void setKlasse(Integer klasse) {
this.klasse = klasse;
}
public Integer getSaldo() {
return saldo;
}
public void setSaldo(Integer saldo) {
this.saldo = saldo;
}
public void voegProductToe(Product product) {
producten.add(product);
}
public void verwijderProduct(Product product) {
producten.remove(product);
}
public List<Product> getProducten() {
return producten;
}
public String toString() {
String product = "";
for (Product p : producten) {
product +=
"nummer #" + p.getProductNummer() +
" naam: " + p.getNaam() + " beschrijving: " + p.getBeschrijving() + " ";
}
if (reiziger_id != null && producten == null) {
return "{kaartnummer: #" + id + " geldigTot: " + geldigTot + " klasse: " + klasse + " saldo: " + saldo +
" {ReizigerID: " + "#" + reiziger_id.getId() + "}";
} else if (producten != null && reiziger_id != null) {
return "{kaartnummer: #" + id + " geldigTot: " + geldigTot + " klasse: " + klasse + " saldo: " + saldo +
"\n Producten{" + product + "}" + " Reiziger{"+reiziger_id.getNaam()+"}";
}
return "{kaartnummer: #" + id + " geldigTot: " + geldigTot + " klasse: " + klasse + " saldo: " + saldo + "}";
}
}
| false | 864 | 15 | 973 | 19 | 939 | 13 | 973 | 19 | 1,117 | 15 | false | false | false | false | false | true |
3,361 | 16720_22 | package model;
import view.*;
import java.awt.Color;
import java.util.List;
import java.util.Random;
/**
* A class representing shared characteristics of animals.
*
* @author David J. Barnes and Michael Kölling
* @version 2011.07.31
*/
public abstract class Animal implements Actor
{
// Whether the animal is alive or not.
protected boolean alive = true;
// The animal's field.
private Field field;
// The animal's position in the field.
private Location location;
// The animal's age
private int age;
// A shared random number generator to control breeding.
private static final Random rand = Randomizer.getRandom();
protected Color color;
protected Color OFFICIAL_COLOR;
/**
* Create a new animal at location in field.
*
* @param field The field currently occupied.
* @param location The location within the field.
*/
public Animal(Field field, Location location)
{
alive = true;
this.field = field;
setLocation(location);
}
/**
* Make this animal act - that is: make it do
* whatever it wants/needs to do.
* @param newAnimals A list to receive newly born animals.
*/
abstract public void act(List<Actor> newActors);
/**
* Returns the current color of the animal.
* @return The animals current color
*/
public Color getColor() {
return color;
}
/**
* Returns the official color linked to the kind of animal.
* @return The animals official color
*/
public Color getOfficialColor() {
return OFFICIAL_COLOR;
}
/**
* Indicate that the animal is no longer alive.
* It is removed from the field.
*/
protected void setDead()
{
alive = false;
if(location != null) {
field.clear(location);
location = null;
field = null;
}
}
/**
* Return the animal's location.
* @return The animal's location.
*/
protected Location getLocation()
{
return location;
}
/**
* Place the animal at the new location in the given field.
* @param newLocation The animal's new location.
*/
protected void setLocation(Location newLocation)
{
if(location != null) {
field.clear(location);
}
location = newLocation;
field.place(this, newLocation);
}
/**
* Return the animal's field.
* @return The animal's field.
*/
protected Field getField()
{
return field;
}
/**
* Increase the age. This could result in the fox's death.
*/
protected void incrementAge()
{
age++;
if(age > getMaxAge()) {
setDead();
}
}
/**
* Generate a number representing the number of births,
* if it can breed.
* @return The number of births (may be zero).
*/
protected int breed()
{
int births = 0;
if(canBreed() && rand.nextDouble() <= getBreedingProbability()) {
births = rand.nextInt(getMaxLitterSize()) + 1;
}
return births;
}
/**
* Een dier kan zich voortplanten als het de
* voortplantingsleeftijd heeft bereikt.
* @return true als het dier zich kan voortplanten
*/
public boolean canBreed()
{
return age >= getBreedingAge();
}
/**
* Check whether or not this fox is to give birth at this step.
* New births will be made into free adjacent locations.
* @param newFoxes A list to return newly born foxes.
*/
protected void giveBirth(List<Actor> newAnimals)
{
// New animals are born into adjacent locations.
// Get a list of adjacent free locations.
Animal animal = this;
Animal nieuw = null;
Field field = getField();
List<Location> free = field.getFreeAdjacentLocations(getLocation());
int births = breed();
for(int b = 0; b < births && free.size() > 0; b++) {
Location loc = free.remove(0);
if (animal instanceof Rabbit) {
nieuw = new Rabbit(false, field, loc);
}
else if (animal instanceof Fox) {
nieuw = new Fox(false, field, loc);
}
else if (animal instanceof Bear) {
nieuw = new Bear(false, field, loc);
}
newAnimals.add(nieuw);
}
}
/**
* Retourneer de voortplantingskans van dit dier.
*/
abstract protected double getBreedingProbability();
/**
* Returns the maximum amount of offspring an animal can have.
*/
abstract protected int getMaxLitterSize();
/**
* Retourneer de voortplantingsleeftijd van dit dier.
* @return De voortplantingsleeftijd van dit dier.
*/
abstract protected int getBreedingAge();
/**
* Retourneer de maximum leeftijd van dit dier.
* @return De maximum leeftijd van dit dier.
*/
abstract protected int getMaxAge();
/**
* Return the animal's age.
* @return The animal's age.
*/
public int getAge() {
return age;
}
/**
* Set the animal's age.
* @param The animal's age.
*/
public void setAge(int age) {
this.age = age;
}
/**
* Returns if animal is alive. False by default;
* @return false.
*/
public boolean isAlive() {
return false;
}
}
| kevinstier/VossenEnKonijnen | Mark/src/model/Animal.java | 1,591 | /**
* Retourneer de voortplantingsleeftijd van dit dier.
* @return De voortplantingsleeftijd van dit dier.
*/ | block_comment | nl | package model;
import view.*;
import java.awt.Color;
import java.util.List;
import java.util.Random;
/**
* A class representing shared characteristics of animals.
*
* @author David J. Barnes and Michael Kölling
* @version 2011.07.31
*/
public abstract class Animal implements Actor
{
// Whether the animal is alive or not.
protected boolean alive = true;
// The animal's field.
private Field field;
// The animal's position in the field.
private Location location;
// The animal's age
private int age;
// A shared random number generator to control breeding.
private static final Random rand = Randomizer.getRandom();
protected Color color;
protected Color OFFICIAL_COLOR;
/**
* Create a new animal at location in field.
*
* @param field The field currently occupied.
* @param location The location within the field.
*/
public Animal(Field field, Location location)
{
alive = true;
this.field = field;
setLocation(location);
}
/**
* Make this animal act - that is: make it do
* whatever it wants/needs to do.
* @param newAnimals A list to receive newly born animals.
*/
abstract public void act(List<Actor> newActors);
/**
* Returns the current color of the animal.
* @return The animals current color
*/
public Color getColor() {
return color;
}
/**
* Returns the official color linked to the kind of animal.
* @return The animals official color
*/
public Color getOfficialColor() {
return OFFICIAL_COLOR;
}
/**
* Indicate that the animal is no longer alive.
* It is removed from the field.
*/
protected void setDead()
{
alive = false;
if(location != null) {
field.clear(location);
location = null;
field = null;
}
}
/**
* Return the animal's location.
* @return The animal's location.
*/
protected Location getLocation()
{
return location;
}
/**
* Place the animal at the new location in the given field.
* @param newLocation The animal's new location.
*/
protected void setLocation(Location newLocation)
{
if(location != null) {
field.clear(location);
}
location = newLocation;
field.place(this, newLocation);
}
/**
* Return the animal's field.
* @return The animal's field.
*/
protected Field getField()
{
return field;
}
/**
* Increase the age. This could result in the fox's death.
*/
protected void incrementAge()
{
age++;
if(age > getMaxAge()) {
setDead();
}
}
/**
* Generate a number representing the number of births,
* if it can breed.
* @return The number of births (may be zero).
*/
protected int breed()
{
int births = 0;
if(canBreed() && rand.nextDouble() <= getBreedingProbability()) {
births = rand.nextInt(getMaxLitterSize()) + 1;
}
return births;
}
/**
* Een dier kan zich voortplanten als het de
* voortplantingsleeftijd heeft bereikt.
* @return true als het dier zich kan voortplanten
*/
public boolean canBreed()
{
return age >= getBreedingAge();
}
/**
* Check whether or not this fox is to give birth at this step.
* New births will be made into free adjacent locations.
* @param newFoxes A list to return newly born foxes.
*/
protected void giveBirth(List<Actor> newAnimals)
{
// New animals are born into adjacent locations.
// Get a list of adjacent free locations.
Animal animal = this;
Animal nieuw = null;
Field field = getField();
List<Location> free = field.getFreeAdjacentLocations(getLocation());
int births = breed();
for(int b = 0; b < births && free.size() > 0; b++) {
Location loc = free.remove(0);
if (animal instanceof Rabbit) {
nieuw = new Rabbit(false, field, loc);
}
else if (animal instanceof Fox) {
nieuw = new Fox(false, field, loc);
}
else if (animal instanceof Bear) {
nieuw = new Bear(false, field, loc);
}
newAnimals.add(nieuw);
}
}
/**
* Retourneer de voortplantingskans van dit dier.
*/
abstract protected double getBreedingProbability();
/**
* Returns the maximum amount of offspring an animal can have.
*/
abstract protected int getMaxLitterSize();
/**
* Retourneer de voortplantingsleeftijd<SUF>*/
abstract protected int getBreedingAge();
/**
* Retourneer de maximum leeftijd van dit dier.
* @return De maximum leeftijd van dit dier.
*/
abstract protected int getMaxAge();
/**
* Return the animal's age.
* @return The animal's age.
*/
public int getAge() {
return age;
}
/**
* Set the animal's age.
* @param The animal's age.
*/
public void setAge(int age) {
this.age = age;
}
/**
* Returns if animal is alive. False by default;
* @return false.
*/
public boolean isAlive() {
return false;
}
}
| false | 1,270 | 39 | 1,372 | 41 | 1,491 | 36 | 1,374 | 41 | 1,613 | 42 | false | false | false | false | false | true |
1,227 | 129795_3 | import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class StartLetter {
// Mapper -> classes tussen <> zijn de classen van de (input key, input_value, output_key, output_value)
public static class WCMapper extends Mapper<Object, Text, Text, IntWritable>{
// hier komt de mapfunctie in
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
// map functie leest lijn per lijn
// lijn splitsen in woorden
// hello world
StringTokenizer itr = new StringTokenizer(value.toString());
// itr = [hello, world]
while(itr.hasMoreTokens()){
// hello -> (h, 1)
// worlds -> (w, 1)
String woord = itr.nextToken();
woord = woord.toLowerCase();
char firstLetter = woord.charAt(0);
if(Character.isLetter(firstLetter)){
Text word = new Text();
word.set(Character.toString(firstLetter));
context.write(word, new IntWritable(1));
}
}
}
}
// Reducer -> classes tussen <> zijn de classen van de (input key, input_value, output_key, output_value)
public static class WCReducer extends Reducer<Text, IntWritable, Text, IntWritable>{
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
// key = hello, values = [1, 1, 1, 1]
int sum = 0;
for (IntWritable val: values) {
sum += val.get();
}
System.out.println(sum);
context.write(key, new IntWritable(sum));
}
}
// configure the MapReduce program
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "start letter java");
job.setJarByClass(WordCount.class);
// configure mapper
job.setMapperClass(WCMapper.class);
// configure combiner (soort van reducer die draait op mapping node voor performantie)
job.setCombinerClass(WCReducer.class);
// configure reducer
job.setReducerClass(WCReducer.class);
// set output key-value classes
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
// set input file (first argument passed to the program)
FileInputFormat.addInputPath(job, new Path(args[0]));
// set output file (second argument passed to the program)
FileOutputFormat.setOutputPath(job, new Path(args[1]));
// In this case, we wait for completion to get the output/logs and not stop the program to early.
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
| OdiseeBigData2223/Leerstof | Week 2/StartLetter.java | 939 | // lijn splitsen in woorden | line_comment | nl | import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class StartLetter {
// Mapper -> classes tussen <> zijn de classen van de (input key, input_value, output_key, output_value)
public static class WCMapper extends Mapper<Object, Text, Text, IntWritable>{
// hier komt de mapfunctie in
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
// map functie leest lijn per lijn
// lijn splitsen<SUF>
// hello world
StringTokenizer itr = new StringTokenizer(value.toString());
// itr = [hello, world]
while(itr.hasMoreTokens()){
// hello -> (h, 1)
// worlds -> (w, 1)
String woord = itr.nextToken();
woord = woord.toLowerCase();
char firstLetter = woord.charAt(0);
if(Character.isLetter(firstLetter)){
Text word = new Text();
word.set(Character.toString(firstLetter));
context.write(word, new IntWritable(1));
}
}
}
}
// Reducer -> classes tussen <> zijn de classen van de (input key, input_value, output_key, output_value)
public static class WCReducer extends Reducer<Text, IntWritable, Text, IntWritable>{
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
// key = hello, values = [1, 1, 1, 1]
int sum = 0;
for (IntWritable val: values) {
sum += val.get();
}
System.out.println(sum);
context.write(key, new IntWritable(sum));
}
}
// configure the MapReduce program
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "start letter java");
job.setJarByClass(WordCount.class);
// configure mapper
job.setMapperClass(WCMapper.class);
// configure combiner (soort van reducer die draait op mapping node voor performantie)
job.setCombinerClass(WCReducer.class);
// configure reducer
job.setReducerClass(WCReducer.class);
// set output key-value classes
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
// set input file (first argument passed to the program)
FileInputFormat.addInputPath(job, new Path(args[0]));
// set output file (second argument passed to the program)
FileOutputFormat.setOutputPath(job, new Path(args[1]));
// In this case, we wait for completion to get the output/logs and not stop the program to early.
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
| false | 681 | 8 | 802 | 8 | 837 | 6 | 802 | 8 | 936 | 9 | false | false | false | false | false | true |
748 | 100666_1 | import org.apache.commons.math3.complex.Complex;_x000D_
import org.apache.commons.math3.transform.DftNormalization;_x000D_
import org.apache.commons.math3.transform.FastFourierTransformer;_x000D_
import org.apache.commons.math3.transform.TransformType;_x000D_
_x000D_
import javax.sound.sampled.AudioInputStream;_x000D_
import javax.sound.sampled.AudioSystem;_x000D_
import java.io.*;_x000D_
import javax.sound.sampled.UnsupportedAudioFileException;_x000D_
_x000D_
public class AudioProcessor {_x000D_
public static void main(String[] args) {_x000D_
File audioFile = new File("RecordAudio.wav");_x000D_
_x000D_
try {_x000D_
_x000D_
// Open het audiobestand_x000D_
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);_x000D_
_x000D_
// Bepaal een buffergrootte_x000D_
int bufferSize = 4096;_x000D_
byte[] audioData = new byte[bufferSize];_x000D_
int bytesRead;_x000D_
_x000D_
// Lees de audiogegevens in de array_x000D_
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();_x000D_
while ((bytesRead = audioStream.read(audioData, 0, bufferSize)) != -1) {_x000D_
byteArrayOutputStream.write(audioData, 0, bytesRead);_x000D_
}_x000D_
_x000D_
byte[] audioDataArray = byteArrayOutputStream.toByteArray();_x000D_
_x000D_
System.out.println("Audiogegevens gelezen: " + audioDataArray.length + " bytes");_x000D_
_x000D_
// Voer Fourier-transformatie uit met Apache Commons Math_x000D_
double[] audioSamples = new double[audioDataArray.length / 2]; // 2 wegen de stero geluid_x000D_
_x000D_
for (int i = 0; i < audioSamples.length; i++) {_x000D_
audioSamples[i] = (double)((audioDataArray[i * 2] & 0xFF) | (audioDataArray[i * 2 + 1] << 8)) / 32768.0;_x000D_
}_x000D_
_x000D_
// Calculate the next power of 2 for the length of audioSamples_x000D_
int powerOf2Length = 1;_x000D_
while (powerOf2Length < audioSamples.length) {_x000D_
powerOf2Length *= 2;_x000D_
}_x000D_
_x000D_
// Pad the audio data with zeros to the next power of 2_x000D_
double[] paddedAudioSamples = new double[powerOf2Length];_x000D_
System.arraycopy(audioSamples, 0, paddedAudioSamples, 0, audioSamples.length);_x000D_
_x000D_
// Voer de Fourier-transformatie uit op het opgevulde audioSamples_x000D_
FastFourierTransformer transformer = new FastFourierTransformer(DftNormalization.STANDARD);_x000D_
Complex[] complexSamples = transformer.transform(paddedAudioSamples, TransformType.FORWARD);_x000D_
int[] positiveIntSamples = new int[complexSamples.length];_x000D_
for (int i = 0; i < complexSamples.length; i++) {_x000D_
complexSamples[i] = Complex.valueOf(complexSamples[i].abs()); // Ensure the value is positive_x000D_
}_x000D_
System.out.println(positiveIntSamples.length);_x000D_
_x000D_
// Save the complexSamples to a text file_x000D_
try (BufferedWriter writer = new BufferedWriter(new FileWriter("complexSamples.txt"))) {_x000D_
for (Complex complex : complexSamples) {_x000D_
writer.write(complex.getReal() + " " + complex.getImaginary() + "\n");_x000D_
}_x000D_
} catch (IOException e) {_x000D_
e.printStackTrace();_x000D_
}_x000D_
_x000D_
_x000D_
// Nu heb je de frequentiegegevens in de complexSamples-array en kun je verdere verwerking uitvoeren._x000D_
_x000D_
// Sluit het audiobestand_x000D_
audioStream.close();_x000D_
} catch (UnsupportedAudioFileException | IOException e) {_x000D_
e.printStackTrace();_x000D_
}_x000D_
_x000D_
_x000D_
}_x000D_
}_x000D_
| IhabSaf/AudioAnalyzer | AudioProcessor.java | 996 | // Bepaal een buffergrootte_x000D_ | line_comment | nl | import org.apache.commons.math3.complex.Complex;_x000D_
import org.apache.commons.math3.transform.DftNormalization;_x000D_
import org.apache.commons.math3.transform.FastFourierTransformer;_x000D_
import org.apache.commons.math3.transform.TransformType;_x000D_
_x000D_
import javax.sound.sampled.AudioInputStream;_x000D_
import javax.sound.sampled.AudioSystem;_x000D_
import java.io.*;_x000D_
import javax.sound.sampled.UnsupportedAudioFileException;_x000D_
_x000D_
public class AudioProcessor {_x000D_
public static void main(String[] args) {_x000D_
File audioFile = new File("RecordAudio.wav");_x000D_
_x000D_
try {_x000D_
_x000D_
// Open het audiobestand_x000D_
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);_x000D_
_x000D_
// Bepaal een<SUF>
int bufferSize = 4096;_x000D_
byte[] audioData = new byte[bufferSize];_x000D_
int bytesRead;_x000D_
_x000D_
// Lees de audiogegevens in de array_x000D_
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();_x000D_
while ((bytesRead = audioStream.read(audioData, 0, bufferSize)) != -1) {_x000D_
byteArrayOutputStream.write(audioData, 0, bytesRead);_x000D_
}_x000D_
_x000D_
byte[] audioDataArray = byteArrayOutputStream.toByteArray();_x000D_
_x000D_
System.out.println("Audiogegevens gelezen: " + audioDataArray.length + " bytes");_x000D_
_x000D_
// Voer Fourier-transformatie uit met Apache Commons Math_x000D_
double[] audioSamples = new double[audioDataArray.length / 2]; // 2 wegen de stero geluid_x000D_
_x000D_
for (int i = 0; i < audioSamples.length; i++) {_x000D_
audioSamples[i] = (double)((audioDataArray[i * 2] & 0xFF) | (audioDataArray[i * 2 + 1] << 8)) / 32768.0;_x000D_
}_x000D_
_x000D_
// Calculate the next power of 2 for the length of audioSamples_x000D_
int powerOf2Length = 1;_x000D_
while (powerOf2Length < audioSamples.length) {_x000D_
powerOf2Length *= 2;_x000D_
}_x000D_
_x000D_
// Pad the audio data with zeros to the next power of 2_x000D_
double[] paddedAudioSamples = new double[powerOf2Length];_x000D_
System.arraycopy(audioSamples, 0, paddedAudioSamples, 0, audioSamples.length);_x000D_
_x000D_
// Voer de Fourier-transformatie uit op het opgevulde audioSamples_x000D_
FastFourierTransformer transformer = new FastFourierTransformer(DftNormalization.STANDARD);_x000D_
Complex[] complexSamples = transformer.transform(paddedAudioSamples, TransformType.FORWARD);_x000D_
int[] positiveIntSamples = new int[complexSamples.length];_x000D_
for (int i = 0; i < complexSamples.length; i++) {_x000D_
complexSamples[i] = Complex.valueOf(complexSamples[i].abs()); // Ensure the value is positive_x000D_
}_x000D_
System.out.println(positiveIntSamples.length);_x000D_
_x000D_
// Save the complexSamples to a text file_x000D_
try (BufferedWriter writer = new BufferedWriter(new FileWriter("complexSamples.txt"))) {_x000D_
for (Complex complex : complexSamples) {_x000D_
writer.write(complex.getReal() + " " + complex.getImaginary() + "\n");_x000D_
}_x000D_
} catch (IOException e) {_x000D_
e.printStackTrace();_x000D_
}_x000D_
_x000D_
_x000D_
// Nu heb je de frequentiegegevens in de complexSamples-array en kun je verdere verwerking uitvoeren._x000D_
_x000D_
// Sluit het audiobestand_x000D_
audioStream.close();_x000D_
} catch (UnsupportedAudioFileException | IOException e) {_x000D_
e.printStackTrace();_x000D_
}_x000D_
_x000D_
_x000D_
}_x000D_
}_x000D_
| false | 1,247 | 15 | 1,355 | 17 | 1,388 | 16 | 1,355 | 17 | 1,512 | 16 | false | false | false | false | false | true |
342 | 22393_3 | package steps.gui.openforms;
import com.microsoft.playwright.Locator;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.options.WaitForSelectorState;
import pages.openforms.GeneriekeOpenformsPage;
import pages.openforms.OpenFormsPage;
import steps.gui.GeneriekeSteps;
import steps.gui.login.DigidLoginSteps;
import users.User;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
public class OpenFormsSteps extends GeneriekeSteps {
public final OpenFormsPage openFormsPage;
protected final GeneriekeOpenformsPage genericPage;
protected final DigidLoginSteps digidLoginSteps;
public OpenFormsSteps(Page page) {
super(page);
openFormsPage = new OpenFormsPage(page);
genericPage = new GeneriekeOpenformsPage(page);
digidLoginSteps = new DigidLoginSteps(page);
}
public void navigate(String url){
page.navigate(url);
}
/**
* Login via Digid
*
* @param user User
*/
public void login_via_digid(User user) {
openFormsPage.buttonAccepteerCookies.click();
openFormsPage.inloggenDigidButton.click();
digidLoginSteps.login_via_digid(user);
}
/**
* Valideer dat de stap als actief staat
*
* @param stapNaam die actief moet zijn
*/
public void valideer_actieve_stap(String stapNaam) {
assertThat(openFormsPage.linkActiveStep).hasText(stapNaam);
}
/**
* Valideer dat een bepaalde h1 header op het scherm staat
* @param tekst
*/
public void controleer_h1_header_is(String tekst) {
assertThat(openFormsPage.textlabelHeaderH1).hasText(tekst);
}
/**
* Valideer dat een bepaalde h2 header op het scherm staat
* @param tekst
*/
public void controleer_h2_header_is(String tekst) {
assertThat(openFormsPage.textlabelHeaderH2).hasText(tekst);
}
/**
* Valideer dat er een bepaalde foutmelding op het scherm staat
*
* @param tekst
*/
public void controleer_foutmelding_is_zichtbaar_met(String tekst) {
assertThat(get_alert().getByText(tekst)).isVisible();
}
/**
* Haal de Locator op van een tekst op het scherm
*
* @param tekst
* @return Locator waarop een actie uitgevoerd kan worden
*/
public Locator get_tekst(String tekst){
return page.getByText(tekst);
}
/**
* Haal de Locator van een inputveld op
*
* @param tekst
* @return Locator waarop een actie uitgevoerd kan worden
*/
public Locator get_input_veld(String tekst){
return genericPage.getInputField(tekst, false);
}
/**
* Haal de Locator van een alert op
*
* @return Locator waarop een actie uitgevoerd kan worden
*/
public Locator get_alert(){
return page.locator("//div[contains(@role,'alert')]//div");
}
/**
* Valideer dat er geen foutmelding zichtbaar is op het scherm
*
*/
public void geen_foutmelding_zichtbaar() {
assertThat(page.locator("//div[@class='form-text error']")).isHidden();
}
/**
* Valideer dat een bepaald veld de goede waarde heeft
*
* @param inputName
* @param prefillWaarde
*/
public void tekstveld_bevat_prefill_gegevens
(String inputName, String prefillWaarde) {
assertThat(
page.locator(
String.format("//input[@name='%s' and contains(@value,\"%s\")]",
inputName,
prefillWaarde)))
.isVisible();
}
/**
* Valideer dat er een bepaalde foutmelding getoond wordt op het scherm
*
* @param locator
* @param verwachteTekst
*/
public void validatie_toon_foutmelding(Locator locator, String verwachteTekst) {
locator.blur();
locator.waitFor(new Locator.WaitForOptions().setTimeout(1000));
page.keyboard().press("Enter");
page.keyboard().press("Tab");
if (verwachteTekst == null) {
geen_foutmelding_zichtbaar();
} else {
controleer_foutmelding_is_zichtbaar_met(verwachteTekst);
}
}
/**
* Klik op de volgende knop
*
*/
public void klik_volgende_knop() {
wacht_op_volgende_knop_response();
klik_knop("Volgende");
}
/**
* Wacht totdat de validatie in de backend is uitgevoerd
*
*/
public void wacht_op_volgende_knop_response(){
try{
page.setDefaultTimeout(2000);
page.waitForResponse(res -> res.url().contains("/_check_logic"), () -> {});
} catch (Exception ex) {
//ignore
} finally {
page.setDefaultTimeout(30000);
}
}
/**
* Haal de Locator op van de checkbox
*
* @param tekst
* @return Locator waarop een actie uitgevoerd kan worden
*/
public Locator get_checkbox(String tekst){
return genericPage.getCheckbox(tekst);
}
/**
* Selecteer een optie bij een radiobox of checkboxgroup
*
* @param tekst van de radio- of checkboxgroep
* @param optie die geselecteerd moet worden
*/
public void selecteer_optie(String tekst, String optie) {
genericPage.selectOption(tekst, optie);
}
/**
*
* Note that this only works on input and textarea fields
*
* @param veld - text of the field you want to enter the text for
* @param text - text you want to enter into the field
*/
public void vul_tekst_in(String veld, String text) {
genericPage.getInputField(veld, false).waitFor(new Locator.WaitForOptions().setTimeout(500));
genericPage.fillTextInputField(veld, text, false);
}
public void selecteer_login_met_digid() {
openFormsPage.inloggenDigidButton.click();
}
public void is_ingelogd() {
openFormsPage.headerFirstFormStep.waitFor();
}
public void waitUntilHeaderPageVisible() {
this.openFormsPage.headerFirstFormStep.waitFor();
}
public void aanvraag_zonder_DigiD_login(){
openFormsPage.aanvraagZonderDigidButton.click();
}
}
| CommonGround-Testing/zgw-playwright-base | src/main/java/steps/gui/openforms/OpenFormsSteps.java | 1,976 | /**
* Valideer dat een bepaalde h2 header op het scherm staat
* @param tekst
*/ | block_comment | nl | package steps.gui.openforms;
import com.microsoft.playwright.Locator;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.options.WaitForSelectorState;
import pages.openforms.GeneriekeOpenformsPage;
import pages.openforms.OpenFormsPage;
import steps.gui.GeneriekeSteps;
import steps.gui.login.DigidLoginSteps;
import users.User;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
public class OpenFormsSteps extends GeneriekeSteps {
public final OpenFormsPage openFormsPage;
protected final GeneriekeOpenformsPage genericPage;
protected final DigidLoginSteps digidLoginSteps;
public OpenFormsSteps(Page page) {
super(page);
openFormsPage = new OpenFormsPage(page);
genericPage = new GeneriekeOpenformsPage(page);
digidLoginSteps = new DigidLoginSteps(page);
}
public void navigate(String url){
page.navigate(url);
}
/**
* Login via Digid
*
* @param user User
*/
public void login_via_digid(User user) {
openFormsPage.buttonAccepteerCookies.click();
openFormsPage.inloggenDigidButton.click();
digidLoginSteps.login_via_digid(user);
}
/**
* Valideer dat de stap als actief staat
*
* @param stapNaam die actief moet zijn
*/
public void valideer_actieve_stap(String stapNaam) {
assertThat(openFormsPage.linkActiveStep).hasText(stapNaam);
}
/**
* Valideer dat een bepaalde h1 header op het scherm staat
* @param tekst
*/
public void controleer_h1_header_is(String tekst) {
assertThat(openFormsPage.textlabelHeaderH1).hasText(tekst);
}
/**
* Valideer dat een<SUF>*/
public void controleer_h2_header_is(String tekst) {
assertThat(openFormsPage.textlabelHeaderH2).hasText(tekst);
}
/**
* Valideer dat er een bepaalde foutmelding op het scherm staat
*
* @param tekst
*/
public void controleer_foutmelding_is_zichtbaar_met(String tekst) {
assertThat(get_alert().getByText(tekst)).isVisible();
}
/**
* Haal de Locator op van een tekst op het scherm
*
* @param tekst
* @return Locator waarop een actie uitgevoerd kan worden
*/
public Locator get_tekst(String tekst){
return page.getByText(tekst);
}
/**
* Haal de Locator van een inputveld op
*
* @param tekst
* @return Locator waarop een actie uitgevoerd kan worden
*/
public Locator get_input_veld(String tekst){
return genericPage.getInputField(tekst, false);
}
/**
* Haal de Locator van een alert op
*
* @return Locator waarop een actie uitgevoerd kan worden
*/
public Locator get_alert(){
return page.locator("//div[contains(@role,'alert')]//div");
}
/**
* Valideer dat er geen foutmelding zichtbaar is op het scherm
*
*/
public void geen_foutmelding_zichtbaar() {
assertThat(page.locator("//div[@class='form-text error']")).isHidden();
}
/**
* Valideer dat een bepaald veld de goede waarde heeft
*
* @param inputName
* @param prefillWaarde
*/
public void tekstveld_bevat_prefill_gegevens
(String inputName, String prefillWaarde) {
assertThat(
page.locator(
String.format("//input[@name='%s' and contains(@value,\"%s\")]",
inputName,
prefillWaarde)))
.isVisible();
}
/**
* Valideer dat er een bepaalde foutmelding getoond wordt op het scherm
*
* @param locator
* @param verwachteTekst
*/
public void validatie_toon_foutmelding(Locator locator, String verwachteTekst) {
locator.blur();
locator.waitFor(new Locator.WaitForOptions().setTimeout(1000));
page.keyboard().press("Enter");
page.keyboard().press("Tab");
if (verwachteTekst == null) {
geen_foutmelding_zichtbaar();
} else {
controleer_foutmelding_is_zichtbaar_met(verwachteTekst);
}
}
/**
* Klik op de volgende knop
*
*/
public void klik_volgende_knop() {
wacht_op_volgende_knop_response();
klik_knop("Volgende");
}
/**
* Wacht totdat de validatie in de backend is uitgevoerd
*
*/
public void wacht_op_volgende_knop_response(){
try{
page.setDefaultTimeout(2000);
page.waitForResponse(res -> res.url().contains("/_check_logic"), () -> {});
} catch (Exception ex) {
//ignore
} finally {
page.setDefaultTimeout(30000);
}
}
/**
* Haal de Locator op van de checkbox
*
* @param tekst
* @return Locator waarop een actie uitgevoerd kan worden
*/
public Locator get_checkbox(String tekst){
return genericPage.getCheckbox(tekst);
}
/**
* Selecteer een optie bij een radiobox of checkboxgroup
*
* @param tekst van de radio- of checkboxgroep
* @param optie die geselecteerd moet worden
*/
public void selecteer_optie(String tekst, String optie) {
genericPage.selectOption(tekst, optie);
}
/**
*
* Note that this only works on input and textarea fields
*
* @param veld - text of the field you want to enter the text for
* @param text - text you want to enter into the field
*/
public void vul_tekst_in(String veld, String text) {
genericPage.getInputField(veld, false).waitFor(new Locator.WaitForOptions().setTimeout(500));
genericPage.fillTextInputField(veld, text, false);
}
public void selecteer_login_met_digid() {
openFormsPage.inloggenDigidButton.click();
}
public void is_ingelogd() {
openFormsPage.headerFirstFormStep.waitFor();
}
public void waitUntilHeaderPageVisible() {
this.openFormsPage.headerFirstFormStep.waitFor();
}
public void aanvraag_zonder_DigiD_login(){
openFormsPage.aanvraagZonderDigidButton.click();
}
}
| false | 1,523 | 29 | 1,704 | 29 | 1,711 | 26 | 1,704 | 29 | 1,991 | 31 | false | false | false | false | false | true |
3,152 | 9379_17 | /*************************************************************************
* Clus - Software for Predictive Clustering *
* Copyright (C) 2007 *
* Katholieke Universiteit Leuven, Leuven, Belgium *
* Jozef Stefan Institute, Ljubljana, Slovenia *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Contact information: <http://www.cs.kuleuven.be/~dtai/clus/>. *
*************************************************************************/
package clus.algo.kNN;
import clus.main.*;
import clus.algo.tdidt.ClusNode;
import clus.data.rows.*;
import clus.statistic.ClusStatistic;
import java.util.Vector;
//import jeans.util.MyArray;
import jeans.tree.MyNode;
/**
* This class represents a node of an extended decision tree.
* It uses kNN to predict the class of a tuple when in a leaf node
*/
public class KNNTree extends ClusNode {
public final static long serialVersionUID = Settings.SERIAL_VERSION_ID;
public ClusStatManager m_SMgr;
private VectorDistance $vectDist;//used for calculating distances in leafs
private Vector $decisionData;//Tuples that are used in this node of the tree to decide target values.
public KNNTree(ClusRun clRun,VectorDistance vDist){
super();
m_SMgr = clRun.getStatManager();
$vectDist = vDist;
//initialize decision data
$decisionData = new Vector(1,10);
}
public KNNTree(KNNTree toClone){
super();
m_SMgr = toClone.m_SMgr;
m_Test = toClone.m_Test;
m_ClusteringStat = toClone.m_ClusteringStat;
$vectDist = toClone.getVectorDistance();
$decisionData = new Vector(1,10);
}
public final ClusStatistic predictWeighted(DataTuple tuple) {
if (atBottomLevel()) {
//return getTotalStat();
return predictLeaf(tuple,getDecisionData());
} else {
int n_idx = m_Test.predictWeighted(tuple);
if (n_idx != -1) {
ClusNode info = (ClusNode)getChild(n_idx);
return info.predictWeighted(tuple);
} else {
int nb_c = getNbChildren();
ClusStatistic stat = m_ClusteringStat.cloneSimple();
for (int i = 0; i < nb_c; i++) {
ClusNode node = (ClusNode)getChild(i);
ClusStatistic nodes = node.predictWeighted(tuple);
stat.addPrediction(nodes, m_Test.getProportion(i));
}
return stat;
}
}
}
// Preforms kNN in a leafnode with given data to decide
private ClusStatistic predictLeaf(DataTuple tuple,Vector dec_data){
if (tuple == null) System.err.println("tuple == null");
if (dec_data == null) System.err.println("dec_data == null");
ClusStatistic stat = m_SMgr.createClusteringStat();
//find out how much neighbours necessary (via settings)
int amountNBS = Settings.kNNT_k.getValue();
//find out if Distance-Weighted kNN used
boolean distWeighted = Settings.kNNT_distWeighted.getValue();
//make a priorityqueue of size amountNBS to find nearest neighbours
//but when fewer elements for prediction then amountNBS then use only those
if (amountDecisionData(dec_data)<amountNBS) amountNBS = amountDecisionData(dec_data);
PriorityQueue q = new PriorityQueue(amountNBS);
//Manier vinden om aan de datatuples te raken die bij dit blad horen
int nbr = amountDecisionData(dec_data);
DataTuple curTup;
double dist;
//find the nearest neighbours
for (int i = 0; i <nbr;i++){
//System.out.print(i);
curTup = getTuple(dec_data,i);
if (curTup == null) System.out.println("curTup == null");
dist = calcDistance(tuple,curTup);
q.addElement(curTup,dist);
}
//add the kNN's to the statistic
//weights all the same for now: changed when needed
double weight = 1.0;
for (int i=0;i<amountNBS;i++){
//Change weights when distance-weighted kNN is wanted
if (distWeighted) weight = 1.0 / Math.pow(q.getValue(i),2);
stat.updateWeighted((DataTuple)q.getElement(i),weight);
}
stat.calcMean();
return stat;
}
/**
* This method transforms an ordinary ClusNode tree into a KNNTree.
*/
public static KNNTree makeTree(ClusRun cr ,ClusNode source,VectorDistance vd){
KNNTree node = new KNNTree(cr,vd);
node.m_Test = source.m_Test;
node.m_ClusteringStat = source.m_ClusteringStat;
int arity = source.getNbChildren();
node.setNbChildren(arity);
for (int i = 0; i < arity; i++) {
ClusNode child = (ClusNode) source.getChild(i);
node.setChild(KNNTree.makeTree(cr,child,vd), i);
}
return node;
}
/**
* Adds given DataTuple to the DataTuples used for prediction in this node.
*/
public void addTuple(DataTuple t){
//if (atBottom()) { ??? misschien voor zorgen dat het echt alleen werkt als in leaf?
$decisionData.addElement(t);
//}
}
/**
* Returns the i'th DataTuple in the given decision data.
*
* Required
* i < amountDecisionData(dec_data)
*/
public DataTuple getTuple(Vector dec_data,int i){
//if (atBottomLevel())
return (DataTuple) dec_data.elementAt(i);
//else return null;
}
/**
* Returns the amount of DataTuples available for decision making.
*/
public int amountDecisionData(Vector dec_data){
return dec_data.size();
}
// Calculates distance between 2 tuples
private double calcDistance(DataTuple t1,DataTuple t2){
if ($vectDist == null) System.out.println("$vectDist == null");
return $vectDist.getDistance(t1,t2);
}
/*
* Returns a vector containing all decision data for this node,
* when not a leaf it returns the concatenated vector of all decisiondata
* from it's children.
*/
public Vector getDecisionData(){
if (atBottomLevel()) return $decisionData;
else {
Vector dec_data = new Vector(5,5);
KNNTree child;
int arity = getNbChildren();
for (int i = 0; i < arity; i++) {
child = (KNNTree) getChild(i);
dec_data.addAll(child.getDecisionData());
}
return dec_data;
}
}
/**
* Sets teh decisiondata to given data.
* Required
* dec_data may only contain DataTuple objects !!!!
*/
public void setDecisionData(Vector dec_data){
$decisionData = dec_data;
}
public VectorDistance getVectorDistance(){
return $vectDist;
}
/**
* This method makes the current node in the tree a leaf, thereby deleting
* it's children and adding there training examples to there own.
*/
public void makeLeaf(){
if (!atBottomLevel()){
//get decisiondata from children and make it own;
$decisionData = getDecisionData();
m_Test = null;
cleanup();
//remove the children
removeAllChildren();
}
}
/**
* Returns the value for the given tuple based on neirest neighbour but
* using the decision data from whole the subtree.
* (thus also usable for internal nodes)
*/
public ClusStatistic predictWeightedLeaf(DataTuple tuple) {
//if (tuple == null) System.err.println("tuple == null");
return predictLeaf(tuple,getDecisionData());
}
/**
* Returns a clone of this node
* required
* this is a leafnode : atBottomLevel() == True
*/
public MyNode cloneNode() {
KNNTree clone = new KNNTree(this);
if (atBottomLevel()) clone.setDecisionData(getDecisionData());
return clone;
}
}
| janezkranjc/clus | clus/algo/kNN/KNNTree.java | 2,544 | //if (atBottom()) { ??? misschien voor zorgen dat het echt alleen werkt als in leaf? | line_comment | nl | /*************************************************************************
* Clus - Software for Predictive Clustering *
* Copyright (C) 2007 *
* Katholieke Universiteit Leuven, Leuven, Belgium *
* Jozef Stefan Institute, Ljubljana, Slovenia *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Contact information: <http://www.cs.kuleuven.be/~dtai/clus/>. *
*************************************************************************/
package clus.algo.kNN;
import clus.main.*;
import clus.algo.tdidt.ClusNode;
import clus.data.rows.*;
import clus.statistic.ClusStatistic;
import java.util.Vector;
//import jeans.util.MyArray;
import jeans.tree.MyNode;
/**
* This class represents a node of an extended decision tree.
* It uses kNN to predict the class of a tuple when in a leaf node
*/
public class KNNTree extends ClusNode {
public final static long serialVersionUID = Settings.SERIAL_VERSION_ID;
public ClusStatManager m_SMgr;
private VectorDistance $vectDist;//used for calculating distances in leafs
private Vector $decisionData;//Tuples that are used in this node of the tree to decide target values.
public KNNTree(ClusRun clRun,VectorDistance vDist){
super();
m_SMgr = clRun.getStatManager();
$vectDist = vDist;
//initialize decision data
$decisionData = new Vector(1,10);
}
public KNNTree(KNNTree toClone){
super();
m_SMgr = toClone.m_SMgr;
m_Test = toClone.m_Test;
m_ClusteringStat = toClone.m_ClusteringStat;
$vectDist = toClone.getVectorDistance();
$decisionData = new Vector(1,10);
}
public final ClusStatistic predictWeighted(DataTuple tuple) {
if (atBottomLevel()) {
//return getTotalStat();
return predictLeaf(tuple,getDecisionData());
} else {
int n_idx = m_Test.predictWeighted(tuple);
if (n_idx != -1) {
ClusNode info = (ClusNode)getChild(n_idx);
return info.predictWeighted(tuple);
} else {
int nb_c = getNbChildren();
ClusStatistic stat = m_ClusteringStat.cloneSimple();
for (int i = 0; i < nb_c; i++) {
ClusNode node = (ClusNode)getChild(i);
ClusStatistic nodes = node.predictWeighted(tuple);
stat.addPrediction(nodes, m_Test.getProportion(i));
}
return stat;
}
}
}
// Preforms kNN in a leafnode with given data to decide
private ClusStatistic predictLeaf(DataTuple tuple,Vector dec_data){
if (tuple == null) System.err.println("tuple == null");
if (dec_data == null) System.err.println("dec_data == null");
ClusStatistic stat = m_SMgr.createClusteringStat();
//find out how much neighbours necessary (via settings)
int amountNBS = Settings.kNNT_k.getValue();
//find out if Distance-Weighted kNN used
boolean distWeighted = Settings.kNNT_distWeighted.getValue();
//make a priorityqueue of size amountNBS to find nearest neighbours
//but when fewer elements for prediction then amountNBS then use only those
if (amountDecisionData(dec_data)<amountNBS) amountNBS = amountDecisionData(dec_data);
PriorityQueue q = new PriorityQueue(amountNBS);
//Manier vinden om aan de datatuples te raken die bij dit blad horen
int nbr = amountDecisionData(dec_data);
DataTuple curTup;
double dist;
//find the nearest neighbours
for (int i = 0; i <nbr;i++){
//System.out.print(i);
curTup = getTuple(dec_data,i);
if (curTup == null) System.out.println("curTup == null");
dist = calcDistance(tuple,curTup);
q.addElement(curTup,dist);
}
//add the kNN's to the statistic
//weights all the same for now: changed when needed
double weight = 1.0;
for (int i=0;i<amountNBS;i++){
//Change weights when distance-weighted kNN is wanted
if (distWeighted) weight = 1.0 / Math.pow(q.getValue(i),2);
stat.updateWeighted((DataTuple)q.getElement(i),weight);
}
stat.calcMean();
return stat;
}
/**
* This method transforms an ordinary ClusNode tree into a KNNTree.
*/
public static KNNTree makeTree(ClusRun cr ,ClusNode source,VectorDistance vd){
KNNTree node = new KNNTree(cr,vd);
node.m_Test = source.m_Test;
node.m_ClusteringStat = source.m_ClusteringStat;
int arity = source.getNbChildren();
node.setNbChildren(arity);
for (int i = 0; i < arity; i++) {
ClusNode child = (ClusNode) source.getChild(i);
node.setChild(KNNTree.makeTree(cr,child,vd), i);
}
return node;
}
/**
* Adds given DataTuple to the DataTuples used for prediction in this node.
*/
public void addTuple(DataTuple t){
//if (atBottom())<SUF>
$decisionData.addElement(t);
//}
}
/**
* Returns the i'th DataTuple in the given decision data.
*
* Required
* i < amountDecisionData(dec_data)
*/
public DataTuple getTuple(Vector dec_data,int i){
//if (atBottomLevel())
return (DataTuple) dec_data.elementAt(i);
//else return null;
}
/**
* Returns the amount of DataTuples available for decision making.
*/
public int amountDecisionData(Vector dec_data){
return dec_data.size();
}
// Calculates distance between 2 tuples
private double calcDistance(DataTuple t1,DataTuple t2){
if ($vectDist == null) System.out.println("$vectDist == null");
return $vectDist.getDistance(t1,t2);
}
/*
* Returns a vector containing all decision data for this node,
* when not a leaf it returns the concatenated vector of all decisiondata
* from it's children.
*/
public Vector getDecisionData(){
if (atBottomLevel()) return $decisionData;
else {
Vector dec_data = new Vector(5,5);
KNNTree child;
int arity = getNbChildren();
for (int i = 0; i < arity; i++) {
child = (KNNTree) getChild(i);
dec_data.addAll(child.getDecisionData());
}
return dec_data;
}
}
/**
* Sets teh decisiondata to given data.
* Required
* dec_data may only contain DataTuple objects !!!!
*/
public void setDecisionData(Vector dec_data){
$decisionData = dec_data;
}
public VectorDistance getVectorDistance(){
return $vectDist;
}
/**
* This method makes the current node in the tree a leaf, thereby deleting
* it's children and adding there training examples to there own.
*/
public void makeLeaf(){
if (!atBottomLevel()){
//get decisiondata from children and make it own;
$decisionData = getDecisionData();
m_Test = null;
cleanup();
//remove the children
removeAllChildren();
}
}
/**
* Returns the value for the given tuple based on neirest neighbour but
* using the decision data from whole the subtree.
* (thus also usable for internal nodes)
*/
public ClusStatistic predictWeightedLeaf(DataTuple tuple) {
//if (tuple == null) System.err.println("tuple == null");
return predictLeaf(tuple,getDecisionData());
}
/**
* Returns a clone of this node
* required
* this is a leafnode : atBottomLevel() == True
*/
public MyNode cloneNode() {
KNNTree clone = new KNNTree(this);
if (atBottomLevel()) clone.setDecisionData(getDecisionData());
return clone;
}
}
| false | 2,024 | 24 | 2,331 | 27 | 2,328 | 20 | 2,331 | 27 | 2,761 | 27 | false | false | false | false | false | true |
1,519 | 24510_8 | /*
* ENTRADA, a big data platform for network data analytics
*
* Copyright (C) 2016 SIDN [https://www.sidn.nl]
*
* This file is part of ENTRADA.
*
* ENTRADA 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.
*
* ENTRADA 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 ENTRADA. If not, see
* [<http://www.gnu.org/licenses/].
*
*/
package nl.sidnlabs.dnslib.util;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import nl.sidnlabs.dnslib.message.records.dnssec.DNSKEYResourceRecord;
import nl.sidnlabs.dnslib.message.records.dnssec.DSResourceRecord;
public class KeyUtil {
private KeyUtil() {}
private static final char KEY_ZONE_FLAG_MASK = 0x0100; // 0000 0001 0000 0000
private static final char KEY_ZONE_SEP_FLAG_MASK = 0x0101; // 0000 0001 0000 0001
public static PublicKey createPublicKey(byte[] key, int algorithm) {
if (algorithm == 5 || algorithm == 7 || algorithm == 8 || algorithm == 10) {
// only create RSA pub keys.
ByteBuffer b = ByteBuffer.wrap(key);
int exponentLength = b.get() & 0xff;
if (exponentLength == 0) {
exponentLength = b.getChar();
}
try {
byte[] data = new byte[exponentLength];
b.get(data);
BigInteger exponent = new BigInteger(1, data);
byte[] modulusData = new byte[b.remaining()];
b.get(modulusData);
BigInteger modulus = new BigInteger(1, modulusData);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePublic(new RSAPublicKeySpec(modulus, exponent));
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
// problem creating pub key
}
}
// no support for Elliptic curves, Ghost etc
return null;
}
/**
* Bereken de keyTag(footprint) van een publieke sleutel. De keyTag berekent een getal waarmee de
* publieke sleutel te herkennen is, dit is niet per definitie uniek per publieke sleutel. Zie
* IETF RFC 4034, Appendix B voor meer informatie.
*
* @see <a href="http://www.ietf.org/rfc/rfc4034.txt">rfc4034</a>
*
* Dit lijkt op het berekenen van 1 complement checksum
* (http://nl.wikipedia.org/wiki/One%27s_complement) De onderstaande implementatie is
* overgenomen van versisign, zie: <a href=
* "http://svn.verisignlabs.com/jdnssec/dnsjava/trunk/org/xbill/DNS/KEYBase.java">jdnssec
* </a>
* @param rdata key
* @param alg de naam van het algoritme waarmee de public key is gemaakt.
* @return integer waarde welke de keytag van de public key is
*/
public static int createKeyTag(byte[] rdata, int alg) {
int foot = 0;
int footprint = -1;
// als de publieke sleuten met RSA/MD5 is gemaakt en gehashed dan
// geld er een ander algoritme voor bepalen keytag
if (1 == alg) { // MD5
int d1 = rdata[rdata.length - 3] & 0xFF;
int d2 = rdata[rdata.length - 2] & 0xFF;
foot = (d1 << 8) + d2;
} else {
int i;
for (i = 0; i < rdata.length - 1; i += 2) {
int d1 = rdata[i] & 0xFF;
int d2 = rdata[i + 1] & 0xFF;
foot += ((d1 << 8) + d2);
}
if (i < rdata.length) {
int d1 = rdata[i] & 0xFF;
foot += (d1 << 8);
}
foot += ((foot >> 16) & 0xFFFF);
}
footprint = (foot & 0xFFFF);
return footprint;
}
public static boolean isZoneKey(DNSKEYResourceRecord key) {
return (key.getFlags() & KEY_ZONE_FLAG_MASK) == KEY_ZONE_FLAG_MASK;
}
public static boolean isSepKey(DNSKEYResourceRecord key) {
return (key.getFlags() & KEY_ZONE_SEP_FLAG_MASK) == KEY_ZONE_SEP_FLAG_MASK;
}
public static boolean isKeyandDSmatch(DNSKEYResourceRecord key, DSResourceRecord ds) {
return (key.getAlgorithm() == ds.getAlgorithm() && key.getKeytag() == ds.getKeytag()
&& key.getName().equalsIgnoreCase(ds.getName()));
}
}
| SIDN/dns-lib | src/main/java/nl/sidnlabs/dnslib/util/KeyUtil.java | 1,576 | // geld er een ander algoritme voor bepalen keytag | line_comment | nl | /*
* ENTRADA, a big data platform for network data analytics
*
* Copyright (C) 2016 SIDN [https://www.sidn.nl]
*
* This file is part of ENTRADA.
*
* ENTRADA 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.
*
* ENTRADA 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 ENTRADA. If not, see
* [<http://www.gnu.org/licenses/].
*
*/
package nl.sidnlabs.dnslib.util;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import nl.sidnlabs.dnslib.message.records.dnssec.DNSKEYResourceRecord;
import nl.sidnlabs.dnslib.message.records.dnssec.DSResourceRecord;
public class KeyUtil {
private KeyUtil() {}
private static final char KEY_ZONE_FLAG_MASK = 0x0100; // 0000 0001 0000 0000
private static final char KEY_ZONE_SEP_FLAG_MASK = 0x0101; // 0000 0001 0000 0001
public static PublicKey createPublicKey(byte[] key, int algorithm) {
if (algorithm == 5 || algorithm == 7 || algorithm == 8 || algorithm == 10) {
// only create RSA pub keys.
ByteBuffer b = ByteBuffer.wrap(key);
int exponentLength = b.get() & 0xff;
if (exponentLength == 0) {
exponentLength = b.getChar();
}
try {
byte[] data = new byte[exponentLength];
b.get(data);
BigInteger exponent = new BigInteger(1, data);
byte[] modulusData = new byte[b.remaining()];
b.get(modulusData);
BigInteger modulus = new BigInteger(1, modulusData);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePublic(new RSAPublicKeySpec(modulus, exponent));
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
// problem creating pub key
}
}
// no support for Elliptic curves, Ghost etc
return null;
}
/**
* Bereken de keyTag(footprint) van een publieke sleutel. De keyTag berekent een getal waarmee de
* publieke sleutel te herkennen is, dit is niet per definitie uniek per publieke sleutel. Zie
* IETF RFC 4034, Appendix B voor meer informatie.
*
* @see <a href="http://www.ietf.org/rfc/rfc4034.txt">rfc4034</a>
*
* Dit lijkt op het berekenen van 1 complement checksum
* (http://nl.wikipedia.org/wiki/One%27s_complement) De onderstaande implementatie is
* overgenomen van versisign, zie: <a href=
* "http://svn.verisignlabs.com/jdnssec/dnsjava/trunk/org/xbill/DNS/KEYBase.java">jdnssec
* </a>
* @param rdata key
* @param alg de naam van het algoritme waarmee de public key is gemaakt.
* @return integer waarde welke de keytag van de public key is
*/
public static int createKeyTag(byte[] rdata, int alg) {
int foot = 0;
int footprint = -1;
// als de publieke sleuten met RSA/MD5 is gemaakt en gehashed dan
// geld er<SUF>
if (1 == alg) { // MD5
int d1 = rdata[rdata.length - 3] & 0xFF;
int d2 = rdata[rdata.length - 2] & 0xFF;
foot = (d1 << 8) + d2;
} else {
int i;
for (i = 0; i < rdata.length - 1; i += 2) {
int d1 = rdata[i] & 0xFF;
int d2 = rdata[i + 1] & 0xFF;
foot += ((d1 << 8) + d2);
}
if (i < rdata.length) {
int d1 = rdata[i] & 0xFF;
foot += (d1 << 8);
}
foot += ((foot >> 16) & 0xFFFF);
}
footprint = (foot & 0xFFFF);
return footprint;
}
public static boolean isZoneKey(DNSKEYResourceRecord key) {
return (key.getFlags() & KEY_ZONE_FLAG_MASK) == KEY_ZONE_FLAG_MASK;
}
public static boolean isSepKey(DNSKEYResourceRecord key) {
return (key.getFlags() & KEY_ZONE_SEP_FLAG_MASK) == KEY_ZONE_SEP_FLAG_MASK;
}
public static boolean isKeyandDSmatch(DNSKEYResourceRecord key, DSResourceRecord ds) {
return (key.getAlgorithm() == ds.getAlgorithm() && key.getKeytag() == ds.getKeytag()
&& key.getName().equalsIgnoreCase(ds.getName()));
}
}
| false | 1,281 | 14 | 1,396 | 16 | 1,430 | 12 | 1,396 | 16 | 1,623 | 16 | false | false | false | false | false | true |
443 | 194334_2 | package com.example.techiteasymodel.config;
import com.example.techiteasymodel.filter.JwtRequestFilter;
import com.example.techiteasymodel.services.CustomUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
/* Deze security is niet de enige manier om het te doen.
In de andere branch van deze github repo staat een ander voorbeeld
*/
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig {
public final CustomUserDetailsService customUserDetailsService;
private final JwtRequestFilter jwtRequestFilter;
public SpringSecurityConfig(CustomUserDetailsService customUserDetailsService, JwtRequestFilter jwtRequestFilter) {
this.customUserDetailsService = customUserDetailsService;
this.jwtRequestFilter = jwtRequestFilter;
}
// PasswordEncoderBean. Deze kun je overal in je applicatie injecteren waar nodig.
// Je kunt dit ook in een aparte configuratie klasse zetten.
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
// Authenticatie met customUserDetailsService en passwordEncoder
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
return http.getSharedObject(AuthenticationManagerBuilder.class)
.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder())
.and()
.build();
}
// Authorizatie met jwt
@Bean
protected SecurityFilterChain filter (HttpSecurity http) throws Exception {
http
.csrf().disable()
.httpBasic().disable()
.cors().and()
.authorizeHttpRequests()
// Wanneer je deze uncomments, staat je hele security open. Je hebt dan alleen nog een jwt nodig.
// .requestMatchers("/**").permitAll()
.requestMatchers(HttpMethod.POST, "/users").permitAll()
.requestMatchers(HttpMethod.GET,"/users").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST, "/cimodules").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/cimodules/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST, "/remotecontrollers").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/remotecontrollers/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST, "/televisions").hasRole("ADMIN")
.requestMatchers(HttpMethod.GET, "/televisions").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/televisions/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST, "/wallbrackets").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/wallbrackets/**").hasRole("ADMIN")
// Je mag meerdere paths tegelijk definieren
.requestMatchers("/cimodules", "/remotecontrollers", "/televisions", "/wallbrackets").hasAnyRole("ADMIN", "USER")
.requestMatchers("/authenticated").authenticated()
.requestMatchers("/authenticate").permitAll()
.anyRequest().denyAll()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
} | EAM26/TechItEasyModel | src/main/java/com/example/techiteasymodel/config/SpringSecurityConfig.java | 1,140 | // Je kunt dit ook in een aparte configuratie klasse zetten. | line_comment | nl | package com.example.techiteasymodel.config;
import com.example.techiteasymodel.filter.JwtRequestFilter;
import com.example.techiteasymodel.services.CustomUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
/* Deze security is niet de enige manier om het te doen.
In de andere branch van deze github repo staat een ander voorbeeld
*/
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig {
public final CustomUserDetailsService customUserDetailsService;
private final JwtRequestFilter jwtRequestFilter;
public SpringSecurityConfig(CustomUserDetailsService customUserDetailsService, JwtRequestFilter jwtRequestFilter) {
this.customUserDetailsService = customUserDetailsService;
this.jwtRequestFilter = jwtRequestFilter;
}
// PasswordEncoderBean. Deze kun je overal in je applicatie injecteren waar nodig.
// Je kunt<SUF>
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
// Authenticatie met customUserDetailsService en passwordEncoder
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
return http.getSharedObject(AuthenticationManagerBuilder.class)
.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder())
.and()
.build();
}
// Authorizatie met jwt
@Bean
protected SecurityFilterChain filter (HttpSecurity http) throws Exception {
http
.csrf().disable()
.httpBasic().disable()
.cors().and()
.authorizeHttpRequests()
// Wanneer je deze uncomments, staat je hele security open. Je hebt dan alleen nog een jwt nodig.
// .requestMatchers("/**").permitAll()
.requestMatchers(HttpMethod.POST, "/users").permitAll()
.requestMatchers(HttpMethod.GET,"/users").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST, "/cimodules").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/cimodules/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST, "/remotecontrollers").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/remotecontrollers/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST, "/televisions").hasRole("ADMIN")
.requestMatchers(HttpMethod.GET, "/televisions").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/televisions/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST, "/wallbrackets").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/wallbrackets/**").hasRole("ADMIN")
// Je mag meerdere paths tegelijk definieren
.requestMatchers("/cimodules", "/remotecontrollers", "/televisions", "/wallbrackets").hasAnyRole("ADMIN", "USER")
.requestMatchers("/authenticated").authenticated()
.requestMatchers("/authenticate").permitAll()
.anyRequest().denyAll()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
} | false | 814 | 16 | 936 | 18 | 932 | 13 | 936 | 18 | 1,102 | 17 | false | false | false | false | false | true |
4,644 | 71944_0 | package com.eomarker.storage;
import android.content.Context;
import android.widget.Toast;
import com.eomarker.device.Device;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class InternalStorage {
private File storageFile;
Context context;
public InternalStorage(Context _context) {
context = _context;
storageFile = new File(context.getFilesDir(), "devices.json");
if (!storageFile.exists()) {
try {
storageFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void saveDevice(Device device) {
try {
JSONArray jsonArray = readJsonArrayFromFile();
JSONObject deviceObject = new JSONObject();
deviceObject.put("macAddress", device.macAddress);
deviceObject.put("name", device.name);
jsonArray.put(deviceObject);
FileOutputStream fos = new FileOutputStream(storageFile);
fos.write(jsonArray.toString().getBytes());
fos.close();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
public List<Device> getDevices() {
List<Device> devices = new ArrayList<>();
try {
JSONArray jsonArray = readJsonArrayFromFile();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject deviceObject = jsonArray.getJSONObject(i);
String macAddress = deviceObject.getString("macAddress");
String name = deviceObject.getString("name");
devices.add(new Device(macAddress, name));
}
} catch (JSONException e) {
e.printStackTrace();
}
return devices;
}
public void updateDeviceName(String macAddress, String newName) {
try {
JSONArray jsonArray = readJsonArrayFromFile();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject deviceObject = jsonArray.getJSONObject(i);
String deviceMacAddress = deviceObject.getString("macAddress");
// Controleer of het macAdres overeenkomt met het gezochte apparaat
if (deviceMacAddress.equals(macAddress)) {
// Wijzig de naam van het apparaat
deviceObject.put("name", newName);
// Sla de bijgewerkte array terug op
FileOutputStream fos = new FileOutputStream(storageFile);
fos.write(jsonArray.toString().getBytes());
fos.close();
return; // Stop de loop omdat het apparaat is gevonden en bijgewerkt
}
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
private JSONArray readJsonArrayFromFile() {
JSONArray jsonArray = new JSONArray();
try {
BufferedReader reader = new BufferedReader(new FileReader(storageFile));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
reader.close();
jsonArray = new JSONArray(stringBuilder.toString());
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return jsonArray;
}
public void deleteData() {
try{
storageFile = new File(context.getFilesDir(), "devices.json");
storageFile.delete();
Toast.makeText(context, "Data deleted!", Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(context, "Unable to delete data...", Toast.LENGTH_SHORT).show();
}
}
public void deleteDevice(Device device) {
try {
JSONArray jsonArray = readJsonArrayFromFile();
JSONArray updatedArray = new JSONArray();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject deviceObject = jsonArray.getJSONObject(i);
String deviceMacAddress = deviceObject.getString("macAddress");
// Als het macAdres overeenkomt met het te verwijderen apparaat, sla het niet op in de bijgewerkte array
if (!deviceMacAddress.equals(device.macAddress)) {
updatedArray.put(deviceObject);
}
}
// Overschrijf het opslaan van de bijgewerkte array
FileOutputStream fos = new FileOutputStream(storageFile);
fos.write(updatedArray.toString().getBytes());
fos.close();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
} | vives-project-xp/EOMarkers | AndroidStudio/EOMarker/app/src/main/java/com/eomarker/storage/InternalStorage.java | 1,298 | // Controleer of het macAdres overeenkomt met het gezochte apparaat | line_comment | nl | package com.eomarker.storage;
import android.content.Context;
import android.widget.Toast;
import com.eomarker.device.Device;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class InternalStorage {
private File storageFile;
Context context;
public InternalStorage(Context _context) {
context = _context;
storageFile = new File(context.getFilesDir(), "devices.json");
if (!storageFile.exists()) {
try {
storageFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void saveDevice(Device device) {
try {
JSONArray jsonArray = readJsonArrayFromFile();
JSONObject deviceObject = new JSONObject();
deviceObject.put("macAddress", device.macAddress);
deviceObject.put("name", device.name);
jsonArray.put(deviceObject);
FileOutputStream fos = new FileOutputStream(storageFile);
fos.write(jsonArray.toString().getBytes());
fos.close();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
public List<Device> getDevices() {
List<Device> devices = new ArrayList<>();
try {
JSONArray jsonArray = readJsonArrayFromFile();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject deviceObject = jsonArray.getJSONObject(i);
String macAddress = deviceObject.getString("macAddress");
String name = deviceObject.getString("name");
devices.add(new Device(macAddress, name));
}
} catch (JSONException e) {
e.printStackTrace();
}
return devices;
}
public void updateDeviceName(String macAddress, String newName) {
try {
JSONArray jsonArray = readJsonArrayFromFile();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject deviceObject = jsonArray.getJSONObject(i);
String deviceMacAddress = deviceObject.getString("macAddress");
// Controleer of<SUF>
if (deviceMacAddress.equals(macAddress)) {
// Wijzig de naam van het apparaat
deviceObject.put("name", newName);
// Sla de bijgewerkte array terug op
FileOutputStream fos = new FileOutputStream(storageFile);
fos.write(jsonArray.toString().getBytes());
fos.close();
return; // Stop de loop omdat het apparaat is gevonden en bijgewerkt
}
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
private JSONArray readJsonArrayFromFile() {
JSONArray jsonArray = new JSONArray();
try {
BufferedReader reader = new BufferedReader(new FileReader(storageFile));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
reader.close();
jsonArray = new JSONArray(stringBuilder.toString());
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return jsonArray;
}
public void deleteData() {
try{
storageFile = new File(context.getFilesDir(), "devices.json");
storageFile.delete();
Toast.makeText(context, "Data deleted!", Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(context, "Unable to delete data...", Toast.LENGTH_SHORT).show();
}
}
public void deleteDevice(Device device) {
try {
JSONArray jsonArray = readJsonArrayFromFile();
JSONArray updatedArray = new JSONArray();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject deviceObject = jsonArray.getJSONObject(i);
String deviceMacAddress = deviceObject.getString("macAddress");
// Als het macAdres overeenkomt met het te verwijderen apparaat, sla het niet op in de bijgewerkte array
if (!deviceMacAddress.equals(device.macAddress)) {
updatedArray.put(deviceObject);
}
}
// Overschrijf het opslaan van de bijgewerkte array
FileOutputStream fos = new FileOutputStream(storageFile);
fos.write(updatedArray.toString().getBytes());
fos.close();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
} | false | 915 | 21 | 1,075 | 23 | 1,111 | 15 | 1,075 | 23 | 1,259 | 22 | false | false | false | false | false | true |
1,520 | 67090_10 | package nl.sidn.entrada2.service.messaging;
import java.io.IOException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import nl.sidn.entrada2.messaging.S3EventNotification;
import nl.sidn.entrada2.messaging.S3EventNotification.S3EventNotificationRecord;
import nl.sidn.entrada2.service.WorkService;
import nl.sidn.entrada2.util.ConditionalOnRabbitMQ;
import nl.sidn.entrada2.util.UrlUtil;
@ConditionalOnRabbitMQ
@Service
@Slf4j
public class RabbitRequestQueueService extends AbstractRabbitQueue implements RequestQueue {
@Value("${entrada.messaging.leader.name}")
private String queueName;
@Autowired(required = false)
@Qualifier("rabbitByteTemplate")
private AmqpTemplate rabbitTemplate;
@Value("${entrada.messaging.request.name}")
private String requestQueue;
@Autowired
private WorkService workService;
@RabbitListener(id = "${entrada.messaging.request.name}", queues = "${entrada.messaging.request.name}-queue")
public void receiveMessageManual(S3EventNotification message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
log.info("Received s3 event: {}", message);
for (S3EventNotificationRecord rec : message.getRecords()) {
// check the getEventName, updating the tags may also generate a put event and
// this should not lead to processing the same file again.
if (isSupportedEvent(rec.getEventName())) {
String bucket = rec.getS3().getBucket().getName();
String key = UrlUtil.decode(rec.getS3().getObject().getKey());
workService.process(bucket, key);
// ack(channel, deliveryTag);
// }else {
// nack(channel, deliveryTag);
// }
}
}
}
// private void ack( Channel channel, long tag ) {
// try {
// channel.basicAck(tag, false);
// } catch (IOException e) {
// log.error("Ack error for tag: {}", tag, e);
// }
// }
//
// private void nack( Channel channel, long tag ) {
// try {
// channel.basicNack(tag, false, true);
// } catch (IOException e) {
// log.error("Nack error for tag: {}", tag, e);
// }
// }
//
// private void process(String bucket, String key) {
//
// workService.process(bucket, key);
//
// }
// veranderd van put in DeleteTagging, werkt het nog steeds?
private boolean isSupportedEvent(String eventName) {
return StringUtils.equalsIgnoreCase(eventName, "s3:ObjectCreated:Put") ||
StringUtils.equalsIgnoreCase(eventName, "s3:ObjectCreated:CompleteMultipartUpload") ||
// some s3 impls also use PutTagging when add deleting a tag
StringUtils.equalsIgnoreCase(eventName, "s3:ObjectCreated:DeleteTagging") ||
StringUtils.equalsIgnoreCase(eventName, "s3:ObjectCreated:PutTagging");
}
@Override
public String name() {
return requestQueue;
}
}
| SIDN/entrada2 | src/main/java/nl/sidn/entrada2/service/messaging/RabbitRequestQueueService.java | 1,108 | // veranderd van put in DeleteTagging, werkt het nog steeds? | line_comment | nl | package nl.sidn.entrada2.service.messaging;
import java.io.IOException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import nl.sidn.entrada2.messaging.S3EventNotification;
import nl.sidn.entrada2.messaging.S3EventNotification.S3EventNotificationRecord;
import nl.sidn.entrada2.service.WorkService;
import nl.sidn.entrada2.util.ConditionalOnRabbitMQ;
import nl.sidn.entrada2.util.UrlUtil;
@ConditionalOnRabbitMQ
@Service
@Slf4j
public class RabbitRequestQueueService extends AbstractRabbitQueue implements RequestQueue {
@Value("${entrada.messaging.leader.name}")
private String queueName;
@Autowired(required = false)
@Qualifier("rabbitByteTemplate")
private AmqpTemplate rabbitTemplate;
@Value("${entrada.messaging.request.name}")
private String requestQueue;
@Autowired
private WorkService workService;
@RabbitListener(id = "${entrada.messaging.request.name}", queues = "${entrada.messaging.request.name}-queue")
public void receiveMessageManual(S3EventNotification message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
log.info("Received s3 event: {}", message);
for (S3EventNotificationRecord rec : message.getRecords()) {
// check the getEventName, updating the tags may also generate a put event and
// this should not lead to processing the same file again.
if (isSupportedEvent(rec.getEventName())) {
String bucket = rec.getS3().getBucket().getName();
String key = UrlUtil.decode(rec.getS3().getObject().getKey());
workService.process(bucket, key);
// ack(channel, deliveryTag);
// }else {
// nack(channel, deliveryTag);
// }
}
}
}
// private void ack( Channel channel, long tag ) {
// try {
// channel.basicAck(tag, false);
// } catch (IOException e) {
// log.error("Ack error for tag: {}", tag, e);
// }
// }
//
// private void nack( Channel channel, long tag ) {
// try {
// channel.basicNack(tag, false, true);
// } catch (IOException e) {
// log.error("Nack error for tag: {}", tag, e);
// }
// }
//
// private void process(String bucket, String key) {
//
// workService.process(bucket, key);
//
// }
// veranderd van<SUF>
private boolean isSupportedEvent(String eventName) {
return StringUtils.equalsIgnoreCase(eventName, "s3:ObjectCreated:Put") ||
StringUtils.equalsIgnoreCase(eventName, "s3:ObjectCreated:CompleteMultipartUpload") ||
// some s3 impls also use PutTagging when add deleting a tag
StringUtils.equalsIgnoreCase(eventName, "s3:ObjectCreated:DeleteTagging") ||
StringUtils.equalsIgnoreCase(eventName, "s3:ObjectCreated:PutTagging");
}
@Override
public String name() {
return requestQueue;
}
}
| false | 763 | 19 | 973 | 20 | 945 | 17 | 973 | 20 | 1,150 | 19 | false | false | false | false | false | true |
2,538 | 143040_4 | package com.devonpouw.week8;
interface Queue {
// voeg een item toe aan de FIFO queue
void add(int value);
// verwijder een item uit de FIFO queue
int remove();
// geef het eerste item in de FIFO queue terug, maar haal het er niet uit
int peek();
// geef aan of de FIFO queue leeg is
boolean isEmpty();
// geef de lengte van de FIFO queue terug
int size();
// Print de inhoud van de FIFO queue
void print();
// verwijder alle items uit de FIFO queue
void clear();
// verwijder de eerste n items uit de FIFO queue
void clear(int n);
// print de inhoud van de FIFO queue in omgekeerde volgorde
void printReverse();
// plaats een element op een bepaalde positie in de FIFO queue
void jumpTheQueue(int n, int value);
// Zet de FIFO queue om naar een String
String toString();
// Kijk of de FIFO queue gelijk is aan een andere FIFO queue
boolean equals(Queue q);
// Bepaal de index van een bepaalde waarde in de FIFO queue
int indexOf(int value);
// bepaal de laatste index van een bepaalde waarde in de FIFO queue
int lastIndexOf(int value);
}
| devonPouw/traineeship | src/com/devonpouw/week8/Queue.java | 368 | // geef de lengte van de FIFO queue terug | line_comment | nl | package com.devonpouw.week8;
interface Queue {
// voeg een item toe aan de FIFO queue
void add(int value);
// verwijder een item uit de FIFO queue
int remove();
// geef het eerste item in de FIFO queue terug, maar haal het er niet uit
int peek();
// geef aan of de FIFO queue leeg is
boolean isEmpty();
// geef de<SUF>
int size();
// Print de inhoud van de FIFO queue
void print();
// verwijder alle items uit de FIFO queue
void clear();
// verwijder de eerste n items uit de FIFO queue
void clear(int n);
// print de inhoud van de FIFO queue in omgekeerde volgorde
void printReverse();
// plaats een element op een bepaalde positie in de FIFO queue
void jumpTheQueue(int n, int value);
// Zet de FIFO queue om naar een String
String toString();
// Kijk of de FIFO queue gelijk is aan een andere FIFO queue
boolean equals(Queue q);
// Bepaal de index van een bepaalde waarde in de FIFO queue
int indexOf(int value);
// bepaal de laatste index van een bepaalde waarde in de FIFO queue
int lastIndexOf(int value);
}
| false | 306 | 11 | 317 | 13 | 304 | 9 | 317 | 13 | 367 | 12 | false | false | false | false | false | true |
1,794 | 101932_2 | import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class TxtFileIODemo {
public void txtFileOutput(String bestandsnaam){
//aanmaken PrintWriterObject
PrintWriter printer = null;
try {
printer = new PrintWriter(bestandsnaam);
} catch (FileNotFoundException e) {
System.out.println("Bestand " + bestandsnaam + " bestaat niet");
}
//lijnen tekst vragen en onmiddelijk inlezen
System.out.println("Geef drie lijnen tekst:");
Scanner keyboard = new Scanner(System.in);
for(int i = 0; i< 3; i++){
String line = keyboard.nextLine();
printer.println(line);
}
printer.close();
//sluiten stream
System.out.println("De lijnen tekst werden weggeschreven naar " + bestandsnaam);
}
public void txtFileInput(String bestandsnaam){
//Scanner object aanmaken voor txt input
Scanner input = null;
try {
input = new Scanner(new File(bestandsnaam));
} catch (FileNotFoundException e) {
System.out.println("Bestand niet gevonden");
}
//alle lijnen van txt bestand inlezen en printen
while(input.hasNextLine()){
String line = input.nextLine();
System.out.println(line);
}
//Scanner object sluiten
input.close();
}
public static void main(String[] args) {
TxtFileIODemo test1 = new TxtFileIODemo();
test1.txtFileOutput("resultaat.txt");
test1.txtFileInput("resultaat.txt");
}
}
| UGent-AD2122-BusinessEngineering/CodevoorbeeldenHOC-2021 | src/TxtFileIODemo.java | 482 | //alle lijnen van txt bestand inlezen en printen | line_comment | nl | import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class TxtFileIODemo {
public void txtFileOutput(String bestandsnaam){
//aanmaken PrintWriterObject
PrintWriter printer = null;
try {
printer = new PrintWriter(bestandsnaam);
} catch (FileNotFoundException e) {
System.out.println("Bestand " + bestandsnaam + " bestaat niet");
}
//lijnen tekst vragen en onmiddelijk inlezen
System.out.println("Geef drie lijnen tekst:");
Scanner keyboard = new Scanner(System.in);
for(int i = 0; i< 3; i++){
String line = keyboard.nextLine();
printer.println(line);
}
printer.close();
//sluiten stream
System.out.println("De lijnen tekst werden weggeschreven naar " + bestandsnaam);
}
public void txtFileInput(String bestandsnaam){
//Scanner object aanmaken voor txt input
Scanner input = null;
try {
input = new Scanner(new File(bestandsnaam));
} catch (FileNotFoundException e) {
System.out.println("Bestand niet gevonden");
}
//alle lijnen<SUF>
while(input.hasNextLine()){
String line = input.nextLine();
System.out.println(line);
}
//Scanner object sluiten
input.close();
}
public static void main(String[] args) {
TxtFileIODemo test1 = new TxtFileIODemo();
test1.txtFileOutput("resultaat.txt");
test1.txtFileInput("resultaat.txt");
}
}
| false | 359 | 14 | 418 | 15 | 428 | 13 | 418 | 15 | 485 | 14 | false | false | false | false | false | true |
1,758 | 10224_2 | package minigui;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class HelloFx extends Application {
public static void main(String[] args) {
//Als je wilt dat de gouwe ouwe main het doet moet je in de IntelliJ run-configuratie het module-path
//correct configureren. Dat weet ik even niet meer uit het hoofd, maar kun je afkijken in OOP:)
StackPane pane = new StackPane();
//pane.layout(); is een voorbeeld van een composite pattern method.
//al zul je die nooit met de hand aanroepen...
Application.launch(args);
//Veel makkelijker is met het maven-menutje naar plugins/javafx/javafx:run te gaan:)
}
@Override
public void start(Stage stage) throws Exception {
Label label = new Label("Counter");
Label counterLabel = new Label();
Button increment = new Button("++");
increment.setOnAction(new WatDoetDeKnopStrategy(
new LabelCounterViewAdapter(counterLabel),
new CounterModel()));
FlowPane root = new FlowPane(label, counterLabel, increment);
root.setOrientation(Orientation.VERTICAL);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
}
| TomKemperNL/hu-sarch-jdkpatterns | src/main/java/minigui/HelloFx.java | 440 | //pane.layout(); is een voorbeeld van een composite pattern method. | line_comment | nl | package minigui;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class HelloFx extends Application {
public static void main(String[] args) {
//Als je wilt dat de gouwe ouwe main het doet moet je in de IntelliJ run-configuratie het module-path
//correct configureren. Dat weet ik even niet meer uit het hoofd, maar kun je afkijken in OOP:)
StackPane pane = new StackPane();
//pane.layout(); is<SUF>
//al zul je die nooit met de hand aanroepen...
Application.launch(args);
//Veel makkelijker is met het maven-menutje naar plugins/javafx/javafx:run te gaan:)
}
@Override
public void start(Stage stage) throws Exception {
Label label = new Label("Counter");
Label counterLabel = new Label();
Button increment = new Button("++");
increment.setOnAction(new WatDoetDeKnopStrategy(
new LabelCounterViewAdapter(counterLabel),
new CounterModel()));
FlowPane root = new FlowPane(label, counterLabel, increment);
root.setOrientation(Orientation.VERTICAL);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
}
| false | 320 | 14 | 386 | 16 | 383 | 14 | 386 | 16 | 425 | 16 | false | false | false | false | false | true |
3,792 | 58008_3 | /*
* [ 1719398 ] First shot at LWPOLYLINE
* Peter Hopfgartner - hopfgartner
*
*/
package org.geotools.data.dxf.entities;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.LinearRing;
import org.geotools.data.dxf.parser.DXFLineNumberReader;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.geotools.data.GeometryType;
import org.geotools.data.dxf.parser.DXFUnivers;
import org.geotools.data.dxf.header.DXFLayer;
import org.geotools.data.dxf.header.DXFLineType;
import org.geotools.data.dxf.header.DXFTables;
import org.geotools.data.dxf.parser.DXFCodeValuePair;
import org.geotools.data.dxf.parser.DXFGroupCode;
import org.geotools.data.dxf.parser.DXFParseException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
*
* @source $URL$
*/
public class DXFLwPolyline extends DXFEntity {
private static final Log log = LogFactory.getLog(DXFLwPolyline.class);
public String _id = "DXFLwPolyline";
public int _flag = 0;
public Vector<DXFLwVertex> theVertices = new Vector<DXFLwVertex>();
public DXFLwPolyline(String name, int flag, int c, DXFLayer l, Vector<DXFLwVertex> v, int visibility, DXFLineType lineType, double thickness) {
super(c, l, visibility, lineType, thickness);
_id = name;
Vector<DXFLwVertex> newV = new Vector<DXFLwVertex>();
for (int i = 0; i < v.size(); i++) {
DXFLwVertex entity = (DXFLwVertex) v.get(i).clone();
newV.add(entity);
}
theVertices = newV;
_flag = flag;
setName("DXFLwPolyline");
}
public DXFLwPolyline(DXFLayer l) {
super(-1, l, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline() {
super(-1, null, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline(DXFLwPolyline orig) {
super(orig.getColor(), orig.getRefLayer(), 0, orig.getLineType(), orig.getThickness());
_id = orig._id;
for (int i = 0; i < orig.theVertices.size(); i++) {
theVertices.add((DXFLwVertex) orig.theVertices.elementAt(i).clone());
}
_flag = orig._flag;
setType(orig.getType());
setStartingLineNumber(orig.getStartingLineNumber());
setUnivers(orig.getUnivers());
setName("DXFLwPolyline");
}
public static DXFLwPolyline read(DXFLineNumberReader br, DXFUnivers univers) throws IOException {
String name = "";
int visibility = 0, flag = 0, c = -1;
DXFLineType lineType = null;
Vector<DXFLwVertex> lv = new Vector<DXFLwVertex>();
DXFLayer l = null;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
boolean doLoop = true;
while (doLoop) {
cvp = new DXFCodeValuePair();
try {
gc = cvp.read(br);
} catch (DXFParseException ex) {
throw new IOException("DXF parse error" + ex.getLocalizedMessage());
} catch (EOFException e) {
doLoop = false;
break;
}
switch (gc) {
case TYPE:
String type = cvp.getStringValue(); // SEQEND ???
// geldt voor alle waarden van type
br.reset();
doLoop = false;
break;
case X_1: //"10"
br.reset();
readLwVertices(br, lv);
break;
case NAME: //"2"
name = cvp.getStringValue();
break;
case LAYER_NAME: //"8"
l = univers.findLayer(cvp.getStringValue());
break;
case LINETYPE_NAME: //"6"
lineType = univers.findLType(cvp.getStringValue());
break;
case COLOR: //"62"
c = cvp.getShortValue();
break;
case INT_1: //"70"
flag = cvp.getShortValue();
break;
case VISIBILITY: //"60"
visibility = cvp.getShortValue();
break;
default:
break;
}
}
DXFLwPolyline e = new DXFLwPolyline(name, flag, c, l, lv, visibility, lineType, DXFTables.defaultThickness);
if ((flag & 1) == 1) {
e.setType(GeometryType.POLYGON);
} else {
e.setType(GeometryType.LINE);
}
e.setStartingLineNumber(sln);
e.setUnivers(univers);
log.debug(e.toString(name, flag, lv.size(), c, visibility, DXFTables.defaultThickness));
log.debug(">>Exit at line: " + br.getLineNumber());
return e;
}
public static void readLwVertices(DXFLineNumberReader br, Vector<DXFLwVertex> theVertices) throws IOException {
double x = 0, y = 0, b = 0;
boolean xFound = false, yFound = false;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
boolean doLoop = true;
while (doLoop) {
cvp = new DXFCodeValuePair();
try {
gc = cvp.read(br);
} catch (DXFParseException ex) {
throw new IOException("DXF parse error" + ex.getLocalizedMessage());
} catch (EOFException e) {
doLoop = false;
break;
}
switch (gc) {
case TYPE:
case X_1: //"10"
// check of vorig vertex opgeslagen kan worden
if (xFound && yFound) {
DXFLwVertex e = new DXFLwVertex(x, y, b);
log.debug(e.toString(b, x, y));
theVertices.add(e);
xFound = false;
yFound = false;
x = 0;
y = 0;
b = 0;
}
// TODO klopt dit???
if (gc == DXFGroupCode.TYPE) {
br.reset();
doLoop = false;
break;
}
x = cvp.getDoubleValue();
xFound = true;
break;
case Y_1: //"20"
y = cvp.getDoubleValue();
yFound = true;
break;
case DOUBLE_3: //"42"
b = cvp.getDoubleValue();
break;
default:
break;
}
}
log.debug(">Exit at line: " + br.getLineNumber());
}
@Override
public Geometry getGeometry() {
if (geometry == null) {
updateGeometry();
}
return super.getGeometry();
}
@Override
public void updateGeometry() {
Coordinate[] ca = toCoordinateArray();
if (ca != null && ca.length > 1) {
if (getType() == GeometryType.POLYGON) {
LinearRing lr = getUnivers().getGeometryFactory().createLinearRing(ca);
geometry = getUnivers().getGeometryFactory().createPolygon(lr, null);
} else {
geometry = getUnivers().getGeometryFactory().createLineString(ca);
}
} else {
addError("coordinate array faulty, size: " + (ca == null ? 0 : ca.length));
}
}
public Coordinate[] toCoordinateArray() {
if (theVertices == null) {
addError("coordinate array can not be created.");
return null;
}
Iterator it = theVertices.iterator();
List<Coordinate> lc = new ArrayList<Coordinate>();
Coordinate firstc = null;
Coordinate lastc = null;
while (it.hasNext()) {
DXFLwVertex v = (DXFLwVertex) it.next();
lastc = v.toCoordinate();
if (firstc == null) {
firstc = lastc;
}
lc.add(lastc);
}
// If only 2 points found, make Line
if (lc.size() == 2) {
setType(GeometryType.LINE);
}
// Forced closing polygon
if (getType() == GeometryType.POLYGON) {
if (!firstc.equals2D(lastc)) {
lc.add(firstc);
}
}
/* TODO uitzoeken of lijn zichzelf snijdt, zo ja nodding
* zie jts union:
* Collection lineStrings = . . .
* Geometry nodedLineStrings = (LineString) lineStrings.get(0);
* for (int i = 1; i < lineStrings.size(); i++) {
* nodedLineStrings = nodedLineStrings.union((LineString)lineStrings.get(i));
* */
return rotateAndPlace(lc.toArray(new Coordinate[]{}));
}
public String toString(String name, int flag, int numVert, int c, int visibility, double thickness) {
StringBuffer s = new StringBuffer();
s.append("DXFPolyline [");
s.append("name: ");
s.append(name + ", ");
s.append("flag: ");
s.append(flag + ", ");
s.append("numVert: ");
s.append(numVert + ", ");
s.append("color: ");
s.append(c + ", ");
s.append("visibility: ");
s.append(visibility + ", ");
s.append("thickness: ");
s.append(thickness);
s.append("]");
return s.toString();
}
@Override
public String toString() {
return toString(getName(), _flag, theVertices.size(), getColor(), (isVisible() ? 0 : 1), getThickness());
}
@Override
public DXFEntity translate(double x, double y) {
// Move all vertices
Iterator iter = theVertices.iterator();
while (iter.hasNext()) {
DXFLwVertex vertex = (DXFLwVertex) iter.next();
vertex._point.x += x;
vertex._point.y += y;
}
return this;
}
@Override
public DXFEntity clone() {
return new DXFLwPolyline(this);
}
}
| netconstructor/GeoTools | modules/unsupported/dxf/src/main/java/org/geotools/data/dxf/entities/DXFLwPolyline.java | 3,243 | // check of vorig vertex opgeslagen kan worden | line_comment | nl | /*
* [ 1719398 ] First shot at LWPOLYLINE
* Peter Hopfgartner - hopfgartner
*
*/
package org.geotools.data.dxf.entities;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.LinearRing;
import org.geotools.data.dxf.parser.DXFLineNumberReader;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.geotools.data.GeometryType;
import org.geotools.data.dxf.parser.DXFUnivers;
import org.geotools.data.dxf.header.DXFLayer;
import org.geotools.data.dxf.header.DXFLineType;
import org.geotools.data.dxf.header.DXFTables;
import org.geotools.data.dxf.parser.DXFCodeValuePair;
import org.geotools.data.dxf.parser.DXFGroupCode;
import org.geotools.data.dxf.parser.DXFParseException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
*
* @source $URL$
*/
public class DXFLwPolyline extends DXFEntity {
private static final Log log = LogFactory.getLog(DXFLwPolyline.class);
public String _id = "DXFLwPolyline";
public int _flag = 0;
public Vector<DXFLwVertex> theVertices = new Vector<DXFLwVertex>();
public DXFLwPolyline(String name, int flag, int c, DXFLayer l, Vector<DXFLwVertex> v, int visibility, DXFLineType lineType, double thickness) {
super(c, l, visibility, lineType, thickness);
_id = name;
Vector<DXFLwVertex> newV = new Vector<DXFLwVertex>();
for (int i = 0; i < v.size(); i++) {
DXFLwVertex entity = (DXFLwVertex) v.get(i).clone();
newV.add(entity);
}
theVertices = newV;
_flag = flag;
setName("DXFLwPolyline");
}
public DXFLwPolyline(DXFLayer l) {
super(-1, l, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline() {
super(-1, null, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline(DXFLwPolyline orig) {
super(orig.getColor(), orig.getRefLayer(), 0, orig.getLineType(), orig.getThickness());
_id = orig._id;
for (int i = 0; i < orig.theVertices.size(); i++) {
theVertices.add((DXFLwVertex) orig.theVertices.elementAt(i).clone());
}
_flag = orig._flag;
setType(orig.getType());
setStartingLineNumber(orig.getStartingLineNumber());
setUnivers(orig.getUnivers());
setName("DXFLwPolyline");
}
public static DXFLwPolyline read(DXFLineNumberReader br, DXFUnivers univers) throws IOException {
String name = "";
int visibility = 0, flag = 0, c = -1;
DXFLineType lineType = null;
Vector<DXFLwVertex> lv = new Vector<DXFLwVertex>();
DXFLayer l = null;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
boolean doLoop = true;
while (doLoop) {
cvp = new DXFCodeValuePair();
try {
gc = cvp.read(br);
} catch (DXFParseException ex) {
throw new IOException("DXF parse error" + ex.getLocalizedMessage());
} catch (EOFException e) {
doLoop = false;
break;
}
switch (gc) {
case TYPE:
String type = cvp.getStringValue(); // SEQEND ???
// geldt voor alle waarden van type
br.reset();
doLoop = false;
break;
case X_1: //"10"
br.reset();
readLwVertices(br, lv);
break;
case NAME: //"2"
name = cvp.getStringValue();
break;
case LAYER_NAME: //"8"
l = univers.findLayer(cvp.getStringValue());
break;
case LINETYPE_NAME: //"6"
lineType = univers.findLType(cvp.getStringValue());
break;
case COLOR: //"62"
c = cvp.getShortValue();
break;
case INT_1: //"70"
flag = cvp.getShortValue();
break;
case VISIBILITY: //"60"
visibility = cvp.getShortValue();
break;
default:
break;
}
}
DXFLwPolyline e = new DXFLwPolyline(name, flag, c, l, lv, visibility, lineType, DXFTables.defaultThickness);
if ((flag & 1) == 1) {
e.setType(GeometryType.POLYGON);
} else {
e.setType(GeometryType.LINE);
}
e.setStartingLineNumber(sln);
e.setUnivers(univers);
log.debug(e.toString(name, flag, lv.size(), c, visibility, DXFTables.defaultThickness));
log.debug(">>Exit at line: " + br.getLineNumber());
return e;
}
public static void readLwVertices(DXFLineNumberReader br, Vector<DXFLwVertex> theVertices) throws IOException {
double x = 0, y = 0, b = 0;
boolean xFound = false, yFound = false;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
boolean doLoop = true;
while (doLoop) {
cvp = new DXFCodeValuePair();
try {
gc = cvp.read(br);
} catch (DXFParseException ex) {
throw new IOException("DXF parse error" + ex.getLocalizedMessage());
} catch (EOFException e) {
doLoop = false;
break;
}
switch (gc) {
case TYPE:
case X_1: //"10"
// check of<SUF>
if (xFound && yFound) {
DXFLwVertex e = new DXFLwVertex(x, y, b);
log.debug(e.toString(b, x, y));
theVertices.add(e);
xFound = false;
yFound = false;
x = 0;
y = 0;
b = 0;
}
// TODO klopt dit???
if (gc == DXFGroupCode.TYPE) {
br.reset();
doLoop = false;
break;
}
x = cvp.getDoubleValue();
xFound = true;
break;
case Y_1: //"20"
y = cvp.getDoubleValue();
yFound = true;
break;
case DOUBLE_3: //"42"
b = cvp.getDoubleValue();
break;
default:
break;
}
}
log.debug(">Exit at line: " + br.getLineNumber());
}
@Override
public Geometry getGeometry() {
if (geometry == null) {
updateGeometry();
}
return super.getGeometry();
}
@Override
public void updateGeometry() {
Coordinate[] ca = toCoordinateArray();
if (ca != null && ca.length > 1) {
if (getType() == GeometryType.POLYGON) {
LinearRing lr = getUnivers().getGeometryFactory().createLinearRing(ca);
geometry = getUnivers().getGeometryFactory().createPolygon(lr, null);
} else {
geometry = getUnivers().getGeometryFactory().createLineString(ca);
}
} else {
addError("coordinate array faulty, size: " + (ca == null ? 0 : ca.length));
}
}
public Coordinate[] toCoordinateArray() {
if (theVertices == null) {
addError("coordinate array can not be created.");
return null;
}
Iterator it = theVertices.iterator();
List<Coordinate> lc = new ArrayList<Coordinate>();
Coordinate firstc = null;
Coordinate lastc = null;
while (it.hasNext()) {
DXFLwVertex v = (DXFLwVertex) it.next();
lastc = v.toCoordinate();
if (firstc == null) {
firstc = lastc;
}
lc.add(lastc);
}
// If only 2 points found, make Line
if (lc.size() == 2) {
setType(GeometryType.LINE);
}
// Forced closing polygon
if (getType() == GeometryType.POLYGON) {
if (!firstc.equals2D(lastc)) {
lc.add(firstc);
}
}
/* TODO uitzoeken of lijn zichzelf snijdt, zo ja nodding
* zie jts union:
* Collection lineStrings = . . .
* Geometry nodedLineStrings = (LineString) lineStrings.get(0);
* for (int i = 1; i < lineStrings.size(); i++) {
* nodedLineStrings = nodedLineStrings.union((LineString)lineStrings.get(i));
* */
return rotateAndPlace(lc.toArray(new Coordinate[]{}));
}
public String toString(String name, int flag, int numVert, int c, int visibility, double thickness) {
StringBuffer s = new StringBuffer();
s.append("DXFPolyline [");
s.append("name: ");
s.append(name + ", ");
s.append("flag: ");
s.append(flag + ", ");
s.append("numVert: ");
s.append(numVert + ", ");
s.append("color: ");
s.append(c + ", ");
s.append("visibility: ");
s.append(visibility + ", ");
s.append("thickness: ");
s.append(thickness);
s.append("]");
return s.toString();
}
@Override
public String toString() {
return toString(getName(), _flag, theVertices.size(), getColor(), (isVisible() ? 0 : 1), getThickness());
}
@Override
public DXFEntity translate(double x, double y) {
// Move all vertices
Iterator iter = theVertices.iterator();
while (iter.hasNext()) {
DXFLwVertex vertex = (DXFLwVertex) iter.next();
vertex._point.x += x;
vertex._point.y += y;
}
return this;
}
@Override
public DXFEntity clone() {
return new DXFLwPolyline(this);
}
}
| false | 2,408 | 11 | 2,640 | 12 | 2,841 | 11 | 2,640 | 12 | 3,235 | 11 | false | false | false | false | false | true |
3,446 | 33262_0 | package oplossing;
public class Node233<E extends Comparable<E>> extends Node<E>{
private Node233<E> leftChild;
private Node233<E> middleChild;
private Node233<E> rightChild;
public Node233(E leftValue, E rightValue) {
super(leftValue, rightValue);
}
/**
* Kleine functie om wat properheid te bewaren in de code.
* Op basis van een Element o, kijk in welke richten er gegaan moet worden
* om dichter bij dit element te komen
* @param o het element waarmee vergeleken wordt
* @return een van de kinderen van deze node
*/
public Node233<E> getChild(E o) {
if (hasLeftValue() && leftValue.compareTo(o) > 0) {
return getLeftChild();
}
if (hasRightValue() && rightValue.compareTo(o) < 0) {
return getRightChild();
}
return getMiddleChild();
}
/**
* Gegeven een nieuw kind, adopteer hem op de juiste plaats.
* @param newNode het kind dat geadopteerd zal worden.
*/
public void setChild(Node233<E> newNode){
E o = newNode.leftValue;
if (hasLeftValue() && leftValue.compareTo(o) > 0) {
setLeftChild(newNode);
} else if (hasRightValue() && rightValue.compareTo(o) < 0) {
setRightChild(newNode);
} else {
setMiddleChild(newNode);
}
}
/**
* Het rechter kind van de parent (deze node dus) in de parent brengen
* Kan enkel wanneer deze node en de parent maar één sleutel hebben
*/
private void percolateUpFromRight(Node233<E> parent){
parent.rightValue = leftValue;
parent.setMiddleChild(getLeftChild());
parent.setRightChild(getMiddleChild());
}
/**
* Zelfde percolateUpFromRight maar dan vanaf links
*/
private void percolateUpFromLeft(Node233<E> parent) {
parent.rightValue = leftValue;
parent.swapValues();
parent.setLeftChild(getLeftChild());
parent.setRightChild(parent.getMiddleChild());
parent.setMiddleChild(getMiddleChild());
}
public void percolateUp(Node233<E> parent, E o) {
if (!parent.hasLeftValue() || parent.leftValue.compareTo(o) > 0) {
percolateUpFromLeft(parent);
} else {
percolateUpFromRight(parent);
}
}
/**
* maakt van een deelboom met twee toppen en drie sleutels een binaire boom:
*
* [ B ]
* / \
* [ A ] [ C ]
*
* @param o linkerwaarde in de laagste node
*/
public void convertToBinary(E o){
if (rightValue.compareTo(o) < 0) {
convertToBinaryFromRight();
} else if (leftValue.compareTo(o) > 0){
convertToBinaryFromLeft();
} else {
convertToBinaryFromMiddle();
}
}
/**
* startpositie
*
* [ A B ]
* \
* [ C ]
*/
private void convertToBinaryFromRight() {
Node233<E> linkerNode = new Node233<>(leftValue, null);
linkerNode.setLeftChild(getLeftChild());
linkerNode.setMiddleChild(getMiddleChild());
leftValue = rightValue;
setLeftChild(linkerNode);
setMiddleChild(getRightChild());
rightValue = null;
setRightChild(null);
}
/**
* startpositie
*
* [ B C ]
* /
* [ A ]
*/
private void convertToBinaryFromLeft() {
Node233<E> rechterNode = new Node233<>(rightValue, null);
rechterNode.setLeftChild(getMiddleChild());
rechterNode.setMiddleChild(getRightChild());
setMiddleChild(rechterNode);
rightValue = null;
setRightChild(null);
}
/**
* startpositie
*
* [ A C ]
* |
* [ B ]
*/
private void convertToBinaryFromMiddle() {
Node233<E> linkerNode = new Node233<>(leftValue, null);
Node233<E> rechterNode = new Node233<>(rightValue, null);
linkerNode.setLeftChild(getLeftChild());
linkerNode.setMiddleChild(getMiddleChild().getLeftChild());
rechterNode.setMiddleChild(getRightChild());
rechterNode.setLeftChild(getMiddleChild().getMiddleChild());
leftValue = getMiddleChild().leftValue;
setLeftChild(linkerNode);
setMiddleChild(rechterNode);
rightValue = null;
setRightChild(null);
}
/**
* De verwijderNode zit in het midden en gebruikt gebruikt zijn midden-sibling om zichzelf op te vullen
*/
private void redistributeFromLeft(Node233<E> verwijderNode){
verwijderNode.leftValue = leftValue;
leftValue = getMiddleChild().leftValue;
getMiddleChild().leftValue = getMiddleChild().rightValue;
getMiddleChild().rightValue = null;
verwijderNode.setLeftChild(verwijderNode.getMiddleChild());
verwijderNode.setMiddleChild(getMiddleChild().getLeftChild());
getMiddleChild().setLeftChild(getMiddleChild().getMiddleChild());
getMiddleChild().setMiddleChild(getMiddleChild().getRightChild());
getMiddleChild().setRightChild(null);
}
/**
* De verwijderNode zit in het midden en gebruikt zijn linker-sibling met twee sleutels
*/
private void redistributeFromMiddle1(Node233<E> verwijderNode) {
verwijderNode.leftValue = leftValue;
leftValue = getLeftChild().rightValue;
getLeftChild().rightValue = null;
getMiddleChild().setLeftChild(getLeftChild().getRightChild());
getLeftChild().setRightChild(null);
}
/**
* De verwijderNode zit in het midden en gebruikt zijn rechter-sibling met twee sleutels
*/
private void redistributeFromMiddle2(Node233<E> verwijderNode) {
verwijderNode.leftValue = rightValue;
rightValue = getRightChild().leftValue;
getRightChild().leftValue = getRightChild().rightValue;
getRightChild().rightValue = null;
verwijderNode.setLeftChild(verwijderNode.getMiddleChild());
verwijderNode.setMiddleChild(getRightChild().getLeftChild());
getRightChild().setLeftChild(getRightChild().getMiddleChild());
getRightChild().setMiddleChild(getRightChild().getRightChild());
getRightChild().setRightChild(null);
}
/**
* De verwijderNode zit rechts en zijn midden-sibling heeft twee nodes
*/
private void redistributeFromRight(Node233<E> verwijderNode) {
verwijderNode.leftValue = rightValue;
rightValue = getMiddleChild().rightValue;
getMiddleChild().rightValue = null;
getRightChild().setLeftChild(getMiddleChild().getRightChild());
getMiddleChild().setRightChild(null);
}
/**
* Gebruik Een node met twee sleutels naast de verwijderNode
* @param verwijderNode de lege node die heropgevuld moet worden.
* @return false als er geen herdistributie is gebeurt
*/
public boolean redistribute(Node233<E> verwijderNode) {
if (verwijderNode == getLeftChild() && getMiddleChild().numberOfKeys() == 2){
redistributeFromLeft(verwijderNode);
return true;
} else if (verwijderNode == getMiddleChild() && getLeftChild().numberOfKeys() == 2) {
redistributeFromMiddle1(verwijderNode);
return true;
} else if (verwijderNode == getMiddleChild() && getRightChild() != null && getRightChild().numberOfKeys() == 2) {
redistributeFromMiddle2(verwijderNode);
return true;
} else if (verwijderNode == getRightChild() && getMiddleChild().numberOfKeys() == 2) {
redistributeFromRight(verwijderNode);
return true;
}
return false;
}
private void mergeIntoLeftChild() {
getLeftChild().leftValue = leftValue;
getLeftChild().rightValue = getMiddleChild().leftValue;
leftValue = null;
swapValues();
getLeftChild().setLeftChild(getLeftChild().getMiddleChild());
getLeftChild().setMiddleChild(getMiddleChild().getLeftChild());
getLeftChild().setRightChild(getMiddleChild().getMiddleChild());
setMiddleChild(getRightChild());
setRightChild(null);
}
private void mergeIntoMiddleChild() {
getLeftChild().rightValue = leftValue;
leftValue = rightValue;
rightValue = null;
getLeftChild().setRightChild(getMiddleChild().getMiddleChild());
setMiddleChild(getRightChild());
setRightChild(null);
}
private void mergeIntoRightChild() {
getMiddleChild().rightValue = rightValue;
rightValue = null;
getMiddleChild().setRightChild(getRightChild().getMiddleChild());
setRightChild(null);
}
/**
* Wanneer deze node twee sleutels heeft, kan een van de kinderen de lege node invullen met een van zijn sleutels,
* Een gat dat daar zou kunnen ontstaan wordt op zijn beurt opgevuld door een van de sleutels uit deze node.
* @param verwijderNode De lege node waarin gemerged moet worden
*/
public void mergeIntoChild(Node233<E> verwijderNode) {
if (getLeftChild() == verwijderNode){
mergeIntoLeftChild();
} else if (getMiddleChild() == verwijderNode){
mergeIntoMiddleChild();
} else if (getRightChild() == verwijderNode) {
mergeIntoRightChild();
}
}
/**
* startpositie
* [ B ]
* /
* [ A ]
*
*/
private void geval2NodesLeft(Node233<E> verwijderNode) {
verwijderNode.leftValue = leftValue;
leftValue = null;
verwijderNode.rightValue = getMiddleChild().leftValue;
verwijderNode.setLeftChild(verwijderNode.getMiddleChild());
verwijderNode.setMiddleChild(getMiddleChild().getLeftChild());
verwijderNode.setRightChild(getMiddleChild().getMiddleChild());
setMiddleChild(getLeftChild());
setLeftChild(null); // TODO het kind van de (null, null) node niet middle child laten zijn maar leftchild
}
/**
* startpositie
* [ A ]
* \
* [ B ]
*/
private void geval2NodesMiddle(Node233<E> verwijderNode) {
verwijderNode.rightValue = leftValue;
verwijderNode.setRightChild(getMiddleChild().getMiddleChild());
leftValue = null;
getMiddleChild().leftValue = getLeftChild().leftValue;
getMiddleChild().setMiddleChild(getLeftChild().getMiddleChild());
getMiddleChild().setLeftChild(getLeftChild().getLeftChild());
setLeftChild(null);
}
/**
* Leeg
* |
* [ A B ]
*
*/
public void geval2nodes(Node233<E> verwijderNode){
if (verwijderNode == getLeftChild()) {
geval2NodesLeft(verwijderNode);
} else {
geval2NodesMiddle(verwijderNode);
}
}
public boolean isLeaf(){
return this.getLeftChild() == null;
}
public Node233<E> getLeftChild() {
return leftChild;
}
public void setLeftChild(Node233<E> leftChild) {
this.leftChild = leftChild;
}
public Node233<E> getMiddleChild() {
return middleChild;
}
public void setMiddleChild(Node233<E> middleChild) {
this.middleChild = middleChild;
}
public Node233<E> getRightChild() {
return rightChild;
}
public void setRightChild(Node233<E> rightChild) {
this.rightChild = rightChild;
}
} | lbarraga/TwoThreeTree | src/oplossing/Node233.java | 3,423 | /**
* Kleine functie om wat properheid te bewaren in de code.
* Op basis van een Element o, kijk in welke richten er gegaan moet worden
* om dichter bij dit element te komen
* @param o het element waarmee vergeleken wordt
* @return een van de kinderen van deze node
*/ | block_comment | nl | package oplossing;
public class Node233<E extends Comparable<E>> extends Node<E>{
private Node233<E> leftChild;
private Node233<E> middleChild;
private Node233<E> rightChild;
public Node233(E leftValue, E rightValue) {
super(leftValue, rightValue);
}
/**
* Kleine functie om<SUF>*/
public Node233<E> getChild(E o) {
if (hasLeftValue() && leftValue.compareTo(o) > 0) {
return getLeftChild();
}
if (hasRightValue() && rightValue.compareTo(o) < 0) {
return getRightChild();
}
return getMiddleChild();
}
/**
* Gegeven een nieuw kind, adopteer hem op de juiste plaats.
* @param newNode het kind dat geadopteerd zal worden.
*/
public void setChild(Node233<E> newNode){
E o = newNode.leftValue;
if (hasLeftValue() && leftValue.compareTo(o) > 0) {
setLeftChild(newNode);
} else if (hasRightValue() && rightValue.compareTo(o) < 0) {
setRightChild(newNode);
} else {
setMiddleChild(newNode);
}
}
/**
* Het rechter kind van de parent (deze node dus) in de parent brengen
* Kan enkel wanneer deze node en de parent maar één sleutel hebben
*/
private void percolateUpFromRight(Node233<E> parent){
parent.rightValue = leftValue;
parent.setMiddleChild(getLeftChild());
parent.setRightChild(getMiddleChild());
}
/**
* Zelfde percolateUpFromRight maar dan vanaf links
*/
private void percolateUpFromLeft(Node233<E> parent) {
parent.rightValue = leftValue;
parent.swapValues();
parent.setLeftChild(getLeftChild());
parent.setRightChild(parent.getMiddleChild());
parent.setMiddleChild(getMiddleChild());
}
public void percolateUp(Node233<E> parent, E o) {
if (!parent.hasLeftValue() || parent.leftValue.compareTo(o) > 0) {
percolateUpFromLeft(parent);
} else {
percolateUpFromRight(parent);
}
}
/**
* maakt van een deelboom met twee toppen en drie sleutels een binaire boom:
*
* [ B ]
* / \
* [ A ] [ C ]
*
* @param o linkerwaarde in de laagste node
*/
public void convertToBinary(E o){
if (rightValue.compareTo(o) < 0) {
convertToBinaryFromRight();
} else if (leftValue.compareTo(o) > 0){
convertToBinaryFromLeft();
} else {
convertToBinaryFromMiddle();
}
}
/**
* startpositie
*
* [ A B ]
* \
* [ C ]
*/
private void convertToBinaryFromRight() {
Node233<E> linkerNode = new Node233<>(leftValue, null);
linkerNode.setLeftChild(getLeftChild());
linkerNode.setMiddleChild(getMiddleChild());
leftValue = rightValue;
setLeftChild(linkerNode);
setMiddleChild(getRightChild());
rightValue = null;
setRightChild(null);
}
/**
* startpositie
*
* [ B C ]
* /
* [ A ]
*/
private void convertToBinaryFromLeft() {
Node233<E> rechterNode = new Node233<>(rightValue, null);
rechterNode.setLeftChild(getMiddleChild());
rechterNode.setMiddleChild(getRightChild());
setMiddleChild(rechterNode);
rightValue = null;
setRightChild(null);
}
/**
* startpositie
*
* [ A C ]
* |
* [ B ]
*/
private void convertToBinaryFromMiddle() {
Node233<E> linkerNode = new Node233<>(leftValue, null);
Node233<E> rechterNode = new Node233<>(rightValue, null);
linkerNode.setLeftChild(getLeftChild());
linkerNode.setMiddleChild(getMiddleChild().getLeftChild());
rechterNode.setMiddleChild(getRightChild());
rechterNode.setLeftChild(getMiddleChild().getMiddleChild());
leftValue = getMiddleChild().leftValue;
setLeftChild(linkerNode);
setMiddleChild(rechterNode);
rightValue = null;
setRightChild(null);
}
/**
* De verwijderNode zit in het midden en gebruikt gebruikt zijn midden-sibling om zichzelf op te vullen
*/
private void redistributeFromLeft(Node233<E> verwijderNode){
verwijderNode.leftValue = leftValue;
leftValue = getMiddleChild().leftValue;
getMiddleChild().leftValue = getMiddleChild().rightValue;
getMiddleChild().rightValue = null;
verwijderNode.setLeftChild(verwijderNode.getMiddleChild());
verwijderNode.setMiddleChild(getMiddleChild().getLeftChild());
getMiddleChild().setLeftChild(getMiddleChild().getMiddleChild());
getMiddleChild().setMiddleChild(getMiddleChild().getRightChild());
getMiddleChild().setRightChild(null);
}
/**
* De verwijderNode zit in het midden en gebruikt zijn linker-sibling met twee sleutels
*/
private void redistributeFromMiddle1(Node233<E> verwijderNode) {
verwijderNode.leftValue = leftValue;
leftValue = getLeftChild().rightValue;
getLeftChild().rightValue = null;
getMiddleChild().setLeftChild(getLeftChild().getRightChild());
getLeftChild().setRightChild(null);
}
/**
* De verwijderNode zit in het midden en gebruikt zijn rechter-sibling met twee sleutels
*/
private void redistributeFromMiddle2(Node233<E> verwijderNode) {
verwijderNode.leftValue = rightValue;
rightValue = getRightChild().leftValue;
getRightChild().leftValue = getRightChild().rightValue;
getRightChild().rightValue = null;
verwijderNode.setLeftChild(verwijderNode.getMiddleChild());
verwijderNode.setMiddleChild(getRightChild().getLeftChild());
getRightChild().setLeftChild(getRightChild().getMiddleChild());
getRightChild().setMiddleChild(getRightChild().getRightChild());
getRightChild().setRightChild(null);
}
/**
* De verwijderNode zit rechts en zijn midden-sibling heeft twee nodes
*/
private void redistributeFromRight(Node233<E> verwijderNode) {
verwijderNode.leftValue = rightValue;
rightValue = getMiddleChild().rightValue;
getMiddleChild().rightValue = null;
getRightChild().setLeftChild(getMiddleChild().getRightChild());
getMiddleChild().setRightChild(null);
}
/**
* Gebruik Een node met twee sleutels naast de verwijderNode
* @param verwijderNode de lege node die heropgevuld moet worden.
* @return false als er geen herdistributie is gebeurt
*/
public boolean redistribute(Node233<E> verwijderNode) {
if (verwijderNode == getLeftChild() && getMiddleChild().numberOfKeys() == 2){
redistributeFromLeft(verwijderNode);
return true;
} else if (verwijderNode == getMiddleChild() && getLeftChild().numberOfKeys() == 2) {
redistributeFromMiddle1(verwijderNode);
return true;
} else if (verwijderNode == getMiddleChild() && getRightChild() != null && getRightChild().numberOfKeys() == 2) {
redistributeFromMiddle2(verwijderNode);
return true;
} else if (verwijderNode == getRightChild() && getMiddleChild().numberOfKeys() == 2) {
redistributeFromRight(verwijderNode);
return true;
}
return false;
}
private void mergeIntoLeftChild() {
getLeftChild().leftValue = leftValue;
getLeftChild().rightValue = getMiddleChild().leftValue;
leftValue = null;
swapValues();
getLeftChild().setLeftChild(getLeftChild().getMiddleChild());
getLeftChild().setMiddleChild(getMiddleChild().getLeftChild());
getLeftChild().setRightChild(getMiddleChild().getMiddleChild());
setMiddleChild(getRightChild());
setRightChild(null);
}
private void mergeIntoMiddleChild() {
getLeftChild().rightValue = leftValue;
leftValue = rightValue;
rightValue = null;
getLeftChild().setRightChild(getMiddleChild().getMiddleChild());
setMiddleChild(getRightChild());
setRightChild(null);
}
private void mergeIntoRightChild() {
getMiddleChild().rightValue = rightValue;
rightValue = null;
getMiddleChild().setRightChild(getRightChild().getMiddleChild());
setRightChild(null);
}
/**
* Wanneer deze node twee sleutels heeft, kan een van de kinderen de lege node invullen met een van zijn sleutels,
* Een gat dat daar zou kunnen ontstaan wordt op zijn beurt opgevuld door een van de sleutels uit deze node.
* @param verwijderNode De lege node waarin gemerged moet worden
*/
public void mergeIntoChild(Node233<E> verwijderNode) {
if (getLeftChild() == verwijderNode){
mergeIntoLeftChild();
} else if (getMiddleChild() == verwijderNode){
mergeIntoMiddleChild();
} else if (getRightChild() == verwijderNode) {
mergeIntoRightChild();
}
}
/**
* startpositie
* [ B ]
* /
* [ A ]
*
*/
private void geval2NodesLeft(Node233<E> verwijderNode) {
verwijderNode.leftValue = leftValue;
leftValue = null;
verwijderNode.rightValue = getMiddleChild().leftValue;
verwijderNode.setLeftChild(verwijderNode.getMiddleChild());
verwijderNode.setMiddleChild(getMiddleChild().getLeftChild());
verwijderNode.setRightChild(getMiddleChild().getMiddleChild());
setMiddleChild(getLeftChild());
setLeftChild(null); // TODO het kind van de (null, null) node niet middle child laten zijn maar leftchild
}
/**
* startpositie
* [ A ]
* \
* [ B ]
*/
private void geval2NodesMiddle(Node233<E> verwijderNode) {
verwijderNode.rightValue = leftValue;
verwijderNode.setRightChild(getMiddleChild().getMiddleChild());
leftValue = null;
getMiddleChild().leftValue = getLeftChild().leftValue;
getMiddleChild().setMiddleChild(getLeftChild().getMiddleChild());
getMiddleChild().setLeftChild(getLeftChild().getLeftChild());
setLeftChild(null);
}
/**
* Leeg
* |
* [ A B ]
*
*/
public void geval2nodes(Node233<E> verwijderNode){
if (verwijderNode == getLeftChild()) {
geval2NodesLeft(verwijderNode);
} else {
geval2NodesMiddle(verwijderNode);
}
}
public boolean isLeaf(){
return this.getLeftChild() == null;
}
public Node233<E> getLeftChild() {
return leftChild;
}
public void setLeftChild(Node233<E> leftChild) {
this.leftChild = leftChild;
}
public Node233<E> getMiddleChild() {
return middleChild;
}
public void setMiddleChild(Node233<E> middleChild) {
this.middleChild = middleChild;
}
public Node233<E> getRightChild() {
return rightChild;
}
public void setRightChild(Node233<E> rightChild) {
this.rightChild = rightChild;
}
} | false | 2,876 | 83 | 3,084 | 86 | 3,144 | 74 | 3,084 | 86 | 3,444 | 87 | false | false | false | false | false | true |
577 | 28782_8 | package be.intecbrussel;
import java.util.Random;
public class MainApp {
public static void main(String[] args) {
System.out.println("Github");
System.out.println("---- Oefening 1 ----");
// Maak een applicatie die kan controleren of een bepaald woord een palindroom is.
String word = "meetsysteem";
String wordReverse = "";
StringBuilder str = new StringBuilder(word);
wordReverse = str.reverse().toString();
if (word.equals(wordReverse)) {
System.out.println(word + " = " + wordReverse + ".");
System.out.println(word + " is wel een palindroom!");
} else {
System.out.println(word + " != " + wordReverse + ".");
System.out.println(word + " is geen palindroom!");
}
System.out.println("---- Oefening 2 ----");
// Maak een applicatie die volgende tekst The Quick BroWn FoX!
// Omzet naar enkel kleine letters.
String text = "The Quick BroWn FoX!";
StringBuilder lowercase = new StringBuilder(text.toLowerCase());
System.out.println(lowercase);
System.out.println("---- StringBuilder - oefenreeks 1 ----");
System.out.println("---- Oefening - 1 ----");
// 1. Maak een stringBuilder aan en voeg een string toe. Print de stringBuilder naar de console.
StringBuilder str1 = new StringBuilder("Hello World!");
System.out.println(str1);
System.out.println("---- Oefening - 2 ----");
// 2. Gebruik de .length() eigenschap om de lengte van een string of stringBuilder te bepalen.
StringBuilder str2 = new StringBuilder("Hello World");
System.out.println(str2.length());
System.out.println("---- Oefening - 3 ----");
// 3. Gebruik de .substring() methode om een deel van een string of stringBuilder
// te selecteren en print dit naar de console.
StringBuilder str3 = new StringBuilder("Hello World");
System.out.println(str3.substring(6, 11));
System.out.println("---- Oefening - 4 ----");
// 4. Gebruik de .delete() methode om een deel van een stringBuilder te verwijderen.
StringBuilder str4 = new StringBuilder("Hello World Wold");
System.out.println(str4.delete(12,17));
System.out.println("---- Oefening - 5 ----");
// 5. Gebruik de .insert() methode om een string toe te voegen aan een specifieke index in een stringBuilder.
StringBuilder str5 = new StringBuilder("Let's");
str5.insert(5, " go");
System.out.println(str5);
System.out.println("---- Oefening - 6 ----");
// 6. Gebruik de .replace() methode om een specifieke string te vervangen door een andere string in een stringBuilder.
StringBuilder strReplace = new StringBuilder("Hello world!");
strReplace.replace(0,12, "Hallo wereld!");
System.out.println(strReplace);
System.out.println("---- Oefening - 7 ----");
// 7. Gebruik de .toString() methode om de inhoud van een stringBuilder om te zetten naar een string.
StringBuilder str6 = new StringBuilder("Hello, my name is Gabriel.");
String str7 = str6.toString();
System.out.println(str7);
System.out.println("---- Oefening - 7 ----");
// 8. Gebruik de .append() methode om een string toe te voegen aan een stringBuilder.
StringBuilder str8 = new StringBuilder("Hi,");
String endOfSentence = " my name is Jos";
str8.append(endOfSentence);
System.out.println(str8);
}
}
| Gabe-Alvess/StringbuilderOefeningen | src/be/intecbrussel/MainApp.java | 1,037 | // 5. Gebruik de .insert() methode om een string toe te voegen aan een specifieke index in een stringBuilder. | line_comment | nl | package be.intecbrussel;
import java.util.Random;
public class MainApp {
public static void main(String[] args) {
System.out.println("Github");
System.out.println("---- Oefening 1 ----");
// Maak een applicatie die kan controleren of een bepaald woord een palindroom is.
String word = "meetsysteem";
String wordReverse = "";
StringBuilder str = new StringBuilder(word);
wordReverse = str.reverse().toString();
if (word.equals(wordReverse)) {
System.out.println(word + " = " + wordReverse + ".");
System.out.println(word + " is wel een palindroom!");
} else {
System.out.println(word + " != " + wordReverse + ".");
System.out.println(word + " is geen palindroom!");
}
System.out.println("---- Oefening 2 ----");
// Maak een applicatie die volgende tekst The Quick BroWn FoX!
// Omzet naar enkel kleine letters.
String text = "The Quick BroWn FoX!";
StringBuilder lowercase = new StringBuilder(text.toLowerCase());
System.out.println(lowercase);
System.out.println("---- StringBuilder - oefenreeks 1 ----");
System.out.println("---- Oefening - 1 ----");
// 1. Maak een stringBuilder aan en voeg een string toe. Print de stringBuilder naar de console.
StringBuilder str1 = new StringBuilder("Hello World!");
System.out.println(str1);
System.out.println("---- Oefening - 2 ----");
// 2. Gebruik de .length() eigenschap om de lengte van een string of stringBuilder te bepalen.
StringBuilder str2 = new StringBuilder("Hello World");
System.out.println(str2.length());
System.out.println("---- Oefening - 3 ----");
// 3. Gebruik de .substring() methode om een deel van een string of stringBuilder
// te selecteren en print dit naar de console.
StringBuilder str3 = new StringBuilder("Hello World");
System.out.println(str3.substring(6, 11));
System.out.println("---- Oefening - 4 ----");
// 4. Gebruik de .delete() methode om een deel van een stringBuilder te verwijderen.
StringBuilder str4 = new StringBuilder("Hello World Wold");
System.out.println(str4.delete(12,17));
System.out.println("---- Oefening - 5 ----");
// 5. Gebruik<SUF>
StringBuilder str5 = new StringBuilder("Let's");
str5.insert(5, " go");
System.out.println(str5);
System.out.println("---- Oefening - 6 ----");
// 6. Gebruik de .replace() methode om een specifieke string te vervangen door een andere string in een stringBuilder.
StringBuilder strReplace = new StringBuilder("Hello world!");
strReplace.replace(0,12, "Hallo wereld!");
System.out.println(strReplace);
System.out.println("---- Oefening - 7 ----");
// 7. Gebruik de .toString() methode om de inhoud van een stringBuilder om te zetten naar een string.
StringBuilder str6 = new StringBuilder("Hello, my name is Gabriel.");
String str7 = str6.toString();
System.out.println(str7);
System.out.println("---- Oefening - 7 ----");
// 8. Gebruik de .append() methode om een string toe te voegen aan een stringBuilder.
StringBuilder str8 = new StringBuilder("Hi,");
String endOfSentence = " my name is Jos";
str8.append(endOfSentence);
System.out.println(str8);
}
}
| false | 828 | 30 | 929 | 31 | 926 | 25 | 929 | 31 | 1,025 | 32 | false | false | false | false | false | true |
2,473 | 184673_3 | package be.pxl.ja.opgave1;
import java.util.List;
public class BuildingApp2TIN {
private List<Building> buildings;
public BuildingApp2TIN() {
// TODO: read data from file buildings.csv and assign to buildings
}
// 1. Geef het aantal buildings van vóór het jaar 1970 (1970 excl.)
public long solution1() {
// TODO
throw new UnsupportedOperationException();
}
// 2. Geef de naam van de hoogste building
public String solution2() {
// TODO
throw new UnsupportedOperationException();
}
// 3. Hoeveel van de buildings worden gebruikt als hotel?
public long solution3() {
// TODO
throw new UnsupportedOperationException();
}
// 4. Geef een tekst met de verschillende landen: geen dubbels, alfabetisch gesorteerd en gescheiden met een komma.
public String solution4() {
// TODO
throw new UnsupportedOperationException();
}
// 5. Geef een lijst van alle buildings met type SKYSCRAPER van het jaar 2000. Sorteer de buildings alfabetisch (A -> Z) op city.
public List<Building> solution5() {
// TODO
throw new UnsupportedOperationException();
}
}
| custersnele/JavaAdv_examen_21_22_zit1 | src/main/java/be/pxl/ja/opgave1/BuildingApp2TIN.java | 341 | // 3. Hoeveel van de buildings worden gebruikt als hotel? | line_comment | nl | package be.pxl.ja.opgave1;
import java.util.List;
public class BuildingApp2TIN {
private List<Building> buildings;
public BuildingApp2TIN() {
// TODO: read data from file buildings.csv and assign to buildings
}
// 1. Geef het aantal buildings van vóór het jaar 1970 (1970 excl.)
public long solution1() {
// TODO
throw new UnsupportedOperationException();
}
// 2. Geef de naam van de hoogste building
public String solution2() {
// TODO
throw new UnsupportedOperationException();
}
// 3. Hoeveel<SUF>
public long solution3() {
// TODO
throw new UnsupportedOperationException();
}
// 4. Geef een tekst met de verschillende landen: geen dubbels, alfabetisch gesorteerd en gescheiden met een komma.
public String solution4() {
// TODO
throw new UnsupportedOperationException();
}
// 5. Geef een lijst van alle buildings met type SKYSCRAPER van het jaar 2000. Sorteer de buildings alfabetisch (A -> Z) op city.
public List<Building> solution5() {
// TODO
throw new UnsupportedOperationException();
}
}
| false | 289 | 16 | 344 | 17 | 318 | 15 | 344 | 17 | 367 | 17 | false | false | false | false | false | true |
3,644 | 57384_2 | package lingo;_x000D_
_x000D_
import java.awt.Color;_x000D_
import java.awt.Dimension;_x000D_
import java.awt.Font;_x000D_
import java.awt.Graphics;_x000D_
import java.awt.LayoutManager;_x000D_
_x000D_
/**_x000D_
* Deze klasse beschrijft het aanmaken van een raster als ook de letters die gedrukt worden in de gui. _x000D_
* _x000D_
* @Author Snoeck Seppe_x000D_
* @Version 1.0 24/08/2015 13:00_x000D_
**/_x000D_
public class Raster extends javax.swing.JPanel {_x000D_
_x000D_
/**_x000D_
* Creates new form Raster_x000D_
*/ _x000D_
Lingo lingo;_x000D_
_x000D_
String inputWoord = " ";_x000D_
_x000D_
public Raster() {_x000D_
initComponents();_x000D_
}_x000D_
_x000D_
@Override_x000D_
public void paintComponent(Graphics g) {_x000D_
for (int y = 0; y < 360; y +=60) {_x000D_
int i = 0;_x000D_
for (int x = 0; x < 300; x +=60) {_x000D_
printKot(g,x,y);_x000D_
printLetter(g,x,y,i);_x000D_
i++;_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
public Raster(String inputwoord) {_x000D_
this.inputWoord = inputwoord;_x000D_
}_x000D_
_x000D_
/**_x000D_
*_x000D_
* @param g Graphics_x000D_
* @param x Een coördinaat op de x-as_x000D_
* @param y Een coördinaat op de y-as_x000D_
*/_x000D_
public void printKot(Graphics g, int x, int y) {_x000D_
g.drawRect(x, y, 60, 60); _x000D_
}_x000D_
_x000D_
/**_x000D_
*_x000D_
* @param g Graphics_x000D_
* @param x Een coördinaat op de x-as_x000D_
* @param y Een coördinaat op de y-as_x000D_
* @param i Een teller om alle letter van het woord te doorlopen_x000D_
*/_x000D_
public void printLetter(Graphics g, int x, int y, int i) {_x000D_
g.setFont(new Font("TimesRoman", Font.BOLD, 40)); _x000D_
g.setColor(Color.red);_x000D_
g.drawString(Character.toString(inputWoord.charAt(i)), 15 + x, 40 + y);_x000D_
g.setColor(Color.black);_x000D_
}_x000D_
_x000D_
/**_x000D_
* This method is called from within the constructor to initialize the form._x000D_
* WARNING: Do NOT modify this code. The content of this method is always_x000D_
* regenerated by the Form Editor._x000D_
*/_x000D_
@SuppressWarnings("unchecked")_x000D_
// <editor-fold defaultstate="collapsed" desc="Generated Code"> _x000D_
private void initComponents() {_x000D_
_x000D_
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);_x000D_
this.setLayout(layout);_x000D_
layout.setHorizontalGroup(_x000D_
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)_x000D_
.addGap(0, 400, Short.MAX_VALUE)_x000D_
);_x000D_
layout.setVerticalGroup(_x000D_
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)_x000D_
.addGap(0, 300, Short.MAX_VALUE)_x000D_
);_x000D_
}// </editor-fold> _x000D_
_x000D_
// Variables declaration - do not modify _x000D_
// End of variables declaration _x000D_
} | micabressan/trabajo_final | codes/H0MHPQHe.Java | 903 | /**_x000D_
*_x000D_
* @param g Graphics_x000D_
* @param x Een coördinaat op de x-as_x000D_
* @param y Een coördinaat op de y-as_x000D_
*/ | block_comment | nl | package lingo;_x000D_
_x000D_
import java.awt.Color;_x000D_
import java.awt.Dimension;_x000D_
import java.awt.Font;_x000D_
import java.awt.Graphics;_x000D_
import java.awt.LayoutManager;_x000D_
_x000D_
/**_x000D_
* Deze klasse beschrijft het aanmaken van een raster als ook de letters die gedrukt worden in de gui. _x000D_
* _x000D_
* @Author Snoeck Seppe_x000D_
* @Version 1.0 24/08/2015 13:00_x000D_
**/_x000D_
public class Raster extends javax.swing.JPanel {_x000D_
_x000D_
/**_x000D_
* Creates new form Raster_x000D_
*/ _x000D_
Lingo lingo;_x000D_
_x000D_
String inputWoord = " ";_x000D_
_x000D_
public Raster() {_x000D_
initComponents();_x000D_
}_x000D_
_x000D_
@Override_x000D_
public void paintComponent(Graphics g) {_x000D_
for (int y = 0; y < 360; y +=60) {_x000D_
int i = 0;_x000D_
for (int x = 0; x < 300; x +=60) {_x000D_
printKot(g,x,y);_x000D_
printLetter(g,x,y,i);_x000D_
i++;_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
public Raster(String inputwoord) {_x000D_
this.inputWoord = inputwoord;_x000D_
}_x000D_
_x000D_
/**_x000D_
*_x000D_
* @param g Graphics_x000D_<SUF>*/_x000D_
public void printKot(Graphics g, int x, int y) {_x000D_
g.drawRect(x, y, 60, 60); _x000D_
}_x000D_
_x000D_
/**_x000D_
*_x000D_
* @param g Graphics_x000D_
* @param x Een coördinaat op de x-as_x000D_
* @param y Een coördinaat op de y-as_x000D_
* @param i Een teller om alle letter van het woord te doorlopen_x000D_
*/_x000D_
public void printLetter(Graphics g, int x, int y, int i) {_x000D_
g.setFont(new Font("TimesRoman", Font.BOLD, 40)); _x000D_
g.setColor(Color.red);_x000D_
g.drawString(Character.toString(inputWoord.charAt(i)), 15 + x, 40 + y);_x000D_
g.setColor(Color.black);_x000D_
}_x000D_
_x000D_
/**_x000D_
* This method is called from within the constructor to initialize the form._x000D_
* WARNING: Do NOT modify this code. The content of this method is always_x000D_
* regenerated by the Form Editor._x000D_
*/_x000D_
@SuppressWarnings("unchecked")_x000D_
// <editor-fold defaultstate="collapsed" desc="Generated Code"> _x000D_
private void initComponents() {_x000D_
_x000D_
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);_x000D_
this.setLayout(layout);_x000D_
layout.setHorizontalGroup(_x000D_
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)_x000D_
.addGap(0, 400, Short.MAX_VALUE)_x000D_
);_x000D_
layout.setVerticalGroup(_x000D_
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)_x000D_
.addGap(0, 300, Short.MAX_VALUE)_x000D_
);_x000D_
}// </editor-fold> _x000D_
_x000D_
// Variables declaration - do not modify _x000D_
// End of variables declaration _x000D_
} | false | 1,226 | 72 | 1,345 | 79 | 1,385 | 80 | 1,345 | 79 | 1,475 | 81 | false | false | false | false | false | true |
1,232 | 74843_0 | package be.odisee;
/**
* Een eenvoudige teller welke per 1 omhoog kan
*/
public class Teller {
private int waarde;
private boolean tellerStaatAan;
/**
* Default constructor: een Teller-object wordt aangemaakt
* met waarde 0 en is uitgeschakeld.
*/
public Teller(){
this.waarde = 0;
this.tellerStaatAan = false;
}
/**
* Vermeerder waarde van Teller met 1.
* Heeft geen effect als de teller uit staat.
*/
public void increment(){
if (tellerStaatAan){
this.waarde++;
}
}
/**
* Zet waarde van Teller op 0.
* Heeft geen effect als de teller uit staat.
*/
public void reset(){
if (tellerStaatAan){
this.waarde = 0;
}
}
/**
* Waarde van de teller. Indien de teller uitstaat, geef nul terug.
* @return waarde van de Teller
*/
public int getWaarde(){
if (tellerStaatAan) {
return this.waarde;
} else {
return 0;
}
}
/** Zet teller aan en zet waarde op 0 */
public void zetTellerAan(){
this.tellerStaatAan = true;
this.waarde = 0;
}
/** Zet teller uit en zet waarde op 0 */
public void zetTellerUit(){
this.tellerStaatAan = false;
this.waarde = 0;
}
/** Controleer of de teller aanstaat
* @return true als de Teller aan staat
*/
public boolean staatTellerAan(){
return this.tellerStaatAan;
}
}
| OdiseeSEF2324/Leerstof-klas-5-6 | Les 2/Demos/Teller/src/main/java/be/odisee/Teller.java | 506 | /**
* Een eenvoudige teller welke per 1 omhoog kan
*/ | block_comment | nl | package be.odisee;
/**
* Een eenvoudige teller<SUF>*/
public class Teller {
private int waarde;
private boolean tellerStaatAan;
/**
* Default constructor: een Teller-object wordt aangemaakt
* met waarde 0 en is uitgeschakeld.
*/
public Teller(){
this.waarde = 0;
this.tellerStaatAan = false;
}
/**
* Vermeerder waarde van Teller met 1.
* Heeft geen effect als de teller uit staat.
*/
public void increment(){
if (tellerStaatAan){
this.waarde++;
}
}
/**
* Zet waarde van Teller op 0.
* Heeft geen effect als de teller uit staat.
*/
public void reset(){
if (tellerStaatAan){
this.waarde = 0;
}
}
/**
* Waarde van de teller. Indien de teller uitstaat, geef nul terug.
* @return waarde van de Teller
*/
public int getWaarde(){
if (tellerStaatAan) {
return this.waarde;
} else {
return 0;
}
}
/** Zet teller aan en zet waarde op 0 */
public void zetTellerAan(){
this.tellerStaatAan = true;
this.waarde = 0;
}
/** Zet teller uit en zet waarde op 0 */
public void zetTellerUit(){
this.tellerStaatAan = false;
this.waarde = 0;
}
/** Controleer of de teller aanstaat
* @return true als de Teller aan staat
*/
public boolean staatTellerAan(){
return this.tellerStaatAan;
}
}
| false | 442 | 20 | 474 | 23 | 437 | 16 | 474 | 23 | 524 | 21 | false | false | false | false | false | true |
524 | 12211_1 | package program;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
public class Controller /*implements Runnable*/{
private List<String> checkedUrls = new ArrayList();
private List<String> brokenUrls = new ArrayList();
//private String theUrl; //enkel voor multithreading
/**
* De list leeg maken.
*/
public void resetCheckedUrls(){
checkedUrls.clear();
}
/**
* De list leeg maken.
*/
public void resetBrokenUrls(){
brokenUrls.clear();
}
/* Enkel voor
@Override
public void run(){
getWebpage(theUrl);
}*/
/**
* valideert of de url een lokale url is.
* @param url
* @return
*/
public static boolean validateUrl(String url) {
return url.matches("((https?://)?localhost){1}([a-zA-Z0-9]*)?/?([a-zA-Z0-9\\:\\-\\._\\?\\,\\'/\\\\\\+&%\\$#\\=~])*");
}
/**
* Poging om de header(HEAD) van een website te krijgen.
* Krijgen we een header, wilt dit zeggen dat de link werkt, anders werkt de link niet.
* @param targetUrl
* @return
* http://singztechmusings.wordpress.com/2011/05/26/java-how-to-check-if-a-web-page-exists-and-is-available/
*/
public static boolean urlExists(String targetUrl) {
HttpURLConnection httpUrlConn;
try {
httpUrlConn = (HttpURLConnection) new URL(targetUrl)
.openConnection();
httpUrlConn.setRequestMethod("HEAD");
// Set timeouts in milliseconds
httpUrlConn.setConnectTimeout(30000);
httpUrlConn.setReadTimeout(30000);
// Print HTTP status code/message for your information.
System.out.println("Response Code: "
+ httpUrlConn.getResponseCode());
System.out.println("Response Message: "
+ httpUrlConn.getResponseMessage() +" - " + targetUrl);
return (httpUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
return false;
}
}
/**
* In de huidige lijn wordt gekeken of er "<a href=" gevonden wordt want dit wil zeggen dat daarachter een link staat.
* @param line
* @return
**/
public static boolean checkForUrl(String line){
return line.matches("(.)*(<a href=){1}(.)*");
}
/**
* controleert of de url nog nagekeken is.
* @param url
* @return
**/
public boolean notYetChecked(String url){
for(String s:checkedUrls){
if(url.equals(s)) return false;
}
return true;
}
/**
* Heel de webpagina wordt ingeladen en er wordt naar links gezocht.
* @param url
* @return
**/
public List[] getWebpage(String url){
List[] allUrls = new List[2];
String address = "127.0.0.1";
int port = 80;
String get = url.split("http://localhost")[1];
String header = "GET " + get + " HTTP/1.1\n"
+ "Host: localhost\n"
+ "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.8) Gecko/20100723 Ubuntu/10.04 (lucid) Firefox/3.6.8\n"
+ "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\n"
+ "Accept-Language: en-us,en;q=0.5\n"
+ "Accept-Encoding: gzip,deflate\n"
+ "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\n"
+ "Keep-Alive: 115\n"
+ "Connection: keep-alive\n"
+ "\r\n";
String link;
//url toevoegen aan de lijst met reeds gecontroleerde url's.
checkedUrls.add(url);
try {
//nieuwe socket aanmaken
Socket sck = new Socket(address, port);
//website inlezen
BufferedReader rd = new BufferedReader(new InputStreamReader(sck.getInputStream()));
BufferedWriter wr = new BufferedWriter(
new OutputStreamWriter(sck.getOutputStream(), "ISO-8859-1"));
wr.write(header);
wr.flush();
System.out.println("REQUEST HEADER");
System.out.println(header);
System.out.println("RESPONSE HEADER");
String line;
//1 voor 1 elke lijn afgaan.
while ((line = rd.readLine()) != null) {
//System.out.println(line);
if(checkForUrl(line)){
//Er staat een url op deze lijn.
//tekst splitsen waar 'a href="' staat.
String[] parts = line.split("a href=\"");
for(int i=0; i<parts.length; i++){
if(parts[i].matches("http.*")){
//Dit gesplitste deel bevat een url met mss nog wat overbodige tekst achter.
//verwijderen van tekst die nog achter de link staat.
link = parts[i].substring(0, parts[i].indexOf("\""));
if(urlExists(link)){
//De url is een werkende url
if(validateUrl(link) && notYetChecked(link) && !link.matches("(.)*.(pdf|jpg|png)")){
//link is een lokale url die nog niet gecontroleerd is.
/*theUrl = link;
Thread t = new Thread();
t.start();*/
getWebpage(link);
} else {}
}else{
//deze url is "broken"
brokenUrls.add("Broken link:\t" + link + "\n On page:\t" + url + "\n\n");
}
}
}
}
}
wr.close();
rd.close();
sck.close();
} catch (Exception e) {
e.printStackTrace();
}
//alle pagina's die gecontroleerd zijn.
allUrls[0] = checkedUrls;
//alle url's die een foutmelding gaven.
allUrls[1] = brokenUrls;
return allUrls;
}
} | FestiPedia-Java/JavaApplication | Linkrot/src/program/Controller.java | 1,963 | /**
* De list leeg maken.
*/ | block_comment | nl | package program;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
public class Controller /*implements Runnable*/{
private List<String> checkedUrls = new ArrayList();
private List<String> brokenUrls = new ArrayList();
//private String theUrl; //enkel voor multithreading
/**
* De list leeg<SUF>*/
public void resetCheckedUrls(){
checkedUrls.clear();
}
/**
* De list leeg maken.
*/
public void resetBrokenUrls(){
brokenUrls.clear();
}
/* Enkel voor
@Override
public void run(){
getWebpage(theUrl);
}*/
/**
* valideert of de url een lokale url is.
* @param url
* @return
*/
public static boolean validateUrl(String url) {
return url.matches("((https?://)?localhost){1}([a-zA-Z0-9]*)?/?([a-zA-Z0-9\\:\\-\\._\\?\\,\\'/\\\\\\+&%\\$#\\=~])*");
}
/**
* Poging om de header(HEAD) van een website te krijgen.
* Krijgen we een header, wilt dit zeggen dat de link werkt, anders werkt de link niet.
* @param targetUrl
* @return
* http://singztechmusings.wordpress.com/2011/05/26/java-how-to-check-if-a-web-page-exists-and-is-available/
*/
public static boolean urlExists(String targetUrl) {
HttpURLConnection httpUrlConn;
try {
httpUrlConn = (HttpURLConnection) new URL(targetUrl)
.openConnection();
httpUrlConn.setRequestMethod("HEAD");
// Set timeouts in milliseconds
httpUrlConn.setConnectTimeout(30000);
httpUrlConn.setReadTimeout(30000);
// Print HTTP status code/message for your information.
System.out.println("Response Code: "
+ httpUrlConn.getResponseCode());
System.out.println("Response Message: "
+ httpUrlConn.getResponseMessage() +" - " + targetUrl);
return (httpUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
return false;
}
}
/**
* In de huidige lijn wordt gekeken of er "<a href=" gevonden wordt want dit wil zeggen dat daarachter een link staat.
* @param line
* @return
**/
public static boolean checkForUrl(String line){
return line.matches("(.)*(<a href=){1}(.)*");
}
/**
* controleert of de url nog nagekeken is.
* @param url
* @return
**/
public boolean notYetChecked(String url){
for(String s:checkedUrls){
if(url.equals(s)) return false;
}
return true;
}
/**
* Heel de webpagina wordt ingeladen en er wordt naar links gezocht.
* @param url
* @return
**/
public List[] getWebpage(String url){
List[] allUrls = new List[2];
String address = "127.0.0.1";
int port = 80;
String get = url.split("http://localhost")[1];
String header = "GET " + get + " HTTP/1.1\n"
+ "Host: localhost\n"
+ "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.8) Gecko/20100723 Ubuntu/10.04 (lucid) Firefox/3.6.8\n"
+ "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\n"
+ "Accept-Language: en-us,en;q=0.5\n"
+ "Accept-Encoding: gzip,deflate\n"
+ "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\n"
+ "Keep-Alive: 115\n"
+ "Connection: keep-alive\n"
+ "\r\n";
String link;
//url toevoegen aan de lijst met reeds gecontroleerde url's.
checkedUrls.add(url);
try {
//nieuwe socket aanmaken
Socket sck = new Socket(address, port);
//website inlezen
BufferedReader rd = new BufferedReader(new InputStreamReader(sck.getInputStream()));
BufferedWriter wr = new BufferedWriter(
new OutputStreamWriter(sck.getOutputStream(), "ISO-8859-1"));
wr.write(header);
wr.flush();
System.out.println("REQUEST HEADER");
System.out.println(header);
System.out.println("RESPONSE HEADER");
String line;
//1 voor 1 elke lijn afgaan.
while ((line = rd.readLine()) != null) {
//System.out.println(line);
if(checkForUrl(line)){
//Er staat een url op deze lijn.
//tekst splitsen waar 'a href="' staat.
String[] parts = line.split("a href=\"");
for(int i=0; i<parts.length; i++){
if(parts[i].matches("http.*")){
//Dit gesplitste deel bevat een url met mss nog wat overbodige tekst achter.
//verwijderen van tekst die nog achter de link staat.
link = parts[i].substring(0, parts[i].indexOf("\""));
if(urlExists(link)){
//De url is een werkende url
if(validateUrl(link) && notYetChecked(link) && !link.matches("(.)*.(pdf|jpg|png)")){
//link is een lokale url die nog niet gecontroleerd is.
/*theUrl = link;
Thread t = new Thread();
t.start();*/
getWebpage(link);
} else {}
}else{
//deze url is "broken"
brokenUrls.add("Broken link:\t" + link + "\n On page:\t" + url + "\n\n");
}
}
}
}
}
wr.close();
rd.close();
sck.close();
} catch (Exception e) {
e.printStackTrace();
}
//alle pagina's die gecontroleerd zijn.
allUrls[0] = checkedUrls;
//alle url's die een foutmelding gaven.
allUrls[1] = brokenUrls;
return allUrls;
}
} | false | 1,479 | 11 | 1,623 | 11 | 1,750 | 13 | 1,623 | 11 | 1,939 | 14 | false | false | false | false | false | true |
4,070 | 133656_0 | package net.finah.GUI;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import net.finah.API.API;
import net.finah.API.Antwoord;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
public class PDFMaker {
public static void drawTable(PDPage page, PDPageContentStream contentStream, float y, float margin, String[][] content, int ID) throws IOException {
final int rows = content.length;
final int cols = content[0].length;
final float rowHeight = 20f;
final float tableWidth = page.findMediaBox().getWidth() - (2 * margin);
final float tableHeight = rowHeight * rows;
final float colWidth = tableWidth / (float) cols;
final float cellMargin = 5f;
// rijen
float nexty = y;
for (int i = 0; i <= rows; i++) {
contentStream.drawLine(margin, nexty, margin + tableWidth, nexty);
nexty -= rowHeight;
}
// kolommen
float nextx = margin;
for (int i = 0; i <= cols; i++) {
contentStream.drawLine(nextx, y, nextx, y - tableHeight);
nextx += colWidth;
}
// tekst toe te voegen
String rapport = "Rapport " + ID;
contentStream.setFont(PDType1Font.HELVETICA_BOLD, 25);
contentStream.beginText();
contentStream.moveTextPositionByAmount(250, 700);
contentStream.drawString(rapport);
contentStream.endText();
float textx = margin + cellMargin;
float texty = y - 15;
for (int i = 0; i < content.length; i++) {
for (int j = 0; j < content[i].length; j++) {
String text = content[i][j];
contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12);
contentStream.beginText();
contentStream.moveTextPositionByAmount(textx, texty);
contentStream.drawString(text);
contentStream.endText();
textx += colWidth;
}
texty -= rowHeight;
textx = margin + cellMargin;
}
}
public static void bekijkRapport(int ID) throws IOException, COSVisitorException {
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
ArrayList<Antwoord> antwoorden = new ArrayList<Antwoord>();
try {
antwoorden = API.getAntwoordLijst(ID);
} catch (FileNotFoundException e) {
JFrame frame = new JFrame();
JOptionPane.showMessageDialog(frame, "Dit is een leeg rapport", "Leeg rapport", JOptionPane.WARNING_MESSAGE);
}
int i = 1;
int size = antwoorden.size();
String[][] content = new String[size + 1][4];
content[0][0] = " ID ";
content[0][1] = " Vraag ID ";
content[0][2] = " Antwoord ";
content[0][3] = " Extra Vraag ";
if (antwoorden.size() != 0) {
for (Antwoord antwoord : antwoorden) {
content[i][0] = antwoord.getId() + " ";
content[i][1] = antwoord.getVraag_Id() + " ";
content[i][2] = antwoord.getAntwoordInt() + " ";
content[i][3] = antwoord.getAntwoordExtra() + " ";
i++;
}
}
drawTable(page, contentStream, 675, 100, content, ID);
contentStream.close();
doc.save("Rapport_" + ID + ".pdf");
}
} | pxlit-projects/AD_IT04 | finah-desktop-java/src/net/finah/GUI/PDFMaker.java | 1,148 | // tekst toe te voegen | line_comment | nl | package net.finah.GUI;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import net.finah.API.API;
import net.finah.API.Antwoord;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
public class PDFMaker {
public static void drawTable(PDPage page, PDPageContentStream contentStream, float y, float margin, String[][] content, int ID) throws IOException {
final int rows = content.length;
final int cols = content[0].length;
final float rowHeight = 20f;
final float tableWidth = page.findMediaBox().getWidth() - (2 * margin);
final float tableHeight = rowHeight * rows;
final float colWidth = tableWidth / (float) cols;
final float cellMargin = 5f;
// rijen
float nexty = y;
for (int i = 0; i <= rows; i++) {
contentStream.drawLine(margin, nexty, margin + tableWidth, nexty);
nexty -= rowHeight;
}
// kolommen
float nextx = margin;
for (int i = 0; i <= cols; i++) {
contentStream.drawLine(nextx, y, nextx, y - tableHeight);
nextx += colWidth;
}
// tekst toe<SUF>
String rapport = "Rapport " + ID;
contentStream.setFont(PDType1Font.HELVETICA_BOLD, 25);
contentStream.beginText();
contentStream.moveTextPositionByAmount(250, 700);
contentStream.drawString(rapport);
contentStream.endText();
float textx = margin + cellMargin;
float texty = y - 15;
for (int i = 0; i < content.length; i++) {
for (int j = 0; j < content[i].length; j++) {
String text = content[i][j];
contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12);
contentStream.beginText();
contentStream.moveTextPositionByAmount(textx, texty);
contentStream.drawString(text);
contentStream.endText();
textx += colWidth;
}
texty -= rowHeight;
textx = margin + cellMargin;
}
}
public static void bekijkRapport(int ID) throws IOException, COSVisitorException {
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
ArrayList<Antwoord> antwoorden = new ArrayList<Antwoord>();
try {
antwoorden = API.getAntwoordLijst(ID);
} catch (FileNotFoundException e) {
JFrame frame = new JFrame();
JOptionPane.showMessageDialog(frame, "Dit is een leeg rapport", "Leeg rapport", JOptionPane.WARNING_MESSAGE);
}
int i = 1;
int size = antwoorden.size();
String[][] content = new String[size + 1][4];
content[0][0] = " ID ";
content[0][1] = " Vraag ID ";
content[0][2] = " Antwoord ";
content[0][3] = " Extra Vraag ";
if (antwoorden.size() != 0) {
for (Antwoord antwoord : antwoorden) {
content[i][0] = antwoord.getId() + " ";
content[i][1] = antwoord.getVraag_Id() + " ";
content[i][2] = antwoord.getAntwoordInt() + " ";
content[i][3] = antwoord.getAntwoordExtra() + " ";
i++;
}
}
drawTable(page, contentStream, 675, 100, content, ID);
contentStream.close();
doc.save("Rapport_" + ID + ".pdf");
}
} | false | 939 | 6 | 1,122 | 8 | 1,059 | 5 | 1,122 | 8 | 1,262 | 7 | false | false | false | false | false | true |
3,655 | 67718_5 | import java.util.jar.Attributes.Name;
public class DivideAndConquer {
public static void printArray(int arr[]) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void mergeSort(int arr[], int si, int ei) {
// base case
if (si >= ei) {
return;
}
// kaam
int mid = (si + ei) / 2;
// int mid = si + (ei - si) / 2;
// calling innerfunction
mergeSort(arr, si, mid);// sortting for left
mergeSort(arr, mid + 1, ei);// sortting for right
// merging both left& right part
merge(arr, si, mid, ei);
}
public static void merge(int arr[], int si, int mid, int ei) {
int temp[] = new int[ei - si + 1];
int i = si;
int j = mid + 1;
int k = 0;// temp array
while (i <= mid && j <= ei) {
if (arr[i] < arr[j]) {
temp[k] = arr[i];
i++;
k++;
// i ko temp mei store kar dunga
} else {
temp[k] = arr[j];
j++;
k++;
}
// k++;
}
// leeft over element
while (i <= mid) {
temp[k++] = arr[i++];
}
// right part
while (j <= ei) {
temp[k++] = arr[j++];
}
// copy temp to orignal array
for (k = 0, i = si; k < temp.length; k++, i++) {
arr[i] = temp[k];
}
}
public static void Name() {
int n = 50, k = 5;
for (int i = 0; i < n; i = i + k) {
for (int j = i + 1; j <= k; j++) {
System.out.print("i = " + i + " ");
System.out.print("j= " + j + " ");
}
}
}
public static int power(int a, int n) {
if (n == 0) {
return 1;
}
return a * power(a, n - 1);
}
public static void main(String[] args) {
int arr[] = { 6, 3, 9, 10, 2, 18, 1 };
// System.out.println("before");
// printArray(arr);
mergeSort(arr, 0, arr.length - 1);
// System.out.println("After ");
// printArray(arr);
// int a = 3;
// int b = 2;
// int c = (a + b) / 2;
// System.out.println("addition is " + c);
// Name();
// System.out.println(power(2, 5));
// int a=3;
// System.out.println(a/2);
}
}
| mihirkate/DSA-IN-AVA | 21.Divide &Conquer/DivideAndConquer.java | 860 | // leeft over element | line_comment | nl | import java.util.jar.Attributes.Name;
public class DivideAndConquer {
public static void printArray(int arr[]) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void mergeSort(int arr[], int si, int ei) {
// base case
if (si >= ei) {
return;
}
// kaam
int mid = (si + ei) / 2;
// int mid = si + (ei - si) / 2;
// calling innerfunction
mergeSort(arr, si, mid);// sortting for left
mergeSort(arr, mid + 1, ei);// sortting for right
// merging both left& right part
merge(arr, si, mid, ei);
}
public static void merge(int arr[], int si, int mid, int ei) {
int temp[] = new int[ei - si + 1];
int i = si;
int j = mid + 1;
int k = 0;// temp array
while (i <= mid && j <= ei) {
if (arr[i] < arr[j]) {
temp[k] = arr[i];
i++;
k++;
// i ko temp mei store kar dunga
} else {
temp[k] = arr[j];
j++;
k++;
}
// k++;
}
// leeft over<SUF>
while (i <= mid) {
temp[k++] = arr[i++];
}
// right part
while (j <= ei) {
temp[k++] = arr[j++];
}
// copy temp to orignal array
for (k = 0, i = si; k < temp.length; k++, i++) {
arr[i] = temp[k];
}
}
public static void Name() {
int n = 50, k = 5;
for (int i = 0; i < n; i = i + k) {
for (int j = i + 1; j <= k; j++) {
System.out.print("i = " + i + " ");
System.out.print("j= " + j + " ");
}
}
}
public static int power(int a, int n) {
if (n == 0) {
return 1;
}
return a * power(a, n - 1);
}
public static void main(String[] args) {
int arr[] = { 6, 3, 9, 10, 2, 18, 1 };
// System.out.println("before");
// printArray(arr);
mergeSort(arr, 0, arr.length - 1);
// System.out.println("After ");
// printArray(arr);
// int a = 3;
// int b = 2;
// int c = (a + b) / 2;
// System.out.println("addition is " + c);
// Name();
// System.out.println(power(2, 5));
// int a=3;
// System.out.println(a/2);
}
}
| false | 701 | 5 | 750 | 5 | 826 | 5 | 750 | 5 | 857 | 5 | false | false | false | false | false | true |
3,415 | 29343_15 | package logic;
/**
* Patterns are used for finding combinations. A 2 dimensional int represents the pattern.
* It uses the following codes to determine if a pattern matches:
* 0 dont care
* 1 must be my color
* 2 must be open
* 3 must be other color
*/
public class Pattern
{
// The pattern
int[][] pattern;
// Geeft aan of de uitkomst van de pattern true of false moet zijn voor een pattern collectie
boolean resultMustbe = true;
/**
* Constructor1
*/
public Pattern(int[][] pattern, boolean resultMustbe)
{
this.pattern = pattern;
this.resultMustbe = resultMustbe;
}
/**
* Constructor2, resultMustbe = standard true.
*/
public Pattern(int[][] pattern)
{
this.pattern = pattern;
}
/**
* Mirrors the pattern horizontaly.
*/
public void mirrorPattern()
{
int[][] mirroredPattern = new int[pattern.length][pattern[0].length];
int count = 0;
for (int i= pattern.length - 1; i >= 0;i--)
{
mirroredPattern[i] = pattern[count].clone();
count++;
}
this.pattern = mirroredPattern;
}
/**
* Rotates the pattern clockwise.
*/
public void rotatePattern()
{
int row = this.pattern.length;
int column = this.pattern[0].length;
int[][] newarray = new int[column][row];
for (int i = 0; i < column; i++)
{
int x = row - 1;
for (int j = 0; j < row; j++)
{
newarray[i][j] = this.pattern[x--][i];
}
}
this.pattern = newarray;
}
/**
* Check if a pattern patches on a given position (patternX, patternY).
* There is an option to check the pattern rotated 45 degrees (rotated45degrees),
* this can only be used on patterns that consist of a single line horizontaly or verticaly.
*/
public boolean checkPattern(Player[][] field, int patternX, int patternY, boolean rotated45degrees)
{
int yFrom = patternY - ((pattern.length - 1) / 2); // y startPosition in field
int xFrom = patternX - ((pattern[0].length - 1) / 2); // x startPosition in field
int yTo = yFrom + pattern.length;
int xTo = xFrom + pattern[0].length;
Player player = field[patternY][patternX];
for (int y=yFrom;y < yTo;y++){
for (int x=xFrom;x < xTo;x++)
{
int pX = x - xFrom; // pattern x
int pY = y - yFrom; // pattern y
int fX = x; // field x
int fY = y; // field y
// When rotated fix x and y
if (rotated45degrees)
{
// Normaly 1 row horizontaly
if (pattern.length == 1)
{
// fix y
fY += pX - ((pattern[0].length - 1) / 2);
}
// Normaly 1 row vertical
else if (pattern[0].length == 1)
{
fX -= pY - ((pattern.length - 1) / 2);
}
}
int patternValue = pattern[pY][pX];
try
{
Player fieldValue = field[fY][fX];
// 1 must be my color
if (patternValue == 1 && fieldValue != player)
return false;
// 2 must be open
if (patternValue == 2 && fieldValue != null)
return false;
// 3 must be other color
if (patternValue == 3 && (fieldValue == player || fieldValue == null))
return false;
}
catch (ArrayIndexOutOfBoundsException e)
{
// Pattern valt buiten het veld,
// als de pattern waarde geen 0 is of blocked
// kan de pattern niet.
// if (pattern[pY][pX] != 0)
// return false;
// {0,0,0,3,2,1,1,2,2,2,0}
if (patternValue != 0 && patternValue != 3){
return false;
}
}
}
}
return true;
}
/**
* Prints a representation of the pattern for testing purposes.
*/
public void print()
{
for(int i = 0; i<pattern.length;i++)
{
for(int j = 0; j<pattern[0].length;j++)
{
System.out.print(pattern[i][j]+" ");
}
System.out.println("");
}
}
}
| kverhoef/connect6 | src/logic/Pattern.java | 1,387 | // Pattern valt buiten het veld, | line_comment | nl | package logic;
/**
* Patterns are used for finding combinations. A 2 dimensional int represents the pattern.
* It uses the following codes to determine if a pattern matches:
* 0 dont care
* 1 must be my color
* 2 must be open
* 3 must be other color
*/
public class Pattern
{
// The pattern
int[][] pattern;
// Geeft aan of de uitkomst van de pattern true of false moet zijn voor een pattern collectie
boolean resultMustbe = true;
/**
* Constructor1
*/
public Pattern(int[][] pattern, boolean resultMustbe)
{
this.pattern = pattern;
this.resultMustbe = resultMustbe;
}
/**
* Constructor2, resultMustbe = standard true.
*/
public Pattern(int[][] pattern)
{
this.pattern = pattern;
}
/**
* Mirrors the pattern horizontaly.
*/
public void mirrorPattern()
{
int[][] mirroredPattern = new int[pattern.length][pattern[0].length];
int count = 0;
for (int i= pattern.length - 1; i >= 0;i--)
{
mirroredPattern[i] = pattern[count].clone();
count++;
}
this.pattern = mirroredPattern;
}
/**
* Rotates the pattern clockwise.
*/
public void rotatePattern()
{
int row = this.pattern.length;
int column = this.pattern[0].length;
int[][] newarray = new int[column][row];
for (int i = 0; i < column; i++)
{
int x = row - 1;
for (int j = 0; j < row; j++)
{
newarray[i][j] = this.pattern[x--][i];
}
}
this.pattern = newarray;
}
/**
* Check if a pattern patches on a given position (patternX, patternY).
* There is an option to check the pattern rotated 45 degrees (rotated45degrees),
* this can only be used on patterns that consist of a single line horizontaly or verticaly.
*/
public boolean checkPattern(Player[][] field, int patternX, int patternY, boolean rotated45degrees)
{
int yFrom = patternY - ((pattern.length - 1) / 2); // y startPosition in field
int xFrom = patternX - ((pattern[0].length - 1) / 2); // x startPosition in field
int yTo = yFrom + pattern.length;
int xTo = xFrom + pattern[0].length;
Player player = field[patternY][patternX];
for (int y=yFrom;y < yTo;y++){
for (int x=xFrom;x < xTo;x++)
{
int pX = x - xFrom; // pattern x
int pY = y - yFrom; // pattern y
int fX = x; // field x
int fY = y; // field y
// When rotated fix x and y
if (rotated45degrees)
{
// Normaly 1 row horizontaly
if (pattern.length == 1)
{
// fix y
fY += pX - ((pattern[0].length - 1) / 2);
}
// Normaly 1 row vertical
else if (pattern[0].length == 1)
{
fX -= pY - ((pattern.length - 1) / 2);
}
}
int patternValue = pattern[pY][pX];
try
{
Player fieldValue = field[fY][fX];
// 1 must be my color
if (patternValue == 1 && fieldValue != player)
return false;
// 2 must be open
if (patternValue == 2 && fieldValue != null)
return false;
// 3 must be other color
if (patternValue == 3 && (fieldValue == player || fieldValue == null))
return false;
}
catch (ArrayIndexOutOfBoundsException e)
{
// Pattern valt<SUF>
// als de pattern waarde geen 0 is of blocked
// kan de pattern niet.
// if (pattern[pY][pX] != 0)
// return false;
// {0,0,0,3,2,1,1,2,2,2,0}
if (patternValue != 0 && patternValue != 3){
return false;
}
}
}
}
return true;
}
/**
* Prints a representation of the pattern for testing purposes.
*/
public void print()
{
for(int i = 0; i<pattern.length;i++)
{
for(int j = 0; j<pattern[0].length;j++)
{
System.out.print(pattern[i][j]+" ");
}
System.out.println("");
}
}
}
| false | 1,129 | 10 | 1,226 | 11 | 1,285 | 8 | 1,226 | 11 | 1,541 | 11 | false | false | false | false | false | true |
4,785 | 70640_12 | package nu.fw.jeti.plugins.ibb;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedList;
import javax.swing.*;
import nu.fw.jeti.backend.roster.Roster;
import nu.fw.jeti.jabber.Backend;
import nu.fw.jeti.jabber.JID;
import nu.fw.jeti.jabber.JIDStatus;
import nu.fw.jeti.jabber.elements.InfoQuery;
import nu.fw.jeti.util.Base64;
import nu.fw.jeti.util.I18N;
import nu.fw.jeti.util.Popups;
/**
* <p>Title: im</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2001</p>
* <p>Company: </p>
* @author E.S. de Boer
* @version 1.0
*/
//TODO translate filetransfer warnings, or wait for socks filetransfer?
public class GetFileWindow extends JFrame
{
private JPanel jPanel1 = new JPanel();
private JLabel jLabel1 = new JLabel();
private JTextArea jTextArea1 = new JTextArea();
private JLabel jLabel2 = new JLabel();
private JTextField jTextField1 = new JTextField();
private JPanel jPanel2 = new JPanel();
private JButton btnGetSize = new JButton();
private JPanel jPanel3 = new JPanel();
private JButton btnDownload = new JButton();
private JButton btnCancel = new JButton();
private URL url;
private JProgressBar jProgressBar1 = new JProgressBar();
private String id;
private JID jid;
private Backend backend;
//private URLConnection connection = null;
private int length;
private Draadje draadje;
private JLabel lblDownload = new JLabel();
public GetFileWindow(JID jid,Backend backend, IBBExtension ibb)
{
//JOptionPane.showConfirmDialog(null,"download "+ urlString )
this.id =id;
this.jid = jid;
this.backend = backend;
try
{
jbInit();
JIDStatus j = Roster.getJIDStatus(jid);
if(j!=null)jTextArea1.setText(j.getNick());
else jTextArea1.setText(jid.toString());
//jTextField1.setText(url.toString());
}
catch(Exception e)
{
e.printStackTrace();
}
pack();
draadje = new Draadje(this);
draadje.start();
addData(ibb.getData());
}
private void jbInit() throws Exception
{
setIconImage(nu.fw.jeti.images.StatusIcons.getImageIcon("jeti").getImage());
getRootPane().setDefaultButton(btnDownload);
jLabel1.setPreferredSize(new Dimension(300, 17));
//jLabel1.setText(I18N.gettext("Description"));
I18N.setTextAndMnemonic("filetransfer.Description",jLabel1);
jTextArea1.setAlignmentX((float) 0.0);
jTextArea1.setPreferredSize(new Dimension(300, 17));
jTextArea1.setEditable(false);
jLabel2.setPreferredSize(new Dimension(300, 17));
I18N.setTextAndMnemonic("filetransfer.URL",jLabel2);
jTextField1.setAlignmentX((float) 0.0);
jTextField1.setPreferredSize(new Dimension(300, 21));
jTextField1.setEditable(false);
//btnGetSize.setMnemonic('G');
//btnGetSize.setText(I18N.gettext("GetSize"));
I18N.setTextAndMnemonic("filetransfer.GetSize",btnGetSize);
btnGetSize.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(ActionEvent e)
{
btnGetSize_actionPerformed(e);
}
});
//btnDownload.setMnemonic('D');
btnDownload.setText(I18N.gettext("filetransfer.Download"));
getRootPane().setDefaultButton(btnDownload);
btnDownload.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(ActionEvent e)
{
btnDownload_actionPerformed(e);
}
});
//btnCancel.setMnemonic('C');
//btnCancel.setText(I18N.gettext("Cancel"));
Action cancelAction = new AbstractAction(I18N.gettext("Cancel"))
{
public void actionPerformed(ActionEvent e)
{
btnCancel_actionPerformed(e);
}
};
btnCancel.setAction(cancelAction);
KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
JLayeredPane layeredPane = getLayeredPane();
layeredPane.getActionMap().put("cancel", cancelAction);
layeredPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(stroke, "cancel");
this.setTitle(I18N.gettext("filetransfer.File_Transfer"));
jPanel2.setAlignmentX((float) 0.0);
jPanel3.setAlignmentX((float) 0.0);
jProgressBar1.setAlignmentX((float) 0.0);
lblDownload.setToolTipText("");
this.getContentPane().add(jPanel1, BorderLayout.CENTER);
jPanel1.setLayout(new BoxLayout(jPanel1,BoxLayout.Y_AXIS));
jPanel1.add(jLabel1, null);
jPanel1.add(jTextArea1, null);
jPanel1.add(jLabel2, null);
jPanel1.add(jTextField1, null);
jPanel1.add(jPanel2, null);
jPanel2.add(btnGetSize, null);
jPanel2.add(lblDownload, null);
jPanel1.add(jProgressBar1, null);
jPanel1.add(jPanel3, null);
jPanel3.add(btnDownload, null);
jPanel3.add(btnCancel, null);
}
void btnGetSize_actionPerformed(ActionEvent e)
{
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
Thread t = new Thread()
{
public void run()
{
//if(connection == null)
HttpURLConnection connection = null;
{
try
{
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("HEAD");
//connection.setRequestMethod()
}
catch (IOException e2)
{
dispose();
Popups.errorPopup(url.toExternalForm() + " could not be reached","File transfer");
return;
}
}
/*
try{
((HttpURLConnection)connection).setRequestMethod("HEAD");
}
catch(ProtocolException e2){e2.printStackTrace();}
*/
length = connection.getContentLength()/1024;
Runnable updateAComponent = new Runnable() {
public void run(){
lblDownload.setText(length + " kB " + length / 1024 + " MB");
setCursor(Cursor.getDefaultCursor());
}};
SwingUtilities.invokeLater(updateAComponent);
}
};
t.start();
}
void btnDownload_actionPerformed(ActionEvent e)
{
//final GetFileWindow w = this;
draadje = new Draadje(this);
draadje.start();
}
void btnCancel_actionPerformed(ActionEvent e)
{
if(draadje !=null)
{
draadje.interrupt();
}
//backend.sendError("406","Not Acceptable",jid,id);
//backend.send(new InfoQuery(to,error ) )
// InfoQueryBuilder iqb = new InfoQueryBuilder();
// iqb.setErrorCode(406);
// iqb.setErrorDescription("Not Acceptable");
// iqb.setId(id);
// iqb.setTo(jid);
// iqb.setType("error");
// backend.send(iqb.build());
backend.send(new InfoQuery(jid,"error",id,null,"Not Acceptable",406));
dispose();
}
public void addData(String data)
{
System.out.println("data added");
draadje.addData(data);
}
public void stopDownloading()
{
draadje.stopDownloading();
System.out.println("download complete");
}
class Draadje extends Thread
{
private GetFileWindow getFileWindow;
private int bytes=0;
private LinkedList queue = new LinkedList();
private volatile boolean isDownloading=true;
Draadje(GetFileWindow w)
{
getFileWindow =w;
}
public void addData(String data)
{
synchronized(queue)
{
queue.addLast(data);
queue.notifyAll();
}
}
public void stopDownloading()
{
isDownloading = false;
synchronized(queue){queue.notifyAll();}
}
public void run()
{
JFileChooser fileChooser = new JFileChooser();
int s = fileChooser.showSaveDialog(getFileWindow);
if(s != JFileChooser.APPROVE_OPTION) return; //cancel
//check if enough space on hd
btnDownload.setEnabled(false);
btnGetSize.setVisible(false);
btnCancel.setText("Abort");
btnCancel.setMnemonic('a');
BufferedOutputStream out=null;
try{
try{
out = new BufferedOutputStream (new FileOutputStream(fileChooser.getSelectedFile()));
}catch(FileNotFoundException e2)
{
Popups.errorPopup(fileChooser.getSelectedFile().getAbsolutePath() + " could not be openend in write mode","File transfer");
}
if(out!=null)
{
try{
while(!queue.isEmpty() || isDownloading)
{
String base64Data;
synchronized(queue)
{
if (queue.isEmpty())
{
try
{
System.out.println("waiting");
queue.wait();
}
catch(InterruptedException e)
{//bug when thrown? called when interrupted
e.printStackTrace();
return;
}
continue;
}
base64Data = (String)queue.removeFirst();
System.out.println("data read");
}
//System.out.println(base64Data);
//System.out.println(Base64.decode2(base64Data));
byte[] data = Base64.decode(base64Data);
System.out.println("data converted");
out.write(data, 0, data.length);
System.out.println("data written");
//bytes++;
if (Thread.interrupted()) throw new InterruptedException();
//yield();
}
//download ok
//backend.send(new InfoQuery(jid,"result",id,null));
}catch (IOException e2) //te weinig schijruimte
{
Popups.errorPopup(e2.getMessage() + " while downloading " + url.toExternalForm(),"File transfer");
//download not ok
backend.send(new InfoQuery(jid,"error",id,null,"Not Acceptable",406));
}
}
dispose();
System.out.println("downloaded");
}catch (InterruptedException e3) {}
try
{
if(out!=null)out.close();
}catch (IOException e2){}
}
}
}
/*
* Overrides for emacs
* Local variables:
* tab-width: 4
* End:
*/
| youngdev/experiment | JETL/nu/fw/jeti/plugins/ibb/GetFileWindow.java | 3,528 | //te weinig schijruimte | line_comment | nl | package nu.fw.jeti.plugins.ibb;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedList;
import javax.swing.*;
import nu.fw.jeti.backend.roster.Roster;
import nu.fw.jeti.jabber.Backend;
import nu.fw.jeti.jabber.JID;
import nu.fw.jeti.jabber.JIDStatus;
import nu.fw.jeti.jabber.elements.InfoQuery;
import nu.fw.jeti.util.Base64;
import nu.fw.jeti.util.I18N;
import nu.fw.jeti.util.Popups;
/**
* <p>Title: im</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2001</p>
* <p>Company: </p>
* @author E.S. de Boer
* @version 1.0
*/
//TODO translate filetransfer warnings, or wait for socks filetransfer?
public class GetFileWindow extends JFrame
{
private JPanel jPanel1 = new JPanel();
private JLabel jLabel1 = new JLabel();
private JTextArea jTextArea1 = new JTextArea();
private JLabel jLabel2 = new JLabel();
private JTextField jTextField1 = new JTextField();
private JPanel jPanel2 = new JPanel();
private JButton btnGetSize = new JButton();
private JPanel jPanel3 = new JPanel();
private JButton btnDownload = new JButton();
private JButton btnCancel = new JButton();
private URL url;
private JProgressBar jProgressBar1 = new JProgressBar();
private String id;
private JID jid;
private Backend backend;
//private URLConnection connection = null;
private int length;
private Draadje draadje;
private JLabel lblDownload = new JLabel();
public GetFileWindow(JID jid,Backend backend, IBBExtension ibb)
{
//JOptionPane.showConfirmDialog(null,"download "+ urlString )
this.id =id;
this.jid = jid;
this.backend = backend;
try
{
jbInit();
JIDStatus j = Roster.getJIDStatus(jid);
if(j!=null)jTextArea1.setText(j.getNick());
else jTextArea1.setText(jid.toString());
//jTextField1.setText(url.toString());
}
catch(Exception e)
{
e.printStackTrace();
}
pack();
draadje = new Draadje(this);
draadje.start();
addData(ibb.getData());
}
private void jbInit() throws Exception
{
setIconImage(nu.fw.jeti.images.StatusIcons.getImageIcon("jeti").getImage());
getRootPane().setDefaultButton(btnDownload);
jLabel1.setPreferredSize(new Dimension(300, 17));
//jLabel1.setText(I18N.gettext("Description"));
I18N.setTextAndMnemonic("filetransfer.Description",jLabel1);
jTextArea1.setAlignmentX((float) 0.0);
jTextArea1.setPreferredSize(new Dimension(300, 17));
jTextArea1.setEditable(false);
jLabel2.setPreferredSize(new Dimension(300, 17));
I18N.setTextAndMnemonic("filetransfer.URL",jLabel2);
jTextField1.setAlignmentX((float) 0.0);
jTextField1.setPreferredSize(new Dimension(300, 21));
jTextField1.setEditable(false);
//btnGetSize.setMnemonic('G');
//btnGetSize.setText(I18N.gettext("GetSize"));
I18N.setTextAndMnemonic("filetransfer.GetSize",btnGetSize);
btnGetSize.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(ActionEvent e)
{
btnGetSize_actionPerformed(e);
}
});
//btnDownload.setMnemonic('D');
btnDownload.setText(I18N.gettext("filetransfer.Download"));
getRootPane().setDefaultButton(btnDownload);
btnDownload.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(ActionEvent e)
{
btnDownload_actionPerformed(e);
}
});
//btnCancel.setMnemonic('C');
//btnCancel.setText(I18N.gettext("Cancel"));
Action cancelAction = new AbstractAction(I18N.gettext("Cancel"))
{
public void actionPerformed(ActionEvent e)
{
btnCancel_actionPerformed(e);
}
};
btnCancel.setAction(cancelAction);
KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
JLayeredPane layeredPane = getLayeredPane();
layeredPane.getActionMap().put("cancel", cancelAction);
layeredPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(stroke, "cancel");
this.setTitle(I18N.gettext("filetransfer.File_Transfer"));
jPanel2.setAlignmentX((float) 0.0);
jPanel3.setAlignmentX((float) 0.0);
jProgressBar1.setAlignmentX((float) 0.0);
lblDownload.setToolTipText("");
this.getContentPane().add(jPanel1, BorderLayout.CENTER);
jPanel1.setLayout(new BoxLayout(jPanel1,BoxLayout.Y_AXIS));
jPanel1.add(jLabel1, null);
jPanel1.add(jTextArea1, null);
jPanel1.add(jLabel2, null);
jPanel1.add(jTextField1, null);
jPanel1.add(jPanel2, null);
jPanel2.add(btnGetSize, null);
jPanel2.add(lblDownload, null);
jPanel1.add(jProgressBar1, null);
jPanel1.add(jPanel3, null);
jPanel3.add(btnDownload, null);
jPanel3.add(btnCancel, null);
}
void btnGetSize_actionPerformed(ActionEvent e)
{
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
Thread t = new Thread()
{
public void run()
{
//if(connection == null)
HttpURLConnection connection = null;
{
try
{
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("HEAD");
//connection.setRequestMethod()
}
catch (IOException e2)
{
dispose();
Popups.errorPopup(url.toExternalForm() + " could not be reached","File transfer");
return;
}
}
/*
try{
((HttpURLConnection)connection).setRequestMethod("HEAD");
}
catch(ProtocolException e2){e2.printStackTrace();}
*/
length = connection.getContentLength()/1024;
Runnable updateAComponent = new Runnable() {
public void run(){
lblDownload.setText(length + " kB " + length / 1024 + " MB");
setCursor(Cursor.getDefaultCursor());
}};
SwingUtilities.invokeLater(updateAComponent);
}
};
t.start();
}
void btnDownload_actionPerformed(ActionEvent e)
{
//final GetFileWindow w = this;
draadje = new Draadje(this);
draadje.start();
}
void btnCancel_actionPerformed(ActionEvent e)
{
if(draadje !=null)
{
draadje.interrupt();
}
//backend.sendError("406","Not Acceptable",jid,id);
//backend.send(new InfoQuery(to,error ) )
// InfoQueryBuilder iqb = new InfoQueryBuilder();
// iqb.setErrorCode(406);
// iqb.setErrorDescription("Not Acceptable");
// iqb.setId(id);
// iqb.setTo(jid);
// iqb.setType("error");
// backend.send(iqb.build());
backend.send(new InfoQuery(jid,"error",id,null,"Not Acceptable",406));
dispose();
}
public void addData(String data)
{
System.out.println("data added");
draadje.addData(data);
}
public void stopDownloading()
{
draadje.stopDownloading();
System.out.println("download complete");
}
class Draadje extends Thread
{
private GetFileWindow getFileWindow;
private int bytes=0;
private LinkedList queue = new LinkedList();
private volatile boolean isDownloading=true;
Draadje(GetFileWindow w)
{
getFileWindow =w;
}
public void addData(String data)
{
synchronized(queue)
{
queue.addLast(data);
queue.notifyAll();
}
}
public void stopDownloading()
{
isDownloading = false;
synchronized(queue){queue.notifyAll();}
}
public void run()
{
JFileChooser fileChooser = new JFileChooser();
int s = fileChooser.showSaveDialog(getFileWindow);
if(s != JFileChooser.APPROVE_OPTION) return; //cancel
//check if enough space on hd
btnDownload.setEnabled(false);
btnGetSize.setVisible(false);
btnCancel.setText("Abort");
btnCancel.setMnemonic('a');
BufferedOutputStream out=null;
try{
try{
out = new BufferedOutputStream (new FileOutputStream(fileChooser.getSelectedFile()));
}catch(FileNotFoundException e2)
{
Popups.errorPopup(fileChooser.getSelectedFile().getAbsolutePath() + " could not be openend in write mode","File transfer");
}
if(out!=null)
{
try{
while(!queue.isEmpty() || isDownloading)
{
String base64Data;
synchronized(queue)
{
if (queue.isEmpty())
{
try
{
System.out.println("waiting");
queue.wait();
}
catch(InterruptedException e)
{//bug when thrown? called when interrupted
e.printStackTrace();
return;
}
continue;
}
base64Data = (String)queue.removeFirst();
System.out.println("data read");
}
//System.out.println(base64Data);
//System.out.println(Base64.decode2(base64Data));
byte[] data = Base64.decode(base64Data);
System.out.println("data converted");
out.write(data, 0, data.length);
System.out.println("data written");
//bytes++;
if (Thread.interrupted()) throw new InterruptedException();
//yield();
}
//download ok
//backend.send(new InfoQuery(jid,"result",id,null));
}catch (IOException e2) //te weinig<SUF>
{
Popups.errorPopup(e2.getMessage() + " while downloading " + url.toExternalForm(),"File transfer");
//download not ok
backend.send(new InfoQuery(jid,"error",id,null,"Not Acceptable",406));
}
}
dispose();
System.out.println("downloaded");
}catch (InterruptedException e3) {}
try
{
if(out!=null)out.close();
}catch (IOException e2){}
}
}
}
/*
* Overrides for emacs
* Local variables:
* tab-width: 4
* End:
*/
| false | 2,443 | 10 | 2,909 | 10 | 2,949 | 6 | 2,909 | 10 | 3,993 | 10 | false | false | false | false | false | true |
2,500 | 15765_1 | import java.util.Arrays;
import java.util.Random;
public class GenderPredictionNeuralNetwork {
private int numInputNodes = 4;
private int numHiddenNodes = 3;
private int numOutputNodes = 1;
private double[] weightsInputToHidden;
private double[] weightsHiddenToOutput;
private double[] hiddenOutputs;
private double bestError = Double.MAX_VALUE;
private double[] bestWeightsInputToHidden;
private double[] bestWeightsHiddenToOutput;
public void setWeightsInputToHidden(double[] input) {
this.weightsInputToHidden = input;
}
public double[] getWeightsHiddenToOutput() {
return weightsHiddenToOutput;
}
public void setWeightsHiddenToOutput(double[] input) {
this.weightsHiddenToOutput = input;
}
public double[] getWeightsInputToHidden() {
return weightsInputToHidden;
}
public int getNumInputNodes() {
return numInputNodes;
}
public int getNumHiddenNodes() {
return numHiddenNodes;
}
public int getNumOutputNodes() {
return numOutputNodes;
}
public GenderPredictionNeuralNetwork() {
// Initializeer de gewichten willekeurig
initializeWeights();
// Initialiseer de beste gewichten met de huidige gewichten
bestWeightsInputToHidden = weightsInputToHidden.clone();
bestWeightsHiddenToOutput = weightsHiddenToOutput.clone();
// initializeWeights();
}
private void initializeWeights() {
Random rand = new Random();
this.weightsHiddenToOutput = new double[numHiddenNodes];
this.weightsInputToHidden = new double[numInputNodes * numHiddenNodes];
for (int i = 0; i < numHiddenNodes; i++) {
weightsHiddenToOutput[i] = rand.nextDouble() - 0.5; // Willekeurige gewichten tussen -0.5 en 0.5
}
for (int i = 0; i < numInputNodes * numHiddenNodes; i++) {
weightsInputToHidden[i] = rand.nextDouble() - 0.5; // Willekeurige gewichten tussen -0.5 en 0.5
}
// Remove randomness for testing stuff
weightsHiddenToOutput = new double[] {-0.2419814405500772, -0.4258861301218023, -0.20395764771837566};
weightsInputToHidden = new double[] {0.3462816638706523, -0.3768482517039504, 0.49991809061492376, -0.03487260530787195, -0.16831879557517182, -0.18590311350808109, -0.4040828389598421, 0.3475805938118687, 0.4549359689900563, 0.21627814379221388, -0.2826987358948527, -0.2675359244943599};
}
public double feedForward(double[] inputs) {
// Berekeningen voor de verborgen laag
hiddenOutputs = new double[numHiddenNodes];
for (int i = 0; i < numHiddenNodes; i++) {
double sum = 0;
for (int j = 0; j < numInputNodes; j++) {
sum += inputs[j] * weightsInputToHidden[j * numHiddenNodes + i];
}
hiddenOutputs[i] = sigmoid(sum);
}
// Berekeningen voor de output
double output = 0;
for (int i = 0; i < numHiddenNodes; i++) {
output += hiddenOutputs[i] * weightsHiddenToOutput[i];
}
return sigmoid(output);
}
private double sigmoid(double x) {
return 1 / (1 + Math.exp(-x));
}
public void train(double[][] inputs, double[] expectedOutputs, double learningRate, int epochs) {
//Random rand = new Random();
for (int epoch = 0; epoch < epochs; epoch++) {
double totalError = 0.0;
for (int i = 0; i < inputs.length; i++) {
double[] input = inputs[i];
double expectedOutput = expectedOutputs[i];
double predictedOutput = feedForward(input);
// Bereken de fout na het bijwerken van de gewichten
double error = calculateError(predictedOutput, expectedOutput);
totalError += error;
// Update de gewichten
updateWeights(input, predictedOutput, expectedOutput, learningRate);
// Houd de beste gewichten bij
if (totalError < bestError) {
bestError = totalError;
bestWeightsInputToHidden = weightsInputToHidden.clone();
bestWeightsHiddenToOutput = weightsHiddenToOutput.clone();
}
}
System.out.println("Epoch " + epoch + ", Total Error: " + totalError);
}
}
private void updateWeights(double[] input, double predictedOutput, double expectedOutput, double learningRate) {
// Update de gewichten van de verborgen laag naar de uitvoerlaag
for (int j = 0; j < numHiddenNodes; j++) {
double deltaOutput = (expectedOutput - predictedOutput) * predictedOutput * (1 - predictedOutput);
weightsHiddenToOutput[j] += learningRate * deltaOutput * hiddenOutputs[j];
}
// Update de gewichten van de invoerlaag naar de verborgen laag
for (int j = 0; j < numInputNodes; j++) {
for (int k = 0; k < numHiddenNodes; k++) {
double deltaHidden = 0;
for (int l = 0; l < numOutputNodes; l++) {
double deltaOutput = (expectedOutput - predictedOutput) * predictedOutput * (1 - predictedOutput);
deltaHidden += deltaOutput * bestWeightsHiddenToOutput[k * numOutputNodes + l] * hiddenOutputs[k] * (1 - hiddenOutputs[k]) * input[j];
}
weightsInputToHidden[j * numHiddenNodes + k] += learningRate * deltaHidden;
}
}
}
public double calculateError(double predicted, double actual) {
return 0.5 * Math.pow((actual - predicted), 2);
}
public static void main(String[] args) {
GenderPredictionNeuralNetwork neuralNetwork = new GenderPredictionNeuralNetwork();
System.out.println(Arrays.toString(neuralNetwork.getWeightsHiddenToOutput()));
System.out.println(Arrays.toString(neuralNetwork.getWeightsInputToHidden()));
// Trainingsdata (lengte, gewicht, leeftijd en bijbehorende gender)
double[][] inputs = {
{190, 120, 30, 100}, // Man
{160, 55, 25, 2}, // Vrouw
{185, 100, 35, 90}, // Man
{175, 63, 28, 14}, // Vrouw
{230, 120, 30, 100}, // Man
{140, 55, 25, 22}, // Vrouw
{195, 100, 35, 90}, // Man
{145, 63, 28, 5}, // Vrouw
// Voeg meer voorbeelden toe...
};
double[] expectedOutputs = {1, 0, 1, 0, 1, 0, 1, 0}; // 1 voor man, 0 voor vrouw
double learningRate = 0.05;
int epochs = 1000;
neuralNetwork.train(inputs, expectedOutputs, learningRate, epochs);
int correctPredictions = 0;
double[][] inputs_vali = {
{170, 110, 30, 110}, // Man
{180, 80, 20, 75}, // Man
{155, 10, 5, 20}, // Vrouw
{160, 40, 18, 24}, // Vrouw
{210, 110, 40, 120}, // Man
{180, 85, 25, 82}, // Man
{135, 30, 35, 30}, // Vrouw
{180, 93, 28, 88}, // Man
// Voeg meer voorbeelden toe...
};
double[] expectedOutputs_vali = {1, 1, 0, 0, 1, 1, 0, 1}; // 1 voor man, 0 voor vrouw
// Voorspel het geslacht voor nieuwe datapunten
for (int i = 0; i < inputs_vali.length; i++) {
double[] input = inputs_vali[i];
double expectedGender = expectedOutputs_vali[i];
double predictedGender = neuralNetwork.feedForward(input);
String genderPrediction = (predictedGender <= 0.5) ? "vrouw" : "man";
String expectedGenderString = (expectedGender == 0) ? "vrouw" : "man";
System.out.println("Input: " + Arrays.toString(input) + ", Predicted Gender: " + genderPrediction + ", Expected Gender: " + expectedGenderString);
if ((predictedGender <= 0.5 && expectedGender == 0) || (predictedGender > 0.5 && expectedGender == 1)) {
correctPredictions++;
}
}
double accuracy = ((double) correctPredictions / inputs_vali.length) * 100;
System.out.println("Accuracy: " + accuracy + "%");
System.out.println("Learning Rate: " + learningRate);
System.out.println("Epochs: " + epochs);
// Voorspel het geslacht voor nieuwe datapunten
// Voeg validatiedata toe en voorspel het geslacht
}
}
| dannynoordamdev/NeuralNetwork | src/GenderPredictionNeuralNetwork.java | 2,615 | // Initialiseer de beste gewichten met de huidige gewichten | line_comment | nl | import java.util.Arrays;
import java.util.Random;
public class GenderPredictionNeuralNetwork {
private int numInputNodes = 4;
private int numHiddenNodes = 3;
private int numOutputNodes = 1;
private double[] weightsInputToHidden;
private double[] weightsHiddenToOutput;
private double[] hiddenOutputs;
private double bestError = Double.MAX_VALUE;
private double[] bestWeightsInputToHidden;
private double[] bestWeightsHiddenToOutput;
public void setWeightsInputToHidden(double[] input) {
this.weightsInputToHidden = input;
}
public double[] getWeightsHiddenToOutput() {
return weightsHiddenToOutput;
}
public void setWeightsHiddenToOutput(double[] input) {
this.weightsHiddenToOutput = input;
}
public double[] getWeightsInputToHidden() {
return weightsInputToHidden;
}
public int getNumInputNodes() {
return numInputNodes;
}
public int getNumHiddenNodes() {
return numHiddenNodes;
}
public int getNumOutputNodes() {
return numOutputNodes;
}
public GenderPredictionNeuralNetwork() {
// Initializeer de gewichten willekeurig
initializeWeights();
// Initialiseer de<SUF>
bestWeightsInputToHidden = weightsInputToHidden.clone();
bestWeightsHiddenToOutput = weightsHiddenToOutput.clone();
// initializeWeights();
}
private void initializeWeights() {
Random rand = new Random();
this.weightsHiddenToOutput = new double[numHiddenNodes];
this.weightsInputToHidden = new double[numInputNodes * numHiddenNodes];
for (int i = 0; i < numHiddenNodes; i++) {
weightsHiddenToOutput[i] = rand.nextDouble() - 0.5; // Willekeurige gewichten tussen -0.5 en 0.5
}
for (int i = 0; i < numInputNodes * numHiddenNodes; i++) {
weightsInputToHidden[i] = rand.nextDouble() - 0.5; // Willekeurige gewichten tussen -0.5 en 0.5
}
// Remove randomness for testing stuff
weightsHiddenToOutput = new double[] {-0.2419814405500772, -0.4258861301218023, -0.20395764771837566};
weightsInputToHidden = new double[] {0.3462816638706523, -0.3768482517039504, 0.49991809061492376, -0.03487260530787195, -0.16831879557517182, -0.18590311350808109, -0.4040828389598421, 0.3475805938118687, 0.4549359689900563, 0.21627814379221388, -0.2826987358948527, -0.2675359244943599};
}
public double feedForward(double[] inputs) {
// Berekeningen voor de verborgen laag
hiddenOutputs = new double[numHiddenNodes];
for (int i = 0; i < numHiddenNodes; i++) {
double sum = 0;
for (int j = 0; j < numInputNodes; j++) {
sum += inputs[j] * weightsInputToHidden[j * numHiddenNodes + i];
}
hiddenOutputs[i] = sigmoid(sum);
}
// Berekeningen voor de output
double output = 0;
for (int i = 0; i < numHiddenNodes; i++) {
output += hiddenOutputs[i] * weightsHiddenToOutput[i];
}
return sigmoid(output);
}
private double sigmoid(double x) {
return 1 / (1 + Math.exp(-x));
}
public void train(double[][] inputs, double[] expectedOutputs, double learningRate, int epochs) {
//Random rand = new Random();
for (int epoch = 0; epoch < epochs; epoch++) {
double totalError = 0.0;
for (int i = 0; i < inputs.length; i++) {
double[] input = inputs[i];
double expectedOutput = expectedOutputs[i];
double predictedOutput = feedForward(input);
// Bereken de fout na het bijwerken van de gewichten
double error = calculateError(predictedOutput, expectedOutput);
totalError += error;
// Update de gewichten
updateWeights(input, predictedOutput, expectedOutput, learningRate);
// Houd de beste gewichten bij
if (totalError < bestError) {
bestError = totalError;
bestWeightsInputToHidden = weightsInputToHidden.clone();
bestWeightsHiddenToOutput = weightsHiddenToOutput.clone();
}
}
System.out.println("Epoch " + epoch + ", Total Error: " + totalError);
}
}
private void updateWeights(double[] input, double predictedOutput, double expectedOutput, double learningRate) {
// Update de gewichten van de verborgen laag naar de uitvoerlaag
for (int j = 0; j < numHiddenNodes; j++) {
double deltaOutput = (expectedOutput - predictedOutput) * predictedOutput * (1 - predictedOutput);
weightsHiddenToOutput[j] += learningRate * deltaOutput * hiddenOutputs[j];
}
// Update de gewichten van de invoerlaag naar de verborgen laag
for (int j = 0; j < numInputNodes; j++) {
for (int k = 0; k < numHiddenNodes; k++) {
double deltaHidden = 0;
for (int l = 0; l < numOutputNodes; l++) {
double deltaOutput = (expectedOutput - predictedOutput) * predictedOutput * (1 - predictedOutput);
deltaHidden += deltaOutput * bestWeightsHiddenToOutput[k * numOutputNodes + l] * hiddenOutputs[k] * (1 - hiddenOutputs[k]) * input[j];
}
weightsInputToHidden[j * numHiddenNodes + k] += learningRate * deltaHidden;
}
}
}
public double calculateError(double predicted, double actual) {
return 0.5 * Math.pow((actual - predicted), 2);
}
public static void main(String[] args) {
GenderPredictionNeuralNetwork neuralNetwork = new GenderPredictionNeuralNetwork();
System.out.println(Arrays.toString(neuralNetwork.getWeightsHiddenToOutput()));
System.out.println(Arrays.toString(neuralNetwork.getWeightsInputToHidden()));
// Trainingsdata (lengte, gewicht, leeftijd en bijbehorende gender)
double[][] inputs = {
{190, 120, 30, 100}, // Man
{160, 55, 25, 2}, // Vrouw
{185, 100, 35, 90}, // Man
{175, 63, 28, 14}, // Vrouw
{230, 120, 30, 100}, // Man
{140, 55, 25, 22}, // Vrouw
{195, 100, 35, 90}, // Man
{145, 63, 28, 5}, // Vrouw
// Voeg meer voorbeelden toe...
};
double[] expectedOutputs = {1, 0, 1, 0, 1, 0, 1, 0}; // 1 voor man, 0 voor vrouw
double learningRate = 0.05;
int epochs = 1000;
neuralNetwork.train(inputs, expectedOutputs, learningRate, epochs);
int correctPredictions = 0;
double[][] inputs_vali = {
{170, 110, 30, 110}, // Man
{180, 80, 20, 75}, // Man
{155, 10, 5, 20}, // Vrouw
{160, 40, 18, 24}, // Vrouw
{210, 110, 40, 120}, // Man
{180, 85, 25, 82}, // Man
{135, 30, 35, 30}, // Vrouw
{180, 93, 28, 88}, // Man
// Voeg meer voorbeelden toe...
};
double[] expectedOutputs_vali = {1, 1, 0, 0, 1, 1, 0, 1}; // 1 voor man, 0 voor vrouw
// Voorspel het geslacht voor nieuwe datapunten
for (int i = 0; i < inputs_vali.length; i++) {
double[] input = inputs_vali[i];
double expectedGender = expectedOutputs_vali[i];
double predictedGender = neuralNetwork.feedForward(input);
String genderPrediction = (predictedGender <= 0.5) ? "vrouw" : "man";
String expectedGenderString = (expectedGender == 0) ? "vrouw" : "man";
System.out.println("Input: " + Arrays.toString(input) + ", Predicted Gender: " + genderPrediction + ", Expected Gender: " + expectedGenderString);
if ((predictedGender <= 0.5 && expectedGender == 0) || (predictedGender > 0.5 && expectedGender == 1)) {
correctPredictions++;
}
}
double accuracy = ((double) correctPredictions / inputs_vali.length) * 100;
System.out.println("Accuracy: " + accuracy + "%");
System.out.println("Learning Rate: " + learningRate);
System.out.println("Epochs: " + epochs);
// Voorspel het geslacht voor nieuwe datapunten
// Voeg validatiedata toe en voorspel het geslacht
}
}
| false | 2,416 | 14 | 2,524 | 20 | 2,585 | 12 | 2,527 | 20 | 2,790 | 15 | false | false | false | false | false | true |
4,590 | 16220_3 | /* This file is part of Waisda
Copyright (c) 2012 Netherlands Institute for Sound and Vision
https://github.com/beeldengeluid/waisda
Waisda 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.
Waisda 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 Waisda. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.waisda.domain;_x000D_
_x000D_
import javax.persistence.Basic;_x000D_
import javax.persistence.Column;_x000D_
import javax.persistence.Entity;_x000D_
import javax.persistence.EnumType;_x000D_
import javax.persistence.Enumerated;_x000D_
import javax.persistence.GeneratedValue;_x000D_
import javax.persistence.GenerationType;_x000D_
import javax.persistence.Id;_x000D_
_x000D_
import org.hibernate.annotations.Formula;_x000D_
_x000D_
@Entity_x000D_
public class Video {_x000D_
_x000D_
@Id_x000D_
@GeneratedValue(strategy = GenerationType.AUTO)_x000D_
private int id;_x000D_
_x000D_
@Basic_x000D_
private String title;_x000D_
_x000D_
/** Duration in ms. */_x000D_
@Column(nullable = false)_x000D_
private int duration;_x000D_
_x000D_
@Basic_x000D_
private String imageUrl;_x000D_
_x000D_
@Basic_x000D_
private boolean enabled;_x000D_
_x000D_
@Formula("(SELECT COUNT(*) FROM Game g WHERE g.video_id = id)")_x000D_
private int timesPlayed;_x000D_
_x000D_
@Enumerated(EnumType.STRING)_x000D_
private PlayerType playerType;_x000D_
_x000D_
@Basic_x000D_
private String fragmentID;_x000D_
_x000D_
/** Start time within episode, in ms. */_x000D_
@Basic_x000D_
private Integer startTime;_x000D_
_x000D_
/** Fragmentenrubriek zoals in MBH dump. */_x000D_
private Integer sectionNid;_x000D_
_x000D_
private String sourceUrl;_x000D_
_x000D_
public int getId() {_x000D_
return id;_x000D_
}_x000D_
_x000D_
public String getTitle() {_x000D_
return title;_x000D_
}_x000D_
_x000D_
public int getDuration() {_x000D_
return duration;_x000D_
}_x000D_
_x000D_
public String getImageUrl() {_x000D_
return imageUrl;_x000D_
}_x000D_
_x000D_
public boolean isEnabled() {_x000D_
return enabled;_x000D_
}_x000D_
_x000D_
public int getTimesPlayed() {_x000D_
return timesPlayed;_x000D_
}_x000D_
_x000D_
public PlayerType getPlayerType() {_x000D_
return playerType;_x000D_
}_x000D_
_x000D_
public String getFragmentID() {_x000D_
return fragmentID;_x000D_
}_x000D_
_x000D_
public Integer getStartTime() {_x000D_
return startTime;_x000D_
}_x000D_
_x000D_
public Integer getSectionNid() {_x000D_
return sectionNid;_x000D_
}_x000D_
_x000D_
public String getSourceUrl() {_x000D_
return sourceUrl;_x000D_
}_x000D_
_x000D_
public String getPrettyDuration() {_x000D_
return TagEntry.getFriendlyTime(duration);_x000D_
}_x000D_
_x000D_
} | ucds-vu/waisda | src/main/java/nl/waisda/domain/Video.java | 816 | /** Fragmentenrubriek zoals in MBH dump. */ | block_comment | nl | /* This file is part of Waisda
Copyright (c) 2012 Netherlands Institute for Sound and Vision
https://github.com/beeldengeluid/waisda
Waisda 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.
Waisda 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 Waisda. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.waisda.domain;_x000D_
_x000D_
import javax.persistence.Basic;_x000D_
import javax.persistence.Column;_x000D_
import javax.persistence.Entity;_x000D_
import javax.persistence.EnumType;_x000D_
import javax.persistence.Enumerated;_x000D_
import javax.persistence.GeneratedValue;_x000D_
import javax.persistence.GenerationType;_x000D_
import javax.persistence.Id;_x000D_
_x000D_
import org.hibernate.annotations.Formula;_x000D_
_x000D_
@Entity_x000D_
public class Video {_x000D_
_x000D_
@Id_x000D_
@GeneratedValue(strategy = GenerationType.AUTO)_x000D_
private int id;_x000D_
_x000D_
@Basic_x000D_
private String title;_x000D_
_x000D_
/** Duration in ms. */_x000D_
@Column(nullable = false)_x000D_
private int duration;_x000D_
_x000D_
@Basic_x000D_
private String imageUrl;_x000D_
_x000D_
@Basic_x000D_
private boolean enabled;_x000D_
_x000D_
@Formula("(SELECT COUNT(*) FROM Game g WHERE g.video_id = id)")_x000D_
private int timesPlayed;_x000D_
_x000D_
@Enumerated(EnumType.STRING)_x000D_
private PlayerType playerType;_x000D_
_x000D_
@Basic_x000D_
private String fragmentID;_x000D_
_x000D_
/** Start time within episode, in ms. */_x000D_
@Basic_x000D_
private Integer startTime;_x000D_
_x000D_
/** Fragmentenrubriek zoals in<SUF>*/_x000D_
private Integer sectionNid;_x000D_
_x000D_
private String sourceUrl;_x000D_
_x000D_
public int getId() {_x000D_
return id;_x000D_
}_x000D_
_x000D_
public String getTitle() {_x000D_
return title;_x000D_
}_x000D_
_x000D_
public int getDuration() {_x000D_
return duration;_x000D_
}_x000D_
_x000D_
public String getImageUrl() {_x000D_
return imageUrl;_x000D_
}_x000D_
_x000D_
public boolean isEnabled() {_x000D_
return enabled;_x000D_
}_x000D_
_x000D_
public int getTimesPlayed() {_x000D_
return timesPlayed;_x000D_
}_x000D_
_x000D_
public PlayerType getPlayerType() {_x000D_
return playerType;_x000D_
}_x000D_
_x000D_
public String getFragmentID() {_x000D_
return fragmentID;_x000D_
}_x000D_
_x000D_
public Integer getStartTime() {_x000D_
return startTime;_x000D_
}_x000D_
_x000D_
public Integer getSectionNid() {_x000D_
return sectionNid;_x000D_
}_x000D_
_x000D_
public String getSourceUrl() {_x000D_
return sourceUrl;_x000D_
}_x000D_
_x000D_
public String getPrettyDuration() {_x000D_
return TagEntry.getFriendlyTime(duration);_x000D_
}_x000D_
_x000D_
} | false | 1,174 | 13 | 1,339 | 14 | 1,370 | 12 | 1,339 | 14 | 1,472 | 14 | false | false | false | false | false | true |
101 | 84745_2 | package be.annelyse.budget;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ResourceBundleMessageSource;
@SpringBootApplication
// @Configuration (beans definiëren)
// @ComponentScan (zoekt beans in pakket en subpakketten waar deze file in zit)
// @EnableAutoConfiguration geldt voor het pakket en subpakketten waar deze file in zit
public class BudgetApplication {
public static void main(String[] args) {
//configuratie van de applicatie (context)
SpringApplication.run(BudgetApplication.class, args);
}
//todo diy is een test vanuit thymeleaf voorbeeld. komt er een internationalisation message ding bij resoures???
/*
* Message externalization/internationalization
*/
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("Messages");
return messageSource;
}
}
| AnnelyseBe/MyBudget_repo3 | src/main/java/be/annelyse/budget/BudgetApplication.java | 287 | // @EnableAutoConfiguration geldt voor het pakket en subpakketten waar deze file in zit | line_comment | nl | package be.annelyse.budget;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ResourceBundleMessageSource;
@SpringBootApplication
// @Configuration (beans definiëren)
// @ComponentScan (zoekt beans in pakket en subpakketten waar deze file in zit)
// @EnableAutoConfiguration geldt<SUF>
public class BudgetApplication {
public static void main(String[] args) {
//configuratie van de applicatie (context)
SpringApplication.run(BudgetApplication.class, args);
}
//todo diy is een test vanuit thymeleaf voorbeeld. komt er een internationalisation message ding bij resoures???
/*
* Message externalization/internationalization
*/
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("Messages");
return messageSource;
}
}
| false | 221 | 22 | 261 | 23 | 251 | 18 | 261 | 23 | 288 | 23 | false | false | false | false | false | true |
1,921 | 17137_0 | package menu;
import model.Review;
import java.util.Scanner;
public class ReviewMenu {
public Scanner scanner = new Scanner(System.in); // kan deze overerven uit de superklasse
public void toonMenu() {
System.out.println("1. Voeg review toe");
System.out.println("2. Terug naar hoofdmenu");
System.out.print("Maak uw keuze: ");
}
public void voerActiesUit() {
int keuze = 0;
while (keuze != 2) {
toonMenu();
keuze = scanner.nextInt(); // miss in try catch zetten
switch (keuze) {
case 1:
voegReviewToe();
break;
case 2:
break;
default:
System.out.println("Ongeldige keuze");
}
}
}
public void voegReviewToe() {
// Vraag de gebruiker voor input voor de review
System.out.println("Bedankt dat u een review wilt achterlaten! ");
System.out.println("Geef cijfers (mag kommagetallen zijn) voor de volgende 3 criteria + een toelichting:");
float scoreGameplay = checkScore("Gameplay");
float scoreGraphics = checkScore("Graphics");
float scoreStoryline = checkScore("Storyline");
System.out.print("Toelichting: ");
String toelichting = scanner.nextLine();
// Maak nieuwe model.Review aan en berekenen de gemiddelde score
Review review = new Review(scoreGameplay, scoreGraphics, scoreStoryline, toelichting);
System.out.printf("Uw gemiddelde score is %.2f%nBedankt voor uw review!",review.getGemiddeldeScore());
// Voeg nieuwe review toe aan de desbetreffende Game
// this.Game.voegReviewToe(review); // dit werkt niet, want Game is niet gedefinieerd
}
public float checkScore(String criteria) {
float answer;
while (true) {
System.out.print(criteria + ": ");
// check of de input een float is en tussen 0 en 10 ligt
if (scanner.hasNextFloat()) {
answer = scanner.nextFloat();
if (answer >= 0 && answer <= 10) {
return answer;
}
}
System.out.println("Ongeldige invoer. Voer een getal tussen 0 en 10 in.");
scanner.next();
}
}
}
| Yppis123/good_ol_games | Ranking Good ol Games/src/menu/ReviewMenu.java | 696 | // kan deze overerven uit de superklasse | line_comment | nl | package menu;
import model.Review;
import java.util.Scanner;
public class ReviewMenu {
public Scanner scanner = new Scanner(System.in); // kan deze<SUF>
public void toonMenu() {
System.out.println("1. Voeg review toe");
System.out.println("2. Terug naar hoofdmenu");
System.out.print("Maak uw keuze: ");
}
public void voerActiesUit() {
int keuze = 0;
while (keuze != 2) {
toonMenu();
keuze = scanner.nextInt(); // miss in try catch zetten
switch (keuze) {
case 1:
voegReviewToe();
break;
case 2:
break;
default:
System.out.println("Ongeldige keuze");
}
}
}
public void voegReviewToe() {
// Vraag de gebruiker voor input voor de review
System.out.println("Bedankt dat u een review wilt achterlaten! ");
System.out.println("Geef cijfers (mag kommagetallen zijn) voor de volgende 3 criteria + een toelichting:");
float scoreGameplay = checkScore("Gameplay");
float scoreGraphics = checkScore("Graphics");
float scoreStoryline = checkScore("Storyline");
System.out.print("Toelichting: ");
String toelichting = scanner.nextLine();
// Maak nieuwe model.Review aan en berekenen de gemiddelde score
Review review = new Review(scoreGameplay, scoreGraphics, scoreStoryline, toelichting);
System.out.printf("Uw gemiddelde score is %.2f%nBedankt voor uw review!",review.getGemiddeldeScore());
// Voeg nieuwe review toe aan de desbetreffende Game
// this.Game.voegReviewToe(review); // dit werkt niet, want Game is niet gedefinieerd
}
public float checkScore(String criteria) {
float answer;
while (true) {
System.out.print(criteria + ": ");
// check of de input een float is en tussen 0 en 10 ligt
if (scanner.hasNextFloat()) {
answer = scanner.nextFloat();
if (answer >= 0 && answer <= 10) {
return answer;
}
}
System.out.println("Ongeldige invoer. Voer een getal tussen 0 en 10 in.");
scanner.next();
}
}
}
| false | 552 | 11 | 610 | 11 | 597 | 9 | 610 | 11 | 684 | 11 | false | false | false | false | false | true |
6 | 21772_5 | package gameapplication.model.chess;
import gameapplication.model.MoveManager;
import gameapplication.model.chess.piece.Piece;
import gameapplication.model.chess.piece.PieceColor;
import gameapplication.model.chess.piece.PieceSets;
import gameapplication.model.chess.piece.pieces.King;
import gameapplication.model.chess.piece.pieces.Piecetype;
import gameapplication.model.chess.spot.Spot;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
/**
* The Board class is the main class of the game. It contains all the pieces and the methods to move them
*/
public class Board {
// Creating an array of pieces.
private Piece[][] pieceIntern;
//creer 2 pieceSets voor black and white
private PieceSets[] pieceSets = new PieceSets[2];
private Player[] players;
//initiliseer laatse ronde kleur met wit;
private PieceColor lastTurnColor = PieceColor.WHITE;
//creer een moveManager
private MoveManager moveManager;
private Player currentPlayer;
private boolean checkedState;
private PieceColor checkedColor;
private boolean gameOver = false;
public Board() {
//Creer 2 pieceSets
pieceSets[0] = new PieceSets(PieceColor.WHITE);
pieceSets[1] = new PieceSets(PieceColor.BLACK);
moveManager = new MoveManager(this);
players = new Player[2];
drawBoard();
}
public void generatePlayers() {
Random random = new Random();
int generatedRandomColor = random.nextInt(2);
//Zet een random kleur
players[0].setColor(PieceColor.values()[generatedRandomColor]);
//Zet de omgekeerde van de eerste kleur
players[1].setColor(PieceColor.values()[generatedRandomColor == 0 ? 1 : 0]);
//Zet huidige speler
currentPlayer = players[0];
}
/**
* For each piece set, for each piece in the piece set, set the piece's location to the piece's location
*/
public void drawBoard() {
pieceIntern = new Piece[8][8];
//Update each spot with the latest piece -> get it's type
for (PieceSets pieceSet : pieceSets) {
for (Piece piece : pieceSet.getPieces()) {
pieceIntern[piece.getColumn()][piece.getRow()] = piece;
//Zet de piece bij de bijhorende spot
pieceIntern[piece.getColumn()][piece.getRow()].getPieceLocation().setPiece(piece);
piece.getPieceLocation().setPiece(piece);
}
}
}
/**
* Find the next player in the list of players
*/
public void switchPlayer() {
//Loop through players
for (Player pl : players) {
// Find the next player
if (pl.getColor() != lastTurnColor) {
currentPlayer = pl;
}
}
lastTurnColor = currentPlayer.getColor();
}
public void nextTurn() {
drawBoard();
}
/**
* Check if the king is in check, and if so, check if it's checkmate
*/
public void checkForCheck() {
// Get all pieces from current player
List<Piece> pieces = getPieceSets()[getArrayIndexForColor(getCurrentPlayer().getColor())].getPieces();
// Initialize the king
King king = null;
// Find the king
for (Iterator<Piece> iterator = pieces.iterator(); iterator.hasNext(); ) {
Piece next = iterator.next();
if (next.getPieceType() == Piecetype.KING) {
king = (King) next;
break;
}
}
// Check if king is in check
boolean isCheck = king.isCheck(this);
// Put the status of isCheck, in the current players pieceSet
pieceSets[getArrayIndexForColor(getCurrentPlayer().getColor())].setChecked(isCheck);
// If, it's check
if (isCheck) {
// Set the color of the player, to later be retrieved by the presenter
setCheckedColor(getCurrentPlayer().getColor());
}
// Add the state to the board
setCheckedState(isCheck);
if (isCheck) {
checkForCheckmate();
}
}
// The above code is looping through all the pieces of the current player and checking if the piece can move to any of
// the spots in the valid moves array. If the spot is null, then it is not a valid move. If the spot is not null, then
// it is a valid move. If the spot is not null and the test move returns false, then the spot will evade the check.
public void checkForCheckmate() {
// Get all pieces from current player
List<Piece> pieces = getPieceSets()[getArrayIndexForColor(getCurrentPlayer().getColor())].getPieces();
//Keep a list of available moves to make during chess
List<Spot> availableMovesDuringChess = new ArrayList<>();
//loop through the pieces
for (Iterator<Piece> iterator = pieces.iterator(); iterator.hasNext(); ) {
Piece next = iterator.next();
//get the array of the current piece valid move
Spot[][] validSpots = next.validMoves(this);
//loop through them
for (Spot[] columns : validSpots) {
for (Spot spot : columns) {
if (spot == null) continue;
//if the test move return false, then the spot will evade the check
if (!moveManager.testMove(spot, next.getPieceLocation())) {
availableMovesDuringChess.add(spot);
}
}
}
}
//if list is empty, then checkmate
if (availableMovesDuringChess.isEmpty()) {
setGameOver(true);
}
}
// This is a getter method. It is used to get the value of a variable.
public Piece getPieceFromSpot(int column, int row) {
return pieceIntern[column][row];
}
public PieceColor getLastTurnColor() {
return lastTurnColor;
}
public MoveManager getMoveManager() {
return moveManager;
}
public Player getCurrentPlayer() {
return currentPlayer;
}
//get pieces by color from board
/**
* Get all the pieces from the internal board with the same color as the given color
*
* @param color The color of the pieces you want to get.
* @return A list of pieces with the same color as the parameter.
*/
public List<Piece> getPiecesFromInternalBoard(PieceColor color) {
//Initialize a list of piece as type
List<Piece> pieces = new ArrayList<>();
//Loop through pieces
for (Piece[] pieceColumns : getPieceIntern()) {
for (Piece piece : pieceColumns) {
if (piece != null && piece.getPieceColor() == color) {
//add the piece with same color
pieces.add(piece);
}
}
}
return pieces;
}
//Get array index of piecesets array
/**
* Given a color, return the array index for that color
*
* @param color The color of the piece.
* @return The index of the array that corresponds to the color.
*/
public int getArrayIndexForColor(PieceColor color) {
return color == PieceColor.WHITE ? 0 : 1;
}
/**
* This function returns the piece array
*
* @return The pieceIntern array.
*/
public Piece[][] getPieceIntern() {
return pieceIntern;
}
/**
* It sets the checked state of the checkbox.
*
* @param checkedState A boolean value that indicates whether the checkbox is checked or not.
*/
public void setCheckedState(boolean checkedState) {
this.checkedState = checkedState;
}
/**
* Returns the checked state of the checkbox
*
* @return The checked state of the checkbox.
*/
public boolean getCheckedState() {
return checkedState;
}
/**
* Get the king of a given color
*
* @param color The color of the piece you want to get.
* @return The King object for the specified color.
*/
public King getKing(PieceColor color) {
return pieceSets[getArrayIndexForColor(color)].getKing();
}
/**
* Given the current player's color, return the opponent's color
*
* @return The color of the opponent.
*/
public PieceColor getOpponentColor() {
// This is a ternary operator. It is a shorthand way of writing an if statement.
return getCurrentPlayer().getColor() == PieceColor.WHITE ? PieceColor.BLACK : PieceColor.WHITE;
}
/**
* It sets the checked color of the checkbox.
*
* @param checkedColor The color of the piece that is currently checked.
*/
public void setCheckedColor(PieceColor checkedColor) {
this.checkedColor = checkedColor;
}
/**
* Returns the color of the piece that is currently being checked
*
* @return The color that is checked.
*/
public PieceColor getCheckedColor() {
return checkedColor;
}
/**
* Returns an array of all the players in the game
*
* @return An array of Player objects.
*/
public Player[] getPlayers() {
return players;
}
/**
* It sets the players array to the players array passed in.
*
* @param players An array of Player objects.
*/
public void setPlayers(Player[] players) {
this.players = players;
}
// Setting the value of the variable `gameOver` to the value of the parameter `gameOver`.
/**
* It sets the gameOver variable to the value passed in.
*
* @param gameOver boolean
*/
private void setGameOver(boolean gameOver) {
this.gameOver = gameOver;
}
/**
* Return true if the game is over, otherwise return false.
*
* @return A boolean value.
*/
public boolean isGameOver() {
return gameOver;
}
/**
* Add a player to the game
*
* @param name The name of the player.
* @param index The index of the player to add.
*/
public void addPlayer(String name, int index) {
players[index] = new Player(name);
}
/**
* This function returns an array of PieceSets
*
* @return An array of PieceSets.
*/
public PieceSets[] getPieceSets() {
return pieceSets;
}
}
| 0xBienCuit/ChessGame | src/gameapplication/model/chess/Board.java | 2,895 | //Creer 2 pieceSets | line_comment | nl | package gameapplication.model.chess;
import gameapplication.model.MoveManager;
import gameapplication.model.chess.piece.Piece;
import gameapplication.model.chess.piece.PieceColor;
import gameapplication.model.chess.piece.PieceSets;
import gameapplication.model.chess.piece.pieces.King;
import gameapplication.model.chess.piece.pieces.Piecetype;
import gameapplication.model.chess.spot.Spot;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
/**
* The Board class is the main class of the game. It contains all the pieces and the methods to move them
*/
public class Board {
// Creating an array of pieces.
private Piece[][] pieceIntern;
//creer 2 pieceSets voor black and white
private PieceSets[] pieceSets = new PieceSets[2];
private Player[] players;
//initiliseer laatse ronde kleur met wit;
private PieceColor lastTurnColor = PieceColor.WHITE;
//creer een moveManager
private MoveManager moveManager;
private Player currentPlayer;
private boolean checkedState;
private PieceColor checkedColor;
private boolean gameOver = false;
public Board() {
//Creer 2<SUF>
pieceSets[0] = new PieceSets(PieceColor.WHITE);
pieceSets[1] = new PieceSets(PieceColor.BLACK);
moveManager = new MoveManager(this);
players = new Player[2];
drawBoard();
}
public void generatePlayers() {
Random random = new Random();
int generatedRandomColor = random.nextInt(2);
//Zet een random kleur
players[0].setColor(PieceColor.values()[generatedRandomColor]);
//Zet de omgekeerde van de eerste kleur
players[1].setColor(PieceColor.values()[generatedRandomColor == 0 ? 1 : 0]);
//Zet huidige speler
currentPlayer = players[0];
}
/**
* For each piece set, for each piece in the piece set, set the piece's location to the piece's location
*/
public void drawBoard() {
pieceIntern = new Piece[8][8];
//Update each spot with the latest piece -> get it's type
for (PieceSets pieceSet : pieceSets) {
for (Piece piece : pieceSet.getPieces()) {
pieceIntern[piece.getColumn()][piece.getRow()] = piece;
//Zet de piece bij de bijhorende spot
pieceIntern[piece.getColumn()][piece.getRow()].getPieceLocation().setPiece(piece);
piece.getPieceLocation().setPiece(piece);
}
}
}
/**
* Find the next player in the list of players
*/
public void switchPlayer() {
//Loop through players
for (Player pl : players) {
// Find the next player
if (pl.getColor() != lastTurnColor) {
currentPlayer = pl;
}
}
lastTurnColor = currentPlayer.getColor();
}
public void nextTurn() {
drawBoard();
}
/**
* Check if the king is in check, and if so, check if it's checkmate
*/
public void checkForCheck() {
// Get all pieces from current player
List<Piece> pieces = getPieceSets()[getArrayIndexForColor(getCurrentPlayer().getColor())].getPieces();
// Initialize the king
King king = null;
// Find the king
for (Iterator<Piece> iterator = pieces.iterator(); iterator.hasNext(); ) {
Piece next = iterator.next();
if (next.getPieceType() == Piecetype.KING) {
king = (King) next;
break;
}
}
// Check if king is in check
boolean isCheck = king.isCheck(this);
// Put the status of isCheck, in the current players pieceSet
pieceSets[getArrayIndexForColor(getCurrentPlayer().getColor())].setChecked(isCheck);
// If, it's check
if (isCheck) {
// Set the color of the player, to later be retrieved by the presenter
setCheckedColor(getCurrentPlayer().getColor());
}
// Add the state to the board
setCheckedState(isCheck);
if (isCheck) {
checkForCheckmate();
}
}
// The above code is looping through all the pieces of the current player and checking if the piece can move to any of
// the spots in the valid moves array. If the spot is null, then it is not a valid move. If the spot is not null, then
// it is a valid move. If the spot is not null and the test move returns false, then the spot will evade the check.
public void checkForCheckmate() {
// Get all pieces from current player
List<Piece> pieces = getPieceSets()[getArrayIndexForColor(getCurrentPlayer().getColor())].getPieces();
//Keep a list of available moves to make during chess
List<Spot> availableMovesDuringChess = new ArrayList<>();
//loop through the pieces
for (Iterator<Piece> iterator = pieces.iterator(); iterator.hasNext(); ) {
Piece next = iterator.next();
//get the array of the current piece valid move
Spot[][] validSpots = next.validMoves(this);
//loop through them
for (Spot[] columns : validSpots) {
for (Spot spot : columns) {
if (spot == null) continue;
//if the test move return false, then the spot will evade the check
if (!moveManager.testMove(spot, next.getPieceLocation())) {
availableMovesDuringChess.add(spot);
}
}
}
}
//if list is empty, then checkmate
if (availableMovesDuringChess.isEmpty()) {
setGameOver(true);
}
}
// This is a getter method. It is used to get the value of a variable.
public Piece getPieceFromSpot(int column, int row) {
return pieceIntern[column][row];
}
public PieceColor getLastTurnColor() {
return lastTurnColor;
}
public MoveManager getMoveManager() {
return moveManager;
}
public Player getCurrentPlayer() {
return currentPlayer;
}
//get pieces by color from board
/**
* Get all the pieces from the internal board with the same color as the given color
*
* @param color The color of the pieces you want to get.
* @return A list of pieces with the same color as the parameter.
*/
public List<Piece> getPiecesFromInternalBoard(PieceColor color) {
//Initialize a list of piece as type
List<Piece> pieces = new ArrayList<>();
//Loop through pieces
for (Piece[] pieceColumns : getPieceIntern()) {
for (Piece piece : pieceColumns) {
if (piece != null && piece.getPieceColor() == color) {
//add the piece with same color
pieces.add(piece);
}
}
}
return pieces;
}
//Get array index of piecesets array
/**
* Given a color, return the array index for that color
*
* @param color The color of the piece.
* @return The index of the array that corresponds to the color.
*/
public int getArrayIndexForColor(PieceColor color) {
return color == PieceColor.WHITE ? 0 : 1;
}
/**
* This function returns the piece array
*
* @return The pieceIntern array.
*/
public Piece[][] getPieceIntern() {
return pieceIntern;
}
/**
* It sets the checked state of the checkbox.
*
* @param checkedState A boolean value that indicates whether the checkbox is checked or not.
*/
public void setCheckedState(boolean checkedState) {
this.checkedState = checkedState;
}
/**
* Returns the checked state of the checkbox
*
* @return The checked state of the checkbox.
*/
public boolean getCheckedState() {
return checkedState;
}
/**
* Get the king of a given color
*
* @param color The color of the piece you want to get.
* @return The King object for the specified color.
*/
public King getKing(PieceColor color) {
return pieceSets[getArrayIndexForColor(color)].getKing();
}
/**
* Given the current player's color, return the opponent's color
*
* @return The color of the opponent.
*/
public PieceColor getOpponentColor() {
// This is a ternary operator. It is a shorthand way of writing an if statement.
return getCurrentPlayer().getColor() == PieceColor.WHITE ? PieceColor.BLACK : PieceColor.WHITE;
}
/**
* It sets the checked color of the checkbox.
*
* @param checkedColor The color of the piece that is currently checked.
*/
public void setCheckedColor(PieceColor checkedColor) {
this.checkedColor = checkedColor;
}
/**
* Returns the color of the piece that is currently being checked
*
* @return The color that is checked.
*/
public PieceColor getCheckedColor() {
return checkedColor;
}
/**
* Returns an array of all the players in the game
*
* @return An array of Player objects.
*/
public Player[] getPlayers() {
return players;
}
/**
* It sets the players array to the players array passed in.
*
* @param players An array of Player objects.
*/
public void setPlayers(Player[] players) {
this.players = players;
}
// Setting the value of the variable `gameOver` to the value of the parameter `gameOver`.
/**
* It sets the gameOver variable to the value passed in.
*
* @param gameOver boolean
*/
private void setGameOver(boolean gameOver) {
this.gameOver = gameOver;
}
/**
* Return true if the game is over, otherwise return false.
*
* @return A boolean value.
*/
public boolean isGameOver() {
return gameOver;
}
/**
* Add a player to the game
*
* @param name The name of the player.
* @param index The index of the player to add.
*/
public void addPlayer(String name, int index) {
players[index] = new Player(name);
}
/**
* This function returns an array of PieceSets
*
* @return An array of PieceSets.
*/
public PieceSets[] getPieceSets() {
return pieceSets;
}
}
| false | 2,310 | 7 | 2,389 | 7 | 2,618 | 7 | 2,389 | 7 | 2,957 | 8 | false | false | false | false | false | true |
959 | 45052_11 | package be.khleuven.nieuws;_x000D_
_x000D_
import android.app.Activity;_x000D_
import android.app.ProgressDialog;_x000D_
import android.content.Intent;_x000D_
import android.content.SharedPreferences;_x000D_
import android.graphics.Bitmap;_x000D_
import android.net.http.SslError;_x000D_
import android.os.Bundle;_x000D_
import android.view.View;_x000D_
import android.webkit.CookieSyncManager;_x000D_
import android.webkit.SslErrorHandler;_x000D_
import android.webkit.WebView;_x000D_
import android.webkit.WebViewClient;_x000D_
_x000D_
/**_x000D_
* @author Laurent Mouha, Robin Vrebos en Bram Miermans_x000D_
* _x000D_
*/_x000D_
public class KHLLoginActivity extends Activity {_x000D_
/**_x000D_
* De webview wat gebruikt wordt._x000D_
*/_x000D_
WebView myWebView;_x000D_
/**_x000D_
* De url die bijgehouden wordt in de preferences wordt hier in gezet._x000D_
*/_x000D_
String mFeedUrl = null;_x000D_
public static final String PREFS_NAME = "MyPrefsFile";_x000D_
/**_x000D_
* Hierin wordt de url opgeslagen._x000D_
*/_x000D_
static SharedPreferences settings;_x000D_
/**_x000D_
* Editor voor aanpassen van data in SharedPreferences._x000D_
*/_x000D_
SharedPreferences.Editor editor;_x000D_
_x000D_
public void onCreate(Bundle savedInstanceState) {_x000D_
super.onCreate(savedInstanceState);_x000D_
setContentView(R.layout.main);_x000D_
_x000D_
settings = getSharedPreferences(PREFS_NAME, 0);_x000D_
editor = settings.edit();_x000D_
_x000D_
mFeedUrl = settings.getString("feedUrl", null);_x000D_
_x000D_
if (mFeedUrl != null) {_x000D_
openRSS(mFeedUrl);_x000D_
} else {_x000D_
_x000D_
/**_x000D_
* Deze klasse wordt gebruikt als interface tussen de java en_x000D_
* javascriptcode die gebruikt wordt bij de webview_x000D_
* _x000D_
* @author Laurent Mouha, Robin Vrebos en Bram Miermans_x000D_
* _x000D_
*/_x000D_
class MyJavaScriptInterface {_x000D_
_x000D_
/**_x000D_
* Verwerkt de html code en opent dan de KHLNieuwsActivity._x000D_
* Wordt aangeroepen vanuit de javascriptcode._x000D_
* _x000D_
* @param html_x000D_
* De string die de htmlcode van de pagina bevat._x000D_
*/_x000D_
@SuppressWarnings("unused")_x000D_
public void processHTML(String html) {_x000D_
String link = fetchLink(html);_x000D_
editor.putString("feedUrl", link);_x000D_
editor.commit();_x000D_
openRSS(link);_x000D_
}_x000D_
_x000D_
/**_x000D_
* Deze functie doorzoekt de htmlcode naar een geldige RSS-link._x000D_
* _x000D_
* @param html_x000D_
* De string die de htmlcode van de pagina bevat._x000D_
* @return De juiste url van de RSS-feed._x000D_
*/_x000D_
private String fetchLink(String html) {_x000D_
String[] temp;_x000D_
temp = html.split("\n");_x000D_
String link = "";_x000D_
boolean stop = false;_x000D_
try {_x000D_
for (String t : temp) {_x000D_
if (t.contains("<a href=\"http://portaal.khleuven.be/rss.php")) {_x000D_
link = t;_x000D_
stop = true;_x000D_
}_x000D_
if (stop)_x000D_
break;_x000D_
}_x000D_
_x000D_
} catch (Exception e) {_x000D_
_x000D_
} finally {_x000D_
if (link != null) {_x000D_
_x000D_
String[] parts = link.split("\"");_x000D_
link = parts[1];_x000D_
_x000D_
}_x000D_
}_x000D_
return link;_x000D_
}_x000D_
}_x000D_
_x000D_
// cookie bijhouden_x000D_
CookieSyncManager.createInstance(this);_x000D_
CookieSyncManager.getInstance().startSync();_x000D_
_x000D_
// webview gebruiken voor login_x000D_
myWebView = (WebView) findViewById(R.id.webview);_x000D_
myWebView.getSettings().setJavaScriptEnabled(true);_x000D_
myWebView.setWebViewClient(new WebViewClient() {_x000D_
public void onReceivedSslError(WebView view,_x000D_
SslErrorHandler handler, SslError error) {_x000D_
handler.proceed(); // Ignore SSL certificate errors_x000D_
}_x000D_
_x000D_
// wat doen wanneer pagina geladen is_x000D_
// checken of ingelogd door te kijken of we terug op de_x000D_
// portaalsite zitten_x000D_
public void onPageFinished(WebView view, String url) {_x000D_
if (view.getUrl().equals("https://portaal.khleuven.be/")) {_x000D_
view.loadUrl("javascript:window.interfaceName.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");_x000D_
}_x000D_
}_x000D_
_x000D_
public void onPageStarted(WebView view, String url,_x000D_
Bitmap favicon) {_x000D_
if (url.equals("https://portaal.khleuven.be/")) {_x000D_
view.setVisibility(View.INVISIBLE);_x000D_
ProgressDialog.show(_x000D_
KHLLoginActivity.this, "",_x000D_
"Fetching RSS. Please wait...", true);_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
myWebView.getSettings().setDatabasePath("khl.news");_x000D_
myWebView.getSettings().setDomStorageEnabled(true);_x000D_
_x000D_
myWebView.addJavascriptInterface(new MyJavaScriptInterface(),_x000D_
"interfaceName");_x000D_
_x000D_
myWebView_x000D_
.loadUrl("https://portaal.khleuven.be/Shibboleth.sso/WAYF/khleuven?target=https%3A%2F%2Fportaal.khleuven.be%2F");_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
private void openRSS(String link) {_x000D_
Intent intent = new Intent(getApplicationContext(),_x000D_
KHLNieuwsActivity.class);_x000D_
intent.putExtra("feedUrl", link);_x000D_
startActivity(intent);_x000D_
}_x000D_
_x000D_
} | LaurentMouha/KHLNieuws | src/be/khleuven/nieuws/KHLLoginActivity.java | 1,583 | // checken of ingelogd door te kijken of we terug op de_x000D_ | line_comment | nl | package be.khleuven.nieuws;_x000D_
_x000D_
import android.app.Activity;_x000D_
import android.app.ProgressDialog;_x000D_
import android.content.Intent;_x000D_
import android.content.SharedPreferences;_x000D_
import android.graphics.Bitmap;_x000D_
import android.net.http.SslError;_x000D_
import android.os.Bundle;_x000D_
import android.view.View;_x000D_
import android.webkit.CookieSyncManager;_x000D_
import android.webkit.SslErrorHandler;_x000D_
import android.webkit.WebView;_x000D_
import android.webkit.WebViewClient;_x000D_
_x000D_
/**_x000D_
* @author Laurent Mouha, Robin Vrebos en Bram Miermans_x000D_
* _x000D_
*/_x000D_
public class KHLLoginActivity extends Activity {_x000D_
/**_x000D_
* De webview wat gebruikt wordt._x000D_
*/_x000D_
WebView myWebView;_x000D_
/**_x000D_
* De url die bijgehouden wordt in de preferences wordt hier in gezet._x000D_
*/_x000D_
String mFeedUrl = null;_x000D_
public static final String PREFS_NAME = "MyPrefsFile";_x000D_
/**_x000D_
* Hierin wordt de url opgeslagen._x000D_
*/_x000D_
static SharedPreferences settings;_x000D_
/**_x000D_
* Editor voor aanpassen van data in SharedPreferences._x000D_
*/_x000D_
SharedPreferences.Editor editor;_x000D_
_x000D_
public void onCreate(Bundle savedInstanceState) {_x000D_
super.onCreate(savedInstanceState);_x000D_
setContentView(R.layout.main);_x000D_
_x000D_
settings = getSharedPreferences(PREFS_NAME, 0);_x000D_
editor = settings.edit();_x000D_
_x000D_
mFeedUrl = settings.getString("feedUrl", null);_x000D_
_x000D_
if (mFeedUrl != null) {_x000D_
openRSS(mFeedUrl);_x000D_
} else {_x000D_
_x000D_
/**_x000D_
* Deze klasse wordt gebruikt als interface tussen de java en_x000D_
* javascriptcode die gebruikt wordt bij de webview_x000D_
* _x000D_
* @author Laurent Mouha, Robin Vrebos en Bram Miermans_x000D_
* _x000D_
*/_x000D_
class MyJavaScriptInterface {_x000D_
_x000D_
/**_x000D_
* Verwerkt de html code en opent dan de KHLNieuwsActivity._x000D_
* Wordt aangeroepen vanuit de javascriptcode._x000D_
* _x000D_
* @param html_x000D_
* De string die de htmlcode van de pagina bevat._x000D_
*/_x000D_
@SuppressWarnings("unused")_x000D_
public void processHTML(String html) {_x000D_
String link = fetchLink(html);_x000D_
editor.putString("feedUrl", link);_x000D_
editor.commit();_x000D_
openRSS(link);_x000D_
}_x000D_
_x000D_
/**_x000D_
* Deze functie doorzoekt de htmlcode naar een geldige RSS-link._x000D_
* _x000D_
* @param html_x000D_
* De string die de htmlcode van de pagina bevat._x000D_
* @return De juiste url van de RSS-feed._x000D_
*/_x000D_
private String fetchLink(String html) {_x000D_
String[] temp;_x000D_
temp = html.split("\n");_x000D_
String link = "";_x000D_
boolean stop = false;_x000D_
try {_x000D_
for (String t : temp) {_x000D_
if (t.contains("<a href=\"http://portaal.khleuven.be/rss.php")) {_x000D_
link = t;_x000D_
stop = true;_x000D_
}_x000D_
if (stop)_x000D_
break;_x000D_
}_x000D_
_x000D_
} catch (Exception e) {_x000D_
_x000D_
} finally {_x000D_
if (link != null) {_x000D_
_x000D_
String[] parts = link.split("\"");_x000D_
link = parts[1];_x000D_
_x000D_
}_x000D_
}_x000D_
return link;_x000D_
}_x000D_
}_x000D_
_x000D_
// cookie bijhouden_x000D_
CookieSyncManager.createInstance(this);_x000D_
CookieSyncManager.getInstance().startSync();_x000D_
_x000D_
// webview gebruiken voor login_x000D_
myWebView = (WebView) findViewById(R.id.webview);_x000D_
myWebView.getSettings().setJavaScriptEnabled(true);_x000D_
myWebView.setWebViewClient(new WebViewClient() {_x000D_
public void onReceivedSslError(WebView view,_x000D_
SslErrorHandler handler, SslError error) {_x000D_
handler.proceed(); // Ignore SSL certificate errors_x000D_
}_x000D_
_x000D_
// wat doen wanneer pagina geladen is_x000D_
// checken of<SUF>
// portaalsite zitten_x000D_
public void onPageFinished(WebView view, String url) {_x000D_
if (view.getUrl().equals("https://portaal.khleuven.be/")) {_x000D_
view.loadUrl("javascript:window.interfaceName.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");_x000D_
}_x000D_
}_x000D_
_x000D_
public void onPageStarted(WebView view, String url,_x000D_
Bitmap favicon) {_x000D_
if (url.equals("https://portaal.khleuven.be/")) {_x000D_
view.setVisibility(View.INVISIBLE);_x000D_
ProgressDialog.show(_x000D_
KHLLoginActivity.this, "",_x000D_
"Fetching RSS. Please wait...", true);_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
myWebView.getSettings().setDatabasePath("khl.news");_x000D_
myWebView.getSettings().setDomStorageEnabled(true);_x000D_
_x000D_
myWebView.addJavascriptInterface(new MyJavaScriptInterface(),_x000D_
"interfaceName");_x000D_
_x000D_
myWebView_x000D_
.loadUrl("https://portaal.khleuven.be/Shibboleth.sso/WAYF/khleuven?target=https%3A%2F%2Fportaal.khleuven.be%2F");_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
private void openRSS(String link) {_x000D_
Intent intent = new Intent(getApplicationContext(),_x000D_
KHLNieuwsActivity.class);_x000D_
intent.putExtra("feedUrl", link);_x000D_
startActivity(intent);_x000D_
}_x000D_
_x000D_
} | false | 2,145 | 21 | 2,395 | 26 | 2,379 | 22 | 2,395 | 26 | 2,833 | 25 | false | false | false | false | false | true |
436 | 79059_1 | package h7.interface3.bke.models;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import h7.interface3.bke.interfaces.Model;
class BKEModelTest {
Model model;
@BeforeEach
void beforeEach() {
model = new BKEModel();
}
@Test
void testGetSetCurrentPlayer() {
assertEquals(Model.PLAYER1, model.getCurrentPlayer(), "Eerste speler");
model.setCurrentPlayer(Model.PLAYER2);
assertEquals(Model.PLAYER2, model.getCurrentPlayer(), "Aanpassen speler");
model.setCurrentPlayer('t');
assertEquals(Model.PLAYER2, model.getCurrentPlayer(), "Ongeldige speler");
}
@Test
void testSetField() {
int testId = 1;
model.setField(testId);
assertEquals(model.getCurrentPlayer(), model.getFields()[testId], "Goede veld gezet");
for (int i=0; i<BKEModel.FIELDCOUNT; i++) {
if (i!=testId) {
assertEquals(0, model.getFields()[i], "Veld "+i+" niet gezet");
}
}
}
@Test
void testCanSet() {
int testId = 1;
assertEquals(true, model.canSet(testId), "Leeg veld");
model.setField(testId);
assertEquals(false, model.canSet(testId),"Veld al gevuld");
model.setField(-1);
assertEquals(false, model.canSet(testId),"Id te laag");
model.setField(10);
assertEquals(false, model.canSet(testId),"Id te hoog");
}
@Test
void testGetTurns() {
assertEquals(0, model.getTurns(), "Start van het spel");
model.setField(1);
assertEquals(1, model.getTurns(), "Een beurt geweest");
//zelfde veld, dus geen verandering in aantal beurten
model.setField(1);
assertEquals(1, model.getTurns(), "Verkeerde zet, geen extra beurt");
model.setField(2);
assertEquals(2, model.getTurns(), "Twee beurten geweest");
}
@Test
void testReset() {
//zet 2 velden in het model
model.setField(1);
model.setCurrentPlayer(Model.PLAYER2);
model.setField(2);
assertEquals(2, model.getTurns(), "2 beurten");
model.reset();
//alle velden moeten leeg zijn en huidige speler PLAYER1
assertEquals(Model.PLAYER1, model.getCurrentPlayer(),"Speler 1");
assertEquals(0, model.getTurns(), "0 beurten");
for(char check: model.getFields()) {
assertEquals(0, check, "Veld is niet leeg");
}
}
}
| DrentheCollege/LE-A4-Java-MVC-Testen | src/h7/interface3/bke/models/BKEModelTest.java | 843 | //zet 2 velden in het model | line_comment | nl | package h7.interface3.bke.models;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import h7.interface3.bke.interfaces.Model;
class BKEModelTest {
Model model;
@BeforeEach
void beforeEach() {
model = new BKEModel();
}
@Test
void testGetSetCurrentPlayer() {
assertEquals(Model.PLAYER1, model.getCurrentPlayer(), "Eerste speler");
model.setCurrentPlayer(Model.PLAYER2);
assertEquals(Model.PLAYER2, model.getCurrentPlayer(), "Aanpassen speler");
model.setCurrentPlayer('t');
assertEquals(Model.PLAYER2, model.getCurrentPlayer(), "Ongeldige speler");
}
@Test
void testSetField() {
int testId = 1;
model.setField(testId);
assertEquals(model.getCurrentPlayer(), model.getFields()[testId], "Goede veld gezet");
for (int i=0; i<BKEModel.FIELDCOUNT; i++) {
if (i!=testId) {
assertEquals(0, model.getFields()[i], "Veld "+i+" niet gezet");
}
}
}
@Test
void testCanSet() {
int testId = 1;
assertEquals(true, model.canSet(testId), "Leeg veld");
model.setField(testId);
assertEquals(false, model.canSet(testId),"Veld al gevuld");
model.setField(-1);
assertEquals(false, model.canSet(testId),"Id te laag");
model.setField(10);
assertEquals(false, model.canSet(testId),"Id te hoog");
}
@Test
void testGetTurns() {
assertEquals(0, model.getTurns(), "Start van het spel");
model.setField(1);
assertEquals(1, model.getTurns(), "Een beurt geweest");
//zelfde veld, dus geen verandering in aantal beurten
model.setField(1);
assertEquals(1, model.getTurns(), "Verkeerde zet, geen extra beurt");
model.setField(2);
assertEquals(2, model.getTurns(), "Twee beurten geweest");
}
@Test
void testReset() {
//zet 2<SUF>
model.setField(1);
model.setCurrentPlayer(Model.PLAYER2);
model.setField(2);
assertEquals(2, model.getTurns(), "2 beurten");
model.reset();
//alle velden moeten leeg zijn en huidige speler PLAYER1
assertEquals(Model.PLAYER1, model.getCurrentPlayer(),"Speler 1");
assertEquals(0, model.getTurns(), "0 beurten");
for(char check: model.getFields()) {
assertEquals(0, check, "Veld is niet leeg");
}
}
}
| false | 646 | 9 | 771 | 9 | 744 | 9 | 771 | 9 | 906 | 9 | false | false | false | false | false | true |
3,510 | 144199_0 | /*
* Subnet Manager – Java OO en Gegevens Banken Project
*/
package Objects;
import Logic.SubnetHelper;
import java.util.Arrays;
/**
*
* @author louisdhauwe
*/
public class Address {
private short[] address = new short[4];
/**
*
* @param address
*/
public Address(short[] address) {
this.address = address;
}
/**
* Returns long because primitives (such as int) are signed in Java
* @return decimal value of the address
*/
public long decimalValue() {
return SubnetHelper.decimalValueForBinaryBitString(SubnetHelper.binaryStringForAddress(this));
}
@Override
public String toString() {
return address[0] + "." + address[1] + "." + address[2] + "." + address[3];
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Address)) {
return false;
}
for (int i = 0; i < address.length; i++) {
if (((Address)o).getAddress()[i] != getAddress()[i]) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
int hash = 3;
hash = 73 * hash + Arrays.hashCode(this.address);
return hash;
}
/**
* @return the address
*/
public short[] getAddress() {
return address;
}
/**
* @param address the address to set
*/
public void setAddress(short[] address) {
this.address = address;
}
}
| louisdh/subnet-manager-java | src/Objects/Address.java | 459 | /*
* Subnet Manager – Java OO en Gegevens Banken Project
*/ | block_comment | nl | /*
* Subnet Manager –<SUF>*/
package Objects;
import Logic.SubnetHelper;
import java.util.Arrays;
/**
*
* @author louisdhauwe
*/
public class Address {
private short[] address = new short[4];
/**
*
* @param address
*/
public Address(short[] address) {
this.address = address;
}
/**
* Returns long because primitives (such as int) are signed in Java
* @return decimal value of the address
*/
public long decimalValue() {
return SubnetHelper.decimalValueForBinaryBitString(SubnetHelper.binaryStringForAddress(this));
}
@Override
public String toString() {
return address[0] + "." + address[1] + "." + address[2] + "." + address[3];
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Address)) {
return false;
}
for (int i = 0; i < address.length; i++) {
if (((Address)o).getAddress()[i] != getAddress()[i]) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
int hash = 3;
hash = 73 * hash + Arrays.hashCode(this.address);
return hash;
}
/**
* @return the address
*/
public short[] getAddress() {
return address;
}
/**
* @param address the address to set
*/
public void setAddress(short[] address) {
this.address = address;
}
}
| false | 364 | 19 | 376 | 20 | 433 | 17 | 376 | 20 | 467 | 21 | false | false | false | false | false | true |
2,183 | 43918_6 | /*
* This file is part of amumag,
* a finite-element micromagnetic simulation program.
* Copyright (C) 2006-2008 Arne Vansteenkiste
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details (licence.txt).
*/
package refsh;
import amu.debug.*;
import java.lang.reflect.*;
import java.io.*;
/**
* Prints text representations of objects and classes for debugging/ general output.
*/
public final class Reflect {
// Debugging is, in general, a cumbersome and tiring task.
// Wikipedia.
/**
* Prints the values of all fields of the object.
*/
public static void printObject(Object obj, PrintStream out){
out.println(toString(obj) + "{");
for(Class clazz = obj.getClass(); clazz != null; clazz = clazz.getSuperclass()){
Field[] fields = clazz.getDeclaredFields();
try{
AccessibleObject.setAccessible(fields,true);
}
catch(SecurityException e){
}
for(Field field: fields){
if(!Modifier.isStatic(field.getModifiers())){
out.print("\t" + field.getName());
try {
Object value = field.get(obj);
out.print(" = ");
printObjectShort(value, out);
out.println();
}
catch (IllegalArgumentException ex) {
throw new Bug();
}
catch (IllegalAccessException e2) {
out.println(" : access denied");
}
}
}
out.println();
}
out.println("}");
}
/**
* Prints the values of all fields of the object to the standard output.
*/
public static void printObject(Object obj){
printObject(obj, System.out);
}
public static void printClass(Class clazz, PrintStream out){
out.println(clazz.getName() + "{");
Field[] fields = clazz.getDeclaredFields();
try{
AccessibleObject.setAccessible(fields,true);
}
catch(SecurityException e){
}
for(Field field: fields){
if(Modifier.isStatic(field.getModifiers())){
out.print("\t" + field.getName());
try {
Object value = field.get(null);
out.print(" = ");
printObjectShort(value, out);
out.println();
} catch (IllegalArgumentException ex) {
throw new Bug();
} catch (IllegalAccessException e2) {
out.println(" : access denied");
}
}
}
out.println("}");
}
public static void printClass(Class clazz){
printClass(clazz, System.out);
}
public static void printObjectShort(Object obj, PrintStream out){
if(obj == null)
out.print(obj);
else if(obj.getClass().isArray()){
out.print(toString(obj) + "{");
int length = Array.getLength(obj);
if(length != 0)
printObjectShort(Array.get(obj, 0), out);
for(int i=1; i<length; i++){
out.print(", ");
printObjectShort(Array.get(obj, i), out);
}
out.print("}");
}
else{
out.print(obj);
}
}
/**
* Creates an easily readible String representation for the Object.
*/
public static synchronized String toString(Object obj){
if(obj == null){
return "null";
} else{
return classString(obj.getClass()) + createNumber(obj);
}
}
private static int createNumber(Object obj){
return System.identityHashCode(obj);
}
/**
* Mooie String voor een klasse, ook array's worden goed weergegeven.
*/
private static String classString(Class clazz){
if(clazz.isArray())
return classString(clazz.getComponentType()) + "[]";
else
return crop(clazz.getName());
}
/**
* Removes the package prefix
*/
private static String crop(String className){
int i = className.length()-1;
while(i > -1 && className.charAt(i) != '.')
i--;
return className.substring(++i, className.length());
}
}
| barnex/amumag | refsh/Reflect.java | 1,346 | /**
* Mooie String voor een klasse, ook array's worden goed weergegeven.
*/ | block_comment | nl | /*
* This file is part of amumag,
* a finite-element micromagnetic simulation program.
* Copyright (C) 2006-2008 Arne Vansteenkiste
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details (licence.txt).
*/
package refsh;
import amu.debug.*;
import java.lang.reflect.*;
import java.io.*;
/**
* Prints text representations of objects and classes for debugging/ general output.
*/
public final class Reflect {
// Debugging is, in general, a cumbersome and tiring task.
// Wikipedia.
/**
* Prints the values of all fields of the object.
*/
public static void printObject(Object obj, PrintStream out){
out.println(toString(obj) + "{");
for(Class clazz = obj.getClass(); clazz != null; clazz = clazz.getSuperclass()){
Field[] fields = clazz.getDeclaredFields();
try{
AccessibleObject.setAccessible(fields,true);
}
catch(SecurityException e){
}
for(Field field: fields){
if(!Modifier.isStatic(field.getModifiers())){
out.print("\t" + field.getName());
try {
Object value = field.get(obj);
out.print(" = ");
printObjectShort(value, out);
out.println();
}
catch (IllegalArgumentException ex) {
throw new Bug();
}
catch (IllegalAccessException e2) {
out.println(" : access denied");
}
}
}
out.println();
}
out.println("}");
}
/**
* Prints the values of all fields of the object to the standard output.
*/
public static void printObject(Object obj){
printObject(obj, System.out);
}
public static void printClass(Class clazz, PrintStream out){
out.println(clazz.getName() + "{");
Field[] fields = clazz.getDeclaredFields();
try{
AccessibleObject.setAccessible(fields,true);
}
catch(SecurityException e){
}
for(Field field: fields){
if(Modifier.isStatic(field.getModifiers())){
out.print("\t" + field.getName());
try {
Object value = field.get(null);
out.print(" = ");
printObjectShort(value, out);
out.println();
} catch (IllegalArgumentException ex) {
throw new Bug();
} catch (IllegalAccessException e2) {
out.println(" : access denied");
}
}
}
out.println("}");
}
public static void printClass(Class clazz){
printClass(clazz, System.out);
}
public static void printObjectShort(Object obj, PrintStream out){
if(obj == null)
out.print(obj);
else if(obj.getClass().isArray()){
out.print(toString(obj) + "{");
int length = Array.getLength(obj);
if(length != 0)
printObjectShort(Array.get(obj, 0), out);
for(int i=1; i<length; i++){
out.print(", ");
printObjectShort(Array.get(obj, i), out);
}
out.print("}");
}
else{
out.print(obj);
}
}
/**
* Creates an easily readible String representation for the Object.
*/
public static synchronized String toString(Object obj){
if(obj == null){
return "null";
} else{
return classString(obj.getClass()) + createNumber(obj);
}
}
private static int createNumber(Object obj){
return System.identityHashCode(obj);
}
/**
* Mooie String voor<SUF>*/
private static String classString(Class clazz){
if(clazz.isArray())
return classString(clazz.getComponentType()) + "[]";
else
return crop(clazz.getName());
}
/**
* Removes the package prefix
*/
private static String crop(String className){
int i = className.length()-1;
while(i > -1 && className.charAt(i) != '.')
i--;
return className.substring(++i, className.length());
}
}
| false | 958 | 23 | 1,083 | 25 | 1,212 | 23 | 1,083 | 25 | 1,349 | 28 | false | false | false | false | false | true |
1,697 | 129147_0 | package net.larsmans.infinitybuttons.block.custom.button;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.larsmans.infinitybuttons.InfinityButtonsInit;
import net.larsmans.infinitybuttons.InfinityButtonsUtil;
import net.larsmans.infinitybuttons.particle.InfinityButtonsParticleTypes;
import net.minecraft.block.BlockState;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.item.ItemStack;
import net.minecraft.sound.SoundEvent;
import net.minecraft.sound.SoundEvents;
import net.minecraft.text.Text;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.random.Random;
import net.minecraft.world.BlockView;
import net.minecraft.world.World;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public class DiamondButton extends AbstractSmallButton {
private final boolean large;
public DiamondButton(FabricBlockSettings settings, boolean large) {
super(false, large, settings);
this.large = large;
}
@Override
public int getPressTicks() {
return 20;
}
@Override
protected SoundEvent getClickSound(boolean var1) {
return var1 ? SoundEvents.BLOCK_STONE_BUTTON_CLICK_ON : SoundEvents.BLOCK_STONE_BUTTON_CLICK_OFF;
}
@Override
public void randomDisplayTick(BlockState state, World world, BlockPos pos, Random random) {
if (InfinityButtonsInit.CONFIG.diamondParticles() && random.nextInt(3) == 0) {
if (large) {
switch (state.get(FACE)) {
case FLOOR -> addParticle(3, 10, 2, 1, 3, 10, world, pos, random);
case WALL -> {
switch (state.get(FACING)) {
case NORTH -> addParticle(3, 10, 3, 10, 13, 1, world, pos, random);
case EAST -> addParticle(2, 1, 3, 10, 3, 10, world, pos, random);
case SOUTH -> addParticle(3, 10, 3, 10, 2, 1, world, pos, random);
case WEST -> addParticle(13, 1, 3, 10, 3, 10, world, pos, random);
}
}
case CEILING -> addParticle(3, 10, 13, 1, 3, 10, world, pos, random);
}
} else {
switch (state.get(FACE)) {
case FLOOR -> {
switch (state.get(FACING)) {
case NORTH, SOUTH -> addParticle(4, 8, 2, 1, 5, 6, world, pos, random);
case EAST, WEST -> addParticle(5, 6, 2, 1, 4, 8, world, pos, random);
}
}
case WALL -> {
switch (state.get(FACING)) {
case NORTH -> addParticle(4, 8, 5, 6, 13, 1, world, pos, random);
case EAST -> addParticle(2, 1, 5, 6, 4, 8, world, pos, random);
case SOUTH -> addParticle(4, 8, 5, 6, 2, 1, world, pos, random);
case WEST -> addParticle(13, 1, 5, 6, 4, 8, world, pos, random);
}
}
case CEILING -> {
switch (state.get(FACING)) {
case NORTH, SOUTH -> addParticle(4, 8, 13, 1, 5, 6, world, pos, random);
case EAST, WEST -> addParticle(5, 6, 13, 1, 4, 8, world, pos, random);
}
}
}
}
}
}
public void addParticle(int x1, int x2, int y1, int y2, int z1, int z2, World world, BlockPos pos, Random random) {
// we kunnen het in de rewrite met een VoxelShape doen en ook draaien enzo :)
world.addParticle(InfinityButtonsParticleTypes.DIAMOND_SPARKLE,
pos.getX() + (double) x1 / 16 + random.nextFloat() * (double) x2 / 16,
pos.getY() + (double) y1 / 16 + random.nextFloat() * (double) y2 / 16,
pos.getZ() + (double) z1 / 16 + random.nextFloat() * (double) z2 / 16,
0, 0, 0);
}
@Override
public void appendTooltip(ItemStack stack, @Nullable BlockView world, List<Text> tooltip, TooltipContext options) {
InfinityButtonsUtil.tooltip(tooltip, "diamond_button");
}
}
| TeamDiopside/InfinityButtons | src/main/java/net/larsmans/infinitybuttons/block/custom/button/DiamondButton.java | 1,413 | // we kunnen het in de rewrite met een VoxelShape doen en ook draaien enzo :) | line_comment | nl | package net.larsmans.infinitybuttons.block.custom.button;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.larsmans.infinitybuttons.InfinityButtonsInit;
import net.larsmans.infinitybuttons.InfinityButtonsUtil;
import net.larsmans.infinitybuttons.particle.InfinityButtonsParticleTypes;
import net.minecraft.block.BlockState;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.item.ItemStack;
import net.minecraft.sound.SoundEvent;
import net.minecraft.sound.SoundEvents;
import net.minecraft.text.Text;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.random.Random;
import net.minecraft.world.BlockView;
import net.minecraft.world.World;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public class DiamondButton extends AbstractSmallButton {
private final boolean large;
public DiamondButton(FabricBlockSettings settings, boolean large) {
super(false, large, settings);
this.large = large;
}
@Override
public int getPressTicks() {
return 20;
}
@Override
protected SoundEvent getClickSound(boolean var1) {
return var1 ? SoundEvents.BLOCK_STONE_BUTTON_CLICK_ON : SoundEvents.BLOCK_STONE_BUTTON_CLICK_OFF;
}
@Override
public void randomDisplayTick(BlockState state, World world, BlockPos pos, Random random) {
if (InfinityButtonsInit.CONFIG.diamondParticles() && random.nextInt(3) == 0) {
if (large) {
switch (state.get(FACE)) {
case FLOOR -> addParticle(3, 10, 2, 1, 3, 10, world, pos, random);
case WALL -> {
switch (state.get(FACING)) {
case NORTH -> addParticle(3, 10, 3, 10, 13, 1, world, pos, random);
case EAST -> addParticle(2, 1, 3, 10, 3, 10, world, pos, random);
case SOUTH -> addParticle(3, 10, 3, 10, 2, 1, world, pos, random);
case WEST -> addParticle(13, 1, 3, 10, 3, 10, world, pos, random);
}
}
case CEILING -> addParticle(3, 10, 13, 1, 3, 10, world, pos, random);
}
} else {
switch (state.get(FACE)) {
case FLOOR -> {
switch (state.get(FACING)) {
case NORTH, SOUTH -> addParticle(4, 8, 2, 1, 5, 6, world, pos, random);
case EAST, WEST -> addParticle(5, 6, 2, 1, 4, 8, world, pos, random);
}
}
case WALL -> {
switch (state.get(FACING)) {
case NORTH -> addParticle(4, 8, 5, 6, 13, 1, world, pos, random);
case EAST -> addParticle(2, 1, 5, 6, 4, 8, world, pos, random);
case SOUTH -> addParticle(4, 8, 5, 6, 2, 1, world, pos, random);
case WEST -> addParticle(13, 1, 5, 6, 4, 8, world, pos, random);
}
}
case CEILING -> {
switch (state.get(FACING)) {
case NORTH, SOUTH -> addParticle(4, 8, 13, 1, 5, 6, world, pos, random);
case EAST, WEST -> addParticle(5, 6, 13, 1, 4, 8, world, pos, random);
}
}
}
}
}
}
public void addParticle(int x1, int x2, int y1, int y2, int z1, int z2, World world, BlockPos pos, Random random) {
// we kunnen<SUF>
world.addParticle(InfinityButtonsParticleTypes.DIAMOND_SPARKLE,
pos.getX() + (double) x1 / 16 + random.nextFloat() * (double) x2 / 16,
pos.getY() + (double) y1 / 16 + random.nextFloat() * (double) y2 / 16,
pos.getZ() + (double) z1 / 16 + random.nextFloat() * (double) z2 / 16,
0, 0, 0);
}
@Override
public void appendTooltip(ItemStack stack, @Nullable BlockView world, List<Text> tooltip, TooltipContext options) {
InfinityButtonsUtil.tooltip(tooltip, "diamond_button");
}
}
| false | 1,088 | 21 | 1,228 | 25 | 1,251 | 20 | 1,228 | 25 | 1,449 | 23 | false | false | false | false | false | true |
1,907 | 203698_0 | package be.odisee.solver;
import be.odisee.domain.*;
import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore;
import org.optaplanner.core.api.score.stream.Constraint;
import org.optaplanner.core.api.score.stream.ConstraintFactory;
import org.optaplanner.core.api.score.stream.ConstraintProvider;
import org.optaplanner.core.api.score.stream.Joiners;
public class ExamTableConstraintProvider implements ConstraintProvider {
@Override
public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
return new Constraint[]{
studentExamTimeSlotConflict(constraintFactory),
timeSlotsBetweenExamsConflict(constraintFactory)
};
}
Constraint studentExamTimeSlotConflict(ConstraintFactory constraintFactory) {
return constraintFactory.forEachUniquePair(Exam.class, Joiners.equal(Exam::getTimeSlot))
.filter((exam1, exam2) -> {
boolean found = false;
for (Student student : exam1.getStudentsList()) {
if (exam2.getStudentsList().contains(student)) {
found = true;
break;
}
}
return found; // Student in zelfde examen? true indien in beide examens.
})
.penalize("Student timeslot conflict", HardSoftScore.ONE_HARD);
}
Constraint timeSlotsBetweenExamsConflict(ConstraintFactory constraintFactory) {
return constraintFactory.forEachUniquePair(Exam.class)
.penalize("Timeslots between exams conflict", HardSoftScore.ONE_SOFT, (exam1, exam2) -> {
int scoreCount = 0;
if (exam1.getTimeSlot().getId() != exam2.getTimeSlot().getId()) { // Beide examens vallen in het zelfde tijdslot
for (Student studentExam1 : exam1.getStudentsList()) {
if (exam2.getStudentsList().contains(studentExam1)) {
int timeslotDiff = Math.abs(exam1.getTimeSlot().getId() - exam2.getTimeSlot().getId());
switch (timeslotDiff) {
case 0:
scoreCount = 16;
break;
case 1:
scoreCount = 8;
break;
case 2:
scoreCount = 4;
break;
case 3:
scoreCount = 2;
break;
case 4:
scoreCount = 1;
break;
default:
break;
}
}
}
}
return scoreCount;
});
}
}
| Xevro/Metaheuristics-exam-scheduling | src/main/java/be/odisee/solver/ExamTableConstraintProvider.java | 783 | // Student in zelfde examen? true indien in beide examens. | line_comment | nl | package be.odisee.solver;
import be.odisee.domain.*;
import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore;
import org.optaplanner.core.api.score.stream.Constraint;
import org.optaplanner.core.api.score.stream.ConstraintFactory;
import org.optaplanner.core.api.score.stream.ConstraintProvider;
import org.optaplanner.core.api.score.stream.Joiners;
public class ExamTableConstraintProvider implements ConstraintProvider {
@Override
public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
return new Constraint[]{
studentExamTimeSlotConflict(constraintFactory),
timeSlotsBetweenExamsConflict(constraintFactory)
};
}
Constraint studentExamTimeSlotConflict(ConstraintFactory constraintFactory) {
return constraintFactory.forEachUniquePair(Exam.class, Joiners.equal(Exam::getTimeSlot))
.filter((exam1, exam2) -> {
boolean found = false;
for (Student student : exam1.getStudentsList()) {
if (exam2.getStudentsList().contains(student)) {
found = true;
break;
}
}
return found; // Student in<SUF>
})
.penalize("Student timeslot conflict", HardSoftScore.ONE_HARD);
}
Constraint timeSlotsBetweenExamsConflict(ConstraintFactory constraintFactory) {
return constraintFactory.forEachUniquePair(Exam.class)
.penalize("Timeslots between exams conflict", HardSoftScore.ONE_SOFT, (exam1, exam2) -> {
int scoreCount = 0;
if (exam1.getTimeSlot().getId() != exam2.getTimeSlot().getId()) { // Beide examens vallen in het zelfde tijdslot
for (Student studentExam1 : exam1.getStudentsList()) {
if (exam2.getStudentsList().contains(studentExam1)) {
int timeslotDiff = Math.abs(exam1.getTimeSlot().getId() - exam2.getTimeSlot().getId());
switch (timeslotDiff) {
case 0:
scoreCount = 16;
break;
case 1:
scoreCount = 8;
break;
case 2:
scoreCount = 4;
break;
case 3:
scoreCount = 2;
break;
case 4:
scoreCount = 1;
break;
default:
break;
}
}
}
}
return scoreCount;
});
}
}
| false | 524 | 16 | 591 | 18 | 646 | 14 | 591 | 18 | 771 | 16 | false | false | false | false | false | true |
3,985 | 115383_0 | /*
* Copyright TNO Geologische Dienst Nederland
*
* Alle rechten voorbehouden.
* Niets uit deze software mag worden vermenigvuldigd en/of openbaar gemaakt door middel van druk, fotokopie,
* microfilm of op welke andere wijze dan ook, zonder voorafgaande toestemming van TNO.
*
* Indien deze software in opdracht werd uitgebracht, wordt voor de rechten en verplichtingen van opdrachtgever
* en opdrachtnemer verwezen naar de Algemene Voorwaarden voor opdrachten aan TNO, dan wel de betreffende
* terzake tussen de partijen gesloten overeenkomst.
*/
package nl.reproducer.vertx;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import io.quarkus.vertx.web.RouteFilter;
import io.vertx.ext.web.RoutingContext;
import org.eclipse.microprofile.config.inject.ConfigProperty;
public class ApiVersionResponseFilter {
private static final String API_VERSION_HEADER = "API-Version";
//CHECKSTYLE:OFF
@Inject
ConfigProvider provider;
//CHECKSTYLE:ON
@RouteFilter
public void addResponse(RoutingContext rc) {
rc.response().headers().set( API_VERSION_HEADER, provider.version );
rc.next();
}
@Dependent
public static class ConfigProvider {
//CHECKSTYLE:OFF
@ConfigProperty( name = "application.version" )
String version;
//CHECKSTYLE:ON
}
}
| phillip-kruger/reproducer_corrs | src/main/java/nl/reproducer/vertx/ApiVersionResponseFilter.java | 414 | /*
* Copyright TNO Geologische Dienst Nederland
*
* Alle rechten voorbehouden.
* Niets uit deze software mag worden vermenigvuldigd en/of openbaar gemaakt door middel van druk, fotokopie,
* microfilm of op welke andere wijze dan ook, zonder voorafgaande toestemming van TNO.
*
* Indien deze software in opdracht werd uitgebracht, wordt voor de rechten en verplichtingen van opdrachtgever
* en opdrachtnemer verwezen naar de Algemene Voorwaarden voor opdrachten aan TNO, dan wel de betreffende
* terzake tussen de partijen gesloten overeenkomst.
*/ | block_comment | nl | /*
* Copyright TNO Geologische<SUF>*/
package nl.reproducer.vertx;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import io.quarkus.vertx.web.RouteFilter;
import io.vertx.ext.web.RoutingContext;
import org.eclipse.microprofile.config.inject.ConfigProperty;
public class ApiVersionResponseFilter {
private static final String API_VERSION_HEADER = "API-Version";
//CHECKSTYLE:OFF
@Inject
ConfigProvider provider;
//CHECKSTYLE:ON
@RouteFilter
public void addResponse(RoutingContext rc) {
rc.response().headers().set( API_VERSION_HEADER, provider.version );
rc.next();
}
@Dependent
public static class ConfigProvider {
//CHECKSTYLE:OFF
@ConfigProperty( name = "application.version" )
String version;
//CHECKSTYLE:ON
}
}
| false | 338 | 163 | 393 | 190 | 350 | 132 | 393 | 190 | 430 | 174 | false | true | false | true | false | false |
1,718 | 143042_2 | package dashboard;_x000D_
_x000D_
import java.util.*;_x000D_
_x000D_
import javax.persistence.Id;_x000D_
_x000D_
public class User {_x000D_
_x000D_
public enum Role {_x000D_
TUTOR, STUDENT;_x000D_
}_x000D_
_x000D_
@Id Long id;_x000D_
_x000D_
private String userName;_x000D_
private String password;_x000D_
private String email;_x000D_
private boolean timing;_x000D_
_x000D_
private List<Course> courses;_x000D_
private List<Activity> activities;_x000D_
private List<String> favourites;_x000D_
private List<Milestone> milestones;_x000D_
_x000D_
private Role role = Role.STUDENT;_x000D_
_x000D_
public User(String username, String password, String email, List<Course> courses, String role)_x000D_
{_x000D_
this.userName = username;_x000D_
this.password = password;_x000D_
this.email = email;_x000D_
this.courses = courses;_x000D_
if(role.equals("Tutor"))_x000D_
this.role = Role.TUTOR;_x000D_
_x000D_
this.activities = new ArrayList<Activity>();_x000D_
this.milestones = new ArrayList<Milestone>();_x000D_
this.favourites = new ArrayList<String>();_x000D_
this.timing = false;_x000D_
}_x000D_
_x000D_
// Getters and setters_x000D_
_x000D_
public boolean setPassword(String password)_x000D_
{_x000D_
this.password = password;_x000D_
return true;_x000D_
}_x000D_
_x000D_
public List<String> getFavourites() {_x000D_
return favourites;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
public List<Milestone> getMilestones() {_x000D_
return milestones;_x000D_
}_x000D_
_x000D_
_x000D_
public boolean setEmail(String email)_x000D_
{_x000D_
this.email = email;_x000D_
return true;_x000D_
}_x000D_
_x000D_
public String getUsername()_x000D_
{_x000D_
return userName;_x000D_
}_x000D_
_x000D_
public String getPassword()_x000D_
{_x000D_
return password;_x000D_
}_x000D_
_x000D_
public Role getRole()_x000D_
{_x000D_
return role;_x000D_
}_x000D_
_x000D_
public String getEmail()_x000D_
{_x000D_
return email;_x000D_
}_x000D_
_x000D_
public List<Course> getCourses()_x000D_
{_x000D_
return courses;_x000D_
}_x000D_
_x000D_
public List<Activity> getActivities()_x000D_
{_x000D_
return activities;_x000D_
}_x000D_
_x000D_
public long getId()_x000D_
{_x000D_
return id;_x000D_
}_x000D_
_x000D_
//adders and remover_x000D_
_x000D_
public boolean addCourse(Course course)_x000D_
{_x000D_
courses.add(course);_x000D_
return true;_x000D_
}_x000D_
_x000D_
public boolean removeCourse(String courseName)_x000D_
{_x000D_
if(courses.size() == 0) return false;_x000D_
for(Course course: courses)_x000D_
{_x000D_
if(course.getCoursename().equals(courseName))_x000D_
{_x000D_
courses.remove(course);_x000D_
_x000D_
return true;_x000D_
}_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
_x000D_
public void addActivity(String type, Date start, int courseId)_x000D_
{_x000D_
Activity activity = new Activity(start, courseId, type);_x000D_
activities.add(activity);_x000D_
timing = true;_x000D_
}_x000D_
_x000D_
public void stopTiming(){_x000D_
timing=false;_x000D_
}_x000D_
public boolean isTiming(){_x000D_
return timing;_x000D_
}_x000D_
public void setTiming(boolean timing){_x000D_
this.timing= timing;_x000D_
}_x000D_
public boolean removeActivity(int activityId)_x000D_
{_x000D_
if(activities.size() == 0) return false;_x000D_
for(Activity activity: activities)_x000D_
{_x000D_
if(activity.getId() == activityId)_x000D_
{_x000D_
activities.remove(activity);_x000D_
return true;_x000D_
}_x000D_
_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
public void addFavourite(String userNumber) {_x000D_
favourites.add(userNumber);_x000D_
}_x000D_
_x000D_
/**_x000D_
* Verwijdert bepaalde user uit favorieten_x000D_
* @param user : te verwijderen gebruiker uit favorieten_x000D_
* @return true als gelukt, false als mislukt_x000D_
*/_x000D_
public boolean removeFavourite(int activityId)_x000D_
{_x000D_
if(favourites.size() == 0) return false;_x000D_
for(String userNumber: favourites)_x000D_
{_x000D_
if(favourites.contains(userNumber))_x000D_
{_x000D_
favourites.remove(userNumber);_x000D_
return true;_x000D_
}_x000D_
_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
public void addMilestone(Milestone milestone)_x000D_
{_x000D_
milestones.add(milestone);_x000D_
}_x000D_
_x000D_
public boolean removeMilestone(int milestoneId)_x000D_
{_x000D_
if(milestones.size() == 0) return false;_x000D_
for(Milestone milestone: milestones)_x000D_
{_x000D_
if(milestone.getId() == milestoneId)_x000D_
{_x000D_
milestones.remove(milestone);_x000D_
return true;_x000D_
}_x000D_
_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
public void setUsername(String username) {_x000D_
_x000D_
this.userName = username;_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
| TheSleepyMonkey/Dashboard-cwa3 | DashBoard/src/dashboard/User.java | 1,284 | /**_x000D_
* Verwijdert bepaalde user uit favorieten_x000D_
* @param user : te verwijderen gebruiker uit favorieten_x000D_
* @return true als gelukt, false als mislukt_x000D_
*/ | block_comment | nl | package dashboard;_x000D_
_x000D_
import java.util.*;_x000D_
_x000D_
import javax.persistence.Id;_x000D_
_x000D_
public class User {_x000D_
_x000D_
public enum Role {_x000D_
TUTOR, STUDENT;_x000D_
}_x000D_
_x000D_
@Id Long id;_x000D_
_x000D_
private String userName;_x000D_
private String password;_x000D_
private String email;_x000D_
private boolean timing;_x000D_
_x000D_
private List<Course> courses;_x000D_
private List<Activity> activities;_x000D_
private List<String> favourites;_x000D_
private List<Milestone> milestones;_x000D_
_x000D_
private Role role = Role.STUDENT;_x000D_
_x000D_
public User(String username, String password, String email, List<Course> courses, String role)_x000D_
{_x000D_
this.userName = username;_x000D_
this.password = password;_x000D_
this.email = email;_x000D_
this.courses = courses;_x000D_
if(role.equals("Tutor"))_x000D_
this.role = Role.TUTOR;_x000D_
_x000D_
this.activities = new ArrayList<Activity>();_x000D_
this.milestones = new ArrayList<Milestone>();_x000D_
this.favourites = new ArrayList<String>();_x000D_
this.timing = false;_x000D_
}_x000D_
_x000D_
// Getters and setters_x000D_
_x000D_
public boolean setPassword(String password)_x000D_
{_x000D_
this.password = password;_x000D_
return true;_x000D_
}_x000D_
_x000D_
public List<String> getFavourites() {_x000D_
return favourites;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
public List<Milestone> getMilestones() {_x000D_
return milestones;_x000D_
}_x000D_
_x000D_
_x000D_
public boolean setEmail(String email)_x000D_
{_x000D_
this.email = email;_x000D_
return true;_x000D_
}_x000D_
_x000D_
public String getUsername()_x000D_
{_x000D_
return userName;_x000D_
}_x000D_
_x000D_
public String getPassword()_x000D_
{_x000D_
return password;_x000D_
}_x000D_
_x000D_
public Role getRole()_x000D_
{_x000D_
return role;_x000D_
}_x000D_
_x000D_
public String getEmail()_x000D_
{_x000D_
return email;_x000D_
}_x000D_
_x000D_
public List<Course> getCourses()_x000D_
{_x000D_
return courses;_x000D_
}_x000D_
_x000D_
public List<Activity> getActivities()_x000D_
{_x000D_
return activities;_x000D_
}_x000D_
_x000D_
public long getId()_x000D_
{_x000D_
return id;_x000D_
}_x000D_
_x000D_
//adders and remover_x000D_
_x000D_
public boolean addCourse(Course course)_x000D_
{_x000D_
courses.add(course);_x000D_
return true;_x000D_
}_x000D_
_x000D_
public boolean removeCourse(String courseName)_x000D_
{_x000D_
if(courses.size() == 0) return false;_x000D_
for(Course course: courses)_x000D_
{_x000D_
if(course.getCoursename().equals(courseName))_x000D_
{_x000D_
courses.remove(course);_x000D_
_x000D_
return true;_x000D_
}_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
_x000D_
public void addActivity(String type, Date start, int courseId)_x000D_
{_x000D_
Activity activity = new Activity(start, courseId, type);_x000D_
activities.add(activity);_x000D_
timing = true;_x000D_
}_x000D_
_x000D_
public void stopTiming(){_x000D_
timing=false;_x000D_
}_x000D_
public boolean isTiming(){_x000D_
return timing;_x000D_
}_x000D_
public void setTiming(boolean timing){_x000D_
this.timing= timing;_x000D_
}_x000D_
public boolean removeActivity(int activityId)_x000D_
{_x000D_
if(activities.size() == 0) return false;_x000D_
for(Activity activity: activities)_x000D_
{_x000D_
if(activity.getId() == activityId)_x000D_
{_x000D_
activities.remove(activity);_x000D_
return true;_x000D_
}_x000D_
_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
public void addFavourite(String userNumber) {_x000D_
favourites.add(userNumber);_x000D_
}_x000D_
_x000D_
/**_x000D_
* Verwijdert bepaalde user<SUF>*/_x000D_
public boolean removeFavourite(int activityId)_x000D_
{_x000D_
if(favourites.size() == 0) return false;_x000D_
for(String userNumber: favourites)_x000D_
{_x000D_
if(favourites.contains(userNumber))_x000D_
{_x000D_
favourites.remove(userNumber);_x000D_
return true;_x000D_
}_x000D_
_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
public void addMilestone(Milestone milestone)_x000D_
{_x000D_
milestones.add(milestone);_x000D_
}_x000D_
_x000D_
public boolean removeMilestone(int milestoneId)_x000D_
{_x000D_
if(milestones.size() == 0) return false;_x000D_
for(Milestone milestone: milestones)_x000D_
{_x000D_
if(milestone.getId() == milestoneId)_x000D_
{_x000D_
milestones.remove(milestone);_x000D_
return true;_x000D_
}_x000D_
_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
public void setUsername(String username) {_x000D_
_x000D_
this.userName = username;_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
| false | 2,166 | 72 | 2,506 | 81 | 2,478 | 72 | 2,506 | 81 | 2,729 | 82 | false | false | false | false | false | true |
3,784 | 83514_1 | package be.thomasmore.party.controllers;
import be.thomasmore.party.model.Client;
import be.thomasmore.party.repositories.ClientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.time.LocalDateTime;
import java.util.Optional;
import static java.time.LocalDateTime.now;
@Controller
public class ClientController {
@Autowired
ClientRepository clientRepository;
@GetMapping("/clienthome")
public String home(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
}
return "clienthome";
}
@GetMapping("/clientgreeting")
public String clientGreeting(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
final Client client = clientFromDb.get();
String message = "%s %s%s%s".formatted(
getGreeting(),
getPrefix(client),
client.getName(),
getPostfix(client));
model.addAttribute("message", message);
}
return "clientgreeting";
}
@GetMapping("/clientdetails")
public String clientDetails(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
final Client client = clientFromDb.get();
model.addAttribute("client", client);
model.addAttribute("discount", calculateDiscount(client));
}
return "clientdetails";
}
private String getPrefix(Client client) {
if (client.getNrOfOrders() < 10) return "";
if (client.getNrOfOrders() < 50) return "beste ";
return "allerliefste ";
}
private String getGreeting() {
LocalDateTime now = now();
//LocalDateTime now = LocalDateTime.parse("2023-09-23T17:15"); //for test purposes
//NOTE: dit is de meest naieve manier om iets te testen. Volgend jaar zien we daar meer over.
if (now.getHour() < 6) return "Goedenacht";
if (now.getHour() < 12) return "Goedemorgen";
if (now.getHour() < 17) return "Goedemiddag";
if (now.getHour() < 22) return "Goedenavond";
return "Goedenacht";
}
private String getPostfix(Client client) {
if (client.getNrOfOrders() == 0) return ", en welkom!";
if (client.getNrOfOrders() >= 80) return ", jij bent een topper!";
return "";
}
private double calculateDiscount(Client client) {
if (client.getTotalAmount() < 50) return 0;
return client.getTotalAmount() / 200;
}
} | neeraj543/Toets | src/main/java/be/thomasmore/party/controllers/ClientController.java | 811 | //NOTE: dit is de meest naieve manier om iets te testen. Volgend jaar zien we daar meer over. | line_comment | nl | package be.thomasmore.party.controllers;
import be.thomasmore.party.model.Client;
import be.thomasmore.party.repositories.ClientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.time.LocalDateTime;
import java.util.Optional;
import static java.time.LocalDateTime.now;
@Controller
public class ClientController {
@Autowired
ClientRepository clientRepository;
@GetMapping("/clienthome")
public String home(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
}
return "clienthome";
}
@GetMapping("/clientgreeting")
public String clientGreeting(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
final Client client = clientFromDb.get();
String message = "%s %s%s%s".formatted(
getGreeting(),
getPrefix(client),
client.getName(),
getPostfix(client));
model.addAttribute("message", message);
}
return "clientgreeting";
}
@GetMapping("/clientdetails")
public String clientDetails(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
final Client client = clientFromDb.get();
model.addAttribute("client", client);
model.addAttribute("discount", calculateDiscount(client));
}
return "clientdetails";
}
private String getPrefix(Client client) {
if (client.getNrOfOrders() < 10) return "";
if (client.getNrOfOrders() < 50) return "beste ";
return "allerliefste ";
}
private String getGreeting() {
LocalDateTime now = now();
//LocalDateTime now = LocalDateTime.parse("2023-09-23T17:15"); //for test purposes
//NOTE: dit<SUF>
if (now.getHour() < 6) return "Goedenacht";
if (now.getHour() < 12) return "Goedemorgen";
if (now.getHour() < 17) return "Goedemiddag";
if (now.getHour() < 22) return "Goedenavond";
return "Goedenacht";
}
private String getPostfix(Client client) {
if (client.getNrOfOrders() == 0) return ", en welkom!";
if (client.getNrOfOrders() >= 80) return ", jij bent een topper!";
return "";
}
private double calculateDiscount(Client client) {
if (client.getTotalAmount() < 50) return 0;
return client.getTotalAmount() / 200;
}
} | false | 628 | 27 | 718 | 32 | 750 | 24 | 718 | 32 | 848 | 31 | false | false | false | false | false | true |
4,239 | 107567_1 | package javabd.slides.h12_annotations;
import java.lang.annotation.*;
// @Documented // Deze annotatie moet NIET getoond worden in de javadoc van het element waar hij op staat:
@Retention(RetentionPolicy.RUNTIME) // Tot waar wordt deze annotatie meegenomen? SOURCE: alleen in source, niet in gecompileerde class en ook niet at runtime beschikbaar.
@Target(ElementType.METHOD) // deze annotatie mag op een method
public @interface MyAnnotation2 {
String value() default "Hello2";
}
| sajanssens/bd2023 | blok1/src/main/java/javabd/slides/h12_annotations/MyAnnotation2.java | 142 | // Tot waar wordt deze annotatie meegenomen? SOURCE: alleen in source, niet in gecompileerde class en ook niet at runtime beschikbaar. | line_comment | nl | package javabd.slides.h12_annotations;
import java.lang.annotation.*;
// @Documented // Deze annotatie moet NIET getoond worden in de javadoc van het element waar hij op staat:
@Retention(RetentionPolicy.RUNTIME) // Tot waar<SUF>
@Target(ElementType.METHOD) // deze annotatie mag op een method
public @interface MyAnnotation2 {
String value() default "Hello2";
}
| false | 117 | 33 | 133 | 37 | 121 | 29 | 133 | 37 | 145 | 35 | false | false | false | false | false | true |
3,339 | 162640_2 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package be.kdg.repaircafe.services.exceptions;
/**
* @author deketelw
*/
public class UserServiceException extends RuntimeException
{
// https://programmeren3-repaircafe.rhcloud.com/repair-cafe-applicatie/repair-cafe-frontend/presentation-layer/error-handling/
/**
* Deze exception wordt gesmeten wanneer iets fout gaat met gebruikers
* Bijvoorbeeld: fout password of foute gebruikersnaam
*
* @param message
*/
public UserServiceException(String message)
{
super(message);
}
}
| kdg-ti/repairbooth | src/main/java/be/kdg/repaircafe/services/exceptions/UserServiceException.java | 193 | /**
* Deze exception wordt gesmeten wanneer iets fout gaat met gebruikers
* Bijvoorbeeld: fout password of foute gebruikersnaam
*
* @param message
*/ | block_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package be.kdg.repaircafe.services.exceptions;
/**
* @author deketelw
*/
public class UserServiceException extends RuntimeException
{
// https://programmeren3-repaircafe.rhcloud.com/repair-cafe-applicatie/repair-cafe-frontend/presentation-layer/error-handling/
/**
* Deze exception wordt<SUF>*/
public UserServiceException(String message)
{
super(message);
}
}
| false | 148 | 44 | 171 | 48 | 166 | 41 | 171 | 48 | 195 | 53 | false | false | false | false | false | true |
231 | 167102_0 | package Domein;
import java.util.ArrayList;
import java.util.List;
public class Product {
private int product_nummer;
private String naam;
private String beschrijving;
private int prijs;
// maak dit list integer naar ovchipkaart
private List<Integer> alleOVChipkaarten = new ArrayList<>();
public Product(int product_nummer, String naam, String beschrijving, int prijs) {
this.product_nummer = product_nummer;
this.naam = naam;
this.beschrijving = beschrijving;
this.prijs = prijs;
}
public List<Integer> getAlleOVChipkaarten() {
return alleOVChipkaarten;
}
public void addOVChipkaart(int ovChipkaartNummer) {
alleOVChipkaarten.add(ovChipkaartNummer);
}
public void removeOVChipkaart(int ovChipkaartNummer) {
alleOVChipkaarten.remove(ovChipkaartNummer);
}
public int getProduct_nummer() {
return product_nummer;
}
public String getNaam() {
return naam;
}
public String getBeschrijving() {
return beschrijving;
}
public int getPrijs() {
return prijs;
}
public void setNaam(String naam) {
this.naam = naam;
}
public void setBeschrijving(String beschrijving) {
this.beschrijving = beschrijving;
}
public void setPrijs(int prijs) {
this.prijs = prijs;
}
@Override
public String toString() {
return String.format("%s, %s, %s, %s, %s", this.product_nummer, this.naam, this.beschrijving, this.prijs, this.alleOVChipkaarten);
}
}
| BramdeGooijer/DP_OV-Chipkaart | src/main/java/Domein/Product.java | 511 | // maak dit list integer naar ovchipkaart | line_comment | nl | package Domein;
import java.util.ArrayList;
import java.util.List;
public class Product {
private int product_nummer;
private String naam;
private String beschrijving;
private int prijs;
// maak dit<SUF>
private List<Integer> alleOVChipkaarten = new ArrayList<>();
public Product(int product_nummer, String naam, String beschrijving, int prijs) {
this.product_nummer = product_nummer;
this.naam = naam;
this.beschrijving = beschrijving;
this.prijs = prijs;
}
public List<Integer> getAlleOVChipkaarten() {
return alleOVChipkaarten;
}
public void addOVChipkaart(int ovChipkaartNummer) {
alleOVChipkaarten.add(ovChipkaartNummer);
}
public void removeOVChipkaart(int ovChipkaartNummer) {
alleOVChipkaarten.remove(ovChipkaartNummer);
}
public int getProduct_nummer() {
return product_nummer;
}
public String getNaam() {
return naam;
}
public String getBeschrijving() {
return beschrijving;
}
public int getPrijs() {
return prijs;
}
public void setNaam(String naam) {
this.naam = naam;
}
public void setBeschrijving(String beschrijving) {
this.beschrijving = beschrijving;
}
public void setPrijs(int prijs) {
this.prijs = prijs;
}
@Override
public String toString() {
return String.format("%s, %s, %s, %s, %s", this.product_nummer, this.naam, this.beschrijving, this.prijs, this.alleOVChipkaarten);
}
}
| false | 415 | 12 | 450 | 12 | 438 | 10 | 450 | 12 | 536 | 13 | false | false | false | false | false | true |
1,233 | 55941_2 | package equality;
/** Stelt een algemeen profiel van een persoon voor */
public class Account {
final int nummer;
final String naam;
public Account(int nummer, String naam) {
this.nummer = nummer;
this.naam = naam;
}
/** Test of 2 objecten gelijkwaardig zijn
* @param o Het andere object waarmee we het this object vergelijken
* @return of this en other gelijkwaardig zijn
* */
@Override
public boolean equals(Object o) {
//TODO herschrijf deze methode om de gelijkwaardigheid te testen. Maak eerst een unit test
Account other=(Account)o;
return false;
}
}
| OdiseeSEF2324/Leerstof-klas-7-8 | BasicOOP/src/main/java/equality/Account.java | 186 | //TODO herschrijf deze methode om de gelijkwaardigheid te testen. Maak eerst een unit test | line_comment | nl | package equality;
/** Stelt een algemeen profiel van een persoon voor */
public class Account {
final int nummer;
final String naam;
public Account(int nummer, String naam) {
this.nummer = nummer;
this.naam = naam;
}
/** Test of 2 objecten gelijkwaardig zijn
* @param o Het andere object waarmee we het this object vergelijken
* @return of this en other gelijkwaardig zijn
* */
@Override
public boolean equals(Object o) {
//TODO herschrijf<SUF>
Account other=(Account)o;
return false;
}
}
| false | 170 | 28 | 185 | 32 | 166 | 20 | 185 | 32 | 194 | 29 | false | false | false | false | false | true |
4,388 | 92079_11 | import java.sql.*;
import javax.swing.table.DefaultTableModel;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Danielle
*/
public class spelersOverzicht extends javax.swing.JFrame {
private String kolomdatum = "N";
/**
* Creates new form spelersOverzicht
*/
public spelersOverzicht() {
initComponents();
labelOverzicht.setText(FullHouse.labeltekst);
//vul de tabel met gegevens uit de database
try {
Connection conn = SimpleDataSourceV2.getConnection();
Statement stat = conn.createStatement();
String query = FullHouse.query;
ResultSet result = stat.executeQuery(query);
// vraag aantal kolommen uit metadata tabel
ResultSetMetaData md = result.getMetaData();
int aantalKolommen = md.getColumnCount();
// maak lege Array voor kolomnamen
String [] kolomnamen = new String [aantalKolommen];
// maak een DefaultTableModel met de naam tabelmodel
DefaultTableModel tabelmodel = new DefaultTableModel() {
// maak typen in cel onmogelijk
public boolean isCellEditable(int rowIndex, int mColIndex) {
return false;
}
};
// vul Array kolomnamen
for (int j=0; j< aantalKolommen; j++){
kolomnamen[j] = md.getColumnLabel(j+1);
// check of er een kolom 'datum' is:
String kolom = kolomnamen[j];
if (kolom.equals ("Datum")){
kolomdatum = "J";
}
}
//ken kolomnamen toe aan tabelmodel
tabelmodel.setColumnIdentifiers(kolomnamen);
while (result.next()){
Object [] rijgegevens = new Object [aantalKolommen];
for (int i=0; i< aantalKolommen; i++){
rijgegevens[i]= result.getObject(i+1);
// als er kolom 'datum' is moet de datum worden omgezet naar NL format
if (kolomdatum.equals ("J")) {
//zet datum uit sql om naar weergave normale nl
String datumsql = result.getString("datum");
try {
java.sql.Date sqlDate = FullHouse.dateStringToMySqlDate(datumsql);
String datum = FullHouse.mySqlDateToString(sqlDate);
//zet juiste datum terug in betreffende kolom: 2 bevat datum
rijgegevens[3] = datum;
} catch (Exception e) {
System.out.println(e);
}
}
}
tabelmodel.addRow(rijgegevens);
}
tabelSpelers.setModel(tabelmodel);
} catch (SQLException e) {
System.out.println("SQL fout bij vullen lijst: " + e);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
tabelSpelers = new javax.swing.JTable();
labelOverzicht = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("FULL HOUSE");
setMinimumSize(new java.awt.Dimension(1024, 768));
tabelSpelers.setAutoCreateRowSorter(true);
tabelSpelers.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
tabelSpelers.setFillsViewportHeight(true);
tabelSpelers.setName(""); // NOI18N
jScrollPane1.setViewportView(tabelSpelers);
labelOverzicht.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
labelOverzicht.setText("Spelersoverzicht");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(layout.createSequentialGroup()
.addComponent(labelOverzicht)
.addGap(0, 731, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(labelOverzicht)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 269, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(spelersOverzicht.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(spelersOverzicht.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(spelersOverzicht.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(spelersOverzicht.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new spelersOverzicht().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel labelOverzicht;
private javax.swing.JTable tabelSpelers;
// End of variables declaration//GEN-END:variables
}
// tabelSpelers.setEnabled(false);
// tabelSpelers.setRowSelectionAllowed(true);
// System.out.println(tabelSpelers.getRowSelectionAllowed());
// System.out.println(tabelSpelers.getSelectedRow());
// System.out.println(tabelSpelers.isEnabled()); | stefanvandoodewaard/the-poker-database-challenge | the-poker-database-challenge/src/spelersOverzicht.java | 2,332 | // als er kolom 'datum' is moet de datum worden omgezet naar NL format | line_comment | nl | import java.sql.*;
import javax.swing.table.DefaultTableModel;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Danielle
*/
public class spelersOverzicht extends javax.swing.JFrame {
private String kolomdatum = "N";
/**
* Creates new form spelersOverzicht
*/
public spelersOverzicht() {
initComponents();
labelOverzicht.setText(FullHouse.labeltekst);
//vul de tabel met gegevens uit de database
try {
Connection conn = SimpleDataSourceV2.getConnection();
Statement stat = conn.createStatement();
String query = FullHouse.query;
ResultSet result = stat.executeQuery(query);
// vraag aantal kolommen uit metadata tabel
ResultSetMetaData md = result.getMetaData();
int aantalKolommen = md.getColumnCount();
// maak lege Array voor kolomnamen
String [] kolomnamen = new String [aantalKolommen];
// maak een DefaultTableModel met de naam tabelmodel
DefaultTableModel tabelmodel = new DefaultTableModel() {
// maak typen in cel onmogelijk
public boolean isCellEditable(int rowIndex, int mColIndex) {
return false;
}
};
// vul Array kolomnamen
for (int j=0; j< aantalKolommen; j++){
kolomnamen[j] = md.getColumnLabel(j+1);
// check of er een kolom 'datum' is:
String kolom = kolomnamen[j];
if (kolom.equals ("Datum")){
kolomdatum = "J";
}
}
//ken kolomnamen toe aan tabelmodel
tabelmodel.setColumnIdentifiers(kolomnamen);
while (result.next()){
Object [] rijgegevens = new Object [aantalKolommen];
for (int i=0; i< aantalKolommen; i++){
rijgegevens[i]= result.getObject(i+1);
// als er<SUF>
if (kolomdatum.equals ("J")) {
//zet datum uit sql om naar weergave normale nl
String datumsql = result.getString("datum");
try {
java.sql.Date sqlDate = FullHouse.dateStringToMySqlDate(datumsql);
String datum = FullHouse.mySqlDateToString(sqlDate);
//zet juiste datum terug in betreffende kolom: 2 bevat datum
rijgegevens[3] = datum;
} catch (Exception e) {
System.out.println(e);
}
}
}
tabelmodel.addRow(rijgegevens);
}
tabelSpelers.setModel(tabelmodel);
} catch (SQLException e) {
System.out.println("SQL fout bij vullen lijst: " + e);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
tabelSpelers = new javax.swing.JTable();
labelOverzicht = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("FULL HOUSE");
setMinimumSize(new java.awt.Dimension(1024, 768));
tabelSpelers.setAutoCreateRowSorter(true);
tabelSpelers.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
tabelSpelers.setFillsViewportHeight(true);
tabelSpelers.setName(""); // NOI18N
jScrollPane1.setViewportView(tabelSpelers);
labelOverzicht.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
labelOverzicht.setText("Spelersoverzicht");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(layout.createSequentialGroup()
.addComponent(labelOverzicht)
.addGap(0, 731, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(labelOverzicht)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 269, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(spelersOverzicht.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(spelersOverzicht.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(spelersOverzicht.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(spelersOverzicht.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new spelersOverzicht().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel labelOverzicht;
private javax.swing.JTable tabelSpelers;
// End of variables declaration//GEN-END:variables
}
// tabelSpelers.setEnabled(false);
// tabelSpelers.setRowSelectionAllowed(true);
// System.out.println(tabelSpelers.getRowSelectionAllowed());
// System.out.println(tabelSpelers.getSelectedRow());
// System.out.println(tabelSpelers.isEnabled()); | false | 1,561 | 19 | 1,861 | 19 | 1,854 | 17 | 1,861 | 19 | 2,257 | 23 | false | false | false | false | false | true |
4,175 | 17418_7 | import java.util.Random;
/**
* Created by rickv on 8-9-2016.
*/
public class Opdracht1_2 {
public static void main(String[] args) {
// Het aantal te sorteren getallen
int amount = 800000;
int arr[];
arr = new int[amount];
// Maakt de random getallen aan
for (int i = 0; i < amount; i++) {
Random random = new Random();
int getal = random.nextInt(amount);
arr[i]=getal;
}
int[] part1 = new int[amount/2];
int[] part2 = new int[amount/2];
// Splitst de arrays in twee delen
System.arraycopy(arr, 0, part1, 0, part1.length);
System.arraycopy(arr, part1.length, part2, 0, part2.length);
// Uitvoer ter controle
//System.out.println("Array vóór sortering");
for(int i=0; i < arr.length; i++){
//System.out.print(arr[i] + " ");
}
//System.out.println();
// Plaatst de twee delen van de array in een eigen bubblesort
BubbleSort bubbleSort = new BubbleSort(part1);
BubbleSort bubbleSort2 = new BubbleSort(part2);
// Maakt een thread aan voor beide bubbesort
Thread t1 = new Thread(bubbleSort);
Thread t2 = new Thread(bubbleSort2);
// START TIMER
long startTime = System.currentTimeMillis();
// Voer beide threads uit
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException IE) {}
// Voegt gesorteerde arrays samen tot één gesorteerde array
int[] mergedArray = Merge.Merge(bubbleSort.getArr(), bubbleSort2.getArr());
// EIND TIMER
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println(totalTime + " ms");
// Uitvoer ter controle
//System.out.println("Array na sortering");
for(int i=0; i < arr.length; i++){
//System.out.print(mergedArray[i] + " ");
}
}
}
| rickvanw/Assignment1Concurrency | src/Opdracht1_2.java | 637 | // Plaatst de twee delen van de array in een eigen bubblesort | line_comment | nl | import java.util.Random;
/**
* Created by rickv on 8-9-2016.
*/
public class Opdracht1_2 {
public static void main(String[] args) {
// Het aantal te sorteren getallen
int amount = 800000;
int arr[];
arr = new int[amount];
// Maakt de random getallen aan
for (int i = 0; i < amount; i++) {
Random random = new Random();
int getal = random.nextInt(amount);
arr[i]=getal;
}
int[] part1 = new int[amount/2];
int[] part2 = new int[amount/2];
// Splitst de arrays in twee delen
System.arraycopy(arr, 0, part1, 0, part1.length);
System.arraycopy(arr, part1.length, part2, 0, part2.length);
// Uitvoer ter controle
//System.out.println("Array vóór sortering");
for(int i=0; i < arr.length; i++){
//System.out.print(arr[i] + " ");
}
//System.out.println();
// Plaatst de<SUF>
BubbleSort bubbleSort = new BubbleSort(part1);
BubbleSort bubbleSort2 = new BubbleSort(part2);
// Maakt een thread aan voor beide bubbesort
Thread t1 = new Thread(bubbleSort);
Thread t2 = new Thread(bubbleSort2);
// START TIMER
long startTime = System.currentTimeMillis();
// Voer beide threads uit
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException IE) {}
// Voegt gesorteerde arrays samen tot één gesorteerde array
int[] mergedArray = Merge.Merge(bubbleSort.getArr(), bubbleSort2.getArr());
// EIND TIMER
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println(totalTime + " ms");
// Uitvoer ter controle
//System.out.println("Array na sortering");
for(int i=0; i < arr.length; i++){
//System.out.print(mergedArray[i] + " ");
}
}
}
| false | 511 | 16 | 573 | 19 | 593 | 14 | 573 | 19 | 666 | 17 | false | false | false | false | false | true |
4,127 | 112701_4 | /*
* B3P Commons GIS is a library with commonly used classes for OGC
* reading and writing. Included are wms, wfs, gml, csv and other
* general helper classes and extensions.
*
* Copyright 2005 - 2008 B3Partners BV
*
* This file is part of B3P Commons GIS.
*
* B3P Commons GIS 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.
*
* B3P Commons GIS 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 B3P Commons GIS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.roybraam.vanenapp.service;
import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author Chris
*/
public class Crypter {
private static final Log log = LogFactory.getLog(Crypter.class);
/**
* Key waarmee de url wordt encrypt/decrypt.
*/
protected final static String CHARSET = "US-ASCII";
protected final static String encryptionAlgorithm = "DES";
protected final static String encryptionMode = "ECB";
protected final static String encryptionPadding = "PKCS5Padding";
protected static SecretKey secretKey;
protected static String cipherParameters;
static {
try {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptionAlgorithm);
DESKeySpec desKeySpec = new DESKeySpec("proxy00000070707707".getBytes(CHARSET));
secretKey = keyFactory.generateSecret(desKeySpec);
} catch (Exception e) {
log.error("error: ", e);
}
cipherParameters = encryptionAlgorithm + "/" + encryptionMode + "/" + encryptionPadding;
}
/**
* Encrypt a string.
*
* @param clearText
* @return clearText, encrypted
*/
public static String encryptText(String clearText) throws Exception {
if (clearText == null) {
log.error("text to encrypt may not be null!");
throw new Exception("text to encrypt may not be null!");
}
Base64 encoder = new Base64();
Cipher c1 = Cipher.getInstance(cipherParameters);
c1.init(Cipher.ENCRYPT_MODE, secretKey);
byte clearTextBytes[];
clearTextBytes = clearText.getBytes();
byte encryptedText[] = c1.doFinal(clearTextBytes);
String encryptedEncodedText = new String(encoder.encode(encryptedText), CHARSET);
/* Verwijder eventuele \r\n karakters die door Commons-Codec 1.4
* zijn toegevoegd. Deze zijn niet toegestaan in een cookie.
*/
encryptedEncodedText = encryptedEncodedText.replaceAll("[\r\n]", "");
return URLEncoder.encode(encryptedEncodedText, "utf-8");
}
/**
* Decrypt a string.
*
* @param encryptedText
* @return encryptedText, decrypted
*/
public static String decryptText(String encryptedText) throws Exception {
if (encryptedText == null) {
return null;
}
String et = URLDecoder.decode(encryptedText, "utf-8");
Base64 decoder = new Base64();
byte decodedEncryptedText[] = decoder.decode(et.getBytes(CHARSET));
Cipher c1 = Cipher.getInstance(cipherParameters);
c1.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedText = c1.doFinal(decodedEncryptedText);
String decryptedTextString = new String(decryptedText);
return decryptedTextString;
}
}
| rbraam/vanenapp | vanenapp/src/main/java/com/roybraam/vanenapp/service/Crypter.java | 1,170 | /* Verwijder eventuele \r\n karakters die door Commons-Codec 1.4
* zijn toegevoegd. Deze zijn niet toegestaan in een cookie.
*/ | block_comment | nl | /*
* B3P Commons GIS is a library with commonly used classes for OGC
* reading and writing. Included are wms, wfs, gml, csv and other
* general helper classes and extensions.
*
* Copyright 2005 - 2008 B3Partners BV
*
* This file is part of B3P Commons GIS.
*
* B3P Commons GIS 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.
*
* B3P Commons GIS 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 B3P Commons GIS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.roybraam.vanenapp.service;
import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author Chris
*/
public class Crypter {
private static final Log log = LogFactory.getLog(Crypter.class);
/**
* Key waarmee de url wordt encrypt/decrypt.
*/
protected final static String CHARSET = "US-ASCII";
protected final static String encryptionAlgorithm = "DES";
protected final static String encryptionMode = "ECB";
protected final static String encryptionPadding = "PKCS5Padding";
protected static SecretKey secretKey;
protected static String cipherParameters;
static {
try {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptionAlgorithm);
DESKeySpec desKeySpec = new DESKeySpec("proxy00000070707707".getBytes(CHARSET));
secretKey = keyFactory.generateSecret(desKeySpec);
} catch (Exception e) {
log.error("error: ", e);
}
cipherParameters = encryptionAlgorithm + "/" + encryptionMode + "/" + encryptionPadding;
}
/**
* Encrypt a string.
*
* @param clearText
* @return clearText, encrypted
*/
public static String encryptText(String clearText) throws Exception {
if (clearText == null) {
log.error("text to encrypt may not be null!");
throw new Exception("text to encrypt may not be null!");
}
Base64 encoder = new Base64();
Cipher c1 = Cipher.getInstance(cipherParameters);
c1.init(Cipher.ENCRYPT_MODE, secretKey);
byte clearTextBytes[];
clearTextBytes = clearText.getBytes();
byte encryptedText[] = c1.doFinal(clearTextBytes);
String encryptedEncodedText = new String(encoder.encode(encryptedText), CHARSET);
/* Verwijder eventuele \r\n<SUF>*/
encryptedEncodedText = encryptedEncodedText.replaceAll("[\r\n]", "");
return URLEncoder.encode(encryptedEncodedText, "utf-8");
}
/**
* Decrypt a string.
*
* @param encryptedText
* @return encryptedText, decrypted
*/
public static String decryptText(String encryptedText) throws Exception {
if (encryptedText == null) {
return null;
}
String et = URLDecoder.decode(encryptedText, "utf-8");
Base64 decoder = new Base64();
byte decodedEncryptedText[] = decoder.decode(et.getBytes(CHARSET));
Cipher c1 = Cipher.getInstance(cipherParameters);
c1.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedText = c1.doFinal(decodedEncryptedText);
String decryptedTextString = new String(decryptedText);
return decryptedTextString;
}
}
| false | 914 | 44 | 994 | 46 | 1,048 | 42 | 994 | 46 | 1,189 | 48 | false | false | false | false | false | true |
201 | 115360_8 | package android.translateapp;
import android.app.NotificationManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import ben.translateapp.R;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class AddwordActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addword);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle("Add word");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == android.R.id.home) {
//Als de 'back' item is geklikt dan wordt deze intent gesloten
this.finish();
}
return super.onOptionsItemSelected(menuItem);
}
public static boolean empty( final String s ) {
// Null-safe, short-circuit evaluation.
return s == null || s.trim().isEmpty();
}
public void addWord() {
SharedPreferences userSettings = getSharedPreferences("UserPreferences", MODE_PRIVATE);
TextView mNederlands;
TextView mFrans;
String sNederlands;
String sFrans;
String userID;
//Variabelen ophalen van de textviews
mNederlands = (TextView)findViewById(R.id.dutchWord);
mFrans = (TextView)findViewById(R.id.frenchWord);
sNederlands = mNederlands.getText().toString();
sFrans = mFrans.getText().toString();
//Geklikt op add Word button
if(!empty(sNederlands) && !empty(sFrans)){
//Connectie maken met de FirebaseDatabase
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference();
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
userID = userSettings.getString("UserName", "");
Integer countWords = 0;
//Klasse woord aanmaken
Words oneWord = new Words(sNederlands, sFrans, userID, countWords);
//Woord toevoegen aan de database
ref.child("words").push().setValue(oneWord);
Toast.makeText(this, "Woord opgeslagen!", Toast.LENGTH_SHORT).show();
//Leegmaken van de velden
mNederlands.setText("");
mFrans.setText("");
} else {
Toast.makeText(this, "Gelieve beide velden in te vullen!", Toast.LENGTH_LONG).show();
}
this.finish();
}
public void onClick(View v) {
addWord();
}
}
| BenWitters/TranslateApp | app/src/main/java/android/translateapp/AddwordActivity.java | 888 | //Leegmaken van de velden | line_comment | nl | package android.translateapp;
import android.app.NotificationManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import ben.translateapp.R;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class AddwordActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addword);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle("Add word");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == android.R.id.home) {
//Als de 'back' item is geklikt dan wordt deze intent gesloten
this.finish();
}
return super.onOptionsItemSelected(menuItem);
}
public static boolean empty( final String s ) {
// Null-safe, short-circuit evaluation.
return s == null || s.trim().isEmpty();
}
public void addWord() {
SharedPreferences userSettings = getSharedPreferences("UserPreferences", MODE_PRIVATE);
TextView mNederlands;
TextView mFrans;
String sNederlands;
String sFrans;
String userID;
//Variabelen ophalen van de textviews
mNederlands = (TextView)findViewById(R.id.dutchWord);
mFrans = (TextView)findViewById(R.id.frenchWord);
sNederlands = mNederlands.getText().toString();
sFrans = mFrans.getText().toString();
//Geklikt op add Word button
if(!empty(sNederlands) && !empty(sFrans)){
//Connectie maken met de FirebaseDatabase
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference();
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
userID = userSettings.getString("UserName", "");
Integer countWords = 0;
//Klasse woord aanmaken
Words oneWord = new Words(sNederlands, sFrans, userID, countWords);
//Woord toevoegen aan de database
ref.child("words").push().setValue(oneWord);
Toast.makeText(this, "Woord opgeslagen!", Toast.LENGTH_SHORT).show();
//Leegmaken van<SUF>
mNederlands.setText("");
mFrans.setText("");
} else {
Toast.makeText(this, "Gelieve beide velden in te vullen!", Toast.LENGTH_LONG).show();
}
this.finish();
}
public void onClick(View v) {
addWord();
}
}
| false | 611 | 9 | 739 | 9 | 743 | 8 | 739 | 9 | 867 | 9 | false | false | false | false | false | true |
3,529 | 203681_4 | package sr.unasat.hello.world.app;
public class Application {
public static void main(String[] args) {
System.out.println("Hello World!");
//declaring a variable of aanmaken/definieren van een variable
boolean isValidAnswer;
System.out.println("is 10 + 0 = 11?");
//initaliseren van een variable is de eerste keer dat we een waarde toekennen aan een variable
isValidAnswer = false; //initializing a variable of initialiseren van een variable
System.out.println("Het antwoord is niet valide. de variable isValidAnswer is: " + isValidAnswer);
System.out.println("is 10 + 0 = 10?");
isValidAnswer = true; //assigning a value to a variable of toekennen van een waarde aan een variable
System.out.println("Het antwoord is valide. de variable isValidAnswer is: " + isValidAnswer);
//Zelfde vraagstuk maar dan met variabelen
int nummer1 = 10;
int nummer2 = 0;
System.out.println();
System.out.println("zelfde vraagstuk maar dan met variabelen");
System.out.println("is 10 + 0 = 11?");
isValidAnswer = ((nummer1 + nummer2) == 11);
System.out.println("het antwoord is " + isValidAnswer);
nummer1 = 10;
nummer2 = 0;
System.out.println();
System.out.println("zelfde vraagstuk maar dan met variabelen");
System.out.println("is 10 + 0 = 10?");
isValidAnswer = ((nummer1 + nummer2) == 10);
System.out.println("het antwoord is " + isValidAnswer);
}
}
| maartennarain/HelloWorld | src/sr/unasat/hello/world/app/Application.java | 476 | //Zelfde vraagstuk maar dan met variabelen | line_comment | nl | package sr.unasat.hello.world.app;
public class Application {
public static void main(String[] args) {
System.out.println("Hello World!");
//declaring a variable of aanmaken/definieren van een variable
boolean isValidAnswer;
System.out.println("is 10 + 0 = 11?");
//initaliseren van een variable is de eerste keer dat we een waarde toekennen aan een variable
isValidAnswer = false; //initializing a variable of initialiseren van een variable
System.out.println("Het antwoord is niet valide. de variable isValidAnswer is: " + isValidAnswer);
System.out.println("is 10 + 0 = 10?");
isValidAnswer = true; //assigning a value to a variable of toekennen van een waarde aan een variable
System.out.println("Het antwoord is valide. de variable isValidAnswer is: " + isValidAnswer);
//Zelfde vraagstuk<SUF>
int nummer1 = 10;
int nummer2 = 0;
System.out.println();
System.out.println("zelfde vraagstuk maar dan met variabelen");
System.out.println("is 10 + 0 = 11?");
isValidAnswer = ((nummer1 + nummer2) == 11);
System.out.println("het antwoord is " + isValidAnswer);
nummer1 = 10;
nummer2 = 0;
System.out.println();
System.out.println("zelfde vraagstuk maar dan met variabelen");
System.out.println("is 10 + 0 = 10?");
isValidAnswer = ((nummer1 + nummer2) == 10);
System.out.println("het antwoord is " + isValidAnswer);
}
}
| false | 400 | 14 | 450 | 16 | 426 | 10 | 450 | 16 | 489 | 15 | false | false | false | false | false | true |
416 | 51686_4 | /*
This file is part of the Navajo Project.
It is subject to the license terms in the COPYING file found in the top-level directory of this distribution and at https://www.gnu.org/licenses/agpl-3.0.txt.
No part of the Navajo Project, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYING file.
*/
package com.dexels.navajo.geo.utils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bbn.openmap.dataAccess.shape.DbfFile;
import com.bbn.openmap.io.BinaryFile;
import com.bbn.openmap.layer.shape.ESRIBoundingBox;
import com.bbn.openmap.layer.shape.ESRIPoint;
import com.bbn.openmap.layer.shape.ESRIPoly;
import com.bbn.openmap.layer.shape.ESRIPoly.ESRIFloatPoly;
import com.bbn.openmap.layer.shape.ESRIPolygonRecord;
import com.bbn.openmap.layer.shape.ESRIRecord;
import com.bbn.openmap.layer.shape.ShapeFile;
import com.dexels.navajo.client.NavajoClientFactory;
import com.dexels.navajo.document.Message;
import com.dexels.navajo.document.Navajo;
import com.dexels.navajo.document.types.Binary;
import com.dexels.navajo.runtime.config.TestConfig;
public class RDShapeImport {
private ShapeFile sf;
private DbfFile db;
private final static Logger logger = LoggerFactory
.getLogger(RDShapeImport.class);
public RDShapeImport(String prefix) {
try {
NavajoClientFactory.resetClient();
NavajoClientFactory.createClient();
NavajoClientFactory.getClient().setServerUrls(new String[] {TestConfig.NAVAJO_TEST_SERVER.getValue()});
NavajoClientFactory.getClient().setUsername(TestConfig.NAVAJO_TEST_USER.getValue());
NavajoClientFactory.getClient().setPassword(TestConfig.NAVAJO_TEST_PASS.getValue());
File shapeFile = new File(prefix + ".shp");
db = new DbfFile(new BinaryFile(new File(prefix + ".dbf")));
db.readData();
sf = new ShapeFile(shapeFile);
} catch (Exception e) {
logger.error("Error: ", e);
}
}
@SuppressWarnings("rawtypes")
public void parseData(boolean storeBoundingBox) {
try {
ESRIRecord record = null;
int count = 0;
// File csv = new File("c:/gemeente.csv");
// BufferedWriter fw = new BufferedWriter(new FileWriter(csv));
while ((record = sf.getNextRecord()) != null) {
// Record numbers??
ArrayList data = (ArrayList) db.getRecord(record.getRecordNumber()-1);
db.getValueAt(count, 0);
count++;
String id = (String)data.get(0);
File recordFile = File.createTempFile("shape", "dat");
BufferedWriter fw = new BufferedWriter(new FileWriter(recordFile));
fw.write("SHAPE: " + id + "\n");
if (record instanceof ESRIPolygonRecord) {
ESRIPolygonRecord polygon = (ESRIPolygonRecord) record;
ESRIPoly[] pols = polygon.polygons;
ESRIBoundingBox bbox = polygon.getBoundingBox();
ESRIPoint min = bbox.min;
ESRIPoint max = bbox.max;
double[] min_latlon = getLatLonForRD(min.x, min.y);
double[] max_latlon = getLatLonForRD(max.x, max.y);
if(storeBoundingBox){
storeBoundingBox(id, min_latlon[0], min_latlon[1], max_latlon[0], max_latlon[1]);
}
for (int i = 0; i < pols.length; i++) {
fw.write("POLYGON: " + (i+1) + "\n");
ESRIPoly poly = pols[i];
ESRIFloatPoly fp = (ESRIFloatPoly) poly;
for (int j = 0; j < fp.nPoints; j++) {
double xd = fp.getX(j);
double yd = fp.getY(j);
double[] latlon = getLatLonForRD(xd, yd);
//storePolygonPoints(id, i + 1, latlon[0], latlon[1]);
fw.write(latlon[1] + "," + latlon[0] + ",0\n");
}
}
}
fw.flush();
fw.close();
storeBinaryShapeRecord(id, recordFile);
}
} catch (Exception e) {
logger.error("Error: ", e);
}
}
private void storeBinaryShapeRecord(String shapeId, File recordFile){
try{
Binary data = new Binary(recordFile);
Navajo pms = NavajoClientFactory.getClient().doSimpleSend(null, "geospatial/InitInsertCBSPolyPoint");
Message params =pms.getMessage("Parameters");
if(params != null){
params.getProperty("ShapeId").setValue(shapeId);
params.getProperty("ShapeData").setValue(data);
NavajoClientFactory.getClient().doSimpleSend(params.getRootDoc(), "geospatial/ProcessInsertCBSPolyPoint");
}
}catch(Exception e){
logger.error("Error: ", e);
}
}
private double[] getLatLonForRD(double x, double y) {
double dX = (x - 155000) / 100000.0;
double dY = (y - 463000) / 100000.0;
double SomN = (3235.65389 * dY) + (-32.58297 * Math.pow(dX, 2.0)) + (-0.2475 * Math.pow(dY, 2.0)) + (-0.84978 * Math.pow(dX, 2.0) * dY) + (-0.0655 * Math.pow(dY, 3.0)) + (-0.01709 * Math.pow(dX, 2.0) * Math.pow(dY, 2.0)) + (-0.00738 * dX) + (0.0053 * Math.pow(dX, 4.0)) + (-0.00039 * Math.pow(dX, 2.0) * Math.pow(dY, 3.0)) + (0.00033 * Math.pow(dX, 4.0) * dY) + (-0.00012 * dX * dY);
double SomE = (5260.52916 * dX) + (105.94684 * dX * dY) + (2.45656 * dX * Math.pow(dY, 2.0)) + (-0.81885 * Math.pow(dX, 3.0)) + (0.05594 * dX * Math.pow(dY, 3.0)) + (-0.05607 * Math.pow(dX, 3.0) * dY) + (0.01199 * dY) + (-0.00256 * Math.pow(dX, 3.0) * Math.pow(dY, 2.0)) + (0.00128 * dX * Math.pow(dY, 4.0)) + (0.00022 * Math.pow(dY, 2.0)) + (-0.00022 * Math.pow(dX, 2.0)) + (0.00026 * Math.pow(dX, 5.0));
double lat = 52.15517440 + (SomN / 3600.0);
double lon = 5.38720621 + (SomE / 3600.0);
return new double[] { lat, lon };
}
private void storeBoundingBox(String shapeId, double min_lat, double min_lon, double max_lat, double max_lon) {
try {
System.err.println(shapeId + ", BBOX: " + min_lat + ", " + min_lon + " - " + max_lat + ", " + max_lon);
Navajo pms = NavajoClientFactory.getClient().doSimpleSend(null, "geospatial/InitUpdateCBSBoundingBox");
Message params = pms.getMessage( "Parameters");
if(params != null){
params.getProperty("ShapeId").setValue(shapeId);
params.getProperty("MinLat").setValue(min_lat);
params.getProperty("MinLon").setValue(min_lon);
params.getProperty("MaxLat").setValue(max_lat);
params.getProperty("MaxLon").setValue(max_lon);
} else {
System.err.println("No connection");
return;
}
if (shapeId.startsWith("GM")) {
// Gemeente bounding box
params.getProperty("Table").setValue("cbs_gemeente");
params.getProperty("ShapeIdKey").setValue("gm_code");
}
if (shapeId.startsWith("WK")) {
// Wijk bounding box
params.getProperty("Table").setValue("cbs_wijk");
params.getProperty("ShapeIdKey").setValue("wk_code");
}
if (shapeId.startsWith("BU")) {
// Buurt bounding box
params.getProperty("Table").setValue("cbs_buurt");
params.getProperty("ShapeIdKey").setValue("bu_code");
}
NavajoClientFactory.getClient().doSimpleSend(params.getRootDoc(), "geospatial/ProcessUpdateCBSBoundingBox");
} catch (Exception e) {
logger.error("Error: ", e);
}
}
public static void main(String[] args) {
RDShapeImport rdsi = new RDShapeImport("c:/cbs/brt_2010_gn1");
rdsi.parseData(true);
}
}
| Dexels/navajo | optional/com.dexels.navajo.kml/src/com/dexels/navajo/geo/utils/RDShapeImport.java | 2,809 | // Gemeente bounding box | line_comment | nl | /*
This file is part of the Navajo Project.
It is subject to the license terms in the COPYING file found in the top-level directory of this distribution and at https://www.gnu.org/licenses/agpl-3.0.txt.
No part of the Navajo Project, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYING file.
*/
package com.dexels.navajo.geo.utils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bbn.openmap.dataAccess.shape.DbfFile;
import com.bbn.openmap.io.BinaryFile;
import com.bbn.openmap.layer.shape.ESRIBoundingBox;
import com.bbn.openmap.layer.shape.ESRIPoint;
import com.bbn.openmap.layer.shape.ESRIPoly;
import com.bbn.openmap.layer.shape.ESRIPoly.ESRIFloatPoly;
import com.bbn.openmap.layer.shape.ESRIPolygonRecord;
import com.bbn.openmap.layer.shape.ESRIRecord;
import com.bbn.openmap.layer.shape.ShapeFile;
import com.dexels.navajo.client.NavajoClientFactory;
import com.dexels.navajo.document.Message;
import com.dexels.navajo.document.Navajo;
import com.dexels.navajo.document.types.Binary;
import com.dexels.navajo.runtime.config.TestConfig;
public class RDShapeImport {
private ShapeFile sf;
private DbfFile db;
private final static Logger logger = LoggerFactory
.getLogger(RDShapeImport.class);
public RDShapeImport(String prefix) {
try {
NavajoClientFactory.resetClient();
NavajoClientFactory.createClient();
NavajoClientFactory.getClient().setServerUrls(new String[] {TestConfig.NAVAJO_TEST_SERVER.getValue()});
NavajoClientFactory.getClient().setUsername(TestConfig.NAVAJO_TEST_USER.getValue());
NavajoClientFactory.getClient().setPassword(TestConfig.NAVAJO_TEST_PASS.getValue());
File shapeFile = new File(prefix + ".shp");
db = new DbfFile(new BinaryFile(new File(prefix + ".dbf")));
db.readData();
sf = new ShapeFile(shapeFile);
} catch (Exception e) {
logger.error("Error: ", e);
}
}
@SuppressWarnings("rawtypes")
public void parseData(boolean storeBoundingBox) {
try {
ESRIRecord record = null;
int count = 0;
// File csv = new File("c:/gemeente.csv");
// BufferedWriter fw = new BufferedWriter(new FileWriter(csv));
while ((record = sf.getNextRecord()) != null) {
// Record numbers??
ArrayList data = (ArrayList) db.getRecord(record.getRecordNumber()-1);
db.getValueAt(count, 0);
count++;
String id = (String)data.get(0);
File recordFile = File.createTempFile("shape", "dat");
BufferedWriter fw = new BufferedWriter(new FileWriter(recordFile));
fw.write("SHAPE: " + id + "\n");
if (record instanceof ESRIPolygonRecord) {
ESRIPolygonRecord polygon = (ESRIPolygonRecord) record;
ESRIPoly[] pols = polygon.polygons;
ESRIBoundingBox bbox = polygon.getBoundingBox();
ESRIPoint min = bbox.min;
ESRIPoint max = bbox.max;
double[] min_latlon = getLatLonForRD(min.x, min.y);
double[] max_latlon = getLatLonForRD(max.x, max.y);
if(storeBoundingBox){
storeBoundingBox(id, min_latlon[0], min_latlon[1], max_latlon[0], max_latlon[1]);
}
for (int i = 0; i < pols.length; i++) {
fw.write("POLYGON: " + (i+1) + "\n");
ESRIPoly poly = pols[i];
ESRIFloatPoly fp = (ESRIFloatPoly) poly;
for (int j = 0; j < fp.nPoints; j++) {
double xd = fp.getX(j);
double yd = fp.getY(j);
double[] latlon = getLatLonForRD(xd, yd);
//storePolygonPoints(id, i + 1, latlon[0], latlon[1]);
fw.write(latlon[1] + "," + latlon[0] + ",0\n");
}
}
}
fw.flush();
fw.close();
storeBinaryShapeRecord(id, recordFile);
}
} catch (Exception e) {
logger.error("Error: ", e);
}
}
private void storeBinaryShapeRecord(String shapeId, File recordFile){
try{
Binary data = new Binary(recordFile);
Navajo pms = NavajoClientFactory.getClient().doSimpleSend(null, "geospatial/InitInsertCBSPolyPoint");
Message params =pms.getMessage("Parameters");
if(params != null){
params.getProperty("ShapeId").setValue(shapeId);
params.getProperty("ShapeData").setValue(data);
NavajoClientFactory.getClient().doSimpleSend(params.getRootDoc(), "geospatial/ProcessInsertCBSPolyPoint");
}
}catch(Exception e){
logger.error("Error: ", e);
}
}
private double[] getLatLonForRD(double x, double y) {
double dX = (x - 155000) / 100000.0;
double dY = (y - 463000) / 100000.0;
double SomN = (3235.65389 * dY) + (-32.58297 * Math.pow(dX, 2.0)) + (-0.2475 * Math.pow(dY, 2.0)) + (-0.84978 * Math.pow(dX, 2.0) * dY) + (-0.0655 * Math.pow(dY, 3.0)) + (-0.01709 * Math.pow(dX, 2.0) * Math.pow(dY, 2.0)) + (-0.00738 * dX) + (0.0053 * Math.pow(dX, 4.0)) + (-0.00039 * Math.pow(dX, 2.0) * Math.pow(dY, 3.0)) + (0.00033 * Math.pow(dX, 4.0) * dY) + (-0.00012 * dX * dY);
double SomE = (5260.52916 * dX) + (105.94684 * dX * dY) + (2.45656 * dX * Math.pow(dY, 2.0)) + (-0.81885 * Math.pow(dX, 3.0)) + (0.05594 * dX * Math.pow(dY, 3.0)) + (-0.05607 * Math.pow(dX, 3.0) * dY) + (0.01199 * dY) + (-0.00256 * Math.pow(dX, 3.0) * Math.pow(dY, 2.0)) + (0.00128 * dX * Math.pow(dY, 4.0)) + (0.00022 * Math.pow(dY, 2.0)) + (-0.00022 * Math.pow(dX, 2.0)) + (0.00026 * Math.pow(dX, 5.0));
double lat = 52.15517440 + (SomN / 3600.0);
double lon = 5.38720621 + (SomE / 3600.0);
return new double[] { lat, lon };
}
private void storeBoundingBox(String shapeId, double min_lat, double min_lon, double max_lat, double max_lon) {
try {
System.err.println(shapeId + ", BBOX: " + min_lat + ", " + min_lon + " - " + max_lat + ", " + max_lon);
Navajo pms = NavajoClientFactory.getClient().doSimpleSend(null, "geospatial/InitUpdateCBSBoundingBox");
Message params = pms.getMessage( "Parameters");
if(params != null){
params.getProperty("ShapeId").setValue(shapeId);
params.getProperty("MinLat").setValue(min_lat);
params.getProperty("MinLon").setValue(min_lon);
params.getProperty("MaxLat").setValue(max_lat);
params.getProperty("MaxLon").setValue(max_lon);
} else {
System.err.println("No connection");
return;
}
if (shapeId.startsWith("GM")) {
// Gemeente bounding<SUF>
params.getProperty("Table").setValue("cbs_gemeente");
params.getProperty("ShapeIdKey").setValue("gm_code");
}
if (shapeId.startsWith("WK")) {
// Wijk bounding box
params.getProperty("Table").setValue("cbs_wijk");
params.getProperty("ShapeIdKey").setValue("wk_code");
}
if (shapeId.startsWith("BU")) {
// Buurt bounding box
params.getProperty("Table").setValue("cbs_buurt");
params.getProperty("ShapeIdKey").setValue("bu_code");
}
NavajoClientFactory.getClient().doSimpleSend(params.getRootDoc(), "geospatial/ProcessUpdateCBSBoundingBox");
} catch (Exception e) {
logger.error("Error: ", e);
}
}
public static void main(String[] args) {
RDShapeImport rdsi = new RDShapeImport("c:/cbs/brt_2010_gn1");
rdsi.parseData(true);
}
}
| false | 2,244 | 5 | 2,639 | 6 | 2,599 | 5 | 2,639 | 6 | 3,183 | 6 | false | false | false | false | false | true |
1,614 | 50544_1 | package be.uantwerpen.sc.models;
import be.uantwerpen.sc.models.MyAbstractPersistable;
import javax.persistence.*;
import java.util.List;
import static javax.persistence.GenerationType.IDENTITY;
/**
* NV 2018
*/
@Entity
public class Job extends MyAbstractPersistable<Long> {
private long idStart;
private long idEnd;
/**
* Start en einde zijn steeds in dezelfde map
*/
private int idMap;
private JobState status;
public Job() {
}
public Job(Long idStart, Long idEnd, int idMap) {
this.idStart = idStart;
this.idEnd = idEnd;
this.idMap = idMap;
this.status = JobState.TODO;
}
public String toString(){
return "[ start: "+idStart+" - end:"+idEnd+" ] map:" + idMap + ", state: "+status;
}
public long getIdStart() {
return idStart;
}
public void setIdStart(long idStart) {
this.idStart = idStart;
}
public long getIdEnd() {
return idEnd;
}
public void setIdEnd(long idEnd) {
this.idEnd = idEnd;
}
public int getIdMap() {
return idMap;
}
public void setIdMap(int idMap) {
this.idMap = idMap;
}
public JobState getStatus() {
return status;
}
public void setStatus(JobState status) {
this.status = status;
}
} | SmartCity-UAntwerpen/SmartCityCommon | src/main/java/be/uantwerpen/sc/models/Job.java | 425 | /**
* Start en einde zijn steeds in dezelfde map
*/ | block_comment | nl | package be.uantwerpen.sc.models;
import be.uantwerpen.sc.models.MyAbstractPersistable;
import javax.persistence.*;
import java.util.List;
import static javax.persistence.GenerationType.IDENTITY;
/**
* NV 2018
*/
@Entity
public class Job extends MyAbstractPersistable<Long> {
private long idStart;
private long idEnd;
/**
* Start en einde<SUF>*/
private int idMap;
private JobState status;
public Job() {
}
public Job(Long idStart, Long idEnd, int idMap) {
this.idStart = idStart;
this.idEnd = idEnd;
this.idMap = idMap;
this.status = JobState.TODO;
}
public String toString(){
return "[ start: "+idStart+" - end:"+idEnd+" ] map:" + idMap + ", state: "+status;
}
public long getIdStart() {
return idStart;
}
public void setIdStart(long idStart) {
this.idStart = idStart;
}
public long getIdEnd() {
return idEnd;
}
public void setIdEnd(long idEnd) {
this.idEnd = idEnd;
}
public int getIdMap() {
return idMap;
}
public void setIdMap(int idMap) {
this.idMap = idMap;
}
public JobState getStatus() {
return status;
}
public void setStatus(JobState status) {
this.status = status;
}
} | false | 330 | 18 | 375 | 19 | 402 | 15 | 375 | 19 | 445 | 19 | false | false | false | false | false | true |
260 | 115378_0 | package bep.chatapp.server;
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
private final static int PORT = 8080;
public static void main(String[] args) throws IOException {
List<PrintWriter> allClients = new ArrayList<PrintWriter>();
try (ServerSocket ss = new ServerSocket(PORT)) {
System.out.printf("Server started on port %d!\n", PORT);
while (true) {
try {
Socket s = ss.accept();
// voor elke nieuwe client een aparte thread om binnenkomende chatberichten te verwerken
new Thread() {
public void run() {
PrintWriter pw = null;
// try-with-resource (scanner wordt na afloop automatisch gesloten):
try (Scanner scanner = new Scanner(s.getInputStream())) {
allClients.add(pw = new PrintWriter(s.getOutputStream()));
while (scanner.hasNextLine()) {
String message = scanner.nextLine();
System.out.println("Incoming and distributing: " + message);
// schrijf het binnenkomende bericht naar alle clients!
for (PrintWriter printer : allClients) {
printer.println(message);
printer.flush();
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
System.out.println("Client-verbinding verbroken!");
allClients.remove(pw);
}
}
}.start();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
}
| BvEijkelenburg/ChatApp | src/bep/chatapp/server/ChatServer.java | 479 | // voor elke nieuwe client een aparte thread om binnenkomende chatberichten te verwerken | line_comment | nl | package bep.chatapp.server;
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
private final static int PORT = 8080;
public static void main(String[] args) throws IOException {
List<PrintWriter> allClients = new ArrayList<PrintWriter>();
try (ServerSocket ss = new ServerSocket(PORT)) {
System.out.printf("Server started on port %d!\n", PORT);
while (true) {
try {
Socket s = ss.accept();
// voor elke<SUF>
new Thread() {
public void run() {
PrintWriter pw = null;
// try-with-resource (scanner wordt na afloop automatisch gesloten):
try (Scanner scanner = new Scanner(s.getInputStream())) {
allClients.add(pw = new PrintWriter(s.getOutputStream()));
while (scanner.hasNextLine()) {
String message = scanner.nextLine();
System.out.println("Incoming and distributing: " + message);
// schrijf het binnenkomende bericht naar alle clients!
for (PrintWriter printer : allClients) {
printer.println(message);
printer.flush();
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
System.out.println("Client-verbinding verbroken!");
allClients.remove(pw);
}
}
}.start();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
}
| false | 325 | 21 | 367 | 26 | 388 | 18 | 367 | 26 | 472 | 23 | false | false | false | false | false | true |
568 | 31684_4 | package be.intecbrussel;
public class GithubArrayOef {
public static void main(String[] args) {
System.out.println("Github");
System.out.println("---- Oefening - 1 ----");
// Creëer op 2 manieren een array.
int[] myArr = new int[10];
myArr[5] = 10;
System.out.println("Eerste manier -> " + myArr[5]);
String[] strArr = {"Jos", "Bob", "Mark", "Jules"};
System.out.println("Tweede manier -> " + strArr[0]);
// Met datatype van double en char.
double[] doubleArr = {15.5, 20.5, 35.5};
char[] charArr = {'a', 'b', 'c', 'd'};
// Druk 1 element van beide array's af in de command lijn.
System.out.println("data type double -> " + doubleArr[1] + "\n" + "data type char -> " + charArr[3]);
System.out.println("---- Oefening - 2 ----");
// 1. Creëer een String array met 5 elementen.
String[] strArray = {"ferrari", "lambhorgni", "bugatti", "mercerdes", "audi"};
// 2. Druk 1 element af in de commando lijn.
System.out.println("One element of the array -> " + strArray[2]);
// 3. Druk de lengte van je array af.
System.out.println("Array lenght -> " + strArray.length);
System.out.println("---- Oefening - 3 ----");
// 1. Schrijf een programma om de even en oneven nummer te vinden in een int array.
int[] numArray = {1,2,3,4,5,6,7,8,9,10,11};
int evenCounter = 0;
int oddCounter = 0;
for (int evenOrOdd : numArray) {
if (evenOrOdd % 2 == 0) {
evenCounter++;
} else {
oddCounter++;
}
}
System.out.println("Number of even numbers -> " + evenCounter + "\n" + "number of odd numbers -> " + oddCounter);
}
}
| Gabe-Alvess/LesArrays | src/be/intecbrussel/GithubArrayOef.java | 595 | // 2. Druk 1 element af in de commando lijn. | line_comment | nl | package be.intecbrussel;
public class GithubArrayOef {
public static void main(String[] args) {
System.out.println("Github");
System.out.println("---- Oefening - 1 ----");
// Creëer op 2 manieren een array.
int[] myArr = new int[10];
myArr[5] = 10;
System.out.println("Eerste manier -> " + myArr[5]);
String[] strArr = {"Jos", "Bob", "Mark", "Jules"};
System.out.println("Tweede manier -> " + strArr[0]);
// Met datatype van double en char.
double[] doubleArr = {15.5, 20.5, 35.5};
char[] charArr = {'a', 'b', 'c', 'd'};
// Druk 1 element van beide array's af in de command lijn.
System.out.println("data type double -> " + doubleArr[1] + "\n" + "data type char -> " + charArr[3]);
System.out.println("---- Oefening - 2 ----");
// 1. Creëer een String array met 5 elementen.
String[] strArray = {"ferrari", "lambhorgni", "bugatti", "mercerdes", "audi"};
// 2. Druk<SUF>
System.out.println("One element of the array -> " + strArray[2]);
// 3. Druk de lengte van je array af.
System.out.println("Array lenght -> " + strArray.length);
System.out.println("---- Oefening - 3 ----");
// 1. Schrijf een programma om de even en oneven nummer te vinden in een int array.
int[] numArray = {1,2,3,4,5,6,7,8,9,10,11};
int evenCounter = 0;
int oddCounter = 0;
for (int evenOrOdd : numArray) {
if (evenOrOdd % 2 == 0) {
evenCounter++;
} else {
oddCounter++;
}
}
System.out.println("Number of even numbers -> " + evenCounter + "\n" + "number of odd numbers -> " + oddCounter);
}
}
| false | 527 | 17 | 563 | 18 | 572 | 15 | 563 | 18 | 614 | 17 | false | false | false | false | false | true |
2,372 | 11194_9 | package com.example.moyeecoffee;
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class FragmentA extends Fragment
{
private ArrayList<PointOfSale> pointsOfSale;
private WebView browser;
private View mContentView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle saved)
{
mContentView = inflater.inflate(R.layout.frag_a, group, false);
browser = (WebView)mContentView.findViewById(R.id.webview);
pointsOfSale = new ArrayList<PointOfSale>();
// Navigatie binnen de pagina dient plaats te vinden binnen dezelfde webview.
// Dus we stellen een nieuwe webclient in.
browser.setWebViewClient(new WebViewClient());
// Stel via de websettings in dat javascript uitgevoerd kan worden.
WebSettings settings = browser.getSettings();
settings.setJavaScriptEnabled(true);
// Maak de Points of Sale, deze kunnen eventueel in een database worden geplaatst.
PointOfSale pos1 = new PointOfSale("Stach", "Van Woustraat 154", 52.352682, 4.902842, null);
PointOfSale pos2 = new PointOfSale("Stach", "Nieuwe Spiegelstraat 52", 52.363467, 4.888659, null);
// Voeg de Point of Sales ook toe aan de pointsOfSale arraylist om later dynamisch een url op te bouwen.
pointsOfSale.add(pos1);
pointsOfSale.add(pos2);
// Maak de dynamische url om mee te geven aan de webview.
// Er wordt per Point of Sale een stuk een de dynamicURL toegevoegt.
String dynamicURL = "http://www.moyeemobile.nl/googlemap.html?";
boolean isEerstePointOfSale = true;
for(int i = 0; i < pointsOfSale.size() ; i++)
{
String urlPerPointOfSale = "";
// Laat bij de eerste Point of Sale het '&' teken weg.
if(!isEerstePointOfSale)
{
urlPerPointOfSale += "&";
}
urlPerPointOfSale += "q=" + pointsOfSale.get(i).getNaam() + "<br>" + pointsOfSale.get(i).getAdress() + "@" + pointsOfSale.get(i).getLatitude() + "," + pointsOfSale.get(i).getLongitude();
// Voeg de URL toe aan de dynamicURL.
dynamicURL += urlPerPointOfSale;
// Maak de variabele isEerstePointOfSale false zodat er in het vervolg wel het '&' teken bij komt.
// Dit is nodig om meerdere Points of Sale te laten zien.
// En dat willen we!
isEerstePointOfSale = false;
}
// Laadt de dynamicURL in de browser. Deze geeft nu de Google Maps weer.
browser.loadUrl(dynamicURL);
return mContentView;
}
@Override
public void onActivityCreated (Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
}
| chill1992/Moyee-official | src/com/example/moyeecoffee/FragmentA.java | 950 | // Maak de variabele isEerstePointOfSale false zodat er in het vervolg wel het '&' teken bij komt. | line_comment | nl | package com.example.moyeecoffee;
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class FragmentA extends Fragment
{
private ArrayList<PointOfSale> pointsOfSale;
private WebView browser;
private View mContentView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle saved)
{
mContentView = inflater.inflate(R.layout.frag_a, group, false);
browser = (WebView)mContentView.findViewById(R.id.webview);
pointsOfSale = new ArrayList<PointOfSale>();
// Navigatie binnen de pagina dient plaats te vinden binnen dezelfde webview.
// Dus we stellen een nieuwe webclient in.
browser.setWebViewClient(new WebViewClient());
// Stel via de websettings in dat javascript uitgevoerd kan worden.
WebSettings settings = browser.getSettings();
settings.setJavaScriptEnabled(true);
// Maak de Points of Sale, deze kunnen eventueel in een database worden geplaatst.
PointOfSale pos1 = new PointOfSale("Stach", "Van Woustraat 154", 52.352682, 4.902842, null);
PointOfSale pos2 = new PointOfSale("Stach", "Nieuwe Spiegelstraat 52", 52.363467, 4.888659, null);
// Voeg de Point of Sales ook toe aan de pointsOfSale arraylist om later dynamisch een url op te bouwen.
pointsOfSale.add(pos1);
pointsOfSale.add(pos2);
// Maak de dynamische url om mee te geven aan de webview.
// Er wordt per Point of Sale een stuk een de dynamicURL toegevoegt.
String dynamicURL = "http://www.moyeemobile.nl/googlemap.html?";
boolean isEerstePointOfSale = true;
for(int i = 0; i < pointsOfSale.size() ; i++)
{
String urlPerPointOfSale = "";
// Laat bij de eerste Point of Sale het '&' teken weg.
if(!isEerstePointOfSale)
{
urlPerPointOfSale += "&";
}
urlPerPointOfSale += "q=" + pointsOfSale.get(i).getNaam() + "<br>" + pointsOfSale.get(i).getAdress() + "@" + pointsOfSale.get(i).getLatitude() + "," + pointsOfSale.get(i).getLongitude();
// Voeg de URL toe aan de dynamicURL.
dynamicURL += urlPerPointOfSale;
// Maak de<SUF>
// Dit is nodig om meerdere Points of Sale te laten zien.
// En dat willen we!
isEerstePointOfSale = false;
}
// Laadt de dynamicURL in de browser. Deze geeft nu de Google Maps weer.
browser.loadUrl(dynamicURL);
return mContentView;
}
@Override
public void onActivityCreated (Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
}
| false | 756 | 31 | 891 | 34 | 827 | 25 | 891 | 34 | 1,036 | 35 | false | false | false | false | false | true |
605 | 65818_3 | package com.example.forumapplication.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.example.forumapplication.Activities.homeItemAdapter;
import com.example.forumapplication.R;
import com.example.forumapplication.Data.HomeItem;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class HomeFragment extends Fragment {
private DrawerLayout drawerLayout;
private RecyclerView recyclerView;
private homeItemAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
public JSONObject jsonObject;
public String category;
public ArrayList<HomeItem> home_items_list;
public HomeItem item;
private static String categorien_End_point = " http://192.168.178.103:4000/categories";
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home,container,false);
home_items_list = new ArrayList<>();
/*
home_items_list.add(new home_items(R.drawable.voetball,"Voetball"));
home_items_list.add(new home_items(R.drawable.basketball,"Basketball"));
home_items_list.add(new home_items(R.drawable.veldhockey,"Veldhockey"));
home_items_list.add(new home_items(R.drawable.swim,"Swimming"));
home_items_list.add(new home_items(R.drawable.volleyball,"Volleyball"));
Log.e(" hi",home_items_list.toString());
*/ recyclerView =(RecyclerView)view.findViewById(R.id.recycle_view);
recyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getContext());
getCategorien();
return view;
}
public void getCategorien(){
final RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, categorien_End_point, null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
System.out.println(response.toString());
for (int i = 0; i < response.length(); i++) {
try {
jsonObject= response.getJSONObject(i);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(mAdapter);
category = jsonObject.getString("category");
Log.e("Voorbeeld", category);
item = new HomeItem(R.drawable.ic_post, category); //HomeItem
item.setId(jsonObject.getString("id"));
home_items_list.add(item);
System.out.println(category);
Log.e("Home_item", item.toString());
Log.e("list",home_items_list.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonArrayRequest);
mAdapter = new homeItemAdapter(home_items_list);
mAdapter.setOnItemClickListener(new homeItemAdapter.OnItemClickListener() {
@Override
public void onItemClick(int position) {
Fragment fragment ;
//ArrayList<HomeItem> temp = new ArrayList<>();
// call naar de backend met de id van de categorie waar je op hebt geklikt
// vervolgens vul je de arraylist met de reponse
// daarmee maak je een nieuwe main
System.out.println(home_items_list.get(position));
if(home_items_list.get(position).getText().equals("Fitness")){
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new FitnessFragment()).commit();
}else if(home_items_list.get(position).getText().equals("Voetbal")){
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new VoetballFragment()).commit();
}else{
Toast.makeText(getActivity(), "Nog geen fragment gemaakt", Toast.LENGTH_SHORT).show();
}
/*HomeItem tmp = home_items_list.get(position);
String url = String.format("http://192.168.178.103:4000/categories/%s/posts", tmp.getID() );
MyPostsFragment mypostFragment = new MyPostsFragment();
mypostFragment.getPostData(url);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,mypostFragment).commit();
*/
/*
switch (category) {
case "Voetbal":fragment = new VoetballFragment();
break;
case "Fitness": fragment = new FitnessFragment();
break;
default:fragment = new Fragment();
}
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
*/
}
});
}
}
| Gertjan1996/Project-2.4-Web-Mobile | ForumApplication/app/src/main/java/com/example/forumapplication/Fragment/HomeFragment.java | 1,642 | // vervolgens vul je de arraylist met de reponse | line_comment | nl | package com.example.forumapplication.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.example.forumapplication.Activities.homeItemAdapter;
import com.example.forumapplication.R;
import com.example.forumapplication.Data.HomeItem;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class HomeFragment extends Fragment {
private DrawerLayout drawerLayout;
private RecyclerView recyclerView;
private homeItemAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
public JSONObject jsonObject;
public String category;
public ArrayList<HomeItem> home_items_list;
public HomeItem item;
private static String categorien_End_point = " http://192.168.178.103:4000/categories";
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home,container,false);
home_items_list = new ArrayList<>();
/*
home_items_list.add(new home_items(R.drawable.voetball,"Voetball"));
home_items_list.add(new home_items(R.drawable.basketball,"Basketball"));
home_items_list.add(new home_items(R.drawable.veldhockey,"Veldhockey"));
home_items_list.add(new home_items(R.drawable.swim,"Swimming"));
home_items_list.add(new home_items(R.drawable.volleyball,"Volleyball"));
Log.e(" hi",home_items_list.toString());
*/ recyclerView =(RecyclerView)view.findViewById(R.id.recycle_view);
recyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getContext());
getCategorien();
return view;
}
public void getCategorien(){
final RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, categorien_End_point, null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
System.out.println(response.toString());
for (int i = 0; i < response.length(); i++) {
try {
jsonObject= response.getJSONObject(i);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(mAdapter);
category = jsonObject.getString("category");
Log.e("Voorbeeld", category);
item = new HomeItem(R.drawable.ic_post, category); //HomeItem
item.setId(jsonObject.getString("id"));
home_items_list.add(item);
System.out.println(category);
Log.e("Home_item", item.toString());
Log.e("list",home_items_list.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonArrayRequest);
mAdapter = new homeItemAdapter(home_items_list);
mAdapter.setOnItemClickListener(new homeItemAdapter.OnItemClickListener() {
@Override
public void onItemClick(int position) {
Fragment fragment ;
//ArrayList<HomeItem> temp = new ArrayList<>();
// call naar de backend met de id van de categorie waar je op hebt geklikt
// vervolgens vul<SUF>
// daarmee maak je een nieuwe main
System.out.println(home_items_list.get(position));
if(home_items_list.get(position).getText().equals("Fitness")){
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new FitnessFragment()).commit();
}else if(home_items_list.get(position).getText().equals("Voetbal")){
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new VoetballFragment()).commit();
}else{
Toast.makeText(getActivity(), "Nog geen fragment gemaakt", Toast.LENGTH_SHORT).show();
}
/*HomeItem tmp = home_items_list.get(position);
String url = String.format("http://192.168.178.103:4000/categories/%s/posts", tmp.getID() );
MyPostsFragment mypostFragment = new MyPostsFragment();
mypostFragment.getPostData(url);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,mypostFragment).commit();
*/
/*
switch (category) {
case "Voetbal":fragment = new VoetballFragment();
break;
case "Fitness": fragment = new FitnessFragment();
break;
default:fragment = new Fragment();
}
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
*/
}
});
}
}
| false | 1,066 | 13 | 1,366 | 13 | 1,393 | 11 | 1,366 | 13 | 1,587 | 13 | false | false | false | false | false | true |
1,791 | 51864_6 | package ui.controller;
import domain.model.Animal;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
public class Add extends RequestHandler {
@Override
public String handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
ArrayList<String> errors = new ArrayList<>();
Animal animal = new Animal();
setName(animal, request, errors);
setType(animal, request, errors);
setFood(animal, request, errors);
if (errors.size() == 0) {
try {
service.addAnimal(animal);
HttpSession session = request.getSession();
// geef bij sendRedirect informatie door via session attribute
// indien nodig: verwijder attribuut als het gebruikt is
// kan ook via parameter in querystring bijv "Controller?command=Overview&laatstToegevoegdId=23"
// in dit voorbeeld: we willen op overzichtspagina altijd laatst toegevoegde dier tonen
// moet via session omdat request attribuut verloren gaat bij sendredirect
session.setAttribute("lastAddedAnimal", animal);
// creëer 300-status met sendRedirect
response.sendRedirect("Controller?command=Overview");
// return value mag niet null zijn, want anders nullpointerException in Controller
// maar de waarde van de string die je returnt is hier onbelangrijk
return "Controller?command=Overview";
}
catch (IllegalArgumentException exc) {
request.setAttribute("error", exc.getMessage());
return "Controller?command=AddForm";
}
}
else {
request.setAttribute("errors", errors);
return "Controller?command=AddForm";
}
}
private void setName(Animal animal, HttpServletRequest request, ArrayList<String> errors) {
String name = request.getParameter("name");
try {
animal.setName(name);
request.setAttribute("nameClass", "has-success");
request.setAttribute("namePreviousValue", name);
}
catch (IllegalArgumentException exc) {
errors.add(exc.getMessage());
request.setAttribute("nameClass", "has-error");
}
}
private void setType(Animal animal, HttpServletRequest request, ArrayList<String> errors) {
String type = request.getParameter("type");
try {
animal.setType(type);
request.setAttribute("typeClass", "has-success");
request.setAttribute("typePreviousValue", type);
}
catch (IllegalArgumentException exc) {
errors.add(exc.getMessage());
request.setAttribute("typeClass", "has-error");
}
}
private void setFood(Animal animal, HttpServletRequest request, ArrayList<String> errors) {
int food;
if(request.getParameter("food").isBlank()){
food = -1;
}else{
food = Integer.parseInt(request.getParameter("food"));
}
try {
animal.setFood(food);
request.setAttribute("foodClass", "has-success");
request.setAttribute("foodPreviousValue", food);
}
catch (IllegalArgumentException exc) {
errors.add(exc.getMessage());
request.setAttribute("foodClass", "has-error");
}
}
}
| UCLLWeb3-2223/PostRedirectGet | src/main/java/ui/controller/Add.java | 912 | // return value mag niet null zijn, want anders nullpointerException in Controller | line_comment | nl | package ui.controller;
import domain.model.Animal;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
public class Add extends RequestHandler {
@Override
public String handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
ArrayList<String> errors = new ArrayList<>();
Animal animal = new Animal();
setName(animal, request, errors);
setType(animal, request, errors);
setFood(animal, request, errors);
if (errors.size() == 0) {
try {
service.addAnimal(animal);
HttpSession session = request.getSession();
// geef bij sendRedirect informatie door via session attribute
// indien nodig: verwijder attribuut als het gebruikt is
// kan ook via parameter in querystring bijv "Controller?command=Overview&laatstToegevoegdId=23"
// in dit voorbeeld: we willen op overzichtspagina altijd laatst toegevoegde dier tonen
// moet via session omdat request attribuut verloren gaat bij sendredirect
session.setAttribute("lastAddedAnimal", animal);
// creëer 300-status met sendRedirect
response.sendRedirect("Controller?command=Overview");
// return value<SUF>
// maar de waarde van de string die je returnt is hier onbelangrijk
return "Controller?command=Overview";
}
catch (IllegalArgumentException exc) {
request.setAttribute("error", exc.getMessage());
return "Controller?command=AddForm";
}
}
else {
request.setAttribute("errors", errors);
return "Controller?command=AddForm";
}
}
private void setName(Animal animal, HttpServletRequest request, ArrayList<String> errors) {
String name = request.getParameter("name");
try {
animal.setName(name);
request.setAttribute("nameClass", "has-success");
request.setAttribute("namePreviousValue", name);
}
catch (IllegalArgumentException exc) {
errors.add(exc.getMessage());
request.setAttribute("nameClass", "has-error");
}
}
private void setType(Animal animal, HttpServletRequest request, ArrayList<String> errors) {
String type = request.getParameter("type");
try {
animal.setType(type);
request.setAttribute("typeClass", "has-success");
request.setAttribute("typePreviousValue", type);
}
catch (IllegalArgumentException exc) {
errors.add(exc.getMessage());
request.setAttribute("typeClass", "has-error");
}
}
private void setFood(Animal animal, HttpServletRequest request, ArrayList<String> errors) {
int food;
if(request.getParameter("food").isBlank()){
food = -1;
}else{
food = Integer.parseInt(request.getParameter("food"));
}
try {
animal.setFood(food);
request.setAttribute("foodClass", "has-success");
request.setAttribute("foodPreviousValue", food);
}
catch (IllegalArgumentException exc) {
errors.add(exc.getMessage());
request.setAttribute("foodClass", "has-error");
}
}
}
| false | 666 | 15 | 755 | 16 | 799 | 15 | 755 | 16 | 893 | 16 | false | false | false | false | false | true |
1,946 | 50052_0 | package com.app.platform.repos;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
import com.app.platform.model.Leerkracht;
import com.app.platform.model.Toets;
public interface ToetsRepository extends JpaRepository<Toets, Integer>{
// save schrijft weg en Flush voor voert wijzigingen meteen uit
@SuppressWarnings("unchecked")
@Transactional
Toets saveAndFlush(Toets newToets);
List<Toets> findAllByLeerkracht(Leerkracht l);
} | aarontenzing/school_platform | platform/src/main/java/com/app/platform/repos/ToetsRepository.java | 171 | // save schrijft weg en Flush voor voert wijzigingen meteen uit | line_comment | nl | package com.app.platform.repos;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
import com.app.platform.model.Leerkracht;
import com.app.platform.model.Toets;
public interface ToetsRepository extends JpaRepository<Toets, Integer>{
// save schrijft<SUF>
@SuppressWarnings("unchecked")
@Transactional
Toets saveAndFlush(Toets newToets);
List<Toets> findAllByLeerkracht(Leerkracht l);
} | false | 119 | 18 | 162 | 20 | 145 | 16 | 162 | 20 | 174 | 19 | false | false | false | false | false | true |
3,528 | 177639_0 | package com.example.f1codingbackend.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import com.microsoft.azure.sdk.iot.service.*;
import java.io.IOException;
import java.net.URISyntaxException;
//mogelijkheid om id te pushen naar rfid path = /rfid/id ( id => userid)
@RestController
public class IotHubController {
private static final String connectionString = "HostName=Project40.azure-devices.net;SharedAccessKeyName=service;SharedAccessKey=8JPey/Gfh44/+0rQFJNlKew/adn+SGRkXPLbq1t01uU=";
private static final String deviceId = "RPIRFID";
private static final IotHubServiceClientProtocol protocol = IotHubServiceClientProtocol.AMQPS;
@PostMapping("/rfid/{id}")
public static void main(String[] args, @PathVariable Long id) throws IOException,
URISyntaxException, Exception {
ServiceClient serviceClient = ServiceClient.createFromConnectionString(
connectionString, protocol);
if (serviceClient != null) {
serviceClient.open();
FeedbackReceiver feedbackReceiver = serviceClient
.getFeedbackReceiver();
if (feedbackReceiver != null) feedbackReceiver.open();
Message messageToSend = new Message("newCardID: " + String.valueOf(id));
messageToSend.setDeliveryAcknowledgement(DeliveryAcknowledgement.Full);
serviceClient.send(deviceId, messageToSend);
System.out.println("Message sent to device");
FeedbackBatch feedbackBatch = feedbackReceiver.receive(10000);
if (feedbackBatch != null) {
System.out.println("Message feedback received, feedback time: "
+ feedbackBatch.getEnqueuedTimeUtc().toString());
}
if (feedbackReceiver != null) feedbackReceiver.close();
serviceClient.close();
}
}
}
| m4t5k4/TeamF1CodingApi | src/main/java/com/example/f1codingbackend/controller/IotHubController.java | 537 | //mogelijkheid om id te pushen naar rfid path = /rfid/id ( id => userid) | line_comment | nl | package com.example.f1codingbackend.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import com.microsoft.azure.sdk.iot.service.*;
import java.io.IOException;
import java.net.URISyntaxException;
//mogelijkheid om<SUF>
@RestController
public class IotHubController {
private static final String connectionString = "HostName=Project40.azure-devices.net;SharedAccessKeyName=service;SharedAccessKey=8JPey/Gfh44/+0rQFJNlKew/adn+SGRkXPLbq1t01uU=";
private static final String deviceId = "RPIRFID";
private static final IotHubServiceClientProtocol protocol = IotHubServiceClientProtocol.AMQPS;
@PostMapping("/rfid/{id}")
public static void main(String[] args, @PathVariable Long id) throws IOException,
URISyntaxException, Exception {
ServiceClient serviceClient = ServiceClient.createFromConnectionString(
connectionString, protocol);
if (serviceClient != null) {
serviceClient.open();
FeedbackReceiver feedbackReceiver = serviceClient
.getFeedbackReceiver();
if (feedbackReceiver != null) feedbackReceiver.open();
Message messageToSend = new Message("newCardID: " + String.valueOf(id));
messageToSend.setDeliveryAcknowledgement(DeliveryAcknowledgement.Full);
serviceClient.send(deviceId, messageToSend);
System.out.println("Message sent to device");
FeedbackBatch feedbackBatch = feedbackReceiver.receive(10000);
if (feedbackBatch != null) {
System.out.println("Message feedback received, feedback time: "
+ feedbackBatch.getEnqueuedTimeUtc().toString());
}
if (feedbackReceiver != null) feedbackReceiver.close();
serviceClient.close();
}
}
}
| false | 397 | 24 | 458 | 26 | 471 | 23 | 458 | 26 | 542 | 27 | false | false | false | false | false | true |
4,207 | 186682_0 | package les6.Practicum6A;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.LocalDate;
import static org.junit.jupiter.api.Assertions.*;
class GameTest {
private Game game1JrOud;
private int ditJaar;
@BeforeEach
public void init(){
ditJaar = LocalDate.now().getYear();
game1JrOud = new Game("Mario Kart", ditJaar-1, 50.0);
}
//region Tests met huidigeWaarde()
@Test
public void testHuidigeWaardeNwPrijsNa0Jr(){
Game game0JrOud = new Game("Mario Kart", ditJaar, 50.0);
assertEquals(50.0, Math.round(game0JrOud.huidigeWaarde() * 100)/100d, "Huidige waarde na 0 jr niet correct.");
}
@Test
public void testHuidigeWaardeNwPrijsNa1Jr(){
assertEquals(35.0, Math.round(game1JrOud.huidigeWaarde() * 100)/100d, "Huidige waarde na 1 jr niet correct.");
}
@Test
public void testHuidigeWaardeNwPrijsNa5Jr(){
Game game5JrOud = new Game("Mario Kart", ditJaar-5, 50.0);
assertEquals(8.4, Math.round(game5JrOud.huidigeWaarde() * 100)/100d, "Huidige waarde na 5 jr niet correct.");
}
@Test
public void testHuidigeWaardeGratisGameNa0Jr(){
Game gratisGame0JrOud = new Game("Mario Kart Free", ditJaar, 0.0);
assertEquals(0.0, Math.round(gratisGame0JrOud.huidigeWaarde() * 100)/100d, "Huidige waarde gratis game na 0 jr niet correct.");
}
@Test
public void testHuidigeWaardeGratisGameNa5Jr(){
Game gratisGame5JrOud = new Game("Mario Kart Free", ditJaar-5, 0.0);
assertEquals(0.0, Math.round(gratisGame5JrOud.huidigeWaarde() * 100)/100d, "Huidige waarde gratis game na 5 jr niet correct.");
}
//endregion
//region Tests met equals()
@Test
public void testGameEqualsZelfdeGame() {
Game zelfdeGame1JrOud = new Game("Mario Kart", ditJaar-1, 50.0);
assertTrue(game1JrOud.equals(zelfdeGame1JrOud), "equals() geeft false bij vgl. met zelfde game");
}
@Test
public void testGameEqualsSelf() {
assertTrue(game1JrOud.equals(game1JrOud), "equals() geeft false bij vgl. met zichzelf");
}
@Test
public void testGameNotEqualsString() {
assertFalse(game1JrOud.equals("testString"), "equals() geeft true bij vgl. tussen game en String");
}
@Test
public void testGameNotEqualsGameAndereNaam() {
Game otherGame1JrOud = new Game("Zelda", ditJaar-1, 35.0);
assertFalse(game1JrOud.equals(otherGame1JrOud), "equals() geeft true bij vgl. met game met andere naam");
}
@Test
public void testGameNotEqualsGameAnderJaar() {
Game game5JrOud = new Game("Mario Kart", ditJaar-5, 50.0);
assertFalse(game1JrOud.equals(game5JrOud), "equals() geeft true bij vgl. met game met ander releaseJaar");
}
@Test
public void testGameEqualsGameAndereNwPrijs() {
Game duurdereGame1JrOud = new Game("Mario Kart", ditJaar-1, 59.95);
assertTrue(game1JrOud.equals(duurdereGame1JrOud), "equals() geeft false bij vgl. met zelfde game met andere nieuwprijs");
}
@Test
public void testGameNotEqualsGameHeelAndereGame() {
Game heelAndereGame = new Game("Zelda", ditJaar-2, 41.95);
assertFalse(game1JrOud.equals(heelAndereGame), "equals() geeft true bij vgl. met heel andere game");
}
//endregion
@Test
public void testToString(){
assertEquals("Mario Kart, uitgegeven in " + (ditJaar-1) + "; nieuwprijs: €50,00 nu voor: €35,00",
game1JrOud.toString(), "toString() geeft niet de juiste tekst terug.");
}
} | rosstuck/practica-tests | test/les6/Practicum6A/GameTest.java | 1,323 | //region Tests met huidigeWaarde() | line_comment | nl | package les6.Practicum6A;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.LocalDate;
import static org.junit.jupiter.api.Assertions.*;
class GameTest {
private Game game1JrOud;
private int ditJaar;
@BeforeEach
public void init(){
ditJaar = LocalDate.now().getYear();
game1JrOud = new Game("Mario Kart", ditJaar-1, 50.0);
}
//region Tests<SUF>
@Test
public void testHuidigeWaardeNwPrijsNa0Jr(){
Game game0JrOud = new Game("Mario Kart", ditJaar, 50.0);
assertEquals(50.0, Math.round(game0JrOud.huidigeWaarde() * 100)/100d, "Huidige waarde na 0 jr niet correct.");
}
@Test
public void testHuidigeWaardeNwPrijsNa1Jr(){
assertEquals(35.0, Math.round(game1JrOud.huidigeWaarde() * 100)/100d, "Huidige waarde na 1 jr niet correct.");
}
@Test
public void testHuidigeWaardeNwPrijsNa5Jr(){
Game game5JrOud = new Game("Mario Kart", ditJaar-5, 50.0);
assertEquals(8.4, Math.round(game5JrOud.huidigeWaarde() * 100)/100d, "Huidige waarde na 5 jr niet correct.");
}
@Test
public void testHuidigeWaardeGratisGameNa0Jr(){
Game gratisGame0JrOud = new Game("Mario Kart Free", ditJaar, 0.0);
assertEquals(0.0, Math.round(gratisGame0JrOud.huidigeWaarde() * 100)/100d, "Huidige waarde gratis game na 0 jr niet correct.");
}
@Test
public void testHuidigeWaardeGratisGameNa5Jr(){
Game gratisGame5JrOud = new Game("Mario Kart Free", ditJaar-5, 0.0);
assertEquals(0.0, Math.round(gratisGame5JrOud.huidigeWaarde() * 100)/100d, "Huidige waarde gratis game na 5 jr niet correct.");
}
//endregion
//region Tests met equals()
@Test
public void testGameEqualsZelfdeGame() {
Game zelfdeGame1JrOud = new Game("Mario Kart", ditJaar-1, 50.0);
assertTrue(game1JrOud.equals(zelfdeGame1JrOud), "equals() geeft false bij vgl. met zelfde game");
}
@Test
public void testGameEqualsSelf() {
assertTrue(game1JrOud.equals(game1JrOud), "equals() geeft false bij vgl. met zichzelf");
}
@Test
public void testGameNotEqualsString() {
assertFalse(game1JrOud.equals("testString"), "equals() geeft true bij vgl. tussen game en String");
}
@Test
public void testGameNotEqualsGameAndereNaam() {
Game otherGame1JrOud = new Game("Zelda", ditJaar-1, 35.0);
assertFalse(game1JrOud.equals(otherGame1JrOud), "equals() geeft true bij vgl. met game met andere naam");
}
@Test
public void testGameNotEqualsGameAnderJaar() {
Game game5JrOud = new Game("Mario Kart", ditJaar-5, 50.0);
assertFalse(game1JrOud.equals(game5JrOud), "equals() geeft true bij vgl. met game met ander releaseJaar");
}
@Test
public void testGameEqualsGameAndereNwPrijs() {
Game duurdereGame1JrOud = new Game("Mario Kart", ditJaar-1, 59.95);
assertTrue(game1JrOud.equals(duurdereGame1JrOud), "equals() geeft false bij vgl. met zelfde game met andere nieuwprijs");
}
@Test
public void testGameNotEqualsGameHeelAndereGame() {
Game heelAndereGame = new Game("Zelda", ditJaar-2, 41.95);
assertFalse(game1JrOud.equals(heelAndereGame), "equals() geeft true bij vgl. met heel andere game");
}
//endregion
@Test
public void testToString(){
assertEquals("Mario Kart, uitgegeven in " + (ditJaar-1) + "; nieuwprijs: €50,00 nu voor: €35,00",
game1JrOud.toString(), "toString() geeft niet de juiste tekst terug.");
}
} | false | 1,168 | 10 | 1,230 | 11 | 1,193 | 8 | 1,230 | 11 | 1,379 | 12 | false | false | false | false | false | true |
4,680 | 79453_0 | package com.ipsene.ipsene.controller;
import com.google.api.core.ApiFuture;
import com.google.cloud.firestore.*;
import com.google.firebase.cloud.FirestoreClient;
import com.ipsene.ipsene.Globals;
import com.ipsene.ipsene.SceneController;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.event.ActionEvent;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class AccusationController {
List<String> solutionList = new ArrayList<>();
@FXML
private ChoiceBox<String> whoChoice;
@FXML
private ChoiceBox<String> whatChoice;
@FXML
private ChoiceBox<String> whereChoice;
@FXML
private Button accusationButton;
public static final String lobbyPin = Globals.get_instance().lobbyPin;
Firestore db = FirestoreClient.getFirestore();
SceneController sceneController = new SceneController();
BoardController boardController = new BoardController();
public AccusationController() throws ExecutionException, InterruptedException{
}
public void initialize() {
fillWhatChoice();
fillWhoChoice();
filWhereChoice();
accusationButton.disableProperty().bind(
whoChoice.getSelectionModel().selectedItemProperty().isNull()
.or(whereChoice.getSelectionModel().selectedItemProperty().isNull())
.or(whatChoice.getSelectionModel().selectedItemProperty().isNull()));
}
public void fillWhoChoice(){
List<String> whoList = Arrays.asList("Miss Scarlet", "Colonel Mustard", "Mrs. White", "Mr. Green", "Mrs. Peacock", "Professor Plum");
whoChoice.getItems().addAll(whoList);
}
public void fillWhoChoiceEx() throws ExecutionException, InterruptedException {
List<String> whoList = new ArrayList<>();
CollectionReference docRef = db.collection(lobbyPin);
ApiFuture<QuerySnapshot> query = docRef.get();
QuerySnapshot snapshot = query.get();
snapshot.forEach((doc)-> {
whoList.add(doc.getId());
});
if(whoList.contains("System")){whoList.remove("System");}
whoChoice.getItems().addAll(whoList);
}
public void fillWhatChoice(){
List<String> whatList = Arrays.asList("Candlestick", "Dagger", "Lead pipe", "Revolver", "Rope", "Wrench");
whatChoice.getItems().addAll(whatList);
}
public void filWhereChoice(){
List<String> whereList = Arrays.asList("Kitchen", "Ballroom", "Conservatory", "Dining room", "Billiard room", "Library", "Lounge", "Hall", "Study");
whereChoice.getItems().addAll(whereList);
}
public void closeButtonAction(ActionEvent event) {
sceneController.closeWindow(event);
}
public List<String> getSolution() throws ExecutionException, InterruptedException {
DocumentReference docRef = db.collection(lobbyPin).document("System");
ApiFuture<DocumentSnapshot> future = docRef.get();
DocumentSnapshot document = future.get();
solutionList.add(Objects.requireNonNull(document.getData()).get("solPerson").toString());
solutionList.add(Objects.requireNonNull(document.getData()).get("solWeapon").toString());
solutionList.add(Objects.requireNonNull(document.getData()).get("solRoom").toString());
return solutionList;
}
public void accusationButton(ActionEvent event) throws IOException {
try{
String currentPlayer = Globals.get_instance().chosenPlayer;
//haalt de informatie op uit de keuzes
Object who = whoChoice.getSelectionModel().getSelectedItem();
Object what = whatChoice.getSelectionModel().getSelectedItem();
Object where = whereChoice.getSelectionModel().getSelectedItem();
//kijkt wat de solution is
solutionList = getSolution();
//vergelijkt de solution met het antwoord
if(solutionList.get(0).contains(who.toString()) && solutionList.get(1).contains(what.toString()) &&
solutionList.get(2).contains(where.toString())){
DocumentReference docRef = db.collection(lobbyPin).document("System");
Map<String, Object> updates = new HashMap<>();
updates.put("win", currentPlayer);
docRef.set(updates, SetOptions.merge());
boardController.switchPlayer(event);
sceneController.closeWindow(event);
} else {
Alert a = new Alert(Alert.AlertType.WARNING);
a.setContentText("You got it wrong \n Your turn has ended") ;
a.show();
boardController.switchPlayer(event);
sceneController.closeWindow(event);
}
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
}
} | wbouhdif/Cluedo-JavaFX | src/main/java/com/ipsene/ipsene/controller/AccusationController.java | 1,366 | //haalt de informatie op uit de keuzes | line_comment | nl | package com.ipsene.ipsene.controller;
import com.google.api.core.ApiFuture;
import com.google.cloud.firestore.*;
import com.google.firebase.cloud.FirestoreClient;
import com.ipsene.ipsene.Globals;
import com.ipsene.ipsene.SceneController;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.event.ActionEvent;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class AccusationController {
List<String> solutionList = new ArrayList<>();
@FXML
private ChoiceBox<String> whoChoice;
@FXML
private ChoiceBox<String> whatChoice;
@FXML
private ChoiceBox<String> whereChoice;
@FXML
private Button accusationButton;
public static final String lobbyPin = Globals.get_instance().lobbyPin;
Firestore db = FirestoreClient.getFirestore();
SceneController sceneController = new SceneController();
BoardController boardController = new BoardController();
public AccusationController() throws ExecutionException, InterruptedException{
}
public void initialize() {
fillWhatChoice();
fillWhoChoice();
filWhereChoice();
accusationButton.disableProperty().bind(
whoChoice.getSelectionModel().selectedItemProperty().isNull()
.or(whereChoice.getSelectionModel().selectedItemProperty().isNull())
.or(whatChoice.getSelectionModel().selectedItemProperty().isNull()));
}
public void fillWhoChoice(){
List<String> whoList = Arrays.asList("Miss Scarlet", "Colonel Mustard", "Mrs. White", "Mr. Green", "Mrs. Peacock", "Professor Plum");
whoChoice.getItems().addAll(whoList);
}
public void fillWhoChoiceEx() throws ExecutionException, InterruptedException {
List<String> whoList = new ArrayList<>();
CollectionReference docRef = db.collection(lobbyPin);
ApiFuture<QuerySnapshot> query = docRef.get();
QuerySnapshot snapshot = query.get();
snapshot.forEach((doc)-> {
whoList.add(doc.getId());
});
if(whoList.contains("System")){whoList.remove("System");}
whoChoice.getItems().addAll(whoList);
}
public void fillWhatChoice(){
List<String> whatList = Arrays.asList("Candlestick", "Dagger", "Lead pipe", "Revolver", "Rope", "Wrench");
whatChoice.getItems().addAll(whatList);
}
public void filWhereChoice(){
List<String> whereList = Arrays.asList("Kitchen", "Ballroom", "Conservatory", "Dining room", "Billiard room", "Library", "Lounge", "Hall", "Study");
whereChoice.getItems().addAll(whereList);
}
public void closeButtonAction(ActionEvent event) {
sceneController.closeWindow(event);
}
public List<String> getSolution() throws ExecutionException, InterruptedException {
DocumentReference docRef = db.collection(lobbyPin).document("System");
ApiFuture<DocumentSnapshot> future = docRef.get();
DocumentSnapshot document = future.get();
solutionList.add(Objects.requireNonNull(document.getData()).get("solPerson").toString());
solutionList.add(Objects.requireNonNull(document.getData()).get("solWeapon").toString());
solutionList.add(Objects.requireNonNull(document.getData()).get("solRoom").toString());
return solutionList;
}
public void accusationButton(ActionEvent event) throws IOException {
try{
String currentPlayer = Globals.get_instance().chosenPlayer;
//haalt de<SUF>
Object who = whoChoice.getSelectionModel().getSelectedItem();
Object what = whatChoice.getSelectionModel().getSelectedItem();
Object where = whereChoice.getSelectionModel().getSelectedItem();
//kijkt wat de solution is
solutionList = getSolution();
//vergelijkt de solution met het antwoord
if(solutionList.get(0).contains(who.toString()) && solutionList.get(1).contains(what.toString()) &&
solutionList.get(2).contains(where.toString())){
DocumentReference docRef = db.collection(lobbyPin).document("System");
Map<String, Object> updates = new HashMap<>();
updates.put("win", currentPlayer);
docRef.set(updates, SetOptions.merge());
boardController.switchPlayer(event);
sceneController.closeWindow(event);
} else {
Alert a = new Alert(Alert.AlertType.WARNING);
a.setContentText("You got it wrong \n Your turn has ended") ;
a.show();
boardController.switchPlayer(event);
sceneController.closeWindow(event);
}
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
}
} | false | 973 | 11 | 1,130 | 11 | 1,181 | 10 | 1,130 | 11 | 1,337 | 12 | false | false | false | false | false | true |
4,745 | 193194_1 | import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class UserDAO { //klasse om te interageren met de database user table
public static ResultSet getAll(int demandedAge, Connection connection){ // voorbeeld van een getAll DAO, moeten deze voor elke mogelijke query
String query = "SELECT user FROM user WHERE age = demandedAge"; // en elke mogelijke combinatie gemaakt worden?
try {
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery(query);
return rs;
} catch (SQLException exception) {
System.err.println(exception.getMessage());
}
return null;
}
public static ResultSet get(long usernumber, Connection connection) { // query om een user uit de lijst te halen
String query = "SELECT FROM user WHERE userNumber = " + usernumber;
try {
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery(query);
return rs;
} catch (SQLException exception) {
System.err.println(exception.getMessage());
}
return null;
}
public static void update(User user, Connection connection) { // query om user up te daten
String query = "INSERT INTO user " + "VALUES (user.getUserNumber,user.getAge(),user.getEmails(), user.getPhoneNumber(),user.getFirstName(), user.getLastName())";
try{
Statement statement = connection.createStatement();
statement.executeUpdate(query);
}
catch (SQLException exception){
System.out.println(exception.getMessage());
}
}
public static void delete(User user, Connection connection){ // query om user te deleten
String query ="DELETE FROM users WHERE userNumber = user.getUserNumber";
try {
Statement st = connection.createStatement();
st.executeUpdate(query);
}
catch (SQLException exception){
System.out.println(exception.getMessage());
}
}
public static void save(User user){ // Ik weet niet wat hier zou moeten gebeuren?
}
} | xanderdecat/Project27 | src/UserDAO.java | 575 | // voorbeeld van een getAll DAO, moeten deze voor elke mogelijke query | line_comment | nl | import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class UserDAO { //klasse om te interageren met de database user table
public static ResultSet getAll(int demandedAge, Connection connection){ // voorbeeld van<SUF>
String query = "SELECT user FROM user WHERE age = demandedAge"; // en elke mogelijke combinatie gemaakt worden?
try {
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery(query);
return rs;
} catch (SQLException exception) {
System.err.println(exception.getMessage());
}
return null;
}
public static ResultSet get(long usernumber, Connection connection) { // query om een user uit de lijst te halen
String query = "SELECT FROM user WHERE userNumber = " + usernumber;
try {
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery(query);
return rs;
} catch (SQLException exception) {
System.err.println(exception.getMessage());
}
return null;
}
public static void update(User user, Connection connection) { // query om user up te daten
String query = "INSERT INTO user " + "VALUES (user.getUserNumber,user.getAge(),user.getEmails(), user.getPhoneNumber(),user.getFirstName(), user.getLastName())";
try{
Statement statement = connection.createStatement();
statement.executeUpdate(query);
}
catch (SQLException exception){
System.out.println(exception.getMessage());
}
}
public static void delete(User user, Connection connection){ // query om user te deleten
String query ="DELETE FROM users WHERE userNumber = user.getUserNumber";
try {
Statement st = connection.createStatement();
st.executeUpdate(query);
}
catch (SQLException exception){
System.out.println(exception.getMessage());
}
}
public static void save(User user){ // Ik weet niet wat hier zou moeten gebeuren?
}
} | false | 423 | 16 | 492 | 20 | 509 | 14 | 492 | 20 | 564 | 19 | false | false | false | false | false | true |
2,328 | 79577_6 | import java.io.IOException;
import nl.knmi.adaguc.tools.Debug;
import ucar.nc2.dataset.NetcdfDataset;
public class Test {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Debug.println("Hi");
//Standaard FEWS OpenDAP geeft Exception in thread "main" java.io.IOException: Server does not support Content-Length:
//NetcdfDataset netcdfDataset = NetcdfDataset.openDataset("https://data.knmi.nl/wms/cgi-bin/wms.cgi/opendap/Rd1nrt_1/prediction");
NetcdfDataset netcdfDataset = NetcdfDataset.openDataset("http://bhw485.knmi.nl:8080/cgi-bin/autoresource.cgi/opendap/testdata.nc");
// NetcdfDataset netcdfDataset = NetcdfDataset.openDataset("http://opendap.knmi.nl/knmi/thredds/dodsC/ADAGUC/testsets/regulargrids/globem_nox_sa_hires-2010-months.nc");
System.out.println(netcdfDataset.getReferencedFile());
//
// //Alternatief (ook met .dds en .das geprobeerd):
// DConnect2 url = new DConnect2("https://data.knmi.nl/wms/cgi-bin/wms.cgi/opendap/Rd1nrt_1/", true);
// try {
//
// //Ook met andere url.getDataXXX() geprobeerd geeft: opendap.dap.DAP2Exception: Not a valid OPeNDAP server - Missing MIME Header fields! Either "XDAP" or "XDODS-Server." must be present.
// DataDDS dataDDX = url.getDataDDX();
// Enumeration variables = dataDDX.getVariables();
// System.out.println(variables.nextElement());
// } catch (DAP2Exception e) {
// System.out.println(e.getMessage());
// }
}
}
| c3s-magic/adaguc-services | src/main/java/Test.java | 586 | // //Ook met andere url.getDataXXX() geprobeerd geeft: opendap.dap.DAP2Exception: Not a valid OPeNDAP server - Missing MIME Header fields! Either "XDAP" or "XDODS-Server." must be present. | line_comment | nl | import java.io.IOException;
import nl.knmi.adaguc.tools.Debug;
import ucar.nc2.dataset.NetcdfDataset;
public class Test {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Debug.println("Hi");
//Standaard FEWS OpenDAP geeft Exception in thread "main" java.io.IOException: Server does not support Content-Length:
//NetcdfDataset netcdfDataset = NetcdfDataset.openDataset("https://data.knmi.nl/wms/cgi-bin/wms.cgi/opendap/Rd1nrt_1/prediction");
NetcdfDataset netcdfDataset = NetcdfDataset.openDataset("http://bhw485.knmi.nl:8080/cgi-bin/autoresource.cgi/opendap/testdata.nc");
// NetcdfDataset netcdfDataset = NetcdfDataset.openDataset("http://opendap.knmi.nl/knmi/thredds/dodsC/ADAGUC/testsets/regulargrids/globem_nox_sa_hires-2010-months.nc");
System.out.println(netcdfDataset.getReferencedFile());
//
// //Alternatief (ook met .dds en .das geprobeerd):
// DConnect2 url = new DConnect2("https://data.knmi.nl/wms/cgi-bin/wms.cgi/opendap/Rd1nrt_1/", true);
// try {
//
// //Ook met<SUF>
// DataDDS dataDDX = url.getDataDDX();
// Enumeration variables = dataDDX.getVariables();
// System.out.println(variables.nextElement());
// } catch (DAP2Exception e) {
// System.out.println(e.getMessage());
// }
}
}
| false | 432 | 58 | 517 | 61 | 509 | 57 | 517 | 61 | 592 | 67 | false | false | false | false | false | true |
709 | 194600_9 | package be.vyncke.service;
import be.vyncke.domain.Ketel;
import org.junit.jupiter.api.*;
import static org.assertj.core.api.Assertions.*;
class KetelServiceImpTest {
static KetelServiceImp ketelServiceImp;
static Ketel ketel;
@BeforeAll
static void setup(){
ketelServiceImp = new KetelServiceImp();
}
@Test
void TC1() {
// no status >> Beschikbaar (S0 - 1)
ketel = ketelServiceImp.ketelKaken();
assertThat(ketel.getStatus().equals("Beschikbaar"));
// Beschikbaar >> Uitgeleend (S1 - 2)
assertThat(ketelServiceImp.ketelUitlenen(ketel).equals("Uitgeleend"));
// Uitgeleend >> Beschikbaar (S2 - 1)
assertThat(ketelServiceImp.ketelTerughalen(ketel).equals("Beschikbaar"));
}
@Test
void TC2() {
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Beschikbaar (S3 - 1)
assertThat(ketelServiceImp.ketelBeschikbaarZetten(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Kapot (S3 - 4)
assertThat(ketelServiceImp.ketelOnrepareerbaarVerklaren(ketel).equals("Kapot"));
}
@Test
void TC3() {
ketel = ketelServiceImp.ketelKaken();
ketel.setStatus("Onder reparatie");
// Onder reparatie >> Beschikbaar (S3 - 1)
assertThat(ketelServiceImp.ketelBeschikbaarZetten(ketel).equals("Beschikbaar"));
// Beschikbaar >> Uitgeleend (S1 - 2)
assertThat(ketelServiceImp.ketelUitlenen(ketel).equals("Uitgeleend"));
// Uitgeleend >> Beschikbaar (S2 - 1)
assertThat(ketelServiceImp.ketelTerughalen(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Beschikbaar (S3 - 1)
assertThat(ketelServiceImp.ketelBeschikbaarZetten(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
}
@Test
void TC4() {
// no status >> Beschikbaar (S0 - 1)
ketel = ketelServiceImp.ketelKaken();
assertThat(ketel.getStatus().equals("Beschikbaar"));
// Beschikbaar >> Uitgeleend (S1 - 2)
assertThat(ketelServiceImp.ketelUitlenen(ketel).equals("Uitgeleend"));
// Uitgeleend >> Beschikbaar (S2 - 1)
assertThat(ketelServiceImp.ketelTerughalen(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Beschikbaar (S3 - 1)
assertThat(ketelServiceImp.ketelBeschikbaarZetten(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Kapot (S3 - 4)
assertThat(ketelServiceImp.ketelOnrepareerbaarVerklaren(ketel).equals("Kapot"));
}
@Test
void TC5(){
ketel = ketelServiceImp.ketelKaken();
// Beschikbaar >> Uitgeleend (S1 - 2)
assertThat(ketelServiceImp.ketelUitlenen(ketel).equals("Uitgeleend"));
// Uitgeleend >> Beschikbaar (S2 - 1)
assertThat(ketelServiceImp.ketelTerughalen(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Kapot (S3 - 4)
assertThat(ketelServiceImp.ketelOnrepareerbaarVerklaren(ketel).equals("Kapot"));
}
@Test
void TC6(){
// no status >> Beschikbaar (S0 - 1)
ketel = ketelServiceImp.ketelKaken();
assertThat(ketel.getStatus().equals("Beschikbaar"));
// Beschikbaar >> Uitgeleend (S1 - 2)
assertThat(ketelServiceImp.ketelUitlenen(ketel).equals("Uitgeleend"));
// Uitgeleend >> Onder reparatie (S2 - 3) IllegalStateException expected
try{
ketelServiceImp.ketelLatenRepareren(ketel);
}catch (Exception e){
assertThat("De ketel is niet beschikbaar en kan niet naar reparatie gestuurd worden"
.equals(e.getMessage()));
}
ketel.setStatus("Kapot");
// Kapot >> Beschikbaar (S4 - 1) IllegalStateException expected
try {
ketelServiceImp.ketelTerughalen(ketel);
}catch (Exception e){
assertThat("De ketel is niet uitgeleed en kan niet teruggehaald worden"
.equals(e.getMessage()));
}
}
} | Husein-Kasem/Vyncke | vyncke_webfront/tests/be/vyncke/service/KetelServiceImpTest.java | 1,706 | // Uitgeleend >> Beschikbaar (S2 - 1) | line_comment | nl | package be.vyncke.service;
import be.vyncke.domain.Ketel;
import org.junit.jupiter.api.*;
import static org.assertj.core.api.Assertions.*;
class KetelServiceImpTest {
static KetelServiceImp ketelServiceImp;
static Ketel ketel;
@BeforeAll
static void setup(){
ketelServiceImp = new KetelServiceImp();
}
@Test
void TC1() {
// no status >> Beschikbaar (S0 - 1)
ketel = ketelServiceImp.ketelKaken();
assertThat(ketel.getStatus().equals("Beschikbaar"));
// Beschikbaar >> Uitgeleend (S1 - 2)
assertThat(ketelServiceImp.ketelUitlenen(ketel).equals("Uitgeleend"));
// Uitgeleend >> Beschikbaar (S2 - 1)
assertThat(ketelServiceImp.ketelTerughalen(ketel).equals("Beschikbaar"));
}
@Test
void TC2() {
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Beschikbaar (S3 - 1)
assertThat(ketelServiceImp.ketelBeschikbaarZetten(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Kapot (S3 - 4)
assertThat(ketelServiceImp.ketelOnrepareerbaarVerklaren(ketel).equals("Kapot"));
}
@Test
void TC3() {
ketel = ketelServiceImp.ketelKaken();
ketel.setStatus("Onder reparatie");
// Onder reparatie >> Beschikbaar (S3 - 1)
assertThat(ketelServiceImp.ketelBeschikbaarZetten(ketel).equals("Beschikbaar"));
// Beschikbaar >> Uitgeleend (S1 - 2)
assertThat(ketelServiceImp.ketelUitlenen(ketel).equals("Uitgeleend"));
// Uitgeleend >><SUF>
assertThat(ketelServiceImp.ketelTerughalen(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Beschikbaar (S3 - 1)
assertThat(ketelServiceImp.ketelBeschikbaarZetten(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
}
@Test
void TC4() {
// no status >> Beschikbaar (S0 - 1)
ketel = ketelServiceImp.ketelKaken();
assertThat(ketel.getStatus().equals("Beschikbaar"));
// Beschikbaar >> Uitgeleend (S1 - 2)
assertThat(ketelServiceImp.ketelUitlenen(ketel).equals("Uitgeleend"));
// Uitgeleend >> Beschikbaar (S2 - 1)
assertThat(ketelServiceImp.ketelTerughalen(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Beschikbaar (S3 - 1)
assertThat(ketelServiceImp.ketelBeschikbaarZetten(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Kapot (S3 - 4)
assertThat(ketelServiceImp.ketelOnrepareerbaarVerklaren(ketel).equals("Kapot"));
}
@Test
void TC5(){
ketel = ketelServiceImp.ketelKaken();
// Beschikbaar >> Uitgeleend (S1 - 2)
assertThat(ketelServiceImp.ketelUitlenen(ketel).equals("Uitgeleend"));
// Uitgeleend >> Beschikbaar (S2 - 1)
assertThat(ketelServiceImp.ketelTerughalen(ketel).equals("Beschikbaar"));
// Beschikbaar >> Onder reparatie (S1 - 3)
assertThat(ketelServiceImp.ketelLatenRepareren(ketel).equals("Onder reparatie"));
// Onder reparatie >> Kapot (S3 - 4)
assertThat(ketelServiceImp.ketelOnrepareerbaarVerklaren(ketel).equals("Kapot"));
}
@Test
void TC6(){
// no status >> Beschikbaar (S0 - 1)
ketel = ketelServiceImp.ketelKaken();
assertThat(ketel.getStatus().equals("Beschikbaar"));
// Beschikbaar >> Uitgeleend (S1 - 2)
assertThat(ketelServiceImp.ketelUitlenen(ketel).equals("Uitgeleend"));
// Uitgeleend >> Onder reparatie (S2 - 3) IllegalStateException expected
try{
ketelServiceImp.ketelLatenRepareren(ketel);
}catch (Exception e){
assertThat("De ketel is niet beschikbaar en kan niet naar reparatie gestuurd worden"
.equals(e.getMessage()));
}
ketel.setStatus("Kapot");
// Kapot >> Beschikbaar (S4 - 1) IllegalStateException expected
try {
ketelServiceImp.ketelTerughalen(ketel);
}catch (Exception e){
assertThat("De ketel is niet uitgeleed en kan niet teruggehaald worden"
.equals(e.getMessage()));
}
}
} | false | 1,471 | 17 | 1,626 | 19 | 1,455 | 14 | 1,626 | 19 | 1,695 | 16 | false | false | false | false | false | true |
1,334 | 35872_0 | import greenfoot.*;_x000D_
import java.io.IOException;_x000D_
import java.util.List;_x000D_
import java.util.ArrayList;_x000D_
import javax.swing.*;_x000D_
_x000D_
public class HelicopterWorld extends World {_x000D_
private Helicopter helicopter;_x000D_
private Counter scoreCounter;_x000D_
private MenuBar menuBar;_x000D_
private Wall wall;_x000D_
private Direction direction;_x000D_
private HeliWater water;_x000D_
private HP hp;_x000D_
private HeliHealth health1;_x000D_
private HeliHealth health2;_x000D_
private HeliHealth health3;_x000D_
private Health2 health4;_x000D_
private Health2 health5;_x000D_
private Health2 health6;_x000D_
private int healthlost;_x000D_
private int healthlostrope;_x000D_
private Victim victim;_x000D_
private House house;_x000D_
private NeedsHelp needshelp;_x000D_
GreenfootSound backgroundMusic = new GreenfootSound("background_music.mp3");_x000D_
_x000D_
public HelicopterWorld() {_x000D_
super(80, 80, 10, false);_x000D_
setBackground("bg.png");_x000D_
backgroundMusic.playLoop();_x000D_
for (int i = 1; i < 100; ++i) {_x000D_
// Willekeurige huizen en slachtoffers worden in het spel geplaatst._x000D_
Victim victim;_x000D_
House house;_x000D_
int yvictim = 58;_x000D_
int yhouse = 65;_x000D_
int x = i * 50 + (-5 + Greenfoot.getRandomNumber(30));_x000D_
int randomhouse = (int)(Math.random() * ((9 - 0) + 1));_x000D_
int randomvictim = 0 + (int)(Math.random() * ((7 - 0) + 1));_x000D_
switch (randomhouse) {_x000D_
case 0: house = new House1(); break;_x000D_
case 1: house = new House2(); yvictim -= 4; yhouse -= 2; break;_x000D_
case 2: house = new House3(); yvictim -= 2; yhouse -= 1; break;_x000D_
case 3: house = new House4(); yvictim -= 37; yhouse -= 19; break;_x000D_
case 4: house = new House5(); yvictim -= 32; yhouse -= 16; break;_x000D_
case 5: house = new House6(); yvictim -= 26; yhouse -= 13; break;_x000D_
case 6: house = new House7(); yvictim -= 8; yhouse -= 4; break;_x000D_
case 7: house = new House8(); yvictim -= 10; yhouse -= 5; break;_x000D_
case 8: house = new House9(); yvictim -= 22; yhouse -= 11; break;_x000D_
case 9: house = new House10(); yvictim -= 22; yhouse -= 11; break;_x000D_
_x000D_
default:_x000D_
// Will never happen._x000D_
assert false;_x000D_
return;_x000D_
}_x000D_
addObject(house, x, yhouse);_x000D_
_x000D_
switch (randomvictim) {_x000D_
case 0: victim = new Victim1(); break;_x000D_
case 1: victim = new Victim2(); break;_x000D_
case 2: victim = new Victim3(); break;_x000D_
case 3: victim = new Victim4(); break;_x000D_
case 4: victim = new Victim5(); break;_x000D_
case 5: victim = new Victim6(); break;_x000D_
case 6: victim = new Victim7(); break;_x000D_
case 7: victim = new Victim8(); break;_x000D_
_x000D_
default:_x000D_
// Will never happen._x000D_
assert false;_x000D_
return;_x000D_
}_x000D_
addObject(victim, x, yvictim);_x000D_
_x000D_
//Uitroeptekens boven de slachtoffers worden geplaatst._x000D_
needshelp = new NeedsHelp();_x000D_
addObject(needshelp, x, yvictim-4);_x000D_
_x000D_
}_x000D_
_x000D_
//Alle start objecten worden geplaatst._x000D_
helicopter = new Helicopter();_x000D_
addObject(helicopter, 40, 10);_x000D_
_x000D_
direction = new Direction();_x000D_
addObject(direction, 20, 68);_x000D_
_x000D_
scoreCounter = new Counter("Score: ");_x000D_
addObject(scoreCounter, 6, 73);_x000D_
_x000D_
menuBar = new MenuBar();_x000D_
addObject(menuBar, 39, 75);_x000D_
_x000D_
wall = new Wall();_x000D_
addObject(wall, -35, 40);_x000D_
_x000D_
water = new HeliWater();_x000D_
addObject(water, 40, 70);_x000D_
_x000D_
hp = new HP();_x000D_
addObject(hp, 60, 64);_x000D_
_x000D_
health1 = new HeliHealth();_x000D_
addObject(health1, 60, 73);_x000D_
_x000D_
health2 = new HeliHealth();_x000D_
addObject(health2, 64, 73);_x000D_
_x000D_
health3 = new HeliHealth();_x000D_
addObject(health3, 68, 73);_x000D_
_x000D_
health4 = new Health2();_x000D_
addObject(health4, 60, 77);_x000D_
_x000D_
health5 = new Health2();_x000D_
addObject(health5, 64, 77);_x000D_
_x000D_
health6 = new Health2();_x000D_
addObject(health6, 68, 77);_x000D_
_x000D_
setPaintOrder(Counter.class, HP.class, Health2.class, HeliHealth.class, Helicopter.class, MenuBar.class, Wall.class, HeliWater.class, Victim.class, MenuBar.class, House.class, SpeedPowerUp.class, RadiusPowerUp.class, NeedsHelp.class);_x000D_
}_x000D_
_x000D_
@Override_x000D_
public void act() {_x000D_
//Check actors_x000D_
for (Actor actor : (List<Actor>)getObjects(null)) {_x000D_
if (actor == helicopter) continue;_x000D_
if (actor == scoreCounter) continue;_x000D_
_x000D_
actor.setLocation(actor.getX() + 40 - helicopter.getX(), actor.getY());_x000D_
}_x000D_
_x000D_
//PowerUp spawn_x000D_
if (Math.random() < 0.003) {_x000D_
Actor powerUp;_x000D_
switch (Greenfoot.getRandomNumber(2)) {_x000D_
case 0: powerUp = new SpeedPowerUp(); break;_x000D_
case 1: powerUp = new RadiusPowerUp(); break;_x000D_
default:_x000D_
// Will never happen._x000D_
assert false;_x000D_
return;_x000D_
}_x000D_
addObject(powerUp, -50 + Greenfoot.getRandomNumber(100), Greenfoot.getRandomNumber(40));_x000D_
}_x000D_
_x000D_
//Zorg ervoor dat bepaalde objecten een vaste plaats op het scherm hebben._x000D_
helicopter.setLocation(40, helicopter.getY());_x000D_
scoreCounter.setLocation(6, 73);_x000D_
menuBar.setLocation(39, 75);_x000D_
health1.setLocation(60, 73);_x000D_
health2.setLocation(64, 73);_x000D_
health3.setLocation(68, 73);_x000D_
health4.setLocation(60, 77);_x000D_
health5.setLocation(64, 77);_x000D_
health6.setLocation(68, 77);_x000D_
hp.setLocation(60,64);_x000D_
_x000D_
}_x000D_
_x000D_
//Return water level_x000D_
public int getWaterLevel() {_x000D_
return water.getLevel();_x000D_
}_x000D_
_x000D_
//Voegt score toe_x000D_
public void addScore(int x) {_x000D_
scoreCounter.add(x);_x000D_
}_x000D_
_x000D_
//Proces bij het verliezen van een leven bij helikopter_x000D_
public void lostLife() {_x000D_
healthlost ++;_x000D_
switch (healthlost) {_x000D_
case 1: removeObject(health1); break;_x000D_
case 2: removeObject(health2); break;_x000D_
case 3:_x000D_
removeObject(health3);_x000D_
gameOver();_x000D_
break;_x000D_
}_x000D_
}_x000D_
_x000D_
//Proces bij het verliezen van een leven bij ropeman_x000D_
public void lostLifeRope() {_x000D_
healthlostrope ++;_x000D_
switch (healthlostrope) {_x000D_
case 1: removeObject(health4); break;_x000D_
case 2: removeObject(health5); break;_x000D_
case 3:_x000D_
removeObject(health6);_x000D_
gameOver();_x000D_
break;_x000D_
}_x000D_
}_x000D_
_x000D_
//Laad gameover scherm_x000D_
private void gameOver() {_x000D_
Greenfoot.setWorld(new GameOverWorld(Game.HELICOPTER_GAME, scoreCounter.getValue()));_x000D_
}_x000D_
}_x000D_
| Project42/game2 | HelicopterWorld.java | 2,157 | // Willekeurige huizen en slachtoffers worden in het spel geplaatst._x000D_ | line_comment | nl | import greenfoot.*;_x000D_
import java.io.IOException;_x000D_
import java.util.List;_x000D_
import java.util.ArrayList;_x000D_
import javax.swing.*;_x000D_
_x000D_
public class HelicopterWorld extends World {_x000D_
private Helicopter helicopter;_x000D_
private Counter scoreCounter;_x000D_
private MenuBar menuBar;_x000D_
private Wall wall;_x000D_
private Direction direction;_x000D_
private HeliWater water;_x000D_
private HP hp;_x000D_
private HeliHealth health1;_x000D_
private HeliHealth health2;_x000D_
private HeliHealth health3;_x000D_
private Health2 health4;_x000D_
private Health2 health5;_x000D_
private Health2 health6;_x000D_
private int healthlost;_x000D_
private int healthlostrope;_x000D_
private Victim victim;_x000D_
private House house;_x000D_
private NeedsHelp needshelp;_x000D_
GreenfootSound backgroundMusic = new GreenfootSound("background_music.mp3");_x000D_
_x000D_
public HelicopterWorld() {_x000D_
super(80, 80, 10, false);_x000D_
setBackground("bg.png");_x000D_
backgroundMusic.playLoop();_x000D_
for (int i = 1; i < 100; ++i) {_x000D_
// Willekeurige huizen<SUF>
Victim victim;_x000D_
House house;_x000D_
int yvictim = 58;_x000D_
int yhouse = 65;_x000D_
int x = i * 50 + (-5 + Greenfoot.getRandomNumber(30));_x000D_
int randomhouse = (int)(Math.random() * ((9 - 0) + 1));_x000D_
int randomvictim = 0 + (int)(Math.random() * ((7 - 0) + 1));_x000D_
switch (randomhouse) {_x000D_
case 0: house = new House1(); break;_x000D_
case 1: house = new House2(); yvictim -= 4; yhouse -= 2; break;_x000D_
case 2: house = new House3(); yvictim -= 2; yhouse -= 1; break;_x000D_
case 3: house = new House4(); yvictim -= 37; yhouse -= 19; break;_x000D_
case 4: house = new House5(); yvictim -= 32; yhouse -= 16; break;_x000D_
case 5: house = new House6(); yvictim -= 26; yhouse -= 13; break;_x000D_
case 6: house = new House7(); yvictim -= 8; yhouse -= 4; break;_x000D_
case 7: house = new House8(); yvictim -= 10; yhouse -= 5; break;_x000D_
case 8: house = new House9(); yvictim -= 22; yhouse -= 11; break;_x000D_
case 9: house = new House10(); yvictim -= 22; yhouse -= 11; break;_x000D_
_x000D_
default:_x000D_
// Will never happen._x000D_
assert false;_x000D_
return;_x000D_
}_x000D_
addObject(house, x, yhouse);_x000D_
_x000D_
switch (randomvictim) {_x000D_
case 0: victim = new Victim1(); break;_x000D_
case 1: victim = new Victim2(); break;_x000D_
case 2: victim = new Victim3(); break;_x000D_
case 3: victim = new Victim4(); break;_x000D_
case 4: victim = new Victim5(); break;_x000D_
case 5: victim = new Victim6(); break;_x000D_
case 6: victim = new Victim7(); break;_x000D_
case 7: victim = new Victim8(); break;_x000D_
_x000D_
default:_x000D_
// Will never happen._x000D_
assert false;_x000D_
return;_x000D_
}_x000D_
addObject(victim, x, yvictim);_x000D_
_x000D_
//Uitroeptekens boven de slachtoffers worden geplaatst._x000D_
needshelp = new NeedsHelp();_x000D_
addObject(needshelp, x, yvictim-4);_x000D_
_x000D_
}_x000D_
_x000D_
//Alle start objecten worden geplaatst._x000D_
helicopter = new Helicopter();_x000D_
addObject(helicopter, 40, 10);_x000D_
_x000D_
direction = new Direction();_x000D_
addObject(direction, 20, 68);_x000D_
_x000D_
scoreCounter = new Counter("Score: ");_x000D_
addObject(scoreCounter, 6, 73);_x000D_
_x000D_
menuBar = new MenuBar();_x000D_
addObject(menuBar, 39, 75);_x000D_
_x000D_
wall = new Wall();_x000D_
addObject(wall, -35, 40);_x000D_
_x000D_
water = new HeliWater();_x000D_
addObject(water, 40, 70);_x000D_
_x000D_
hp = new HP();_x000D_
addObject(hp, 60, 64);_x000D_
_x000D_
health1 = new HeliHealth();_x000D_
addObject(health1, 60, 73);_x000D_
_x000D_
health2 = new HeliHealth();_x000D_
addObject(health2, 64, 73);_x000D_
_x000D_
health3 = new HeliHealth();_x000D_
addObject(health3, 68, 73);_x000D_
_x000D_
health4 = new Health2();_x000D_
addObject(health4, 60, 77);_x000D_
_x000D_
health5 = new Health2();_x000D_
addObject(health5, 64, 77);_x000D_
_x000D_
health6 = new Health2();_x000D_
addObject(health6, 68, 77);_x000D_
_x000D_
setPaintOrder(Counter.class, HP.class, Health2.class, HeliHealth.class, Helicopter.class, MenuBar.class, Wall.class, HeliWater.class, Victim.class, MenuBar.class, House.class, SpeedPowerUp.class, RadiusPowerUp.class, NeedsHelp.class);_x000D_
}_x000D_
_x000D_
@Override_x000D_
public void act() {_x000D_
//Check actors_x000D_
for (Actor actor : (List<Actor>)getObjects(null)) {_x000D_
if (actor == helicopter) continue;_x000D_
if (actor == scoreCounter) continue;_x000D_
_x000D_
actor.setLocation(actor.getX() + 40 - helicopter.getX(), actor.getY());_x000D_
}_x000D_
_x000D_
//PowerUp spawn_x000D_
if (Math.random() < 0.003) {_x000D_
Actor powerUp;_x000D_
switch (Greenfoot.getRandomNumber(2)) {_x000D_
case 0: powerUp = new SpeedPowerUp(); break;_x000D_
case 1: powerUp = new RadiusPowerUp(); break;_x000D_
default:_x000D_
// Will never happen._x000D_
assert false;_x000D_
return;_x000D_
}_x000D_
addObject(powerUp, -50 + Greenfoot.getRandomNumber(100), Greenfoot.getRandomNumber(40));_x000D_
}_x000D_
_x000D_
//Zorg ervoor dat bepaalde objecten een vaste plaats op het scherm hebben._x000D_
helicopter.setLocation(40, helicopter.getY());_x000D_
scoreCounter.setLocation(6, 73);_x000D_
menuBar.setLocation(39, 75);_x000D_
health1.setLocation(60, 73);_x000D_
health2.setLocation(64, 73);_x000D_
health3.setLocation(68, 73);_x000D_
health4.setLocation(60, 77);_x000D_
health5.setLocation(64, 77);_x000D_
health6.setLocation(68, 77);_x000D_
hp.setLocation(60,64);_x000D_
_x000D_
}_x000D_
_x000D_
//Return water level_x000D_
public int getWaterLevel() {_x000D_
return water.getLevel();_x000D_
}_x000D_
_x000D_
//Voegt score toe_x000D_
public void addScore(int x) {_x000D_
scoreCounter.add(x);_x000D_
}_x000D_
_x000D_
//Proces bij het verliezen van een leven bij helikopter_x000D_
public void lostLife() {_x000D_
healthlost ++;_x000D_
switch (healthlost) {_x000D_
case 1: removeObject(health1); break;_x000D_
case 2: removeObject(health2); break;_x000D_
case 3:_x000D_
removeObject(health3);_x000D_
gameOver();_x000D_
break;_x000D_
}_x000D_
}_x000D_
_x000D_
//Proces bij het verliezen van een leven bij ropeman_x000D_
public void lostLifeRope() {_x000D_
healthlostrope ++;_x000D_
switch (healthlostrope) {_x000D_
case 1: removeObject(health4); break;_x000D_
case 2: removeObject(health5); break;_x000D_
case 3:_x000D_
removeObject(health6);_x000D_
gameOver();_x000D_
break;_x000D_
}_x000D_
}_x000D_
_x000D_
//Laad gameover scherm_x000D_
private void gameOver() {_x000D_
Greenfoot.setWorld(new GameOverWorld(Game.HELICOPTER_GAME, scoreCounter.getValue()));_x000D_
}_x000D_
}_x000D_
| false | 3,131 | 29 | 3,259 | 28 | 3,352 | 23 | 3,259 | 28 | 3,600 | 28 | false | false | false | false | false | true |