index
int64
1
4.83k
file_id
stringlengths
5
9
content
stringlengths
167
16.5k
repo
stringlengths
7
82
path
stringlengths
8
164
token_length
int64
72
4.23k
original_comment
stringlengths
11
2.7k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
142
16.5k
Inclusion
stringclasses
4 values
file-tokens-Qwen/Qwen2-7B
int64
64
3.93k
comment-tokens-Qwen/Qwen2-7B
int64
4
972
file-tokens-bigcode/starcoder2-7b
int64
74
3.98k
comment-tokens-bigcode/starcoder2-7b
int64
4
959
file-tokens-google/codegemma-7b
int64
56
3.99k
comment-tokens-google/codegemma-7b
int64
3
953
file-tokens-ibm-granite/granite-8b-code-base
int64
74
3.98k
comment-tokens-ibm-granite/granite-8b-code-base
int64
4
959
file-tokens-meta-llama/CodeLlama-7b-hf
int64
77
4.12k
comment-tokens-meta-llama/CodeLlama-7b-hf
int64
4
1.11k
excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool
2 classes
excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool
2 classes
excluded-based-on-tokenizer-google/codegemma-7b
bool
2 classes
excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool
2 classes
excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool
2 classes
include-for-inference
bool
2 classes
3,681
91801_5
package nl.geozet.common;_x000D_ _x000D_ import java.io.FileNotFoundException;_x000D_ import java.io.IOException;_x000D_ import java.util.Collections;_x000D_ import java.util.List;_x000D_ import java.util.Properties;_x000D_ import java.util.Vector;_x000D_ _x000D_ import org.apache.log4j.Logger;_x000D_ _x000D_ /**_x000D_ * Deze klasse levert de thema's of categorieen voro de applicatie. Deze zijn_x000D_ * runtime configureerbaar middels de property file_x000D_ * {@code core-datacategorieen.properties} zie ook de js pendant_x000D_ * {@code Geozet.config.classificationInfo} in settings.js. De volgorde van de_x000D_ * elementen wordt bepaald door de volgorde in de property file._x000D_ * _x000D_ * @author [email protected]_x000D_ * @since 1.6_x000D_ */_x000D_ public final class DataCategorieen { /* implements Enumeration<String[]> */_x000D_ /** log4j logger. */_x000D_ private static final Logger LOGGER = Logger_x000D_ .getLogger(DataCategorieen.class);_x000D_ _x000D_ /** de itemList. */_x000D_ private static final List<String[]> ITEMLIST = new Vector<String[]>();_x000D_ _x000D_ /** de itemKeys. */_x000D_ private static final List<String> ITEMKEYS = new Vector<String>();_x000D_ _x000D_ /** het pad naar de property file, relatief tav de class resource. */_x000D_ private static final String INIT_FILE = "/core-datacategorieen.properties";_x000D_ _x000D_ static {_x000D_ /**_x000D_ * runtime applicatie properties uit de file_x000D_ * 'core-datacategorieen.properties' laden._x000D_ */_x000D_ final Properties props = new Properties();_x000D_ try {_x000D_ props.load(DataCategorieen.class.getResourceAsStream(INIT_FILE));_x000D_ } catch (final FileNotFoundException e) {_x000D_ LOGGER.fatal("Het initialisatie bestand (" + INIT_FILE_x000D_ + ") is niet gevonden.", e);_x000D_ throw new ExceptionInInitializerError(e);_x000D_ } catch (final IOException e) {_x000D_ LOGGER.fatal("I/O fout tijden inlezen initialisatie bestand ("_x000D_ + INIT_FILE + ").", e);_x000D_ throw new ExceptionInInitializerError(e);_x000D_ }_x000D_ // process properties content_x000D_ final String csvString = props.getProperty("categorieen");_x000D_ LOGGER.debug(csvString);_x000D_ final String[] result = csvString.split(";");_x000D_ for (final String element : result) {_x000D_ ITEMLIST.add(element.split(":"));_x000D_ ITEMKEYS.add(element.split(":")[0]);_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Instantiates a new data categorieen, Private constructor voor deze_x000D_ * utility klasse._x000D_ */_x000D_ private DataCategorieen() {_x000D_ /* Private constructor voor deze utility klasse. */_x000D_ }_x000D_ _x000D_ /**_x000D_ * Geeft de elementen in deze verzameling. Een element bestaat uit een_x000D_ * {@code String[3] [key,class,desc]}_x000D_ * _x000D_ * @return de {@code List<String[]>} met [sleutel,klasse,beschrijving]_x000D_ */_x000D_ public static List<String[]> elements() {_x000D_ return Collections.unmodifiableList((ITEMLIST));_x000D_ }_x000D_ _x000D_ /**_x000D_ * geeft de sleutels in deze verzameling._x000D_ * _x000D_ * @return de {@code List<String>} met sleutels_x000D_ */_x000D_ public static List<String> keys() {_x000D_ return Collections.unmodifiableList((ITEMKEYS));_x000D_ }_x000D_ _x000D_ /**_x000D_ * geeft de sleutels van deze verzameling in een array._x000D_ * _x000D_ * @return het {@code String[]} met sleutels_x000D_ */_x000D_ public static String[] keysAsArray() {_x000D_ return keys().toArray(new String[] {});_x000D_ }_x000D_ }_x000D_
mizanRahman/geozet
geozet-webapp/src/main/java/nl/geozet/common/DataCategorieen.java
997
/* Private constructor voor deze utility klasse. */
block_comment
nl
package nl.geozet.common;_x000D_ _x000D_ import java.io.FileNotFoundException;_x000D_ import java.io.IOException;_x000D_ import java.util.Collections;_x000D_ import java.util.List;_x000D_ import java.util.Properties;_x000D_ import java.util.Vector;_x000D_ _x000D_ import org.apache.log4j.Logger;_x000D_ _x000D_ /**_x000D_ * Deze klasse levert de thema's of categorieen voro de applicatie. Deze zijn_x000D_ * runtime configureerbaar middels de property file_x000D_ * {@code core-datacategorieen.properties} zie ook de js pendant_x000D_ * {@code Geozet.config.classificationInfo} in settings.js. De volgorde van de_x000D_ * elementen wordt bepaald door de volgorde in de property file._x000D_ * _x000D_ * @author [email protected]_x000D_ * @since 1.6_x000D_ */_x000D_ public final class DataCategorieen { /* implements Enumeration<String[]> */_x000D_ /** log4j logger. */_x000D_ private static final Logger LOGGER = Logger_x000D_ .getLogger(DataCategorieen.class);_x000D_ _x000D_ /** de itemList. */_x000D_ private static final List<String[]> ITEMLIST = new Vector<String[]>();_x000D_ _x000D_ /** de itemKeys. */_x000D_ private static final List<String> ITEMKEYS = new Vector<String>();_x000D_ _x000D_ /** het pad naar de property file, relatief tav de class resource. */_x000D_ private static final String INIT_FILE = "/core-datacategorieen.properties";_x000D_ _x000D_ static {_x000D_ /**_x000D_ * runtime applicatie properties uit de file_x000D_ * 'core-datacategorieen.properties' laden._x000D_ */_x000D_ final Properties props = new Properties();_x000D_ try {_x000D_ props.load(DataCategorieen.class.getResourceAsStream(INIT_FILE));_x000D_ } catch (final FileNotFoundException e) {_x000D_ LOGGER.fatal("Het initialisatie bestand (" + INIT_FILE_x000D_ + ") is niet gevonden.", e);_x000D_ throw new ExceptionInInitializerError(e);_x000D_ } catch (final IOException e) {_x000D_ LOGGER.fatal("I/O fout tijden inlezen initialisatie bestand ("_x000D_ + INIT_FILE + ").", e);_x000D_ throw new ExceptionInInitializerError(e);_x000D_ }_x000D_ // process properties content_x000D_ final String csvString = props.getProperty("categorieen");_x000D_ LOGGER.debug(csvString);_x000D_ final String[] result = csvString.split(";");_x000D_ for (final String element : result) {_x000D_ ITEMLIST.add(element.split(":"));_x000D_ ITEMKEYS.add(element.split(":")[0]);_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Instantiates a new data categorieen, Private constructor voor deze_x000D_ * utility klasse._x000D_ */_x000D_ private DataCategorieen() {_x000D_ /* Private constructor voor<SUF>*/_x000D_ }_x000D_ _x000D_ /**_x000D_ * Geeft de elementen in deze verzameling. Een element bestaat uit een_x000D_ * {@code String[3] [key,class,desc]}_x000D_ * _x000D_ * @return de {@code List<String[]>} met [sleutel,klasse,beschrijving]_x000D_ */_x000D_ public static List<String[]> elements() {_x000D_ return Collections.unmodifiableList((ITEMLIST));_x000D_ }_x000D_ _x000D_ /**_x000D_ * geeft de sleutels in deze verzameling._x000D_ * _x000D_ * @return de {@code List<String>} met sleutels_x000D_ */_x000D_ public static List<String> keys() {_x000D_ return Collections.unmodifiableList((ITEMKEYS));_x000D_ }_x000D_ _x000D_ /**_x000D_ * geeft de sleutels van deze verzameling in een array._x000D_ * _x000D_ * @return het {@code String[]} met sleutels_x000D_ */_x000D_ public static String[] keysAsArray() {_x000D_ return keys().toArray(new String[] {});_x000D_ }_x000D_ }_x000D_
False
1,369
10
1,495
10
1,511
9
1,495
10
1,631
10
false
false
false
false
false
true
3,565
18940_13
package SELMA; import java.util.*; import SELMA.SELMATree.SR_Type; import SELMA.SELMATree.SR_Kind; import SELMA.SELMATree.SR_Func; import SELMA.SELMAChecker; import org.antlr.runtime.RecognitionException; import org.antlr.runtime.tree.Tree; /** * Implementatie van een symbol table voor de compiler. */ public class SymbolTable<Entry extends IdEntry> { public int nextAddr = 1; public int funclevel = 0; // Set of global variables along with their type denoters that should become fields public Set<String> globals = new HashSet<String>(); private int currentLevel; private Map<String, Stack<Entry>> entries; int localCount; /** * * @return Address voor een locale variabele */ public int nextAddr(){ return nextAddr; } /** * Constructor. * @ensure this.currentLevel() == -1 */ public SymbolTable() { currentLevel = -1; entries = new HashMap<String, Stack<Entry>>(); } /** * Opens a new scope. * @ensure this.currentLevel() == old.currentLevel()+1 */ public void openScope() { currentLevel++; } /** * Closes the current scope. All identifiers in * the current scope will be removed from the SymbolTable. * @require old.currentLevel() > -1 * @ensure this.currentLevel() == old.currentLevel()-1 */ public void closeScope() { for (Map.Entry<String, Stack<Entry>> entry: entries.entrySet()){ Stack<Entry> stack = entry.getValue(); if ((stack != null) && (!stack.isEmpty()) && (stack.peek().level >= currentLevel)){ Entry e = stack.pop(); localCount = nextAddr > localCount ? nextAddr : localCount; if (isLocal(e)) nextAddr--; } } currentLevel--; } /** Returns the current scope level. */ public int currentLevel() { return currentLevel; } /** Return whether the entry takes up space on the stack */ private boolean isLocal(Entry entry) { return entry instanceof CheckerEntry && ((CheckerEntry) entry).kind != SR_Kind.CONST; } /** * Enters an id together with an entry into this SymbolTable using the * current scope level. The entry's level is set to currentLevel(). * @require String != null && String != "" && entry != null * @ensure this.retrieve(id).getLevel() == currentLevel() * @throws SymbolTableException when there is no valid current scope level, * or when the id is already declared on the current level. */ public void enter(Tree tree, Entry entry) throws SymbolTableException { String id = tree.getText(); if (currentLevel < 0) { throw new SymbolTableException(tree, "Not in a valid scope."); } Stack<Entry> s = entries.get(id); if (s == null) { s = new Stack<Entry>(); entries.put(id, s); } if (s.isEmpty() || s.peek().level != currentLevel) { entry.level = currentLevel; s.push(entry); if (isLocal(entry)) nextAddr++; } else { throw new SymbolTableException(tree, "Entry "+id+" already exists in current scope."); } if (entry instanceof CompilerEntry) { CompilerEntry e = (CompilerEntry) entry; e.isGlobal = funclevel == 0; if (e.isGlobal && e.kind == SR_Kind.VAR && e.func != SR_Func.YES) globals.add(e.getIdentifier(id) + " " + getTypeDenoter(e.type, false)); } } /** * Get the Entry corresponding with id whose level is the highest. * In other words, the method returns the Entry that is defined last. * @return Entry of this id on the highest level * null if this SymbolTable does not contain id */ public Entry retrieve(Tree tree) throws SymbolTableException { String id = tree.getText(); Stack<Entry> s = entries.get(id); if (s==null||s.isEmpty()) { throw new SymbolTableException(tree, "Entry not found: " + id); } return s.peek(); } public void addParamToFunc(Tree func, Tree param, Tree type) { SR_Type selmaType = ((SELMATree) type).getSelmaType(); CheckerEntry function = (CheckerEntry) retrieve(func); function.addParam(param, selmaType); CompilerEntry paramentry = new CompilerEntry(selmaType, SR_Kind.VAR, nextAddr); paramentry.initialized = true; enter(param, (Entry) paramentry); } public String toString(){ String s = ""; for (Map.Entry<String, Stack<Entry>> entry: entries.entrySet()){ Stack<Entry> stack = entry.getValue(); s += String.format("Id=%-10s : %s=%s\n", entry.getKey(), stack, stack.peek().getClass()); //s+=entry.getKey(); //s+=stack.toString(); } return s; } /* Get the locals limit for this stack frame */ public int getLocalsCount() { return nextAddr > localCount ? nextAddr : localCount; } /** * Return the JVM type denoter of the Symbol Table SR_Type * @param type the type to get the denoter for * @param printing whether the denoter is used to format * values using the print() statement * @return The type denoter (String) */ public String getTypeDenoter(SR_Type type, boolean printing) { if (type == SR_Type.INT) { return "I"; } else if (type == SR_Type.BOOL) { if (printing) return "Ljava/lang/String;"; else return "I"; } else if (type == SR_Type.VOID) { return "V"; } else if (type == SR_Type.CHAR) { return "C"; } else { throw new RuntimeException(":( Invalid type: " + type); } } /** * Enter een functie scope. Houdt bij of we in een functie zitten of niet, zodat we weten of variabelen globaal zijn of niet. */ public void enterFuncScope() { openScope(); funclevel++; } /** * Verlaat een functie scope. Houdt bij of we in een functie zitten of niet, zodat we weten of variabelen globaal zijn of niet. */ public void leaveFuncScope() { closeScope(); funclevel--; } } /** Exception class to signal problems with the SymbolTable */ class SymbolTableException extends RuntimeException { //RecognitionException { public static final long serialVersionUID = 24362462L; // for Serializable private String msg; public SymbolTableException(Tree tree, String msg) { super(); this.msg = tree.getText() + " (" + tree.getLine() + ":" + tree.getCharPositionInLine() + ") " + msg; } public String getMessage() { return msg; } }
markflorisson/selma
src/SELMA/SymbolTable.java
2,003
/** * Verlaat een functie scope. Houdt bij of we in een functie zitten of niet, zodat we weten of variabelen globaal zijn of niet. */
block_comment
nl
package SELMA; import java.util.*; import SELMA.SELMATree.SR_Type; import SELMA.SELMATree.SR_Kind; import SELMA.SELMATree.SR_Func; import SELMA.SELMAChecker; import org.antlr.runtime.RecognitionException; import org.antlr.runtime.tree.Tree; /** * Implementatie van een symbol table voor de compiler. */ public class SymbolTable<Entry extends IdEntry> { public int nextAddr = 1; public int funclevel = 0; // Set of global variables along with their type denoters that should become fields public Set<String> globals = new HashSet<String>(); private int currentLevel; private Map<String, Stack<Entry>> entries; int localCount; /** * * @return Address voor een locale variabele */ public int nextAddr(){ return nextAddr; } /** * Constructor. * @ensure this.currentLevel() == -1 */ public SymbolTable() { currentLevel = -1; entries = new HashMap<String, Stack<Entry>>(); } /** * Opens a new scope. * @ensure this.currentLevel() == old.currentLevel()+1 */ public void openScope() { currentLevel++; } /** * Closes the current scope. All identifiers in * the current scope will be removed from the SymbolTable. * @require old.currentLevel() > -1 * @ensure this.currentLevel() == old.currentLevel()-1 */ public void closeScope() { for (Map.Entry<String, Stack<Entry>> entry: entries.entrySet()){ Stack<Entry> stack = entry.getValue(); if ((stack != null) && (!stack.isEmpty()) && (stack.peek().level >= currentLevel)){ Entry e = stack.pop(); localCount = nextAddr > localCount ? nextAddr : localCount; if (isLocal(e)) nextAddr--; } } currentLevel--; } /** Returns the current scope level. */ public int currentLevel() { return currentLevel; } /** Return whether the entry takes up space on the stack */ private boolean isLocal(Entry entry) { return entry instanceof CheckerEntry && ((CheckerEntry) entry).kind != SR_Kind.CONST; } /** * Enters an id together with an entry into this SymbolTable using the * current scope level. The entry's level is set to currentLevel(). * @require String != null && String != "" && entry != null * @ensure this.retrieve(id).getLevel() == currentLevel() * @throws SymbolTableException when there is no valid current scope level, * or when the id is already declared on the current level. */ public void enter(Tree tree, Entry entry) throws SymbolTableException { String id = tree.getText(); if (currentLevel < 0) { throw new SymbolTableException(tree, "Not in a valid scope."); } Stack<Entry> s = entries.get(id); if (s == null) { s = new Stack<Entry>(); entries.put(id, s); } if (s.isEmpty() || s.peek().level != currentLevel) { entry.level = currentLevel; s.push(entry); if (isLocal(entry)) nextAddr++; } else { throw new SymbolTableException(tree, "Entry "+id+" already exists in current scope."); } if (entry instanceof CompilerEntry) { CompilerEntry e = (CompilerEntry) entry; e.isGlobal = funclevel == 0; if (e.isGlobal && e.kind == SR_Kind.VAR && e.func != SR_Func.YES) globals.add(e.getIdentifier(id) + " " + getTypeDenoter(e.type, false)); } } /** * Get the Entry corresponding with id whose level is the highest. * In other words, the method returns the Entry that is defined last. * @return Entry of this id on the highest level * null if this SymbolTable does not contain id */ public Entry retrieve(Tree tree) throws SymbolTableException { String id = tree.getText(); Stack<Entry> s = entries.get(id); if (s==null||s.isEmpty()) { throw new SymbolTableException(tree, "Entry not found: " + id); } return s.peek(); } public void addParamToFunc(Tree func, Tree param, Tree type) { SR_Type selmaType = ((SELMATree) type).getSelmaType(); CheckerEntry function = (CheckerEntry) retrieve(func); function.addParam(param, selmaType); CompilerEntry paramentry = new CompilerEntry(selmaType, SR_Kind.VAR, nextAddr); paramentry.initialized = true; enter(param, (Entry) paramentry); } public String toString(){ String s = ""; for (Map.Entry<String, Stack<Entry>> entry: entries.entrySet()){ Stack<Entry> stack = entry.getValue(); s += String.format("Id=%-10s : %s=%s\n", entry.getKey(), stack, stack.peek().getClass()); //s+=entry.getKey(); //s+=stack.toString(); } return s; } /* Get the locals limit for this stack frame */ public int getLocalsCount() { return nextAddr > localCount ? nextAddr : localCount; } /** * Return the JVM type denoter of the Symbol Table SR_Type * @param type the type to get the denoter for * @param printing whether the denoter is used to format * values using the print() statement * @return The type denoter (String) */ public String getTypeDenoter(SR_Type type, boolean printing) { if (type == SR_Type.INT) { return "I"; } else if (type == SR_Type.BOOL) { if (printing) return "Ljava/lang/String;"; else return "I"; } else if (type == SR_Type.VOID) { return "V"; } else if (type == SR_Type.CHAR) { return "C"; } else { throw new RuntimeException(":( Invalid type: " + type); } } /** * Enter een functie scope. Houdt bij of we in een functie zitten of niet, zodat we weten of variabelen globaal zijn of niet. */ public void enterFuncScope() { openScope(); funclevel++; } /** * Verlaat een functie<SUF>*/ public void leaveFuncScope() { closeScope(); funclevel--; } } /** Exception class to signal problems with the SymbolTable */ class SymbolTableException extends RuntimeException { //RecognitionException { public static final long serialVersionUID = 24362462L; // for Serializable private String msg; public SymbolTableException(Tree tree, String msg) { super(); this.msg = tree.getText() + " (" + tree.getLine() + ":" + tree.getCharPositionInLine() + ") " + msg; } public String getMessage() { return msg; } }
True
1,608
44
1,749
47
1,892
38
1,749
47
2,030
48
false
false
false
false
false
true
3,939
105965_2
package de.dhbwka.java.exercise.classes.swapgame; import java.awt.Color; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; /** * Spielfeld */ public class Spielfeld { // #region private members private final int SIZE = 9; private final int COLOR_COUNT = 7; @SuppressWarnings("unused") private Color[] colors = generateColors(COLOR_COUNT); private Integer[][] matchfield = new Integer[SIZE][SIZE]; // [Spalte][Zeile] private int points; private PropertyChangeSupport pointsChange = new PropertyChangeSupport(points); private PropertyChangeSupport matchfieldChanged = new PropertyChangeSupport(matchfield); // #endregion private members // #region constructors public Spielfeld() { Random r = new Random(); for (Integer[] col : matchfield) for (int i = 0; i < SIZE; i++) col[i] = r.nextInt(COLOR_COUNT); calcPoints(); } // #endregion constructors // #region private methods /** * Generiert {@code i} unterschiedliche Farben * * @param i Anzahl der zu generierenden Farben * @return Liste an Farben */ private Color[] generateColors(int i) { Color[] colors = new Color[i]; int offSet = Integer.parseInt("FFFFFF", 16) / i; for (int c = 0; c < i; c++) colors[c] = new Color(offSet * (c + 1)); return colors; } /** * Berechnet, fuer die aktuelle Spielsituation erzielbare Punkte. Wenn ja, * werden die Felder aufgeloest. Felder rutschen nach / werden neu generiert und * es werden dadurch neue moegliche Punkte berechnet. * * @return insgesamt erzielte Punkte */ private int calcPoints() { Position[] pos = getPointFields(); if (pos.length > 0) { // Zerstörte Felder auf null setzen for (Position p : pos) setFieldValue(p, null); Integer[][] oldMatchfield = this.matchfield; // null Felder nach vorne sortieren for (Integer[] col : matchfield) { java.util.Arrays.sort(col, (a, b) -> (a == null ? -1 : 1) - (b == null ? -1 : 1)); // null Felder neu befüllen Random r = new Random(); for (int i = 0; i < SIZE; i++) { if (col[i] != null) break; col[i] = r.nextInt(COLOR_COUNT); } } matchfieldChanged.firePropertyChange("matchfield", oldMatchfield, this.matchfield); return (10 * pos.length) + calcPoints(); } return 0; } /** * Liste von Feldern, durch welche Punkte erzielt werden. mehrfache Aufführugen * sind möglich, wenn das Feld sowohl Senkrecht als auch Wagerecht Punkte erzielt. * * @return Liste mit Felder, fuer die Punkte vergeben werden */ private Position[] getPointFields() { List<Position> positions = new ArrayList<Position>(); for (int c = 0; c < SIZE; c++) { for (int r = 0; r < SIZE; r++) { positions = searchBlocks(c, r, positions); } // letzter Block, incl. beginnendem [null] entfernen, wenn kein vollständiger // Block int lastBlockSize = positions.size() - positions.lastIndexOf(null); lastBlockSize = lastBlockSize < 0 || lastBlockSize > positions.size() ? positions.size() : lastBlockSize; if (lastBlockSize < 4) positions = positions.subList(0, positions.size() - lastBlockSize); positions.add(null); } for (int r = 0; r < SIZE; r++) { for (int c = 0; c < SIZE; c++) { positions = searchBlocks(c, r, positions); } // letzter Block, incl. beginnendem [null] entfernen, wenn kein vollständiger // Block int lastBlockSize = positions.size() - positions.lastIndexOf(null); lastBlockSize = lastBlockSize < 0 || lastBlockSize > positions.size() ? positions.size() : lastBlockSize; if (lastBlockSize < 4) positions = positions.subList(0, positions.size() - lastBlockSize); positions.add(null); } positions.removeAll(Collections.singleton(null)); return positions.toArray(new Position[positions.size()]); } /** * Vergleicht eine Position auf dem Spielfeld mit den vorherigen. Speichert den * Block ggfs. als Wertbar ab, wenn es min. 3 gleiche Felder in Folge sind. Die * Felder muessen in der Liste mit {@code null} separiert werden. * * @param c aktuelle Spalte * @param r aktuelle Zeile * @param positions Positionsliste, mit bereits erkannten Blöcken * @return neue Positionsliste, da es Probleme mit der Referenz-Liste bei * neuinitialisierung in der Methode gibt. */ private List<Position> searchBlocks(int c, int r, List<Position> positions) { // Wenn dieses Feld das erste ist, oder das vorherige gleich / null ist, kann es // hinzugefügt werden if (positions.size() == 0 || positions.get(positions.size() - 1) == null || getFieldValue(positions.get(positions.size() - 1)) == getFieldValue(c, r)) { positions.add(new Position(c, r)); } else { // wenn min. 3 vorgänger gleich sind, kann null eingefügt werden, um den Block // abzuschließen und mit diesem Feld einen neuen zu beginnen. // ansonsten werden die Vorgänger bis zum Ende des letzten Blocks (null) // gelöscht. if (positions.size() < 3) { positions = new ArrayList<Position>(); positions.add(null); } else { // min 3 gleiche: null einfügen; Integer curVal = getFieldValue(positions.get(positions.size() - 1)); if (curVal == getFieldValue(positions.get(positions.size() - 2)) && curVal == getFieldValue(positions.get(positions.size() - 3))) positions.add(null); else positions = positions.subList(0, positions.lastIndexOf(null) + 1); } // dieses Feld hinzufügen positions.add(new Position(c, r)); } return positions; } private Integer getFieldValue(Position p) { return p == null ? null : getFieldValue(p.getColArrayIndex(), p.getRowArrayIndex()); } private Integer getFieldValue(int col, int row) { return matchfield[col][row]; } private void setFieldValue(Position p, Integer value) { if(p == null) return; setFieldValue(p.getColArrayIndex(), p.getRowArrayIndex(), value); } private void setFieldValue(int col, int row, Integer value) { matchfield[col][row] = value; } private void increasePoints(int points) { if (points != 0) pointsChange.firePropertyChange("points", this.points, this.points += points); } // #endregion private methods // #region public methods /** * Tauscht zwei Felder auf dem Spielfeld, falls dadurch Punkte erzielt werden * koennen. * * @param pos1 Zeilennummer & Spalte des ersten Feldes * @param pos2 Zeilennummer & Spalte des zweiten Feldes * @return durch diesen Spielzug verdiente Punkte. 0 für einen ungueltigen * Spielzug. */ public int swap(Position pos1, Position pos2) { // Nur tauschen, wenn die Felder nebeneinander liegen if (Math.abs(pos1.getColArrayIndex() - pos2.getColArrayIndex()) + Math.abs(pos1.getRowArrayIndex() - pos2.getRowArrayIndex()) != 1) return 0; Integer cell1 = getFieldValue(pos1); Integer cell2 = getFieldValue(pos2); setFieldValue(pos1, cell2); setFieldValue(pos2, cell1); int points = calcPoints(); if (points == 0) { setFieldValue(pos1, cell1); setFieldValue(pos2, cell2); } else { increasePoints(points); } return points; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(" "); for (int i = 0; i < SIZE; i++) sb.append(new Position(i, i).getCol() + " "); sb.append("\r\n"); sb.append(" __________________\r\n"); for (int i = 0; i < SIZE; i++) { sb.append((i + 1) + "| "); for (int j = 0; j < SIZE; j++) { sb.append(matchfield[j][i] + " "); } sb.append("\r\n"); } sb.append("Punkte: [" + points + "]"); return sb.toString(); } public void addPointsChangeListener(PropertyChangeListener listener) { pointsChange.addPropertyChangeListener(listener); } public void removePointsChangeListener(PropertyChangeListener listener) { pointsChange.removePropertyChangeListener(listener); } public void addMatchfieldChangeListener(PropertyChangeListener listener) { matchfieldChanged.addPropertyChangeListener(listener); } public void removeMatchfieldChangeListener(PropertyChangeListener listener) { matchfieldChanged.removePropertyChangeListener(listener); } // #endregion public methods }
pa-ssch/study-java-exercises
src/de/dhbwka/java/exercise/classes/swapgame/Spielfeld.java
2,749
// #region private methods
line_comment
nl
package de.dhbwka.java.exercise.classes.swapgame; import java.awt.Color; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; /** * Spielfeld */ public class Spielfeld { // #region private members private final int SIZE = 9; private final int COLOR_COUNT = 7; @SuppressWarnings("unused") private Color[] colors = generateColors(COLOR_COUNT); private Integer[][] matchfield = new Integer[SIZE][SIZE]; // [Spalte][Zeile] private int points; private PropertyChangeSupport pointsChange = new PropertyChangeSupport(points); private PropertyChangeSupport matchfieldChanged = new PropertyChangeSupport(matchfield); // #endregion private members // #region constructors public Spielfeld() { Random r = new Random(); for (Integer[] col : matchfield) for (int i = 0; i < SIZE; i++) col[i] = r.nextInt(COLOR_COUNT); calcPoints(); } // #endregion constructors // #region private<SUF> /** * Generiert {@code i} unterschiedliche Farben * * @param i Anzahl der zu generierenden Farben * @return Liste an Farben */ private Color[] generateColors(int i) { Color[] colors = new Color[i]; int offSet = Integer.parseInt("FFFFFF", 16) / i; for (int c = 0; c < i; c++) colors[c] = new Color(offSet * (c + 1)); return colors; } /** * Berechnet, fuer die aktuelle Spielsituation erzielbare Punkte. Wenn ja, * werden die Felder aufgeloest. Felder rutschen nach / werden neu generiert und * es werden dadurch neue moegliche Punkte berechnet. * * @return insgesamt erzielte Punkte */ private int calcPoints() { Position[] pos = getPointFields(); if (pos.length > 0) { // Zerstörte Felder auf null setzen for (Position p : pos) setFieldValue(p, null); Integer[][] oldMatchfield = this.matchfield; // null Felder nach vorne sortieren for (Integer[] col : matchfield) { java.util.Arrays.sort(col, (a, b) -> (a == null ? -1 : 1) - (b == null ? -1 : 1)); // null Felder neu befüllen Random r = new Random(); for (int i = 0; i < SIZE; i++) { if (col[i] != null) break; col[i] = r.nextInt(COLOR_COUNT); } } matchfieldChanged.firePropertyChange("matchfield", oldMatchfield, this.matchfield); return (10 * pos.length) + calcPoints(); } return 0; } /** * Liste von Feldern, durch welche Punkte erzielt werden. mehrfache Aufführugen * sind möglich, wenn das Feld sowohl Senkrecht als auch Wagerecht Punkte erzielt. * * @return Liste mit Felder, fuer die Punkte vergeben werden */ private Position[] getPointFields() { List<Position> positions = new ArrayList<Position>(); for (int c = 0; c < SIZE; c++) { for (int r = 0; r < SIZE; r++) { positions = searchBlocks(c, r, positions); } // letzter Block, incl. beginnendem [null] entfernen, wenn kein vollständiger // Block int lastBlockSize = positions.size() - positions.lastIndexOf(null); lastBlockSize = lastBlockSize < 0 || lastBlockSize > positions.size() ? positions.size() : lastBlockSize; if (lastBlockSize < 4) positions = positions.subList(0, positions.size() - lastBlockSize); positions.add(null); } for (int r = 0; r < SIZE; r++) { for (int c = 0; c < SIZE; c++) { positions = searchBlocks(c, r, positions); } // letzter Block, incl. beginnendem [null] entfernen, wenn kein vollständiger // Block int lastBlockSize = positions.size() - positions.lastIndexOf(null); lastBlockSize = lastBlockSize < 0 || lastBlockSize > positions.size() ? positions.size() : lastBlockSize; if (lastBlockSize < 4) positions = positions.subList(0, positions.size() - lastBlockSize); positions.add(null); } positions.removeAll(Collections.singleton(null)); return positions.toArray(new Position[positions.size()]); } /** * Vergleicht eine Position auf dem Spielfeld mit den vorherigen. Speichert den * Block ggfs. als Wertbar ab, wenn es min. 3 gleiche Felder in Folge sind. Die * Felder muessen in der Liste mit {@code null} separiert werden. * * @param c aktuelle Spalte * @param r aktuelle Zeile * @param positions Positionsliste, mit bereits erkannten Blöcken * @return neue Positionsliste, da es Probleme mit der Referenz-Liste bei * neuinitialisierung in der Methode gibt. */ private List<Position> searchBlocks(int c, int r, List<Position> positions) { // Wenn dieses Feld das erste ist, oder das vorherige gleich / null ist, kann es // hinzugefügt werden if (positions.size() == 0 || positions.get(positions.size() - 1) == null || getFieldValue(positions.get(positions.size() - 1)) == getFieldValue(c, r)) { positions.add(new Position(c, r)); } else { // wenn min. 3 vorgänger gleich sind, kann null eingefügt werden, um den Block // abzuschließen und mit diesem Feld einen neuen zu beginnen. // ansonsten werden die Vorgänger bis zum Ende des letzten Blocks (null) // gelöscht. if (positions.size() < 3) { positions = new ArrayList<Position>(); positions.add(null); } else { // min 3 gleiche: null einfügen; Integer curVal = getFieldValue(positions.get(positions.size() - 1)); if (curVal == getFieldValue(positions.get(positions.size() - 2)) && curVal == getFieldValue(positions.get(positions.size() - 3))) positions.add(null); else positions = positions.subList(0, positions.lastIndexOf(null) + 1); } // dieses Feld hinzufügen positions.add(new Position(c, r)); } return positions; } private Integer getFieldValue(Position p) { return p == null ? null : getFieldValue(p.getColArrayIndex(), p.getRowArrayIndex()); } private Integer getFieldValue(int col, int row) { return matchfield[col][row]; } private void setFieldValue(Position p, Integer value) { if(p == null) return; setFieldValue(p.getColArrayIndex(), p.getRowArrayIndex(), value); } private void setFieldValue(int col, int row, Integer value) { matchfield[col][row] = value; } private void increasePoints(int points) { if (points != 0) pointsChange.firePropertyChange("points", this.points, this.points += points); } // #endregion private methods // #region public methods /** * Tauscht zwei Felder auf dem Spielfeld, falls dadurch Punkte erzielt werden * koennen. * * @param pos1 Zeilennummer & Spalte des ersten Feldes * @param pos2 Zeilennummer & Spalte des zweiten Feldes * @return durch diesen Spielzug verdiente Punkte. 0 für einen ungueltigen * Spielzug. */ public int swap(Position pos1, Position pos2) { // Nur tauschen, wenn die Felder nebeneinander liegen if (Math.abs(pos1.getColArrayIndex() - pos2.getColArrayIndex()) + Math.abs(pos1.getRowArrayIndex() - pos2.getRowArrayIndex()) != 1) return 0; Integer cell1 = getFieldValue(pos1); Integer cell2 = getFieldValue(pos2); setFieldValue(pos1, cell2); setFieldValue(pos2, cell1); int points = calcPoints(); if (points == 0) { setFieldValue(pos1, cell1); setFieldValue(pos2, cell2); } else { increasePoints(points); } return points; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(" "); for (int i = 0; i < SIZE; i++) sb.append(new Position(i, i).getCol() + " "); sb.append("\r\n"); sb.append(" __________________\r\n"); for (int i = 0; i < SIZE; i++) { sb.append((i + 1) + "| "); for (int j = 0; j < SIZE; j++) { sb.append(matchfield[j][i] + " "); } sb.append("\r\n"); } sb.append("Punkte: [" + points + "]"); return sb.toString(); } public void addPointsChangeListener(PropertyChangeListener listener) { pointsChange.addPropertyChangeListener(listener); } public void removePointsChangeListener(PropertyChangeListener listener) { pointsChange.removePropertyChangeListener(listener); } public void addMatchfieldChangeListener(PropertyChangeListener listener) { matchfieldChanged.addPropertyChangeListener(listener); } public void removeMatchfieldChangeListener(PropertyChangeListener listener) { matchfieldChanged.removePropertyChangeListener(listener); } // #endregion public methods }
False
2,220
5
2,452
5
2,475
5
2,452
5
2,747
5
false
false
false
false
false
true
4,782
99635_10
package com.example.AppArt.thaliapp.Calendar.Backend; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; import com.example.AppArt.thaliapp.R; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; /** * Withholds all knowledge of a ThaliaEvent * * @author Frank Gerlings (s4384873), Lisa Kalse (s4338340), Serena Rietbergen (s4182804) */ public class ThaliaEvent implements Comparable<ThaliaEvent>, Parcelable { private final GregorianCalendar startDate = new GregorianCalendar(); private final GregorianCalendar endDate = new GregorianCalendar(); private final String location; private final String description; private final String summary; private final EventCategory category; private final int catIcon; /** * Initialises the Event object given string input. * * @param startDate The starting time of the event in millis * @param endDate The ending time of the event in millis * @param location The location of the event * @param description A large description of the event * @param summary The event in 3 words or fewer */ public ThaliaEvent(Long startDate, Long endDate, String location, String description, String summary) { this.startDate.setTimeInMillis(startDate); this.endDate.setTimeInMillis(endDate); this.location = location; this.description = description; this.summary = summary; this.category = categoryFinder(); this.catIcon = catIconFinder(category); } /***************************************************************** Methods to help initialise *****************************************************************/ /** * Uses the summary and the description of an ThaliaEvent to figure out what * category it is. * * When multiple keywords are found it will use the following order: * LECTURE > PARTY > ALV > WORKSHOP > BORREL > DEFAULT * (e.g. kinderFEESTjesBORREL -> PARTY) * * @return an EventCategory */ private EventCategory categoryFinder() { String eventText = this.summary.concat(this.description); if (eventText.matches("(?i:.*lezing.*)")) { return EventCategory.LECTURE; } else if (eventText.matches("(?i:.*feest.*)") || eventText.matches("(?i:.*party.*)")) { return EventCategory.PARTY; } else if (eventText.matches("(?i:.*alv.*)")){ return EventCategory.ALV; } else if (eventText.matches("(?i:.*workshop.*)")) { return EventCategory.WORKSHOP; } else if (eventText.matches("(?i:.*borrel.*)")) { return EventCategory.BORREL; } else return EventCategory.DEFAULT; } /** * Returns the right drawable according to the category * * @param cat the category of this event * @return A .png file that represents the category of this event */ private int catIconFinder(EventCategory cat) { int catIcon; switch (cat) { case ALV: catIcon = R.drawable.alvicoon; break; case BORREL: catIcon = R.drawable.borrelicoon; break; case LECTURE: catIcon = R.drawable.lezingicoon; break; case PARTY: catIcon = R.drawable.feesticoon; break; case WORKSHOP: catIcon = R.drawable.workshopicoon; break; default: catIcon = R.drawable.overigicoon; } return catIcon; } /***************************************************************** Getters for all attributes *****************************************************************/ public GregorianCalendar getStartDate() { return startDate; } public GregorianCalendar getEndDate() { return endDate; } public String getLocation() { return location; } /** * A possibly broad description of the ThaliaEvent * Can contain HTML * @return possibly very large string */ public String getDescription() { return description; } /** * The ThaliaEvent in less than 5 words * Can contain HTML * @return small String */ public String getSummary() { return summary; } public EventCategory getCategory() { return category; } public int getCatIcon() { return catIcon; } /** * Small composition of ThaliaEvent information * @return summary + "\n" + duration() + "\n" + location */ public String makeSynopsis() { return summary + "\n" + duration() + "\n" + location; } /** * A readable abbreviation of the day * e.g. di 18 aug * * @return dd - dd - mmm */ public String getDateString() { StringBuilder date; date = new StringBuilder(""); date.append(this.startDate.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault())); date.append(" "); date.append(this.startDate.get(Calendar.DAY_OF_MONTH)); date.append(" "); date.append(this.startDate.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault())); return date.toString(); } /***************************************************************** Default Methods *****************************************************************/ /** * A neat stringformat of the beginning and ending times * * @return hh:mm-hh:mm */ public String duration() { StringBuilder sb = new StringBuilder(); sb.append(startDate.get(Calendar.HOUR_OF_DAY)); sb.append(":"); if (startDate.get(Calendar.MINUTE) == 0) { sb.append("00"); } else { sb.append(startDate.get(Calendar.MINUTE)); } sb.append(" - "); sb.append(endDate.get(Calendar.HOUR_OF_DAY)); sb.append(":"); if (endDate.get(Calendar.MINUTE) == 0) { sb.append("00"); } else { sb.append(endDate.get(Calendar.MINUTE)); } System.out.println("EoF durationfunction: "+sb.toString()); return sb.toString(); } /** * Printmethod, useful when you're debugging * * @return a string of the event */ @Override public String toString() { return ("\nstart = " + startDate + ", end = " + endDate + "\nlocation = " + location + "\ndescription = " + description + "\nsummary = " + summary); } /** * @param another the ThaliaEvent with which you want to compare it * @return The difference in time between the two */ @Override public int compareTo(@NonNull ThaliaEvent another) { return startDate.compareTo(another.startDate); } /***************************************************************** Making it a Parcelable, so it can be passed through with an intent *****************************************************************/ @Override public int describeContents() { return 0; } /** * Pretty much all information about this ThaliaEvent object is being * compressed into a Parcel * * @param dest Destination * @param flags Flags */ @Override public void writeToParcel(Parcel dest, int flags) { dest.writeLong(startDate.getTimeInMillis()); dest.writeLong(endDate.getTimeInMillis()); dest.writeString(location); dest.writeString(description); dest.writeString(summary); } /** * Reconstructs the ThaliaEvent through a parcel. */ public static final Parcelable.Creator<ThaliaEvent> CREATOR = new Parcelable.Creator<ThaliaEvent>() { // Parcels work FIFO public ThaliaEvent createFromParcel(Parcel parcel) { Long startDate = parcel.readLong(); Long endDate = parcel.readLong(); String location = parcel.readString(); String description = parcel.readString(); String summary = parcel.readString(); return new ThaliaEvent(startDate, endDate, location, description, summary); } public ThaliaEvent[] newArray(int size) { return new ThaliaEvent[size]; } }; }
yorickvP/ThaliAppMap
app/src/main/java/com/example/AppArt/thaliapp/Calendar/Backend/ThaliaEvent.java
2,340
/***************************************************************** Default Methods *****************************************************************/
block_comment
nl
package com.example.AppArt.thaliapp.Calendar.Backend; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; import com.example.AppArt.thaliapp.R; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; /** * Withholds all knowledge of a ThaliaEvent * * @author Frank Gerlings (s4384873), Lisa Kalse (s4338340), Serena Rietbergen (s4182804) */ public class ThaliaEvent implements Comparable<ThaliaEvent>, Parcelable { private final GregorianCalendar startDate = new GregorianCalendar(); private final GregorianCalendar endDate = new GregorianCalendar(); private final String location; private final String description; private final String summary; private final EventCategory category; private final int catIcon; /** * Initialises the Event object given string input. * * @param startDate The starting time of the event in millis * @param endDate The ending time of the event in millis * @param location The location of the event * @param description A large description of the event * @param summary The event in 3 words or fewer */ public ThaliaEvent(Long startDate, Long endDate, String location, String description, String summary) { this.startDate.setTimeInMillis(startDate); this.endDate.setTimeInMillis(endDate); this.location = location; this.description = description; this.summary = summary; this.category = categoryFinder(); this.catIcon = catIconFinder(category); } /***************************************************************** Methods to help initialise *****************************************************************/ /** * Uses the summary and the description of an ThaliaEvent to figure out what * category it is. * * When multiple keywords are found it will use the following order: * LECTURE > PARTY > ALV > WORKSHOP > BORREL > DEFAULT * (e.g. kinderFEESTjesBORREL -> PARTY) * * @return an EventCategory */ private EventCategory categoryFinder() { String eventText = this.summary.concat(this.description); if (eventText.matches("(?i:.*lezing.*)")) { return EventCategory.LECTURE; } else if (eventText.matches("(?i:.*feest.*)") || eventText.matches("(?i:.*party.*)")) { return EventCategory.PARTY; } else if (eventText.matches("(?i:.*alv.*)")){ return EventCategory.ALV; } else if (eventText.matches("(?i:.*workshop.*)")) { return EventCategory.WORKSHOP; } else if (eventText.matches("(?i:.*borrel.*)")) { return EventCategory.BORREL; } else return EventCategory.DEFAULT; } /** * Returns the right drawable according to the category * * @param cat the category of this event * @return A .png file that represents the category of this event */ private int catIconFinder(EventCategory cat) { int catIcon; switch (cat) { case ALV: catIcon = R.drawable.alvicoon; break; case BORREL: catIcon = R.drawable.borrelicoon; break; case LECTURE: catIcon = R.drawable.lezingicoon; break; case PARTY: catIcon = R.drawable.feesticoon; break; case WORKSHOP: catIcon = R.drawable.workshopicoon; break; default: catIcon = R.drawable.overigicoon; } return catIcon; } /***************************************************************** Getters for all attributes *****************************************************************/ public GregorianCalendar getStartDate() { return startDate; } public GregorianCalendar getEndDate() { return endDate; } public String getLocation() { return location; } /** * A possibly broad description of the ThaliaEvent * Can contain HTML * @return possibly very large string */ public String getDescription() { return description; } /** * The ThaliaEvent in less than 5 words * Can contain HTML * @return small String */ public String getSummary() { return summary; } public EventCategory getCategory() { return category; } public int getCatIcon() { return catIcon; } /** * Small composition of ThaliaEvent information * @return summary + "\n" + duration() + "\n" + location */ public String makeSynopsis() { return summary + "\n" + duration() + "\n" + location; } /** * A readable abbreviation of the day * e.g. di 18 aug * * @return dd - dd - mmm */ public String getDateString() { StringBuilder date; date = new StringBuilder(""); date.append(this.startDate.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault())); date.append(" "); date.append(this.startDate.get(Calendar.DAY_OF_MONTH)); date.append(" "); date.append(this.startDate.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault())); return date.toString(); } /***************************************************************** Default Methods <SUF>*/ /** * A neat stringformat of the beginning and ending times * * @return hh:mm-hh:mm */ public String duration() { StringBuilder sb = new StringBuilder(); sb.append(startDate.get(Calendar.HOUR_OF_DAY)); sb.append(":"); if (startDate.get(Calendar.MINUTE) == 0) { sb.append("00"); } else { sb.append(startDate.get(Calendar.MINUTE)); } sb.append(" - "); sb.append(endDate.get(Calendar.HOUR_OF_DAY)); sb.append(":"); if (endDate.get(Calendar.MINUTE) == 0) { sb.append("00"); } else { sb.append(endDate.get(Calendar.MINUTE)); } System.out.println("EoF durationfunction: "+sb.toString()); return sb.toString(); } /** * Printmethod, useful when you're debugging * * @return a string of the event */ @Override public String toString() { return ("\nstart = " + startDate + ", end = " + endDate + "\nlocation = " + location + "\ndescription = " + description + "\nsummary = " + summary); } /** * @param another the ThaliaEvent with which you want to compare it * @return The difference in time between the two */ @Override public int compareTo(@NonNull ThaliaEvent another) { return startDate.compareTo(another.startDate); } /***************************************************************** Making it a Parcelable, so it can be passed through with an intent *****************************************************************/ @Override public int describeContents() { return 0; } /** * Pretty much all information about this ThaliaEvent object is being * compressed into a Parcel * * @param dest Destination * @param flags Flags */ @Override public void writeToParcel(Parcel dest, int flags) { dest.writeLong(startDate.getTimeInMillis()); dest.writeLong(endDate.getTimeInMillis()); dest.writeString(location); dest.writeString(description); dest.writeString(summary); } /** * Reconstructs the ThaliaEvent through a parcel. */ public static final Parcelable.Creator<ThaliaEvent> CREATOR = new Parcelable.Creator<ThaliaEvent>() { // Parcels work FIFO public ThaliaEvent createFromParcel(Parcel parcel) { Long startDate = parcel.readLong(); Long endDate = parcel.readLong(); String location = parcel.readString(); String description = parcel.readString(); String summary = parcel.readString(); return new ThaliaEvent(startDate, endDate, location, description, summary); } public ThaliaEvent[] newArray(int size) { return new ThaliaEvent[size]; } }; }
False
1,742
9
1,902
8
2,095
16
1,902
8
2,329
19
false
false
false
false
false
true
1,131
48566_1
/* * Copyright (c) Forge Development LLC and contributors * SPDX-License-Identifier: LGPL-2.1-only */ package net.minecraftforge.fml.loading; import com.mojang.logging.LogUtils; import cpw.mods.modlauncher.Launcher; import cpw.mods.modlauncher.api.*; import net.minecraftforge.fml.loading.moddiscovery.BackgroundScanHandler; import net.minecraftforge.fml.loading.moddiscovery.ModDiscoverer; import net.minecraftforge.fml.loading.moddiscovery.ModFile; import net.minecraftforge.fml.loading.moddiscovery.ModValidator; import net.minecraftforge.accesstransformer.service.AccessTransformerService; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.fml.loading.targets.CommonLaunchHandler; import net.minecraftforge.forgespi.Environment; import net.minecraftforge.forgespi.coremod.ICoreModProvider; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.ServiceConfigurationError; import java.util.ServiceLoader; import java.util.Set; import java.util.function.BiFunction; import static net.minecraftforge.fml.loading.LogMarkers.CORE; import static net.minecraftforge.fml.loading.LogMarkers.SCAN; public class FMLLoader { private static final Logger LOGGER = LogUtils.getLogger(); private static AccessTransformerService accessTransformer; private static ModDiscoverer modDiscoverer; private static ICoreModProvider coreModProvider; private static LanguageLoadingProvider languageLoadingProvider; private static Dist dist; private static String naming; private static LoadingModList loadingModList; private static RuntimeDistCleaner runtimeDistCleaner; private static Path gamePath; private static final VersionInfo versionInfo = VersionInfo.detect(); private static String launchHandlerName; private static CommonLaunchHandler commonLaunchHandler; public static Runnable progressWindowTick; private static ModValidator modValidator; public static BackgroundScanHandler backgroundScanHandler; private static boolean production; private static IModuleLayerManager moduleLayerManager; static void onInitialLoad(IEnvironment env, Set<String> otherServices) throws IncompatibleEnvironmentException { LOGGER.debug(CORE, "Detected version data : {}", versionInfo); LOGGER.debug(CORE, "FML {} loading", LauncherVersion.getVersion()); checkPackage(ITransformationService.class, "4.0", "ModLauncher"); accessTransformer = getPlugin(env, "accesstransformer", "1.0", "AccessTransformer"); /*eventBus =*/ getPlugin(env, "eventbus", "1.0", "EventBus"); runtimeDistCleaner = getPlugin(env, "runtimedistcleaner", "1.0", "RuntimeDistCleaner"); coreModProvider = getSingleService(ICoreModProvider.class, "CoreMod"); LOGGER.debug(CORE,"FML found CoreMod version : {}", JarVersionLookupHandler.getInfo(coreModProvider.getClass()).impl().version().orElse("MISSING")); checkPackage(Environment.class, "2.0", "ForgeSPI"); try { Class.forName("com.electronwill.nightconfig.core.Config", false, env.getClass().getClassLoader()); Class.forName("com.electronwill.nightconfig.toml.TomlFormat", false, env.getClass().getClassLoader()); } catch (ClassNotFoundException e) { LOGGER.error(CORE, "Failed to load NightConfig"); throw new IncompatibleEnvironmentException("Missing NightConfig"); } } private static <T> T getPlugin(IEnvironment env, String id, String version, String name) throws IncompatibleEnvironmentException { @SuppressWarnings("unchecked") var plugin = (T)env.findLaunchPlugin(id).orElseThrow(() -> { LOGGER.error(CORE, "{} library is missing, we need this to run", name); return new IncompatibleEnvironmentException("Missing " + name + ", cannot run"); }); checkPackage(plugin.getClass(), version, name); return plugin; } private static void checkPackage(Class<?> cls, String version, String name) throws IncompatibleEnvironmentException { var pkg = cls.getPackage(); var info = JarVersionLookupHandler.getInfo(pkg); LOGGER.debug(CORE, "Found {} version: {}", name, info.impl().version().orElse("MISSING")); if (!pkg.isCompatibleWith(version)) { LOGGER.error(CORE, "Found incompatible {} specification: {}, version {} from {}", name, info.spec().version().orElse("MISSING"), info.impl().version().orElse("MISSING"), info.impl().vendor().orElse("MISSING") ); throw new IncompatibleEnvironmentException("Incompatible " + name + " found " + info.spec().version().orElse("MISSING")); } } private static <T> T getSingleService(Class<T> clazz, String name) throws IncompatibleEnvironmentException { var providers = new ArrayList<T>(); for (var itr = ServiceLoader.load(FMLLoader.class.getModule().getLayer(), clazz).iterator(); itr.hasNext(); ) { try { providers.add(itr.next()); } catch (ServiceConfigurationError e) { LOGGER.error(CORE, "Failed to load a " + name + " library, expect problems", e); } } if (providers.isEmpty()) { LOGGER.error(CORE, "Found no {} provider. Cannot run", name); throw new IncompatibleEnvironmentException("No " + name + " library found"); } else if (providers.size() > 1) { LOGGER.error(CORE, "Found multiple {} providers: {}. Cannot run", name, providers.stream().map(p -> p.getClass().getName()).toList()); throw new IncompatibleEnvironmentException("Multiple " + name + " libraries found"); } return providers.get(0); } static void setupLaunchHandler(final IEnvironment environment, final Map<String, Object> arguments) { final String launchTarget = environment.getProperty(IEnvironment.Keys.LAUNCHTARGET.get()).orElse("MISSING"); arguments.put("launchTarget", launchTarget); final Optional<ILaunchHandlerService> launchHandler = environment.findLaunchHandler(launchTarget); LOGGER.debug(CORE, "Using {} as launch service", launchTarget); if (launchHandler.isEmpty()) { LOGGER.error(CORE, "Missing LaunchHandler {}, cannot continue", launchTarget); throw new RuntimeException("Missing launch handler: " + launchTarget); } // TODO: [FML][Loader] What the fuck is the point of using a service if you require a specific concrete class if (!(launchHandler.get() instanceof CommonLaunchHandler)) { LOGGER.error(CORE, "Incompatible Launch handler found - type {}, cannot continue", launchHandler.get().getClass().getName()); throw new RuntimeException("Incompatible launch handler found"); } commonLaunchHandler = (CommonLaunchHandler)launchHandler.get(); launchHandlerName = launchHandler.get().name(); gamePath = environment.getProperty(IEnvironment.Keys.GAMEDIR.get()).orElse(Paths.get(".").toAbsolutePath()); naming = commonLaunchHandler.getNaming(); dist = commonLaunchHandler.getDist(); production = commonLaunchHandler.isProduction(); accessTransformer.getExtension().accept(Pair.of(naming, "srg")); runtimeDistCleaner.getExtension().accept(dist); } public static List<ITransformationService.Resource> beginModScan(final Map<String,?> arguments) { LOGGER.debug(SCAN,"Scanning for Mod Locators"); modDiscoverer = new ModDiscoverer(arguments); modValidator = modDiscoverer.discoverMods(); var pluginResources = modValidator.getPluginResources(); return List.of(pluginResources); } public static List<ITransformationService.Resource> completeScan(IModuleLayerManager layerManager) { moduleLayerManager = layerManager; languageLoadingProvider = new LanguageLoadingProvider(); backgroundScanHandler = modValidator.stage2Validation(); loadingModList = backgroundScanHandler.getLoadingModList(); return List.of(modValidator.getModResources()); } public static ICoreModProvider getCoreModProvider() { return coreModProvider; } public static LanguageLoadingProvider getLanguageLoadingProvider() { return languageLoadingProvider; } static ModDiscoverer getModDiscoverer() { return modDiscoverer; } public static CommonLaunchHandler getLaunchHandler() { return commonLaunchHandler; } public static void addAccessTransformer(Path atPath, ModFile modName) { LOGGER.debug(SCAN, "Adding Access Transformer in {}", modName.getFilePath()); accessTransformer.offerResource(atPath, modName.getFileName()); } public static Dist getDist() { return dist; } public static void beforeStart(ModuleLayer gameLayer) { ImmediateWindowHandler.acceptGameLayer(gameLayer); ImmediateWindowHandler.updateProgress("Launching minecraft"); progressWindowTick.run(); } public static LoadingModList getLoadingModList() { return loadingModList; } public static Path getGamePath() { return gamePath; } public static String getNaming() { return naming; } public static Optional<BiFunction<INameMappingService.Domain, String, String>> getNameFunction(final String naming) { return Launcher.INSTANCE.environment().findNameMapping(naming); } public static String getLauncherInfo() { return Launcher.INSTANCE.environment().getProperty(IEnvironment.Keys.MLIMPL_VERSION.get()).orElse("MISSING"); } public static List<Map<String, String>> modLauncherModList() { return Launcher.INSTANCE.environment().getProperty(IEnvironment.Keys.MODLIST.get()).orElse(List.of()); } public static String launcherHandlerName() { return launchHandlerName; } public static boolean isProduction() { return production; } public static boolean isSecureJarEnabled() { return true; } public static ModuleLayer getGameLayer() { return moduleLayerManager.getLayer(IModuleLayerManager.Layer.GAME).orElseThrow(); } public static VersionInfo versionInfo() { return versionInfo; } }
MinecraftForge/MinecraftForge
fmlloader/src/main/java/net/minecraftforge/fml/loading/FMLLoader.java
2,910
/*eventBus =*/
block_comment
nl
/* * Copyright (c) Forge Development LLC and contributors * SPDX-License-Identifier: LGPL-2.1-only */ package net.minecraftforge.fml.loading; import com.mojang.logging.LogUtils; import cpw.mods.modlauncher.Launcher; import cpw.mods.modlauncher.api.*; import net.minecraftforge.fml.loading.moddiscovery.BackgroundScanHandler; import net.minecraftforge.fml.loading.moddiscovery.ModDiscoverer; import net.minecraftforge.fml.loading.moddiscovery.ModFile; import net.minecraftforge.fml.loading.moddiscovery.ModValidator; import net.minecraftforge.accesstransformer.service.AccessTransformerService; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.fml.loading.targets.CommonLaunchHandler; import net.minecraftforge.forgespi.Environment; import net.minecraftforge.forgespi.coremod.ICoreModProvider; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.ServiceConfigurationError; import java.util.ServiceLoader; import java.util.Set; import java.util.function.BiFunction; import static net.minecraftforge.fml.loading.LogMarkers.CORE; import static net.minecraftforge.fml.loading.LogMarkers.SCAN; public class FMLLoader { private static final Logger LOGGER = LogUtils.getLogger(); private static AccessTransformerService accessTransformer; private static ModDiscoverer modDiscoverer; private static ICoreModProvider coreModProvider; private static LanguageLoadingProvider languageLoadingProvider; private static Dist dist; private static String naming; private static LoadingModList loadingModList; private static RuntimeDistCleaner runtimeDistCleaner; private static Path gamePath; private static final VersionInfo versionInfo = VersionInfo.detect(); private static String launchHandlerName; private static CommonLaunchHandler commonLaunchHandler; public static Runnable progressWindowTick; private static ModValidator modValidator; public static BackgroundScanHandler backgroundScanHandler; private static boolean production; private static IModuleLayerManager moduleLayerManager; static void onInitialLoad(IEnvironment env, Set<String> otherServices) throws IncompatibleEnvironmentException { LOGGER.debug(CORE, "Detected version data : {}", versionInfo); LOGGER.debug(CORE, "FML {} loading", LauncherVersion.getVersion()); checkPackage(ITransformationService.class, "4.0", "ModLauncher"); accessTransformer = getPlugin(env, "accesstransformer", "1.0", "AccessTransformer"); /*eventBus <SUF>*/ getPlugin(env, "eventbus", "1.0", "EventBus"); runtimeDistCleaner = getPlugin(env, "runtimedistcleaner", "1.0", "RuntimeDistCleaner"); coreModProvider = getSingleService(ICoreModProvider.class, "CoreMod"); LOGGER.debug(CORE,"FML found CoreMod version : {}", JarVersionLookupHandler.getInfo(coreModProvider.getClass()).impl().version().orElse("MISSING")); checkPackage(Environment.class, "2.0", "ForgeSPI"); try { Class.forName("com.electronwill.nightconfig.core.Config", false, env.getClass().getClassLoader()); Class.forName("com.electronwill.nightconfig.toml.TomlFormat", false, env.getClass().getClassLoader()); } catch (ClassNotFoundException e) { LOGGER.error(CORE, "Failed to load NightConfig"); throw new IncompatibleEnvironmentException("Missing NightConfig"); } } private static <T> T getPlugin(IEnvironment env, String id, String version, String name) throws IncompatibleEnvironmentException { @SuppressWarnings("unchecked") var plugin = (T)env.findLaunchPlugin(id).orElseThrow(() -> { LOGGER.error(CORE, "{} library is missing, we need this to run", name); return new IncompatibleEnvironmentException("Missing " + name + ", cannot run"); }); checkPackage(plugin.getClass(), version, name); return plugin; } private static void checkPackage(Class<?> cls, String version, String name) throws IncompatibleEnvironmentException { var pkg = cls.getPackage(); var info = JarVersionLookupHandler.getInfo(pkg); LOGGER.debug(CORE, "Found {} version: {}", name, info.impl().version().orElse("MISSING")); if (!pkg.isCompatibleWith(version)) { LOGGER.error(CORE, "Found incompatible {} specification: {}, version {} from {}", name, info.spec().version().orElse("MISSING"), info.impl().version().orElse("MISSING"), info.impl().vendor().orElse("MISSING") ); throw new IncompatibleEnvironmentException("Incompatible " + name + " found " + info.spec().version().orElse("MISSING")); } } private static <T> T getSingleService(Class<T> clazz, String name) throws IncompatibleEnvironmentException { var providers = new ArrayList<T>(); for (var itr = ServiceLoader.load(FMLLoader.class.getModule().getLayer(), clazz).iterator(); itr.hasNext(); ) { try { providers.add(itr.next()); } catch (ServiceConfigurationError e) { LOGGER.error(CORE, "Failed to load a " + name + " library, expect problems", e); } } if (providers.isEmpty()) { LOGGER.error(CORE, "Found no {} provider. Cannot run", name); throw new IncompatibleEnvironmentException("No " + name + " library found"); } else if (providers.size() > 1) { LOGGER.error(CORE, "Found multiple {} providers: {}. Cannot run", name, providers.stream().map(p -> p.getClass().getName()).toList()); throw new IncompatibleEnvironmentException("Multiple " + name + " libraries found"); } return providers.get(0); } static void setupLaunchHandler(final IEnvironment environment, final Map<String, Object> arguments) { final String launchTarget = environment.getProperty(IEnvironment.Keys.LAUNCHTARGET.get()).orElse("MISSING"); arguments.put("launchTarget", launchTarget); final Optional<ILaunchHandlerService> launchHandler = environment.findLaunchHandler(launchTarget); LOGGER.debug(CORE, "Using {} as launch service", launchTarget); if (launchHandler.isEmpty()) { LOGGER.error(CORE, "Missing LaunchHandler {}, cannot continue", launchTarget); throw new RuntimeException("Missing launch handler: " + launchTarget); } // TODO: [FML][Loader] What the fuck is the point of using a service if you require a specific concrete class if (!(launchHandler.get() instanceof CommonLaunchHandler)) { LOGGER.error(CORE, "Incompatible Launch handler found - type {}, cannot continue", launchHandler.get().getClass().getName()); throw new RuntimeException("Incompatible launch handler found"); } commonLaunchHandler = (CommonLaunchHandler)launchHandler.get(); launchHandlerName = launchHandler.get().name(); gamePath = environment.getProperty(IEnvironment.Keys.GAMEDIR.get()).orElse(Paths.get(".").toAbsolutePath()); naming = commonLaunchHandler.getNaming(); dist = commonLaunchHandler.getDist(); production = commonLaunchHandler.isProduction(); accessTransformer.getExtension().accept(Pair.of(naming, "srg")); runtimeDistCleaner.getExtension().accept(dist); } public static List<ITransformationService.Resource> beginModScan(final Map<String,?> arguments) { LOGGER.debug(SCAN,"Scanning for Mod Locators"); modDiscoverer = new ModDiscoverer(arguments); modValidator = modDiscoverer.discoverMods(); var pluginResources = modValidator.getPluginResources(); return List.of(pluginResources); } public static List<ITransformationService.Resource> completeScan(IModuleLayerManager layerManager) { moduleLayerManager = layerManager; languageLoadingProvider = new LanguageLoadingProvider(); backgroundScanHandler = modValidator.stage2Validation(); loadingModList = backgroundScanHandler.getLoadingModList(); return List.of(modValidator.getModResources()); } public static ICoreModProvider getCoreModProvider() { return coreModProvider; } public static LanguageLoadingProvider getLanguageLoadingProvider() { return languageLoadingProvider; } static ModDiscoverer getModDiscoverer() { return modDiscoverer; } public static CommonLaunchHandler getLaunchHandler() { return commonLaunchHandler; } public static void addAccessTransformer(Path atPath, ModFile modName) { LOGGER.debug(SCAN, "Adding Access Transformer in {}", modName.getFilePath()); accessTransformer.offerResource(atPath, modName.getFileName()); } public static Dist getDist() { return dist; } public static void beforeStart(ModuleLayer gameLayer) { ImmediateWindowHandler.acceptGameLayer(gameLayer); ImmediateWindowHandler.updateProgress("Launching minecraft"); progressWindowTick.run(); } public static LoadingModList getLoadingModList() { return loadingModList; } public static Path getGamePath() { return gamePath; } public static String getNaming() { return naming; } public static Optional<BiFunction<INameMappingService.Domain, String, String>> getNameFunction(final String naming) { return Launcher.INSTANCE.environment().findNameMapping(naming); } public static String getLauncherInfo() { return Launcher.INSTANCE.environment().getProperty(IEnvironment.Keys.MLIMPL_VERSION.get()).orElse("MISSING"); } public static List<Map<String, String>> modLauncherModList() { return Launcher.INSTANCE.environment().getProperty(IEnvironment.Keys.MODLIST.get()).orElse(List.of()); } public static String launcherHandlerName() { return launchHandlerName; } public static boolean isProduction() { return production; } public static boolean isSecureJarEnabled() { return true; } public static ModuleLayer getGameLayer() { return moduleLayerManager.getLayer(IModuleLayerManager.Layer.GAME).orElseThrow(); } public static VersionInfo versionInfo() { return versionInfo; } }
False
2,112
6
2,370
6
2,503
5
2,370
6
2,845
6
false
false
false
false
false
true
3,391
25495_15
/* * Copyright (C) 2013 Koen Vlaswinkel * * 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.phphulp.app; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import android.widget.Toast; public class ArticleAdapter extends BaseAdapter { private Context context; private ArrayList<Article> items; /** * Dit wordt gebruikt voor een hogere snelheid */ static class ViewHolder { public TextView title; public TextView text; } public ArticleAdapter(Context context, ArrayList<Article> items) { super(); this.context = context; this.items = items; } /** * Hoe groot is onze lijst? * * @return grootte van de lijst */ @Override public int getCount() { return items.size(); } /** * Een item uit de lijst * * @return een object dat het item is */ @Override public Object getItem(int position) { return items.get(position); } /** * Dit is een beetje onzinnig voor onze applicatie * * @return de positie */ @Override public long getItemId(int position) { return position; } /** * Hier maken we de view die zichtbaar is in de lijst * * @param position * @param convertView * @param parent * * @return De view */ @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { // Zorg ervoor dat we een layout kunnen maken LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // Zorg voor een standaard view met 2 regels view = inflater.inflate(android.R.layout.simple_list_item_2, parent, false); // We gaan voor wat snelheid zorgen ViewHolder viewHolder = new ViewHolder(); viewHolder.title = (TextView) view.findViewById(android.R.id.text1); viewHolder.text = (TextView) view.findViewById(android.R.id.text2); // En deze snelheid opslaan view.setTag(viewHolder); } // Hier kunnen we de snelheid weer terugkrijgen ViewHolder holder = (ViewHolder) view.getTag(); // Dit is ons artikel dat we moeten laten zien final Article article = items.get(position); // We gaan op de eerste regel een titel laten zien holder.title.setText(article.getTitle()); // En op de tweede regel wat content holder.text.setText(article.getContent()); // En nu gaan we zorgen dat er een 'Toast' verschijnt als je op het item // klikt view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Hier maken we een 'Toast' Toast.makeText( context, "Je hebt op artikel " + article.getId() + " geklikt met slug " + article.getSlug(), Toast.LENGTH_LONG).show(); } }); return view; } }
koesie10/phphulp-android
Android/src/nl/phphulp/app/ArticleAdapter.java
1,074
// Hier maken we een 'Toast'
line_comment
nl
/* * Copyright (C) 2013 Koen Vlaswinkel * * 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.phphulp.app; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import android.widget.Toast; public class ArticleAdapter extends BaseAdapter { private Context context; private ArrayList<Article> items; /** * Dit wordt gebruikt voor een hogere snelheid */ static class ViewHolder { public TextView title; public TextView text; } public ArticleAdapter(Context context, ArrayList<Article> items) { super(); this.context = context; this.items = items; } /** * Hoe groot is onze lijst? * * @return grootte van de lijst */ @Override public int getCount() { return items.size(); } /** * Een item uit de lijst * * @return een object dat het item is */ @Override public Object getItem(int position) { return items.get(position); } /** * Dit is een beetje onzinnig voor onze applicatie * * @return de positie */ @Override public long getItemId(int position) { return position; } /** * Hier maken we de view die zichtbaar is in de lijst * * @param position * @param convertView * @param parent * * @return De view */ @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { // Zorg ervoor dat we een layout kunnen maken LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // Zorg voor een standaard view met 2 regels view = inflater.inflate(android.R.layout.simple_list_item_2, parent, false); // We gaan voor wat snelheid zorgen ViewHolder viewHolder = new ViewHolder(); viewHolder.title = (TextView) view.findViewById(android.R.id.text1); viewHolder.text = (TextView) view.findViewById(android.R.id.text2); // En deze snelheid opslaan view.setTag(viewHolder); } // Hier kunnen we de snelheid weer terugkrijgen ViewHolder holder = (ViewHolder) view.getTag(); // Dit is ons artikel dat we moeten laten zien final Article article = items.get(position); // We gaan op de eerste regel een titel laten zien holder.title.setText(article.getTitle()); // En op de tweede regel wat content holder.text.setText(article.getContent()); // En nu gaan we zorgen dat er een 'Toast' verschijnt als je op het item // klikt view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Hier maken<SUF> Toast.makeText( context, "Je hebt op artikel " + article.getId() + " geklikt met slug " + article.getSlug(), Toast.LENGTH_LONG).show(); } }); return view; } }
True
834
8
1,015
9
958
8
1,015
9
1,177
10
false
false
false
false
false
true
154
174732_3
package com.practice.miscellaneous; import java.util.*; /**Problem statement: Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Each row must contain the digits 1-9 without repetition. Each column must contain the digits 1-9 without repetition. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition. Note: A Sudoku board (partially filled) could be valid but is not necessarily solvable. Only the filled cells need to be validated according to the mentioned rules. Example 1: Input: board = [["5","3",".",".","7",".",".",".","."] ,["6",".",".","1","9","5",".",".","."] ,[".","9","8",".",".",".",".","6","."] ,["8",".",".",".","6",".",".",".","3"] ,["4",".",".","8",".","3",".",".","1"] ,["7",".",".",".","2",".",".",".","6"] ,[".","6",".",".",".",".","2","8","."] ,[".",".",".","4","1","9",".",".","5"] ,[".",".",".",".","8",".",".","7","9"]] Output: true Example 2: Input: board = [["8","3",".",".","7",".",".",".","."] ,["6",".",".","1","9","5",".",".","."] ,[".","9","8",".",".",".",".","6","."] ,["8",".",".",".","6",".",".",".","3"] ,["4",".",".","8",".","3",".",".","1"] ,["7",".",".",".","2",".",".",".","6"] ,[".","6",".",".",".",".","2","8","."] ,[".",".",".","4","1","9",".",".","5"] ,[".",".",".",".","8",".",".","7","9"]] Output: false Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid. Constraints: board.length == 9 board[i].length == 9 board[i][j] is a digit 1-9 or '.'. Leetcode link: https://leetcode.com/problems/valid-sudoku/description/ **/ public class ValidSudoku { public boolean isValidSudoku(char[][] board) { Coordinates coord = new Coordinates(0, 0); //check rows boolean rowsAreValid = allRowsAreValid(board, coord ); //check columns boolean colsAreValid = allColumnsAreValid(board, coord ); //check boxes List<List<Character>> cubesList = createCubesList(board, coord); boolean cubesAreValid = allCubesAreValid(cubesList, coord); return rowsAreValid && colsAreValid && cubesAreValid; } public static boolean allCubesAreValid(List < List < Character >> cubesList, Coordinates coord ) { for (List < Character > singleCubeList: cubesList) { Set < Character > set = new HashSet < > (); for (Character c: singleCubeList) { if (!set.add(c)) { return false; } } } return true; } public static List < List < Character >> createCubesList(char[][] board, Coordinates coord ) { List < List < Character >> result = new ArrayList < > (); int width = board[0].length; int height = board.length; //get the top while (coord.wall <= width) { List < Character > singleCubeList = addElementsForCube(board, coord); result.add(singleCubeList); coord.goRight(); } //get the middle coord.resetCoordinatesToZero(); coord.goDown(); while (coord.wall <= width) { List < Character > singleCubeList = addElementsForCube(board, coord); result.add(singleCubeList); coord.goRight(); } //get the end coord.resetCoordinatesToZero(); coord.goDown(); coord.goDown(); while (coord.wall <= width) { List < Character > singleCubeList = addElementsForCube(board, coord); result.add(singleCubeList); coord.goRight(); } return result; } public static List < Character > addElementsForCube(char[][] board, Coordinates coord) { List < Character > result = new ArrayList < > (); for (int row = coord.floor - 3; row < coord.floor; row++) { for (int col = coord.wall - 3; col < coord.wall; col++) { char current = board[row][col]; if (Character.isDigit(current)) { result.add(current); } } } return result; } public static boolean allColumnsAreValid(char[][] board, Coordinates coord ) { int height = board.length; int width = board[0].length; for (int col = 0; col < width; col++) { Set < Character > set = new HashSet < > (); for (int row = 0; row < height; row++) { char number = board[row][col]; if (Character.isDigit(number)) { if (!set.add(number)) { return false; } } } } return true; } public static boolean allRowsAreValid(char[][] board, Coordinates coord ) { for (char[] singleRow: board) { Set < Character > set = new HashSet < > (); for (char number: singleRow) { if (Character.isDigit(number)) { if (!set.add(number)) { return false; } } } } return true; } } class Coordinates { int row; int col; int wall; int floor; Coordinates(int row, int col) { this.row = row; this.col = col; this.wall = col + 3; this.floor = row + 3; } public void goRight() { col += 3; wall += 3; } public void resetCoordinatesToZero() { row = 0; col = 0; wall = col + 3; floor = row + 3; } public void goDown() { row += 3; floor += 3; } }
AveryCS/data-structures-and-algorithms
src/com/practice/miscellaneous/ValidSudoku.java
1,847
//get the end
line_comment
nl
package com.practice.miscellaneous; import java.util.*; /**Problem statement: Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Each row must contain the digits 1-9 without repetition. Each column must contain the digits 1-9 without repetition. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition. Note: A Sudoku board (partially filled) could be valid but is not necessarily solvable. Only the filled cells need to be validated according to the mentioned rules. Example 1: Input: board = [["5","3",".",".","7",".",".",".","."] ,["6",".",".","1","9","5",".",".","."] ,[".","9","8",".",".",".",".","6","."] ,["8",".",".",".","6",".",".",".","3"] ,["4",".",".","8",".","3",".",".","1"] ,["7",".",".",".","2",".",".",".","6"] ,[".","6",".",".",".",".","2","8","."] ,[".",".",".","4","1","9",".",".","5"] ,[".",".",".",".","8",".",".","7","9"]] Output: true Example 2: Input: board = [["8","3",".",".","7",".",".",".","."] ,["6",".",".","1","9","5",".",".","."] ,[".","9","8",".",".",".",".","6","."] ,["8",".",".",".","6",".",".",".","3"] ,["4",".",".","8",".","3",".",".","1"] ,["7",".",".",".","2",".",".",".","6"] ,[".","6",".",".",".",".","2","8","."] ,[".",".",".","4","1","9",".",".","5"] ,[".",".",".",".","8",".",".","7","9"]] Output: false Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid. Constraints: board.length == 9 board[i].length == 9 board[i][j] is a digit 1-9 or '.'. Leetcode link: https://leetcode.com/problems/valid-sudoku/description/ **/ public class ValidSudoku { public boolean isValidSudoku(char[][] board) { Coordinates coord = new Coordinates(0, 0); //check rows boolean rowsAreValid = allRowsAreValid(board, coord ); //check columns boolean colsAreValid = allColumnsAreValid(board, coord ); //check boxes List<List<Character>> cubesList = createCubesList(board, coord); boolean cubesAreValid = allCubesAreValid(cubesList, coord); return rowsAreValid && colsAreValid && cubesAreValid; } public static boolean allCubesAreValid(List < List < Character >> cubesList, Coordinates coord ) { for (List < Character > singleCubeList: cubesList) { Set < Character > set = new HashSet < > (); for (Character c: singleCubeList) { if (!set.add(c)) { return false; } } } return true; } public static List < List < Character >> createCubesList(char[][] board, Coordinates coord ) { List < List < Character >> result = new ArrayList < > (); int width = board[0].length; int height = board.length; //get the top while (coord.wall <= width) { List < Character > singleCubeList = addElementsForCube(board, coord); result.add(singleCubeList); coord.goRight(); } //get the middle coord.resetCoordinatesToZero(); coord.goDown(); while (coord.wall <= width) { List < Character > singleCubeList = addElementsForCube(board, coord); result.add(singleCubeList); coord.goRight(); } //get the<SUF> coord.resetCoordinatesToZero(); coord.goDown(); coord.goDown(); while (coord.wall <= width) { List < Character > singleCubeList = addElementsForCube(board, coord); result.add(singleCubeList); coord.goRight(); } return result; } public static List < Character > addElementsForCube(char[][] board, Coordinates coord) { List < Character > result = new ArrayList < > (); for (int row = coord.floor - 3; row < coord.floor; row++) { for (int col = coord.wall - 3; col < coord.wall; col++) { char current = board[row][col]; if (Character.isDigit(current)) { result.add(current); } } } return result; } public static boolean allColumnsAreValid(char[][] board, Coordinates coord ) { int height = board.length; int width = board[0].length; for (int col = 0; col < width; col++) { Set < Character > set = new HashSet < > (); for (int row = 0; row < height; row++) { char number = board[row][col]; if (Character.isDigit(number)) { if (!set.add(number)) { return false; } } } } return true; } public static boolean allRowsAreValid(char[][] board, Coordinates coord ) { for (char[] singleRow: board) { Set < Character > set = new HashSet < > (); for (char number: singleRow) { if (Character.isDigit(number)) { if (!set.add(number)) { return false; } } } } return true; } } class Coordinates { int row; int col; int wall; int floor; Coordinates(int row, int col) { this.row = row; this.col = col; this.wall = col + 3; this.floor = row + 3; } public void goRight() { col += 3; wall += 3; } public void resetCoordinatesToZero() { row = 0; col = 0; wall = col + 3; floor = row + 3; } public void goDown() { row += 3; floor += 3; } }
False
1,392
4
1,511
4
1,703
4
1,511
4
1,833
4
false
false
false
false
false
true
476
52687_6
package novi.nl.Les11BESpringbootmodelhuiswerk.models; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.*; import java.util.List; @Entity @Table(name = "cimodules") public class CIModule { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private String type; private Double price; // Een ManyToOne relatie tussen Television en CI-Module // @OneToMany(mappedBy = "cimodule") // private List<Television> televisions; // OneToMany relatie tussen Television en CI-Module @ManyToOne private Television television; //getters & setters........................................ public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } // hoort bij ManyToOne public Television getTelevision() { return television; } public void setTelevision(Television television) { this.television = television; } // hoort bij OneToMany // public List<Television> getTelevisions() { // return televisions; // } // // public void setTelevisions(List<Television> televisions) { // this.televisions = televisions; // } }
Ellen-van-Duikeren/BE-spring-boot-model-huiswerk-Les11
src/main/java/novi/nl/Les11BESpringbootmodelhuiswerk/models/CIModule.java
493
// hoort bij OneToMany
line_comment
nl
package novi.nl.Les11BESpringbootmodelhuiswerk.models; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.*; import java.util.List; @Entity @Table(name = "cimodules") public class CIModule { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private String type; private Double price; // Een ManyToOne relatie tussen Television en CI-Module // @OneToMany(mappedBy = "cimodule") // private List<Television> televisions; // OneToMany relatie tussen Television en CI-Module @ManyToOne private Television television; //getters & setters........................................ public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } // hoort bij ManyToOne public Television getTelevision() { return television; } public void setTelevision(Television television) { this.television = television; } // hoort bij<SUF> // public List<Television> getTelevisions() { // return televisions; // } // // public void setTelevisions(List<Television> televisions) { // this.televisions = televisions; // } }
True
366
6
426
6
422
5
426
6
501
7
false
false
false
false
false
true
3,891
121895_20
/** * */ package org.sharks.service.producer; import java.util.Collection; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import org.sharks.service.dto.EntityDetails; import org.sharks.service.dto.EntityDocument; import org.sharks.service.dto.EntityEntry; import org.sharks.service.dto.FaoLexDocument; import org.sharks.service.dto.GroupEntry; import org.sharks.service.dto.InformationSourceEntry; import org.sharks.service.dto.MeasureEntry; import org.sharks.service.dto.PoAEntry; import org.sharks.service.moniker.dto.FaoLexFiDocument; import org.sharks.storage.domain.CustomSpeciesGrp; import org.sharks.storage.domain.InformationSource; import org.sharks.storage.domain.Measure; import org.sharks.storage.domain.MgmtEntity; import org.sharks.storage.domain.PoA; /** * @author "Federico De Faveri [email protected]" * */ public class EntryProducers { public static <I, O> List<O> convert(Collection<I> input, EntryProducer<I, O> converter) { return input.stream().map(converter).collect(Collectors.toList()); } public static final EntryProducer<EntityDetails, EntityDocument> TO_ENTITY_DOC = new AbstractEntryProducer<EntityDetails, EntityDocument>() { @Override public EntityDocument produce(EntityDetails item) { // private final long id; // private final String acronym; // private final String name; // private final Long type; // private final String logoUrl; // private final String webSite; // private final String factsheetUrl; // private final List<EntityMember> members; // private final List<MeasureEntry> measures; // private final List<EntityDocument> others; // private final String title; // private final Integer year; // private final String type; // private final String url; // private final String symbol; return new EntityDocument(item.getAcronym(), 0, item.getType().toString(), item.getWebSite(), null); } }; public static final EntryProducer<Measure, MeasureEntry> TO_MEASURE_ENTRY = new AbstractEntryProducer<Measure, MeasureEntry>() { @Override public MeasureEntry produce(Measure measure) { String replacedMeasureSourceUrl = null; if (measure.getReplaces() != null) { Measure replaced = measure.getReplaces(); List<InformationSource> replacedSources = replaced.getInformationSources(); replacedMeasureSourceUrl = !replacedSources.isEmpty() ? replacedSources.get(0).getUrl() : null; } return new MeasureEntry(measure.getCode(), measure.getSymbol(), measure.getTitle(), measure.getDocumentType() != null ? measure.getDocumentType().getDescription() : null, measure.getMeasureYear(), measure.getBinding(), measure.getMgmtEntity().getAcronym(), convert(measure.getInformationSources(), TO_INFORMATION_SOURCE_ENTRY), replacedMeasureSourceUrl); } // private String findEntityAcronym(List<InformationSource> sources) { // for (InformationSource source : sources) { // for (MgmtEntity mgmtEntity : source.getMgmtEntities()) { // if (mgmtEntity != null && mgmtEntity.getAcronym() != null) // return mgmtEntity.getAcronym(); // } // } // // return "werkelijk niks"; // return null; // } }; public static final EntryProducer<InformationSource, InformationSourceEntry> TO_INFORMATION_SOURCE_ENTRY = new AbstractEntryProducer<InformationSource, InformationSourceEntry>() { @Override public InformationSourceEntry produce(InformationSource source) { return new InformationSourceEntry(source.getUrl()); } }; public static final EntryProducer<CustomSpeciesGrp, GroupEntry> TO_GROUP_ENTRY = new AbstractEntryProducer<CustomSpeciesGrp, GroupEntry>() { @Override public GroupEntry produce(CustomSpeciesGrp group) { return new GroupEntry(group.getCode(), group.getCustomSpeciesGrp()); } }; public static final EntryProducer<PoA, PoAEntry> TO_POA_ENTRY = new AbstractEntryProducer<PoA, PoAEntry>() { @Override public PoAEntry produce(PoA poa) { return new PoAEntry(poa.getCode(), poa.getTitle(), poa.getPoAYear(), poa.getPoAType() != null ? poa.getPoAType().getDescription() : null, poa.getStatus() != null ? poa.getStatus().getDescription() : null, convert(poa.getInformationSources(), TO_INFORMATION_SOURCE_ENTRY)); } }; public static final EntryProducer<MgmtEntity, EntityEntry> TO_ENTITY_ENTRY = new AbstractEntryProducer<MgmtEntity, EntityEntry>() { @Override public EntityEntry produce(MgmtEntity entity) { return new EntityEntry(entity.getAcronym(), entity.getMgmtEntityName(), entity.getMgmtEntityType().getCode()); } }; public static final EntryProducer<InformationSource, EntityDocument> TO_ENTITY_DOCUMENT = new AbstractEntryProducer<InformationSource, EntityDocument>() { @Override public EntityDocument produce(InformationSource source) { return new EntityDocument(source.getTitle(), source.getInfoSrcYear(), source.getInformationType().getDescription(), source.getUrl(), source.getSymbol()); } }; public static final EntryProducer<FaoLexFiDocument, FaoLexDocument> TO_FAOLEX_DOCUMENT = new AbstractEntryProducer<FaoLexFiDocument, FaoLexDocument>() { @Override public FaoLexDocument produce(FaoLexFiDocument doc) { return new FaoLexDocument(doc.getFaolexId(), doc.getTitle(), doc.getLongTitle(), doc.getDateOfText(), doc.getDateOfOriginalText(), doc.getDateOfConsolidation(), doc.getUri()); } }; public static abstract class AbstractEntryProducer<I, O> implements EntryProducer<I, O> { @Override public O apply(I t) { return produce(t); } } public interface EntryProducer<I, O> extends Function<I, O> { public O produce(I item); } }
openfigis/sharks
sharks-server/sharks-service/src/main/java/org/sharks/service/producer/EntryProducers.java
1,761
// // return "werkelijk niks";
line_comment
nl
/** * */ package org.sharks.service.producer; import java.util.Collection; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import org.sharks.service.dto.EntityDetails; import org.sharks.service.dto.EntityDocument; import org.sharks.service.dto.EntityEntry; import org.sharks.service.dto.FaoLexDocument; import org.sharks.service.dto.GroupEntry; import org.sharks.service.dto.InformationSourceEntry; import org.sharks.service.dto.MeasureEntry; import org.sharks.service.dto.PoAEntry; import org.sharks.service.moniker.dto.FaoLexFiDocument; import org.sharks.storage.domain.CustomSpeciesGrp; import org.sharks.storage.domain.InformationSource; import org.sharks.storage.domain.Measure; import org.sharks.storage.domain.MgmtEntity; import org.sharks.storage.domain.PoA; /** * @author "Federico De Faveri [email protected]" * */ public class EntryProducers { public static <I, O> List<O> convert(Collection<I> input, EntryProducer<I, O> converter) { return input.stream().map(converter).collect(Collectors.toList()); } public static final EntryProducer<EntityDetails, EntityDocument> TO_ENTITY_DOC = new AbstractEntryProducer<EntityDetails, EntityDocument>() { @Override public EntityDocument produce(EntityDetails item) { // private final long id; // private final String acronym; // private final String name; // private final Long type; // private final String logoUrl; // private final String webSite; // private final String factsheetUrl; // private final List<EntityMember> members; // private final List<MeasureEntry> measures; // private final List<EntityDocument> others; // private final String title; // private final Integer year; // private final String type; // private final String url; // private final String symbol; return new EntityDocument(item.getAcronym(), 0, item.getType().toString(), item.getWebSite(), null); } }; public static final EntryProducer<Measure, MeasureEntry> TO_MEASURE_ENTRY = new AbstractEntryProducer<Measure, MeasureEntry>() { @Override public MeasureEntry produce(Measure measure) { String replacedMeasureSourceUrl = null; if (measure.getReplaces() != null) { Measure replaced = measure.getReplaces(); List<InformationSource> replacedSources = replaced.getInformationSources(); replacedMeasureSourceUrl = !replacedSources.isEmpty() ? replacedSources.get(0).getUrl() : null; } return new MeasureEntry(measure.getCode(), measure.getSymbol(), measure.getTitle(), measure.getDocumentType() != null ? measure.getDocumentType().getDescription() : null, measure.getMeasureYear(), measure.getBinding(), measure.getMgmtEntity().getAcronym(), convert(measure.getInformationSources(), TO_INFORMATION_SOURCE_ENTRY), replacedMeasureSourceUrl); } // private String findEntityAcronym(List<InformationSource> sources) { // for (InformationSource source : sources) { // for (MgmtEntity mgmtEntity : source.getMgmtEntities()) { // if (mgmtEntity != null && mgmtEntity.getAcronym() != null) // return mgmtEntity.getAcronym(); // } // } // // return "werkelijk<SUF> // return null; // } }; public static final EntryProducer<InformationSource, InformationSourceEntry> TO_INFORMATION_SOURCE_ENTRY = new AbstractEntryProducer<InformationSource, InformationSourceEntry>() { @Override public InformationSourceEntry produce(InformationSource source) { return new InformationSourceEntry(source.getUrl()); } }; public static final EntryProducer<CustomSpeciesGrp, GroupEntry> TO_GROUP_ENTRY = new AbstractEntryProducer<CustomSpeciesGrp, GroupEntry>() { @Override public GroupEntry produce(CustomSpeciesGrp group) { return new GroupEntry(group.getCode(), group.getCustomSpeciesGrp()); } }; public static final EntryProducer<PoA, PoAEntry> TO_POA_ENTRY = new AbstractEntryProducer<PoA, PoAEntry>() { @Override public PoAEntry produce(PoA poa) { return new PoAEntry(poa.getCode(), poa.getTitle(), poa.getPoAYear(), poa.getPoAType() != null ? poa.getPoAType().getDescription() : null, poa.getStatus() != null ? poa.getStatus().getDescription() : null, convert(poa.getInformationSources(), TO_INFORMATION_SOURCE_ENTRY)); } }; public static final EntryProducer<MgmtEntity, EntityEntry> TO_ENTITY_ENTRY = new AbstractEntryProducer<MgmtEntity, EntityEntry>() { @Override public EntityEntry produce(MgmtEntity entity) { return new EntityEntry(entity.getAcronym(), entity.getMgmtEntityName(), entity.getMgmtEntityType().getCode()); } }; public static final EntryProducer<InformationSource, EntityDocument> TO_ENTITY_DOCUMENT = new AbstractEntryProducer<InformationSource, EntityDocument>() { @Override public EntityDocument produce(InformationSource source) { return new EntityDocument(source.getTitle(), source.getInfoSrcYear(), source.getInformationType().getDescription(), source.getUrl(), source.getSymbol()); } }; public static final EntryProducer<FaoLexFiDocument, FaoLexDocument> TO_FAOLEX_DOCUMENT = new AbstractEntryProducer<FaoLexFiDocument, FaoLexDocument>() { @Override public FaoLexDocument produce(FaoLexFiDocument doc) { return new FaoLexDocument(doc.getFaolexId(), doc.getTitle(), doc.getLongTitle(), doc.getDateOfText(), doc.getDateOfOriginalText(), doc.getDateOfConsolidation(), doc.getUri()); } }; public static abstract class AbstractEntryProducer<I, O> implements EntryProducer<I, O> { @Override public O apply(I t) { return produce(t); } } public interface EntryProducer<I, O> extends Function<I, O> { public O produce(I item); } }
True
1,326
10
1,580
10
1,561
8
1,580
10
1,904
9
false
false
false
false
false
true
1,039
146043_0
public class Main { public static void main(String args[]) { Werknemer dieter = new Werknemer("Dieter", "Clauwaert", 1, 1000); Werknemer jasper = new Werknemer("Jasper", "Cludts", 2, 2000); Werknemer mats = new Werknemer("Mats", "Kennes", 3, 3000); Werknemer jonah = new Werknemer("Jonah", "Boons", 4, 4000); PartTimeWerknemer alex = new PartTimeWerknemer("Alex", "Spildooren", 5, 5000, 5); PartTimeWerknemer alexis = new PartTimeWerknemer("Alexis", "Guiette", 6, 6000, 6); /* dieter.salarisVerhogen(10); jasper.salarisVerhogen(10); mats.salarisVerhogen(10); jonah.salarisVerhogen(10); System.out.println(dieter.voornaam + " verdient " + dieter.getsalaris()); System.out.println(jasper.voornaam + " verdient " + jasper.getsalaris()); System.out.println(mats.voornaam + " verdient " + mats.getsalaris()); System.out.println(jonah.voornaam + " verdient " + jonah.getsalaris()); alex.salarisVerhogen(4); alexis.salarisVerhogen(4); System.out.println(alex.voornaam + " verdient " + alex.getsalaris() + " en werkt " + alex.urenGewerkt + " uur "); System.out.println(alexis.voornaam + " verdient " + alexis.getsalaris() + " en werkt " + alexis.urenGewerkt + " uur "); */ System.out.println(alex.voornaam + " betaalt " + alex.getRSZ() + " % RSZ "); System.out.println(dieter.voornaam + " betaalt " + dieter.getRSZ() + " % RSZ "); } }
MTA-Digital-Broadcast-2/V-Clauwaert-Dieter-Boons-Jonah-Project-MHP
Dieter Clauwaert/Oefeningen Java/Labojava/blz31/Oef6/Main.java
590
/* dieter.salarisVerhogen(10); jasper.salarisVerhogen(10); mats.salarisVerhogen(10); jonah.salarisVerhogen(10); System.out.println(dieter.voornaam + " verdient " + dieter.getsalaris()); System.out.println(jasper.voornaam + " verdient " + jasper.getsalaris()); System.out.println(mats.voornaam + " verdient " + mats.getsalaris()); System.out.println(jonah.voornaam + " verdient " + jonah.getsalaris()); alex.salarisVerhogen(4); alexis.salarisVerhogen(4); System.out.println(alex.voornaam + " verdient " + alex.getsalaris() + " en werkt " + alex.urenGewerkt + " uur "); System.out.println(alexis.voornaam + " verdient " + alexis.getsalaris() + " en werkt " + alexis.urenGewerkt + " uur "); */
block_comment
nl
public class Main { public static void main(String args[]) { Werknemer dieter = new Werknemer("Dieter", "Clauwaert", 1, 1000); Werknemer jasper = new Werknemer("Jasper", "Cludts", 2, 2000); Werknemer mats = new Werknemer("Mats", "Kennes", 3, 3000); Werknemer jonah = new Werknemer("Jonah", "Boons", 4, 4000); PartTimeWerknemer alex = new PartTimeWerknemer("Alex", "Spildooren", 5, 5000, 5); PartTimeWerknemer alexis = new PartTimeWerknemer("Alexis", "Guiette", 6, 6000, 6); /* dieter.salarisVerhogen(10); <SUF>*/ System.out.println(alex.voornaam + " betaalt " + alex.getRSZ() + " % RSZ "); System.out.println(dieter.voornaam + " betaalt " + dieter.getRSZ() + " % RSZ "); } }
False
519
255
602
294
538
269
602
294
626
314
true
true
true
true
true
false
2,549
10808_8
/* Copyright Alexander Drechsel 2012 * Copyright Niels Kamp 2012 * Copyright Kasper Vaessen 2012 * Copyright Niels Visser 2012 * * This file is part of MusicTable. * * MusicTable 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. * * MusicTable 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 MusicTable. If not, see <http://www.gnu.org/licenses/>. */ package playback; import GUI.ParticlePanel; //import GUI.VisualizationPanel; import java.util.ArrayList; import java.util.List; import javax.sound.midi.Instrument; import javax.sound.midi.MidiChannel; /** * * @param <syncronized> */ public class ToneGrid { protected List<List<Boolean>> grid; protected int width; protected int height; protected boolean isActive; protected GridConfiguration gc; public ToneGrid(GridConfiguration gc) { this.height = 10; this.gc = gc; } /** * Wisselt de status van een gegeven noot van actief naar inactief or van inactief naar actief. * @param column welke kolom de noot aan behoord * @param note welke rij de noot aan behoord */ public void toggleTone(int column, int note) { List<Boolean> col = this.grid.get(column); synchronized (col) { col.set(note, !col.get(note)); } } /** * Wisselt de status van een gegeven noot naar actief of doet niets als de noot al actief is. * @param column welke kolom de noot aan behoord * @param note welke rij de noot aan behoord */ public void activateTone(int column, int note) { List<Boolean> col = this.grid.get(column); synchronized (col) { col.set(note, true); } } /** * Wisselt de status van een gegeven noot naar inactief of doet niets als de noot al inactief is. * @param column welke kolom de noot aan behoord * @param note welke rij de noot aan behoord */ public void deactivateTone(int column, int note) { List<Boolean> col = this.grid.get(column); synchronized (col) { col.set(note, false); } } /** * Geeft de lijst van alle noten in de vorm van een lijst van kolomen met daarin de rijen. * @return */ public synchronized List<List<Boolean>> getAllTones() { List<List<Boolean>> result = new ArrayList<List<Boolean>>(); for (int i = 0; i < this.width; i++) { List<Boolean> el = new ArrayList<Boolean>(); result.add(el); for (int j = 0; j < this.height; j++) { el.add(this.grid.get(i).get(j)); } } return result; } /** * Geeft de status van een gegeven noot. * @param column welke kolom de noot aan behoord * @param note welke rij de noot aan behoord * @return true==actief;inactief==false */ public boolean getTone(int column, int note) { synchronized (this.grid) { return this.grid.get(column).get(note); } } /** * Delegeert aan gridconfig * @param column * @param vp */ public void playColumnTones(int column, ParticlePanel vp) { List<Integer> tones = this.getColumnTones(column); this.gc.playTones(tones, vp); } public List<Integer> getColumnTones(int x) { List<Boolean> notesArray = this.grid.get(x); List<Integer> notesList = new ArrayList<Integer>(); for(int i=0; i<notesArray.size(); i++) { if(notesArray.get(i)) notesList.add(i); } return notesList; } public void setConfiguration(GridConfiguration gc) { this.gc = gc; } public GridConfiguration getGridConfiguration() { return gc; } public boolean isIsActive() { return isActive; } public void setIsActive(boolean isActive) { this.isActive = isActive; } /** * Tweede gedeelte van de registratie methode. * Registreerd het aantal kolomen en initaliseerd de dubbele lijst van noten die allemaal inactief zijn. * Het grid is na deze methode inactief. * @param w aantal kolomen de ToneGrid heeft */ public void registerCallBack(int w) { this.width = w; this.grid = new ArrayList<List<Boolean>>(); for (int i = 0; i < w; i++) { List<Boolean> el = new ArrayList<Boolean>(); this.grid.add(el); for (int j = 0; j < height; j++) { el.add(false); } } this.isActive = false; } /** * Zet alle noten op inactief. */ public void clear() { for(List<Boolean> l1 : this.grid) { for(int i = 0; i < l1.size(); i++) { l1.set(i, false); } } } }
diddle/UED
code/src/playback/ToneGrid.java
1,665
/** * Tweede gedeelte van de registratie methode. * Registreerd het aantal kolomen en initaliseerd de dubbele lijst van noten die allemaal inactief zijn. * Het grid is na deze methode inactief. * @param w aantal kolomen de ToneGrid heeft */
block_comment
nl
/* Copyright Alexander Drechsel 2012 * Copyright Niels Kamp 2012 * Copyright Kasper Vaessen 2012 * Copyright Niels Visser 2012 * * This file is part of MusicTable. * * MusicTable 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. * * MusicTable 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 MusicTable. If not, see <http://www.gnu.org/licenses/>. */ package playback; import GUI.ParticlePanel; //import GUI.VisualizationPanel; import java.util.ArrayList; import java.util.List; import javax.sound.midi.Instrument; import javax.sound.midi.MidiChannel; /** * * @param <syncronized> */ public class ToneGrid { protected List<List<Boolean>> grid; protected int width; protected int height; protected boolean isActive; protected GridConfiguration gc; public ToneGrid(GridConfiguration gc) { this.height = 10; this.gc = gc; } /** * Wisselt de status van een gegeven noot van actief naar inactief or van inactief naar actief. * @param column welke kolom de noot aan behoord * @param note welke rij de noot aan behoord */ public void toggleTone(int column, int note) { List<Boolean> col = this.grid.get(column); synchronized (col) { col.set(note, !col.get(note)); } } /** * Wisselt de status van een gegeven noot naar actief of doet niets als de noot al actief is. * @param column welke kolom de noot aan behoord * @param note welke rij de noot aan behoord */ public void activateTone(int column, int note) { List<Boolean> col = this.grid.get(column); synchronized (col) { col.set(note, true); } } /** * Wisselt de status van een gegeven noot naar inactief of doet niets als de noot al inactief is. * @param column welke kolom de noot aan behoord * @param note welke rij de noot aan behoord */ public void deactivateTone(int column, int note) { List<Boolean> col = this.grid.get(column); synchronized (col) { col.set(note, false); } } /** * Geeft de lijst van alle noten in de vorm van een lijst van kolomen met daarin de rijen. * @return */ public synchronized List<List<Boolean>> getAllTones() { List<List<Boolean>> result = new ArrayList<List<Boolean>>(); for (int i = 0; i < this.width; i++) { List<Boolean> el = new ArrayList<Boolean>(); result.add(el); for (int j = 0; j < this.height; j++) { el.add(this.grid.get(i).get(j)); } } return result; } /** * Geeft de status van een gegeven noot. * @param column welke kolom de noot aan behoord * @param note welke rij de noot aan behoord * @return true==actief;inactief==false */ public boolean getTone(int column, int note) { synchronized (this.grid) { return this.grid.get(column).get(note); } } /** * Delegeert aan gridconfig * @param column * @param vp */ public void playColumnTones(int column, ParticlePanel vp) { List<Integer> tones = this.getColumnTones(column); this.gc.playTones(tones, vp); } public List<Integer> getColumnTones(int x) { List<Boolean> notesArray = this.grid.get(x); List<Integer> notesList = new ArrayList<Integer>(); for(int i=0; i<notesArray.size(); i++) { if(notesArray.get(i)) notesList.add(i); } return notesList; } public void setConfiguration(GridConfiguration gc) { this.gc = gc; } public GridConfiguration getGridConfiguration() { return gc; } public boolean isIsActive() { return isActive; } public void setIsActive(boolean isActive) { this.isActive = isActive; } /** * Tweede gedeelte van<SUF>*/ public void registerCallBack(int w) { this.width = w; this.grid = new ArrayList<List<Boolean>>(); for (int i = 0; i < w; i++) { List<Boolean> el = new ArrayList<Boolean>(); this.grid.add(el); for (int j = 0; j < height; j++) { el.add(false); } } this.isActive = false; } /** * Zet alle noten op inactief. */ public void clear() { for(List<Boolean> l1 : this.grid) { for(int i = 0; i < l1.size(); i++) { l1.set(i, false); } } } }
True
1,321
76
1,465
85
1,528
68
1,465
85
1,672
82
false
false
false
false
false
true
551
70437_4
package nl.han.ise.DAO; import nl.han.ise.ConnectionFactory; import redis.clients.jedis.Jedis; import java.sql.*; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; public class RapportageDAO { private ConnectionFactory connectionFactory; private Jedis jedis; private Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); public RapportageDAO(){ connectionFactory = new ConnectionFactory(); jedis = new Jedis(connectionFactory.getRedisHost()); } //Vraagt de opgevraagde rapportage op via REDIS public String getRapportage(String rapportage){ String rapportageJson = jedis.get(rapportage); jedis.close(); return rapportageJson; } //Leegt de Redis database en vult hem opnieuw in vanuit de SQL database. public void addAndUpdateAllRapportages(){ logger.log(Level.INFO, "redis geupdated op " + DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss").format(LocalDateTime.now())); jedis.flushAll(); List<String> lijstRapportages = lijstRapportagesSql(); for(int i = 0; i <= lijstRapportages.size()-1; i++){ addOrUpdateRapportage(lijstRapportages.get(i)); } jedis.close(); } //Functie om een rapportage toe te voegen of te wijzigen public void addOrUpdateRapportage(String rapportage){ try (Connection connection = connectionFactory.getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT (SELECT * FROM "+rapportage+" FOR JSON AUTO) AS Rapportage")) { ResultSet resultSet = statement.executeQuery(); if(resultSet.next()){ if(resultSet.getString("Rapportage") != null){ jedis.set(rapportage, resultSet.getString("Rapportage")); } } } catch (SQLException e) { logger.log(Level.SEVERE, "SQL EXCEPTION BIJ OPHALEN VAN RAPPORTAGES", e); throw new RuntimeException(e); } } //Functie om een lijst van rapportages op te halen van Jedis. public List<String> lijstRapportagesRedis(){ List<String> rapportageLijst = new ArrayList<>(); Set<String> keys = jedis.keys("RAPPORTAGE_*"); for (String key : keys) { rapportageLijst.add(key); } java.util.Collections.sort(rapportageLijst); jedis.close(); return rapportageLijst; } //Functie om een lijst van rapportages op te halen van SQL. public List<String> lijstRapportagesSql() { List<String> rapportageLijst = new ArrayList<>(); try (Connection connection = connectionFactory.getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT name FROM sys.views WHERE name LIKE 'RAPPORTAGE_%'")) { ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { rapportageLijst.add(resultSet.getString("name")); } return rapportageLijst; } catch (SQLException e) { logger.log(Level.SEVERE, "SQL EXCEPTION BIJ OPHALEN LIJST VAN RAPPORTAGES", e); throw new RuntimeException(e); } } }
GGWPs/Filmcheques_API
filmcheques_API/src/main/java/nl/han/ise/DAO/RapportageDAO.java
1,014
//Functie om een lijst van rapportages op te halen van SQL.
line_comment
nl
package nl.han.ise.DAO; import nl.han.ise.ConnectionFactory; import redis.clients.jedis.Jedis; import java.sql.*; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; public class RapportageDAO { private ConnectionFactory connectionFactory; private Jedis jedis; private Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); public RapportageDAO(){ connectionFactory = new ConnectionFactory(); jedis = new Jedis(connectionFactory.getRedisHost()); } //Vraagt de opgevraagde rapportage op via REDIS public String getRapportage(String rapportage){ String rapportageJson = jedis.get(rapportage); jedis.close(); return rapportageJson; } //Leegt de Redis database en vult hem opnieuw in vanuit de SQL database. public void addAndUpdateAllRapportages(){ logger.log(Level.INFO, "redis geupdated op " + DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss").format(LocalDateTime.now())); jedis.flushAll(); List<String> lijstRapportages = lijstRapportagesSql(); for(int i = 0; i <= lijstRapportages.size()-1; i++){ addOrUpdateRapportage(lijstRapportages.get(i)); } jedis.close(); } //Functie om een rapportage toe te voegen of te wijzigen public void addOrUpdateRapportage(String rapportage){ try (Connection connection = connectionFactory.getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT (SELECT * FROM "+rapportage+" FOR JSON AUTO) AS Rapportage")) { ResultSet resultSet = statement.executeQuery(); if(resultSet.next()){ if(resultSet.getString("Rapportage") != null){ jedis.set(rapportage, resultSet.getString("Rapportage")); } } } catch (SQLException e) { logger.log(Level.SEVERE, "SQL EXCEPTION BIJ OPHALEN VAN RAPPORTAGES", e); throw new RuntimeException(e); } } //Functie om een lijst van rapportages op te halen van Jedis. public List<String> lijstRapportagesRedis(){ List<String> rapportageLijst = new ArrayList<>(); Set<String> keys = jedis.keys("RAPPORTAGE_*"); for (String key : keys) { rapportageLijst.add(key); } java.util.Collections.sort(rapportageLijst); jedis.close(); return rapportageLijst; } //Functie om<SUF> public List<String> lijstRapportagesSql() { List<String> rapportageLijst = new ArrayList<>(); try (Connection connection = connectionFactory.getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT name FROM sys.views WHERE name LIKE 'RAPPORTAGE_%'")) { ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { rapportageLijst.add(resultSet.getString("name")); } return rapportageLijst; } catch (SQLException e) { logger.log(Level.SEVERE, "SQL EXCEPTION BIJ OPHALEN LIJST VAN RAPPORTAGES", e); throw new RuntimeException(e); } } }
True
741
18
855
18
852
16
855
18
993
18
false
false
false
false
false
true
3,017
14615_8
package nl.atd.model; import java.util.Calendar; /** * Auto data object * * @author ATD Developers * */ public class Auto { private String merk; private String model; private int bouwjaar; private Calendar laatsteBeurt; private String kenteken; public Auto(String mk, String ml, int bj, Calendar lb) { this.merk = mk; this.model = ml; this.bouwjaar = bj; this.kenteken = ""; this.laatsteBeurt = lb; } /** * Is laatste beurt na 6 maanden geweest? * * @return na 6 maanden? */ public boolean isLaatsteBeurtRedelijk() { if(this.laatsteBeurt == null) return false; Calendar streef = Calendar.getInstance(); Calendar lb = (Calendar)laatsteBeurt.clone(); if(lb == null) return false; streef.add(Calendar.MONTH, -6); return !lb.before(streef); } /** * Get merk * * @return merk */ public String getMerk() { return merk; } /** * Get model * * @return model */ public String getModel() { return model; } /** * Get bouwjaar * * @return bouwjaar */ public int getBouwjaar() { return bouwjaar; } /** * Get laatste beurt datum * * @return Datum van laatste beurt */ public Calendar getLaatsteBeurt() { return laatsteBeurt; } /** * Set laatste beurt datum * * @param cal nieuwe datum */ public void setLaatsteBeurt(Calendar cal) { this.laatsteBeurt = cal; } /** * Get Kenteken van auto * * @return Kenteken */ public String getKenteken() { return this.kenteken; } /** * Set Kenteken van auto * * @param Nieuw * kenteken */ public void setKenteken(String nieuwKent) { this.kenteken = nieuwKent; } @Override public String toString() { return merk + " " + model; } @Override public boolean equals(Object ander) { boolean b; if (ander instanceof Auto) { b = true; } else { b = false; } b = b && (this.merk.equals(((Auto) ander).getMerk())); b = b && (this.model.equals(((Auto) ander).getModel())); b = b && (this.bouwjaar == ((Auto) ander).getBouwjaar()); b = b && (this.kenteken.equals(((Auto) ander).getKenteken())); // Calendar vergelijken, DAY.OF.YEAR - YEAR - HOURS : MINUTES b = b && ((this.laatsteBeurt == null && ((Auto)ander).getLaatsteBeurt() == null) || ((this.laatsteBeurt).get(Calendar.YEAR) == ((Auto)ander).getLaatsteBeurt().get(Calendar.YEAR) && (this.laatsteBeurt).get(Calendar.HOUR_OF_DAY) == ((Auto)ander).getLaatsteBeurt().get(Calendar.HOUR_OF_DAY) && (this.laatsteBeurt).get(Calendar.MINUTE) == ((Auto)ander).getLaatsteBeurt().get(Calendar.MINUTE))); return b; } }
hu-team/atd-garagesysteem
src/nl/atd/model/Auto.java
1,041
/** * Set Kenteken van auto * * @param Nieuw * kenteken */
block_comment
nl
package nl.atd.model; import java.util.Calendar; /** * Auto data object * * @author ATD Developers * */ public class Auto { private String merk; private String model; private int bouwjaar; private Calendar laatsteBeurt; private String kenteken; public Auto(String mk, String ml, int bj, Calendar lb) { this.merk = mk; this.model = ml; this.bouwjaar = bj; this.kenteken = ""; this.laatsteBeurt = lb; } /** * Is laatste beurt na 6 maanden geweest? * * @return na 6 maanden? */ public boolean isLaatsteBeurtRedelijk() { if(this.laatsteBeurt == null) return false; Calendar streef = Calendar.getInstance(); Calendar lb = (Calendar)laatsteBeurt.clone(); if(lb == null) return false; streef.add(Calendar.MONTH, -6); return !lb.before(streef); } /** * Get merk * * @return merk */ public String getMerk() { return merk; } /** * Get model * * @return model */ public String getModel() { return model; } /** * Get bouwjaar * * @return bouwjaar */ public int getBouwjaar() { return bouwjaar; } /** * Get laatste beurt datum * * @return Datum van laatste beurt */ public Calendar getLaatsteBeurt() { return laatsteBeurt; } /** * Set laatste beurt datum * * @param cal nieuwe datum */ public void setLaatsteBeurt(Calendar cal) { this.laatsteBeurt = cal; } /** * Get Kenteken van auto * * @return Kenteken */ public String getKenteken() { return this.kenteken; } /** * Set Kenteken van<SUF>*/ public void setKenteken(String nieuwKent) { this.kenteken = nieuwKent; } @Override public String toString() { return merk + " " + model; } @Override public boolean equals(Object ander) { boolean b; if (ander instanceof Auto) { b = true; } else { b = false; } b = b && (this.merk.equals(((Auto) ander).getMerk())); b = b && (this.model.equals(((Auto) ander).getModel())); b = b && (this.bouwjaar == ((Auto) ander).getBouwjaar()); b = b && (this.kenteken.equals(((Auto) ander).getKenteken())); // Calendar vergelijken, DAY.OF.YEAR - YEAR - HOURS : MINUTES b = b && ((this.laatsteBeurt == null && ((Auto)ander).getLaatsteBeurt() == null) || ((this.laatsteBeurt).get(Calendar.YEAR) == ((Auto)ander).getLaatsteBeurt().get(Calendar.YEAR) && (this.laatsteBeurt).get(Calendar.HOUR_OF_DAY) == ((Auto)ander).getLaatsteBeurt().get(Calendar.HOUR_OF_DAY) && (this.laatsteBeurt).get(Calendar.MINUTE) == ((Auto)ander).getLaatsteBeurt().get(Calendar.MINUTE))); return b; } }
True
829
29
965
26
935
30
965
26
1,091
30
false
false
false
false
false
true
1,087
103882_3
package mazestormer.barcode.action; import static com.google.common.base.Preconditions.checkNotNull; import mazestormer.player.Player; import mazestormer.robot.ControllableRobot; import mazestormer.robot.Pilot; import mazestormer.state.State; import mazestormer.state.StateMachine; import mazestormer.util.Future; public class DriveOverSeesawAction extends StateMachine<DriveOverSeesawAction, DriveOverSeesawAction.SeesawState> implements IAction { private Player player; @Override public Future<?> performAction(Player player) { checkNotNull(player); this.player = player; stop(); // indien nog niet gestopt. // Resolve when finished FinishFuture future = new FinishFuture(); addStateListener(future); // Start from the initial state start(); transition(SeesawState.ONWARDS); return future; } private ControllableRobot getControllableRobot() { return (ControllableRobot) player.getRobot(); } private Pilot getPilot() { return getControllableRobot().getPilot(); } /** * <ol> * <li>rijd vooruit tot aan een bruin-zwart overgang (van de barcode aan de * andere kant van de wip)</li> * <li>informatie over wip aan het ontdekte doolhof toevoegen</li> * <li>rijd vooruit tot 20 cm over een witte lijn (= eerste bruin-wit * overgang)</li> * <li>verwijder eventueel tegels uit de queue</li> * </ol> * * @pre robot staat voor de wip aan de neergelaten kant, hij kijkt naar de * wip * @post robot staat op een tegel achter de tegel achter de wip, in het * midden, en kijkt weg van de wip (tegel achter de wip bevat een * andere barcode). alle informatie over de gepasseerde tegels staat * in de observedMaze. de eerste tegel, de tegels van de wip en de * tegel na de wip staan niet meer in de queue */ protected void onwards() { bindTransition(getPilot().travelComplete(122), // TODO 122 juist? SeesawState.RESUME_EXPLORING); } protected void resumeExploring() { finish(); } public enum SeesawState implements State<DriveOverSeesawAction, DriveOverSeesawAction.SeesawState> { ONWARDS { @Override public void execute(DriveOverSeesawAction input) { input.onwards(); } }, RESUME_EXPLORING { @Override public void execute(DriveOverSeesawAction input) { input.resumeExploring(); } }; } private class FinishFuture extends StateMachine.FinishFuture<SeesawState> { @Override public boolean isFinished() { return true; } } }
MattiasBuelens/MazeStormer
MazeStormer-PC/src/mazestormer/barcode/action/DriveOverSeesawAction.java
832
/** * <ol> * <li>rijd vooruit tot aan een bruin-zwart overgang (van de barcode aan de * andere kant van de wip)</li> * <li>informatie over wip aan het ontdekte doolhof toevoegen</li> * <li>rijd vooruit tot 20 cm over een witte lijn (= eerste bruin-wit * overgang)</li> * <li>verwijder eventueel tegels uit de queue</li> * </ol> * * @pre robot staat voor de wip aan de neergelaten kant, hij kijkt naar de * wip * @post robot staat op een tegel achter de tegel achter de wip, in het * midden, en kijkt weg van de wip (tegel achter de wip bevat een * andere barcode). alle informatie over de gepasseerde tegels staat * in de observedMaze. de eerste tegel, de tegels van de wip en de * tegel na de wip staan niet meer in de queue */
block_comment
nl
package mazestormer.barcode.action; import static com.google.common.base.Preconditions.checkNotNull; import mazestormer.player.Player; import mazestormer.robot.ControllableRobot; import mazestormer.robot.Pilot; import mazestormer.state.State; import mazestormer.state.StateMachine; import mazestormer.util.Future; public class DriveOverSeesawAction extends StateMachine<DriveOverSeesawAction, DriveOverSeesawAction.SeesawState> implements IAction { private Player player; @Override public Future<?> performAction(Player player) { checkNotNull(player); this.player = player; stop(); // indien nog niet gestopt. // Resolve when finished FinishFuture future = new FinishFuture(); addStateListener(future); // Start from the initial state start(); transition(SeesawState.ONWARDS); return future; } private ControllableRobot getControllableRobot() { return (ControllableRobot) player.getRobot(); } private Pilot getPilot() { return getControllableRobot().getPilot(); } /** * <ol> <SUF>*/ protected void onwards() { bindTransition(getPilot().travelComplete(122), // TODO 122 juist? SeesawState.RESUME_EXPLORING); } protected void resumeExploring() { finish(); } public enum SeesawState implements State<DriveOverSeesawAction, DriveOverSeesawAction.SeesawState> { ONWARDS { @Override public void execute(DriveOverSeesawAction input) { input.onwards(); } }, RESUME_EXPLORING { @Override public void execute(DriveOverSeesawAction input) { input.resumeExploring(); } }; } private class FinishFuture extends StateMachine.FinishFuture<SeesawState> { @Override public boolean isFinished() { return true; } } }
False
714
269
810
280
747
254
810
280
930
291
true
true
true
true
true
false
3,472
183748_10
package com.hva.tsse.juniorleraar.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.hva.tsse.juniorleraar.R; import com.hva.tsse.juniorleraar.model.DialogueCard; import java.util.List; /** * Created by Melanie on 21-2-2018. */ public class DialogueCardAdapter extends BaseAdapter { private Context context; private List<DialogueCard> mDialogueCards; public DialogueCardAdapter() { super(); } public DialogueCardAdapter(Context context, List<DialogueCard> mDialogueCards) { this.context = context; this.mDialogueCards = mDialogueCards; } /** * @return The amount of cards in the list */ @Override public int getCount() { return mDialogueCards.size(); } /** * @param position The position of the card in the list * @return The card at the position */ @Override public DialogueCard getItem(int position) { return mDialogueCards.get(position); } /** * @param position The position of the card in the list * @return Id of the card is the position */ @Override public long getItemId(int position) { return position; } /** * This method will devide the headers and listitems in the list. If header the item must look differently * When item * * @param position The position of the card * @param view view * @param viewGroup viewgroup * @return */ @Override public View getView(int position, View view, ViewGroup viewGroup) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); // The item in the list is an header when // matches a digit and a point and after a space or a 1. // the card must be the same as the card after otherwise it isn't a header // for that there must be a check that the card is not the last one if (mDialogueCards.get(position).getTitle().matches("\\d\\.(\\s|1).*") && position + 1 < mDialogueCards.size() && mDialogueCards.get(position).getTitle() == mDialogueCards.get(position + 1).getTitle()) { // if section header view = inflater.inflate(R.layout.list_section_item, viewGroup, false); TextView item_section_title = (TextView) view.findViewById(R.id.list_item_section_title); item_section_title.setText((mDialogueCards.get(position)).getCompetence()); view.setOnClickListener(null); setBackgroundColor(item_section_title, true, mDialogueCards.get(position).getTheme()); } else { // if item view = inflater.inflate(R.layout.list_item, viewGroup, false); TextView item_title = (TextView) view.findViewById(R.id.list_item_title); item_title.setText((mDialogueCards.get(position)).getTitle()); setBackgroundColor(item_title, false, mDialogueCards.get(position).getTheme()); } return view; } private void setBackgroundColor(TextView text, boolean title, String theme){ if (title) { switch (theme){ case "Didactisch Bekwaam": text.setBackgroundColor(context.getResources().getColor(R.color.colorDidAccent)); break; case "Collegiale Samenwerking": text.setBackgroundColor(context.getResources().getColor(R.color.colorCollAccent)); break; case "Pedagogisch Bekwaam": text.setBackgroundColor(context.getResources().getColor(R.color.colorPedAccent)); break; } } else { switch (theme){ case "Didactisch Bekwaam": text.setBackgroundColor(context.getResources().getColor(R.color.colorDid60)); break; case "Collegiale Samenwerking": text.setBackgroundColor(context.getResources().getColor(R.color.colorColl60)); break; case "Pedagogisch Bekwaam": text.setBackgroundColor(context.getResources().getColor(R.color.colorPed60)); break; } } // switch (theme){ // case "Didactisch Bekwaam": // context.setTheme(context.getResources(R.style.Dida)); // break; // case "Collegiale Samenwerking": // context.setTheme(context.getResources(R.style.Coll)); // break; // case "Pedagogisch Bekwaam": // context.setTheme(context.getResources(R.style.Peda)); // break; // } } }
lifelynl/JuniorLeraar
app/src/main/java/com/hva/tsse/juniorleraar/adapter/DialogueCardAdapter.java
1,388
// case "Didactisch Bekwaam":
line_comment
nl
package com.hva.tsse.juniorleraar.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.hva.tsse.juniorleraar.R; import com.hva.tsse.juniorleraar.model.DialogueCard; import java.util.List; /** * Created by Melanie on 21-2-2018. */ public class DialogueCardAdapter extends BaseAdapter { private Context context; private List<DialogueCard> mDialogueCards; public DialogueCardAdapter() { super(); } public DialogueCardAdapter(Context context, List<DialogueCard> mDialogueCards) { this.context = context; this.mDialogueCards = mDialogueCards; } /** * @return The amount of cards in the list */ @Override public int getCount() { return mDialogueCards.size(); } /** * @param position The position of the card in the list * @return The card at the position */ @Override public DialogueCard getItem(int position) { return mDialogueCards.get(position); } /** * @param position The position of the card in the list * @return Id of the card is the position */ @Override public long getItemId(int position) { return position; } /** * This method will devide the headers and listitems in the list. If header the item must look differently * When item * * @param position The position of the card * @param view view * @param viewGroup viewgroup * @return */ @Override public View getView(int position, View view, ViewGroup viewGroup) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); // The item in the list is an header when // matches a digit and a point and after a space or a 1. // the card must be the same as the card after otherwise it isn't a header // for that there must be a check that the card is not the last one if (mDialogueCards.get(position).getTitle().matches("\\d\\.(\\s|1).*") && position + 1 < mDialogueCards.size() && mDialogueCards.get(position).getTitle() == mDialogueCards.get(position + 1).getTitle()) { // if section header view = inflater.inflate(R.layout.list_section_item, viewGroup, false); TextView item_section_title = (TextView) view.findViewById(R.id.list_item_section_title); item_section_title.setText((mDialogueCards.get(position)).getCompetence()); view.setOnClickListener(null); setBackgroundColor(item_section_title, true, mDialogueCards.get(position).getTheme()); } else { // if item view = inflater.inflate(R.layout.list_item, viewGroup, false); TextView item_title = (TextView) view.findViewById(R.id.list_item_title); item_title.setText((mDialogueCards.get(position)).getTitle()); setBackgroundColor(item_title, false, mDialogueCards.get(position).getTheme()); } return view; } private void setBackgroundColor(TextView text, boolean title, String theme){ if (title) { switch (theme){ case "Didactisch Bekwaam": text.setBackgroundColor(context.getResources().getColor(R.color.colorDidAccent)); break; case "Collegiale Samenwerking": text.setBackgroundColor(context.getResources().getColor(R.color.colorCollAccent)); break; case "Pedagogisch Bekwaam": text.setBackgroundColor(context.getResources().getColor(R.color.colorPedAccent)); break; } } else { switch (theme){ case "Didactisch Bekwaam": text.setBackgroundColor(context.getResources().getColor(R.color.colorDid60)); break; case "Collegiale Samenwerking": text.setBackgroundColor(context.getResources().getColor(R.color.colorColl60)); break; case "Pedagogisch Bekwaam": text.setBackgroundColor(context.getResources().getColor(R.color.colorPed60)); break; } } // switch (theme){ // case "Didactisch<SUF> // context.setTheme(context.getResources(R.style.Dida)); // break; // case "Collegiale Samenwerking": // context.setTheme(context.getResources(R.style.Coll)); // break; // case "Pedagogisch Bekwaam": // context.setTheme(context.getResources(R.style.Peda)); // break; // } } }
False
984
11
1,186
12
1,221
11
1,186
12
1,363
11
false
false
false
false
false
true
382
38772_0
package Facade; public class TestBankAccount { public static void main(String[] args) { //nieuwe facade maken en bank account nr 123456 gebruiken met code 1234 BankAccountFacade accessingBank = new BankAccountFacade(123456, 1234); accessingBank.withDrawCash(50.00); accessingBank.withDrawCash(900.00); accessingBank.depositCash(200.00); accessingBank.depositCash(150.00); } }
DalderupMaurice/Facade_Pattern_Demo
src/Facade/TestBankAccount.java
143
//nieuwe facade maken en bank account nr 123456 gebruiken met code 1234
line_comment
nl
package Facade; public class TestBankAccount { public static void main(String[] args) { //nieuwe facade<SUF> BankAccountFacade accessingBank = new BankAccountFacade(123456, 1234); accessingBank.withDrawCash(50.00); accessingBank.withDrawCash(900.00); accessingBank.depositCash(200.00); accessingBank.depositCash(150.00); } }
True
143
26
149
29
150
24
149
29
187
27
false
false
false
false
false
true
4,471
109118_5
package de._13ducks.spacebatz.server.gamelogic; import de._13ducks.spacebatz.server.data.Client; import de._13ducks.spacebatz.server.data.quests.Quest; import de._13ducks.spacebatz.shared.network.messages.STC.STC_NEW_QUEST; import de._13ducks.spacebatz.shared.network.messages.STC.STC_QUEST_RESULT; import java.util.ArrayList; import java.util.Iterator; /** * Verwaltet die Quests. * * @author Tobias Fleig <[email protected]> */ public class QuestManager { /** * Alle aktiven Quests. */ private ArrayList<Quest> activeQuests = new ArrayList<>(); /** * Quests, die im nächsten Tick hinzugefügt werden. * Notwendig, sonst funktioniert der Iterator in tick() nicht sauber, wenn neue Quests von alten Quests eingefügt werden. */ private ArrayList<Quest> newQuests = new ArrayList<>(); /** * Muss ein Mal pro Tick aufgerufen werden, tickt alle aktiven Quests. */ public void tick() { // Neue Quests hinzufügen activeQuests.addAll(newQuests); for (Quest q : newQuests) { // An Client senden if (!q.isHidden()) { STC_NEW_QUEST.sendQuest(q); } } newQuests.clear(); Iterator<Quest> iter = activeQuests.iterator(); while (iter.hasNext()) { Quest quest = iter.next(); try { // Quest ticken, dann Status abfragen quest.tick(); int state = quest.check(); // Bei -1 wurde das Statusberechnen verschoben, das wird nur ein Mal pro Tick gemacht if (state != -1) { if (state == Quest.STATE_RUNNING) { // Nichts spannendes, weiterlaufen lassen continue; } if (state == Quest.STATE_COMPLETED) { // Erfolgreich //@TODO: Belohnung verteilen? System.out.println("[INFO][QuestManager]: Quest " + quest.getName() + " completed."); } else if (state == Quest.STATE_FAILED) { System.out.println("[INFO][QuestManager]: Quest " + quest.getName() + " failed."); } else if (state == Quest.STATE_ABORTED) { System.out.println("[WARNING][QuestManager]: Quest " + quest.getName() + " was aborted for unknown reasons..."); } // Jeder der drei Zustände bedeutet, dass der Quest in Zukunft nichtmehr laufen muss iter.remove(); // Client quest entfernen lassen STC_QUEST_RESULT.sendQuestResult(quest.questID, (byte) state); } } catch (Exception ex) { // Quest ist abgestürzt - Loggen und Quest löschen iter.remove(); System.out.println("[ERROR][QuestManager]: Quest " + quest.getName() + " crashed and has been deleted. Exception:"); ex.printStackTrace(); } } } /** * Fügt einen neuen Quest hinzu. * Es ist sicher, diese Methode während der Bearbeitung eines anderen Quests aufzurufen. * * @param quest der neue Quest, läuft ab dem nächsten Tick mit */ public void addQuest(Quest quest) { newQuests.add(quest); } /** * Aufrufen, wenn ein neuer Client eingefügt wurde. * Sendet alle aktiven, nicht geheimen Quests an den neuen. * * @param client */ void newClient(Client client) { for (Quest quest : activeQuests) { if (!quest.isHidden()) { STC_NEW_QUEST.sendQuest(quest); } } } }
tfg13/spacebatz
src/de/_13ducks/spacebatz/server/gamelogic/QuestManager.java
1,107
// An Client senden
line_comment
nl
package de._13ducks.spacebatz.server.gamelogic; import de._13ducks.spacebatz.server.data.Client; import de._13ducks.spacebatz.server.data.quests.Quest; import de._13ducks.spacebatz.shared.network.messages.STC.STC_NEW_QUEST; import de._13ducks.spacebatz.shared.network.messages.STC.STC_QUEST_RESULT; import java.util.ArrayList; import java.util.Iterator; /** * Verwaltet die Quests. * * @author Tobias Fleig <[email protected]> */ public class QuestManager { /** * Alle aktiven Quests. */ private ArrayList<Quest> activeQuests = new ArrayList<>(); /** * Quests, die im nächsten Tick hinzugefügt werden. * Notwendig, sonst funktioniert der Iterator in tick() nicht sauber, wenn neue Quests von alten Quests eingefügt werden. */ private ArrayList<Quest> newQuests = new ArrayList<>(); /** * Muss ein Mal pro Tick aufgerufen werden, tickt alle aktiven Quests. */ public void tick() { // Neue Quests hinzufügen activeQuests.addAll(newQuests); for (Quest q : newQuests) { // An Client<SUF> if (!q.isHidden()) { STC_NEW_QUEST.sendQuest(q); } } newQuests.clear(); Iterator<Quest> iter = activeQuests.iterator(); while (iter.hasNext()) { Quest quest = iter.next(); try { // Quest ticken, dann Status abfragen quest.tick(); int state = quest.check(); // Bei -1 wurde das Statusberechnen verschoben, das wird nur ein Mal pro Tick gemacht if (state != -1) { if (state == Quest.STATE_RUNNING) { // Nichts spannendes, weiterlaufen lassen continue; } if (state == Quest.STATE_COMPLETED) { // Erfolgreich //@TODO: Belohnung verteilen? System.out.println("[INFO][QuestManager]: Quest " + quest.getName() + " completed."); } else if (state == Quest.STATE_FAILED) { System.out.println("[INFO][QuestManager]: Quest " + quest.getName() + " failed."); } else if (state == Quest.STATE_ABORTED) { System.out.println("[WARNING][QuestManager]: Quest " + quest.getName() + " was aborted for unknown reasons..."); } // Jeder der drei Zustände bedeutet, dass der Quest in Zukunft nichtmehr laufen muss iter.remove(); // Client quest entfernen lassen STC_QUEST_RESULT.sendQuestResult(quest.questID, (byte) state); } } catch (Exception ex) { // Quest ist abgestürzt - Loggen und Quest löschen iter.remove(); System.out.println("[ERROR][QuestManager]: Quest " + quest.getName() + " crashed and has been deleted. Exception:"); ex.printStackTrace(); } } } /** * Fügt einen neuen Quest hinzu. * Es ist sicher, diese Methode während der Bearbeitung eines anderen Quests aufzurufen. * * @param quest der neue Quest, läuft ab dem nächsten Tick mit */ public void addQuest(Quest quest) { newQuests.add(quest); } /** * Aufrufen, wenn ein neuer Client eingefügt wurde. * Sendet alle aktiven, nicht geheimen Quests an den neuen. * * @param client */ void newClient(Client client) { for (Quest quest : activeQuests) { if (!quest.isHidden()) { STC_NEW_QUEST.sendQuest(quest); } } } }
False
837
5
952
5
913
4
952
5
1,092
5
false
false
false
false
false
true
4,655
127401_1
package com.mybaggage.controllers; import com.jfoenix.controls.JFXButton; import com.mybaggage.Utilities; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.animation.FadeTransition; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.input.KeyEvent; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import javafx.util.Duration; /** * * @author Ludo Bak */ public class AdminController implements Initializable { @FXML private AnchorPane holderPane; @FXML private JFXButton btnHome; @FXML private Button btnLogOut; @FXML private Button btnExit; @FXML private Button btnHelpdesk; @FXML private Button btnBagage; @FXML private Button btnUM; @FXML private Button btnRegistreerSchadevergoeding; @FXML private Button btnBagageZoeken; @FXML private Button btnBagageOverzicht; @FXML private Button btnBagageToevoegen; AnchorPane bagageOverzicht, bagageZoeken, faq, helpdesk, fxml2, inlogscherm, UM, registreerSchadevergoeding; //Zet waarden leeg en maakt nieuwe objecten via classes. Stage dialogStage = new Stage(); Scene scene; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; ResultSet resultSet2 = null; @Override public void initialize(URL url, ResourceBundle rb) { //Load all fxmls in a cache try { bagageOverzicht = FXMLLoader.load(getClass().getResource("BagageOverzicht.fxml")); bagageZoeken = FXMLLoader.load(getClass().getResource("FXML2.fxml")); inlogscherm = FXMLLoader.load(getClass().getResource("Inlogscherm.fxml")); faq = FXMLLoader.load(getClass().getResource("FAQ.fxml")); fxml2 = FXMLLoader.load(getClass().getResource("Rapportage.fxml")); UM = FXMLLoader.load(getClass().getResource("UM.fxml")); helpdesk = FXMLLoader.load(getClass().getResource("HelpdeskAdmin.fxml")); registreerSchadevergoeding = FXMLLoader.load(getClass().getResource("RegistreerSchadevergoeding.fxml")); setNode(fxml2); } catch (IOException ex) { Logger.getLogger(MedewerkerController.class.getName()).log(Level.SEVERE, null, ex); } } @FXML private void logOff(ActionEvent event) throws IOException { Node source = (Node) event.getSource(); dialogStage = (Stage) source.getScene().getWindow(); dialogStage.close(); scene = new Scene((Parent) FXMLLoader.load(getClass().getResource("Inlogscherm.fxml"))); dialogStage.setScene(scene); dialogStage.show(); } @FXML private void exit(ActionEvent event) throws IOException { Stage stage = (Stage) btnExit.getScene().getWindow(); stage.close(); } //Set selected node to a content holder private void setNode(Node node) { holderPane.getChildren().clear(); holderPane.getChildren().add((Node) node); FadeTransition ft = new FadeTransition(Duration.millis(1500)); ft.setNode(node); ft.setFromValue(0.1); ft.setToValue(1); ft.setCycleCount(1); ft.setAutoReverse(false); ft.play(); } /** * Keyboard-shortcuts methode om te navigeren met F-Keys. * * @author Ismail Bahar (500783727) */ @FXML private void keyPressed(KeyEvent event) throws IOException { switch (event.getCode()) { case F2: Utilities.switchSchermNaarFXML("BagageOverzicht.fxml", holderPane); break; case F3: Utilities.switchSchermNaarFXML("GevondenBagageRegistratie.fxml", holderPane); break; case F4: Utilities.switchSchermNaarFXML("RegistreerSchadevergoeding.fxml", holderPane); break; case F5: Utilities.switchSchermNaarFXML("VermisteBagageRegistratie.fxml", holderPane); break; case F6: Utilities.switchSchermNaarFXML("FAQ.fxml", holderPane); break; case F7: Utilities.switchSchermNaarFXML("HelpdeskAdmin.fxml", holderPane); break; case F8: Utilities.switchSchermNaarFXML("UM.fxml", holderPane); break; default: break; } } @FXML private void openHome(ActionEvent event) { setNode(fxml2); } @FXML private void openBagageToevoegen(ActionEvent event) throws IOException { //setNode(bagageToevoegen); Utilities.switchSchermNaarFXML("GevondenBagageRegistratie.fxml", holderPane); } @FXML private void openBagageOverzicht(ActionEvent event) throws IOException { //setNode(bagageOverzicht); Utilities.switchSchermNaarFXML("BagageOverzicht.fxml", holderPane); } @FXML private void openBagageZoeken(ActionEvent event) throws IOException { //setNode(bagageZoeken); Utilities.switchSchermNaarFXML("VermisteBagageRegistratie.fxml", holderPane); } @FXML private void openContact(ActionEvent event) { setNode(faq); } @FXML private void openHelpdesk(ActionEvent event) { setNode(helpdesk); } @FXML private void openUM(ActionEvent event) { setNode(UM); } @FXML private void openRegistreerSchadevergoeding(ActionEvent event) throws IOException { //setNode(registreerSchadevergoeding); Utilities.switchSchermNaarFXML("RegistreerSchadevergoeding.fxml", holderPane); } }
vriesr032/MyBaggage
src/main/java/com/mybaggage/controllers/AdminController.java
1,963
//Zet waarden leeg en maakt nieuwe objecten via classes.
line_comment
nl
package com.mybaggage.controllers; import com.jfoenix.controls.JFXButton; import com.mybaggage.Utilities; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.animation.FadeTransition; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.input.KeyEvent; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import javafx.util.Duration; /** * * @author Ludo Bak */ public class AdminController implements Initializable { @FXML private AnchorPane holderPane; @FXML private JFXButton btnHome; @FXML private Button btnLogOut; @FXML private Button btnExit; @FXML private Button btnHelpdesk; @FXML private Button btnBagage; @FXML private Button btnUM; @FXML private Button btnRegistreerSchadevergoeding; @FXML private Button btnBagageZoeken; @FXML private Button btnBagageOverzicht; @FXML private Button btnBagageToevoegen; AnchorPane bagageOverzicht, bagageZoeken, faq, helpdesk, fxml2, inlogscherm, UM, registreerSchadevergoeding; //Zet waarden<SUF> Stage dialogStage = new Stage(); Scene scene; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; ResultSet resultSet2 = null; @Override public void initialize(URL url, ResourceBundle rb) { //Load all fxmls in a cache try { bagageOverzicht = FXMLLoader.load(getClass().getResource("BagageOverzicht.fxml")); bagageZoeken = FXMLLoader.load(getClass().getResource("FXML2.fxml")); inlogscherm = FXMLLoader.load(getClass().getResource("Inlogscherm.fxml")); faq = FXMLLoader.load(getClass().getResource("FAQ.fxml")); fxml2 = FXMLLoader.load(getClass().getResource("Rapportage.fxml")); UM = FXMLLoader.load(getClass().getResource("UM.fxml")); helpdesk = FXMLLoader.load(getClass().getResource("HelpdeskAdmin.fxml")); registreerSchadevergoeding = FXMLLoader.load(getClass().getResource("RegistreerSchadevergoeding.fxml")); setNode(fxml2); } catch (IOException ex) { Logger.getLogger(MedewerkerController.class.getName()).log(Level.SEVERE, null, ex); } } @FXML private void logOff(ActionEvent event) throws IOException { Node source = (Node) event.getSource(); dialogStage = (Stage) source.getScene().getWindow(); dialogStage.close(); scene = new Scene((Parent) FXMLLoader.load(getClass().getResource("Inlogscherm.fxml"))); dialogStage.setScene(scene); dialogStage.show(); } @FXML private void exit(ActionEvent event) throws IOException { Stage stage = (Stage) btnExit.getScene().getWindow(); stage.close(); } //Set selected node to a content holder private void setNode(Node node) { holderPane.getChildren().clear(); holderPane.getChildren().add((Node) node); FadeTransition ft = new FadeTransition(Duration.millis(1500)); ft.setNode(node); ft.setFromValue(0.1); ft.setToValue(1); ft.setCycleCount(1); ft.setAutoReverse(false); ft.play(); } /** * Keyboard-shortcuts methode om te navigeren met F-Keys. * * @author Ismail Bahar (500783727) */ @FXML private void keyPressed(KeyEvent event) throws IOException { switch (event.getCode()) { case F2: Utilities.switchSchermNaarFXML("BagageOverzicht.fxml", holderPane); break; case F3: Utilities.switchSchermNaarFXML("GevondenBagageRegistratie.fxml", holderPane); break; case F4: Utilities.switchSchermNaarFXML("RegistreerSchadevergoeding.fxml", holderPane); break; case F5: Utilities.switchSchermNaarFXML("VermisteBagageRegistratie.fxml", holderPane); break; case F6: Utilities.switchSchermNaarFXML("FAQ.fxml", holderPane); break; case F7: Utilities.switchSchermNaarFXML("HelpdeskAdmin.fxml", holderPane); break; case F8: Utilities.switchSchermNaarFXML("UM.fxml", holderPane); break; default: break; } } @FXML private void openHome(ActionEvent event) { setNode(fxml2); } @FXML private void openBagageToevoegen(ActionEvent event) throws IOException { //setNode(bagageToevoegen); Utilities.switchSchermNaarFXML("GevondenBagageRegistratie.fxml", holderPane); } @FXML private void openBagageOverzicht(ActionEvent event) throws IOException { //setNode(bagageOverzicht); Utilities.switchSchermNaarFXML("BagageOverzicht.fxml", holderPane); } @FXML private void openBagageZoeken(ActionEvent event) throws IOException { //setNode(bagageZoeken); Utilities.switchSchermNaarFXML("VermisteBagageRegistratie.fxml", holderPane); } @FXML private void openContact(ActionEvent event) { setNode(faq); } @FXML private void openHelpdesk(ActionEvent event) { setNode(helpdesk); } @FXML private void openUM(ActionEvent event) { setNode(UM); } @FXML private void openRegistreerSchadevergoeding(ActionEvent event) throws IOException { //setNode(registreerSchadevergoeding); Utilities.switchSchermNaarFXML("RegistreerSchadevergoeding.fxml", holderPane); } }
True
1,377
16
1,596
18
1,637
14
1,596
18
1,871
16
false
false
false
false
false
true
482
102998_82
/****************************************************************************** * Product: ADempiere ERP & CRM Smart Business Solution * * Copyright (C) 2006-2017 ADempiere Foundation, All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * or (at your option) any later version. * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY, without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program, if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * or via [email protected] or http://www.adempiere.net/license.html * *****************************************************************************/ package org.compiere.model; import java.math.BigDecimal; import java.sql.Timestamp; import org.compiere.util.KeyNamePair; /** Generated Interface for PA_DashboardContent * @author Adempiere (generated) * @version Release 3.9.2 */ public interface I_PA_DashboardContent { /** TableName=PA_DashboardContent */ public static final String Table_Name = "PA_DashboardContent"; /** AD_Table_ID=50010 */ public static final int Table_ID = MTable.getTable_ID(Table_Name); KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name); /** AccessLevel = 6 - System - Client */ BigDecimal accessLevel = BigDecimal.valueOf(6); /** Load Meta Data */ /** Column name AD_Browse_ID */ public static final String COLUMNNAME_AD_Browse_ID = "AD_Browse_ID"; /** Set Smart Browse */ public void setAD_Browse_ID (int AD_Browse_ID); /** Get Smart Browse */ public int getAD_Browse_ID(); public org.adempiere.model.I_AD_Browse getAD_Browse() throws RuntimeException; /** Column name AD_Client_ID */ public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID"; /** Get Client. * Client/Tenant for this installation. */ public int getAD_Client_ID(); /** Column name AD_Org_ID */ public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID"; /** Set Organization. * Organizational entity within client */ public void setAD_Org_ID (int AD_Org_ID); /** Get Organization. * Organizational entity within client */ public int getAD_Org_ID(); /** Column name AD_Window_ID */ public static final String COLUMNNAME_AD_Window_ID = "AD_Window_ID"; /** Set Window. * Data entry or display window */ public void setAD_Window_ID (int AD_Window_ID); /** Get Window. * Data entry or display window */ public int getAD_Window_ID(); public org.compiere.model.I_AD_Window getAD_Window() throws RuntimeException; /** Column name AccessLevel */ public static final String COLUMNNAME_AccessLevel = "AccessLevel"; /** Set Data Access Level. * Access Level required */ public void setAccessLevel (String AccessLevel); /** Get Data Access Level. * Access Level required */ public String getAccessLevel(); /** Column name ColumnNo */ public static final String COLUMNNAME_ColumnNo = "ColumnNo"; /** Set Column No. * Dashboard content column number */ public void setColumnNo (int ColumnNo); /** Get Column No. * Dashboard content column number */ public int getColumnNo(); /** Column name Created */ public static final String COLUMNNAME_Created = "Created"; /** Get Created. * Date this record was created */ public Timestamp getCreated(); /** Column name CreatedBy */ public static final String COLUMNNAME_CreatedBy = "CreatedBy"; /** Get Created By. * User who created this records */ public int getCreatedBy(); /** Column name Description */ public static final String COLUMNNAME_Description = "Description"; /** Set Description. * Optional short description of the record */ public void setDescription (String Description); /** Get Description. * Optional short description of the record */ public String getDescription(); /** Column name GoalDisplay */ public static final String COLUMNNAME_GoalDisplay = "GoalDisplay"; /** Set Goal Display. * Type of goal display on dashboard */ public void setGoalDisplay (String GoalDisplay); /** Get Goal Display. * Type of goal display on dashboard */ public String getGoalDisplay(); /** Column name HTML */ public static final String COLUMNNAME_HTML = "HTML"; /** Set HTML */ public void setHTML (String HTML); /** Get HTML */ public String getHTML(); /** Column name IsActive */ public static final String COLUMNNAME_IsActive = "IsActive"; /** Set Active. * The record is active in the system */ public void setIsActive (boolean IsActive); /** Get Active. * The record is active in the system */ public boolean isActive(); /** Column name IsCollapsible */ public static final String COLUMNNAME_IsCollapsible = "IsCollapsible"; /** Set Collapsible. * Flag to indicate the state of the dashboard panel */ public void setIsCollapsible (boolean IsCollapsible); /** Get Collapsible. * Flag to indicate the state of the dashboard panel */ public boolean isCollapsible(); /** Column name IsEventRequired */ public static final String COLUMNNAME_IsEventRequired = "IsEventRequired"; /** Set IsEventRequired */ public void setIsEventRequired (boolean IsEventRequired); /** Get IsEventRequired */ public boolean isEventRequired(); /** Column name IsOpenByDefault */ public static final String COLUMNNAME_IsOpenByDefault = "IsOpenByDefault"; /** Set Open By Default */ public void setIsOpenByDefault (boolean IsOpenByDefault); /** Get Open By Default */ public boolean isOpenByDefault(); /** Column name Line */ public static final String COLUMNNAME_Line = "Line"; /** Set Line No. * Unique line for this document */ public void setLine (int Line); /** Get Line No. * Unique line for this document */ public int getLine(); /** Column name Name */ public static final String COLUMNNAME_Name = "Name"; /** Set Name. * Alphanumeric identifier of the entity */ public void setName (String Name); /** Get Name. * Alphanumeric identifier of the entity */ public String getName(); /** Column name PA_DashboardContent_ID */ public static final String COLUMNNAME_PA_DashboardContent_ID = "PA_DashboardContent_ID"; /** Set Dashboard Content */ public void setPA_DashboardContent_ID (int PA_DashboardContent_ID); /** Get Dashboard Content */ public int getPA_DashboardContent_ID(); /** Column name PA_Goal_ID */ public static final String COLUMNNAME_PA_Goal_ID = "PA_Goal_ID"; /** Set Goal. * Performance Goal */ public void setPA_Goal_ID (int PA_Goal_ID); /** Get Goal. * Performance Goal */ public int getPA_Goal_ID(); public org.compiere.model.I_PA_Goal getPA_Goal() throws RuntimeException; /** Column name PageSize */ public static final String COLUMNNAME_PageSize = "PageSize"; /** Set PageSize */ public void setPageSize (BigDecimal PageSize); /** Get PageSize */ public BigDecimal getPageSize(); /** Column name UUID */ public static final String COLUMNNAME_UUID = "UUID"; /** Set Immutable Universally Unique Identifier. * Immutable Universally Unique Identifier */ public void setUUID (String UUID); /** Get Immutable Universally Unique Identifier. * Immutable Universally Unique Identifier */ public String getUUID(); /** Column name Updated */ public static final String COLUMNNAME_Updated = "Updated"; /** Get Updated. * Date this record was updated */ public Timestamp getUpdated(); /** Column name UpdatedBy */ public static final String COLUMNNAME_UpdatedBy = "UpdatedBy"; /** Get Updated By. * User who updated this records */ public int getUpdatedBy(); /** Column name Zoom_Field_ID */ public static final String COLUMNNAME_Zoom_Field_ID = "Zoom_Field_ID"; /** Set Zoom_Field_ID */ public void setZoom_Field_ID (int Zoom_Field_ID); /** Get Zoom_Field_ID */ public int getZoom_Field_ID(); public org.adempiere.model.I_AD_Browse_Field getZoom_Field() throws RuntimeException; /** Column name Zoom_Tab_ID */ public static final String COLUMNNAME_Zoom_Tab_ID = "Zoom_Tab_ID"; /** Set Zoom_Tab_ID */ public void setZoom_Tab_ID (int Zoom_Tab_ID); /** Get Zoom_Tab_ID */ public int getZoom_Tab_ID(); public org.compiere.model.I_AD_Tab getZoom_Tab() throws RuntimeException; /** Column name Zoom_Window_ID */ public static final String COLUMNNAME_Zoom_Window_ID = "Zoom_Window_ID"; /** Set Zoom_Window_ID */ public void setZoom_Window_ID (int Zoom_Window_ID); /** Get Zoom_Window_ID */ public int getZoom_Window_ID(); public org.compiere.model.I_AD_Window getZoom_Window() throws RuntimeException; /** Column name ZulFilePath */ public static final String COLUMNNAME_ZulFilePath = "ZulFilePath"; /** Set ZUL File Path. * Absolute path to zul file */ public void setZulFilePath (String ZulFilePath); /** Get ZUL File Path. * Absolute path to zul file */ public String getZulFilePath(); /** Column name onevent */ public static final String COLUMNNAME_onevent = "onevent"; /** Set onevent */ public void setonevent (String onevent); /** Get onevent */ public String getonevent(); }
EmerisScala/adempiere
base/src/org/compiere/model/I_PA_DashboardContent.java
3,029
/** Get onevent */
block_comment
nl
/****************************************************************************** * Product: ADempiere ERP & CRM Smart Business Solution * * Copyright (C) 2006-2017 ADempiere Foundation, All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * or (at your option) any later version. * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY, without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program, if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * or via [email protected] or http://www.adempiere.net/license.html * *****************************************************************************/ package org.compiere.model; import java.math.BigDecimal; import java.sql.Timestamp; import org.compiere.util.KeyNamePair; /** Generated Interface for PA_DashboardContent * @author Adempiere (generated) * @version Release 3.9.2 */ public interface I_PA_DashboardContent { /** TableName=PA_DashboardContent */ public static final String Table_Name = "PA_DashboardContent"; /** AD_Table_ID=50010 */ public static final int Table_ID = MTable.getTable_ID(Table_Name); KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name); /** AccessLevel = 6 - System - Client */ BigDecimal accessLevel = BigDecimal.valueOf(6); /** Load Meta Data */ /** Column name AD_Browse_ID */ public static final String COLUMNNAME_AD_Browse_ID = "AD_Browse_ID"; /** Set Smart Browse */ public void setAD_Browse_ID (int AD_Browse_ID); /** Get Smart Browse */ public int getAD_Browse_ID(); public org.adempiere.model.I_AD_Browse getAD_Browse() throws RuntimeException; /** Column name AD_Client_ID */ public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID"; /** Get Client. * Client/Tenant for this installation. */ public int getAD_Client_ID(); /** Column name AD_Org_ID */ public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID"; /** Set Organization. * Organizational entity within client */ public void setAD_Org_ID (int AD_Org_ID); /** Get Organization. * Organizational entity within client */ public int getAD_Org_ID(); /** Column name AD_Window_ID */ public static final String COLUMNNAME_AD_Window_ID = "AD_Window_ID"; /** Set Window. * Data entry or display window */ public void setAD_Window_ID (int AD_Window_ID); /** Get Window. * Data entry or display window */ public int getAD_Window_ID(); public org.compiere.model.I_AD_Window getAD_Window() throws RuntimeException; /** Column name AccessLevel */ public static final String COLUMNNAME_AccessLevel = "AccessLevel"; /** Set Data Access Level. * Access Level required */ public void setAccessLevel (String AccessLevel); /** Get Data Access Level. * Access Level required */ public String getAccessLevel(); /** Column name ColumnNo */ public static final String COLUMNNAME_ColumnNo = "ColumnNo"; /** Set Column No. * Dashboard content column number */ public void setColumnNo (int ColumnNo); /** Get Column No. * Dashboard content column number */ public int getColumnNo(); /** Column name Created */ public static final String COLUMNNAME_Created = "Created"; /** Get Created. * Date this record was created */ public Timestamp getCreated(); /** Column name CreatedBy */ public static final String COLUMNNAME_CreatedBy = "CreatedBy"; /** Get Created By. * User who created this records */ public int getCreatedBy(); /** Column name Description */ public static final String COLUMNNAME_Description = "Description"; /** Set Description. * Optional short description of the record */ public void setDescription (String Description); /** Get Description. * Optional short description of the record */ public String getDescription(); /** Column name GoalDisplay */ public static final String COLUMNNAME_GoalDisplay = "GoalDisplay"; /** Set Goal Display. * Type of goal display on dashboard */ public void setGoalDisplay (String GoalDisplay); /** Get Goal Display. * Type of goal display on dashboard */ public String getGoalDisplay(); /** Column name HTML */ public static final String COLUMNNAME_HTML = "HTML"; /** Set HTML */ public void setHTML (String HTML); /** Get HTML */ public String getHTML(); /** Column name IsActive */ public static final String COLUMNNAME_IsActive = "IsActive"; /** Set Active. * The record is active in the system */ public void setIsActive (boolean IsActive); /** Get Active. * The record is active in the system */ public boolean isActive(); /** Column name IsCollapsible */ public static final String COLUMNNAME_IsCollapsible = "IsCollapsible"; /** Set Collapsible. * Flag to indicate the state of the dashboard panel */ public void setIsCollapsible (boolean IsCollapsible); /** Get Collapsible. * Flag to indicate the state of the dashboard panel */ public boolean isCollapsible(); /** Column name IsEventRequired */ public static final String COLUMNNAME_IsEventRequired = "IsEventRequired"; /** Set IsEventRequired */ public void setIsEventRequired (boolean IsEventRequired); /** Get IsEventRequired */ public boolean isEventRequired(); /** Column name IsOpenByDefault */ public static final String COLUMNNAME_IsOpenByDefault = "IsOpenByDefault"; /** Set Open By Default */ public void setIsOpenByDefault (boolean IsOpenByDefault); /** Get Open By Default */ public boolean isOpenByDefault(); /** Column name Line */ public static final String COLUMNNAME_Line = "Line"; /** Set Line No. * Unique line for this document */ public void setLine (int Line); /** Get Line No. * Unique line for this document */ public int getLine(); /** Column name Name */ public static final String COLUMNNAME_Name = "Name"; /** Set Name. * Alphanumeric identifier of the entity */ public void setName (String Name); /** Get Name. * Alphanumeric identifier of the entity */ public String getName(); /** Column name PA_DashboardContent_ID */ public static final String COLUMNNAME_PA_DashboardContent_ID = "PA_DashboardContent_ID"; /** Set Dashboard Content */ public void setPA_DashboardContent_ID (int PA_DashboardContent_ID); /** Get Dashboard Content */ public int getPA_DashboardContent_ID(); /** Column name PA_Goal_ID */ public static final String COLUMNNAME_PA_Goal_ID = "PA_Goal_ID"; /** Set Goal. * Performance Goal */ public void setPA_Goal_ID (int PA_Goal_ID); /** Get Goal. * Performance Goal */ public int getPA_Goal_ID(); public org.compiere.model.I_PA_Goal getPA_Goal() throws RuntimeException; /** Column name PageSize */ public static final String COLUMNNAME_PageSize = "PageSize"; /** Set PageSize */ public void setPageSize (BigDecimal PageSize); /** Get PageSize */ public BigDecimal getPageSize(); /** Column name UUID */ public static final String COLUMNNAME_UUID = "UUID"; /** Set Immutable Universally Unique Identifier. * Immutable Universally Unique Identifier */ public void setUUID (String UUID); /** Get Immutable Universally Unique Identifier. * Immutable Universally Unique Identifier */ public String getUUID(); /** Column name Updated */ public static final String COLUMNNAME_Updated = "Updated"; /** Get Updated. * Date this record was updated */ public Timestamp getUpdated(); /** Column name UpdatedBy */ public static final String COLUMNNAME_UpdatedBy = "UpdatedBy"; /** Get Updated By. * User who updated this records */ public int getUpdatedBy(); /** Column name Zoom_Field_ID */ public static final String COLUMNNAME_Zoom_Field_ID = "Zoom_Field_ID"; /** Set Zoom_Field_ID */ public void setZoom_Field_ID (int Zoom_Field_ID); /** Get Zoom_Field_ID */ public int getZoom_Field_ID(); public org.adempiere.model.I_AD_Browse_Field getZoom_Field() throws RuntimeException; /** Column name Zoom_Tab_ID */ public static final String COLUMNNAME_Zoom_Tab_ID = "Zoom_Tab_ID"; /** Set Zoom_Tab_ID */ public void setZoom_Tab_ID (int Zoom_Tab_ID); /** Get Zoom_Tab_ID */ public int getZoom_Tab_ID(); public org.compiere.model.I_AD_Tab getZoom_Tab() throws RuntimeException; /** Column name Zoom_Window_ID */ public static final String COLUMNNAME_Zoom_Window_ID = "Zoom_Window_ID"; /** Set Zoom_Window_ID */ public void setZoom_Window_ID (int Zoom_Window_ID); /** Get Zoom_Window_ID */ public int getZoom_Window_ID(); public org.compiere.model.I_AD_Window getZoom_Window() throws RuntimeException; /** Column name ZulFilePath */ public static final String COLUMNNAME_ZulFilePath = "ZulFilePath"; /** Set ZUL File Path. * Absolute path to zul file */ public void setZulFilePath (String ZulFilePath); /** Get ZUL File Path. * Absolute path to zul file */ public String getZulFilePath(); /** Column name onevent */ public static final String COLUMNNAME_onevent = "onevent"; /** Set onevent */ public void setonevent (String onevent); /** Get onevent <SUF>*/ public String getonevent(); }
False
2,230
6
2,543
6
2,740
7
2,543
6
3,127
7
false
false
false
false
false
true
4,250
117578_8
package com.thealgorithms.searches; import com.thealgorithms.devutils.searches.SearchAlgorithm; import java.util.Arrays; import java.util.Random; import java.util.stream.Stream; /** * A ternary search algorithm is a technique in computer science for finding the * minimum or maximum of a unimodal function The algorithm determines either * that the minimum or maximum cannot be in the first third of the domain or * that it cannot be in the last third of the domain, then repeats on the * remaining third. * * <p> * Worst-case performance Θ(log3(N)) Best-case performance O(1) Average * performance Θ(log3(N)) Worst-case space complexity O(1) * * @author Podshivalov Nikita (https://github.com/nikitap492) * @see SearchAlgorithm * @see IterativeBinarySearch */ public class TernarySearch implements SearchAlgorithm { /** * @param arr The **Sorted** array in which we will search the element. * @param value The value that we want to search for. * @return The index of the element if found. Else returns -1. */ @Override public <T extends Comparable<T>> int find(T[] arr, T value) { return ternarySearch(arr, value, 0, arr.length - 1); } /** * @param arr The **Sorted** array in which we will search the element. * @param key The value that we want to search for. * @param start The starting index from which we will start Searching. * @param end The ending index till which we will Search. * @return Returns the index of the Element if found. Else returns -1. */ private <T extends Comparable<T>> int ternarySearch(T[] arr, T key, int start, int end) { if (start > end) { return -1; } /* First boundary: add 1/3 of length to start */ int mid1 = start + (end - start) / 3; /* Second boundary: add 2/3 of length to start */ int mid2 = start + 2 * (end - start) / 3; if (key.compareTo(arr[mid1]) == 0) { return mid1; } else if (key.compareTo(arr[mid2]) == 0) { return mid2; } /* Search the first (1/3) rd part of the array.*/ else if (key.compareTo(arr[mid1]) < 0) { return ternarySearch(arr, key, start, --mid1); } /* Search 3rd (1/3)rd part of the array */ else if (key.compareTo(arr[mid2]) > 0) { return ternarySearch(arr, key, ++mid2, end); } /* Search middle (1/3)rd part of the array */ else { return ternarySearch(arr, key, mid1, mid2); } } public static void main(String[] args) { // just generate data Random r = new Random(); int size = 100; int maxElement = 100000; Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[] ::new); // the element that should be found Integer shouldBeFound = integers[r.nextInt(size - 1)]; TernarySearch search = new TernarySearch(); int atIndex = search.find(integers, shouldBeFound); System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", shouldBeFound, integers[atIndex], atIndex, size); int toCheck = Arrays.binarySearch(integers, shouldBeFound); System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); } }
satishppawar/Java
src/main/java/com/thealgorithms/searches/TernarySearch.java
1,008
// just generate data
line_comment
nl
package com.thealgorithms.searches; import com.thealgorithms.devutils.searches.SearchAlgorithm; import java.util.Arrays; import java.util.Random; import java.util.stream.Stream; /** * A ternary search algorithm is a technique in computer science for finding the * minimum or maximum of a unimodal function The algorithm determines either * that the minimum or maximum cannot be in the first third of the domain or * that it cannot be in the last third of the domain, then repeats on the * remaining third. * * <p> * Worst-case performance Θ(log3(N)) Best-case performance O(1) Average * performance Θ(log3(N)) Worst-case space complexity O(1) * * @author Podshivalov Nikita (https://github.com/nikitap492) * @see SearchAlgorithm * @see IterativeBinarySearch */ public class TernarySearch implements SearchAlgorithm { /** * @param arr The **Sorted** array in which we will search the element. * @param value The value that we want to search for. * @return The index of the element if found. Else returns -1. */ @Override public <T extends Comparable<T>> int find(T[] arr, T value) { return ternarySearch(arr, value, 0, arr.length - 1); } /** * @param arr The **Sorted** array in which we will search the element. * @param key The value that we want to search for. * @param start The starting index from which we will start Searching. * @param end The ending index till which we will Search. * @return Returns the index of the Element if found. Else returns -1. */ private <T extends Comparable<T>> int ternarySearch(T[] arr, T key, int start, int end) { if (start > end) { return -1; } /* First boundary: add 1/3 of length to start */ int mid1 = start + (end - start) / 3; /* Second boundary: add 2/3 of length to start */ int mid2 = start + 2 * (end - start) / 3; if (key.compareTo(arr[mid1]) == 0) { return mid1; } else if (key.compareTo(arr[mid2]) == 0) { return mid2; } /* Search the first (1/3) rd part of the array.*/ else if (key.compareTo(arr[mid1]) < 0) { return ternarySearch(arr, key, start, --mid1); } /* Search 3rd (1/3)rd part of the array */ else if (key.compareTo(arr[mid2]) > 0) { return ternarySearch(arr, key, ++mid2, end); } /* Search middle (1/3)rd part of the array */ else { return ternarySearch(arr, key, mid1, mid2); } } public static void main(String[] args) { // just generate<SUF> Random r = new Random(); int size = 100; int maxElement = 100000; Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[] ::new); // the element that should be found Integer shouldBeFound = integers[r.nextInt(size - 1)]; TernarySearch search = new TernarySearch(); int atIndex = search.find(integers, shouldBeFound); System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", shouldBeFound, integers[atIndex], atIndex, size); int toCheck = Arrays.binarySearch(integers, shouldBeFound); System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); } }
False
852
4
933
4
963
4
933
4
1,024
4
false
false
false
false
false
true
2,185
121894_5
public class Tester { public Tester() { // Dit compileert niet; we kunnen er niet van uitgaan dat het Object dat we // aanmaken werkelijk een String is // compile-time: linkerkant van het is-gelijkteken // run-time: rechterkant van het is-gelijkteken Object demo1 ="Hallo"; //String s1 = demo1; // We kunnen de compiler er wel van overtuigen dat we wel degelijk met een // String te maken hebben -> casting Object demo2 = "Hallo"; String s = (String)demo2; // Het volgende compileert wel, maar geeft in run-time een error // omdat we een boolean niet naar een string kunnen casten Object demo3 = Boolean.FALSE; String s2 = (String)demo3; // linkerkant -> STATISCHE DATATYPE // rechterkant -> DYNAMISCHE DATATYPE } }
bart314/ITANN
StaticAndDynamicDemo/Tester.java
268
// We kunnen de compiler er wel van overtuigen dat we wel degelijk met een
line_comment
nl
public class Tester { public Tester() { // Dit compileert niet; we kunnen er niet van uitgaan dat het Object dat we // aanmaken werkelijk een String is // compile-time: linkerkant van het is-gelijkteken // run-time: rechterkant van het is-gelijkteken Object demo1 ="Hallo"; //String s1 = demo1; // We kunnen<SUF> // String te maken hebben -> casting Object demo2 = "Hallo"; String s = (String)demo2; // Het volgende compileert wel, maar geeft in run-time een error // omdat we een boolean niet naar een string kunnen casten Object demo3 = Boolean.FALSE; String s2 = (String)demo3; // linkerkant -> STATISCHE DATATYPE // rechterkant -> DYNAMISCHE DATATYPE } }
True
226
19
241
22
238
18
241
22
265
19
false
false
false
false
false
true
3,778
165188_6
package boeren.com.appsuline.app.bmedical.appsuline.fragments; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.TimePickerDialog; import android.os.Bundle; import android.app.Fragment; import android.support.v4.app.DialogFragment; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.TimePicker; import java.text.DateFormat; import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import boeren.com.appsuline.app.bmedical.appsuline.R; import boeren.com.appsuline.app.bmedical.appsuline.controllers.BaseController; import boeren.com.appsuline.app.bmedical.appsuline.models.CalendarEvent; import boeren.com.appsuline.app.bmedical.appsuline.utils.CalendarManagerNew; import boeren.com.appsuline.app.bmedical.appsuline.utils.DateUtils; import boeren.com.appsuline.app.bmedical.appsuline.utils.DialogEditingListener; /** * A simple {@link Fragment} subclass. */ public class EventProductBestellingEditFragment extends DialogFragment implements TextView.OnEditorActionListener { static private Button btntime, btnorderdate; private ImageView btnCancel, btnSave; private int xhour; private int xminute; public static int xDay, xMonth, xYear; private EditText edit_naamproduct; private DialogEditingListener mCallback; private CalendarEvent mEvent; private static final String KEY_EVENT = "event"; private boolean isDualPan = false; public static EventProductBestellingEditFragment newInstance(CalendarEvent event){ EventProductBestellingEditFragment s = new EventProductBestellingEditFragment(); Bundle args = new Bundle(); args.putSerializable(KEY_EVENT, event); s.setArguments(args); return s; } public EventProductBestellingEditFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getActivity().findViewById(R.id.container2) != null) isDualPan = true; setRetainInstance(true); } public void setEvent(CalendarEvent event) { this.mEvent = event; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_eventdelete, menu); super.onCreateOptionsMenu(menu, inflater); MenuItem shareItem = menu.findItem(R.id.action_eventdelete); shareItem.setActionView(R.layout.deleteiconlayout); ImageView img = (ImageView) shareItem.getActionView().findViewById(R.id.img_view_del); img.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.e("appsuline del", BaseController.getInstance().getDbManager(getActivity()).getEventsTable().delete(mEvent) + ""); if (isDualPan) { HerinneringenFragment fragment = (HerinneringenFragment) getCurrentFragment(); fragment.loadEventsAndUpdateList(); } getActivity().onBackPressed(); } }); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_event_product_bestelling_edit, container, false); ActionBar actionBar = ((ActionBarActivity) getActivity()).getSupportActionBar(); setHasOptionsMenu(true); actionBar.setDisplayHomeAsUpEnabled(true); Bundle arguments = getArguments(); if (arguments != null && arguments.containsKey(KEY_EVENT)) { mEvent = (CalendarEvent) getArguments().getSerializable(KEY_EVENT); } btntime = (Button) view.findViewById(R.id.btn_bloedmetentime); btnCancel = (ImageView) view.findViewById(R.id.btnCancel); btnSave = (ImageView) view.findViewById(R.id.btnSave); btnorderdate = (Button) view.findViewById(R.id.btn_dateofororder); edit_naamproduct = (EditText) view.findViewById(R.id.edit_naamproduct); btnorderdate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showStartDatePickerDialog(view); } }); btntime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Process to get Current Time final Calendar c = Calendar.getInstance(); xhour = c.get(Calendar.HOUR_OF_DAY); xminute = c.get(Calendar.MINUTE); // Launch Time Picker Dialog TimePickerDialog tpd = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { // Display Selected time in textbox xhour = hourOfDay; xminute = minute; btntime.setText(new StringBuilder().append(padding_str(hourOfDay)).append(":").append(padding_str(minute))); mEvent.setEventEndTime(String.format("%02d:%02d",xhour,xminute)); mEvent.setEventTitle(edit_naamproduct.getText().toString().trim()); Log.e("appsuline", BaseController.getInstance().getDbManager(getActivity()).getEventsTable().update(mEvent) + ""); mCallback.onCheckChangeCallback(-1); } }, xhour, xminute, true); tpd.show(); } }); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Log.e("appsuline del", BaseController.getInstance().getDbManager(getActivity()).getEventsTable().delete(mEvent) + ""); //mCallback.onCheckChangeCallback(-1); // getDialog().dismiss(); getActivity().onBackPressed(); } }); btnSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CalendarManagerNew cm = new CalendarManagerNew(); mEvent.setEventTitle(edit_naamproduct.getText().toString().trim()); mEvent.setEventEndDate(DateUtils.getDateString(xDay, xMonth, xYear)); Log.e("appsuline", BaseController.getInstance().getDbManager(getActivity()).getEventsTable().update(mEvent) + ""); mCallback.onCheckChangeCallback(-1); cm.addReminder(getActivity(), xDay, xMonth, xYear, xhour, xminute, mEvent.getEventID()); getActivity().onBackPressed(); } }); getActivity().setTitle(R.string.productbestllen); setCurrentEvent(); return view; } @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (EditorInfo.IME_ACTION_DONE == actionId) { // Return input text to activity mCallback.onFinishEditDialog(btntime.getText().toString()); this.dismiss(); return true; } return false; } protected int getFragmentCount() { return getActivity().getSupportFragmentManager().getBackStackEntryCount(); } private android.support.v4.app.Fragment getFragmentAt(int index) { return getFragmentCount() > 0 ? getActivity().getSupportFragmentManager().findFragmentByTag(Integer.toString(index)) : null; } protected android.support.v4.app.Fragment getCurrentFragment() { return getFragmentAt(getFragmentCount()); } public void showStartDatePickerDialog(View v) { DialogFragment newFragment = new OrderDatePickerFragment(); newFragment.show(getActivity().getSupportFragmentManager(), "datePicker"); } private void setCurrentEvent() { if(this.mEvent!=null) { Calendar c=Calendar.getInstance(); DateFormat format=new SimpleDateFormat("dd/mm/yyyy"); Date formatedDate; formatedDate = DateUtils.getDateFromString(mEvent.getEventEndDate()); format.format(formatedDate); c=format.getCalendar(); xYear = c.get(Calendar.YEAR); xMonth = c.get(Calendar.MONTH); xDay = c.get(Calendar.DAY_OF_MONTH); btnorderdate.setText(new StringBuilder().append((xDay)).append(" ").append((getMonth(xMonth))).append(" ").append((xYear))); System.out.println(mEvent.getEventEndTime()); btntime.setText(mEvent.getEventEndTime()); edit_naamproduct.setText(mEvent.getEventTitle()); } } private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) { xhour = selectedHour; xminute = selectedMinute; // set current time into textview btntime.setText(new StringBuilder().append(padding_str(xhour)).append(":").append(padding_str(xminute))); System.out.println(new StringBuilder().append(padding_str(xhour)).append(":").append(padding_str(xminute))); } }; public static String getMonth(int month) { return new DateFormatSymbols().getMonths()[month]; } private static String padding_str(int c) { if (c >= 10) return String.valueOf(c); else return "0" + String.valueOf(c); } public static class OrderDatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Calendar c = Calendar.getInstance(); xYear = c.get(Calendar.YEAR); xMonth = c.get(Calendar.MONTH); c.add(Calendar.DAY_OF_MONTH, 1); xDay = c.get(Calendar.DAY_OF_MONTH); // Create a new instance of DatePickerDialog and return it return new DatePickerDialog(getActivity(), this, xYear, xMonth, xDay); } public void onDateSet(DatePicker view, int year, int month, int day) { // Do something with the date chosen by the user // set current time into textview xMonth = month; xDay = day; xYear = year; btnorderdate.setText(new StringBuilder().append((day)).append(" ").append((getMonth(month))).append(" ").append((year))); } } public void registerCallbacks(DialogEditingListener callback) { this.mCallback = callback; } }
navyon/suline
app/src/main/java/boeren/com/appsuline/app/bmedical/appsuline/fragments/EventProductBestellingEditFragment.java
3,205
//Log.e("appsuline del", BaseController.getInstance().getDbManager(getActivity()).getEventsTable().delete(mEvent) + "");
line_comment
nl
package boeren.com.appsuline.app.bmedical.appsuline.fragments; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.TimePickerDialog; import android.os.Bundle; import android.app.Fragment; import android.support.v4.app.DialogFragment; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.TimePicker; import java.text.DateFormat; import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import boeren.com.appsuline.app.bmedical.appsuline.R; import boeren.com.appsuline.app.bmedical.appsuline.controllers.BaseController; import boeren.com.appsuline.app.bmedical.appsuline.models.CalendarEvent; import boeren.com.appsuline.app.bmedical.appsuline.utils.CalendarManagerNew; import boeren.com.appsuline.app.bmedical.appsuline.utils.DateUtils; import boeren.com.appsuline.app.bmedical.appsuline.utils.DialogEditingListener; /** * A simple {@link Fragment} subclass. */ public class EventProductBestellingEditFragment extends DialogFragment implements TextView.OnEditorActionListener { static private Button btntime, btnorderdate; private ImageView btnCancel, btnSave; private int xhour; private int xminute; public static int xDay, xMonth, xYear; private EditText edit_naamproduct; private DialogEditingListener mCallback; private CalendarEvent mEvent; private static final String KEY_EVENT = "event"; private boolean isDualPan = false; public static EventProductBestellingEditFragment newInstance(CalendarEvent event){ EventProductBestellingEditFragment s = new EventProductBestellingEditFragment(); Bundle args = new Bundle(); args.putSerializable(KEY_EVENT, event); s.setArguments(args); return s; } public EventProductBestellingEditFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getActivity().findViewById(R.id.container2) != null) isDualPan = true; setRetainInstance(true); } public void setEvent(CalendarEvent event) { this.mEvent = event; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_eventdelete, menu); super.onCreateOptionsMenu(menu, inflater); MenuItem shareItem = menu.findItem(R.id.action_eventdelete); shareItem.setActionView(R.layout.deleteiconlayout); ImageView img = (ImageView) shareItem.getActionView().findViewById(R.id.img_view_del); img.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.e("appsuline del", BaseController.getInstance().getDbManager(getActivity()).getEventsTable().delete(mEvent) + ""); if (isDualPan) { HerinneringenFragment fragment = (HerinneringenFragment) getCurrentFragment(); fragment.loadEventsAndUpdateList(); } getActivity().onBackPressed(); } }); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_event_product_bestelling_edit, container, false); ActionBar actionBar = ((ActionBarActivity) getActivity()).getSupportActionBar(); setHasOptionsMenu(true); actionBar.setDisplayHomeAsUpEnabled(true); Bundle arguments = getArguments(); if (arguments != null && arguments.containsKey(KEY_EVENT)) { mEvent = (CalendarEvent) getArguments().getSerializable(KEY_EVENT); } btntime = (Button) view.findViewById(R.id.btn_bloedmetentime); btnCancel = (ImageView) view.findViewById(R.id.btnCancel); btnSave = (ImageView) view.findViewById(R.id.btnSave); btnorderdate = (Button) view.findViewById(R.id.btn_dateofororder); edit_naamproduct = (EditText) view.findViewById(R.id.edit_naamproduct); btnorderdate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showStartDatePickerDialog(view); } }); btntime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Process to get Current Time final Calendar c = Calendar.getInstance(); xhour = c.get(Calendar.HOUR_OF_DAY); xminute = c.get(Calendar.MINUTE); // Launch Time Picker Dialog TimePickerDialog tpd = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { // Display Selected time in textbox xhour = hourOfDay; xminute = minute; btntime.setText(new StringBuilder().append(padding_str(hourOfDay)).append(":").append(padding_str(minute))); mEvent.setEventEndTime(String.format("%02d:%02d",xhour,xminute)); mEvent.setEventTitle(edit_naamproduct.getText().toString().trim()); Log.e("appsuline", BaseController.getInstance().getDbManager(getActivity()).getEventsTable().update(mEvent) + ""); mCallback.onCheckChangeCallback(-1); } }, xhour, xminute, true); tpd.show(); } }); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Log.e("appsuline del",<SUF> //mCallback.onCheckChangeCallback(-1); // getDialog().dismiss(); getActivity().onBackPressed(); } }); btnSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CalendarManagerNew cm = new CalendarManagerNew(); mEvent.setEventTitle(edit_naamproduct.getText().toString().trim()); mEvent.setEventEndDate(DateUtils.getDateString(xDay, xMonth, xYear)); Log.e("appsuline", BaseController.getInstance().getDbManager(getActivity()).getEventsTable().update(mEvent) + ""); mCallback.onCheckChangeCallback(-1); cm.addReminder(getActivity(), xDay, xMonth, xYear, xhour, xminute, mEvent.getEventID()); getActivity().onBackPressed(); } }); getActivity().setTitle(R.string.productbestllen); setCurrentEvent(); return view; } @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (EditorInfo.IME_ACTION_DONE == actionId) { // Return input text to activity mCallback.onFinishEditDialog(btntime.getText().toString()); this.dismiss(); return true; } return false; } protected int getFragmentCount() { return getActivity().getSupportFragmentManager().getBackStackEntryCount(); } private android.support.v4.app.Fragment getFragmentAt(int index) { return getFragmentCount() > 0 ? getActivity().getSupportFragmentManager().findFragmentByTag(Integer.toString(index)) : null; } protected android.support.v4.app.Fragment getCurrentFragment() { return getFragmentAt(getFragmentCount()); } public void showStartDatePickerDialog(View v) { DialogFragment newFragment = new OrderDatePickerFragment(); newFragment.show(getActivity().getSupportFragmentManager(), "datePicker"); } private void setCurrentEvent() { if(this.mEvent!=null) { Calendar c=Calendar.getInstance(); DateFormat format=new SimpleDateFormat("dd/mm/yyyy"); Date formatedDate; formatedDate = DateUtils.getDateFromString(mEvent.getEventEndDate()); format.format(formatedDate); c=format.getCalendar(); xYear = c.get(Calendar.YEAR); xMonth = c.get(Calendar.MONTH); xDay = c.get(Calendar.DAY_OF_MONTH); btnorderdate.setText(new StringBuilder().append((xDay)).append(" ").append((getMonth(xMonth))).append(" ").append((xYear))); System.out.println(mEvent.getEventEndTime()); btntime.setText(mEvent.getEventEndTime()); edit_naamproduct.setText(mEvent.getEventTitle()); } } private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) { xhour = selectedHour; xminute = selectedMinute; // set current time into textview btntime.setText(new StringBuilder().append(padding_str(xhour)).append(":").append(padding_str(xminute))); System.out.println(new StringBuilder().append(padding_str(xhour)).append(":").append(padding_str(xminute))); } }; public static String getMonth(int month) { return new DateFormatSymbols().getMonths()[month]; } private static String padding_str(int c) { if (c >= 10) return String.valueOf(c); else return "0" + String.valueOf(c); } public static class OrderDatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Calendar c = Calendar.getInstance(); xYear = c.get(Calendar.YEAR); xMonth = c.get(Calendar.MONTH); c.add(Calendar.DAY_OF_MONTH, 1); xDay = c.get(Calendar.DAY_OF_MONTH); // Create a new instance of DatePickerDialog and return it return new DatePickerDialog(getActivity(), this, xYear, xMonth, xDay); } public void onDateSet(DatePicker view, int year, int month, int day) { // Do something with the date chosen by the user // set current time into textview xMonth = month; xDay = day; xYear = year; btnorderdate.setText(new StringBuilder().append((day)).append(" ").append((getMonth(month))).append(" ").append((year))); } } public void registerCallbacks(DialogEditingListener callback) { this.mCallback = callback; } }
False
2,188
26
2,634
31
2,747
29
2,634
31
3,052
34
false
false
false
false
false
true
2,024
79963_3
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; public class Solution { public static List<List<String>> groupStrings(String[] strings){ List<List<String>> allGroups=new ArrayList<List<String>>(); //Use hash string HashMap<String, List<String>> map=new HashMap<>(); for(String str: strings){ if(!map.containsKey(hashStr(str))){ List<String> l=new ArrayList<String>(); l.add(str); map.put(hashStr(str), l); } else map.get(hashStr(str)).add(str); } for(String key:map.keySet()){ Collections.sort(map.get(key)); //Sort to make sure each list is in lexicographic order allGroups.add(new ArrayList<String>(map.get(key))); } return allGroups; } //Convert string to hash string private static String hashStr(String s){ if(s.length()==0) return ""; char base=s.charAt(0); StringBuffer str=new StringBuffer(s); for(int i=0; i<s.length(); i++){ char c=s.charAt(i); str.setCharAt(i, (char)('a'+(c-base>=0?c-base:c-base+26))); } return str.toString(); } public static void main(String[] args) { //String[] strings={"fpbnsbrkbcyzdmmmoisaa", "cpjtwqcdwbldwwrryuclcngw", "a", "fnuqwejouqzrif", "js", "qcpr", "zghmdiaqmfelr", "iedda", "l", "dgwlvcyubde", "lpt", "qzq", "zkddvitlk", "xbogegswmad", "mkndeyrh", "llofdjckor", "lebzshcb", "firomjjlidqpsdeqyn", "dclpiqbypjpfafukqmjnjg", "lbpabjpcmkyivbtgdwhzlxa", "wmalmuanxvjtgmerohskwil", "yxgkdlwtkekavapflheieb", "oraxvssurmzybmnzhw", "ohecvkfe", "kknecibjnq", "wuxnoibr", "gkxpnpbfvjm", "lwpphufxw", "sbs", "txb", "ilbqahdzgij", "i", "zvuur", "yfglchzpledkq", "eqdf", "nw", "aiplrzejplumda", "d", "huoybvhibgqibbwwdzhqhslb", "rbnzendwnoklpyyyauemm"}; String[] strings={"aa","a","bb"}; System.out.println("The input string array is: " +Arrays.toString(strings)); System.out.println("The grouped shifted strings is: "); for(List<String> l:groupStrings(strings)) System.out.println(Arrays.deepToString(l.toArray())); } }
allenwhc/Leetcode
Java/(P)GroupShiftedStrings/src/Solution.java
861
//String[] strings={"fpbnsbrkbcyzdmmmoisaa", "cpjtwqcdwbldwwrryuclcngw", "a", "fnuqwejouqzrif", "js", "qcpr", "zghmdiaqmfelr", "iedda", "l", "dgwlvcyubde", "lpt", "qzq", "zkddvitlk", "xbogegswmad", "mkndeyrh", "llofdjckor", "lebzshcb", "firomjjlidqpsdeqyn", "dclpiqbypjpfafukqmjnjg", "lbpabjpcmkyivbtgdwhzlxa", "wmalmuanxvjtgmerohskwil", "yxgkdlwtkekavapflheieb", "oraxvssurmzybmnzhw", "ohecvkfe", "kknecibjnq", "wuxnoibr", "gkxpnpbfvjm", "lwpphufxw", "sbs", "txb", "ilbqahdzgij", "i", "zvuur", "yfglchzpledkq", "eqdf", "nw", "aiplrzejplumda", "d", "huoybvhibgqibbwwdzhqhslb", "rbnzendwnoklpyyyauemm"};
line_comment
nl
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; public class Solution { public static List<List<String>> groupStrings(String[] strings){ List<List<String>> allGroups=new ArrayList<List<String>>(); //Use hash string HashMap<String, List<String>> map=new HashMap<>(); for(String str: strings){ if(!map.containsKey(hashStr(str))){ List<String> l=new ArrayList<String>(); l.add(str); map.put(hashStr(str), l); } else map.get(hashStr(str)).add(str); } for(String key:map.keySet()){ Collections.sort(map.get(key)); //Sort to make sure each list is in lexicographic order allGroups.add(new ArrayList<String>(map.get(key))); } return allGroups; } //Convert string to hash string private static String hashStr(String s){ if(s.length()==0) return ""; char base=s.charAt(0); StringBuffer str=new StringBuffer(s); for(int i=0; i<s.length(); i++){ char c=s.charAt(i); str.setCharAt(i, (char)('a'+(c-base>=0?c-base:c-base+26))); } return str.toString(); } public static void main(String[] args) { //String[] strings={"fpbnsbrkbcyzdmmmoisaa",<SUF> String[] strings={"aa","a","bb"}; System.out.println("The input string array is: " +Arrays.toString(strings)); System.out.println("The grouped shifted strings is: "); for(List<String> l:groupStrings(strings)) System.out.println(Arrays.deepToString(l.toArray())); } }
False
676
319
793
316
784
300
793
316
896
343
true
true
true
true
true
false
2,008
210934_0
package mathunited; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletContext; import javax.xml.transform.Source; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.URIResolver; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import mathunited.configuration.TransformationSpec; /** * @author martijn */ public class XSLTbean { private static ServletContext context; private static final String XSLTroot = "/xslt/"; private final static Logger LOGGER = Logger.getLogger(XSLTbean.class.getName()); private static Map<String, Templates> templateMap = new HashMap<String, Templates>(); private static TransformerFactory tFactory = TransformerFactory.newInstance(); static { tFactory.setURIResolver(new URIResolver() { public StreamSource resolve(String href, String base){ InputStream xmlStream = context.getResourceAsStream(XSLTroot+href); return new StreamSource(xmlStream); } }); } private Map<String,TransformationSpec> transformationMap; //the constructor simply gets a new TransformerFactory instance public XSLTbean(ServletContext ctxt, Map<String,TransformationSpec> transformationMap) throws Exception { LOGGER.setLevel(Level.INFO); context = ctxt; this.transformationMap = transformationMap; } public static Templates getTemplate(String name, Map<String,TransformationSpec> transformationMap) throws Exception{ Templates template = templateMap.get(name); try{ if(template==null){ TransformationSpec spec = transformationMap.get(name); String path = spec.path; if(path==null) throw new Exception("Onbekende transformatie: "+name); InputStream is = context.getResourceAsStream(path); StreamSource xslSource = new StreamSource(is); System.out.println("XSLTbean: Compiling variant "+name); template = tFactory.newTemplates(xslSource); templateMap.put(name, template); } } catch(Exception e) { throw new Exception("Error when trying to compile xslt-script "+name,e); } return template; } public static void clearTemplates() { templateMap.clear(); } /* public static void setTemplates(Map<String, String> variantMap, boolean forced, ServletContext ctxt) throws Exception{ try { context = ctxt; TransformerFactory tFactory; Map<String, Templates> tempMap = new HashMap<String, Templates>(); tFactory = TransformerFactory.newInstance(); tFactory.setURIResolver(new URIResolver() { public StreamSource resolve(String href, String base){ InputStream xmlStream = context.getResourceAsStream(XSLTroot+href); if(xmlStream==null) { LOGGER.log(Level.SEVERE, "Could not locate XSLT file "+XSLTroot+href); } return new StreamSource(xmlStream); } }); boolean changed = false; for(Map.Entry<String,String> entry:variantMap.entrySet()) { String key = entry.getKey(); String val = entry.getValue(); if(forced || templateMap.get(key)==null){ InputStream is = context.getResourceAsStream(val); if(is==null) { LOGGER.log(Level.SEVERE, "Could not locate XSLT file "+val); } StreamSource xslSource = new StreamSource(is); Templates templ = tFactory.newTemplates(xslSource); tempMap.put(key, templ); changed = true; } else { tempMap.put(key, templateMap.get(key)); } if(changed) templateMap = tempMap; } }catch(TransformerConfigurationException e){ e.printStackTrace(); throw e; } } */ //this method takes as input a XML source, a XSL source, and returns the output of the transformation to the servlet output stream public void process(Source xmlSource, String variant, Map<String, String> parameterMap, URIResolver resolver, java.io.ByteArrayOutputStream out) throws Exception { Templates templ = getTemplate(variant, transformationMap); Transformer transformer = templ.newTransformer(); for(Map.Entry<String,String> entry : parameterMap.entrySet()) { transformer.setParameter(entry.getKey(), entry.getValue()); } transformer.setURIResolver(resolver); StreamResult result= new StreamResult(out); //Start the transformation and rendering process transformer.transform(xmlSource, result); //xml->html } //this method takes as input a XML source, a XSL source, and returns the output of the transformation to the servlet output stream public org.w3c.dom.Node processToDOM(Source xmlSource, String variant, Map<String, String> parameterMap, URIResolver resolver, Map<String,TransformationSpec> transformationMap) throws Exception{ Templates templ = getTemplate(variant, transformationMap); Transformer transformer = templ.newTransformer(); for(Map.Entry<String,String> entry : parameterMap.entrySet()) { transformer.setParameter(entry.getKey(), entry.getValue()); } transformer.setURIResolver(resolver); DOMResult result= new DOMResult(); //Start the transformation and rendering process transformer.transform(xmlSource, result); //transform to xml DOM return result.getNode();//.getOwnerDocument().getDocumentElement(); } }
algebrakit/mathunited
GAE/Mathunited/src/mathunited/XSLTbean.java
1,586
/** * @author martijn */
block_comment
nl
package mathunited; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletContext; import javax.xml.transform.Source; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.URIResolver; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import mathunited.configuration.TransformationSpec; /** * @author martijn <SUF>*/ public class XSLTbean { private static ServletContext context; private static final String XSLTroot = "/xslt/"; private final static Logger LOGGER = Logger.getLogger(XSLTbean.class.getName()); private static Map<String, Templates> templateMap = new HashMap<String, Templates>(); private static TransformerFactory tFactory = TransformerFactory.newInstance(); static { tFactory.setURIResolver(new URIResolver() { public StreamSource resolve(String href, String base){ InputStream xmlStream = context.getResourceAsStream(XSLTroot+href); return new StreamSource(xmlStream); } }); } private Map<String,TransformationSpec> transformationMap; //the constructor simply gets a new TransformerFactory instance public XSLTbean(ServletContext ctxt, Map<String,TransformationSpec> transformationMap) throws Exception { LOGGER.setLevel(Level.INFO); context = ctxt; this.transformationMap = transformationMap; } public static Templates getTemplate(String name, Map<String,TransformationSpec> transformationMap) throws Exception{ Templates template = templateMap.get(name); try{ if(template==null){ TransformationSpec spec = transformationMap.get(name); String path = spec.path; if(path==null) throw new Exception("Onbekende transformatie: "+name); InputStream is = context.getResourceAsStream(path); StreamSource xslSource = new StreamSource(is); System.out.println("XSLTbean: Compiling variant "+name); template = tFactory.newTemplates(xslSource); templateMap.put(name, template); } } catch(Exception e) { throw new Exception("Error when trying to compile xslt-script "+name,e); } return template; } public static void clearTemplates() { templateMap.clear(); } /* public static void setTemplates(Map<String, String> variantMap, boolean forced, ServletContext ctxt) throws Exception{ try { context = ctxt; TransformerFactory tFactory; Map<String, Templates> tempMap = new HashMap<String, Templates>(); tFactory = TransformerFactory.newInstance(); tFactory.setURIResolver(new URIResolver() { public StreamSource resolve(String href, String base){ InputStream xmlStream = context.getResourceAsStream(XSLTroot+href); if(xmlStream==null) { LOGGER.log(Level.SEVERE, "Could not locate XSLT file "+XSLTroot+href); } return new StreamSource(xmlStream); } }); boolean changed = false; for(Map.Entry<String,String> entry:variantMap.entrySet()) { String key = entry.getKey(); String val = entry.getValue(); if(forced || templateMap.get(key)==null){ InputStream is = context.getResourceAsStream(val); if(is==null) { LOGGER.log(Level.SEVERE, "Could not locate XSLT file "+val); } StreamSource xslSource = new StreamSource(is); Templates templ = tFactory.newTemplates(xslSource); tempMap.put(key, templ); changed = true; } else { tempMap.put(key, templateMap.get(key)); } if(changed) templateMap = tempMap; } }catch(TransformerConfigurationException e){ e.printStackTrace(); throw e; } } */ //this method takes as input a XML source, a XSL source, and returns the output of the transformation to the servlet output stream public void process(Source xmlSource, String variant, Map<String, String> parameterMap, URIResolver resolver, java.io.ByteArrayOutputStream out) throws Exception { Templates templ = getTemplate(variant, transformationMap); Transformer transformer = templ.newTransformer(); for(Map.Entry<String,String> entry : parameterMap.entrySet()) { transformer.setParameter(entry.getKey(), entry.getValue()); } transformer.setURIResolver(resolver); StreamResult result= new StreamResult(out); //Start the transformation and rendering process transformer.transform(xmlSource, result); //xml->html } //this method takes as input a XML source, a XSL source, and returns the output of the transformation to the servlet output stream public org.w3c.dom.Node processToDOM(Source xmlSource, String variant, Map<String, String> parameterMap, URIResolver resolver, Map<String,TransformationSpec> transformationMap) throws Exception{ Templates templ = getTemplate(variant, transformationMap); Transformer transformer = templ.newTransformer(); for(Map.Entry<String,String> entry : parameterMap.entrySet()) { transformer.setParameter(entry.getKey(), entry.getValue()); } transformer.setURIResolver(resolver); DOMResult result= new DOMResult(); //Start the transformation and rendering process transformer.transform(xmlSource, result); //transform to xml DOM return result.getNode();//.getOwnerDocument().getDocumentElement(); } }
False
1,141
8
1,317
10
1,430
9
1,317
10
1,570
9
false
false
false
false
false
true
918
160538_1
package com.PPinera.Torrent_Movies.Activities; import android.app.Activity; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.widget.DrawerLayout; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import android.widget.ListAdapter; import android.widget.ListView; import com.PPinera.Torrent_Movies.Adapters.FilmsGridAdapter; import com.PPinera.Torrent_Movies.Adapters.MenuAdapter; import com.PPinera.Torrent_Movies.R; import com.PPinera.Torrent_Movies.Web.MovieItem; import com.PPinera.Torrent_Movies.Web.YIFIClient; import java.util.ArrayList; public class MainActivity extends Activity { private DrawerLayout drawerLayout; private ListView drawerList; private ActionBarDrawerToggle drawerToggle; private GridView gridview; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); setupDrawerLayout(); setupActionBar(); gridview = (GridView) findViewById(R.id.gridview); } private void reloadGridWithGenre(String genre){ YIFIClient.getFilmsByGenre(new YIFIClient.filmsListHandler() { @Override public void onSuccessFilms(ArrayList<MovieItem> films) { FilmsGridAdapter adapter = new FilmsGridAdapter(MainActivity.this,films); gridview.setAdapter(adapter); } @Override public void onErrorFilms(Throwable e) { } },genre); } private void setupDrawerLayout() { drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); drawerList = (ListView) findViewById(R.id.left_drawer); drawerList.setAdapter(new MenuAdapter(this)); drawerList.setOnItemClickListener(new DrawerItemClickListener()); drawerToggle = new ActionBarDrawerToggle( this, /* host Activity */ drawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */ R.string.drawer_open, /* "open drawer" description */ R.string.drawer_close /* "close drawer" description */ ) { public void onDrawerClosed(View view) { super.onDrawerClosed(view); } public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); } }; drawerLayout.setDrawerListener(drawerToggle); } private void setupActionBar() { getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); } private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { selectItem(position); gridview.setAdapter(null); getActionBar().setTitle((String)parent.getItemAtPosition(position)); reloadGridWithGenre((String)parent.getItemAtPosition(position)); } } private void selectItem(int position) { drawerList.setItemChecked(position, true); drawerLayout.closeDrawer(drawerList); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); drawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); drawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (drawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } }
KhalidElSayed/Torrent-Movies
src/com/PPinera/Torrent_Movies/Activities/MainActivity.java
1,127
/* "open drawer" description */
block_comment
nl
package com.PPinera.Torrent_Movies.Activities; import android.app.Activity; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.widget.DrawerLayout; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import android.widget.ListAdapter; import android.widget.ListView; import com.PPinera.Torrent_Movies.Adapters.FilmsGridAdapter; import com.PPinera.Torrent_Movies.Adapters.MenuAdapter; import com.PPinera.Torrent_Movies.R; import com.PPinera.Torrent_Movies.Web.MovieItem; import com.PPinera.Torrent_Movies.Web.YIFIClient; import java.util.ArrayList; public class MainActivity extends Activity { private DrawerLayout drawerLayout; private ListView drawerList; private ActionBarDrawerToggle drawerToggle; private GridView gridview; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); setupDrawerLayout(); setupActionBar(); gridview = (GridView) findViewById(R.id.gridview); } private void reloadGridWithGenre(String genre){ YIFIClient.getFilmsByGenre(new YIFIClient.filmsListHandler() { @Override public void onSuccessFilms(ArrayList<MovieItem> films) { FilmsGridAdapter adapter = new FilmsGridAdapter(MainActivity.this,films); gridview.setAdapter(adapter); } @Override public void onErrorFilms(Throwable e) { } },genre); } private void setupDrawerLayout() { drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); drawerList = (ListView) findViewById(R.id.left_drawer); drawerList.setAdapter(new MenuAdapter(this)); drawerList.setOnItemClickListener(new DrawerItemClickListener()); drawerToggle = new ActionBarDrawerToggle( this, /* host Activity */ drawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */ R.string.drawer_open, /* "open drawer" description<SUF>*/ R.string.drawer_close /* "close drawer" description */ ) { public void onDrawerClosed(View view) { super.onDrawerClosed(view); } public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); } }; drawerLayout.setDrawerListener(drawerToggle); } private void setupActionBar() { getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); } private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { selectItem(position); gridview.setAdapter(null); getActionBar().setTitle((String)parent.getItemAtPosition(position)); reloadGridWithGenre((String)parent.getItemAtPosition(position)); } } private void selectItem(int position) { drawerList.setItemChecked(position, true); drawerLayout.closeDrawer(drawerList); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); drawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); drawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (drawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } }
False
731
7
893
7
939
7
893
7
1,082
8
false
false
false
false
false
true
2,982
43439_2
package techiteasy1121.config; @Configuration @EnableWebSecurity public class SpringSecurityConfig { /*TODO inject customUserDetailService en 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, PasswordEncoder passwordEncoder) throws Exception { var auth = new DaoAuthenticationProvider(); auth.setPasswordEncoder(passwordEncoder); auth.setUserDetailsService(customUserDetailsService); return new ProviderManager(auth); } // Authorizatie met jwt @Bean protected SecurityFilterChain filter (HttpSecurity http) throws Exception { //JWT token authentication http .csrf(csrf -> csrf.disable()) .httpBasic(basic -> basic.disable()) .cors(Customizer.withDefaults()) .authorizeHttpRequests(auth -> auth // Wanneer je deze uncomments, staat je hele security open. Je hebt dan alleen nog een jwt nodig. // .requestMatchers("/**").permitAll() .requestMatchers(HttpMethod.POST, "/users").hasRole("ADMIN") .requestMatchers(HttpMethod.GET,"/users").hasRole("ADMIN") .requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN") /*TODO voeg de antmatchers toe voor admin(post en delete) en user (overige)*/ .requestMatchers("/authenticated").authenticated() .requestMatchers("/authenticate").permitAll()/*alleen dit punt mag toegankelijk zijn voor niet ingelogde gebruikers*/ .anyRequest().denyAll() /*Deze voeg je altijd als laatste toe, om een default beveiliging te hebben voor eventuele vergeten endpoints of endpoints die je later toevoegd. */ ) .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); } }
hogeschoolnovi/backend-spring-boot-tech-it-easy-security
src/techiteasy1121/config/SpringSecurityConfig.java
640
// Je kunt dit ook in een aparte configuratie klasse zetten.
line_comment
nl
package techiteasy1121.config; @Configuration @EnableWebSecurity public class SpringSecurityConfig { /*TODO inject customUserDetailService en 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, PasswordEncoder passwordEncoder) throws Exception { var auth = new DaoAuthenticationProvider(); auth.setPasswordEncoder(passwordEncoder); auth.setUserDetailsService(customUserDetailsService); return new ProviderManager(auth); } // Authorizatie met jwt @Bean protected SecurityFilterChain filter (HttpSecurity http) throws Exception { //JWT token authentication http .csrf(csrf -> csrf.disable()) .httpBasic(basic -> basic.disable()) .cors(Customizer.withDefaults()) .authorizeHttpRequests(auth -> auth // Wanneer je deze uncomments, staat je hele security open. Je hebt dan alleen nog een jwt nodig. // .requestMatchers("/**").permitAll() .requestMatchers(HttpMethod.POST, "/users").hasRole("ADMIN") .requestMatchers(HttpMethod.GET,"/users").hasRole("ADMIN") .requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN") /*TODO voeg de antmatchers toe voor admin(post en delete) en user (overige)*/ .requestMatchers("/authenticated").authenticated() .requestMatchers("/authenticate").permitAll()/*alleen dit punt mag toegankelijk zijn voor niet ingelogde gebruikers*/ .anyRequest().denyAll() /*Deze voeg je altijd als laatste toe, om een default beveiliging te hebben voor eventuele vergeten endpoints of endpoints die je later toevoegd. */ ) .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); } }
True
485
16
527
18
520
13
527
18
628
17
false
false
false
false
false
true
473
1684_13
/** * @author Vera Wise * @author Elias De Hondt * @since 08/12/2022 */ // ===================================================================================================================== /* * Canvas KdG * @see https://canvas.kdg.be/courses/37158/pages/afspraken-en-deadlines?module_item_id=663060 * * Github * @see https://github.com/EliasDeHondt/Memo-Race * * Google Docs * @see https://docs.google.com/spreadsheets/d/199y9TW0weDEmgGD8Iv0UWyqQnMW8zF_RrBZ8XB4lQBc/edit#gid=0 * */ // ===================================================================================================================== // TODO: - Voorzie een startscherm waar je de namen van de spelers kan ingeven. // - Elke speler kan een avatar kiezen of zelf een foto toevoegen. // - Voorzie een lijst op het scherm met eerder aangemaakte spelers. Sla deze op in een bestand. // - Zorg voor een mooi grafische vormgeving. // - Tijdens het spelverloop moet volgende zichtbaar zijn: // - Een dobbelsteen. // - Het speelveld met in het midden de omgedraaide kaarten. // - Per speler zijn naam, de avatar en de gewonnen kaarten. // - Een pion die automatisch verplaatst na een worp. // - Kaarten moeten met de muis omgedraaid kunnen worden. // - Als een figuur gevonden is moet het overeenkomstige vak een alternatieve opmaak // (bv. donkerder) krijgen zodat duidelijk is dat de pion deze vakken mag overslaan. // - Maak visueel zichtbaar welke speler aan de beurt is. // ===================================================================================================================== // SPELBESCHRIJVING /* * MemoRace is een variant op memory, maar een dobbelsteen zorgt voor een extra dimensie. Het * spel leert kinderen dezelfde vaardigheden als Memory en de dobbelsteen bevorderd het tellen. * Een pion loopt op een pad met in elk vak een verschillende afbeelding rond een speelveld. In het * speelveld liggen omgedraaide kaarten met de verschillende afbeeldingen. De spelers moeten * zoveel mogelijk van de afbeeldingen op het pad terugvinden bij de omgedraaide kaarten in het * midden van het speelveld. De speler die op het einde de meeste kaarten gevonden heeft wint * het spel. Het kan gespeeld worden met 2 tot 6 spelers * Hieronder een overzicht van de belangrijkste spelonderdelen: * • een spelbord * • 16 kaarten die willekeurig in het midden van het spelbord gelegd worden * • 1 dobbelsteen * • 1 pion */ // ===================================================================================================================== // SPELVERLOOP /* * Er wordt om de beurt gespeeld. Het spel beslist random in welke * volgorde de spelers mogen spelen. De pion start op “go”. De eerste * speler werpt de dobbelsteen en zet de pion evenveel vakken (groene * genummerd in de afbeelding) vooruit. Elk vak toont een afbeelding. * Het is de bedoeling dat de speler de kaart met dezelfde afbeelding * omdraait (kaarten zijn de witte vakjes in de afbeelding). Als dat lukt, * dan krijgt hij de kaart. In het andere geval wordt de kaart terug * omgedraaid. Hierna is de beurt van deze speler om en is het aan de * volgende speler. Hij gooit en verplaatst de pion. Ook hij moet proberen * die kaart om te draaien die overeenkomt met de afbeelding van het * vak waar de pion nu op staat. Het spel loopt zo verder tot alle kaarten van het veld verdwenen * zijn. De persoon met de meeste kaarten wint het spel. De pion slaat de vakken met reeds * gevonden figuren en de hoekvakken over. */ // =====================================================================================================================
EliasDeHondt/Memo-Race
TODO.java
1,134
// (bv. donkerder) krijgen zodat duidelijk is dat de pion deze vakken mag overslaan.
line_comment
nl
/** * @author Vera Wise * @author Elias De Hondt * @since 08/12/2022 */ // ===================================================================================================================== /* * Canvas KdG * @see https://canvas.kdg.be/courses/37158/pages/afspraken-en-deadlines?module_item_id=663060 * * Github * @see https://github.com/EliasDeHondt/Memo-Race * * Google Docs * @see https://docs.google.com/spreadsheets/d/199y9TW0weDEmgGD8Iv0UWyqQnMW8zF_RrBZ8XB4lQBc/edit#gid=0 * */ // ===================================================================================================================== // TODO: - Voorzie een startscherm waar je de namen van de spelers kan ingeven. // - Elke speler kan een avatar kiezen of zelf een foto toevoegen. // - Voorzie een lijst op het scherm met eerder aangemaakte spelers. Sla deze op in een bestand. // - Zorg voor een mooi grafische vormgeving. // - Tijdens het spelverloop moet volgende zichtbaar zijn: // - Een dobbelsteen. // - Het speelveld met in het midden de omgedraaide kaarten. // - Per speler zijn naam, de avatar en de gewonnen kaarten. // - Een pion die automatisch verplaatst na een worp. // - Kaarten moeten met de muis omgedraaid kunnen worden. // - Als een figuur gevonden is moet het overeenkomstige vak een alternatieve opmaak // (bv. donkerder)<SUF> // - Maak visueel zichtbaar welke speler aan de beurt is. // ===================================================================================================================== // SPELBESCHRIJVING /* * MemoRace is een variant op memory, maar een dobbelsteen zorgt voor een extra dimensie. Het * spel leert kinderen dezelfde vaardigheden als Memory en de dobbelsteen bevorderd het tellen. * Een pion loopt op een pad met in elk vak een verschillende afbeelding rond een speelveld. In het * speelveld liggen omgedraaide kaarten met de verschillende afbeeldingen. De spelers moeten * zoveel mogelijk van de afbeeldingen op het pad terugvinden bij de omgedraaide kaarten in het * midden van het speelveld. De speler die op het einde de meeste kaarten gevonden heeft wint * het spel. Het kan gespeeld worden met 2 tot 6 spelers * Hieronder een overzicht van de belangrijkste spelonderdelen: * • een spelbord * • 16 kaarten die willekeurig in het midden van het spelbord gelegd worden * • 1 dobbelsteen * • 1 pion */ // ===================================================================================================================== // SPELVERLOOP /* * Er wordt om de beurt gespeeld. Het spel beslist random in welke * volgorde de spelers mogen spelen. De pion start op “go”. De eerste * speler werpt de dobbelsteen en zet de pion evenveel vakken (groene * genummerd in de afbeelding) vooruit. Elk vak toont een afbeelding. * Het is de bedoeling dat de speler de kaart met dezelfde afbeelding * omdraait (kaarten zijn de witte vakjes in de afbeelding). Als dat lukt, * dan krijgt hij de kaart. In het andere geval wordt de kaart terug * omgedraaid. Hierna is de beurt van deze speler om en is het aan de * volgende speler. Hij gooit en verplaatst de pion. Ook hij moet proberen * die kaart om te draaien die overeenkomt met de afbeelding van het * vak waar de pion nu op staat. Het spel loopt zo verder tot alle kaarten van het veld verdwenen * zijn. De persoon met de meeste kaarten wint het spel. De pion slaat de vakken met reeds * gevonden figuren en de hoekvakken over. */ // =====================================================================================================================
True
1,019
30
1,166
32
948
23
1,166
32
1,152
34
false
false
false
false
false
true
4,152
43972_0
package prog2.util; import java.util.Random; public class Noise { /* Perlin Noise generator genomen en aangepast van https://stackoverflow.com/questions/5531019/perlin-noise-in-java door jt78 * deze wordt gebruikt voor het genereren van mooiere patronen voor de achtergrondtegels */ private final Random rand_; private final float roughness_; private final float[][] grid; public Noise(Random rand, float roughness, int width, int height) { roughness_ = roughness / width; grid = new float[width][height]; rand_ = (rand == null) ? new Random() : rand; } public void initialise() { int xh = grid.length - 1; int yh = grid[0].length - 1; grid[0][0] = rand_.nextFloat() - 0.5f; grid[0][yh] = rand_.nextFloat() - 0.5f; grid[xh][0] = rand_.nextFloat() - 0.5f; grid[xh][yh] = rand_.nextFloat() - 0.5f; generate(0, 0, xh, yh); } private float roughen(float v, int l, int h) { return v + roughness_ * (float) (rand_.nextGaussian() * (h - l)); } private void generate(int xl, int yl, int xh, int yh) { int xm = (xl + xh) / 2; int ym = (yl + yh) / 2; if ((xl == xm) && (yl == ym)) return; grid[xm][yl] = 0.5f * (grid[xl][yl] + grid[xh][yl]); grid[xm][yh] = 0.5f * (grid[xl][yh] + grid[xh][yh]); grid[xl][ym] = 0.5f * (grid[xl][yl] + grid[xl][yh]); grid[xh][ym] = 0.5f * (grid[xh][yl] + grid[xh][yh]); float v = roughen(0.5f * (grid[xm][yl] + grid[xm][yh]), xl + yl, yh + xh); grid[xm][ym] = v; grid[xm][yl] = roughen(grid[xm][yl], xl, xh); grid[xm][yh] = roughen(grid[xm][yh], xl, xh); grid[xl][ym] = roughen(grid[xl][ym], yl, yh); grid[xh][ym] = roughen(grid[xh][ym], yl, yh); generate(xl, yl, xm, ym); generate(xm, yl, xh, ym); generate(xl, ym, xm, yh); generate(xm, ym, xh, yh); } public float[][] getGrid() { return grid; } }
renevds/polis
src/prog2/util/Noise.java
828
/* Perlin Noise generator genomen en aangepast van https://stackoverflow.com/questions/5531019/perlin-noise-in-java door jt78 * deze wordt gebruikt voor het genereren van mooiere patronen voor de achtergrondtegels */
block_comment
nl
package prog2.util; import java.util.Random; public class Noise { /* Perlin Noise generator<SUF>*/ private final Random rand_; private final float roughness_; private final float[][] grid; public Noise(Random rand, float roughness, int width, int height) { roughness_ = roughness / width; grid = new float[width][height]; rand_ = (rand == null) ? new Random() : rand; } public void initialise() { int xh = grid.length - 1; int yh = grid[0].length - 1; grid[0][0] = rand_.nextFloat() - 0.5f; grid[0][yh] = rand_.nextFloat() - 0.5f; grid[xh][0] = rand_.nextFloat() - 0.5f; grid[xh][yh] = rand_.nextFloat() - 0.5f; generate(0, 0, xh, yh); } private float roughen(float v, int l, int h) { return v + roughness_ * (float) (rand_.nextGaussian() * (h - l)); } private void generate(int xl, int yl, int xh, int yh) { int xm = (xl + xh) / 2; int ym = (yl + yh) / 2; if ((xl == xm) && (yl == ym)) return; grid[xm][yl] = 0.5f * (grid[xl][yl] + grid[xh][yl]); grid[xm][yh] = 0.5f * (grid[xl][yh] + grid[xh][yh]); grid[xl][ym] = 0.5f * (grid[xl][yl] + grid[xl][yh]); grid[xh][ym] = 0.5f * (grid[xh][yl] + grid[xh][yh]); float v = roughen(0.5f * (grid[xm][yl] + grid[xm][yh]), xl + yl, yh + xh); grid[xm][ym] = v; grid[xm][yl] = roughen(grid[xm][yl], xl, xh); grid[xm][yh] = roughen(grid[xm][yh], xl, xh); grid[xl][ym] = roughen(grid[xl][ym], yl, yh); grid[xh][ym] = roughen(grid[xh][ym], yl, yh); generate(xl, yl, xm, ym); generate(xm, yl, xh, ym); generate(xl, ym, xm, yh); generate(xm, ym, xh, yh); } public float[][] getGrid() { return grid; } }
False
701
60
730
68
732
59
730
68
829
70
false
false
false
false
false
true
89
104020_5
package des; import java.util.BitSet; /** * Author: allight */ public class Des { public static final boolean LITTLE_ENDIAN = true; public static final boolean BIG_ENDIAN = false; private static final char HIGH_PART_CHAR_MASK = 0xFF00; private static final char LOW_PART_CHAR_MASK = 0x00FF; protected static final int FEISTEL_CYCLES_NUM = 16; private static final int[] INITIAL_PERMUTATION_TABLE = { 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7, 56, 48, 40, 32, 24, 16, 8, 0, 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6 }; private Block initialPermutation(Block inputBlock) { BitSet result = new BitSet(Block.LENGTH); for (int i = 0; i < Block.LENGTH; ++i) result.set(i, inputBlock.get(INITIAL_PERMUTATION_TABLE[i])); return new Block(result); } private Block finalPermutation(Block inputBlock) { BitSet result = new BitSet(Block.LENGTH); for (int i = 0; i < Block.LENGTH; ++i) result.set(INITIAL_PERMUTATION_TABLE[i], inputBlock.get(i)); return new Block(result); } public BitSet encrypt(BitSet input, Key key) { int size = input.size(); BitSet output = new BitSet(size); for (int i = 0; i < size; i += Block.LENGTH) { Block block = new Block(input.get(i, i + Block.LENGTH)); // printBin("block", block.get(), true, 64); // printBin("IP", initialPermutation(block).get(), true, 64); PairLR t = new PairLR(initialPermutation(block)); for (int j = 0; j < FEISTEL_CYCLES_NUM; j++) { // printBin("L" + j, t.getLeft().get(), true, 32); // printBin("R" + j, t.getRight().get(), true, 32); // printHex("L" + j, t.getLeft().get(), true, 32); // printHex("R" + j, t.getRight().get(), true, 32); t = feistelCell(t, key.nextSubKey()); } // printBin("L16", t.getLeft().get(), true, 32); // printBin("R16", t.getRight().get(), true, 32); block = finalPermutation(new Block(t.swap())); for (int j = i, k = 0; k < Block.LENGTH; j++, k++) output.set(j, block.get(k)); } return output; } public BitSet decrypt(BitSet input, Key key) { int size = input.size(); BitSet output = new BitSet(size); for (int i = 0; i < size; i += Block.LENGTH) { Block block = new Block(input.get(i, i + Block.LENGTH)); PairLR t = new PairLR(initialPermutation(block)).swap(); for (int j = 0; j < FEISTEL_CYCLES_NUM; j++) { t = feistelCellInverse(t, key.prevSubKey()); } block = finalPermutation(new Block(t)); for (int j = i, k = 0; k < Block.LENGTH; j++, k++) output.set(j, block.get(k)); } return output; } private PairLR feistelCell(PairLR tPrev, ExtHalfBlock key) { HalfBlock lNext = tPrev.getRight(); BitSet rNext = tPrev.getLeft().get(); rNext.xor(feistelEncrypt(tPrev.getRight(), key).get()); return new PairLR(lNext, new HalfBlock(rNext)); } private PairLR feistelCellInverse(PairLR tNext, ExtHalfBlock key) { HalfBlock rPrev = tNext.getLeft(); BitSet lPrev = tNext.getRight().get(); lPrev.xor(feistelEncrypt(tNext.getLeft(), key).get()); return new PairLR(new HalfBlock(lPrev), rPrev); } private HalfBlock feistelEncrypt(HalfBlock rPrev, ExtHalfBlock key) { // printBin("\tK ", key.get(), true, 48); // printBin("\tRpr", rPrev.get(), true, 32); ExtHalfBlock r = new ExtHalfBlock(rPrev); // printBin("\tEr ", r.get(), true, 48); r.get().xor(key.get()); // printBin("\tK+E", r.get(), true, 48); HalfBlock hb = new HalfBlock(r); // printBin("\tSB ", hb.get(), true, 32); // printBin("\tP ", hb.permutation().get(), true, 32); return hb.permutation(); } public static byte[] stringToBytes(String str) { char[] buffer = str.toCharArray(); int length = buffer.length; byte[] b = new byte[length << 1]; for (int i = 0; i < length; i++) { int bPos = i << 1; b[bPos] = (byte) ((buffer[i] & HIGH_PART_CHAR_MASK) >> 8); b[bPos + 1] = (byte) (buffer[i] & LOW_PART_CHAR_MASK); } return b; } public static String bytesToString(byte[] bytes) { char[] buffer = new char[bytes.length >> 1]; int length = buffer.length; for (int i = 0; i < length; i++) { int bPos = i << 1; buffer[i] = (char) (((bytes[bPos] & LOW_PART_CHAR_MASK) << 8) + (bytes[bPos + 1] & LOW_PART_CHAR_MASK)); } return new String(buffer); } public String encryptString(String input, Key key) { BitSet inputBitSet = BitSet.valueOf(stringToBytes(input)); BitSet outputBitSet = encrypt(inputBitSet, key); assert (inputBitSet.size() == outputBitSet.size()); return bytesToString(outputBitSet.toByteArray()); } public String decryptString(String input, Key key) { BitSet inputBitSet = BitSet.valueOf(stringToBytes(input)); BitSet outputBitSet = decrypt(inputBitSet, key); assert (inputBitSet.size() == outputBitSet.size()); return bytesToString(outputBitSet.toByteArray()); } protected static BitSet swapDirection(BitSet in, int size) { BitSet result = new BitSet(size); for (int i = 0, j = size - 1; j >= 0; i++, j--) result.set(i, in.get(j)); return result; } public static void printHex(String name, BitSet bs, boolean reverse, int BitSize) { if (reverse) bs = swapDirection(bs, BitSize); String s = String.format("%" + BitSize / 4 + "s", Long.toHexString(bs.cardinality() == 0 ? 0x0L : bs.toLongArray()[0])).replace(' ', '0'); System.out.println(name + " = " + s); } public static void printBin(String name, BitSet bs, boolean reverse, int bitSize) { if (reverse) bs = swapDirection(bs, bitSize); String s = String.format("%" + bitSize + "s", Long.toBinaryString(bs.cardinality() == 0 ? 0x0L : bs.toLongArray()[0])).replace(' ', '0'); System.out.println(name + " = " + s); } }
Allight7/ru.ifmo.cryptography.des
src/main/java/des/Des.java
2,310
// printHex("L" + j, t.getLeft().get(), true, 32);
line_comment
nl
package des; import java.util.BitSet; /** * Author: allight */ public class Des { public static final boolean LITTLE_ENDIAN = true; public static final boolean BIG_ENDIAN = false; private static final char HIGH_PART_CHAR_MASK = 0xFF00; private static final char LOW_PART_CHAR_MASK = 0x00FF; protected static final int FEISTEL_CYCLES_NUM = 16; private static final int[] INITIAL_PERMUTATION_TABLE = { 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7, 56, 48, 40, 32, 24, 16, 8, 0, 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6 }; private Block initialPermutation(Block inputBlock) { BitSet result = new BitSet(Block.LENGTH); for (int i = 0; i < Block.LENGTH; ++i) result.set(i, inputBlock.get(INITIAL_PERMUTATION_TABLE[i])); return new Block(result); } private Block finalPermutation(Block inputBlock) { BitSet result = new BitSet(Block.LENGTH); for (int i = 0; i < Block.LENGTH; ++i) result.set(INITIAL_PERMUTATION_TABLE[i], inputBlock.get(i)); return new Block(result); } public BitSet encrypt(BitSet input, Key key) { int size = input.size(); BitSet output = new BitSet(size); for (int i = 0; i < size; i += Block.LENGTH) { Block block = new Block(input.get(i, i + Block.LENGTH)); // printBin("block", block.get(), true, 64); // printBin("IP", initialPermutation(block).get(), true, 64); PairLR t = new PairLR(initialPermutation(block)); for (int j = 0; j < FEISTEL_CYCLES_NUM; j++) { // printBin("L" + j, t.getLeft().get(), true, 32); // printBin("R" + j, t.getRight().get(), true, 32); // printHex("L" +<SUF> // printHex("R" + j, t.getRight().get(), true, 32); t = feistelCell(t, key.nextSubKey()); } // printBin("L16", t.getLeft().get(), true, 32); // printBin("R16", t.getRight().get(), true, 32); block = finalPermutation(new Block(t.swap())); for (int j = i, k = 0; k < Block.LENGTH; j++, k++) output.set(j, block.get(k)); } return output; } public BitSet decrypt(BitSet input, Key key) { int size = input.size(); BitSet output = new BitSet(size); for (int i = 0; i < size; i += Block.LENGTH) { Block block = new Block(input.get(i, i + Block.LENGTH)); PairLR t = new PairLR(initialPermutation(block)).swap(); for (int j = 0; j < FEISTEL_CYCLES_NUM; j++) { t = feistelCellInverse(t, key.prevSubKey()); } block = finalPermutation(new Block(t)); for (int j = i, k = 0; k < Block.LENGTH; j++, k++) output.set(j, block.get(k)); } return output; } private PairLR feistelCell(PairLR tPrev, ExtHalfBlock key) { HalfBlock lNext = tPrev.getRight(); BitSet rNext = tPrev.getLeft().get(); rNext.xor(feistelEncrypt(tPrev.getRight(), key).get()); return new PairLR(lNext, new HalfBlock(rNext)); } private PairLR feistelCellInverse(PairLR tNext, ExtHalfBlock key) { HalfBlock rPrev = tNext.getLeft(); BitSet lPrev = tNext.getRight().get(); lPrev.xor(feistelEncrypt(tNext.getLeft(), key).get()); return new PairLR(new HalfBlock(lPrev), rPrev); } private HalfBlock feistelEncrypt(HalfBlock rPrev, ExtHalfBlock key) { // printBin("\tK ", key.get(), true, 48); // printBin("\tRpr", rPrev.get(), true, 32); ExtHalfBlock r = new ExtHalfBlock(rPrev); // printBin("\tEr ", r.get(), true, 48); r.get().xor(key.get()); // printBin("\tK+E", r.get(), true, 48); HalfBlock hb = new HalfBlock(r); // printBin("\tSB ", hb.get(), true, 32); // printBin("\tP ", hb.permutation().get(), true, 32); return hb.permutation(); } public static byte[] stringToBytes(String str) { char[] buffer = str.toCharArray(); int length = buffer.length; byte[] b = new byte[length << 1]; for (int i = 0; i < length; i++) { int bPos = i << 1; b[bPos] = (byte) ((buffer[i] & HIGH_PART_CHAR_MASK) >> 8); b[bPos + 1] = (byte) (buffer[i] & LOW_PART_CHAR_MASK); } return b; } public static String bytesToString(byte[] bytes) { char[] buffer = new char[bytes.length >> 1]; int length = buffer.length; for (int i = 0; i < length; i++) { int bPos = i << 1; buffer[i] = (char) (((bytes[bPos] & LOW_PART_CHAR_MASK) << 8) + (bytes[bPos + 1] & LOW_PART_CHAR_MASK)); } return new String(buffer); } public String encryptString(String input, Key key) { BitSet inputBitSet = BitSet.valueOf(stringToBytes(input)); BitSet outputBitSet = encrypt(inputBitSet, key); assert (inputBitSet.size() == outputBitSet.size()); return bytesToString(outputBitSet.toByteArray()); } public String decryptString(String input, Key key) { BitSet inputBitSet = BitSet.valueOf(stringToBytes(input)); BitSet outputBitSet = decrypt(inputBitSet, key); assert (inputBitSet.size() == outputBitSet.size()); return bytesToString(outputBitSet.toByteArray()); } protected static BitSet swapDirection(BitSet in, int size) { BitSet result = new BitSet(size); for (int i = 0, j = size - 1; j >= 0; i++, j--) result.set(i, in.get(j)); return result; } public static void printHex(String name, BitSet bs, boolean reverse, int BitSize) { if (reverse) bs = swapDirection(bs, BitSize); String s = String.format("%" + BitSize / 4 + "s", Long.toHexString(bs.cardinality() == 0 ? 0x0L : bs.toLongArray()[0])).replace(' ', '0'); System.out.println(name + " = " + s); } public static void printBin(String name, BitSet bs, boolean reverse, int bitSize) { if (reverse) bs = swapDirection(bs, bitSize); String s = String.format("%" + bitSize + "s", Long.toBinaryString(bs.cardinality() == 0 ? 0x0L : bs.toLongArray()[0])).replace(' ', '0'); System.out.println(name + " = " + s); } }
False
1,894
21
2,120
23
2,180
22
2,120
23
2,389
24
false
false
false
false
false
true
850
36825_1
package app; import java.util.Scanner; import java.io.FileWriter; import java.io.IOException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class App { static ChatClient client; static boolean shouldLog = false; static String[] kamers = {"Zolder", "Woonkamer", "WC"}; public static void main(String[] args) throws Exception { System.out.println("Welkom bij deze chatapp, we hebben uw naam nodig om te kunnen chatten.."); String username = getUserInput("Wat is uw naam?"); // start de chatclient client = new ChatClient(); client.start(username, new IWantNewMessages(){ @Override public void processNewMessage(String message) { while (message.contains("room ")) { char roomnumber = message.charAt(message.indexOf("room ") + 5); if (roomnumber != 'u') { int roomno = Integer.parseInt(roomnumber + ""); String kamer = kamers[roomno-1]; message = message.replace("room " + roomno,kamer); } else { message = message.replace("room undefined", "onbekend"); } } System.out.println(Log("SERVER SENDS: " + message)); } }); client.sendMessage(Log("USER:" + username)); // zolang de gebruiker iets wil, doen we dat String command = getUserInput("client :>"); while (!command.equals("q")){ processCommand(command); command = getUserInput("client :>"); } System.out.println("Ok, bye!"); } public static void processCommand(String command){ switch (command) { case "h": { System.out.println("De beschikbare commando's zijn: "); System.out.println("\th: toont deze hulp functie"); System.out.println("\tq: eindigt dit programma"); System.out.println("\tr: verander van kamer"); System.out.println("\ts: stuur een bericht"); System.out.println("\tx: voer een ban uit (admin only)"); System.out.println("\tb: vraag om een ban"); System.out.println("\t?: vraag om status informatie"); break; } case "r": { System.out.println("De beschikbare kamers zijn: "); for (int i = 0; i < kamers.length; i++) { System.out.println("\th: " + (i + 1) + ". " + kamers[i]); } String kamer = getUserInput("Welke kamer wilt u in?"); client.sendMessage(Log("ROOM:" + kamer)); break; } case "s": { String datatosend = getUserInput("Wat wilt u versturen?"); client.sendMessage(Log("MESSAGE:" + datatosend )); break; } case "log": { shouldLog = !shouldLog; System.out.println(Log("Logging is set to " + shouldLog)); break; } case "x": { String user = getUserInput("execute ban on user?"); client.sendMessage(Log("EXECUTEBAN:" + user )); break; } case "xx": { String user = getUserInput("execute superban on?"); client.sendMessage(Log("EXECUTEBAN2:" + user )); break; } case "b": { String user = getUserInput("Wie wilt u bannen?"); client.sendMessage(Log("BAN:" + user )); break; } case "?": { client.sendMessage(Log("STATUS")); break; } default: { System.out.println(Log("onbekend commando!")); break; } } } public static String Log(String line) { if (shouldLog) { try { FileWriter logFile = new FileWriter("./log.txt", true); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); LocalDateTime now = LocalDateTime.now(); logFile.append(dtf.format(now) + " " + line + "\r\n"); logFile.close(); } catch (IOException io){ System.out.println("error: " + io.getMessage()); } } return line; } public static String getUserInput(String prompt){ System.out.println(prompt); Scanner s = new Scanner(System.in); String data = s.nextLine(); return data; } }
JohnGorter/JavaChatDemo
src/app/App.java
1,250
// zolang de gebruiker iets wil, doen we dat
line_comment
nl
package app; import java.util.Scanner; import java.io.FileWriter; import java.io.IOException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class App { static ChatClient client; static boolean shouldLog = false; static String[] kamers = {"Zolder", "Woonkamer", "WC"}; public static void main(String[] args) throws Exception { System.out.println("Welkom bij deze chatapp, we hebben uw naam nodig om te kunnen chatten.."); String username = getUserInput("Wat is uw naam?"); // start de chatclient client = new ChatClient(); client.start(username, new IWantNewMessages(){ @Override public void processNewMessage(String message) { while (message.contains("room ")) { char roomnumber = message.charAt(message.indexOf("room ") + 5); if (roomnumber != 'u') { int roomno = Integer.parseInt(roomnumber + ""); String kamer = kamers[roomno-1]; message = message.replace("room " + roomno,kamer); } else { message = message.replace("room undefined", "onbekend"); } } System.out.println(Log("SERVER SENDS: " + message)); } }); client.sendMessage(Log("USER:" + username)); // zolang de<SUF> String command = getUserInput("client :>"); while (!command.equals("q")){ processCommand(command); command = getUserInput("client :>"); } System.out.println("Ok, bye!"); } public static void processCommand(String command){ switch (command) { case "h": { System.out.println("De beschikbare commando's zijn: "); System.out.println("\th: toont deze hulp functie"); System.out.println("\tq: eindigt dit programma"); System.out.println("\tr: verander van kamer"); System.out.println("\ts: stuur een bericht"); System.out.println("\tx: voer een ban uit (admin only)"); System.out.println("\tb: vraag om een ban"); System.out.println("\t?: vraag om status informatie"); break; } case "r": { System.out.println("De beschikbare kamers zijn: "); for (int i = 0; i < kamers.length; i++) { System.out.println("\th: " + (i + 1) + ". " + kamers[i]); } String kamer = getUserInput("Welke kamer wilt u in?"); client.sendMessage(Log("ROOM:" + kamer)); break; } case "s": { String datatosend = getUserInput("Wat wilt u versturen?"); client.sendMessage(Log("MESSAGE:" + datatosend )); break; } case "log": { shouldLog = !shouldLog; System.out.println(Log("Logging is set to " + shouldLog)); break; } case "x": { String user = getUserInput("execute ban on user?"); client.sendMessage(Log("EXECUTEBAN:" + user )); break; } case "xx": { String user = getUserInput("execute superban on?"); client.sendMessage(Log("EXECUTEBAN2:" + user )); break; } case "b": { String user = getUserInput("Wie wilt u bannen?"); client.sendMessage(Log("BAN:" + user )); break; } case "?": { client.sendMessage(Log("STATUS")); break; } default: { System.out.println(Log("onbekend commando!")); break; } } } public static String Log(String line) { if (shouldLog) { try { FileWriter logFile = new FileWriter("./log.txt", true); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); LocalDateTime now = LocalDateTime.now(); logFile.append(dtf.format(now) + " " + line + "\r\n"); logFile.close(); } catch (IOException io){ System.out.println("error: " + io.getMessage()); } } return line; } public static String getUserInput(String prompt){ System.out.println(prompt); Scanner s = new Scanner(System.in); String data = s.nextLine(); return data; } }
True
951
12
1,075
15
1,139
13
1,075
15
1,261
15
false
false
false
false
false
true
297
158361_1
package me.goowen.kitpvp.modules.kits; import me.goowen.kitpvp.Kitpvp; import me.goowen.kitpvp.modules.config.ConfigModule; import me.goowen.kitpvp.modules.utilities.ItemBuilder; import org.bukkit.ChatColor; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import java.util.List; import java.util.Objects; public class KitsManager { private ConfigModule configModule = Kitpvp.getConfigModule(); private Kitpvp plugin = Kitpvp.getInstance(); /** * Slaat de kit op in een config vanuit de spelers inventory op basis van naam! * @param player de speler wiens inventory moet worden opgeslagen als kit! * @param name de naam van de kit! */ public void saveKit(Player player, String name) { configModule.getKitsConfig().getConfigConfiguration().set("kits." + name + ".armor", player.getInventory().getArmorContents()); configModule.getKitsConfig().getConfigConfiguration().set("kits." + name + ".items", player.getInventory().getContents()); configModule.getKitsConfig().getConfigConfiguration().set("kits." + name + ".icon", new ItemBuilder(player.getInventory().getItemInMainHand().clone()).setName(ChatColor.DARK_AQUA + name).addLoreLine(ChatColor.GRAY + "" + ChatColor.UNDERLINE + "Click to select this kit").toItemStack()); configModule.getKitsConfig().saveAsync(configModule.getKitsConfig()); } public void deleteKit(String name) { configModule.getKitsConfig().getConfigConfiguration().set("kits." + name, null); configModule.getKitsConfig().saveAsync(configModule.getKitsConfig()); } /** * Haalt de kit op uit de config en zet hem om in een inventory. * Geeft de zojuist opgehaalde kit aan de speler. * @param player de speler die de kit moet krijgen. * @param name de naam van de kit die de speler moet krijgen. */ @SuppressWarnings("unchecked") public void giveKit(Player player, String name) { FileConfiguration kitsConfig = configModule.getKitsConfig().getConfigConfiguration(); //Haalt de armor op een geeft deze. ItemStack[] content = ((List<ItemStack>) Objects.requireNonNull(kitsConfig.get("kits." + name + ".armor"))).toArray(new ItemStack[0]); player.getInventory().setArmorContents(content); //Haalt de Items in de inventory op een geeft deze. content = ((List<ItemStack>) Objects.requireNonNull(kitsConfig.get("kits." + name + ".items"))).toArray(new ItemStack[0]); player.getInventory().setContents(content); } /** * Maakt het kits menu aan en toont hem aan de speler. * @param player de speler die het menu moet krijgen */ public void kitsMenu(Player player) { try { //Maakt de inventory aan. Inventory kits = plugin.getServer().createInventory(null, 9, ChatColor.DARK_AQUA + "Kies een Kit!"); for(String name : configModule.getKitsConfig().getConfigConfiguration().getConfigurationSection("kits").getKeys(false)) { kits.addItem(configModule.getKitsConfig().getConfigConfiguration().getItemStack("kits." + name + ".icon")); } //Toont(Opent) de inventory aan de speler. player.openInventory(kits); } catch (NullPointerException exeption) { player.sendMessage(ChatColor.RED + "There are not current kits, please make some!"); } } }
Caaarlowsz/Kitpvp-21
src/main/java/me/goowen/kitpvp/modules/kits/KitsManager.java
1,043
/** * Haalt de kit op uit de config en zet hem om in een inventory. * Geeft de zojuist opgehaalde kit aan de speler. * @param player de speler die de kit moet krijgen. * @param name de naam van de kit die de speler moet krijgen. */
block_comment
nl
package me.goowen.kitpvp.modules.kits; import me.goowen.kitpvp.Kitpvp; import me.goowen.kitpvp.modules.config.ConfigModule; import me.goowen.kitpvp.modules.utilities.ItemBuilder; import org.bukkit.ChatColor; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import java.util.List; import java.util.Objects; public class KitsManager { private ConfigModule configModule = Kitpvp.getConfigModule(); private Kitpvp plugin = Kitpvp.getInstance(); /** * Slaat de kit op in een config vanuit de spelers inventory op basis van naam! * @param player de speler wiens inventory moet worden opgeslagen als kit! * @param name de naam van de kit! */ public void saveKit(Player player, String name) { configModule.getKitsConfig().getConfigConfiguration().set("kits." + name + ".armor", player.getInventory().getArmorContents()); configModule.getKitsConfig().getConfigConfiguration().set("kits." + name + ".items", player.getInventory().getContents()); configModule.getKitsConfig().getConfigConfiguration().set("kits." + name + ".icon", new ItemBuilder(player.getInventory().getItemInMainHand().clone()).setName(ChatColor.DARK_AQUA + name).addLoreLine(ChatColor.GRAY + "" + ChatColor.UNDERLINE + "Click to select this kit").toItemStack()); configModule.getKitsConfig().saveAsync(configModule.getKitsConfig()); } public void deleteKit(String name) { configModule.getKitsConfig().getConfigConfiguration().set("kits." + name, null); configModule.getKitsConfig().saveAsync(configModule.getKitsConfig()); } /** * Haalt de kit<SUF>*/ @SuppressWarnings("unchecked") public void giveKit(Player player, String name) { FileConfiguration kitsConfig = configModule.getKitsConfig().getConfigConfiguration(); //Haalt de armor op een geeft deze. ItemStack[] content = ((List<ItemStack>) Objects.requireNonNull(kitsConfig.get("kits." + name + ".armor"))).toArray(new ItemStack[0]); player.getInventory().setArmorContents(content); //Haalt de Items in de inventory op een geeft deze. content = ((List<ItemStack>) Objects.requireNonNull(kitsConfig.get("kits." + name + ".items"))).toArray(new ItemStack[0]); player.getInventory().setContents(content); } /** * Maakt het kits menu aan en toont hem aan de speler. * @param player de speler die het menu moet krijgen */ public void kitsMenu(Player player) { try { //Maakt de inventory aan. Inventory kits = plugin.getServer().createInventory(null, 9, ChatColor.DARK_AQUA + "Kies een Kit!"); for(String name : configModule.getKitsConfig().getConfigConfiguration().getConfigurationSection("kits").getKeys(false)) { kits.addItem(configModule.getKitsConfig().getConfigConfiguration().getItemStack("kits." + name + ".icon")); } //Toont(Opent) de inventory aan de speler. player.openInventory(kits); } catch (NullPointerException exeption) { player.sendMessage(ChatColor.RED + "There are not current kits, please make some!"); } } }
True
806
74
931
79
918
74
931
79
1,095
89
false
false
false
false
false
true
2,644
55340_6
//200 gram ongezouten roomboter //200 gram witte bastard suiker //400 gram zelfrijzend bakmeel //1 stuk(s) ei //8 gram vanillesuiker //1 snuf zout //1.5 kilo zoetzure appels //75 gram kristal suiker //3 theelepels kaneel //15 gram paneermeel public class applePieRecipe { Ingredients boter = new Ingredients(200,"gram","ongezouten roomboter"); Ingredients suiker = new Ingredients(200, "gram", "witte bastard suiker"); Ingredients bakmeel = new Ingredients(400,"gram", "zelfrijzend bakmeel"); Ingredients ei = new Ingredients(1, "stuk", "ei"); Ingredients vanillesuiker = new Ingredients(8, "gram", "vanillesuiker"); Ingredients zout = new Ingredients(1, "snuf", "zout"); Ingredients appels = new Ingredients(1.5, "kilo", "zoetzure appels"); Ingredients kristalsuiker = new Ingredients(75, "gram", "kristalsuiker"); Ingredients kaneel = new Ingredients(3, "theelepels", "kaneel"); Ingredients paneermeel = new Ingredients(15, "gram", "paneermeel"); public void voorverwarmen(){ System.out.println("Verwarm de oven van te voren op 170 graden Celsius (boven en onderwarmte)"); }; public void opkloppen(){ System.out.println("Klop het ei los en verdeel deze in twee delen. De ene helft is voor het deeg, " + "het andere deel is voor het bestrijken van de appeltaart."); }; public void mix(){ System.out.println("Meng de boter, bastard suiker, zelfrijzend bakmeel, een helft van het ei, vanille suiker en een snufje zout tot een stevig deeg en verdeel deze in 3 gelijke delen."); }; public void schilMeng(){ System.out.println("Schil nu de appels en snij deze in plakjes. Vermeng in een kopje de suiker en kaneel."); }; public void invetten() { System.out.println("Vet de springvorm in en bestrooi deze met bloem"); } public void deeg() { System.out.println("Gebruik een deel van het deeg om de bodem van de vorm te bedekken. Gebruik een deel van het deeg om de rand van de springvorm te bekleden. Strooi het paneermeel op de bodem van de beklede vorm. De paneermeel neemt het vocht van de appels op."); } public void appelbereiding() { System.out.println("Doe de heft van de appels in de vorm en strooi hier 1/3 van het kaneel-suiker mengsel overheen. Meng de ander helft van de appels met het overgebleven kaneel-suiker mengsel en leg deze in de vorm."); } public void bovenkant() { System.out.println("Rol het laatste deel van de deeg uit tot een dunne lap en snij stroken van ongeveer 1 cm breed."); } public void look() { System.out.println("Leg de stroken kuislings op de appeltaart. Met wat extra deegstroken werk je de rand rondom af. Gebruik het overgebleven ei om de bovenkant van het deeg te bestrijken"); } public void bakken() { System.out.println("Zet de taart iets onder het midden van de oven. Bak de taart in 60 minuten op 170 graden Celsius (boven en onderwarmte) gaar en goudbruin."); } public void stappenplan () { System.out.println("doorloop de volgende stappen"); voorverwarmen(); opkloppen(); mix(); schilMeng(); invetten(); deeg(); appelbereiding(); bovenkant(); look(); bakken(); } public void ingredientenlijst () { System.out.println(ei); System.out.println(boter); System.out.println(suiker); System.out.println(bakmeel); System.out.println(vanillesuiker); System.out.println(zout); System.out.println(appels); System.out.println(kristalsuiker); System.out.println(kaneel); System.out.println(paneermeel); } public applePieRecipe() { } }
elinefwd/backend1
src/applePieRecipe.java
1,244
//1.5 kilo zoetzure appels
line_comment
nl
//200 gram ongezouten roomboter //200 gram witte bastard suiker //400 gram zelfrijzend bakmeel //1 stuk(s) ei //8 gram vanillesuiker //1 snuf zout //1.5 kilo<SUF> //75 gram kristal suiker //3 theelepels kaneel //15 gram paneermeel public class applePieRecipe { Ingredients boter = new Ingredients(200,"gram","ongezouten roomboter"); Ingredients suiker = new Ingredients(200, "gram", "witte bastard suiker"); Ingredients bakmeel = new Ingredients(400,"gram", "zelfrijzend bakmeel"); Ingredients ei = new Ingredients(1, "stuk", "ei"); Ingredients vanillesuiker = new Ingredients(8, "gram", "vanillesuiker"); Ingredients zout = new Ingredients(1, "snuf", "zout"); Ingredients appels = new Ingredients(1.5, "kilo", "zoetzure appels"); Ingredients kristalsuiker = new Ingredients(75, "gram", "kristalsuiker"); Ingredients kaneel = new Ingredients(3, "theelepels", "kaneel"); Ingredients paneermeel = new Ingredients(15, "gram", "paneermeel"); public void voorverwarmen(){ System.out.println("Verwarm de oven van te voren op 170 graden Celsius (boven en onderwarmte)"); }; public void opkloppen(){ System.out.println("Klop het ei los en verdeel deze in twee delen. De ene helft is voor het deeg, " + "het andere deel is voor het bestrijken van de appeltaart."); }; public void mix(){ System.out.println("Meng de boter, bastard suiker, zelfrijzend bakmeel, een helft van het ei, vanille suiker en een snufje zout tot een stevig deeg en verdeel deze in 3 gelijke delen."); }; public void schilMeng(){ System.out.println("Schil nu de appels en snij deze in plakjes. Vermeng in een kopje de suiker en kaneel."); }; public void invetten() { System.out.println("Vet de springvorm in en bestrooi deze met bloem"); } public void deeg() { System.out.println("Gebruik een deel van het deeg om de bodem van de vorm te bedekken. Gebruik een deel van het deeg om de rand van de springvorm te bekleden. Strooi het paneermeel op de bodem van de beklede vorm. De paneermeel neemt het vocht van de appels op."); } public void appelbereiding() { System.out.println("Doe de heft van de appels in de vorm en strooi hier 1/3 van het kaneel-suiker mengsel overheen. Meng de ander helft van de appels met het overgebleven kaneel-suiker mengsel en leg deze in de vorm."); } public void bovenkant() { System.out.println("Rol het laatste deel van de deeg uit tot een dunne lap en snij stroken van ongeveer 1 cm breed."); } public void look() { System.out.println("Leg de stroken kuislings op de appeltaart. Met wat extra deegstroken werk je de rand rondom af. Gebruik het overgebleven ei om de bovenkant van het deeg te bestrijken"); } public void bakken() { System.out.println("Zet de taart iets onder het midden van de oven. Bak de taart in 60 minuten op 170 graden Celsius (boven en onderwarmte) gaar en goudbruin."); } public void stappenplan () { System.out.println("doorloop de volgende stappen"); voorverwarmen(); opkloppen(); mix(); schilMeng(); invetten(); deeg(); appelbereiding(); bovenkant(); look(); bakken(); } public void ingredientenlijst () { System.out.println(ei); System.out.println(boter); System.out.println(suiker); System.out.println(bakmeel); System.out.println(vanillesuiker); System.out.println(zout); System.out.println(appels); System.out.println(kristalsuiker); System.out.println(kaneel); System.out.println(paneermeel); } public applePieRecipe() { } }
False
1,082
11
1,213
11
1,096
9
1,213
11
1,294
11
false
false
false
false
false
true
527
173925_2
package com.vogella.android.multitouch; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PointF; import android.util.AttributeSet; import android.util.SparseArray; import android.view.MotionEvent; import android.view.View; public class MultitouchView extends View { private static final int SIZE = 60; private SparseArray<PointF> mActivePointers; private Paint mPaint; private int[] colors = { Color.BLUE, Color.GREEN, Color.MAGENTA, Color.BLACK, Color.CYAN, Color.GRAY, Color.RED, Color.DKGRAY, Color.LTGRAY, Color.YELLOW }; private Paint textPaint; public MultitouchView(Context context, AttributeSet attrs) { super(context, attrs); initView(); } private void initView() { mActivePointers = new SparseArray<PointF>(); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); // set painter color to a color you like mPaint.setColor(Color.BLUE); mPaint.setStyle(Paint.Style.FILL_AND_STROKE); textPaint = new Paint(Paint.ANTI_ALIAS_FLAG); textPaint.setTextSize(20); } @Override public boolean onTouchEvent(MotionEvent event) { // get pointer index from the event object int pointerIndex = event.getActionIndex(); // get pointer ID int pointerId = event.getPointerId(pointerIndex); // get masked (not specific to a pointer) action int maskedAction = event.getActionMasked(); switch (maskedAction) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: { // We have a new pointer. Lets add it to the list of pointers PointF f = new PointF(); f.x = event.getX(pointerIndex); f.y = event.getY(pointerIndex); mActivePointers.put(pointerId, f); break; } case MotionEvent.ACTION_MOVE: { // a pointer was moved for (int size = event.getPointerCount(), i = 0; i < size; i++) { PointF point = mActivePointers.get(event.getPointerId(i)); if (point != null) { point.x = event.getX(i); point.y = event.getY(i); } } break; } case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: case MotionEvent.ACTION_CANCEL: { mActivePointers.remove(pointerId); break; } } invalidate(); return true; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // draw all pointers for (int size = mActivePointers.size(), i = 0; i < size; i++) { PointF point = mActivePointers.valueAt(i); if (point != null) mPaint.setColor(colors[i % 9]); canvas.drawCircle(point.x, point.y, SIZE, mPaint); } canvas.drawText("Total pointers: " + mActivePointers.size(), 10, 40 , textPaint); } }
FinHead/codeexamples-android
com.vogella.android.multitouch/src/com/vogella/android/multitouch/MultitouchView.java
953
// get pointer ID
line_comment
nl
package com.vogella.android.multitouch; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PointF; import android.util.AttributeSet; import android.util.SparseArray; import android.view.MotionEvent; import android.view.View; public class MultitouchView extends View { private static final int SIZE = 60; private SparseArray<PointF> mActivePointers; private Paint mPaint; private int[] colors = { Color.BLUE, Color.GREEN, Color.MAGENTA, Color.BLACK, Color.CYAN, Color.GRAY, Color.RED, Color.DKGRAY, Color.LTGRAY, Color.YELLOW }; private Paint textPaint; public MultitouchView(Context context, AttributeSet attrs) { super(context, attrs); initView(); } private void initView() { mActivePointers = new SparseArray<PointF>(); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); // set painter color to a color you like mPaint.setColor(Color.BLUE); mPaint.setStyle(Paint.Style.FILL_AND_STROKE); textPaint = new Paint(Paint.ANTI_ALIAS_FLAG); textPaint.setTextSize(20); } @Override public boolean onTouchEvent(MotionEvent event) { // get pointer index from the event object int pointerIndex = event.getActionIndex(); // get pointer<SUF> int pointerId = event.getPointerId(pointerIndex); // get masked (not specific to a pointer) action int maskedAction = event.getActionMasked(); switch (maskedAction) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: { // We have a new pointer. Lets add it to the list of pointers PointF f = new PointF(); f.x = event.getX(pointerIndex); f.y = event.getY(pointerIndex); mActivePointers.put(pointerId, f); break; } case MotionEvent.ACTION_MOVE: { // a pointer was moved for (int size = event.getPointerCount(), i = 0; i < size; i++) { PointF point = mActivePointers.get(event.getPointerId(i)); if (point != null) { point.x = event.getX(i); point.y = event.getY(i); } } break; } case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: case MotionEvent.ACTION_CANCEL: { mActivePointers.remove(pointerId); break; } } invalidate(); return true; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // draw all pointers for (int size = mActivePointers.size(), i = 0; i < size; i++) { PointF point = mActivePointers.valueAt(i); if (point != null) mPaint.setColor(colors[i % 9]); canvas.drawCircle(point.x, point.y, SIZE, mPaint); } canvas.drawText("Total pointers: " + mActivePointers.size(), 10, 40 , textPaint); } }
False
671
4
843
4
812
4
843
4
1,021
4
false
false
false
false
false
true
442
68696_2
package nl.novi.uitleg.week2.debuggen; import java.io.IOException; public class Excepties { /** * Java heeft verschillende ingebouwde excepties, zoals: * * 1. ArithmeticException * 2. ArrayIndexOutOfBoundsException * 3. FileNotFoundException * 4. IOException * 5. NullPointerException * 6. StringIndexOutOfBoundException */ static char[] board; public static void main(String[] args) { voorbeeldArthmeticException(); voorbeeldArrayIndexOutOfBoundsException(); voorbeeldFileNotFoundException(); voorbeeldIOException(); voorbeeldNullPointerException(); voorbeeldStringIndexOutOfBoundException(); } //Haal de // weg op de exceptie te gooien. public static void voorbeeldArthmeticException() { //int cijfer = 12 / 0; } //Haal de // weg op de exceptie te gooien. public static void voorbeeldArrayIndexOutOfBoundsException() { int[] nummer = {1,2,3}; //System.out.println(nummer[4]); } // Spreekt voor zich public static void voorbeeldFileNotFoundException() { } /** * * @throws IOException wanneer de code toegang probeert te krijgen tot een bestand dat * al in gebruik is of als het lezen of schrijven onverwacht onderbroken wordt. */ public static void voorbeeldIOException() { } //Haal de // weg op de exceptie te fixen. public static void voorbeeldNullPointerException() { //board = new char[9]; System.out.println(board.length); } //Haal de // weg op de exceptie te fixen. public static void voorbeeldStringIndexOutOfBoundException() { String s = "aa"; //if(s.length() >= 77) { s.charAt(77); //} } }
EAM26/Lijsten-les3
src/nl/novi/uitleg/week2/debuggen/Excepties.java
518
//int cijfer = 12 / 0;
line_comment
nl
package nl.novi.uitleg.week2.debuggen; import java.io.IOException; public class Excepties { /** * Java heeft verschillende ingebouwde excepties, zoals: * * 1. ArithmeticException * 2. ArrayIndexOutOfBoundsException * 3. FileNotFoundException * 4. IOException * 5. NullPointerException * 6. StringIndexOutOfBoundException */ static char[] board; public static void main(String[] args) { voorbeeldArthmeticException(); voorbeeldArrayIndexOutOfBoundsException(); voorbeeldFileNotFoundException(); voorbeeldIOException(); voorbeeldNullPointerException(); voorbeeldStringIndexOutOfBoundException(); } //Haal de // weg op de exceptie te gooien. public static void voorbeeldArthmeticException() { //int cijfer<SUF> } //Haal de // weg op de exceptie te gooien. public static void voorbeeldArrayIndexOutOfBoundsException() { int[] nummer = {1,2,3}; //System.out.println(nummer[4]); } // Spreekt voor zich public static void voorbeeldFileNotFoundException() { } /** * * @throws IOException wanneer de code toegang probeert te krijgen tot een bestand dat * al in gebruik is of als het lezen of schrijven onverwacht onderbroken wordt. */ public static void voorbeeldIOException() { } //Haal de // weg op de exceptie te fixen. public static void voorbeeldNullPointerException() { //board = new char[9]; System.out.println(board.length); } //Haal de // weg op de exceptie te fixen. public static void voorbeeldStringIndexOutOfBoundException() { String s = "aa"; //if(s.length() >= 77) { s.charAt(77); //} } }
False
427
13
464
13
465
12
464
13
543
13
false
false
false
false
false
true
72
109505_11
package org.adaway.ui.hosts; import android.content.Context; import android.content.res.Resources; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.DiffUtil; import androidx.recyclerview.widget.ListAdapter; import androidx.recyclerview.widget.RecyclerView; import org.adaway.R; import org.adaway.db.entity.HostsSource; import java.time.Duration; import java.time.ZonedDateTime; /** * This class is a the {@link RecyclerView.Adapter} for the hosts sources view. * * @author Bruce BUJON (bruce.bujon(at)gmail(dot)com) */ class HostsSourcesAdapter extends ListAdapter<HostsSource, HostsSourcesAdapter.ViewHolder> { /** * This callback is use to compare hosts sources. */ private static final DiffUtil.ItemCallback<HostsSource> DIFF_CALLBACK = new DiffUtil.ItemCallback<HostsSource>() { @Override public boolean areItemsTheSame(@NonNull HostsSource oldSource, @NonNull HostsSource newSource) { return oldSource.getUrl().equals(newSource.getUrl()); } @Override public boolean areContentsTheSame(@NonNull HostsSource oldSource, @NonNull HostsSource newSource) { // NOTE: if you use equals, your object must properly override Object#equals() // Incorrectly returning false here will result in too many animations. return oldSource.equals(newSource); } }; /** * This callback is use to call view actions. */ @NonNull private final HostsSourcesViewCallback viewCallback; private static final String[] QUANTITY_PREFIXES = new String[]{"k", "M", "G"}; /** * Constructor. * * @param viewCallback The view callback. */ HostsSourcesAdapter(@NonNull HostsSourcesViewCallback viewCallback) { super(DIFF_CALLBACK); this.viewCallback = viewCallback; } /** * Get the approximate delay from a date to now. * * @param context The application context. * @param from The date from which computes the delay. * @return The approximate delay. */ private static String getApproximateDelay(Context context, ZonedDateTime from) { // Get resource for plurals Resources resources = context.getResources(); // Get current date in UTC timezone ZonedDateTime now = ZonedDateTime.now(); // Get delay between from and now in minutes long delay = Duration.between(from, now).toMinutes(); // Check if delay is lower than an hour if (delay < 60) { return resources.getString(R.string.hosts_source_few_minutes); } // Get delay in hours delay /= 60; // Check if delay is lower than a day if (delay < 24) { int hours = (int) delay; return resources.getQuantityString(R.plurals.hosts_source_hours, hours, hours); } // Get delay in days delay /= 24; // Check if delay is lower than a month if (delay < 30) { int days = (int) delay; return resources.getQuantityString(R.plurals.hosts_source_days, days, days); } // Get delay in months int months = (int) delay / 30; return resources.getQuantityString(R.plurals.hosts_source_months, months, months); } @NonNull @Override public HostsSourcesAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); View view = layoutInflater.inflate(R.layout.hosts_sources_card, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { HostsSource source = this.getItem(position); holder.enabledCheckBox.setChecked(source.isEnabled()); holder.enabledCheckBox.setOnClickListener(view -> viewCallback.toggleEnabled(source)); holder.labelTextView.setText(source.getLabel()); holder.urlTextView.setText(source.getUrl()); holder.updateTextView.setText(getUpdateText(source)); holder.sizeTextView.setText(getHostCount(source)); holder.itemView.setOnClickListener(view -> viewCallback.edit(source)); } private String getUpdateText(HostsSource source) { // Get context Context context = this.viewCallback.getContext(); // Check if source is enabled if (!source.isEnabled()) { return context.getString(R.string.hosts_source_disabled); } // Check modification dates boolean lastOnlineModificationDefined = source.getOnlineModificationDate() != null; boolean lastLocalModificationDefined = source.getLocalModificationDate() != null; // Declare update text String updateText; // Check if last online modification date is known if (lastOnlineModificationDefined) { // Get last online modification delay String approximateDelay = getApproximateDelay(context, source.getOnlineModificationDate()); if (!lastLocalModificationDefined) { updateText = context.getString(R.string.hosts_source_last_update, approximateDelay); } else if (source.getOnlineModificationDate().isAfter(source.getLocalModificationDate())) { updateText = context.getString(R.string.hosts_source_need_update, approximateDelay); } else { updateText = context.getString(R.string.hosts_source_up_to_date, approximateDelay); } } else { if (lastLocalModificationDefined) { String approximateDelay = getApproximateDelay(context, source.getLocalModificationDate()); updateText = context.getString(R.string.hosts_source_installed, approximateDelay); } else { updateText = context.getString(R.string.hosts_source_unknown_status); } } return updateText; } private String getHostCount(HostsSource source) { // Note: NumberFormat.getCompactNumberInstance is Java 12 only // Check empty source int size = source.getSize(); if (size <= 0 || !source.isEnabled()) { return ""; } // Compute size decimal length int length = 1; while (size > 10) { size /= 10; length++; } // Compute prefix to use int prefixIndex = (length - 1) / 3 - 1; // Return formatted count Context context = this.viewCallback.getContext(); size = source.getSize(); if (prefixIndex < 0) { return context.getString(R.string.hosts_count, Integer.toString(size)); } else if (prefixIndex >= QUANTITY_PREFIXES.length) { prefixIndex = QUANTITY_PREFIXES.length - 1; size = 13; } size = Math.toIntExact(Math.round(size / Math.pow(10, (prefixIndex + 1) * 3D))); return context.getString(R.string.hosts_count, size + QUANTITY_PREFIXES[prefixIndex]); } /** * This class is a the {@link RecyclerView.ViewHolder} for the hosts sources view. * * @author Bruce BUJON (bruce.bujon(at)gmail(dot)com) */ static class ViewHolder extends RecyclerView.ViewHolder { final CheckBox enabledCheckBox; final TextView labelTextView; final TextView urlTextView; final TextView updateTextView; final TextView sizeTextView; /** * Constructor. * * @param itemView The hosts sources view. */ ViewHolder(View itemView) { super(itemView); this.enabledCheckBox = itemView.findViewById(R.id.sourceEnabledCheckBox); this.labelTextView = itemView.findViewById(R.id.sourceLabelTextView); this.urlTextView = itemView.findViewById(R.id.sourceUrlTextView); this.updateTextView = itemView.findViewById(R.id.sourceUpdateTextView); this.sizeTextView = itemView.findViewById(R.id.sourceSizeTextView); } } }
AdAway/AdAway
app/src/main/java/org/adaway/ui/hosts/HostsSourcesAdapter.java
2,301
// Get delay in hours
line_comment
nl
package org.adaway.ui.hosts; import android.content.Context; import android.content.res.Resources; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.DiffUtil; import androidx.recyclerview.widget.ListAdapter; import androidx.recyclerview.widget.RecyclerView; import org.adaway.R; import org.adaway.db.entity.HostsSource; import java.time.Duration; import java.time.ZonedDateTime; /** * This class is a the {@link RecyclerView.Adapter} for the hosts sources view. * * @author Bruce BUJON (bruce.bujon(at)gmail(dot)com) */ class HostsSourcesAdapter extends ListAdapter<HostsSource, HostsSourcesAdapter.ViewHolder> { /** * This callback is use to compare hosts sources. */ private static final DiffUtil.ItemCallback<HostsSource> DIFF_CALLBACK = new DiffUtil.ItemCallback<HostsSource>() { @Override public boolean areItemsTheSame(@NonNull HostsSource oldSource, @NonNull HostsSource newSource) { return oldSource.getUrl().equals(newSource.getUrl()); } @Override public boolean areContentsTheSame(@NonNull HostsSource oldSource, @NonNull HostsSource newSource) { // NOTE: if you use equals, your object must properly override Object#equals() // Incorrectly returning false here will result in too many animations. return oldSource.equals(newSource); } }; /** * This callback is use to call view actions. */ @NonNull private final HostsSourcesViewCallback viewCallback; private static final String[] QUANTITY_PREFIXES = new String[]{"k", "M", "G"}; /** * Constructor. * * @param viewCallback The view callback. */ HostsSourcesAdapter(@NonNull HostsSourcesViewCallback viewCallback) { super(DIFF_CALLBACK); this.viewCallback = viewCallback; } /** * Get the approximate delay from a date to now. * * @param context The application context. * @param from The date from which computes the delay. * @return The approximate delay. */ private static String getApproximateDelay(Context context, ZonedDateTime from) { // Get resource for plurals Resources resources = context.getResources(); // Get current date in UTC timezone ZonedDateTime now = ZonedDateTime.now(); // Get delay between from and now in minutes long delay = Duration.between(from, now).toMinutes(); // Check if delay is lower than an hour if (delay < 60) { return resources.getString(R.string.hosts_source_few_minutes); } // Get delay<SUF> delay /= 60; // Check if delay is lower than a day if (delay < 24) { int hours = (int) delay; return resources.getQuantityString(R.plurals.hosts_source_hours, hours, hours); } // Get delay in days delay /= 24; // Check if delay is lower than a month if (delay < 30) { int days = (int) delay; return resources.getQuantityString(R.plurals.hosts_source_days, days, days); } // Get delay in months int months = (int) delay / 30; return resources.getQuantityString(R.plurals.hosts_source_months, months, months); } @NonNull @Override public HostsSourcesAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); View view = layoutInflater.inflate(R.layout.hosts_sources_card, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { HostsSource source = this.getItem(position); holder.enabledCheckBox.setChecked(source.isEnabled()); holder.enabledCheckBox.setOnClickListener(view -> viewCallback.toggleEnabled(source)); holder.labelTextView.setText(source.getLabel()); holder.urlTextView.setText(source.getUrl()); holder.updateTextView.setText(getUpdateText(source)); holder.sizeTextView.setText(getHostCount(source)); holder.itemView.setOnClickListener(view -> viewCallback.edit(source)); } private String getUpdateText(HostsSource source) { // Get context Context context = this.viewCallback.getContext(); // Check if source is enabled if (!source.isEnabled()) { return context.getString(R.string.hosts_source_disabled); } // Check modification dates boolean lastOnlineModificationDefined = source.getOnlineModificationDate() != null; boolean lastLocalModificationDefined = source.getLocalModificationDate() != null; // Declare update text String updateText; // Check if last online modification date is known if (lastOnlineModificationDefined) { // Get last online modification delay String approximateDelay = getApproximateDelay(context, source.getOnlineModificationDate()); if (!lastLocalModificationDefined) { updateText = context.getString(R.string.hosts_source_last_update, approximateDelay); } else if (source.getOnlineModificationDate().isAfter(source.getLocalModificationDate())) { updateText = context.getString(R.string.hosts_source_need_update, approximateDelay); } else { updateText = context.getString(R.string.hosts_source_up_to_date, approximateDelay); } } else { if (lastLocalModificationDefined) { String approximateDelay = getApproximateDelay(context, source.getLocalModificationDate()); updateText = context.getString(R.string.hosts_source_installed, approximateDelay); } else { updateText = context.getString(R.string.hosts_source_unknown_status); } } return updateText; } private String getHostCount(HostsSource source) { // Note: NumberFormat.getCompactNumberInstance is Java 12 only // Check empty source int size = source.getSize(); if (size <= 0 || !source.isEnabled()) { return ""; } // Compute size decimal length int length = 1; while (size > 10) { size /= 10; length++; } // Compute prefix to use int prefixIndex = (length - 1) / 3 - 1; // Return formatted count Context context = this.viewCallback.getContext(); size = source.getSize(); if (prefixIndex < 0) { return context.getString(R.string.hosts_count, Integer.toString(size)); } else if (prefixIndex >= QUANTITY_PREFIXES.length) { prefixIndex = QUANTITY_PREFIXES.length - 1; size = 13; } size = Math.toIntExact(Math.round(size / Math.pow(10, (prefixIndex + 1) * 3D))); return context.getString(R.string.hosts_count, size + QUANTITY_PREFIXES[prefixIndex]); } /** * This class is a the {@link RecyclerView.ViewHolder} for the hosts sources view. * * @author Bruce BUJON (bruce.bujon(at)gmail(dot)com) */ static class ViewHolder extends RecyclerView.ViewHolder { final CheckBox enabledCheckBox; final TextView labelTextView; final TextView urlTextView; final TextView updateTextView; final TextView sizeTextView; /** * Constructor. * * @param itemView The hosts sources view. */ ViewHolder(View itemView) { super(itemView); this.enabledCheckBox = itemView.findViewById(R.id.sourceEnabledCheckBox); this.labelTextView = itemView.findViewById(R.id.sourceLabelTextView); this.urlTextView = itemView.findViewById(R.id.sourceUrlTextView); this.updateTextView = itemView.findViewById(R.id.sourceUpdateTextView); this.sizeTextView = itemView.findViewById(R.id.sourceSizeTextView); } } }
False
1,648
5
1,876
5
2,014
5
1,876
5
2,218
5
false
false
false
false
false
true
2,754
57593_2
package com.mycompany.minorigv.gffparser; import com.mycompany.minorigv.blast.BlastORF; import com.mycompany.minorigv.blast.ColorORFs; import com.mycompany.minorigv.sequence.FindORF; import java.awt.*; import java.util.ArrayList; import java.util.HashMap; /** * Deze class maakt objecten voor chromosomen/contigs. Ook worden hier de bijbehorende features in object gezet. * * @author Anne van Ewijk en Amber Janssen Groesbeek */ public class Chromosome { private String id; private ArrayList<Feature> features; private String seqTemp; private ArrayList<ORF> listORF; private HashMap<String, Object> readingframe; private HashMap<String, Color> headerColor; /** * De constructor. */ public Chromosome() { features = new ArrayList<Feature>(); } /** * De constructor. * @param id Het id van het chromosoom/contig. * @param features Features zijn het CDS, Exon, Gene, mRNA en Region. */ public Chromosome(String id, ArrayList<Feature> features) { this.id = id; this.features = features; } /** * De constructor. * @param id Het id van het chromosoom/contig * @param seqTemp Sequentie van de template strand * @param listORF Lijst met alle ORFs gevonden */ public Chromosome(String id, String seqTemp, ArrayList<ORF> listORF){ this.id = id; this.seqTemp = seqTemp; this.listORF = listORF; } /** * Het toevoegen van features aan het chromosoom. * @param feat Features zijn het CDS, Exon, Gene, mRNA en Region. */ public void addFeature(Feature feat){ if (feat instanceof Feature){ features.add(feat); } } /** * Het returned het id van het chromosoom/contig. * @return id is een String. Het is het id van het chromosoom/contig. */ public String getId() { return id; } /** * Het genereerd het id van het chromosoom/contig. * @param id is een String. Het is het id van het chromosoom/contig. */ public void setId(String id) { this.id = id; } /** * Het returned de sequentie van het chromosoom/contig. * @return seqTemp is een String. Het is de DNA sequentie van het chromosoom. */ public String getSeqTemp() { return seqTemp; } /** * Het genereerd de sequentie van het chromosoom/contig. * @param seqTemp */ public void setSeqTemp(String seqTemp) { this.seqTemp = seqTemp; } /** * Het returned een ArrayList met de features erin. * @return features is een ArrayList met daarin de features */ public ArrayList<Feature> getFeatures() { return features; } /** * Het genereerd de ArrayList met daarin de features. * @param features is een Arraylist met daarin de features */ public void setFeatures(ArrayList<Feature> features) { this.features = features; } /** * Het returned een ArrayList met daarin de ORFs. * @return listORF is een ArrayList met daarin de ORFs. */ public ArrayList<ORF> getListORF() { return listORF; } public void setListORF(ArrayList<ORF> newListOrf){ this.listORF = newListOrf; } /** * Het genereerd de ArrayList met daarin de ORFs */ public void createListOrf(int lenghtORF) { // ORFs zoeken in de template strand en complementaire streng. listORF = FindORF.searchORF(getId(), getSeqTemp(), lenghtORF); } /** * Hashmap met als key de readingframes (RF1, RF2, ..., RF6) en als value de aminozuursequentie * @return Een hashmap. key: readingframes, value: aminozuursequentie */ public HashMap<String, Object> getReadingframe() { return readingframe; } /** * Het opslaan van de hashmap met daarin voor elk readingframe (key), de aminozuursequentie (value) * @param readingframe Hashmap. Key: readingframes, value: aminozuursequentie */ public void setReadingframe(HashMap<String, Object> readingframe) { this.readingframe = readingframe; } /** * Alle features die tussen de start en stop positie voorkomen wordenom eem ArrayList gezet. * @param start Start positie van de feature op het chromosoom. * @param stop Stop positie van de feature op het chromosoom * @return Een lijst met de features die voldoen aan de start en stop */ public ArrayList<Feature> getFeaturesBetween(int start, int stop){ ArrayList<Feature> featureList = new ArrayList<Feature>(); for(Feature f : features){ if (f.getStop() > start && f.getStop() < stop){ featureList.add(f); }else if(f.getStart() >= start && f.getStart() < stop){ featureList.add(f); }else if(f.getStart() <= start && f.getStop() > stop){ featureList.add(f); } } return featureList; } /** * De Features worden opgehaald na keuze van de gebruiker. * Stel de gebruiker wilt alleen Gene en CDS zien, dan worden deze features opgehaald die behoren tot CDS en Gene. * @param featureList is de lijst met alle features uit het chromosoom/contig. * @param SelectedFeatures is de lijst met de gekozen features (dus bijv. Gene en CDS) die de gebruiker heeft gekozen. * @return Een lijst met de gekozen features wordt gereturned. */ public static ArrayList<Feature> filterFeatures(ArrayList<Feature> featureList, ArrayList<String> SelectedFeatures){ ArrayList<Feature> featureFilteredList = new ArrayList<Feature>(); for (Feature feat : featureList){ String klas = feat.getClass().toString(); for (String optie : SelectedFeatures){ if (klas.contains(optie)){ featureFilteredList.add(feat); } } } return featureFilteredList; } /** * Alle ORFs die tussen de start en stop positie voorkomen worden om eem ArrayList gezet. * @param start Startpositie waar vandaan de orfs gezocht moeten worden * @param stop Stoppositie tot waar de orfs gezocht moeten worden * @return Een lijst met de orfs die voldoen aan de start en stop */ public ArrayList<ORF> getORFsBetween(int start, int stop){ ArrayList<ORF> orfsFilteredList = new ArrayList<>(); if(listORF != null){ for(ORF o : listORF){ if (o.getStop() > start && o.getStop() < stop){ orfsFilteredList.add(o); }else if(o.getStart() > start && o.getStart() < stop){ orfsFilteredList.add(o); }else if(o.getStart() < start && o.getStop() > stop){ orfsFilteredList.add(o); } } return orfsFilteredList; }else{ return null; } } @Override public String toString() { return "Chromosome{" + "id='" + id + '\'' + ", features=" + features + '}'; } }
gabeplz/intership-genome-viewer-backup
MinorIGV/src/main/java/com/mycompany/minorigv/gffparser/Chromosome.java
2,153
/** * De constructor. * @param id Het id van het chromosoom/contig. * @param features Features zijn het CDS, Exon, Gene, mRNA en Region. */
block_comment
nl
package com.mycompany.minorigv.gffparser; import com.mycompany.minorigv.blast.BlastORF; import com.mycompany.minorigv.blast.ColorORFs; import com.mycompany.minorigv.sequence.FindORF; import java.awt.*; import java.util.ArrayList; import java.util.HashMap; /** * Deze class maakt objecten voor chromosomen/contigs. Ook worden hier de bijbehorende features in object gezet. * * @author Anne van Ewijk en Amber Janssen Groesbeek */ public class Chromosome { private String id; private ArrayList<Feature> features; private String seqTemp; private ArrayList<ORF> listORF; private HashMap<String, Object> readingframe; private HashMap<String, Color> headerColor; /** * De constructor. */ public Chromosome() { features = new ArrayList<Feature>(); } /** * De constructor. <SUF>*/ public Chromosome(String id, ArrayList<Feature> features) { this.id = id; this.features = features; } /** * De constructor. * @param id Het id van het chromosoom/contig * @param seqTemp Sequentie van de template strand * @param listORF Lijst met alle ORFs gevonden */ public Chromosome(String id, String seqTemp, ArrayList<ORF> listORF){ this.id = id; this.seqTemp = seqTemp; this.listORF = listORF; } /** * Het toevoegen van features aan het chromosoom. * @param feat Features zijn het CDS, Exon, Gene, mRNA en Region. */ public void addFeature(Feature feat){ if (feat instanceof Feature){ features.add(feat); } } /** * Het returned het id van het chromosoom/contig. * @return id is een String. Het is het id van het chromosoom/contig. */ public String getId() { return id; } /** * Het genereerd het id van het chromosoom/contig. * @param id is een String. Het is het id van het chromosoom/contig. */ public void setId(String id) { this.id = id; } /** * Het returned de sequentie van het chromosoom/contig. * @return seqTemp is een String. Het is de DNA sequentie van het chromosoom. */ public String getSeqTemp() { return seqTemp; } /** * Het genereerd de sequentie van het chromosoom/contig. * @param seqTemp */ public void setSeqTemp(String seqTemp) { this.seqTemp = seqTemp; } /** * Het returned een ArrayList met de features erin. * @return features is een ArrayList met daarin de features */ public ArrayList<Feature> getFeatures() { return features; } /** * Het genereerd de ArrayList met daarin de features. * @param features is een Arraylist met daarin de features */ public void setFeatures(ArrayList<Feature> features) { this.features = features; } /** * Het returned een ArrayList met daarin de ORFs. * @return listORF is een ArrayList met daarin de ORFs. */ public ArrayList<ORF> getListORF() { return listORF; } public void setListORF(ArrayList<ORF> newListOrf){ this.listORF = newListOrf; } /** * Het genereerd de ArrayList met daarin de ORFs */ public void createListOrf(int lenghtORF) { // ORFs zoeken in de template strand en complementaire streng. listORF = FindORF.searchORF(getId(), getSeqTemp(), lenghtORF); } /** * Hashmap met als key de readingframes (RF1, RF2, ..., RF6) en als value de aminozuursequentie * @return Een hashmap. key: readingframes, value: aminozuursequentie */ public HashMap<String, Object> getReadingframe() { return readingframe; } /** * Het opslaan van de hashmap met daarin voor elk readingframe (key), de aminozuursequentie (value) * @param readingframe Hashmap. Key: readingframes, value: aminozuursequentie */ public void setReadingframe(HashMap<String, Object> readingframe) { this.readingframe = readingframe; } /** * Alle features die tussen de start en stop positie voorkomen wordenom eem ArrayList gezet. * @param start Start positie van de feature op het chromosoom. * @param stop Stop positie van de feature op het chromosoom * @return Een lijst met de features die voldoen aan de start en stop */ public ArrayList<Feature> getFeaturesBetween(int start, int stop){ ArrayList<Feature> featureList = new ArrayList<Feature>(); for(Feature f : features){ if (f.getStop() > start && f.getStop() < stop){ featureList.add(f); }else if(f.getStart() >= start && f.getStart() < stop){ featureList.add(f); }else if(f.getStart() <= start && f.getStop() > stop){ featureList.add(f); } } return featureList; } /** * De Features worden opgehaald na keuze van de gebruiker. * Stel de gebruiker wilt alleen Gene en CDS zien, dan worden deze features opgehaald die behoren tot CDS en Gene. * @param featureList is de lijst met alle features uit het chromosoom/contig. * @param SelectedFeatures is de lijst met de gekozen features (dus bijv. Gene en CDS) die de gebruiker heeft gekozen. * @return Een lijst met de gekozen features wordt gereturned. */ public static ArrayList<Feature> filterFeatures(ArrayList<Feature> featureList, ArrayList<String> SelectedFeatures){ ArrayList<Feature> featureFilteredList = new ArrayList<Feature>(); for (Feature feat : featureList){ String klas = feat.getClass().toString(); for (String optie : SelectedFeatures){ if (klas.contains(optie)){ featureFilteredList.add(feat); } } } return featureFilteredList; } /** * Alle ORFs die tussen de start en stop positie voorkomen worden om eem ArrayList gezet. * @param start Startpositie waar vandaan de orfs gezocht moeten worden * @param stop Stoppositie tot waar de orfs gezocht moeten worden * @return Een lijst met de orfs die voldoen aan de start en stop */ public ArrayList<ORF> getORFsBetween(int start, int stop){ ArrayList<ORF> orfsFilteredList = new ArrayList<>(); if(listORF != null){ for(ORF o : listORF){ if (o.getStop() > start && o.getStop() < stop){ orfsFilteredList.add(o); }else if(o.getStart() > start && o.getStart() < stop){ orfsFilteredList.add(o); }else if(o.getStart() < start && o.getStop() > stop){ orfsFilteredList.add(o); } } return orfsFilteredList; }else{ return null; } } @Override public String toString() { return "Chromosome{" + "id='" + id + '\'' + ", features=" + features + '}'; } }
True
1,780
46
1,913
47
1,942
49
1,913
47
2,174
53
false
false
false
false
false
true
1,138
60692_0
package nl.allergieradar; /** * Meer informatie over views: * http://www.baeldung.com/jackson-json-view-annotation * * @author Peter van Vliet <[email protected]> * @since 1.0 */ public class View { public static class Internal extends Private {} public static class Private extends Protected {} public static class Protected extends Public {} public static class Public {} }
MitchvanWijngaarden/Allergieradarserver
src/main/java/nl/allergieradar/View.java
128
/** * Meer informatie over views: * http://www.baeldung.com/jackson-json-view-annotation * * @author Peter van Vliet <[email protected]> * @since 1.0 */
block_comment
nl
package nl.allergieradar; /** * Meer informatie over<SUF>*/ public class View { public static class Internal extends Private {} public static class Private extends Protected {} public static class Protected extends Public {} public static class Public {} }
False
99
52
113
62
117
58
113
62
131
65
false
false
false
false
false
true