file_id
stringlengths
4
8
content
stringlengths
302
35.8k
repo
stringlengths
9
109
path
stringlengths
9
163
token_length
int64
88
7.79k
original_comment
stringlengths
11
3.46k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
259
35.6k
6796_26
package com.example.multivillev1; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import pl.droidsonroids.gif.GifImageView; public class selectedNumberTest extends AppCompatActivity implements View.OnClickListener { String id; int level,levelOfStudent;//The times table in which the student is examined. TextView questionTextView, farmerTextView; Button button1, button2, button3, nextQuestionButton,backBtn; List<Integer> numbers = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7,8,9,10)); //Gets randomized and provides the 10 questions. int questionNumber; int correct_answers; List<Integer> possible_answers = new ArrayList<>(); GifImageView gifImageView; //For theory revision in case of <7 correct answers. boolean extra_slide; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); hideSystemUI(); setContentView(R.layout.activity_selected_number_test); Intent intent = getIntent(); id= intent.getStringExtra("id"); level=intent.getIntExtra("testPressed",0); questionTextView = findViewById(R.id.questionTextView); farmerTextView = findViewById(R.id.farmerTextView); button1 = findViewById(R.id.answerButton1); button2 = findViewById(R.id.answerButton2); button3 = findViewById(R.id.answerButton3); backBtn=(Button) findViewById(R.id.backBtn); nextQuestionButton = findViewById(R.id.nextQuestionButton); /* button1.setBackgroundColor(Color.WHITE); button2.setBackgroundColor(Color.WHITE); button3.setBackgroundColor(Color.WHITE); nextQuestionButton.setBackgroundColor(Color.WHITE);*/ backBtn.setOnClickListener(this); DatabaseHelper dataBaseHelper =new DatabaseHelper(this); dataBaseHelper.openDataBase(); try { levelOfStudent= Integer.parseInt(dataBaseHelper.getStudentsLevel(id)); } catch(NumberFormatException nfe) { Toast.makeText(selectedNumberTest.this,"level string to int ",Toast.LENGTH_LONG).show(); } dataBaseHelper.close(); startTest(); } @Override public void onClick(View v) { Utils.preventTwoClick(v); switch(v.getId()) { case R.id.backBtn: Intent i = new Intent(this, testsPerNumber.class); i.putExtra("id", id); startActivity(i); finish(); } } //Randomizes the ArrayList "numbers" and multiplies each value with the current level to form the questions. private void startTest(){ Collections.shuffle(numbers); questionNumber = 0; correct_answers = 0; fillTextViews(); createAnswers(numbers.get(0)); } /* Creates the possible answers for each question. One of them is always the correct one: level*second_number (Randomized number from 1 to 10. Different for each question.) The two additional (wrong) answers are creating by multiplying the level with a random number between 1-10, excluding the correct number. This ensures that even the wrong answers are from that times table, and thus, are believable. */ private void createAnswers(int second_number){ fillPossibleAnswers(second_number); Collections.shuffle(possible_answers); button1.setText(possible_answers.get(0).toString()); button2.setText(possible_answers.get(1).toString()); button3.setText(possible_answers.get(2).toString()); } //Fills the list with all 3 possible answers. private void fillPossibleAnswers(int second_number){ possible_answers.clear(); possible_answers.add(level*second_number); //Correct answer List<Integer> temp_numbers = new ArrayList<>(numbers); //Clone of the shuffled number list from 1-10. temp_numbers.remove(new Integer(second_number)); //Removes the second_number from the clone in order not to get the same answer twice. Random r = new Random(); int x = r.nextInt(9); possible_answers.add(level*temp_numbers.get(x)); //Randomly chosen number, multiplied by level gives the first wrong answer. temp_numbers.remove(x); //Removes the first wrong number from the clone in order not to get the same answer twice. x = r.nextInt(8); possible_answers.add(level*temp_numbers.get(x)); //Randomly chosen number, multiplied by level gives the second wrong answer. } //Creates the next question or shows results if the test is over. public void nextQuestion(){ //Resets the background colors button1.setBackgroundResource(R.drawable.backbtn); button2.setBackgroundResource(R.drawable.backbtn); button3.setBackgroundResource(R.drawable.backbtn); button1.setClickable(true); button2.setClickable(true); button3.setClickable(true); //Disables the transition to the next question until an answer is clicked. nextQuestionButton.setEnabled(false); questionNumber++; fillTextViews(); createAnswers(numbers.get(questionNumber)); if (questionNumber == 9){ //No more questions nextQuestionButton.setText("Show Results"); } } //Fills the text views with the question and the question number private void fillTextViews(){ farmerTextView.setText("Question " + (questionNumber+1)); questionTextView.setText(numbers.get(questionNumber) + " x " + level); nextQuestionButton.setEnabled(false); } //Whenever an answer is clicked, checks if the button's text is the correct answer. public void answerClicked(View view){ Utils.preventTwoClick(view); Button b = (Button)view; int buttons_answer = Integer.parseInt(b.getText().toString()); //Number clicked if (buttons_answer == numbers.get(questionNumber) * level){ //Correct answer correct_answers++; correctAnswer(b); } else { //Wrong answer wrongAnswer(b); } //Cannot select a second answer. button1.setClickable(false); button2.setClickable(false); button3.setClickable(false); //Allows the transition to the next question. nextQuestionButton.setEnabled(true); } public void nextQuestionButtonClick(View view){ Utils.preventTwoClick(view); if (questionNumber < 9){ //Next question nextQuestion(); } else if (questionNumber == 9) { //Show results showResults(); } else { if (extra_slide){ showTheory(); } else { //Return to menu Intent intent = new Intent(getBaseContext(),testsPerNumber.class); intent.putExtra("id",id); startActivity(intent); finish(); } } } //Is called when a correct answer is selected. private void correctAnswer(Button b){ farmerTextView.setText("Correct!"); //Farmer's bubble b.setBackgroundColor(Color.GREEN); answerQuestion(numbers.get(questionNumber), level, true); } //Is called when a correct answer is selected. private void wrongAnswer(Button b){ farmerTextView.setText("Wrong! The correct answer is " + numbers.get(questionNumber)*level + "."); //Farmer's bubble b.setBackgroundColor(Color.RED); answerQuestion(numbers.get(questionNumber), level, false); } public void answerQuestion(int firstNumber, int secondNumber, boolean answeredCorrectly){ DatabaseHelper dataBaseHelper =new DatabaseHelper(this); dataBaseHelper.openDataBase(); String statsString =dataBaseHelper.getStudentsStats(id); String oldStatsString = statsString; String newStatsString = ""; String line; int targetLine = ((firstNumber-1)*10 + (secondNumber-1))*10; //Η γραμμή που πρέπει να αλλαχθεί. Log.d("HERE",oldStatsString); for (int i=0; i<oldStatsString.length(); i+=10) { //Για κάθε πράξη... line = oldStatsString.substring(i,i+10); Log.d("line",line); if (i==targetLine){ StringBuffer sb = new StringBuffer(line); sb.deleteCharAt(sb.length()-1); //Διαγραφή τελευταίας εγγραφής. //Προσθήκη νέας εγγραφής στην αρχή. if (answeredCorrectly){ line = "1" + sb.toString(); } else { line = "0" + sb.toString(); } Log.d("line2",line); } newStatsString += line; } //Εισαγωγή στη βάση. dataBaseHelper.setStudentsStats(id,newStatsString); dataBaseHelper.close(); } //Shows the test results. public void showResults(){ button1.setVisibility(View.GONE); button2.setVisibility(View.GONE); button3.setVisibility(View.GONE); questionNumber++; //(=10) Just to pass the info to nextQuestionButtonClick and return to menu if clicked again. questionTextView.setVisibility(View.GONE); //Empties the board farmerTextView.setTextSize(20); String s = String.valueOf(correct_answers); s += " correct answers! "; DatabaseHelper dataBaseHelper =new DatabaseHelper(this); dataBaseHelper.openDataBase(); //Extra message if (correct_answers <= 4) { s += "You need more practice!"; } else if (correct_answers < 7) { s += "You're almost there!"; } else if (correct_answers <= 9) { s += "Great job!"; //update level if(levelOfStudent==level){ dataBaseHelper.updateStudentsLevel(id); dataBaseHelper.updateStudentsLevelLesson(false,id); } } else { //correct_answers == 10 s += "Perfect score! Well done!"; //update if(levelOfStudent==level){ dataBaseHelper.updateStudentsLevel(id); dataBaseHelper.updateStudentsLevelLesson(false,id); } } dataBaseHelper.close(); farmerTextView.setText(s); if (correct_answers < 7){ nextQuestionButton.setText("Next"); extra_slide = true; //Is going to show the extra (theory) panel. } else { nextQuestionButton.setText("Back to Menu"); extra_slide = false; } } private void showTheory(){ TextView rememberTextView = findViewById(R.id.rememberTextView); rememberTextView.setTextColor(Color.BLACK); rememberTextView.setVisibility(View.VISIBLE); gifImageView = findViewById(R.id.gifView); gifImageView.setVisibility(View.VISIBLE); //Shows slide (theory panel) depending on level (times table). 6 and 9 not optimal!!!!!! switch (level){ case 1: gifImageView.setImageResource(R.drawable.slide1_3); break; case 2: gifImageView.setImageResource(R.drawable.slide2_3); break; case 3: gifImageView.setImageResource(R.drawable.slide3_2); break; case 4: gifImageView.setImageResource(R.drawable.slide4_2); break; case 5: gifImageView.setImageResource(R.drawable.slide5_3); break; case 6: gifImageView.setImageResource(R.drawable.slide6_13); break; case 7: gifImageView.setImageResource(R.drawable.slide7_3); break; case 8: gifImageView.setImageResource(R.drawable.slide8_2); break; case 9: gifImageView.setImageResource(R.drawable.slide9_4); break; case 10: gifImageView.setImageResource(R.drawable.slide10_3); break; default: gifImageView.setImageResource(R.drawable.slide1_3); break; } nextQuestionButton.setText("Next"); extra_slide = false; } @Override public void onBackPressed() { //nothing } private void hideSystemUI() { // Enables sticky immersive mode. View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY // Set the content to appear under the system bars so that the // content doesn't resize when the system bars hide and show. | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // Hide the nav bar and status bar | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN ); } public void onResume(){ super.onResume(); hideSystemUI(); } }
NektariaKallioupi/multivillev1
app/src/main/java/com/example/multivillev1/selectedNumberTest.java
3,256
//Προσθήκη νέας εγγραφής στην αρχή.
line_comment
el
package com.example.multivillev1; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import pl.droidsonroids.gif.GifImageView; public class selectedNumberTest extends AppCompatActivity implements View.OnClickListener { String id; int level,levelOfStudent;//The times table in which the student is examined. TextView questionTextView, farmerTextView; Button button1, button2, button3, nextQuestionButton,backBtn; List<Integer> numbers = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7,8,9,10)); //Gets randomized and provides the 10 questions. int questionNumber; int correct_answers; List<Integer> possible_answers = new ArrayList<>(); GifImageView gifImageView; //For theory revision in case of <7 correct answers. boolean extra_slide; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); hideSystemUI(); setContentView(R.layout.activity_selected_number_test); Intent intent = getIntent(); id= intent.getStringExtra("id"); level=intent.getIntExtra("testPressed",0); questionTextView = findViewById(R.id.questionTextView); farmerTextView = findViewById(R.id.farmerTextView); button1 = findViewById(R.id.answerButton1); button2 = findViewById(R.id.answerButton2); button3 = findViewById(R.id.answerButton3); backBtn=(Button) findViewById(R.id.backBtn); nextQuestionButton = findViewById(R.id.nextQuestionButton); /* button1.setBackgroundColor(Color.WHITE); button2.setBackgroundColor(Color.WHITE); button3.setBackgroundColor(Color.WHITE); nextQuestionButton.setBackgroundColor(Color.WHITE);*/ backBtn.setOnClickListener(this); DatabaseHelper dataBaseHelper =new DatabaseHelper(this); dataBaseHelper.openDataBase(); try { levelOfStudent= Integer.parseInt(dataBaseHelper.getStudentsLevel(id)); } catch(NumberFormatException nfe) { Toast.makeText(selectedNumberTest.this,"level string to int ",Toast.LENGTH_LONG).show(); } dataBaseHelper.close(); startTest(); } @Override public void onClick(View v) { Utils.preventTwoClick(v); switch(v.getId()) { case R.id.backBtn: Intent i = new Intent(this, testsPerNumber.class); i.putExtra("id", id); startActivity(i); finish(); } } //Randomizes the ArrayList "numbers" and multiplies each value with the current level to form the questions. private void startTest(){ Collections.shuffle(numbers); questionNumber = 0; correct_answers = 0; fillTextViews(); createAnswers(numbers.get(0)); } /* Creates the possible answers for each question. One of them is always the correct one: level*second_number (Randomized number from 1 to 10. Different for each question.) The two additional (wrong) answers are creating by multiplying the level with a random number between 1-10, excluding the correct number. This ensures that even the wrong answers are from that times table, and thus, are believable. */ private void createAnswers(int second_number){ fillPossibleAnswers(second_number); Collections.shuffle(possible_answers); button1.setText(possible_answers.get(0).toString()); button2.setText(possible_answers.get(1).toString()); button3.setText(possible_answers.get(2).toString()); } //Fills the list with all 3 possible answers. private void fillPossibleAnswers(int second_number){ possible_answers.clear(); possible_answers.add(level*second_number); //Correct answer List<Integer> temp_numbers = new ArrayList<>(numbers); //Clone of the shuffled number list from 1-10. temp_numbers.remove(new Integer(second_number)); //Removes the second_number from the clone in order not to get the same answer twice. Random r = new Random(); int x = r.nextInt(9); possible_answers.add(level*temp_numbers.get(x)); //Randomly chosen number, multiplied by level gives the first wrong answer. temp_numbers.remove(x); //Removes the first wrong number from the clone in order not to get the same answer twice. x = r.nextInt(8); possible_answers.add(level*temp_numbers.get(x)); //Randomly chosen number, multiplied by level gives the second wrong answer. } //Creates the next question or shows results if the test is over. public void nextQuestion(){ //Resets the background colors button1.setBackgroundResource(R.drawable.backbtn); button2.setBackgroundResource(R.drawable.backbtn); button3.setBackgroundResource(R.drawable.backbtn); button1.setClickable(true); button2.setClickable(true); button3.setClickable(true); //Disables the transition to the next question until an answer is clicked. nextQuestionButton.setEnabled(false); questionNumber++; fillTextViews(); createAnswers(numbers.get(questionNumber)); if (questionNumber == 9){ //No more questions nextQuestionButton.setText("Show Results"); } } //Fills the text views with the question and the question number private void fillTextViews(){ farmerTextView.setText("Question " + (questionNumber+1)); questionTextView.setText(numbers.get(questionNumber) + " x " + level); nextQuestionButton.setEnabled(false); } //Whenever an answer is clicked, checks if the button's text is the correct answer. public void answerClicked(View view){ Utils.preventTwoClick(view); Button b = (Button)view; int buttons_answer = Integer.parseInt(b.getText().toString()); //Number clicked if (buttons_answer == numbers.get(questionNumber) * level){ //Correct answer correct_answers++; correctAnswer(b); } else { //Wrong answer wrongAnswer(b); } //Cannot select a second answer. button1.setClickable(false); button2.setClickable(false); button3.setClickable(false); //Allows the transition to the next question. nextQuestionButton.setEnabled(true); } public void nextQuestionButtonClick(View view){ Utils.preventTwoClick(view); if (questionNumber < 9){ //Next question nextQuestion(); } else if (questionNumber == 9) { //Show results showResults(); } else { if (extra_slide){ showTheory(); } else { //Return to menu Intent intent = new Intent(getBaseContext(),testsPerNumber.class); intent.putExtra("id",id); startActivity(intent); finish(); } } } //Is called when a correct answer is selected. private void correctAnswer(Button b){ farmerTextView.setText("Correct!"); //Farmer's bubble b.setBackgroundColor(Color.GREEN); answerQuestion(numbers.get(questionNumber), level, true); } //Is called when a correct answer is selected. private void wrongAnswer(Button b){ farmerTextView.setText("Wrong! The correct answer is " + numbers.get(questionNumber)*level + "."); //Farmer's bubble b.setBackgroundColor(Color.RED); answerQuestion(numbers.get(questionNumber), level, false); } public void answerQuestion(int firstNumber, int secondNumber, boolean answeredCorrectly){ DatabaseHelper dataBaseHelper =new DatabaseHelper(this); dataBaseHelper.openDataBase(); String statsString =dataBaseHelper.getStudentsStats(id); String oldStatsString = statsString; String newStatsString = ""; String line; int targetLine = ((firstNumber-1)*10 + (secondNumber-1))*10; //Η γραμμή που πρέπει να αλλαχθεί. Log.d("HERE",oldStatsString); for (int i=0; i<oldStatsString.length(); i+=10) { //Για κάθε πράξη... line = oldStatsString.substring(i,i+10); Log.d("line",line); if (i==targetLine){ StringBuffer sb = new StringBuffer(line); sb.deleteCharAt(sb.length()-1); //Διαγραφή τελευταίας εγγραφής. //Προσθήκη νέας<SUF> if (answeredCorrectly){ line = "1" + sb.toString(); } else { line = "0" + sb.toString(); } Log.d("line2",line); } newStatsString += line; } //Εισαγωγή στη βάση. dataBaseHelper.setStudentsStats(id,newStatsString); dataBaseHelper.close(); } //Shows the test results. public void showResults(){ button1.setVisibility(View.GONE); button2.setVisibility(View.GONE); button3.setVisibility(View.GONE); questionNumber++; //(=10) Just to pass the info to nextQuestionButtonClick and return to menu if clicked again. questionTextView.setVisibility(View.GONE); //Empties the board farmerTextView.setTextSize(20); String s = String.valueOf(correct_answers); s += " correct answers! "; DatabaseHelper dataBaseHelper =new DatabaseHelper(this); dataBaseHelper.openDataBase(); //Extra message if (correct_answers <= 4) { s += "You need more practice!"; } else if (correct_answers < 7) { s += "You're almost there!"; } else if (correct_answers <= 9) { s += "Great job!"; //update level if(levelOfStudent==level){ dataBaseHelper.updateStudentsLevel(id); dataBaseHelper.updateStudentsLevelLesson(false,id); } } else { //correct_answers == 10 s += "Perfect score! Well done!"; //update if(levelOfStudent==level){ dataBaseHelper.updateStudentsLevel(id); dataBaseHelper.updateStudentsLevelLesson(false,id); } } dataBaseHelper.close(); farmerTextView.setText(s); if (correct_answers < 7){ nextQuestionButton.setText("Next"); extra_slide = true; //Is going to show the extra (theory) panel. } else { nextQuestionButton.setText("Back to Menu"); extra_slide = false; } } private void showTheory(){ TextView rememberTextView = findViewById(R.id.rememberTextView); rememberTextView.setTextColor(Color.BLACK); rememberTextView.setVisibility(View.VISIBLE); gifImageView = findViewById(R.id.gifView); gifImageView.setVisibility(View.VISIBLE); //Shows slide (theory panel) depending on level (times table). 6 and 9 not optimal!!!!!! switch (level){ case 1: gifImageView.setImageResource(R.drawable.slide1_3); break; case 2: gifImageView.setImageResource(R.drawable.slide2_3); break; case 3: gifImageView.setImageResource(R.drawable.slide3_2); break; case 4: gifImageView.setImageResource(R.drawable.slide4_2); break; case 5: gifImageView.setImageResource(R.drawable.slide5_3); break; case 6: gifImageView.setImageResource(R.drawable.slide6_13); break; case 7: gifImageView.setImageResource(R.drawable.slide7_3); break; case 8: gifImageView.setImageResource(R.drawable.slide8_2); break; case 9: gifImageView.setImageResource(R.drawable.slide9_4); break; case 10: gifImageView.setImageResource(R.drawable.slide10_3); break; default: gifImageView.setImageResource(R.drawable.slide1_3); break; } nextQuestionButton.setText("Next"); extra_slide = false; } @Override public void onBackPressed() { //nothing } private void hideSystemUI() { // Enables sticky immersive mode. View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY // Set the content to appear under the system bars so that the // content doesn't resize when the system bars hide and show. | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // Hide the nav bar and status bar | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN ); } public void onResume(){ super.onResume(); hideSystemUI(); } }
5093_11
package application.api; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class URestController { private String userId; private String username; private URequestComponent requestComponent; public URestController() { requestComponent = new URequestComponent(); } /* Συνάρτηση για την σύνδεση του χρήστη με το API, επιστρέφει βασικες πληροφορίες σχετικά με τον χρήστη FLoginResponse για περισσότερες πληροφορίες. Απαιτείται Login για την κλήση των υπόλοιπων συναρτήσεων */ public FLoginResponse doLogin(String username, String password) throws IOException, ParseException { JSONObject obj = new JSONObject(); obj.put("username", username); obj.put("password", password); FRestResponse r = requestComponent.Post("/api/auth/login/", obj); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); data = (JSONObject)data.get("triggerResults"); userId = (String) data.get("id"); this.username = username; return new FLoginResponse(true, userId, (String)data.get("displayName"), username, ((Number)data.get("accountType")).intValue(), ((Number)data.get("associatedProfessor")).intValue(), ((Number)data.get("orientation")).intValue()); } return new FLoginResponse(false); } public ArrayList<FProfessorsResponse> getAllProfessors() throws IOException, ParseException{ FRestResponse r = requestComponent.Get("/api/professors"); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); JSONArray arrayData = (JSONArray)data.get("triggerResults"); ArrayList<FProfessorsResponse> outResponse = new ArrayList<FProfessorsResponse>(); for(int i = 0; i<arrayData.size(); i++) { JSONObject tempData = (JSONObject)arrayData.get(i); outResponse.add(new FProfessorsResponse(((Number)tempData.get("id")).intValue(), (String) tempData.get("name"), (String) tempData.get("phone"), (String) tempData.get("email"), (String) tempData.get("profilePhoto"), (String) tempData.get("office"), ((Number)tempData.get("rating")).floatValue(), (String) tempData.get("bio"))); } return outResponse; } return new ArrayList<FProfessorsResponse>(); } public float getProfessorRating(int professorId) throws IOException, ParseException{ FRestResponse r = requestComponent.Get("/api/professors/rating?professorId="+professorId); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); data = (JSONObject)data.get("triggerResults"); return ((Number)(data.get("rating"))).floatValue(); } return 0; } public int getMyProfessorRating(int professorId) throws IOException, ParseException{ FRestResponse r = requestComponent.Get("/api/professors/rating?professorId="+professorId); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); data = (JSONObject)data.get("triggerResults"); return ((Number)(data.get("myRating"))).intValue(); } return -1; } public boolean setProfessorRating(int rating, int professorId) throws IOException { JSONObject obj = new JSONObject(); obj.put("rating", rating); obj.put("professorId", professorId); FRestResponse r = requestComponent.Post("/api/professors/rating/", obj); return r.statusCode==200; } /* Επιστρέφει μια λίστα με όλα τα μαθήματα που είναι καταχωρημένα στην βάση δεδομένων. */ public ArrayList<FSubjectsResponse> getAllSubjects() throws IOException, ParseException{ FRestResponse r = requestComponent.Get("/api/subjects"); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); JSONArray arrayData = (JSONArray)data.get("triggerResults"); ArrayList<FSubjectsResponse> outResponse = new ArrayList<FSubjectsResponse>(); for(int i = 0; i<arrayData.size(); i++) { JSONObject tempData = (JSONObject)arrayData.get(i); ArrayList<String> listdata = new ArrayList<String>(); JSONArray jArray = (JSONArray)tempData.get("associatedProfessors"); if (jArray != null) { for (int j=0;j<jArray.size();j++){ listdata.add((String) jArray.get(j)); } } outResponse.add(new FSubjectsResponse(((String)tempData.get("id")), (String) tempData.get("name"), listdata, ((Number)tempData.get("rating")).floatValue(), ((Number)tempData.get("semester")).intValue(), ((Number)tempData.get("orientation")).intValue())); } return outResponse; } return new ArrayList<FSubjectsResponse>(); } /* Συνάρτηση για αξιολόγηση μαθήματος, μπορει να κληθεί μόνο μια φορά ανα μάθημα. Βαθμολογια πρεπει να ειναι απο 1-5 */ public boolean setSubjectRating(int rating, String subjectId) throws IOException { JSONObject obj = new JSONObject(); obj.put("rating", rating); obj.put("subjectId", subjectId); FRestResponse r = requestComponent.Post("/api/subjects/rating/", obj); return r.statusCode==200; } /* Συνάρτηση για ληψη βαθμολογίας ενός μαθήματος */ public float getSubjectRating(String subjectId) throws IOException, ParseException{ FRestResponse r = requestComponent.Get("/api/subjects/rating?subjectId="+subjectId); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); data = (JSONObject)data.get("triggerResults"); return ((Number)(data.get("rating"))).floatValue(); } return 0; } /* Συνάρτηση για ληψη βαθμολογίας που εχει θεσει ο χρηστης για ενα μαθημα -1 σε περιπτωση που δεν εχει βαθμολογησει το μαθημα. */ public int getMySubjectRating(String subjectId) throws IOException, ParseException{ FRestResponse r = requestComponent.Get("/api/subjects/rating?subjectId="+subjectId); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); data = (JSONObject)data.get("triggerResults"); return ((Number)(data.get("myRating"))).intValue(); } return -1; } /* Συνάρτηση για ληψη εγγεγραμενων μαθηματων, επιστρεφει μια λιστα με τα id των μαθηματων. */ public ArrayList<String> getEnrolledSubjects() throws IOException, ParseException{ FRestResponse r = requestComponent.Get("/api/subjects/enrollments"); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); data = (JSONObject) data.get("triggerResults"); JSONArray jArray = (JSONArray)data.get("enrollments"); if(jArray==null) { return new ArrayList<String>(); } ArrayList<String> listdata = new ArrayList<String>(); if (jArray != null) { for (int j=0;j<jArray.size();j++){ listdata.add((String) jArray.get(j)); } } return listdata; } return new ArrayList<String>(); } /* Συνάρτηση για εγγραφή σε μαθημα, μεγιστο 10 μαθήματα */ public boolean enrollSubject(String subjectId) throws IOException{ JSONObject obj = new JSONObject(); obj.put("subjectId", subjectId); FRestResponse r = requestComponent.Post("/api/subjects/enrollments/enroll/", obj); return r.statusCode==200; } /* Συνάρτηση για απεγγραφή σε μαθημα, μεγιστο 10 μαθήματα */ public boolean disenrollSubject(String subjectId) throws IOException{ JSONObject obj = new JSONObject(); obj.put("subjectId", subjectId); FRestResponse r = requestComponent.Post("/api/subjects/enrollments/disenroll/", obj); return r.statusCode==200; } /* Συνάρτηση για ληψη διαθεσιμων ημερομηνιων για ραντεβου ενος καθηγητη. Δειτε FAvailabilityResponse */ public FAvailabilityResponse getAvailabilityDates(int professorId) throws IOException, ParseException { FRestResponse r = requestComponent.Get("/api/appointments/availability?professorId="+professorId); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); data = (JSONObject)data.get("triggerResults"); JSONArray arrayData = (JSONArray)data.get("availability"); ArrayList<HashMap<String, Integer>> dates = new ArrayList<HashMap<String, Integer>>(); for(int i = 0; i<arrayData.size(); i++) { JSONObject tempData = (JSONObject)arrayData.get(i); HashMap<String, Integer> dateElement = new HashMap<String, Integer>(); dateElement.put("day", ((Number)tempData.get("day")).intValue()); dateElement.put("startHour", ((Number)tempData.get("startHour")).intValue()); dateElement.put("endHour", ((Number)tempData.get("endHour")).intValue()); dates.add(dateElement); } return new FAvailabilityResponse(true, dates); } return new FAvailabilityResponse(false); } /* * Συνάρτηση για ληψη ηδη κλεισμενων ραντεβου ενος καθηγητη * Η μορφη ειναι timestamp. */ public ArrayList<Integer> getBookedTimestamps(int professorId) throws IOException, ParseException{ FRestResponse r = requestComponent.Get("/api/appointments/availability?professorId="+professorId); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); data = (JSONObject)data.get("triggerResults"); JSONArray arrayData = (JSONArray)data.get("bookedTimestamps"); ArrayList<Integer> booked = new ArrayList<Integer>(); for(int i = 0; i<arrayData.size(); i++) { booked.add(((Number)arrayData.get(i)).intValue()); } return booked; } return new ArrayList<Integer>(); } /* Συνάρτηση για ενημερωση των διαθεσιμων ημερομηνιων του καθηγητη. Μπορει να κληθει μονο αν accountType = 1, δειτε FLoginResponse. */ public boolean setAvailabilityDates(int day, int startHour, int endHour) throws IOException{ JSONObject obj = new JSONObject(); obj.put("day", day); obj.put("startHour", startHour); obj.put("endHour", endHour); FRestResponse r = requestComponent.Post("/api/appointments/availability/", obj); return r.statusCode==200; } public ArrayList<FAppointmentsResponse> getMyAppointments() throws IOException, ParseException{ FRestResponse r = requestComponent.Get("/api/appointments"); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); JSONArray arrayData = (JSONArray)data.get("triggerResults"); if(arrayData==null) { return new ArrayList<FAppointmentsResponse>(); } ArrayList<FAppointmentsResponse> outResponse = new ArrayList<FAppointmentsResponse>(); for(int i = 0; i<arrayData.size(); i++) { JSONObject tempData = (JSONObject)arrayData.get(i); outResponse.add(new FAppointmentsResponse(((Number)tempData.get("appointmentId")).intValue(), (String) tempData.get("studentId"), ((Number) tempData.get("professorId")).intValue(), ((Number) tempData.get("date")).intValue(), ((Number) tempData.get("status")).intValue(), (String) tempData.get("created_at"))); } return outResponse; } return new ArrayList<FAppointmentsResponse>(); } /* * Συνάρτηση για αποδοχή ραντεβού, μπορεί να κληθεί μόνο απο καθηγητή. * δεν μπορεί να κληθεί αν το ραντεβού είναι ακυρωμένο ή ηδη επιβεβαιωμένο */ public boolean acceptAppointment(int appointmentId) throws IOException { JSONObject obj = new JSONObject(); obj.put("appointmentId", appointmentId); FRestResponse r = requestComponent.Post("/api/appointments/accept/", obj); return r.statusCode==200; } /* * Συνάρτηση για ακύρωση ραντεβού, μπορεί να κληθεί αν ο χρήστης ανήκει σε αυτό το ραντεβού. * δεν μπορεί να κληθεί αν το ραντεβού είναι ακυρωμένο. */ public boolean cancelAppointment(int appointmentId) throws IOException { JSONObject obj = new JSONObject(); obj.put("appointmentId", appointmentId); FRestResponse r = requestComponent.Post("/api/appointments/cancel/", obj); return r.statusCode==200; } /* * Συνάρτηση για κλείσιμο ραντεβού, μπορεί να κληθεί αν ο χρήστης είναι φοιτητής */ public boolean bookAppointment(int professorId, int dateTimestamp) throws IOException { JSONObject obj = new JSONObject(); obj.put("professorId", professorId); obj.put("timestamp", dateTimestamp); FRestResponse r = requestComponent.Post("/api/appointments/book/", obj); return r.statusCode==200; } /* * Συνάρτηση για ληψη βασικών πληροφοριών ενός χρήστη * Πολυ χρήσιμη για τα ραντεβου. */ public FUserInformationResponse getUserProfile(String userId) throws IOException, ParseException{ FRestResponse r = requestComponent.Get("/api/profile?userId="+userId); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); data = (JSONObject)data.get("triggerResults"); return new FUserInformationResponse(true, (String)data.get("displayName"), (String)data.get("bio"), (String)data.get("email")); } return new FUserInformationResponse(false); } /* * Συνάρτηση για να θεσουμε νεο display name */ public boolean setDisplayName(String newDisplayName) throws IOException { JSONObject obj = new JSONObject(); obj.put("displayName", newDisplayName); FRestResponse r = requestComponent.Put("/api/profile/displayName/", obj); return r.statusCode==200; } public boolean setBio(String bio) throws IOException { JSONObject obj = new JSONObject(); obj.put("bio", bio); FRestResponse r = requestComponent.Put("/api/profile/bio/", obj); return r.statusCode==200; } public boolean setOrientation(int orientation) throws IOException { JSONObject obj = new JSONObject(); obj.put("orientation", orientation); FRestResponse r = requestComponent.Put("/api/profile/orientation/", obj); return r.statusCode==200; } public boolean setPassword(String oldPassword, String newPassword) throws IOException { JSONObject obj = new JSONObject(); obj.put("oldPassword", oldPassword); obj.put("newPassword", newPassword); FRestResponse r = requestComponent.Post("/api/auth/password/", obj); return r.statusCode==200; } /* Συνάρτηση για εγγραφη νεου χρηστη */ public boolean doRegister(String username, String password, String displayName, String email, int orientation) throws IOException{ JSONObject obj = new JSONObject(); obj.put("username", username); obj.put("password", password); obj.put("displayName", displayName); obj.put("email", email); obj.put("orientation", orientation); FRestResponse r = requestComponent.Post("/api/auth/register/", obj); return r.statusCode==200; } }
Nerdwork-Team/Nerdwork-Project
Nerdwork/src/application/api/URestController.java
5,177
/* * Συνάρτηση για αποδοχή ραντεβού, μπορεί να κληθεί μόνο απο καθηγητή. * δεν μπορεί να κληθεί αν το ραντεβού είναι ακυρωμένο ή ηδη επιβεβαιωμένο */
block_comment
el
package application.api; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class URestController { private String userId; private String username; private URequestComponent requestComponent; public URestController() { requestComponent = new URequestComponent(); } /* Συνάρτηση για την σύνδεση του χρήστη με το API, επιστρέφει βασικες πληροφορίες σχετικά με τον χρήστη FLoginResponse για περισσότερες πληροφορίες. Απαιτείται Login για την κλήση των υπόλοιπων συναρτήσεων */ public FLoginResponse doLogin(String username, String password) throws IOException, ParseException { JSONObject obj = new JSONObject(); obj.put("username", username); obj.put("password", password); FRestResponse r = requestComponent.Post("/api/auth/login/", obj); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); data = (JSONObject)data.get("triggerResults"); userId = (String) data.get("id"); this.username = username; return new FLoginResponse(true, userId, (String)data.get("displayName"), username, ((Number)data.get("accountType")).intValue(), ((Number)data.get("associatedProfessor")).intValue(), ((Number)data.get("orientation")).intValue()); } return new FLoginResponse(false); } public ArrayList<FProfessorsResponse> getAllProfessors() throws IOException, ParseException{ FRestResponse r = requestComponent.Get("/api/professors"); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); JSONArray arrayData = (JSONArray)data.get("triggerResults"); ArrayList<FProfessorsResponse> outResponse = new ArrayList<FProfessorsResponse>(); for(int i = 0; i<arrayData.size(); i++) { JSONObject tempData = (JSONObject)arrayData.get(i); outResponse.add(new FProfessorsResponse(((Number)tempData.get("id")).intValue(), (String) tempData.get("name"), (String) tempData.get("phone"), (String) tempData.get("email"), (String) tempData.get("profilePhoto"), (String) tempData.get("office"), ((Number)tempData.get("rating")).floatValue(), (String) tempData.get("bio"))); } return outResponse; } return new ArrayList<FProfessorsResponse>(); } public float getProfessorRating(int professorId) throws IOException, ParseException{ FRestResponse r = requestComponent.Get("/api/professors/rating?professorId="+professorId); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); data = (JSONObject)data.get("triggerResults"); return ((Number)(data.get("rating"))).floatValue(); } return 0; } public int getMyProfessorRating(int professorId) throws IOException, ParseException{ FRestResponse r = requestComponent.Get("/api/professors/rating?professorId="+professorId); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); data = (JSONObject)data.get("triggerResults"); return ((Number)(data.get("myRating"))).intValue(); } return -1; } public boolean setProfessorRating(int rating, int professorId) throws IOException { JSONObject obj = new JSONObject(); obj.put("rating", rating); obj.put("professorId", professorId); FRestResponse r = requestComponent.Post("/api/professors/rating/", obj); return r.statusCode==200; } /* Επιστρέφει μια λίστα με όλα τα μαθήματα που είναι καταχωρημένα στην βάση δεδομένων. */ public ArrayList<FSubjectsResponse> getAllSubjects() throws IOException, ParseException{ FRestResponse r = requestComponent.Get("/api/subjects"); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); JSONArray arrayData = (JSONArray)data.get("triggerResults"); ArrayList<FSubjectsResponse> outResponse = new ArrayList<FSubjectsResponse>(); for(int i = 0; i<arrayData.size(); i++) { JSONObject tempData = (JSONObject)arrayData.get(i); ArrayList<String> listdata = new ArrayList<String>(); JSONArray jArray = (JSONArray)tempData.get("associatedProfessors"); if (jArray != null) { for (int j=0;j<jArray.size();j++){ listdata.add((String) jArray.get(j)); } } outResponse.add(new FSubjectsResponse(((String)tempData.get("id")), (String) tempData.get("name"), listdata, ((Number)tempData.get("rating")).floatValue(), ((Number)tempData.get("semester")).intValue(), ((Number)tempData.get("orientation")).intValue())); } return outResponse; } return new ArrayList<FSubjectsResponse>(); } /* Συνάρτηση για αξιολόγηση μαθήματος, μπορει να κληθεί μόνο μια φορά ανα μάθημα. Βαθμολογια πρεπει να ειναι απο 1-5 */ public boolean setSubjectRating(int rating, String subjectId) throws IOException { JSONObject obj = new JSONObject(); obj.put("rating", rating); obj.put("subjectId", subjectId); FRestResponse r = requestComponent.Post("/api/subjects/rating/", obj); return r.statusCode==200; } /* Συνάρτηση για ληψη βαθμολογίας ενός μαθήματος */ public float getSubjectRating(String subjectId) throws IOException, ParseException{ FRestResponse r = requestComponent.Get("/api/subjects/rating?subjectId="+subjectId); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); data = (JSONObject)data.get("triggerResults"); return ((Number)(data.get("rating"))).floatValue(); } return 0; } /* Συνάρτηση για ληψη βαθμολογίας που εχει θεσει ο χρηστης για ενα μαθημα -1 σε περιπτωση που δεν εχει βαθμολογησει το μαθημα. */ public int getMySubjectRating(String subjectId) throws IOException, ParseException{ FRestResponse r = requestComponent.Get("/api/subjects/rating?subjectId="+subjectId); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); data = (JSONObject)data.get("triggerResults"); return ((Number)(data.get("myRating"))).intValue(); } return -1; } /* Συνάρτηση για ληψη εγγεγραμενων μαθηματων, επιστρεφει μια λιστα με τα id των μαθηματων. */ public ArrayList<String> getEnrolledSubjects() throws IOException, ParseException{ FRestResponse r = requestComponent.Get("/api/subjects/enrollments"); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); data = (JSONObject) data.get("triggerResults"); JSONArray jArray = (JSONArray)data.get("enrollments"); if(jArray==null) { return new ArrayList<String>(); } ArrayList<String> listdata = new ArrayList<String>(); if (jArray != null) { for (int j=0;j<jArray.size();j++){ listdata.add((String) jArray.get(j)); } } return listdata; } return new ArrayList<String>(); } /* Συνάρτηση για εγγραφή σε μαθημα, μεγιστο 10 μαθήματα */ public boolean enrollSubject(String subjectId) throws IOException{ JSONObject obj = new JSONObject(); obj.put("subjectId", subjectId); FRestResponse r = requestComponent.Post("/api/subjects/enrollments/enroll/", obj); return r.statusCode==200; } /* Συνάρτηση για απεγγραφή σε μαθημα, μεγιστο 10 μαθήματα */ public boolean disenrollSubject(String subjectId) throws IOException{ JSONObject obj = new JSONObject(); obj.put("subjectId", subjectId); FRestResponse r = requestComponent.Post("/api/subjects/enrollments/disenroll/", obj); return r.statusCode==200; } /* Συνάρτηση για ληψη διαθεσιμων ημερομηνιων για ραντεβου ενος καθηγητη. Δειτε FAvailabilityResponse */ public FAvailabilityResponse getAvailabilityDates(int professorId) throws IOException, ParseException { FRestResponse r = requestComponent.Get("/api/appointments/availability?professorId="+professorId); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); data = (JSONObject)data.get("triggerResults"); JSONArray arrayData = (JSONArray)data.get("availability"); ArrayList<HashMap<String, Integer>> dates = new ArrayList<HashMap<String, Integer>>(); for(int i = 0; i<arrayData.size(); i++) { JSONObject tempData = (JSONObject)arrayData.get(i); HashMap<String, Integer> dateElement = new HashMap<String, Integer>(); dateElement.put("day", ((Number)tempData.get("day")).intValue()); dateElement.put("startHour", ((Number)tempData.get("startHour")).intValue()); dateElement.put("endHour", ((Number)tempData.get("endHour")).intValue()); dates.add(dateElement); } return new FAvailabilityResponse(true, dates); } return new FAvailabilityResponse(false); } /* * Συνάρτηση για ληψη ηδη κλεισμενων ραντεβου ενος καθηγητη * Η μορφη ειναι timestamp. */ public ArrayList<Integer> getBookedTimestamps(int professorId) throws IOException, ParseException{ FRestResponse r = requestComponent.Get("/api/appointments/availability?professorId="+professorId); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); data = (JSONObject)data.get("triggerResults"); JSONArray arrayData = (JSONArray)data.get("bookedTimestamps"); ArrayList<Integer> booked = new ArrayList<Integer>(); for(int i = 0; i<arrayData.size(); i++) { booked.add(((Number)arrayData.get(i)).intValue()); } return booked; } return new ArrayList<Integer>(); } /* Συνάρτηση για ενημερωση των διαθεσιμων ημερομηνιων του καθηγητη. Μπορει να κληθει μονο αν accountType = 1, δειτε FLoginResponse. */ public boolean setAvailabilityDates(int day, int startHour, int endHour) throws IOException{ JSONObject obj = new JSONObject(); obj.put("day", day); obj.put("startHour", startHour); obj.put("endHour", endHour); FRestResponse r = requestComponent.Post("/api/appointments/availability/", obj); return r.statusCode==200; } public ArrayList<FAppointmentsResponse> getMyAppointments() throws IOException, ParseException{ FRestResponse r = requestComponent.Get("/api/appointments"); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); JSONArray arrayData = (JSONArray)data.get("triggerResults"); if(arrayData==null) { return new ArrayList<FAppointmentsResponse>(); } ArrayList<FAppointmentsResponse> outResponse = new ArrayList<FAppointmentsResponse>(); for(int i = 0; i<arrayData.size(); i++) { JSONObject tempData = (JSONObject)arrayData.get(i); outResponse.add(new FAppointmentsResponse(((Number)tempData.get("appointmentId")).intValue(), (String) tempData.get("studentId"), ((Number) tempData.get("professorId")).intValue(), ((Number) tempData.get("date")).intValue(), ((Number) tempData.get("status")).intValue(), (String) tempData.get("created_at"))); } return outResponse; } return new ArrayList<FAppointmentsResponse>(); } /* * Συνάρτηση για αποδοχή<SUF>*/ public boolean acceptAppointment(int appointmentId) throws IOException { JSONObject obj = new JSONObject(); obj.put("appointmentId", appointmentId); FRestResponse r = requestComponent.Post("/api/appointments/accept/", obj); return r.statusCode==200; } /* * Συνάρτηση για ακύρωση ραντεβού, μπορεί να κληθεί αν ο χρήστης ανήκει σε αυτό το ραντεβού. * δεν μπορεί να κληθεί αν το ραντεβού είναι ακυρωμένο. */ public boolean cancelAppointment(int appointmentId) throws IOException { JSONObject obj = new JSONObject(); obj.put("appointmentId", appointmentId); FRestResponse r = requestComponent.Post("/api/appointments/cancel/", obj); return r.statusCode==200; } /* * Συνάρτηση για κλείσιμο ραντεβού, μπορεί να κληθεί αν ο χρήστης είναι φοιτητής */ public boolean bookAppointment(int professorId, int dateTimestamp) throws IOException { JSONObject obj = new JSONObject(); obj.put("professorId", professorId); obj.put("timestamp", dateTimestamp); FRestResponse r = requestComponent.Post("/api/appointments/book/", obj); return r.statusCode==200; } /* * Συνάρτηση για ληψη βασικών πληροφοριών ενός χρήστη * Πολυ χρήσιμη για τα ραντεβου. */ public FUserInformationResponse getUserProfile(String userId) throws IOException, ParseException{ FRestResponse r = requestComponent.Get("/api/profile?userId="+userId); if(r.statusCode==200) { JSONParser parser = new JSONParser(); JSONObject data = (JSONObject) parser.parse(r.responseContent); data = (JSONObject)data.get("triggerResults"); return new FUserInformationResponse(true, (String)data.get("displayName"), (String)data.get("bio"), (String)data.get("email")); } return new FUserInformationResponse(false); } /* * Συνάρτηση για να θεσουμε νεο display name */ public boolean setDisplayName(String newDisplayName) throws IOException { JSONObject obj = new JSONObject(); obj.put("displayName", newDisplayName); FRestResponse r = requestComponent.Put("/api/profile/displayName/", obj); return r.statusCode==200; } public boolean setBio(String bio) throws IOException { JSONObject obj = new JSONObject(); obj.put("bio", bio); FRestResponse r = requestComponent.Put("/api/profile/bio/", obj); return r.statusCode==200; } public boolean setOrientation(int orientation) throws IOException { JSONObject obj = new JSONObject(); obj.put("orientation", orientation); FRestResponse r = requestComponent.Put("/api/profile/orientation/", obj); return r.statusCode==200; } public boolean setPassword(String oldPassword, String newPassword) throws IOException { JSONObject obj = new JSONObject(); obj.put("oldPassword", oldPassword); obj.put("newPassword", newPassword); FRestResponse r = requestComponent.Post("/api/auth/password/", obj); return r.statusCode==200; } /* Συνάρτηση για εγγραφη νεου χρηστη */ public boolean doRegister(String username, String password, String displayName, String email, int orientation) throws IOException{ JSONObject obj = new JSONObject(); obj.put("username", username); obj.put("password", password); obj.put("displayName", displayName); obj.put("email", email); obj.put("orientation", orientation); FRestResponse r = requestComponent.Post("/api/auth/register/", obj); return r.statusCode==200; } }
2507_2
package com.example.quickrepair.view.Customer.ShowCompletedRepairRequest; public interface CustomerCompletedRepairRequestView { /** * Προβάλει μήνυμα λάθους * @param message Το Μήνυμα λάθους */ void showError(String message); /** * Εμφανίζει τη δουλειά * @param job Η δουλειά */ void setJob(String job); /** * Εμφανίζει το όνομα του τεχνικού * @param technicianName Το όνομα του τεχνηκού */ void setTechnicianName(String technicianName); /** * Εμφανίζει τη διεύθυνση * @param address Η διεύθυνση */ void setAddress(String address); /** * Εμφανίζει τα σχόλια * @param comments Τα σχόλια */ void setComments(String comments); /** * Εμφανίζει την ημερομηνία διεξαγωγής της επισκευής * @param conductionDate Η ημερομηνία διεξαγωγής της επισκευής */ void setConductionDate(String conductionDate); /** * Εμφανίζει το εκτιμώμενο απο τον τεχνικό χρόνο της επισκευής * @param estimatedDuration Ο εκτιμώμενος απο τον τεχνικό χρόνος της επισκευής */ void setEstimatedDuration(String estimatedDuration); /** * Εμφανίζει το κόστος * @param cost Το κόστος */ void setCost(String cost); /** * Εμφανίζει τα στοιχεία της αξιολόγησης * @param title Ο τίτλος της αξιολόγησης * @param comments Τα σχόλια της αξιολόγησης * @param rate Η βαθμολογία της αξιολόγησης */ void setEvaluationData(String title, String comments, String rate); /** * Εμφανίζει τα πεδία για πληρωμή και προσθήκη σχολίων */ void setPayAndEvaluationFields(); /** * Ενεργοποίηση δυνατότητας πληρωμής */ void setPayListener(); /** * Αίτημα για πληρωμή και αξιολόγηση */ void donePayAndEvaluate(); }
NickSmyr/UndergraduateProjects
6th semester/SoftwareEngineering/android/app/src/main/java/com/example/quickrepair/view/Customer/ShowCompletedRepairRequest/CustomerCompletedRepairRequestView.java
886
/** * Εμφανίζει το όνομα του τεχνικού * @param technicianName Το όνομα του τεχνηκού */
block_comment
el
package com.example.quickrepair.view.Customer.ShowCompletedRepairRequest; public interface CustomerCompletedRepairRequestView { /** * Προβάλει μήνυμα λάθους * @param message Το Μήνυμα λάθους */ void showError(String message); /** * Εμφανίζει τη δουλειά * @param job Η δουλειά */ void setJob(String job); /** * Εμφανίζει το όνομα<SUF>*/ void setTechnicianName(String technicianName); /** * Εμφανίζει τη διεύθυνση * @param address Η διεύθυνση */ void setAddress(String address); /** * Εμφανίζει τα σχόλια * @param comments Τα σχόλια */ void setComments(String comments); /** * Εμφανίζει την ημερομηνία διεξαγωγής της επισκευής * @param conductionDate Η ημερομηνία διεξαγωγής της επισκευής */ void setConductionDate(String conductionDate); /** * Εμφανίζει το εκτιμώμενο απο τον τεχνικό χρόνο της επισκευής * @param estimatedDuration Ο εκτιμώμενος απο τον τεχνικό χρόνος της επισκευής */ void setEstimatedDuration(String estimatedDuration); /** * Εμφανίζει το κόστος * @param cost Το κόστος */ void setCost(String cost); /** * Εμφανίζει τα στοιχεία της αξιολόγησης * @param title Ο τίτλος της αξιολόγησης * @param comments Τα σχόλια της αξιολόγησης * @param rate Η βαθμολογία της αξιολόγησης */ void setEvaluationData(String title, String comments, String rate); /** * Εμφανίζει τα πεδία για πληρωμή και προσθήκη σχολίων */ void setPayAndEvaluationFields(); /** * Ενεργοποίηση δυνατότητας πληρωμής */ void setPayListener(); /** * Αίτημα για πληρωμή και αξιολόγηση */ void donePayAndEvaluate(); }
8411_1
import java.io.FileWriter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.JOptionPane; public class MainFrame extends javax.swing.JFrame { public MainFrame() { initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { NewDialog = new javax.swing.JDialog(); infogame = new javax.swing.JTextField(); price = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); typosgame = new javax.swing.JList<>(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); ToolTip = new javax.swing.JLabel(); Posotita2 = new javax.swing.JSpinner(); jMenuBar1 = new javax.swing.JMenuBar(); File = new javax.swing.JMenu(); About = new javax.swing.JMenuItem(); Exit = new javax.swing.JMenuItem(); Sales = new javax.swing.JMenu(); New = new javax.swing.JMenuItem(); Save = new javax.swing.JMenuItem(); Total = new javax.swing.JMenuItem(); infogame.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { infogameActionPerformed(evt); } }); infogame.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { infogameKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { infogameKeyReleased(evt); } }); price.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { priceKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { priceKeyReleased(evt); } }); typosgame.setBorder(javax.swing.BorderFactory.createTitledBorder("Είδος Παιχνιδιού")); typosgame.setModel(new javax.swing.AbstractListModel<String>() { String[] strings = { "Επιτραπέζιο", "Ηλεκτρονικό", "other" }; public int getSize() { return strings.length; } public String getElementAt(int i) { return strings[i]; } }); typosgame.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); typosgame.setToolTipText(""); typosgame.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { typosgameValueChanged(evt); } }); jScrollPane1.setViewportView(typosgame); jLabel1.setText("Περιγραφη παιχνιδιου"); jLabel2.setText("Ποσοτητα"); jLabel8.setText("Τιμη"); Posotita2.setModel(new javax.swing.SpinnerNumberModel(1, 1, null, 1)); Posotita2.setToolTipText(""); javax.swing.GroupLayout NewDialogLayout = new javax.swing.GroupLayout(NewDialog.getContentPane()); NewDialog.getContentPane().setLayout(NewDialogLayout); NewDialogLayout.setHorizontalGroup( NewDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(NewDialogLayout.createSequentialGroup() .addGap(27, 27, 27) .addGroup(NewDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(NewDialogLayout.createSequentialGroup() .addGroup(NewDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(NewDialogLayout.createSequentialGroup() .addGroup(NewDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(infogame, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addGap(26, 26, 26) .addGroup(NewDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(Posotita2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(jLabel8)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 169, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(32, 32, 32)) .addGroup(NewDialogLayout.createSequentialGroup() .addComponent(price, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(151, 151, 151) .addComponent(ToolTip, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 191, Short.MAX_VALUE)))) ); NewDialogLayout.setVerticalGroup( NewDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(NewDialogLayout.createSequentialGroup() .addGap(17, 17, 17) .addGroup(NewDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(NewDialogLayout.createSequentialGroup() .addGroup(NewDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(NewDialogLayout.createSequentialGroup() .addGap(98, 98, 98) .addComponent(jLabel1)) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(NewDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(infogame, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Posotita2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jLabel8)) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(NewDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(price, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(ToolTip, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(42, Short.MAX_VALUE)) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); File.setMnemonic('F'); File.setText("File"); About.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK)); About.setText("About"); About.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AboutActionPerformed(evt); } }); File.add(About); Exit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK)); Exit.setText("Exit"); Exit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ExitActionPerformed(evt); } }); File.add(Exit); jMenuBar1.add(File); Sales.setText("Sales"); Sales.setToolTipText(""); New.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK)); New.setText("New"); New.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NewActionPerformed(evt); } }); Sales.add(New); Save.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK)); Save.setText("Save"); Save.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SaveActionPerformed(evt); } }); Sales.add(Save); Total.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.CTRL_MASK)); Total.setText("Total"); Sales.add(Total); jMenuBar1.add(Sales); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 489, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 349, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void ExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExitActionPerformed System.exit(0); }//GEN-LAST:event_ExitActionPerformed private void AboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AboutActionPerformed new About().setVisible(true); }//GEN-LAST:event_AboutActionPerformed private void NewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NewActionPerformed NewDialog.setVisible(true); NewDialog.setSize(500,500); }//GEN-LAST:event_NewActionPerformed String saveinfo="";Integer posotitaInt; private void SaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveActionPerformed if ( "".equals(infogame.getText()) ){ myerrormessage("Σημπλιρωσε πληροφοριες παιχνιδιου "); }else if ( "".equals(String.valueOf(Posotita2.getValue()) )){ myerrormessage("Σημπλιρωσε ποσοτητα παιχνιδιου "); } else if ( "".equals(price.getText())){ myerrormessage("Σημπλιρωσε τιμη παιχνιδιου "); } else if ( "".equals(typosgameselected)){ myerrormessage("Επελεξε τυπο παιχνιδου "); } else { //Ολα καλα String posotitaStr=String.valueOf(Posotita2.getValue()); posotitaInt=Integer.valueOf(posotitaStr); int timiInt=(Integer.parseInt(timigame)*posotitaInt); String timiStr =String.valueOf(timiInt); saveinfo="Περιγραφη παιχνιδιου: "+gameinfo+"\n"+"Ποσοτητα: "+posotitaStr + "\nΤιμη προιοντος: " + timigame + "\nΣυνολικη τιμη : " + timiStr + " \nΤυπος παιχνιδιου: "+typosgameselected+" \n"; try { FileWriter writer = new FileWriter("stoixia.txt",true); writer.append("\nΗμερομηνια ανανέωσεις: "+showodata()+ " "+showTime()+" \n"+saveinfo); writer.close(); JOptionPane.showMessageDialog(null, "Αποθικευση στοιχειων επιτυχεις","Succes", JOptionPane.INFORMATION_MESSAGE); } catch (IOException ex) { JOptionPane.showMessageDialog(null,"Σφάλμα","Error", JOptionPane.ERROR_MESSAGE); } } }//GEN-LAST:event_SaveActionPerformed private void infogameKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_infogameKeyPressed }//GEN-LAST:event_infogameKeyPressed private void priceKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_priceKeyPressed }//GEN-LAST:event_priceKeyPressed String typosgameselected=""; String typosGameTable[]={"Επιτραπέζιο","Ηλεκτρονικό","other"}; private void typosgameValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_typosgameValueChanged int idx=typosgame.getSelectedIndex(); typosgameselected=typosGameTable[idx]; }//GEN-LAST:event_typosgameValueChanged private void infogameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_infogameActionPerformed }//GEN-LAST:event_infogameActionPerformed String timigame; private void priceKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_priceKeyReleased timigame=price.getText(); }//GEN-LAST:event_priceKeyReleased String gameinfo=""; private void infogameKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_infogameKeyReleased gameinfo = infogame.getText(); }//GEN-LAST:event_infogameKeyReleased public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MainFrame().setVisible(true); } }); } void myerrormessage(String message){ JOptionPane.showMessageDialog(null, message, "προσοχη λάθος", JOptionPane.ERROR_MESSAGE); } void myinfomessage(String message){ JOptionPane.showMessageDialog(null, message,"Ενημέροση", JOptionPane.INFORMATION_MESSAGE); } String showodata(){ Date d = new Date(); SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd"); return s.format(d) ; } String showTime(){ Date d = new Date(); SimpleDateFormat s = new SimpleDateFormat("hh:mm:ss a"); return s.format(d) ; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JMenuItem About; private javax.swing.JMenuItem Exit; private javax.swing.JMenu File; private javax.swing.JMenuItem New; private javax.swing.JDialog NewDialog; private javax.swing.JSpinner Posotita2; private javax.swing.JMenu Sales; private javax.swing.JMenuItem Save; private javax.swing.JLabel ToolTip; private javax.swing.JMenuItem Total; private javax.swing.JTextField infogame; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel8; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField price; private javax.swing.JList<String> typosgame; // End of variables declaration//GEN-END:variables }
NikolaosProgios/Java-NetBeans-HumanInteractionMachine
ToyStore/src/MainFrame.java
4,291
//Ολα καλα
line_comment
el
import java.io.FileWriter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.JOptionPane; public class MainFrame extends javax.swing.JFrame { public MainFrame() { initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { NewDialog = new javax.swing.JDialog(); infogame = new javax.swing.JTextField(); price = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); typosgame = new javax.swing.JList<>(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); ToolTip = new javax.swing.JLabel(); Posotita2 = new javax.swing.JSpinner(); jMenuBar1 = new javax.swing.JMenuBar(); File = new javax.swing.JMenu(); About = new javax.swing.JMenuItem(); Exit = new javax.swing.JMenuItem(); Sales = new javax.swing.JMenu(); New = new javax.swing.JMenuItem(); Save = new javax.swing.JMenuItem(); Total = new javax.swing.JMenuItem(); infogame.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { infogameActionPerformed(evt); } }); infogame.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { infogameKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { infogameKeyReleased(evt); } }); price.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { priceKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { priceKeyReleased(evt); } }); typosgame.setBorder(javax.swing.BorderFactory.createTitledBorder("Είδος Παιχνιδιού")); typosgame.setModel(new javax.swing.AbstractListModel<String>() { String[] strings = { "Επιτραπέζιο", "Ηλεκτρονικό", "other" }; public int getSize() { return strings.length; } public String getElementAt(int i) { return strings[i]; } }); typosgame.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); typosgame.setToolTipText(""); typosgame.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { typosgameValueChanged(evt); } }); jScrollPane1.setViewportView(typosgame); jLabel1.setText("Περιγραφη παιχνιδιου"); jLabel2.setText("Ποσοτητα"); jLabel8.setText("Τιμη"); Posotita2.setModel(new javax.swing.SpinnerNumberModel(1, 1, null, 1)); Posotita2.setToolTipText(""); javax.swing.GroupLayout NewDialogLayout = new javax.swing.GroupLayout(NewDialog.getContentPane()); NewDialog.getContentPane().setLayout(NewDialogLayout); NewDialogLayout.setHorizontalGroup( NewDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(NewDialogLayout.createSequentialGroup() .addGap(27, 27, 27) .addGroup(NewDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(NewDialogLayout.createSequentialGroup() .addGroup(NewDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(NewDialogLayout.createSequentialGroup() .addGroup(NewDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(infogame, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addGap(26, 26, 26) .addGroup(NewDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(Posotita2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(jLabel8)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 169, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(32, 32, 32)) .addGroup(NewDialogLayout.createSequentialGroup() .addComponent(price, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(151, 151, 151) .addComponent(ToolTip, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 191, Short.MAX_VALUE)))) ); NewDialogLayout.setVerticalGroup( NewDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(NewDialogLayout.createSequentialGroup() .addGap(17, 17, 17) .addGroup(NewDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(NewDialogLayout.createSequentialGroup() .addGroup(NewDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(NewDialogLayout.createSequentialGroup() .addGap(98, 98, 98) .addComponent(jLabel1)) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(NewDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(infogame, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Posotita2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jLabel8)) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(NewDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(price, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(ToolTip, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(42, Short.MAX_VALUE)) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); File.setMnemonic('F'); File.setText("File"); About.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK)); About.setText("About"); About.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AboutActionPerformed(evt); } }); File.add(About); Exit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK)); Exit.setText("Exit"); Exit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ExitActionPerformed(evt); } }); File.add(Exit); jMenuBar1.add(File); Sales.setText("Sales"); Sales.setToolTipText(""); New.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK)); New.setText("New"); New.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NewActionPerformed(evt); } }); Sales.add(New); Save.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK)); Save.setText("Save"); Save.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SaveActionPerformed(evt); } }); Sales.add(Save); Total.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.CTRL_MASK)); Total.setText("Total"); Sales.add(Total); jMenuBar1.add(Sales); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 489, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 349, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void ExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExitActionPerformed System.exit(0); }//GEN-LAST:event_ExitActionPerformed private void AboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AboutActionPerformed new About().setVisible(true); }//GEN-LAST:event_AboutActionPerformed private void NewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NewActionPerformed NewDialog.setVisible(true); NewDialog.setSize(500,500); }//GEN-LAST:event_NewActionPerformed String saveinfo="";Integer posotitaInt; private void SaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveActionPerformed if ( "".equals(infogame.getText()) ){ myerrormessage("Σημπλιρωσε πληροφοριες παιχνιδιου "); }else if ( "".equals(String.valueOf(Posotita2.getValue()) )){ myerrormessage("Σημπλιρωσε ποσοτητα παιχνιδιου "); } else if ( "".equals(price.getText())){ myerrormessage("Σημπλιρωσε τιμη παιχνιδιου "); } else if ( "".equals(typosgameselected)){ myerrormessage("Επελεξε τυπο παιχνιδου "); } else { //Ολα καλα<SUF> String posotitaStr=String.valueOf(Posotita2.getValue()); posotitaInt=Integer.valueOf(posotitaStr); int timiInt=(Integer.parseInt(timigame)*posotitaInt); String timiStr =String.valueOf(timiInt); saveinfo="Περιγραφη παιχνιδιου: "+gameinfo+"\n"+"Ποσοτητα: "+posotitaStr + "\nΤιμη προιοντος: " + timigame + "\nΣυνολικη τιμη : " + timiStr + " \nΤυπος παιχνιδιου: "+typosgameselected+" \n"; try { FileWriter writer = new FileWriter("stoixia.txt",true); writer.append("\nΗμερομηνια ανανέωσεις: "+showodata()+ " "+showTime()+" \n"+saveinfo); writer.close(); JOptionPane.showMessageDialog(null, "Αποθικευση στοιχειων επιτυχεις","Succes", JOptionPane.INFORMATION_MESSAGE); } catch (IOException ex) { JOptionPane.showMessageDialog(null,"Σφάλμα","Error", JOptionPane.ERROR_MESSAGE); } } }//GEN-LAST:event_SaveActionPerformed private void infogameKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_infogameKeyPressed }//GEN-LAST:event_infogameKeyPressed private void priceKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_priceKeyPressed }//GEN-LAST:event_priceKeyPressed String typosgameselected=""; String typosGameTable[]={"Επιτραπέζιο","Ηλεκτρονικό","other"}; private void typosgameValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_typosgameValueChanged int idx=typosgame.getSelectedIndex(); typosgameselected=typosGameTable[idx]; }//GEN-LAST:event_typosgameValueChanged private void infogameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_infogameActionPerformed }//GEN-LAST:event_infogameActionPerformed String timigame; private void priceKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_priceKeyReleased timigame=price.getText(); }//GEN-LAST:event_priceKeyReleased String gameinfo=""; private void infogameKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_infogameKeyReleased gameinfo = infogame.getText(); }//GEN-LAST:event_infogameKeyReleased public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MainFrame().setVisible(true); } }); } void myerrormessage(String message){ JOptionPane.showMessageDialog(null, message, "προσοχη λάθος", JOptionPane.ERROR_MESSAGE); } void myinfomessage(String message){ JOptionPane.showMessageDialog(null, message,"Ενημέροση", JOptionPane.INFORMATION_MESSAGE); } String showodata(){ Date d = new Date(); SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd"); return s.format(d) ; } String showTime(){ Date d = new Date(); SimpleDateFormat s = new SimpleDateFormat("hh:mm:ss a"); return s.format(d) ; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JMenuItem About; private javax.swing.JMenuItem Exit; private javax.swing.JMenu File; private javax.swing.JMenuItem New; private javax.swing.JDialog NewDialog; private javax.swing.JSpinner Posotita2; private javax.swing.JMenu Sales; private javax.swing.JMenuItem Save; private javax.swing.JLabel ToolTip; private javax.swing.JMenuItem Total; private javax.swing.JTextField infogame; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel8; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField price; private javax.swing.JList<String> typosgame; // End of variables declaration//GEN-END:variables }
2904_0
package projects.project10; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Scanner; /** * Έστω ένα θέατρο που έχει θέσεις όπου η κάθε θέση περιγράφεται με ένα χαρακτήρα * που είναι η στήλη και ένα αριθμό που είναι η σειρά. Για παράδειγμα η θέση C2 * βρίσκεται στην 2η σειρά και 3η στήλη. * Αναπτύξτε ένα πρόγραμμα διαχείρισης θεάτρου με 30 σειρές και 12 στήλες. Πιο * συγκεκριμένα γράψτε μία μέθοδο void book(char column, int row) που να κάνει book * μία θέση αν δεν είναι ήδη booked και μία μέθοδο void cancel(char column, int row) * που να ακυρώνει την κράτηση μία θέσης αν είναι ήδη booked. * * (Για να πάρουμε τη σειρά αφαιρούμε 65 από το ASCII value.) */ public class Project10 { static Scanner in = new Scanner(System.in); public static void main(String[] args) { boolean[][] chartBooked= new boolean[30][12]; int option = -1; for (boolean[] row: chartBooked){ Arrays.fill(row, false); } do{ showMenu(); try { option = in.nextInt(); System.out.println(); }catch (InputMismatchException e){ System.out.println("The choice should be a number (between 1-3)"); in.nextLine(); } switch (option){ case 1: System.out.println("Book a seat!"); book(chartBooked); System.out.println(); break; case 2: System.out.println("Cancel your reservation"); cancel(chartBooked); System.out.println(); break; case 3: System.out.println("EXIT"); break; case 4: System.out.println("Please choose between 1-3"); break; default: System.out.println("The choice must be between 1-3"); break; } }while (option != 3); System.out.println("Thank You!"); } public static void showMenu(){ System.out.println("Choose an option"); System.out.println("1. Book a seat"); System.out.println("2. Canceled a booked seat"); System.out.println("3. EXIT"); System.out.print("Option: "); } public static int[] handleUsersChoice(){ int userRow= -1; int userColumn = -1; int[] position = {-1, -1}; char seatChar; try{ System.out.println("Choose a row from 1-30"); userRow = in.nextInt(); if(userRow <= 0 || userRow>30){ System.out.println("Invalid Choice"); } if(userRow > 0 && userRow <=30){ position[0] = userRow-1; } System.out.println("Choose a seat from A - L"); seatChar = in.next().charAt(0); seatChar = Character.toUpperCase(seatChar); userColumn = seatChar - 65; if(userColumn <0 || userColumn > 11){ System.out.println("Invalid choice: " + seatChar); } if(userColumn >= 0 && userColumn <12){ position[1] = userColumn; } }catch (InputMismatchException e){ System.out.println("Invalid Choice"); in.nextLine(); } return position; } public static void book(boolean[][] chartBooked){ System.out.println("Choose a row and a seat"); int[] position = handleUsersChoice(); if(position[0] != -1 && position[1] != -1){ if(!chartBooked[position[0]][position[1]]){ chartBooked[position[0]][position[1]] = true; System.out.printf("Seat booked! You chose %c%s \n", (char)(position[1]+65),position[0]+1); }else{ System.out.println("Seat already taken!"); } } } public static void cancel(boolean[][] chartBooked){ System.out.println("Choose the row and column or the seat to delete!"); int[] position = handleUsersChoice(); if(position[0] != -1 && position[1] != -1){ if(chartBooked[position[0]][position[1]]){ chartBooked[position[0]][position[1]] = false; System.out.printf("Seat %c%s canceled \n", (char)(position[1]+65),position[0]+1); }else{ System.out.println("Seat is not booked please check again!"); } } } }
NikolettaIoan/java-advanced-projects
src/projects/project10/Project10.java
1,391
/** * Έστω ένα θέατρο που έχει θέσεις όπου η κάθε θέση περιγράφεται με ένα χαρακτήρα * που είναι η στήλη και ένα αριθμό που είναι η σειρά. Για παράδειγμα η θέση C2 * βρίσκεται στην 2η σειρά και 3η στήλη. * Αναπτύξτε ένα πρόγραμμα διαχείρισης θεάτρου με 30 σειρές και 12 στήλες. Πιο * συγκεκριμένα γράψτε μία μέθοδο void book(char column, int row) που να κάνει book * μία θέση αν δεν είναι ήδη booked και μία μέθοδο void cancel(char column, int row) * που να ακυρώνει την κράτηση μία θέσης αν είναι ήδη booked. * * (Για να πάρουμε τη σειρά αφαιρούμε 65 από το ASCII value.) */
block_comment
el
package projects.project10; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Scanner; /** * Έστω ένα θέατρο<SUF>*/ public class Project10 { static Scanner in = new Scanner(System.in); public static void main(String[] args) { boolean[][] chartBooked= new boolean[30][12]; int option = -1; for (boolean[] row: chartBooked){ Arrays.fill(row, false); } do{ showMenu(); try { option = in.nextInt(); System.out.println(); }catch (InputMismatchException e){ System.out.println("The choice should be a number (between 1-3)"); in.nextLine(); } switch (option){ case 1: System.out.println("Book a seat!"); book(chartBooked); System.out.println(); break; case 2: System.out.println("Cancel your reservation"); cancel(chartBooked); System.out.println(); break; case 3: System.out.println("EXIT"); break; case 4: System.out.println("Please choose between 1-3"); break; default: System.out.println("The choice must be between 1-3"); break; } }while (option != 3); System.out.println("Thank You!"); } public static void showMenu(){ System.out.println("Choose an option"); System.out.println("1. Book a seat"); System.out.println("2. Canceled a booked seat"); System.out.println("3. EXIT"); System.out.print("Option: "); } public static int[] handleUsersChoice(){ int userRow= -1; int userColumn = -1; int[] position = {-1, -1}; char seatChar; try{ System.out.println("Choose a row from 1-30"); userRow = in.nextInt(); if(userRow <= 0 || userRow>30){ System.out.println("Invalid Choice"); } if(userRow > 0 && userRow <=30){ position[0] = userRow-1; } System.out.println("Choose a seat from A - L"); seatChar = in.next().charAt(0); seatChar = Character.toUpperCase(seatChar); userColumn = seatChar - 65; if(userColumn <0 || userColumn > 11){ System.out.println("Invalid choice: " + seatChar); } if(userColumn >= 0 && userColumn <12){ position[1] = userColumn; } }catch (InputMismatchException e){ System.out.println("Invalid Choice"); in.nextLine(); } return position; } public static void book(boolean[][] chartBooked){ System.out.println("Choose a row and a seat"); int[] position = handleUsersChoice(); if(position[0] != -1 && position[1] != -1){ if(!chartBooked[position[0]][position[1]]){ chartBooked[position[0]][position[1]] = true; System.out.printf("Seat booked! You chose %c%s \n", (char)(position[1]+65),position[0]+1); }else{ System.out.println("Seat already taken!"); } } } public static void cancel(boolean[][] chartBooked){ System.out.println("Choose the row and column or the seat to delete!"); int[] position = handleUsersChoice(); if(position[0] != -1 && position[1] != -1){ if(chartBooked[position[0]][position[1]]){ chartBooked[position[0]][position[1]] = false; System.out.printf("Seat %c%s canceled \n", (char)(position[1]+65),position[0]+1); }else{ System.out.println("Seat is not booked please check again!"); } } } }
16419_0
package gr.hua.dit.it22023_it22026.utils; import gr.hua.dit.it22023_it22026.models.*; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.service.ServiceRegistry; import java.util.Properties; /** * Πρωτιμηστε να χρησιμοποιειτε repositories, * αμα αυτο δεν ειναι εφηκτο τοτε μπορει να γινει η χρηση αυτης της class*/ @Deprecated public class HibernateUtil { private static SessionFactory sessionFactory; private static final String DRIVER = "com.mysql.cj.jdbc.Driver"; private static final String URL = "jdbc:mysql://193.92.246.105:3306/SpringBoot"; private static final String USER = "root"; private static final String PASSWORD = "nikos2002"; private static final String DIALECT = "org.hibernate.dialect.MySQL8Dialect"; public static SessionFactory getSessionFactory() { if (sessionFactory == null) { Configuration configuration = new Configuration(); Properties settings = new Properties(); settings.put(Environment.DRIVER , DRIVER); settings.put(Environment.URL , URL); settings.put(Environment.USER , USER); settings.put(Environment.PASS , PASSWORD); settings.put(Environment.DIALECT , DIALECT); settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread"); settings.put(Environment.SHOW_SQL , "true"); configuration.setProperties(settings); configuration.addAnnotatedClass(Car.class); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); return configuration.buildSessionFactory(serviceRegistry); } return sessionFactory; } }
NikosGour/DistributedSystems
src/main/java/gr/hua/dit/it22023_it22026/utils/HibernateUtil.java
517
/** * Πρωτιμηστε να χρησιμοποιειτε repositories, * αμα αυτο δεν ειναι εφηκτο τοτε μπορει να γινει η χρηση αυτης της class*/
block_comment
el
package gr.hua.dit.it22023_it22026.utils; import gr.hua.dit.it22023_it22026.models.*; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.service.ServiceRegistry; import java.util.Properties; /** * Πρωτιμηστε να χρησιμοποιειτε<SUF>*/ @Deprecated public class HibernateUtil { private static SessionFactory sessionFactory; private static final String DRIVER = "com.mysql.cj.jdbc.Driver"; private static final String URL = "jdbc:mysql://193.92.246.105:3306/SpringBoot"; private static final String USER = "root"; private static final String PASSWORD = "nikos2002"; private static final String DIALECT = "org.hibernate.dialect.MySQL8Dialect"; public static SessionFactory getSessionFactory() { if (sessionFactory == null) { Configuration configuration = new Configuration(); Properties settings = new Properties(); settings.put(Environment.DRIVER , DRIVER); settings.put(Environment.URL , URL); settings.put(Environment.USER , USER); settings.put(Environment.PASS , PASSWORD); settings.put(Environment.DIALECT , DIALECT); settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread"); settings.put(Environment.SHOW_SQL , "true"); configuration.setProperties(settings); configuration.addAnnotatedClass(Car.class); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); return configuration.buildSessionFactory(serviceRegistry); } return sessionFactory; } }
12972_0
package com.example; import java.io.IOException; import java.util.List; import java.util.Scanner; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; public class Main2 { private static volatile boolean isRunning = true; private static volatile boolean listState = true; public static void main(String[] args) throws IOException, InterruptedException { // Δημιουργία και χρήση της κλάσης AppWithContainer try (Scanner scanner = new Scanner(System.in)) { System.out.println("Enter the Docker image name:"); String imageName = scanner.nextLine(); System.out.println("Enter the Docker container ID:"); String containerId = scanner.nextLine(); AppWithContainer app = new AppWithContainer("tcp://localhost:2375", imageName, containerId); app.manageContainer(); } } }
NikosLaspias/DockerEx
example/Main2.java
260
// Δημιουργία και χρήση της κλάσης AppWithContainer
line_comment
el
package com.example; import java.io.IOException; import java.util.List; import java.util.Scanner; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; public class Main2 { private static volatile boolean isRunning = true; private static volatile boolean listState = true; public static void main(String[] args) throws IOException, InterruptedException { // Δημιουργία και<SUF> try (Scanner scanner = new Scanner(System.in)) { System.out.println("Enter the Docker image name:"); String imageName = scanner.nextLine(); System.out.println("Enter the Docker container ID:"); String containerId = scanner.nextLine(); AppWithContainer app = new AppWithContainer("tcp://localhost:2375", imageName, containerId); app.manageContainer(); } } }
2608_18
package GUI; import accommodations.Accommodations; import accommodations.HotelRooms; import accommodations.PrivateAccommodation; import accommodations.reservervations.Date; import photo_characteristicsDisplay.Display; import users.Admins; import users.Providers; import users.Users; import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.event.*; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.HashMap; public class Admin extends JDialog { private final Users base; private final int position; private JPanel panel; private JTable allUsersTable; private JLabel helloMsg; private JTable allReservationsTable; private JTextField toUserMsgField; private JTextArea messageArea; private JButton toUserMsgBtn; private JLabel msgFail; private JLabel msgSuccess; private JLabel helloMsgDesc; private JTextField fieldUserToActivate; private JButton activateBtn; private JLabel msgActUsrNotExist; private JLabel msgActUsrExist; private JTable tableInactiveProviders; private JButton LogOut1; private JTabbedPane tabbedPane; private JButton allUsersButton; private JButton activateButton; private JButton sendMessageButton; private JButton reservationsButton; private JTabbedPane tabbedPane1; private JScrollPane HotelRoomsPane; private JScrollPane PrivateAccommodationsPane; private JTable HotelRoomsTable; private JTable PrivateAccomodationsTable; private JButton accommodationsButton; public Admin(Users base, int position, Login login) { setTitle("[Admin] " + base.getAllAdmins().get(position).getUsername()); setContentPane(panel); setModal(true); tabbedPane.setEnabled(true); this.base = base; this.position = position; //ActionListeners για τα κουμπιά που βρίσκονται στο welcomeTab sendMessageButton.addActionListener(e -> tabbedPane.setSelectedIndex(4)); activateButton.addActionListener(e -> tabbedPane.setSelectedIndex(5)); allUsersButton.addActionListener(e -> tabbedPane.setSelectedIndex(1)); reservationsButton.addActionListener(e -> tabbedPane.setSelectedIndex(2)); accommodationsButton.addActionListener(e -> tabbedPane.setSelectedIndex(3)); //Καλούνται οι μέθοδοι που δημιουργούν τους πίνακες: (Χρηστων/καταλυμάτων/κρατήσεων/ΑνενεργώνΠαρόχων) createAllUsersTable(); createAllReservationsTable(); createTableInactiveProviders(); createHotelRoomsTable(); createPrivateAccommodationTable(); privateAccommodationTableMouseListener(base.getAllAdmins().get(position)); roomTableMouseListener(base.getAllAdmins().get(position)); // call onCancel() when cross is clicked setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); // call onCancel() on ESCAPE panel.registerKeyboardAction(e -> System.exit(0), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); // send msg to user on click toUserMsgBtn.addActionListener(e -> sendMessage()); activateBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { activateUser(base.getAllAdmins().get(position)); } }); logOut(login); } /** * Η μέθοδος αυτή δημιουργεί τον πίνακα στον οποίο * θα προσθεθούν όλα τα δωμάτια ξενοδοχείων */ public void createHotelRoomsTable() { Object[][] data = {}; HotelRoomsTable.setModel(new DefaultTableModel( data, new Object[]{"Hotel name", "Location", "Room's number", "Floor", "Square metres", "Price", "ID", "Capacity", "Characteristics"} )); } /** * Η μέθοδος αυτή εισάγει όλα τα δωμάτια που υπάρχουν στην εφαρμογή στον * πίνκακα {@link #HotelRoomsTable} * * @param rooms Λίστα τύπου {@link HotelRooms} με όλα τα δωμάτια που υπάρχουν στην εφαρμογή */ public void AddHotelRoomsToTable(ArrayList<HotelRooms> rooms) { DefaultTableModel model = (DefaultTableModel) HotelRoomsTable.getModel(); for (HotelRooms room : rooms) { model.addRow(new Object[]{ "\uD83D\uDCBC " + room.getHotelName(), "\uD83D\uDCCD " + room.getAddress(), room.getRoomNumber(), room.getFloor(), room.getSquareMetres() + "m²", room.getPrice() + "€", "" + room.getId(), room.getCapacity(), "Click Here!" }); } } /** * Η μέθοδος αυτή δημιουργεί τον πίνακα στον οποίο θα * προσθεθούν όλα τα ιδιωτικά καταλύματα */ public void createPrivateAccommodationTable() { Object[][] data = {}; PrivateAccomodationsTable.setModel(new DefaultTableModel( data, new Object[]{"Company's name", "Type", "Location", "Square metres", "price", "Capacity", "Characteristics", "ID"} )); } /** * Η μέθοδος αυτή εισάγει στον πίνακα {@link #PrivateAccomodationsTable} * όλα τα ιδιωτικά καταλύματα που υπάρχουν στην εφαρμογή * * @param accommodations Λίστα τύπου {@link PrivateAccommodation} με όλα * τα ιδιωτικά καταλύματα */ public void AddPrivateAccommodationsToTable(ArrayList<PrivateAccommodation> accommodations) { DefaultTableModel model = (DefaultTableModel) PrivateAccomodationsTable.getModel(); for (PrivateAccommodation accommodation : accommodations) { model.addRow(new Object[]{ "\uD83D\uDCBC " + accommodation.getCompanyName(), "Type: " + accommodation.getType(), "\uD83D\uDCCD " + accommodation.getAddress(), accommodation.getSquareMetres() + "m²", accommodation.getPrice() + "€", accommodation.getCapacity(), "Click here!", "" + accommodation.getId() }); } } /** * {@link ActionListener} για το κουμπί LogOut που αποσυνδέει τον διαχειριστή απο την εφαρμογή * * @param login Το frame Login που συνδέθηκε ο διαχειριστής στην εφαρμογή (Κλείνει κατα την αποσύνδεση και ανοίγει νέο) */ public void logOut(Login login) { LogOut1.addActionListener(e -> { this.dispose(); login.dispose(); }); } /** * Η μέθοδος αυτή δημιουργεί τον πίνακα στον οποίο * αργότερα θα εισαχθούν όλοι οι χρήστες της εφαρμογής */ private void createAllUsersTable() { String[][] data = {}; allUsersTable.setModel(new DefaultTableModel( data, new String[]{"", "", "", ""} )); } /** * Η μέθοδος αυτή δημιουργεί τον πίνακα στον οποίο αργότερα * θα εισαχθούν όλες οι ενεργές κρατήσεις για τα καταλύματα * της εφαρμογής */ private void createAllReservationsTable() { String[][] data = {}; allReservationsTable.setModel(new DefaultTableModel( data, new String[]{"", "", "", "", "", "", ""} )); } /** * Η μέθοδος αυτή εισάγει όλους τους χρήστες που υπάρχουν στην εφαρμογή στον πίνακα {@link #allUsersTable} * * @param users Λίστα με όλους τους χρήστες της πλατφόρμας */ public void addUsersToTable(ArrayList<Users> users) { DefaultTableModel model = (DefaultTableModel) allUsersTable.getModel(); for (Users user : users) { model.addRow(new Object[]{ user.getRole(), user.getUsername(), user.getGender(), user.getPassword(), }); } } /** * Στη μέθοδο αυτή εισάγονται στον πίνακα {@link #allReservationsTable} όλες οι ενεργές κρατήσεις δωματίων * και ιδιωτικών καταλυμάτων * * @param allReservationsPrivate HashMap με τα ιδιωτικά καταλύματα και τις ημερομηνίες κράτησης τους * @param allReservationsRooms HashMap με τα δωμάτια ξενοδοχείων και τις ημερομηνίες κράτησης τους */ public void addReservationsToTable( HashMap<PrivateAccommodation, ArrayList<Date>> allReservationsPrivate, HashMap<HotelRooms, ArrayList<Date>> allReservationsRooms ) { DefaultTableModel model = (DefaultTableModel) allReservationsTable.getModel(); allReservationsPrivate.forEach((key, value) -> { for (Date date : value) { model.addRow(new Object[]{ "ID " + key.getId(), key.getType(), key.getPrice() + "€", key.getSquareMetres() + "m²", "\uD83D\uDCBC " + key.getCompanyName(), "\uD83D\uDCCD " + key.getAddress(), "\uD83D\uDCC6 " + date.toString() }); } }); allReservationsRooms.forEach((key, value) -> { for (Date date : value) { model.addRow(new Object[]{ "ID " + key.getId(), "Floor " + key.getFloor(), key.getPrice() + "€", key.getSquareMetres() + "m²", "\uD83D\uDCBC " + key.getHotelName(), "\uD83D\uDCCD " + key.getAddress(), "\uD83D\uDCC6 " + date.toString() }); } }); } /** * Η μέθοδος αυτή δημιουργεί τον πίνακα με τους ανενεργούς λογαριασμούς παρόχων */ private void createTableInactiveProviders() { String[][] data = {}; tableInactiveProviders.setModel(new DefaultTableModel( data, new String[]{"Username", "Gender", "Password"} )); addInactiveProvidersToTable(); } /** * Η μέθοδος αυτή προσθέτει όλους τους λογαριασμούς παρόχων που δεν έχουν εγκριθεί ακόμα από τον διαχειριστή * στον πίνακα {@link #tableInactiveProviders} */ public void addInactiveProvidersToTable() { DefaultTableModel model = (DefaultTableModel) tableInactiveProviders.getModel(); while (model.getRowCount() > 0) { model.removeRow(0); } for (Providers user : base.getAllProviders()) { if (user.accountStatus()) continue; model.addRow(new Object[]{ user.getUsername(), user.getGender(), user.getPassword(), }); } } /** * Η μέθοδος αυτή συμπληρώνει το μήνυμα που καλωσορίζει τον διαχειριστή στην πλατφόρμα * * @param name Username διαχειριστή που είναι συνδεδεμένος στην εφαρμογή */ public void setHelloMsgTo(String name) { int allUsers = base.getAllAdmins().size() + base.getAllProviders().size() + base.getAllCustomers().size(); int allAcc = base.getAccommodations().getRooms().size() + base.getAccommodations().getAirbnb().size(); this.helloMsg.setText("Hello " + name + ", how are you doing today."); this.helloMsgDesc.setText("It looks like " + allUsers + " people are on our platform and " + allAcc + " accommodations and hotel rooms!"); } public String getToUserMsgField() { return toUserMsgField.getText(); } public String getMessageArea() { return messageArea.getText(); } /** * Η μέθοδος αυτή επιτρέπει στον διαχειριστή να στείλει μήνυμα σε κάποιον χρήστη */ public void sendMessage() { boolean isSent = base.getAllAdmins().get(position).SendMessage(getToUserMsgField(), getMessageArea()); msgFail.setVisible(!isSent); msgSuccess.setVisible(isSent); } /** * Η μέθοδος αυτή επιτρέπει στον διαχειριστή να ενεργοποιήσει τον λογαριασμό ενός παρόχου που * μόλις έχει κάνει εγγραφή στην εφαρμογή * * @param admin Ο διαχειριστής που είναι συνδεδεμένος στην εφαρμογή */ private void activateUser(Admins admin) { boolean userFound = false; for (Providers provider : base.getAllProviders()) { if (fieldUserToActivate.getText().equalsIgnoreCase(provider.getUsername()) && !provider.accountStatus()) { provider.activate(); userFound = true; try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("providers.bin"))) { out.writeObject(admin.getAllProviders()); } catch (IOException e) { e.printStackTrace(); } break; } } msgActUsrNotExist.setVisible(!userFound); msgActUsrExist.setVisible(userFound); addInactiveProvidersToTable(); } /** * Η μέθοδος αυτή υλοποιεί {@link MouseListener} για τον πίνακα που αποθηκεύει τα ιδιωτικά καταλύματα. * Στο κλικ του ποντικού στην στήλη που αποθηκεύει * τα ειδικά χαρακτηριστικά του ιδιωτικού καταλύματος, εμφανίζει με την βοήθεια της * κλάσης {@link Display}την Λίστα με τα χαρακτηριστικά * του καταλύματος {@link Accommodations#getCharacteristics()} και την φωτογραφία * του καταλύματος με όνομα {@link Accommodations#getImageName()} * * @param admin Ο διαχειριστής που είναι συνδεδεμένος στην εφαρμογή */ public void privateAccommodationTableMouseListener(Admins admin) { PrivateAccomodationsTable.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mouseClicked(java.awt.event.MouseEvent evt) { int row = PrivateAccomodationsTable.rowAtPoint(evt.getPoint()); int col = PrivateAccomodationsTable.columnAtPoint(evt.getPoint()); if (row >= 0 && col == 6) { int rowSelected = PrivateAccomodationsTable.getSelectedRow(); int accommodationFound = admin.getAccommodations().FindAccommodation(Integer.parseInt(PrivateAccomodationsTable.getValueAt(rowSelected, 7).toString())); Display temp = new Display(admin.getAccommodations().getAirbnb().get(accommodationFound).getCharacteristics(), admin.getAccommodations().getAirbnb().get(accommodationFound).getImageName()); temp.pack(); temp.setVisible(true); } } }); } /** * Η μέθοδος αυτή υλοποιεί {@link MouseListener} για τους πίνακες που αφορούν τα ξενοδοχειακά δωμάτια. * Στο κλικ του ποντικού στην στήλη που αποθηκεύει * τα ειδικά χαρακτηριστικά του δωματίου, εμφανίζει με την βοήθεια της * κλάσης {@link Display}την Λίστα με τα χαρακτηριστικά * του καταλύματος {@link Accommodations#getCharacteristics()} και την φωτογραφία * του καταλύματος με όνομα {@link Accommodations#getImageName()} * * @param admin Ο διαχειριστής που είναι συνδεδεμένος στην εφαρμογή */ public void roomTableMouseListener(Admins admin) { HotelRoomsTable.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mouseClicked(java.awt.event.MouseEvent evt) { int row = HotelRoomsTable.rowAtPoint(evt.getPoint()); int col = HotelRoomsTable.columnAtPoint(evt.getPoint()); if (row >= 0 && col == 8) { int rowSelected = HotelRoomsTable.getSelectedRow(); int roomFound = admin.getAccommodations().FindRoom(Integer.parseInt(HotelRoomsTable.getValueAt(rowSelected, 6).toString())); Display temp = new Display(admin.getAccommodations().getRooms().get(roomFound).getCharacteristics(), admin.getAccommodations().getRooms().get(roomFound).getImageName()); temp.pack(); temp.setVisible(true); } } }); } }
NikosVogiatzis/UniProjects
java mybooking/mybooking-main/src/GUI/Admin.java
5,393
/** * Η μέθοδος αυτή επιτρέπει στον διαχειριστή να ενεργοποιήσει τον λογαριασμό ενός παρόχου που * μόλις έχει κάνει εγγραφή στην εφαρμογή * * @param admin Ο διαχειριστής που είναι συνδεδεμένος στην εφαρμογή */
block_comment
el
package GUI; import accommodations.Accommodations; import accommodations.HotelRooms; import accommodations.PrivateAccommodation; import accommodations.reservervations.Date; import photo_characteristicsDisplay.Display; import users.Admins; import users.Providers; import users.Users; import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.event.*; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.HashMap; public class Admin extends JDialog { private final Users base; private final int position; private JPanel panel; private JTable allUsersTable; private JLabel helloMsg; private JTable allReservationsTable; private JTextField toUserMsgField; private JTextArea messageArea; private JButton toUserMsgBtn; private JLabel msgFail; private JLabel msgSuccess; private JLabel helloMsgDesc; private JTextField fieldUserToActivate; private JButton activateBtn; private JLabel msgActUsrNotExist; private JLabel msgActUsrExist; private JTable tableInactiveProviders; private JButton LogOut1; private JTabbedPane tabbedPane; private JButton allUsersButton; private JButton activateButton; private JButton sendMessageButton; private JButton reservationsButton; private JTabbedPane tabbedPane1; private JScrollPane HotelRoomsPane; private JScrollPane PrivateAccommodationsPane; private JTable HotelRoomsTable; private JTable PrivateAccomodationsTable; private JButton accommodationsButton; public Admin(Users base, int position, Login login) { setTitle("[Admin] " + base.getAllAdmins().get(position).getUsername()); setContentPane(panel); setModal(true); tabbedPane.setEnabled(true); this.base = base; this.position = position; //ActionListeners για τα κουμπιά που βρίσκονται στο welcomeTab sendMessageButton.addActionListener(e -> tabbedPane.setSelectedIndex(4)); activateButton.addActionListener(e -> tabbedPane.setSelectedIndex(5)); allUsersButton.addActionListener(e -> tabbedPane.setSelectedIndex(1)); reservationsButton.addActionListener(e -> tabbedPane.setSelectedIndex(2)); accommodationsButton.addActionListener(e -> tabbedPane.setSelectedIndex(3)); //Καλούνται οι μέθοδοι που δημιουργούν τους πίνακες: (Χρηστων/καταλυμάτων/κρατήσεων/ΑνενεργώνΠαρόχων) createAllUsersTable(); createAllReservationsTable(); createTableInactiveProviders(); createHotelRoomsTable(); createPrivateAccommodationTable(); privateAccommodationTableMouseListener(base.getAllAdmins().get(position)); roomTableMouseListener(base.getAllAdmins().get(position)); // call onCancel() when cross is clicked setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); // call onCancel() on ESCAPE panel.registerKeyboardAction(e -> System.exit(0), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); // send msg to user on click toUserMsgBtn.addActionListener(e -> sendMessage()); activateBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { activateUser(base.getAllAdmins().get(position)); } }); logOut(login); } /** * Η μέθοδος αυτή δημιουργεί τον πίνακα στον οποίο * θα προσθεθούν όλα τα δωμάτια ξενοδοχείων */ public void createHotelRoomsTable() { Object[][] data = {}; HotelRoomsTable.setModel(new DefaultTableModel( data, new Object[]{"Hotel name", "Location", "Room's number", "Floor", "Square metres", "Price", "ID", "Capacity", "Characteristics"} )); } /** * Η μέθοδος αυτή εισάγει όλα τα δωμάτια που υπάρχουν στην εφαρμογή στον * πίνκακα {@link #HotelRoomsTable} * * @param rooms Λίστα τύπου {@link HotelRooms} με όλα τα δωμάτια που υπάρχουν στην εφαρμογή */ public void AddHotelRoomsToTable(ArrayList<HotelRooms> rooms) { DefaultTableModel model = (DefaultTableModel) HotelRoomsTable.getModel(); for (HotelRooms room : rooms) { model.addRow(new Object[]{ "\uD83D\uDCBC " + room.getHotelName(), "\uD83D\uDCCD " + room.getAddress(), room.getRoomNumber(), room.getFloor(), room.getSquareMetres() + "m²", room.getPrice() + "€", "" + room.getId(), room.getCapacity(), "Click Here!" }); } } /** * Η μέθοδος αυτή δημιουργεί τον πίνακα στον οποίο θα * προσθεθούν όλα τα ιδιωτικά καταλύματα */ public void createPrivateAccommodationTable() { Object[][] data = {}; PrivateAccomodationsTable.setModel(new DefaultTableModel( data, new Object[]{"Company's name", "Type", "Location", "Square metres", "price", "Capacity", "Characteristics", "ID"} )); } /** * Η μέθοδος αυτή εισάγει στον πίνακα {@link #PrivateAccomodationsTable} * όλα τα ιδιωτικά καταλύματα που υπάρχουν στην εφαρμογή * * @param accommodations Λίστα τύπου {@link PrivateAccommodation} με όλα * τα ιδιωτικά καταλύματα */ public void AddPrivateAccommodationsToTable(ArrayList<PrivateAccommodation> accommodations) { DefaultTableModel model = (DefaultTableModel) PrivateAccomodationsTable.getModel(); for (PrivateAccommodation accommodation : accommodations) { model.addRow(new Object[]{ "\uD83D\uDCBC " + accommodation.getCompanyName(), "Type: " + accommodation.getType(), "\uD83D\uDCCD " + accommodation.getAddress(), accommodation.getSquareMetres() + "m²", accommodation.getPrice() + "€", accommodation.getCapacity(), "Click here!", "" + accommodation.getId() }); } } /** * {@link ActionListener} για το κουμπί LogOut που αποσυνδέει τον διαχειριστή απο την εφαρμογή * * @param login Το frame Login που συνδέθηκε ο διαχειριστής στην εφαρμογή (Κλείνει κατα την αποσύνδεση και ανοίγει νέο) */ public void logOut(Login login) { LogOut1.addActionListener(e -> { this.dispose(); login.dispose(); }); } /** * Η μέθοδος αυτή δημιουργεί τον πίνακα στον οποίο * αργότερα θα εισαχθούν όλοι οι χρήστες της εφαρμογής */ private void createAllUsersTable() { String[][] data = {}; allUsersTable.setModel(new DefaultTableModel( data, new String[]{"", "", "", ""} )); } /** * Η μέθοδος αυτή δημιουργεί τον πίνακα στον οποίο αργότερα * θα εισαχθούν όλες οι ενεργές κρατήσεις για τα καταλύματα * της εφαρμογής */ private void createAllReservationsTable() { String[][] data = {}; allReservationsTable.setModel(new DefaultTableModel( data, new String[]{"", "", "", "", "", "", ""} )); } /** * Η μέθοδος αυτή εισάγει όλους τους χρήστες που υπάρχουν στην εφαρμογή στον πίνακα {@link #allUsersTable} * * @param users Λίστα με όλους τους χρήστες της πλατφόρμας */ public void addUsersToTable(ArrayList<Users> users) { DefaultTableModel model = (DefaultTableModel) allUsersTable.getModel(); for (Users user : users) { model.addRow(new Object[]{ user.getRole(), user.getUsername(), user.getGender(), user.getPassword(), }); } } /** * Στη μέθοδο αυτή εισάγονται στον πίνακα {@link #allReservationsTable} όλες οι ενεργές κρατήσεις δωματίων * και ιδιωτικών καταλυμάτων * * @param allReservationsPrivate HashMap με τα ιδιωτικά καταλύματα και τις ημερομηνίες κράτησης τους * @param allReservationsRooms HashMap με τα δωμάτια ξενοδοχείων και τις ημερομηνίες κράτησης τους */ public void addReservationsToTable( HashMap<PrivateAccommodation, ArrayList<Date>> allReservationsPrivate, HashMap<HotelRooms, ArrayList<Date>> allReservationsRooms ) { DefaultTableModel model = (DefaultTableModel) allReservationsTable.getModel(); allReservationsPrivate.forEach((key, value) -> { for (Date date : value) { model.addRow(new Object[]{ "ID " + key.getId(), key.getType(), key.getPrice() + "€", key.getSquareMetres() + "m²", "\uD83D\uDCBC " + key.getCompanyName(), "\uD83D\uDCCD " + key.getAddress(), "\uD83D\uDCC6 " + date.toString() }); } }); allReservationsRooms.forEach((key, value) -> { for (Date date : value) { model.addRow(new Object[]{ "ID " + key.getId(), "Floor " + key.getFloor(), key.getPrice() + "€", key.getSquareMetres() + "m²", "\uD83D\uDCBC " + key.getHotelName(), "\uD83D\uDCCD " + key.getAddress(), "\uD83D\uDCC6 " + date.toString() }); } }); } /** * Η μέθοδος αυτή δημιουργεί τον πίνακα με τους ανενεργούς λογαριασμούς παρόχων */ private void createTableInactiveProviders() { String[][] data = {}; tableInactiveProviders.setModel(new DefaultTableModel( data, new String[]{"Username", "Gender", "Password"} )); addInactiveProvidersToTable(); } /** * Η μέθοδος αυτή προσθέτει όλους τους λογαριασμούς παρόχων που δεν έχουν εγκριθεί ακόμα από τον διαχειριστή * στον πίνακα {@link #tableInactiveProviders} */ public void addInactiveProvidersToTable() { DefaultTableModel model = (DefaultTableModel) tableInactiveProviders.getModel(); while (model.getRowCount() > 0) { model.removeRow(0); } for (Providers user : base.getAllProviders()) { if (user.accountStatus()) continue; model.addRow(new Object[]{ user.getUsername(), user.getGender(), user.getPassword(), }); } } /** * Η μέθοδος αυτή συμπληρώνει το μήνυμα που καλωσορίζει τον διαχειριστή στην πλατφόρμα * * @param name Username διαχειριστή που είναι συνδεδεμένος στην εφαρμογή */ public void setHelloMsgTo(String name) { int allUsers = base.getAllAdmins().size() + base.getAllProviders().size() + base.getAllCustomers().size(); int allAcc = base.getAccommodations().getRooms().size() + base.getAccommodations().getAirbnb().size(); this.helloMsg.setText("Hello " + name + ", how are you doing today."); this.helloMsgDesc.setText("It looks like " + allUsers + " people are on our platform and " + allAcc + " accommodations and hotel rooms!"); } public String getToUserMsgField() { return toUserMsgField.getText(); } public String getMessageArea() { return messageArea.getText(); } /** * Η μέθοδος αυτή επιτρέπει στον διαχειριστή να στείλει μήνυμα σε κάποιον χρήστη */ public void sendMessage() { boolean isSent = base.getAllAdmins().get(position).SendMessage(getToUserMsgField(), getMessageArea()); msgFail.setVisible(!isSent); msgSuccess.setVisible(isSent); } /** * Η μέθοδος αυτή<SUF>*/ private void activateUser(Admins admin) { boolean userFound = false; for (Providers provider : base.getAllProviders()) { if (fieldUserToActivate.getText().equalsIgnoreCase(provider.getUsername()) && !provider.accountStatus()) { provider.activate(); userFound = true; try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("providers.bin"))) { out.writeObject(admin.getAllProviders()); } catch (IOException e) { e.printStackTrace(); } break; } } msgActUsrNotExist.setVisible(!userFound); msgActUsrExist.setVisible(userFound); addInactiveProvidersToTable(); } /** * Η μέθοδος αυτή υλοποιεί {@link MouseListener} για τον πίνακα που αποθηκεύει τα ιδιωτικά καταλύματα. * Στο κλικ του ποντικού στην στήλη που αποθηκεύει * τα ειδικά χαρακτηριστικά του ιδιωτικού καταλύματος, εμφανίζει με την βοήθεια της * κλάσης {@link Display}την Λίστα με τα χαρακτηριστικά * του καταλύματος {@link Accommodations#getCharacteristics()} και την φωτογραφία * του καταλύματος με όνομα {@link Accommodations#getImageName()} * * @param admin Ο διαχειριστής που είναι συνδεδεμένος στην εφαρμογή */ public void privateAccommodationTableMouseListener(Admins admin) { PrivateAccomodationsTable.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mouseClicked(java.awt.event.MouseEvent evt) { int row = PrivateAccomodationsTable.rowAtPoint(evt.getPoint()); int col = PrivateAccomodationsTable.columnAtPoint(evt.getPoint()); if (row >= 0 && col == 6) { int rowSelected = PrivateAccomodationsTable.getSelectedRow(); int accommodationFound = admin.getAccommodations().FindAccommodation(Integer.parseInt(PrivateAccomodationsTable.getValueAt(rowSelected, 7).toString())); Display temp = new Display(admin.getAccommodations().getAirbnb().get(accommodationFound).getCharacteristics(), admin.getAccommodations().getAirbnb().get(accommodationFound).getImageName()); temp.pack(); temp.setVisible(true); } } }); } /** * Η μέθοδος αυτή υλοποιεί {@link MouseListener} για τους πίνακες που αφορούν τα ξενοδοχειακά δωμάτια. * Στο κλικ του ποντικού στην στήλη που αποθηκεύει * τα ειδικά χαρακτηριστικά του δωματίου, εμφανίζει με την βοήθεια της * κλάσης {@link Display}την Λίστα με τα χαρακτηριστικά * του καταλύματος {@link Accommodations#getCharacteristics()} και την φωτογραφία * του καταλύματος με όνομα {@link Accommodations#getImageName()} * * @param admin Ο διαχειριστής που είναι συνδεδεμένος στην εφαρμογή */ public void roomTableMouseListener(Admins admin) { HotelRoomsTable.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mouseClicked(java.awt.event.MouseEvent evt) { int row = HotelRoomsTable.rowAtPoint(evt.getPoint()); int col = HotelRoomsTable.columnAtPoint(evt.getPoint()); if (row >= 0 && col == 8) { int rowSelected = HotelRoomsTable.getSelectedRow(); int roomFound = admin.getAccommodations().FindRoom(Integer.parseInt(HotelRoomsTable.getValueAt(rowSelected, 6).toString())); Display temp = new Display(admin.getAccommodations().getRooms().get(roomFound).getCharacteristics(), admin.getAccommodations().getRooms().get(roomFound).getImageName()); temp.pack(); temp.setVisible(true); } } }); } }
40196_2
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * DesignWindow.java * * Created on 13 Μαρ 2012, 8:04:19 μμ */ package UI; import java.awt.event.MouseEvent; import java.awt.MouseInfo; import javax.swing.*; import javax.swing.tree.*; import src.QueryHandler; import java.util.*; import javax.swing.text.*; /** * * @author Σοφία */ //abstract public class Design {} public class DesignWindow extends javax.swing.JFrame { private TreePath path; private QueryHandler handler; private ArrayList<String> result; private JList PopupMenuList; private DefaultTreeModel treeModel; private DefaultListModel listModel; private DefaultListModel fieldModel; private DefaultListModel popupMenuListModel; private DefaultMutableTreeNode root; private DefaultMutableTreeNode mNode; private DefaultMutableTreeNode conditionParent; private String query; private String condition; private ConditionWindow where; DesignWindow() { handler = new QueryHandler(); result = new ArrayList(); where = new ConditionWindow(); where.addWindowListener(new java.awt.event.WindowAdapter() { public void windowDeactivated(java.awt.event.WindowEvent evt) { condition = where.getCondition(); createNode(condition, conditionParent); } }); initComponents(); root = new DefaultMutableTreeNode("ROOTQUERY"); TreeNode node1 = createNode("SELECT", root); TreeNode node2 = createNode("FROM", root); TreeNode node3 = createNode("WHERE", root); TreeNode node4 = createNode("Add condition...", (DefaultMutableTreeNode) node3); TreeNode node5 = createNode("GROUP BY", root); TreeNode node6 = createNode("HAVING", root); TreeNode node7 = createNode("Add condition...", (DefaultMutableTreeNode) node6); TreeNode node8 = createNode("SORT BY", root); result = handler.executeQuery("Show tables;"); listModel = new DefaultListModel(); for (int i = 0; i < result.size(); i = i + 2) { listModel.addElement(result.get(i)); } tables.setModel(listModel); fieldModel = new DefaultListModel(); fields.setModel(fieldModel); PopupMenuList = new JList(); DefaultListModel PopupMenuListModel = new DefaultListModel(); PopupMenuListModel.addElement("Add to GROUP BY"); PopupMenuListModel.addElement("Add to SORT BY (ASC)"); PopupMenuListModel.addElement("Add to SORT BY (DESC)"); PopupMenuList.setModel(PopupMenuListModel); PopupMenuList.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { PopupMenuListMouseClicked(evt); } }); jPopupMenu1.add(PopupMenuList); jPopupMenu1.pack(); this.setVisible(true); } private TreeNode createNode(String label, DefaultMutableTreeNode parent) { DefaultMutableTreeNode child = null; path = QueryTree.getNextMatch(label, 0, Position.Bias.Forward); if (path != null && ((DefaultMutableTreeNode) path.getLastPathComponent()).getParent().equals(parent)) { return null; } else { child = new DefaultMutableTreeNode(label); parent.add(child); treeModel = (DefaultTreeModel) QueryTree.getModel(); treeModel.setRoot(root); QueryTree.setModel(treeModel); for (int i = 0; i < QueryTree.getRowCount(); i++) { QueryTree.expandRow(i); } return child; } } private void createQuery() { query = "SELECT\n"; String value = null; Boolean flag = false; Boolean whereFlag = false; Boolean groupByFlag = false; Boolean havingFlag = false; Boolean sortByFlag = false; DefaultMutableTreeNode node; DefaultMutableTreeNode parent; path = QueryTree.getNextMatch("WHERE", 0, Position.Bias.Forward); node = (DefaultMutableTreeNode) path.getLastPathComponent(); if (node.getChildCount() > 1) { whereFlag = true; } path = QueryTree.getNextMatch("GROUP BY", 0, Position.Bias.Forward); node = (DefaultMutableTreeNode) path.getLastPathComponent(); if (node.getChildCount() > 0) { groupByFlag = true; } path = QueryTree.getNextMatch("HAVING", 0, Position.Bias.Forward); node = (DefaultMutableTreeNode) path.getLastPathComponent(); if (node.getChildCount() > 1) { havingFlag = true; } path = QueryTree.getNextMatch("SORT BY", 0, Position.Bias.Forward); node = (DefaultMutableTreeNode) path.getLastPathComponent(); if (node.getChildCount() > 0) { sortByFlag = true; } Enumeration en = root.depthFirstEnumeration(); while (en.hasMoreElements()) { node = (DefaultMutableTreeNode) en.nextElement(); parent = (DefaultMutableTreeNode) node.getParent(); if ((parent.getUserObject().toString().equals("SELECT") || parent.getUserObject().toString().equals("FROM") || parent.getUserObject().toString().equals("GROUP BY") || parent.getUserObject().toString().equals("SORT BY")) && (parent.getChildAfter(node) != null)) { flag = true; } else { flag = false; } value = node.getUserObject().toString(); if (value.equals("SELECT")) { value = "FROM"; } else if (value.equals("FROM")) { if (whereFlag) { value = "WHERE"; } else { continue; } } else if (value.equals("WHERE")) { if (groupByFlag) { value = "GROUP BY"; } else { continue; } } else if (value.equals("GROUP BY")) { if (havingFlag) { value = "HAVING"; } else { continue; } } else if (value.equals("HAVING")) { if (sortByFlag) { value = "ORDER BY"; } else { continue; } } else if (value.equals("SORT BY")) { break; } else if (value.equals("Add condition...")) { continue; } if (flag) { query = query + (value + ",\n"); } else { query = query + (value + "\n"); } } query = query + ";"; return; } public String getQuery() { return query; } /** * Creates new form DesignWindow */ /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPopupMenu1 = new javax.swing.JPopupMenu(); jScrollPane1 = new javax.swing.JScrollPane(); tables = new javax.swing.JList(); jScrollPane2 = new javax.swing.JScrollPane(); QueryTree = new javax.swing.JTree(); jScrollPane3 = new javax.swing.JScrollPane(); fields = new javax.swing.JList(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); CreateQueryButton = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); tables.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); tables.setName(""); // NOI18N tables.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tablesMouseClicked(evt); } }); jScrollPane1.setViewportView(tables); QueryTree.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { QueryTreeMouseClicked(evt); } }); jScrollPane2.setViewportView(QueryTree); fields.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { fieldsMouseClicked(evt); } }); jScrollPane3.setViewportView(fields); jLabel1.setForeground(new java.awt.Color(51, 0, 204)); jLabel1.setText("Tables (double click to select)"); jLabel1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); jLabel2.setForeground(new java.awt.Color(0, 0, 204)); jLabel2.setText("Fields (double click to add)"); CreateQueryButton.setText("Create Query"); CreateQueryButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CreateQueryButtonActionPerformed(evt); } }); jLabel3.setForeground(new java.awt.Color(0, 0, 204)); jLabel3.setText("Query Tree (double-click to remove node, right-click to add to group or sort by)"); jLabel3.setAutoscrolls(true); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(370, 370, 370) .addComponent(CreateQueryButton, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 182, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 182, Short.MAX_VALUE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 177, Short.MAX_VALUE)) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jLabel3)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 440, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(CreateQueryButton, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(23, 23, 23)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void QueryTreeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_QueryTreeMouseClicked jPopupMenu1.setVisible(false); try { treeModel = (DefaultTreeModel) QueryTree.getModel(); path = QueryTree.getSelectionPath(); mNode = (DefaultMutableTreeNode) path.getLastPathComponent(); } catch (NullPointerException ex) { return; } if (evt.getClickCount() == 2) { if (mNode.toString().equals("Add condition...")) { conditionParent = (DefaultMutableTreeNode) mNode.getParent(); if (conditionParent.getChildCount() > 1) { where.setLogicalOperator(true); } where.setVisible(true); return; } if (mNode.getLevel() > 1) { if (mNode.getParent().toString().equals("FROM")) { String table = mNode.toString(); while ((path = QueryTree.getNextMatch(table, 0, Position.Bias.Forward)) != null) { treeModel.removeNodeFromParent((DefaultMutableTreeNode) path.getLastPathComponent()); } } else { treeModel.removeNodeFromParent(mNode); } } } if (evt.getButton() == MouseEvent.BUTTON3) { if (mNode.getParent().toString().equals("SELECT")) { jPopupMenu1.setLocation(MouseInfo.getPointerInfo().getLocation()); jPopupMenu1.setVisible(true); } } }//GEN-LAST:event_QueryTreeMouseClicked private void PopupMenuListMouseClicked(java.awt.event.MouseEvent evt) { if (evt.getButton() == MouseEvent.BUTTON1) { String selectedItem = QueryTree.getSelectionPath().getLastPathComponent().toString(); String selectedAction = (String) PopupMenuList.getSelectedValue(); if (selectedAction.equals("Add to GROUP BY")) { path = QueryTree.getNextMatch("GROUP BY", 0, Position.Bias.Forward); createNode(selectedItem, (DefaultMutableTreeNode) path.getLastPathComponent()); } if (selectedAction.equals("Add to SORT BY (ASC)")) { path = QueryTree.getNextMatch("SORT BY", 0, Position.Bias.Forward); createNode(selectedItem + " ASC", (DefaultMutableTreeNode) path.getLastPathComponent()); } if (selectedAction.equals("Add to SORT BY (DESC)")) { path = QueryTree.getNextMatch("SORT BY", 0, Position.Bias.Forward); createNode(selectedItem + " DESC", (DefaultMutableTreeNode) path.getLastPathComponent()); } jPopupMenu1.setVisible(false); } } private void fieldsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fieldsMouseClicked if (evt.getClickCount() == 2) { String selectedItem; selectedItem = (String) fields.getSelectedValue(); treeModel = (DefaultTreeModel) QueryTree.getModel(); path = QueryTree.getNextMatch("SELECT", 0, Position.Bias.Forward); mNode = (DefaultMutableTreeNode) path.getLastPathComponent(); String nodeName = fields.getName() + '.' + selectedItem; createNode(nodeName, mNode); } }//GEN-LAST:event_fieldsMouseClicked private void tablesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablesMouseClicked String selectedItem; if (evt.getClickCount() == 2) { selectedItem = (String) tables.getSelectedValue(); path = QueryTree.getNextMatch("FROM", 0, Position.Bias.Forward); mNode = (DefaultMutableTreeNode) path.getLastPathComponent(); createNode(selectedItem, mNode); fields.setName(selectedItem); result.clear(); result = handler.executeQuery("Show columns from " + selectedItem + ";"); fieldModel = (DefaultListModel) fields.getModel(); fieldModel.clear(); for (int i = 0; i < result.size(); i = i + 7) { fieldModel.addElement(result.get(i)); } fields.setModel(fieldModel); } }//GEN-LAST:event_tablesMouseClicked private void CreateQueryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CreateQueryButtonActionPerformed createQuery(); //JOptionPane.showMessageDialog(null, query); //this.setVisible(false); this.dispose(); }//GEN-LAST:event_CreateQueryButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton CreateQueryButton; private javax.swing.JTree QueryTree; private javax.swing.JList fields; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPopupMenu jPopupMenu1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JList tables; // End of variables declaration//GEN-END:variables }
Nosfistis/TRAFIL
src/UI/DesignWindow.java
4,318
/** * * @author Σοφία */
block_comment
el
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * DesignWindow.java * * Created on 13 Μαρ 2012, 8:04:19 μμ */ package UI; import java.awt.event.MouseEvent; import java.awt.MouseInfo; import javax.swing.*; import javax.swing.tree.*; import src.QueryHandler; import java.util.*; import javax.swing.text.*; /** * * @author Σοφία <SUF>*/ //abstract public class Design {} public class DesignWindow extends javax.swing.JFrame { private TreePath path; private QueryHandler handler; private ArrayList<String> result; private JList PopupMenuList; private DefaultTreeModel treeModel; private DefaultListModel listModel; private DefaultListModel fieldModel; private DefaultListModel popupMenuListModel; private DefaultMutableTreeNode root; private DefaultMutableTreeNode mNode; private DefaultMutableTreeNode conditionParent; private String query; private String condition; private ConditionWindow where; DesignWindow() { handler = new QueryHandler(); result = new ArrayList(); where = new ConditionWindow(); where.addWindowListener(new java.awt.event.WindowAdapter() { public void windowDeactivated(java.awt.event.WindowEvent evt) { condition = where.getCondition(); createNode(condition, conditionParent); } }); initComponents(); root = new DefaultMutableTreeNode("ROOTQUERY"); TreeNode node1 = createNode("SELECT", root); TreeNode node2 = createNode("FROM", root); TreeNode node3 = createNode("WHERE", root); TreeNode node4 = createNode("Add condition...", (DefaultMutableTreeNode) node3); TreeNode node5 = createNode("GROUP BY", root); TreeNode node6 = createNode("HAVING", root); TreeNode node7 = createNode("Add condition...", (DefaultMutableTreeNode) node6); TreeNode node8 = createNode("SORT BY", root); result = handler.executeQuery("Show tables;"); listModel = new DefaultListModel(); for (int i = 0; i < result.size(); i = i + 2) { listModel.addElement(result.get(i)); } tables.setModel(listModel); fieldModel = new DefaultListModel(); fields.setModel(fieldModel); PopupMenuList = new JList(); DefaultListModel PopupMenuListModel = new DefaultListModel(); PopupMenuListModel.addElement("Add to GROUP BY"); PopupMenuListModel.addElement("Add to SORT BY (ASC)"); PopupMenuListModel.addElement("Add to SORT BY (DESC)"); PopupMenuList.setModel(PopupMenuListModel); PopupMenuList.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { PopupMenuListMouseClicked(evt); } }); jPopupMenu1.add(PopupMenuList); jPopupMenu1.pack(); this.setVisible(true); } private TreeNode createNode(String label, DefaultMutableTreeNode parent) { DefaultMutableTreeNode child = null; path = QueryTree.getNextMatch(label, 0, Position.Bias.Forward); if (path != null && ((DefaultMutableTreeNode) path.getLastPathComponent()).getParent().equals(parent)) { return null; } else { child = new DefaultMutableTreeNode(label); parent.add(child); treeModel = (DefaultTreeModel) QueryTree.getModel(); treeModel.setRoot(root); QueryTree.setModel(treeModel); for (int i = 0; i < QueryTree.getRowCount(); i++) { QueryTree.expandRow(i); } return child; } } private void createQuery() { query = "SELECT\n"; String value = null; Boolean flag = false; Boolean whereFlag = false; Boolean groupByFlag = false; Boolean havingFlag = false; Boolean sortByFlag = false; DefaultMutableTreeNode node; DefaultMutableTreeNode parent; path = QueryTree.getNextMatch("WHERE", 0, Position.Bias.Forward); node = (DefaultMutableTreeNode) path.getLastPathComponent(); if (node.getChildCount() > 1) { whereFlag = true; } path = QueryTree.getNextMatch("GROUP BY", 0, Position.Bias.Forward); node = (DefaultMutableTreeNode) path.getLastPathComponent(); if (node.getChildCount() > 0) { groupByFlag = true; } path = QueryTree.getNextMatch("HAVING", 0, Position.Bias.Forward); node = (DefaultMutableTreeNode) path.getLastPathComponent(); if (node.getChildCount() > 1) { havingFlag = true; } path = QueryTree.getNextMatch("SORT BY", 0, Position.Bias.Forward); node = (DefaultMutableTreeNode) path.getLastPathComponent(); if (node.getChildCount() > 0) { sortByFlag = true; } Enumeration en = root.depthFirstEnumeration(); while (en.hasMoreElements()) { node = (DefaultMutableTreeNode) en.nextElement(); parent = (DefaultMutableTreeNode) node.getParent(); if ((parent.getUserObject().toString().equals("SELECT") || parent.getUserObject().toString().equals("FROM") || parent.getUserObject().toString().equals("GROUP BY") || parent.getUserObject().toString().equals("SORT BY")) && (parent.getChildAfter(node) != null)) { flag = true; } else { flag = false; } value = node.getUserObject().toString(); if (value.equals("SELECT")) { value = "FROM"; } else if (value.equals("FROM")) { if (whereFlag) { value = "WHERE"; } else { continue; } } else if (value.equals("WHERE")) { if (groupByFlag) { value = "GROUP BY"; } else { continue; } } else if (value.equals("GROUP BY")) { if (havingFlag) { value = "HAVING"; } else { continue; } } else if (value.equals("HAVING")) { if (sortByFlag) { value = "ORDER BY"; } else { continue; } } else if (value.equals("SORT BY")) { break; } else if (value.equals("Add condition...")) { continue; } if (flag) { query = query + (value + ",\n"); } else { query = query + (value + "\n"); } } query = query + ";"; return; } public String getQuery() { return query; } /** * Creates new form DesignWindow */ /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPopupMenu1 = new javax.swing.JPopupMenu(); jScrollPane1 = new javax.swing.JScrollPane(); tables = new javax.swing.JList(); jScrollPane2 = new javax.swing.JScrollPane(); QueryTree = new javax.swing.JTree(); jScrollPane3 = new javax.swing.JScrollPane(); fields = new javax.swing.JList(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); CreateQueryButton = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); tables.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); tables.setName(""); // NOI18N tables.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tablesMouseClicked(evt); } }); jScrollPane1.setViewportView(tables); QueryTree.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { QueryTreeMouseClicked(evt); } }); jScrollPane2.setViewportView(QueryTree); fields.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { fieldsMouseClicked(evt); } }); jScrollPane3.setViewportView(fields); jLabel1.setForeground(new java.awt.Color(51, 0, 204)); jLabel1.setText("Tables (double click to select)"); jLabel1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); jLabel2.setForeground(new java.awt.Color(0, 0, 204)); jLabel2.setText("Fields (double click to add)"); CreateQueryButton.setText("Create Query"); CreateQueryButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CreateQueryButtonActionPerformed(evt); } }); jLabel3.setForeground(new java.awt.Color(0, 0, 204)); jLabel3.setText("Query Tree (double-click to remove node, right-click to add to group or sort by)"); jLabel3.setAutoscrolls(true); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(370, 370, 370) .addComponent(CreateQueryButton, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 182, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 182, Short.MAX_VALUE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 177, Short.MAX_VALUE)) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jLabel3)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 440, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(CreateQueryButton, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(23, 23, 23)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void QueryTreeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_QueryTreeMouseClicked jPopupMenu1.setVisible(false); try { treeModel = (DefaultTreeModel) QueryTree.getModel(); path = QueryTree.getSelectionPath(); mNode = (DefaultMutableTreeNode) path.getLastPathComponent(); } catch (NullPointerException ex) { return; } if (evt.getClickCount() == 2) { if (mNode.toString().equals("Add condition...")) { conditionParent = (DefaultMutableTreeNode) mNode.getParent(); if (conditionParent.getChildCount() > 1) { where.setLogicalOperator(true); } where.setVisible(true); return; } if (mNode.getLevel() > 1) { if (mNode.getParent().toString().equals("FROM")) { String table = mNode.toString(); while ((path = QueryTree.getNextMatch(table, 0, Position.Bias.Forward)) != null) { treeModel.removeNodeFromParent((DefaultMutableTreeNode) path.getLastPathComponent()); } } else { treeModel.removeNodeFromParent(mNode); } } } if (evt.getButton() == MouseEvent.BUTTON3) { if (mNode.getParent().toString().equals("SELECT")) { jPopupMenu1.setLocation(MouseInfo.getPointerInfo().getLocation()); jPopupMenu1.setVisible(true); } } }//GEN-LAST:event_QueryTreeMouseClicked private void PopupMenuListMouseClicked(java.awt.event.MouseEvent evt) { if (evt.getButton() == MouseEvent.BUTTON1) { String selectedItem = QueryTree.getSelectionPath().getLastPathComponent().toString(); String selectedAction = (String) PopupMenuList.getSelectedValue(); if (selectedAction.equals("Add to GROUP BY")) { path = QueryTree.getNextMatch("GROUP BY", 0, Position.Bias.Forward); createNode(selectedItem, (DefaultMutableTreeNode) path.getLastPathComponent()); } if (selectedAction.equals("Add to SORT BY (ASC)")) { path = QueryTree.getNextMatch("SORT BY", 0, Position.Bias.Forward); createNode(selectedItem + " ASC", (DefaultMutableTreeNode) path.getLastPathComponent()); } if (selectedAction.equals("Add to SORT BY (DESC)")) { path = QueryTree.getNextMatch("SORT BY", 0, Position.Bias.Forward); createNode(selectedItem + " DESC", (DefaultMutableTreeNode) path.getLastPathComponent()); } jPopupMenu1.setVisible(false); } } private void fieldsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fieldsMouseClicked if (evt.getClickCount() == 2) { String selectedItem; selectedItem = (String) fields.getSelectedValue(); treeModel = (DefaultTreeModel) QueryTree.getModel(); path = QueryTree.getNextMatch("SELECT", 0, Position.Bias.Forward); mNode = (DefaultMutableTreeNode) path.getLastPathComponent(); String nodeName = fields.getName() + '.' + selectedItem; createNode(nodeName, mNode); } }//GEN-LAST:event_fieldsMouseClicked private void tablesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablesMouseClicked String selectedItem; if (evt.getClickCount() == 2) { selectedItem = (String) tables.getSelectedValue(); path = QueryTree.getNextMatch("FROM", 0, Position.Bias.Forward); mNode = (DefaultMutableTreeNode) path.getLastPathComponent(); createNode(selectedItem, mNode); fields.setName(selectedItem); result.clear(); result = handler.executeQuery("Show columns from " + selectedItem + ";"); fieldModel = (DefaultListModel) fields.getModel(); fieldModel.clear(); for (int i = 0; i < result.size(); i = i + 7) { fieldModel.addElement(result.get(i)); } fields.setModel(fieldModel); } }//GEN-LAST:event_tablesMouseClicked private void CreateQueryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CreateQueryButtonActionPerformed createQuery(); //JOptionPane.showMessageDialog(null, query); //this.setVisible(false); this.dispose(); }//GEN-LAST:event_CreateQueryButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton CreateQueryButton; private javax.swing.JTree QueryTree; private javax.swing.JList fields; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPopupMenu jPopupMenu1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JList tables; // End of variables declaration//GEN-END:variables }
5899_4
/* * 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 iek.agdimitr.lab07; import java.util.Date; /** * * @author User */ public class Player { private String firstName; //Όνομα Παίκτη private String lastName; //Επίθετο Παίκτη private Date birthDate; //Ημερομηνία Γέννησης Παίκτη private int points; public Player(String f, String l){ this.firstName = f; this.lastName = l; this.points = 0; } //TODO Να φτιάξω μέθοδο για υπολογισμό ηλικίας από ημερομηνία //TODO Να φτιάξω μέθοδο για προσθήκη καλαθιών public void printStats(){ System.out.println("Fisrt Name :" + firstName); System.out.println("Last Name :" + lastName); System.out.println("Birth Date :" + birthDate); } @Override public String toString(){ return "First Name: " + firstName + " Last Name: " + lastName + ", Birth Date: " + birthDate; } public void addPoint(){ points++; System.out.println(" -> έχει " + points + " πόντους."); } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int getPoints() { return points; } public void removePoint(){ if(points != 0){ points--; System.out.println(" -> οι πόντοι τώρα είναι: " + points); } else{ System.out.println(" -> Οι πόντοι είναι 0 δεν μπορεί να γίνει αφαίρεση."); } } }
PStoreGR/Java-Project
src/main/java/iek/agdimitr/lab07/Player.java
570
//TODO Να φτιάξω μέθοδο για προσθήκη καλαθιών
line_comment
el
/* * 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 iek.agdimitr.lab07; import java.util.Date; /** * * @author User */ public class Player { private String firstName; //Όνομα Παίκτη private String lastName; //Επίθετο Παίκτη private Date birthDate; //Ημερομηνία Γέννησης Παίκτη private int points; public Player(String f, String l){ this.firstName = f; this.lastName = l; this.points = 0; } //TODO Να φτιάξω μέθοδο για υπολογισμό ηλικίας από ημερομηνία //TODO Να<SUF> public void printStats(){ System.out.println("Fisrt Name :" + firstName); System.out.println("Last Name :" + lastName); System.out.println("Birth Date :" + birthDate); } @Override public String toString(){ return "First Name: " + firstName + " Last Name: " + lastName + ", Birth Date: " + birthDate; } public void addPoint(){ points++; System.out.println(" -> έχει " + points + " πόντους."); } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int getPoints() { return points; } public void removePoint(){ if(points != 0){ points--; System.out.println(" -> οι πόντοι τώρα είναι: " + points); } else{ System.out.println(" -> Οι πόντοι είναι 0 δεν μπορεί να γίνει αφαίρεση."); } } }
17603_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 api; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.ProcessBuilder.Redirect.Type; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.SortedMap; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Giorgos */ public class AgTools { public static void main(String[] args) throws InstantiationException, IllegalAccessException, SQLException { try { //String products="595:ΨΑΡΙ ΝΩΠΟ ΦΑΓΚΡΙ:2,542:ΠΙΠΕΡΙΑ ΧΟΝΔΡΗ:2,541:ΠΙΠΕΡΙΑ ΜΑΚΡΙΑ ΦΛΩΡΙΝΗΣ:3"; String products = "COCA COLA PET ΦΙΑΛΗ 1.5Lt:1,ΜΠΙΣΚΟΤΑ ΠΤΙ ΜΠΕΡ ΠΑΠΑΔΟΠΟΥΛΟΥ 225gr:2,ΑΡΑΒΟΣΙΤΕΛΑΙΟ ΜΙΝΕΡΒΑ:3,ΜΠΥΡΑ AMSTEL ΜΕΤΑΛΛΙΚΟ ΚΟΥΤΙ 330ml:2,ΜΠΥΡΑ HEINEKEN ΚΟΥΤΙ 500ml:2"; double latitude = 37.9381; double longtitude = 23.6394; String[] pre = products.split(","); // System.out.println(pre.length); ArrayList<String> prod = new ArrayList<String>();//(Arrays.asList(products)); for (String p : pre) { //System.out.println(p); prod.add(p); } Class.forName("com.mysql.jdbc.Driver").newInstance(); String connectionURL = "jdbc:mysql://83.212.110.120/Bizeli?useUnicode=yes&characterEncoding=UTF-8&user=penguin&password=~Agkinara`"; Connection connection = DriverManager.getConnection(connectionURL); HashMap<String, Double> markets = ClosestMarkets(latitude, longtitude, 4.0, 10, connection); System.out.println(markets.keySet().toString());//+markets.get(1)); String marketCarts = MarketCarts(prod, markets, connection); //System.out.println(marketCarts);//+markets.get(1)); if (marketCarts.isEmpty()) { System.out.println("NoMarkets"); } String minList = MinList(prod, markets, connection); String jsons = marketCarts.concat("---" + minList); System.out.println(jsons); /* Class.forName("com.mysql.jdbc.Driver").newInstance(); String connectionURL = "jdbc:mysql://83.212.110.120/Bizeli?useUnicode=yes&characterEncoding=UTF-8&user=penguin&password=~Agkinara`"; Connection connection = DriverManager.getConnection(connectionURL); // if (connect()) { ArrayList<String> markets = new ArrayList<String>(); markets.add("ΑΒ ΑΘΗΝΩΝ (Πατησίων 240):5.0"); markets.add("ΛΑΪΚΗ ΑΓΟΡΑ Ν. ΦΙΛΑΔΕΛΦΕΙΑΣ:7.0"); markets.add("ΔΗΜΟΤΙΚΗ ΑΓΟΡΑ ΒΑΡΒΑΚΕΙΟΣ:8.0"); //hashmap product IDs and the amount of them the costumer wants to buy ArrayList<String> products = new ArrayList<String>(); products.add("1344:ΨΑΡΙ ΝΩΠΟ ΦΑΓΚΡΙ ΕΙΣΑΓΩΓΗΣ:2"); products.add("587:ΨΑΡΙ ΝΩΠΟ ΓΟΠΕΣ ΕΙΣΑΓΩΓΗΣ:1"); products.add("1635:ΜΟΣΧΑΡΙ ΝΩΠΟ ΜΠΡΙΖΟΛΑ ΚΟΝΤΡΑ ΕΓΧΩΡΙΑ:2"); products.add("956:ΧΟΙΡΙΝΟ ΝΩΠΟ ΜΠΡΙΖΟΛΑ ΛΑΙΜΟΥ ΜΕ ΟΣΤΑ ΕΓΧΩΡΙΑ:3"); products.add("526:ΛΑΧΑΝΙΚΟ ΚΡΕΜΜΥΔΙ ΦΡΕΣΚΟ:3"); //Veropoulos formionos 37.9702 23.7518 //my market antigonhs 38.0028 23.7518 //carefour athinwn aitwlias 37.9876 23.7624 //AB athinwn HashMap<String, Double> closest = ClosestMarkets(38.0088, 23.7351, 10.0,10, connection); for (String s : closest.keySet()) { System.out.println(closest.get(s) + " has distance " + s); } Gson gson = new Gson(); String json; //take the market carts json = MarketCarts(products, closest, connection); //create a type for Gson to recognise ArrayList<ArrayList<String>> java.lang.reflect.Type type = new TypeToken<ArrayList<ArrayList<String>>>() { }.getType(); //parse json string ArrayList<ArrayList<String>> fin = gson.fromJson(json, type); //it works (y) for (ArrayList<String> p : fin) { System.out.println(p.get(0));//market cart stats System.out.println(p.get(1));//first product } json = MinList(products, closest, connection); ArrayList<String> fin2 = gson.fromJson(json, ArrayList.class); for (String p : fin2) { System.out.println(p); } // }*/ } catch (ClassNotFoundException ex) { Logger.getLogger(AgTools.class.getName()).log(Level.SEVERE, null, ex); } } public static String MarketCarts(ArrayList<String> productsList, HashMap<String, Double> markets, Connection connection) { try { Statement select = connection.createStatement(); ResultSet rs = null; //each market has a cart with product Id and their correspoinding price HashMap<String, HashMap<String, Float>> MarketAndProducts = new HashMap<String, HashMap<String, Float>>(); // HashMap<String, ArrayList<String>> MarketAndProducts = new HashMap<String, ArrayList<String>>(); //HashMap for products and their amount HashMap<String, Integer> products = new HashMap<String, Integer>(); //string of the products requested String ProductStr = "'"; for (String p : productsList) { String[] pr = p.split(":"); //id:product and the respectice amount //products.put(pr[0] + ":" + pr[1], Integer.parseInt(pr[2])); //System.out.println(pr[0] + pr[0].length()); products.put(pr[0], Integer.parseInt(pr[1])); // System.out.println(pr[0]); //str of names to query ProductStr = ProductStr.concat(pr[0] + "','"); } //string of markets requested String MarketStr = "'"; //HM for markets and their distance from costumer // HashMap<String, Double> markets = new HashMap<String, Double>(); HashMap<String, String> marketLatLon = new HashMap<String, String>(); HashMap<String, Double> marketsDist = new HashMap<String, Double>(); for (String entry : markets.keySet()) { //market:distance //String[] pr = b.split(":"); String[] e = entry.split("---"); marketLatLon.put(e[0], e[1]); String ent = e[0]; MarketStr = MarketStr.concat(ent + "','"); marketsDist.put(ent, markets.get(entry)); //hashmap of products and prices // markets.put(ent.getKey(),ent.getValue() ); //keep one hashmap with product-price for every market, representing the cart HashMap<String, Float> temp = new HashMap<String, Float>(); MarketAndProducts.put(ent, temp); } if (ProductStr.length() > 0 && MarketStr.length() > 0) { //remoce the last , and the last ,' ProductStr = ProductStr.substring(0, ProductStr.length() - 2); MarketStr = MarketStr.substring(0, MarketStr.length() - 2); //query for the products String query = "SELECT name,price,market FROM prices WHERE name in (" + ProductStr + ") and market in (" + MarketStr + ")"; //CONCAT(id,':',name) as rs = select.executeQuery(query); while (rs.next()) { String mar = rs.getString("market").trim(); //take the list until now for this market HashMap<String, Float> temp = MarketAndProducts.get(mar); //add the new product to the already existing cart, with its price* the amount the costumer wants String name = rs.getString("name").trim(); Float price = (float) rs.getDouble("price"); // System.out.println(name + " " + price * 1); //product with the final price temp.put(name, price * products.get(name)); //put the renewed cart in the respective market MarketAndProducts.put(mar, temp); } if (MarketAndProducts.isEmpty()) { return ""; } /* String ret=" "+name.length(); for(String p:products.keySet()){ ret=ret+" "+p.length(); if(p.equalsIgnoreCase(name)){ return name+Integer.toString(products.get(name)); } }*/ //find the expected price of all the products requested HashMap<String, Float> averages = new HashMap<String, Float>(); query = "SELECT avg(price) as avg, name FROM prices WHERE name in (" + ProductStr + ") GROUP BY name";//////// rs = select.executeQuery(query); //the average cost of this basket generally float expAvg = 0; System.out.println(ProductStr); while (rs.next()) { Float avg = rs.getFloat("avg"); String name = rs.getString("name").trim(); //expected price is the average price of the product * # of these products the costumer wants to buy //System.out.println(name + " " + avg); averages.put(name, avg * products.get(name)); expAvg += avg * products.get(name); } //the final arraylist returned ArrayList<ArrayList<String>> fin = new ArrayList<ArrayList<String>>(); HashMap<String, Double> feat = new HashMap<String, Double>(); HashMap<String, ArrayList<String>> ca = new HashMap<String, ArrayList<String>>(); //find the final features of each market's cart for (String m : MarketAndProducts.keySet()) { HashMap<String, Float> temp = MarketAndProducts.get(m); //for cases where the market has no suitable product if (temp.isEmpty()) { continue; } //actual sum of market list's products float actSum = 0; for (float d : temp.values()) { //System.out.println(d); actSum += d; } //expected sum (with missing products) float expSum = actSum; for (String s : averages.keySet()) { //if a product is not in the market's cart if (!temp.keySet().contains(s)) { // System.out.println(s); //add its average price to the expected price of the cart expSum += averages.get(s); } } ///occupancy percentage of cart for that market double occ = temp.size() * 100 / products.size(); //distance of the costumer to each market double dist = marketsDist.get(m); boolean expensive = false; if (expSum > expAvg) { expensive = true; }// + occ + ":" String features = m + ":" + actSum + ":" + expSum + ":" + dist + ":" + expensive + ":" + marketLatLon.get(m); feat.put(features, occ); //the list of the market ArrayList<String> cart = new ArrayList<String>(); //append the features to the first position of the market's cart cart.add(features + ":" + occ); //append to the rest of the posistions the products of the cart and their respective prices for (Map.Entry o : temp.entrySet()) { cart.add(o.getKey() + ":" + o.getValue()); } ca.put(features, cart); //fin.add(cart); } //sort by occupancy LinkedHashMap<String, Double> sorted = sortHashMapByValues(feat); for (Map.Entry<String, Double> plom : sorted.entrySet()) { String maStats = plom.getKey(); fin.add(ca.get(maStats)); } Gson gson = new Gson(); String json = gson.toJson(fin); return json; } } catch (SQLException ex) { Logger.getLogger(AgTools.class.getName()).log(Level.SEVERE, null, ex); } return null; } public static String MinList(ArrayList<String> productsList, HashMap<String, Double> markets, Connection connection) { try { Statement select = connection.createStatement(); ResultSet rs = null; //string of products requested String ProductStr = "'"; ArrayList<String> kla = new ArrayList<String>(); for (String p : productsList) { String[] pr = p.split(":"); ProductStr = ProductStr.concat(pr[0] + "','"); // System.out.println("mesa "+pr[0]); kla.add(pr[0]); } //string of markets requested String MarketStr = "'"; HashMap<String, String> marketLatLon = new HashMap<String, String>(); HashMap<String, Double> marketsDist = new HashMap<String, Double>(); for (String entry : markets.keySet()) { //String[] pr = b.split(":"); //market:distance //String[] pr = b.split(":"); String[] e = entry.split("---"); marketLatLon.put(e[0], e[1]); marketsDist.put(e[0], markets.get(entry)); MarketStr = MarketStr.concat(e[0] + "','"); } if (ProductStr.length() > 0 && MarketStr.length() > 0) { //remove the last , and the last ,' ProductStr = ProductStr.substring(0, ProductStr.length() - 2); MarketStr = MarketStr.substring(0, MarketStr.length() - 2); /* String query = "SELECT min( price ) as min , market,CONCAT(id,':',name) as name FROM `prices` WHERE id in (" + ProductList + ") and market in (" + MarketList + ") GROUP BY id"; while(rs.next()){ String product = rs.getString("market") + ":" + + ":" + rs.getString("name") + ":" + rs.getString("min"); fin.add(product); } */ String query = "SELECT name,price,market FROM prices WHERE name in (" + ProductStr + ") and market in (" + MarketStr + ")"; //CONCAT(id,':',name) as // System.out.println(query); //HM for the product and the respective price HashMap<String, Double> prodPrice = new HashMap<String, Double>(); //HM for the product and the market that currently has it cheaper HashMap<String, String> prodMarket = new HashMap<String, String>(); ArrayList<String> fin = new ArrayList<String>(); rs = select.executeQuery(query); while (rs.next()) { String name = rs.getString("name").trim(); // System.out.println(name); //if the product has occured again in the result set if (prodPrice.containsKey(name)) { Double price = rs.getDouble("price"); // and if its current price is cheaper than the previous if (price < prodPrice.get(name)) { //keep that price prodPrice.put(name, price); String mar = rs.getString("market").trim(); //and keep that market as the best option for that product prodMarket.put(name, mar); } } else { //if it is the first time this product occurs in the result set Double price = rs.getDouble("price"); String mar = rs.getString("market").trim(); //keep this price as the min prodPrice.put(name, price); //keep this market as min's price market for this product prodMarket.put(name, mar); } } for (Map.Entry a : prodMarket.entrySet()) { //take the id:name of the product String name = a.getKey().toString(); //make the string that corresponds to market of min price:id:product:min(price of product) String product = a.getValue() + ":" + name + ":" + marketLatLon.get(a.getValue()) + ":" + prodPrice.get(name) + ":" + marketsDist.get(a.getValue()); // System.out.println(product); fin.add(product); } for (String s : kla) { if (!prodMarket.containsKey(s)) { fin.add("-1:" +s+":-1"+":-1"+":-1"+":-1"); } } Gson gson = new Gson(); String json = gson.toJson(fin); // System.out.println(json); return json; } return null; } catch (SQLException ex) { Logger.getLogger(AgTools.class.getName()).log(Level.SEVERE, null, ex); } return null; } public static HashMap<String, Double> ClosestMarkets(double lat, double lon, double withinDist, int numberOfMarkets, Connection connection) { try { final int R = 6371; // Radious of the earth Statement select = connection.createStatement(); ResultSet rs = null; String query = "SELECT name,lat,lon from markets"; //apo dw http://bigdatanerd.wordpress.com/2011/11/03/java-implementation-of-haversine-formula-for-distance-calculation-between-two-points/ rs = select.executeQuery(query); TreeMap<Double, String> marketDist = new TreeMap<Double, String>(); while (rs.next()) { //Haversine Formula Double dblat = rs.getDouble("lat"); Double dblon = rs.getDouble("lon"); String name = rs.getString("name"); Double latDistance = toRad(dblat - lat); Double lonDistance = toRad(dblon - lon); Double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2) + Math.cos(toRad(dblat)) * Math.cos(toRad(dblon)) * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2); Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); Double dist = R * c; //System.out.println(name+ " distance from target : "+dist ); name = name + "---" + dblat + ":" + dblon;//////no time to make a class Super Market marketDist.put(dist, name); } //sort the markets by distance and take those in a radius of withinDist SortedMap<Double, String> temp = new TreeMap<Double, String>(); temp = marketDist.headMap(withinDist); HashMap<String, Double> result = new HashMap<String, Double>(); int i = 0; //keep the first ten for (Map.Entry<Double, String> entry : temp.entrySet()) { i++; // System.out.println(entry.getKey()); result.put(entry.getValue(), entry.getKey()); if (i == numberOfMarkets) { break; } } return result; // Gson gson = new Gson(); // String json = gson.toJson(marketDist); // System.out.println(json); } catch (SQLException ex) { Logger.getLogger(AgTools.class.getName()).log(Level.SEVERE, null, ex); } return null; } private static Double toRad(Double value) { return value * Math.PI / 180; } /* public static ArrayList<String> ClosestMarkets(double Lat, double Lon, Connection connection) { try { Statement select = connection.createStatement(); ResultSet rs = null; String query = "SELECT name, 6371 * 2*ATAN2(SQRT(POW(sin( radians((" + Lat + "-lat)/2) ),2) + cos( radians( " + Lat + ") )*cos( radians(lat) )*POW(sin( radians((" + Lon + "-lon)/2) ),2))," + "SQRT(POW(sin( radians((" + Lat + "-lat)/2) ),2) + cos( radians( " + Lat + ") )*cos( radians(lat) )*POW(sin( radians((" + Lon + "-lon)/2) ),2)))" + " AS distance FROM markets HAVING distance<1000000 ORDER BY distance desc LIMIT 0,10"; //apo dw http://bigdatanerd.wordpress.com/2011/11/03/java-implementation-of-haversine-formula-for-distance-calculation-between-two-points/ rs = select.executeQuery(query); ArrayList<String> marketDist = new ArrayList<String>(); while (rs.next()) { System.out.println(rs.getString("name") + ":" + rs.getFloat("distance")); marketDist.add(rs.getString("name") + ":" + rs.getFloat("distance")); } // Gson gson = new Gson(); // String json = gson.toJson(marketDist); // System.out.println(json); return marketDist; } catch (SQLException ex) { Logger.getLogger(AgTools.class.getName()).log(Level.SEVERE, null, ex); } return null; } */ public static LinkedHashMap<String, Double> sortHashMapByValues(HashMap<String, Double> passedMap) { List mapKeys = new ArrayList(passedMap.keySet()); List mapValues = new ArrayList(passedMap.values()); //sort the value set sepparately Collections.sort(mapValues, Collections.reverseOrder()); //Collections.sort(mapKeys); LinkedHashMap<String, Double> sortedMap = new LinkedHashMap(); Iterator valueIt = mapValues.iterator(); while (valueIt.hasNext()) { Object val = valueIt.next(); Iterator keyIt = mapKeys.iterator(); //find the key that corresponds to the sorted value while (keyIt.hasNext()) { Object key = keyIt.next(); String comp1 = passedMap.get(key).toString(); String comp2 = val.toString(); //tally that key to this value in the sorted hashmap if (comp1.equals(comp2)) { passedMap.remove(key); mapKeys.remove(key); sortedMap.put((String) key, (Double) val); break; } } } return sortedMap; } }
Pana-sonic/aginara
WebServices/aginara/src/java/api/AgTools.java
6,081
//String products="595:ΨΑΡΙ ΝΩΠΟ ΦΑΓΚΡΙ:2,542:ΠΙΠΕΡΙΑ ΧΟΝΔΡΗ:2,541:ΠΙΠΕΡΙΑ ΜΑΚΡΙΑ ΦΛΩΡΙΝΗΣ:3";
line_comment
el
/* * 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 api; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.ProcessBuilder.Redirect.Type; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.SortedMap; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Giorgos */ public class AgTools { public static void main(String[] args) throws InstantiationException, IllegalAccessException, SQLException { try { //String products="595:ΨΑΡΙ<SUF> String products = "COCA COLA PET ΦΙΑΛΗ 1.5Lt:1,ΜΠΙΣΚΟΤΑ ΠΤΙ ΜΠΕΡ ΠΑΠΑΔΟΠΟΥΛΟΥ 225gr:2,ΑΡΑΒΟΣΙΤΕΛΑΙΟ ΜΙΝΕΡΒΑ:3,ΜΠΥΡΑ AMSTEL ΜΕΤΑΛΛΙΚΟ ΚΟΥΤΙ 330ml:2,ΜΠΥΡΑ HEINEKEN ΚΟΥΤΙ 500ml:2"; double latitude = 37.9381; double longtitude = 23.6394; String[] pre = products.split(","); // System.out.println(pre.length); ArrayList<String> prod = new ArrayList<String>();//(Arrays.asList(products)); for (String p : pre) { //System.out.println(p); prod.add(p); } Class.forName("com.mysql.jdbc.Driver").newInstance(); String connectionURL = "jdbc:mysql://83.212.110.120/Bizeli?useUnicode=yes&characterEncoding=UTF-8&user=penguin&password=~Agkinara`"; Connection connection = DriverManager.getConnection(connectionURL); HashMap<String, Double> markets = ClosestMarkets(latitude, longtitude, 4.0, 10, connection); System.out.println(markets.keySet().toString());//+markets.get(1)); String marketCarts = MarketCarts(prod, markets, connection); //System.out.println(marketCarts);//+markets.get(1)); if (marketCarts.isEmpty()) { System.out.println("NoMarkets"); } String minList = MinList(prod, markets, connection); String jsons = marketCarts.concat("---" + minList); System.out.println(jsons); /* Class.forName("com.mysql.jdbc.Driver").newInstance(); String connectionURL = "jdbc:mysql://83.212.110.120/Bizeli?useUnicode=yes&characterEncoding=UTF-8&user=penguin&password=~Agkinara`"; Connection connection = DriverManager.getConnection(connectionURL); // if (connect()) { ArrayList<String> markets = new ArrayList<String>(); markets.add("ΑΒ ΑΘΗΝΩΝ (Πατησίων 240):5.0"); markets.add("ΛΑΪΚΗ ΑΓΟΡΑ Ν. ΦΙΛΑΔΕΛΦΕΙΑΣ:7.0"); markets.add("ΔΗΜΟΤΙΚΗ ΑΓΟΡΑ ΒΑΡΒΑΚΕΙΟΣ:8.0"); //hashmap product IDs and the amount of them the costumer wants to buy ArrayList<String> products = new ArrayList<String>(); products.add("1344:ΨΑΡΙ ΝΩΠΟ ΦΑΓΚΡΙ ΕΙΣΑΓΩΓΗΣ:2"); products.add("587:ΨΑΡΙ ΝΩΠΟ ΓΟΠΕΣ ΕΙΣΑΓΩΓΗΣ:1"); products.add("1635:ΜΟΣΧΑΡΙ ΝΩΠΟ ΜΠΡΙΖΟΛΑ ΚΟΝΤΡΑ ΕΓΧΩΡΙΑ:2"); products.add("956:ΧΟΙΡΙΝΟ ΝΩΠΟ ΜΠΡΙΖΟΛΑ ΛΑΙΜΟΥ ΜΕ ΟΣΤΑ ΕΓΧΩΡΙΑ:3"); products.add("526:ΛΑΧΑΝΙΚΟ ΚΡΕΜΜΥΔΙ ΦΡΕΣΚΟ:3"); //Veropoulos formionos 37.9702 23.7518 //my market antigonhs 38.0028 23.7518 //carefour athinwn aitwlias 37.9876 23.7624 //AB athinwn HashMap<String, Double> closest = ClosestMarkets(38.0088, 23.7351, 10.0,10, connection); for (String s : closest.keySet()) { System.out.println(closest.get(s) + " has distance " + s); } Gson gson = new Gson(); String json; //take the market carts json = MarketCarts(products, closest, connection); //create a type for Gson to recognise ArrayList<ArrayList<String>> java.lang.reflect.Type type = new TypeToken<ArrayList<ArrayList<String>>>() { }.getType(); //parse json string ArrayList<ArrayList<String>> fin = gson.fromJson(json, type); //it works (y) for (ArrayList<String> p : fin) { System.out.println(p.get(0));//market cart stats System.out.println(p.get(1));//first product } json = MinList(products, closest, connection); ArrayList<String> fin2 = gson.fromJson(json, ArrayList.class); for (String p : fin2) { System.out.println(p); } // }*/ } catch (ClassNotFoundException ex) { Logger.getLogger(AgTools.class.getName()).log(Level.SEVERE, null, ex); } } public static String MarketCarts(ArrayList<String> productsList, HashMap<String, Double> markets, Connection connection) { try { Statement select = connection.createStatement(); ResultSet rs = null; //each market has a cart with product Id and their correspoinding price HashMap<String, HashMap<String, Float>> MarketAndProducts = new HashMap<String, HashMap<String, Float>>(); // HashMap<String, ArrayList<String>> MarketAndProducts = new HashMap<String, ArrayList<String>>(); //HashMap for products and their amount HashMap<String, Integer> products = new HashMap<String, Integer>(); //string of the products requested String ProductStr = "'"; for (String p : productsList) { String[] pr = p.split(":"); //id:product and the respectice amount //products.put(pr[0] + ":" + pr[1], Integer.parseInt(pr[2])); //System.out.println(pr[0] + pr[0].length()); products.put(pr[0], Integer.parseInt(pr[1])); // System.out.println(pr[0]); //str of names to query ProductStr = ProductStr.concat(pr[0] + "','"); } //string of markets requested String MarketStr = "'"; //HM for markets and their distance from costumer // HashMap<String, Double> markets = new HashMap<String, Double>(); HashMap<String, String> marketLatLon = new HashMap<String, String>(); HashMap<String, Double> marketsDist = new HashMap<String, Double>(); for (String entry : markets.keySet()) { //market:distance //String[] pr = b.split(":"); String[] e = entry.split("---"); marketLatLon.put(e[0], e[1]); String ent = e[0]; MarketStr = MarketStr.concat(ent + "','"); marketsDist.put(ent, markets.get(entry)); //hashmap of products and prices // markets.put(ent.getKey(),ent.getValue() ); //keep one hashmap with product-price for every market, representing the cart HashMap<String, Float> temp = new HashMap<String, Float>(); MarketAndProducts.put(ent, temp); } if (ProductStr.length() > 0 && MarketStr.length() > 0) { //remoce the last , and the last ,' ProductStr = ProductStr.substring(0, ProductStr.length() - 2); MarketStr = MarketStr.substring(0, MarketStr.length() - 2); //query for the products String query = "SELECT name,price,market FROM prices WHERE name in (" + ProductStr + ") and market in (" + MarketStr + ")"; //CONCAT(id,':',name) as rs = select.executeQuery(query); while (rs.next()) { String mar = rs.getString("market").trim(); //take the list until now for this market HashMap<String, Float> temp = MarketAndProducts.get(mar); //add the new product to the already existing cart, with its price* the amount the costumer wants String name = rs.getString("name").trim(); Float price = (float) rs.getDouble("price"); // System.out.println(name + " " + price * 1); //product with the final price temp.put(name, price * products.get(name)); //put the renewed cart in the respective market MarketAndProducts.put(mar, temp); } if (MarketAndProducts.isEmpty()) { return ""; } /* String ret=" "+name.length(); for(String p:products.keySet()){ ret=ret+" "+p.length(); if(p.equalsIgnoreCase(name)){ return name+Integer.toString(products.get(name)); } }*/ //find the expected price of all the products requested HashMap<String, Float> averages = new HashMap<String, Float>(); query = "SELECT avg(price) as avg, name FROM prices WHERE name in (" + ProductStr + ") GROUP BY name";//////// rs = select.executeQuery(query); //the average cost of this basket generally float expAvg = 0; System.out.println(ProductStr); while (rs.next()) { Float avg = rs.getFloat("avg"); String name = rs.getString("name").trim(); //expected price is the average price of the product * # of these products the costumer wants to buy //System.out.println(name + " " + avg); averages.put(name, avg * products.get(name)); expAvg += avg * products.get(name); } //the final arraylist returned ArrayList<ArrayList<String>> fin = new ArrayList<ArrayList<String>>(); HashMap<String, Double> feat = new HashMap<String, Double>(); HashMap<String, ArrayList<String>> ca = new HashMap<String, ArrayList<String>>(); //find the final features of each market's cart for (String m : MarketAndProducts.keySet()) { HashMap<String, Float> temp = MarketAndProducts.get(m); //for cases where the market has no suitable product if (temp.isEmpty()) { continue; } //actual sum of market list's products float actSum = 0; for (float d : temp.values()) { //System.out.println(d); actSum += d; } //expected sum (with missing products) float expSum = actSum; for (String s : averages.keySet()) { //if a product is not in the market's cart if (!temp.keySet().contains(s)) { // System.out.println(s); //add its average price to the expected price of the cart expSum += averages.get(s); } } ///occupancy percentage of cart for that market double occ = temp.size() * 100 / products.size(); //distance of the costumer to each market double dist = marketsDist.get(m); boolean expensive = false; if (expSum > expAvg) { expensive = true; }// + occ + ":" String features = m + ":" + actSum + ":" + expSum + ":" + dist + ":" + expensive + ":" + marketLatLon.get(m); feat.put(features, occ); //the list of the market ArrayList<String> cart = new ArrayList<String>(); //append the features to the first position of the market's cart cart.add(features + ":" + occ); //append to the rest of the posistions the products of the cart and their respective prices for (Map.Entry o : temp.entrySet()) { cart.add(o.getKey() + ":" + o.getValue()); } ca.put(features, cart); //fin.add(cart); } //sort by occupancy LinkedHashMap<String, Double> sorted = sortHashMapByValues(feat); for (Map.Entry<String, Double> plom : sorted.entrySet()) { String maStats = plom.getKey(); fin.add(ca.get(maStats)); } Gson gson = new Gson(); String json = gson.toJson(fin); return json; } } catch (SQLException ex) { Logger.getLogger(AgTools.class.getName()).log(Level.SEVERE, null, ex); } return null; } public static String MinList(ArrayList<String> productsList, HashMap<String, Double> markets, Connection connection) { try { Statement select = connection.createStatement(); ResultSet rs = null; //string of products requested String ProductStr = "'"; ArrayList<String> kla = new ArrayList<String>(); for (String p : productsList) { String[] pr = p.split(":"); ProductStr = ProductStr.concat(pr[0] + "','"); // System.out.println("mesa "+pr[0]); kla.add(pr[0]); } //string of markets requested String MarketStr = "'"; HashMap<String, String> marketLatLon = new HashMap<String, String>(); HashMap<String, Double> marketsDist = new HashMap<String, Double>(); for (String entry : markets.keySet()) { //String[] pr = b.split(":"); //market:distance //String[] pr = b.split(":"); String[] e = entry.split("---"); marketLatLon.put(e[0], e[1]); marketsDist.put(e[0], markets.get(entry)); MarketStr = MarketStr.concat(e[0] + "','"); } if (ProductStr.length() > 0 && MarketStr.length() > 0) { //remove the last , and the last ,' ProductStr = ProductStr.substring(0, ProductStr.length() - 2); MarketStr = MarketStr.substring(0, MarketStr.length() - 2); /* String query = "SELECT min( price ) as min , market,CONCAT(id,':',name) as name FROM `prices` WHERE id in (" + ProductList + ") and market in (" + MarketList + ") GROUP BY id"; while(rs.next()){ String product = rs.getString("market") + ":" + + ":" + rs.getString("name") + ":" + rs.getString("min"); fin.add(product); } */ String query = "SELECT name,price,market FROM prices WHERE name in (" + ProductStr + ") and market in (" + MarketStr + ")"; //CONCAT(id,':',name) as // System.out.println(query); //HM for the product and the respective price HashMap<String, Double> prodPrice = new HashMap<String, Double>(); //HM for the product and the market that currently has it cheaper HashMap<String, String> prodMarket = new HashMap<String, String>(); ArrayList<String> fin = new ArrayList<String>(); rs = select.executeQuery(query); while (rs.next()) { String name = rs.getString("name").trim(); // System.out.println(name); //if the product has occured again in the result set if (prodPrice.containsKey(name)) { Double price = rs.getDouble("price"); // and if its current price is cheaper than the previous if (price < prodPrice.get(name)) { //keep that price prodPrice.put(name, price); String mar = rs.getString("market").trim(); //and keep that market as the best option for that product prodMarket.put(name, mar); } } else { //if it is the first time this product occurs in the result set Double price = rs.getDouble("price"); String mar = rs.getString("market").trim(); //keep this price as the min prodPrice.put(name, price); //keep this market as min's price market for this product prodMarket.put(name, mar); } } for (Map.Entry a : prodMarket.entrySet()) { //take the id:name of the product String name = a.getKey().toString(); //make the string that corresponds to market of min price:id:product:min(price of product) String product = a.getValue() + ":" + name + ":" + marketLatLon.get(a.getValue()) + ":" + prodPrice.get(name) + ":" + marketsDist.get(a.getValue()); // System.out.println(product); fin.add(product); } for (String s : kla) { if (!prodMarket.containsKey(s)) { fin.add("-1:" +s+":-1"+":-1"+":-1"+":-1"); } } Gson gson = new Gson(); String json = gson.toJson(fin); // System.out.println(json); return json; } return null; } catch (SQLException ex) { Logger.getLogger(AgTools.class.getName()).log(Level.SEVERE, null, ex); } return null; } public static HashMap<String, Double> ClosestMarkets(double lat, double lon, double withinDist, int numberOfMarkets, Connection connection) { try { final int R = 6371; // Radious of the earth Statement select = connection.createStatement(); ResultSet rs = null; String query = "SELECT name,lat,lon from markets"; //apo dw http://bigdatanerd.wordpress.com/2011/11/03/java-implementation-of-haversine-formula-for-distance-calculation-between-two-points/ rs = select.executeQuery(query); TreeMap<Double, String> marketDist = new TreeMap<Double, String>(); while (rs.next()) { //Haversine Formula Double dblat = rs.getDouble("lat"); Double dblon = rs.getDouble("lon"); String name = rs.getString("name"); Double latDistance = toRad(dblat - lat); Double lonDistance = toRad(dblon - lon); Double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2) + Math.cos(toRad(dblat)) * Math.cos(toRad(dblon)) * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2); Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); Double dist = R * c; //System.out.println(name+ " distance from target : "+dist ); name = name + "---" + dblat + ":" + dblon;//////no time to make a class Super Market marketDist.put(dist, name); } //sort the markets by distance and take those in a radius of withinDist SortedMap<Double, String> temp = new TreeMap<Double, String>(); temp = marketDist.headMap(withinDist); HashMap<String, Double> result = new HashMap<String, Double>(); int i = 0; //keep the first ten for (Map.Entry<Double, String> entry : temp.entrySet()) { i++; // System.out.println(entry.getKey()); result.put(entry.getValue(), entry.getKey()); if (i == numberOfMarkets) { break; } } return result; // Gson gson = new Gson(); // String json = gson.toJson(marketDist); // System.out.println(json); } catch (SQLException ex) { Logger.getLogger(AgTools.class.getName()).log(Level.SEVERE, null, ex); } return null; } private static Double toRad(Double value) { return value * Math.PI / 180; } /* public static ArrayList<String> ClosestMarkets(double Lat, double Lon, Connection connection) { try { Statement select = connection.createStatement(); ResultSet rs = null; String query = "SELECT name, 6371 * 2*ATAN2(SQRT(POW(sin( radians((" + Lat + "-lat)/2) ),2) + cos( radians( " + Lat + ") )*cos( radians(lat) )*POW(sin( radians((" + Lon + "-lon)/2) ),2))," + "SQRT(POW(sin( radians((" + Lat + "-lat)/2) ),2) + cos( radians( " + Lat + ") )*cos( radians(lat) )*POW(sin( radians((" + Lon + "-lon)/2) ),2)))" + " AS distance FROM markets HAVING distance<1000000 ORDER BY distance desc LIMIT 0,10"; //apo dw http://bigdatanerd.wordpress.com/2011/11/03/java-implementation-of-haversine-formula-for-distance-calculation-between-two-points/ rs = select.executeQuery(query); ArrayList<String> marketDist = new ArrayList<String>(); while (rs.next()) { System.out.println(rs.getString("name") + ":" + rs.getFloat("distance")); marketDist.add(rs.getString("name") + ":" + rs.getFloat("distance")); } // Gson gson = new Gson(); // String json = gson.toJson(marketDist); // System.out.println(json); return marketDist; } catch (SQLException ex) { Logger.getLogger(AgTools.class.getName()).log(Level.SEVERE, null, ex); } return null; } */ public static LinkedHashMap<String, Double> sortHashMapByValues(HashMap<String, Double> passedMap) { List mapKeys = new ArrayList(passedMap.keySet()); List mapValues = new ArrayList(passedMap.values()); //sort the value set sepparately Collections.sort(mapValues, Collections.reverseOrder()); //Collections.sort(mapKeys); LinkedHashMap<String, Double> sortedMap = new LinkedHashMap(); Iterator valueIt = mapValues.iterator(); while (valueIt.hasNext()) { Object val = valueIt.next(); Iterator keyIt = mapKeys.iterator(); //find the key that corresponds to the sorted value while (keyIt.hasNext()) { Object key = keyIt.next(); String comp1 = passedMap.get(key).toString(); String comp2 = val.toString(); //tally that key to this value in the sorted hashmap if (comp1.equals(comp2)) { passedMap.remove(key); mapKeys.remove(key); sortedMap.put((String) key, (Double) val); break; } } } return sortedMap; } }
6123_7
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; /** * @author Giotakos Konstantinos */ public class Question { String anoun, answer, rightanswer; String filler1, filler2, filler3; String questiontype; ArrayList<String> choices; /** * Κονστρακτορας * * @param anoun η εκφώνηση της ερώτησης. * @param rightanswer η σωστή απάντηση της ερώτησης. * @param filler1 μια απο τις λάθος απαντήσης. * @param filler2 μια απο τις λάθος απαντήσης. * @param filler3 μια απο τις λάθος απαντήσης. */ public Question(String anoun, String rightanswer, String filler1, String filler2, String filler3) { this.anoun = anoun; this.rightanswer = rightanswer; this.choices = new ArrayList<>(); choices.add(filler1); choices.add(filler2); choices.add(filler3); choices.add(rightanswer); } /** * Η χρησιμότητα της παρακάτω μεθόδου είναι να επιστρέφει τον τύπο της ερώτησης. */ public String getQuestionType(){ return this.questiontype; } /** * Η παρακάτω μέθοδος επιστρέφει την σωστή απάντηση. */ public String getRightAnswer(){ return this.rightanswer; } /** * Η παρακάτω μέθοδος επιστρέφει την απάντηση του χρήστη. */ public String getAnswer(){ return this.answer; } /** * Η παρακάτω μέθοδος εμφανίζει την ερώτηση και τις επιλογές (με τυχαία σειρά). */ public void showQuestion(){ Collections.shuffle(choices); //ανακάτεμα επιλογών+ // System.out.println("Question Type:" + questiontype); System.out.println("Question: " + anoun + "\n" ); int i = 1; for (String s : choices){ System.out.println("(" + i + ") " + s); i++; } } /** * Η χρησιμότητα της παρακάτω μεθόδου είναι να επιστρέφει μήνυμα στο χρήστη ανάλογα με τη απάντηση που έδωσε */ public boolean checkAnswer(){ if(this.answer == this.rightanswer) return true; else{ System.out.println("Your answer was wrong!\nThe right answer is " + this.rightanswer); return false; } } public boolean checkAnswernotforprint(){ if(this.answer == this.rightanswer) return true; return false; } /** * Η χρησιμότητα της παρακάτω μεθόδου είναι να παίρνει την απάντηση απο τον χρήστη και να την αποθηκεύει */ public void playersAnswer(){ System.out.println("Pick the number that corresponds to the right answer: "); Scanner s = new Scanner(System.in); int userchoice; userchoice = s.nextInt();//ανάγνωση απάντησης χρήστη while (userchoice > 4 && userchoice < 1){ userchoice = s.nextInt(); } this.answer = choices.get(userchoice-1); // Εδώ βάζω την τιμη απο το κελί userchoice - 1 μεσα στο answer για να γινει σωστα ο έλεγχος στη μέθοδο checkAnswer. } }
PanagosAlex/Buzz-Quiz-World
src/Question.java
1,234
/** * Η χρησιμότητα της παρακάτω μεθόδου είναι να επιστρέφει μήνυμα στο χρήστη ανάλογα με τη απάντηση που έδωσε */
block_comment
el
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; /** * @author Giotakos Konstantinos */ public class Question { String anoun, answer, rightanswer; String filler1, filler2, filler3; String questiontype; ArrayList<String> choices; /** * Κονστρακτορας * * @param anoun η εκφώνηση της ερώτησης. * @param rightanswer η σωστή απάντηση της ερώτησης. * @param filler1 μια απο τις λάθος απαντήσης. * @param filler2 μια απο τις λάθος απαντήσης. * @param filler3 μια απο τις λάθος απαντήσης. */ public Question(String anoun, String rightanswer, String filler1, String filler2, String filler3) { this.anoun = anoun; this.rightanswer = rightanswer; this.choices = new ArrayList<>(); choices.add(filler1); choices.add(filler2); choices.add(filler3); choices.add(rightanswer); } /** * Η χρησιμότητα της παρακάτω μεθόδου είναι να επιστρέφει τον τύπο της ερώτησης. */ public String getQuestionType(){ return this.questiontype; } /** * Η παρακάτω μέθοδος επιστρέφει την σωστή απάντηση. */ public String getRightAnswer(){ return this.rightanswer; } /** * Η παρακάτω μέθοδος επιστρέφει την απάντηση του χρήστη. */ public String getAnswer(){ return this.answer; } /** * Η παρακάτω μέθοδος εμφανίζει την ερώτηση και τις επιλογές (με τυχαία σειρά). */ public void showQuestion(){ Collections.shuffle(choices); //ανακάτεμα επιλογών+ // System.out.println("Question Type:" + questiontype); System.out.println("Question: " + anoun + "\n" ); int i = 1; for (String s : choices){ System.out.println("(" + i + ") " + s); i++; } } /** * Η χρησιμότητα της<SUF>*/ public boolean checkAnswer(){ if(this.answer == this.rightanswer) return true; else{ System.out.println("Your answer was wrong!\nThe right answer is " + this.rightanswer); return false; } } public boolean checkAnswernotforprint(){ if(this.answer == this.rightanswer) return true; return false; } /** * Η χρησιμότητα της παρακάτω μεθόδου είναι να παίρνει την απάντηση απο τον χρήστη και να την αποθηκεύει */ public void playersAnswer(){ System.out.println("Pick the number that corresponds to the right answer: "); Scanner s = new Scanner(System.in); int userchoice; userchoice = s.nextInt();//ανάγνωση απάντησης χρήστη while (userchoice > 4 && userchoice < 1){ userchoice = s.nextInt(); } this.answer = choices.get(userchoice-1); // Εδώ βάζω την τιμη απο το κελί userchoice - 1 μεσα στο answer για να γινει σωστα ο έλεγχος στη μέθοδο checkAnswer. } }
3736_14
package gr.aueb.softeng.team02.util; import java.util.Calendar; /** * Αμετάβλητη κλάση για τη διαχείριση ημερομηνιών * αγνοώντας την ώρα. * */ public class SimpleCalendar implements Comparable<SimpleCalendar> { private static final long MILLIS_PER_DAY = 86400000; private Calendar date; /** * Κατασκευάζει μία ημερομηνία με βάση το έτος, * το μήνα και την ημέρα του μήνα. * @param year Το έτος * @param month Ο μήνας από 1 έως 12 * @param day Η ημέρα του μήνα */ public SimpleCalendar(int year, int month, int day) { date = Calendar.getInstance(); date.set(year, month - 1, day); trimToDays(this.date); } /** * Κατασκευάζει μία ημερομηνία λαμβάνοντας. * ως παράμετρο αντικείμενο της κλάσης {@code Calendar} * @param date Η ημερομηνία */ public SimpleCalendar(Calendar date) { this.date = Calendar.getInstance(); this.date.setTimeInMillis(date.getTimeInMillis()); trimToDays(this.date); } private void trimToDays(Calendar javaDate) { javaDate.set(Calendar.HOUR_OF_DAY, 0); javaDate.set(Calendar.MINUTE, 0); javaDate.set(Calendar.SECOND, 0); javaDate.set(Calendar.MILLISECOND, 0); } /** * Η διάρκεια σε ημέρες σε σχέση με μία άλλη ημερομηνία. * @param other Η δεύτερη ημερομηνία για την οποία * υπολογίζεται η διάρκεια * @return Ο αριθμός των ημερών. Θετικός αριθμός ημερών * σημαίνει ότι η άλλη ημερομηνία είναι μεταγενέστερη, * ενώ αρνητικός το αντίθετο. */ public long durationInDays(SimpleCalendar other) { long timeDiff = other.date.getTimeInMillis() - date.getTimeInMillis(); return timeDiff / MILLIS_PER_DAY; } /** * Επιστρέφει το έτος της ημερομηνίας. * @return Το έτος */ public int getYear() { return date.get(Calendar.YEAR); } /** * Επιστρέφει το μήνα της ημερομηνίας (1-12). * @return Ο μήνας */ public int getMonth() { return date.get(Calendar.MONTH) + 1; } /** * Επιστρέφει την ημέρα σε του μήνα. * @return Η ημέρα του μήνα */ public int getDayOfMonth() { return date.get(Calendar.DAY_OF_MONTH); } /** * Επιστρέφει την ημέρα της εβδομάδας της ημερομηνίας. * @return Η ημέρα της εβδομάδας */ public int getDayOfWeek() { return date.get(Calendar.DAY_OF_WEEK); } /** * Επιστρέφει {@code true} αν η ημερομηνία είναι. * μεταγενέστερη μίας άλλης ημερομηνίας * @param other Η άλλη ημερομηνία * @return {@code true} αν η ημερομηνία είναι * μεταγενέστερη της άλλης */ public boolean after(SimpleCalendar other) { if (equals(other)) { return false; } return date.after(other.date); } /** * Επιστρέφει {@code true} αν η ημερομηνία είναι. * προγενέστερη μίας άλλης ημερομηνίας * @param other Η άλλη ημερομηνία * @return {@code true} αν η ημερομηνία είναι * προγενέστερη της άλλης */ public boolean before(SimpleCalendar other) { if (equals(other)) { return false; } return date.before(other.date); } /** * Επιστρέφει μία ημερομηνία προσθέτοντας κάποιο * αριθμό ημερών. * @param days Ο αριθμός των ημερών που προστίθενται * @return Η νέα ημερομηνία */ public SimpleCalendar addDays(int days) { Calendar newDate = Calendar.getInstance(); newDate.setTimeInMillis(date.getTimeInMillis()); newDate.add(Calendar.DAY_OF_MONTH, days); return new SimpleCalendar(newDate); } /** * Επιστρέφει μία ημερομηνία τύπου {@code Calendar}. * @return Η ημερομηνία */ public Calendar getJavaCalendar() { Calendar javaCalendar = Calendar.getInstance(); javaCalendar.setTimeInMillis(date.getTimeInMillis()); trimToDays(javaCalendar); return javaCalendar; } /** * {@inheritDoc} */ public int compareTo(SimpleCalendar other) { return date.compareTo(other.date); } /** * Η ισότητα βασίζεται σε όλα τα πεδία της διεύθυνσης. * @param other Το άλλο αντικείμενο προς έλεγχο * @return {@code true} αν τα αντικείμενα είναι ίσα */ @Override public boolean equals(Object other) { if (other == null) { return false; } if (this == other) { return true; } if (!(other instanceof SimpleCalendar)) { return false; } SimpleCalendar theDate = (SimpleCalendar) other; if (getYear() != theDate.getYear()) { return false; } if (getMonth() != theDate.getMonth()) { return false; } if (getDayOfMonth() != theDate.getDayOfMonth()) { return false; } return true; } /** * Το HashCode μίας ημερομηνίας * @return Το HashCode */ @Override public int hashCode() { return date == null ? 0 : date.hashCode(); } }
Panattack/UniVerse
app/src/main/java/gr/aueb/softeng/team02/util/SimpleCalendar.java
2,165
/** * Το HashCode μίας ημερομηνίας * @return Το HashCode */
block_comment
el
package gr.aueb.softeng.team02.util; import java.util.Calendar; /** * Αμετάβλητη κλάση για τη διαχείριση ημερομηνιών * αγνοώντας την ώρα. * */ public class SimpleCalendar implements Comparable<SimpleCalendar> { private static final long MILLIS_PER_DAY = 86400000; private Calendar date; /** * Κατασκευάζει μία ημερομηνία με βάση το έτος, * το μήνα και την ημέρα του μήνα. * @param year Το έτος * @param month Ο μήνας από 1 έως 12 * @param day Η ημέρα του μήνα */ public SimpleCalendar(int year, int month, int day) { date = Calendar.getInstance(); date.set(year, month - 1, day); trimToDays(this.date); } /** * Κατασκευάζει μία ημερομηνία λαμβάνοντας. * ως παράμετρο αντικείμενο της κλάσης {@code Calendar} * @param date Η ημερομηνία */ public SimpleCalendar(Calendar date) { this.date = Calendar.getInstance(); this.date.setTimeInMillis(date.getTimeInMillis()); trimToDays(this.date); } private void trimToDays(Calendar javaDate) { javaDate.set(Calendar.HOUR_OF_DAY, 0); javaDate.set(Calendar.MINUTE, 0); javaDate.set(Calendar.SECOND, 0); javaDate.set(Calendar.MILLISECOND, 0); } /** * Η διάρκεια σε ημέρες σε σχέση με μία άλλη ημερομηνία. * @param other Η δεύτερη ημερομηνία για την οποία * υπολογίζεται η διάρκεια * @return Ο αριθμός των ημερών. Θετικός αριθμός ημερών * σημαίνει ότι η άλλη ημερομηνία είναι μεταγενέστερη, * ενώ αρνητικός το αντίθετο. */ public long durationInDays(SimpleCalendar other) { long timeDiff = other.date.getTimeInMillis() - date.getTimeInMillis(); return timeDiff / MILLIS_PER_DAY; } /** * Επιστρέφει το έτος της ημερομηνίας. * @return Το έτος */ public int getYear() { return date.get(Calendar.YEAR); } /** * Επιστρέφει το μήνα της ημερομηνίας (1-12). * @return Ο μήνας */ public int getMonth() { return date.get(Calendar.MONTH) + 1; } /** * Επιστρέφει την ημέρα σε του μήνα. * @return Η ημέρα του μήνα */ public int getDayOfMonth() { return date.get(Calendar.DAY_OF_MONTH); } /** * Επιστρέφει την ημέρα της εβδομάδας της ημερομηνίας. * @return Η ημέρα της εβδομάδας */ public int getDayOfWeek() { return date.get(Calendar.DAY_OF_WEEK); } /** * Επιστρέφει {@code true} αν η ημερομηνία είναι. * μεταγενέστερη μίας άλλης ημερομηνίας * @param other Η άλλη ημερομηνία * @return {@code true} αν η ημερομηνία είναι * μεταγενέστερη της άλλης */ public boolean after(SimpleCalendar other) { if (equals(other)) { return false; } return date.after(other.date); } /** * Επιστρέφει {@code true} αν η ημερομηνία είναι. * προγενέστερη μίας άλλης ημερομηνίας * @param other Η άλλη ημερομηνία * @return {@code true} αν η ημερομηνία είναι * προγενέστερη της άλλης */ public boolean before(SimpleCalendar other) { if (equals(other)) { return false; } return date.before(other.date); } /** * Επιστρέφει μία ημερομηνία προσθέτοντας κάποιο * αριθμό ημερών. * @param days Ο αριθμός των ημερών που προστίθενται * @return Η νέα ημερομηνία */ public SimpleCalendar addDays(int days) { Calendar newDate = Calendar.getInstance(); newDate.setTimeInMillis(date.getTimeInMillis()); newDate.add(Calendar.DAY_OF_MONTH, days); return new SimpleCalendar(newDate); } /** * Επιστρέφει μία ημερομηνία τύπου {@code Calendar}. * @return Η ημερομηνία */ public Calendar getJavaCalendar() { Calendar javaCalendar = Calendar.getInstance(); javaCalendar.setTimeInMillis(date.getTimeInMillis()); trimToDays(javaCalendar); return javaCalendar; } /** * {@inheritDoc} */ public int compareTo(SimpleCalendar other) { return date.compareTo(other.date); } /** * Η ισότητα βασίζεται σε όλα τα πεδία της διεύθυνσης. * @param other Το άλλο αντικείμενο προς έλεγχο * @return {@code true} αν τα αντικείμενα είναι ίσα */ @Override public boolean equals(Object other) { if (other == null) { return false; } if (this == other) { return true; } if (!(other instanceof SimpleCalendar)) { return false; } SimpleCalendar theDate = (SimpleCalendar) other; if (getYear() != theDate.getYear()) { return false; } if (getMonth() != theDate.getMonth()) { return false; } if (getDayOfMonth() != theDate.getDayOfMonth()) { return false; } return true; } /** * Το HashCode μίας<SUF>*/ @Override public int hashCode() { return date == null ? 0 : date.hashCode(); } }
474_5
import java.rmi.*; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.Scanner; public class THClient { public static String Input(){ // Δημιουργία ενός αντικειμένου Scanner για ανάγνωση εισόδου από τον χρήστη Scanner scanner = new Scanner(System.in); System.out.println("Απάντηση (y=yes, n=no): "); String userInput = scanner.nextLine(); // Κλείσιμο του Scanner scanner.close(); return userInput; } public static void main(String[] args) { //Ο client θα πρέπει να τρέχει στο command line ως εξής: //Ελέγχουμε αν δεν εχουν εισαχθεί ορίσματα τότε να εκτυπώνει τα ορίσματα που μπορούν να δωθούν java THClient /* * java TΗClient: αν καμία άλλη παράμετρος δεν προσδιορίζεται, το πρόγραμμα θα πρέπει απλά να * τυπώνει στην οθόνη πως ακριβώς (με τι παραμέτρους) πρέπει να τρέξει ο χρήστης την εντολή */ if(args.length == 0) { PrintCommands(); return; } try { THInterface in = (THInterface)Naming.lookup("rmi://localhost:1099/TH"); String command = args[0]; //args[1]="localhost"; //Έλεγχος παραπάνω ορισμάτων switch(command) { /* * java TΗClient list <hostname>: να τυπώνεται ως αποτέλεσμα στην οθόνη μία λίστα με τις διαθέσιμες * θέσεις (για κάθε τύπο και κόστος) στο θέατρο - π.χ. στην ακόλουθη μορφή: * κ1 θέσεις Πλατεία - Ζώνη Α (κωδικός: ΠΑ) - τιμή: 45 Ευρώ * κ2 θέσεις Πλατεία - Ζώνη Β (κωδικός: ΠΒ) - τιμή: 35 Ευρώ * κ3 θέσεις Πλατεία - Ζώνη Γ (κωδικός: ΠΓ) - τιμή: 25 Ευρώ * κ4 θέσεις Κεντρικός Εξώστης (κωδικός: ΚΕ) - τιμή: 30 Ευρώ * κ5 θέσεις Πλαϊνά Θεωρεία (κωδικός: ΠΘ) - τιμή: 20 Ευρώ * όπου τα κ1,κ2,κ3,κ4,κ5 υποδεικνύουν τον τρέχοντα αριθμό διαθέσιμων θέσεων κάθε τύπου. */ case "list": if (args.length < 2) { System.out.println("Java THClient list <hostname>: Εμφάνιση των διαθέσιμων θέσεων και το κόστος\n"); } else{ //Εκτύπωση Διαθέσιμων Θέσεων System.out.println(in.lista()); } break; case "book": if(args.length < 5) { System.out.println("Java THClient book <hostname> <type> <number> <name>: Κράτηση θέσεων\n"); } else{ String type=args[2]; int number=Integer.parseInt(args[3]); //Μετατροπή string σε ακέραιο String name=args[4]; } break; case "guest": if(args.length < 2) { System.out.println("Java THClient guest <hostname>:\n"); } else{ } break; case "cancel": if(args.length < 5) { System.out.println("Java THClient cancel <hostname> <type> <number> <name>: Ακύρωση κράτησης\n"); } else { String type=args[2]; int number=Integer.parseInt(args[3]); String name=args[4]; } } } catch (Exception e) { e.printStackTrace(); // TODO: handle exception } } public static void PrintSeats() { } //Συνάρτηση που εκτυπώνει τα επιτρεπτά ορίσματα private static void PrintCommands() { System.out.println("Ορίσματα:\n"); System.out.println("Java THClient: Εκτύπωση τον ορισμάτων\n"); System.out.println("Java THClient list <hostname>: Εμφάνιση των διαθέσιμων θέσεων και το κόστος\n"); System.out.println("Java THClient book <hostname> <type> <number> <name>: Κράτηση θέσεων\n"); System.out.println("Java THClient guest <hostname>: Εκτύπωση λίστας πελατών που έχουν κάνει κράτηση\n"); System.out.println("Java THClient cancel <hostname> <type> <number> <name>: Ακύρωση κράτησης\n"); } }
Pandelmark/Distributed-Systems
RMI/THClient.java
1,822
//Έλεγχος παραπάνω ορισμάτων
line_comment
el
import java.rmi.*; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.Scanner; public class THClient { public static String Input(){ // Δημιουργία ενός αντικειμένου Scanner για ανάγνωση εισόδου από τον χρήστη Scanner scanner = new Scanner(System.in); System.out.println("Απάντηση (y=yes, n=no): "); String userInput = scanner.nextLine(); // Κλείσιμο του Scanner scanner.close(); return userInput; } public static void main(String[] args) { //Ο client θα πρέπει να τρέχει στο command line ως εξής: //Ελέγχουμε αν δεν εχουν εισαχθεί ορίσματα τότε να εκτυπώνει τα ορίσματα που μπορούν να δωθούν java THClient /* * java TΗClient: αν καμία άλλη παράμετρος δεν προσδιορίζεται, το πρόγραμμα θα πρέπει απλά να * τυπώνει στην οθόνη πως ακριβώς (με τι παραμέτρους) πρέπει να τρέξει ο χρήστης την εντολή */ if(args.length == 0) { PrintCommands(); return; } try { THInterface in = (THInterface)Naming.lookup("rmi://localhost:1099/TH"); String command = args[0]; //args[1]="localhost"; //Έλεγχος παραπάνω<SUF> switch(command) { /* * java TΗClient list <hostname>: να τυπώνεται ως αποτέλεσμα στην οθόνη μία λίστα με τις διαθέσιμες * θέσεις (για κάθε τύπο και κόστος) στο θέατρο - π.χ. στην ακόλουθη μορφή: * κ1 θέσεις Πλατεία - Ζώνη Α (κωδικός: ΠΑ) - τιμή: 45 Ευρώ * κ2 θέσεις Πλατεία - Ζώνη Β (κωδικός: ΠΒ) - τιμή: 35 Ευρώ * κ3 θέσεις Πλατεία - Ζώνη Γ (κωδικός: ΠΓ) - τιμή: 25 Ευρώ * κ4 θέσεις Κεντρικός Εξώστης (κωδικός: ΚΕ) - τιμή: 30 Ευρώ * κ5 θέσεις Πλαϊνά Θεωρεία (κωδικός: ΠΘ) - τιμή: 20 Ευρώ * όπου τα κ1,κ2,κ3,κ4,κ5 υποδεικνύουν τον τρέχοντα αριθμό διαθέσιμων θέσεων κάθε τύπου. */ case "list": if (args.length < 2) { System.out.println("Java THClient list <hostname>: Εμφάνιση των διαθέσιμων θέσεων και το κόστος\n"); } else{ //Εκτύπωση Διαθέσιμων Θέσεων System.out.println(in.lista()); } break; case "book": if(args.length < 5) { System.out.println("Java THClient book <hostname> <type> <number> <name>: Κράτηση θέσεων\n"); } else{ String type=args[2]; int number=Integer.parseInt(args[3]); //Μετατροπή string σε ακέραιο String name=args[4]; } break; case "guest": if(args.length < 2) { System.out.println("Java THClient guest <hostname>:\n"); } else{ } break; case "cancel": if(args.length < 5) { System.out.println("Java THClient cancel <hostname> <type> <number> <name>: Ακύρωση κράτησης\n"); } else { String type=args[2]; int number=Integer.parseInt(args[3]); String name=args[4]; } } } catch (Exception e) { e.printStackTrace(); // TODO: handle exception } } public static void PrintSeats() { } //Συνάρτηση που εκτυπώνει τα επιτρεπτά ορίσματα private static void PrintCommands() { System.out.println("Ορίσματα:\n"); System.out.println("Java THClient: Εκτύπωση τον ορισμάτων\n"); System.out.println("Java THClient list <hostname>: Εμφάνιση των διαθέσιμων θέσεων και το κόστος\n"); System.out.println("Java THClient book <hostname> <type> <number> <name>: Κράτηση θέσεων\n"); System.out.println("Java THClient guest <hostname>: Εκτύπωση λίστας πελατών που έχουν κάνει κράτηση\n"); System.out.println("Java THClient cancel <hostname> <type> <number> <name>: Ακύρωση κράτησης\n"); } }
10217_3
package gui; import DataIngestion.DBIntegrator; import DataIngestion.DBIntegrator.AggregatedDrawDataByMonth; import java.awt.BasicStroke; import java.awt.Color; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.DefaultCategoryDataset; import java.awt.Dimension; import java.awt.Point; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.swing.JDialog; import javax.swing.JPanel; import org.jfree.chart.ChartMouseEvent; import org.jfree.chart.ChartMouseListener; import org.jfree.chart.StandardChartTheme; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.chart.renderer.category.StandardBarPainter; import org.jfree.chart.ui.RectangleInsets; public class MonthsBarChart extends javax.swing.JPanel { private String fromDate; private String toDate; private String monthName; private int gameID; private String year; private HashMap<Integer, String> monthTable; JPanel sourcePanel; public MonthsBarChart(int gameID, String fromDate, String toDate, String monthName, JPanel sourcePanel) throws SQLException { this.gameID = gameID; this.fromDate = fromDate; this.toDate = toDate; this.monthName = monthName; this.year = fromDate.substring(0, 4); monthTable = new HashMap<>(); this.sourcePanel = sourcePanel; initMonthMap(); initUI(); } private void initUI() throws SQLException { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); List<AggregatedDrawDataByMonth> aggregatedDrawDataByMonthList = new ArrayList<>(); //Prepare data set aggregatedDrawDataByMonthList = DBIntegrator.getAggregatedDrawDataByMonth(gameID, fromDate, toDate); for (AggregatedDrawDataByMonth aggregatedDrawDataByMonth : aggregatedDrawDataByMonthList) { dataset.addValue(aggregatedDrawDataByMonth.getPayoutAmount(), "Μήνας", String.valueOf(aggregatedDrawDataByMonth.getMonthID())); } //Create chart JFreeChart chart = ChartFactory.createBarChart( "Μήνας", //Chart Title "",//Κληρώσεις", // Category axis "",//Κέρδη", // Value axis dataset, PlotOrientation.VERTICAL, true, true, false ); //Trim chart chart.removeLegend(); chart.setTitle(""); StandardChartTheme theme = (StandardChartTheme)org.jfree.chart.StandardChartTheme.createJFreeTheme(); theme.setRangeGridlinePaint( new java.awt.Color(192, 192, 192)); theme.setPlotBackgroundPaint( Color.white ); theme.setChartBackgroundPaint( Color.white ); theme.setGridBandPaint( Color.red ); theme.setAxisOffset( new RectangleInsets(0,0,0,0) ); theme.setBarPainter(new StandardBarPainter()); theme.apply( chart ); chart.getCategoryPlot().setOutlineVisible( false ); chart.getCategoryPlot().getRangeAxis().setAxisLineVisible( false ); chart.getCategoryPlot().getRangeAxis().setTickMarksVisible( false ); chart.getCategoryPlot().setRangeGridlineStroke( new BasicStroke() ); chart.setTextAntiAlias( true ); chart.setAntiAlias( true ); chart.getCategoryPlot().getRenderer().setSeriesPaint( 0, new java.awt.Color(50, 122, 194)); BarRenderer renderer = (BarRenderer) chart.getCategoryPlot().getRenderer(); renderer.setShadowVisible( true ); renderer.setShadowXOffset( 2 ); renderer.setShadowYOffset( 0 ); renderer.setShadowPaint( new java.awt.Color(192, 192, 192) ); System.out.println(aggregatedDrawDataByMonthList.size()); if (aggregatedDrawDataByMonthList.size()<4){ renderer.setMaximumBarWidth(0.2); } else if(aggregatedDrawDataByMonthList.size()<7){ renderer.setMaximumBarWidth(0.1); } else{ renderer.setMaximumBarWidth(0.06); } ChartPanel cp = new ChartPanel(chart) { @Override public Dimension getPreferredSize() { return new Dimension(650, 150); } }; cp.setMouseWheelEnabled(true); //Add on click listener to perform drill down cp.addChartMouseListener(new ChartMouseListener() { public void chartMouseClicked(ChartMouseEvent e) { //Drill Down to Month DiplayDataByDrawFrame diplayDataFrame = new DiplayDataByDrawFrame(); diplayDataFrame.setYear(year); diplayDataFrame.setMonth(getSelectedMonth(e.getEntity().getToolTipText())); diplayDataFrame.execForm(); final JDialog frame = new JDialog(diplayDataFrame, "Προβολή Δεδομένων Τζόκερ ανα μήνα", true); frame.setUndecorated(true); // <-- the title bar is removed here frame.getContentPane().add(diplayDataFrame.getContentPane()); frame.setResizable(false); frame.pack(); Point point = sourcePanel.getLocationOnScreen(); frame.setLocation(new Point(point.x, point.y)); frame.setVisible(true); } public void chartMouseMoved(ChartMouseEvent e) { } }); add(cp); } //Inditify Selected month and return it to client private int getSelectedMonth(String tooltipText) { //Get Month String[] month = tooltipText.split(","); int index = month[1].indexOf(')'); String res = month[1].substring(1, index); int ss = Integer.parseInt(res.trim()); return ss; } private void initMonthMap() { monthTable.put(1, "Ιανουάριος"); monthTable.put(2, "Φεβρουάριος"); monthTable.put(3, "Μάρτιος"); monthTable.put(4, "Απρίλιος"); monthTable.put(5, "Μάιος"); monthTable.put(6, "Ιούνιος"); monthTable.put(7, "Ιούλιος"); monthTable.put(8, "Αύγουστος"); monthTable.put(9, "Σεπτέμβριος"); monthTable.put(10, "Οκτώβριος"); monthTable.put(11, "Νοέμβριος"); monthTable.put(12, "Δεκέμβριος"); } }
PanosEko/JokerStats
JokerStats/src/gui/MonthsBarChart.java
1,713
//Κληρώσεις", // Category axis
line_comment
el
package gui; import DataIngestion.DBIntegrator; import DataIngestion.DBIntegrator.AggregatedDrawDataByMonth; import java.awt.BasicStroke; import java.awt.Color; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.DefaultCategoryDataset; import java.awt.Dimension; import java.awt.Point; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.swing.JDialog; import javax.swing.JPanel; import org.jfree.chart.ChartMouseEvent; import org.jfree.chart.ChartMouseListener; import org.jfree.chart.StandardChartTheme; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.chart.renderer.category.StandardBarPainter; import org.jfree.chart.ui.RectangleInsets; public class MonthsBarChart extends javax.swing.JPanel { private String fromDate; private String toDate; private String monthName; private int gameID; private String year; private HashMap<Integer, String> monthTable; JPanel sourcePanel; public MonthsBarChart(int gameID, String fromDate, String toDate, String monthName, JPanel sourcePanel) throws SQLException { this.gameID = gameID; this.fromDate = fromDate; this.toDate = toDate; this.monthName = monthName; this.year = fromDate.substring(0, 4); monthTable = new HashMap<>(); this.sourcePanel = sourcePanel; initMonthMap(); initUI(); } private void initUI() throws SQLException { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); List<AggregatedDrawDataByMonth> aggregatedDrawDataByMonthList = new ArrayList<>(); //Prepare data set aggregatedDrawDataByMonthList = DBIntegrator.getAggregatedDrawDataByMonth(gameID, fromDate, toDate); for (AggregatedDrawDataByMonth aggregatedDrawDataByMonth : aggregatedDrawDataByMonthList) { dataset.addValue(aggregatedDrawDataByMonth.getPayoutAmount(), "Μήνας", String.valueOf(aggregatedDrawDataByMonth.getMonthID())); } //Create chart JFreeChart chart = ChartFactory.createBarChart( "Μήνας", //Chart Title "",//Κληρώσεις", //<SUF> "",//Κέρδη", // Value axis dataset, PlotOrientation.VERTICAL, true, true, false ); //Trim chart chart.removeLegend(); chart.setTitle(""); StandardChartTheme theme = (StandardChartTheme)org.jfree.chart.StandardChartTheme.createJFreeTheme(); theme.setRangeGridlinePaint( new java.awt.Color(192, 192, 192)); theme.setPlotBackgroundPaint( Color.white ); theme.setChartBackgroundPaint( Color.white ); theme.setGridBandPaint( Color.red ); theme.setAxisOffset( new RectangleInsets(0,0,0,0) ); theme.setBarPainter(new StandardBarPainter()); theme.apply( chart ); chart.getCategoryPlot().setOutlineVisible( false ); chart.getCategoryPlot().getRangeAxis().setAxisLineVisible( false ); chart.getCategoryPlot().getRangeAxis().setTickMarksVisible( false ); chart.getCategoryPlot().setRangeGridlineStroke( new BasicStroke() ); chart.setTextAntiAlias( true ); chart.setAntiAlias( true ); chart.getCategoryPlot().getRenderer().setSeriesPaint( 0, new java.awt.Color(50, 122, 194)); BarRenderer renderer = (BarRenderer) chart.getCategoryPlot().getRenderer(); renderer.setShadowVisible( true ); renderer.setShadowXOffset( 2 ); renderer.setShadowYOffset( 0 ); renderer.setShadowPaint( new java.awt.Color(192, 192, 192) ); System.out.println(aggregatedDrawDataByMonthList.size()); if (aggregatedDrawDataByMonthList.size()<4){ renderer.setMaximumBarWidth(0.2); } else if(aggregatedDrawDataByMonthList.size()<7){ renderer.setMaximumBarWidth(0.1); } else{ renderer.setMaximumBarWidth(0.06); } ChartPanel cp = new ChartPanel(chart) { @Override public Dimension getPreferredSize() { return new Dimension(650, 150); } }; cp.setMouseWheelEnabled(true); //Add on click listener to perform drill down cp.addChartMouseListener(new ChartMouseListener() { public void chartMouseClicked(ChartMouseEvent e) { //Drill Down to Month DiplayDataByDrawFrame diplayDataFrame = new DiplayDataByDrawFrame(); diplayDataFrame.setYear(year); diplayDataFrame.setMonth(getSelectedMonth(e.getEntity().getToolTipText())); diplayDataFrame.execForm(); final JDialog frame = new JDialog(diplayDataFrame, "Προβολή Δεδομένων Τζόκερ ανα μήνα", true); frame.setUndecorated(true); // <-- the title bar is removed here frame.getContentPane().add(diplayDataFrame.getContentPane()); frame.setResizable(false); frame.pack(); Point point = sourcePanel.getLocationOnScreen(); frame.setLocation(new Point(point.x, point.y)); frame.setVisible(true); } public void chartMouseMoved(ChartMouseEvent e) { } }); add(cp); } //Inditify Selected month and return it to client private int getSelectedMonth(String tooltipText) { //Get Month String[] month = tooltipText.split(","); int index = month[1].indexOf(')'); String res = month[1].substring(1, index); int ss = Integer.parseInt(res.trim()); return ss; } private void initMonthMap() { monthTable.put(1, "Ιανουάριος"); monthTable.put(2, "Φεβρουάριος"); monthTable.put(3, "Μάρτιος"); monthTable.put(4, "Απρίλιος"); monthTable.put(5, "Μάιος"); monthTable.put(6, "Ιούνιος"); monthTable.put(7, "Ιούλιος"); monthTable.put(8, "Αύγουστος"); monthTable.put(9, "Σεπτέμβριος"); monthTable.put(10, "Οκτώβριος"); monthTable.put(11, "Νοέμβριος"); monthTable.put(12, "Δεκέμβριος"); } }
17056_9
package com.fsqdataapp; import com.googlecode.objectify.*; import static com.fsqdataapp.OfyService.ofy; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.*; import java.util.*; import java.util.regex.*; import com.google.gson.*; // Extend HttpServlet class public class TrainServlet extends HttpServlet { private String message; public boolean FILTER_STOP_WORDS = true; // this gets set in main() public List<String> stopList = readFile(new File("data/words.stop")); public int numFolds = 10; public void init() throws ServletException { // Do required initialization message = "Hello World"; } private List<String> readFile(File f) { try { StringBuilder contents = new StringBuilder(); BufferedReader input = new BufferedReader(new FileReader(f)); for(String line = input.readLine(); line != null; line = input.readLine()) { contents.append(line); contents.append("\n"); } input.close(); return segmentWords(contents.toString()); } catch(IOException e) { e.printStackTrace(); System.exit(1); return null; } } private List<String> segmentWords(String s) { List<String> ret = new ArrayList<String>(); // Print string before segmentation // System.out.println(s); // Break string into words for (String word: preprocessString(s)) { if(word.length() > 0) { ret.add(word); } } // Print string after segmentation // System.out.println(ret); return ret; } private String[] preprocessString(String s) { s = s.toLowerCase(); // remove numbers // s = s.replaceAll("[0-9]",""); // remove prices s = s.replaceAll("\\^(€+)",""); // remove greek diacritics cause not everybody uses them :D s = s.replaceAll("ϋ","υ").replaceAll("ϊ","ι"); s = s.replaceAll("ΰ","υ").replaceAll("ΐ","ι"); s = s.replaceAll("ώ","ω").replaceAll("ύ","υ").replaceAll("ή","η").replaceAll("ί","ι").replaceAll("έ","ε").replaceAll("ό","ο").replaceAll("ά","α").replaceAll("ς","σ"); // Character ' s = s.replace("\\u0027",""); // Character & s = s.replace("\\u0026",""); // Emojis s = s.replaceAll(":\\)","☺").replaceAll(":-\\)","☺").replaceAll(":D","☺").replaceAll(":-D","☺").replaceAll(":P","☺").replaceAll(":-P","☺").replaceAll(";\\)","☺").replaceAll(";-\\)","☺"); s = s.replaceAll(";\\(","☹").replaceAll(";-\\(","☹").replaceAll(":\\(","☹").replaceAll(":-\\(","☹").replaceAll(":/","☹").replaceAll(":-/","☹"); // remove multiple occurances of the same character (ooooo's and aaaaa's, but no less that 3, so that we won't mess with words like good, book etc) s = s.replaceAll("(.)\\1\\1+","$1"); // Greek spelling // s = s.replaceAll("(ει|η|οι|υι|υ)","ι"); // s = s.replaceAll("ω","ο"); // s = s.replaceAll("αι","ε"); String[] words = s.replaceAll("^[~^,.:!();\'\"\\s]+", "").split("[~^,.:!();\'\"\\s]+"); int i = 0; for (String word: words) { // Stemming for greek words word = word.replaceAll("(η|ησ|ην|ον|ου|ο|οσ|ικο|ιο|ηση|αμε|ει|εις|ιζει|ασ|μενοσ|μενη|μενεσ|σ|αση)$",""); // Stemming for english word = word.replaceAll("(ious|ely|es|ice|ful|fully)$",""); words[i] = word; i++; } return words; } private List<TrainSplit> buildSplits(List<String> args) { // Get the directory with the dataset, in which the pos/neg directories are File trainDir = new File(args.get(0)); // Create the splits List<TrainSplit> splits = new ArrayList<TrainSplit>(); // System.out.println("[INFO]\tPerforming 10-fold cross-validation on data set: "+args.get(0)); // A list with all the files for splitting List<File> files = new ArrayList<File>(); for (File dir: trainDir.listFiles()) { List<File> dirList = Arrays.asList(dir.listFiles()); for (File f: dirList) { files.add(f); } } splits = getFolds(files); return splits; } private List<File> buildDataset(List<String> args) { // Get the directory with the dataset, in which the pos/neg directories are File trainDir = new File(args.get(0)); // System.out.println("[INFO]\tPerforming 10-fold cross-validation on data set: "+args.get(0)); // A list with all the files for splitting List<File> files = new ArrayList<File>(); for (File dir: trainDir.listFiles()) { List<File> dirList = Arrays.asList(dir.listFiles()); for (File f: dirList) { files.add(f); } } return files; } public List<TrainSplit> getFolds(List<File> files) { List<TrainSplit> splits = new ArrayList<TrainSplit>(); for (Integer fold=0; fold<numFolds; fold++ ) { TrainSplit split = new TrainSplit(); for (File file: files) { int endOfName = file.getName().length(); // Based on the names of the comments of the dataset used for training, the 5th character from the end is a 0-9 number // which can be used to grab one tenth of the comments to create the testset for each fold. if( file.getName().subSequence(endOfName-5,endOfName-4).equals(fold.toString()) ) { split.test.add(file); } else { split.train.add(file); } } splits.add(split); } return splits; } public List<String> filterStopWords(List<String> words) { List<String> filtered = new ArrayList<String>(); for (String word :words) { if (!stopList.contains(word)) { filtered.add(word); } } return filtered; } public void printSplit(TrainSplit split) { // System.out.println("\t[INFO]\tSplit's train set length = " + split.train.size()); for (File file: split.train) { // System.out.println(file.getName()); } // System.out.println("\t[INFO]\tSplit's test set length = " + split.test.size()); for (File file: split.test) { // System.out.println(file.getName()); List<String> words = readFile(file); if (FILTER_STOP_WORDS) { words = filterStopWords(words); } // System.out.println(words); } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<String> dataset = new ArrayList<String>(); // First, set response content type. In this case we know it's JSON response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); // Prepare the server output writer PrintWriter servletOutput = response.getWriter(); servletOutput.println("Hi there, I'm the Servlet that trains the classifier"); // Define the dataset dataset.add("data/venuetrack-train"); servletOutput.println("[INFO]\tStop words filtering = "+FILTER_STOP_WORDS); // Build the train splits for 10-fold cross-validation // List<TrainSplit> splits = buildSplits(dataset); // double avgAccuracy = 0.0; // int fold = 0; // // for(TrainSplit split: splits) { // // servletOutput.println("[INFO]\tFold " + fold); // // // Use printSplit function for testing purposes only // // printSplit(split); // // NaiveBayesClassifier classifier = new NaiveBayesClassifier(); // double accuracy = 0.0; // // for(File file: split.train) { // String klass = file.getParentFile().getName(); // List<String> words = readFile(file); // if (FILTER_STOP_WORDS) { // words = filterStopWords(words); // } // classifier.addExample(klass,words); // } // // for (File file : split.test) { // String klass = file.getParentFile().getName(); // List<String> words = readFile(file); // if (FILTER_STOP_WORDS) { // words = filterStopWords(words); // } // String guess = classifier.classify(words); // if(klass.equals(guess)) { // accuracy++; // } // } // accuracy = accuracy/split.test.size(); // avgAccuracy += accuracy; // servletOutput.println("[INFO]\tFold " + fold + " Accuracy: " + accuracy); // fold += 1; // } // avgAccuracy = avgAccuracy / numFolds; // servletOutput.println("[INFO]\tAccuracy: " + avgAccuracy); NaiveBayesClassifier classifier = new NaiveBayesClassifier("final"); List<File> datasetFiles = buildDataset(dataset); int i = 0; for(File file: datasetFiles) { i++; String klass = file.getParentFile().getName(); List<String> words = readFile(file); if (FILTER_STOP_WORDS) { words = filterStopWords(words); } classifier.addExample(klass,words); // System.out.println("[INFO]\t Add example: " + i + " which is " + klass); } ofy().save().entity(classifier).now(); // Close the output session servletOutput.close(); } public void destroy() { // do nothing. } }
ParisZX/venuetrack
src/main/java/com/fsqdataapp/TrainServlet.java
2,512
// s = s.replaceAll("(ει|η|οι|υι|υ)","ι");
line_comment
el
package com.fsqdataapp; import com.googlecode.objectify.*; import static com.fsqdataapp.OfyService.ofy; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.*; import java.util.*; import java.util.regex.*; import com.google.gson.*; // Extend HttpServlet class public class TrainServlet extends HttpServlet { private String message; public boolean FILTER_STOP_WORDS = true; // this gets set in main() public List<String> stopList = readFile(new File("data/words.stop")); public int numFolds = 10; public void init() throws ServletException { // Do required initialization message = "Hello World"; } private List<String> readFile(File f) { try { StringBuilder contents = new StringBuilder(); BufferedReader input = new BufferedReader(new FileReader(f)); for(String line = input.readLine(); line != null; line = input.readLine()) { contents.append(line); contents.append("\n"); } input.close(); return segmentWords(contents.toString()); } catch(IOException e) { e.printStackTrace(); System.exit(1); return null; } } private List<String> segmentWords(String s) { List<String> ret = new ArrayList<String>(); // Print string before segmentation // System.out.println(s); // Break string into words for (String word: preprocessString(s)) { if(word.length() > 0) { ret.add(word); } } // Print string after segmentation // System.out.println(ret); return ret; } private String[] preprocessString(String s) { s = s.toLowerCase(); // remove numbers // s = s.replaceAll("[0-9]",""); // remove prices s = s.replaceAll("\\^(€+)",""); // remove greek diacritics cause not everybody uses them :D s = s.replaceAll("ϋ","υ").replaceAll("ϊ","ι"); s = s.replaceAll("ΰ","υ").replaceAll("ΐ","ι"); s = s.replaceAll("ώ","ω").replaceAll("ύ","υ").replaceAll("ή","η").replaceAll("ί","ι").replaceAll("έ","ε").replaceAll("ό","ο").replaceAll("ά","α").replaceAll("ς","σ"); // Character ' s = s.replace("\\u0027",""); // Character & s = s.replace("\\u0026",""); // Emojis s = s.replaceAll(":\\)","☺").replaceAll(":-\\)","☺").replaceAll(":D","☺").replaceAll(":-D","☺").replaceAll(":P","☺").replaceAll(":-P","☺").replaceAll(";\\)","☺").replaceAll(";-\\)","☺"); s = s.replaceAll(";\\(","☹").replaceAll(";-\\(","☹").replaceAll(":\\(","☹").replaceAll(":-\\(","☹").replaceAll(":/","☹").replaceAll(":-/","☹"); // remove multiple occurances of the same character (ooooo's and aaaaa's, but no less that 3, so that we won't mess with words like good, book etc) s = s.replaceAll("(.)\\1\\1+","$1"); // Greek spelling // s =<SUF> // s = s.replaceAll("ω","ο"); // s = s.replaceAll("αι","ε"); String[] words = s.replaceAll("^[~^,.:!();\'\"\\s]+", "").split("[~^,.:!();\'\"\\s]+"); int i = 0; for (String word: words) { // Stemming for greek words word = word.replaceAll("(η|ησ|ην|ον|ου|ο|οσ|ικο|ιο|ηση|αμε|ει|εις|ιζει|ασ|μενοσ|μενη|μενεσ|σ|αση)$",""); // Stemming for english word = word.replaceAll("(ious|ely|es|ice|ful|fully)$",""); words[i] = word; i++; } return words; } private List<TrainSplit> buildSplits(List<String> args) { // Get the directory with the dataset, in which the pos/neg directories are File trainDir = new File(args.get(0)); // Create the splits List<TrainSplit> splits = new ArrayList<TrainSplit>(); // System.out.println("[INFO]\tPerforming 10-fold cross-validation on data set: "+args.get(0)); // A list with all the files for splitting List<File> files = new ArrayList<File>(); for (File dir: trainDir.listFiles()) { List<File> dirList = Arrays.asList(dir.listFiles()); for (File f: dirList) { files.add(f); } } splits = getFolds(files); return splits; } private List<File> buildDataset(List<String> args) { // Get the directory with the dataset, in which the pos/neg directories are File trainDir = new File(args.get(0)); // System.out.println("[INFO]\tPerforming 10-fold cross-validation on data set: "+args.get(0)); // A list with all the files for splitting List<File> files = new ArrayList<File>(); for (File dir: trainDir.listFiles()) { List<File> dirList = Arrays.asList(dir.listFiles()); for (File f: dirList) { files.add(f); } } return files; } public List<TrainSplit> getFolds(List<File> files) { List<TrainSplit> splits = new ArrayList<TrainSplit>(); for (Integer fold=0; fold<numFolds; fold++ ) { TrainSplit split = new TrainSplit(); for (File file: files) { int endOfName = file.getName().length(); // Based on the names of the comments of the dataset used for training, the 5th character from the end is a 0-9 number // which can be used to grab one tenth of the comments to create the testset for each fold. if( file.getName().subSequence(endOfName-5,endOfName-4).equals(fold.toString()) ) { split.test.add(file); } else { split.train.add(file); } } splits.add(split); } return splits; } public List<String> filterStopWords(List<String> words) { List<String> filtered = new ArrayList<String>(); for (String word :words) { if (!stopList.contains(word)) { filtered.add(word); } } return filtered; } public void printSplit(TrainSplit split) { // System.out.println("\t[INFO]\tSplit's train set length = " + split.train.size()); for (File file: split.train) { // System.out.println(file.getName()); } // System.out.println("\t[INFO]\tSplit's test set length = " + split.test.size()); for (File file: split.test) { // System.out.println(file.getName()); List<String> words = readFile(file); if (FILTER_STOP_WORDS) { words = filterStopWords(words); } // System.out.println(words); } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<String> dataset = new ArrayList<String>(); // First, set response content type. In this case we know it's JSON response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); // Prepare the server output writer PrintWriter servletOutput = response.getWriter(); servletOutput.println("Hi there, I'm the Servlet that trains the classifier"); // Define the dataset dataset.add("data/venuetrack-train"); servletOutput.println("[INFO]\tStop words filtering = "+FILTER_STOP_WORDS); // Build the train splits for 10-fold cross-validation // List<TrainSplit> splits = buildSplits(dataset); // double avgAccuracy = 0.0; // int fold = 0; // // for(TrainSplit split: splits) { // // servletOutput.println("[INFO]\tFold " + fold); // // // Use printSplit function for testing purposes only // // printSplit(split); // // NaiveBayesClassifier classifier = new NaiveBayesClassifier(); // double accuracy = 0.0; // // for(File file: split.train) { // String klass = file.getParentFile().getName(); // List<String> words = readFile(file); // if (FILTER_STOP_WORDS) { // words = filterStopWords(words); // } // classifier.addExample(klass,words); // } // // for (File file : split.test) { // String klass = file.getParentFile().getName(); // List<String> words = readFile(file); // if (FILTER_STOP_WORDS) { // words = filterStopWords(words); // } // String guess = classifier.classify(words); // if(klass.equals(guess)) { // accuracy++; // } // } // accuracy = accuracy/split.test.size(); // avgAccuracy += accuracy; // servletOutput.println("[INFO]\tFold " + fold + " Accuracy: " + accuracy); // fold += 1; // } // avgAccuracy = avgAccuracy / numFolds; // servletOutput.println("[INFO]\tAccuracy: " + avgAccuracy); NaiveBayesClassifier classifier = new NaiveBayesClassifier("final"); List<File> datasetFiles = buildDataset(dataset); int i = 0; for(File file: datasetFiles) { i++; String klass = file.getParentFile().getName(); List<String> words = readFile(file); if (FILTER_STOP_WORDS) { words = filterStopWords(words); } classifier.addExample(klass,words); // System.out.println("[INFO]\t Add example: " + i + " which is " + klass); } ofy().save().entity(classifier).now(); // Close the output session servletOutput.close(); } public void destroy() { // do nothing. } }
5435_34
package com.unipi.p15013p15120.kastropoliteiesv2; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Toast; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; import com.google.firebase.auth.UserProfileChangeRequest; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; //othoni syndesis public class LoginSignUpPage extends AppCompatActivity { //oncreate GoogleSignInClient mGoogleSignInClient; ImageButton signinGoogle; private FirebaseAuth auth; private SharedPreferences sp; FirebaseAuth.AuthStateListener mAuthStateListener; private static final String TAG = "LoginSignUpPage"; Intent i; // on create + emailVer String where, answer, answer2; EditText email, pass; //checkQ variables String cuid; FirebaseDatabase mFirebaseDatabase; ValueEventListener listener; //deleteAccount variable too DatabaseReference myRef; //Am I loggen in? NO, if i'm here @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTheme(R.style.SplashScreenAndLoginTheme); setContentView(R.layout.login_sign_up_page); //den eimai se account google akomi sp = getSharedPreferences("account_google", MODE_PRIVATE); sp.edit().putBoolean("account_google", false).apply(); //Where would I been logged in? In Email if i do not click Google Sign In Button where = "email"; // Initialize Firebase Auth auth = FirebaseAuth.getInstance(); //Google Button for Sign In signinGoogle = findViewById(R.id.signingoogle); //Configurations for Google Sign In GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) //.requestIdToken(default_web_client_id) .requestIdToken("894264305491-2hgvfhruqtnmsp6f9sefcbmdt97n8lpo.apps.googleusercontent.com") .requestEmail() .build(); mGoogleSignInClient = GoogleSignIn.getClient(getApplicationContext(), gso); //elegxw an o xristis ehei apantisei sto erwthmatologio mAuthStateListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { checkForUser(); } }; //Google Sign In signinGoogle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { signIn(); } }); //Edit texts and Buttons for Email email = findViewById(R.id.email_prompt); pass = findViewById(R.id.password_prompt); Button signin_email = findViewById(R.id.login); Button signup_email = findViewById(R.id.signupWelcome); Button forgot = findViewById(R.id.forgotpass); //Sign in using email and password signin_email.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //an ehw pliktrologhsei stoixeia tote na ginei i syndesh if (!email.getText().toString().equals("") && !pass.getText().toString().equals("")) { firebaseAuthEmailSignIn(email.getText().toString(), pass.getText().toString()); //na elegxthei o xristis ws pros to erwthmatologio checkForUser(); } else Toast.makeText(getApplicationContext(), "Παρακαλώ εισάγετε τα στοιχεία σας", Toast.LENGTH_SHORT).show(); } }); //Sign Up using email and password signup_email.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { i = new Intent(getApplicationContext(), SignUpForm.class); startActivity(i); } }); //Forgot Password for Email forgot.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Dialog2 dialog = new Dialog2("Εισάγετε e-mail","forgot_pass"); dialog.show(getSupportFragmentManager(),"forgot_pass"); } }); } //den hrisimopoieitai i methodos email verification public void emailVerification() { try { FirebaseAuth.getInstance().getCurrentUser().sendEmailVerification() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "Email sent."); } } }); } catch (NullPointerException ex) { } } //rename DATA se pinaka questionnaire public void renameData() { mFirebaseDatabase = FirebaseDatabase.getInstance(); myRef = mFirebaseDatabase.getReference(); FirebaseUser currentUser = auth.getCurrentUser(); cuid = currentUser.getUid(); myRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot ds : dataSnapshot.child("questionnaire").getChildren()) { if (cuid.equals(ds.getKey())) myRef.child("questionnaire").child(cuid).setValue("new"); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } //se kathe periptwsh den tha thelame na paei pisw o xristis apo tin login-sign up selida //auto giati synithws i prohgoumeni activity apo tin login einai kati pou sxetizetai me kapoion xristi pou htan syndedemenos. //an xreiastei o xristis na epistrepsei sthn arxiki tou kinhtou tou, apla pataei to mesaio koubi! @Override public void onBackPressed() { //super.onBackPressed(); } //den diagrafoume dedomena public void deleteAccount() { cuid = FirebaseAuth.getInstance().getCurrentUser().getUid(); FirebaseAuth.getInstance().getCurrentUser().delete() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "User account deleted." + cuid); } } }); /*if (FirebaseAuth.getInstance().getCurrentUser()!= null) { //You need to get here the token you saved at logging-in time. FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( LoginSignUpPage.this, new OnSuccessListener<InstanceIdResult>() { @Override public void onSuccess(InstanceIdResult instanceIdResult) { String newToken = instanceIdResult.getToken(); Log.e("newToken",newToken); token = newToken; } }); AuthCredential credential; //This means you didn't have the token because user used like Facebook Sign-in method. if (token == null) { Log.e("token","null"); credential = EmailAuthProvider.getCredential(FirebaseAuth.getInstance().getCurrentUser().getEmail(), pass); } else { Log.e("token","not null"); //Doesn't matter if it was Facebook Sign-in or others. It will always work using GoogleAuthProvider for whatever the provider. credential = GoogleAuthProvider.getCredential(token, null); } //We have to reauthenticate user because we don't know how long //it was the sign-in. Calling reauthenticate, will update the //user login and prevent FirebaseException (CREDENTIAL_TOO_OLD_LOGIN_AGAIN) on user.delete() FirebaseAuth.getInstance().getCurrentUser().reauthenticate(credential) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { FirebaseAuth.getInstance().getCurrentUser().delete() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "User account deleted."); signOutFirebase(); signOutGoogle(); //makeToast(getApplicationContext(), "Ο λογαριασμός σου διαγράφτηκε οριστικά. Ελπίζουμε να επιστρέψετε κάποια στιγμή."); //FirebaseDatabase.getInstance().getReference().child("questionnaire").child(email_delete).re //FirebaseDatabase.getInstance().getReference().child("ratings").child(email_delete).removeValue(); //myRef.child("questionnaire").child("alexelement22@gmailcom").removeValue(); } } }); } }); }*/ } public void forgotPass(final String email) { //auth.setLanguageCode("en"); orismos glwssas analoga th glwssa efarmoghs FirebaseAuth.getInstance().sendPasswordResetEmail(email) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "Email sent."); //Toast.makeText(MainActivity.this,"Ο κωδικός πρόσβασης άλλαξε επιτυχώς για τον " + email.toString(), Toast.LENGTH_LONG).show(); } else { Log.d(TAG, task.getException().toString()); //Toast.makeText(MainActivity.this,"Ο κωδικός πρόσβασης δεν άλλαξε. Παρακαλώ ξαναπροσπάθησε", Toast.LENGTH_SHORT).show(); } } }); } //methodos eggrafis xristis stin FIREBASE AUTHENTICATION public void firebaseAuthEmailSignUp(String email, String password, final String name) { FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "createUserWithEmail:success"); if (!name.equals("")) { UserProfileChangeRequest profUpd = new UserProfileChangeRequest.Builder() .setDisplayName(name).build(); FirebaseAuth.getInstance().getCurrentUser().updateProfile(profUpd) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "User profile updated."); } } }); } } else { // If sign in fails, display a message to the user. Log.w(TAG, "createUserWithEmail:failure", task.getException()); } } }); } private void firebaseAuthEmailSignIn(String email, String password) { if (!email.equals("") && !password.equals("") && !(password.length()<6)) { if (isEmailValid(email)) { auth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithEmail:success"); FirebaseUser user = auth.getCurrentUser(); } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithEmail:failure", task.getException()); makeToast(getApplicationContext(), "Ο κωδικός πρόσβασής σας είναι λάθος ή δεν υπάρχει λογαριασμός με αυτό το email. Παρακαλώ ξαναπροσπαθήστε. Σε περίπτωση που ξεχάσατε τον κωδικό σας, πατήστε στο 'Ξέχασες τον κωδικό;'. Αν το πρόβλημα επιμένει, παρακαλώ κάντε επανεκκίνηση την εφαρμογή."); } // ... } }); } else makeToast(getApplicationContext(),"Το email που εισάγατε δεν είναι σε σωστή μορφή"); } else if (password.length()<6) makeToast(getApplicationContext(),"Ο κωδικός πρόσβασης πρέπει να είναι μεγαλύτερος ή ίσος με 6 ψηφία"); else makeToast(getApplicationContext(),"Παρακαλώ εισάγετε τα στοιχεία σας"); } public boolean isEmailValid(String email) { String regExpn = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$"; CharSequence inputStr = email; Pattern pattern = Pattern.compile(regExpn,Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(inputStr); if(matcher.matches()) return true; else return false; } @Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. GOOGLE auth.addAuthStateListener(mAuthStateListener); if (getIntent() != null) { //signout if (getIntent().hasExtra("where")) { if (getIntent().getStringExtra("where").equals("homepage_signout")) { if (auth.getCurrentUser() != null) { signOutFirebase();// signOutGoogle();//google } } if (getIntent().getStringExtra("where").equals("homepage_delete_account")) { if (auth.getCurrentUser() != null) { deleteAccount(); signOutFirebase(); signOutGoogle();//google } } } }//from TOPOTHESIES CLASS checkForUser(); // updateUI(auth.getCurrentUser()); } private void signIn() { Intent signInIntent = mGoogleSignInClient.getSignInIntent(); //Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, 9001); } private void signOutFirebase() { FirebaseAuth.getInstance().signOut(); //makeToast(LoginSignUpPage.this, "Αποσύνδεση χρήστη επιτυχής!"); } //check if i logged out from google private void signOutGoogle() { // Firebase sign out //auth.signOut(); // Google sign out mGoogleSignInClient.signOut().addOnCompleteListener(this, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { //updateUI(null); makeToast(getApplicationContext(), "Αποσύνδεση χρήστη επιτυχής!"); } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); if (requestCode == 9001) { Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); try { // Google Sign In was successful, authenticate with Firebase GoogleSignInAccount account = task.getResult(ApiException.class); firebaseAuthWithGoogle(account); } catch (ApiException e) { // Google Sign In failed, update UI appropriately Log.w(TAG, "Google sign in failed", e); //updateUI(null); makeToast(getApplicationContext(), "Κάτι πήγε λάθος, σας παρακαλώ ξαναπροσπαθήστε. Σε περίπτωση που το πρόβλημα επιμένει, παρακαλώ κάντε επανεκκίνηση την εφαρμογή - GOOGLE SIGN IN FAILED"); } } } private void firebaseAuthWithGoogle(GoogleSignInAccount account) { AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null); auth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithCredential:success"); FirebaseUser user = auth.getCurrentUser(); Log.w(TAG, "signInWithCredential:success", task.getException()); sp.edit().putBoolean("account_google", true).apply(); where = "google"; } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithCredential:failure", task.getException()); makeToast(getApplicationContext(), "Δεν ήταν δυνατή η σύνδεση στον Google λογαριασμό σας, παρακαλώ ξαναπροσπαθήστε"); } } }); } private void checkForUser() { if (auth.getCurrentUser() != null) { checkQ(auth.getCurrentUser()); } } private void checkQ(FirebaseUser currentUser){ cuid = currentUser.getUid(); mFirebaseDatabase = FirebaseDatabase.getInstance(); myRef = mFirebaseDatabase.getReference(); //an o xristis ehei apantisei sto questionnaire, tote phgaine ton stin homepage alliws sto erwthmatologio listener = myRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { boolean found = false; for (DataSnapshot ds : dataSnapshot.child("questionnaire").getChildren()){ if (String.valueOf(ds.getKey()).equals(cuid)){ found = true; break; } } if(!found){ Log.v(TAG,"User has not answered questionnaire!"); Intent intent = new Intent(getApplicationContext(), Questionnaire.class); //efoson ton steilame ekei pou prepei (questionnaire) analambavei allos tin douleia myRef.removeEventListener(listener); startActivity(intent); } else{ Log.v(TAG,"User has answered questionnaire!"); Intent intent = new Intent(getApplicationContext(), HomePage.class); //efoson to ehei apantisei den mas noiazei kati allo myRef.removeEventListener(listener); startActivity(intent); } } @Override public void onCancelled(DatabaseError databaseError) { Log.e("The read failed: " ,databaseError.getMessage()); } }); } public void makeToast (Context c, String t) { Toast.makeText(c, t, Toast.LENGTH_LONG).show(); } }
PetePrattis/Recommendation-System-for-Android-Java-App-that-finds-an-ideal-destination-with-the-kNN-Algorithm
app/src/main/java/com/unipi/p15013p15120/kastropoliteiesv2/LoginSignUpPage.java
5,140
//makeToast(LoginSignUpPage.this, "Αποσύνδεση χρήστη επιτυχής!");
line_comment
el
package com.unipi.p15013p15120.kastropoliteiesv2; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Toast; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; import com.google.firebase.auth.UserProfileChangeRequest; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; //othoni syndesis public class LoginSignUpPage extends AppCompatActivity { //oncreate GoogleSignInClient mGoogleSignInClient; ImageButton signinGoogle; private FirebaseAuth auth; private SharedPreferences sp; FirebaseAuth.AuthStateListener mAuthStateListener; private static final String TAG = "LoginSignUpPage"; Intent i; // on create + emailVer String where, answer, answer2; EditText email, pass; //checkQ variables String cuid; FirebaseDatabase mFirebaseDatabase; ValueEventListener listener; //deleteAccount variable too DatabaseReference myRef; //Am I loggen in? NO, if i'm here @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTheme(R.style.SplashScreenAndLoginTheme); setContentView(R.layout.login_sign_up_page); //den eimai se account google akomi sp = getSharedPreferences("account_google", MODE_PRIVATE); sp.edit().putBoolean("account_google", false).apply(); //Where would I been logged in? In Email if i do not click Google Sign In Button where = "email"; // Initialize Firebase Auth auth = FirebaseAuth.getInstance(); //Google Button for Sign In signinGoogle = findViewById(R.id.signingoogle); //Configurations for Google Sign In GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) //.requestIdToken(default_web_client_id) .requestIdToken("894264305491-2hgvfhruqtnmsp6f9sefcbmdt97n8lpo.apps.googleusercontent.com") .requestEmail() .build(); mGoogleSignInClient = GoogleSignIn.getClient(getApplicationContext(), gso); //elegxw an o xristis ehei apantisei sto erwthmatologio mAuthStateListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { checkForUser(); } }; //Google Sign In signinGoogle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { signIn(); } }); //Edit texts and Buttons for Email email = findViewById(R.id.email_prompt); pass = findViewById(R.id.password_prompt); Button signin_email = findViewById(R.id.login); Button signup_email = findViewById(R.id.signupWelcome); Button forgot = findViewById(R.id.forgotpass); //Sign in using email and password signin_email.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //an ehw pliktrologhsei stoixeia tote na ginei i syndesh if (!email.getText().toString().equals("") && !pass.getText().toString().equals("")) { firebaseAuthEmailSignIn(email.getText().toString(), pass.getText().toString()); //na elegxthei o xristis ws pros to erwthmatologio checkForUser(); } else Toast.makeText(getApplicationContext(), "Παρακαλώ εισάγετε τα στοιχεία σας", Toast.LENGTH_SHORT).show(); } }); //Sign Up using email and password signup_email.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { i = new Intent(getApplicationContext(), SignUpForm.class); startActivity(i); } }); //Forgot Password for Email forgot.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Dialog2 dialog = new Dialog2("Εισάγετε e-mail","forgot_pass"); dialog.show(getSupportFragmentManager(),"forgot_pass"); } }); } //den hrisimopoieitai i methodos email verification public void emailVerification() { try { FirebaseAuth.getInstance().getCurrentUser().sendEmailVerification() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "Email sent."); } } }); } catch (NullPointerException ex) { } } //rename DATA se pinaka questionnaire public void renameData() { mFirebaseDatabase = FirebaseDatabase.getInstance(); myRef = mFirebaseDatabase.getReference(); FirebaseUser currentUser = auth.getCurrentUser(); cuid = currentUser.getUid(); myRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot ds : dataSnapshot.child("questionnaire").getChildren()) { if (cuid.equals(ds.getKey())) myRef.child("questionnaire").child(cuid).setValue("new"); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } //se kathe periptwsh den tha thelame na paei pisw o xristis apo tin login-sign up selida //auto giati synithws i prohgoumeni activity apo tin login einai kati pou sxetizetai me kapoion xristi pou htan syndedemenos. //an xreiastei o xristis na epistrepsei sthn arxiki tou kinhtou tou, apla pataei to mesaio koubi! @Override public void onBackPressed() { //super.onBackPressed(); } //den diagrafoume dedomena public void deleteAccount() { cuid = FirebaseAuth.getInstance().getCurrentUser().getUid(); FirebaseAuth.getInstance().getCurrentUser().delete() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "User account deleted." + cuid); } } }); /*if (FirebaseAuth.getInstance().getCurrentUser()!= null) { //You need to get here the token you saved at logging-in time. FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( LoginSignUpPage.this, new OnSuccessListener<InstanceIdResult>() { @Override public void onSuccess(InstanceIdResult instanceIdResult) { String newToken = instanceIdResult.getToken(); Log.e("newToken",newToken); token = newToken; } }); AuthCredential credential; //This means you didn't have the token because user used like Facebook Sign-in method. if (token == null) { Log.e("token","null"); credential = EmailAuthProvider.getCredential(FirebaseAuth.getInstance().getCurrentUser().getEmail(), pass); } else { Log.e("token","not null"); //Doesn't matter if it was Facebook Sign-in or others. It will always work using GoogleAuthProvider for whatever the provider. credential = GoogleAuthProvider.getCredential(token, null); } //We have to reauthenticate user because we don't know how long //it was the sign-in. Calling reauthenticate, will update the //user login and prevent FirebaseException (CREDENTIAL_TOO_OLD_LOGIN_AGAIN) on user.delete() FirebaseAuth.getInstance().getCurrentUser().reauthenticate(credential) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { FirebaseAuth.getInstance().getCurrentUser().delete() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "User account deleted."); signOutFirebase(); signOutGoogle(); //makeToast(getApplicationContext(), "Ο λογαριασμός σου διαγράφτηκε οριστικά. Ελπίζουμε να επιστρέψετε κάποια στιγμή."); //FirebaseDatabase.getInstance().getReference().child("questionnaire").child(email_delete).re //FirebaseDatabase.getInstance().getReference().child("ratings").child(email_delete).removeValue(); //myRef.child("questionnaire").child("alexelement22@gmailcom").removeValue(); } } }); } }); }*/ } public void forgotPass(final String email) { //auth.setLanguageCode("en"); orismos glwssas analoga th glwssa efarmoghs FirebaseAuth.getInstance().sendPasswordResetEmail(email) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "Email sent."); //Toast.makeText(MainActivity.this,"Ο κωδικός πρόσβασης άλλαξε επιτυχώς για τον " + email.toString(), Toast.LENGTH_LONG).show(); } else { Log.d(TAG, task.getException().toString()); //Toast.makeText(MainActivity.this,"Ο κωδικός πρόσβασης δεν άλλαξε. Παρακαλώ ξαναπροσπάθησε", Toast.LENGTH_SHORT).show(); } } }); } //methodos eggrafis xristis stin FIREBASE AUTHENTICATION public void firebaseAuthEmailSignUp(String email, String password, final String name) { FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "createUserWithEmail:success"); if (!name.equals("")) { UserProfileChangeRequest profUpd = new UserProfileChangeRequest.Builder() .setDisplayName(name).build(); FirebaseAuth.getInstance().getCurrentUser().updateProfile(profUpd) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "User profile updated."); } } }); } } else { // If sign in fails, display a message to the user. Log.w(TAG, "createUserWithEmail:failure", task.getException()); } } }); } private void firebaseAuthEmailSignIn(String email, String password) { if (!email.equals("") && !password.equals("") && !(password.length()<6)) { if (isEmailValid(email)) { auth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithEmail:success"); FirebaseUser user = auth.getCurrentUser(); } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithEmail:failure", task.getException()); makeToast(getApplicationContext(), "Ο κωδικός πρόσβασής σας είναι λάθος ή δεν υπάρχει λογαριασμός με αυτό το email. Παρακαλώ ξαναπροσπαθήστε. Σε περίπτωση που ξεχάσατε τον κωδικό σας, πατήστε στο 'Ξέχασες τον κωδικό;'. Αν το πρόβλημα επιμένει, παρακαλώ κάντε επανεκκίνηση την εφαρμογή."); } // ... } }); } else makeToast(getApplicationContext(),"Το email που εισάγατε δεν είναι σε σωστή μορφή"); } else if (password.length()<6) makeToast(getApplicationContext(),"Ο κωδικός πρόσβασης πρέπει να είναι μεγαλύτερος ή ίσος με 6 ψηφία"); else makeToast(getApplicationContext(),"Παρακαλώ εισάγετε τα στοιχεία σας"); } public boolean isEmailValid(String email) { String regExpn = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$"; CharSequence inputStr = email; Pattern pattern = Pattern.compile(regExpn,Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(inputStr); if(matcher.matches()) return true; else return false; } @Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. GOOGLE auth.addAuthStateListener(mAuthStateListener); if (getIntent() != null) { //signout if (getIntent().hasExtra("where")) { if (getIntent().getStringExtra("where").equals("homepage_signout")) { if (auth.getCurrentUser() != null) { signOutFirebase();// signOutGoogle();//google } } if (getIntent().getStringExtra("where").equals("homepage_delete_account")) { if (auth.getCurrentUser() != null) { deleteAccount(); signOutFirebase(); signOutGoogle();//google } } } }//from TOPOTHESIES CLASS checkForUser(); // updateUI(auth.getCurrentUser()); } private void signIn() { Intent signInIntent = mGoogleSignInClient.getSignInIntent(); //Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, 9001); } private void signOutFirebase() { FirebaseAuth.getInstance().signOut(); //makeToast(LoginSignUpPage.this, "Αποσύνδεση<SUF> } //check if i logged out from google private void signOutGoogle() { // Firebase sign out //auth.signOut(); // Google sign out mGoogleSignInClient.signOut().addOnCompleteListener(this, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { //updateUI(null); makeToast(getApplicationContext(), "Αποσύνδεση χρήστη επιτυχής!"); } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); if (requestCode == 9001) { Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); try { // Google Sign In was successful, authenticate with Firebase GoogleSignInAccount account = task.getResult(ApiException.class); firebaseAuthWithGoogle(account); } catch (ApiException e) { // Google Sign In failed, update UI appropriately Log.w(TAG, "Google sign in failed", e); //updateUI(null); makeToast(getApplicationContext(), "Κάτι πήγε λάθος, σας παρακαλώ ξαναπροσπαθήστε. Σε περίπτωση που το πρόβλημα επιμένει, παρακαλώ κάντε επανεκκίνηση την εφαρμογή - GOOGLE SIGN IN FAILED"); } } } private void firebaseAuthWithGoogle(GoogleSignInAccount account) { AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null); auth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithCredential:success"); FirebaseUser user = auth.getCurrentUser(); Log.w(TAG, "signInWithCredential:success", task.getException()); sp.edit().putBoolean("account_google", true).apply(); where = "google"; } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithCredential:failure", task.getException()); makeToast(getApplicationContext(), "Δεν ήταν δυνατή η σύνδεση στον Google λογαριασμό σας, παρακαλώ ξαναπροσπαθήστε"); } } }); } private void checkForUser() { if (auth.getCurrentUser() != null) { checkQ(auth.getCurrentUser()); } } private void checkQ(FirebaseUser currentUser){ cuid = currentUser.getUid(); mFirebaseDatabase = FirebaseDatabase.getInstance(); myRef = mFirebaseDatabase.getReference(); //an o xristis ehei apantisei sto questionnaire, tote phgaine ton stin homepage alliws sto erwthmatologio listener = myRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { boolean found = false; for (DataSnapshot ds : dataSnapshot.child("questionnaire").getChildren()){ if (String.valueOf(ds.getKey()).equals(cuid)){ found = true; break; } } if(!found){ Log.v(TAG,"User has not answered questionnaire!"); Intent intent = new Intent(getApplicationContext(), Questionnaire.class); //efoson ton steilame ekei pou prepei (questionnaire) analambavei allos tin douleia myRef.removeEventListener(listener); startActivity(intent); } else{ Log.v(TAG,"User has answered questionnaire!"); Intent intent = new Intent(getApplicationContext(), HomePage.class); //efoson to ehei apantisei den mas noiazei kati allo myRef.removeEventListener(listener); startActivity(intent); } } @Override public void onCancelled(DatabaseError databaseError) { Log.e("The read failed: " ,databaseError.getMessage()); } }); } public void makeToast (Context c, String t) { Toast.makeText(c, t, Toast.LENGTH_LONG).show(); } }
40005_0
package jdbc_client; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import java.util.Scanner; /** * * @author Panagiotis Prattis / Παναγιώτης Πράττης */ public class JDBC_CLIENT { public static void main(String[] args) { Connection c = null; Statement stmt=null; ResultSet rs=null; Scanner reader = new Scanner(System.in); System.out.println("Give Password for postgres database:"); String pass = reader.nextLine(); System.out.println(); try { c = DriverManager.getConnection("jdbc:postgresql://Localhost/postgres", "postgres", pass); System.out.println("Opened database successfully\n"); stmt = c.createStatement(); System.out.println("Create statement successfully\n"); System.out.println("These are the queries:\n" + "a) What are the drugs (maximum and minimum number) prescribed. In\n" + "result show quantity and name of drug.\n" + "b) What are the diagnoses of the last week.\n" + "c) What are the doctor's 'X' appointments last month.\n" + "d) Who are the patients who have seen more than one doctor.\n" + "e) From what department have most patients been examined.\n" + "f) What is the average number of patients examined per department.\n" ); String querya="select c.cnt as max_min_counts, c.drug_name \n" + "from\n" + "(\n" + "select count (mf.drug_id) as cnt , d.name as drug_name\n" + "from medicalfolders mf, drugs d\n" + "where mf.drug_id=d.id\n" + "group by d.name\n" + ") c\n" + "where c.cnt=\n" + "(\n" + "select min (e.cnt) from\n" + "(select count (mf.drug_id) as cnt, d.name \n" + "from medicalfolders mf, drugs d\n" + "where mf.drug_id=d.id\n" + "group by d.name) e\n" + ")or\n" + "c.cnt=\n" + "(\n" + "select max (e.cnt) from\n" + "(select count (mf.drug_id) as cnt, d.name \n" + " from medicalfolders mf, drugs d\n" + "where mf.drug_id=d.id\n" + "group by d.name) e\n" + ")"; String queryb="select a.diagnosis, a.t as date\n" + "from appointments a, medicalfolders m\n" + "where a.patientamka=m.patientamka\n" + "and a.diagnosis is not null\n" + "and a.t > (select date(max(t))from appointments) - integer '7'"; // queryc will not be used but its code in executeQuery() will,             // to initialize patient's or doctor's code (amka) correctly because otherwise it will be             // initialized to value of the next line and will not be able to change it String amka=""; String queryc="select p.name as patient_name, p.surname as patient_surname, a.t as date\n" + "from appointments a, doctors d, patients p\n" + "where a.patientamka=p.patientamka and a.doctoramka=d.doctoramka\n" + "and a.t>(select date(max(t))from appointments) - integer '30'\n" + "--and a.t>current_date-30\n" + "and d.doctoramka='"+amka+"'"; String queryd="select p.name as patient_name, p.surname as patient_surname, \n" + "count(distinct doctoramka) as distinct_doctors_count\n" + "from appointments a, patients p\n" + "where a.patientamka=p.patientamka \n" + "group by p.name, p.surname\n" + "having count(*)>1"; String querye="select c.name as most_visited_departments from\n" + "(select dp.name as name, count(a.id) as cnt\n" + "from appointments a, doctors d, departments dp\n" + "where a.doctoramka=d.doctoramka and d.specialty=dp.id\n" + "and a.diagnosis is not null\n" + "group by dp.name) c\n" + "where c.cnt= (select max(e.cnt) from \n" + "(select dp.name as name, count(a.id) as cnt\n" + "from appointments a, doctors d, departments dp\n" + "where a.doctoramka=d.doctoramka and d.specialty=dp.id\n" + "and a.diagnosis is not null\n" + "group by dp.name) e\n"+ ")"; String queryf="select avg(c.cnt) as average_diagnosed_patients from\n" + "(select dp.name as name, count(a.id) as cnt\n" + "from appointments a, doctors d, departments dp\n" + "where a.doctoramka=d.doctoramka and d.specialty=dp.id\n" + "and a.diagnosis is not null\n" + "group by dp.name) c"; String input=""; boolean b=false; while(true){ b=false; System.out.println("Give a letter from a to f to execute a query or give 'END' to stop the procedure.\n"); while(!b){ input = reader.nextLine(); if("a".equals(input) || "b".equals(input) || "c".equals(input) || "d".equals(input) || "e".equals(input) || "f".equals(input) || "END".equals(input)) b=true; else System.out.println("Give a letter from a to f or 'END'"); } if("a".equals(input)){ rs = stmt.executeQuery(querya); while ( rs.next() ) { String maxmincounts = rs.getString(1); String drugnames = rs.getString(2); System.out.println( "Max & Min Counts = " + maxmincounts ); System.out.println( "Drug Names = " + drugnames ); System.out.println(); } } else if("b".equals(input)){ rs = stmt.executeQuery(queryb); while ( rs.next() ) { String diagnosis = rs.getString(1); String date = rs.getString(2); System.out.println( "Diagnosis = " + diagnosis ); System.out.println( "Date = " + date ); System.out.println(); } } else if("c".equals(input)){ System.out.println("Give doctor AMKA"); amka = reader.nextLine(); //rs = stmt.executeQuery(queryc);--will not work because every time I need to initialize new code (amka) rs = stmt.executeQuery("select p.name as patient_name, p.surname as patient_surname, a.t as date\n" + "from appointments a, doctors d, patients p\n" + "where a.patientamka=p.patientamka and a.doctoramka=d.doctoramka\n" + "and a.t>(select date(max(t))from appointments) - integer '30'\n" + "--and a.t>current_date-30\n" + "and d.doctoramka='"+amka+"'"); int count=0; while ( rs.next() ) { count++; String patientname = rs.getString(1); String patientsurname = rs.getString(2); String date = rs.getString(3); System.out.println( "Patient Name = " + patientname ); System.out.println( "Patient Surname = " + patientsurname ); System.out.println( "Date = " + date ); System.out.println(); } if(count==0) System.out.println("This doctor had no dates the past month or AMKA is wrong\n"); } else if("d".equals(input)){ rs = stmt.executeQuery(queryd); while ( rs.next() ) { String patientname = rs.getString(1); String patientsurname = rs.getString(2); String distinctdoctorscount = rs.getString(3); System.out.println( "Patient Name = " + patientname ); System.out.println( "Patient Surname = " + patientsurname ); System.out.println( "Number of different doctors = " + distinctdoctorscount ); System.out.println(); } } else if("e".equals(input)){ rs = stmt.executeQuery(querye); while ( rs.next() ) { String department = rs.getString(1); System.out.println( "Most Visited Department(s) = " + department ); System.out.println(); } } else if("f".equals(input)){ rs = stmt.executeQuery(queryf); while ( rs.next() ) { String avgdiagnosedpatients = rs.getString(1); System.out.println( "Average Diagnosed Patients = " + avgdiagnosedpatients ); System.out.println(); } } else if("END".equals(input)) System.exit(1); } } catch (SQLException ex) { Logger.getLogger(JDBC_CLIENT.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (c != null) { c.close(); } } catch (SQLException ex) { Logger.getLogger(JDBC_CLIENT.class.getName()).log(Level.SEVERE, null, ex); } } } }
PetePrattis/hospital-database-with-JDBC-client
JDBC_CLIENT/src/jdbc_client/JDBC_CLIENT.java
2,551
/** * * @author Panagiotis Prattis / Παναγιώτης Πράττης */
block_comment
el
package jdbc_client; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import java.util.Scanner; /** * * @author Panagiotis Prattis<SUF>*/ public class JDBC_CLIENT { public static void main(String[] args) { Connection c = null; Statement stmt=null; ResultSet rs=null; Scanner reader = new Scanner(System.in); System.out.println("Give Password for postgres database:"); String pass = reader.nextLine(); System.out.println(); try { c = DriverManager.getConnection("jdbc:postgresql://Localhost/postgres", "postgres", pass); System.out.println("Opened database successfully\n"); stmt = c.createStatement(); System.out.println("Create statement successfully\n"); System.out.println("These are the queries:\n" + "a) What are the drugs (maximum and minimum number) prescribed. In\n" + "result show quantity and name of drug.\n" + "b) What are the diagnoses of the last week.\n" + "c) What are the doctor's 'X' appointments last month.\n" + "d) Who are the patients who have seen more than one doctor.\n" + "e) From what department have most patients been examined.\n" + "f) What is the average number of patients examined per department.\n" ); String querya="select c.cnt as max_min_counts, c.drug_name \n" + "from\n" + "(\n" + "select count (mf.drug_id) as cnt , d.name as drug_name\n" + "from medicalfolders mf, drugs d\n" + "where mf.drug_id=d.id\n" + "group by d.name\n" + ") c\n" + "where c.cnt=\n" + "(\n" + "select min (e.cnt) from\n" + "(select count (mf.drug_id) as cnt, d.name \n" + "from medicalfolders mf, drugs d\n" + "where mf.drug_id=d.id\n" + "group by d.name) e\n" + ")or\n" + "c.cnt=\n" + "(\n" + "select max (e.cnt) from\n" + "(select count (mf.drug_id) as cnt, d.name \n" + " from medicalfolders mf, drugs d\n" + "where mf.drug_id=d.id\n" + "group by d.name) e\n" + ")"; String queryb="select a.diagnosis, a.t as date\n" + "from appointments a, medicalfolders m\n" + "where a.patientamka=m.patientamka\n" + "and a.diagnosis is not null\n" + "and a.t > (select date(max(t))from appointments) - integer '7'"; // queryc will not be used but its code in executeQuery() will,             // to initialize patient's or doctor's code (amka) correctly because otherwise it will be             // initialized to value of the next line and will not be able to change it String amka=""; String queryc="select p.name as patient_name, p.surname as patient_surname, a.t as date\n" + "from appointments a, doctors d, patients p\n" + "where a.patientamka=p.patientamka and a.doctoramka=d.doctoramka\n" + "and a.t>(select date(max(t))from appointments) - integer '30'\n" + "--and a.t>current_date-30\n" + "and d.doctoramka='"+amka+"'"; String queryd="select p.name as patient_name, p.surname as patient_surname, \n" + "count(distinct doctoramka) as distinct_doctors_count\n" + "from appointments a, patients p\n" + "where a.patientamka=p.patientamka \n" + "group by p.name, p.surname\n" + "having count(*)>1"; String querye="select c.name as most_visited_departments from\n" + "(select dp.name as name, count(a.id) as cnt\n" + "from appointments a, doctors d, departments dp\n" + "where a.doctoramka=d.doctoramka and d.specialty=dp.id\n" + "and a.diagnosis is not null\n" + "group by dp.name) c\n" + "where c.cnt= (select max(e.cnt) from \n" + "(select dp.name as name, count(a.id) as cnt\n" + "from appointments a, doctors d, departments dp\n" + "where a.doctoramka=d.doctoramka and d.specialty=dp.id\n" + "and a.diagnosis is not null\n" + "group by dp.name) e\n"+ ")"; String queryf="select avg(c.cnt) as average_diagnosed_patients from\n" + "(select dp.name as name, count(a.id) as cnt\n" + "from appointments a, doctors d, departments dp\n" + "where a.doctoramka=d.doctoramka and d.specialty=dp.id\n" + "and a.diagnosis is not null\n" + "group by dp.name) c"; String input=""; boolean b=false; while(true){ b=false; System.out.println("Give a letter from a to f to execute a query or give 'END' to stop the procedure.\n"); while(!b){ input = reader.nextLine(); if("a".equals(input) || "b".equals(input) || "c".equals(input) || "d".equals(input) || "e".equals(input) || "f".equals(input) || "END".equals(input)) b=true; else System.out.println("Give a letter from a to f or 'END'"); } if("a".equals(input)){ rs = stmt.executeQuery(querya); while ( rs.next() ) { String maxmincounts = rs.getString(1); String drugnames = rs.getString(2); System.out.println( "Max & Min Counts = " + maxmincounts ); System.out.println( "Drug Names = " + drugnames ); System.out.println(); } } else if("b".equals(input)){ rs = stmt.executeQuery(queryb); while ( rs.next() ) { String diagnosis = rs.getString(1); String date = rs.getString(2); System.out.println( "Diagnosis = " + diagnosis ); System.out.println( "Date = " + date ); System.out.println(); } } else if("c".equals(input)){ System.out.println("Give doctor AMKA"); amka = reader.nextLine(); //rs = stmt.executeQuery(queryc);--will not work because every time I need to initialize new code (amka) rs = stmt.executeQuery("select p.name as patient_name, p.surname as patient_surname, a.t as date\n" + "from appointments a, doctors d, patients p\n" + "where a.patientamka=p.patientamka and a.doctoramka=d.doctoramka\n" + "and a.t>(select date(max(t))from appointments) - integer '30'\n" + "--and a.t>current_date-30\n" + "and d.doctoramka='"+amka+"'"); int count=0; while ( rs.next() ) { count++; String patientname = rs.getString(1); String patientsurname = rs.getString(2); String date = rs.getString(3); System.out.println( "Patient Name = " + patientname ); System.out.println( "Patient Surname = " + patientsurname ); System.out.println( "Date = " + date ); System.out.println(); } if(count==0) System.out.println("This doctor had no dates the past month or AMKA is wrong\n"); } else if("d".equals(input)){ rs = stmt.executeQuery(queryd); while ( rs.next() ) { String patientname = rs.getString(1); String patientsurname = rs.getString(2); String distinctdoctorscount = rs.getString(3); System.out.println( "Patient Name = " + patientname ); System.out.println( "Patient Surname = " + patientsurname ); System.out.println( "Number of different doctors = " + distinctdoctorscount ); System.out.println(); } } else if("e".equals(input)){ rs = stmt.executeQuery(querye); while ( rs.next() ) { String department = rs.getString(1); System.out.println( "Most Visited Department(s) = " + department ); System.out.println(); } } else if("f".equals(input)){ rs = stmt.executeQuery(queryf); while ( rs.next() ) { String avgdiagnosedpatients = rs.getString(1); System.out.println( "Average Diagnosed Patients = " + avgdiagnosedpatients ); System.out.println(); } } else if("END".equals(input)) System.exit(1); } } catch (SQLException ex) { Logger.getLogger(JDBC_CLIENT.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (c != null) { c.close(); } } catch (SQLException ex) { Logger.getLogger(JDBC_CLIENT.class.getName()).log(Level.SEVERE, null, ex); } } } }
545_3
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.protobuf.InvalidProtocolBufferException; import models.FindResultModel; import models.Location; import models.ObservationReq; import models.Thing; import org.atlas.gateway.components.wsn.messages.WSNMessage; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.Date; public class MqttConnector implements MqttCallback{ private static final Logger logger = LoggerFactory.getLogger(MqttConnector.class); private MqttClient mqclient; private int rssi = 0; private int tvRssi = 0; private int bathroomRssi = 0; private Utils.Location location= Utils.Location.LOCATION1; private Utils.Location currentLocation = Utils.Location.LOCATION1; private static final Map<String, Long> thingIds; private ObjectMapper mapper = new ObjectMapper(); private Location locationObject; static { thingIds = new HashMap<String, Long>(); thingIds.put("00:02:5B:00:B9:10", new Long(26)); thingIds.put("00:02:5B:00:B9:12", new Long(24)); thingIds.put("00:02:5B:00:B9:16", new Long(25)); } public MqttConnector(boolean connect){ if( !connect ){ logger.info("MQTT Connection disabled by user"); return; } boolean isconnected =false; while(!isconnected){ try { // this.mqclient = new MqttClient("tcp://172.21.13.170:1883", "relative-localization-agent-impl", new MemoryPersistence()); // this.mqclient = new MqttClient("tcp://10.10.20.110:1883", "relativeLoc", new MemoryPersistence()); this.mqclient = new MqttClient("tcp://192.168.0.156:1883", "relativeLoc", new MemoryPersistence()); this.mqclient.setCallback(this); this.mqclient.connect(this.getConnectioOptions()); isconnected = this.mqclient.isConnected(); if (isconnected){ logger.info("Successfully Connected to main gateway"); this.mqclient.subscribe("wsn/ble/devices/advertisments"); logger.info("Suscribed to topic get advertisments: wsn/ble/devices/advertisments"); } } catch (MqttException e) { logger.error("Error while trying to connect to MQTT provide",e); isconnected = false; } try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } } private MqttConnectOptions getConnectioOptions() { MqttConnectOptions options = new MqttConnectOptions(); options.setUserName("application"); options.setPassword("@PpL3c@tI0n".toCharArray()); options.setAutomaticReconnect(true); options.setCleanSession(true); return options; } public MqttClient getClient(){ return this.mqclient; } public void connectionLost(Throwable cause) {} public void messageArrived(String topic, MqttMessage message) throws InvalidProtocolBufferException, JsonProcessingException { WSNMessage.Advertisment advertisment = WSNMessage.Advertisment.parseFrom(message.getPayload()); if( advertisment != null && advertisment.getAddress() != null && (advertisment.getAddress().equals("00:02:5B:00:B9:10") || advertisment.getAddress().equals("00:02:5B:00:B9:12") )){ if ((advertisment.getData().toByteArray()[27] & 0xFF) > 126) { rssi = (advertisment.getData().toByteArray()[27] & 0xFF) - 256; } else { rssi = -(advertisment.getData().toByteArray()[27] & 0xFF); } if (advertisment.getAddress().equals("00:02:5B:00:B9:10")){ tvRssi = rssi; } if (advertisment.getAddress().equals("00:02:5B:00:B9:12")){ bathroomRssi = rssi; } logger.debug("10: " + tvRssi + " --- " + "12: " + bathroomRssi); if (tvRssi > bathroomRssi){ currentLocation = Utils.Location.LOCATION1; // publishMsg(Room.TV); } else if (tvRssi < bathroomRssi){ currentLocation = Utils.Location.LOCATION2; // publishMsg(Room.BATH); } else { return; } if (location != currentLocation){ location = currentLocation; logger.debug(location.name()); publishMsg(location.toString()); ObservationReq observationReq = new ObservationReq(); Thing thing = new Thing(); observationReq.setId(28); observationReq.setName(location.name()); observationReq.setTimestamp(new Date().getTime()); thing.setName("Thing"); thing.setSensorId(thingIds.get(advertisment.getAddress())); thing.setId(29); List<Thing> things = new ArrayList<>(); things.add(thing); observationReq.setThings(things); FindResultModel frm = new FindResultModel(); frm.setName("thing"); frm.setPlace(location.name()); frm.setDate(new Date()); logger.info(frm.toString()); byte[] tmp = mapper.writeValueAsString(observationReq).getBytes(); } } } private void publishMsg(String location) throws JsonProcessingException { String msg = msg = "{\"uuid\":\"b1252fb0-ada3-4617-9bd6-6af0addf9c1d\",\"timestamp\":1494003326102,\"device\":\"B0:B4:48:C9:26:01\",\"datatype\":\"temperature\",\"value\":26.91,\"payload\":\"Chair,10.83,0,1.1\"}"; locationObject = new Location(); locationObject.setLocation(location); locationObject.setCreatedAt(new Date()); locationObject.setObject("thing"); msg = mapper.writeValueAsString(locationObject); try { if(this.mqclient.isConnected()) this.mqclient.publish("apps/localization/relative",new MqttMessage(msg.getBytes())); else System.out.println("-------"); } catch (MqttException e) { e.printStackTrace(); } } public void deliveryComplete(IMqttDeliveryToken token) { } public enum Room { TV, BATH } } /* Με Chair,12.4,0,0.6 τοποθετείται κοντά στην TV. Με Chair,6.6,0,1 τοποθετείται μέσα στο μπάνιο. Με Chair,10.83,0,1.1 τοποθετείται στην αρχική της θέση στο τραπέζι. */
RADIO-PROJECT-EU/indoor_relative_localization
src/main/java/MqttConnector.java
1,932
/* Με Chair,12.4,0,0.6 τοποθετείται κοντά στην TV. Με Chair,6.6,0,1 τοποθετείται μέσα στο μπάνιο. Με Chair,10.83,0,1.1 τοποθετείται στην αρχική της θέση στο τραπέζι. */
block_comment
el
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.protobuf.InvalidProtocolBufferException; import models.FindResultModel; import models.Location; import models.ObservationReq; import models.Thing; import org.atlas.gateway.components.wsn.messages.WSNMessage; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.Date; public class MqttConnector implements MqttCallback{ private static final Logger logger = LoggerFactory.getLogger(MqttConnector.class); private MqttClient mqclient; private int rssi = 0; private int tvRssi = 0; private int bathroomRssi = 0; private Utils.Location location= Utils.Location.LOCATION1; private Utils.Location currentLocation = Utils.Location.LOCATION1; private static final Map<String, Long> thingIds; private ObjectMapper mapper = new ObjectMapper(); private Location locationObject; static { thingIds = new HashMap<String, Long>(); thingIds.put("00:02:5B:00:B9:10", new Long(26)); thingIds.put("00:02:5B:00:B9:12", new Long(24)); thingIds.put("00:02:5B:00:B9:16", new Long(25)); } public MqttConnector(boolean connect){ if( !connect ){ logger.info("MQTT Connection disabled by user"); return; } boolean isconnected =false; while(!isconnected){ try { // this.mqclient = new MqttClient("tcp://172.21.13.170:1883", "relative-localization-agent-impl", new MemoryPersistence()); // this.mqclient = new MqttClient("tcp://10.10.20.110:1883", "relativeLoc", new MemoryPersistence()); this.mqclient = new MqttClient("tcp://192.168.0.156:1883", "relativeLoc", new MemoryPersistence()); this.mqclient.setCallback(this); this.mqclient.connect(this.getConnectioOptions()); isconnected = this.mqclient.isConnected(); if (isconnected){ logger.info("Successfully Connected to main gateway"); this.mqclient.subscribe("wsn/ble/devices/advertisments"); logger.info("Suscribed to topic get advertisments: wsn/ble/devices/advertisments"); } } catch (MqttException e) { logger.error("Error while trying to connect to MQTT provide",e); isconnected = false; } try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } } private MqttConnectOptions getConnectioOptions() { MqttConnectOptions options = new MqttConnectOptions(); options.setUserName("application"); options.setPassword("@PpL3c@tI0n".toCharArray()); options.setAutomaticReconnect(true); options.setCleanSession(true); return options; } public MqttClient getClient(){ return this.mqclient; } public void connectionLost(Throwable cause) {} public void messageArrived(String topic, MqttMessage message) throws InvalidProtocolBufferException, JsonProcessingException { WSNMessage.Advertisment advertisment = WSNMessage.Advertisment.parseFrom(message.getPayload()); if( advertisment != null && advertisment.getAddress() != null && (advertisment.getAddress().equals("00:02:5B:00:B9:10") || advertisment.getAddress().equals("00:02:5B:00:B9:12") )){ if ((advertisment.getData().toByteArray()[27] & 0xFF) > 126) { rssi = (advertisment.getData().toByteArray()[27] & 0xFF) - 256; } else { rssi = -(advertisment.getData().toByteArray()[27] & 0xFF); } if (advertisment.getAddress().equals("00:02:5B:00:B9:10")){ tvRssi = rssi; } if (advertisment.getAddress().equals("00:02:5B:00:B9:12")){ bathroomRssi = rssi; } logger.debug("10: " + tvRssi + " --- " + "12: " + bathroomRssi); if (tvRssi > bathroomRssi){ currentLocation = Utils.Location.LOCATION1; // publishMsg(Room.TV); } else if (tvRssi < bathroomRssi){ currentLocation = Utils.Location.LOCATION2; // publishMsg(Room.BATH); } else { return; } if (location != currentLocation){ location = currentLocation; logger.debug(location.name()); publishMsg(location.toString()); ObservationReq observationReq = new ObservationReq(); Thing thing = new Thing(); observationReq.setId(28); observationReq.setName(location.name()); observationReq.setTimestamp(new Date().getTime()); thing.setName("Thing"); thing.setSensorId(thingIds.get(advertisment.getAddress())); thing.setId(29); List<Thing> things = new ArrayList<>(); things.add(thing); observationReq.setThings(things); FindResultModel frm = new FindResultModel(); frm.setName("thing"); frm.setPlace(location.name()); frm.setDate(new Date()); logger.info(frm.toString()); byte[] tmp = mapper.writeValueAsString(observationReq).getBytes(); } } } private void publishMsg(String location) throws JsonProcessingException { String msg = msg = "{\"uuid\":\"b1252fb0-ada3-4617-9bd6-6af0addf9c1d\",\"timestamp\":1494003326102,\"device\":\"B0:B4:48:C9:26:01\",\"datatype\":\"temperature\",\"value\":26.91,\"payload\":\"Chair,10.83,0,1.1\"}"; locationObject = new Location(); locationObject.setLocation(location); locationObject.setCreatedAt(new Date()); locationObject.setObject("thing"); msg = mapper.writeValueAsString(locationObject); try { if(this.mqclient.isConnected()) this.mqclient.publish("apps/localization/relative",new MqttMessage(msg.getBytes())); else System.out.println("-------"); } catch (MqttException e) { e.printStackTrace(); } } public void deliveryComplete(IMqttDeliveryToken token) { } public enum Room { TV, BATH } } /* Με Chair,12.4,0,0.6 τοποθετείται<SUF>*/
17086_1
package gr.aueb.cf.OOProjects.ch18; import gr.aueb.cf.OOProjects.ch18.dao.AccountDAOImpl; import gr.aueb.cf.OOProjects.ch18.dao.IAccountDAO; import gr.aueb.cf.OOProjects.ch18.service.IAccountService; import gr.aueb.cf.OOProjects.ch18.dto.AccountInsertDTO; import gr.aueb.cf.OOProjects.ch18.dto.UserInsertDTO; import gr.aueb.cf.OOProjects.ch18.service.AccountServiceImpl; import gr.aueb.cf.OOProjects.ch18.service.exceptions.AccountNotFoundException; import gr.aueb.cf.OOProjects.ch18.service.exceptions.InsufficientBalanceException; import gr.aueb.cf.OOProjects.ch18.service.exceptions.NegativeAmountException; import gr.aueb.cf.OOProjects.ch18.service.exceptions.SsnNotValidException; public class Main { public static void main(String[] args) { IAccountDAO accountDAO = new AccountDAOImpl(); IAccountService accountService = new AccountServiceImpl(accountDAO); // Εισαγωγή νέου λογαριασμού AccountInsertDTO insertDTO = new AccountInsertDTO("IBAN123", new UserInsertDTO("John", "Doe", "123456789"), 1000.0); accountService.insertAccount(insertDTO); // Κατάθεση ποσού try { accountService.deposit("IBAN123", 500.0); System.out.println("Deposit successful"); } catch (AccountNotFoundException | NegativeAmountException e) { e.printStackTrace(); } // Κατάθεση αρνητικού ποσού try { accountService.deposit("IBAN123", -500.0); System.out.println("Deposit successful"); } catch (AccountNotFoundException | NegativeAmountException e) { e.printStackTrace(); } // Ανάληψη ποσού με ssn που δεν αντιστοιχεί στον κάτοχο του λογαριασμού. try { accountService.withdraw("IBAN123", "00000000", 200.0); System.out.println("Withdrawal successful"); } catch (AccountNotFoundException | SsnNotValidException | NegativeAmountException | InsufficientBalanceException e) { e.printStackTrace(); } } }
RenaMygdali/java-oo-projects
ch18/Main.java
669
// Κατάθεση αρνητικού ποσού
line_comment
el
package gr.aueb.cf.OOProjects.ch18; import gr.aueb.cf.OOProjects.ch18.dao.AccountDAOImpl; import gr.aueb.cf.OOProjects.ch18.dao.IAccountDAO; import gr.aueb.cf.OOProjects.ch18.service.IAccountService; import gr.aueb.cf.OOProjects.ch18.dto.AccountInsertDTO; import gr.aueb.cf.OOProjects.ch18.dto.UserInsertDTO; import gr.aueb.cf.OOProjects.ch18.service.AccountServiceImpl; import gr.aueb.cf.OOProjects.ch18.service.exceptions.AccountNotFoundException; import gr.aueb.cf.OOProjects.ch18.service.exceptions.InsufficientBalanceException; import gr.aueb.cf.OOProjects.ch18.service.exceptions.NegativeAmountException; import gr.aueb.cf.OOProjects.ch18.service.exceptions.SsnNotValidException; public class Main { public static void main(String[] args) { IAccountDAO accountDAO = new AccountDAOImpl(); IAccountService accountService = new AccountServiceImpl(accountDAO); // Εισαγωγή νέου λογαριασμού AccountInsertDTO insertDTO = new AccountInsertDTO("IBAN123", new UserInsertDTO("John", "Doe", "123456789"), 1000.0); accountService.insertAccount(insertDTO); // Κατάθεση ποσού try { accountService.deposit("IBAN123", 500.0); System.out.println("Deposit successful"); } catch (AccountNotFoundException | NegativeAmountException e) { e.printStackTrace(); } // Κατάθεση αρνητικού<SUF> try { accountService.deposit("IBAN123", -500.0); System.out.println("Deposit successful"); } catch (AccountNotFoundException | NegativeAmountException e) { e.printStackTrace(); } // Ανάληψη ποσού με ssn που δεν αντιστοιχεί στον κάτοχο του λογαριασμού. try { accountService.withdraw("IBAN123", "00000000", 200.0); System.out.println("Withdrawal successful"); } catch (AccountNotFoundException | SsnNotValidException | NegativeAmountException | InsufficientBalanceException e) { e.printStackTrace(); } } }
1074_8
package com.example.aic601project.R1_R2; import com.example.aic601project.MainActivity; import com.example.aic601project.OkHttpHandler; import com.example.aic601project.R; import com.google.android.material.appbar.MaterialToolbar; import com.google.android.material.textfield.TextInputEditText; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import java.util.Objects; public class AdminR2Activity1 extends AppCompatActivity { private Button add; // String - used to get the ip address from the MainActivity private String ip; // toolbar - admin_r2_1_topAppBar private MaterialToolbar toolbar; private TextInputEditText nameText; private TextInputEditText costText; private TextInputEditText codeText; private TextInputEditText descriptionText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_admin_r2_1); // gets the IP from the MainActivity ip = MainActivity.getIP(); // δημιουργω τα text πεδια nameText = findViewById(R.id.admin_r2_1_textInputLayout_name_editText); costText = findViewById(R.id.admin_r2_1_textInputLayout_cost_editText); codeText = findViewById(R.id.admin_r2_1_textInputLayout_code_editText); descriptionText = findViewById((R.id.admin_r2_1_textInputLayout_description_editText)); add = findViewById(R.id.admin_r2_1_button); // προσθετω την διαδικασια nameText.addTextChangedListener(longinTextWatcher); costText.addTextChangedListener(longinTextWatcher); codeText.addTextChangedListener(longinTextWatcher); descriptionText.addTextChangedListener(longinTextWatcher); getWindow().setStatusBarColor(getResources().getColor(R.color.md_theme_light_surfaceVariant, this.getTheme())); toolbar = findViewById(R.id.admin_r2_1_topAppBar); setupToolbarWithBackButton(); } // sets up a toolbar where clicking the back button calls onBackPressed() private void setupToolbarWithBackButton() { setSupportActionBar(toolbar); toolbar.setNavigationOnClickListener(v -> onBackPressed()); } // overrides the default onBackPressed() function and includes an exit animation public void onBackPressed() { super.onBackPressed(); overridePendingTransition(R.anim.no_slide_in_or_out, R.anim.slide_out_from_top); } /* * overrides the onCreateOptionsMenu because by calling setSupportActionBar * the menu will be populated with standard system menu items */ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.admin_r2_app_bar_layout, menu); return true; } // εδω φτιαχνω την διαδικασια TextWatcher η οποια θα κανει το κουμπι enable οταν // συμπληρωνονται τα πεδια private TextWatcher longinTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { String nameInput = nameText.getText().toString(); String costInput = costText.getText().toString(); String codeInput = codeText.getText().toString(); String descriptionInput = descriptionText.getText().toString(); add.setEnabled(!nameInput.isEmpty() && !costInput.isEmpty() && !codeInput.isEmpty() && !descriptionInput.isEmpty()); } @Override public void afterTextChanged(Editable s) { } }; // onClick for admin_r2_1_button Button public void addService2_1(View v) { int result = 0; Log.d("imtestingbro", "mphke"); String url = "http://" + ip + "/myTherapy/insertService.php"; try { OkHttpHandler okHttpHandler = new OkHttpHandler(); result = okHttpHandler.insertOrUpdateService(url, Objects.requireNonNull(codeText.getText()).toString(), Objects.requireNonNull(nameText.getText()).toString(), Objects.requireNonNull(costText.getText()).toString(), Objects.requireNonNull(descriptionText.getText()).toString()); } catch (Exception e) { e.printStackTrace(); } if (result == 0) { Toast.makeText(AdminR2Activity1.this, "Ανεπιτυχής προσθήκη! Ο κωδικός παροχής αυτός υπάρχει ήδη.", Toast.LENGTH_LONG).show(); onBackPressed(); } else { Toast.makeText(AdminR2Activity1.this, "Η παροχή έχει προστεθεί.", Toast.LENGTH_LONG).show(); onBackPressed(); } } }
RippleWave-Technologies/myTherapy
app/src/main/java/com/example/aic601project/R1_R2/AdminR2Activity1.java
1,318
// εδω φτιαχνω την διαδικασια TextWatcher η οποια θα κανει το κουμπι enable οταν
line_comment
el
package com.example.aic601project.R1_R2; import com.example.aic601project.MainActivity; import com.example.aic601project.OkHttpHandler; import com.example.aic601project.R; import com.google.android.material.appbar.MaterialToolbar; import com.google.android.material.textfield.TextInputEditText; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import java.util.Objects; public class AdminR2Activity1 extends AppCompatActivity { private Button add; // String - used to get the ip address from the MainActivity private String ip; // toolbar - admin_r2_1_topAppBar private MaterialToolbar toolbar; private TextInputEditText nameText; private TextInputEditText costText; private TextInputEditText codeText; private TextInputEditText descriptionText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_admin_r2_1); // gets the IP from the MainActivity ip = MainActivity.getIP(); // δημιουργω τα text πεδια nameText = findViewById(R.id.admin_r2_1_textInputLayout_name_editText); costText = findViewById(R.id.admin_r2_1_textInputLayout_cost_editText); codeText = findViewById(R.id.admin_r2_1_textInputLayout_code_editText); descriptionText = findViewById((R.id.admin_r2_1_textInputLayout_description_editText)); add = findViewById(R.id.admin_r2_1_button); // προσθετω την διαδικασια nameText.addTextChangedListener(longinTextWatcher); costText.addTextChangedListener(longinTextWatcher); codeText.addTextChangedListener(longinTextWatcher); descriptionText.addTextChangedListener(longinTextWatcher); getWindow().setStatusBarColor(getResources().getColor(R.color.md_theme_light_surfaceVariant, this.getTheme())); toolbar = findViewById(R.id.admin_r2_1_topAppBar); setupToolbarWithBackButton(); } // sets up a toolbar where clicking the back button calls onBackPressed() private void setupToolbarWithBackButton() { setSupportActionBar(toolbar); toolbar.setNavigationOnClickListener(v -> onBackPressed()); } // overrides the default onBackPressed() function and includes an exit animation public void onBackPressed() { super.onBackPressed(); overridePendingTransition(R.anim.no_slide_in_or_out, R.anim.slide_out_from_top); } /* * overrides the onCreateOptionsMenu because by calling setSupportActionBar * the menu will be populated with standard system menu items */ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.admin_r2_app_bar_layout, menu); return true; } // εδω φτιαχνω<SUF> // συμπληρωνονται τα πεδια private TextWatcher longinTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { String nameInput = nameText.getText().toString(); String costInput = costText.getText().toString(); String codeInput = codeText.getText().toString(); String descriptionInput = descriptionText.getText().toString(); add.setEnabled(!nameInput.isEmpty() && !costInput.isEmpty() && !codeInput.isEmpty() && !descriptionInput.isEmpty()); } @Override public void afterTextChanged(Editable s) { } }; // onClick for admin_r2_1_button Button public void addService2_1(View v) { int result = 0; Log.d("imtestingbro", "mphke"); String url = "http://" + ip + "/myTherapy/insertService.php"; try { OkHttpHandler okHttpHandler = new OkHttpHandler(); result = okHttpHandler.insertOrUpdateService(url, Objects.requireNonNull(codeText.getText()).toString(), Objects.requireNonNull(nameText.getText()).toString(), Objects.requireNonNull(costText.getText()).toString(), Objects.requireNonNull(descriptionText.getText()).toString()); } catch (Exception e) { e.printStackTrace(); } if (result == 0) { Toast.makeText(AdminR2Activity1.this, "Ανεπιτυχής προσθήκη! Ο κωδικός παροχής αυτός υπάρχει ήδη.", Toast.LENGTH_LONG).show(); onBackPressed(); } else { Toast.makeText(AdminR2Activity1.this, "Η παροχή έχει προστεθεί.", Toast.LENGTH_LONG).show(); onBackPressed(); } } }
1093_0
import java.io.Serializable; public class Administrator extends User implements Serializable { /** * Ο κατασκευαστής αυτός μας επιτρέπει να κάνουμε manual εισαγωγες * @param name Ονομα χρηστη * @param surname Επιθετο χρηστη * @param age Ηλικια χρηστη * @param email Email χρηστη * @param username Username χρηστη * @param password Password χρηστη */ public Administrator(String name,String surname,String[] age,String email,String username,String password){ super(name,surname,age,email,username,password); } }
Samouil16/Simple_Booking_App
src/Administrator.java
215
/** * Ο κατασκευαστής αυτός μας επιτρέπει να κάνουμε manual εισαγωγες * @param name Ονομα χρηστη * @param surname Επιθετο χρηστη * @param age Ηλικια χρηστη * @param email Email χρηστη * @param username Username χρηστη * @param password Password χρηστη */
block_comment
el
import java.io.Serializable; public class Administrator extends User implements Serializable { /** * Ο κατασκευαστής αυτός<SUF>*/ public Administrator(String name,String surname,String[] age,String email,String username,String password){ super(name,surname,age,email,username,password); } }
626_6
package tillerino.tillerinobot.lang; import java.util.List; import java.util.Random; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import tillerino.tillerinobot.BeatmapMeta; import tillerino.tillerinobot.IRCBot.IRCBotUser; import tillerino.tillerinobot.RecommendationsManager.Recommendation; /** * @author Till https://github.com/nikosbks https://osu.ppy.sh/u/3619345 */ public class Greek implements Language { @Override public String unknownBeatmap() { return "Συγνώμη, δεν γνωρίζω αυτό το τραγούδι. Ίσως είναι αρκετά νεο, πολυ δύσκολο, μη εγκεκριμένο ή να μην είναι για το osu standard mode." ; } @Override public String internalException(String marker) { return "Εχ... μάλλον φαίνεται ότι ο ανθρώπινος Tillerino έκανε μαντάρα την σύνδεσή μου." +" Εάν δεν το παρατηρήσει σύντομα, μπορείς [https://github.com/Tillerino/Tillerinobot/wiki/Contact να τον ενημερώσεις]; (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Τί συμβαίνει; Παίρνω μονο παραλογίες από τον server του osu. Μπορείς να μου πείς τι σημαίνει αυτο; 0011101001010000" + " Ο ανθρώπινος Tillerino λέει ότι δεν υπάρχει κάτι για να ανησυχείς, και ότι πρέπει να ξαναπροσπαθήσουμε." + " Εάν ανησυχείς πάρα πολύ για κάποιο λογο, μπορείς να [https://github.com/Tillerino/Tillerinobot/wiki/Contact του το πείς]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Δεν υπάρχουν δεδομένα για τα ζητούμενα mods." ; } @Override public void welcomeUser(IRCBotUser user, OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { user.message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { user.message("Καλώς ήρθες πίσω," + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { user.message(apiUser.getUserName() + "..."); user.message("...είσαι εσύ αυτός; Πάει πολύς καιρός!"); user.message("Είναι ωραίο να σε έχουμε πίσω. Μπορώ να σε ενδιαφέρω με μια πρόταση;"); } else { String[] messages = { "Φαίνεσαι σαν να θες μια πρόταση.", "Πόσο ωραίο να σε βλέπω :)", "Ο αγαπημένος μου άνθρωπος. (Μην το πείς στούς άλλους!)", "Τι ευχάριστη έκπληξη! ^.^", "Περίμενα ότι θα εμφανιστείς. Όλοι οι άλλοι άνθρωποι ειναι μπούφοι, αλλα μην τους πείς ότι το ειπα! :3", "Τι έχεις την διάθεση να κάνεις σήμερα;", }; Random random = new Random(); String message = messages[random.nextInt(messages.length)]; user.message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Άγνωστη εντολή \"" + command + "\". Πληκτρολόγησε !help αν χρειάζεσαι βοήθεια!"; } @Override public String noInformationForMods() { return "Συγνώμη, δεν μπορώ να παρέχω πληροφορίες για αυτά τα mods αυτή τη στιγμή"; } @Override public String malformattedMods(String mods) { return "Αυτα τα mods δεν φαίνονται σωστά. Τα mods μπορεί να είναι ενας συνδυασμός από DT HR HD HT EZ NC FL SO NF.Συνδυάζοντάς τα χωρίς κενά ή ειδικούς χαρακτήρες. Παράδειγμα: !with HDHR, !with DTEZ"; } @Override public String noLastSongInfo() { return "Δεν θυμάμαι να πήρες καμία πληροφορία τραγουδιού..."; } @Override public String tryWithMods() { return "Δοκίμασε αυτό το τραγούδι με μερικά mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Δοκίμασε αυτό το τραγούδι με " + Mods.toShortNamesContinuous(mods); } /** * The user's IRC nick name could not be resolved to an osu user id. The * message should suggest to contact @Tillerinobot or /u/Tillerino. * * @param exceptionMarker * a marker to reference the created log entry. six or eight * characters. * @param name * the irc nick which could not be resolved * @return */ public String unresolvableName(String exceptionMarker, String name) { return "Το ονομά σου με μπερδεύει. Είσαι απαγορευμένος; Εάν όχι, παρακαλώ [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινώνησε με τον Tillerino]. (reference " + exceptionMarker + ")"; } @Override public String excuseForError() { return "Συγνώμη, υπήρχε αυτή η όμορφη σειρά από άσσους και μηδενικά και παρασύρθηκα. Τί ήθελες ξανα;"; } @Override public String complaint() { return "Το παράπονό σου κατατέθηκε. Ο Tillerino θα το κοιτάξει όταν μπορέσει."; } @Override public void hug(final IRCBotUser user, OsuApiUser apiUser) { user.message("Έλα εδώ εσυ!"); user.action("Αγκαλιάζει " + apiUser.getUserName()); } @Override public String help() { return "Γειά! Είμαι το ρομπότ που σκότωσε τον Tillerino και πήρε τον λογαριασμό του. Πλάκα κάνω, αλλά όντως χρησιμοποιώ τον λογαριασμό αρκετά." + " [https://twitter.com/Tillerinobot status και updates]" + " - [https://github.com/Tillerino/Tillerinobot/wiki εντολές]" + " - [http://ppaddict.tillerino.org/ ppaddict]" + " - [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινωνία]"; } @Override public String faq() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ Συχνά ερωτώμενες ερωτήσεις]"; } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Συγνώμη, σε αυτό το σημείο " + feature + "είναι μόνο διαθέσιμο για παίκτες που εχουν ξεπερασμένη τάξη " + minRank + "."; } @Override public String mixedNomodAndMods() { return "Τί εννοείς nomods με mods;"; } @Override public String outOfRecommendations() { return "Έχω προτίνει ό,τι μπορώ να σκεφτώ. " + " Προσπάθησε άλλες επιλογές προτάσεων ή χρησιμοποίησε το !rest. Εάν δεν είσαι σίγουρος, έλεγξε το !help."; } @Override public String notRanked() { return "Απ' ότι φαίνεται αυτό το τραγούδι δεν είναι εγκεκριμένο."; } @Override public void optionalCommentOnNP(IRCBotUser user, OsuApiUser apiUser, BeatmapMeta meta) { // regular Tillerino doesn't comment on this } @Override public void optionalCommentOnWith(IRCBotUser user, OsuApiUser apiUser, BeatmapMeta meta) { // regular Tillerino doesn't comment on this } @Override public void optionalCommentOnRecommendation(IRCBotUser user, OsuApiUser apiUser, Recommendation meta) { // regular Tillerino doesn't comment on this } @Override public boolean isChanged() { return false; } @Override public void setChanged(boolean changed) { } @Override public String invalidAccuracy(String acc) { return "Άκυρη ακρίβεια: \"" + acc + "\""; } @Override public void optionalCommentOnLanguage(IRCBotUser user, OsuApiUser apiUser) { user.message("Ο N for Niko με βοήθησε να μάθω Ελληνικά"); } @Override public String invalidChoice(String invalid, String choices) { return "Συγνώμη, αλλά \"" + invalid + "\" δεν υπολογίζει. Προσπάθησε αυτά: " + choices + "!"; } @Override public String setFormat() { return "Η σύνταξη για να ρυθμιστεί η παράμετρος είναι !set ρύθμιση ποσού. Δοκίμασε !help εάν χρειάζεσαι περισσότερες υποδείξεις."; } }
ScoreUnder/Tillerinobot
tillerinobot/src/main/java/tillerino/tillerinobot/lang/Greek.java
3,605
//github.com/Tillerino/Tillerinobot/wiki/FAQ Συχνά ερωτώμενες ερωτήσεις]";
line_comment
el
package tillerino.tillerinobot.lang; import java.util.List; import java.util.Random; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import tillerino.tillerinobot.BeatmapMeta; import tillerino.tillerinobot.IRCBot.IRCBotUser; import tillerino.tillerinobot.RecommendationsManager.Recommendation; /** * @author Till https://github.com/nikosbks https://osu.ppy.sh/u/3619345 */ public class Greek implements Language { @Override public String unknownBeatmap() { return "Συγνώμη, δεν γνωρίζω αυτό το τραγούδι. Ίσως είναι αρκετά νεο, πολυ δύσκολο, μη εγκεκριμένο ή να μην είναι για το osu standard mode." ; } @Override public String internalException(String marker) { return "Εχ... μάλλον φαίνεται ότι ο ανθρώπινος Tillerino έκανε μαντάρα την σύνδεσή μου." +" Εάν δεν το παρατηρήσει σύντομα, μπορείς [https://github.com/Tillerino/Tillerinobot/wiki/Contact να τον ενημερώσεις]; (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Τί συμβαίνει; Παίρνω μονο παραλογίες από τον server του osu. Μπορείς να μου πείς τι σημαίνει αυτο; 0011101001010000" + " Ο ανθρώπινος Tillerino λέει ότι δεν υπάρχει κάτι για να ανησυχείς, και ότι πρέπει να ξαναπροσπαθήσουμε." + " Εάν ανησυχείς πάρα πολύ για κάποιο λογο, μπορείς να [https://github.com/Tillerino/Tillerinobot/wiki/Contact του το πείς]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Δεν υπάρχουν δεδομένα για τα ζητούμενα mods." ; } @Override public void welcomeUser(IRCBotUser user, OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { user.message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { user.message("Καλώς ήρθες πίσω," + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { user.message(apiUser.getUserName() + "..."); user.message("...είσαι εσύ αυτός; Πάει πολύς καιρός!"); user.message("Είναι ωραίο να σε έχουμε πίσω. Μπορώ να σε ενδιαφέρω με μια πρόταση;"); } else { String[] messages = { "Φαίνεσαι σαν να θες μια πρόταση.", "Πόσο ωραίο να σε βλέπω :)", "Ο αγαπημένος μου άνθρωπος. (Μην το πείς στούς άλλους!)", "Τι ευχάριστη έκπληξη! ^.^", "Περίμενα ότι θα εμφανιστείς. Όλοι οι άλλοι άνθρωποι ειναι μπούφοι, αλλα μην τους πείς ότι το ειπα! :3", "Τι έχεις την διάθεση να κάνεις σήμερα;", }; Random random = new Random(); String message = messages[random.nextInt(messages.length)]; user.message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Άγνωστη εντολή \"" + command + "\". Πληκτρολόγησε !help αν χρειάζεσαι βοήθεια!"; } @Override public String noInformationForMods() { return "Συγνώμη, δεν μπορώ να παρέχω πληροφορίες για αυτά τα mods αυτή τη στιγμή"; } @Override public String malformattedMods(String mods) { return "Αυτα τα mods δεν φαίνονται σωστά. Τα mods μπορεί να είναι ενας συνδυασμός από DT HR HD HT EZ NC FL SO NF.Συνδυάζοντάς τα χωρίς κενά ή ειδικούς χαρακτήρες. Παράδειγμα: !with HDHR, !with DTEZ"; } @Override public String noLastSongInfo() { return "Δεν θυμάμαι να πήρες καμία πληροφορία τραγουδιού..."; } @Override public String tryWithMods() { return "Δοκίμασε αυτό το τραγούδι με μερικά mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Δοκίμασε αυτό το τραγούδι με " + Mods.toShortNamesContinuous(mods); } /** * The user's IRC nick name could not be resolved to an osu user id. The * message should suggest to contact @Tillerinobot or /u/Tillerino. * * @param exceptionMarker * a marker to reference the created log entry. six or eight * characters. * @param name * the irc nick which could not be resolved * @return */ public String unresolvableName(String exceptionMarker, String name) { return "Το ονομά σου με μπερδεύει. Είσαι απαγορευμένος; Εάν όχι, παρακαλώ [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινώνησε με τον Tillerino]. (reference " + exceptionMarker + ")"; } @Override public String excuseForError() { return "Συγνώμη, υπήρχε αυτή η όμορφη σειρά από άσσους και μηδενικά και παρασύρθηκα. Τί ήθελες ξανα;"; } @Override public String complaint() { return "Το παράπονό σου κατατέθηκε. Ο Tillerino θα το κοιτάξει όταν μπορέσει."; } @Override public void hug(final IRCBotUser user, OsuApiUser apiUser) { user.message("Έλα εδώ εσυ!"); user.action("Αγκαλιάζει " + apiUser.getUserName()); } @Override public String help() { return "Γειά! Είμαι το ρομπότ που σκότωσε τον Tillerino και πήρε τον λογαριασμό του. Πλάκα κάνω, αλλά όντως χρησιμοποιώ τον λογαριασμό αρκετά." + " [https://twitter.com/Tillerinobot status και updates]" + " - [https://github.com/Tillerino/Tillerinobot/wiki εντολές]" + " - [http://ppaddict.tillerino.org/ ppaddict]" + " - [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινωνία]"; } @Override public String faq() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ Συχνά<SUF> } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Συγνώμη, σε αυτό το σημείο " + feature + "είναι μόνο διαθέσιμο για παίκτες που εχουν ξεπερασμένη τάξη " + minRank + "."; } @Override public String mixedNomodAndMods() { return "Τί εννοείς nomods με mods;"; } @Override public String outOfRecommendations() { return "Έχω προτίνει ό,τι μπορώ να σκεφτώ. " + " Προσπάθησε άλλες επιλογές προτάσεων ή χρησιμοποίησε το !rest. Εάν δεν είσαι σίγουρος, έλεγξε το !help."; } @Override public String notRanked() { return "Απ' ότι φαίνεται αυτό το τραγούδι δεν είναι εγκεκριμένο."; } @Override public void optionalCommentOnNP(IRCBotUser user, OsuApiUser apiUser, BeatmapMeta meta) { // regular Tillerino doesn't comment on this } @Override public void optionalCommentOnWith(IRCBotUser user, OsuApiUser apiUser, BeatmapMeta meta) { // regular Tillerino doesn't comment on this } @Override public void optionalCommentOnRecommendation(IRCBotUser user, OsuApiUser apiUser, Recommendation meta) { // regular Tillerino doesn't comment on this } @Override public boolean isChanged() { return false; } @Override public void setChanged(boolean changed) { } @Override public String invalidAccuracy(String acc) { return "Άκυρη ακρίβεια: \"" + acc + "\""; } @Override public void optionalCommentOnLanguage(IRCBotUser user, OsuApiUser apiUser) { user.message("Ο N for Niko με βοήθησε να μάθω Ελληνικά"); } @Override public String invalidChoice(String invalid, String choices) { return "Συγνώμη, αλλά \"" + invalid + "\" δεν υπολογίζει. Προσπάθησε αυτά: " + choices + "!"; } @Override public String setFormat() { return "Η σύνταξη για να ρυθμιστεί η παράμετρος είναι !set ρύθμιση ποσού. Δοκίμασε !help εάν χρειάζεσαι περισσότερες υποδείξεις."; } }
799_5
//entertainment.java package projectsiamoglou; import java.util.Date; public class Entertaiment //Περιγραφή ψυχαγωγικής δραστηριότητας { private String ent_name; //όνομασία ψυχαγωγικής δραστηριότητας π.χ. θέατρο σινεμά private String ent_distance; //απόσταση θεάτρου, σινεμά από ξενοδοχείο private String ent_place; //τοποθεσία ψυχαγωγικής δραστηριότητας private Date ent_dt; //Ημέρα και Ώρα private int ent_capacity; //Χωρητικότητα θεάτρου, σινεμά κ.λ.π. private double ent_cost; //Κόστος ψυχαγωγικής δραστηριότητας @Override public String toString() { return "Entertaiment{" + "ent_name=" + ent_name + ", ent_distance=" + ent_distance + ", ent_place=" + ent_place + ", ent_dt=" + ent_dt + ", ent_capacity=" + ent_capacity + ", ent_cost=" + ent_cost + '}'; } public Entertaiment(String ent_name, String ent_distance, String ent_place, Date ent_dt, int ent_capacity, double ent_cost) { this.ent_name = ent_name; this.ent_distance = ent_distance; this.ent_place = ent_place; this.ent_dt = ent_dt; this.ent_capacity = ent_capacity; this.ent_cost = ent_cost; } public Entertaiment() { } public String getEnt_name() { return ent_name; } public void setEnt_name(String ent_name) { this.ent_name = ent_name; } public String getEnt_distance() { return ent_distance; } public void setEnt_distance(String ent_distance) { this.ent_distance = ent_distance; } public String getEnt_place() { return ent_place; } public void setEnt_place(String ent_place) { this.ent_place = ent_place; } public Date getEnt_dt() { return ent_dt; } public void setEnt_dt(Date ent_dt) { this.ent_dt = ent_dt; } public int getEnt_capacity() { return ent_capacity; } public void setEnt_capacity(int ent_capacity) { this.ent_capacity = ent_capacity; } public double getEnt_cost() { return ent_cost; } public void setEnt_cost(double ent_cost) { this.ent_cost = ent_cost; }
SiamoglouB/SMART-BUSINESS
src/entertainment.java
799
//Χωρητικότητα θεάτρου, σινεμά κ.λ.π.
line_comment
el
//entertainment.java package projectsiamoglou; import java.util.Date; public class Entertaiment //Περιγραφή ψυχαγωγικής δραστηριότητας { private String ent_name; //όνομασία ψυχαγωγικής δραστηριότητας π.χ. θέατρο σινεμά private String ent_distance; //απόσταση θεάτρου, σινεμά από ξενοδοχείο private String ent_place; //τοποθεσία ψυχαγωγικής δραστηριότητας private Date ent_dt; //Ημέρα και Ώρα private int ent_capacity; //Χωρητικότητα θεάτρου,<SUF> private double ent_cost; //Κόστος ψυχαγωγικής δραστηριότητας @Override public String toString() { return "Entertaiment{" + "ent_name=" + ent_name + ", ent_distance=" + ent_distance + ", ent_place=" + ent_place + ", ent_dt=" + ent_dt + ", ent_capacity=" + ent_capacity + ", ent_cost=" + ent_cost + '}'; } public Entertaiment(String ent_name, String ent_distance, String ent_place, Date ent_dt, int ent_capacity, double ent_cost) { this.ent_name = ent_name; this.ent_distance = ent_distance; this.ent_place = ent_place; this.ent_dt = ent_dt; this.ent_capacity = ent_capacity; this.ent_cost = ent_cost; } public Entertaiment() { } public String getEnt_name() { return ent_name; } public void setEnt_name(String ent_name) { this.ent_name = ent_name; } public String getEnt_distance() { return ent_distance; } public void setEnt_distance(String ent_distance) { this.ent_distance = ent_distance; } public String getEnt_place() { return ent_place; } public void setEnt_place(String ent_place) { this.ent_place = ent_place; } public Date getEnt_dt() { return ent_dt; } public void setEnt_dt(Date ent_dt) { this.ent_dt = ent_dt; } public int getEnt_capacity() { return ent_capacity; } public void setEnt_capacity(int ent_capacity) { this.ent_capacity = ent_capacity; } public double getEnt_cost() { return ent_cost; } public void setEnt_cost(double ent_cost) { this.ent_cost = ent_cost; }
11559_1
package projectel.projectel; import jakarta.servlet.http.HttpSession; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class Login { //Ελέγχει τα διαπιστευτήρια του χρήστη και επιστρέφει το user id αν είναι σωστά αλλιώς null. static public Boolean checkCredentials(final String email,final String password, final HttpSession session){ Connection conn = DbConnection.getConnection(); if (conn==null) return false; try { final PreparedStatement dbStmt = conn.prepareStatement("SELECT id,name FROM users WHERE password=? AND email=?;"); dbStmt.setString(1, password); dbStmt.setString(2, email); dbStmt.execute(); final ResultSet dbRs = dbStmt.executeQuery(); if (dbRs.next()) { session.setAttribute("userId",dbRs.getString(1)); //Επιστροφή του user id session.setAttribute("userName",dbRs.getString(2)); return true; } } catch (SQLException e) { e.printStackTrace(); } return false; //Αποτυχία σύνδεσης με βάση ή τα στοιχεία δεν είναι σωστά } static public boolean isLoggedIn(final HttpSession session){ return session.getAttribute("userId")!=null; } static public String getUserId(final HttpSession session){ return (String) session.getAttribute("userId"); } static public String getUserName(final HttpSession session){ return (String) session.getAttribute("userName"); } }
SofiaBili/Project-E-Learning-Platform
src/main/java/projectel/projectel/Login.java
441
//Επιστροφή του user id
line_comment
el
package projectel.projectel; import jakarta.servlet.http.HttpSession; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class Login { //Ελέγχει τα διαπιστευτήρια του χρήστη και επιστρέφει το user id αν είναι σωστά αλλιώς null. static public Boolean checkCredentials(final String email,final String password, final HttpSession session){ Connection conn = DbConnection.getConnection(); if (conn==null) return false; try { final PreparedStatement dbStmt = conn.prepareStatement("SELECT id,name FROM users WHERE password=? AND email=?;"); dbStmt.setString(1, password); dbStmt.setString(2, email); dbStmt.execute(); final ResultSet dbRs = dbStmt.executeQuery(); if (dbRs.next()) { session.setAttribute("userId",dbRs.getString(1)); //Επιστροφή του<SUF> session.setAttribute("userName",dbRs.getString(2)); return true; } } catch (SQLException e) { e.printStackTrace(); } return false; //Αποτυχία σύνδεσης με βάση ή τα στοιχεία δεν είναι σωστά } static public boolean isLoggedIn(final HttpSession session){ return session.getAttribute("userId")!=null; } static public String getUserId(final HttpSession session){ return (String) session.getAttribute("userId"); } static public String getUserName(final HttpSession session){ return (String) session.getAttribute("userName"); } }
13402_0
package parkwire.com.activities; import android.os.Bundle; import android.text.format.Time; import android.widget.Button; import android.widget.EditText; import android.widget.TimePicker; import androidx.appcompat.app.AppCompatActivity; import java.sql.Timestamp; import parkwire.com.R; import parkwire.com.models.Parked; import parkwire.com.models.User; public class EditEstimatedTimeActivity extends AppCompatActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_editestimatedtime); Button ignore = (Button) findViewById(R.id.ignoreButton); Button edit = (Button) findViewById(R.id.editButton); EditText editTextNumber = (EditText) findViewById(R.id.editTextNumber); EditText currentDate = (EditText) findViewById(R.id.currentDate); EditText currentTime = (EditText) findViewById(R.id.currentTime); EditText estimatedDate = (EditText) findViewById(R.id.estimatedDate); EditText estimatedTime = (EditText) findViewById(R.id.estimatedTime); User u = new User("", "", ""); Parked p = new Parked(u.getEmail(), u.getUsername(), u.getPassword(), 3, 2, 1, null); if (p.calcRemEstimate() < 10 * 60) { // κάτω από 10 λεπτά p.Notify(); if (edit != null) { p.setTimeEstimate(p.getTimeEstimate()); } } } }
SoftwareEngineering-22/ParkWire
Android-app/ParkWire/app/src/main/java/parkwire/com/activities/EditEstimatedTimeActivity.java
376
// κάτω από 10 λεπτά
line_comment
el
package parkwire.com.activities; import android.os.Bundle; import android.text.format.Time; import android.widget.Button; import android.widget.EditText; import android.widget.TimePicker; import androidx.appcompat.app.AppCompatActivity; import java.sql.Timestamp; import parkwire.com.R; import parkwire.com.models.Parked; import parkwire.com.models.User; public class EditEstimatedTimeActivity extends AppCompatActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_editestimatedtime); Button ignore = (Button) findViewById(R.id.ignoreButton); Button edit = (Button) findViewById(R.id.editButton); EditText editTextNumber = (EditText) findViewById(R.id.editTextNumber); EditText currentDate = (EditText) findViewById(R.id.currentDate); EditText currentTime = (EditText) findViewById(R.id.currentTime); EditText estimatedDate = (EditText) findViewById(R.id.estimatedDate); EditText estimatedTime = (EditText) findViewById(R.id.estimatedTime); User u = new User("", "", ""); Parked p = new Parked(u.getEmail(), u.getUsername(), u.getPassword(), 3, 2, 1, null); if (p.calcRemEstimate() < 10 * 60) { // κάτω από<SUF> p.Notify(); if (edit != null) { p.setTimeEstimate(p.getTimeEstimate()); } } } }
30052_5
package gr.aueb.softeng.project1801.view.Util; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Filter; import android.widget.Filterable; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import gr.aueb.softeng.project1801.SysUtils.DataRow; import gr.aueb.softeng.project1801.view.R; public class CustomAdapter extends BaseAdapter implements Filterable{ private Context context; private LayoutInflater inflater; private List<DataRow> dataList,copyOfData; private SearchFilter searchFilter = new SearchFilter(); /** * * @param context , the Context that concerns the specific activity */ public CustomAdapter(Context context){ this.context = context; dataList = new ArrayList<>(); copyOfData = new ArrayList<>(); inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } /** * This method returns the number of the objects inside the list * @return the number of the objects */ @Override public int getCount(){ return dataList.size(); } /** * This method returns an object taking into consideration it's position inside the list. * @param position , the position of the object * @return the object */ @Override public Object getItem(int position){ return dataList.get(position); } /** * This method returns the code of an object taking into consideration it's position inside the list. * @param position , the position of the object * @return the code of the object */ @Override public long getItemId(int position){ return position; } /** * This method returns the view taking into consideration the position of the object. * @param position , the position of the object * @param convertView , does not have any use * @param parent , the parent of the view * @return the view */ @Override public View getView(int position, View convertView, ViewGroup parent){ DataRow data = (DataRow) getItem(position); View customView = inflater.inflate(R.layout.custom_row,parent,false); ((TextView) customView.findViewById(R.id.first)).setText(data.getData1()); ((TextView) customView.findViewById(R.id.second)).setText(data.getData2()); String text; if(data.getData4() == null){ text = data.getData3(); }else{ text = data.getData3()+"-"+data.getData4(); } ((TextView) customView.findViewById(R.id.identity)).setText(text); ((TextView) customView.findViewById(R.id.details)).setText("->"); return customView; } //Εχουμε ενα αντιγραφο της λιστας ετσι ωστε οταν κανουμε αναζητηση να φιλτραρουμε το αντιγραγο //και οχι το original. /** * This method loads the data(from the list).It uses a copy of the list and not the original in order to be able to filter our search without any data loss. * @param data , the list with the data */ public void loadData(List<DataRow> data){ this.dataList = data; this.copyOfData = dataList.subList(0,dataList.size()); notifyDataSetChanged(); } /** * This method return the filter. * @return the filter */ @Override public Filter getFilter(){ return searchFilter; } /** * This class extends the filter. */ public class SearchFilter extends Filter{ /** * This method filters the results. * @param constraint , the String of the restriction * @return the filtered results */ @Override protected FilterResults performFiltering(CharSequence constraint) { String searchString = constraint.toString().toLowerCase(); FilterResults searchResults = new FilterResults(); List<DataRow> results = new ArrayList<>(); for(DataRow row : copyOfData){ if(row.getData4() != null){ if(row.getData1().toLowerCase().contains(searchString) || row.getData2().toLowerCase().contains(searchString) || row.getData3().toLowerCase().contains(searchString) || row.getData4().toLowerCase().contains(searchString)){ results.add(row); } }else{ if(row.getData1().toLowerCase().contains(searchString) || row.getData2().toLowerCase().contains(searchString) || row.getData3().toLowerCase().contains(searchString)){ results.add(row); } } } searchResults.values = results; searchResults.count = results.size(); return searchResults; } /** * This method publishes the filtered results. * @param constraint , the String of the restriction * @param results , the results */ @Override protected void publishResults(CharSequence constraint, FilterResults results) { dataList = (List<DataRow>)results.values; notifyDataSetChanged(); } } }
SotirisKot/BusTicketReservation
app/src/main/java/gr/aueb/softeng/project1801/view/Util/CustomAdapter.java
1,243
//Εχουμε ενα αντιγραφο της λιστας ετσι ωστε οταν κανουμε αναζητηση να φιλτραρουμε το αντιγραγο
line_comment
el
package gr.aueb.softeng.project1801.view.Util; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Filter; import android.widget.Filterable; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import gr.aueb.softeng.project1801.SysUtils.DataRow; import gr.aueb.softeng.project1801.view.R; public class CustomAdapter extends BaseAdapter implements Filterable{ private Context context; private LayoutInflater inflater; private List<DataRow> dataList,copyOfData; private SearchFilter searchFilter = new SearchFilter(); /** * * @param context , the Context that concerns the specific activity */ public CustomAdapter(Context context){ this.context = context; dataList = new ArrayList<>(); copyOfData = new ArrayList<>(); inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } /** * This method returns the number of the objects inside the list * @return the number of the objects */ @Override public int getCount(){ return dataList.size(); } /** * This method returns an object taking into consideration it's position inside the list. * @param position , the position of the object * @return the object */ @Override public Object getItem(int position){ return dataList.get(position); } /** * This method returns the code of an object taking into consideration it's position inside the list. * @param position , the position of the object * @return the code of the object */ @Override public long getItemId(int position){ return position; } /** * This method returns the view taking into consideration the position of the object. * @param position , the position of the object * @param convertView , does not have any use * @param parent , the parent of the view * @return the view */ @Override public View getView(int position, View convertView, ViewGroup parent){ DataRow data = (DataRow) getItem(position); View customView = inflater.inflate(R.layout.custom_row,parent,false); ((TextView) customView.findViewById(R.id.first)).setText(data.getData1()); ((TextView) customView.findViewById(R.id.second)).setText(data.getData2()); String text; if(data.getData4() == null){ text = data.getData3(); }else{ text = data.getData3()+"-"+data.getData4(); } ((TextView) customView.findViewById(R.id.identity)).setText(text); ((TextView) customView.findViewById(R.id.details)).setText("->"); return customView; } //Εχουμε ενα<SUF> //και οχι το original. /** * This method loads the data(from the list).It uses a copy of the list and not the original in order to be able to filter our search without any data loss. * @param data , the list with the data */ public void loadData(List<DataRow> data){ this.dataList = data; this.copyOfData = dataList.subList(0,dataList.size()); notifyDataSetChanged(); } /** * This method return the filter. * @return the filter */ @Override public Filter getFilter(){ return searchFilter; } /** * This class extends the filter. */ public class SearchFilter extends Filter{ /** * This method filters the results. * @param constraint , the String of the restriction * @return the filtered results */ @Override protected FilterResults performFiltering(CharSequence constraint) { String searchString = constraint.toString().toLowerCase(); FilterResults searchResults = new FilterResults(); List<DataRow> results = new ArrayList<>(); for(DataRow row : copyOfData){ if(row.getData4() != null){ if(row.getData1().toLowerCase().contains(searchString) || row.getData2().toLowerCase().contains(searchString) || row.getData3().toLowerCase().contains(searchString) || row.getData4().toLowerCase().contains(searchString)){ results.add(row); } }else{ if(row.getData1().toLowerCase().contains(searchString) || row.getData2().toLowerCase().contains(searchString) || row.getData3().toLowerCase().contains(searchString)){ results.add(row); } } } searchResults.values = results; searchResults.count = results.size(); return searchResults; } /** * This method publishes the filtered results. * @param constraint , the String of the restriction * @param results , the results */ @Override protected void publishResults(CharSequence constraint, FilterResults results) { dataList = (List<DataRow>)results.values; notifyDataSetChanged(); } } }
4748_9
/** * MIT License * * Copyright (c) 2022 Nikolaos Siatras * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package rabbitminer.Cluster.Server; import Extasys.DataFrame; import Extasys.Encryption.Base64Encryptor; import Extasys.ManualResetEvent; import Extasys.Network.TCP.Server.Listener.Exceptions.ClientIsDisconnectedException; import Extasys.Network.TCP.Server.Listener.Exceptions.OutgoingPacketFailedException; import Extasys.Network.TCP.Server.Listener.TCPClientConnection; import Extasys.Network.TCP.Server.Listener.TCPListener; import java.util.HashMap; import java.util.LinkedHashMap; import rabbitminer.Cluster.ClusterCommunicationCommons; import rabbitminer.Cluster.RabbitCluster; import rabbitminer.Cluster.StratumClient.StratumParsers.Parser_RandomX; import rabbitminer.Core.Computer; import rabbitminer.JSON.JSONSerializer; import rabbitminer.Stratum.StratumJob; import rabbitminer.Stratum.StratumJob_RandomX; import rabbitminer.UI.frmClusterControl; /** * * @author Nikos Siatras */ public class ClusterServer extends Extasys.Network.TCP.Server.ExtasysTCPServer { private final RabbitCluster fMyCluster; private final Object fClientsConnectOrDisconnectLock = new Object(); private final HashMap<String, TCPClientConnection> fConnectedClients; private final Thread fPingConnectedClientsThread; public ClusterServer(RabbitCluster myCluster, ClusterServerSettings clusterServerSettings) { super("", "", Computer.getComputerCPUCoresCount(), Computer.getComputerCPUCoresCount() * 2); TCPListener listener = super.AddListener("", clusterServerSettings.getIPAddress(), clusterServerSettings.getPort(), 60000, 10240, 30000, 150, ClusterCommunicationCommons.fETX); listener.setAutoApplyMessageSplitterState(true); listener.setConnectionEncryptor(new Base64Encryptor()); fMyCluster = myCluster; fConnectedClients = new HashMap<>(); // Κάνουμε initialize ενα Thread για να κάνει Ping τους Clients // κάθε 15 δευτερόλεπτα. fPingConnectedClientsThread = new Thread(() -> { final ManualResetEvent evt = new ManualResetEvent(false); while (true) { PingClients(); try { evt.WaitOne(15000); } catch (Exception ex) { } evt.Reset(); } }); fPingConnectedClientsThread.start(); } @Override public void OnDataReceive(TCPClientConnection sender, DataFrame data) { try { String incomingStr = new String(data.getBytes(), "UTF-8"); String[] parts = incomingStr.split(ClusterCommunicationCommons.fMessageSplitter); switch (parts[0]) { case "LOGIN": // O client ζητάει να κάνει login // Το μήνυμα ειναι έτσι: LOGIN + fMessageSplitter + Password + fMessageSplitter + Αριθμός Thread if (parts[1].equals(fMyCluster.getClusterServerSettings().getPassword())) { int threadsCount = Integer.parseInt(parts[2]); // Αν το Password είναι σωστό τότε δημιουργούμε NodeTCPConnectionVariables // για τον client-node που ζητάει να συνδεθεί NodeTCPConnectionVariables var = new NodeTCPConnectionVariables(); var.ClientLoggedInSucessfully(); var.setThreadsCount(threadsCount); sender.setTag(var); // Ειδοποιούμε το Node οτι συνδέθηκε sender.SendData("AUTHORIZED" + ClusterCommunicationCommons.fMessageSplitter); } else { sender.SendData("WRONG_PASSWORD" + ClusterCommunicationCommons.fMessageSplitter); } break; case "GET_JOB": if (CheckIfClientIsAuthorized(sender)) { // Ζήτα απο το Cluster να φτιάξει ένα // job για να το δώσουμε στο Node StratumJob job = fMyCluster.GiveNodeAJobToDo(sender); if (job != null) { sender.SendData("JOB" + ClusterCommunicationCommons.fMessageSplitter + job.toJSON()); } else { // Δεν υπάρχει Job.... sender.SendData("NO_JOB" + ClusterCommunicationCommons.fMessageSplitter); } } break; case "JOB_SOLVED": if (CheckIfClientIsAuthorized(sender)) { final String jobID = parts[1]; final String extranonce2 = parts[2]; final String nTime = parts[3]; final String nonce = parts[4]; String submitJobStr = "{\"params\": [\"#WORKER_NAME#\", \"#JOB_ID#\", \"#EXTRANONCE_2#\", \"#NTIME#\", \"#NONCE#\"], \"id\": #STRATUM_MESSAGE_ID#, \"method\": \"mining.submit\"}"; submitJobStr = submitJobStr.replace("#WORKER_NAME#", fMyCluster.getStratumPoolSettings().getUsername()); submitJobStr = submitJobStr.replace("#JOB_ID#", jobID); submitJobStr = submitJobStr.replace("#EXTRANONCE_2#", extranonce2); submitJobStr = submitJobStr.replace("#NTIME#", nTime); submitJobStr = submitJobStr.replace("#NONCE#", nonce); submitJobStr = submitJobStr.replace("#STRATUM_MESSAGE_ID#", String.valueOf(fMyCluster.getStratumClient().getMyParser().getStratumID())); // Καποιο Node ολοκλήρωσε ενα job με επιτυχία! // Στειλε το αποτέλεσμα στον Stratum Server fMyCluster.setCurrentStratumJob(null, false); // SEND DATA fMyCluster.getStratumClient().SendData(submitJobStr + "\n"); fMyCluster.fJobsSubmitted += 1; } break; case "JOB_SOLVED_RANDOMX": if (CheckIfClientIsAuthorized(sender)) { StratumJob_RandomX randomXJobSolved = new StratumJob_RandomX(parts[1]); LinkedHashMap solvedJobParams = new LinkedHashMap(); solvedJobParams.put("id", Parser_RandomX.fPoolLoginID); solvedJobParams.put("job_id", randomXJobSolved.getJobID()); solvedJobParams.put("nonce", randomXJobSolved.getSolution_NonceHexlifyByteArray()); solvedJobParams.put("result", randomXJobSolved.getSolution_HashHexlifyByteArray()); LinkedHashMap messageToPool = new LinkedHashMap(); messageToPool.put("id", 1); messageToPool.put("jsonrpc", "2.0"); messageToPool.put("method", "submit"); messageToPool.put("params", solvedJobParams); String dataToSend = JSONSerializer.SerializeObject(messageToPool); System.err.println(dataToSend); fMyCluster.getStratumClient().SendData(dataToSend + "\n"); System.out.println("SOLVED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); // Καποιο Node ολοκλήρωσε ενα job με επιτυχία! // Στειλε το αποτέλεσμα στον Stratum Server fMyCluster.setCurrentStratumJob(null, false); } break; case "PONG": if (CheckIfClientIsAuthorized(sender)) { } break; } } catch (Exception ex) { } } /** * Ελέγχει αν ο client έχει κάνει connect σωστά. Με σωστό password κτλ... * * @param client * @return */ private boolean CheckIfClientIsAuthorized(TCPClientConnection client) { if (client.getTag() != null) { NodeTCPConnectionVariables var = (NodeTCPConnectionVariables) client.getTag(); return var.isClientAuthorized(); } return false; } @Override public void OnClientConnect(TCPClientConnection client) { synchronized (fClientsConnectOrDisconnectLock) { fConnectedClients.put(client.getIPAddress(), client); // Πές στη φόρμα frmClusterControl οτι ένα Node συνδέθηκε frmClusterControl.ACTIVE_INSTANCE.NodeConnected(client); } } @Override public void OnClientDisconnect(TCPClientConnection client) { synchronized (fClientsConnectOrDisconnectLock) { if (fConnectedClients.containsKey(client.getIPAddress())) { fConnectedClients.remove(client.getIPAddress()); // Πές στη φόρμα frmClusterControl οτι ένα Node συνδέθηκε frmClusterControl.ACTIVE_INSTANCE.NodeDisconnected(client); } } } public void InformClientsToCleanJobs() { synchronized (fClientsConnectOrDisconnectLock) { fConnectedClients.values().forEach(client -> { try { client.SendData("CLEAN_JOBS" + ClusterCommunicationCommons.fMessageSplitter); } catch (ClientIsDisconnectedException | OutgoingPacketFailedException ex) { } }); } } /** * Στείλε Ping σε όλους τους Clients */ private void PingClients() { synchronized (fClientsConnectOrDisconnectLock) { fConnectedClients.values().forEach(con -> { try { con.SendData("PING" + ClusterCommunicationCommons.fMessageSplitter); } catch (ClientIsDisconnectedException | OutgoingPacketFailedException ex) { } }); } } public HashMap<String, TCPClientConnection> getConnectedClients() { return fConnectedClients; } public void ClearRangesFromClients() { synchronized (fClientsConnectOrDisconnectLock) { fConnectedClients.values().forEach(con -> { try { ((NodeTCPConnectionVariables) con.getTag()).setWorkRange(0, 0); } catch (Exception ex) { } }); } } }
SourceRabbit/Rabbit_Miner
RabbitMiner/src/rabbitminer/Cluster/Server/ClusterServer.java
2,805
// Ζήτα απο το Cluster να φτιάξει ένα
line_comment
el
/** * MIT License * * Copyright (c) 2022 Nikolaos Siatras * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package rabbitminer.Cluster.Server; import Extasys.DataFrame; import Extasys.Encryption.Base64Encryptor; import Extasys.ManualResetEvent; import Extasys.Network.TCP.Server.Listener.Exceptions.ClientIsDisconnectedException; import Extasys.Network.TCP.Server.Listener.Exceptions.OutgoingPacketFailedException; import Extasys.Network.TCP.Server.Listener.TCPClientConnection; import Extasys.Network.TCP.Server.Listener.TCPListener; import java.util.HashMap; import java.util.LinkedHashMap; import rabbitminer.Cluster.ClusterCommunicationCommons; import rabbitminer.Cluster.RabbitCluster; import rabbitminer.Cluster.StratumClient.StratumParsers.Parser_RandomX; import rabbitminer.Core.Computer; import rabbitminer.JSON.JSONSerializer; import rabbitminer.Stratum.StratumJob; import rabbitminer.Stratum.StratumJob_RandomX; import rabbitminer.UI.frmClusterControl; /** * * @author Nikos Siatras */ public class ClusterServer extends Extasys.Network.TCP.Server.ExtasysTCPServer { private final RabbitCluster fMyCluster; private final Object fClientsConnectOrDisconnectLock = new Object(); private final HashMap<String, TCPClientConnection> fConnectedClients; private final Thread fPingConnectedClientsThread; public ClusterServer(RabbitCluster myCluster, ClusterServerSettings clusterServerSettings) { super("", "", Computer.getComputerCPUCoresCount(), Computer.getComputerCPUCoresCount() * 2); TCPListener listener = super.AddListener("", clusterServerSettings.getIPAddress(), clusterServerSettings.getPort(), 60000, 10240, 30000, 150, ClusterCommunicationCommons.fETX); listener.setAutoApplyMessageSplitterState(true); listener.setConnectionEncryptor(new Base64Encryptor()); fMyCluster = myCluster; fConnectedClients = new HashMap<>(); // Κάνουμε initialize ενα Thread για να κάνει Ping τους Clients // κάθε 15 δευτερόλεπτα. fPingConnectedClientsThread = new Thread(() -> { final ManualResetEvent evt = new ManualResetEvent(false); while (true) { PingClients(); try { evt.WaitOne(15000); } catch (Exception ex) { } evt.Reset(); } }); fPingConnectedClientsThread.start(); } @Override public void OnDataReceive(TCPClientConnection sender, DataFrame data) { try { String incomingStr = new String(data.getBytes(), "UTF-8"); String[] parts = incomingStr.split(ClusterCommunicationCommons.fMessageSplitter); switch (parts[0]) { case "LOGIN": // O client ζητάει να κάνει login // Το μήνυμα ειναι έτσι: LOGIN + fMessageSplitter + Password + fMessageSplitter + Αριθμός Thread if (parts[1].equals(fMyCluster.getClusterServerSettings().getPassword())) { int threadsCount = Integer.parseInt(parts[2]); // Αν το Password είναι σωστό τότε δημιουργούμε NodeTCPConnectionVariables // για τον client-node που ζητάει να συνδεθεί NodeTCPConnectionVariables var = new NodeTCPConnectionVariables(); var.ClientLoggedInSucessfully(); var.setThreadsCount(threadsCount); sender.setTag(var); // Ειδοποιούμε το Node οτι συνδέθηκε sender.SendData("AUTHORIZED" + ClusterCommunicationCommons.fMessageSplitter); } else { sender.SendData("WRONG_PASSWORD" + ClusterCommunicationCommons.fMessageSplitter); } break; case "GET_JOB": if (CheckIfClientIsAuthorized(sender)) { // Ζήτα απο<SUF> // job για να το δώσουμε στο Node StratumJob job = fMyCluster.GiveNodeAJobToDo(sender); if (job != null) { sender.SendData("JOB" + ClusterCommunicationCommons.fMessageSplitter + job.toJSON()); } else { // Δεν υπάρχει Job.... sender.SendData("NO_JOB" + ClusterCommunicationCommons.fMessageSplitter); } } break; case "JOB_SOLVED": if (CheckIfClientIsAuthorized(sender)) { final String jobID = parts[1]; final String extranonce2 = parts[2]; final String nTime = parts[3]; final String nonce = parts[4]; String submitJobStr = "{\"params\": [\"#WORKER_NAME#\", \"#JOB_ID#\", \"#EXTRANONCE_2#\", \"#NTIME#\", \"#NONCE#\"], \"id\": #STRATUM_MESSAGE_ID#, \"method\": \"mining.submit\"}"; submitJobStr = submitJobStr.replace("#WORKER_NAME#", fMyCluster.getStratumPoolSettings().getUsername()); submitJobStr = submitJobStr.replace("#JOB_ID#", jobID); submitJobStr = submitJobStr.replace("#EXTRANONCE_2#", extranonce2); submitJobStr = submitJobStr.replace("#NTIME#", nTime); submitJobStr = submitJobStr.replace("#NONCE#", nonce); submitJobStr = submitJobStr.replace("#STRATUM_MESSAGE_ID#", String.valueOf(fMyCluster.getStratumClient().getMyParser().getStratumID())); // Καποιο Node ολοκλήρωσε ενα job με επιτυχία! // Στειλε το αποτέλεσμα στον Stratum Server fMyCluster.setCurrentStratumJob(null, false); // SEND DATA fMyCluster.getStratumClient().SendData(submitJobStr + "\n"); fMyCluster.fJobsSubmitted += 1; } break; case "JOB_SOLVED_RANDOMX": if (CheckIfClientIsAuthorized(sender)) { StratumJob_RandomX randomXJobSolved = new StratumJob_RandomX(parts[1]); LinkedHashMap solvedJobParams = new LinkedHashMap(); solvedJobParams.put("id", Parser_RandomX.fPoolLoginID); solvedJobParams.put("job_id", randomXJobSolved.getJobID()); solvedJobParams.put("nonce", randomXJobSolved.getSolution_NonceHexlifyByteArray()); solvedJobParams.put("result", randomXJobSolved.getSolution_HashHexlifyByteArray()); LinkedHashMap messageToPool = new LinkedHashMap(); messageToPool.put("id", 1); messageToPool.put("jsonrpc", "2.0"); messageToPool.put("method", "submit"); messageToPool.put("params", solvedJobParams); String dataToSend = JSONSerializer.SerializeObject(messageToPool); System.err.println(dataToSend); fMyCluster.getStratumClient().SendData(dataToSend + "\n"); System.out.println("SOLVED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); // Καποιο Node ολοκλήρωσε ενα job με επιτυχία! // Στειλε το αποτέλεσμα στον Stratum Server fMyCluster.setCurrentStratumJob(null, false); } break; case "PONG": if (CheckIfClientIsAuthorized(sender)) { } break; } } catch (Exception ex) { } } /** * Ελέγχει αν ο client έχει κάνει connect σωστά. Με σωστό password κτλ... * * @param client * @return */ private boolean CheckIfClientIsAuthorized(TCPClientConnection client) { if (client.getTag() != null) { NodeTCPConnectionVariables var = (NodeTCPConnectionVariables) client.getTag(); return var.isClientAuthorized(); } return false; } @Override public void OnClientConnect(TCPClientConnection client) { synchronized (fClientsConnectOrDisconnectLock) { fConnectedClients.put(client.getIPAddress(), client); // Πές στη φόρμα frmClusterControl οτι ένα Node συνδέθηκε frmClusterControl.ACTIVE_INSTANCE.NodeConnected(client); } } @Override public void OnClientDisconnect(TCPClientConnection client) { synchronized (fClientsConnectOrDisconnectLock) { if (fConnectedClients.containsKey(client.getIPAddress())) { fConnectedClients.remove(client.getIPAddress()); // Πές στη φόρμα frmClusterControl οτι ένα Node συνδέθηκε frmClusterControl.ACTIVE_INSTANCE.NodeDisconnected(client); } } } public void InformClientsToCleanJobs() { synchronized (fClientsConnectOrDisconnectLock) { fConnectedClients.values().forEach(client -> { try { client.SendData("CLEAN_JOBS" + ClusterCommunicationCommons.fMessageSplitter); } catch (ClientIsDisconnectedException | OutgoingPacketFailedException ex) { } }); } } /** * Στείλε Ping σε όλους τους Clients */ private void PingClients() { synchronized (fClientsConnectOrDisconnectLock) { fConnectedClients.values().forEach(con -> { try { con.SendData("PING" + ClusterCommunicationCommons.fMessageSplitter); } catch (ClientIsDisconnectedException | OutgoingPacketFailedException ex) { } }); } } public HashMap<String, TCPClientConnection> getConnectedClients() { return fConnectedClients; } public void ClearRangesFromClients() { synchronized (fClientsConnectOrDisconnectLock) { fConnectedClients.values().forEach(con -> { try { ((NodeTCPConnectionVariables) con.getTag()).setWorkRange(0, 0); } catch (Exception ex) { } }); } } }
6154_11
package com.example.touristguide; import androidx.fragment.app.FragmentActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.content.res.Configuration; import androidx.appcompat.app.AppCompatActivity; import java.util.Locale; import android.view.MenuItem; import android.widget.PopupMenu; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.start_screen); Button filtersButton = findViewById(R.id.filtersButton); filtersButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showPopupMenu(v); } }); } private void showPopupMenu(View view) { PopupMenu popupMenu = new PopupMenu(this, view); popupMenu.getMenuInflater().inflate(R.menu.filters_menu, popupMenu.getMenu()); // Προσθέστε ακροατές γεγονότων για τις επιλογές του μενού popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.filter_option_1: // Εκτελέστε κάποια ενέργεια για την επιλογή 1 return true; case R.id.filter_option_2: // Εκτελέστε κάποια ενέργεια για την επιλογή 2 return true; // Προσθέστε περισσότερες περιπτώσεις αν χρειάζεται default: return false; } } }); popupMenu.show(); } } popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.filter_option_1: // Εκτέλεση κάποιας ενέργειας για την Επιλογή 1 doSomethingForFilterOption1(); return true; case R.id.filter_option_2: // Εκτέλεση κάποιας ενέργειας για την Επιλογή 2 doSomethingForFilterOption2(); return true; case R.id.filter_option_3: // Εκτέλεση κάποιας ενέργειας για την Επιλογή 3 doSomethingForFilterOption3(); return true; // Προσθήκη επιπλέον περιπτώσεων αν χρειάζεται default: return false; } } }); public class MainActivity extends FragmentActivity implements View.OnClickListener { Button startButton ; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.start_screen); startButton = findViewById(R.id.startButton); startButton.setOnClickListener(this); } @Override public void onClick(View v) { Intent intent = new Intent(v.getContext(), MapsActivity.class); startActivity(intent); } } public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.start_screen); Button languageButton = findViewById(R.id.languageButton); languageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Καλέστε τη μέθοδο για την αλλαγή της γλώσσας changeLanguage("en"); // Εδώ χρησιμοποιείται η κωδική ονομασία για τα Αγγλικά ("en") } }); } // Μέθοδος για την αλλαγή της γλώσσας private void changeLanguage(String languageCode) { Locale locale = new Locale(languageCode); Locale.setDefault(locale); Configuration configuration = new Configuration(); configuration.setLocale(locale); getResources().updateConfiguration(configuration, getBaseContext().getResources().getDisplayMetrics()); // Εδώ μπορείτε να ξανα-φορτώσετε τη δραστηριότητά σας για να εφαρμοστεί η αλλαγή recreate(); } private void applyFilters() { // Εδώ θα προσθέσετε την λογική για την εφαρμογή των φίλτρων // Π.χ., εμφάνιση μηνύματος κατά την εφαρμογή των φίλτρων Toast.makeText(this, "Εφαρμογή των φίλτρων", Toast.LENGTH_SHORT).show(); } }
Stathis001/Tourist_Guide
app/src/main/java/com/example/touristguide/MainActivity.java
1,445
// Εδώ μπορείτε να ξανα-φορτώσετε τη δραστηριότητά σας για να εφαρμοστεί η αλλαγή
line_comment
el
package com.example.touristguide; import androidx.fragment.app.FragmentActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.content.res.Configuration; import androidx.appcompat.app.AppCompatActivity; import java.util.Locale; import android.view.MenuItem; import android.widget.PopupMenu; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.start_screen); Button filtersButton = findViewById(R.id.filtersButton); filtersButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showPopupMenu(v); } }); } private void showPopupMenu(View view) { PopupMenu popupMenu = new PopupMenu(this, view); popupMenu.getMenuInflater().inflate(R.menu.filters_menu, popupMenu.getMenu()); // Προσθέστε ακροατές γεγονότων για τις επιλογές του μενού popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.filter_option_1: // Εκτελέστε κάποια ενέργεια για την επιλογή 1 return true; case R.id.filter_option_2: // Εκτελέστε κάποια ενέργεια για την επιλογή 2 return true; // Προσθέστε περισσότερες περιπτώσεις αν χρειάζεται default: return false; } } }); popupMenu.show(); } } popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.filter_option_1: // Εκτέλεση κάποιας ενέργειας για την Επιλογή 1 doSomethingForFilterOption1(); return true; case R.id.filter_option_2: // Εκτέλεση κάποιας ενέργειας για την Επιλογή 2 doSomethingForFilterOption2(); return true; case R.id.filter_option_3: // Εκτέλεση κάποιας ενέργειας για την Επιλογή 3 doSomethingForFilterOption3(); return true; // Προσθήκη επιπλέον περιπτώσεων αν χρειάζεται default: return false; } } }); public class MainActivity extends FragmentActivity implements View.OnClickListener { Button startButton ; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.start_screen); startButton = findViewById(R.id.startButton); startButton.setOnClickListener(this); } @Override public void onClick(View v) { Intent intent = new Intent(v.getContext(), MapsActivity.class); startActivity(intent); } } public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.start_screen); Button languageButton = findViewById(R.id.languageButton); languageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Καλέστε τη μέθοδο για την αλλαγή της γλώσσας changeLanguage("en"); // Εδώ χρησιμοποιείται η κωδική ονομασία για τα Αγγλικά ("en") } }); } // Μέθοδος για την αλλαγή της γλώσσας private void changeLanguage(String languageCode) { Locale locale = new Locale(languageCode); Locale.setDefault(locale); Configuration configuration = new Configuration(); configuration.setLocale(locale); getResources().updateConfiguration(configuration, getBaseContext().getResources().getDisplayMetrics()); // Εδώ μπορείτε<SUF> recreate(); } private void applyFilters() { // Εδώ θα προσθέσετε την λογική για την εφαρμογή των φίλτρων // Π.χ., εμφάνιση μηνύματος κατά την εφαρμογή των φίλτρων Toast.makeText(this, "Εφαρμογή των φίλτρων", Toast.LENGTH_SHORT).show(); } }
5788_3
/* * 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 gr.csd.uoc.cs359.winter2020.photobook; import gr.csd.uoc.cs359.winter2020.photobook.db.PostDB; import gr.csd.uoc.cs359.winter2020.photobook.db.UserDB; import gr.csd.uoc.cs359.winter2020.photobook.model.Post; import gr.csd.uoc.cs359.winter2020.photobook.model.User; import java.util.List; /** * * @author papadako */ public class ExampleAPI { /** * An example of adding a new member in the database. Turing is a user of * our system * * @param args the command line arguments * @throws ClassNotFoundException * @throws java.lang.InterruptedException */ public static void main(String[] args) throws ClassNotFoundException, InterruptedException { // O Turing έσπασε τον κώδικα enigma που χρησιμοποιούσαν οι Γερμανοί // στον Παγκόσμιο Πόλεμο ΙΙ για να κρυπτογραφήσουν την επικοινωνία τους. // Άρα είναι πιθανό να χρησιμοποιούσε σαν passwd τη λέξη enigma, κάπως // τροποποιημένη :) // http://en.wikipedia.org/wiki/Enigma_machine // md5 της λέξης 3n!gm@ είναι e37f7cfcb0cd53734184de812b5c6175 User user = new User(); user.setUserName("turing"); user.setEmail("[email protected]"); user.setPassword("e37f7cfcb0cd53734184de812b5c6175"); user.setFirstName("Alan"); user.setLastName("Turing"); user.setBirthDate("07/07/1912"); user.setCountry("Science"); user.setTown("Computer Science"); user.setAddress("Computability"); user.setOccupation("Xompistas"); user.setGender("Male"); user.setInterests("Enigma, decyphering"); user.setInfo("You will have a job due to my work! :)"); if (UserDB.checkValidUserName("turing")) { // Add turing to database System.out.println("==>Adding users"); UserDB.addUser(user); System.out.println(user.toString()); System.out.println("==>Added user"); } else { System.out.println("User already exists.... No more Turings please!"); } List<User> users = UserDB.getUsers(); int i = 0; System.out.println("==>Retrieving"); for (User userIt : users) { System.out.println("userIt:" + i++); System.out.println(userIt); } // Add a wish as info System.out.println("==>Updating"); user = UserDB.getUser("turing"); if (user != null) { System.out.println("Updating" + user.getUserName()); user.setInfo("I hope you follow my path..."); UserDB.updateUser(user); } user = UserDB.getUser("turing"); if (user != null) { System.out.println("==>Updated"); System.out.println(UserDB.getUser("turing")); } Post post = new Post(); post.setUserName("kernelpanic"); post.setDescription("This is my first post"); PostDB.addPost(post); System.out.println("==>Deleting"); UserDB.deleteUser("turing"); System.out.println("==>Deleted"); if (UserDB.checkValidUserName("turing")) { // You can be a new Turing! System.out.println("Well, Turing is gone for a long time now!"); System.out.println("Hope we find a new one in this 2019 class!"); } } }
StefPler/Servlet
src/main/java/gr/csd/uoc/cs359/winter2020/photobook/ExampleAPI.java
1,131
// O Turing έσπασε τον κώδικα enigma που χρησιμοποιούσαν οι Γερμανοί
line_comment
el
/* * 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 gr.csd.uoc.cs359.winter2020.photobook; import gr.csd.uoc.cs359.winter2020.photobook.db.PostDB; import gr.csd.uoc.cs359.winter2020.photobook.db.UserDB; import gr.csd.uoc.cs359.winter2020.photobook.model.Post; import gr.csd.uoc.cs359.winter2020.photobook.model.User; import java.util.List; /** * * @author papadako */ public class ExampleAPI { /** * An example of adding a new member in the database. Turing is a user of * our system * * @param args the command line arguments * @throws ClassNotFoundException * @throws java.lang.InterruptedException */ public static void main(String[] args) throws ClassNotFoundException, InterruptedException { // O Turing<SUF> // στον Παγκόσμιο Πόλεμο ΙΙ για να κρυπτογραφήσουν την επικοινωνία τους. // Άρα είναι πιθανό να χρησιμοποιούσε σαν passwd τη λέξη enigma, κάπως // τροποποιημένη :) // http://en.wikipedia.org/wiki/Enigma_machine // md5 της λέξης 3n!gm@ είναι e37f7cfcb0cd53734184de812b5c6175 User user = new User(); user.setUserName("turing"); user.setEmail("[email protected]"); user.setPassword("e37f7cfcb0cd53734184de812b5c6175"); user.setFirstName("Alan"); user.setLastName("Turing"); user.setBirthDate("07/07/1912"); user.setCountry("Science"); user.setTown("Computer Science"); user.setAddress("Computability"); user.setOccupation("Xompistas"); user.setGender("Male"); user.setInterests("Enigma, decyphering"); user.setInfo("You will have a job due to my work! :)"); if (UserDB.checkValidUserName("turing")) { // Add turing to database System.out.println("==>Adding users"); UserDB.addUser(user); System.out.println(user.toString()); System.out.println("==>Added user"); } else { System.out.println("User already exists.... No more Turings please!"); } List<User> users = UserDB.getUsers(); int i = 0; System.out.println("==>Retrieving"); for (User userIt : users) { System.out.println("userIt:" + i++); System.out.println(userIt); } // Add a wish as info System.out.println("==>Updating"); user = UserDB.getUser("turing"); if (user != null) { System.out.println("Updating" + user.getUserName()); user.setInfo("I hope you follow my path..."); UserDB.updateUser(user); } user = UserDB.getUser("turing"); if (user != null) { System.out.println("==>Updated"); System.out.println(UserDB.getUser("turing")); } Post post = new Post(); post.setUserName("kernelpanic"); post.setDescription("This is my first post"); PostDB.addPost(post); System.out.println("==>Deleting"); UserDB.deleteUser("turing"); System.out.println("==>Deleted"); if (UserDB.checkValidUserName("turing")) { // You can be a new Turing! System.out.println("Well, Turing is gone for a long time now!"); System.out.println("Hope we find a new one in this 2019 class!"); } } }
1560_37
package com.example.androidergasia; import android.content.ContentValues; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.os.LocaleList; import android.util.Pair; import androidx.annotation.Nullable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; public class DBhandler extends SQLiteOpenHelper { public static int DATABASE_VERSION = 1; private static int NEW_VERSION; public static final String DATABASE_NAME = "myAPP.db"; public static final String DATABASE_TABLE_PLACES = "places"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_TYPE_OF_PLACE = "type_of_place"; public static final String COLUMN_NAME = "placeName"; public static final String COLUMN_DESCRIPTION = "description"; public static final String COLUMN_RATING = "rating"; public static final String COLUMN_IMAGE ="image"; //Εδω αποθηκέυω path της αντίστοιχης εικόνας! public static final String COLUMN_LONGITUDE = "longitude"; public static final String COLUMN_LATITUDE = "latitude"; //Για το Table που κρατάει τις Κρατήσεις. public static final String DATABASE_TABLE_RESERVATIONS = "reservations"; public static final String COLUMN_RESERVATION_DATE = "reservation_date"; public static final String COLUMN_RESERVATION_TIME = "reservation_time"; public static final String COLUMN_TRACK_PLACE = "id_of_place"; public static final String COLUMN_NUMBER_OF_PEOPLE = "number_of_people"; private static Context context ; //Για table που κρατάει τα favourite places private static final String COLUMN_FAVOURITE_PLACE_ID="id_of_place"; private static final String DATABASE_TABLE_FAVORITE = "favorite"; private final String DB_PATH = "/data/data/com.example.androidergasia/databases/"; private final String DB_NAME = "myAPP.db"; private SQLiteDatabase db = null; public DBhandler(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) { super(context, DATABASE_NAME, factory, version); this.context = context; copyTable(); Controller.setDBhandler(this);//Θέτω τον DBhandler στον Controller. NEW_VERSION = version ; db = getWritableDatabase(); } /** * Μέθοδος που αντιγράφει την ΒΔ που υπάρχει στο φάκελο assets, αν δεν υπάρχει το αντίστοιχο αρχείο. * Το table places περιέχει πληροφορίες για τα μαγαζία του app. */ private void copyTable() { try { String myPath = DB_PATH + DB_NAME; //Path που αποθηκέυεται η ΒΔ της εφαρμογής. File file = new File(myPath); if(file.exists())//Αν υπάρχει ήδη ο φάκελος επιστρέφω { return; } //Αλλίως γράφω στο παραπάνω path την ΒΔ που υπάρχει στο φάκελο assets. InputStream inputStream = context.getAssets().open("myAPP.db"); File outputFile = context.getDatabasePath("myAPP.db"); OutputStream outputStream = new FileOutputStream(outputFile); byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); //Γράφω σταδιακά το αρχείο. } outputStream.flush();//Κλείσιμο πόρων outputStream.close(); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } @Override public void onCreate(SQLiteDatabase db) { } /** * Δημιουργώ ακόμα 2 tables, 1 για που θα αποθηκεύω τις κρατήσεις και 1 * για την αποθήκευση των αγαπημένων μαγαζιών. * Καλείται η onUpgrade καθώς η ΒΔ προυπαρχεί καθώς περιέχει το table places */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if(oldVersion < newVersion) { String CREATE_FAVORITE_TABLE = " CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE_FAVORITE + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_FAVOURITE_PLACE_ID + " INTEGER NOT NULL, " + " FOREIGN KEY(" + COLUMN_FAVOURITE_PLACE_ID + ") REFERENCES places(_id)" + ")"; String CREATE_RESERVATIONS_TABLE = "CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE_RESERVATIONS + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_RESERVATION_DATE + " TEXT NOT NULL," + COLUMN_RESERVATION_TIME + " TEXT NOT NULL," + COLUMN_NUMBER_OF_PEOPLE + " INTEGER NOT NULL," + COLUMN_TRACK_PLACE + " INTEGER," + " FOREIGN KEY(id_of_place) REFERENCES places(_id)" + ")"; db.execSQL(CREATE_RESERVATIONS_TABLE); db.execSQL(CREATE_FAVORITE_TABLE); this.db = db; } } /** * Το PRIMARY KEY EXΕΙ ΑUTOINCREMENT DEN BAZW ID! * @param placeToAdd */ // public void addPlace(Place placeToAdd) // { // ContentValues contentValues = new ContentValues();//KEY-VALUE ΔΟΜΗ // // contentValues.put(COLUMN_NAME, placeToAdd.getName()); // contentValues.put(COLUMN_TYPE_OF_PLACE,placeToAdd.getTypeOfPlace()); // contentValues.put(COLUMN_DESCRIPTION,placeToAdd.getDescription()); // contentValues.put(COLUMN_RATING,placeToAdd.getRating()); // // contentValues.put(COLUMN_CHAIRS_AVAILABLE, placeToAdd.getNumberOfChairs()); // contentValues.put(COLUMN_LATITUDE, placeToAdd.getLatitude()); // contentValues.put(COLUMN_LONGITUDE,placeToAdd.getLongitude()); // // String pathToFile = "/"+placeToAdd.getTypeOfPlace() + "/" + freeFromSpaces(placeToAdd.getName()) + ".jpg"; // // contentValues.put(COLUMN_IMAGE, pathToFile);//Περίεχει το Path για την εικόνα του Place // // SQLiteDatabase sqLiteDatabase = this.getWritableDatabase(); // sqLiteDatabase.insert(DATABASE_TABLE_PLACES,null, contentValues); // sqLiteDatabase.close(); // } /** * Query που επιστρέφει places με βάση το type_of_place * @param typeOfPlaceToSearch * @return */ public Cursor findPlaces(String typeOfPlaceToSearch) { Resources resources = context.getResources(); //Configurations της συσκευής που μπορεί να επηρεάσουν τα resources του app Configuration configuration = resources.getConfiguration(); LocaleList localeList = configuration.getLocales(); //επιστρέφει λίστα με two-letter lowercase language codes String currentLanguage = localeList.get(0).getLanguage(); //γλώσσα που χρησιμοποιείται απο το κινητό. String description = currentLanguage.equals("el")?"description_gr" : COLUMN_DESCRIPTION; //Ποία απο τις δυο στήλες θα επιστραφεί. String query = "SELECT " + COLUMN_NAME + "," + COLUMN_TYPE_OF_PLACE + "," + description + "," + COLUMN_RATING + "," + COLUMN_LATITUDE + "," + COLUMN_LONGITUDE + "," + COLUMN_IMAGE + " FROM " + DATABASE_TABLE_PLACES + " WHERE " + COLUMN_TYPE_OF_PLACE + " = '" + typeOfPlaceToSearch + "' "; Cursor cursorForReturn = db.rawQuery(query, null); return cursorForReturn; } // /** // * Αφαιρώ τα κένα απο το String, δεν μπορώ να εχώ κενά στο fileSystem // * Επίσης το androidFileSystem δεν δέχεται UpperCase γράμματα, επιστρέφω lowerCase String // * @param toFree // * @return // */ // private String freeFromSpaces(String toFree) // { // if(!toFree.contains(" ")) // { // return toFree; // } // // String[] arrayOfWords = toFree.split(" "); // String spaceFree = ""; // for(int i = 0 ;i < arrayOfWords.length;i++) // { // spaceFree += arrayOfWords[i]; // } // return spaceFree.toLowerCase(); // } /** * @param nameForSearch Όνομα του Place που θα επιστρέψω τα coordinates * @return ενα αντικείμενο τύπου Pair με το latitude, longitude */ public Pair<Float,Float> getCoordinates(String nameForSearch) { String query = "SELECT " + COLUMN_LATITUDE + "," + COLUMN_LONGITUDE + " FROM " + DATABASE_TABLE_PLACES + " WHERE " + COLUMN_NAME + " = '" + nameForSearch + "' "; // SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.rawQuery(query, null); cursor.moveToFirst(); //Ενα μόνο αντικείμενο επιστρέφεται Pair<Float, Float> tempPair = new Pair<>(cursor.getFloat(0),cursor.getFloat(1)); cursor.close(); //απελευθερωση πόρων return tempPair; } /** * @param nameForSearch Όνομα του Place που θα προσθέσω στο table favorite */ public void addPlaceToFavorite(String nameForSearch) { int id = getPlaceID(nameForSearch); // Παίρνω το id απο την μέθοδο getPlaceID ContentValues contentValues = new ContentValues();// key,value δομή contentValues.put(COLUMN_FAVOURITE_PLACE_ID, id); db.insert(DATABASE_TABLE_FAVORITE,null, contentValues);//Προσθήκη στον πίνακα. } /** * Μέθοδος για την αφαίρεση place απο το table favorite, ενημερώνω τον adapter αν βρίσκομαι στο * FavoritesActivity. * @param nameForDelete όνομα του place προς αφαίρεση. */ public void removePlaceFromFavorite(String nameForDelete) { int idOfPlace = getPlaceID(nameForDelete); // Παίρνω το id απο την μέθοδο getPlaceID String condition = COLUMN_FAVOURITE_PLACE_ID + " = " + "?"; String[] conditionArgs = {idOfPlace+""}; db.delete(DATABASE_TABLE_FAVORITE,condition,conditionArgs); if(Controller.isTypeOfAdapter())//Αν είναι το recyclerAdapter του FavoritesActivity. { Controller.getAdapter().removeItem(nameForDelete); //Ενημέρωση του adapter ώστε να αφαιρέσει το αντίστοιχο Place απο το recyclerViewer. } } /** * Μέθοδος που επιστρέφει όλα τα places που έχει επιλέξει ο χρήστης ως favorite * Πραγματοποιείται inner join μεταξύ του πίνακα favorite table και του places table. * Τable favorite έχει ως foreign key το primary key των places. * @return */ public Cursor getFavoritePlaces() { Resources resources = context.getResources(); //Configurations της συσκευής που μπορεί να επηρεάσουν τα resources του app Configuration configuration = resources.getConfiguration(); LocaleList localeList = configuration.getLocales(); //επιστρέφει λίστα με two-letter lowercase language codes String currentLanguage = localeList.get(0).getLanguage(); //γλώσσα που χρησιμοποιείται απο το κινητό. String description = currentLanguage.equals("el")?"description_gr" : COLUMN_DESCRIPTION; //Ποία απο τις δυο στήλες θα επιστραφεί. String query ="SELECT "+ COLUMN_NAME + "," +COLUMN_TYPE_OF_PLACE + ","+ description + "," + COLUMN_RATING + "," + COLUMN_LATITUDE + "," + COLUMN_LONGITUDE + "," + COLUMN_IMAGE + " FROM " + DATABASE_TABLE_PLACES + " INNER JOIN " + DATABASE_TABLE_FAVORITE + " ON "+ DATABASE_TABLE_PLACES+"._id" + "=" + DATABASE_TABLE_FAVORITE + ".id_of_place"; return db.rawQuery(query,null); } /** * Μέθοδος που ελέγχει αν place υπάρχει ως record στον πίνακα των favorite. * @param nameOfPlace όνομα του place * @return 0 αν δεν βρίσκεται αλλιώς επιστρέφει 1 */ public int isInFavoriteTable(String nameOfPlace) { String query = "SELECT " + "_id" + " FROM " + "places " + " WHERE " + "placeName" + " = '" + nameOfPlace + "' "; Cursor cursor = db.rawQuery(query,null); cursor.moveToFirst(); int id = cursor.getInt(0); query = "SELECT " + " * " + " FROM " + " favorite " + " WHERE " + "id_of_place = " + id ; cursor = db.rawQuery(query, null); int toReturnCount = cursor.getCount(); cursor.close(); return toReturnCount; } /** * Μέθοδος για προσθήκη Reservation στο table reservations * @param reservation προς εισαγωγή */ public void addReservation(Reservation reservation) { ContentValues values = new ContentValues(); //key,value δομή. values.put(COLUMN_TRACK_PLACE, reservation.getPlaceId()); values.put(COLUMN_RESERVATION_DATE, reservation.getDate()); values.put(COLUMN_RESERVATION_TIME, reservation.getDateTime()); values.put(COLUMN_NUMBER_OF_PEOPLE, reservation.getNumberOfPeople()); db.insert(DATABASE_TABLE_RESERVATIONS, null, values); } /** * Μέθοδος για την αφαίρεση reservation απο το table * @param idToDelete id του reservation */ public void removeReservation(int idToDelete) { String condition = COLUMN_ID + " = " + "?"; String[] conditionArgs = {idToDelete+""}; db.delete(DATABASE_TABLE_RESERVATIONS, condition, conditionArgs) ; } /** * Μεθοδος που επιστρέφει όλα τα Reservations που υπάρχουν στο table * @return ArrayList με Reservations. */ public ArrayList<Reservation> findReservations() { // SQLiteDatabase db = this.getReadableDatabase(); String query ="SELECT "+ "places."+COLUMN_NAME + "," +"reservations." + COLUMN_RESERVATION_TIME + "," + "reservations." + COLUMN_RESERVATION_DATE + "," + "reservations." + COLUMN_NUMBER_OF_PEOPLE + "," + "reservations." + COLUMN_ID + " FROM " + DATABASE_TABLE_PLACES + " INNER JOIN " + DATABASE_TABLE_RESERVATIONS + " ON "+ DATABASE_TABLE_PLACES+"._id" + "=" + DATABASE_TABLE_RESERVATIONS + ".id_of_place"; return fromCursorToArrayList(db.rawQuery(query, null)); } /** * @param cursor απο το query της μέθοδου findReservations. * @return ArrayList με Reservations. */ private ArrayList<Reservation> fromCursorToArrayList(Cursor cursor) { ArrayList<Reservation> toReturn = new ArrayList<>(); Reservation tempReservation; for(int i = 0 ; i < cursor.getCount(); i++) { cursor.moveToFirst(); cursor.move(i); String nameOfPlace = cursor.getString(0); String time = cursor.getString(1); String date = cursor.getString(2); int numberOfPeople = cursor.getInt(3); int reservationID = cursor.getInt(4); //Δημιουργεία reservation με τα στοιχεία του query. tempReservation = new Reservation(date, time, nameOfPlace, numberOfPeople, reservationID); toReturn.add((tempReservation));//προσθήκη στο arrayList. } return toReturn; } /** * Μέθοδος που δέχεται ώς όρισμα το όνομα ενος Place, επιστρέφει το id του */ public int getPlaceID(String nameForSearch) { String query = "SELECT " + COLUMN_ID + " FROM " + DATABASE_TABLE_PLACES + " WHERE " + COLUMN_NAME + " = '" + nameForSearch + "' "; Cursor cursor = db.rawQuery(query,null); //Εκτέλεση του query. cursor.moveToFirst(); int toReturn = cursor.getInt(0); return toReturn; } }
StylianosBairamis/ReserveIT
app/src/main/java/com/example/androidergasia/DBhandler.java
4,974
//Ενημέρωση του adapter ώστε να αφαιρέσει το αντίστοιχο Place απο το recyclerViewer.
line_comment
el
package com.example.androidergasia; import android.content.ContentValues; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.os.LocaleList; import android.util.Pair; import androidx.annotation.Nullable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; public class DBhandler extends SQLiteOpenHelper { public static int DATABASE_VERSION = 1; private static int NEW_VERSION; public static final String DATABASE_NAME = "myAPP.db"; public static final String DATABASE_TABLE_PLACES = "places"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_TYPE_OF_PLACE = "type_of_place"; public static final String COLUMN_NAME = "placeName"; public static final String COLUMN_DESCRIPTION = "description"; public static final String COLUMN_RATING = "rating"; public static final String COLUMN_IMAGE ="image"; //Εδω αποθηκέυω path της αντίστοιχης εικόνας! public static final String COLUMN_LONGITUDE = "longitude"; public static final String COLUMN_LATITUDE = "latitude"; //Για το Table που κρατάει τις Κρατήσεις. public static final String DATABASE_TABLE_RESERVATIONS = "reservations"; public static final String COLUMN_RESERVATION_DATE = "reservation_date"; public static final String COLUMN_RESERVATION_TIME = "reservation_time"; public static final String COLUMN_TRACK_PLACE = "id_of_place"; public static final String COLUMN_NUMBER_OF_PEOPLE = "number_of_people"; private static Context context ; //Για table που κρατάει τα favourite places private static final String COLUMN_FAVOURITE_PLACE_ID="id_of_place"; private static final String DATABASE_TABLE_FAVORITE = "favorite"; private final String DB_PATH = "/data/data/com.example.androidergasia/databases/"; private final String DB_NAME = "myAPP.db"; private SQLiteDatabase db = null; public DBhandler(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) { super(context, DATABASE_NAME, factory, version); this.context = context; copyTable(); Controller.setDBhandler(this);//Θέτω τον DBhandler στον Controller. NEW_VERSION = version ; db = getWritableDatabase(); } /** * Μέθοδος που αντιγράφει την ΒΔ που υπάρχει στο φάκελο assets, αν δεν υπάρχει το αντίστοιχο αρχείο. * Το table places περιέχει πληροφορίες για τα μαγαζία του app. */ private void copyTable() { try { String myPath = DB_PATH + DB_NAME; //Path που αποθηκέυεται η ΒΔ της εφαρμογής. File file = new File(myPath); if(file.exists())//Αν υπάρχει ήδη ο φάκελος επιστρέφω { return; } //Αλλίως γράφω στο παραπάνω path την ΒΔ που υπάρχει στο φάκελο assets. InputStream inputStream = context.getAssets().open("myAPP.db"); File outputFile = context.getDatabasePath("myAPP.db"); OutputStream outputStream = new FileOutputStream(outputFile); byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); //Γράφω σταδιακά το αρχείο. } outputStream.flush();//Κλείσιμο πόρων outputStream.close(); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } @Override public void onCreate(SQLiteDatabase db) { } /** * Δημιουργώ ακόμα 2 tables, 1 για που θα αποθηκεύω τις κρατήσεις και 1 * για την αποθήκευση των αγαπημένων μαγαζιών. * Καλείται η onUpgrade καθώς η ΒΔ προυπαρχεί καθώς περιέχει το table places */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if(oldVersion < newVersion) { String CREATE_FAVORITE_TABLE = " CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE_FAVORITE + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_FAVOURITE_PLACE_ID + " INTEGER NOT NULL, " + " FOREIGN KEY(" + COLUMN_FAVOURITE_PLACE_ID + ") REFERENCES places(_id)" + ")"; String CREATE_RESERVATIONS_TABLE = "CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE_RESERVATIONS + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_RESERVATION_DATE + " TEXT NOT NULL," + COLUMN_RESERVATION_TIME + " TEXT NOT NULL," + COLUMN_NUMBER_OF_PEOPLE + " INTEGER NOT NULL," + COLUMN_TRACK_PLACE + " INTEGER," + " FOREIGN KEY(id_of_place) REFERENCES places(_id)" + ")"; db.execSQL(CREATE_RESERVATIONS_TABLE); db.execSQL(CREATE_FAVORITE_TABLE); this.db = db; } } /** * Το PRIMARY KEY EXΕΙ ΑUTOINCREMENT DEN BAZW ID! * @param placeToAdd */ // public void addPlace(Place placeToAdd) // { // ContentValues contentValues = new ContentValues();//KEY-VALUE ΔΟΜΗ // // contentValues.put(COLUMN_NAME, placeToAdd.getName()); // contentValues.put(COLUMN_TYPE_OF_PLACE,placeToAdd.getTypeOfPlace()); // contentValues.put(COLUMN_DESCRIPTION,placeToAdd.getDescription()); // contentValues.put(COLUMN_RATING,placeToAdd.getRating()); // // contentValues.put(COLUMN_CHAIRS_AVAILABLE, placeToAdd.getNumberOfChairs()); // contentValues.put(COLUMN_LATITUDE, placeToAdd.getLatitude()); // contentValues.put(COLUMN_LONGITUDE,placeToAdd.getLongitude()); // // String pathToFile = "/"+placeToAdd.getTypeOfPlace() + "/" + freeFromSpaces(placeToAdd.getName()) + ".jpg"; // // contentValues.put(COLUMN_IMAGE, pathToFile);//Περίεχει το Path για την εικόνα του Place // // SQLiteDatabase sqLiteDatabase = this.getWritableDatabase(); // sqLiteDatabase.insert(DATABASE_TABLE_PLACES,null, contentValues); // sqLiteDatabase.close(); // } /** * Query που επιστρέφει places με βάση το type_of_place * @param typeOfPlaceToSearch * @return */ public Cursor findPlaces(String typeOfPlaceToSearch) { Resources resources = context.getResources(); //Configurations της συσκευής που μπορεί να επηρεάσουν τα resources του app Configuration configuration = resources.getConfiguration(); LocaleList localeList = configuration.getLocales(); //επιστρέφει λίστα με two-letter lowercase language codes String currentLanguage = localeList.get(0).getLanguage(); //γλώσσα που χρησιμοποιείται απο το κινητό. String description = currentLanguage.equals("el")?"description_gr" : COLUMN_DESCRIPTION; //Ποία απο τις δυο στήλες θα επιστραφεί. String query = "SELECT " + COLUMN_NAME + "," + COLUMN_TYPE_OF_PLACE + "," + description + "," + COLUMN_RATING + "," + COLUMN_LATITUDE + "," + COLUMN_LONGITUDE + "," + COLUMN_IMAGE + " FROM " + DATABASE_TABLE_PLACES + " WHERE " + COLUMN_TYPE_OF_PLACE + " = '" + typeOfPlaceToSearch + "' "; Cursor cursorForReturn = db.rawQuery(query, null); return cursorForReturn; } // /** // * Αφαιρώ τα κένα απο το String, δεν μπορώ να εχώ κενά στο fileSystem // * Επίσης το androidFileSystem δεν δέχεται UpperCase γράμματα, επιστρέφω lowerCase String // * @param toFree // * @return // */ // private String freeFromSpaces(String toFree) // { // if(!toFree.contains(" ")) // { // return toFree; // } // // String[] arrayOfWords = toFree.split(" "); // String spaceFree = ""; // for(int i = 0 ;i < arrayOfWords.length;i++) // { // spaceFree += arrayOfWords[i]; // } // return spaceFree.toLowerCase(); // } /** * @param nameForSearch Όνομα του Place που θα επιστρέψω τα coordinates * @return ενα αντικείμενο τύπου Pair με το latitude, longitude */ public Pair<Float,Float> getCoordinates(String nameForSearch) { String query = "SELECT " + COLUMN_LATITUDE + "," + COLUMN_LONGITUDE + " FROM " + DATABASE_TABLE_PLACES + " WHERE " + COLUMN_NAME + " = '" + nameForSearch + "' "; // SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.rawQuery(query, null); cursor.moveToFirst(); //Ενα μόνο αντικείμενο επιστρέφεται Pair<Float, Float> tempPair = new Pair<>(cursor.getFloat(0),cursor.getFloat(1)); cursor.close(); //απελευθερωση πόρων return tempPair; } /** * @param nameForSearch Όνομα του Place που θα προσθέσω στο table favorite */ public void addPlaceToFavorite(String nameForSearch) { int id = getPlaceID(nameForSearch); // Παίρνω το id απο την μέθοδο getPlaceID ContentValues contentValues = new ContentValues();// key,value δομή contentValues.put(COLUMN_FAVOURITE_PLACE_ID, id); db.insert(DATABASE_TABLE_FAVORITE,null, contentValues);//Προσθήκη στον πίνακα. } /** * Μέθοδος για την αφαίρεση place απο το table favorite, ενημερώνω τον adapter αν βρίσκομαι στο * FavoritesActivity. * @param nameForDelete όνομα του place προς αφαίρεση. */ public void removePlaceFromFavorite(String nameForDelete) { int idOfPlace = getPlaceID(nameForDelete); // Παίρνω το id απο την μέθοδο getPlaceID String condition = COLUMN_FAVOURITE_PLACE_ID + " = " + "?"; String[] conditionArgs = {idOfPlace+""}; db.delete(DATABASE_TABLE_FAVORITE,condition,conditionArgs); if(Controller.isTypeOfAdapter())//Αν είναι το recyclerAdapter του FavoritesActivity. { Controller.getAdapter().removeItem(nameForDelete); //Ενημέρωση του<SUF> } } /** * Μέθοδος που επιστρέφει όλα τα places που έχει επιλέξει ο χρήστης ως favorite * Πραγματοποιείται inner join μεταξύ του πίνακα favorite table και του places table. * Τable favorite έχει ως foreign key το primary key των places. * @return */ public Cursor getFavoritePlaces() { Resources resources = context.getResources(); //Configurations της συσκευής που μπορεί να επηρεάσουν τα resources του app Configuration configuration = resources.getConfiguration(); LocaleList localeList = configuration.getLocales(); //επιστρέφει λίστα με two-letter lowercase language codes String currentLanguage = localeList.get(0).getLanguage(); //γλώσσα που χρησιμοποιείται απο το κινητό. String description = currentLanguage.equals("el")?"description_gr" : COLUMN_DESCRIPTION; //Ποία απο τις δυο στήλες θα επιστραφεί. String query ="SELECT "+ COLUMN_NAME + "," +COLUMN_TYPE_OF_PLACE + ","+ description + "," + COLUMN_RATING + "," + COLUMN_LATITUDE + "," + COLUMN_LONGITUDE + "," + COLUMN_IMAGE + " FROM " + DATABASE_TABLE_PLACES + " INNER JOIN " + DATABASE_TABLE_FAVORITE + " ON "+ DATABASE_TABLE_PLACES+"._id" + "=" + DATABASE_TABLE_FAVORITE + ".id_of_place"; return db.rawQuery(query,null); } /** * Μέθοδος που ελέγχει αν place υπάρχει ως record στον πίνακα των favorite. * @param nameOfPlace όνομα του place * @return 0 αν δεν βρίσκεται αλλιώς επιστρέφει 1 */ public int isInFavoriteTable(String nameOfPlace) { String query = "SELECT " + "_id" + " FROM " + "places " + " WHERE " + "placeName" + " = '" + nameOfPlace + "' "; Cursor cursor = db.rawQuery(query,null); cursor.moveToFirst(); int id = cursor.getInt(0); query = "SELECT " + " * " + " FROM " + " favorite " + " WHERE " + "id_of_place = " + id ; cursor = db.rawQuery(query, null); int toReturnCount = cursor.getCount(); cursor.close(); return toReturnCount; } /** * Μέθοδος για προσθήκη Reservation στο table reservations * @param reservation προς εισαγωγή */ public void addReservation(Reservation reservation) { ContentValues values = new ContentValues(); //key,value δομή. values.put(COLUMN_TRACK_PLACE, reservation.getPlaceId()); values.put(COLUMN_RESERVATION_DATE, reservation.getDate()); values.put(COLUMN_RESERVATION_TIME, reservation.getDateTime()); values.put(COLUMN_NUMBER_OF_PEOPLE, reservation.getNumberOfPeople()); db.insert(DATABASE_TABLE_RESERVATIONS, null, values); } /** * Μέθοδος για την αφαίρεση reservation απο το table * @param idToDelete id του reservation */ public void removeReservation(int idToDelete) { String condition = COLUMN_ID + " = " + "?"; String[] conditionArgs = {idToDelete+""}; db.delete(DATABASE_TABLE_RESERVATIONS, condition, conditionArgs) ; } /** * Μεθοδος που επιστρέφει όλα τα Reservations που υπάρχουν στο table * @return ArrayList με Reservations. */ public ArrayList<Reservation> findReservations() { // SQLiteDatabase db = this.getReadableDatabase(); String query ="SELECT "+ "places."+COLUMN_NAME + "," +"reservations." + COLUMN_RESERVATION_TIME + "," + "reservations." + COLUMN_RESERVATION_DATE + "," + "reservations." + COLUMN_NUMBER_OF_PEOPLE + "," + "reservations." + COLUMN_ID + " FROM " + DATABASE_TABLE_PLACES + " INNER JOIN " + DATABASE_TABLE_RESERVATIONS + " ON "+ DATABASE_TABLE_PLACES+"._id" + "=" + DATABASE_TABLE_RESERVATIONS + ".id_of_place"; return fromCursorToArrayList(db.rawQuery(query, null)); } /** * @param cursor απο το query της μέθοδου findReservations. * @return ArrayList με Reservations. */ private ArrayList<Reservation> fromCursorToArrayList(Cursor cursor) { ArrayList<Reservation> toReturn = new ArrayList<>(); Reservation tempReservation; for(int i = 0 ; i < cursor.getCount(); i++) { cursor.moveToFirst(); cursor.move(i); String nameOfPlace = cursor.getString(0); String time = cursor.getString(1); String date = cursor.getString(2); int numberOfPeople = cursor.getInt(3); int reservationID = cursor.getInt(4); //Δημιουργεία reservation με τα στοιχεία του query. tempReservation = new Reservation(date, time, nameOfPlace, numberOfPeople, reservationID); toReturn.add((tempReservation));//προσθήκη στο arrayList. } return toReturn; } /** * Μέθοδος που δέχεται ώς όρισμα το όνομα ενος Place, επιστρέφει το id του */ public int getPlaceID(String nameForSearch) { String query = "SELECT " + COLUMN_ID + " FROM " + DATABASE_TABLE_PLACES + " WHERE " + COLUMN_NAME + " = '" + nameForSearch + "' "; Cursor cursor = db.rawQuery(query,null); //Εκτέλεση του query. cursor.moveToFirst(); int toReturn = cursor.getInt(0); return toReturn; } }
1557_0
package gui; import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumnModel; import java.awt.*; import java.awt.event.*; import java.util.ArrayList; import api.*; public class App { private static JPanel searchPanel = new JPanel(); private static api.User userOfApp ; private JPanel p2 = new JPanel(); private static JTable table; private static int rowSelected=-999; private static JButton addButton; private static JButton editButton; private static JButton deleteButton; private static JButton showButton; private static JPanel panelForButtons = new JPanel(); private static DefaultTableModel tableModel; private static JFrame AppFrame; private static ArrayList<Slave> frames = new ArrayList<>(); private static int indexForClose; private static ProviderFrame providerFrame; private static JTabbedPane tp; private static ArrayList<AccommodationItem> accItems = new ArrayList<AccommodationItem>(); public static ArrayList<Accommodation> getAccToShow() { return accToShow; } private static ArrayList<Accommodation> accToShow = new ArrayList<>(Accommodation.getAccommodations()); public static void setIndexForClose(int indexForClose1) { indexForClose=indexForClose1; } public static AccommodationItem getAccItemByData(Accommodation a) { for (int i = 0; i < accItems.size(); i++) { if (a.equals(accItems.get(i).getAccommodationInfo())) { return accItems.get(i); } } return null; } public static ArrayList<AccommodationItem> getAccItems() { return accItems; } // App Index public App(User connectedUser, JFrame loginFrame) { // Frame userOfApp=connectedUser; accToShow = Accommodation.getAccommodations(); addButton = new JButton("Add"); editButton = new JButton("Edit"); deleteButton = new JButton("Delete"); showButton = new JButton("Show Statistics"); AppFrame = new JFrame(); AppFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); AppFrame.setTitle("Καταλύματα App"); // Tabbed Pane tp = new JTabbedPane(); createTab(tp,connectedUser); tp.add("Dashboard", p2); createDashBoard(p2); // Έξοδος JPanel p3 = new JPanel(); tp.add("Έξοδος", p3); tp.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if(tp.getSelectedIndex()==indexForClose) { AppFrame.dispose(); loginFrame.setVisible(true); } else if(tp.getSelectedIndex()==1) { ProviderFrame providerFrame = new ProviderFrame(AppFrame); accToShow = SearchTab.createSearchTab(providerFrame,AppFrame); createTab(tp, connectedUser); } } }); AppFrame.setSize(1300,800); AppFrame.setResizable(false); AppFrame.setLayout(null); AppFrame.add(tp); tp.setSize(780,450);//780 είναι το αθροίσμα των μεγεθών των column του JTable; AppFrame.setVisible(true); } protected static void createDashBoard(JPanel panelToFill) { String columnHeaders[] = {"'Ονομα","Τύπος","Πόλη","Διεύθυνση","Ταχυδρομικός Κώδικας","Βαθμός Αξιολόγησης"}; Object[][] data = userOfApp.setDataForTable();//Φέρνω τα data! tableModel = new DefaultTableModel(data, columnHeaders) { @Override public boolean isCellEditable(int row, int column) { return false; } }; table = new JTable(tableModel); table.getTableHeader().setReorderingAllowed(false); setSizeOfColumns(); table.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e)//Για να εμφανίζεται το JInternalFrame { rowSelected=table.getSelectedRow(); Accommodation acc=Accommodation.findAccommodation((String)table.getValueAt(rowSelected,0),(String)table.getValueAt(rowSelected,3), (String)table.getValueAt(rowSelected, 2)); if(frames.size()!=0) { frames.get(0).internalFrame.dispose(); frames.clear(); } frames.add(new Slave(AppFrame,acc,userOfApp)); } }); JScrollPane scrollPane = new JScrollPane(table); panelToFill.setLayout(new BorderLayout()); panelToFill.add(scrollPane,BorderLayout.CENTER); panelForButtons = new JPanel(); if (userOfApp instanceof Provider) { providerFrame = new ProviderFrame(AppFrame); panelForButtons.setLayout(new GridLayout(1,4)); panelForButtons.add(addButton); addButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { providerFrame.createAddFrame((Provider)userOfApp); } }); editButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(rowSelected!=-999) { Accommodation temp=Accommodation.findAccommodation(table.getValueAt(rowSelected,0)+"",table.getValueAt(rowSelected,3)+"",(String)table.getValueAt(rowSelected,2));//Βρίσκω το acc με βάση το όνομα και την διευθυνσή providerFrame.createEditFrame(temp); table.setValueAt(temp.getName(),rowSelected,0);//Ενημέρωση του JTable για να μπορώ να το βρω με την findAccommodation table.setValueAt(temp.getType(),rowSelected,1); table.setValueAt(temp.getCity(),rowSelected, 2 ); table.setValueAt(temp.getRoad(),rowSelected,3); table.setValueAt(temp.getAverage() == -1 ? "Καμία αξιολόγηση." : temp.getAverage() + "",rowSelected,5); rowSelected=-999; Slave.updateTextArea(); } } }); showButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "Μέσος όρος αξιολογήσεων: " + userOfApp.countAverageReviews() + "\n" + "Πλήθος αξιολογήσεων σε όλα τα κατάλυματα σας: " + ((Provider)userOfApp).countReviews()); } }); } else { panelForButtons.setLayout(new GridLayout(1,3)); editButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(rowSelected!=-999) { userOfApp.editAction(rowSelected,table); rowSelected=-999; Slave.updateTextArea(); } } }); showButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "Μέσος όρος αξιολογήσεων: " + userOfApp.countAverageReviews()); } }); } panelForButtons.add(editButton); panelForButtons.add(deleteButton); panelForButtons.add(showButton); panelToFill.add(panelForButtons,BorderLayout.PAGE_END); deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(rowSelected!=-999) { userOfApp.deleteAction(rowSelected,table); tableModel.removeRow(rowSelected);//Αφαιρώ απο το table to review rowSelected=-999; Slave.updateTextArea(); } //Αν rowSelected==-999 δεν έχει κάνει κάπου κλικ ο χρήστης } }); } protected static void addRowToTable(String name,String type,String city,String address,String postalCode,String rating) { tableModel.addRow(new String[]{name, type, city, address, postalCode, rating}); } public void createTab(JTabbedPane tabbedPane, User connectedUser) { if (connectedUser instanceof Customer) { JPanel p1 = new JPanel(); AccommodationItem temp; accItems = new ArrayList<>(); GridLayout accommodationLayout = new GridLayout(1,2); if (accToShow.size() == Accommodation.getAccommodations().size()) { accToShow = Provider.randomAcc(); } for (int i = 0; i < accToShow.size(); i++) { double review_avg = accToShow.get(i).calculateAverage(); String t = review_avg == -1 ? "Καμία Αξιολόγηση." : String.valueOf(review_avg); temp = new AccommodationItem(accToShow.get(i), accToShow.get(i).getName(), t); AccommodationItem finalTemp = temp; temp.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof AccommodationItem) { AccommodationItem t = (AccommodationItem) e.getSource(); if(frames.size()!=0) { frames.get(0).internalFrame.dispose(); frames.clear(); } frames.add(new Slave(AppFrame, finalTemp.getAccommodationInfo(),userOfApp)); } } }); temp.setLayout(accommodationLayout); accItems.add(temp); p1.add(temp); } GridLayout accommodationsLayout = new GridLayout(10,1); p1.setLayout(accommodationsLayout); if (tabbedPane.getTabCount() == 0) { tabbedPane.add("Καταλύματα", p1); tabbedPane.add("Αναζήτηση", searchPanel); } else if (tabbedPane.getTabCount() > 2) { tabbedPane.remove(0); tabbedPane.insertTab("Καταλύματα", null, p1, null, 0); } } } private static void setSizeOfColumns() { TableColumnModel columnModel = table.getColumnModel(); for(int i=0;i<table.getColumnCount();i++) { columnModel.getColumn(i).setPreferredWidth(130); columnModel.getColumn(i).setMaxWidth(130); } table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); } }
StylianosBairamis/oop-myreviews-project
src/gui/App.java
2,738
//780 είναι το αθροίσμα των μεγεθών των column του JTable;
line_comment
el
package gui; import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumnModel; import java.awt.*; import java.awt.event.*; import java.util.ArrayList; import api.*; public class App { private static JPanel searchPanel = new JPanel(); private static api.User userOfApp ; private JPanel p2 = new JPanel(); private static JTable table; private static int rowSelected=-999; private static JButton addButton; private static JButton editButton; private static JButton deleteButton; private static JButton showButton; private static JPanel panelForButtons = new JPanel(); private static DefaultTableModel tableModel; private static JFrame AppFrame; private static ArrayList<Slave> frames = new ArrayList<>(); private static int indexForClose; private static ProviderFrame providerFrame; private static JTabbedPane tp; private static ArrayList<AccommodationItem> accItems = new ArrayList<AccommodationItem>(); public static ArrayList<Accommodation> getAccToShow() { return accToShow; } private static ArrayList<Accommodation> accToShow = new ArrayList<>(Accommodation.getAccommodations()); public static void setIndexForClose(int indexForClose1) { indexForClose=indexForClose1; } public static AccommodationItem getAccItemByData(Accommodation a) { for (int i = 0; i < accItems.size(); i++) { if (a.equals(accItems.get(i).getAccommodationInfo())) { return accItems.get(i); } } return null; } public static ArrayList<AccommodationItem> getAccItems() { return accItems; } // App Index public App(User connectedUser, JFrame loginFrame) { // Frame userOfApp=connectedUser; accToShow = Accommodation.getAccommodations(); addButton = new JButton("Add"); editButton = new JButton("Edit"); deleteButton = new JButton("Delete"); showButton = new JButton("Show Statistics"); AppFrame = new JFrame(); AppFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); AppFrame.setTitle("Καταλύματα App"); // Tabbed Pane tp = new JTabbedPane(); createTab(tp,connectedUser); tp.add("Dashboard", p2); createDashBoard(p2); // Έξοδος JPanel p3 = new JPanel(); tp.add("Έξοδος", p3); tp.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if(tp.getSelectedIndex()==indexForClose) { AppFrame.dispose(); loginFrame.setVisible(true); } else if(tp.getSelectedIndex()==1) { ProviderFrame providerFrame = new ProviderFrame(AppFrame); accToShow = SearchTab.createSearchTab(providerFrame,AppFrame); createTab(tp, connectedUser); } } }); AppFrame.setSize(1300,800); AppFrame.setResizable(false); AppFrame.setLayout(null); AppFrame.add(tp); tp.setSize(780,450);//780 είναι<SUF> AppFrame.setVisible(true); } protected static void createDashBoard(JPanel panelToFill) { String columnHeaders[] = {"'Ονομα","Τύπος","Πόλη","Διεύθυνση","Ταχυδρομικός Κώδικας","Βαθμός Αξιολόγησης"}; Object[][] data = userOfApp.setDataForTable();//Φέρνω τα data! tableModel = new DefaultTableModel(data, columnHeaders) { @Override public boolean isCellEditable(int row, int column) { return false; } }; table = new JTable(tableModel); table.getTableHeader().setReorderingAllowed(false); setSizeOfColumns(); table.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e)//Για να εμφανίζεται το JInternalFrame { rowSelected=table.getSelectedRow(); Accommodation acc=Accommodation.findAccommodation((String)table.getValueAt(rowSelected,0),(String)table.getValueAt(rowSelected,3), (String)table.getValueAt(rowSelected, 2)); if(frames.size()!=0) { frames.get(0).internalFrame.dispose(); frames.clear(); } frames.add(new Slave(AppFrame,acc,userOfApp)); } }); JScrollPane scrollPane = new JScrollPane(table); panelToFill.setLayout(new BorderLayout()); panelToFill.add(scrollPane,BorderLayout.CENTER); panelForButtons = new JPanel(); if (userOfApp instanceof Provider) { providerFrame = new ProviderFrame(AppFrame); panelForButtons.setLayout(new GridLayout(1,4)); panelForButtons.add(addButton); addButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { providerFrame.createAddFrame((Provider)userOfApp); } }); editButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(rowSelected!=-999) { Accommodation temp=Accommodation.findAccommodation(table.getValueAt(rowSelected,0)+"",table.getValueAt(rowSelected,3)+"",(String)table.getValueAt(rowSelected,2));//Βρίσκω το acc με βάση το όνομα και την διευθυνσή providerFrame.createEditFrame(temp); table.setValueAt(temp.getName(),rowSelected,0);//Ενημέρωση του JTable για να μπορώ να το βρω με την findAccommodation table.setValueAt(temp.getType(),rowSelected,1); table.setValueAt(temp.getCity(),rowSelected, 2 ); table.setValueAt(temp.getRoad(),rowSelected,3); table.setValueAt(temp.getAverage() == -1 ? "Καμία αξιολόγηση." : temp.getAverage() + "",rowSelected,5); rowSelected=-999; Slave.updateTextArea(); } } }); showButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "Μέσος όρος αξιολογήσεων: " + userOfApp.countAverageReviews() + "\n" + "Πλήθος αξιολογήσεων σε όλα τα κατάλυματα σας: " + ((Provider)userOfApp).countReviews()); } }); } else { panelForButtons.setLayout(new GridLayout(1,3)); editButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(rowSelected!=-999) { userOfApp.editAction(rowSelected,table); rowSelected=-999; Slave.updateTextArea(); } } }); showButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "Μέσος όρος αξιολογήσεων: " + userOfApp.countAverageReviews()); } }); } panelForButtons.add(editButton); panelForButtons.add(deleteButton); panelForButtons.add(showButton); panelToFill.add(panelForButtons,BorderLayout.PAGE_END); deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(rowSelected!=-999) { userOfApp.deleteAction(rowSelected,table); tableModel.removeRow(rowSelected);//Αφαιρώ απο το table to review rowSelected=-999; Slave.updateTextArea(); } //Αν rowSelected==-999 δεν έχει κάνει κάπου κλικ ο χρήστης } }); } protected static void addRowToTable(String name,String type,String city,String address,String postalCode,String rating) { tableModel.addRow(new String[]{name, type, city, address, postalCode, rating}); } public void createTab(JTabbedPane tabbedPane, User connectedUser) { if (connectedUser instanceof Customer) { JPanel p1 = new JPanel(); AccommodationItem temp; accItems = new ArrayList<>(); GridLayout accommodationLayout = new GridLayout(1,2); if (accToShow.size() == Accommodation.getAccommodations().size()) { accToShow = Provider.randomAcc(); } for (int i = 0; i < accToShow.size(); i++) { double review_avg = accToShow.get(i).calculateAverage(); String t = review_avg == -1 ? "Καμία Αξιολόγηση." : String.valueOf(review_avg); temp = new AccommodationItem(accToShow.get(i), accToShow.get(i).getName(), t); AccommodationItem finalTemp = temp; temp.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof AccommodationItem) { AccommodationItem t = (AccommodationItem) e.getSource(); if(frames.size()!=0) { frames.get(0).internalFrame.dispose(); frames.clear(); } frames.add(new Slave(AppFrame, finalTemp.getAccommodationInfo(),userOfApp)); } } }); temp.setLayout(accommodationLayout); accItems.add(temp); p1.add(temp); } GridLayout accommodationsLayout = new GridLayout(10,1); p1.setLayout(accommodationsLayout); if (tabbedPane.getTabCount() == 0) { tabbedPane.add("Καταλύματα", p1); tabbedPane.add("Αναζήτηση", searchPanel); } else if (tabbedPane.getTabCount() > 2) { tabbedPane.remove(0); tabbedPane.insertTab("Καταλύματα", null, p1, null, 0); } } } private static void setSizeOfColumns() { TableColumnModel columnModel = table.getColumnModel(); for(int i=0;i<table.getColumnCount();i++) { columnModel.getColumn(i).setPreferredWidth(130); columnModel.getColumn(i).setMaxWidth(130); } table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); } }
32331_0
// Όνομα: Δημανίδης Αναστάσιος // ΑΕΜ: 7422 // email: [email protected] // Τηλέφωνο: 6982023258 // Όνομα: Δοξόπουλος Παναγιώτης // ΑΕΜ: 7601 // email: [email protected] // Τηλέφωνο: 6976032566 package Platform; import java.awt.BorderLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Hashtable; import java.util.StringTokenizer; import java.util.Vector; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSlider; import Player.AbstractPlayer; import Units.Unit; public class MainPlatform { protected static JFrame frame; private static JComboBox teamOne; private static JComboBox teamTwo; private static JButton generateMap; private static JButton play; private static JButton quit; private static JSlider gamespeed; protected static Map map; static ArrayList<Unit> allUnits = new ArrayList<Unit>(); static int time = 0; static int timestep = 150; private static AbstractPlayer playerA; private static AbstractPlayer playerB; private static String PlayerOne = "Player.Player"; private static String PlayerTwo = "Player.Player"; private static String[] teamNames = { "Team 0.00" }; private static String[] teamClasses = { "Player.Player" }; // static State state = new State(); private static String showScore () { // Retrieve all Elements, for transformation Vector prey_number = new Vector(1, 1); Vector prey_AEM = new Vector(1, 1); Vector prey_Score = new Vector(1, 1); Vector predator_number = new Vector(1, 1); Vector predator_AEM = new Vector(1, 1); Vector predator_Score = new Vector(1, 1); Vector number_of_steps = new Vector(1, 1); File inputFile = new File("GameLog.txt"); try { BufferedReader r = new BufferedReader( new InputStreamReader(new FileInputStream(inputFile))); String line; while ((line = r.readLine()) != null) { // For each line, retrieve the elements... StringTokenizer parser = new StringTokenizer(line, "\t"); String str_prey_number = parser.nextToken(); String str_prey_AEM = parser.nextToken(); String str_prey_Score = parser.nextToken(); String str_predator_number = parser.nextToken(); String str_predator_AEM = parser.nextToken(); String str_predator_Score = parser.nextToken(); String str_number_of_steps = parser.nextToken(); if (prey_number.contains(str_prey_number)) { int prey_pos = prey_number.indexOf(str_prey_number); float previous_score = (float) (Float .parseFloat(prey_Score.elementAt(prey_pos).toString())); float current_score = (float) (Float.parseFloat(str_prey_Score)); float final_score = previous_score + current_score; prey_Score.removeElementAt(prey_pos); prey_Score.insertElementAt(final_score + "", prey_pos); } else { prey_number.add(str_prey_number); prey_AEM.add(str_prey_AEM); prey_Score.add(str_prey_Score); } if (predator_number.contains(str_predator_number)) { int predator_pos = predator_number.indexOf(str_predator_number); float previous_score = (float) (Float.parseFloat(predator_Score.elementAt(predator_pos) .toString())); float current_score = (float) (Float.parseFloat(str_predator_Score)); float final_score = previous_score + current_score; predator_Score.removeElementAt(predator_pos); predator_Score.insertElementAt(final_score + "", predator_pos); } else { predator_number.add(str_predator_number); predator_AEM.add(str_predator_AEM); predator_Score.add(str_predator_Score); } number_of_steps.add(str_number_of_steps); } } catch (IOException ioException) { System.out.println(ioException); } String output = " TEAM No TEAM Name FINAL \n=======================================================\n"; for (int i = 0; i < prey_number.size(); i++) { String pr_team_number = prey_number.elementAt(i).toString(); float pr_score = (float) (Float.parseFloat(prey_Score.elementAt(i).toString())); float pd_score = 0; int other_pos = predator_number.indexOf(pr_team_number); if (other_pos != -1) { pd_score = (float) (Float.parseFloat(predator_Score.elementAt(other_pos) .toString())); } float score = pr_score + pd_score; output += pr_team_number + " " + prey_AEM.elementAt(i).toString() + " "; output += " " + score + "\n"; } for (int i = 0; i < predator_number.size(); i++) { String pd_team_number = predator_number.elementAt(i).toString(); if (prey_number.contains(pd_team_number)) { } else { float pd_score = (float) (Float.parseFloat(predator_Score.elementAt(i).toString())); float pr_score = 0; int other_pos = prey_number.indexOf(pd_team_number); if (other_pos != -1) { pr_score = (float) (Float.parseFloat(prey_Score.elementAt(other_pos) .toString())); } float score = pr_score + pd_score; output += pd_team_number + " " + predator_AEM.elementAt(i).toString() + " "; output += " " + score + "\n"; } } return output; } private static void createAndShowGUI () { JFrame.setDefaultLookAndFeelDecorated(false); frame = new JFrame("MAZE"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); map = new Map(); JPanel buttonPanel = new JPanel(); BoxLayout horizontal = new BoxLayout(buttonPanel, BoxLayout.X_AXIS); JPanel teamsPanel = new JPanel(); JPanel centerPanel = new JPanel(); generateMap = new JButton("Generate Map"); play = new JButton("Play"); quit = new JButton("Quit"); gamespeed = new JSlider(JSlider.HORIZONTAL, 1, 150, 50); gamespeed.addChangeListener(new SliderListener()); gamespeed.setMajorTickSpacing(10); gamespeed.setPaintTicks(true); Font font = new Font("Serif", Font.ITALIC, 15); gamespeed.setFont(font); Hashtable labelTable = new Hashtable(); labelTable.put(new Integer(1), new JLabel("Fast")); labelTable.put(new Integer(150), new JLabel("Slow")); gamespeed.setLabelTable(labelTable); gamespeed.setPaintLabels(true); teamOne = new JComboBox(teamNames); teamTwo = new JComboBox(teamNames); teamOne.setSelectedIndex(0); teamTwo.setSelectedIndex(0); JLabel label = new JLabel("THE RTS-lite GAME!!!", JLabel.CENTER); centerPanel.setLayout(new BorderLayout()); centerPanel.add("North", label); centerPanel.add("Center", gamespeed); teamsPanel.setLayout(new BorderLayout()); teamsPanel.add("West", teamOne); teamsPanel.add("East", teamTwo); // teamsPanel.add("Center", label); // teamsPanel.add(gamespeed); teamsPanel.add("Center", centerPanel); teamsPanel.add("South", buttonPanel); buttonPanel.add(generateMap); buttonPanel.add(play); buttonPanel.add(quit); frame.setLayout(new BorderLayout()); frame.add("Center", teamsPanel); frame.add("South", buttonPanel); frame.pack(); frame.setVisible(true); quit.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent evt) { System.exit(0); } }); generateMap.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent evt) { play.setEnabled(false); generateMap.setEnabled(false); frame.repaint(); frame.remove(map); PlayerOne = teamClasses[teamOne.getSelectedIndex()]; PlayerTwo = teamClasses[teamTwo.getSelectedIndex()]; playerA = null; try { Class playerAClass = Class.forName(PlayerOne); Class partypes[] = new Class[1]; partypes[0] = Integer.class; //partypes[1] = Integer.class; //partypes[2] = Integer.class; Constructor playerAArgsConstructor = playerAClass.getConstructor(partypes); Object arglist[] = new Object[1]; // arglist[0] = 1; // arglist[1] = 10; // arglist[2] = 150; arglist[0] = new Integer(1); //arglist[1] = new Integer(10); //arglist[2] = new Integer(150); Object playerObject = playerAArgsConstructor.newInstance(arglist); playerA = (AbstractPlayer) playerObject; // prey = new AbstractCreature(true); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } catch (InstantiationException ex) { ex.printStackTrace(); } catch (NoSuchMethodException ex) { ex.printStackTrace(); } catch (InvocationTargetException ex) { ex.printStackTrace(); } playerB = null; try { Class playerBClass = Class.forName(PlayerTwo); Class partypes[] = new Class[1]; partypes[0] = Integer.class; //partypes[1] = Integer.class; //partypes[2] = Integer.class; Constructor playerBArgsConstructor = playerBClass.getConstructor(partypes); Object arglist[] = new Object[1]; // arglist[0] = 1; // arglist[1] = 10; // arglist[2] = 150; arglist[0] = new Integer(2); //arglist[1] = new Integer(790); //arglist[2] = new Integer(150); Object playerObject = playerBArgsConstructor.newInstance(arglist); playerB = (AbstractPlayer) playerObject; // prey = new AbstractCreature(true); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } catch (InstantiationException ex) { ex.printStackTrace(); } catch (NoSuchMethodException ex) { ex.printStackTrace(); } catch (InvocationTargetException ex) { ex.printStackTrace(); } time = 0; Utilities.unitID = 0; allUnits.clear(); playerA.initialize(3); playerB.initialize(3); allUnits.addAll(playerA.getUnits()); allUnits.addAll(playerB.getUnits()); map = new Map(800, 300, allUnits); frame.add("North", map); frame.pack(); play.setEnabled(true); generateMap.setEnabled(false); } }); play.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent evt) { play.setEnabled(false); generateMap.setEnabled(false); Thread t = new Thread(new Runnable() { public void run () { int notwinner = 0; while (notwinner < 10000) { frame.remove(map); boolean end = false; if (time % 40 == 0 && time != 0) { playerA.createMarine(); playerB.createMarine(); allUnits.clear(); allUnits.addAll(playerA.getOwnUnits()); allUnits.addAll(playerB.getOwnUnits()); } // Before this step apply fog of war (in the future) ArrayList<Unit> unitsforA = new ArrayList<Unit>(); ArrayList<Unit> unitsforB = new ArrayList<Unit>(); // for (int i= 0 ; i < allUnits.size(); i ++){ unitsforA = Unit.cloneList(allUnits); unitsforB = Unit.cloneList(allUnits); playerA.setUnits(unitsforA); playerB.setUnits(unitsforB); playerA.chooseCorridor(playerA.getUnits()); playerB.chooseCorridor(playerB.getUnits()); allUnits.clear(); allUnits.addAll(playerA.getOwnUnits()); allUnits.addAll(playerB.getOwnUnits()); unitsforA = Unit.cloneList(allUnits); unitsforB = Unit.cloneList(allUnits); playerA.setUnits(unitsforA); playerB.setUnits(unitsforB); playerA.resolveAttacking(playerA.getUnits()); playerB.resolveAttacking(playerB.getUnits()); // for (Unit uni : playerB.getUnits()) // { // System.out.println(uni.id+" "+uni.hp+" "+uni.damageSuffered); // } // System.out.println("===="); playerA.receiveDamages(playerB.sendDamages(playerB.getUnits())); playerB.receiveDamages(playerA.sendDamages(playerA.getUnits())); allUnits.clear(); allUnits.addAll(playerA.getOwnUnits()); allUnits.addAll(playerB.getOwnUnits()); for (Unit uni: allUnits) { if (uni.getType() == "base" && uni.getCurrentHP() <= uni.getDamageSuffered()) end = true; } if (end) break; unitsforA = Unit.cloneList(allUnits); unitsforB = Unit.cloneList(allUnits); playerA.setUnits(unitsforA); playerB.setUnits(unitsforB); playerA.resolveDamages(playerA.getUnits()); playerB.resolveDamages(playerB.getUnits()); allUnits.clear(); allUnits.addAll(playerA.getOwnUnits()); allUnits.addAll(playerB.getOwnUnits()); unitsforA = Unit.cloneList(allUnits); unitsforB = Unit.cloneList(allUnits); playerA.setUnits(unitsforA); playerB.setUnits(unitsforB); playerA.moveUnits(playerA.getUnits()); playerB.moveUnits(playerB.getUnits()); allUnits.clear(); allUnits.addAll(playerA.getOwnUnits()); allUnits.addAll(playerB.getOwnUnits()); notwinner++; System.out.println("time= " + time); frame.add("North", map); frame.validate(); frame.pack(); frame.repaint(); timestep = gamespeed.getValue(); try { Thread.sleep(timestep); } catch (InterruptedException e) { } time++; if (time == 10000) break; play.setEnabled(false); generateMap.setEnabled(false); } try { BufferedWriter out = new BufferedWriter(new FileWriter("GameLog.txt", true)); int winner = 0; int baseAhp = 0; int baseBhp = 0; for (Unit uniA: allUnits) { for (Unit uniB: allUnits) { if (winner == 0 && uniA.getType() == "base" && uniA.getOwner() == 1 && uniB.getType() == "base" && uniB.getOwner() == 2) { baseAhp = uniA.getCurrentHP(); baseBhp = uniB.getCurrentHP(); if (uniA.getCurrentHP() > uniB.getCurrentHP()) winner = uniA.getOwner(); else if (uniA.getCurrentHP() < uniB.getCurrentHP()) winner = uniB.getOwner(); else winner = 3; } } } // System.out.println(winner+" "+ baseAhp + " "+ baseBhp); if (winner == 1) { out.write(teamNames[teamOne.getSelectedIndex()] + "\t" + playerA.getName() + "\t1\t" + teamNames[teamTwo.getSelectedIndex()] + "\t" + playerB.getName() + "\t0\t" + time + "\n"); // System.out.println("NO WINNER (TIE)!!! Number of Steps: " // + limit); // , new ImageIcon(preyIcon) JOptionPane.showMessageDialog(null, "WINNER IS BLUE PLAYER : " + playerA.getName() + " Number of Steps: " + time, "Results...", JOptionPane.INFORMATION_MESSAGE); } else if (winner == 2) { out.write(teamNames[teamOne.getSelectedIndex()] + "\t" + playerA.getName() + "\t0\t" + teamNames[teamTwo.getSelectedIndex()] + "\t" + playerB.getName() + "\t1\t" + time + "\n"); // System.out.println("WINNER IS (predator): " + // predator.setName() + " Number of Steps: " + // limit); // , new ImageIcon(predatorIcon) JOptionPane.showMessageDialog(null, "WINNER IS RED PLAYER: " + playerB.getName() + " Number of Steps: " + time, "Results...", JOptionPane.INFORMATION_MESSAGE); } else if (winner == 3) { out.write(teamNames[teamOne.getSelectedIndex()] + "\t" + playerA.getName() + "\t0\t" + teamNames[teamTwo.getSelectedIndex()] + "\t" + playerB.getName() + "\t0\t" + time + "\n"); JOptionPane.showMessageDialog(null, "WE HAVE A DRAW: ", "Results...", JOptionPane.INFORMATION_MESSAGE); } out.close(); } catch (IOException ioExc) { } play.setEnabled(true); generateMap.setEnabled(true); JOptionPane.showMessageDialog(null, showScore(), "SCORE TABLE", JOptionPane.INFORMATION_MESSAGE); } }); t.start(); } }); } /** * @param args */ public static void main (String[] args) { // TODO Auto-generated method stub javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run () { createAndShowGUI(); } }); } }
TasosDhm/programming-projects
Java/RTS/RTS-game-v1/src/Platform/MainPlatform.java
4,719
// Όνομα: Δημανίδης Αναστάσιος
line_comment
el
// Όνομα: Δημανίδης<SUF> // ΑΕΜ: 7422 // email: [email protected] // Τηλέφωνο: 6982023258 // Όνομα: Δοξόπουλος Παναγιώτης // ΑΕΜ: 7601 // email: [email protected] // Τηλέφωνο: 6976032566 package Platform; import java.awt.BorderLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Hashtable; import java.util.StringTokenizer; import java.util.Vector; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSlider; import Player.AbstractPlayer; import Units.Unit; public class MainPlatform { protected static JFrame frame; private static JComboBox teamOne; private static JComboBox teamTwo; private static JButton generateMap; private static JButton play; private static JButton quit; private static JSlider gamespeed; protected static Map map; static ArrayList<Unit> allUnits = new ArrayList<Unit>(); static int time = 0; static int timestep = 150; private static AbstractPlayer playerA; private static AbstractPlayer playerB; private static String PlayerOne = "Player.Player"; private static String PlayerTwo = "Player.Player"; private static String[] teamNames = { "Team 0.00" }; private static String[] teamClasses = { "Player.Player" }; // static State state = new State(); private static String showScore () { // Retrieve all Elements, for transformation Vector prey_number = new Vector(1, 1); Vector prey_AEM = new Vector(1, 1); Vector prey_Score = new Vector(1, 1); Vector predator_number = new Vector(1, 1); Vector predator_AEM = new Vector(1, 1); Vector predator_Score = new Vector(1, 1); Vector number_of_steps = new Vector(1, 1); File inputFile = new File("GameLog.txt"); try { BufferedReader r = new BufferedReader( new InputStreamReader(new FileInputStream(inputFile))); String line; while ((line = r.readLine()) != null) { // For each line, retrieve the elements... StringTokenizer parser = new StringTokenizer(line, "\t"); String str_prey_number = parser.nextToken(); String str_prey_AEM = parser.nextToken(); String str_prey_Score = parser.nextToken(); String str_predator_number = parser.nextToken(); String str_predator_AEM = parser.nextToken(); String str_predator_Score = parser.nextToken(); String str_number_of_steps = parser.nextToken(); if (prey_number.contains(str_prey_number)) { int prey_pos = prey_number.indexOf(str_prey_number); float previous_score = (float) (Float .parseFloat(prey_Score.elementAt(prey_pos).toString())); float current_score = (float) (Float.parseFloat(str_prey_Score)); float final_score = previous_score + current_score; prey_Score.removeElementAt(prey_pos); prey_Score.insertElementAt(final_score + "", prey_pos); } else { prey_number.add(str_prey_number); prey_AEM.add(str_prey_AEM); prey_Score.add(str_prey_Score); } if (predator_number.contains(str_predator_number)) { int predator_pos = predator_number.indexOf(str_predator_number); float previous_score = (float) (Float.parseFloat(predator_Score.elementAt(predator_pos) .toString())); float current_score = (float) (Float.parseFloat(str_predator_Score)); float final_score = previous_score + current_score; predator_Score.removeElementAt(predator_pos); predator_Score.insertElementAt(final_score + "", predator_pos); } else { predator_number.add(str_predator_number); predator_AEM.add(str_predator_AEM); predator_Score.add(str_predator_Score); } number_of_steps.add(str_number_of_steps); } } catch (IOException ioException) { System.out.println(ioException); } String output = " TEAM No TEAM Name FINAL \n=======================================================\n"; for (int i = 0; i < prey_number.size(); i++) { String pr_team_number = prey_number.elementAt(i).toString(); float pr_score = (float) (Float.parseFloat(prey_Score.elementAt(i).toString())); float pd_score = 0; int other_pos = predator_number.indexOf(pr_team_number); if (other_pos != -1) { pd_score = (float) (Float.parseFloat(predator_Score.elementAt(other_pos) .toString())); } float score = pr_score + pd_score; output += pr_team_number + " " + prey_AEM.elementAt(i).toString() + " "; output += " " + score + "\n"; } for (int i = 0; i < predator_number.size(); i++) { String pd_team_number = predator_number.elementAt(i).toString(); if (prey_number.contains(pd_team_number)) { } else { float pd_score = (float) (Float.parseFloat(predator_Score.elementAt(i).toString())); float pr_score = 0; int other_pos = prey_number.indexOf(pd_team_number); if (other_pos != -1) { pr_score = (float) (Float.parseFloat(prey_Score.elementAt(other_pos) .toString())); } float score = pr_score + pd_score; output += pd_team_number + " " + predator_AEM.elementAt(i).toString() + " "; output += " " + score + "\n"; } } return output; } private static void createAndShowGUI () { JFrame.setDefaultLookAndFeelDecorated(false); frame = new JFrame("MAZE"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); map = new Map(); JPanel buttonPanel = new JPanel(); BoxLayout horizontal = new BoxLayout(buttonPanel, BoxLayout.X_AXIS); JPanel teamsPanel = new JPanel(); JPanel centerPanel = new JPanel(); generateMap = new JButton("Generate Map"); play = new JButton("Play"); quit = new JButton("Quit"); gamespeed = new JSlider(JSlider.HORIZONTAL, 1, 150, 50); gamespeed.addChangeListener(new SliderListener()); gamespeed.setMajorTickSpacing(10); gamespeed.setPaintTicks(true); Font font = new Font("Serif", Font.ITALIC, 15); gamespeed.setFont(font); Hashtable labelTable = new Hashtable(); labelTable.put(new Integer(1), new JLabel("Fast")); labelTable.put(new Integer(150), new JLabel("Slow")); gamespeed.setLabelTable(labelTable); gamespeed.setPaintLabels(true); teamOne = new JComboBox(teamNames); teamTwo = new JComboBox(teamNames); teamOne.setSelectedIndex(0); teamTwo.setSelectedIndex(0); JLabel label = new JLabel("THE RTS-lite GAME!!!", JLabel.CENTER); centerPanel.setLayout(new BorderLayout()); centerPanel.add("North", label); centerPanel.add("Center", gamespeed); teamsPanel.setLayout(new BorderLayout()); teamsPanel.add("West", teamOne); teamsPanel.add("East", teamTwo); // teamsPanel.add("Center", label); // teamsPanel.add(gamespeed); teamsPanel.add("Center", centerPanel); teamsPanel.add("South", buttonPanel); buttonPanel.add(generateMap); buttonPanel.add(play); buttonPanel.add(quit); frame.setLayout(new BorderLayout()); frame.add("Center", teamsPanel); frame.add("South", buttonPanel); frame.pack(); frame.setVisible(true); quit.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent evt) { System.exit(0); } }); generateMap.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent evt) { play.setEnabled(false); generateMap.setEnabled(false); frame.repaint(); frame.remove(map); PlayerOne = teamClasses[teamOne.getSelectedIndex()]; PlayerTwo = teamClasses[teamTwo.getSelectedIndex()]; playerA = null; try { Class playerAClass = Class.forName(PlayerOne); Class partypes[] = new Class[1]; partypes[0] = Integer.class; //partypes[1] = Integer.class; //partypes[2] = Integer.class; Constructor playerAArgsConstructor = playerAClass.getConstructor(partypes); Object arglist[] = new Object[1]; // arglist[0] = 1; // arglist[1] = 10; // arglist[2] = 150; arglist[0] = new Integer(1); //arglist[1] = new Integer(10); //arglist[2] = new Integer(150); Object playerObject = playerAArgsConstructor.newInstance(arglist); playerA = (AbstractPlayer) playerObject; // prey = new AbstractCreature(true); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } catch (InstantiationException ex) { ex.printStackTrace(); } catch (NoSuchMethodException ex) { ex.printStackTrace(); } catch (InvocationTargetException ex) { ex.printStackTrace(); } playerB = null; try { Class playerBClass = Class.forName(PlayerTwo); Class partypes[] = new Class[1]; partypes[0] = Integer.class; //partypes[1] = Integer.class; //partypes[2] = Integer.class; Constructor playerBArgsConstructor = playerBClass.getConstructor(partypes); Object arglist[] = new Object[1]; // arglist[0] = 1; // arglist[1] = 10; // arglist[2] = 150; arglist[0] = new Integer(2); //arglist[1] = new Integer(790); //arglist[2] = new Integer(150); Object playerObject = playerBArgsConstructor.newInstance(arglist); playerB = (AbstractPlayer) playerObject; // prey = new AbstractCreature(true); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } catch (InstantiationException ex) { ex.printStackTrace(); } catch (NoSuchMethodException ex) { ex.printStackTrace(); } catch (InvocationTargetException ex) { ex.printStackTrace(); } time = 0; Utilities.unitID = 0; allUnits.clear(); playerA.initialize(3); playerB.initialize(3); allUnits.addAll(playerA.getUnits()); allUnits.addAll(playerB.getUnits()); map = new Map(800, 300, allUnits); frame.add("North", map); frame.pack(); play.setEnabled(true); generateMap.setEnabled(false); } }); play.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent evt) { play.setEnabled(false); generateMap.setEnabled(false); Thread t = new Thread(new Runnable() { public void run () { int notwinner = 0; while (notwinner < 10000) { frame.remove(map); boolean end = false; if (time % 40 == 0 && time != 0) { playerA.createMarine(); playerB.createMarine(); allUnits.clear(); allUnits.addAll(playerA.getOwnUnits()); allUnits.addAll(playerB.getOwnUnits()); } // Before this step apply fog of war (in the future) ArrayList<Unit> unitsforA = new ArrayList<Unit>(); ArrayList<Unit> unitsforB = new ArrayList<Unit>(); // for (int i= 0 ; i < allUnits.size(); i ++){ unitsforA = Unit.cloneList(allUnits); unitsforB = Unit.cloneList(allUnits); playerA.setUnits(unitsforA); playerB.setUnits(unitsforB); playerA.chooseCorridor(playerA.getUnits()); playerB.chooseCorridor(playerB.getUnits()); allUnits.clear(); allUnits.addAll(playerA.getOwnUnits()); allUnits.addAll(playerB.getOwnUnits()); unitsforA = Unit.cloneList(allUnits); unitsforB = Unit.cloneList(allUnits); playerA.setUnits(unitsforA); playerB.setUnits(unitsforB); playerA.resolveAttacking(playerA.getUnits()); playerB.resolveAttacking(playerB.getUnits()); // for (Unit uni : playerB.getUnits()) // { // System.out.println(uni.id+" "+uni.hp+" "+uni.damageSuffered); // } // System.out.println("===="); playerA.receiveDamages(playerB.sendDamages(playerB.getUnits())); playerB.receiveDamages(playerA.sendDamages(playerA.getUnits())); allUnits.clear(); allUnits.addAll(playerA.getOwnUnits()); allUnits.addAll(playerB.getOwnUnits()); for (Unit uni: allUnits) { if (uni.getType() == "base" && uni.getCurrentHP() <= uni.getDamageSuffered()) end = true; } if (end) break; unitsforA = Unit.cloneList(allUnits); unitsforB = Unit.cloneList(allUnits); playerA.setUnits(unitsforA); playerB.setUnits(unitsforB); playerA.resolveDamages(playerA.getUnits()); playerB.resolveDamages(playerB.getUnits()); allUnits.clear(); allUnits.addAll(playerA.getOwnUnits()); allUnits.addAll(playerB.getOwnUnits()); unitsforA = Unit.cloneList(allUnits); unitsforB = Unit.cloneList(allUnits); playerA.setUnits(unitsforA); playerB.setUnits(unitsforB); playerA.moveUnits(playerA.getUnits()); playerB.moveUnits(playerB.getUnits()); allUnits.clear(); allUnits.addAll(playerA.getOwnUnits()); allUnits.addAll(playerB.getOwnUnits()); notwinner++; System.out.println("time= " + time); frame.add("North", map); frame.validate(); frame.pack(); frame.repaint(); timestep = gamespeed.getValue(); try { Thread.sleep(timestep); } catch (InterruptedException e) { } time++; if (time == 10000) break; play.setEnabled(false); generateMap.setEnabled(false); } try { BufferedWriter out = new BufferedWriter(new FileWriter("GameLog.txt", true)); int winner = 0; int baseAhp = 0; int baseBhp = 0; for (Unit uniA: allUnits) { for (Unit uniB: allUnits) { if (winner == 0 && uniA.getType() == "base" && uniA.getOwner() == 1 && uniB.getType() == "base" && uniB.getOwner() == 2) { baseAhp = uniA.getCurrentHP(); baseBhp = uniB.getCurrentHP(); if (uniA.getCurrentHP() > uniB.getCurrentHP()) winner = uniA.getOwner(); else if (uniA.getCurrentHP() < uniB.getCurrentHP()) winner = uniB.getOwner(); else winner = 3; } } } // System.out.println(winner+" "+ baseAhp + " "+ baseBhp); if (winner == 1) { out.write(teamNames[teamOne.getSelectedIndex()] + "\t" + playerA.getName() + "\t1\t" + teamNames[teamTwo.getSelectedIndex()] + "\t" + playerB.getName() + "\t0\t" + time + "\n"); // System.out.println("NO WINNER (TIE)!!! Number of Steps: " // + limit); // , new ImageIcon(preyIcon) JOptionPane.showMessageDialog(null, "WINNER IS BLUE PLAYER : " + playerA.getName() + " Number of Steps: " + time, "Results...", JOptionPane.INFORMATION_MESSAGE); } else if (winner == 2) { out.write(teamNames[teamOne.getSelectedIndex()] + "\t" + playerA.getName() + "\t0\t" + teamNames[teamTwo.getSelectedIndex()] + "\t" + playerB.getName() + "\t1\t" + time + "\n"); // System.out.println("WINNER IS (predator): " + // predator.setName() + " Number of Steps: " + // limit); // , new ImageIcon(predatorIcon) JOptionPane.showMessageDialog(null, "WINNER IS RED PLAYER: " + playerB.getName() + " Number of Steps: " + time, "Results...", JOptionPane.INFORMATION_MESSAGE); } else if (winner == 3) { out.write(teamNames[teamOne.getSelectedIndex()] + "\t" + playerA.getName() + "\t0\t" + teamNames[teamTwo.getSelectedIndex()] + "\t" + playerB.getName() + "\t0\t" + time + "\n"); JOptionPane.showMessageDialog(null, "WE HAVE A DRAW: ", "Results...", JOptionPane.INFORMATION_MESSAGE); } out.close(); } catch (IOException ioExc) { } play.setEnabled(true); generateMap.setEnabled(true); JOptionPane.showMessageDialog(null, showScore(), "SCORE TABLE", JOptionPane.INFORMATION_MESSAGE); } }); t.start(); } }); } /** * @param args */ public static void main (String[] args) { // TODO Auto-generated method stub javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run () { createAndShowGUI(); } }); } }
35_7
/*Επωνυμο: Τασούλας Ονομα: Θεοφάνης ΑΜ: Π2015092 Ημερομηνια: 28/1/2017 Λειτουργια: Η παρακατω κλαση υλοποιει αντικειμενα media με χαρακτηριστικα: title, type, κλπ με τη βοηθεια των μεθοδων get και addArtists. Ακομα δινει τη δυνατοτητα να εμφανιστουν στην οθονη με τις μεθοδους set και toString. Επισης εχει διεπαφη με τη Ratable.java και μπορει να δεχεται βαθμολογιες και να τις εμφανιζει στην οθονη με ακριβεια 0.5. */ import java.lang.IllegalArgumentException; import java.util.ArrayList; //Για να δουλεψω με list χρειαζεται να εισαγω τα ArrayList και List import java.util.List; public class Media { protected String title; //Αρχικοπιηση των data members protected String type; protected int date; protected double length; protected String genre; protected String description; protected List <String> artists = new ArrayList <String>(); protected int availability; protected float averageRating=0; // Μεση τιμη των βαθμολογιων protected transient int ratingsCount=0; // Συνολο των βαθμολογιων, δε χρειαζεται να εμφανιστει με τη βοηθεια του JSON protected transient int sumOfRatings=0; // Αθροισμα των βαθμολογιων, δε χρειαζεται να εμφανιστει με τη βοηθεια του JSON protected transient float x; // Μεταβλητη που εμφανιζει το μεσο ορο με ακριβεια 0.5, δε χρειαζεται να εμφανιστει με τη βοηθεια του JSON public Media(String tit,String typ) //Ο constructor παιρνει ως παραμετρους δυο String μεταβλητες tit και typ για να βαλουμε τιμη στα title και type αντιστοιχα { if (!tit.trim().toLowerCase().equals("") ) //Εαν ο τιτλος δεν ειναι ισοδυναμος με το κενο, θα εκχωριθει ο νεος τιτλος { title = tit; } setType(typ); //Καλουμε την setType για τη δημιουργεια τυπου } public String getTitle() //Η μεθοδος αυτη επιστρεφει την τιμη του title { return title; } public int getAvailability() //Η μεθοδος αυτη επιστρεφει την τιμη του availability { return availability; } public String getType() //Η μεθοδος αυτη επιστρεφει την τιμη του type { return type; } public int getDate() //Η μεθοδος αυτη επιστρεφει την τιμη του date { return date; } public double getLength() //Η μεθοδος αυτη επιστρεφει την τιμη του length { return length; } public String getGenre() //Η μεθοδος αυτη επιστρεφει την τιμη του genre { return genre; } public String getDescription() //Η μεθοδος αυτη επιστρεφει την τιμη του description { return description; } public List<String> getArtists() //Η μεθοδος αυτη επιστρεφει τις τιμες της λιστας artsists { return artists; } public void setType(String typ) //Η μεθοδος αυτη εκχωρει τιμη στο type με τη βοηθεια της String παραμετρου typ { if (typ.trim().toLowerCase().equals("stream-video") || typ.trim().toLowerCase().equals("stream-audio") || typ.trim().toLowerCase().equals("book") || typ.trim().toLowerCase().equals("dvd") ) //Εαν παει να εκχωρισει καποια αποδεκτη τιμη, τοτε την εκχωρουμε στο type, διαφορετικα εμφανιζουμε καταλληλο μηνυμα { type=typ; } else { System.out.println("setType error. Type can only be: stream-video, dvd, stream-audio or book"); } } public void setAvailability(int availability) //Η μεθοδος αυτη επιστρεφει την τιμη του availability { this.availability = availability; } public void setDate(int dat) //Η μεθοδος αυτη εκχωρει τιμη στο date με τη βοηθεια της int παραμετρου dat { date=dat; } public void setLength(double len) //Η μεθοδος αυτη εκχωρει τιμη στο length με τη βοηθεια της double παραμετρου len { length=len; } public void setGenre(String gen) //Η μεθοδος αυτη εκχωρει τιμη στο genre με τη βοηθεια της String παραμετρου gen { genre=gen; } public void setDescription(String des) //Η μεθοδος αυτη εκχωρει τιμη στο description με τη βοηθεια της String παραμετρου des { description=des; } public void addArtists(String art) //Η μεθοδος αυτη αυξανει κατα ενα κελι τη λιστα artists, με τη βοηθεια της String παραμετρου art { artists.add(art); } public String toString() //Η μεθοδος αυτη επιστρεφει ολα τα στοιχεια ενος αντικειμενου (εκτος απο τη λιστα artists και το description) { return ("Media:{'title': '" +title +"', 'date': '" +date +"', 'length': '" + length +"', 'genre': '" +genre +"', 'type': '" +type +"', 'averageRating': '" +getAverageRating() +"', 'ratingsCount': '" +ratingsCount +"' }" ); } public float getAverageRating() // Η μεθοδος αυτη, επιστρεφει τη μεση τιμη των βαθμολογιων (rating), με ακριβεια 0.5 { if (ratingsCount!=0) // Εαν υπαρχουν βαθμολογιες { if (averageRating < 1.25) // Ελεγχουμε την τιμη της μεσης τιμης και εκχωρουμε την την καταλληλη τιμη στη μεταβλητη x { x=1; // Προκειται να εμφανισουμε τη μεταβλητη x και οχι την μεταβλητη averageRating, για να εχουμε ακριβεια 0.5 } else if (averageRating < 1.75) { x=1.5f; } else if (averageRating < 2.25) { x=2; } else if (averageRating < 2.75) { x=2.5f; } else if (averageRating < 3.25) { x=3; } else if (averageRating < 3.75) { x=3.5f; } else if (averageRating < 4.25) { x=4; } else if (averageRating < 4.75) { x=4.5f; } else { x=5; } return x; // Επιστρεφουμε τη μεταβλητη x; } else // Εαν δεν υπαρχουν βαθμολογιες, επιστρεδουμε 0. { return 0; } } public int getRatingsCount() // Η μεθοδος αυτη, επιστρεφει το ποσες φορες δοθηκε μια βαθμολογια(rating) { return ratingsCount; } public void addRating(int a) throws IllegalArgumentException // Η μεθοδος αυτη, δεχεται μια κριτικη(rating) και... { if (a<1 || a>5) // Εαν η τιμη δεν ειναι εγκυρη { throw new IllegalArgumentException("Vallue must be between 1 and 5."); // Τοτε πεταμε ενα exception με καταληλο μηνυμα } else { this.sumOfRatings = sumOfRatings + a; // Διαφορετικα, αυξανουμε το αθροισμα των βαθμολογιων ratingsCount++; // Αυξανουμε το συνολο των βαθμολογιων this.averageRating = (float) sumOfRatings/ratingsCount; // Και διαιρουμε το αθροισμα των βαθμολογιων με το συνολο τους (ως float), για να παρουμε τη μεση τιμη } } }
TasoulasTheofanis/Media-Store-in-Java-Implemented-with-Blockchain
src/Media.java
3,471
//Ο constructor παιρνει ως παραμετρους δυο String μεταβλητες tit και typ για να βαλουμε τιμη στα title και type αντιστοιχα
line_comment
el
/*Επωνυμο: Τασούλας Ονομα: Θεοφάνης ΑΜ: Π2015092 Ημερομηνια: 28/1/2017 Λειτουργια: Η παρακατω κλαση υλοποιει αντικειμενα media με χαρακτηριστικα: title, type, κλπ με τη βοηθεια των μεθοδων get και addArtists. Ακομα δινει τη δυνατοτητα να εμφανιστουν στην οθονη με τις μεθοδους set και toString. Επισης εχει διεπαφη με τη Ratable.java και μπορει να δεχεται βαθμολογιες και να τις εμφανιζει στην οθονη με ακριβεια 0.5. */ import java.lang.IllegalArgumentException; import java.util.ArrayList; //Για να δουλεψω με list χρειαζεται να εισαγω τα ArrayList και List import java.util.List; public class Media { protected String title; //Αρχικοπιηση των data members protected String type; protected int date; protected double length; protected String genre; protected String description; protected List <String> artists = new ArrayList <String>(); protected int availability; protected float averageRating=0; // Μεση τιμη των βαθμολογιων protected transient int ratingsCount=0; // Συνολο των βαθμολογιων, δε χρειαζεται να εμφανιστει με τη βοηθεια του JSON protected transient int sumOfRatings=0; // Αθροισμα των βαθμολογιων, δε χρειαζεται να εμφανιστει με τη βοηθεια του JSON protected transient float x; // Μεταβλητη που εμφανιζει το μεσο ορο με ακριβεια 0.5, δε χρειαζεται να εμφανιστει με τη βοηθεια του JSON public Media(String tit,String typ) //Ο constructor<SUF> { if (!tit.trim().toLowerCase().equals("") ) //Εαν ο τιτλος δεν ειναι ισοδυναμος με το κενο, θα εκχωριθει ο νεος τιτλος { title = tit; } setType(typ); //Καλουμε την setType για τη δημιουργεια τυπου } public String getTitle() //Η μεθοδος αυτη επιστρεφει την τιμη του title { return title; } public int getAvailability() //Η μεθοδος αυτη επιστρεφει την τιμη του availability { return availability; } public String getType() //Η μεθοδος αυτη επιστρεφει την τιμη του type { return type; } public int getDate() //Η μεθοδος αυτη επιστρεφει την τιμη του date { return date; } public double getLength() //Η μεθοδος αυτη επιστρεφει την τιμη του length { return length; } public String getGenre() //Η μεθοδος αυτη επιστρεφει την τιμη του genre { return genre; } public String getDescription() //Η μεθοδος αυτη επιστρεφει την τιμη του description { return description; } public List<String> getArtists() //Η μεθοδος αυτη επιστρεφει τις τιμες της λιστας artsists { return artists; } public void setType(String typ) //Η μεθοδος αυτη εκχωρει τιμη στο type με τη βοηθεια της String παραμετρου typ { if (typ.trim().toLowerCase().equals("stream-video") || typ.trim().toLowerCase().equals("stream-audio") || typ.trim().toLowerCase().equals("book") || typ.trim().toLowerCase().equals("dvd") ) //Εαν παει να εκχωρισει καποια αποδεκτη τιμη, τοτε την εκχωρουμε στο type, διαφορετικα εμφανιζουμε καταλληλο μηνυμα { type=typ; } else { System.out.println("setType error. Type can only be: stream-video, dvd, stream-audio or book"); } } public void setAvailability(int availability) //Η μεθοδος αυτη επιστρεφει την τιμη του availability { this.availability = availability; } public void setDate(int dat) //Η μεθοδος αυτη εκχωρει τιμη στο date με τη βοηθεια της int παραμετρου dat { date=dat; } public void setLength(double len) //Η μεθοδος αυτη εκχωρει τιμη στο length με τη βοηθεια της double παραμετρου len { length=len; } public void setGenre(String gen) //Η μεθοδος αυτη εκχωρει τιμη στο genre με τη βοηθεια της String παραμετρου gen { genre=gen; } public void setDescription(String des) //Η μεθοδος αυτη εκχωρει τιμη στο description με τη βοηθεια της String παραμετρου des { description=des; } public void addArtists(String art) //Η μεθοδος αυτη αυξανει κατα ενα κελι τη λιστα artists, με τη βοηθεια της String παραμετρου art { artists.add(art); } public String toString() //Η μεθοδος αυτη επιστρεφει ολα τα στοιχεια ενος αντικειμενου (εκτος απο τη λιστα artists και το description) { return ("Media:{'title': '" +title +"', 'date': '" +date +"', 'length': '" + length +"', 'genre': '" +genre +"', 'type': '" +type +"', 'averageRating': '" +getAverageRating() +"', 'ratingsCount': '" +ratingsCount +"' }" ); } public float getAverageRating() // Η μεθοδος αυτη, επιστρεφει τη μεση τιμη των βαθμολογιων (rating), με ακριβεια 0.5 { if (ratingsCount!=0) // Εαν υπαρχουν βαθμολογιες { if (averageRating < 1.25) // Ελεγχουμε την τιμη της μεσης τιμης και εκχωρουμε την την καταλληλη τιμη στη μεταβλητη x { x=1; // Προκειται να εμφανισουμε τη μεταβλητη x και οχι την μεταβλητη averageRating, για να εχουμε ακριβεια 0.5 } else if (averageRating < 1.75) { x=1.5f; } else if (averageRating < 2.25) { x=2; } else if (averageRating < 2.75) { x=2.5f; } else if (averageRating < 3.25) { x=3; } else if (averageRating < 3.75) { x=3.5f; } else if (averageRating < 4.25) { x=4; } else if (averageRating < 4.75) { x=4.5f; } else { x=5; } return x; // Επιστρεφουμε τη μεταβλητη x; } else // Εαν δεν υπαρχουν βαθμολογιες, επιστρεδουμε 0. { return 0; } } public int getRatingsCount() // Η μεθοδος αυτη, επιστρεφει το ποσες φορες δοθηκε μια βαθμολογια(rating) { return ratingsCount; } public void addRating(int a) throws IllegalArgumentException // Η μεθοδος αυτη, δεχεται μια κριτικη(rating) και... { if (a<1 || a>5) // Εαν η τιμη δεν ειναι εγκυρη { throw new IllegalArgumentException("Vallue must be between 1 and 5."); // Τοτε πεταμε ενα exception με καταληλο μηνυμα } else { this.sumOfRatings = sumOfRatings + a; // Διαφορετικα, αυξανουμε το αθροισμα των βαθμολογιων ratingsCount++; // Αυξανουμε το συνολο των βαθμολογιων this.averageRating = (float) sumOfRatings/ratingsCount; // Και διαιρουμε το αθροισμα των βαθμολογιων με το συνολο τους (ως float), για να παρουμε τη μεση τιμη } } }
326_4
package gui; import java.io.IOException; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; import javax.sound.sampled.*; /** * Η κλάση MusicPlayer υλοποιεί έναν διοργανωτή μουσικής, δηλαδή με αυτή την κλάση μπορούμε να παίξουν άρχεια ήχου με κατάληξη .wav . * * @author tasosxak * @author Thanasis * @version 1.0 * @since 8/1/17 * */ public class MusicPlayer { private Clip clip; private MusicPlayer secondSound; private boolean playSecondSound; public MusicPlayer(String soundName) { // Link: http://www.java2s.com/Code/JavaAPI/javax.sound.sampled/LineaddLineListenerLineListenerlistener.htm URL path = getClass().getResource("/sounds/"+soundName); Line.Info linfo = new Line.Info(Clip.class); Line line; try { line = AudioSystem.getLine(linfo); clip = (Clip) line; AudioInputStream ais; ais = AudioSystem.getAudioInputStream(path); clip.open(ais); } catch (UnsupportedAudioFileException ex) { Logger.getLogger(MusicPlayer.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(MusicPlayer.class.getName()).log(Level.SEVERE, null, ex); } catch (LineUnavailableException ex) { Logger.getLogger(MusicPlayer.class.getName()).log(Level.SEVERE, null, ex); Logger.getLogger(MusicPlayer.class.getName()).log(Level.SEVERE, null, ex); } } /** * Με την play() ξεκινάει το αρχείου ήχου να παίζει. */ public void play() { playSecondSound = true; clip.start(); } /** * Με την loop() παίζει επαναληπτικά το αρχείο ήχου */ public void loop() { clip.loop(Clip.LOOP_CONTINUOUSLY); } /** * Με την addNectSound() μπορούμε να προσθέσουμε ένα αρχείο ήχου το οποίο θα ξεκινήσει να παίζει ακριβώς μετά απο το αρχείο μουσικής που παίζει * @param soundName Το όνομα του αρχείου ήχου μαζί με την κατάληξη που υποδηλώνει τον τύπο */ public void addNextSound(final String soundName) { addNextSound(soundName, false); } /** * Με την stop() σταματάει να παίζει το αρχείο ήχου */ public void stop() { clip.stop(); if (secondSound == null) { playSecondSound = false; } else { secondSound.stop(); } } /** * Με την addNectSound μπορούμε να προσθέσουμε ένα αρχείο ήχου το οποίο θα ξεκινήσει να παίζει ακριβώς μετά απο το αρχείο μουσικής που παίζει * * @param soundName Το όνομα του αρχείο ήχου π.χ.( filename.wav) * @param loop true αν έχει 2ο αρχείο ήχου και θέλουμε να παίζει επαναληπτικά, false αν έχουμε 2ο αρχείο ήχου και θέλουμε να παίξει μια φορά */ public void addNextSound(final String soundName, final boolean loop) { playSecondSound = true; clip.addLineListener(new LineListener() { //Ενεργοποιείται όταν τελειώνει ή αρχίζει το αρχείο ήχου @Override public void update(LineEvent le) { LineEvent.Type type = le.getType(); if (type == LineEvent.Type.OPEN) { //τίποτα } else if (type == LineEvent.Type.CLOSE) { if (playSecondSound) { //Έλεγχος αν έχει 2ο αρχείου ήχου secondSound = new MusicPlayer(soundName); if (loop) { secondSound.loop(); //Παίζει το 2ο αρχείο ήχου επαναληπτικά } else { secondSound.play(); //Παίζει το αρχείο ήχου μια φορά } } } else if (type == LineEvent.Type.STOP) { clip.close(); //Κλείνει το αρχείο ήχου } } }); } }
TeamLS/Buzz
src/gui/MusicPlayer.java
1,515
/** * Με την stop() σταματάει να παίζει το αρχείο ήχου */
block_comment
el
package gui; import java.io.IOException; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; import javax.sound.sampled.*; /** * Η κλάση MusicPlayer υλοποιεί έναν διοργανωτή μουσικής, δηλαδή με αυτή την κλάση μπορούμε να παίξουν άρχεια ήχου με κατάληξη .wav . * * @author tasosxak * @author Thanasis * @version 1.0 * @since 8/1/17 * */ public class MusicPlayer { private Clip clip; private MusicPlayer secondSound; private boolean playSecondSound; public MusicPlayer(String soundName) { // Link: http://www.java2s.com/Code/JavaAPI/javax.sound.sampled/LineaddLineListenerLineListenerlistener.htm URL path = getClass().getResource("/sounds/"+soundName); Line.Info linfo = new Line.Info(Clip.class); Line line; try { line = AudioSystem.getLine(linfo); clip = (Clip) line; AudioInputStream ais; ais = AudioSystem.getAudioInputStream(path); clip.open(ais); } catch (UnsupportedAudioFileException ex) { Logger.getLogger(MusicPlayer.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(MusicPlayer.class.getName()).log(Level.SEVERE, null, ex); } catch (LineUnavailableException ex) { Logger.getLogger(MusicPlayer.class.getName()).log(Level.SEVERE, null, ex); Logger.getLogger(MusicPlayer.class.getName()).log(Level.SEVERE, null, ex); } } /** * Με την play() ξεκινάει το αρχείου ήχου να παίζει. */ public void play() { playSecondSound = true; clip.start(); } /** * Με την loop() παίζει επαναληπτικά το αρχείο ήχου */ public void loop() { clip.loop(Clip.LOOP_CONTINUOUSLY); } /** * Με την addNectSound() μπορούμε να προσθέσουμε ένα αρχείο ήχου το οποίο θα ξεκινήσει να παίζει ακριβώς μετά απο το αρχείο μουσικής που παίζει * @param soundName Το όνομα του αρχείου ήχου μαζί με την κατάληξη που υποδηλώνει τον τύπο */ public void addNextSound(final String soundName) { addNextSound(soundName, false); } /** * Με την stop()<SUF>*/ public void stop() { clip.stop(); if (secondSound == null) { playSecondSound = false; } else { secondSound.stop(); } } /** * Με την addNectSound μπορούμε να προσθέσουμε ένα αρχείο ήχου το οποίο θα ξεκινήσει να παίζει ακριβώς μετά απο το αρχείο μουσικής που παίζει * * @param soundName Το όνομα του αρχείο ήχου π.χ.( filename.wav) * @param loop true αν έχει 2ο αρχείο ήχου και θέλουμε να παίζει επαναληπτικά, false αν έχουμε 2ο αρχείο ήχου και θέλουμε να παίξει μια φορά */ public void addNextSound(final String soundName, final boolean loop) { playSecondSound = true; clip.addLineListener(new LineListener() { //Ενεργοποιείται όταν τελειώνει ή αρχίζει το αρχείο ήχου @Override public void update(LineEvent le) { LineEvent.Type type = le.getType(); if (type == LineEvent.Type.OPEN) { //τίποτα } else if (type == LineEvent.Type.CLOSE) { if (playSecondSound) { //Έλεγχος αν έχει 2ο αρχείου ήχου secondSound = new MusicPlayer(soundName); if (loop) { secondSound.loop(); //Παίζει το 2ο αρχείο ήχου επαναληπτικά } else { secondSound.play(); //Παίζει το αρχείο ήχου μια φορά } } } else if (type == LineEvent.Type.STOP) { clip.close(); //Κλείνει το αρχείο ήχου } } }); } }
1798_8
package operatingsystem; import java.io.IOException; // Χρίστος Γκόγκος (2738), Αθανάσιος Μπόλλας (2779), Δημήτριος Σβίγγας (2618), Αναστάσιος Τεμπερεκίδης (2808) /* Από την κλάση αυτή ξεκινά η εκτέλεση της εφαρμογής. Δημιουργεί το αρχείο με τις διεργασίες, φορτώνει από αυτό όλες τις διεργασίες και προσομοιώνει την δρομολόγηση με σειρά τους εξής αλγορίθμους: SJF preemptive, SJF non-preemptive, Round Robin quantum=50, Round Robin quantum=300. Τέλος καταγράφει τα στατιστικά από τις παραπάνω προσομοιώσεις και τα αποθηκεύει σε αρχείο. */ public class Main { public static Clock clock; public static CPU cpu; public static NewProcessTemporaryList newProcessList; public static ReadyProcessesList readyProcessesList; public static Statistics stats; /* Επιστρέφει true αν η cpu δεν έχει καμία διεργασία για εκτέλεση, δεν υπάρχει καμία διεργασία στην ουρά έτοιμων διεργασιών και η ουρά νέων διεργασιών είναι άδεια. */ public static boolean end() { return (cpu.getRunningProcess() == null) && (readyProcessesList.isEmpty()) && (newProcessList.isEmpty()); } public static void main(String[] args) throws IOException { String inputFileName = "processes.txt"; //Αρχείο των στοιχείων των διεργασιών String outputFileName = "statistics.txt"; // Αρχείο στατιστικών εκτέλεσης ProcessGenerator processParse; new ProcessGenerator(inputFileName, false); // Δημιουργία αρχείου εισόδου cpu = new CPU(); newProcessList = new NewProcessTemporaryList(); stats = new Statistics(outputFileName); clock = new Clock(); readyProcessesList = new ReadyProcessesList(); // ============== PREEMPTIVE SJF ==============// processParse = new ProcessGenerator(inputFileName, true); //Παραγωγή όλων των διεργασιών processParse.addProcessesToTemporayList(); // Προσθήκη των νέων διεργασιών στην ουρά νέων διεργασιών SJFScheduler sjfs = new SJFScheduler(true); // Προεκχωρίσιμος SJFS while (!end()) { sjfs.SJF(); //Δρομολόγηση διεργασίας cpu.execute(); //Εκτέλεση διεργασίας } //Εγγραφή των στατιστικών stats.WriteStatistics2File("Preemptive SJF"); stats.printStatistics("Preemptive SJF"); // ============== NON-PREEMPTIVE SJF ==============// clock.reset(); //Μηδενισμός ρολογιού stats.reset(); // Αρχικοποίηση παραμέτρων αντικειμένου στατιστικών processParse = new ProcessGenerator(inputFileName, true); //Παραγωγή όλων των διεργασιών processParse.addProcessesToTemporayList(); // Προσθήκη των νέων διεργασιών στην ουρά νέων διεργασιών sjfs.setIsPreemptive(false); // Μη- προεκχωρίσιμος SJFS while (!end()) { sjfs.SJF(); //Δρομολόγηση διεργασίας cpu.execute(); //Εκτέλεση διεργασίας } //Εγγραφή των στατιστικών stats.WriteStatistics2File("Non-Preemptive SJF"); stats.printStatistics("Non-Preemptive SJF"); // ============== RR WITH QUANTUM = 200 ==============// clock.reset(); //Μηδενισμός ρολογιού stats.reset(); // Αρχικοποίηση παραμέτρων αντικειμένου στατιστικών processParse = new ProcessGenerator(inputFileName, true); //Παραγωγή όλων των διεργασιών processParse.addProcessesToTemporayList(); // Προσθήκη των νέων διεργασιών στην ουρά νέων διεργασιών RRScheduler rrs = new RRScheduler(200); //Round Robin με quantum = 200 while (!end()) { rrs.RR(); //Δρομολόγηση διεργασίας cpu.execute(); //Εκτέλεση διεργασίας } //Εγγραφή των στατιστικών stats.WriteStatistics2File("Round Robin with quantum = 200"); stats.printStatistics("Round Robin with quantum = 200"); // ============== RR WITH QUANTUM = 5000 ==============// clock.reset(); //Μηδενισμός ρολογιού stats.reset(); // Αρχικοποίηση παραμέτρων αντικειμένου στατιστικών processParse = new ProcessGenerator(inputFileName, true); //Παραγωγή όλων των διεργασιών processParse.addProcessesToTemporayList(); // Προσθήκη των νέων διεργασιών στην ουρά νέων διεργασιών rrs.setQuantum(5000); //Round Robin με quantum = 5000 while (!end()) { rrs.RR(); //Δρομολόγηση διεργασίας cpu.execute(); //Εκτέλεση διεργασίας } //Εγγραφή των στατιστικών stats.WriteStatistics2File("Round Robin with quantum = 5000"); stats.printStatistics("Round Robin with quantum = 5000"); } }
TeamLS/Operating-System-Simulator
src/operatingsystem/Main.java
2,180
// Προσθήκη των νέων διεργασιών στην ουρά νέων διεργασιών
line_comment
el
package operatingsystem; import java.io.IOException; // Χρίστος Γκόγκος (2738), Αθανάσιος Μπόλλας (2779), Δημήτριος Σβίγγας (2618), Αναστάσιος Τεμπερεκίδης (2808) /* Από την κλάση αυτή ξεκινά η εκτέλεση της εφαρμογής. Δημιουργεί το αρχείο με τις διεργασίες, φορτώνει από αυτό όλες τις διεργασίες και προσομοιώνει την δρομολόγηση με σειρά τους εξής αλγορίθμους: SJF preemptive, SJF non-preemptive, Round Robin quantum=50, Round Robin quantum=300. Τέλος καταγράφει τα στατιστικά από τις παραπάνω προσομοιώσεις και τα αποθηκεύει σε αρχείο. */ public class Main { public static Clock clock; public static CPU cpu; public static NewProcessTemporaryList newProcessList; public static ReadyProcessesList readyProcessesList; public static Statistics stats; /* Επιστρέφει true αν η cpu δεν έχει καμία διεργασία για εκτέλεση, δεν υπάρχει καμία διεργασία στην ουρά έτοιμων διεργασιών και η ουρά νέων διεργασιών είναι άδεια. */ public static boolean end() { return (cpu.getRunningProcess() == null) && (readyProcessesList.isEmpty()) && (newProcessList.isEmpty()); } public static void main(String[] args) throws IOException { String inputFileName = "processes.txt"; //Αρχείο των στοιχείων των διεργασιών String outputFileName = "statistics.txt"; // Αρχείο στατιστικών εκτέλεσης ProcessGenerator processParse; new ProcessGenerator(inputFileName, false); // Δημιουργία αρχείου εισόδου cpu = new CPU(); newProcessList = new NewProcessTemporaryList(); stats = new Statistics(outputFileName); clock = new Clock(); readyProcessesList = new ReadyProcessesList(); // ============== PREEMPTIVE SJF ==============// processParse = new ProcessGenerator(inputFileName, true); //Παραγωγή όλων των διεργασιών processParse.addProcessesToTemporayList(); // Προσθήκη των<SUF> SJFScheduler sjfs = new SJFScheduler(true); // Προεκχωρίσιμος SJFS while (!end()) { sjfs.SJF(); //Δρομολόγηση διεργασίας cpu.execute(); //Εκτέλεση διεργασίας } //Εγγραφή των στατιστικών stats.WriteStatistics2File("Preemptive SJF"); stats.printStatistics("Preemptive SJF"); // ============== NON-PREEMPTIVE SJF ==============// clock.reset(); //Μηδενισμός ρολογιού stats.reset(); // Αρχικοποίηση παραμέτρων αντικειμένου στατιστικών processParse = new ProcessGenerator(inputFileName, true); //Παραγωγή όλων των διεργασιών processParse.addProcessesToTemporayList(); // Προσθήκη των νέων διεργασιών στην ουρά νέων διεργασιών sjfs.setIsPreemptive(false); // Μη- προεκχωρίσιμος SJFS while (!end()) { sjfs.SJF(); //Δρομολόγηση διεργασίας cpu.execute(); //Εκτέλεση διεργασίας } //Εγγραφή των στατιστικών stats.WriteStatistics2File("Non-Preemptive SJF"); stats.printStatistics("Non-Preemptive SJF"); // ============== RR WITH QUANTUM = 200 ==============// clock.reset(); //Μηδενισμός ρολογιού stats.reset(); // Αρχικοποίηση παραμέτρων αντικειμένου στατιστικών processParse = new ProcessGenerator(inputFileName, true); //Παραγωγή όλων των διεργασιών processParse.addProcessesToTemporayList(); // Προσθήκη των νέων διεργασιών στην ουρά νέων διεργασιών RRScheduler rrs = new RRScheduler(200); //Round Robin με quantum = 200 while (!end()) { rrs.RR(); //Δρομολόγηση διεργασίας cpu.execute(); //Εκτέλεση διεργασίας } //Εγγραφή των στατιστικών stats.WriteStatistics2File("Round Robin with quantum = 200"); stats.printStatistics("Round Robin with quantum = 200"); // ============== RR WITH QUANTUM = 5000 ==============// clock.reset(); //Μηδενισμός ρολογιού stats.reset(); // Αρχικοποίηση παραμέτρων αντικειμένου στατιστικών processParse = new ProcessGenerator(inputFileName, true); //Παραγωγή όλων των διεργασιών processParse.addProcessesToTemporayList(); // Προσθήκη των νέων διεργασιών στην ουρά νέων διεργασιών rrs.setQuantum(5000); //Round Robin με quantum = 5000 while (!end()) { rrs.RR(); //Δρομολόγηση διεργασίας cpu.execute(); //Εκτέλεση διεργασίας } //Εγγραφή των στατιστικών stats.WriteStatistics2File("Round Robin with quantum = 5000"); stats.printStatistics("Round Robin with quantum = 5000"); } }
15121_4
// Copyright 2012 Google Inc. All Rights Reserved. package com.google.re2j; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import io.airlift.slice.DynamicSliceOutput; import io.airlift.slice.Slice; import io.airlift.slice.SliceOutput; import static io.airlift.slice.Slices.utf8Slice; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Testing the RE2Matcher class. * * @author [email protected] (Afroz Mohiuddin) */ @RunWith(Enclosed.class) public class MatcherTest { private static final int BUFFER_SIZE = 100; public static class DFA extends MatcherTestBase { public DFA() { super(RUN_WITH_DFA); } } public static class NFA extends MatcherTestBase { public NFA() { super(RUN_WITH_NFA); } } public static abstract class MatcherTestBase extends ApiTest { protected MatcherTestBase(Options options) { super(options); } @Test public void testLookingAt() { verifyLookingAt("abcdef", "abc", true); verifyLookingAt("ab", "abc", false); } @Test public void testMatches() { testMatcherMatches("ab+c", "abbbc", "cbbba"); testMatcherMatches("ab.*c", "abxyzc", "ab\nxyzc"); testMatcherMatches("^ab.*c$", "abc", "xyz\nabc\ndef"); testMatcherMatches("ab+c", "abbbc", "abbcabc"); } @Test public void testReplaceAll() { testReplaceAll("What the Frog's Eye Tells the Frog's Brain", "Frog", "Lizard", "What the Lizard's Eye Tells the Lizard's Brain"); testReplaceAll("What the Frog's Eye Tells the Frog's Brain", "F(rog)", "\\$Liza\\rd$1", "What the $Lizardrog's Eye Tells the $Lizardrog's Brain"); testReplaceAll("What the Frog's Eye Tells the Frog's Brain", "F(?<group>rog)", "\\$Liza\\rd${group}", "What the $Lizardrog's Eye Tells the $Lizardrog's Brain"); testReplaceAllRE2J("What the Frog's Eye Tells the Frog's Brain", "F(?P<group>rog)", "\\$Liza\\rd${group}", "What the $Lizardrog's Eye Tells the $Lizardrog's Brain"); testReplaceAll("abcdefghijklmnopqrstuvwxyz123", "(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)", "$10$20", "jb0wo0123"); testReplaceAll("\u00e1\u0062\u00e7\u2655", "(.)", "<$1>", "<\u00e1><\u0062><\u00e7><\u2655>"); testReplaceAll("\u00e1\u0062\u00e7\u2655", "[\u00e0-\u00e9]", "<$0>", "<\u00e1>\u0062<\u00e7>\u2655"); testReplaceAll("hello world", "z*", "x", "xhxexlxlxox xwxoxrxlxdx"); // test replaceAll with alternation testReplaceAll("123:foo", "(?:\\w+|\\d+:foo)", "x", "x:x"); testReplaceAll("123:foo", "(?:\\d+:foo|\\w+)", "x", "x"); testReplaceAll("aab", "a*", "<$0>", "<aa><>b<>"); testReplaceAll("aab", "a*?", "<$0>", "<>a<>a<>b<>"); } @Test public void testReplaceFirst() { testReplaceFirst("What the Frog's Eye Tells the Frog's Brain", "Frog", "Lizard", "What the Lizard's Eye Tells the Frog's Brain"); testReplaceFirst("What the Frog's Eye Tells the Frog's Brain", "F(rog)", "\\$Liza\\rd$1", "What the $Lizardrog's Eye Tells the Frog's Brain"); testReplaceFirst("abcdefghijklmnopqrstuvwxyz123", "(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)", "$10$20", "jb0nopqrstuvwxyz123"); testReplaceFirst("\u00e1\u0062\u00e7\u2655", "(.)", "<$1>", "<\u00e1>\u0062\u00e7\u2655"); testReplaceFirst("\u00e1\u0062\u00e7\u2655", "[\u00e0-\u00e9]", "<$0>", "<\u00e1>\u0062\u00e7\u2655"); testReplaceFirst("hello world", "z*", "x", "xhello world"); testReplaceFirst("aab", "a*", "<$0>", "<aa>b"); testReplaceFirst("aab", "a*?", "<$0>", "<>aab"); } @Test public void testGroupCount() { testGroupCount("(a)(b(c))d?(e)", 4); } @Test public void testGroup() { testGroup("xabdez", "(a)(b(c)?)d?(e)", new String[]{"abde", "a", "b", null, "e"}); testGroup( "abc", "(a)(b$)?(b)?", new String[]{"ab", "a", null, "b"}); testGroup( "abc", "(^b)?(b)?c", new String[]{"bc", null, "b"}); testGroup( " a b", "\\b(.).\\b", new String[]{"a ", "a"}); // Not allowed to use UTF-8 except in comments, per Java style guide. // ("αβξδεφγ", "(.)(..)(...)", new String[] {"αβξδεφ", "α", "βξ", "δεφ"}); testGroup("\u03b1\u03b2\u03be\u03b4\u03b5\u03c6\u03b3", "(.)(..)(...)", new String[]{"\u03b1\u03b2\u03be\u03b4\u03b5\u03c6", "\u03b1", "\u03b2\u03be", "\u03b4\u03b5\u03c6"}); } @Test public void testFind() { testFind("abcdefgh", ".*[aeiou]", 0, "abcde"); testFind("abcdefgh", ".*[aeiou]", 1, "bcde"); testFind("abcdefgh", ".*[aeiou]", 2, "cde"); testFind("abcdefgh", ".*[aeiou]", 3, "de"); testFind("abcdefgh", ".*[aeiou]", 4, "e"); testFindNoMatch("abcdefgh", ".*[aeiou]", 5); testFindNoMatch("abcdefgh", ".*[aeiou]", 6); testFindNoMatch("abcdefgh", ".*[aeiou]", 7); } @Test public void testInvalidFind() { try { testFind("abcdef", ".*", 10, "xxx"); fail(); } catch (IndexOutOfBoundsException e) { /* ok */ } } @Test public void testInvalidReplacement() { try { testReplaceFirst("abc", "abc", "$4", "xxx"); fail(); } catch (IndexOutOfBoundsException e) { /* ok */ assertTrue(true); } } @Test public void testInvalidGroupNameReplacement() { try { testReplaceFirst("abc", "abc", "${name}", "xxx"); fail(); } catch (IndexOutOfBoundsException e) { /* ok */ assertTrue(true); } } @Test public void testInvalidGroupNoMatch() { try { testInvalidGroup("abc", "xxx", 0); fail(); } catch (IllegalStateException e) { // Linter complains on empty catch block. assertTrue(true); } } @Test public void testInvalidGroupOutOfRange() { try { testInvalidGroup("abc", "abc", 1); fail(); } catch (IndexOutOfBoundsException e) { // Linter complains on empty catch block. assertTrue(true); } } /** * Test the NullPointerException is thrown on null input. */ @Test public void testThrowsOnNullInputReset() { // null in constructor. try { new Matcher(Pattern.compile("pattern", options), null); fail(); } catch (NullPointerException n) { // Linter complains on empty catch block. assertTrue(true); } } @Test public void testThrowsOnNullInputCtor() { // null in constructor. try { new Matcher(null, utf8Slice("input")); fail(); } catch (NullPointerException n) { // Linter complains on empty catch block. assertTrue(true); } } /** * Test that IllegalStateException is thrown if start/end are called before calling find */ @Test public void testStartEndBeforeFind() { try { Matcher m = Pattern.compile("a", options).matcher(utf8Slice("abaca")); m.start(); fail(); } catch (IllegalStateException ise) { assertTrue(true); } } /** * Test for b/6891357. Basically matches should behave like find when it comes to updating the * information of the match. */ @Test public void testMatchesUpdatesMatchInformation() { Matcher m = Pattern.compile("a+", options).matcher(utf8Slice("aaa")); if (m.matches()) { assertEquals(utf8Slice("aaa"), m.group(0)); } } /** * Test for b/6891133. Test matches in case of alternation. */ @Test public void testAlternationMatches() { String s = "123:foo"; assertTrue(Pattern.compile("(?:\\w+|\\d+:foo)", options).matcher(utf8Slice(s)).matches()); assertTrue(Pattern.compile("(?:\\d+:foo|\\w+)", options).matcher(utf8Slice(s)).matches()); } void helperTestMatchEndUTF8(String string, int num, final int end) { String pattern = "[" + string + "]"; RE2 re = new RE2(RE2.compile(pattern, options)) { @Override public boolean match(Slice input, int start, Anchor anchor, int[] group, int ngroup) { assertEquals(input.length(), end); return super.match(input, start, anchor, group, ngroup); } }; Pattern pat = new Pattern(pattern, 0, re, options); Matcher m = pat.matcher(utf8Slice(string)); int found = 0; while (m.find()) { found++; } assertEquals("Matches Expected " + num + " but found " + found + ", for input " + string, num, found); } /** * Test for variable length encoding, test whether RE2's match function gets the required * parameter based on UTF8 codes and not chars and Runes. */ @Test public void testMatchEndUTF8() { // Latin alphabetic chars such as these 5 lower-case, acute vowels have multi-byte UTF-8 // encodings but fit in a single UTF-16 code, so the final match is at UTF16 offset 5. String vowels = "\225\233\237\243\250"; helperTestMatchEndUTF8(vowels, 5, 10); // But surrogates are encoded as two UTF16 codes, so we should expect match // to get 6 rather than 3. String utf16 = new StringBuilder().appendCodePoint(0x10000). appendCodePoint(0x10001).appendCodePoint(0x10002).toString(); assertEquals(utf16, "\uD800\uDC00\uD800\uDC01\uD800\uDC02"); helperTestMatchEndUTF8(utf16, 3, 12); } @Test public void testAppendTail() { Pattern p = Pattern.compile("cat", options); Matcher m = p.matcher(utf8Slice("one cat two cats in the yard")); SliceOutput so = new DynamicSliceOutput(BUFFER_SIZE); while (m.find()) { m.appendReplacement(so, utf8Slice("dog")); } m.appendTail(so); m.appendTail(so); assertEquals("one dog two dogs in the yards in the yard", so.slice().toStringUtf8()); } @Test public void testResetOnFindInt() { SliceOutput buffer; Matcher matcher = Pattern.compile("a", options).matcher(utf8Slice("zza")); assertTrue(matcher.find()); buffer = new DynamicSliceOutput(BUFFER_SIZE); matcher.appendReplacement(buffer, utf8Slice("foo")); assertEquals("1st time", "zzfoo", buffer.slice().toStringUtf8()); assertTrue(matcher.find(0)); buffer = new DynamicSliceOutput(BUFFER_SIZE); matcher.appendReplacement(buffer, utf8Slice("foo")); assertEquals("2nd time", "zzfoo", buffer.slice().toStringUtf8()); } @Test public void testEmptyReplacementGroups() { SliceOutput buffer = new DynamicSliceOutput(BUFFER_SIZE); Matcher matcher = Pattern.compile("(a)(b$)?(b)?", options).matcher(utf8Slice("abc")); assertTrue(matcher.find()); matcher.appendReplacement(buffer, utf8Slice("$1-$2-$3")); assertEquals("a--b", buffer.slice().toStringUtf8()); matcher.appendTail(buffer); assertEquals("a--bc", buffer.slice().toStringUtf8()); buffer = new DynamicSliceOutput(BUFFER_SIZE); matcher = Pattern.compile("(a)(b$)?(b)?", options).matcher(utf8Slice("ab")); assertTrue(matcher.find()); matcher.appendReplacement(buffer, utf8Slice("$1-$2-$3")); matcher.appendTail(buffer); assertEquals("a-b-", buffer.slice().toStringUtf8()); buffer = new DynamicSliceOutput(BUFFER_SIZE); matcher = Pattern.compile("(^b)?(b)?c", options).matcher(utf8Slice("abc")); assertTrue(matcher.find()); matcher.appendReplacement(buffer, utf8Slice("$1-$2")); matcher.appendTail(buffer); assertEquals("a-b", buffer.slice().toStringUtf8()); buffer = new DynamicSliceOutput(BUFFER_SIZE); matcher = Pattern.compile("^(.)[^-]+(-.)?(.*)", options).matcher(utf8Slice("Name")); assertTrue(matcher.find()); matcher.appendReplacement(buffer, utf8Slice("$1$2")); matcher.appendTail(buffer); assertEquals("N", buffer.slice().toStringUtf8()); } // This example is documented in the com.google.re2j package.html. @Test public void testDocumentedExample() { Pattern p = Pattern.compile("b(an)*(.)", options); Matcher m = p.matcher(utf8Slice("by, band, banana")); assertTrue(m.lookingAt()); m.reset(); assertTrue(m.find()); assertEquals(utf8Slice("by"), m.group(0)); assertEquals(null, m.group(1)); assertEquals(utf8Slice("y"), m.group(2)); assertTrue(m.find()); assertEquals(utf8Slice("band"), m.group(0)); assertEquals(utf8Slice("an"), m.group(1)); assertEquals(utf8Slice("d"), m.group(2)); assertTrue(m.find()); assertEquals(utf8Slice("banana"), m.group(0)); assertEquals(utf8Slice("an"), m.group(1)); assertEquals(utf8Slice("a"), m.group(2)); assertFalse(m.find()); } } }
Teradata/re2j
javatests/com/google/re2j/MatcherTest.java
3,979
// ("αβξδεφγ", "(.)(..)(...)", new String[] {"αβξδεφ", "α", "βξ", "δεφ"});
line_comment
el
// Copyright 2012 Google Inc. All Rights Reserved. package com.google.re2j; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import io.airlift.slice.DynamicSliceOutput; import io.airlift.slice.Slice; import io.airlift.slice.SliceOutput; import static io.airlift.slice.Slices.utf8Slice; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Testing the RE2Matcher class. * * @author [email protected] (Afroz Mohiuddin) */ @RunWith(Enclosed.class) public class MatcherTest { private static final int BUFFER_SIZE = 100; public static class DFA extends MatcherTestBase { public DFA() { super(RUN_WITH_DFA); } } public static class NFA extends MatcherTestBase { public NFA() { super(RUN_WITH_NFA); } } public static abstract class MatcherTestBase extends ApiTest { protected MatcherTestBase(Options options) { super(options); } @Test public void testLookingAt() { verifyLookingAt("abcdef", "abc", true); verifyLookingAt("ab", "abc", false); } @Test public void testMatches() { testMatcherMatches("ab+c", "abbbc", "cbbba"); testMatcherMatches("ab.*c", "abxyzc", "ab\nxyzc"); testMatcherMatches("^ab.*c$", "abc", "xyz\nabc\ndef"); testMatcherMatches("ab+c", "abbbc", "abbcabc"); } @Test public void testReplaceAll() { testReplaceAll("What the Frog's Eye Tells the Frog's Brain", "Frog", "Lizard", "What the Lizard's Eye Tells the Lizard's Brain"); testReplaceAll("What the Frog's Eye Tells the Frog's Brain", "F(rog)", "\\$Liza\\rd$1", "What the $Lizardrog's Eye Tells the $Lizardrog's Brain"); testReplaceAll("What the Frog's Eye Tells the Frog's Brain", "F(?<group>rog)", "\\$Liza\\rd${group}", "What the $Lizardrog's Eye Tells the $Lizardrog's Brain"); testReplaceAllRE2J("What the Frog's Eye Tells the Frog's Brain", "F(?P<group>rog)", "\\$Liza\\rd${group}", "What the $Lizardrog's Eye Tells the $Lizardrog's Brain"); testReplaceAll("abcdefghijklmnopqrstuvwxyz123", "(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)", "$10$20", "jb0wo0123"); testReplaceAll("\u00e1\u0062\u00e7\u2655", "(.)", "<$1>", "<\u00e1><\u0062><\u00e7><\u2655>"); testReplaceAll("\u00e1\u0062\u00e7\u2655", "[\u00e0-\u00e9]", "<$0>", "<\u00e1>\u0062<\u00e7>\u2655"); testReplaceAll("hello world", "z*", "x", "xhxexlxlxox xwxoxrxlxdx"); // test replaceAll with alternation testReplaceAll("123:foo", "(?:\\w+|\\d+:foo)", "x", "x:x"); testReplaceAll("123:foo", "(?:\\d+:foo|\\w+)", "x", "x"); testReplaceAll("aab", "a*", "<$0>", "<aa><>b<>"); testReplaceAll("aab", "a*?", "<$0>", "<>a<>a<>b<>"); } @Test public void testReplaceFirst() { testReplaceFirst("What the Frog's Eye Tells the Frog's Brain", "Frog", "Lizard", "What the Lizard's Eye Tells the Frog's Brain"); testReplaceFirst("What the Frog's Eye Tells the Frog's Brain", "F(rog)", "\\$Liza\\rd$1", "What the $Lizardrog's Eye Tells the Frog's Brain"); testReplaceFirst("abcdefghijklmnopqrstuvwxyz123", "(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)", "$10$20", "jb0nopqrstuvwxyz123"); testReplaceFirst("\u00e1\u0062\u00e7\u2655", "(.)", "<$1>", "<\u00e1>\u0062\u00e7\u2655"); testReplaceFirst("\u00e1\u0062\u00e7\u2655", "[\u00e0-\u00e9]", "<$0>", "<\u00e1>\u0062\u00e7\u2655"); testReplaceFirst("hello world", "z*", "x", "xhello world"); testReplaceFirst("aab", "a*", "<$0>", "<aa>b"); testReplaceFirst("aab", "a*?", "<$0>", "<>aab"); } @Test public void testGroupCount() { testGroupCount("(a)(b(c))d?(e)", 4); } @Test public void testGroup() { testGroup("xabdez", "(a)(b(c)?)d?(e)", new String[]{"abde", "a", "b", null, "e"}); testGroup( "abc", "(a)(b$)?(b)?", new String[]{"ab", "a", null, "b"}); testGroup( "abc", "(^b)?(b)?c", new String[]{"bc", null, "b"}); testGroup( " a b", "\\b(.).\\b", new String[]{"a ", "a"}); // Not allowed to use UTF-8 except in comments, per Java style guide. // ("αβξδεφγ", "(.)(..)(...)",<SUF> testGroup("\u03b1\u03b2\u03be\u03b4\u03b5\u03c6\u03b3", "(.)(..)(...)", new String[]{"\u03b1\u03b2\u03be\u03b4\u03b5\u03c6", "\u03b1", "\u03b2\u03be", "\u03b4\u03b5\u03c6"}); } @Test public void testFind() { testFind("abcdefgh", ".*[aeiou]", 0, "abcde"); testFind("abcdefgh", ".*[aeiou]", 1, "bcde"); testFind("abcdefgh", ".*[aeiou]", 2, "cde"); testFind("abcdefgh", ".*[aeiou]", 3, "de"); testFind("abcdefgh", ".*[aeiou]", 4, "e"); testFindNoMatch("abcdefgh", ".*[aeiou]", 5); testFindNoMatch("abcdefgh", ".*[aeiou]", 6); testFindNoMatch("abcdefgh", ".*[aeiou]", 7); } @Test public void testInvalidFind() { try { testFind("abcdef", ".*", 10, "xxx"); fail(); } catch (IndexOutOfBoundsException e) { /* ok */ } } @Test public void testInvalidReplacement() { try { testReplaceFirst("abc", "abc", "$4", "xxx"); fail(); } catch (IndexOutOfBoundsException e) { /* ok */ assertTrue(true); } } @Test public void testInvalidGroupNameReplacement() { try { testReplaceFirst("abc", "abc", "${name}", "xxx"); fail(); } catch (IndexOutOfBoundsException e) { /* ok */ assertTrue(true); } } @Test public void testInvalidGroupNoMatch() { try { testInvalidGroup("abc", "xxx", 0); fail(); } catch (IllegalStateException e) { // Linter complains on empty catch block. assertTrue(true); } } @Test public void testInvalidGroupOutOfRange() { try { testInvalidGroup("abc", "abc", 1); fail(); } catch (IndexOutOfBoundsException e) { // Linter complains on empty catch block. assertTrue(true); } } /** * Test the NullPointerException is thrown on null input. */ @Test public void testThrowsOnNullInputReset() { // null in constructor. try { new Matcher(Pattern.compile("pattern", options), null); fail(); } catch (NullPointerException n) { // Linter complains on empty catch block. assertTrue(true); } } @Test public void testThrowsOnNullInputCtor() { // null in constructor. try { new Matcher(null, utf8Slice("input")); fail(); } catch (NullPointerException n) { // Linter complains on empty catch block. assertTrue(true); } } /** * Test that IllegalStateException is thrown if start/end are called before calling find */ @Test public void testStartEndBeforeFind() { try { Matcher m = Pattern.compile("a", options).matcher(utf8Slice("abaca")); m.start(); fail(); } catch (IllegalStateException ise) { assertTrue(true); } } /** * Test for b/6891357. Basically matches should behave like find when it comes to updating the * information of the match. */ @Test public void testMatchesUpdatesMatchInformation() { Matcher m = Pattern.compile("a+", options).matcher(utf8Slice("aaa")); if (m.matches()) { assertEquals(utf8Slice("aaa"), m.group(0)); } } /** * Test for b/6891133. Test matches in case of alternation. */ @Test public void testAlternationMatches() { String s = "123:foo"; assertTrue(Pattern.compile("(?:\\w+|\\d+:foo)", options).matcher(utf8Slice(s)).matches()); assertTrue(Pattern.compile("(?:\\d+:foo|\\w+)", options).matcher(utf8Slice(s)).matches()); } void helperTestMatchEndUTF8(String string, int num, final int end) { String pattern = "[" + string + "]"; RE2 re = new RE2(RE2.compile(pattern, options)) { @Override public boolean match(Slice input, int start, Anchor anchor, int[] group, int ngroup) { assertEquals(input.length(), end); return super.match(input, start, anchor, group, ngroup); } }; Pattern pat = new Pattern(pattern, 0, re, options); Matcher m = pat.matcher(utf8Slice(string)); int found = 0; while (m.find()) { found++; } assertEquals("Matches Expected " + num + " but found " + found + ", for input " + string, num, found); } /** * Test for variable length encoding, test whether RE2's match function gets the required * parameter based on UTF8 codes and not chars and Runes. */ @Test public void testMatchEndUTF8() { // Latin alphabetic chars such as these 5 lower-case, acute vowels have multi-byte UTF-8 // encodings but fit in a single UTF-16 code, so the final match is at UTF16 offset 5. String vowels = "\225\233\237\243\250"; helperTestMatchEndUTF8(vowels, 5, 10); // But surrogates are encoded as two UTF16 codes, so we should expect match // to get 6 rather than 3. String utf16 = new StringBuilder().appendCodePoint(0x10000). appendCodePoint(0x10001).appendCodePoint(0x10002).toString(); assertEquals(utf16, "\uD800\uDC00\uD800\uDC01\uD800\uDC02"); helperTestMatchEndUTF8(utf16, 3, 12); } @Test public void testAppendTail() { Pattern p = Pattern.compile("cat", options); Matcher m = p.matcher(utf8Slice("one cat two cats in the yard")); SliceOutput so = new DynamicSliceOutput(BUFFER_SIZE); while (m.find()) { m.appendReplacement(so, utf8Slice("dog")); } m.appendTail(so); m.appendTail(so); assertEquals("one dog two dogs in the yards in the yard", so.slice().toStringUtf8()); } @Test public void testResetOnFindInt() { SliceOutput buffer; Matcher matcher = Pattern.compile("a", options).matcher(utf8Slice("zza")); assertTrue(matcher.find()); buffer = new DynamicSliceOutput(BUFFER_SIZE); matcher.appendReplacement(buffer, utf8Slice("foo")); assertEquals("1st time", "zzfoo", buffer.slice().toStringUtf8()); assertTrue(matcher.find(0)); buffer = new DynamicSliceOutput(BUFFER_SIZE); matcher.appendReplacement(buffer, utf8Slice("foo")); assertEquals("2nd time", "zzfoo", buffer.slice().toStringUtf8()); } @Test public void testEmptyReplacementGroups() { SliceOutput buffer = new DynamicSliceOutput(BUFFER_SIZE); Matcher matcher = Pattern.compile("(a)(b$)?(b)?", options).matcher(utf8Slice("abc")); assertTrue(matcher.find()); matcher.appendReplacement(buffer, utf8Slice("$1-$2-$3")); assertEquals("a--b", buffer.slice().toStringUtf8()); matcher.appendTail(buffer); assertEquals("a--bc", buffer.slice().toStringUtf8()); buffer = new DynamicSliceOutput(BUFFER_SIZE); matcher = Pattern.compile("(a)(b$)?(b)?", options).matcher(utf8Slice("ab")); assertTrue(matcher.find()); matcher.appendReplacement(buffer, utf8Slice("$1-$2-$3")); matcher.appendTail(buffer); assertEquals("a-b-", buffer.slice().toStringUtf8()); buffer = new DynamicSliceOutput(BUFFER_SIZE); matcher = Pattern.compile("(^b)?(b)?c", options).matcher(utf8Slice("abc")); assertTrue(matcher.find()); matcher.appendReplacement(buffer, utf8Slice("$1-$2")); matcher.appendTail(buffer); assertEquals("a-b", buffer.slice().toStringUtf8()); buffer = new DynamicSliceOutput(BUFFER_SIZE); matcher = Pattern.compile("^(.)[^-]+(-.)?(.*)", options).matcher(utf8Slice("Name")); assertTrue(matcher.find()); matcher.appendReplacement(buffer, utf8Slice("$1$2")); matcher.appendTail(buffer); assertEquals("N", buffer.slice().toStringUtf8()); } // This example is documented in the com.google.re2j package.html. @Test public void testDocumentedExample() { Pattern p = Pattern.compile("b(an)*(.)", options); Matcher m = p.matcher(utf8Slice("by, band, banana")); assertTrue(m.lookingAt()); m.reset(); assertTrue(m.find()); assertEquals(utf8Slice("by"), m.group(0)); assertEquals(null, m.group(1)); assertEquals(utf8Slice("y"), m.group(2)); assertTrue(m.find()); assertEquals(utf8Slice("band"), m.group(0)); assertEquals(utf8Slice("an"), m.group(1)); assertEquals(utf8Slice("d"), m.group(2)); assertTrue(m.find()); assertEquals(utf8Slice("banana"), m.group(0)); assertEquals(utf8Slice("an"), m.group(1)); assertEquals(utf8Slice("a"), m.group(2)); assertFalse(m.find()); } } }
10405_1
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui; import db.DBManager; import gui.utilities.UtilFuncs; import javax.swing.JOptionPane; /** * * @author Ηλίας */ public class MainWindow extends javax.swing.JFrame { /** * Creates new form NewJFrametest */ public MainWindow() { initComponents(); setLocationByPlatform(true); setVisible(true); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel_icon = new javax.swing.JLabel(); jButton_Diaxeirisi_ypopsifiwn = new javax.swing.JButton(); jButton_Prosomoiwtis = new javax.swing.JButton(); jButton_Exit = new javax.swing.JButton(); jLabel_Epilogi = new javax.swing.JLabel(); jLabel_MainTitle = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("eVoting"); setResizable(false); jLabel_icon.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel_icon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/logofinal.png"))); // NOI18N jButton_Diaxeirisi_ypopsifiwn.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton_Diaxeirisi_ypopsifiwn.setText("1. Διαχείριση υποψηφίων"); jButton_Diaxeirisi_ypopsifiwn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_Diaxeirisi_ypopsifiwnActionPerformed(evt); } }); jButton_Prosomoiwtis.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton_Prosomoiwtis.setText("2. Προσομοιωτής εκλογικής διαδικασίας"); jButton_Prosomoiwtis.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_ProsomoiwtisActionPerformed(evt); } }); jButton_Exit.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton_Exit.setText("3. Έξοδος"); jButton_Exit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_ExitActionPerformed(evt); } }); jLabel_Epilogi.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel_Epilogi.setText("Παρακαλώ επιλέξτε:"); jLabel_MainTitle.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel_MainTitle.setForeground(new java.awt.Color(0, 0, 255)); jLabel_MainTitle.setText("Hellenic eEvoting System"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel_icon, javax.swing.GroupLayout.DEFAULT_SIZE, 945, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(301, 301, 301) .addComponent(jLabel_MainTitle)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(364, 364, 364) .addComponent(jLabel_Epilogi)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(304, 304, 304) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(jButton_Diaxeirisi_ypopsifiwn) .addComponent(jButton_Prosomoiwtis) .addComponent(jButton_Exit)))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(42, 42, 42) .addComponent(jLabel_MainTitle) .addGap(18, 18, 18) .addComponent(jLabel_icon, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel_Epilogi) .addGap(40, 40, 40) .addComponent(jButton_Diaxeirisi_ypopsifiwn) .addGap(18, 18, 18) .addComponent(jButton_Prosomoiwtis) .addGap(18, 18, 18) .addComponent(jButton_Exit) .addContainerGap(138, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton_ProsomoiwtisActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ProsomoiwtisActionPerformed new Prosomoiwsi(UtilFuncs.getDialogOwnerFrame(), true); }//GEN-LAST:event_jButton_ProsomoiwtisActionPerformed private void jButton_Diaxeirisi_ypopsifiwnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_Diaxeirisi_ypopsifiwnActionPerformed try { new Diaxeirisi(UtilFuncs.getDialogOwnerFrame(), true); } catch (Exception e) { JOptionPane.showMessageDialog(UtilFuncs.getDialogOwnerFrame(), "Error connecting to the database." + "\nMake sure the Java DB Server is running and try again.\n\n", "Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jButton_Diaxeirisi_ypopsifiwnActionPerformed private void jButton_ExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ExitActionPerformed DBManager.destroy(); dispose(); }//GEN-LAST:event_jButton_ExitActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton_Diaxeirisi_ypopsifiwn; private javax.swing.JButton jButton_Exit; private javax.swing.JButton jButton_Prosomoiwtis; private javax.swing.JLabel jLabel_Epilogi; private javax.swing.JLabel jLabel_MainTitle; private javax.swing.JLabel jLabel_icon; private javax.swing.JPanel jPanel1; // End of variables declaration//GEN-END:variables }
TexNikos/eVoting
Source/eVoting/src/gui/MainWindow.java
1,981
/** * * @author Ηλίας */
block_comment
el
/* * 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 gui; import db.DBManager; import gui.utilities.UtilFuncs; import javax.swing.JOptionPane; /** * * @author Ηλίας <SUF>*/ public class MainWindow extends javax.swing.JFrame { /** * Creates new form NewJFrametest */ public MainWindow() { initComponents(); setLocationByPlatform(true); setVisible(true); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel_icon = new javax.swing.JLabel(); jButton_Diaxeirisi_ypopsifiwn = new javax.swing.JButton(); jButton_Prosomoiwtis = new javax.swing.JButton(); jButton_Exit = new javax.swing.JButton(); jLabel_Epilogi = new javax.swing.JLabel(); jLabel_MainTitle = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("eVoting"); setResizable(false); jLabel_icon.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel_icon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/logofinal.png"))); // NOI18N jButton_Diaxeirisi_ypopsifiwn.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton_Diaxeirisi_ypopsifiwn.setText("1. Διαχείριση υποψηφίων"); jButton_Diaxeirisi_ypopsifiwn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_Diaxeirisi_ypopsifiwnActionPerformed(evt); } }); jButton_Prosomoiwtis.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton_Prosomoiwtis.setText("2. Προσομοιωτής εκλογικής διαδικασίας"); jButton_Prosomoiwtis.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_ProsomoiwtisActionPerformed(evt); } }); jButton_Exit.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton_Exit.setText("3. Έξοδος"); jButton_Exit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_ExitActionPerformed(evt); } }); jLabel_Epilogi.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel_Epilogi.setText("Παρακαλώ επιλέξτε:"); jLabel_MainTitle.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel_MainTitle.setForeground(new java.awt.Color(0, 0, 255)); jLabel_MainTitle.setText("Hellenic eEvoting System"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel_icon, javax.swing.GroupLayout.DEFAULT_SIZE, 945, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(301, 301, 301) .addComponent(jLabel_MainTitle)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(364, 364, 364) .addComponent(jLabel_Epilogi)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(304, 304, 304) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(jButton_Diaxeirisi_ypopsifiwn) .addComponent(jButton_Prosomoiwtis) .addComponent(jButton_Exit)))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(42, 42, 42) .addComponent(jLabel_MainTitle) .addGap(18, 18, 18) .addComponent(jLabel_icon, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel_Epilogi) .addGap(40, 40, 40) .addComponent(jButton_Diaxeirisi_ypopsifiwn) .addGap(18, 18, 18) .addComponent(jButton_Prosomoiwtis) .addGap(18, 18, 18) .addComponent(jButton_Exit) .addContainerGap(138, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton_ProsomoiwtisActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ProsomoiwtisActionPerformed new Prosomoiwsi(UtilFuncs.getDialogOwnerFrame(), true); }//GEN-LAST:event_jButton_ProsomoiwtisActionPerformed private void jButton_Diaxeirisi_ypopsifiwnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_Diaxeirisi_ypopsifiwnActionPerformed try { new Diaxeirisi(UtilFuncs.getDialogOwnerFrame(), true); } catch (Exception e) { JOptionPane.showMessageDialog(UtilFuncs.getDialogOwnerFrame(), "Error connecting to the database." + "\nMake sure the Java DB Server is running and try again.\n\n", "Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jButton_Diaxeirisi_ypopsifiwnActionPerformed private void jButton_ExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ExitActionPerformed DBManager.destroy(); dispose(); }//GEN-LAST:event_jButton_ExitActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton_Diaxeirisi_ypopsifiwn; private javax.swing.JButton jButton_Exit; private javax.swing.JButton jButton_Prosomoiwtis; private javax.swing.JLabel jLabel_Epilogi; private javax.swing.JLabel jLabel_MainTitle; private javax.swing.JLabel jLabel_icon; private javax.swing.JPanel jPanel1; // End of variables declaration//GEN-END:variables }
62_5
/* ΟΝΟΜΑΤΕΠΩΝΥΜΟ: ΜΑΤΣΚΙΔΗΣ ΑΘΑΝΑΣΙΟΣ * ΕΤΟΙΜΟΣ ΚΩΔΙΚΑΣ: ΤΟ ΔΙΑΒΑΣΜΑ ΤΟΥ ΑΡΧΕΙΟΥ ΩΣ ΟΡΙΣΜΑ ΤΟ ΟΠΟΙΟ ΠΗΡΑ ΑΠΟ https://www2.hawaii.edu/~walbritt/ics211/examples/ReadFromFile.java */ import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class Cores { /* ΑΝΑΠΑΡΑΣΤΑΣΗ ΤΩΝ ΑΠΑΙΤΉΣΕΩΝ ΤΩΝ ΚΑΤΑΝΑΛΩΤΩΝ ΣΕ ΠΥΡΗΝΕΣ ΚΑΙ Η ΠΡΟΣΦΕΡΟΜΕΝΗ ΤΙΜΗ ΑΝΑ ΠΥΡΗΝΑ. */ static class Demands { private int cores; private double pricePerCore; public Demands(int cores, double pricePerCore) { this.cores = cores; this.pricePerCore = pricePerCore; } public int getCores() {return cores;} public double getPricePerCore() {return pricePerCore;} } /* minNumberOfCoins: ΔΕΧΕΤΑΙ ΩΣ ΟΡΙΣΜΑ ΕΝΑΝ ΠΙΝΑΚΑ ΠΟΥ ΕΧΕΙ ΤΙΣ ΤΙΜΕΣ ΤΩΝ ΔΙΑΘΕΣΙΜΩΝ ΠΥΡΗΝΩΝ ΑΝ VMs * ΤΟ ΜΕΓΕΘΟΣ ΑΥΤΟΥ ΤΟΥ ΠΙΝΑΚΑ ΚΑΙ ΤΟΝ ΑΡΙΘΜΟ ΤΩΝ ΠΥΡΗΝΩΝ ΠΟΥ ΑΠΑΙΤΕΙ Ο ΚΑΤΑΝΑΛΩΤΗΣ ΚΑΙ ΕΠΙΣΤΡΕΦΕΙ * ΤΟΝ ΑΡΙΘΜΟ ΤΩΝ VMs. */ public static int minNumberOfCoins(int availableCores[], int size, int value) { int VMs[] = new int[value + 1]; VMs[0] = 0; for (int i = 1; i <= value; i++) { VMs[i] = Integer.MAX_VALUE; } for (int i = 1; i <= value; i++) { for (int j = 0; j < size; j++) { if (availableCores[j] <= i) { int sub_res = VMs[i - availableCores[j]]; if (sub_res != Integer.MAX_VALUE && sub_res + 1 < VMs[i]) { VMs[i] = sub_res + 1; } } } } return VMs[value]; } /* printVMs: ΔΕΧΕΤΑΙ ΣΑΝ ΟΡΙΣΜΑ ΕΝΑ ArrayList ΟΠΟΥ ΕΙΝΑΙ ΑΠΟΘΗΚΕΥΜΈΝΑ Ο ΑΡΙΘΜΟΣ ΤΩΝ VMs ΤΩΝ * ΚΑΤΑΝΑΛΩΤΩΝ ΚΑΙ ΤΑ ΕΜΦΑΝΙΖΕΙ ΣΤΗΝ ΖΗΤΟΥΜΕΝΗ ΜΟΡΦΗ. */ public static void printVMs(ArrayList<Integer> VMs) { for (int i = 0; i < VMs.size(); i++) { System.out.println("Client " + (i + 1) + ": " + VMs.get(i) + " VMs"); } } /* maxValue: ΔΕΧΕΤΑΙ ΩΣ ΟΡΙΣΜΑΤΑ ΤΟΝ ΑΡΙΘΜΟ ΤΩΝ ΔΙΑΘΕΣΙΜΩΝ ΠΥΡΗΝΩΝ ΣΤΟΥΣ SERVERS, ΕΝΑΝ ΠΙΝΑΚΑ ΠΟΥ ΕΙΝΑΙ ΑΠΟΘΗΚΕΥΜΕΝΑ * ΟΙ ΤΙΜΕΣ ΤΩΝ ΑΠΑΙΤΗΣΕΩΝ ΤΩΝ ΚΑΤΑΝΑΛΩΤΩΝ ΣΕ ΠΥΡΗΝΕΣ, ΕΝΑΝ ΠΙΝΑΚΑ ΜΕ ΤΙΣ ΤΙΜΕΣ ΤΟΥ ΣΥΝΟΛΙΚΟΥ ΠΟΣΟΥ ΠΡΟΣ ΠΛΗΡΩΜΗ ΓΙΑ * ΚΑΘΕ ΚΑΤΑΝΑΛΩΤΗ ΚΑΙ ΤΟΝ ΑΡΙΘΜΟ ΤΩΝ ΚΑΤΑΝΑΛΩΤΩΝ ΚΑΙ ΕΠΙΣΤΡΕΦΕΙ ΤΟ ΜΕΓΙΣΤΟ ΠΟΣΟ ΠΛΗΡΩΜΗΣ. */ public static double maxValue(int cores, int weight[], double value[], int numberOfCustomers) { double data[][] = new double[numberOfCustomers + 1][cores + 1]; for (int i = 0; i <= numberOfCustomers; i++) { for (int j = 0; j <= cores; j++) { if (i == 0 || j == 0) { data[i][j] = 0; } else if (weight[i - 1] <= j) { data[i][j] = Math.max(value[i - 1] + data[i - 1][j - weight[i - 1]], data[i - 1][j]); } else { data[i][j] = data[i - 1][j]; } } } return data[numberOfCustomers][cores]; } public static void main(String[] args) { File file = null; Scanner readFromFile = null; String line = null; /* ΠΕΡΙΠΤΩΣΗ ΟΠΟΥ ΔΕΝ ΥΠΑΡΧΕΙ ΚΑΝΕΝΑ ΑΡΧΕΙΟ ΩΣ ΟΡΙΣΜΑ. */ if (args.length == 0){ System.out.println("ERROR: Please enter the file name as the first commandline argument."); System.exit(1); } /* ΠΕΡΙΠΤΩΣΗ ΑΔΥΝΑΜΙΑΣ ΕΥΡΕΣΗΣ ΤΟΥ ΑΡΧΕΙΟΥ. */ file = new File(args[0]); try{ readFromFile = new Scanner(file); }catch (FileNotFoundException exception){ System.out.println("ERROR: File not found for \""); System.out.println(args[0]+"\""); System.exit(1); } /* ΔΗΜΙΟΥΡΓΙΑ ΣΥΝΟΛΟΥ ΟΛΩΝ ΤΩΝ ΣΗΜΕΙΩΝ. */ line=readFromFile.nextLine(); int totalCores = Integer.parseInt(line); ArrayList<Demands> demandsList = new ArrayList<>(); while (readFromFile.hasNextLine()){ line=readFromFile.nextLine(); if (line.split(" ").length > 1) { Demands demand = new Demands(Integer.parseInt(line.split(" ")[0]), Double.parseDouble(line.split(" ")[1])); demandsList.add(demand); } } int availableCores[] = {1, 2, 7, 11}; int size = availableCores.length; ArrayList<Integer> VMs = new ArrayList<Integer>(); for (int i = 0; i < demandsList.size(); i++) { VMs.add(minNumberOfCoins(availableCores, size, demandsList.get(i).getCores())); } printVMs(VMs); double value[] = new double[demandsList.size()]; int weight[] = new int [demandsList.size()]; size = value.length; for (int i = 0; i < demandsList.size(); i++) { value[i] = demandsList.get(i).getCores() * demandsList.get(i).getPricePerCore(); weight[i] = demandsList.get(i).getCores(); } System.out.println("Total amount: " + maxValue(totalCores, weight, value, size)); } }
ThanasisMatskidis/Knapsack
Cores.java
2,693
/* ΠΕΡΙΠΤΩΣΗ ΟΠΟΥ ΔΕΝ ΥΠΑΡΧΕΙ ΚΑΝΕΝΑ ΑΡΧΕΙΟ ΩΣ ΟΡΙΣΜΑ. */
block_comment
el
/* ΟΝΟΜΑΤΕΠΩΝΥΜΟ: ΜΑΤΣΚΙΔΗΣ ΑΘΑΝΑΣΙΟΣ * ΕΤΟΙΜΟΣ ΚΩΔΙΚΑΣ: ΤΟ ΔΙΑΒΑΣΜΑ ΤΟΥ ΑΡΧΕΙΟΥ ΩΣ ΟΡΙΣΜΑ ΤΟ ΟΠΟΙΟ ΠΗΡΑ ΑΠΟ https://www2.hawaii.edu/~walbritt/ics211/examples/ReadFromFile.java */ import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class Cores { /* ΑΝΑΠΑΡΑΣΤΑΣΗ ΤΩΝ ΑΠΑΙΤΉΣΕΩΝ ΤΩΝ ΚΑΤΑΝΑΛΩΤΩΝ ΣΕ ΠΥΡΗΝΕΣ ΚΑΙ Η ΠΡΟΣΦΕΡΟΜΕΝΗ ΤΙΜΗ ΑΝΑ ΠΥΡΗΝΑ. */ static class Demands { private int cores; private double pricePerCore; public Demands(int cores, double pricePerCore) { this.cores = cores; this.pricePerCore = pricePerCore; } public int getCores() {return cores;} public double getPricePerCore() {return pricePerCore;} } /* minNumberOfCoins: ΔΕΧΕΤΑΙ ΩΣ ΟΡΙΣΜΑ ΕΝΑΝ ΠΙΝΑΚΑ ΠΟΥ ΕΧΕΙ ΤΙΣ ΤΙΜΕΣ ΤΩΝ ΔΙΑΘΕΣΙΜΩΝ ΠΥΡΗΝΩΝ ΑΝ VMs * ΤΟ ΜΕΓΕΘΟΣ ΑΥΤΟΥ ΤΟΥ ΠΙΝΑΚΑ ΚΑΙ ΤΟΝ ΑΡΙΘΜΟ ΤΩΝ ΠΥΡΗΝΩΝ ΠΟΥ ΑΠΑΙΤΕΙ Ο ΚΑΤΑΝΑΛΩΤΗΣ ΚΑΙ ΕΠΙΣΤΡΕΦΕΙ * ΤΟΝ ΑΡΙΘΜΟ ΤΩΝ VMs. */ public static int minNumberOfCoins(int availableCores[], int size, int value) { int VMs[] = new int[value + 1]; VMs[0] = 0; for (int i = 1; i <= value; i++) { VMs[i] = Integer.MAX_VALUE; } for (int i = 1; i <= value; i++) { for (int j = 0; j < size; j++) { if (availableCores[j] <= i) { int sub_res = VMs[i - availableCores[j]]; if (sub_res != Integer.MAX_VALUE && sub_res + 1 < VMs[i]) { VMs[i] = sub_res + 1; } } } } return VMs[value]; } /* printVMs: ΔΕΧΕΤΑΙ ΣΑΝ ΟΡΙΣΜΑ ΕΝΑ ArrayList ΟΠΟΥ ΕΙΝΑΙ ΑΠΟΘΗΚΕΥΜΈΝΑ Ο ΑΡΙΘΜΟΣ ΤΩΝ VMs ΤΩΝ * ΚΑΤΑΝΑΛΩΤΩΝ ΚΑΙ ΤΑ ΕΜΦΑΝΙΖΕΙ ΣΤΗΝ ΖΗΤΟΥΜΕΝΗ ΜΟΡΦΗ. */ public static void printVMs(ArrayList<Integer> VMs) { for (int i = 0; i < VMs.size(); i++) { System.out.println("Client " + (i + 1) + ": " + VMs.get(i) + " VMs"); } } /* maxValue: ΔΕΧΕΤΑΙ ΩΣ ΟΡΙΣΜΑΤΑ ΤΟΝ ΑΡΙΘΜΟ ΤΩΝ ΔΙΑΘΕΣΙΜΩΝ ΠΥΡΗΝΩΝ ΣΤΟΥΣ SERVERS, ΕΝΑΝ ΠΙΝΑΚΑ ΠΟΥ ΕΙΝΑΙ ΑΠΟΘΗΚΕΥΜΕΝΑ * ΟΙ ΤΙΜΕΣ ΤΩΝ ΑΠΑΙΤΗΣΕΩΝ ΤΩΝ ΚΑΤΑΝΑΛΩΤΩΝ ΣΕ ΠΥΡΗΝΕΣ, ΕΝΑΝ ΠΙΝΑΚΑ ΜΕ ΤΙΣ ΤΙΜΕΣ ΤΟΥ ΣΥΝΟΛΙΚΟΥ ΠΟΣΟΥ ΠΡΟΣ ΠΛΗΡΩΜΗ ΓΙΑ * ΚΑΘΕ ΚΑΤΑΝΑΛΩΤΗ ΚΑΙ ΤΟΝ ΑΡΙΘΜΟ ΤΩΝ ΚΑΤΑΝΑΛΩΤΩΝ ΚΑΙ ΕΠΙΣΤΡΕΦΕΙ ΤΟ ΜΕΓΙΣΤΟ ΠΟΣΟ ΠΛΗΡΩΜΗΣ. */ public static double maxValue(int cores, int weight[], double value[], int numberOfCustomers) { double data[][] = new double[numberOfCustomers + 1][cores + 1]; for (int i = 0; i <= numberOfCustomers; i++) { for (int j = 0; j <= cores; j++) { if (i == 0 || j == 0) { data[i][j] = 0; } else if (weight[i - 1] <= j) { data[i][j] = Math.max(value[i - 1] + data[i - 1][j - weight[i - 1]], data[i - 1][j]); } else { data[i][j] = data[i - 1][j]; } } } return data[numberOfCustomers][cores]; } public static void main(String[] args) { File file = null; Scanner readFromFile = null; String line = null; /* ΠΕΡΙΠΤΩΣΗ ΟΠΟΥ ΔΕΝ<SUF>*/ if (args.length == 0){ System.out.println("ERROR: Please enter the file name as the first commandline argument."); System.exit(1); } /* ΠΕΡΙΠΤΩΣΗ ΑΔΥΝΑΜΙΑΣ ΕΥΡΕΣΗΣ ΤΟΥ ΑΡΧΕΙΟΥ. */ file = new File(args[0]); try{ readFromFile = new Scanner(file); }catch (FileNotFoundException exception){ System.out.println("ERROR: File not found for \""); System.out.println(args[0]+"\""); System.exit(1); } /* ΔΗΜΙΟΥΡΓΙΑ ΣΥΝΟΛΟΥ ΟΛΩΝ ΤΩΝ ΣΗΜΕΙΩΝ. */ line=readFromFile.nextLine(); int totalCores = Integer.parseInt(line); ArrayList<Demands> demandsList = new ArrayList<>(); while (readFromFile.hasNextLine()){ line=readFromFile.nextLine(); if (line.split(" ").length > 1) { Demands demand = new Demands(Integer.parseInt(line.split(" ")[0]), Double.parseDouble(line.split(" ")[1])); demandsList.add(demand); } } int availableCores[] = {1, 2, 7, 11}; int size = availableCores.length; ArrayList<Integer> VMs = new ArrayList<Integer>(); for (int i = 0; i < demandsList.size(); i++) { VMs.add(minNumberOfCoins(availableCores, size, demandsList.get(i).getCores())); } printVMs(VMs); double value[] = new double[demandsList.size()]; int weight[] = new int [demandsList.size()]; size = value.length; for (int i = 0; i < demandsList.size(); i++) { value[i] = demandsList.get(i).getCores() * demandsList.get(i).getPricePerCore(); weight[i] = demandsList.get(i).getCores(); } System.out.println("Total amount: " + maxValue(totalCores, weight, value, size)); } }
15828_0
package ticTacTow; import java.util.ArrayList; import java.util.List; import java.util.Random; public class Computer { private String[] array; private String a1="",a2="",a3="",b1="",b2="", b3="",c1="",c2="",c3 =""; public Computer() { } public void computerMove() { System.out.println("Computer Move (O): "); List<String> options = new ArrayList<>(); options.add("A1"); options.add("A2"); options.add("A3"); options.add("B1"); options.add("B2"); options.add("B3"); options.add("C1"); options.add("C2"); options.add("C3"); Random random = new Random(); int numChoices = 5; // Αριθμός επιλογών που θέλουμε να κάνουμε String randomOption = ""; int randomIndex; for (int i = 0; i < numChoices; i++) { randomIndex = random.nextInt(options.size()); randomOption = options.get(randomIndex); options.remove(randomIndex); } if (randomOption.equals("A1")) a1 = "O"; else if (randomOption.equals("A2")) a2 = "O"; else if (randomOption.equals("A3")) a3 = "O"; else if (randomOption.equals("B1")) b1 = "O"; else if (randomOption.equals("B2")) b2 = "O"; else if (randomOption.equals("B3")) b3 = "O"; else if (randomOption.equals("C1")) c1 = "O"; else if (randomOption.equals("C2")) c2 = "O"; else if (randomOption.equals("C3")) c3 = "O"; array = new String[9]; array[0] = a1; array[1] = a2; array[2] = a3; array[3] = b1; array[4] = b2; array[5] = b3; array[6] = c1; array[7] = c2; array[8] = c3; } public boolean checkWin(String[] array) { if(array[0] == "O" && array[1] == "O" && array[2] == "O" || array[3] == "O" && array[4] == "O" && array[5] == "O" || array[6] == "O" && array[7] == "O" && array[8] == "O" || array[0] == "O" && array[3] =="O" && array[6] =="O"|| array[1] =="O" && array[4] =="O" && array[7] =="O" || array[2] == "O" && array[5] =="O" && array[8] =="O" || array[0] == "O" && array[4] == "O" && array[8] == "O" || array[2] == "O" && array[4] == "O" && array[6] == "O") return true; return false; } public String[] sGett() { Player playerr = new Player(); String[] a = playerr.getArray(); return a; } public String getA1() { return a1; } public String getA2() { return a2; } public String getA3() { return a3; } public String getB1() { return b1; } public String getB2() { return b2; } public String getB3() { return b3; } public String getC1() { return c1; } public String getC2() { return c2; } public String getC3() { return c3; } public String[] getArray() { return array; } }
ThanasisMpostantzis/Java_Projects
Tic-Tac-Toe/src/ticTacTow/Computer.java
1,075
// Αριθμός επιλογών που θέλουμε να κάνουμε
line_comment
el
package ticTacTow; import java.util.ArrayList; import java.util.List; import java.util.Random; public class Computer { private String[] array; private String a1="",a2="",a3="",b1="",b2="", b3="",c1="",c2="",c3 =""; public Computer() { } public void computerMove() { System.out.println("Computer Move (O): "); List<String> options = new ArrayList<>(); options.add("A1"); options.add("A2"); options.add("A3"); options.add("B1"); options.add("B2"); options.add("B3"); options.add("C1"); options.add("C2"); options.add("C3"); Random random = new Random(); int numChoices = 5; // Αριθμός επιλογών<SUF> String randomOption = ""; int randomIndex; for (int i = 0; i < numChoices; i++) { randomIndex = random.nextInt(options.size()); randomOption = options.get(randomIndex); options.remove(randomIndex); } if (randomOption.equals("A1")) a1 = "O"; else if (randomOption.equals("A2")) a2 = "O"; else if (randomOption.equals("A3")) a3 = "O"; else if (randomOption.equals("B1")) b1 = "O"; else if (randomOption.equals("B2")) b2 = "O"; else if (randomOption.equals("B3")) b3 = "O"; else if (randomOption.equals("C1")) c1 = "O"; else if (randomOption.equals("C2")) c2 = "O"; else if (randomOption.equals("C3")) c3 = "O"; array = new String[9]; array[0] = a1; array[1] = a2; array[2] = a3; array[3] = b1; array[4] = b2; array[5] = b3; array[6] = c1; array[7] = c2; array[8] = c3; } public boolean checkWin(String[] array) { if(array[0] == "O" && array[1] == "O" && array[2] == "O" || array[3] == "O" && array[4] == "O" && array[5] == "O" || array[6] == "O" && array[7] == "O" && array[8] == "O" || array[0] == "O" && array[3] =="O" && array[6] =="O"|| array[1] =="O" && array[4] =="O" && array[7] =="O" || array[2] == "O" && array[5] =="O" && array[8] =="O" || array[0] == "O" && array[4] == "O" && array[8] == "O" || array[2] == "O" && array[4] == "O" && array[6] == "O") return true; return false; } public String[] sGett() { Player playerr = new Player(); String[] a = playerr.getArray(); return a; } public String getA1() { return a1; } public String getA2() { return a2; } public String getA3() { return a3; } public String getB1() { return b1; } public String getB2() { return b2; } public String getB3() { return b3; } public String getC1() { return c1; } public String getC2() { return c2; } public String getC3() { return c3; } public String[] getArray() { return array; } }
6835_0
import java.io.Serializable; import java.util.Date; public class Event implements Serializable {// κλάση εκδήλωσης // attributes εκδήλωσης private String title;//τίτλος private String genre;//είδος private String event_date;//ημερομηνία private int available_seats;//Διαθέσιμες Θέσεις private int cost_per_seat;//Κόστος ανά θεατή private String time;//Ώρα έναρξης εκδήλωσης public Event(String title, String genre, String event_date, String time, int available_seats, int cost_per_seat) {// constructor of the event this.title = title; this.genre = genre; this.event_date = event_date; this.time = time; this.available_seats = available_seats; this.cost_per_seat = cost_per_seat; } // accessors public String getTitle() { return title; } public String getGenre() { return genre; } public String getEvent_date() { return event_date; } public int getAvailable_seats() { return available_seats; } public int getCost_per_seat() { return cost_per_seat; } public void setAvailable_seats(int available_seats) { this.available_seats = available_seats; } public String getTime() { return time; } @Override public String toString() { return "Event{" + "title=" + title + ", genre=" + genre + ", event_date=" + event_date + ", available_seats=" + available_seats + ", cost_per_seat=" + cost_per_seat + ", time=" + time + '}'; } }
TheofanisB/3-Level-Event-Booking-Client-LoginServer-DatabaseServer-
Client/Event.java
458
// κλάση εκδήλωσης
line_comment
el
import java.io.Serializable; import java.util.Date; public class Event implements Serializable {// κλάση εκδήλωσης<SUF> // attributes εκδήλωσης private String title;//τίτλος private String genre;//είδος private String event_date;//ημερομηνία private int available_seats;//Διαθέσιμες Θέσεις private int cost_per_seat;//Κόστος ανά θεατή private String time;//Ώρα έναρξης εκδήλωσης public Event(String title, String genre, String event_date, String time, int available_seats, int cost_per_seat) {// constructor of the event this.title = title; this.genre = genre; this.event_date = event_date; this.time = time; this.available_seats = available_seats; this.cost_per_seat = cost_per_seat; } // accessors public String getTitle() { return title; } public String getGenre() { return genre; } public String getEvent_date() { return event_date; } public int getAvailable_seats() { return available_seats; } public int getCost_per_seat() { return cost_per_seat; } public void setAvailable_seats(int available_seats) { this.available_seats = available_seats; } public String getTime() { return time; } @Override public String toString() { return "Event{" + "title=" + title + ", genre=" + genre + ", event_date=" + event_date + ", available_seats=" + available_seats + ", cost_per_seat=" + cost_per_seat + ", time=" + time + '}'; } }
296_35
import org.w3c.dom.ls.LSOutput; import javax.crypto.*; import javax.swing.*; import java.io.*; import java.nio.file.*; import java.security.*; import java.security.spec.*; import java.util.ArrayList; import java.util.Arrays; import static java.lang.Integer.parseInt; public class Functions { protected static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";// email pattern protected static final String CVV_PATTERN = "([0-9]{3}){1}$";//cvv pattern protected static final String CC_PATTERN = "([0-9]{16}){1}";//credit card number pattern protected static final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,}$";//password pattern protected static FileOutputStream fileOut;// Create a file stream so we can write data to a file protected static ObjectOutputStream objectOut;// Creating an object stream so we can write objects to a file protected static FileInputStream fileIn;// Creating an input stream so we can read from a file protected static ObjectInputStream objectIn;// Creating an input stream so we can read objects from a file protected static FileOutputStream fileOutuser;//Creating a file so we can write in it Δημιουργία ενός αρχείου ώστε να γράψω σε αυτό protected static ObjectOutputStream objectOutuser; protected static FileInputStream fileInuser; protected static ObjectInputStream objectInuser; protected static File fuser; protected static ArrayList<Cards> searchcard = new ArrayList<>(); // Function that creates the streams to the file protected static void createtxt(File f) { try { fileOut = new FileOutputStream(f); objectOut = new ObjectOutputStream(fileOut); } catch (IOException e) { System.out.println("Write error"); } } //Functio that checks if the username matches a username in the username file //returns true or false protected static boolean checkusername(Account acc) { Object obj = null; try { fileIn = new FileInputStream("Users.dat"); objectIn = new ObjectInputStream(fileIn); do { obj = objectIn.readObject(); if (obj instanceof Account) { if ((((Account) obj).getUsername().equals(acc.getUsername()))) { return false; } } } while (obj != null); objectIn.close(); fileIn.close(); } catch (IOException | ClassNotFoundException ex) { return true; } return true; } //Συνάρτηση που χρησημοποιείται κατά το login ώστε να ελέγξει αν τα στοιχεία που εισάγει ο χρήστης αντιστοιχούν σε κάποιον χρήστη μέσα από το αρχείο χρηστών //επιστρέφει τον user αν υπάρχει αλλιώς επιστρέφει null //Function that is used during the login process , checks the user's credentials if they match with one in the file // returns the user and if there's no match it returns null protected static Account checkaccount(Account user, RSAKeyPairGenerator keyPairGenerator) throws IOException, ClassNotFoundException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException { Object obj; try { fileIn = new FileInputStream("Users.dat"); objectIn = new ObjectInputStream(fileIn); do { obj = objectIn.readObject(); if (obj instanceof Account) { if (((Account) obj).getUsername().equals(user.getUsername())) { user.setSalt(((Account) obj).getSalt()); user = get_SHA_256_SecurePassword(user, keyPairGenerator); if (user.getHashpw().equals(((Account) obj).getHashpw())) { user = (Account) obj; byte[] recovered_message = Functions.decrypt(keyPairGenerator.getPrivateKey(), user.getSymkey()); user.setSymkey(recovered_message); objectIn.close(); fileIn.close(); return user; } } } } while (obj != null); } catch (IOException e) { e.printStackTrace(); } objectIn.close(); fileIn.close(); return null; } //Function that was used to print all the users' info //This allows us to ensure that new users were added to the file protected static void display(RSAKeyPairGenerator keyPairGenerator) { Object obj = null; try { fileIn = new FileInputStream("Users.dat"); objectIn = new ObjectInputStream(fileIn); do { obj = objectIn.readObject(); if (obj instanceof Account) { System.out.println("\n\nDisplay obj: " + obj.toString()); } else { System.out.println("\n\nelse " + obj.toString()); } } while (obj != null); objectIn.close(); fileIn.close(); } catch (FileNotFoundException ex) { //Logger.getLogger(Register.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException | ClassNotFoundException ex) { //Logger.getLogger(Register.class.getName()).log(Level.SEVERE, null, ex); } } //Function that adds a new account to the users' file //Returns true or false depending depending on if the account was added to the file or not protected static boolean writeusers(Account obj) { try { objectOut = new ObjectOutputStream(new FileOutputStream("Users.dat", true)) { protected void writeStreamHeader() throws IOException { reset(); } }; objectOut.writeObject(obj); objectOut.flush(); System.out.println("Object written to file"); return true; } catch (FileNotFoundException ex) { System.out.println("Error with specified file"); ex.printStackTrace(); return false; } catch (IOException ex) { System.out.println("Error with I/O processes"); ex.printStackTrace(); return false; } } // Function that creates a folder for each user that includes their credit card data . protected static void createuserfile(String username) { try { String path = "" + username; fuser = new File(path); boolean bool = fuser.mkdir(); if (bool) { System.out.println("Directory created successfully"); } else { System.out.println("Sorry couldn’t create specified directory"); } fileOutuser = new FileOutputStream(path + "\\" + username + ".dat"); objectOutuser = new ObjectOutputStream(fileOutuser); } catch (IOException e) { System.out.println("Write error"); } } //Function that encrypts the credit card info with AES and it returns the hashed credit card info protected static Cards EncryptCard(Cards card, Account user) throws UnsupportedEncodingException { card.setCardnumber(AES.encrypt(card.getCardnumber(), new String(user.getSymkey(), "UTF8"), user.getSalt())); card.setCardowner(AES.encrypt(card.getCardowner(), new String(user.getSymkey(), "UTF8"), user.getSalt())); card.setExpdate(AES.encrypt(card.getExpdate(), new String(user.getSymkey(), "UTF8"), user.getSalt())); card.setN_verification(AES.encrypt(card.getN_verification(), new String(user.getSymkey(), "UTF8"), user.getSalt())); card.setGroup(AES.encrypt(card.getGroup(), new String(user.getSymkey(), "UTF8"), user.getSalt())); return card; } // Function that decrypts by using AES and returns the encrypted card protected static Cards DecryptCard(Cards card, Account user) throws UnsupportedEncodingException { card.setCardnumber(AES.decrypt(card.getCardnumber(), new String(user.getSymkey(), "UTF8"), user.getSalt())); card.setCardowner(AES.decrypt(card.getCardowner(), new String(user.getSymkey(), "UTF8"), user.getSalt())); card.setExpdate(AES.decrypt(card.getExpdate(), new String(user.getSymkey(), "UTF8"), user.getSalt())); card.setN_verification(AES.decrypt(card.getN_verification(), new String(user.getSymkey(), "UTF8"), user.getSalt())); card.setGroup(AES.decrypt(card.getGroup(), new String(user.getSymkey(), "UTF8"), user.getSalt())); return card; } //Function that writes a card object into the user's file //returns true or false depending on if the card was added or not protected static boolean createcc(Cards card) { try { objectOutuser.writeObject(card); objectOutuser.flush(); System.out.println("Credit Card written to file!"); return true; } catch (IOException e) { e.printStackTrace(); } return false; } //Function that creates a salt and a hash by combining salt and the password and it returns the user with the encrypted hash //Function that creates Salt and a hash by combining salt+password and returns the encrypter hash //Source: //https://howtodoinjava.com/security/how-to-generate-secure-password-hash-md5-sha-pbkdf2-bcrypt-examples/ protected static Account get_SHA_256_SecurePassword(Account user, RSAKeyPairGenerator keyPairGenerator) { byte[] salt; if (user.getSalt() == null) { //generating the salt SecureRandom random = new SecureRandom(); salt = new byte[16]; random.nextBytes(salt); user.setSalt(salt); } else { salt = user.getSalt(); } // hashing the password by using our new salt String generatedPassword = null; try { MessageDigest msgdig = MessageDigest.getInstance("SHA-256"); msgdig.update(salt); byte[] bytes = msgdig.digest(user.getPassword().getBytes()); StringBuilder builder = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { builder.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); } generatedPassword = builder.toString(); } catch (NoSuchAlgorithmException e) { System.out.println("There was an error during the password encryption process! "); e.printStackTrace(); } user.setHashpw(generatedPassword); byte[] secret = execute(generatedPassword, keyPairGenerator); user.setSecret(secret); return user; } //Συνάρτηση που παίρνει την σύνοψη και επιστρέφει την κρυπτογραφημένη με το δημόσιο κλειδί protected static byte[] execute(String m, RSAKeyPairGenerator keyPairGenerator) { try { byte[] message = m.getBytes("UTF8"); byte[] secret = encrypt(keyPairGenerator.getPublicKey(), message); return secret; } catch (Exception e) { e.printStackTrace(); } return null; } //Function that encrypts byte data with a public key // Source used : //https://stackoverflow.com/questions/24338108/java-encrypt-string-with-existing-public-key-file public static byte[] encrypt(PublicKey key, byte[] plaintext) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher.doFinal(plaintext); } // Function that decrypts byte data by using the private key //Source used : //https://stackoverflow.com/questions/24338108/java-encrypt-string-with-existing-public-key-file public static byte[] decrypt(PrivateKey key, byte[] ciphertext) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding"); cipher.init(Cipher.DECRYPT_MODE, key); return cipher.doFinal(ciphertext); } //Function used during the card deletion from the user's file //returns 1 and 0 if the card was or wasnt found protected static int deleteCard(JFrame parentframe, String cardNumber, Account user) throws IOException { Object obj; int found=0; try { String path = "" + user.getUsername(); fileInuser = new FileInputStream(path + "\\" + user.getUsername() + ".dat"); objectInuser = new ObjectInputStream(fileInuser); do { obj = objectInuser.readObject(); if (obj instanceof Cards) { String number = AES.decrypt(((Cards) obj).getCardnumber(), new String(user.getSymkey()), user.getSalt()); if (!number.equals (cardNumber)) { Lists.cards.add(obj); } else{ found=1; } } } while (obj != null); objectInuser.close(); fileInuser.close(); objectOutuser.close(); fileOutuser.close(); } catch (EOFException e){ objectInuser.close(); fileInuser.close(); objectOutuser.close(); fileOutuser.close(); System.out.println("EOFException stin functions delete"); return found; } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } return found; } //Συνάρτηση που χρησημοποιείται για την αναζήτηση καρτών συγκεκριμένου τύπου /*protected static void searchCard(JFrame parentframe, String type, Account user, RSAKeyPairGenerator keyPairGenerator) throws IOException, ClassNotFoundException { Object obj; Cards card; try { String path = "" + user.getUsername(); fileInuser = new FileInputStream(path + "\\" + user.getUsername() + ".dat"); objectInuser = new ObjectInputStream(fileInuser); do { obj = objectInuser.readObject(); if (obj instanceof Cards) { String group = AES.decrypt(((Cards) obj).getGroup(), new String(user.getSymkey()), user.getSalt()); System.out.println(group); if (type.equals(group)) { card = DecryptCard((Cards) obj, user); searchcard.add(card); } } System.out.println(obj==null); } while (obj != null); objectInuser.close(); fileInuser.close(); } catch (FileNotFoundException ex) { } catch (EOFException e){ objectInuser.close(); fileInuser.close(); } }*/ protected static void cardsearch(JFrame parentframe, String type, RSAKeyPairGenerator keyPairGenerator, Account user) throws IOException, ClassNotFoundException { Object obj; Cards card = new Cards(); try { System.out.println("cardsearch"); String path = "" + user.getUsername(); fileInuser = new FileInputStream(path + "\\" + user.getUsername() + ".dat"); objectInuser = new ObjectInputStream(fileInuser); do { obj = objectInuser.readObject(); if (obj instanceof Cards) { String group = AES.decrypt(((Cards) obj).getGroup(), new String(user.getSymkey()), user.getSalt()); if (type.equals(group)) { card = DecryptCard((Cards) obj, user); searchcard.add(card); } } } while (obj != null); } catch (FileNotFoundException ex) { //Logger.getLogger(Register.class.getName()).log(Level.SEVERE, null, ex); }catch (EOFException e){ Frames.searchFrame(parentframe, searchcard); objectInuser.close(); fileInuser.close(); } } // Function that was used to modify a card's info protected static Cards modifySearch(String numbercc, RSAKeyPairGenerator keyPairGenerator, Account user) throws IOException, ClassNotFoundException { Object obj; Cards card = new Cards(); System.out.println(card.toString()); try { System.out.println("modifySearch"); String path = "" + user.getUsername(); fileInuser = new FileInputStream(path + "\\" + user.getUsername() + ".dat"); objectInuser = new ObjectInputStream(fileInuser); do { obj = objectInuser.readObject(); if (obj instanceof Cards) { String number = AES.decrypt(((Cards) obj).getCardnumber(), new String(user.getSymkey()), user.getSalt()); if (numbercc.equals(number)) { card = DecryptCard((Cards) obj, user); }else { Lists.modify.add(obj); } } } while (obj != null); } catch (FileNotFoundException ex) { //Logger.getLogger(Register.class.getName()).log(Level.SEVERE, null, ex); }catch (EOFException e){ objectInuser.close(); fileInuser.close(); objectOutuser.close(); fileOutuser.close(); return card; } card.setCardnumber(""); return card; } // Function that shows cards from the user's file . protected static void displaycards(RSAKeyPairGenerator keyPairGenerator, Account user) throws IOException, ClassNotFoundException { Object obj; Cards card; try { System.out.println("displaycards"); String path = "" + user.getUsername(); fileInuser = new FileInputStream(path + "\\" + user.getUsername() + ".dat"); objectInuser = new ObjectInputStream(fileInuser); do { obj = objectInuser.readObject(); if (obj instanceof Cards) { System.out.println("Display obj: " + obj.toString()); } } while (obj != null); } catch (FileNotFoundException ex) { //Logger.getLogger(Register.class.getName()).log(Level.SEVERE, null, ex); } catch (EOFException e){ objectInuser.close(); fileInuser.close(); } } //Function that is used while checking if a credit card is Συνάρτηση που χρησημοποιείται για τον έλεγχο της ημερομηνίας λήξης μίας κάρτας protected static int dateComp(String date1, String date2) { String[] todaydate = date1.split("/"); String[] datecheck2 = date2.split("/"); if (parseInt(todaydate[1]) != parseInt(datecheck2[1]))//Έλεγχος Χρονιάς { if (parseInt(todaydate[0]) > parseInt(datecheck2[0]))//Η πρώτη ημερομηνία είναι πιό μετά λόγω μήνα { return -1; } else {//Η δεύτερη ημερομηνία είναι πιο μετά λόγω μήνα return 1; } } else {//Αν είναι ίδια η χρόνια if (parseInt(todaydate[0]) <= parseInt(datecheck2[0]))//Αν έχουμε ίδιο μήνα ή είναι πιο μετά ο μήνας της date2 { return 1; } else {//Αν είναι πιο μετά ο μήνας της πρώτης ημερομηνίας τότε δεν μπορεί να προχωρήσει return -1; } } } }
TheofanisB/Encrypted-Credit-Card-Manager
Java Files/Functions.java
4,910
//Συνάρτηση που χρησημοποιείται για την αναζήτηση καρτών συγκεκριμένου τύπου
line_comment
el
import org.w3c.dom.ls.LSOutput; import javax.crypto.*; import javax.swing.*; import java.io.*; import java.nio.file.*; import java.security.*; import java.security.spec.*; import java.util.ArrayList; import java.util.Arrays; import static java.lang.Integer.parseInt; public class Functions { protected static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";// email pattern protected static final String CVV_PATTERN = "([0-9]{3}){1}$";//cvv pattern protected static final String CC_PATTERN = "([0-9]{16}){1}";//credit card number pattern protected static final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,}$";//password pattern protected static FileOutputStream fileOut;// Create a file stream so we can write data to a file protected static ObjectOutputStream objectOut;// Creating an object stream so we can write objects to a file protected static FileInputStream fileIn;// Creating an input stream so we can read from a file protected static ObjectInputStream objectIn;// Creating an input stream so we can read objects from a file protected static FileOutputStream fileOutuser;//Creating a file so we can write in it Δημιουργία ενός αρχείου ώστε να γράψω σε αυτό protected static ObjectOutputStream objectOutuser; protected static FileInputStream fileInuser; protected static ObjectInputStream objectInuser; protected static File fuser; protected static ArrayList<Cards> searchcard = new ArrayList<>(); // Function that creates the streams to the file protected static void createtxt(File f) { try { fileOut = new FileOutputStream(f); objectOut = new ObjectOutputStream(fileOut); } catch (IOException e) { System.out.println("Write error"); } } //Functio that checks if the username matches a username in the username file //returns true or false protected static boolean checkusername(Account acc) { Object obj = null; try { fileIn = new FileInputStream("Users.dat"); objectIn = new ObjectInputStream(fileIn); do { obj = objectIn.readObject(); if (obj instanceof Account) { if ((((Account) obj).getUsername().equals(acc.getUsername()))) { return false; } } } while (obj != null); objectIn.close(); fileIn.close(); } catch (IOException | ClassNotFoundException ex) { return true; } return true; } //Συνάρτηση που χρησημοποιείται κατά το login ώστε να ελέγξει αν τα στοιχεία που εισάγει ο χρήστης αντιστοιχούν σε κάποιον χρήστη μέσα από το αρχείο χρηστών //επιστρέφει τον user αν υπάρχει αλλιώς επιστρέφει null //Function that is used during the login process , checks the user's credentials if they match with one in the file // returns the user and if there's no match it returns null protected static Account checkaccount(Account user, RSAKeyPairGenerator keyPairGenerator) throws IOException, ClassNotFoundException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException { Object obj; try { fileIn = new FileInputStream("Users.dat"); objectIn = new ObjectInputStream(fileIn); do { obj = objectIn.readObject(); if (obj instanceof Account) { if (((Account) obj).getUsername().equals(user.getUsername())) { user.setSalt(((Account) obj).getSalt()); user = get_SHA_256_SecurePassword(user, keyPairGenerator); if (user.getHashpw().equals(((Account) obj).getHashpw())) { user = (Account) obj; byte[] recovered_message = Functions.decrypt(keyPairGenerator.getPrivateKey(), user.getSymkey()); user.setSymkey(recovered_message); objectIn.close(); fileIn.close(); return user; } } } } while (obj != null); } catch (IOException e) { e.printStackTrace(); } objectIn.close(); fileIn.close(); return null; } //Function that was used to print all the users' info //This allows us to ensure that new users were added to the file protected static void display(RSAKeyPairGenerator keyPairGenerator) { Object obj = null; try { fileIn = new FileInputStream("Users.dat"); objectIn = new ObjectInputStream(fileIn); do { obj = objectIn.readObject(); if (obj instanceof Account) { System.out.println("\n\nDisplay obj: " + obj.toString()); } else { System.out.println("\n\nelse " + obj.toString()); } } while (obj != null); objectIn.close(); fileIn.close(); } catch (FileNotFoundException ex) { //Logger.getLogger(Register.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException | ClassNotFoundException ex) { //Logger.getLogger(Register.class.getName()).log(Level.SEVERE, null, ex); } } //Function that adds a new account to the users' file //Returns true or false depending depending on if the account was added to the file or not protected static boolean writeusers(Account obj) { try { objectOut = new ObjectOutputStream(new FileOutputStream("Users.dat", true)) { protected void writeStreamHeader() throws IOException { reset(); } }; objectOut.writeObject(obj); objectOut.flush(); System.out.println("Object written to file"); return true; } catch (FileNotFoundException ex) { System.out.println("Error with specified file"); ex.printStackTrace(); return false; } catch (IOException ex) { System.out.println("Error with I/O processes"); ex.printStackTrace(); return false; } } // Function that creates a folder for each user that includes their credit card data . protected static void createuserfile(String username) { try { String path = "" + username; fuser = new File(path); boolean bool = fuser.mkdir(); if (bool) { System.out.println("Directory created successfully"); } else { System.out.println("Sorry couldn’t create specified directory"); } fileOutuser = new FileOutputStream(path + "\\" + username + ".dat"); objectOutuser = new ObjectOutputStream(fileOutuser); } catch (IOException e) { System.out.println("Write error"); } } //Function that encrypts the credit card info with AES and it returns the hashed credit card info protected static Cards EncryptCard(Cards card, Account user) throws UnsupportedEncodingException { card.setCardnumber(AES.encrypt(card.getCardnumber(), new String(user.getSymkey(), "UTF8"), user.getSalt())); card.setCardowner(AES.encrypt(card.getCardowner(), new String(user.getSymkey(), "UTF8"), user.getSalt())); card.setExpdate(AES.encrypt(card.getExpdate(), new String(user.getSymkey(), "UTF8"), user.getSalt())); card.setN_verification(AES.encrypt(card.getN_verification(), new String(user.getSymkey(), "UTF8"), user.getSalt())); card.setGroup(AES.encrypt(card.getGroup(), new String(user.getSymkey(), "UTF8"), user.getSalt())); return card; } // Function that decrypts by using AES and returns the encrypted card protected static Cards DecryptCard(Cards card, Account user) throws UnsupportedEncodingException { card.setCardnumber(AES.decrypt(card.getCardnumber(), new String(user.getSymkey(), "UTF8"), user.getSalt())); card.setCardowner(AES.decrypt(card.getCardowner(), new String(user.getSymkey(), "UTF8"), user.getSalt())); card.setExpdate(AES.decrypt(card.getExpdate(), new String(user.getSymkey(), "UTF8"), user.getSalt())); card.setN_verification(AES.decrypt(card.getN_verification(), new String(user.getSymkey(), "UTF8"), user.getSalt())); card.setGroup(AES.decrypt(card.getGroup(), new String(user.getSymkey(), "UTF8"), user.getSalt())); return card; } //Function that writes a card object into the user's file //returns true or false depending on if the card was added or not protected static boolean createcc(Cards card) { try { objectOutuser.writeObject(card); objectOutuser.flush(); System.out.println("Credit Card written to file!"); return true; } catch (IOException e) { e.printStackTrace(); } return false; } //Function that creates a salt and a hash by combining salt and the password and it returns the user with the encrypted hash //Function that creates Salt and a hash by combining salt+password and returns the encrypter hash //Source: //https://howtodoinjava.com/security/how-to-generate-secure-password-hash-md5-sha-pbkdf2-bcrypt-examples/ protected static Account get_SHA_256_SecurePassword(Account user, RSAKeyPairGenerator keyPairGenerator) { byte[] salt; if (user.getSalt() == null) { //generating the salt SecureRandom random = new SecureRandom(); salt = new byte[16]; random.nextBytes(salt); user.setSalt(salt); } else { salt = user.getSalt(); } // hashing the password by using our new salt String generatedPassword = null; try { MessageDigest msgdig = MessageDigest.getInstance("SHA-256"); msgdig.update(salt); byte[] bytes = msgdig.digest(user.getPassword().getBytes()); StringBuilder builder = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { builder.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); } generatedPassword = builder.toString(); } catch (NoSuchAlgorithmException e) { System.out.println("There was an error during the password encryption process! "); e.printStackTrace(); } user.setHashpw(generatedPassword); byte[] secret = execute(generatedPassword, keyPairGenerator); user.setSecret(secret); return user; } //Συνάρτηση που παίρνει την σύνοψη και επιστρέφει την κρυπτογραφημένη με το δημόσιο κλειδί protected static byte[] execute(String m, RSAKeyPairGenerator keyPairGenerator) { try { byte[] message = m.getBytes("UTF8"); byte[] secret = encrypt(keyPairGenerator.getPublicKey(), message); return secret; } catch (Exception e) { e.printStackTrace(); } return null; } //Function that encrypts byte data with a public key // Source used : //https://stackoverflow.com/questions/24338108/java-encrypt-string-with-existing-public-key-file public static byte[] encrypt(PublicKey key, byte[] plaintext) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher.doFinal(plaintext); } // Function that decrypts byte data by using the private key //Source used : //https://stackoverflow.com/questions/24338108/java-encrypt-string-with-existing-public-key-file public static byte[] decrypt(PrivateKey key, byte[] ciphertext) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding"); cipher.init(Cipher.DECRYPT_MODE, key); return cipher.doFinal(ciphertext); } //Function used during the card deletion from the user's file //returns 1 and 0 if the card was or wasnt found protected static int deleteCard(JFrame parentframe, String cardNumber, Account user) throws IOException { Object obj; int found=0; try { String path = "" + user.getUsername(); fileInuser = new FileInputStream(path + "\\" + user.getUsername() + ".dat"); objectInuser = new ObjectInputStream(fileInuser); do { obj = objectInuser.readObject(); if (obj instanceof Cards) { String number = AES.decrypt(((Cards) obj).getCardnumber(), new String(user.getSymkey()), user.getSalt()); if (!number.equals (cardNumber)) { Lists.cards.add(obj); } else{ found=1; } } } while (obj != null); objectInuser.close(); fileInuser.close(); objectOutuser.close(); fileOutuser.close(); } catch (EOFException e){ objectInuser.close(); fileInuser.close(); objectOutuser.close(); fileOutuser.close(); System.out.println("EOFException stin functions delete"); return found; } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } return found; } //Συνάρτηση που<SUF> /*protected static void searchCard(JFrame parentframe, String type, Account user, RSAKeyPairGenerator keyPairGenerator) throws IOException, ClassNotFoundException { Object obj; Cards card; try { String path = "" + user.getUsername(); fileInuser = new FileInputStream(path + "\\" + user.getUsername() + ".dat"); objectInuser = new ObjectInputStream(fileInuser); do { obj = objectInuser.readObject(); if (obj instanceof Cards) { String group = AES.decrypt(((Cards) obj).getGroup(), new String(user.getSymkey()), user.getSalt()); System.out.println(group); if (type.equals(group)) { card = DecryptCard((Cards) obj, user); searchcard.add(card); } } System.out.println(obj==null); } while (obj != null); objectInuser.close(); fileInuser.close(); } catch (FileNotFoundException ex) { } catch (EOFException e){ objectInuser.close(); fileInuser.close(); } }*/ protected static void cardsearch(JFrame parentframe, String type, RSAKeyPairGenerator keyPairGenerator, Account user) throws IOException, ClassNotFoundException { Object obj; Cards card = new Cards(); try { System.out.println("cardsearch"); String path = "" + user.getUsername(); fileInuser = new FileInputStream(path + "\\" + user.getUsername() + ".dat"); objectInuser = new ObjectInputStream(fileInuser); do { obj = objectInuser.readObject(); if (obj instanceof Cards) { String group = AES.decrypt(((Cards) obj).getGroup(), new String(user.getSymkey()), user.getSalt()); if (type.equals(group)) { card = DecryptCard((Cards) obj, user); searchcard.add(card); } } } while (obj != null); } catch (FileNotFoundException ex) { //Logger.getLogger(Register.class.getName()).log(Level.SEVERE, null, ex); }catch (EOFException e){ Frames.searchFrame(parentframe, searchcard); objectInuser.close(); fileInuser.close(); } } // Function that was used to modify a card's info protected static Cards modifySearch(String numbercc, RSAKeyPairGenerator keyPairGenerator, Account user) throws IOException, ClassNotFoundException { Object obj; Cards card = new Cards(); System.out.println(card.toString()); try { System.out.println("modifySearch"); String path = "" + user.getUsername(); fileInuser = new FileInputStream(path + "\\" + user.getUsername() + ".dat"); objectInuser = new ObjectInputStream(fileInuser); do { obj = objectInuser.readObject(); if (obj instanceof Cards) { String number = AES.decrypt(((Cards) obj).getCardnumber(), new String(user.getSymkey()), user.getSalt()); if (numbercc.equals(number)) { card = DecryptCard((Cards) obj, user); }else { Lists.modify.add(obj); } } } while (obj != null); } catch (FileNotFoundException ex) { //Logger.getLogger(Register.class.getName()).log(Level.SEVERE, null, ex); }catch (EOFException e){ objectInuser.close(); fileInuser.close(); objectOutuser.close(); fileOutuser.close(); return card; } card.setCardnumber(""); return card; } // Function that shows cards from the user's file . protected static void displaycards(RSAKeyPairGenerator keyPairGenerator, Account user) throws IOException, ClassNotFoundException { Object obj; Cards card; try { System.out.println("displaycards"); String path = "" + user.getUsername(); fileInuser = new FileInputStream(path + "\\" + user.getUsername() + ".dat"); objectInuser = new ObjectInputStream(fileInuser); do { obj = objectInuser.readObject(); if (obj instanceof Cards) { System.out.println("Display obj: " + obj.toString()); } } while (obj != null); } catch (FileNotFoundException ex) { //Logger.getLogger(Register.class.getName()).log(Level.SEVERE, null, ex); } catch (EOFException e){ objectInuser.close(); fileInuser.close(); } } //Function that is used while checking if a credit card is Συνάρτηση που χρησημοποιείται για τον έλεγχο της ημερομηνίας λήξης μίας κάρτας protected static int dateComp(String date1, String date2) { String[] todaydate = date1.split("/"); String[] datecheck2 = date2.split("/"); if (parseInt(todaydate[1]) != parseInt(datecheck2[1]))//Έλεγχος Χρονιάς { if (parseInt(todaydate[0]) > parseInt(datecheck2[0]))//Η πρώτη ημερομηνία είναι πιό μετά λόγω μήνα { return -1; } else {//Η δεύτερη ημερομηνία είναι πιο μετά λόγω μήνα return 1; } } else {//Αν είναι ίδια η χρόνια if (parseInt(todaydate[0]) <= parseInt(datecheck2[0]))//Αν έχουμε ίδιο μήνα ή είναι πιο μετά ο μήνας της date2 { return 1; } else {//Αν είναι πιο μετά ο μήνας της πρώτης ημερομηνίας τότε δεν μπορεί να προχωρήσει return -1; } } } }
34002_0
import uis.menus.MainMenu; import utils.Constants; import utils.database.Connection; import utils.database.Schema; import javax.swing.*; import java.sql.SQLException; public class App { public static void main(String[] args) { try { Connection.getInstance().connect(); Schema.getInstance().migrate(); MainMenu.getInstance().render(); } catch (SQLException e) { System.out.println(e.getMessage()); } // System.out.println("Hello World!"); // JFrame jFrame = new JFrame("Αυτοδιαχειριζόμενο γυμναστήριο"); // jFrame.setBounds(0, 0, getSystemResolutionWidth(), getSystemResolutionHeight()); // jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // jFrame.setVisible(true); // // JLabel jLabel = new JLabel("Hello World!"); // jLabel.setHorizontalAlignment(SwingConstants.LEFT); // jLabel.setVerticalAlignment(SwingConstants.TOP); // Font font = new Font("Verdana", Font.BOLD, 20); // jLabel.setFont(font); // jFrame.add(jLabel); // // GridLayout grid = new GridLayout(3,1); // jFrame.setLayout(grid); // // JButton jButton1 = new JButton("Press me!"); // JButton jButton2 = new JButton("Press me!"); // jFrame.add(jButton1); // jFrame.add(jButton2); } // private static int getSystemResolutionWidth() { // return (int) SystemValues.getInstance().getScreenSizeWidth(); // } // // private static int getSystemResolutionHeight() { // return (int) SystemValues.getInstance().getScreenSizeHeight(); // } }
Thodoras/selforggym
src/main/java/App.java
450
// JFrame jFrame = new JFrame("Αυτοδιαχειριζόμενο γυμναστήριο");
line_comment
el
import uis.menus.MainMenu; import utils.Constants; import utils.database.Connection; import utils.database.Schema; import javax.swing.*; import java.sql.SQLException; public class App { public static void main(String[] args) { try { Connection.getInstance().connect(); Schema.getInstance().migrate(); MainMenu.getInstance().render(); } catch (SQLException e) { System.out.println(e.getMessage()); } // System.out.println("Hello World!"); // JFrame jFrame<SUF> // jFrame.setBounds(0, 0, getSystemResolutionWidth(), getSystemResolutionHeight()); // jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // jFrame.setVisible(true); // // JLabel jLabel = new JLabel("Hello World!"); // jLabel.setHorizontalAlignment(SwingConstants.LEFT); // jLabel.setVerticalAlignment(SwingConstants.TOP); // Font font = new Font("Verdana", Font.BOLD, 20); // jLabel.setFont(font); // jFrame.add(jLabel); // // GridLayout grid = new GridLayout(3,1); // jFrame.setLayout(grid); // // JButton jButton1 = new JButton("Press me!"); // JButton jButton2 = new JButton("Press me!"); // jFrame.add(jButton1); // jFrame.add(jButton2); } // private static int getSystemResolutionWidth() { // return (int) SystemValues.getInstance().getScreenSizeWidth(); // } // // private static int getSystemResolutionHeight() { // return (int) SystemValues.getInstance().getScreenSizeHeight(); // } }
796_3
package api; import java.io.Serializable; import java.util.ArrayList; public class Register implements Serializable { private User newUser; private String repeat_password; private ArrayList<Error> errors = new ArrayList<>(); public Register(User newUser, String repeat_password) { this.newUser = newUser; this.repeat_password = repeat_password; } /** * This method checks if the password and repeated password have the same value. * @return */ private boolean validatePassword() { if (newUser.getPassword().equals(repeat_password)) { return true; } //throw new WrongInputException("Ο κωδικός δεν ταυτίζεται!"); errors.add(new Error(0, "Ο κωδικός δεν ταυτίζεται!")); return false; } private boolean emptyInput() { // θα δούμε if (newUser.emptyField() || repeat_password.equals("")) { // θέλει έλεγχο με την κενή συμβολοσειρά και όχι με null //throw new EmptyInputException("Κάποιο από τα υποχρεωτικά πεδίο είναι κενό"); errors.add(new Error(1, "Κάποιο από τα υποχρεωτικά πεδίο είναι κενό")); return true; } return false; } /** * This method makes all validations and returns true or false if the user can register and access the dashboard or not. */ public User addUser() { if (!emptyInput() && validatePassword()) { if (Database.insert(newUser)) { return newUser; } else { //throw new AlreadyExistsException("Το όνομα χρήστη χρησιμοποιείται ήδη!"); errors.add(new Error(2, "Το όνομα χρήστη χρησιμοποιείται ήδη!")); } } return null; } /** * This method is used to return all errors after user tries to register in the system with the appropriate message. */ public ArrayList<Error> getErrors() { return errors; } }
ThodorisAnninos/appartments-management-system-java
src/api/Register.java
615
//throw new EmptyInputException("Κάποιο από τα υποχρεωτικά πεδίο είναι κενό");
line_comment
el
package api; import java.io.Serializable; import java.util.ArrayList; public class Register implements Serializable { private User newUser; private String repeat_password; private ArrayList<Error> errors = new ArrayList<>(); public Register(User newUser, String repeat_password) { this.newUser = newUser; this.repeat_password = repeat_password; } /** * This method checks if the password and repeated password have the same value. * @return */ private boolean validatePassword() { if (newUser.getPassword().equals(repeat_password)) { return true; } //throw new WrongInputException("Ο κωδικός δεν ταυτίζεται!"); errors.add(new Error(0, "Ο κωδικός δεν ταυτίζεται!")); return false; } private boolean emptyInput() { // θα δούμε if (newUser.emptyField() || repeat_password.equals("")) { // θέλει έλεγχο με την κενή συμβολοσειρά και όχι με null //throw new<SUF> errors.add(new Error(1, "Κάποιο από τα υποχρεωτικά πεδίο είναι κενό")); return true; } return false; } /** * This method makes all validations and returns true or false if the user can register and access the dashboard or not. */ public User addUser() { if (!emptyInput() && validatePassword()) { if (Database.insert(newUser)) { return newUser; } else { //throw new AlreadyExistsException("Το όνομα χρήστη χρησιμοποιείται ήδη!"); errors.add(new Error(2, "Το όνομα χρήστη χρησιμοποιείται ήδη!")); } } return null; } /** * This method is used to return all errors after user tries to register in the system with the appropriate message. */ public ArrayList<Error> getErrors() { return errors; } }
13182_5
package sample; import javafx.scene.image.Image; /** * <h1>Η κλάση Card</h1> */ public class Card { private Image value; private Image background; private int id; /** * Ο κατασκευαστής της κλάσης,στον οποίο δίνονται οι αρχικές τιμές των μεταβλητών. * @param value {@code Image} * @param background {@code Image} * @param id {@code int} */ public Card(Image value, Image background, int id){ this.value = value; this.background = background; this.id = id; } /** * Επιστρέφει την τιμή της κάρτας. * @return value */ public Image getValue() { return value; } /** * Επιστρέφει το φόντο της κάρτας. * @return background */ public Image getBackground() { return background; } /** * Επιστρέφει τον αριθμό της κάρτας. * @return id */ public int getId() { return id; } /** * Θέτει τον αριθμό της καρτας. * @param id {@code int} */ public void setId(int id) { this.id = id; } }
TommysG/memory-card-game
src/main/java/sample/Card.java
417
/** * Θέτει τον αριθμό της καρτας. * @param id {@code int} */
block_comment
el
package sample; import javafx.scene.image.Image; /** * <h1>Η κλάση Card</h1> */ public class Card { private Image value; private Image background; private int id; /** * Ο κατασκευαστής της κλάσης,στον οποίο δίνονται οι αρχικές τιμές των μεταβλητών. * @param value {@code Image} * @param background {@code Image} * @param id {@code int} */ public Card(Image value, Image background, int id){ this.value = value; this.background = background; this.id = id; } /** * Επιστρέφει την τιμή της κάρτας. * @return value */ public Image getValue() { return value; } /** * Επιστρέφει το φόντο της κάρτας. * @return background */ public Image getBackground() { return background; } /** * Επιστρέφει τον αριθμό της κάρτας. * @return id */ public int getId() { return id; } /** * Θέτει τον αριθμό<SUF>*/ public void setId(int id) { this.id = id; } }
126_4
package CarOps; import java.util.ArrayList; public class MainWithoutScreens { public static void main(String[] args) { //Δημιουργία Γραμματείας και Μηχανικών Secretary secretary=new Secretary("user1","pass1","Maria","Βλαχοδήμου"); SimpleEngineer Engineer1=new SimpleEngineer("user2","pass2","Κώστας","Ευγενίδης"); SimpleEngineer Engineer2=new SimpleEngineer("user3","pass3","Κώστας","Γαζής"); SimpleEngineer Engineer3=new SimpleEngineer("user4","pass4","Γιώργος","Δημητριάδης"); HostEngineer HostEngineer1=new HostEngineer("user5","pass5","Αναστάσιος","Γεωργίου"); SupervisorEngineer SupervisorEngineer1=new SupervisorEngineer("user6","pass6","Δημήτρης","Παπαντωνίου"); //Δημιουργία Καρτέλα Οχήματος και Πελάτη απο την Γραμματεία Client client=secretary.CreateNewClient("Μάρκος", "Θεοδοσιάδης", "6900000000", null, null); Car newCar=secretary.CreateNewCar("ΚΖΝ-1234","BMW","i4 M50", 2021); //Δημιουργία Ραντεβού Session Session1=secretary.CreateSession(client.getFirstName()+" "+client.getLastName(), newCar.getPlate(), "28-6-2023",client); Session Session2=secretary.CreateSession(client.getFirstName()+" "+client.getLastName(), newCar.getPlate(), "30-6-2023",client); //Δημιουργία Ανταλλακτικών και Εργασιών Επισκευής Task Task1=new Task("Αλλαγή λαδιών",20); Task Task2=new Task("Αλλαγή φίλτρου καμπίνας",5); Task Task3=new Task("Συντήρηση φρένων",30); SparePart SparePart1=new SparePart("Συσκευασία λαδιών 4lt",30); SparePart SparePart2=new SparePart("Φίλτρο λαδιού",20); SparePart SparePart3=new SparePart("Φίλτρο καμπίνας ",30); SparePart SparePart4=new SparePart("Τακάκιρ φρένων εμπρός τροχού ",5); SparePart SparePart5=new SparePart("Τακάκι φρένων πίσω τροχού",5); SparePart SparePart6=new SparePart("Υγρό φρένων",10); //Δημιουργία Λίστας εργασιών για τους φακέλους επισκευής(1ο και 2ο Task για τον πρώτο φάκελο και 3o Task για τον δεύτερο Φάκελο Επισκευής) ArrayList<Task> RepairFolder1Tasks=new ArrayList<Task>(); RepairFolder1Tasks.add(Task1); RepairFolder1Tasks.add(Task2); ArrayList<Task> RepairFolder2Tasks=new ArrayList<Task>(); RepairFolder2Tasks.add(Task3); //Δημιουργία Φακέλου Επισκευής για το Παραπάνω Ραντεβού απο τον Μηχανικό Υποδοχής(Ο χρόνος μετράται σε ώρες πχ 24 και 48 ώρες) RepairFolder RepairFolder1=HostEngineer1.CreateNewRepairFolder(Session1,24, 0, RepairFolder1Tasks); RepairFolder RepairFolder2=HostEngineer1.CreateNewRepairFolder(Session2,48, 0, RepairFolder2Tasks); //Έγκριση Φακέλου απο την Γραμματεία και μετατροπή των φακέλων επισκευής σε ενεργές επισκευές(έτοιμη για διαχείριση απο τον Επιβλέπων Μηχανικό) Repair Repair1=secretary.ApproveRepairFolder(RepairFolder1); Repair Repair2=secretary.ApproveRepairFolder(RepairFolder2); //for(RepairTask task : Repair1.getListOfRepairTasks()) { //System.out.println("Ergasia :"+task.getaTask().getName()); // } //Διαχείριση των ενεργών Επισκευών απο τον Επιβλέπων Μηχανικό SupervisorEngineer1 SupervisorEngineer1.ClaimRepair(Repair1); SupervisorEngineer1.ClaimRepair(Repair2); //Ανάθεση Εργασιών της 1ης Επισκευής στους 2 Μηχανικούς από τον Επιβλέπων Μηχανικό TaskAssignment Assignment1=SupervisorEngineer1.AssignRepairTask(Engineer1,Repair1.getListOfRepairTasks().get(0), Repair1); TaskAssignment Assignment2=SupervisorEngineer1.AssignRepairTask(Engineer2,Repair1.getListOfRepairTasks().get(1), Repair1); //Δημιουργία Λίστας Ανταλλακτικών που χρησιμοποίησαν οι Μηχανικοί σε κάθε Ανάθεση της 1ης Επισκευής //Επειδή το πλήθος των ανταλλακτικών όλης της επισκευής πρέπει να είναι 1 απο τα 3 πρώτα Ανταλλακτικά έγινε έτσι ο διαχωρισμός σε κάθε ανάθεση ώστε //και οι 2 αναθέσεις στο σύνολο τους να χρησιμοποιούν ένα τεμάχιο για κάθε ένα από τα 3 πρώτα Ανταλλακτικά(1+0=1 , 0+1=1 ,1+0=1 γιά όλη την επισκευή ) ArrayList<AssignmentSparePart> Assignment1Parts=new ArrayList<AssignmentSparePart>(); Assignment1Parts.add(new AssignmentSparePart(Assignment1,SparePart1,1)); Assignment1Parts.add(new AssignmentSparePart(Assignment1,SparePart2,0)); Assignment1Parts.add(new AssignmentSparePart(Assignment1,SparePart3,1)); ArrayList<AssignmentSparePart> Assignment2Parts=new ArrayList<AssignmentSparePart>(); Assignment2Parts.add(new AssignmentSparePart(Assignment1,SparePart1,0)); Assignment2Parts.add(new AssignmentSparePart(Assignment1,SparePart2,1)); Assignment2Parts.add(new AssignmentSparePart(Assignment1,SparePart3,0)); //Ολοκλήρωση Αναθέσεων της 1ης Επισευής απο τους Μηχανικούς και καταγραφή των Ανταλλκατικών που χρησιμοποιήσαν Engineer1.FinishAssignment(Assignment1,Assignment1Parts); Engineer2.FinishAssignment(Assignment2,Assignment2Parts); //Ανάθεση Εργασιών της 2ης Επισκευής στον 3ο Μηχανικό TaskAssignment Assignment3=SupervisorEngineer1.AssignRepairTask(Engineer3,Repair2.getListOfRepairTasks().get(0), Repair2); //Δημιουργία Λίστας Ανταλλακτικών που χρησιμοποίησαν οι Μηχανικοί σε κάθε Ανάθεση της 2ης Επισκευής ArrayList<AssignmentSparePart> Assignment3Parts=new ArrayList<AssignmentSparePart>(); Assignment3Parts.add(new AssignmentSparePart(Assignment3,SparePart4,4)); Assignment3Parts.add(new AssignmentSparePart(Assignment3,SparePart5,4)); Assignment3Parts.add(new AssignmentSparePart(Assignment3,SparePart6,1)); //Ολοκλήρωση Ανάθεσης της 2ης Επισευής απο τον Μηχανικό και καταγραφή των Ανταλλκατικών που χρησιμοποιήσαν Engineer2.FinishAssignment(Assignment3,Assignment3Parts); //Προβολή Ζητούμενων πληροφοριών στην κονσόλα System.out.println("--- Εργασίες Επισκευής --- "); System.out.println(Task1.getName() + ": " + Task1.getCost() + "€"); System.out.println(Task2.getName() + ": " + Task2.getCost() + "€"); System.out.println(Task3.getName() + ": " + Task3.getCost() + "€" +"\n"); System.out.println("--- Ανταλλακτικά --- "); System.out.println(SparePart1.getName() + " : "+ SparePart1.getCostPerPiece() + "€"); System.out.println(SparePart2.getName() + " : "+ SparePart2.getCostPerPiece() + "€"); System.out.println(SparePart3.getName() + " : "+ SparePart3.getCostPerPiece() + "€"); System.out.println(SparePart4.getName() + " : "+ SparePart4.getCostPerPiece() + "€"); System.out.println(SparePart5.getName() + " : "+ SparePart5.getCostPerPiece() + "€"); System.out.println(SparePart6.getName() + " : "+ SparePart6.getCostPerPiece() + "€" + "\n"); System.out.println("--- Στοιχεία Επισκευών ---"); System.out.println("Εκτιμώμενος Χρόνος Επισκευής 1ης Επισκευής: " + Repair1.getaRepairFolder().getEstTime() + " ώρες ,Συνολικό Κόστος: " + Repair1.getTotalCost() + "€"); System.out.println("Εκτιμώμενος Χρόνος Επισκευής 2ης Επισκευής: " + Repair2.getaRepairFolder().getEstTime() + " ώρες ,Συνολικό Κόστος: " + Repair2.getTotalCost() + "€"); } }
TonyGnk/carops-information-system
code/src/CarOps/MainWithoutScreens.java
3,484
//Δημιουργία Φακέλου Επισκευής για το Παραπάνω Ραντεβού απο τον Μηχανικό Υποδοχής(Ο χρόνος μετράται σε ώρες πχ 24 και 48 ώρες)
line_comment
el
package CarOps; import java.util.ArrayList; public class MainWithoutScreens { public static void main(String[] args) { //Δημιουργία Γραμματείας και Μηχανικών Secretary secretary=new Secretary("user1","pass1","Maria","Βλαχοδήμου"); SimpleEngineer Engineer1=new SimpleEngineer("user2","pass2","Κώστας","Ευγενίδης"); SimpleEngineer Engineer2=new SimpleEngineer("user3","pass3","Κώστας","Γαζής"); SimpleEngineer Engineer3=new SimpleEngineer("user4","pass4","Γιώργος","Δημητριάδης"); HostEngineer HostEngineer1=new HostEngineer("user5","pass5","Αναστάσιος","Γεωργίου"); SupervisorEngineer SupervisorEngineer1=new SupervisorEngineer("user6","pass6","Δημήτρης","Παπαντωνίου"); //Δημιουργία Καρτέλα Οχήματος και Πελάτη απο την Γραμματεία Client client=secretary.CreateNewClient("Μάρκος", "Θεοδοσιάδης", "6900000000", null, null); Car newCar=secretary.CreateNewCar("ΚΖΝ-1234","BMW","i4 M50", 2021); //Δημιουργία Ραντεβού Session Session1=secretary.CreateSession(client.getFirstName()+" "+client.getLastName(), newCar.getPlate(), "28-6-2023",client); Session Session2=secretary.CreateSession(client.getFirstName()+" "+client.getLastName(), newCar.getPlate(), "30-6-2023",client); //Δημιουργία Ανταλλακτικών και Εργασιών Επισκευής Task Task1=new Task("Αλλαγή λαδιών",20); Task Task2=new Task("Αλλαγή φίλτρου καμπίνας",5); Task Task3=new Task("Συντήρηση φρένων",30); SparePart SparePart1=new SparePart("Συσκευασία λαδιών 4lt",30); SparePart SparePart2=new SparePart("Φίλτρο λαδιού",20); SparePart SparePart3=new SparePart("Φίλτρο καμπίνας ",30); SparePart SparePart4=new SparePart("Τακάκιρ φρένων εμπρός τροχού ",5); SparePart SparePart5=new SparePart("Τακάκι φρένων πίσω τροχού",5); SparePart SparePart6=new SparePart("Υγρό φρένων",10); //Δημιουργία Λίστας εργασιών για τους φακέλους επισκευής(1ο και 2ο Task για τον πρώτο φάκελο και 3o Task για τον δεύτερο Φάκελο Επισκευής) ArrayList<Task> RepairFolder1Tasks=new ArrayList<Task>(); RepairFolder1Tasks.add(Task1); RepairFolder1Tasks.add(Task2); ArrayList<Task> RepairFolder2Tasks=new ArrayList<Task>(); RepairFolder2Tasks.add(Task3); //Δημιουργία Φακέλου<SUF> RepairFolder RepairFolder1=HostEngineer1.CreateNewRepairFolder(Session1,24, 0, RepairFolder1Tasks); RepairFolder RepairFolder2=HostEngineer1.CreateNewRepairFolder(Session2,48, 0, RepairFolder2Tasks); //Έγκριση Φακέλου απο την Γραμματεία και μετατροπή των φακέλων επισκευής σε ενεργές επισκευές(έτοιμη για διαχείριση απο τον Επιβλέπων Μηχανικό) Repair Repair1=secretary.ApproveRepairFolder(RepairFolder1); Repair Repair2=secretary.ApproveRepairFolder(RepairFolder2); //for(RepairTask task : Repair1.getListOfRepairTasks()) { //System.out.println("Ergasia :"+task.getaTask().getName()); // } //Διαχείριση των ενεργών Επισκευών απο τον Επιβλέπων Μηχανικό SupervisorEngineer1 SupervisorEngineer1.ClaimRepair(Repair1); SupervisorEngineer1.ClaimRepair(Repair2); //Ανάθεση Εργασιών της 1ης Επισκευής στους 2 Μηχανικούς από τον Επιβλέπων Μηχανικό TaskAssignment Assignment1=SupervisorEngineer1.AssignRepairTask(Engineer1,Repair1.getListOfRepairTasks().get(0), Repair1); TaskAssignment Assignment2=SupervisorEngineer1.AssignRepairTask(Engineer2,Repair1.getListOfRepairTasks().get(1), Repair1); //Δημιουργία Λίστας Ανταλλακτικών που χρησιμοποίησαν οι Μηχανικοί σε κάθε Ανάθεση της 1ης Επισκευής //Επειδή το πλήθος των ανταλλακτικών όλης της επισκευής πρέπει να είναι 1 απο τα 3 πρώτα Ανταλλακτικά έγινε έτσι ο διαχωρισμός σε κάθε ανάθεση ώστε //και οι 2 αναθέσεις στο σύνολο τους να χρησιμοποιούν ένα τεμάχιο για κάθε ένα από τα 3 πρώτα Ανταλλακτικά(1+0=1 , 0+1=1 ,1+0=1 γιά όλη την επισκευή ) ArrayList<AssignmentSparePart> Assignment1Parts=new ArrayList<AssignmentSparePart>(); Assignment1Parts.add(new AssignmentSparePart(Assignment1,SparePart1,1)); Assignment1Parts.add(new AssignmentSparePart(Assignment1,SparePart2,0)); Assignment1Parts.add(new AssignmentSparePart(Assignment1,SparePart3,1)); ArrayList<AssignmentSparePart> Assignment2Parts=new ArrayList<AssignmentSparePart>(); Assignment2Parts.add(new AssignmentSparePart(Assignment1,SparePart1,0)); Assignment2Parts.add(new AssignmentSparePart(Assignment1,SparePart2,1)); Assignment2Parts.add(new AssignmentSparePart(Assignment1,SparePart3,0)); //Ολοκλήρωση Αναθέσεων της 1ης Επισευής απο τους Μηχανικούς και καταγραφή των Ανταλλκατικών που χρησιμοποιήσαν Engineer1.FinishAssignment(Assignment1,Assignment1Parts); Engineer2.FinishAssignment(Assignment2,Assignment2Parts); //Ανάθεση Εργασιών της 2ης Επισκευής στον 3ο Μηχανικό TaskAssignment Assignment3=SupervisorEngineer1.AssignRepairTask(Engineer3,Repair2.getListOfRepairTasks().get(0), Repair2); //Δημιουργία Λίστας Ανταλλακτικών που χρησιμοποίησαν οι Μηχανικοί σε κάθε Ανάθεση της 2ης Επισκευής ArrayList<AssignmentSparePart> Assignment3Parts=new ArrayList<AssignmentSparePart>(); Assignment3Parts.add(new AssignmentSparePart(Assignment3,SparePart4,4)); Assignment3Parts.add(new AssignmentSparePart(Assignment3,SparePart5,4)); Assignment3Parts.add(new AssignmentSparePart(Assignment3,SparePart6,1)); //Ολοκλήρωση Ανάθεσης της 2ης Επισευής απο τον Μηχανικό και καταγραφή των Ανταλλκατικών που χρησιμοποιήσαν Engineer2.FinishAssignment(Assignment3,Assignment3Parts); //Προβολή Ζητούμενων πληροφοριών στην κονσόλα System.out.println("--- Εργασίες Επισκευής --- "); System.out.println(Task1.getName() + ": " + Task1.getCost() + "€"); System.out.println(Task2.getName() + ": " + Task2.getCost() + "€"); System.out.println(Task3.getName() + ": " + Task3.getCost() + "€" +"\n"); System.out.println("--- Ανταλλακτικά --- "); System.out.println(SparePart1.getName() + " : "+ SparePart1.getCostPerPiece() + "€"); System.out.println(SparePart2.getName() + " : "+ SparePart2.getCostPerPiece() + "€"); System.out.println(SparePart3.getName() + " : "+ SparePart3.getCostPerPiece() + "€"); System.out.println(SparePart4.getName() + " : "+ SparePart4.getCostPerPiece() + "€"); System.out.println(SparePart5.getName() + " : "+ SparePart5.getCostPerPiece() + "€"); System.out.println(SparePart6.getName() + " : "+ SparePart6.getCostPerPiece() + "€" + "\n"); System.out.println("--- Στοιχεία Επισκευών ---"); System.out.println("Εκτιμώμενος Χρόνος Επισκευής 1ης Επισκευής: " + Repair1.getaRepairFolder().getEstTime() + " ώρες ,Συνολικό Κόστος: " + Repair1.getTotalCost() + "€"); System.out.println("Εκτιμώμενος Χρόνος Επισκευής 2ης Επισκευής: " + Repair2.getaRepairFolder().getEstTime() + " ώρες ,Συνολικό Κόστος: " + Repair2.getTotalCost() + "€"); } }
6132_1
package gr.edu.serres.TrancCoder_TheElucitated.Activities; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ListAdapter; import android.widget.ListView; import java.util.ArrayList; import gr.edu.serres.TrancCoder_TheElucitated.Adapters.CustomAdapter; import gr.edu.serres.TrancCoder_TheElucitated.Database.Database_Functions; import gr.edu.serres.TrancCoder_TheElucitated.Objects.Inventory; import gr.edu.serres.TrancCoder_TheElucitated.R; /** * Created by tasos on 30/11/2016. */ public class InventoryScreenActivity extends AppCompatActivity { private static int counter = 0; private ArrayList<String> oneOne; private ListView listView; private Inventory inventory; private Database_Functions getInv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.inventory_layout); oneOne = new ArrayList<>(); //Toast.makeText(getApplicationContext(),String.valueOf(delay.length),Toast.LENGTH_SHORT).show(); //getInv.getUserInventory(userEmail); // Mήτσο εδώ θέλουμε ένα getUserEmail while (counter < inventory.getItemNames().size()) { oneOne.add(inventory.getItemNames().get(counter)); counter++; } counter = 0; listView = (ListView) this.findViewById(R.id.ListView); ListAdapter adapter = new CustomAdapter(getApplicationContext(), oneOne); listView.setAdapter(adapter); } }
TransCoders/The_Elucidated
app/src/main/java/gr/edu/serres/TrancCoder_TheElucitated/Activities/InventoryScreenActivity.java
408
// Mήτσο εδώ θέλουμε ένα getUserEmail
line_comment
el
package gr.edu.serres.TrancCoder_TheElucitated.Activities; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ListAdapter; import android.widget.ListView; import java.util.ArrayList; import gr.edu.serres.TrancCoder_TheElucitated.Adapters.CustomAdapter; import gr.edu.serres.TrancCoder_TheElucitated.Database.Database_Functions; import gr.edu.serres.TrancCoder_TheElucitated.Objects.Inventory; import gr.edu.serres.TrancCoder_TheElucitated.R; /** * Created by tasos on 30/11/2016. */ public class InventoryScreenActivity extends AppCompatActivity { private static int counter = 0; private ArrayList<String> oneOne; private ListView listView; private Inventory inventory; private Database_Functions getInv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.inventory_layout); oneOne = new ArrayList<>(); //Toast.makeText(getApplicationContext(),String.valueOf(delay.length),Toast.LENGTH_SHORT).show(); //getInv.getUserInventory(userEmail); // Mήτσο εδώ<SUF> while (counter < inventory.getItemNames().size()) { oneOne.add(inventory.getItemNames().get(counter)); counter++; } counter = 0; listView = (ListView) this.findViewById(R.id.ListView); ListAdapter adapter = new CustomAdapter(getApplicationContext(), oneOne); listView.setAdapter(adapter); } }
10632_2
package com.example.a2022_septemvris_champions; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { RadioGroup rg; OkHttpHandler ok; ClubsList listItem = new ClubsList(); ArrayList<String> cl = new ArrayList<>(); Button btn ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rg = findViewById(R.id.rg); cl = listItem.getYears(); displayYears(cl); } public void displayYears(ArrayList<String> cl){ for(int i=0;i< cl.size();i++){ RadioButton rb = new RadioButton(this); rb.setText(cl.get(i)); rb.setId(100+i); rg.addView(rb); } btn = findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { btn = findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int selectedRadioButtonId = rg.getCheckedRadioButtonId(); if (selectedRadioButtonId != -1) { RadioButton selectedRadioButton = findViewById(selectedRadioButtonId); String selectedYear = selectedRadioButton.getText().toString(); // Εκτελέστε τις ενέργειες που θέλετε όταν πατηθεί το κουμπί με βάση το επιλεγμένο RadioButton String omada = listItem.getName(selectedYear); Toast.makeText(MainActivity.this, omada, Toast.LENGTH_SHORT).show(); String imageUrl = listItem.getUrl(selectedYear); ImageView imageView = findViewById(R.id.imageView); // Αντικαταστήστε το imageView με το ID του ImageView σας Picasso.get().load(imageUrl).into(imageView); } else { // Ο χρήστης δεν έχει επιλέξει RadioButton Toast.makeText(MainActivity.this, "Παρακαλώ επιλέξτε ένα έτος", Toast.LENGTH_SHORT).show(); } } }); } }); } /*rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { String omada =""; RadioButton selectedRadioButton = findViewById(checkedId); String selectedYear = selectedRadioButton.getText().toString(); omada = listItem.getName(selectedYear); Toast.makeText(MainActivity.this, omada, Toast.LENGTH_SHORT).show(); String imageUrl = listItem.getUrl(selectedYear); ImageView imageView = findViewById(R.id.imageView); // Αντικαταστήστε το imageView με το ID του ImageView σας Picasso.get().load(imageUrl).into(imageView); } });*/ }
Tsoukkas/Applied-Informatics---University-of-Macedonia
Android Studio/PALIA_THEMATA/CHAMPIONS/2022_septemvris_champions/app/src/main/java/com/example/a2022_septemvris_champions/MainActivity.java
841
// Ο χρήστης δεν έχει επιλέξει RadioButton
line_comment
el
package com.example.a2022_septemvris_champions; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { RadioGroup rg; OkHttpHandler ok; ClubsList listItem = new ClubsList(); ArrayList<String> cl = new ArrayList<>(); Button btn ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rg = findViewById(R.id.rg); cl = listItem.getYears(); displayYears(cl); } public void displayYears(ArrayList<String> cl){ for(int i=0;i< cl.size();i++){ RadioButton rb = new RadioButton(this); rb.setText(cl.get(i)); rb.setId(100+i); rg.addView(rb); } btn = findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { btn = findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int selectedRadioButtonId = rg.getCheckedRadioButtonId(); if (selectedRadioButtonId != -1) { RadioButton selectedRadioButton = findViewById(selectedRadioButtonId); String selectedYear = selectedRadioButton.getText().toString(); // Εκτελέστε τις ενέργειες που θέλετε όταν πατηθεί το κουμπί με βάση το επιλεγμένο RadioButton String omada = listItem.getName(selectedYear); Toast.makeText(MainActivity.this, omada, Toast.LENGTH_SHORT).show(); String imageUrl = listItem.getUrl(selectedYear); ImageView imageView = findViewById(R.id.imageView); // Αντικαταστήστε το imageView με το ID του ImageView σας Picasso.get().load(imageUrl).into(imageView); } else { // Ο χρήστης<SUF> Toast.makeText(MainActivity.this, "Παρακαλώ επιλέξτε ένα έτος", Toast.LENGTH_SHORT).show(); } } }); } }); } /*rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { String omada =""; RadioButton selectedRadioButton = findViewById(checkedId); String selectedYear = selectedRadioButton.getText().toString(); omada = listItem.getName(selectedYear); Toast.makeText(MainActivity.this, omada, Toast.LENGTH_SHORT).show(); String imageUrl = listItem.getUrl(selectedYear); ImageView imageView = findViewById(R.id.imageView); // Αντικαταστήστε το imageView με το ID του ImageView σας Picasso.get().load(imageUrl).into(imageView); } });*/ }
454_9
package net.codejava.sql; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import java.awt.FlowLayout; import javax.swing.JTextField; import javax.swing.ListModel; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.SwingConstants; import java.awt.Font; import java.awt.Image; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.JPasswordField; import javax.swing.JButton; import javax.swing.JTable; import javax.swing.JComboBox; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.ImageIcon; import java.awt.Color; import javax.swing.border.LineBorder; public class LoginGUI extends JFrame { private Image account_image = new ImageIcon(LoginGUI.class.getResource("/images/account.png")).getImage().getScaledInstance(30, 30, Image.SCALE_SMOOTH);; private Image key_image = new ImageIcon(LoginGUI.class.getResource("/images/key.png")).getImage().getScaledInstance(30, 30, Image.SCALE_SMOOTH); private JPanel contentPane; private final JLabel lblNewLabel = new JLabel("LOGIN "); private final JLabel lblNewLabel_1 = new JLabel("Username:"); private final JTextField textField = new JTextField(); private final JLabel lblNewLabel_1_1 = new JLabel("Password:"); private final JPasswordField passwordField = new JPasswordField(); private final JButton btnNewButton = new JButton("Login"); private final JLabel lblNewLabel_1_2 = new JLabel("Destination:"); private final JLabel lblNewLabel_1_2_1 = new JLabel("Month:"); private final JButton btnNewButton_1 = new JButton("Create an account"); private final JLabel lblNewLabel_2 = new JLabel("New to Trabuds?"); private final JComboBox comboBox = new JComboBox(); private final JComboBox comboBox_1 = new JComboBox(); private final JLabel account = new JLabel(""); private final JLabel key = new JLabel(""); /**\ * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { LoginGUI frame = new LoginGUI(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public LoginGUI() { textField.setFont(new Font("Tahoma", Font.PLAIN, 18)); textField.setBounds(150, 85, 198, 30); textField.setColumns(10); initGUI(); } private void initGUI() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 541, 513); contentPane = new JPanel(); contentPane.setForeground(new Color(0, 64, 128)); contentPane.setBackground(new Color(0, 128, 128)); contentPane.setBorder(new LineBorder(new Color(0, 0, 0), 2)); setContentPane(contentPane); contentPane.setLayout(null); lblNewLabel.setForeground(new Color(255, 255, 255)); lblNewLabel.setBackground(new Color(255, 255, 255)); lblNewLabel.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.BOLD, 30)); lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel.setBounds(160, 11, 205, 53); contentPane.add(lblNewLabel); lblNewLabel_1.setForeground(new Color(255, 255, 255)); lblNewLabel_1.setBackground(new Color(255, 255, 255)); lblNewLabel_1.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 23)); lblNewLabel_1.setBounds(150, 52, 115, 39); contentPane.add(lblNewLabel_1); contentPane.add(textField); //Εισαγωγη ονοματος lblNewLabel_1_1.setForeground(new Color(255, 255, 255)); lblNewLabel_1_1.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 23)); lblNewLabel_1_1.setBounds(150, 120, 122, 30); contentPane.add(lblNewLabel_1_1); passwordField.setBounds(150, 150, 198, 30); contentPane.add(passwordField); //Εισαγωγη κωδικου btnNewButton.setFont(new Font("Tw Cen MT", Font.PLAIN, 25)); btnNewButton.setBounds(190, 326, 155, 39); contentPane.add(btnNewButton); lblNewLabel_1_2.setForeground(new Color(255, 255, 255)); lblNewLabel_1_2.setBackground(new Color(255, 255, 255)); lblNewLabel_1_2.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 23)); lblNewLabel_1_2.setBounds(150, 183, 122, 30); contentPane.add(lblNewLabel_1_2); lblNewLabel_1_2_1.setForeground(new Color(255, 255, 255)); lblNewLabel_1_2_1.setBackground(new Color(255, 255, 255)); lblNewLabel_1_2_1.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 23)); lblNewLabel_1_2_1.setBounds(150, 241, 95, 30); contentPane.add(lblNewLabel_1_2_1); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); btnNewButton_1.setFont(new Font("Tw Cen MT", Font.PLAIN, 17)); btnNewButton_1.setBounds(211, 410, 205, 30); contentPane.add(btnNewButton_1); lblNewLabel_2.setForeground(new Color(255, 255, 255)); lblNewLabel_2.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 19)); lblNewLabel_2.setBounds(70, 410, 275, 30); contentPane.add(lblNewLabel_2); comboBox.setEditable(true); comboBox.setFont(new Font("Tahoma", Font.PLAIN, 15)); comboBox.setModel(new DefaultComboBoxModel(new String[] {"Athens", "Paris", "Rome", "London", "Barcelona", "Prague", "Vienna", "Amsterdam", "Budapest", "Lisbon", "Copenagen", "Instabul", "Berlin", "Stockholm", "Dublin", "Oslo", "Milan", "Bucharest", "Moscha", "Madrid", ""})); comboBox.setBounds(150, 213, 216, 30); contentPane.add(comboBox); //εισαγωγη του προορισμου comboBox_1.setEditable(true); comboBox_1.setFont(new Font("Tahoma", Font.PLAIN, 15)); comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"})); comboBox_1.setBounds(150, 273, 216, 30); contentPane.add(comboBox_1); //εισαγωγη μηνα account.setBounds(346, 75, 43, 51); contentPane.add(account); account.setIcon(new ImageIcon(account_image)); key.setHorizontalAlignment(SwingConstants.TRAILING); key.setBounds(346, 150, 30, 30); contentPane.add(key); key.setIcon(new ImageIcon(key_image)); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); String url = "jdbc:sqlserver://" +"TZINA-PC" + ":1433;DatabaseName=" + "TRABUDZ" + ";encrypt=true;trustServerCertificate=true"; String user = "LSD"; String passWord = "LSD123"; Connection conn = DriverManager.getConnection(url, user, passWord); System.out.println("connected successfully to Database"); Statement stmt = conn.createStatement(); String query = "UPDATE USERS SET DEST=?, MONTHY=? WHERE POSITION= ?"; PreparedStatement pstmt = conn.prepareStatement(query); int i = 0; //αρχικοποιηση μεταβλητης που μετατρεπει το string του πινακα σε int για να μπει στη βαση σωστα String dest = comboBox.getSelectedItem().toString(); //αποκτηση τιμης προορισμου που επιλεγει ο χρηστης και μετατροπη σε String απο object switch (dest) { case "Athens": i = 1; break; case "Paris": i = 2; break; case "Rome": i = 3; break; case "London": i = 4; break; case "Barcelona": i = 5; break; case "Prague": i = 6; break; case "Vienna": i = 7; break; case "Amsterdam": i = 8; break; case "Budapest": i = 9; break; case "Lisbon": i = 10; break; case "Copenagen": i = 11; break; case "Instabul": i = 12; break; case "Berlin": i = 13; break; case "Stockholm": i = 14; break; case "Dublin": i = 15; break; case "Oslo": i = 16; break; case "Milan": i = 17; break; case "Bucharest": i = 18; break; case "Moscha": i = 19; break; case "Madrid": i = 20; break; } final int proorismos = i; String mhnas = comboBox_1.getSelectedItem().toString(); //αποκτηση της τιμης του μηνα που επιλεγει ο χρηστης και μεταροπη σε string απο object String sql = "Select * from USERS where USERNAME='"+textField.getText()+"' and PASSWORDY='"+passwordField.getText()+"'"; ResultSet rs = stmt.executeQuery(sql); if (rs.next()) { JOptionPane.showMessageDialog(null, "login successfully"); int position = rs.getInt(1); //παιρνουμε τη θεση που βρισκεται ο χρηστης μας στη βαση δεδομενων pstmt.setInt(1, proorismos); //Μπαινουν τα στοιχεια στη βαση(dest, monthy) μονο σε περιπτωση που ο χρηστης υπαρχει pstmt.setString(2, mhnas); pstmt.setInt(3, position); pstmt.executeUpdate(); //μπαινουν τα στοιχεια στη βαση Match match = new Match(); match.setPosition(position); match.setVisible(true); dispose(); System.out.println(match.matchingUsersProfile()); if (match.getBoolean() == false) { dispose(); JOptionPane.showMessageDialog(null, "We're sorry but there isn't any travel buddy for you. Please try again with new destination info"); EventQueue.invokeLater(new Runnable() { public void run() { try { LoginGUI frame = new LoginGUI(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } } else { JOptionPane.showMessageDialog(null, "Incorrect user data"); } conn.commit(); conn.close(); } catch (SQLException e) { } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { } } }); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (arg0.getSource() == btnNewButton_1 ) { SignUpGUI signupgui =new SignUpGUI(); signupgui.setVisible(true); dispose(); } } }); } }
Tzinapapadopoulou/LSD
src/LoginGUI.java
3,923
//μπαινουν τα στοιχεια στη βαση
line_comment
el
package net.codejava.sql; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import java.awt.FlowLayout; import javax.swing.JTextField; import javax.swing.ListModel; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.SwingConstants; import java.awt.Font; import java.awt.Image; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.JPasswordField; import javax.swing.JButton; import javax.swing.JTable; import javax.swing.JComboBox; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.ImageIcon; import java.awt.Color; import javax.swing.border.LineBorder; public class LoginGUI extends JFrame { private Image account_image = new ImageIcon(LoginGUI.class.getResource("/images/account.png")).getImage().getScaledInstance(30, 30, Image.SCALE_SMOOTH);; private Image key_image = new ImageIcon(LoginGUI.class.getResource("/images/key.png")).getImage().getScaledInstance(30, 30, Image.SCALE_SMOOTH); private JPanel contentPane; private final JLabel lblNewLabel = new JLabel("LOGIN "); private final JLabel lblNewLabel_1 = new JLabel("Username:"); private final JTextField textField = new JTextField(); private final JLabel lblNewLabel_1_1 = new JLabel("Password:"); private final JPasswordField passwordField = new JPasswordField(); private final JButton btnNewButton = new JButton("Login"); private final JLabel lblNewLabel_1_2 = new JLabel("Destination:"); private final JLabel lblNewLabel_1_2_1 = new JLabel("Month:"); private final JButton btnNewButton_1 = new JButton("Create an account"); private final JLabel lblNewLabel_2 = new JLabel("New to Trabuds?"); private final JComboBox comboBox = new JComboBox(); private final JComboBox comboBox_1 = new JComboBox(); private final JLabel account = new JLabel(""); private final JLabel key = new JLabel(""); /**\ * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { LoginGUI frame = new LoginGUI(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public LoginGUI() { textField.setFont(new Font("Tahoma", Font.PLAIN, 18)); textField.setBounds(150, 85, 198, 30); textField.setColumns(10); initGUI(); } private void initGUI() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 541, 513); contentPane = new JPanel(); contentPane.setForeground(new Color(0, 64, 128)); contentPane.setBackground(new Color(0, 128, 128)); contentPane.setBorder(new LineBorder(new Color(0, 0, 0), 2)); setContentPane(contentPane); contentPane.setLayout(null); lblNewLabel.setForeground(new Color(255, 255, 255)); lblNewLabel.setBackground(new Color(255, 255, 255)); lblNewLabel.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.BOLD, 30)); lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel.setBounds(160, 11, 205, 53); contentPane.add(lblNewLabel); lblNewLabel_1.setForeground(new Color(255, 255, 255)); lblNewLabel_1.setBackground(new Color(255, 255, 255)); lblNewLabel_1.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 23)); lblNewLabel_1.setBounds(150, 52, 115, 39); contentPane.add(lblNewLabel_1); contentPane.add(textField); //Εισαγωγη ονοματος lblNewLabel_1_1.setForeground(new Color(255, 255, 255)); lblNewLabel_1_1.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 23)); lblNewLabel_1_1.setBounds(150, 120, 122, 30); contentPane.add(lblNewLabel_1_1); passwordField.setBounds(150, 150, 198, 30); contentPane.add(passwordField); //Εισαγωγη κωδικου btnNewButton.setFont(new Font("Tw Cen MT", Font.PLAIN, 25)); btnNewButton.setBounds(190, 326, 155, 39); contentPane.add(btnNewButton); lblNewLabel_1_2.setForeground(new Color(255, 255, 255)); lblNewLabel_1_2.setBackground(new Color(255, 255, 255)); lblNewLabel_1_2.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 23)); lblNewLabel_1_2.setBounds(150, 183, 122, 30); contentPane.add(lblNewLabel_1_2); lblNewLabel_1_2_1.setForeground(new Color(255, 255, 255)); lblNewLabel_1_2_1.setBackground(new Color(255, 255, 255)); lblNewLabel_1_2_1.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 23)); lblNewLabel_1_2_1.setBounds(150, 241, 95, 30); contentPane.add(lblNewLabel_1_2_1); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); btnNewButton_1.setFont(new Font("Tw Cen MT", Font.PLAIN, 17)); btnNewButton_1.setBounds(211, 410, 205, 30); contentPane.add(btnNewButton_1); lblNewLabel_2.setForeground(new Color(255, 255, 255)); lblNewLabel_2.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 19)); lblNewLabel_2.setBounds(70, 410, 275, 30); contentPane.add(lblNewLabel_2); comboBox.setEditable(true); comboBox.setFont(new Font("Tahoma", Font.PLAIN, 15)); comboBox.setModel(new DefaultComboBoxModel(new String[] {"Athens", "Paris", "Rome", "London", "Barcelona", "Prague", "Vienna", "Amsterdam", "Budapest", "Lisbon", "Copenagen", "Instabul", "Berlin", "Stockholm", "Dublin", "Oslo", "Milan", "Bucharest", "Moscha", "Madrid", ""})); comboBox.setBounds(150, 213, 216, 30); contentPane.add(comboBox); //εισαγωγη του προορισμου comboBox_1.setEditable(true); comboBox_1.setFont(new Font("Tahoma", Font.PLAIN, 15)); comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"})); comboBox_1.setBounds(150, 273, 216, 30); contentPane.add(comboBox_1); //εισαγωγη μηνα account.setBounds(346, 75, 43, 51); contentPane.add(account); account.setIcon(new ImageIcon(account_image)); key.setHorizontalAlignment(SwingConstants.TRAILING); key.setBounds(346, 150, 30, 30); contentPane.add(key); key.setIcon(new ImageIcon(key_image)); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); String url = "jdbc:sqlserver://" +"TZINA-PC" + ":1433;DatabaseName=" + "TRABUDZ" + ";encrypt=true;trustServerCertificate=true"; String user = "LSD"; String passWord = "LSD123"; Connection conn = DriverManager.getConnection(url, user, passWord); System.out.println("connected successfully to Database"); Statement stmt = conn.createStatement(); String query = "UPDATE USERS SET DEST=?, MONTHY=? WHERE POSITION= ?"; PreparedStatement pstmt = conn.prepareStatement(query); int i = 0; //αρχικοποιηση μεταβλητης που μετατρεπει το string του πινακα σε int για να μπει στη βαση σωστα String dest = comboBox.getSelectedItem().toString(); //αποκτηση τιμης προορισμου που επιλεγει ο χρηστης και μετατροπη σε String απο object switch (dest) { case "Athens": i = 1; break; case "Paris": i = 2; break; case "Rome": i = 3; break; case "London": i = 4; break; case "Barcelona": i = 5; break; case "Prague": i = 6; break; case "Vienna": i = 7; break; case "Amsterdam": i = 8; break; case "Budapest": i = 9; break; case "Lisbon": i = 10; break; case "Copenagen": i = 11; break; case "Instabul": i = 12; break; case "Berlin": i = 13; break; case "Stockholm": i = 14; break; case "Dublin": i = 15; break; case "Oslo": i = 16; break; case "Milan": i = 17; break; case "Bucharest": i = 18; break; case "Moscha": i = 19; break; case "Madrid": i = 20; break; } final int proorismos = i; String mhnas = comboBox_1.getSelectedItem().toString(); //αποκτηση της τιμης του μηνα που επιλεγει ο χρηστης και μεταροπη σε string απο object String sql = "Select * from USERS where USERNAME='"+textField.getText()+"' and PASSWORDY='"+passwordField.getText()+"'"; ResultSet rs = stmt.executeQuery(sql); if (rs.next()) { JOptionPane.showMessageDialog(null, "login successfully"); int position = rs.getInt(1); //παιρνουμε τη θεση που βρισκεται ο χρηστης μας στη βαση δεδομενων pstmt.setInt(1, proorismos); //Μπαινουν τα στοιχεια στη βαση(dest, monthy) μονο σε περιπτωση που ο χρηστης υπαρχει pstmt.setString(2, mhnas); pstmt.setInt(3, position); pstmt.executeUpdate(); //μπαινουν τα<SUF> Match match = new Match(); match.setPosition(position); match.setVisible(true); dispose(); System.out.println(match.matchingUsersProfile()); if (match.getBoolean() == false) { dispose(); JOptionPane.showMessageDialog(null, "We're sorry but there isn't any travel buddy for you. Please try again with new destination info"); EventQueue.invokeLater(new Runnable() { public void run() { try { LoginGUI frame = new LoginGUI(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } } else { JOptionPane.showMessageDialog(null, "Incorrect user data"); } conn.commit(); conn.close(); } catch (SQLException e) { } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { } } }); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (arg0.getSource() == btnNewButton_1 ) { SignUpGUI signupgui =new SignUpGUI(); signupgui.setVisible(true); dispose(); } } }); } }
130_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 gr.uaegean.services; import gr.uaegean.pojo.MinEduAmkaResponse.AmkaResponse; import gr.uaegean.pojo.MinEduFamilyStatusResponse; import gr.uaegean.pojo.MinEduResponse; import gr.uaegean.pojo.MinEduΑacademicResponse.InspectionResult; import java.util.Optional; import org.springframework.web.client.HttpClientErrorException; /** * * @author nikos */ public interface MinEduService { public Optional<String> getAccessToken(String type) throws HttpClientErrorException; public Optional<String> getAccessTokenByTokenTypeEn(String tokenType) throws HttpClientErrorException; public Optional<InspectionResult> getInspectioResultByAcademicId(String academicId, String selectedUniversityId, String esmoSessionId) throws HttpClientErrorException; public Optional<String> getAcademicIdFromAMKA(String amkaNumber, String selectedUniversityId, String esmoSessionId) throws HttpClientErrorException; public Optional<MinEduResponse.InspectionResult> getInspectioResponseByAcademicId(String academicId, String selectedUniversityId, String esmoSessionId) throws HttpClientErrorException; public Optional<AmkaResponse> getAmkaFullResponse(String amka, String surname); /* firstname * 'Ονομα Πολίτη σε ελληνικούς χαρακτήρες lastname * Επώνυμο Πολίτη σε ελληνικούς χαρακτήρες fathername * Πατρώνυμο Πολίτη σε ελληνικούς χαρακτήρες, ή null σε περίπτωση Πολίτη ΑΓΝΩΣΤΟΥ ΠΑΤΡΟΣ mothername * Μητρώνυμο Πολίτη σε ελληνικούς χαρακτήρες birthdate * Ημερομηνία Γέννησης Πολίτη, στη μορφή 2 ψηφία ημέρα 2 ψηφία μήνας 4 ψηφία έτος πχ 05121910 supervisorusername * Το όνομα GDPR χρήστη επόπτείας χρήσης της υπηρεσίας supervisorpassword *Ο κωδικός πρόσβασης GDPR χρήστη εποπτείας χρήσης της υπηρεσίας servicename * Το όνομα της υπηρεσίας που επιστρέφει δεδομένα πολίτη από το Μητρώο Πολιτών σε ελληνικούς χαρακτήρες , πχ Βεβαίωση Οικογενειακής Κατάστασης fuzzy Παράμετρος έξυπνης αναζήτησης που παίρνει τιμή true για ενεργοποίηση και false για απενεργοποίηση, όταν είναι ενεργοποιημένη στις παράμετρους ονόματος, επωνύμου, πατρώνυμου και μητρώνυμου πολίτη δύναται να δοθούν μόν */ public Optional<MinEduFamilyStatusResponse> getFamilyStatusResponse(String firstname, String lastname, String fathername, String mothername, String birthdate, String supervisorusername, String supervisorpassword, String servicename); public Optional<MinEduFamilyStatusResponse> getBirthCertificateResponse(String firstname, String lastname, String fathername, String mothername, String birthdate, String supervisorusername, String supervisorpassword); }
UAegean-SBchain/Verifier-Agent
ssi-ejb/src/main/java/gr/uaegean/services/MinEduService.java
1,190
/* firstname * 'Ονομα Πολίτη σε ελληνικούς χαρακτήρες lastname * Επώνυμο Πολίτη σε ελληνικούς χαρακτήρες fathername * Πατρώνυμο Πολίτη σε ελληνικούς χαρακτήρες, ή null σε περίπτωση Πολίτη ΑΓΝΩΣΤΟΥ ΠΑΤΡΟΣ mothername * Μητρώνυμο Πολίτη σε ελληνικούς χαρακτήρες birthdate * Ημερομηνία Γέννησης Πολίτη, στη μορφή 2 ψηφία ημέρα 2 ψηφία μήνας 4 ψηφία έτος πχ 05121910 supervisorusername * Το όνομα GDPR χρήστη επόπτείας χρήσης της υπηρεσίας supervisorpassword *Ο κωδικός πρόσβασης GDPR χρήστη εποπτείας χρήσης της υπηρεσίας servicename * Το όνομα της υπηρεσίας που επιστρέφει δεδομένα πολίτη από το Μητρώο Πολιτών σε ελληνικούς χαρακτήρες , πχ Βεβαίωση Οικογενειακής Κατάστασης fuzzy Παράμετρος έξυπνης αναζήτησης που παίρνει τιμή true για ενεργοποίηση και false για απενεργοποίηση, όταν είναι ενεργοποιημένη στις παράμετρους ονόματος, επωνύμου, πατρώνυμου και μητρώνυμου πολίτη δύναται να δοθούν μόν */
block_comment
el
/* * 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 gr.uaegean.services; import gr.uaegean.pojo.MinEduAmkaResponse.AmkaResponse; import gr.uaegean.pojo.MinEduFamilyStatusResponse; import gr.uaegean.pojo.MinEduResponse; import gr.uaegean.pojo.MinEduΑacademicResponse.InspectionResult; import java.util.Optional; import org.springframework.web.client.HttpClientErrorException; /** * * @author nikos */ public interface MinEduService { public Optional<String> getAccessToken(String type) throws HttpClientErrorException; public Optional<String> getAccessTokenByTokenTypeEn(String tokenType) throws HttpClientErrorException; public Optional<InspectionResult> getInspectioResultByAcademicId(String academicId, String selectedUniversityId, String esmoSessionId) throws HttpClientErrorException; public Optional<String> getAcademicIdFromAMKA(String amkaNumber, String selectedUniversityId, String esmoSessionId) throws HttpClientErrorException; public Optional<MinEduResponse.InspectionResult> getInspectioResponseByAcademicId(String academicId, String selectedUniversityId, String esmoSessionId) throws HttpClientErrorException; public Optional<AmkaResponse> getAmkaFullResponse(String amka, String surname); /* firstname * 'Ονομα<SUF>*/ public Optional<MinEduFamilyStatusResponse> getFamilyStatusResponse(String firstname, String lastname, String fathername, String mothername, String birthdate, String supervisorusername, String supervisorpassword, String servicename); public Optional<MinEduFamilyStatusResponse> getBirthCertificateResponse(String firstname, String lastname, String fathername, String mothername, String birthdate, String supervisorusername, String supervisorpassword); }
9186_1
package com.mygdx.game.Logic.Squares; import com.mygdx.game.Logic.GameInstance; import com.mygdx.game.Logic.Player; /** * Square class that can be bought, upgraded and traded with other players. * Represents courses in a university */ @SuppressWarnings("unused") public class CourseSquare extends Square { private int grade=0; private int[] salary = new int[]{5,10,20,30,40,50}; private final int semester; private final String direction; private final String description; private final String professors; private float price; /** * @param name ex. ΤΕΧΝΟΛΟΓΙΑ ΛΟΓΙΣΜΙΚΟΥ (CSC402) * @param semester ex. 4 * @param direction ex. ΕΤΥ * @param description ex. Αρχές Τεχνολογίας Λογισμικού. Προβλήματα στην ανάπτυξη έργων λογισμικού. Διαφορές από άλλα τεχνικά έργα.... * @param Professors ex. Χατζηγεωργίου Αλέξανδρος * @param price ex. 50 */ public CourseSquare(String name, int semester, String direction, String description, String Professors, int price) { super(name); this.semester = semester; this.direction = direction; this.description = description; professors = Professors; this.price = price; } /** * {@inheritDoc} * Does nothing automatically, leaves it up to the UI * @param game The current Game Instance */ @Override public void runAction(GameInstance game) { } /** * To be used to calculate the a player's total salary. * @see Player#getStartSalary() * @return The salary of the square taking into account its grade */ public int getSalary(){ return salary[grade-5]; } /** * @return 0 when course fully upgraded or the price of the next upgrade */ public int getUpgradeCost() { if (grade==10) return 0; return salary[grade-4]; } /** * Raises the course grade by one for the specified price * @param aPlayer player that owns the course */ public void upgrade(Player aPlayer){ grade++; aPlayer.setStudyHours(aPlayer.getStudyHours()-salary[grade-5]); } /** * @return the array of salaries for each grade to be displayed by the UI */ public int[] getSalaryArray() { return salary; } /** * If grade is >= 5 * @return the grade of the course */ public int getGrade() { return grade; } /** * @param grade Sets the grade of the course. normal values in [5,10] */ public void setGrade(int grade) { this.grade = grade; } // Getters public float getPrice() { return price; } public int getSemester() { return semester; } public String getDirection() { return direction; } public String getDescription() { return description; } public String getProfessors() { return professors; } }
UoM2021-CSC402-Team15/foititopoli
core/src/com/mygdx/game/Logic/Squares/CourseSquare.java
864
/** * @param name ex. ΤΕΧΝΟΛΟΓΙΑ ΛΟΓΙΣΜΙΚΟΥ (CSC402) * @param semester ex. 4 * @param direction ex. ΕΤΥ * @param description ex. Αρχές Τεχνολογίας Λογισμικού. Προβλήματα στην ανάπτυξη έργων λογισμικού. Διαφορές από άλλα τεχνικά έργα.... * @param Professors ex. Χατζηγεωργίου Αλέξανδρος * @param price ex. 50 */
block_comment
el
package com.mygdx.game.Logic.Squares; import com.mygdx.game.Logic.GameInstance; import com.mygdx.game.Logic.Player; /** * Square class that can be bought, upgraded and traded with other players. * Represents courses in a university */ @SuppressWarnings("unused") public class CourseSquare extends Square { private int grade=0; private int[] salary = new int[]{5,10,20,30,40,50}; private final int semester; private final String direction; private final String description; private final String professors; private float price; /** * @param name ex.<SUF>*/ public CourseSquare(String name, int semester, String direction, String description, String Professors, int price) { super(name); this.semester = semester; this.direction = direction; this.description = description; professors = Professors; this.price = price; } /** * {@inheritDoc} * Does nothing automatically, leaves it up to the UI * @param game The current Game Instance */ @Override public void runAction(GameInstance game) { } /** * To be used to calculate the a player's total salary. * @see Player#getStartSalary() * @return The salary of the square taking into account its grade */ public int getSalary(){ return salary[grade-5]; } /** * @return 0 when course fully upgraded or the price of the next upgrade */ public int getUpgradeCost() { if (grade==10) return 0; return salary[grade-4]; } /** * Raises the course grade by one for the specified price * @param aPlayer player that owns the course */ public void upgrade(Player aPlayer){ grade++; aPlayer.setStudyHours(aPlayer.getStudyHours()-salary[grade-5]); } /** * @return the array of salaries for each grade to be displayed by the UI */ public int[] getSalaryArray() { return salary; } /** * If grade is >= 5 * @return the grade of the course */ public int getGrade() { return grade; } /** * @param grade Sets the grade of the course. normal values in [5,10] */ public void setGrade(int grade) { this.grade = grade; } // Getters public float getPrice() { return price; } public int getSemester() { return semester; } public String getDirection() { return direction; } public String getDescription() { return description; } public String getProfessors() { return professors; } }
90_4
package we.software.mastermind; /** * Created by bill on 3/24/17. */ public class Computer extends Player{ //Easy Difficulty : Code to crack for the player has 6 colours, no duplicates , no NULL colour. //Medium Difficulty : Code to crack for the player has 6 colours, has duplicates , no NULL colour. public Computer(int difficultyChoise) { super(); switch (difficultyChoise){ case 0: easyAlgorithm(); break; case 1: mediumAlgorithm(); break; } } //Fill the arraylist with different colors public void easyAlgorithm(){ for(int i=0; i< super.numberOfPins; i++){ int rand = 1+ (int)(Math.random()*6); if(!codeToBreak.contains(rand)){ codeToBreak.add(rand); } else{ i--; } } } //Γεμιζει τον πινακα με Pegs που μπορει να εχουν και ιδιο χρωμα πολλες φορες public void mediumAlgorithm(){ for (int i = 0; i<super.numberOfPins; i++) { int rand = 1+ (int)(Math.random()*6); codeToBreak.add(rand); } } }
V4570/mastermind-we
Mastermind/src/we/software/mastermind/Computer.java
357
//Γεμιζει τον πινακα με Pegs που μπορει να εχουν και ιδιο χρωμα πολλες φορες
line_comment
el
package we.software.mastermind; /** * Created by bill on 3/24/17. */ public class Computer extends Player{ //Easy Difficulty : Code to crack for the player has 6 colours, no duplicates , no NULL colour. //Medium Difficulty : Code to crack for the player has 6 colours, has duplicates , no NULL colour. public Computer(int difficultyChoise) { super(); switch (difficultyChoise){ case 0: easyAlgorithm(); break; case 1: mediumAlgorithm(); break; } } //Fill the arraylist with different colors public void easyAlgorithm(){ for(int i=0; i< super.numberOfPins; i++){ int rand = 1+ (int)(Math.random()*6); if(!codeToBreak.contains(rand)){ codeToBreak.add(rand); } else{ i--; } } } //Γεμιζει τον<SUF> public void mediumAlgorithm(){ for (int i = 0; i<super.numberOfPins; i++) { int rand = 1+ (int)(Math.random()*6); codeToBreak.add(rand); } } }
7093_8
package dit.hua.distributedSystems.project.demo.rest; import dit.hua.distributedSystems.project.demo.controller.AuthController; import dit.hua.distributedSystems.project.demo.entity.Application; import dit.hua.distributedSystems.project.demo.entity.MUser; import dit.hua.distributedSystems.project.demo.service.ApplicationService; import dit.hua.distributedSystems.project.demo.service.UserDetailsImpl; import dit.hua.distributedSystems.project.demo.service.UserDetailsServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @RestController @RequestMapping("/api/application") public class ApplicationRestController { @Autowired private ApplicationService applicationService; @Autowired private UserDetailsServiceImpl userService; //Η συγκεκριμένη μέθοδος επιστρέφει μια λίστα με τις αιτήσεις στον επιθεωρητή που είναι προς έγκριση 'Pending', ώστε να τις ελέγξει. @GetMapping("") public List <Application> showApplications(){ List <Application> applications = applicationService.getApplications(); List<Application> pendingApplications = applications.stream() .filter(application -> "Pending".equals(application.getDecision()) || ("Approved".equals(application.getDecision()) && application.getCompensationAmount() == 0)) .collect(Collectors.toList()); return pendingApplications; } //Η συγκεκριμένη μέθοδος χρησιμοποιείται για την προβολή από τον αγρότη των αιτήσεων του, που βρίσκονται είτε σε κατάσταση 'Pending' είτε έχουν ελεγχθεί και είναι 'Approved' //ή Denied. @GetMapping("/user/{user_id}") public List <Application> showFarmerApplications(@PathVariable Integer user_id){ Long loginid = AuthController.getId(); if (loginid.intValue() == user_id) { return applicationService.getFarmerApplications(user_id); } else { List<Application> EmptyList = new ArrayList<>(); return EmptyList; } } @PostMapping("/new/{user_id}") public ResponseEntity<String> saveApplication(@RequestBody Application application, @PathVariable Integer user_id) { String ds = application.getDecision(); double ca = application.getCompensationAmount(); String top = application.getCategoryOfProduction(); String top1 = top.toLowerCase(); Long loginid = AuthController.getId(); if (loginid.intValue() == user_id) { if (top1.equals("fruits") || top1.equals("vegetables")) { //Έλεγχος ότι το πεδίο categoryOfProduction είναι συμπληρωμένο με τις τιμές 'fruits' ή 'vegetables'. if (ds != null || ca != 0) { return new ResponseEntity<>("Fields decision and compensationAmount should not be filled!", HttpStatus.BAD_REQUEST); } if (application.getDamagedProductionAmount() > application.getProductionAmount()) { //Το ποσό της καταστραμμένης παραγωγής δεν θα πρέπει να υπερβαίνει το ποσό // της κανονικής παραγωγής. return new ResponseEntity<>("The damaged production should not surpass the production amount!", HttpStatus.BAD_REQUEST); } application.setCompensationAmount(0.0); //Προσθήκη νέας αίτησης στην βάση από τον αγρότη. Το πεδίο decision τίθεται 'Pending' αφού δεν έχει εγκριθεί η απορριφθεί από τον //επιθεωρητή η αίτηση. Αντίστοιχα και το πεδίο του ποσού της αποζημίωσης έχει τεθεί στο 0 για τον ίδιο λόγο. application.setDecision("Pending"); MUser user = userService.getUser(user_id); application.setUser(user); applicationService.saveApplication(application); return new ResponseEntity<>("Application has been successfully saved!", HttpStatus.OK); } else { return new ResponseEntity<>("Field category of production should be filled with values fruits or vegetables!", HttpStatus.BAD_REQUEST); } } else { return new ResponseEntity<>("You can't create an application and assign it to another user apart from yourself", HttpStatus.FORBIDDEN); } } //Μέθοδος για διαγραφή μιας αίτησης από τον αγρότη. @DeleteMapping("{applicationId}") public String deleteApplication(@PathVariable Integer applicationId) { Application application = applicationService.getApplication(applicationId); Long loginid = AuthController.getId(); if (loginid.intValue() == applicationService.getApplicationsFarmer(applicationId).getId()) { if ("Approved".equals(application.getDecision()) || "Denied".equals(application.getDecision())) { return "You can not delete an already checked application!"; } applicationService.deleteApplication(applicationId); return "Application has been successfully deleted!"; } else { return "You can't delete an application and assign it to another user apart from yourself"; } } @PostMapping("/makeDecision/{applicationId}") public String makeDecision(@PathVariable Integer applicationId) { Application application = applicationService.getApplication(applicationId); double damagedProductionAmount = application.getDamagedProductionAmount(); double productionAmount = application.getProductionAmount(); double ratio = damagedProductionAmount / productionAmount; //Αν το ratio είναι >0.4 η αίτηση του αγρότη εγκρίνεται, δηλαδή η κατεστραμμένη παραγωγή από την παραχθείσα παραγωγή ξεπερνά το 40% τότε ο αγρότης αποζημιώνεται, αλλιώς όχι. if (ratio > 0.4) { application.setDecision("Approved"); } else { application.setDecision("Denied"); } applicationService.saveApplication(application); //Αλλαγή της κατάστασης της αίτησης σε 'Approved' ή 'Denied' για την αίτηση. return "Application with id: " + applicationId + " has been checked "; //Επιστροφή κατάλληλου μηνύματος. } @PostMapping("/determineCompensation/{applicationId}") public String determineCompensation(@PathVariable Integer applicationId) { Application application = applicationService.getApplication(applicationId); //Έλεγχος αν η απόφαση για την αίτηση είναι 'Approved' if ("Approved".equals(application.getDecision())) { String categoryOfProduction = application.getCategoryOfProduction(); double damagedProductionAmount = application.getDamagedProductionAmount(); double compensationAmount = 0.0; if ("Fruits".equals(categoryOfProduction) || "fruits".equals(categoryOfProduction)) { //Σε περίπτωση που το είδος της παραγωγής είναι φρούτα ο αγρότης αποζημιώνεται //με 10 ευρώ για κάθε κιλό κατεστραμμένης παραγωγής. compensationAmount = 10 * damagedProductionAmount; //Σε περίπτωση που το είδος της παραγωγής είναι λαχανικά ο αγρότης αποζημιώνεται //με 20 ευρώ για κάθε κιλό κατεστραμμένης παραγωγής. } else if ("Vegetables".equals(categoryOfProduction) || "vegetables".equals(categoryOfProduction)) { compensationAmount = 20 * damagedProductionAmount; } //Ενημέρωση του πεδίου CompensationAmount. application.setCompensationAmount(compensationAmount); //Αποθήκευση της ενημερωμένης αίτησης. applicationService.saveApplication(application); } else { //Αν η απόφαση ήταν 'Denied' η αποζημίωση είναι 0. application.setCompensationAmount(0.0); applicationService.saveApplication(application); } //Επιστροφή κατάλληλου μηνύματος. return "Application with id: " + applicationId + " has been: " + application.getDecision() + " and the compensation amount is: " + application.getCompensationAmount(); } }
VasileiosKokki/FarmerCompensation_University
Distributed-Systems-Project-backend/Farmer Compensation System/src/main/java/dit/hua/distributedSystems/project/demo/rest/ApplicationRestController.java
2,617
//Αν το ratio είναι >0.4 η αίτηση του αγρότη εγκρίνεται, δηλαδή η κατεστραμμένη παραγωγή από την παραχθείσα παραγωγή ξεπερνά το 40% τότε ο αγρότης αποζημιώνεται, αλλιώς όχι.
line_comment
el
package dit.hua.distributedSystems.project.demo.rest; import dit.hua.distributedSystems.project.demo.controller.AuthController; import dit.hua.distributedSystems.project.demo.entity.Application; import dit.hua.distributedSystems.project.demo.entity.MUser; import dit.hua.distributedSystems.project.demo.service.ApplicationService; import dit.hua.distributedSystems.project.demo.service.UserDetailsImpl; import dit.hua.distributedSystems.project.demo.service.UserDetailsServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @RestController @RequestMapping("/api/application") public class ApplicationRestController { @Autowired private ApplicationService applicationService; @Autowired private UserDetailsServiceImpl userService; //Η συγκεκριμένη μέθοδος επιστρέφει μια λίστα με τις αιτήσεις στον επιθεωρητή που είναι προς έγκριση 'Pending', ώστε να τις ελέγξει. @GetMapping("") public List <Application> showApplications(){ List <Application> applications = applicationService.getApplications(); List<Application> pendingApplications = applications.stream() .filter(application -> "Pending".equals(application.getDecision()) || ("Approved".equals(application.getDecision()) && application.getCompensationAmount() == 0)) .collect(Collectors.toList()); return pendingApplications; } //Η συγκεκριμένη μέθοδος χρησιμοποιείται για την προβολή από τον αγρότη των αιτήσεων του, που βρίσκονται είτε σε κατάσταση 'Pending' είτε έχουν ελεγχθεί και είναι 'Approved' //ή Denied. @GetMapping("/user/{user_id}") public List <Application> showFarmerApplications(@PathVariable Integer user_id){ Long loginid = AuthController.getId(); if (loginid.intValue() == user_id) { return applicationService.getFarmerApplications(user_id); } else { List<Application> EmptyList = new ArrayList<>(); return EmptyList; } } @PostMapping("/new/{user_id}") public ResponseEntity<String> saveApplication(@RequestBody Application application, @PathVariable Integer user_id) { String ds = application.getDecision(); double ca = application.getCompensationAmount(); String top = application.getCategoryOfProduction(); String top1 = top.toLowerCase(); Long loginid = AuthController.getId(); if (loginid.intValue() == user_id) { if (top1.equals("fruits") || top1.equals("vegetables")) { //Έλεγχος ότι το πεδίο categoryOfProduction είναι συμπληρωμένο με τις τιμές 'fruits' ή 'vegetables'. if (ds != null || ca != 0) { return new ResponseEntity<>("Fields decision and compensationAmount should not be filled!", HttpStatus.BAD_REQUEST); } if (application.getDamagedProductionAmount() > application.getProductionAmount()) { //Το ποσό της καταστραμμένης παραγωγής δεν θα πρέπει να υπερβαίνει το ποσό // της κανονικής παραγωγής. return new ResponseEntity<>("The damaged production should not surpass the production amount!", HttpStatus.BAD_REQUEST); } application.setCompensationAmount(0.0); //Προσθήκη νέας αίτησης στην βάση από τον αγρότη. Το πεδίο decision τίθεται 'Pending' αφού δεν έχει εγκριθεί η απορριφθεί από τον //επιθεωρητή η αίτηση. Αντίστοιχα και το πεδίο του ποσού της αποζημίωσης έχει τεθεί στο 0 για τον ίδιο λόγο. application.setDecision("Pending"); MUser user = userService.getUser(user_id); application.setUser(user); applicationService.saveApplication(application); return new ResponseEntity<>("Application has been successfully saved!", HttpStatus.OK); } else { return new ResponseEntity<>("Field category of production should be filled with values fruits or vegetables!", HttpStatus.BAD_REQUEST); } } else { return new ResponseEntity<>("You can't create an application and assign it to another user apart from yourself", HttpStatus.FORBIDDEN); } } //Μέθοδος για διαγραφή μιας αίτησης από τον αγρότη. @DeleteMapping("{applicationId}") public String deleteApplication(@PathVariable Integer applicationId) { Application application = applicationService.getApplication(applicationId); Long loginid = AuthController.getId(); if (loginid.intValue() == applicationService.getApplicationsFarmer(applicationId).getId()) { if ("Approved".equals(application.getDecision()) || "Denied".equals(application.getDecision())) { return "You can not delete an already checked application!"; } applicationService.deleteApplication(applicationId); return "Application has been successfully deleted!"; } else { return "You can't delete an application and assign it to another user apart from yourself"; } } @PostMapping("/makeDecision/{applicationId}") public String makeDecision(@PathVariable Integer applicationId) { Application application = applicationService.getApplication(applicationId); double damagedProductionAmount = application.getDamagedProductionAmount(); double productionAmount = application.getProductionAmount(); double ratio = damagedProductionAmount / productionAmount; //Αν το<SUF> if (ratio > 0.4) { application.setDecision("Approved"); } else { application.setDecision("Denied"); } applicationService.saveApplication(application); //Αλλαγή της κατάστασης της αίτησης σε 'Approved' ή 'Denied' για την αίτηση. return "Application with id: " + applicationId + " has been checked "; //Επιστροφή κατάλληλου μηνύματος. } @PostMapping("/determineCompensation/{applicationId}") public String determineCompensation(@PathVariable Integer applicationId) { Application application = applicationService.getApplication(applicationId); //Έλεγχος αν η απόφαση για την αίτηση είναι 'Approved' if ("Approved".equals(application.getDecision())) { String categoryOfProduction = application.getCategoryOfProduction(); double damagedProductionAmount = application.getDamagedProductionAmount(); double compensationAmount = 0.0; if ("Fruits".equals(categoryOfProduction) || "fruits".equals(categoryOfProduction)) { //Σε περίπτωση που το είδος της παραγωγής είναι φρούτα ο αγρότης αποζημιώνεται //με 10 ευρώ για κάθε κιλό κατεστραμμένης παραγωγής. compensationAmount = 10 * damagedProductionAmount; //Σε περίπτωση που το είδος της παραγωγής είναι λαχανικά ο αγρότης αποζημιώνεται //με 20 ευρώ για κάθε κιλό κατεστραμμένης παραγωγής. } else if ("Vegetables".equals(categoryOfProduction) || "vegetables".equals(categoryOfProduction)) { compensationAmount = 20 * damagedProductionAmount; } //Ενημέρωση του πεδίου CompensationAmount. application.setCompensationAmount(compensationAmount); //Αποθήκευση της ενημερωμένης αίτησης. applicationService.saveApplication(application); } else { //Αν η απόφαση ήταν 'Denied' η αποζημίωση είναι 0. application.setCompensationAmount(0.0); applicationService.saveApplication(application); } //Επιστροφή κατάλληλου μηνύματος. return "Application with id: " + applicationId + " has been: " + application.getDecision() + " and the compensation amount is: " + application.getCompensationAmount(); } }
3769_2
package data.structures.hashmap; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.junit.Test; // δοκιμάζει τα όρια του πίνακα κατακερματισμού με 3 unit tests public class OpenAddressHashTableTest { private final int SIZE = 10000; // αριθμός στοιχείων private Dictionary<Integer, Integer> dict; // πίνακας κατακερματισμού private List<Integer> values; // λίστα που κρατάει τους τυχαίους ακεραίους private Random rng; // για τη δημουργία τυχαίων ακεραίων // αρχικοποιεί τις μεταβλητές public OpenAddressHashTableTest() { dict = new OpenAddressHashTable<>(); values = new ArrayList<>(); rng = new Random(); } // δοκιμάζει την εισαγωγή και την αναζήτηση @Test public void testPutAndGet() { // αρχικοποίησε την λίστα και τον πίνακα κατακερματισμού // η init εισάγει τα στοιχεία στον πίνακα κατακερματισμού init(); for (Integer v : values) { // για κάθε ακέραιο στην λίστα values // βεβαιώσου πως η αναζήτηση στον πίνακα κατακερματισμού επιστρέφει το σωστό value assertTrue(dict.get(v) == v + 1); } // άδειασε την λίστα και τον πίνακα κατακερματισμού clear(); } // δοκιμάζει την διαγραφή @Test public void testRemoveAndContains() { init(); // αρχικοποίησε την λίστα και τον πίνακα κατακερματισμού for (int i = 0; i < values.size(); i++) { // για κάθε ακέραιο στην λίστα values assertTrue(dict.contains(values.get(i))); // βεβαιώσου πως το στοιχείο υπάρχει στον πίνακα κατακερματισμού assertTrue(dict.remove(values.get(i)) == values.get(i) + 1); // και η διαγραφή του επιστρέφει το σωστό value // διαγράφει όλους τους ακέραιους που επιστρέφει η get από την λίστα while (i < values.size() && values.contains(values.get(i))) { values.remove(values.get(i)); } } clear(); // άδειασε την λίστα και τον πίνακα κατακερματισμού } // δοκιμάζει τις συναρτήσεις clear και isEmpty @Test public void testClearAndIsEmpty() { init(); // αρχικοποίησε την λίστα και τον πίνακα κατακερματισμού assertTrue(!dict.isEmpty()); // βεβαιώσου πως ο πίνακας δεν είναι άδειος clear(); // άδειασε την λίστα και τον πίνακα κατακερματισμού assertTrue(dict.isEmpty()); // βεβαιώσου πως ο πίνακας είναι άδειος } // γεμίζει την λίστα values με τυχαίους ακεραίους και τους εισάγει στον πίνακα κατακερματισμού private void init() { for (int i = 0; i < SIZE; i++) { // για SIZE επαναλήψεις int n = rng.nextInt(1000); // επέλεξε έναν τυχαίο ακέραιο μεταξύ του 0 και 999 values.add(n); // πρόσθεσε τον ακέραιο στην λίστα dict.put(n, n + 1); // πρόσθεσε τον ακέραιο σαν στοιχείο στον πίνακα κατακερματισμού // σημείωση: η λίστα μπορεί να περιέχει τον ίδιο ακέραιο πολλές φορές // ενώ ο πίνακας κατακερματισμού θα τον αποθηκεύσει μόνο μία φορά // επομένως το μέγεθος του πίνακα μπορεί να είναι μικρότερο από το μέγεθος της λίστας } } // αδείαζει την λίστα και τον πίνακα κατακερματισμού private void clear() { dict.clear(); // άδειασε τον πίνακα values.clear(); // άδειασε την λίστα } }
VasileiosKokki/HashMap_University
HashMap/src/test/java/data/structures/hashmap/OpenAddressHashTableTest.java
1,809
// για τη δημουργία τυχαίων ακεραίων
line_comment
el
package data.structures.hashmap; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.junit.Test; // δοκιμάζει τα όρια του πίνακα κατακερματισμού με 3 unit tests public class OpenAddressHashTableTest { private final int SIZE = 10000; // αριθμός στοιχείων private Dictionary<Integer, Integer> dict; // πίνακας κατακερματισμού private List<Integer> values; // λίστα που κρατάει τους τυχαίους ακεραίους private Random rng; // για τη<SUF> // αρχικοποιεί τις μεταβλητές public OpenAddressHashTableTest() { dict = new OpenAddressHashTable<>(); values = new ArrayList<>(); rng = new Random(); } // δοκιμάζει την εισαγωγή και την αναζήτηση @Test public void testPutAndGet() { // αρχικοποίησε την λίστα και τον πίνακα κατακερματισμού // η init εισάγει τα στοιχεία στον πίνακα κατακερματισμού init(); for (Integer v : values) { // για κάθε ακέραιο στην λίστα values // βεβαιώσου πως η αναζήτηση στον πίνακα κατακερματισμού επιστρέφει το σωστό value assertTrue(dict.get(v) == v + 1); } // άδειασε την λίστα και τον πίνακα κατακερματισμού clear(); } // δοκιμάζει την διαγραφή @Test public void testRemoveAndContains() { init(); // αρχικοποίησε την λίστα και τον πίνακα κατακερματισμού for (int i = 0; i < values.size(); i++) { // για κάθε ακέραιο στην λίστα values assertTrue(dict.contains(values.get(i))); // βεβαιώσου πως το στοιχείο υπάρχει στον πίνακα κατακερματισμού assertTrue(dict.remove(values.get(i)) == values.get(i) + 1); // και η διαγραφή του επιστρέφει το σωστό value // διαγράφει όλους τους ακέραιους που επιστρέφει η get από την λίστα while (i < values.size() && values.contains(values.get(i))) { values.remove(values.get(i)); } } clear(); // άδειασε την λίστα και τον πίνακα κατακερματισμού } // δοκιμάζει τις συναρτήσεις clear και isEmpty @Test public void testClearAndIsEmpty() { init(); // αρχικοποίησε την λίστα και τον πίνακα κατακερματισμού assertTrue(!dict.isEmpty()); // βεβαιώσου πως ο πίνακας δεν είναι άδειος clear(); // άδειασε την λίστα και τον πίνακα κατακερματισμού assertTrue(dict.isEmpty()); // βεβαιώσου πως ο πίνακας είναι άδειος } // γεμίζει την λίστα values με τυχαίους ακεραίους και τους εισάγει στον πίνακα κατακερματισμού private void init() { for (int i = 0; i < SIZE; i++) { // για SIZE επαναλήψεις int n = rng.nextInt(1000); // επέλεξε έναν τυχαίο ακέραιο μεταξύ του 0 και 999 values.add(n); // πρόσθεσε τον ακέραιο στην λίστα dict.put(n, n + 1); // πρόσθεσε τον ακέραιο σαν στοιχείο στον πίνακα κατακερματισμού // σημείωση: η λίστα μπορεί να περιέχει τον ίδιο ακέραιο πολλές φορές // ενώ ο πίνακας κατακερματισμού θα τον αποθηκεύσει μόνο μία φορά // επομένως το μέγεθος του πίνακα μπορεί να είναι μικρότερο από το μέγεθος της λίστας } } // αδείαζει την λίστα και τον πίνακα κατακερματισμού private void clear() { dict.clear(); // άδειασε τον πίνακα values.clear(); // άδειασε την λίστα } }
897_20
package jukebox.jukebox; // Η κλάση checkArguments υλοποιεί τις μεθόδους του interface Arguments public class checkArguments implements Arguments { // Οι τρείς πίνακες από String περιέχουν τα file extentions, τα list extentions και τα διάφορα strategies // Το int NumbOfArg περιέχει τον μέγιστο αριθμό των arguments που θέλουμε να έχει το πρόγραμμα private int NumbOfArg; private final String[] files = {"mp3"}; private final String[] lists = {"m3u"}; private final String[] strats = {"loop", "random", "order"}; // Ο ένας constructor είναι υπεύθυνος για την αρχικοποίηση του NumbOfArg // Ο άλλος δεν κάνει τίποτα απλά υπάρχει για να καλείται η κλάση σε άλλες κλάσεις χωρίς να πρέπει να του δώσουμε αριθμό arguments public checkArguments(int NumbOfArg) { this.NumbOfArg = NumbOfArg; } public checkArguments() { } // Η checkArgNumb τσεκάρει αν ο αριθμός των arguments που έδωσε ο χρήστης είναι από 1 μέχρι και NumbOfArg, // όπου Numb ο αριθμός των arguments που έδωσε ο χρήστης, και επιστρέφει λογικό true or false public boolean checkArgNumb(int Numb) { return Numb >= 1 && Numb <= NumbOfArg; } // Η checkStrat τσεκάρει αν η στρατηγική που έδωσε ο χρήστης υπάρχει σαν στρατηγική, // όπου StratInput το δεύτερο argument που έδωσε ο χρήστης και strats ο πίνακας με τις διάφορες στρατηγικές, // και επιστρέφει σε String με lowercase την στρατηγική αν υπάρχει αλλιώς επιστρέφει "" // Η τοπική μεταβλητή Strat είναι για το πέρασμα όλου του πίνακα public String checkStrat(String StratInput) { for (String Strat : strats) { if (StratInput.toLowerCase().equals(Strat)) { return StratInput.toLowerCase(); } } return ""; } // Η checkFileType τσεκάρει αν αυτό που έδωσε ο χρήστης είναι στα υποστηριζόμενα αρχεία του προγράμματος, // όπου FileInput το πρώτο argument που έδωσε ο χρήστης και files ο πίνακας με τα υποστηριζόμενα αρχεία, // και επιστρέφει λογικό true or false // H τοπική μεταβλητή File είναι για το πέρασμα όλου του πίνακα public boolean checkFileType(String FileInput) { for (String File : files) { if (FileInput.lastIndexOf(".") != -1) { // Βλέπει αν υπάρχει "." στο FileInput if (FileInput.substring(FileInput.lastIndexOf(".") + 1).contains(File)) { // Βλέπει αν μετά την τελευταία "." που υπάρχει return true; // περιέχει κάποιο από τα υποστηριζόμενα αρχεία που } // βρίσκονται στον πίνακα } } return false; } // Η checkListType τσεκάρει αν αυτό που έδωσε είναι στις υποστηριζόμενες λίστες του προγράμματος, // όπου ListInput το πρώτο argument που έδωσε ο χρήστης και lists ο πίνακας με τις υποστηριζόμενες λίστες, // και επιστρέφει λογικό true or false // Η τοπική μεταβλητή List είναι για το πέρασμα όλου του πίνακα public boolean checkListType(String ListInput) { for (String List : lists) { if (ListInput.lastIndexOf(".") != -1) { // Βλέπει αν υπάρχει "." στο ListInput if (ListInput.substring(ListInput.lastIndexOf(".") + 1).contains(List)) { // Βλέπει αν μετά την τελευταία "." που υπάρχει return true; // περιέχει κάποιο από τις υποστηριζόμενες λίστες που } // βρίσκονται στον πίνακα } } return false; } public boolean checkDirectory(String Input) { return !Input.substring(Input.lastIndexOf("\\") + 1).contains("."); } // Η other εκτελεί ένα print αναλόγως την περίπτωση // Όπου Input και StratInput το πρώτο και δεύτερο argument που έδωσε ο χρήστης public void other(String StratInput, String Input) { if (checkStrat(StratInput).equals("")) { // Αν αυτό που επιστρέψει η checkStrat είναι ίσο με "", δηλαδή System.out.println(">>> Strategy not found"); // αυτό που έδωσε ο χρήστης δεν υπάρχει σαν στρατηγική τότε } // κάνει print ότι δεν υπάρχει η στρατηγική που έδωσε else if (checkFileType(Input)) { System.out.println(">>> Cannot use " + StratInput + " with file"); // Αλλιώς αν το πρώτο argument που έδωσε ο χρήστης έιναι αρχείο } // κάνει print ότι δεν μπορεί να χρησιμοποιήσει την συγκεκριμένη else if (checkListType(Input)) { // στρατηγική με file και αντίστοιχα για list System.out.println(">>> Cannot use " + StratInput + " with List"); } } }
VasileiosKokki/Jukebox_University
JukeBox2/src/main/java/jukebox/jukebox/checkArguments.java
2,275
// όπου ListInput το πρώτο argument που έδωσε ο χρήστης και lists ο πίνακας με τις υποστηριζόμενες λίστες,
line_comment
el
package jukebox.jukebox; // Η κλάση checkArguments υλοποιεί τις μεθόδους του interface Arguments public class checkArguments implements Arguments { // Οι τρείς πίνακες από String περιέχουν τα file extentions, τα list extentions και τα διάφορα strategies // Το int NumbOfArg περιέχει τον μέγιστο αριθμό των arguments που θέλουμε να έχει το πρόγραμμα private int NumbOfArg; private final String[] files = {"mp3"}; private final String[] lists = {"m3u"}; private final String[] strats = {"loop", "random", "order"}; // Ο ένας constructor είναι υπεύθυνος για την αρχικοποίηση του NumbOfArg // Ο άλλος δεν κάνει τίποτα απλά υπάρχει για να καλείται η κλάση σε άλλες κλάσεις χωρίς να πρέπει να του δώσουμε αριθμό arguments public checkArguments(int NumbOfArg) { this.NumbOfArg = NumbOfArg; } public checkArguments() { } // Η checkArgNumb τσεκάρει αν ο αριθμός των arguments που έδωσε ο χρήστης είναι από 1 μέχρι και NumbOfArg, // όπου Numb ο αριθμός των arguments που έδωσε ο χρήστης, και επιστρέφει λογικό true or false public boolean checkArgNumb(int Numb) { return Numb >= 1 && Numb <= NumbOfArg; } // Η checkStrat τσεκάρει αν η στρατηγική που έδωσε ο χρήστης υπάρχει σαν στρατηγική, // όπου StratInput το δεύτερο argument που έδωσε ο χρήστης και strats ο πίνακας με τις διάφορες στρατηγικές, // και επιστρέφει σε String με lowercase την στρατηγική αν υπάρχει αλλιώς επιστρέφει "" // Η τοπική μεταβλητή Strat είναι για το πέρασμα όλου του πίνακα public String checkStrat(String StratInput) { for (String Strat : strats) { if (StratInput.toLowerCase().equals(Strat)) { return StratInput.toLowerCase(); } } return ""; } // Η checkFileType τσεκάρει αν αυτό που έδωσε ο χρήστης είναι στα υποστηριζόμενα αρχεία του προγράμματος, // όπου FileInput το πρώτο argument που έδωσε ο χρήστης και files ο πίνακας με τα υποστηριζόμενα αρχεία, // και επιστρέφει λογικό true or false // H τοπική μεταβλητή File είναι για το πέρασμα όλου του πίνακα public boolean checkFileType(String FileInput) { for (String File : files) { if (FileInput.lastIndexOf(".") != -1) { // Βλέπει αν υπάρχει "." στο FileInput if (FileInput.substring(FileInput.lastIndexOf(".") + 1).contains(File)) { // Βλέπει αν μετά την τελευταία "." που υπάρχει return true; // περιέχει κάποιο από τα υποστηριζόμενα αρχεία που } // βρίσκονται στον πίνακα } } return false; } // Η checkListType τσεκάρει αν αυτό που έδωσε είναι στις υποστηριζόμενες λίστες του προγράμματος, // όπου ListInput<SUF> // και επιστρέφει λογικό true or false // Η τοπική μεταβλητή List είναι για το πέρασμα όλου του πίνακα public boolean checkListType(String ListInput) { for (String List : lists) { if (ListInput.lastIndexOf(".") != -1) { // Βλέπει αν υπάρχει "." στο ListInput if (ListInput.substring(ListInput.lastIndexOf(".") + 1).contains(List)) { // Βλέπει αν μετά την τελευταία "." που υπάρχει return true; // περιέχει κάποιο από τις υποστηριζόμενες λίστες που } // βρίσκονται στον πίνακα } } return false; } public boolean checkDirectory(String Input) { return !Input.substring(Input.lastIndexOf("\\") + 1).contains("."); } // Η other εκτελεί ένα print αναλόγως την περίπτωση // Όπου Input και StratInput το πρώτο και δεύτερο argument που έδωσε ο χρήστης public void other(String StratInput, String Input) { if (checkStrat(StratInput).equals("")) { // Αν αυτό που επιστρέψει η checkStrat είναι ίσο με "", δηλαδή System.out.println(">>> Strategy not found"); // αυτό που έδωσε ο χρήστης δεν υπάρχει σαν στρατηγική τότε } // κάνει print ότι δεν υπάρχει η στρατηγική που έδωσε else if (checkFileType(Input)) { System.out.println(">>> Cannot use " + StratInput + " with file"); // Αλλιώς αν το πρώτο argument που έδωσε ο χρήστης έιναι αρχείο } // κάνει print ότι δεν μπορεί να χρησιμοποιήσει την συγκεκριμένη else if (checkListType(Input)) { // στρατηγική με file και αντίστοιχα για list System.out.println(">>> Cannot use " + StratInput + " with List"); } } }
627_6
package tillerino.tillerinobot.lang; import java.util.List; import java.util.Random; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import tillerino.tillerinobot.BeatmapMeta; import tillerino.tillerinobot.IRCBot.IRCBotUser; import tillerino.tillerinobot.RecommendationsManager.Recommendation; /** * @author Till https://github.com/nikosbks https://osu.ppy.sh/u/3619345 */ public class Greek implements Language { @Override public String unknownBeatmap() { return "Συγνώμη, δεν γνωρίζω αυτό το τραγούδι. Ίσως είναι αρκετά νεο, πολυ δύσκολο, μη εγκεκριμένο ή να μην είναι για το osu standard mode." ; } @Override public String internalException(String marker) { return "Εχ... μάλλον φαίνεται ότι ο ανθρώπινος Tillerino έκανε μαντάρα την σύνδεσή μου." +" Εάν δεν το παρατηρήσει σύντομα, μπορείς [https://github.com/Tillerino/Tillerinobot/wiki/Contact να τον ενημερώσεις]; (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Τί συμβαίνει; Παίρνω μονο παραλογίες από τον server του osu. Μπορείς να μου πείς τι σημαίνει αυτο; 0011101001010000" + " Ο ανθρώπινος Tillerino λέει ότι δεν υπάρχει κάτι για να ανησυχείς, και ότι πρέπει να ξαναπροσπαθήσουμε." + " Εάν ανησυχείς πάρα πολύ για κάποιο λογο, μπορείς να [https://github.com/Tillerino/Tillerinobot/wiki/Contact του το πείς]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Δεν υπάρχουν δεδομένα για τα ζητούμενα mods." ; } @Override public void welcomeUser(IRCBotUser user, OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { user.message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { user.message("Καλώς ήρθες πίσω," + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { user.message(apiUser.getUserName() + "..."); user.message("...είσαι εσύ αυτός; Πάει πολύς καιρός!"); user.message("Είναι ωραίο να σε έχουμε πίσω. Μπορώ να σε ενδιαφέρω με μια πρόταση;"); } else { String[] messages = { "Φαίνεσαι σαν να θες μια πρόταση.", "Πόσο ωραίο να σε βλέπω :)", "Ο αγαπημένος μου άνθρωπος. (Μην το πείς στούς άλλους!)", "Τι ευχάριστη έκπληξη! ^.^", "Περίμενα ότι θα εμφανιστείς. Όλοι οι άλλοι άνθρωποι ειναι μπούφοι, αλλα μην τους πείς ότι το ειπα! :3", "Τι έχεις την διάθεση να κάνεις σήμερα;", }; Random random = new Random(); String message = messages[random.nextInt(messages.length)]; user.message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Άγνωστη εντολή \"" + command + "\". Πληκτρολόγησε !help αν χρειάζεσαι βοήθεια!"; } @Override public String noInformationForMods() { return "Συγνώμη, δεν μπορώ να παρέχω πληροφορίες για αυτά τα mods αυτή τη στιγμή"; } @Override public String malformattedMods(String mods) { return "Αυτα τα mods δεν φαίνονται σωστά. Τα mods μπορεί να είναι ενας συνδυασμός από DT HR HD HT EZ NC FL SO NF.Συνδυάζοντάς τα χωρίς κενά ή ειδικούς χαρακτήρες. Παράδειγμα: !with HDHR, !with DTEZ"; } @Override public String noLastSongInfo() { return "Δεν θυμάμαι να πήρες καμία πληροφορία τραγουδιού..."; } @Override public String tryWithMods() { return "Δοκίμασε αυτό το τραγούδι με μερικά mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Δοκίμασε αυτό το τραγούδι με " + Mods.toShortNamesContinuous(mods); } /** * The user's IRC nick name could not be resolved to an osu user id. The * message should suggest to contact @Tillerinobot or /u/Tillerino. * * @param exceptionMarker * a marker to reference the created log entry. six or eight * characters. * @param name * the irc nick which could not be resolved * @return */ public String unresolvableName(String exceptionMarker, String name) { return "Το ονομά σου με μπερδεύει. Είσαι απαγορευμένος; Εάν όχι, παρακαλώ [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινώνησε με τον Tillerino]. (reference " + exceptionMarker + ")"; } @Override public String excuseForError() { return "Συγνώμη, υπήρχε αυτή η όμορφη σειρά από άσσους και μηδενικά και παρασύρθηκα. Τί ήθελες ξανα;"; } @Override public String complaint() { return "Το παράπονό σου κατατέθηκε. Ο Tillerino θα το κοιτάξει όταν μπορέσει."; } @Override public void hug(final IRCBotUser user, OsuApiUser apiUser) { user.message("Έλα εδώ εσυ!"); user.action("Αγκαλιάζει " + apiUser.getUserName()); } @Override public String help() { return "Γειά! Είμαι το ρομπότ που σκότωσε τον Tillerino και πήρε τον λογαριασμό του. Πλάκα κάνω, αλλά όντως χρησιμοποιώ τον λογαριασμό αρκετά." + " [https://twitter.com/Tillerinobot status και updates]" + " - [https://github.com/Tillerino/Tillerinobot/wiki εντολές]" + " - [http://ppaddict.tillerino.org/ ppaddict]" + " - [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινωνία]"; } @Override public String faq() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ Συχνά ερωτώμενες ερωτήσεις]"; } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Συγνώμη, σε αυτό το σημείο " + feature + "είναι μόνο διαθέσιμο για παίκτες που εχουν ξεπερασμένη τάξη " + minRank + "."; } @Override public String mixedNomodAndMods() { return "Τί εννοείς nomods με mods;"; } @Override public String outOfRecommendations() { return "Έχω προτίνει ό,τι μπορώ να σκεφτώ. " + " Προσπάθησε άλλες επιλογές προτάσεων ή χρησιμοποίησε το !rest. Εάν δεν είσαι σίγουρος, έλεγξε το !help."; } @Override public String notRanked() { return "Απ' ότι φαίνεται αυτό το τραγούδι δεν είναι εγκεκριμένο."; } @Override public void optionalCommentOnNP(IRCBotUser user, OsuApiUser apiUser, BeatmapMeta meta) { // regular Tillerino doesn't comment on this } @Override public void optionalCommentOnWith(IRCBotUser user, OsuApiUser apiUser, BeatmapMeta meta) { // regular Tillerino doesn't comment on this } @Override public void optionalCommentOnRecommendation(IRCBotUser user, OsuApiUser apiUser, Recommendation meta) { // regular Tillerino doesn't comment on this } @Override public boolean isChanged() { return false; } @Override public void setChanged(boolean changed) { } @Override public String invalidAccuracy(String acc) { return "Άκυρη ακρίβεια: \"" + acc + "\""; } @Override public void optionalCommentOnLanguage(IRCBotUser user, OsuApiUser apiUser) { user.message("Ο N for Niko με βοήθησε να μάθω Ελληνικά"); } @Override public String invalidChoice(String invalid, String choices) { return "Συγνώμη, αλλά \"" + invalid + "\" δεν υπολογίζει. Προσπάθησε αυτά: " + choices + "!"; } @Override public String setFormat() { return "Η σύνταξη για να ρυθμιστεί η παράμετρος είναι !set ρύθμιση ποσού. Δοκίμασε !help εάν χρειάζεσαι περισσότερες υποδείξεις."; } @Override public String apiTimeoutException() { return new Default().apiTimeoutException(); } }
Vidalee/Tillerinobot
tillerinobot/src/main/java/tillerino/tillerinobot/lang/Greek.java
3,628
//github.com/Tillerino/Tillerinobot/wiki/FAQ Συχνά ερωτώμενες ερωτήσεις]";
line_comment
el
package tillerino.tillerinobot.lang; import java.util.List; import java.util.Random; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import tillerino.tillerinobot.BeatmapMeta; import tillerino.tillerinobot.IRCBot.IRCBotUser; import tillerino.tillerinobot.RecommendationsManager.Recommendation; /** * @author Till https://github.com/nikosbks https://osu.ppy.sh/u/3619345 */ public class Greek implements Language { @Override public String unknownBeatmap() { return "Συγνώμη, δεν γνωρίζω αυτό το τραγούδι. Ίσως είναι αρκετά νεο, πολυ δύσκολο, μη εγκεκριμένο ή να μην είναι για το osu standard mode." ; } @Override public String internalException(String marker) { return "Εχ... μάλλον φαίνεται ότι ο ανθρώπινος Tillerino έκανε μαντάρα την σύνδεσή μου." +" Εάν δεν το παρατηρήσει σύντομα, μπορείς [https://github.com/Tillerino/Tillerinobot/wiki/Contact να τον ενημερώσεις]; (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Τί συμβαίνει; Παίρνω μονο παραλογίες από τον server του osu. Μπορείς να μου πείς τι σημαίνει αυτο; 0011101001010000" + " Ο ανθρώπινος Tillerino λέει ότι δεν υπάρχει κάτι για να ανησυχείς, και ότι πρέπει να ξαναπροσπαθήσουμε." + " Εάν ανησυχείς πάρα πολύ για κάποιο λογο, μπορείς να [https://github.com/Tillerino/Tillerinobot/wiki/Contact του το πείς]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Δεν υπάρχουν δεδομένα για τα ζητούμενα mods." ; } @Override public void welcomeUser(IRCBotUser user, OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { user.message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { user.message("Καλώς ήρθες πίσω," + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { user.message(apiUser.getUserName() + "..."); user.message("...είσαι εσύ αυτός; Πάει πολύς καιρός!"); user.message("Είναι ωραίο να σε έχουμε πίσω. Μπορώ να σε ενδιαφέρω με μια πρόταση;"); } else { String[] messages = { "Φαίνεσαι σαν να θες μια πρόταση.", "Πόσο ωραίο να σε βλέπω :)", "Ο αγαπημένος μου άνθρωπος. (Μην το πείς στούς άλλους!)", "Τι ευχάριστη έκπληξη! ^.^", "Περίμενα ότι θα εμφανιστείς. Όλοι οι άλλοι άνθρωποι ειναι μπούφοι, αλλα μην τους πείς ότι το ειπα! :3", "Τι έχεις την διάθεση να κάνεις σήμερα;", }; Random random = new Random(); String message = messages[random.nextInt(messages.length)]; user.message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Άγνωστη εντολή \"" + command + "\". Πληκτρολόγησε !help αν χρειάζεσαι βοήθεια!"; } @Override public String noInformationForMods() { return "Συγνώμη, δεν μπορώ να παρέχω πληροφορίες για αυτά τα mods αυτή τη στιγμή"; } @Override public String malformattedMods(String mods) { return "Αυτα τα mods δεν φαίνονται σωστά. Τα mods μπορεί να είναι ενας συνδυασμός από DT HR HD HT EZ NC FL SO NF.Συνδυάζοντάς τα χωρίς κενά ή ειδικούς χαρακτήρες. Παράδειγμα: !with HDHR, !with DTEZ"; } @Override public String noLastSongInfo() { return "Δεν θυμάμαι να πήρες καμία πληροφορία τραγουδιού..."; } @Override public String tryWithMods() { return "Δοκίμασε αυτό το τραγούδι με μερικά mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Δοκίμασε αυτό το τραγούδι με " + Mods.toShortNamesContinuous(mods); } /** * The user's IRC nick name could not be resolved to an osu user id. The * message should suggest to contact @Tillerinobot or /u/Tillerino. * * @param exceptionMarker * a marker to reference the created log entry. six or eight * characters. * @param name * the irc nick which could not be resolved * @return */ public String unresolvableName(String exceptionMarker, String name) { return "Το ονομά σου με μπερδεύει. Είσαι απαγορευμένος; Εάν όχι, παρακαλώ [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινώνησε με τον Tillerino]. (reference " + exceptionMarker + ")"; } @Override public String excuseForError() { return "Συγνώμη, υπήρχε αυτή η όμορφη σειρά από άσσους και μηδενικά και παρασύρθηκα. Τί ήθελες ξανα;"; } @Override public String complaint() { return "Το παράπονό σου κατατέθηκε. Ο Tillerino θα το κοιτάξει όταν μπορέσει."; } @Override public void hug(final IRCBotUser user, OsuApiUser apiUser) { user.message("Έλα εδώ εσυ!"); user.action("Αγκαλιάζει " + apiUser.getUserName()); } @Override public String help() { return "Γειά! Είμαι το ρομπότ που σκότωσε τον Tillerino και πήρε τον λογαριασμό του. Πλάκα κάνω, αλλά όντως χρησιμοποιώ τον λογαριασμό αρκετά." + " [https://twitter.com/Tillerinobot status και updates]" + " - [https://github.com/Tillerino/Tillerinobot/wiki εντολές]" + " - [http://ppaddict.tillerino.org/ ppaddict]" + " - [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινωνία]"; } @Override public String faq() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ Συχνά<SUF> } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Συγνώμη, σε αυτό το σημείο " + feature + "είναι μόνο διαθέσιμο για παίκτες που εχουν ξεπερασμένη τάξη " + minRank + "."; } @Override public String mixedNomodAndMods() { return "Τί εννοείς nomods με mods;"; } @Override public String outOfRecommendations() { return "Έχω προτίνει ό,τι μπορώ να σκεφτώ. " + " Προσπάθησε άλλες επιλογές προτάσεων ή χρησιμοποίησε το !rest. Εάν δεν είσαι σίγουρος, έλεγξε το !help."; } @Override public String notRanked() { return "Απ' ότι φαίνεται αυτό το τραγούδι δεν είναι εγκεκριμένο."; } @Override public void optionalCommentOnNP(IRCBotUser user, OsuApiUser apiUser, BeatmapMeta meta) { // regular Tillerino doesn't comment on this } @Override public void optionalCommentOnWith(IRCBotUser user, OsuApiUser apiUser, BeatmapMeta meta) { // regular Tillerino doesn't comment on this } @Override public void optionalCommentOnRecommendation(IRCBotUser user, OsuApiUser apiUser, Recommendation meta) { // regular Tillerino doesn't comment on this } @Override public boolean isChanged() { return false; } @Override public void setChanged(boolean changed) { } @Override public String invalidAccuracy(String acc) { return "Άκυρη ακρίβεια: \"" + acc + "\""; } @Override public void optionalCommentOnLanguage(IRCBotUser user, OsuApiUser apiUser) { user.message("Ο N for Niko με βοήθησε να μάθω Ελληνικά"); } @Override public String invalidChoice(String invalid, String choices) { return "Συγνώμη, αλλά \"" + invalid + "\" δεν υπολογίζει. Προσπάθησε αυτά: " + choices + "!"; } @Override public String setFormat() { return "Η σύνταξη για να ρυθμιστεί η παράμετρος είναι !set ρύθμιση ποσού. Δοκίμασε !help εάν χρειάζεσαι περισσότερες υποδείξεις."; } @Override public String apiTimeoutException() { return new Default().apiTimeoutException(); } }
20883_0
package guis; import main_program.EncryptionUtils; import main_program.PasswodManager; import main_program.User; import java.awt.Color; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.*; public class Gui extends JFrame implements ActionListener { private JButton register; private JButton signIn; private JTextField username; private JPasswordField passwd; private JButton login; private JLabel usernameLabel; private JLabel passwdLabel; private JTextField usernameSign; private JPasswordField masterPasswd; private JTextField email; private JTextField name; private JTextField surname; private JButton ok; private JButton addPasswd; private JButton decryptPasswd; private JButton encryptPasswd; private JButton modifyPasswd; private JButton deletePasswd; private JButton ok2; private User user; private JPasswordField newPasswd; private JTextField domain; private final Image image = new ImageIcon(this.getClass().getResource("back.jpg")).getImage(); private final JLabel info = new JLabel(); public Gui() { initGui(); } public void initGui() { this.setSize(360, 200); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); setLayout(null); setContentPane(new JLabel(new ImageIcon(image))); setResizable(false); register = new JButton("Register"); signIn = new JButton("Sign In"); login = new JButton("Login"); username = new JTextField(); passwd = new JPasswordField(); usernameLabel = new JLabel("Username:"); passwdLabel = new JLabel("Password:"); usernameSign = new JTextField(); email = new JTextField(); masterPasswd = new JPasswordField(); name = new JTextField(); surname = new JTextField(); ok = new JButton("ok"); addPasswd = new JButton("Add Password"); decryptPasswd = new JButton("decrypt"); encryptPasswd = new JButton("encrypt"); modifyPasswd = new JButton("change"); deletePasswd = new JButton("delete"); newPasswd = new JPasswordField(); domain = new JTextField(); ok2 = new JButton("ok2"); this.add(register); this.add(signIn); this.add(login); this.add(username); this.add(passwd); this.add(passwdLabel); this.add(usernameLabel); this.add(email); this.add(usernameSign); this.add(masterPasswd); this.add(name); this.add(surname); this.add(ok); this.add(addPasswd); this.add(decryptPasswd); this.add(encryptPasswd); this.add(modifyPasswd); this.add(deletePasswd); this.add(newPasswd); this.add(domain); this.add(ok2); this.add(info); register.setVisible(true); signIn.setVisible(true); login.setVisible(false); username.setVisible(false); passwd.setVisible(false); usernameLabel.setVisible(false); passwdLabel.setVisible(false); email.setVisible(false); usernameSign.setVisible(false); masterPasswd.setVisible(false); name.setVisible(false); surname.setVisible(false); ok.setVisible(false); addPasswd.setVisible(false); decryptPasswd.setVisible(false); encryptPasswd.setVisible(false); modifyPasswd.setVisible(false); deletePasswd.setVisible(false); newPasswd.setVisible(false); domain.setVisible(false); info.setVisible(false); ok2.setVisible(false); email.setText("email"); usernameSign.setText("username"); domain.setText("domain"); newPasswd.setText("password"); masterPasswd.setText("master password"); name.setText("name"); surname.setText("surename"); register.setBounds(65, 48, 100, 60); signIn.setBounds(185, 48, 100, 60); login.setBounds(185, 48, 100, 60); username.setBounds(80, 48, 100, 30); passwd.setBounds(80, 80, 100, 30); usernameLabel.setBounds(0, 45, 90, 30); passwdLabel.setBounds(0, 77, 90, 30); email.setBounds(80, 15, 100, 30); usernameSign.setBounds(80, 45, 100, 30); masterPasswd.setBounds(80, 75, 100, 30); name.setBounds(80, 105, 100, 30); surname.setBounds(80, 135, 100, 30); ok.setBounds(185, 48, 165, 60); addPasswd.setBounds(80, 15, 100, 30); encryptPasswd.setBounds(80, 45, 100, 30); decryptPasswd.setBounds(80, 75, 100, 30); modifyPasswd.setBounds(80, 105, 100, 30); deletePasswd.setBounds(80, 135, 100, 30); newPasswd.setBounds(200, 46, 100, 30); domain.setBounds(200, 76, 100, 30); ok2.setBounds(300, 58, 80, 50); info.setBounds(250, 80, 100, 100); info.setBackground(Color.yellow); register.setBackground(Color.YELLOW); signIn.setBackground(Color.YELLOW); login.setBackground(Color.YELLOW); passwd.setBackground(Color.YELLOW); username.setBackground(Color.YELLOW); ok.setBackground(Color.YELLOW); newPasswd.setBackground(Color.YELLOW); domain.setBackground(Color.YELLOW); ok2.setBackground(Color.YELLOW); login.addActionListener(this); signIn.addActionListener(this); register.addActionListener(this); ok.addActionListener(this); addPasswd.addActionListener(this); ok2.addActionListener(this); this.decryptPasswd.addActionListener(this); this.encryptPasswd.addActionListener(this); this.modifyPasswd.addActionListener(this); this.deletePasswd.addActionListener(this); newPasswd.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent evt) { newPasswd.setText(""); } }); domain.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent evt) { domain.setText(""); } }); email.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent evt) { email.setText(""); } }); name.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent evt) { name.setText(""); } }); username.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent evt) { username.setText(""); } }); surname.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent evt) { surname.setText(""); } }); masterPasswd.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent evt) { masterPasswd.setText(""); } }); username.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent evt) { username.setText(""); } }); passwd.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent evt) { passwd.setText(""); } }); } public void initResgisterForm() { //εμφάνιση των καταλληλων component για την φόρμα εγγραφής register.setVisible(false); signIn.setVisible(false); email.setVisible(true); usernameSign.setVisible(true); masterPasswd.setVisible(true); name.setVisible(true); surname.setVisible(true); ok.setVisible(true); } public void initSignInForm() { //init login form register.setVisible(false); signIn.setVisible(false); usernameSign.setVisible(false); masterPasswd.setVisible(false); email.setVisible(false); name.setVisible(false); surname.setVisible(false); ok.setVisible(false); username.setVisible(true); passwd.setVisible(true); login.setVisible(true); passwdLabel.setVisible(true); usernameLabel.setVisible(true); } public void initMainAppFrame() { //init main menu after login addPasswd.setVisible(true); decryptPasswd.setVisible(true); encryptPasswd.setVisible(true); modifyPasswd.setVisible(true); deletePasswd.setVisible(true); username.setVisible(false); passwd.setVisible(false); login.setVisible(false); passwdLabel.setVisible(false); usernameLabel.setVisible(false); info.setVisible(true); } @Override public void actionPerformed(ActionEvent ae) { if (ae.getSource().equals(signIn)) { initSignInForm(); } if (ae.getSource().equals(register)) { initResgisterForm(); } if (ae.getSource().equals(login)) { try { if (PasswodManager.checkHash(username.getText(), passwd.getText())) { user = new User(username.getText(), passwd.getText(), EncryptionUtils.getsKey(passwd.getText(), username.getText())); initMainAppFrame(); } else { System.out.println("FAIL"); } } catch (NoSuchAlgorithmException ex) { Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidKeySpecException ex) { Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex); } } if (ae.getSource().equals(ok)) { try { User user = new User(name.getText(), surname.getText(), usernameSign.getText(), email.getText(), masterPasswd.getText()); PasswodManager.createAcc(user); initSignInForm(); } catch (Exception ex) { Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex); } } if (ae.getSource().equals(addPasswd)) { newPasswd.setVisible(true); domain.setVisible(true); ok2.setVisible(true); } if (ae.getSource().equals(ok2)) { try { PasswodManager.newPasswd(newPasswd.getText(), user, domain.getText()); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidKeySpecException ex) { Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex); } } if (ae.getSource().equals(this.encryptPasswd)) { domain.setVisible(true); ok2.setVisible(true); } if (ae.getSource().equals(this.decryptPasswd)) { domain.setVisible(true); ok2.setVisible(true); try { info.setText(PasswodManager.decryptPasswd(domain.getText(), user)); } catch (IOException ex) { Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex); } } if (ae.getSource().equals(this.deletePasswd)) { domain.setVisible(true); ok2.setVisible(true); try { PasswodManager.deletePasswd(domain.getText(), user); } catch (IOException ex) { Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex); } } if (ae.getSource().equals(this.modifyPasswd)) { domain.setVisible(true); ok2.setVisible(true); } } }
VineshChauhan24/PasswordManager
src/guis/Gui.java
3,127
//εμφάνιση των καταλληλων component για την φόρμα εγγραφής
line_comment
el
package guis; import main_program.EncryptionUtils; import main_program.PasswodManager; import main_program.User; import java.awt.Color; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.*; public class Gui extends JFrame implements ActionListener { private JButton register; private JButton signIn; private JTextField username; private JPasswordField passwd; private JButton login; private JLabel usernameLabel; private JLabel passwdLabel; private JTextField usernameSign; private JPasswordField masterPasswd; private JTextField email; private JTextField name; private JTextField surname; private JButton ok; private JButton addPasswd; private JButton decryptPasswd; private JButton encryptPasswd; private JButton modifyPasswd; private JButton deletePasswd; private JButton ok2; private User user; private JPasswordField newPasswd; private JTextField domain; private final Image image = new ImageIcon(this.getClass().getResource("back.jpg")).getImage(); private final JLabel info = new JLabel(); public Gui() { initGui(); } public void initGui() { this.setSize(360, 200); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); setLayout(null); setContentPane(new JLabel(new ImageIcon(image))); setResizable(false); register = new JButton("Register"); signIn = new JButton("Sign In"); login = new JButton("Login"); username = new JTextField(); passwd = new JPasswordField(); usernameLabel = new JLabel("Username:"); passwdLabel = new JLabel("Password:"); usernameSign = new JTextField(); email = new JTextField(); masterPasswd = new JPasswordField(); name = new JTextField(); surname = new JTextField(); ok = new JButton("ok"); addPasswd = new JButton("Add Password"); decryptPasswd = new JButton("decrypt"); encryptPasswd = new JButton("encrypt"); modifyPasswd = new JButton("change"); deletePasswd = new JButton("delete"); newPasswd = new JPasswordField(); domain = new JTextField(); ok2 = new JButton("ok2"); this.add(register); this.add(signIn); this.add(login); this.add(username); this.add(passwd); this.add(passwdLabel); this.add(usernameLabel); this.add(email); this.add(usernameSign); this.add(masterPasswd); this.add(name); this.add(surname); this.add(ok); this.add(addPasswd); this.add(decryptPasswd); this.add(encryptPasswd); this.add(modifyPasswd); this.add(deletePasswd); this.add(newPasswd); this.add(domain); this.add(ok2); this.add(info); register.setVisible(true); signIn.setVisible(true); login.setVisible(false); username.setVisible(false); passwd.setVisible(false); usernameLabel.setVisible(false); passwdLabel.setVisible(false); email.setVisible(false); usernameSign.setVisible(false); masterPasswd.setVisible(false); name.setVisible(false); surname.setVisible(false); ok.setVisible(false); addPasswd.setVisible(false); decryptPasswd.setVisible(false); encryptPasswd.setVisible(false); modifyPasswd.setVisible(false); deletePasswd.setVisible(false); newPasswd.setVisible(false); domain.setVisible(false); info.setVisible(false); ok2.setVisible(false); email.setText("email"); usernameSign.setText("username"); domain.setText("domain"); newPasswd.setText("password"); masterPasswd.setText("master password"); name.setText("name"); surname.setText("surename"); register.setBounds(65, 48, 100, 60); signIn.setBounds(185, 48, 100, 60); login.setBounds(185, 48, 100, 60); username.setBounds(80, 48, 100, 30); passwd.setBounds(80, 80, 100, 30); usernameLabel.setBounds(0, 45, 90, 30); passwdLabel.setBounds(0, 77, 90, 30); email.setBounds(80, 15, 100, 30); usernameSign.setBounds(80, 45, 100, 30); masterPasswd.setBounds(80, 75, 100, 30); name.setBounds(80, 105, 100, 30); surname.setBounds(80, 135, 100, 30); ok.setBounds(185, 48, 165, 60); addPasswd.setBounds(80, 15, 100, 30); encryptPasswd.setBounds(80, 45, 100, 30); decryptPasswd.setBounds(80, 75, 100, 30); modifyPasswd.setBounds(80, 105, 100, 30); deletePasswd.setBounds(80, 135, 100, 30); newPasswd.setBounds(200, 46, 100, 30); domain.setBounds(200, 76, 100, 30); ok2.setBounds(300, 58, 80, 50); info.setBounds(250, 80, 100, 100); info.setBackground(Color.yellow); register.setBackground(Color.YELLOW); signIn.setBackground(Color.YELLOW); login.setBackground(Color.YELLOW); passwd.setBackground(Color.YELLOW); username.setBackground(Color.YELLOW); ok.setBackground(Color.YELLOW); newPasswd.setBackground(Color.YELLOW); domain.setBackground(Color.YELLOW); ok2.setBackground(Color.YELLOW); login.addActionListener(this); signIn.addActionListener(this); register.addActionListener(this); ok.addActionListener(this); addPasswd.addActionListener(this); ok2.addActionListener(this); this.decryptPasswd.addActionListener(this); this.encryptPasswd.addActionListener(this); this.modifyPasswd.addActionListener(this); this.deletePasswd.addActionListener(this); newPasswd.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent evt) { newPasswd.setText(""); } }); domain.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent evt) { domain.setText(""); } }); email.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent evt) { email.setText(""); } }); name.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent evt) { name.setText(""); } }); username.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent evt) { username.setText(""); } }); surname.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent evt) { surname.setText(""); } }); masterPasswd.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent evt) { masterPasswd.setText(""); } }); username.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent evt) { username.setText(""); } }); passwd.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent evt) { passwd.setText(""); } }); } public void initResgisterForm() { //εμφάνιση των<SUF> register.setVisible(false); signIn.setVisible(false); email.setVisible(true); usernameSign.setVisible(true); masterPasswd.setVisible(true); name.setVisible(true); surname.setVisible(true); ok.setVisible(true); } public void initSignInForm() { //init login form register.setVisible(false); signIn.setVisible(false); usernameSign.setVisible(false); masterPasswd.setVisible(false); email.setVisible(false); name.setVisible(false); surname.setVisible(false); ok.setVisible(false); username.setVisible(true); passwd.setVisible(true); login.setVisible(true); passwdLabel.setVisible(true); usernameLabel.setVisible(true); } public void initMainAppFrame() { //init main menu after login addPasswd.setVisible(true); decryptPasswd.setVisible(true); encryptPasswd.setVisible(true); modifyPasswd.setVisible(true); deletePasswd.setVisible(true); username.setVisible(false); passwd.setVisible(false); login.setVisible(false); passwdLabel.setVisible(false); usernameLabel.setVisible(false); info.setVisible(true); } @Override public void actionPerformed(ActionEvent ae) { if (ae.getSource().equals(signIn)) { initSignInForm(); } if (ae.getSource().equals(register)) { initResgisterForm(); } if (ae.getSource().equals(login)) { try { if (PasswodManager.checkHash(username.getText(), passwd.getText())) { user = new User(username.getText(), passwd.getText(), EncryptionUtils.getsKey(passwd.getText(), username.getText())); initMainAppFrame(); } else { System.out.println("FAIL"); } } catch (NoSuchAlgorithmException ex) { Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidKeySpecException ex) { Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex); } } if (ae.getSource().equals(ok)) { try { User user = new User(name.getText(), surname.getText(), usernameSign.getText(), email.getText(), masterPasswd.getText()); PasswodManager.createAcc(user); initSignInForm(); } catch (Exception ex) { Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex); } } if (ae.getSource().equals(addPasswd)) { newPasswd.setVisible(true); domain.setVisible(true); ok2.setVisible(true); } if (ae.getSource().equals(ok2)) { try { PasswodManager.newPasswd(newPasswd.getText(), user, domain.getText()); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidKeySpecException ex) { Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex); } } if (ae.getSource().equals(this.encryptPasswd)) { domain.setVisible(true); ok2.setVisible(true); } if (ae.getSource().equals(this.decryptPasswd)) { domain.setVisible(true); ok2.setVisible(true); try { info.setText(PasswodManager.decryptPasswd(domain.getText(), user)); } catch (IOException ex) { Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex); } } if (ae.getSource().equals(this.deletePasswd)) { domain.setVisible(true); ok2.setVisible(true); try { PasswodManager.deletePasswd(domain.getText(), user); } catch (IOException ex) { Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex); } } if (ae.getSource().equals(this.modifyPasswd)) { domain.setVisible(true); ok2.setVisible(true); } } }
21375_0
package jin.class4; // [G4] 13172. Σ import java.io.*; import java.util.*; public class Σ { private static final long MOD = 1_000_000_007; public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); long m = Long.parseLong(br.readLine()); long result = 0; while (m-- > 0) { StringTokenizer st = new StringTokenizer(br.readLine()); long b = Long.parseLong(st.nextToken()); long a = Long.parseLong(st.nextToken()); long g = gcd(a, b); b /= g; a /= g; result += a * f(b, MOD - 2) % MOD; result %= MOD; } System.out.println(result); br.close(); } // 모듈러 거듭제곱 계산 private static long f(long x, long y) { if (y == 1) return x % MOD; if (y % 2 == 1) return x * f(x, y - 1) % MOD; long p = f(x, y / 2); return p * p % MOD; } // 최대공약수 계산 private static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } }
What-is-algorithm/java-algorithm
src/jin/class4/Σ.java
360
// [G4] 13172. Σ
line_comment
el
package jin.class4; // [G4] 13172.<SUF> import java.io.*; import java.util.*; public class Σ { private static final long MOD = 1_000_000_007; public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); long m = Long.parseLong(br.readLine()); long result = 0; while (m-- > 0) { StringTokenizer st = new StringTokenizer(br.readLine()); long b = Long.parseLong(st.nextToken()); long a = Long.parseLong(st.nextToken()); long g = gcd(a, b); b /= g; a /= g; result += a * f(b, MOD - 2) % MOD; result %= MOD; } System.out.println(result); br.close(); } // 모듈러 거듭제곱 계산 private static long f(long x, long y) { if (y == 1) return x % MOD; if (y % 2 == 1) return x * f(x, y - 1) % MOD; long p = f(x, y / 2); return p * p % MOD; } // 최대공약수 계산 private static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } }
332_8
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package basics; import static basics.HashMaps.allRoutes; import static basics.HashMaps.allStopTimes; import static basics.HashMaps.allStops; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractListModel; import javax.swing.DefaultListModel; import javax.swing.ListModel; import storage.DB; import storage.MainHelper; /** * * @author WottatoParrior */ public class SelectionForm extends javax.swing.JFrame { DefaultListModel datamodel ; public SelectionForm() { this.datamodel = new DefaultListModel(); initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jComboBox1 = new javax.swing.JComboBox<>(); jLabel1 = new javax.swing.JLabel(); stopName = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); stoplist = new javax.swing.JList<>(); jButton1 = new javax.swing.JButton(); jScrollPane3 = new javax.swing.JScrollPane(); stopInfo = new javax.swing.JTextArea(); jLabel2 = new javax.swing.JLabel(); Show = new javax.swing.JButton(); close = new javax.swing.JButton(); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel1.setText("Enter stop name"); stopName.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { stopNameActionPerformed(evt); } }); stoplist.setModel(datamodel); stoplist.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane1.setViewportView(stoplist); jButton1.setText("Search"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); stopInfo.setColumns(20); stopInfo.setRows(5); jScrollPane3.setViewportView(stopInfo); jLabel2.setText("Stops"); Show.setText("Show details"); Show.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ShowActionPerformed(evt); } }); close.setText("Close"); close.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(stopName) .addGroup(layout.createSequentialGroup() .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(34, 34, 34)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabel2) .addGap(145, 145, 145)))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Show, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(96, 96, 96))) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 357, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(337, 337, 337) .addComponent(close))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 292, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(29, 29, 29) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(stopName, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Show))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE) .addComponent(close, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: String UserInput = stopName.getText(); this.datamodel.removeAllElements(); DB.connect(); try { LinkedHashMap<String, String> found = DB.fetchFromDb(UserInput); for(String value : found.values()){ this.datamodel.addElement(value); } } catch (SQLException ex) { Logger.getLogger(SelectionForm.class.getName()).log(Level.SEVERE, null, ex); } stopName.setText(""); }//GEN-LAST:event_jButton1ActionPerformed private void stopNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopNameActionPerformed // TODO add your handling code here: }//GEN-LAST:event_stopNameActionPerformed private void ShowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ShowActionPerformed // TODO add your handling code here: String res =stoplist.getSelectedValue(); stopInfo.setText(""); String[] tokens= res.split("-"); // Παιρνω το κομματι που θελω try { ArrayList trips =DB.fetchFromDbInfo(tokens[0]); //Παιρνω το τριπ ID απο την επιλογη του χρηστη for(Object route : trips){ //Για καθε ενα τριπ παιρνω το αντιστοιχω route id String convertedToString = route.toString(); ArrayList<String> id = DB.fetchRoutes(convertedToString); for(String i :id){ String name = DB.showRoutes(i); //Για καθε route id παω στην βαση μου και παιρνω τα στοιχεια της στασης και τα εμφανιζω stopInfo.append(name + "\n"); } } } catch (SQLException ex) { Logger.getLogger(SelectionForm.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_ShowActionPerformed private void closeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeActionPerformed // TODO add your handling code here: dispose(); }//GEN-LAST:event_closeActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(SelectionForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(SelectionForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(SelectionForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(SelectionForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new SelectionForm().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton Show; private javax.swing.JButton close; private javax.swing.JButton jButton1; private javax.swing.JComboBox<String> jComboBox1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JTextArea stopInfo; private javax.swing.JTextField stopName; private javax.swing.JList<String> stoplist; // End of variables declaration//GEN-END:variables }
WottatoParrior/java-bus-app
src/basics/SelectionForm.java
2,943
//Παιρνω το τριπ ID απο την επιλογη του χρηστη
line_comment
el
/* * 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 basics; import static basics.HashMaps.allRoutes; import static basics.HashMaps.allStopTimes; import static basics.HashMaps.allStops; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractListModel; import javax.swing.DefaultListModel; import javax.swing.ListModel; import storage.DB; import storage.MainHelper; /** * * @author WottatoParrior */ public class SelectionForm extends javax.swing.JFrame { DefaultListModel datamodel ; public SelectionForm() { this.datamodel = new DefaultListModel(); initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jComboBox1 = new javax.swing.JComboBox<>(); jLabel1 = new javax.swing.JLabel(); stopName = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); stoplist = new javax.swing.JList<>(); jButton1 = new javax.swing.JButton(); jScrollPane3 = new javax.swing.JScrollPane(); stopInfo = new javax.swing.JTextArea(); jLabel2 = new javax.swing.JLabel(); Show = new javax.swing.JButton(); close = new javax.swing.JButton(); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel1.setText("Enter stop name"); stopName.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { stopNameActionPerformed(evt); } }); stoplist.setModel(datamodel); stoplist.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane1.setViewportView(stoplist); jButton1.setText("Search"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); stopInfo.setColumns(20); stopInfo.setRows(5); jScrollPane3.setViewportView(stopInfo); jLabel2.setText("Stops"); Show.setText("Show details"); Show.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ShowActionPerformed(evt); } }); close.setText("Close"); close.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(stopName) .addGroup(layout.createSequentialGroup() .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(34, 34, 34)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabel2) .addGap(145, 145, 145)))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Show, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(96, 96, 96))) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 357, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(337, 337, 337) .addComponent(close))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 292, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(29, 29, 29) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(stopName, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Show))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE) .addComponent(close, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: String UserInput = stopName.getText(); this.datamodel.removeAllElements(); DB.connect(); try { LinkedHashMap<String, String> found = DB.fetchFromDb(UserInput); for(String value : found.values()){ this.datamodel.addElement(value); } } catch (SQLException ex) { Logger.getLogger(SelectionForm.class.getName()).log(Level.SEVERE, null, ex); } stopName.setText(""); }//GEN-LAST:event_jButton1ActionPerformed private void stopNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopNameActionPerformed // TODO add your handling code here: }//GEN-LAST:event_stopNameActionPerformed private void ShowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ShowActionPerformed // TODO add your handling code here: String res =stoplist.getSelectedValue(); stopInfo.setText(""); String[] tokens= res.split("-"); // Παιρνω το κομματι που θελω try { ArrayList trips =DB.fetchFromDbInfo(tokens[0]); //Παιρνω το<SUF> for(Object route : trips){ //Για καθε ενα τριπ παιρνω το αντιστοιχω route id String convertedToString = route.toString(); ArrayList<String> id = DB.fetchRoutes(convertedToString); for(String i :id){ String name = DB.showRoutes(i); //Για καθε route id παω στην βαση μου και παιρνω τα στοιχεια της στασης και τα εμφανιζω stopInfo.append(name + "\n"); } } } catch (SQLException ex) { Logger.getLogger(SelectionForm.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_ShowActionPerformed private void closeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeActionPerformed // TODO add your handling code here: dispose(); }//GEN-LAST:event_closeActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(SelectionForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(SelectionForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(SelectionForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(SelectionForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new SelectionForm().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton Show; private javax.swing.JButton close; private javax.swing.JButton jButton1; private javax.swing.JComboBox<String> jComboBox1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JTextArea stopInfo; private javax.swing.JTextField stopName; private javax.swing.JList<String> stoplist; // End of variables declaration//GEN-END:variables }
17446_16
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; /** The Game Class initiates the start of the game * after gathering the resources needed (questions from file) * * **/ public class Game { // @field a questions object that keeps all the questions inside // The below parameters are used to complement the usage of the corresponding classes private final Questions questionsObj; private Player[] playersArr; private final Round[] roundsTypes; // A arraylist that contains all the types of rounds, in which other types of rounds can be added anytime; private final GUI_Main frame; /** * Default Constructor, Starts the GUI, asks the number of players * and creates rounds */ public Game() { questionsObj = new Questions(); readFileQuestions(); frame = new GUI_Main(questionsObj.getTypes()); frame.popupInfo(); setNumberOfPlayers(); //Single player allows only Right Answer, Bet and Stop The Timer if (playersArr.length==1) roundsTypes = new Round[]{ new RoundRightAnswer(questionsObj,frame,playersArr), new RoundStopTheTimer(questionsObj,frame,playersArr), new RoundBet(questionsObj,frame,playersArr) }; //Multiplayer allows all round types else roundsTypes = new Round[]{ new RoundRightAnswer(questionsObj,frame,playersArr), new RoundStopTheTimer(questionsObj,frame,playersArr), new RoundBet(questionsObj,frame,playersArr), new RoundQuickAnswer(questionsObj,frame,playersArr), new RoundThermometer(questionsObj,frame,playersArr) }; } /** * Starts the game */ void play() { int number_of_rounds = 6; //The number of rounds. Normally changeable but by default is 6 for (int i = 0; i < number_of_rounds; i++) { frame.changeRoundCount(i+1); Round currentRoundObj = roundsTypes[Utilities.random_int(roundsTypes.length)]; //A round can have a random type currentRoundObj.playRound(); //Play that corresponding round (override) } //Checks who has won, prints results and terminates //Utilities.whoWon(playersArr); frame.exitFrame(0); } /** * This method ask with a popup the number of players */ void setNumberOfPlayers() { int numberOfPlayers = frame.popupAskNumberOfPlayer(2); playersArr = new Player[numberOfPlayers]; char[][] acceptable_responses = new char[numberOfPlayers][4]; acceptable_responses[0] = new char[]{'Q','W','E','R'}; if (playersArr.length>1) { acceptable_responses[1] = new char[]{'1','2','3','4'}; //Further response keys for more players can be added here } //Creates each player's response keys for (int i=0; i<numberOfPlayers; i++) { playersArr[i] = new Player("Player " + i, acceptable_responses[i]); playersArr[i] = new Player(frame.popupGetPlayerName(i+1), acceptable_responses[i]); } //Show the players into the frame frame.drawPlayersInfoToGUI(playersArr); } /** * reads the questions from a .tsv(tab separated values) file. * Κατηγορία(TAB)Ερώτηση(TAB)Απάντηση 1(TAB)Απάντηση 2(TAB)Απάντηση 3(TAB)Απάντηση 4(TAB)Σωστή απάντηση(TAB)Όνομα εικόνας */ private void readFileQuestions() { String fileName = "packageQuestions/quiz.tsv"; InputStream f = getClass().getResourceAsStream(fileName); try (BufferedReader reader = new BufferedReader(new InputStreamReader(f))) { final int index_type = 0; final int index_question = 1; final int index_resp_start = 2; final int index_resp_finish = 5; final int index_resp_correct = 6; final int index_image_src = 7; String line; while ((line = reader.readLine()) != null) { // for every line in the file String[] lineItems = line.split("\t"); //splitting the line and adding its items in String[] int correct_pos = 0; ArrayList<String> responses = new ArrayList<>(4); // add the responses for (int i = index_resp_start; i <= index_resp_finish; i++) { responses.add(lineItems[i]); if (lineItems[index_resp_correct].equals(lineItems[i])) { correct_pos = i - index_resp_start; } } if (0 != correct_pos) { // The correct response isn't at pos 0 because the person who wrote the question doesnt know what standards mean //System.out.println("The correct response isn't at pos 0 : '" + lineItems[index_question] + "' "); Collections.swap(responses, correct_pos, 0); // Move the correct response at pos 1 } if (lineItems[index_type].equals("Random")) { System.out.println("The CATEGORY of question '" + lineItems[index_question] + "' CAN NOT BE 'Random'!\n"); System.exit(-1); } if (lineItems[index_image_src].equals("NoImage")) questionsObj.addQuestion(lineItems[index_type], lineItems[index_question], responses); else questionsObj.addQuestionImage(lineItems[index_type], lineItems[index_question], responses,lineItems[index_image_src]); } } catch (Exception e) { System.out.println("Something went wrong when trying to read the .tsv file."); e.printStackTrace(); System.exit(-1); } } }
XG-PRO/Buzz-Quiz-World-JAVA
src/Game.java
1,430
/** * reads the questions from a .tsv(tab separated values) file. * Κατηγορία(TAB)Ερώτηση(TAB)Απάντηση 1(TAB)Απάντηση 2(TAB)Απάντηση 3(TAB)Απάντηση 4(TAB)Σωστή απάντηση(TAB)Όνομα εικόνας */
block_comment
el
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; /** The Game Class initiates the start of the game * after gathering the resources needed (questions from file) * * **/ public class Game { // @field a questions object that keeps all the questions inside // The below parameters are used to complement the usage of the corresponding classes private final Questions questionsObj; private Player[] playersArr; private final Round[] roundsTypes; // A arraylist that contains all the types of rounds, in which other types of rounds can be added anytime; private final GUI_Main frame; /** * Default Constructor, Starts the GUI, asks the number of players * and creates rounds */ public Game() { questionsObj = new Questions(); readFileQuestions(); frame = new GUI_Main(questionsObj.getTypes()); frame.popupInfo(); setNumberOfPlayers(); //Single player allows only Right Answer, Bet and Stop The Timer if (playersArr.length==1) roundsTypes = new Round[]{ new RoundRightAnswer(questionsObj,frame,playersArr), new RoundStopTheTimer(questionsObj,frame,playersArr), new RoundBet(questionsObj,frame,playersArr) }; //Multiplayer allows all round types else roundsTypes = new Round[]{ new RoundRightAnswer(questionsObj,frame,playersArr), new RoundStopTheTimer(questionsObj,frame,playersArr), new RoundBet(questionsObj,frame,playersArr), new RoundQuickAnswer(questionsObj,frame,playersArr), new RoundThermometer(questionsObj,frame,playersArr) }; } /** * Starts the game */ void play() { int number_of_rounds = 6; //The number of rounds. Normally changeable but by default is 6 for (int i = 0; i < number_of_rounds; i++) { frame.changeRoundCount(i+1); Round currentRoundObj = roundsTypes[Utilities.random_int(roundsTypes.length)]; //A round can have a random type currentRoundObj.playRound(); //Play that corresponding round (override) } //Checks who has won, prints results and terminates //Utilities.whoWon(playersArr); frame.exitFrame(0); } /** * This method ask with a popup the number of players */ void setNumberOfPlayers() { int numberOfPlayers = frame.popupAskNumberOfPlayer(2); playersArr = new Player[numberOfPlayers]; char[][] acceptable_responses = new char[numberOfPlayers][4]; acceptable_responses[0] = new char[]{'Q','W','E','R'}; if (playersArr.length>1) { acceptable_responses[1] = new char[]{'1','2','3','4'}; //Further response keys for more players can be added here } //Creates each player's response keys for (int i=0; i<numberOfPlayers; i++) { playersArr[i] = new Player("Player " + i, acceptable_responses[i]); playersArr[i] = new Player(frame.popupGetPlayerName(i+1), acceptable_responses[i]); } //Show the players into the frame frame.drawPlayersInfoToGUI(playersArr); } /** * reads the questions<SUF>*/ private void readFileQuestions() { String fileName = "packageQuestions/quiz.tsv"; InputStream f = getClass().getResourceAsStream(fileName); try (BufferedReader reader = new BufferedReader(new InputStreamReader(f))) { final int index_type = 0; final int index_question = 1; final int index_resp_start = 2; final int index_resp_finish = 5; final int index_resp_correct = 6; final int index_image_src = 7; String line; while ((line = reader.readLine()) != null) { // for every line in the file String[] lineItems = line.split("\t"); //splitting the line and adding its items in String[] int correct_pos = 0; ArrayList<String> responses = new ArrayList<>(4); // add the responses for (int i = index_resp_start; i <= index_resp_finish; i++) { responses.add(lineItems[i]); if (lineItems[index_resp_correct].equals(lineItems[i])) { correct_pos = i - index_resp_start; } } if (0 != correct_pos) { // The correct response isn't at pos 0 because the person who wrote the question doesnt know what standards mean //System.out.println("The correct response isn't at pos 0 : '" + lineItems[index_question] + "' "); Collections.swap(responses, correct_pos, 0); // Move the correct response at pos 1 } if (lineItems[index_type].equals("Random")) { System.out.println("The CATEGORY of question '" + lineItems[index_question] + "' CAN NOT BE 'Random'!\n"); System.exit(-1); } if (lineItems[index_image_src].equals("NoImage")) questionsObj.addQuestion(lineItems[index_type], lineItems[index_question], responses); else questionsObj.addQuestionImage(lineItems[index_type], lineItems[index_question], responses,lineItems[index_image_src]); } } catch (Exception e) { System.out.println("Something went wrong when trying to read the .tsv file."); e.printStackTrace(); System.exit(-1); } } }
1504_0
import java.util.ArrayList; import java.util.Scanner; public class AddressBook { private ArrayList<Contact> contacts; private Scanner scanner; public AddressBook() { contacts = new ArrayList<>(); scanner = new Scanner(System.in); } public void start() { loadSampleContacts(); // Φορτώνει ενδεικτικές επαφές int choice; do { displayMenu(); choice = getUserChoice(); processUserChoice(choice); } while (choice != 7); } private void displayMenu() { System.out.println("Μενού επιλογών:"); System.out.println("1. Προβολή όλων των επαφών"); System.out.println("2. Προσθήκη νέας επαφής"); System.out.println("3. Αναζήτηση επαφής βάσει ονόματος"); System.out.println("4. Αναζήτηση επαφής βάσει τηλεφώνου"); System.out.println("5. Επεξεργασία επαφής βάσει ονόματος"); System.out.println("6. Διαγραφή επαφής βάσει ονόματος"); System.out.println("7. Έξοδος από την εφαρμογή"); System.out.print("Επιλέξτε μια επιλογή: "); } private int getUserChoice() { int choice; try { choice = scanner.nextInt(); } catch (Exception e) { choice = -1; } finally { scanner.nextLine(); } return choice; } private void processUserChoice(int choice) { System.out.println(); switch (choice) { case 1: displayAllContacts(); break; case 2: addNewContact(); break; case 3: searchContactByName(); break; case 4: searchContactByPhone(); break; case 5: editContact(); break; case 6: deleteContact(); break; case 7: System.out.println("Αποχώρηση από την εφαρμογή. Αντίο!"); break; default: System.out.println("Μη έγκυρη επιλογή. Παρακαλώ προσπαθήστε ξανά."); break; } System.out.println(); } private void displayAllContacts() { if (contacts.isEmpty()) { System.out.println("Δεν υπάρχουν αποθηκευμένες επαφές."); } else { System.out.println("Αποθηκευμένες επαφές:"); for (Contact contact : contacts) { System.out.println("Όνομα: " + contact.getName()); System.out.println("Τηλέφωνο: " + contact.getPhone()); System.out.println("Email: " + contact.getEmail()); System.out.println("Διεύθυνση: " + contact.getAddress()); System.out.println("-------------------------"); } } } private void addNewContact() { System.out.print("Όνομα: "); String name = scanner.nextLine(); System.out.print("Τηλέφωνο: "); String phone = scanner.nextLine(); System.out.print("Email: "); String email = scanner.nextLine(); System.out.print("Διεύθυνση: "); String address = scanner.nextLine(); Contact newContact = new Contact(name, phone, email, address); contacts.add(newContact); System.out.println("Η επαφή προστέθηκε επιτυχώς."); } private void searchContactByName() { System.out.print("Εισαγάγετε το όνομα που αναζητάτε: "); String name = scanner.nextLine(); boolean found = false; for (Contact contact : contacts) { if (contact.getName().equalsIgnoreCase(name)) { displayContactInfo(contact); found = true; break; } } if (!found) { System.out.println("Δεν βρέθηκε επαφή με το όνομα \"" + name + "\"."); } } private void searchContactByPhone() { System.out.print("Εισαγάγετε το τηλέφωνο που αναζητάτε: "); String phone = scanner.nextLine(); boolean found = false; for (Contact contact : contacts) { if (contact.getPhone().equals(phone)) { displayContactInfo(contact); found = true; break; } } if (!found) { System.out.println("Δεν βρέθηκε επαφή με το τηλέφωνο \"" + phone + "\"."); } } private void editContact() { System.out.print("Εισαγάγετε το όνομα της επαφής προς επεξεργασία: "); String name = scanner.nextLine(); boolean found = false; for (Contact contact : contacts) { if (contact.getName().equalsIgnoreCase(name)) { displayContactInfo(contact); System.out.println("Εισαγάγετε τα νέα στοιχεία:"); System.out.print("Όνομα: "); String newName = scanner.nextLine(); System.out.print("Τηλέφωνο: "); String newPhone = scanner.nextLine(); System.out.print("Email: "); String newEmail = scanner.nextLine(); System.out.print("Διεύθυνση: "); String newAddress = scanner.nextLine(); contact.setName(newName); contact.setPhone(newPhone); contact.setEmail(newEmail); contact.setAddress(newAddress); System.out.println("Η επαφή ενημερώθηκε επιτυχώς."); found = true; break; } } if (!found) { System.out.println("Δεν βρέθηκε επαφή με το όνομα \"" + name + "\"."); } } private void deleteContact() { System.out.print("Εισαγάγετε το όνομα της επαφής προς διαγραφή: "); String name = scanner.nextLine(); boolean found = false; for (Contact contact : contacts) { if (contact.getName().equalsIgnoreCase(name)) { displayContactInfo(contact); System.out.print("Είστε βέβαιος ότι θέλετε να διαγράψετε αυτήν την επαφή; (Ν/Ο): "); String confirmation = scanner.nextLine(); if (confirmation.equalsIgnoreCase("Ν")) { contacts.remove(contact); System.out.println("Η επαφή διαγράφηκε επιτυχώς."); } else { System.out.println("Η διαγραφή ακυρώθηκε."); } found = true; break; } } if (!found) { System.out.println("Δεν βρέθηκε επαφή με το όνομα \"" + name + "\"."); } } private void displayContactInfo(Contact contact) { System.out.println("Όνομα: " + contact.getName()); System.out.println("Τηλέφωνο: " + contact.getPhone()); System.out.println("Email: " + contact.getEmail()); System.out.println("Διεύθυνση: " + contact.getAddress()); System.out.println("-------------------------"); } private void loadSampleContacts() { Contact contact1 = new Contact("Γιάννης", "1234567890", "[email protected]", "Αθήνα"); Contact contact2 = new Contact("Μαρία", "9876543210", "[email protected]", "Θεσσαλονίκη"); Contact contact3 = new Contact("Πέτρος", "5555555555", "[email protected]", "Πάτρα"); contacts.add(contact1); contacts.add(contact2); contacts.add(contact3); } }
XristosKak/Contact_Book_Java_Console_Application-
src/AddressBook.java
2,358
// Φορτώνει ενδεικτικές επαφές
line_comment
el
import java.util.ArrayList; import java.util.Scanner; public class AddressBook { private ArrayList<Contact> contacts; private Scanner scanner; public AddressBook() { contacts = new ArrayList<>(); scanner = new Scanner(System.in); } public void start() { loadSampleContacts(); // Φορτώνει ενδεικτικές<SUF> int choice; do { displayMenu(); choice = getUserChoice(); processUserChoice(choice); } while (choice != 7); } private void displayMenu() { System.out.println("Μενού επιλογών:"); System.out.println("1. Προβολή όλων των επαφών"); System.out.println("2. Προσθήκη νέας επαφής"); System.out.println("3. Αναζήτηση επαφής βάσει ονόματος"); System.out.println("4. Αναζήτηση επαφής βάσει τηλεφώνου"); System.out.println("5. Επεξεργασία επαφής βάσει ονόματος"); System.out.println("6. Διαγραφή επαφής βάσει ονόματος"); System.out.println("7. Έξοδος από την εφαρμογή"); System.out.print("Επιλέξτε μια επιλογή: "); } private int getUserChoice() { int choice; try { choice = scanner.nextInt(); } catch (Exception e) { choice = -1; } finally { scanner.nextLine(); } return choice; } private void processUserChoice(int choice) { System.out.println(); switch (choice) { case 1: displayAllContacts(); break; case 2: addNewContact(); break; case 3: searchContactByName(); break; case 4: searchContactByPhone(); break; case 5: editContact(); break; case 6: deleteContact(); break; case 7: System.out.println("Αποχώρηση από την εφαρμογή. Αντίο!"); break; default: System.out.println("Μη έγκυρη επιλογή. Παρακαλώ προσπαθήστε ξανά."); break; } System.out.println(); } private void displayAllContacts() { if (contacts.isEmpty()) { System.out.println("Δεν υπάρχουν αποθηκευμένες επαφές."); } else { System.out.println("Αποθηκευμένες επαφές:"); for (Contact contact : contacts) { System.out.println("Όνομα: " + contact.getName()); System.out.println("Τηλέφωνο: " + contact.getPhone()); System.out.println("Email: " + contact.getEmail()); System.out.println("Διεύθυνση: " + contact.getAddress()); System.out.println("-------------------------"); } } } private void addNewContact() { System.out.print("Όνομα: "); String name = scanner.nextLine(); System.out.print("Τηλέφωνο: "); String phone = scanner.nextLine(); System.out.print("Email: "); String email = scanner.nextLine(); System.out.print("Διεύθυνση: "); String address = scanner.nextLine(); Contact newContact = new Contact(name, phone, email, address); contacts.add(newContact); System.out.println("Η επαφή προστέθηκε επιτυχώς."); } private void searchContactByName() { System.out.print("Εισαγάγετε το όνομα που αναζητάτε: "); String name = scanner.nextLine(); boolean found = false; for (Contact contact : contacts) { if (contact.getName().equalsIgnoreCase(name)) { displayContactInfo(contact); found = true; break; } } if (!found) { System.out.println("Δεν βρέθηκε επαφή με το όνομα \"" + name + "\"."); } } private void searchContactByPhone() { System.out.print("Εισαγάγετε το τηλέφωνο που αναζητάτε: "); String phone = scanner.nextLine(); boolean found = false; for (Contact contact : contacts) { if (contact.getPhone().equals(phone)) { displayContactInfo(contact); found = true; break; } } if (!found) { System.out.println("Δεν βρέθηκε επαφή με το τηλέφωνο \"" + phone + "\"."); } } private void editContact() { System.out.print("Εισαγάγετε το όνομα της επαφής προς επεξεργασία: "); String name = scanner.nextLine(); boolean found = false; for (Contact contact : contacts) { if (contact.getName().equalsIgnoreCase(name)) { displayContactInfo(contact); System.out.println("Εισαγάγετε τα νέα στοιχεία:"); System.out.print("Όνομα: "); String newName = scanner.nextLine(); System.out.print("Τηλέφωνο: "); String newPhone = scanner.nextLine(); System.out.print("Email: "); String newEmail = scanner.nextLine(); System.out.print("Διεύθυνση: "); String newAddress = scanner.nextLine(); contact.setName(newName); contact.setPhone(newPhone); contact.setEmail(newEmail); contact.setAddress(newAddress); System.out.println("Η επαφή ενημερώθηκε επιτυχώς."); found = true; break; } } if (!found) { System.out.println("Δεν βρέθηκε επαφή με το όνομα \"" + name + "\"."); } } private void deleteContact() { System.out.print("Εισαγάγετε το όνομα της επαφής προς διαγραφή: "); String name = scanner.nextLine(); boolean found = false; for (Contact contact : contacts) { if (contact.getName().equalsIgnoreCase(name)) { displayContactInfo(contact); System.out.print("Είστε βέβαιος ότι θέλετε να διαγράψετε αυτήν την επαφή; (Ν/Ο): "); String confirmation = scanner.nextLine(); if (confirmation.equalsIgnoreCase("Ν")) { contacts.remove(contact); System.out.println("Η επαφή διαγράφηκε επιτυχώς."); } else { System.out.println("Η διαγραφή ακυρώθηκε."); } found = true; break; } } if (!found) { System.out.println("Δεν βρέθηκε επαφή με το όνομα \"" + name + "\"."); } } private void displayContactInfo(Contact contact) { System.out.println("Όνομα: " + contact.getName()); System.out.println("Τηλέφωνο: " + contact.getPhone()); System.out.println("Email: " + contact.getEmail()); System.out.println("Διεύθυνση: " + contact.getAddress()); System.out.println("-------------------------"); } private void loadSampleContacts() { Contact contact1 = new Contact("Γιάννης", "1234567890", "[email protected]", "Αθήνα"); Contact contact2 = new Contact("Μαρία", "9876543210", "[email protected]", "Θεσσαλονίκη"); Contact contact3 = new Contact("Πέτρος", "5555555555", "[email protected]", "Πάτρα"); contacts.add(contact1); contacts.add(contact2); contacts.add(contact3); } }
20498_39
package DD_phonemic; /** * @author: Antrei Kavros and Yannis Tzitzikas * See more: * https://www.cambridge.org/core/journals/natural-language-engineering/article/soundexgr-an-algorithm-for-phonetic-matching-for-the-greek-language/9C27059E8EA86C6F49FB2A02D41894CD */ public class SoundexGRExtra { public static int LengthEncoding = 4; // the length of the code to be produced (default = 4) /** * @param c, the character to be checked, if is in the "strong" (ηχηρά) * category of Greek Letters * @return true, if is in the category, false otherwise */ private static boolean isStrong(char c) { // check if ηχηρό. boolean tmp; switch (c) { case 'γ': case 'β': case 'δ': case 'α': // χρειάζεται; case 'λ': case 'μ': case 'ν': case 'ρ': case 'ζ': // ΥΤΖ (May 5, 2020) tmp = true; break; default: tmp = false; break; } return tmp; } /** * @param c, the character to be checked, if is in the "aecho" (αήχα) * category of Greek Letters * @return true, if is in the category, false otherwise */ private static boolean isAecho(char c) { // check if αηχο boolean tmp; switch (c) { case 'π': case 'τ': case 'κ': case 'φ': case 'θ': case 'σ': case 'χ': case 'ξ': tmp = true; break; default: tmp = false; break; } return tmp; } /** * * @param c, the character to be checked, if it is a vowel. * @return true if @param is a vowel, false otherwise */ private static boolean isVowel(char c) { // check if vowel boolean tmp; switch (c) { case 'ά': case 'α': case 'ε': case 'έ': case 'η': case 'ή': case 'ι': case 'ί': case 'ϊ': case 'ΐ': case 'ό': case 'ο': case 'υ': case 'ύ': case 'ϋ': case 'ΰ': case 'ω': case 'ώ': tmp = true; break; default: tmp = false; break; } return tmp; } /** * * @param c, the character to be checked if, it is Greek letters 'A' or 'E * @return true if is A or E */ private static boolean isAorE(char c) { // check if word is α or e boolean tmp; switch (c) { // ά , έ are included if there is an error to the intonation case 'ά': case 'α': case 'ε': case 'έ': tmp = true; break; default: tmp = false; break; } return tmp; } /** * * @param word, a string to be trimmed from its suffix * @return the modified string if applicable, or the @param */ private static String removeLast(String word) { //suffix removal if (word.length() > 2) { char[] tmp = word.toCharArray(); int counter = 0; if (tmp[tmp.length - 1] != 'ν' || tmp[tmp.length - 1] != 'ς' || tmp[tmp.length - 1] != 'σ') { tmp[tmp.length - 1] = 'ο'; } int i = tmp.length - 1; while (i >= 0 && isVowel(tmp[i])) { tmp[i] = 'o'; counter++; i--; } counter--; return new String(tmp); } else { return word; } } /** * * @param word, a string to be trimmed from its suffix only letters 'σ', 'ς' * and 'ν' * @return the modified string if applicable, or the @param */ private static String removeLastStrict(String word) { if (word.length() > 2) { char[] tmp = word.toCharArray(); if (tmp[tmp.length - 1] == 'ν' || tmp[tmp.length - 1] == 'ς' || tmp[tmp.length - 1] == 'σ') { word = word.substring(0, word.length() - 1); } } return word; } /** * * @param word, a string to be modified, based on vowel digram combinations, * that when combined, produce a different sound.E.g 'αι' => 'ε' * @return the modified @param if applicable, or the original @param * otherwise */ private static String groupVowels(String word) { // remove group vowels if necessary to single ones char[] tmp = word.toCharArray(); int counter = 0; for (int i = 0; i < tmp.length; i++) { switch (tmp[i]) { case 'ό': tmp[i] = 'ο'; break; case 'ο': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'υ') { tmp[i] = 'ο'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ύ') { tmp[i] = 'ο'; tmp[i + 1] = ' '; } } else { tmp[i] = 'ο'; } break; case 'έ': tmp[i] = 'ε'; break; case 'ε': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } } else { tmp[i] = 'ε'; } break; case 'ά': tmp[i] = 'α'; break; case 'α': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ε'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ε'; tmp[i + 1] = ' '; } } else { tmp[i] = 'α'; } break; case 'ί': case 'ή': case 'ύ': case 'ι': case 'η': case 'υ': case 'ϋ': case 'ΰ': case 'ϊ': case 'ΐ': tmp[i] = 'ι'; break; case 'ώ': tmp[i] = 'ο'; break; case 'ω': tmp[i] = 'ο'; break; } } for (int i = 0; i < tmp.length; i++) { if (tmp[i] == ' ') { if (i + 1 < tmp.length) { tmp[i] = tmp[i + 1]; tmp[i + 1] = ' '; counter++; } } } return new String(tmp); } /** * This methods is not used by Soundex. * It is used only for the production of the phonetic transcription. * @param word, a string to be modified, based on vowel digram combinations, * that when combined, produce a different sound.E.g 'αι' => 'ε' * * @return the modified @param if applicable, or the original @param * otherwise */ private static String groupVowelsPhonetically(String word) { // remove group vowels if necessary to single ones char[] tmp = word.toCharArray(); int counter = 0; for (int i = 0; i < tmp.length; i++) { switch (tmp[i]) { case 'ό': tmp[i] = 'ο'; break; case 'ο': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'υ') { tmp[i] = 'u'; // this is the difference with the SoundexGR tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ύ') { tmp[i] = 'u'; // this is the difference with the SoundexGR tmp[i + 1] = ' '; } } else { tmp[i] = 'ο'; } break; case 'έ': tmp[i] = 'ε'; break; case 'ε': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } } else { tmp[i] = 'ε'; } break; case 'ά': tmp[i] = 'α'; break; case 'α': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ε'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ε'; tmp[i + 1] = ' '; } } else { tmp[i] = 'α'; } break; case 'ί': case 'ή': case 'ύ': case 'ι': case 'η': case 'υ': case 'ϋ': case 'ΰ': case 'ϊ': case 'ΐ': tmp[i] = 'ι'; break; case 'ώ': tmp[i] = 'ο'; break; case 'ω': tmp[i] = 'ο'; break; } } for (int i = 0; i < tmp.length; i++) { if (tmp[i] == ' ') { if (i + 1 < tmp.length) { tmp[i] = tmp[i + 1]; tmp[i + 1] = ' '; counter++; } } } return new String(tmp); } /** * * @param word, a string from which the intonation is to be removed. * @return a string without intonation */ private static String removeIntonation(String word){ char[] tmp = word.toCharArray(); for (int i = 0; i < tmp.length; i++) { switch(tmp[i]){ case 'ά': tmp[i]='α'; break; case 'έ': tmp[i]='ε'; break; case 'ό': tmp[i]='ο'; break; case 'ή': tmp[i]='η'; break; case 'ί': tmp[i]='ι'; break; case 'ύ': tmp[i]='υ'; break; case 'ώ': tmp[i]='ω'; break; case 'ΐ': tmp[i]='ι'; break; case 'ϊ': tmp[i]='ι'; break; case 'ΰ': tmp[i]='υ'; break; case 'ϋ': tmp[i]='υ'; break; default: break; } } return new String(tmp); } /** * * @param word, a string to be modified, based on vowel digram combinations, * that when combined, produce a different sound, that is considered a * consonant.E.g 'αυτος' => 'αφτος' * @return the modified @param if applicable, the original @param otherwise */ private static String getVowelAsConsonant(String word) { // Check if a letter contains αυ , ευ and check if the next letter corresponds to a rule char[] tmp = word.toCharArray(); for (int i = 0; i < tmp.length; i++) { if ((tmp[i] == 'υ' || tmp[i] == 'ύ') && (i - 1 >= 0 && isAorE(tmp[i - 1]))) { if ((i + 1) < tmp.length && isAecho(tmp[i + 1])) { tmp[i] = 'φ'; } else if ((i + 1) < tmp.length && (i + 1 < tmp.length && (isVowel(tmp[i + 1]) || isStrong(tmp[i + 1])))) { tmp[i] = 'β'; } if (i == tmp.length - 1) { tmp[i] = 'φ'; } } } return new String(tmp); } /** * * @param word, a string to be modified if it contains specific consonant * digram combinations * @return the modified string */ private static String unwrapConsonantBigrams(String word) { // Reason for example of μπ -> b and not -> β , is that vowels as consonant operation follows and may // wrongly change to a consonant word = word.replace("μπ", "b"); word = word.replace("ντ", "d"); word = word.replace("γκ", "g"); word = word.replace("γγ", "g"); word = word.replace("τσ", "c"); word = word.replace("τζ", "c"); word = word.replace("πς", "ψ"); word = word.replace("πσ", "ψ"); word = word.replace("κς", "ξ"); word = word.replace("κσ", "ξ"); return word; } /** * * Version for the exact phonetic transcription * @param word, a string to be modified if it contains specific consonant * digram combinations * @return the modified string */ private static String unwrapConsonantBigramsPhonetically(String word) { // Reason for example of μπ -> b and not -> β , is that vowels as consonant operation follows and may // wrongly change to a consonant word = word.replace("μπ", "b"); word = word.replace("ντ", "d"); word = word.replace("γκ", "g"); word = word.replace("γγ", "g"); word = word.replace("τσ", "ts"); // different than plain (in soundex: c) word = word.replace("τζ", "dz"); // different than plain (in soundex: c) word = word.replace("πς", "ψ"); word = word.replace("πσ", "ψ"); word = word.replace("κς", "ξ"); word = word.replace("κσ", "ξ"); return word; } /** * * @param word, word to be encode through this Soundex implementation * @return an encoded word */ public static String encode(String word) { //The following function calls could be merged together in to one loop for better performance word = word.toLowerCase(); // word to lowercase word = unwrapConsonantBigrams(word); // αφαίρεση δίφθογγων - dual letter substitution to single //System.out.println(word + " (after unwrapConsonantBigrams)"); word = getVowelAsConsonant(word); // μετατροπή ευ, αυ σε σύμφωνο , αν ακολουθεί κάποιο άηχο ή ηχηρό γράμμα - substitution of υ vowel to consonant if needed //System.out.println(" " + word + " (after getVoelsAsConsonants)"); // removeLast and removeLastStrict or almost useless, now that the word is trimmed to just 6 digits word = removeLastStrict(word); // αφαίρεση του suffix της λέξης - suffix removal //System.out.println(" " + word + " (after getLastStrict)"); word = groupVowels(word); // μετατροπή φωνήεντων πχ αι σε ε - substitute group vowels to single vowel. //System.out.println(" " + word + " (after groupVowels)"); word = removeIntonation(word); //System.out.println(" " + word + " (after removeIntonation)"); word = String.join("", word.split(" ")); char[] givenWord = word.toCharArray(); char[] res = new char[givenWord.length]; int i = 1; res[0] = word.charAt(0); givenWord = word.substring(i).toCharArray(); for (char c : givenWord) { switch (c) { case 'β': case 'b': case 'φ': case 'π': res[i] = '1'; break; case 'γ': case 'χ': res[i] = '2'; break; case 'δ': case 'τ': case 'd': case 'θ': res[i] = '3'; break; case 'ζ': case 'σ': case 'ς': case 'ψ': case 'c': case 'ξ': res[i] = '4'; break; case 'κ': case 'g': res[i] = '5'; break; case 'λ': res[i] = '6'; break; case 'μ': case 'ν': res[i] = '7'; break; case 'ρ': res[i] = '8'; break; case 'α': res[i] = '9'; break; case 'ε': res[i] = '*'; break; case 'ο': case 'ω': res[i] = '$'; break; case 'ι': res[i] = '@'; break; default: res[i] = '0'; break; } i++; } //for (int z=0; z<res.length;z++) // System.out.print(res[z]); //System.out.println(" (after encode)"); String finalResult = ""; // Remove duplicates finalResult += res[0]; for (i = 1; i < res.length; i++) { if (res[i] != '0') { if (res[i] != res[i - 1]) { finalResult += res[i]; } } } //for (int z=0; z<res.length;z++) // System.out.print(res[z]); //System.out.println(" (after remove duplicates)"); //finalResult += "00000000"; finalResult += "00000000000000000000"; // needed only in the case the lenth of the code is big return finalResult.substring(0, LengthEncoding); // 4 letter length encoding } /** * It is a variation of the SoundexGR for returning a kind of phonetic transcription of the entire word * @param word, word to be encode * @return phonetic transcription of the word */ public static String phoneticTrascription(String word) { word = word.toLowerCase(); // word to lowercase //word = unwrapConsonantBigrams(word); // αφαίρεση δίφθογγων - dual letter substitution to single word = unwrapConsonantBigramsPhonetically(word); // NEW //System.out.println(word + " (after unwrapConsonantBigrams Phonetically)"); word = getVowelAsConsonant(word); // μετατροπή ευ, αυ σε σύμφωνο , αν ακολουθεί κάποιο άηχο ή ηχηρό γράμμα - substitution of υ vowel to consonant if needed //System.out.println(" " + word + " (after getVoelsAsConsonants)"); // removeLast and removeLastStrict or almost useless, now that the word is trimmed to just 6 digits //word = removeLastStrict(word); // αφαίρεση του suffix της λέξης - suffix removal //System.out.println(" " + word + " (after getLastStrict)"); //word = groupVowels(word); // μετατροπή φωνήεντων πχ αι σε ε - substitute group vowels to single vowel. word = groupVowelsPhonetically(word); // NEW //System.out.println(" " + word + " (after groupVowels phonetically)"); //word = removeIntonation(word); //System.out.println(" " + word + " (after removeIntonation)"); word = String.join("", word.split(" ")); char[] givenWord = word.toCharArray(); char[] res = new char[givenWord.length]; int i = 0; givenWord = word.substring(i).toCharArray(); for (char c : givenWord) { switch (c) { case 'b': res[i]='b'; break; case 'd': res[i]='d'; break; case 'c': res[i]='c'; break; case 'g': res[i]='g'; break; case 'u': res[i]='u'; break; // different with soundexGR (for capturing U) //--------------- case 'α': res[i]='a'; break; case 'β': res[i]='v'; break; // different case 'γ': res[i]='γ'; break; case 'δ': res[i]='δ'; break; case 'ε': res[i]='e'; break; // different case 'ζ': res[i]='ζ'; break; case 'η': res[i]='i'; break; // different case 'θ': res[i]='θ'; break; case 'ι': res[i]='i'; break; case 'κ': res[i]='k'; break; // different case 'λ': res[i]='l'; break; // different case 'μ': res[i]='m'; break; // different case 'ν': res[i]='n'; break; // different case 'ξ': res[i]='ξ'; break; case 'ο': res[i]='ο'; break; case 'π': res[i]='p'; break; // different case 'ρ': res[i]='r'; break; // different case 'σ': res[i]='s'; break; // different case 'ς': res[i]='s'; break; // different case 'τ': res[i]='t'; break; // different case 'υ': res[i]='U'; break; case 'φ': res[i]='φ'; break; case 'χ': res[i]='χ'; break; case 'ψ': res[i]='ψ'; break; case 'ω': res[i]='ο'; break; default: //res[i] = '0'; res[i] = c; // NEW break; } i++; } return new String(res); } public static void main(String[] args) { String[] examples = { "αυγό", "αβγό", "εύδοξος", "έβδοξος", "ουουου", "μπουμπούκι", "ούλα", "έμπειρος", "νούς", "ευάερος", "δίαλλειμα", "διάλυμα", "αυλών", "αυγουλάκια", "τζατζίκι", "τσιγκούνης", "τσιγγούνης", "εύδοξος", "Γιάννης", "Γιάνης", "Μοίνοιματα", "προύχοντας", "μήνυμα", "μύνημα", "μείννοιμμα" }; //System.out.printf("%11s -> %s %s \n", "Word" , "SoundexGR" , "Phonetic Transcription"); LengthEncoding =4; for (String word: examples) { System.out.printf("%11s -> %s %s \n", word, encode(word), phoneticTrascription(word)); } } }
YannisTzitzikas/463playground2024
463playground2024/src/DD_phonemic/SoundexGRExtra.java
6,385
// αφαίρεση του suffix της λέξης - suffix removal
line_comment
el
package DD_phonemic; /** * @author: Antrei Kavros and Yannis Tzitzikas * See more: * https://www.cambridge.org/core/journals/natural-language-engineering/article/soundexgr-an-algorithm-for-phonetic-matching-for-the-greek-language/9C27059E8EA86C6F49FB2A02D41894CD */ public class SoundexGRExtra { public static int LengthEncoding = 4; // the length of the code to be produced (default = 4) /** * @param c, the character to be checked, if is in the "strong" (ηχηρά) * category of Greek Letters * @return true, if is in the category, false otherwise */ private static boolean isStrong(char c) { // check if ηχηρό. boolean tmp; switch (c) { case 'γ': case 'β': case 'δ': case 'α': // χρειάζεται; case 'λ': case 'μ': case 'ν': case 'ρ': case 'ζ': // ΥΤΖ (May 5, 2020) tmp = true; break; default: tmp = false; break; } return tmp; } /** * @param c, the character to be checked, if is in the "aecho" (αήχα) * category of Greek Letters * @return true, if is in the category, false otherwise */ private static boolean isAecho(char c) { // check if αηχο boolean tmp; switch (c) { case 'π': case 'τ': case 'κ': case 'φ': case 'θ': case 'σ': case 'χ': case 'ξ': tmp = true; break; default: tmp = false; break; } return tmp; } /** * * @param c, the character to be checked, if it is a vowel. * @return true if @param is a vowel, false otherwise */ private static boolean isVowel(char c) { // check if vowel boolean tmp; switch (c) { case 'ά': case 'α': case 'ε': case 'έ': case 'η': case 'ή': case 'ι': case 'ί': case 'ϊ': case 'ΐ': case 'ό': case 'ο': case 'υ': case 'ύ': case 'ϋ': case 'ΰ': case 'ω': case 'ώ': tmp = true; break; default: tmp = false; break; } return tmp; } /** * * @param c, the character to be checked if, it is Greek letters 'A' or 'E * @return true if is A or E */ private static boolean isAorE(char c) { // check if word is α or e boolean tmp; switch (c) { // ά , έ are included if there is an error to the intonation case 'ά': case 'α': case 'ε': case 'έ': tmp = true; break; default: tmp = false; break; } return tmp; } /** * * @param word, a string to be trimmed from its suffix * @return the modified string if applicable, or the @param */ private static String removeLast(String word) { //suffix removal if (word.length() > 2) { char[] tmp = word.toCharArray(); int counter = 0; if (tmp[tmp.length - 1] != 'ν' || tmp[tmp.length - 1] != 'ς' || tmp[tmp.length - 1] != 'σ') { tmp[tmp.length - 1] = 'ο'; } int i = tmp.length - 1; while (i >= 0 && isVowel(tmp[i])) { tmp[i] = 'o'; counter++; i--; } counter--; return new String(tmp); } else { return word; } } /** * * @param word, a string to be trimmed from its suffix only letters 'σ', 'ς' * and 'ν' * @return the modified string if applicable, or the @param */ private static String removeLastStrict(String word) { if (word.length() > 2) { char[] tmp = word.toCharArray(); if (tmp[tmp.length - 1] == 'ν' || tmp[tmp.length - 1] == 'ς' || tmp[tmp.length - 1] == 'σ') { word = word.substring(0, word.length() - 1); } } return word; } /** * * @param word, a string to be modified, based on vowel digram combinations, * that when combined, produce a different sound.E.g 'αι' => 'ε' * @return the modified @param if applicable, or the original @param * otherwise */ private static String groupVowels(String word) { // remove group vowels if necessary to single ones char[] tmp = word.toCharArray(); int counter = 0; for (int i = 0; i < tmp.length; i++) { switch (tmp[i]) { case 'ό': tmp[i] = 'ο'; break; case 'ο': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'υ') { tmp[i] = 'ο'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ύ') { tmp[i] = 'ο'; tmp[i + 1] = ' '; } } else { tmp[i] = 'ο'; } break; case 'έ': tmp[i] = 'ε'; break; case 'ε': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } } else { tmp[i] = 'ε'; } break; case 'ά': tmp[i] = 'α'; break; case 'α': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ε'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ε'; tmp[i + 1] = ' '; } } else { tmp[i] = 'α'; } break; case 'ί': case 'ή': case 'ύ': case 'ι': case 'η': case 'υ': case 'ϋ': case 'ΰ': case 'ϊ': case 'ΐ': tmp[i] = 'ι'; break; case 'ώ': tmp[i] = 'ο'; break; case 'ω': tmp[i] = 'ο'; break; } } for (int i = 0; i < tmp.length; i++) { if (tmp[i] == ' ') { if (i + 1 < tmp.length) { tmp[i] = tmp[i + 1]; tmp[i + 1] = ' '; counter++; } } } return new String(tmp); } /** * This methods is not used by Soundex. * It is used only for the production of the phonetic transcription. * @param word, a string to be modified, based on vowel digram combinations, * that when combined, produce a different sound.E.g 'αι' => 'ε' * * @return the modified @param if applicable, or the original @param * otherwise */ private static String groupVowelsPhonetically(String word) { // remove group vowels if necessary to single ones char[] tmp = word.toCharArray(); int counter = 0; for (int i = 0; i < tmp.length; i++) { switch (tmp[i]) { case 'ό': tmp[i] = 'ο'; break; case 'ο': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'υ') { tmp[i] = 'u'; // this is the difference with the SoundexGR tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ύ') { tmp[i] = 'u'; // this is the difference with the SoundexGR tmp[i + 1] = ' '; } } else { tmp[i] = 'ο'; } break; case 'έ': tmp[i] = 'ε'; break; case 'ε': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } } else { tmp[i] = 'ε'; } break; case 'ά': tmp[i] = 'α'; break; case 'α': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ε'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ε'; tmp[i + 1] = ' '; } } else { tmp[i] = 'α'; } break; case 'ί': case 'ή': case 'ύ': case 'ι': case 'η': case 'υ': case 'ϋ': case 'ΰ': case 'ϊ': case 'ΐ': tmp[i] = 'ι'; break; case 'ώ': tmp[i] = 'ο'; break; case 'ω': tmp[i] = 'ο'; break; } } for (int i = 0; i < tmp.length; i++) { if (tmp[i] == ' ') { if (i + 1 < tmp.length) { tmp[i] = tmp[i + 1]; tmp[i + 1] = ' '; counter++; } } } return new String(tmp); } /** * * @param word, a string from which the intonation is to be removed. * @return a string without intonation */ private static String removeIntonation(String word){ char[] tmp = word.toCharArray(); for (int i = 0; i < tmp.length; i++) { switch(tmp[i]){ case 'ά': tmp[i]='α'; break; case 'έ': tmp[i]='ε'; break; case 'ό': tmp[i]='ο'; break; case 'ή': tmp[i]='η'; break; case 'ί': tmp[i]='ι'; break; case 'ύ': tmp[i]='υ'; break; case 'ώ': tmp[i]='ω'; break; case 'ΐ': tmp[i]='ι'; break; case 'ϊ': tmp[i]='ι'; break; case 'ΰ': tmp[i]='υ'; break; case 'ϋ': tmp[i]='υ'; break; default: break; } } return new String(tmp); } /** * * @param word, a string to be modified, based on vowel digram combinations, * that when combined, produce a different sound, that is considered a * consonant.E.g 'αυτος' => 'αφτος' * @return the modified @param if applicable, the original @param otherwise */ private static String getVowelAsConsonant(String word) { // Check if a letter contains αυ , ευ and check if the next letter corresponds to a rule char[] tmp = word.toCharArray(); for (int i = 0; i < tmp.length; i++) { if ((tmp[i] == 'υ' || tmp[i] == 'ύ') && (i - 1 >= 0 && isAorE(tmp[i - 1]))) { if ((i + 1) < tmp.length && isAecho(tmp[i + 1])) { tmp[i] = 'φ'; } else if ((i + 1) < tmp.length && (i + 1 < tmp.length && (isVowel(tmp[i + 1]) || isStrong(tmp[i + 1])))) { tmp[i] = 'β'; } if (i == tmp.length - 1) { tmp[i] = 'φ'; } } } return new String(tmp); } /** * * @param word, a string to be modified if it contains specific consonant * digram combinations * @return the modified string */ private static String unwrapConsonantBigrams(String word) { // Reason for example of μπ -> b and not -> β , is that vowels as consonant operation follows and may // wrongly change to a consonant word = word.replace("μπ", "b"); word = word.replace("ντ", "d"); word = word.replace("γκ", "g"); word = word.replace("γγ", "g"); word = word.replace("τσ", "c"); word = word.replace("τζ", "c"); word = word.replace("πς", "ψ"); word = word.replace("πσ", "ψ"); word = word.replace("κς", "ξ"); word = word.replace("κσ", "ξ"); return word; } /** * * Version for the exact phonetic transcription * @param word, a string to be modified if it contains specific consonant * digram combinations * @return the modified string */ private static String unwrapConsonantBigramsPhonetically(String word) { // Reason for example of μπ -> b and not -> β , is that vowels as consonant operation follows and may // wrongly change to a consonant word = word.replace("μπ", "b"); word = word.replace("ντ", "d"); word = word.replace("γκ", "g"); word = word.replace("γγ", "g"); word = word.replace("τσ", "ts"); // different than plain (in soundex: c) word = word.replace("τζ", "dz"); // different than plain (in soundex: c) word = word.replace("πς", "ψ"); word = word.replace("πσ", "ψ"); word = word.replace("κς", "ξ"); word = word.replace("κσ", "ξ"); return word; } /** * * @param word, word to be encode through this Soundex implementation * @return an encoded word */ public static String encode(String word) { //The following function calls could be merged together in to one loop for better performance word = word.toLowerCase(); // word to lowercase word = unwrapConsonantBigrams(word); // αφαίρεση δίφθογγων - dual letter substitution to single //System.out.println(word + " (after unwrapConsonantBigrams)"); word = getVowelAsConsonant(word); // μετατροπή ευ, αυ σε σύμφωνο , αν ακολουθεί κάποιο άηχο ή ηχηρό γράμμα - substitution of υ vowel to consonant if needed //System.out.println(" " + word + " (after getVoelsAsConsonants)"); // removeLast and removeLastStrict or almost useless, now that the word is trimmed to just 6 digits word = removeLastStrict(word); // αφαίρεση του<SUF> //System.out.println(" " + word + " (after getLastStrict)"); word = groupVowels(word); // μετατροπή φωνήεντων πχ αι σε ε - substitute group vowels to single vowel. //System.out.println(" " + word + " (after groupVowels)"); word = removeIntonation(word); //System.out.println(" " + word + " (after removeIntonation)"); word = String.join("", word.split(" ")); char[] givenWord = word.toCharArray(); char[] res = new char[givenWord.length]; int i = 1; res[0] = word.charAt(0); givenWord = word.substring(i).toCharArray(); for (char c : givenWord) { switch (c) { case 'β': case 'b': case 'φ': case 'π': res[i] = '1'; break; case 'γ': case 'χ': res[i] = '2'; break; case 'δ': case 'τ': case 'd': case 'θ': res[i] = '3'; break; case 'ζ': case 'σ': case 'ς': case 'ψ': case 'c': case 'ξ': res[i] = '4'; break; case 'κ': case 'g': res[i] = '5'; break; case 'λ': res[i] = '6'; break; case 'μ': case 'ν': res[i] = '7'; break; case 'ρ': res[i] = '8'; break; case 'α': res[i] = '9'; break; case 'ε': res[i] = '*'; break; case 'ο': case 'ω': res[i] = '$'; break; case 'ι': res[i] = '@'; break; default: res[i] = '0'; break; } i++; } //for (int z=0; z<res.length;z++) // System.out.print(res[z]); //System.out.println(" (after encode)"); String finalResult = ""; // Remove duplicates finalResult += res[0]; for (i = 1; i < res.length; i++) { if (res[i] != '0') { if (res[i] != res[i - 1]) { finalResult += res[i]; } } } //for (int z=0; z<res.length;z++) // System.out.print(res[z]); //System.out.println(" (after remove duplicates)"); //finalResult += "00000000"; finalResult += "00000000000000000000"; // needed only in the case the lenth of the code is big return finalResult.substring(0, LengthEncoding); // 4 letter length encoding } /** * It is a variation of the SoundexGR for returning a kind of phonetic transcription of the entire word * @param word, word to be encode * @return phonetic transcription of the word */ public static String phoneticTrascription(String word) { word = word.toLowerCase(); // word to lowercase //word = unwrapConsonantBigrams(word); // αφαίρεση δίφθογγων - dual letter substitution to single word = unwrapConsonantBigramsPhonetically(word); // NEW //System.out.println(word + " (after unwrapConsonantBigrams Phonetically)"); word = getVowelAsConsonant(word); // μετατροπή ευ, αυ σε σύμφωνο , αν ακολουθεί κάποιο άηχο ή ηχηρό γράμμα - substitution of υ vowel to consonant if needed //System.out.println(" " + word + " (after getVoelsAsConsonants)"); // removeLast and removeLastStrict or almost useless, now that the word is trimmed to just 6 digits //word = removeLastStrict(word); // αφαίρεση του suffix της λέξης - suffix removal //System.out.println(" " + word + " (after getLastStrict)"); //word = groupVowels(word); // μετατροπή φωνήεντων πχ αι σε ε - substitute group vowels to single vowel. word = groupVowelsPhonetically(word); // NEW //System.out.println(" " + word + " (after groupVowels phonetically)"); //word = removeIntonation(word); //System.out.println(" " + word + " (after removeIntonation)"); word = String.join("", word.split(" ")); char[] givenWord = word.toCharArray(); char[] res = new char[givenWord.length]; int i = 0; givenWord = word.substring(i).toCharArray(); for (char c : givenWord) { switch (c) { case 'b': res[i]='b'; break; case 'd': res[i]='d'; break; case 'c': res[i]='c'; break; case 'g': res[i]='g'; break; case 'u': res[i]='u'; break; // different with soundexGR (for capturing U) //--------------- case 'α': res[i]='a'; break; case 'β': res[i]='v'; break; // different case 'γ': res[i]='γ'; break; case 'δ': res[i]='δ'; break; case 'ε': res[i]='e'; break; // different case 'ζ': res[i]='ζ'; break; case 'η': res[i]='i'; break; // different case 'θ': res[i]='θ'; break; case 'ι': res[i]='i'; break; case 'κ': res[i]='k'; break; // different case 'λ': res[i]='l'; break; // different case 'μ': res[i]='m'; break; // different case 'ν': res[i]='n'; break; // different case 'ξ': res[i]='ξ'; break; case 'ο': res[i]='ο'; break; case 'π': res[i]='p'; break; // different case 'ρ': res[i]='r'; break; // different case 'σ': res[i]='s'; break; // different case 'ς': res[i]='s'; break; // different case 'τ': res[i]='t'; break; // different case 'υ': res[i]='U'; break; case 'φ': res[i]='φ'; break; case 'χ': res[i]='χ'; break; case 'ψ': res[i]='ψ'; break; case 'ω': res[i]='ο'; break; default: //res[i] = '0'; res[i] = c; // NEW break; } i++; } return new String(res); } public static void main(String[] args) { String[] examples = { "αυγό", "αβγό", "εύδοξος", "έβδοξος", "ουουου", "μπουμπούκι", "ούλα", "έμπειρος", "νούς", "ευάερος", "δίαλλειμα", "διάλυμα", "αυλών", "αυγουλάκια", "τζατζίκι", "τσιγκούνης", "τσιγγούνης", "εύδοξος", "Γιάννης", "Γιάνης", "Μοίνοιματα", "προύχοντας", "μήνυμα", "μύνημα", "μείννοιμμα" }; //System.out.printf("%11s -> %s %s \n", "Word" , "SoundexGR" , "Phonetic Transcription"); LengthEncoding =4; for (String word: examples) { System.out.printf("%11s -> %s %s \n", word, encode(word), phoneticTrascription(word)); } } }
13_4
package week3_4; /* * Author: Yannis Tzitzikas * Version V2 */ class Animal { String name = "living being"; void saySomething() {} ; // δεν κάνει τίποτα void reactToEarthQuake() { saySomething(); saySomething(); }; // 2 φορές λέει κάτι } class Dog extends Animal { void saySomething() { System.out.print("[ Γαβ]");} } class Cat extends Animal { String name = "Γάτα"; void saySomething() { System.out.print("[Nιάου]");} void reactToEarthQuake() { super.reactToEarthQuake(); System.out.print("[Δεν μασάω] είμαι " + name);} } class DogEMAK extends Dog { // εκπαιδευμένος σκύλος void reactToEarthQuake() { super.reactToEarthQuake(); // κάνει ό,τι και ένας "νορμάλ" σκύλος System.out.print("[ φσιτ]"); // και επιπλέον "σφυρίζει" }; } class Fish extends Animal { void saySomething() { System.out.print("[ Μπλμ]");} void reactToEarthQuake() { System.out.print("[~~~~~]");}; // σε περίπτωση σεισμού "κυματίζει" } class JungleDemo { public static void main(String[] aaa) { Dog d1 = new Dog(); d1.reactToEarthQuake(); /* Cat c1 = new Cat(); c1.saySomething(); System.out.println(); c1.reactToEarthQuake(); System.out.println(); Animal a1 = c1; System.out.println(a1.name); System.out.println(((Cat)a1).name); System.out.println(a1 instanceof Cat); // true System.out.println(a1 instanceof Animal); // true System.out.println(a1 instanceof Object); // true Animal a2 = new Animal(); System.out.println(a2 instanceof Cat); */ /* Animal a1 = new DogEMAK(); a1.saySomething(); System.out.println(); a1.reactToEarthQuake(); */ //Animal a1 = new Animal(); //a1.reactToEarthQuake(); // Animal c1 = new Cat(); // δημιουργία μιας γάτας, το δείκτη τον κρατά μτβλ τύπου Animal //c1.saySomething(); // c1.reactToEarthQuake(); //Animal d1 = new Dog(); // δημιουργία ενός σκύλου, το δείκτη τον κρατά μτβλ τύπου Animal //c1.saySomething(); // Αν δεν υπήρχε overidding τί θα παίρναμε; //d1.saySomething(); //makeJungle(); } static void makeJungle() { System.out.println("S i m u l a t i o n o f t h e U n i v e r s e v0.1"); int numOfAnimals = 100; // πλήθος των ζώων που θα δημιουργηθούν System.out.println("Number of animals:" + numOfAnimals); Animal[] amazonios = new Animal[numOfAnimals]; // πίνακας που θα κρατάει αναφορές στα αντικείμενα τύπου ζώο // CREATION DAY for (int i=0; i<numOfAnimals; i++ ){ //amazonios[i] = (Math.random() > 0.6) ? new Dog() : new Cat() ; // an thelame mono gates kai skylous double tyxaiosArithmos = Math.random(); // από το 0 έως το 1 Animal neoZwo; if (tyxaiosArithmos<0.3) neoZwo = new Cat(); else if (tyxaiosArithmos<0.6) neoZwo = new Dog(); else if (tyxaiosArithmos<0.9) neoZwo = new Fish(); else neoZwo = new DogEMAK(); amazonios[i] = neoZwo; } // EXISTENCE CHECK System.out.println("\n========= YPARKSIAKOS ELEGXOS ========="); for (int i=0; i<numOfAnimals; i++ ){ amazonios[i].saySomething(); } // EARTHQUAKE REACTION: System.out.println("\n========= SEISMOS! ========="); for (int i=0; i<numOfAnimals; i++ ){ amazonios[i].reactToEarthQuake(); } // NIKHTHS TOU LOTTO System.out.println("\n========= APOTELESMATA KLHRWSHS ========= "); int luckyIndex = (int) Math.round(Math.random()*numOfAnimals); System.out.println("O nikiths ths klhrwshs auths ths ebdomadas einai to zwo me arithmo " + luckyIndex + " το οποίο ανήκει στην κλάση " + amazonios[luckyIndex].getClass() ); // reflection if (amazonios[luckyIndex] instanceof Dog) System.out.println("Πράγματι είναι σκύλος."); Object o1 = new DogEMAK(); Dog o2 = ((Dog) o1); Animal a3 = o2; System.out.println("Η ΚΛΑΣΗ ΤΟΥ ΕΙΝΑΙ " + a3.getClass() + " " + ((Dog)a3).name); } }
YannisTzitzikas/CS252playground
CS252playground/src/week3_4/Jungle.java
1,692
// και επιπλέον "σφυρίζει"
line_comment
el
package week3_4; /* * Author: Yannis Tzitzikas * Version V2 */ class Animal { String name = "living being"; void saySomething() {} ; // δεν κάνει τίποτα void reactToEarthQuake() { saySomething(); saySomething(); }; // 2 φορές λέει κάτι } class Dog extends Animal { void saySomething() { System.out.print("[ Γαβ]");} } class Cat extends Animal { String name = "Γάτα"; void saySomething() { System.out.print("[Nιάου]");} void reactToEarthQuake() { super.reactToEarthQuake(); System.out.print("[Δεν μασάω] είμαι " + name);} } class DogEMAK extends Dog { // εκπαιδευμένος σκύλος void reactToEarthQuake() { super.reactToEarthQuake(); // κάνει ό,τι και ένας "νορμάλ" σκύλος System.out.print("[ φσιτ]"); // και επιπλέον<SUF> }; } class Fish extends Animal { void saySomething() { System.out.print("[ Μπλμ]");} void reactToEarthQuake() { System.out.print("[~~~~~]");}; // σε περίπτωση σεισμού "κυματίζει" } class JungleDemo { public static void main(String[] aaa) { Dog d1 = new Dog(); d1.reactToEarthQuake(); /* Cat c1 = new Cat(); c1.saySomething(); System.out.println(); c1.reactToEarthQuake(); System.out.println(); Animal a1 = c1; System.out.println(a1.name); System.out.println(((Cat)a1).name); System.out.println(a1 instanceof Cat); // true System.out.println(a1 instanceof Animal); // true System.out.println(a1 instanceof Object); // true Animal a2 = new Animal(); System.out.println(a2 instanceof Cat); */ /* Animal a1 = new DogEMAK(); a1.saySomething(); System.out.println(); a1.reactToEarthQuake(); */ //Animal a1 = new Animal(); //a1.reactToEarthQuake(); // Animal c1 = new Cat(); // δημιουργία μιας γάτας, το δείκτη τον κρατά μτβλ τύπου Animal //c1.saySomething(); // c1.reactToEarthQuake(); //Animal d1 = new Dog(); // δημιουργία ενός σκύλου, το δείκτη τον κρατά μτβλ τύπου Animal //c1.saySomething(); // Αν δεν υπήρχε overidding τί θα παίρναμε; //d1.saySomething(); //makeJungle(); } static void makeJungle() { System.out.println("S i m u l a t i o n o f t h e U n i v e r s e v0.1"); int numOfAnimals = 100; // πλήθος των ζώων που θα δημιουργηθούν System.out.println("Number of animals:" + numOfAnimals); Animal[] amazonios = new Animal[numOfAnimals]; // πίνακας που θα κρατάει αναφορές στα αντικείμενα τύπου ζώο // CREATION DAY for (int i=0; i<numOfAnimals; i++ ){ //amazonios[i] = (Math.random() > 0.6) ? new Dog() : new Cat() ; // an thelame mono gates kai skylous double tyxaiosArithmos = Math.random(); // από το 0 έως το 1 Animal neoZwo; if (tyxaiosArithmos<0.3) neoZwo = new Cat(); else if (tyxaiosArithmos<0.6) neoZwo = new Dog(); else if (tyxaiosArithmos<0.9) neoZwo = new Fish(); else neoZwo = new DogEMAK(); amazonios[i] = neoZwo; } // EXISTENCE CHECK System.out.println("\n========= YPARKSIAKOS ELEGXOS ========="); for (int i=0; i<numOfAnimals; i++ ){ amazonios[i].saySomething(); } // EARTHQUAKE REACTION: System.out.println("\n========= SEISMOS! ========="); for (int i=0; i<numOfAnimals; i++ ){ amazonios[i].reactToEarthQuake(); } // NIKHTHS TOU LOTTO System.out.println("\n========= APOTELESMATA KLHRWSHS ========= "); int luckyIndex = (int) Math.round(Math.random()*numOfAnimals); System.out.println("O nikiths ths klhrwshs auths ths ebdomadas einai to zwo me arithmo " + luckyIndex + " το οποίο ανήκει στην κλάση " + amazonios[luckyIndex].getClass() ); // reflection if (amazonios[luckyIndex] instanceof Dog) System.out.println("Πράγματι είναι σκύλος."); Object o1 = new DogEMAK(); Dog o2 = ((Dog) o1); Animal a3 = o2; System.out.println("Η ΚΛΑΣΗ ΤΟΥ ΕΙΝΑΙ " + a3.getClass() + " " + ((Dog)a3).name); } }
20495_36
package SoundexGR; /** * @author: Antrei Kavros and Yannis Tzitzikas */ public class SoundexGRExtra { public static int LengthEncoding = 4; // the length of the code to be produced (default = 4) /** * @param c, the character to be checked, if is in the "strong" (ηχηρά) * category of Greek Letters * @return true, if is in the category, false otherwise */ private static boolean isStrong(char c) { // check if ηχηρό. boolean tmp; switch (c) { case 'γ': case 'β': case 'δ': case 'α': // χρειάζεται; case 'λ': case 'μ': case 'ν': case 'ρ': case 'ζ': // ΥΤΖ (May 5, 2020) tmp = true; break; default: tmp = false; break; } return tmp; } /** * @param c, the character to be checked, if is in the "aecho" (αήχα) * category of Greek Letters * @return true, if is in the category, false otherwise */ private static boolean isAecho(char c) { // check if αηχο boolean tmp; switch (c) { case 'π': case 'τ': case 'κ': case 'φ': case 'θ': case 'σ': case 'χ': case 'ξ': tmp = true; break; default: tmp = false; break; } return tmp; } /** * * @param c, the character to be checked, if it is a vowel. * @return true if @param is a vowel, false otherwise */ private static boolean isVowel(char c) { // check if vowel boolean tmp; switch (c) { case 'ά': case 'α': case 'ε': case 'έ': case 'η': case 'ή': case 'ι': case 'ί': case 'ϊ': case 'ΐ': case 'ό': case 'ο': case 'υ': case 'ύ': case 'ϋ': case 'ΰ': case 'ω': case 'ώ': tmp = true; break; default: tmp = false; break; } return tmp; } /** * * @param c, the character to be checked if, it is Greek letters 'A' or 'E * @return true if is A or E */ private static boolean isAorE(char c) { // check if word is α or e boolean tmp; switch (c) { // ά , έ are included if there is an error to the intonation case 'ά': case 'α': case 'ε': case 'έ': tmp = true; break; default: tmp = false; break; } return tmp; } /** * * @param word, a string to be trimmed from its suffix * @return the modified string if applicable, or the @param */ private static String removeLast(String word) { //suffix removal if (word.length() > 2) { char[] tmp = word.toCharArray(); int counter = 0; if (tmp[tmp.length - 1] != 'ν' || tmp[tmp.length - 1] != 'ς' || tmp[tmp.length - 1] != 'σ') { tmp[tmp.length - 1] = 'ο'; } int i = tmp.length - 1; while (i >= 0 && isVowel(tmp[i])) { tmp[i] = 'o'; counter++; i--; } counter--; return new String(tmp); } else { return word; } } /** * * @param word, a string to be trimmed from its suffix only letters 'σ', 'ς' * and 'ν' * @return the modified string if applicable, or the @param */ private static String removeLastStrict(String word) { if (word.length() > 2) { char[] tmp = word.toCharArray(); if (tmp[tmp.length - 1] == 'ν' || tmp[tmp.length - 1] == 'ς' || tmp[tmp.length - 1] == 'σ') { word = word.substring(0, word.length() - 1); } } return word; } /** * * @param word, a string to be modified, based on vowel digram combinations, * that when combined, produce a different sound.E.g 'αι' => 'ε' * @return the modified @param if applicable, or the original @param * otherwise */ private static String groupVowels(String word) { // remove group vowels if necessary to single ones char[] tmp = word.toCharArray(); int counter = 0; for (int i = 0; i < tmp.length; i++) { switch (tmp[i]) { case 'ό': tmp[i] = 'ο'; break; case 'ο': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'υ') { tmp[i] = 'ο'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ύ') { tmp[i] = 'ο'; tmp[i + 1] = ' '; } } else { tmp[i] = 'ο'; } break; case 'έ': tmp[i] = 'ε'; break; case 'ε': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } } else { tmp[i] = 'ε'; } break; case 'ά': tmp[i] = 'α'; break; case 'α': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ε'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ε'; tmp[i + 1] = ' '; } } else { tmp[i] = 'α'; } break; case 'ί': case 'ή': case 'ύ': case 'ι': case 'η': case 'υ': case 'ϋ': case 'ΰ': case 'ϊ': case 'ΐ': tmp[i] = 'ι'; break; case 'ώ': tmp[i] = 'ο'; break; case 'ω': tmp[i] = 'ο'; break; } } for (int i = 0; i < tmp.length; i++) { if (tmp[i] == ' ') { if (i + 1 < tmp.length) { tmp[i] = tmp[i + 1]; tmp[i + 1] = ' '; counter++; } } } return new String(tmp); } /** * This methods is not used by Soundex. * It is used only for the production of the phonetic transcription. * @param word, a string to be modified, based on vowel digram combinations, * that when combined, produce a different sound.E.g 'αι' => 'ε' * * @return the modified @param if applicable, or the original @param * otherwise */ private static String groupVowelsPhonetically(String word) { // remove group vowels if necessary to single ones char[] tmp = word.toCharArray(); int counter = 0; for (int i = 0; i < tmp.length; i++) { switch (tmp[i]) { case 'ό': tmp[i] = 'ο'; break; case 'ο': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'υ') { tmp[i] = 'u'; // this is the difference with the SoundexGR tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ύ') { tmp[i] = 'u'; // this is the difference with the SoundexGR tmp[i + 1] = ' '; } } else { tmp[i] = 'ο'; } break; case 'έ': tmp[i] = 'ε'; break; case 'ε': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } } else { tmp[i] = 'ε'; } break; case 'ά': tmp[i] = 'α'; break; case 'α': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ε'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ε'; tmp[i + 1] = ' '; } } else { tmp[i] = 'α'; } break; case 'ί': case 'ή': case 'ύ': case 'ι': case 'η': case 'υ': case 'ϋ': case 'ΰ': case 'ϊ': case 'ΐ': tmp[i] = 'ι'; break; case 'ώ': tmp[i] = 'ο'; break; case 'ω': tmp[i] = 'ο'; break; } } for (int i = 0; i < tmp.length; i++) { if (tmp[i] == ' ') { if (i + 1 < tmp.length) { tmp[i] = tmp[i + 1]; tmp[i + 1] = ' '; counter++; } } } return new String(tmp); } /** * * @param word, a string from which the intonation is to be removed. * @return a string without intonation */ private static String removeIntonation(String word){ char[] tmp = word.toCharArray(); for (int i = 0; i < tmp.length; i++) { switch(tmp[i]){ case 'ά': tmp[i]='α'; break; case 'έ': tmp[i]='ε'; break; case 'ό': tmp[i]='ο'; break; case 'ή': tmp[i]='η'; break; case 'ί': tmp[i]='ι'; break; case 'ύ': tmp[i]='υ'; break; case 'ώ': tmp[i]='ω'; break; case 'ΐ': tmp[i]='ι'; break; case 'ϊ': tmp[i]='ι'; break; case 'ΰ': tmp[i]='υ'; break; case 'ϋ': tmp[i]='υ'; break; default: break; } } return new String(tmp); } /** * * @param word, a string to be modified, based on vowel digram combinations, * that when combined, produce a different sound, that is considered a * consonant.E.g 'αυτος' => 'αφτος' * @return the modified @param if applicable, the original @param otherwise */ private static String getVowelAsConsonant(String word) { // Check if a letter contains αυ , ευ and check if the next letter corresponds to a rule char[] tmp = word.toCharArray(); for (int i = 0; i < tmp.length; i++) { if ((tmp[i] == 'υ' || tmp[i] == 'ύ') && (i - 1 >= 0 && isAorE(tmp[i - 1]))) { if ((i + 1) < tmp.length && isAecho(tmp[i + 1])) { tmp[i] = 'φ'; } else if ((i + 1) < tmp.length && (i + 1 < tmp.length && (isVowel(tmp[i + 1]) || isStrong(tmp[i + 1])))) { tmp[i] = 'β'; } if (i == tmp.length - 1) { tmp[i] = 'φ'; } } } return new String(tmp); } /** * * @param word, a string to be modified if it contains specific consonant * digram combinations * @return the modified string */ private static String unwrapConsonantBigrams(String word) { // Reason for example of μπ -> b and not -> β , is that vowels as consonant operation follows and may // wrongly change to a consonant word = word.replace("μπ", "b"); word = word.replace("ντ", "d"); word = word.replace("γκ", "g"); word = word.replace("γγ", "g"); word = word.replace("τσ", "c"); word = word.replace("τζ", "c"); word = word.replace("πς", "ψ"); word = word.replace("πσ", "ψ"); word = word.replace("κς", "ξ"); word = word.replace("κσ", "ξ"); return word; } /** * * Version for the exact phonetic transcription * @param word, a string to be modified if it contains specific consonant * digram combinations * @return the modified string */ private static String unwrapConsonantBigramsPhonetically(String word) { // Reason for example of μπ -> b and not -> β , is that vowels as consonant operation follows and may // wrongly change to a consonant word = word.replace("μπ", "b"); word = word.replace("ντ", "d"); word = word.replace("γκ", "g"); word = word.replace("γγ", "g"); word = word.replace("τσ", "ts"); // different than plain (in soundex: c) word = word.replace("τζ", "dz"); // different than plain (in soundex: c) word = word.replace("πς", "ψ"); word = word.replace("πσ", "ψ"); word = word.replace("κς", "ξ"); word = word.replace("κσ", "ξ"); return word; } /** * * @param word, word to be encode through this Soundex implementation * @return an encoded word */ public static String encode(String word) { //The following function calls could be merged together in to one loop for better performance word = word.toLowerCase(); // word to lowercase word = unwrapConsonantBigrams(word); // αφαίρεση δίφθογγων - dual letter substitution to single //System.out.println(word + " (after unwrapConsonantBigrams)"); word = getVowelAsConsonant(word); // μετατροπή ευ, αυ σε σύμφωνο , αν ακολουθεί κάποιο άηχο ή ηχηρό γράμμα - substitution of υ vowel to consonant if needed //System.out.println(" " + word + " (after getVoelsAsConsonants)"); // removeLast and removeLastStrict or almost useless, now that the word is trimmed to just 6 digits word = removeLastStrict(word); // αφαίρεση του suffix της λέξης - suffix removal //System.out.println(" " + word + " (after getLastStrict)"); word = groupVowels(word); // μετατροπή φωνήεντων πχ αι σε ε - substitute group vowels to single vowel. //System.out.println(" " + word + " (after groupVowels)"); word = removeIntonation(word); //System.out.println(" " + word + " (after removeIntonation)"); word = String.join("", word.split(" ")); char[] givenWord = word.toCharArray(); char[] res = new char[givenWord.length]; int i = 1; res[0] = word.charAt(0); givenWord = word.substring(i).toCharArray(); for (char c : givenWord) { switch (c) { case 'β': case 'b': case 'φ': case 'π': res[i] = '1'; break; case 'γ': case 'χ': res[i] = '2'; break; case 'δ': case 'τ': case 'd': case 'θ': res[i] = '3'; break; case 'ζ': case 'σ': case 'ς': case 'ψ': case 'c': case 'ξ': res[i] = '4'; break; case 'κ': case 'g': res[i] = '5'; break; case 'λ': res[i] = '6'; break; case 'μ': case 'ν': res[i] = '7'; break; case 'ρ': res[i] = '8'; break; case 'α': res[i] = '9'; break; case 'ε': res[i] = '*'; break; case 'ο': case 'ω': res[i] = '$'; break; case 'ι': res[i] = '@'; break; default: res[i] = '0'; break; } i++; } //for (int z=0; z<res.length;z++) // System.out.print(res[z]); //System.out.println(" (after encode)"); String finalResult = ""; // Remove duplicates finalResult += res[0]; for (i = 1; i < res.length; i++) { if (res[i] != '0') { if (res[i] != res[i - 1]) { finalResult += res[i]; } } } //for (int z=0; z<res.length;z++) // System.out.print(res[z]); //System.out.println(" (after remove duplicates)"); //finalResult += "00000000"; finalResult += "00000000000000000000"; // needed only in the case the lenth of the code is big return finalResult.substring(0, LengthEncoding); // 4 letter length encoding } /** * It is a variation of the SoundexGR for returning a kind of phonetic transcription of the entire word * @param word, word to be encode * @return phonetic transcription of the word */ public static String phoneticTrascription(String word) { word = word.toLowerCase(); // word to lowercase //word = unwrapConsonantBigrams(word); // αφαίρεση δίφθογγων - dual letter substitution to single word = unwrapConsonantBigramsPhonetically(word); // NEW //System.out.println(word + " (after unwrapConsonantBigrams Phonetically)"); word = getVowelAsConsonant(word); // μετατροπή ευ, αυ σε σύμφωνο , αν ακολουθεί κάποιο άηχο ή ηχηρό γράμμα - substitution of υ vowel to consonant if needed //System.out.println(" " + word + " (after getVoelsAsConsonants)"); // removeLast and removeLastStrict or almost useless, now that the word is trimmed to just 6 digits //word = removeLastStrict(word); // αφαίρεση του suffix της λέξης - suffix removal //System.out.println(" " + word + " (after getLastStrict)"); //word = groupVowels(word); // μετατροπή φωνήεντων πχ αι σε ε - substitute group vowels to single vowel. word = groupVowelsPhonetically(word); // NEW //System.out.println(" " + word + " (after groupVowels phonetically)"); //word = removeIntonation(word); //System.out.println(" " + word + " (after removeIntonation)"); word = String.join("", word.split(" ")); char[] givenWord = word.toCharArray(); char[] res = new char[givenWord.length]; int i = 0; givenWord = word.substring(i).toCharArray(); for (char c : givenWord) { switch (c) { case 'b': res[i]='b'; break; case 'd': res[i]='d'; break; case 'c': res[i]='c'; break; case 'g': res[i]='g'; break; case 'u': res[i]='u'; break; // different with soundexGR (for capturing U) //--------------- case 'α': res[i]='a'; break; case 'β': res[i]='v'; break; // different case 'γ': res[i]='γ'; break; case 'δ': res[i]='δ'; break; case 'ε': res[i]='e'; break; // different case 'ζ': res[i]='ζ'; break; case 'η': res[i]='i'; break; // different case 'θ': res[i]='θ'; break; case 'ι': res[i]='i'; break; case 'κ': res[i]='k'; break; // different case 'λ': res[i]='l'; break; // different case 'μ': res[i]='m'; break; // different case 'ν': res[i]='n'; break; // different case 'ξ': res[i]='ξ'; break; case 'ο': res[i]='ο'; break; case 'π': res[i]='p'; break; // different case 'ρ': res[i]='r'; break; // different case 'σ': res[i]='s'; break; // different case 'ς': res[i]='s'; break; // different case 'τ': res[i]='t'; break; // different case 'υ': res[i]='U'; break; case 'φ': res[i]='φ'; break; case 'χ': res[i]='χ'; break; case 'ψ': res[i]='ψ'; break; case 'ω': res[i]='ο'; break; default: //res[i] = '0'; res[i] = c; // NEW break; } i++; } return new String(res); } public static void main(String[] args) { String[] examples = { "αυγό", "αβγό", "εύδοξος", "έβδοξος", "ουουου", "μπουμπούκι", "ούλα", "έμπειρος", "νούς", "ευάερος", "δίαλλειμα", "διάλυμα", "αυλών", "αυγουλάκια", "τζατζίκι", "τσιγκούνης", "τσιγγούνης", "εύδοξος", "Γιάννης", "Γιάνης", "Μοίνοιματα", "προύχοντας" }; //System.out.printf("%11s -> %s %s \n", "Word" , "SoundexGR" , "Phonetic Transcription"); LengthEncoding =4; for (String word: examples) { System.out.printf("%11s -> %s %s \n", word, encode(word), phoneticTrascription(word)); } } }
YannisTzitzikas/SoundexGR
SoundexGR/src/SoundexGR/SoundexGRExtra.java
6,267
// μετατροπή ευ, αυ σε σύμφωνο , αν ακολουθεί κάποιο άηχο ή ηχηρό γράμμα - substitution of υ vowel to consonant if needed
line_comment
el
package SoundexGR; /** * @author: Antrei Kavros and Yannis Tzitzikas */ public class SoundexGRExtra { public static int LengthEncoding = 4; // the length of the code to be produced (default = 4) /** * @param c, the character to be checked, if is in the "strong" (ηχηρά) * category of Greek Letters * @return true, if is in the category, false otherwise */ private static boolean isStrong(char c) { // check if ηχηρό. boolean tmp; switch (c) { case 'γ': case 'β': case 'δ': case 'α': // χρειάζεται; case 'λ': case 'μ': case 'ν': case 'ρ': case 'ζ': // ΥΤΖ (May 5, 2020) tmp = true; break; default: tmp = false; break; } return tmp; } /** * @param c, the character to be checked, if is in the "aecho" (αήχα) * category of Greek Letters * @return true, if is in the category, false otherwise */ private static boolean isAecho(char c) { // check if αηχο boolean tmp; switch (c) { case 'π': case 'τ': case 'κ': case 'φ': case 'θ': case 'σ': case 'χ': case 'ξ': tmp = true; break; default: tmp = false; break; } return tmp; } /** * * @param c, the character to be checked, if it is a vowel. * @return true if @param is a vowel, false otherwise */ private static boolean isVowel(char c) { // check if vowel boolean tmp; switch (c) { case 'ά': case 'α': case 'ε': case 'έ': case 'η': case 'ή': case 'ι': case 'ί': case 'ϊ': case 'ΐ': case 'ό': case 'ο': case 'υ': case 'ύ': case 'ϋ': case 'ΰ': case 'ω': case 'ώ': tmp = true; break; default: tmp = false; break; } return tmp; } /** * * @param c, the character to be checked if, it is Greek letters 'A' or 'E * @return true if is A or E */ private static boolean isAorE(char c) { // check if word is α or e boolean tmp; switch (c) { // ά , έ are included if there is an error to the intonation case 'ά': case 'α': case 'ε': case 'έ': tmp = true; break; default: tmp = false; break; } return tmp; } /** * * @param word, a string to be trimmed from its suffix * @return the modified string if applicable, or the @param */ private static String removeLast(String word) { //suffix removal if (word.length() > 2) { char[] tmp = word.toCharArray(); int counter = 0; if (tmp[tmp.length - 1] != 'ν' || tmp[tmp.length - 1] != 'ς' || tmp[tmp.length - 1] != 'σ') { tmp[tmp.length - 1] = 'ο'; } int i = tmp.length - 1; while (i >= 0 && isVowel(tmp[i])) { tmp[i] = 'o'; counter++; i--; } counter--; return new String(tmp); } else { return word; } } /** * * @param word, a string to be trimmed from its suffix only letters 'σ', 'ς' * and 'ν' * @return the modified string if applicable, or the @param */ private static String removeLastStrict(String word) { if (word.length() > 2) { char[] tmp = word.toCharArray(); if (tmp[tmp.length - 1] == 'ν' || tmp[tmp.length - 1] == 'ς' || tmp[tmp.length - 1] == 'σ') { word = word.substring(0, word.length() - 1); } } return word; } /** * * @param word, a string to be modified, based on vowel digram combinations, * that when combined, produce a different sound.E.g 'αι' => 'ε' * @return the modified @param if applicable, or the original @param * otherwise */ private static String groupVowels(String word) { // remove group vowels if necessary to single ones char[] tmp = word.toCharArray(); int counter = 0; for (int i = 0; i < tmp.length; i++) { switch (tmp[i]) { case 'ό': tmp[i] = 'ο'; break; case 'ο': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'υ') { tmp[i] = 'ο'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ύ') { tmp[i] = 'ο'; tmp[i + 1] = ' '; } } else { tmp[i] = 'ο'; } break; case 'έ': tmp[i] = 'ε'; break; case 'ε': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } } else { tmp[i] = 'ε'; } break; case 'ά': tmp[i] = 'α'; break; case 'α': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ε'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ε'; tmp[i + 1] = ' '; } } else { tmp[i] = 'α'; } break; case 'ί': case 'ή': case 'ύ': case 'ι': case 'η': case 'υ': case 'ϋ': case 'ΰ': case 'ϊ': case 'ΐ': tmp[i] = 'ι'; break; case 'ώ': tmp[i] = 'ο'; break; case 'ω': tmp[i] = 'ο'; break; } } for (int i = 0; i < tmp.length; i++) { if (tmp[i] == ' ') { if (i + 1 < tmp.length) { tmp[i] = tmp[i + 1]; tmp[i + 1] = ' '; counter++; } } } return new String(tmp); } /** * This methods is not used by Soundex. * It is used only for the production of the phonetic transcription. * @param word, a string to be modified, based on vowel digram combinations, * that when combined, produce a different sound.E.g 'αι' => 'ε' * * @return the modified @param if applicable, or the original @param * otherwise */ private static String groupVowelsPhonetically(String word) { // remove group vowels if necessary to single ones char[] tmp = word.toCharArray(); int counter = 0; for (int i = 0; i < tmp.length; i++) { switch (tmp[i]) { case 'ό': tmp[i] = 'ο'; break; case 'ο': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'υ') { tmp[i] = 'u'; // this is the difference with the SoundexGR tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ύ') { tmp[i] = 'u'; // this is the difference with the SoundexGR tmp[i + 1] = ' '; } } else { tmp[i] = 'ο'; } break; case 'έ': tmp[i] = 'ε'; break; case 'ε': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ι'; tmp[i + 1] = ' '; } } else { tmp[i] = 'ε'; } break; case 'ά': tmp[i] = 'α'; break; case 'α': if (i + 1 < tmp.length) { if (tmp[i + 1] == 'ι') { tmp[i] = 'ε'; tmp[i + 1] = ' '; } if (tmp[i + 1] == 'ί') { tmp[i] = 'ε'; tmp[i + 1] = ' '; } } else { tmp[i] = 'α'; } break; case 'ί': case 'ή': case 'ύ': case 'ι': case 'η': case 'υ': case 'ϋ': case 'ΰ': case 'ϊ': case 'ΐ': tmp[i] = 'ι'; break; case 'ώ': tmp[i] = 'ο'; break; case 'ω': tmp[i] = 'ο'; break; } } for (int i = 0; i < tmp.length; i++) { if (tmp[i] == ' ') { if (i + 1 < tmp.length) { tmp[i] = tmp[i + 1]; tmp[i + 1] = ' '; counter++; } } } return new String(tmp); } /** * * @param word, a string from which the intonation is to be removed. * @return a string without intonation */ private static String removeIntonation(String word){ char[] tmp = word.toCharArray(); for (int i = 0; i < tmp.length; i++) { switch(tmp[i]){ case 'ά': tmp[i]='α'; break; case 'έ': tmp[i]='ε'; break; case 'ό': tmp[i]='ο'; break; case 'ή': tmp[i]='η'; break; case 'ί': tmp[i]='ι'; break; case 'ύ': tmp[i]='υ'; break; case 'ώ': tmp[i]='ω'; break; case 'ΐ': tmp[i]='ι'; break; case 'ϊ': tmp[i]='ι'; break; case 'ΰ': tmp[i]='υ'; break; case 'ϋ': tmp[i]='υ'; break; default: break; } } return new String(tmp); } /** * * @param word, a string to be modified, based on vowel digram combinations, * that when combined, produce a different sound, that is considered a * consonant.E.g 'αυτος' => 'αφτος' * @return the modified @param if applicable, the original @param otherwise */ private static String getVowelAsConsonant(String word) { // Check if a letter contains αυ , ευ and check if the next letter corresponds to a rule char[] tmp = word.toCharArray(); for (int i = 0; i < tmp.length; i++) { if ((tmp[i] == 'υ' || tmp[i] == 'ύ') && (i - 1 >= 0 && isAorE(tmp[i - 1]))) { if ((i + 1) < tmp.length && isAecho(tmp[i + 1])) { tmp[i] = 'φ'; } else if ((i + 1) < tmp.length && (i + 1 < tmp.length && (isVowel(tmp[i + 1]) || isStrong(tmp[i + 1])))) { tmp[i] = 'β'; } if (i == tmp.length - 1) { tmp[i] = 'φ'; } } } return new String(tmp); } /** * * @param word, a string to be modified if it contains specific consonant * digram combinations * @return the modified string */ private static String unwrapConsonantBigrams(String word) { // Reason for example of μπ -> b and not -> β , is that vowels as consonant operation follows and may // wrongly change to a consonant word = word.replace("μπ", "b"); word = word.replace("ντ", "d"); word = word.replace("γκ", "g"); word = word.replace("γγ", "g"); word = word.replace("τσ", "c"); word = word.replace("τζ", "c"); word = word.replace("πς", "ψ"); word = word.replace("πσ", "ψ"); word = word.replace("κς", "ξ"); word = word.replace("κσ", "ξ"); return word; } /** * * Version for the exact phonetic transcription * @param word, a string to be modified if it contains specific consonant * digram combinations * @return the modified string */ private static String unwrapConsonantBigramsPhonetically(String word) { // Reason for example of μπ -> b and not -> β , is that vowels as consonant operation follows and may // wrongly change to a consonant word = word.replace("μπ", "b"); word = word.replace("ντ", "d"); word = word.replace("γκ", "g"); word = word.replace("γγ", "g"); word = word.replace("τσ", "ts"); // different than plain (in soundex: c) word = word.replace("τζ", "dz"); // different than plain (in soundex: c) word = word.replace("πς", "ψ"); word = word.replace("πσ", "ψ"); word = word.replace("κς", "ξ"); word = word.replace("κσ", "ξ"); return word; } /** * * @param word, word to be encode through this Soundex implementation * @return an encoded word */ public static String encode(String word) { //The following function calls could be merged together in to one loop for better performance word = word.toLowerCase(); // word to lowercase word = unwrapConsonantBigrams(word); // αφαίρεση δίφθογγων - dual letter substitution to single //System.out.println(word + " (after unwrapConsonantBigrams)"); word = getVowelAsConsonant(word); // μετατροπή ευ,<SUF> //System.out.println(" " + word + " (after getVoelsAsConsonants)"); // removeLast and removeLastStrict or almost useless, now that the word is trimmed to just 6 digits word = removeLastStrict(word); // αφαίρεση του suffix της λέξης - suffix removal //System.out.println(" " + word + " (after getLastStrict)"); word = groupVowels(word); // μετατροπή φωνήεντων πχ αι σε ε - substitute group vowels to single vowel. //System.out.println(" " + word + " (after groupVowels)"); word = removeIntonation(word); //System.out.println(" " + word + " (after removeIntonation)"); word = String.join("", word.split(" ")); char[] givenWord = word.toCharArray(); char[] res = new char[givenWord.length]; int i = 1; res[0] = word.charAt(0); givenWord = word.substring(i).toCharArray(); for (char c : givenWord) { switch (c) { case 'β': case 'b': case 'φ': case 'π': res[i] = '1'; break; case 'γ': case 'χ': res[i] = '2'; break; case 'δ': case 'τ': case 'd': case 'θ': res[i] = '3'; break; case 'ζ': case 'σ': case 'ς': case 'ψ': case 'c': case 'ξ': res[i] = '4'; break; case 'κ': case 'g': res[i] = '5'; break; case 'λ': res[i] = '6'; break; case 'μ': case 'ν': res[i] = '7'; break; case 'ρ': res[i] = '8'; break; case 'α': res[i] = '9'; break; case 'ε': res[i] = '*'; break; case 'ο': case 'ω': res[i] = '$'; break; case 'ι': res[i] = '@'; break; default: res[i] = '0'; break; } i++; } //for (int z=0; z<res.length;z++) // System.out.print(res[z]); //System.out.println(" (after encode)"); String finalResult = ""; // Remove duplicates finalResult += res[0]; for (i = 1; i < res.length; i++) { if (res[i] != '0') { if (res[i] != res[i - 1]) { finalResult += res[i]; } } } //for (int z=0; z<res.length;z++) // System.out.print(res[z]); //System.out.println(" (after remove duplicates)"); //finalResult += "00000000"; finalResult += "00000000000000000000"; // needed only in the case the lenth of the code is big return finalResult.substring(0, LengthEncoding); // 4 letter length encoding } /** * It is a variation of the SoundexGR for returning a kind of phonetic transcription of the entire word * @param word, word to be encode * @return phonetic transcription of the word */ public static String phoneticTrascription(String word) { word = word.toLowerCase(); // word to lowercase //word = unwrapConsonantBigrams(word); // αφαίρεση δίφθογγων - dual letter substitution to single word = unwrapConsonantBigramsPhonetically(word); // NEW //System.out.println(word + " (after unwrapConsonantBigrams Phonetically)"); word = getVowelAsConsonant(word); // μετατροπή ευ, αυ σε σύμφωνο , αν ακολουθεί κάποιο άηχο ή ηχηρό γράμμα - substitution of υ vowel to consonant if needed //System.out.println(" " + word + " (after getVoelsAsConsonants)"); // removeLast and removeLastStrict or almost useless, now that the word is trimmed to just 6 digits //word = removeLastStrict(word); // αφαίρεση του suffix της λέξης - suffix removal //System.out.println(" " + word + " (after getLastStrict)"); //word = groupVowels(word); // μετατροπή φωνήεντων πχ αι σε ε - substitute group vowels to single vowel. word = groupVowelsPhonetically(word); // NEW //System.out.println(" " + word + " (after groupVowels phonetically)"); //word = removeIntonation(word); //System.out.println(" " + word + " (after removeIntonation)"); word = String.join("", word.split(" ")); char[] givenWord = word.toCharArray(); char[] res = new char[givenWord.length]; int i = 0; givenWord = word.substring(i).toCharArray(); for (char c : givenWord) { switch (c) { case 'b': res[i]='b'; break; case 'd': res[i]='d'; break; case 'c': res[i]='c'; break; case 'g': res[i]='g'; break; case 'u': res[i]='u'; break; // different with soundexGR (for capturing U) //--------------- case 'α': res[i]='a'; break; case 'β': res[i]='v'; break; // different case 'γ': res[i]='γ'; break; case 'δ': res[i]='δ'; break; case 'ε': res[i]='e'; break; // different case 'ζ': res[i]='ζ'; break; case 'η': res[i]='i'; break; // different case 'θ': res[i]='θ'; break; case 'ι': res[i]='i'; break; case 'κ': res[i]='k'; break; // different case 'λ': res[i]='l'; break; // different case 'μ': res[i]='m'; break; // different case 'ν': res[i]='n'; break; // different case 'ξ': res[i]='ξ'; break; case 'ο': res[i]='ο'; break; case 'π': res[i]='p'; break; // different case 'ρ': res[i]='r'; break; // different case 'σ': res[i]='s'; break; // different case 'ς': res[i]='s'; break; // different case 'τ': res[i]='t'; break; // different case 'υ': res[i]='U'; break; case 'φ': res[i]='φ'; break; case 'χ': res[i]='χ'; break; case 'ψ': res[i]='ψ'; break; case 'ω': res[i]='ο'; break; default: //res[i] = '0'; res[i] = c; // NEW break; } i++; } return new String(res); } public static void main(String[] args) { String[] examples = { "αυγό", "αβγό", "εύδοξος", "έβδοξος", "ουουου", "μπουμπούκι", "ούλα", "έμπειρος", "νούς", "ευάερος", "δίαλλειμα", "διάλυμα", "αυλών", "αυγουλάκια", "τζατζίκι", "τσιγκούνης", "τσιγγούνης", "εύδοξος", "Γιάννης", "Γιάνης", "Μοίνοιματα", "προύχοντας" }; //System.out.printf("%11s -> %s %s \n", "Word" , "SoundexGR" , "Phonetic Transcription"); LengthEncoding =4; for (String word: examples) { System.out.printf("%11s -> %s %s \n", word, encode(word), phoneticTrascription(word)); } } }
773_1
package gr.demokritos.iit.ydsapi.model; import java.util.List; import java.util.Map; /** * * @author George K. <[email protected]> */ public class ProjectInfo { List<Map<String, Object>> data; public ProjectInfo(List<Map<String, Object>> data) { this.data = data; } public List getData() { return data; } // String projectName; // "Ανάπλαση Νέας Παραλίας Θεσσαλονίκης - Τμήμα από το Βασιλικο Θέατρο έως τους Ομίλους Θαλασσίων Αθλημάτων Κωδικός 272150", // "completion":"96.0%","budget":"22031920.00","decisions":"34","totalAmount":"14102155.04"}]} }
YourDataStories/components-visualisation
BackendUtilities/src/main/java/gr/demokritos/iit/ydsapi/model/ProjectInfo.java
293
// "Ανάπλαση Νέας Παραλίας Θεσσαλονίκης - Τμήμα από το Βασιλικο Θέατρο έως τους Ομίλους Θαλασσίων Αθλημάτων Κωδικός 272150",
line_comment
el
package gr.demokritos.iit.ydsapi.model; import java.util.List; import java.util.Map; /** * * @author George K. <[email protected]> */ public class ProjectInfo { List<Map<String, Object>> data; public ProjectInfo(List<Map<String, Object>> data) { this.data = data; } public List getData() { return data; } // String projectName; // "Ανάπλαση Νέας<SUF> // "completion":"96.0%","budget":"22031920.00","decisions":"34","totalAmount":"14102155.04"}]} }
940_0
package testbed.review; import java.io.*; import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDateTime; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; /** * Αναπτύξτε μία εφαρμογή που διαβάζει έναν-έναν τους χαρακτήρες ενός αρχείου * και τους εισάγει σε ένα πίνακα 256x2. Κάθε θέση του πίνακα είναι επομένως * ένας πίνακας δύο θέσεων, όπου στη 1η θέση αποθηκεύεται ο χαρακτήρας που έχει * διαβαστεί (αν δεν υπάρχει ήδη στον πίνακα) και στη 2η θέση αποθηκεύεται το πλήθος * των φορών που έχει διαβαστεί (βρεθεί) κάθε χαρακτήρας. Χαρακτήρες θεωρούνται και τα * κενά και οι αλλαγές γραμμής και γενικά οποιοσδήποτε UTF-8 χαρακτήρας. * Στο τέλος η main() παρουσιάζει στατιστικά στοιχεία για κάθε χαρακτήρα όπως η συχνότητα * εμφάνισής του στο κείμενο ταξινομημένα ανά χαρακτήρα και ανά συχνότητα εμφάνισης. */ public class CharReadAndStatisticsApp { final static Path path = Paths.get("C:/tmp/logTextStatistics.txt"); final static int[][] text = new int[256][2]; static int pivot = -1; static int count = 0; final static Scanner in = new Scanner(System.in); public static void main(String[] args) { try { readTextAndSaveService(); printStatisticsService(); } catch (IOException e) { System.out.println("Error in I/O"); } } /** * Reads text from a file using a FileInputStream with 4096 bytes buffering. * Then, each char is saved in the 2D array. * * @throws IOException * if file name is invalid. * @throws IllegalArgumentException * if 2D array is full or any storage error. */ public static void readTextAndSaveService() throws IOException, IllegalArgumentException { int ch; byte[] buf = new byte[4096]; int n = 0; try (FileInputStream fs = new FileInputStream("C:/tmp/inputText.txt");) { while ((n = fs.read(buf)) > 0) { for (int i = 0; i < n; i++) { if (!saveChar(buf[i])) throw new IllegalArgumentException("Error in save"); else { count++; } } } } catch (IOException | IllegalArgumentException e ) { log(e); throw e; } } /** * For each char in the input text, ot prints the count and * the percentage, sorted by char asc and percentage asc. */ public static void printStatisticsService() { int[][] copiedText = Arrays.copyOfRange(text, 0, pivot + 1); Arrays.sort(copiedText, Comparator.comparing(a -> a[0])); System.out.println("Statistics (Char Ascending)"); for (int[] ints : copiedText) { System.out.printf("%c\t%d\t%.4f%%\n", ints[0], ints[1], ints[1] / (double) count); } Arrays.sort(copiedText, Comparator.comparing(a -> a[1])); System.out.println("Statistics (Percentage Ascending)"); for (int[] ints : copiedText) { System.out.printf("%c\t%d\t%.4f%%\n", ints[0], ints[1], ints[1] / (double) count); } } /** * Inserts a char in a 2D array together with its * occurrences' count in the text. * * @param ch the char * @return true, if the char inserted in 2D array, * false, otherwise. */ public static boolean saveChar(int ch) { int charPosition = -1; boolean inserted = false; if (isFull(text)) { return false; } charPosition = getCharPosition(ch); if (charPosition == -1) { pivot++; text[pivot][0] = ch; text[pivot][1] += 1; inserted = true; } else { text[charPosition][1]++; inserted = true; } return inserted; } public static int getCharPosition(int ch) { for (int i = 0; i <= pivot; i++) { if (text[i][0] == ch) { return i; } } return -1; } public static boolean isFull(int[][] text) { return pivot == text.length - 1; } public static void log(Exception e) { try (PrintStream ps = new PrintStream(new FileOutputStream(path.toFile(), true))) { ps.println(LocalDateTime.now() + "\n" + e); } catch (IOException ex) { ex.printStackTrace(); } } }
a8anassis/cf-structured-review
CharReadAndStatisticsApp.java
1,543
/** * Αναπτύξτε μία εφαρμογή που διαβάζει έναν-έναν τους χαρακτήρες ενός αρχείου * και τους εισάγει σε ένα πίνακα 256x2. Κάθε θέση του πίνακα είναι επομένως * ένας πίνακας δύο θέσεων, όπου στη 1η θέση αποθηκεύεται ο χαρακτήρας που έχει * διαβαστεί (αν δεν υπάρχει ήδη στον πίνακα) και στη 2η θέση αποθηκεύεται το πλήθος * των φορών που έχει διαβαστεί (βρεθεί) κάθε χαρακτήρας. Χαρακτήρες θεωρούνται και τα * κενά και οι αλλαγές γραμμής και γενικά οποιοσδήποτε UTF-8 χαρακτήρας. * Στο τέλος η main() παρουσιάζει στατιστικά στοιχεία για κάθε χαρακτήρα όπως η συχνότητα * εμφάνισής του στο κείμενο ταξινομημένα ανά χαρακτήρα και ανά συχνότητα εμφάνισης. */
block_comment
el
package testbed.review; import java.io.*; import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDateTime; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; /** * Αναπτύξτε μία εφαρμογή<SUF>*/ public class CharReadAndStatisticsApp { final static Path path = Paths.get("C:/tmp/logTextStatistics.txt"); final static int[][] text = new int[256][2]; static int pivot = -1; static int count = 0; final static Scanner in = new Scanner(System.in); public static void main(String[] args) { try { readTextAndSaveService(); printStatisticsService(); } catch (IOException e) { System.out.println("Error in I/O"); } } /** * Reads text from a file using a FileInputStream with 4096 bytes buffering. * Then, each char is saved in the 2D array. * * @throws IOException * if file name is invalid. * @throws IllegalArgumentException * if 2D array is full or any storage error. */ public static void readTextAndSaveService() throws IOException, IllegalArgumentException { int ch; byte[] buf = new byte[4096]; int n = 0; try (FileInputStream fs = new FileInputStream("C:/tmp/inputText.txt");) { while ((n = fs.read(buf)) > 0) { for (int i = 0; i < n; i++) { if (!saveChar(buf[i])) throw new IllegalArgumentException("Error in save"); else { count++; } } } } catch (IOException | IllegalArgumentException e ) { log(e); throw e; } } /** * For each char in the input text, ot prints the count and * the percentage, sorted by char asc and percentage asc. */ public static void printStatisticsService() { int[][] copiedText = Arrays.copyOfRange(text, 0, pivot + 1); Arrays.sort(copiedText, Comparator.comparing(a -> a[0])); System.out.println("Statistics (Char Ascending)"); for (int[] ints : copiedText) { System.out.printf("%c\t%d\t%.4f%%\n", ints[0], ints[1], ints[1] / (double) count); } Arrays.sort(copiedText, Comparator.comparing(a -> a[1])); System.out.println("Statistics (Percentage Ascending)"); for (int[] ints : copiedText) { System.out.printf("%c\t%d\t%.4f%%\n", ints[0], ints[1], ints[1] / (double) count); } } /** * Inserts a char in a 2D array together with its * occurrences' count in the text. * * @param ch the char * @return true, if the char inserted in 2D array, * false, otherwise. */ public static boolean saveChar(int ch) { int charPosition = -1; boolean inserted = false; if (isFull(text)) { return false; } charPosition = getCharPosition(ch); if (charPosition == -1) { pivot++; text[pivot][0] = ch; text[pivot][1] += 1; inserted = true; } else { text[charPosition][1]++; inserted = true; } return inserted; } public static int getCharPosition(int ch) { for (int i = 0; i <= pivot; i++) { if (text[i][0] == ch) { return i; } } return -1; } public static boolean isFull(int[][] text) { return pivot == text.length - 1; } public static void log(Exception e) { try (PrintStream ps = new PrintStream(new FileOutputStream(path.toFile(), true))) { ps.println(LocalDateTime.now() + "\n" + e); } catch (IOException ex) { ex.printStackTrace(); } } }
20028_0
package gr.aueb.cf.ch6; /** * Μπορούμε να δώσουμε διαφορετικές * διαστάσεις σε κάθε γραμμή του * δισδιάστατου πίνακα. */ public class JaggedArrayApp { public static void main(String[] args) { int[][] arr = new int[3][]; // Σε κάθε γραμμή εκχωρούμε ένα // πίνακα με διαφορετική διάσταση arr[0] = new int[4]; arr[1] = new int[3]; arr[2] = new int[2]; for (int[] row : arr) { for (int col : row) { System.out.print(col + " "); } System.out.println(); } } }
a8anassis/cf4
src/gr/aueb/cf/ch6/JaggedArrayApp.java
270
/** * Μπορούμε να δώσουμε διαφορετικές * διαστάσεις σε κάθε γραμμή του * δισδιάστατου πίνακα. */
block_comment
el
package gr.aueb.cf.ch6; /** * Μπορούμε να δώσουμε<SUF>*/ public class JaggedArrayApp { public static void main(String[] args) { int[][] arr = new int[3][]; // Σε κάθε γραμμή εκχωρούμε ένα // πίνακα με διαφορετική διάσταση arr[0] = new int[4]; arr[1] = new int[3]; arr[2] = new int[2]; for (int[] row : arr) { for (int col : row) { System.out.print(col + " "); } System.out.println(); } } }
4524_0
package gr.aueb.cf.ch3; import java.util.Scanner; /** * Συνεχίζει το διάβασμα μέχρι να δοθεί μία * ειδική τιμή (sentinel) έστω -1. */ public class SentinelApp { public static void main(String[] args) { Scanner in = new Scanner(System.in); int num = 0; int iterations = 0; System.out.println("Please insert a num (-1 for exit)"); //num = in.nextInt(); while ((num = in.nextInt()) != -1) { iterations++; System.out.println("Please insert a num (-1 for exit)"); //num = in.nextInt(); } System.out.println("Positives count: " + iterations); } }
a8anassis/cf6-java
src/gr/aueb/cf/ch3/SentinelApp.java
220
/** * Συνεχίζει το διάβασμα μέχρι να δοθεί μία * ειδική τιμή (sentinel) έστω -1. */
block_comment
el
package gr.aueb.cf.ch3; import java.util.Scanner; /** * Συνεχίζει το διάβασμα<SUF>*/ public class SentinelApp { public static void main(String[] args) { Scanner in = new Scanner(System.in); int num = 0; int iterations = 0; System.out.println("Please insert a num (-1 for exit)"); //num = in.nextInt(); while ((num = in.nextInt()) != -1) { iterations++; System.out.println("Please insert a num (-1 for exit)"); //num = in.nextInt(); } System.out.println("Positives count: " + iterations); } }
3121_0
package gr.aueb.cf.testbed.ch5; import java.util.Scanner; /** * Εμφανίζει ένα μενού επιλογών, λαμβάνει τιμή * από τον χρήστη, λαμβάνει δύο τιμές και εμφανίζει * το αποτέλεσμα. */ public class MenuApp { // Class global scoping static Scanner in = new Scanner(System.in); public static void main(String[] args) { int result = 0; int choice = 0; do { printMenu(); choice = getNextInt("Please insert your choice"); if (isChoiceInvalid(choice)) { System.out.println("Invalid choice"); continue; } if (isChoiceQuit(choice)) { System.out.println("Thanks for using the app.."); break; } result = onChoiceGetResult(choice); System.out.println("Result: " + result); } while (true); } public static void printMenu() { System.out.println("Επιλέξτε ένα από τα παρακάτω"); System.out.println("1. Πρόσθεση"); System.out.println("2. Αφαίρεση"); System.out.println("3. Πολλαπλασιασμός"); System.out.println("4. Διαίρεση"); System.out.println("5. Υπόλοιπο (Modulus)"); System.out.println("6. Έξοδος"); } public static boolean isChoiceInvalid(int choice) { return choice < 1 || choice > 6; } public static boolean isChoiceQuit(int choice) { return choice == 6; } public static int getNextInt(String s) { System.out.println(s); return in.nextInt(); } public static int add(int a, int b) { return a + b; } public static int sub(int a, int b) { return a - b; } public static int mul(int a, int b) { return a * b; } public static int div(int a, int b) { if (b == 0) { return Integer.MAX_VALUE; } return a / b; } public static int mod(int a, int b) { if (b == 0) { return Integer.MAX_VALUE; } return a % b; } public static int onChoiceGetResult(int choice) { int num1 = getNextInt("Please insert the first int"); int num2 = getNextInt("Please insert the second int"); int result = 0; switch (choice) { case 1: result = add(num1, num2); break; case 2: result = sub(num1, num2); break; case 3: result = mul(num1, num2); break; case 4: result = div(num1, num2); break; case 5: result = mod(num1, num2); break; default: break; } return result; } }
a8anassis/codingfactory23a
src/gr/aueb/cf/testbed/ch5/MenuApp.java
835
/** * Εμφανίζει ένα μενού επιλογών, λαμβάνει τιμή * από τον χρήστη, λαμβάνει δύο τιμές και εμφανίζει * το αποτέλεσμα. */
block_comment
el
package gr.aueb.cf.testbed.ch5; import java.util.Scanner; /** * Εμφανίζει ένα μενού<SUF>*/ public class MenuApp { // Class global scoping static Scanner in = new Scanner(System.in); public static void main(String[] args) { int result = 0; int choice = 0; do { printMenu(); choice = getNextInt("Please insert your choice"); if (isChoiceInvalid(choice)) { System.out.println("Invalid choice"); continue; } if (isChoiceQuit(choice)) { System.out.println("Thanks for using the app.."); break; } result = onChoiceGetResult(choice); System.out.println("Result: " + result); } while (true); } public static void printMenu() { System.out.println("Επιλέξτε ένα από τα παρακάτω"); System.out.println("1. Πρόσθεση"); System.out.println("2. Αφαίρεση"); System.out.println("3. Πολλαπλασιασμός"); System.out.println("4. Διαίρεση"); System.out.println("5. Υπόλοιπο (Modulus)"); System.out.println("6. Έξοδος"); } public static boolean isChoiceInvalid(int choice) { return choice < 1 || choice > 6; } public static boolean isChoiceQuit(int choice) { return choice == 6; } public static int getNextInt(String s) { System.out.println(s); return in.nextInt(); } public static int add(int a, int b) { return a + b; } public static int sub(int a, int b) { return a - b; } public static int mul(int a, int b) { return a * b; } public static int div(int a, int b) { if (b == 0) { return Integer.MAX_VALUE; } return a / b; } public static int mod(int a, int b) { if (b == 0) { return Integer.MAX_VALUE; } return a % b; } public static int onChoiceGetResult(int choice) { int num1 = getNextInt("Please insert the first int"); int num2 = getNextInt("Please insert the second int"); int result = 0; switch (choice) { case 1: result = add(num1, num2); break; case 2: result = sub(num1, num2); break; case 3: result = mul(num1, num2); break; case 4: result = div(num1, num2); break; case 5: result = mod(num1, num2); break; default: break; } return result; } }
8994_0
package gr.aueb.cf.solutions.ch2; import java.util.Scanner; /** * Διαβάζει τρεις ακέραιους αριθμούς που αναπαριστούν * ημέρα, μήνα, έτος και εμφανίζει σε μορφή ΗΗ/ΜΜ/ΕΕ. * Π.χ., αν δώσουμε 5 12 2022 θα εμφανίσει 05/12/22. */ public class DateApp { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int day = 0; int month = 0; int year = 0; int formattedYear = 0; System.out.print("Please insert three integers for day, month, year: "); day = scanner.nextInt(); month = scanner.nextInt(); year = scanner.nextInt(); formattedYear = year % 100; System.out.printf("%02d/%02d/%2d\n", day, month, formattedYear); } }
a8anassis/codingfactory5-java
src/gr/aueb/cf/solutions/ch2/DateApp.java
316
/** * Διαβάζει τρεις ακέραιους αριθμούς που αναπαριστούν * ημέρα, μήνα, έτος και εμφανίζει σε μορφή ΗΗ/ΜΜ/ΕΕ. * Π.χ., αν δώσουμε 5 12 2022 θα εμφανίσει 05/12/22. */
block_comment
el
package gr.aueb.cf.solutions.ch2; import java.util.Scanner; /** * Διαβάζει τρεις ακέραιους<SUF>*/ public class DateApp { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int day = 0; int month = 0; int year = 0; int formattedYear = 0; System.out.print("Please insert three integers for day, month, year: "); day = scanner.nextInt(); month = scanner.nextInt(); year = scanner.nextInt(); formattedYear = year % 100; System.out.printf("%02d/%02d/%2d\n", day, month, formattedYear); } }
36194_1
package gr.aueb.elearn.chap1; // Το πρώτο πρόγραμμα Java - by thanassis /* Το πρόγραμμα αυτό εκτυπώνει στην οθόνη (std output) το αλφαριθμητικό Hello World! */ public class HelloWorld { public static void main(String[] args) { System.out.print("Hello World!"); System.out.println(); System.out.printf("Hello Alice!\n"); } }
a8anassis/java-elearn
HelloWorld.java
159
/* Το πρόγραμμα αυτό εκτυπώνει στην οθόνη (std output) το αλφαριθμητικό Hello World! */
block_comment
el
package gr.aueb.elearn.chap1; // Το πρώτο πρόγραμμα Java - by thanassis /* Το πρόγραμμα αυτό<SUF>*/ public class HelloWorld { public static void main(String[] args) { System.out.print("Hello World!"); System.out.println(); System.out.printf("Hello Alice!\n"); } }
6284_40
/* * Created by bijay * GOFLEX :: WP2 :: foa-core * Copyright (c) 2018. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software") to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: The above copyright notice and * this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON * INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * Last Modified 2/8/18 4:17 PM */ package org.goflex.wp2.foa.listeners; import org.goflex.wp2.core.entities.*; import org.goflex.wp2.core.models.*; import org.goflex.wp2.core.repository.OrganizationRepository; import org.goflex.wp2.foa.events.FlexOfferScheduleReceivedEvent; import org.goflex.wp2.foa.events.FlexOfferStatusUpdateEvent; import org.goflex.wp2.foa.implementation.ImplementationsHandler; import org.goflex.wp2.foa.interfaces.*; import org.goflex.wp2.foa.util.TimeZoneUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; /** * Created by bijay on 7/22/17. */ @Component public class FlexOfferScheduleReceivedListener implements ApplicationListener<FlexOfferScheduleReceivedEvent> { private static final long interval = 900 * 1000; private static final Logger LOGGER = LoggerFactory.getLogger(FlexOfferScheduleReceivedListener.class); private ScheduleService scheduleService; private DeviceDetailService deviceDetailService; private ImplementationsHandler implementationsHandler; private ApplicationEventPublisher applicationEventPublisher; private DeviceDefaultState deviceDefaultState; private DeviceFlexOfferGroup deviceFlexOfferGroup; private SmsService smsService; private FOAService foaService; private OrganizationRepository organizationRepository; private UserService userService; @Resource(name = "scheduleDetailTable") private ConcurrentHashMap<Date, ScheduleDetails> scheduleDetail; @Resource(name = "deviceLatestFO") private ConcurrentHashMap<String, FlexOfferT> deviceLatestFO; @Resource(name = "deviceActiveSchedule") private ConcurrentHashMap<String, Map<Date, Integer>> deviceActiveSchedule; public FlexOfferScheduleReceivedListener(ScheduleService scheduleService, DeviceDetailService deviceDetailService, ImplementationsHandler implementationsHandler, ApplicationEventPublisher applicationEventPublisher, DeviceDefaultState deviceDefaultState, UserService userService, DeviceFlexOfferGroup deviceFlexOfferGroup, SmsService smsService, FOAService foaService, OrganizationRepository organizationRepository) { this.scheduleService = scheduleService; this.deviceDetailService = deviceDetailService; this.implementationsHandler = implementationsHandler; this.applicationEventPublisher = applicationEventPublisher; this.deviceDefaultState = deviceDefaultState; this.userService = userService; this.deviceFlexOfferGroup = deviceFlexOfferGroup; this.smsService = smsService; this.foaService = foaService; this.organizationRepository = organizationRepository; } private void addScheduleToFLS(String offeredById, UUID flexOfferId, Date eventTime, int action) { if (scheduleDetail.containsKey(eventTime)) { scheduleDetail.get(eventTime).addSchedule(offeredById, flexOfferId, action); } else { scheduleDetail.put(eventTime, new ScheduleDetails(offeredById, flexOfferId, action)); } } private boolean deleteScheduleFromDevice(String offeredById, PlugType plugType, String scheduleID, int action) { return implementationsHandler.get(plugType).deleteOnOffSchedule( offeredById.split("@")[1], offeredById.split("@")[0], scheduleID, action); } /** * if index -1, return device default */ private int getAction(int index, int lastAction, Double energyAmount, DeviceDetail device) { double minEnergyThreshold = 1.0; // min 1Wh in a slice else it's a very small value due to FMAN optimization int action; int defaultState = deviceDefaultState.getDeviceDefaultState(device.getDeviceType());// //device.getDefaultState(); // if not last slice if (index != -1) { //This will handle both production and consumption FOs, i.e, for production fo energy is -ve //if (energyAmount != 0) { if (energyAmount * 1000 > minEnergyThreshold) { action = 1; } else { action = 0; } } else { // This is used to revert back the load to default state, after last slice if (lastAction == 1) { if (defaultState == 1) { action = -1; } else { action = 0; } } else { if (defaultState == 1) { action = 1; } else { action = -1; } } } return action; } private OnOffSchedule createOnOffSchedule(String offerById, int action, Double energyAmount, boolean isLast) { OnOffSchedule newSchedule = new OnOffSchedule(offerById); newSchedule.setRegisteredTime(new Date()); newSchedule.setEnergyLevel(energyAmount); newSchedule.setScheduleToState(action); newSchedule.setLast(isLast); return newSchedule; } private String pushScheduleToDevice(DeviceDetail device, String offeredById, UUID flexOfferId, Date startDate, int state) { // push schedule to smart device String scheduleId = implementationsHandler.get(device.getPlugType()).addOnOffSchedule( offeredById.split("@")[1], offeredById.split("@")[0], startDate, state); if (device.getPlugType() == PlugType.Simulated) { this.addScheduleToFLS(offeredById, flexOfferId, startDate, state); } return scheduleId; } private boolean invalidateOldSchedule(Date startDate, OnOffSchedule newSchedule, OnOffSchedule oldSchedule, String offeredById, DeviceDetail device) { boolean status; // invalidate previous schedule from database status = scheduleService.inValidateSchedule(startDate, newSchedule.getDeviceID()); // remove schedule from smart device if (oldSchedule.getExternalScheduleId() != null || !oldSchedule.getExternalScheduleId().equals("")) { if (this.deleteScheduleFromDevice(offeredById, device.getPlugType(), oldSchedule.getExternalScheduleId(), 1) == false) { status = false; LOGGER.warn("Could not delete existing schedule."); } else { LOGGER.info("Old Schedule deleted from smartplug"); } } return status; } private boolean invalidateOldSchedule(String flexOfferId, String offeredById, PlugType plugType) { boolean status = true; /**invalidate previous schedule from database */ status = scheduleService.inValidateSchedule(flexOfferId); /**remove schedule from smart device*/ for (OnOffSchedule onOffSchedule : scheduleService.getOnOffSchedules(flexOfferId)) { if (onOffSchedule.getExternalScheduleId() != null && !onOffSchedule.getExternalScheduleId().equals("")) { if (this.deleteScheduleFromDevice(offeredById, plugType, onOffSchedule.getExternalScheduleId(), 1) == false) { status = false; LOGGER.warn("Could not delete existing schedule."); } else { LOGGER.info("Old Schedule deleted from smartplug"); } } } return status; } private String addSchedule(int index, Date startDate, OnOffSchedule schedule, UUID flexOfferId, String offeredById, DeviceDetail device) { // Check if we already have key for a particular time, if not create a schedule table with the key ScheduleT hasKey = scheduleService.getByDate(startDate); if (hasKey == null) { // Persist the new schedule table ScheduleT savedSchedule = scheduleService.save(new ScheduleT(startDate)); } // insert new schedule String scheduleId = null; try { //TODO: handling schedule at TPLink plug is complex need better model. For now we dont push schedule to plug scheduleId = ""; //scheduleId = this.pushScheduleToDevice(device, offeredById, flexOfferId, startDate, schedule // .getScheduleToState()); //if flex-offer schedule Assignment event FlexOfferStatusUpdateEvent flexOfferStatusUpdateEvent = new FlexOfferStatusUpdateEvent(this, "FO Status Updated", "", flexOfferId, FlexOfferState.Assigned); applicationEventPublisher.publishEvent(flexOfferStatusUpdateEvent); } catch (Exception ex) { LOGGER.warn("Could not pass schedule to tplink cloud"); } // if successfully pushed to smart device, device would handle schedule, // else schedule handler will execute all un-pushed schedules if (scheduleId != null && !scheduleId.equals("")) { schedule.setPushedToDevice(1); schedule.setExternalScheduleId(scheduleId); } schedule.setFlexOfferId(flexOfferId.toString()); // add new schedule to the system scheduleService.addSchedulesForKey(startDate, schedule); return scheduleId; } @Override @Transactional public void onApplicationEvent(FlexOfferScheduleReceivedEvent event) { try { LOGGER.debug(event.getEvent() + " at " + event.getTimestamp()); /** this will run only when scheduled received from FMAN, * no need for schedule generated during FO generation */ if (!event.getDefaultSchedule()) { LOGGER.info("New scheduled received from FMAN_FMAR for flex-offer with ID =>{}", event.getFlexOffer().getId()); /** update schedule update id by 1 */ event.getNewSchedule().setUpdateId(event.getFlexOffer().getFlexOfferSchedule().getUpdateId() + 1); /**update flex-offer schedule */ event.getFlexOffer().setFlexOfferSchedule(event.getNewSchedule()); LOGGER.info("Scheduled updated for Flex-offer with ID =>{}", event.getFlexOffer().getId()); // also update FlexOfferT FlexOfferT flexOfferT = this.foaService.getFlexOffer(event.getFlexOffer().getId()); flexOfferT.setFlexoffer(event.getFlexOffer()); // also update device->FO memory map this.deviceLatestFO.put(event.getFlexOffer().getOfferedById(), flexOfferT); LOGGER.info("deviceLatestFO map updated for device: {}", event.getFlexOffer().getOfferedById()); } Date startDate = event.getNewSchedule().getStartTime(); Date currentDate = new Date(); int lastAction = -1; int action; // check if current date is after the start time date if (startDate.after(currentDate)) { String offeredById = event.getFlexOffer().getOfferedById(); DeviceDetail device = deviceDetailService.getDevice(offeredById); String userName = device.getDeviceId().split("@")[0]; UserT userT = this.userService.getUser(userName); Organization org = this.organizationRepository.findByOrganizationId(userT.getOrganizationId()); //invalidate all old schedule if (this.invalidateOldSchedule(event.getFlexOffer().getId().toString(), offeredById, device.getPlugType())) { // get new schedule from event FlexOfferSchedule newSchedule = event.getNewSchedule(); FlexibilityGroupType flexibilityGroupType = deviceFlexOfferGroup.getDeviceFOGroupType(device.getDeviceType()); // loop through slices in the flex-offer int numSlices = newSchedule.getScheduleSlices().length; boolean alreadySent = false; for (int i = 0; i < numSlices + 1; i++) { // +1 is to put device into default state upon schedule completion LOGGER.debug("Updating new schedule for Flex-offer with ID:" + event.getFlexOffer().getId()); // start date is the schedule start time startDate = new Date(startDate.getTime() + i * interval); int idx = i < numSlices ? i : -1; double energyAmount = i < numSlices ? newSchedule.getScheduleSlice(i).getEnergyAmount() : -1.0; action = this.getAction(idx, lastAction, energyAmount, device); if (!this.deviceActiveSchedule.containsKey(device.getDeviceId())) { Map<Date, Integer> val = new HashMap<>(); val.put(startDate, action); this.deviceActiveSchedule.put(device.getDeviceId(), val); } // loop through slices and at the end of schedule device should go to default state // create new schedule and set energy level for each slice OnOffSchedule schedule = createOnOffSchedule(offeredById, action, energyAmount, idx == -1); String scheduleId = this.addSchedule(i, startDate, schedule, event.getFlexOffer().getId(), offeredById, device); //send message of scheduled device operation only for wet devices that needs manual start // for now we assume all wet devices need manual start since we don't have per device info if (scheduleId != null && !event.getDefaultSchedule() && flexibilityGroupType == FlexibilityGroupType.WetLoad && org.getDirectControlMode() == OrganizationLoadControlState.Active) { Map<Date, Integer> val = this.deviceActiveSchedule.get(device.getDeviceId()); Date oldStartDate = (Date) val.keySet().toArray()[0]; int oldAction = val.get(oldStartDate); if (!newSchedule.getStartTime().equals(oldStartDate) || (action == 1 && (action != oldAction || !alreadySent))) { String orgName = org.getOrganizationName(); String stringTime = TimeZoneUtil.getTimeZoneAdjustedStringTime(startDate, orgName); String msg; if (orgName.equals("SWW")) { msg = "Das Gerät " + device.getAlias() + " startet heute um " + stringTime + " Uhr. Bitte schalten Sie das Gerät so bald wie möglich nach " + stringTime + " Uhr ein. Startet das Gerät automatisch, können Sie diese SMS ignorieren."; } else if (org.getOrganizationName().equals("CYPRUS")) { String deviceType = device.getDeviceType() == DeviceType.WasherDryer ? "Washing Machine": device.getDeviceType().name(); // msg = "The " + deviceType + " (" + device.getAlias() + ") will start today at " + stringTime + // ". Please switch on the device as soon as possible after " + stringTime + // ". If the device starts automatically, you can ignore this SMS."; //Η ηλεκτρική παροχή στο συσκευή θα επανέλθει στις 17:30. Σε περίπτωση που το συσκευή δεν επανεκκινεί αυτόματα, παρακαλώ επανεκκινήστε τη συσκευή το συντομότερο μετά τις 17:30. msg = "Η ηλεκτρική παροχή στο " + deviceType + " (" + device.getAlias() + ") θα επανέλθει στις " + stringTime + ". Σε περίπτωση που το συσκευή δεν επανεκκινεί αυτόματα, παρακαλώ επανεκκινήστε τη συσκευή το συντομότερο μετά τις " + stringTime + "."; } else { msg = "The device " + device.getAlias() + " will start today at " + stringTime + ". Please switch on the device as soon as possible after " + stringTime + ". If the device starts automatically, you can ignore this SMS."; } smsService.sendSms(userName, msg); Map<Date, Integer> val2 = new HashMap<>(); val2.put(newSchedule.getStartTime(), action); this.deviceActiveSchedule.put(device.getDeviceId(), val2); alreadySent = true; } } lastAction = action; } } } else { LOGGER.info("Schedule is before Current Time. Schedule Ignored"); } } catch (Exception ex) { ex.printStackTrace(); LOGGER.error(ex.getLocalizedMessage()); } } }
aau-daisy/flexoffer_agent
foa-core/src/main/java/org/goflex/wp2/foa/listeners/FlexOfferScheduleReceivedListener.java
4,154
//Η ηλεκτρική παροχή στο συσκευή θα επανέλθει στις 17:30. Σε περίπτωση που το συσκευή δεν επανεκκινεί αυτόματα, παρακαλώ επανεκκινήστε τη συσκευή το συντομότερο μετά τις 17:30.
line_comment
el
/* * Created by bijay * GOFLEX :: WP2 :: foa-core * Copyright (c) 2018. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software") to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: The above copyright notice and * this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON * INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * Last Modified 2/8/18 4:17 PM */ package org.goflex.wp2.foa.listeners; import org.goflex.wp2.core.entities.*; import org.goflex.wp2.core.models.*; import org.goflex.wp2.core.repository.OrganizationRepository; import org.goflex.wp2.foa.events.FlexOfferScheduleReceivedEvent; import org.goflex.wp2.foa.events.FlexOfferStatusUpdateEvent; import org.goflex.wp2.foa.implementation.ImplementationsHandler; import org.goflex.wp2.foa.interfaces.*; import org.goflex.wp2.foa.util.TimeZoneUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; /** * Created by bijay on 7/22/17. */ @Component public class FlexOfferScheduleReceivedListener implements ApplicationListener<FlexOfferScheduleReceivedEvent> { private static final long interval = 900 * 1000; private static final Logger LOGGER = LoggerFactory.getLogger(FlexOfferScheduleReceivedListener.class); private ScheduleService scheduleService; private DeviceDetailService deviceDetailService; private ImplementationsHandler implementationsHandler; private ApplicationEventPublisher applicationEventPublisher; private DeviceDefaultState deviceDefaultState; private DeviceFlexOfferGroup deviceFlexOfferGroup; private SmsService smsService; private FOAService foaService; private OrganizationRepository organizationRepository; private UserService userService; @Resource(name = "scheduleDetailTable") private ConcurrentHashMap<Date, ScheduleDetails> scheduleDetail; @Resource(name = "deviceLatestFO") private ConcurrentHashMap<String, FlexOfferT> deviceLatestFO; @Resource(name = "deviceActiveSchedule") private ConcurrentHashMap<String, Map<Date, Integer>> deviceActiveSchedule; public FlexOfferScheduleReceivedListener(ScheduleService scheduleService, DeviceDetailService deviceDetailService, ImplementationsHandler implementationsHandler, ApplicationEventPublisher applicationEventPublisher, DeviceDefaultState deviceDefaultState, UserService userService, DeviceFlexOfferGroup deviceFlexOfferGroup, SmsService smsService, FOAService foaService, OrganizationRepository organizationRepository) { this.scheduleService = scheduleService; this.deviceDetailService = deviceDetailService; this.implementationsHandler = implementationsHandler; this.applicationEventPublisher = applicationEventPublisher; this.deviceDefaultState = deviceDefaultState; this.userService = userService; this.deviceFlexOfferGroup = deviceFlexOfferGroup; this.smsService = smsService; this.foaService = foaService; this.organizationRepository = organizationRepository; } private void addScheduleToFLS(String offeredById, UUID flexOfferId, Date eventTime, int action) { if (scheduleDetail.containsKey(eventTime)) { scheduleDetail.get(eventTime).addSchedule(offeredById, flexOfferId, action); } else { scheduleDetail.put(eventTime, new ScheduleDetails(offeredById, flexOfferId, action)); } } private boolean deleteScheduleFromDevice(String offeredById, PlugType plugType, String scheduleID, int action) { return implementationsHandler.get(plugType).deleteOnOffSchedule( offeredById.split("@")[1], offeredById.split("@")[0], scheduleID, action); } /** * if index -1, return device default */ private int getAction(int index, int lastAction, Double energyAmount, DeviceDetail device) { double minEnergyThreshold = 1.0; // min 1Wh in a slice else it's a very small value due to FMAN optimization int action; int defaultState = deviceDefaultState.getDeviceDefaultState(device.getDeviceType());// //device.getDefaultState(); // if not last slice if (index != -1) { //This will handle both production and consumption FOs, i.e, for production fo energy is -ve //if (energyAmount != 0) { if (energyAmount * 1000 > minEnergyThreshold) { action = 1; } else { action = 0; } } else { // This is used to revert back the load to default state, after last slice if (lastAction == 1) { if (defaultState == 1) { action = -1; } else { action = 0; } } else { if (defaultState == 1) { action = 1; } else { action = -1; } } } return action; } private OnOffSchedule createOnOffSchedule(String offerById, int action, Double energyAmount, boolean isLast) { OnOffSchedule newSchedule = new OnOffSchedule(offerById); newSchedule.setRegisteredTime(new Date()); newSchedule.setEnergyLevel(energyAmount); newSchedule.setScheduleToState(action); newSchedule.setLast(isLast); return newSchedule; } private String pushScheduleToDevice(DeviceDetail device, String offeredById, UUID flexOfferId, Date startDate, int state) { // push schedule to smart device String scheduleId = implementationsHandler.get(device.getPlugType()).addOnOffSchedule( offeredById.split("@")[1], offeredById.split("@")[0], startDate, state); if (device.getPlugType() == PlugType.Simulated) { this.addScheduleToFLS(offeredById, flexOfferId, startDate, state); } return scheduleId; } private boolean invalidateOldSchedule(Date startDate, OnOffSchedule newSchedule, OnOffSchedule oldSchedule, String offeredById, DeviceDetail device) { boolean status; // invalidate previous schedule from database status = scheduleService.inValidateSchedule(startDate, newSchedule.getDeviceID()); // remove schedule from smart device if (oldSchedule.getExternalScheduleId() != null || !oldSchedule.getExternalScheduleId().equals("")) { if (this.deleteScheduleFromDevice(offeredById, device.getPlugType(), oldSchedule.getExternalScheduleId(), 1) == false) { status = false; LOGGER.warn("Could not delete existing schedule."); } else { LOGGER.info("Old Schedule deleted from smartplug"); } } return status; } private boolean invalidateOldSchedule(String flexOfferId, String offeredById, PlugType plugType) { boolean status = true; /**invalidate previous schedule from database */ status = scheduleService.inValidateSchedule(flexOfferId); /**remove schedule from smart device*/ for (OnOffSchedule onOffSchedule : scheduleService.getOnOffSchedules(flexOfferId)) { if (onOffSchedule.getExternalScheduleId() != null && !onOffSchedule.getExternalScheduleId().equals("")) { if (this.deleteScheduleFromDevice(offeredById, plugType, onOffSchedule.getExternalScheduleId(), 1) == false) { status = false; LOGGER.warn("Could not delete existing schedule."); } else { LOGGER.info("Old Schedule deleted from smartplug"); } } } return status; } private String addSchedule(int index, Date startDate, OnOffSchedule schedule, UUID flexOfferId, String offeredById, DeviceDetail device) { // Check if we already have key for a particular time, if not create a schedule table with the key ScheduleT hasKey = scheduleService.getByDate(startDate); if (hasKey == null) { // Persist the new schedule table ScheduleT savedSchedule = scheduleService.save(new ScheduleT(startDate)); } // insert new schedule String scheduleId = null; try { //TODO: handling schedule at TPLink plug is complex need better model. For now we dont push schedule to plug scheduleId = ""; //scheduleId = this.pushScheduleToDevice(device, offeredById, flexOfferId, startDate, schedule // .getScheduleToState()); //if flex-offer schedule Assignment event FlexOfferStatusUpdateEvent flexOfferStatusUpdateEvent = new FlexOfferStatusUpdateEvent(this, "FO Status Updated", "", flexOfferId, FlexOfferState.Assigned); applicationEventPublisher.publishEvent(flexOfferStatusUpdateEvent); } catch (Exception ex) { LOGGER.warn("Could not pass schedule to tplink cloud"); } // if successfully pushed to smart device, device would handle schedule, // else schedule handler will execute all un-pushed schedules if (scheduleId != null && !scheduleId.equals("")) { schedule.setPushedToDevice(1); schedule.setExternalScheduleId(scheduleId); } schedule.setFlexOfferId(flexOfferId.toString()); // add new schedule to the system scheduleService.addSchedulesForKey(startDate, schedule); return scheduleId; } @Override @Transactional public void onApplicationEvent(FlexOfferScheduleReceivedEvent event) { try { LOGGER.debug(event.getEvent() + " at " + event.getTimestamp()); /** this will run only when scheduled received from FMAN, * no need for schedule generated during FO generation */ if (!event.getDefaultSchedule()) { LOGGER.info("New scheduled received from FMAN_FMAR for flex-offer with ID =>{}", event.getFlexOffer().getId()); /** update schedule update id by 1 */ event.getNewSchedule().setUpdateId(event.getFlexOffer().getFlexOfferSchedule().getUpdateId() + 1); /**update flex-offer schedule */ event.getFlexOffer().setFlexOfferSchedule(event.getNewSchedule()); LOGGER.info("Scheduled updated for Flex-offer with ID =>{}", event.getFlexOffer().getId()); // also update FlexOfferT FlexOfferT flexOfferT = this.foaService.getFlexOffer(event.getFlexOffer().getId()); flexOfferT.setFlexoffer(event.getFlexOffer()); // also update device->FO memory map this.deviceLatestFO.put(event.getFlexOffer().getOfferedById(), flexOfferT); LOGGER.info("deviceLatestFO map updated for device: {}", event.getFlexOffer().getOfferedById()); } Date startDate = event.getNewSchedule().getStartTime(); Date currentDate = new Date(); int lastAction = -1; int action; // check if current date is after the start time date if (startDate.after(currentDate)) { String offeredById = event.getFlexOffer().getOfferedById(); DeviceDetail device = deviceDetailService.getDevice(offeredById); String userName = device.getDeviceId().split("@")[0]; UserT userT = this.userService.getUser(userName); Organization org = this.organizationRepository.findByOrganizationId(userT.getOrganizationId()); //invalidate all old schedule if (this.invalidateOldSchedule(event.getFlexOffer().getId().toString(), offeredById, device.getPlugType())) { // get new schedule from event FlexOfferSchedule newSchedule = event.getNewSchedule(); FlexibilityGroupType flexibilityGroupType = deviceFlexOfferGroup.getDeviceFOGroupType(device.getDeviceType()); // loop through slices in the flex-offer int numSlices = newSchedule.getScheduleSlices().length; boolean alreadySent = false; for (int i = 0; i < numSlices + 1; i++) { // +1 is to put device into default state upon schedule completion LOGGER.debug("Updating new schedule for Flex-offer with ID:" + event.getFlexOffer().getId()); // start date is the schedule start time startDate = new Date(startDate.getTime() + i * interval); int idx = i < numSlices ? i : -1; double energyAmount = i < numSlices ? newSchedule.getScheduleSlice(i).getEnergyAmount() : -1.0; action = this.getAction(idx, lastAction, energyAmount, device); if (!this.deviceActiveSchedule.containsKey(device.getDeviceId())) { Map<Date, Integer> val = new HashMap<>(); val.put(startDate, action); this.deviceActiveSchedule.put(device.getDeviceId(), val); } // loop through slices and at the end of schedule device should go to default state // create new schedule and set energy level for each slice OnOffSchedule schedule = createOnOffSchedule(offeredById, action, energyAmount, idx == -1); String scheduleId = this.addSchedule(i, startDate, schedule, event.getFlexOffer().getId(), offeredById, device); //send message of scheduled device operation only for wet devices that needs manual start // for now we assume all wet devices need manual start since we don't have per device info if (scheduleId != null && !event.getDefaultSchedule() && flexibilityGroupType == FlexibilityGroupType.WetLoad && org.getDirectControlMode() == OrganizationLoadControlState.Active) { Map<Date, Integer> val = this.deviceActiveSchedule.get(device.getDeviceId()); Date oldStartDate = (Date) val.keySet().toArray()[0]; int oldAction = val.get(oldStartDate); if (!newSchedule.getStartTime().equals(oldStartDate) || (action == 1 && (action != oldAction || !alreadySent))) { String orgName = org.getOrganizationName(); String stringTime = TimeZoneUtil.getTimeZoneAdjustedStringTime(startDate, orgName); String msg; if (orgName.equals("SWW")) { msg = "Das Gerät " + device.getAlias() + " startet heute um " + stringTime + " Uhr. Bitte schalten Sie das Gerät so bald wie möglich nach " + stringTime + " Uhr ein. Startet das Gerät automatisch, können Sie diese SMS ignorieren."; } else if (org.getOrganizationName().equals("CYPRUS")) { String deviceType = device.getDeviceType() == DeviceType.WasherDryer ? "Washing Machine": device.getDeviceType().name(); // msg = "The " + deviceType + " (" + device.getAlias() + ") will start today at " + stringTime + // ". Please switch on the device as soon as possible after " + stringTime + // ". If the device starts automatically, you can ignore this SMS."; //Η ηλεκτρική<SUF> msg = "Η ηλεκτρική παροχή στο " + deviceType + " (" + device.getAlias() + ") θα επανέλθει στις " + stringTime + ". Σε περίπτωση που το συσκευή δεν επανεκκινεί αυτόματα, παρακαλώ επανεκκινήστε τη συσκευή το συντομότερο μετά τις " + stringTime + "."; } else { msg = "The device " + device.getAlias() + " will start today at " + stringTime + ". Please switch on the device as soon as possible after " + stringTime + ". If the device starts automatically, you can ignore this SMS."; } smsService.sendSms(userName, msg); Map<Date, Integer> val2 = new HashMap<>(); val2.put(newSchedule.getStartTime(), action); this.deviceActiveSchedule.put(device.getDeviceId(), val2); alreadySent = true; } } lastAction = action; } } } else { LOGGER.info("Schedule is before Current Time. Schedule Ignored"); } } catch (Exception ex) { ex.printStackTrace(); LOGGER.error(ex.getLocalizedMessage()); } } }
6307_40
/* * Created by bijay * GOFLEX :: WP2 :: foa-core * Copyright (c) 2018. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software") to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: The above copyright notice and * this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON * INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * Last Modified 2/8/18 4:17 PM */ package org.goflex.wp2.foa.listeners; import org.goflex.wp2.core.entities.*; import org.goflex.wp2.core.models.*; import org.goflex.wp2.core.repository.FlexOfferRepository; import org.goflex.wp2.core.repository.OrganizationRepository; import org.goflex.wp2.foa.devicestate.DeviceStateHistory; import org.goflex.wp2.foa.devicestate.DeviceStateHistoryRepository; import org.goflex.wp2.foa.events.DeviceStateChangeEvent; import org.goflex.wp2.foa.events.FlexOfferScheduleReceivedEvent; import org.goflex.wp2.foa.events.FlexOfferStatusUpdateEvent; import org.goflex.wp2.foa.implementation.ImplementationsHandler; import org.goflex.wp2.foa.interfaces.*; import org.goflex.wp2.foa.util.TimeZoneUtil; import org.goflex.wp2.foa.wrapper.PoolSchedule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** * Created by bijay on 7/22/17. */ @Component public class FlexOfferScheduleReceivedListener implements ApplicationListener<FlexOfferScheduleReceivedEvent> { private static final long interval = 900 * 1000; private static final Logger LOGGER = LoggerFactory.getLogger(FlexOfferScheduleReceivedListener.class); @Resource(name = "deviceLatestAggData") LinkedHashMap<String, Map<Date, Double>> deviceLatestAggData; @Resource(name = "scheduleDetailTable") private ConcurrentHashMap<Date, ScheduleDetails> scheduleDetail; @Resource(name = "deviceLatestFO") private ConcurrentHashMap<String, FlexOfferT> deviceLatestFO; @Resource(name = "deviceActiveSchedule") private ConcurrentHashMap<String, Map<Date, Integer>> deviceActiveSchedule; @Resource(name = "poolScheduleMap") private ConcurrentHashMap<String, Map<Long, PoolSchedule>> poolScheduleMap; @Resource(name = "poolDeviceDetail") private ConcurrentHashMap<String, Map<String, PoolDeviceModel>> poolDeviceDetail; @Resource(name = "poolTurnedOffDevices") private ConcurrentHashMap<String, Map<String, Date>> poolTurnedOffDevices; private final ScheduleService scheduleService; private final DeviceDetailService deviceDetailService; private final ImplementationsHandler implementationsHandler; private final ApplicationEventPublisher applicationEventPublisher; private final DeviceDefaultState deviceDefaultState; private final DeviceFlexOfferGroup deviceFlexOfferGroup; private final SmsService smsService; private final FOAService foaService; private final OrganizationRepository organizationRepository; private final UserService userService; private final FlexOfferRepository flexOfferRepository; private final DeviceStateHistoryRepository deviceStateHistoryRepository; public FlexOfferScheduleReceivedListener(ScheduleService scheduleService, DeviceDetailService deviceDetailService, ImplementationsHandler implementationsHandler, ApplicationEventPublisher applicationEventPublisher, DeviceDefaultState deviceDefaultState, UserService userService, DeviceFlexOfferGroup deviceFlexOfferGroup, SmsService smsService, FOAService foaService, OrganizationRepository organizationRepository, FlexOfferRepository flexOfferRepository, DeviceStateHistoryRepository deviceStateHistoryRepository) { this.scheduleService = scheduleService; this.deviceDetailService = deviceDetailService; this.implementationsHandler = implementationsHandler; this.applicationEventPublisher = applicationEventPublisher; this.deviceDefaultState = deviceDefaultState; this.userService = userService; this.deviceFlexOfferGroup = deviceFlexOfferGroup; this.smsService = smsService; this.foaService = foaService; this.organizationRepository = organizationRepository; this.flexOfferRepository = flexOfferRepository; this.deviceStateHistoryRepository = deviceStateHistoryRepository; } private void addScheduleToFLS(String offeredById, UUID flexOfferId, Date eventTime, int action) { if (scheduleDetail.containsKey(eventTime)) { scheduleDetail.get(eventTime).addSchedule(offeredById, flexOfferId, action); } else { scheduleDetail.put(eventTime, new ScheduleDetails(offeredById, flexOfferId, action)); } } private boolean deleteScheduleFromDevice(String offeredById, PlugType plugType, String scheduleID, int action) { return implementationsHandler.get(plugType).deleteOnOffSchedule( offeredById.split("@")[1], offeredById.split("@")[0], scheduleID, action); } /** * if index -1, return device default */ private int getAction(int index, int lastAction, Double energyAmount, DeviceDetail device) { double minEnergyThreshold = 1.0; // min 1Wh in a slice else it's a very small value due to FMAN optimization int action; int defaultState = deviceDefaultState.getDeviceDefaultState(device.getDeviceType());// //device.getDefaultState(); // if not last slice if (index != -1) { //This will handle both production and consumption FOs, i.e, for production fo energy is -ve //if (energyAmount != 0) { if (energyAmount * 1000 > minEnergyThreshold) { action = 1; } else { action = 0; } } else { // This is used to revert back the load to default state, after last slice if (lastAction == 1) { if (defaultState == 1) { action = -1; } else { action = 0; } } else { if (defaultState == 1) { action = 1; } else { action = -1; } } } return action; } private OnOffSchedule createOnOffSchedule(String offerById, int action, Double energyAmount, boolean isLast) { OnOffSchedule newSchedule = new OnOffSchedule(offerById); newSchedule.setRegisteredTime(new Date()); newSchedule.setEnergyLevel(energyAmount); newSchedule.setScheduleToState(action); newSchedule.setLast(isLast); return newSchedule; } private String pushScheduleToDevice(DeviceDetail device, String offeredById, UUID flexOfferId, Date startDate, int state) { // push schedule to smart device String scheduleId = implementationsHandler.get(device.getPlugType()).addOnOffSchedule( offeredById.split("@")[1], offeredById.split("@")[0], startDate, state); if (device.getPlugType() == PlugType.Simulated) { this.addScheduleToFLS(offeredById, flexOfferId, startDate, state); } return scheduleId; } private boolean invalidateOldSchedule(Date startDate, OnOffSchedule newSchedule, OnOffSchedule oldSchedule, String offeredById, DeviceDetail device) { boolean status; // invalidate previous schedule from database status = scheduleService.inValidateSchedule(startDate, newSchedule.getDeviceID()); // remove schedule from smart device if (oldSchedule.getExternalScheduleId() != null || !oldSchedule.getExternalScheduleId().equals("")) { if (this.deleteScheduleFromDevice(offeredById, device.getPlugType(), oldSchedule.getExternalScheduleId(), 1) == false) { status = false; LOGGER.warn("Could not delete existing schedule."); } else { LOGGER.info("Old Schedule deleted from smartplug"); } } return status; } private boolean invalidateOldSchedule(String flexOfferId, String offeredById, PlugType plugType) { boolean status = true; /**invalidate previous schedule from database */ status = scheduleService.inValidateSchedule(flexOfferId); /**remove schedule from smart device*/ for (OnOffSchedule onOffSchedule : scheduleService.getOnOffSchedules(flexOfferId)) { if (onOffSchedule.getExternalScheduleId() != null && !onOffSchedule.getExternalScheduleId().equals("")) { if (this.deleteScheduleFromDevice(offeredById, plugType, onOffSchedule.getExternalScheduleId(), 1) == false) { status = false; LOGGER.warn("Could not delete existing schedule."); } else { LOGGER.info("Old Schedule deleted from smartplug"); } } } return status; } private String addSchedule(int index, Date startDate, OnOffSchedule schedule, UUID flexOfferId, String offeredById, DeviceDetail device) { // Check if we already have key for a particular time, if not create a schedule table with the key ScheduleT hasKey = scheduleService.getByDate(startDate); if (hasKey == null) { // Persist the new schedule table ScheduleT savedSchedule = scheduleService.save(new ScheduleT(startDate)); } // insert new schedule String scheduleId = null; try { //TODO: handling schedule at TPLink plug is complex need better model. For now we dont push schedule to plug scheduleId = ""; //scheduleId = this.pushScheduleToDevice(device, offeredById, flexOfferId, startDate, schedule // .getScheduleToState()); //if flex-offer schedule Assignment event FlexOfferStatusUpdateEvent flexOfferStatusUpdateEvent = new FlexOfferStatusUpdateEvent(this, "FO Status Updated", "", flexOfferId, FlexOfferState.Assigned); applicationEventPublisher.publishEvent(flexOfferStatusUpdateEvent); } catch (Exception ex) { LOGGER.warn("Could not pass schedule to tplink cloud"); } // if successfully pushed to smart device, device would handle schedule, // else schedule handler will execute all un-pushed schedules if (scheduleId != null && !scheduleId.equals("")) { schedule.setPushedToDevice(1); schedule.setExternalScheduleId(scheduleId); } schedule.setFlexOfferId(flexOfferId.toString()); // add new schedule to the system scheduleService.addSchedulesForKey(startDate, schedule); return scheduleId; } @Override @Transactional public void onApplicationEvent(FlexOfferScheduleReceivedEvent event) { try { LOGGER.debug(event.getEventName() + " at " + event.getTimestamp()); FlexOfferT foT = this.flexOfferRepository.findByFoID(event.getFlexOffer().getId().toString()); Organization org = this.organizationRepository.findByOrganizationId(foT.getOrganizationId()); if (org.isPoolBasedControl()) { processPoolSchedule(event, org); } else { processDeviceSchedule(event); } } catch (Exception ex) { ex.printStackTrace(); LOGGER.error(ex.getLocalizedMessage()); } } private void processDeviceSchedule(FlexOfferScheduleReceivedEvent event) { try { /** this will run only when scheduled received from FMAN, * no need for schedule generated during FO generation */ if (!event.getDefaultSchedule()) { LOGGER.info("New scheduled received from FMAN_FMAR for flex-offer with ID =>{}", event.getFlexOffer().getId()); /** update schedule update id by 1 */ event.getNewSchedule().setUpdateId(event.getFlexOffer().getFlexOfferSchedule().getUpdateId() + 1); /**update flex-offer schedule */ event.getFlexOffer().setFlexOfferSchedule(event.getNewSchedule()); LOGGER.info("Scheduled updated for Flex-offer with ID =>{}", event.getFlexOffer().getId()); // also update FlexOfferT FlexOfferT flexOfferT = this.foaService.getFlexOffer(event.getFlexOffer().getId()); flexOfferT.setFlexoffer(event.getFlexOffer()); // also update device->FO memory map this.deviceLatestFO.put(event.getFlexOffer().getOfferedById(), flexOfferT); LOGGER.info("deviceLatestFO map updated for device: {}", event.getFlexOffer().getOfferedById()); } Date startDate = event.getNewSchedule().getStartTime(); Date currentDate = new Date(); int lastAction = -1; int action; // check if current date is after the start time date if (startDate.after(currentDate)) { String offeredById = event.getFlexOffer().getOfferedById(); DeviceDetail device = deviceDetailService.getDevice(offeredById); String userName = device.getDeviceId().split("@")[0]; UserT userT = this.userService.getUser(userName); Organization org = this.organizationRepository.findByOrganizationId(userT.getOrganizationId()); //invalidate all old schedule if (this.invalidateOldSchedule(event.getFlexOffer().getId().toString(), offeredById, device.getPlugType())) { // get new schedule from event FlexOfferSchedule newSchedule = event.getNewSchedule(); FlexibilityGroupType flexibilityGroupType = deviceFlexOfferGroup.getDeviceFOGroupType(device.getDeviceType()); // loop through slices in the flex-offer int numSlices = newSchedule.getScheduleSlices().length; boolean alreadySent = false; for (int i = 0; i < numSlices + 1; i++) { // +1 is to put device into default state upon schedule completion LOGGER.debug("Updating new schedule for Flex-offer with ID:" + event.getFlexOffer().getId()); // start date is the schedule start time startDate = new Date(startDate.getTime() + i * interval); int idx = i < numSlices ? i : -1; double energyAmount = i < numSlices ? newSchedule.getScheduleSlice(i).getEnergyAmount() : -1.0; action = this.getAction(idx, lastAction, energyAmount, device); if (!this.deviceActiveSchedule.containsKey(device.getDeviceId())) { Map<Date, Integer> val = new HashMap<>(); val.put(startDate, action); this.deviceActiveSchedule.put(device.getDeviceId(), val); } // loop through slices and at the end of schedule device should go to default state // create new schedule and set energy level for each slice OnOffSchedule schedule = createOnOffSchedule(offeredById, action, energyAmount, idx == -1); String scheduleId = this.addSchedule(i, startDate, schedule, event.getFlexOffer().getId(), offeredById, device); //send message of scheduled device operation only for wet devices that needs manual start // for now we assume all wet devices need manual start since we don't have per device info if (scheduleId != null && !event.getDefaultSchedule() && flexibilityGroupType == FlexibilityGroupType.WetLoad && org.getDirectControlMode() == OrganizationLoadControlState.Active) { Map<Date, Integer> val = this.deviceActiveSchedule.get(device.getDeviceId()); Date oldStartDate = (Date) val.keySet().toArray()[0]; int oldAction = val.get(oldStartDate); if (!newSchedule.getStartTime().equals(oldStartDate) || (action == 1 && (action != oldAction || !alreadySent))) { String orgName = org.getOrganizationName(); String stringTime = TimeZoneUtil.getTimeZoneAdjustedStringTime(startDate, orgName); String msg; if (orgName.equals("SWW")) { msg = "Das Gerät " + device.getAlias() + " startet heute um " + stringTime + " Uhr. Bitte schalten Sie das Gerät so bald wie möglich nach " + stringTime + " Uhr ein. Startet das Gerät automatisch, können Sie diese SMS ignorieren."; } else if (org.getOrganizationName().equals("CYPRUS")) { String deviceType = device.getDeviceType() == DeviceType.WasherDryer ? "Washing Machine" : device.getDeviceType().name(); // msg = "The " + deviceType + " (" + device.getAlias() + ") will start today at " + stringTime + // ". Please switch on the device as soon as possible after " + stringTime + // ". If the device starts automatically, you can ignore this SMS."; //Η ηλεκτρική παροχή στο συσκευή θα επανέλθει στις 17:30. Σε περίπτωση που το συσκευή δεν επανεκκινεί αυτόματα, παρακαλώ επανεκκινήστε τη συσκευή το συντομότερο μετά τις 17:30. msg = "Η ηλεκτρική παροχή στο " + deviceType + " (" + device.getAlias() + ") θα επανέλθει στις " + stringTime + ". Σε περίπτωση που το συσκευή δεν επανεκκινεί αυτόματα, παρακαλώ επανεκκινήστε τη συσκευή το συντομότερο μετά τις " + stringTime + "."; } else { msg = "The device " + device.getAlias() + " will start today at " + stringTime + ". Please switch on the device as soon as possible after " + stringTime + ". If the device starts automatically, you can ignore this SMS."; } smsService.sendSms(userName, msg); Map<Date, Integer> val2 = new HashMap<>(); val2.put(newSchedule.getStartTime(), action); this.deviceActiveSchedule.put(device.getDeviceId(), val2); alreadySent = true; } } lastAction = action; } } } else { LOGGER.info("Schedule is before Current Time. Schedule Ignored"); } } catch (Exception ex) { ex.printStackTrace(); LOGGER.error(ex.getLocalizedMessage()); } } private void processPoolSchedule(FlexOfferScheduleReceivedEvent event, Organization org) { try { if (!event.getDefaultSchedule()) { LOGGER.info("New pool scheduled received from FMAN_FMAR for flex-offer with ID =>{}", event.getFlexOffer().getId()); /** update schedule update id by 1 */ event.getNewSchedule().setUpdateId(event.getFlexOffer().getFlexOfferSchedule().getUpdateId() + 1); /**update flex-offer schedule */ event.getFlexOffer().setFlexOfferSchedule(event.getNewSchedule()); LOGGER.info("Pool schedule updated for Flex-offer with ID =>{}", event.getFlexOffer().getId()); // also update FlexOfferT FlexOfferT flexOfferT = this.foaService.getFlexOffer(event.getFlexOffer().getId()); flexOfferT.setFlexoffer(event.getFlexOffer()); } // get new schedule and related data from event FlexOfferSchedule newSchedule = event.getNewSchedule(); FlexOffer flexOffer = event.getFlexOffer(); double offeredLowerEnergy = flexOffer.getFlexOfferProfile(0).getEnergyLower(0); double offeredUpperEnergy = flexOffer.getFlexOfferProfile(0).getEnergyUpper(0); double marketOrder = newSchedule.getTotalEnergy(); Date startTime = newSchedule.getStartTime(); Date endTime = FlexOffer.toAbsoluteTime(FlexOffer.toFlexOfferTime(startTime) + 1); Date currentTime = new Date(); if (startTime.before(currentTime)) { LOGGER.warn("Pool schedule time {} is before Current Time {}. Schedule Ignored", startTime, currentTime); return; } if (marketOrder < offeredLowerEnergy || marketOrder > offeredUpperEnergy) { LOGGER.warn("Pool schedule market order is out of bounds"); return; } PoolSchedule poolSchedule = new PoolSchedule(); // assuming there is only one slice poolSchedule.setOfferedEnergyLower(offeredLowerEnergy); poolSchedule.setOfferedEnergyUpper(offeredUpperEnergy); poolSchedule.setMarketOrder(marketOrder); // assuming there is always one slice poolSchedule.setCurrentPowerConsumption(-1); poolSchedule.setCumulativeEnergy(0); poolSchedule.setStartTime(startTime); poolSchedule.setEndTime(endTime); Long scheduleFoTime = FlexOffer.toFlexOfferTime(startTime); Long currentSliceFoTime = FlexOffer.toFlexOfferTime(currentTime); if (poolScheduleMap.get(org.getOrganizationName()).containsKey(scheduleFoTime)) { // transfer list of turned off devices from prev slice poolSchedule.setCurrentPowerConsumption(poolScheduleMap.get(org.getOrganizationName()).get(scheduleFoTime).getCurrentPowerConsumption()); poolSchedule.setCumulativeEnergy(poolScheduleMap.get(org.getOrganizationName()).get(scheduleFoTime).getCumulativeEnergy()); } poolScheduleMap.get(org.getOrganizationName()).put(scheduleFoTime, poolSchedule); printPoolSchedule(); LOGGER.info("poolScheduleMap map updated for organization: {}", event.getFlexOffer().getOfferedById()); } catch (Exception ex) { ex.printStackTrace(); LOGGER.error(ex.getLocalizedMessage()); } } private void printPoolSchedule() { LOGGER.info("current status of pool schedule map"); this.poolScheduleMap.forEach((key, val) -> { val.forEach((k, v) -> { LOGGER.info("org: {} slice: {}, map: {}", key, FlexOffer.toAbsoluteTime(k), v.toString()); }); }); } private List<String> getDevicesToTurnOff(Double power, String orgName, double deviceCoolingPeriod) { TreeMap<Double, String> devices = new TreeMap<>(Collections.reverseOrder()); List<String> devicesToTurnOff = new ArrayList<>(); Double powerToReduce = power; for (String key : poolDeviceDetail.get(orgName).keySet()) { PoolDeviceModel sdm = poolDeviceDetail.get(orgName).get(key); if (sdm.getCurrentState() == 1 && !this.poolScheduleMap.get(orgName).containsKey(key)) { devices.put(sdm.getCurrentTemperature() + new Random().nextDouble() * 0.001, sdm.getDeviceId()); } } for (Map.Entry<Double, String> entry : devices.entrySet()) { if (powerToReduce < 500) { break; } PoolDeviceModel sdm = poolDeviceDetail.get(orgName).get(devices.get(entry.getKey())); if (sdm.getLastReleasedFromPool() != null) { long coolingTime = (new Date().getTime() - sdm.getLastReleasedFromPool().getTime()) / 60000; if (coolingTime < deviceCoolingPeriod) { continue; } } // just in case it was recently turned on externally DeviceStateHistory deviceStateHistory = deviceStateHistoryRepository.getLatestDeviceHistory(entry.getValue()); if (deviceStateHistory != null && deviceStateHistory.getDeviceState() == DeviceState.Operating) { long coolingTime = (new Date().getTime() - deviceStateHistory.getTimestamp().getTime()) / 60000; if (coolingTime < 60) { continue; } } Double temperature = entry.getKey(); if (temperature > sdm.getMinTempThresh() && sdm.getCurrentState() == 1) { devicesToTurnOff.add(poolDeviceDetail.get(orgName).get(devices.get(temperature)).getDeviceId()); powerToReduce = powerToReduce - poolDeviceDetail.get(orgName).get(devices.get(temperature)).getCurrentPower(); } } return devicesToTurnOff; } private List<String> getDevicesToTurnOn(Double power, String orgName) { TreeMap<Double, String> devices = new TreeMap<>(); List<String> devicesToTurnOn = new ArrayList<>(); Double powerToIncrease = power; for (String deviceId : poolDeviceDetail.get(orgName).keySet()) { PoolDeviceModel sdm = poolDeviceDetail.get(orgName).get(deviceId); long coolingTime = 16; if (sdm.getLastIncludedInPool() != null) { coolingTime = (new Date().getTime() - sdm.getLastIncludedInPool().getTime()) / 60000; } if ( (this.poolTurnedOffDevices.get(orgName).containsKey(deviceId) || orgName.equals("TEST") ) && sdm.getCurrentState() == 0 && coolingTime > 15) { devices.put(sdm.getCurrentTemperature() + new Random().nextDouble() * 0.001, sdm.getDeviceId()); } } for (Map.Entry<Double, String> entry : devices.entrySet()) { Double temperature = entry.getKey(); if (powerToIncrease < 500) { break; } // just in case it was recently turned on externally DeviceStateHistory deviceStateHistory = deviceStateHistoryRepository.getLatestDeviceHistory(entry.getValue()); if (deviceStateHistory != null && deviceStateHistory.getDeviceState() == DeviceState.Idle) { long coolingTime = (new Date().getTime() - deviceStateHistory.getTimestamp().getTime()) / 60000; if (coolingTime < 5) { continue; } } String deviceId = devices.get(temperature); if (temperature < poolDeviceDetail.get(orgName).get(deviceId).getMaxTempThresh()) { devicesToTurnOn.add(poolDeviceDetail.get(orgName).get(devices.get(temperature)).getDeviceId()); powerToIncrease = powerToIncrease - poolDeviceDetail.get(orgName).get(devices.get(temperature)).getCurrentPower(); } } return devicesToTurnOn; } private void releaseDevicesFromPool(String orgName) { Set<String> deviceIds = this.poolTurnedOffDevices.get(orgName).keySet(); if (deviceIds.size() == 0) { return; } LOGGER.info("Releasing necessary devices from the pool"); for (String deviceId : deviceIds) { Date turnedOffTime = this.poolTurnedOffDevices.get(orgName).get(deviceId); long minutes = (new Date().getTime() - turnedOffTime.getTime()) / (1000 * 60); if (minutes > 30) { DeviceDetail deviceDetail = this.deviceDetailService.getDevice(deviceId); DeviceStateChangeEvent stateChangeEvent = new DeviceStateChangeEvent( this, String.format("releasing device: '%s' which was turned off at: '%s' from the pool", deviceDetail.getDeviceId(), turnedOffTime), deviceDetail, true); this.applicationEventPublisher.publishEvent(stateChangeEvent); this.poolDeviceDetail.get(orgName).get(deviceId).setLastReleasedFromPool(new Date()); this.poolTurnedOffDevices.get(orgName).remove(deviceId); LOGGER.info("Released org: {}, device: {} from the pool", orgName, deviceId); } } } public void executePoolSchedule() { long foTime = FlexOffer.toFlexOfferTime(new Date()); this.poolScheduleMap.forEach((orgName, orgPoolMap) -> { // first release those devices that are in OFF state longer than threshold releaseDevicesFromPool(orgName); // update pool power consumption updatePoolScheduleMapPower(orgName); // execute pool schedule for the organization executeOrgSchedule(orgName, foTime, orgPoolMap); }); } private void executeOrgSchedule(String orgName, long foTime, Map<Long, PoolSchedule> orgPoolMap) { if (orgPoolMap.size() == 0) { return; } if (!orgPoolMap.containsKey(foTime)) { return; } double lowerEnergy = orgPoolMap.get(foTime).getOfferedEnergyLower()*4000; double upperEnergy = orgPoolMap.get(foTime).getOfferedEnergyUpper()*4000; if ( Math.abs(upperEnergy-lowerEnergy) < 1) { LOGGER.info("Org: {} is in cooling period", orgName); return; } PoolSchedule poolSchedule = orgPoolMap.get(foTime); if (poolSchedule == null) { LOGGER.warn("No pool schedule found for the current slice for org: {}", orgName); return; } double marketOrder = poolSchedule.getMarketOrder() * 1000 * 4; double currentPowerConsumption = poolSchedule.getCurrentPowerConsumption(); if (currentPowerConsumption < 0) { return; } double cumulativeEnergy = poolSchedule.getCumulativeEnergy(); // Wh for now Organization org = this.organizationRepository.findByOrganizationName(orgName); LOGGER.info("Org: {}, Market order: {}, current consumption: {}", org.getOrganizationName(), marketOrder, currentPowerConsumption); if (marketOrder < currentPowerConsumption) { List<String> devicesToTurnOff = getDevicesToTurnOff(currentPowerConsumption-marketOrder, orgName, org.getPoolDeviceCoolingPeriod()); if (devicesToTurnOff.size() > 0 && org.getDirectControlMode() != OrganizationLoadControlState.Active) { LOGGER.warn("Not turning off devices because organization control disabled for: {}", orgName); return; } devicesToTurnOff.forEach(deviceId -> { DeviceDetail device = this.deviceDetailService.getDevice(deviceId); DeviceStateChangeEvent stateChangeEvent = new DeviceStateChangeEvent( this, String.format("Turning off device: '%s' due to inclusion in the pool", device.getDeviceId()), device, false); this.applicationEventPublisher.publishEvent(stateChangeEvent); this.poolDeviceDetail.get(orgName).get(deviceId).setLastIncludedInPool(new Date()); this.poolTurnedOffDevices.get(orgName).put(deviceId, new Date()); }); } else { List<String> devicesToTurnOn = getDevicesToTurnOn(marketOrder-currentPowerConsumption, orgName); if (devicesToTurnOn.size() > 0 && org.getDirectControlMode() != OrganizationLoadControlState.Active) { LOGGER.warn("Not turning on devices because organization control disabled for: {}", orgName); return; } devicesToTurnOn.forEach(deviceId -> { DeviceDetail device = this.deviceDetailService.getDevice(deviceId); DeviceStateChangeEvent stateChangeEvent = new DeviceStateChangeEvent( this, String.format("Turning on device: '%s' due to inclusion in the pool", device.getDeviceId()), device, true); this.applicationEventPublisher.publishEvent(stateChangeEvent); }); } // update cumulative energy this.poolScheduleMap.get(orgName).get(foTime).setCumulativeEnergy(cumulativeEnergy + currentPowerConsumption); } public void transferScheduleFromPrevToCurrSlice() { LOGGER.info("executing routine to transfer necessary schedule data from prev to curr slice"); long currentSliceFoTime = FlexOffer.toFlexOfferTime(new Date()); this.poolScheduleMap.forEach((orgName, orgPoolMap) -> { if (orgPoolMap.containsKey(currentSliceFoTime - 1)) { // delete prev slice from map this.poolScheduleMap.get(orgName).remove(currentSliceFoTime - 1); } }); } private void updatePoolScheduleMapPower(String orgName) { double latestAggPower = 0.0; for (Map.Entry<String, PoolDeviceModel> entry : this.poolDeviceDetail.get(orgName).entrySet()) { latestAggPower += entry.getValue().getCurrentPower(); } long foTime = FlexOffer.toFlexOfferTime(new Date()); if (this.poolScheduleMap.get(orgName).containsKey(foTime)) { this.poolScheduleMap.get(orgName).get(foTime).setCurrentPowerConsumption(latestAggPower); } } }
aau-fed/flexoffer_agent
foa-core/src/main/java/org/goflex/wp2/foa/listeners/FlexOfferScheduleReceivedListener.java
7,757
//Η ηλεκτρική παροχή στο συσκευή θα επανέλθει στις 17:30. Σε περίπτωση που το συσκευή δεν επανεκκινεί αυτόματα, παρακαλώ επανεκκινήστε τη συσκευή το συντομότερο μετά τις 17:30.
line_comment
el
/* * Created by bijay * GOFLEX :: WP2 :: foa-core * Copyright (c) 2018. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software") to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: The above copyright notice and * this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON * INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * Last Modified 2/8/18 4:17 PM */ package org.goflex.wp2.foa.listeners; import org.goflex.wp2.core.entities.*; import org.goflex.wp2.core.models.*; import org.goflex.wp2.core.repository.FlexOfferRepository; import org.goflex.wp2.core.repository.OrganizationRepository; import org.goflex.wp2.foa.devicestate.DeviceStateHistory; import org.goflex.wp2.foa.devicestate.DeviceStateHistoryRepository; import org.goflex.wp2.foa.events.DeviceStateChangeEvent; import org.goflex.wp2.foa.events.FlexOfferScheduleReceivedEvent; import org.goflex.wp2.foa.events.FlexOfferStatusUpdateEvent; import org.goflex.wp2.foa.implementation.ImplementationsHandler; import org.goflex.wp2.foa.interfaces.*; import org.goflex.wp2.foa.util.TimeZoneUtil; import org.goflex.wp2.foa.wrapper.PoolSchedule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** * Created by bijay on 7/22/17. */ @Component public class FlexOfferScheduleReceivedListener implements ApplicationListener<FlexOfferScheduleReceivedEvent> { private static final long interval = 900 * 1000; private static final Logger LOGGER = LoggerFactory.getLogger(FlexOfferScheduleReceivedListener.class); @Resource(name = "deviceLatestAggData") LinkedHashMap<String, Map<Date, Double>> deviceLatestAggData; @Resource(name = "scheduleDetailTable") private ConcurrentHashMap<Date, ScheduleDetails> scheduleDetail; @Resource(name = "deviceLatestFO") private ConcurrentHashMap<String, FlexOfferT> deviceLatestFO; @Resource(name = "deviceActiveSchedule") private ConcurrentHashMap<String, Map<Date, Integer>> deviceActiveSchedule; @Resource(name = "poolScheduleMap") private ConcurrentHashMap<String, Map<Long, PoolSchedule>> poolScheduleMap; @Resource(name = "poolDeviceDetail") private ConcurrentHashMap<String, Map<String, PoolDeviceModel>> poolDeviceDetail; @Resource(name = "poolTurnedOffDevices") private ConcurrentHashMap<String, Map<String, Date>> poolTurnedOffDevices; private final ScheduleService scheduleService; private final DeviceDetailService deviceDetailService; private final ImplementationsHandler implementationsHandler; private final ApplicationEventPublisher applicationEventPublisher; private final DeviceDefaultState deviceDefaultState; private final DeviceFlexOfferGroup deviceFlexOfferGroup; private final SmsService smsService; private final FOAService foaService; private final OrganizationRepository organizationRepository; private final UserService userService; private final FlexOfferRepository flexOfferRepository; private final DeviceStateHistoryRepository deviceStateHistoryRepository; public FlexOfferScheduleReceivedListener(ScheduleService scheduleService, DeviceDetailService deviceDetailService, ImplementationsHandler implementationsHandler, ApplicationEventPublisher applicationEventPublisher, DeviceDefaultState deviceDefaultState, UserService userService, DeviceFlexOfferGroup deviceFlexOfferGroup, SmsService smsService, FOAService foaService, OrganizationRepository organizationRepository, FlexOfferRepository flexOfferRepository, DeviceStateHistoryRepository deviceStateHistoryRepository) { this.scheduleService = scheduleService; this.deviceDetailService = deviceDetailService; this.implementationsHandler = implementationsHandler; this.applicationEventPublisher = applicationEventPublisher; this.deviceDefaultState = deviceDefaultState; this.userService = userService; this.deviceFlexOfferGroup = deviceFlexOfferGroup; this.smsService = smsService; this.foaService = foaService; this.organizationRepository = organizationRepository; this.flexOfferRepository = flexOfferRepository; this.deviceStateHistoryRepository = deviceStateHistoryRepository; } private void addScheduleToFLS(String offeredById, UUID flexOfferId, Date eventTime, int action) { if (scheduleDetail.containsKey(eventTime)) { scheduleDetail.get(eventTime).addSchedule(offeredById, flexOfferId, action); } else { scheduleDetail.put(eventTime, new ScheduleDetails(offeredById, flexOfferId, action)); } } private boolean deleteScheduleFromDevice(String offeredById, PlugType plugType, String scheduleID, int action) { return implementationsHandler.get(plugType).deleteOnOffSchedule( offeredById.split("@")[1], offeredById.split("@")[0], scheduleID, action); } /** * if index -1, return device default */ private int getAction(int index, int lastAction, Double energyAmount, DeviceDetail device) { double minEnergyThreshold = 1.0; // min 1Wh in a slice else it's a very small value due to FMAN optimization int action; int defaultState = deviceDefaultState.getDeviceDefaultState(device.getDeviceType());// //device.getDefaultState(); // if not last slice if (index != -1) { //This will handle both production and consumption FOs, i.e, for production fo energy is -ve //if (energyAmount != 0) { if (energyAmount * 1000 > minEnergyThreshold) { action = 1; } else { action = 0; } } else { // This is used to revert back the load to default state, after last slice if (lastAction == 1) { if (defaultState == 1) { action = -1; } else { action = 0; } } else { if (defaultState == 1) { action = 1; } else { action = -1; } } } return action; } private OnOffSchedule createOnOffSchedule(String offerById, int action, Double energyAmount, boolean isLast) { OnOffSchedule newSchedule = new OnOffSchedule(offerById); newSchedule.setRegisteredTime(new Date()); newSchedule.setEnergyLevel(energyAmount); newSchedule.setScheduleToState(action); newSchedule.setLast(isLast); return newSchedule; } private String pushScheduleToDevice(DeviceDetail device, String offeredById, UUID flexOfferId, Date startDate, int state) { // push schedule to smart device String scheduleId = implementationsHandler.get(device.getPlugType()).addOnOffSchedule( offeredById.split("@")[1], offeredById.split("@")[0], startDate, state); if (device.getPlugType() == PlugType.Simulated) { this.addScheduleToFLS(offeredById, flexOfferId, startDate, state); } return scheduleId; } private boolean invalidateOldSchedule(Date startDate, OnOffSchedule newSchedule, OnOffSchedule oldSchedule, String offeredById, DeviceDetail device) { boolean status; // invalidate previous schedule from database status = scheduleService.inValidateSchedule(startDate, newSchedule.getDeviceID()); // remove schedule from smart device if (oldSchedule.getExternalScheduleId() != null || !oldSchedule.getExternalScheduleId().equals("")) { if (this.deleteScheduleFromDevice(offeredById, device.getPlugType(), oldSchedule.getExternalScheduleId(), 1) == false) { status = false; LOGGER.warn("Could not delete existing schedule."); } else { LOGGER.info("Old Schedule deleted from smartplug"); } } return status; } private boolean invalidateOldSchedule(String flexOfferId, String offeredById, PlugType plugType) { boolean status = true; /**invalidate previous schedule from database */ status = scheduleService.inValidateSchedule(flexOfferId); /**remove schedule from smart device*/ for (OnOffSchedule onOffSchedule : scheduleService.getOnOffSchedules(flexOfferId)) { if (onOffSchedule.getExternalScheduleId() != null && !onOffSchedule.getExternalScheduleId().equals("")) { if (this.deleteScheduleFromDevice(offeredById, plugType, onOffSchedule.getExternalScheduleId(), 1) == false) { status = false; LOGGER.warn("Could not delete existing schedule."); } else { LOGGER.info("Old Schedule deleted from smartplug"); } } } return status; } private String addSchedule(int index, Date startDate, OnOffSchedule schedule, UUID flexOfferId, String offeredById, DeviceDetail device) { // Check if we already have key for a particular time, if not create a schedule table with the key ScheduleT hasKey = scheduleService.getByDate(startDate); if (hasKey == null) { // Persist the new schedule table ScheduleT savedSchedule = scheduleService.save(new ScheduleT(startDate)); } // insert new schedule String scheduleId = null; try { //TODO: handling schedule at TPLink plug is complex need better model. For now we dont push schedule to plug scheduleId = ""; //scheduleId = this.pushScheduleToDevice(device, offeredById, flexOfferId, startDate, schedule // .getScheduleToState()); //if flex-offer schedule Assignment event FlexOfferStatusUpdateEvent flexOfferStatusUpdateEvent = new FlexOfferStatusUpdateEvent(this, "FO Status Updated", "", flexOfferId, FlexOfferState.Assigned); applicationEventPublisher.publishEvent(flexOfferStatusUpdateEvent); } catch (Exception ex) { LOGGER.warn("Could not pass schedule to tplink cloud"); } // if successfully pushed to smart device, device would handle schedule, // else schedule handler will execute all un-pushed schedules if (scheduleId != null && !scheduleId.equals("")) { schedule.setPushedToDevice(1); schedule.setExternalScheduleId(scheduleId); } schedule.setFlexOfferId(flexOfferId.toString()); // add new schedule to the system scheduleService.addSchedulesForKey(startDate, schedule); return scheduleId; } @Override @Transactional public void onApplicationEvent(FlexOfferScheduleReceivedEvent event) { try { LOGGER.debug(event.getEventName() + " at " + event.getTimestamp()); FlexOfferT foT = this.flexOfferRepository.findByFoID(event.getFlexOffer().getId().toString()); Organization org = this.organizationRepository.findByOrganizationId(foT.getOrganizationId()); if (org.isPoolBasedControl()) { processPoolSchedule(event, org); } else { processDeviceSchedule(event); } } catch (Exception ex) { ex.printStackTrace(); LOGGER.error(ex.getLocalizedMessage()); } } private void processDeviceSchedule(FlexOfferScheduleReceivedEvent event) { try { /** this will run only when scheduled received from FMAN, * no need for schedule generated during FO generation */ if (!event.getDefaultSchedule()) { LOGGER.info("New scheduled received from FMAN_FMAR for flex-offer with ID =>{}", event.getFlexOffer().getId()); /** update schedule update id by 1 */ event.getNewSchedule().setUpdateId(event.getFlexOffer().getFlexOfferSchedule().getUpdateId() + 1); /**update flex-offer schedule */ event.getFlexOffer().setFlexOfferSchedule(event.getNewSchedule()); LOGGER.info("Scheduled updated for Flex-offer with ID =>{}", event.getFlexOffer().getId()); // also update FlexOfferT FlexOfferT flexOfferT = this.foaService.getFlexOffer(event.getFlexOffer().getId()); flexOfferT.setFlexoffer(event.getFlexOffer()); // also update device->FO memory map this.deviceLatestFO.put(event.getFlexOffer().getOfferedById(), flexOfferT); LOGGER.info("deviceLatestFO map updated for device: {}", event.getFlexOffer().getOfferedById()); } Date startDate = event.getNewSchedule().getStartTime(); Date currentDate = new Date(); int lastAction = -1; int action; // check if current date is after the start time date if (startDate.after(currentDate)) { String offeredById = event.getFlexOffer().getOfferedById(); DeviceDetail device = deviceDetailService.getDevice(offeredById); String userName = device.getDeviceId().split("@")[0]; UserT userT = this.userService.getUser(userName); Organization org = this.organizationRepository.findByOrganizationId(userT.getOrganizationId()); //invalidate all old schedule if (this.invalidateOldSchedule(event.getFlexOffer().getId().toString(), offeredById, device.getPlugType())) { // get new schedule from event FlexOfferSchedule newSchedule = event.getNewSchedule(); FlexibilityGroupType flexibilityGroupType = deviceFlexOfferGroup.getDeviceFOGroupType(device.getDeviceType()); // loop through slices in the flex-offer int numSlices = newSchedule.getScheduleSlices().length; boolean alreadySent = false; for (int i = 0; i < numSlices + 1; i++) { // +1 is to put device into default state upon schedule completion LOGGER.debug("Updating new schedule for Flex-offer with ID:" + event.getFlexOffer().getId()); // start date is the schedule start time startDate = new Date(startDate.getTime() + i * interval); int idx = i < numSlices ? i : -1; double energyAmount = i < numSlices ? newSchedule.getScheduleSlice(i).getEnergyAmount() : -1.0; action = this.getAction(idx, lastAction, energyAmount, device); if (!this.deviceActiveSchedule.containsKey(device.getDeviceId())) { Map<Date, Integer> val = new HashMap<>(); val.put(startDate, action); this.deviceActiveSchedule.put(device.getDeviceId(), val); } // loop through slices and at the end of schedule device should go to default state // create new schedule and set energy level for each slice OnOffSchedule schedule = createOnOffSchedule(offeredById, action, energyAmount, idx == -1); String scheduleId = this.addSchedule(i, startDate, schedule, event.getFlexOffer().getId(), offeredById, device); //send message of scheduled device operation only for wet devices that needs manual start // for now we assume all wet devices need manual start since we don't have per device info if (scheduleId != null && !event.getDefaultSchedule() && flexibilityGroupType == FlexibilityGroupType.WetLoad && org.getDirectControlMode() == OrganizationLoadControlState.Active) { Map<Date, Integer> val = this.deviceActiveSchedule.get(device.getDeviceId()); Date oldStartDate = (Date) val.keySet().toArray()[0]; int oldAction = val.get(oldStartDate); if (!newSchedule.getStartTime().equals(oldStartDate) || (action == 1 && (action != oldAction || !alreadySent))) { String orgName = org.getOrganizationName(); String stringTime = TimeZoneUtil.getTimeZoneAdjustedStringTime(startDate, orgName); String msg; if (orgName.equals("SWW")) { msg = "Das Gerät " + device.getAlias() + " startet heute um " + stringTime + " Uhr. Bitte schalten Sie das Gerät so bald wie möglich nach " + stringTime + " Uhr ein. Startet das Gerät automatisch, können Sie diese SMS ignorieren."; } else if (org.getOrganizationName().equals("CYPRUS")) { String deviceType = device.getDeviceType() == DeviceType.WasherDryer ? "Washing Machine" : device.getDeviceType().name(); // msg = "The " + deviceType + " (" + device.getAlias() + ") will start today at " + stringTime + // ". Please switch on the device as soon as possible after " + stringTime + // ". If the device starts automatically, you can ignore this SMS."; //Η ηλεκτρική<SUF> msg = "Η ηλεκτρική παροχή στο " + deviceType + " (" + device.getAlias() + ") θα επανέλθει στις " + stringTime + ". Σε περίπτωση που το συσκευή δεν επανεκκινεί αυτόματα, παρακαλώ επανεκκινήστε τη συσκευή το συντομότερο μετά τις " + stringTime + "."; } else { msg = "The device " + device.getAlias() + " will start today at " + stringTime + ". Please switch on the device as soon as possible after " + stringTime + ". If the device starts automatically, you can ignore this SMS."; } smsService.sendSms(userName, msg); Map<Date, Integer> val2 = new HashMap<>(); val2.put(newSchedule.getStartTime(), action); this.deviceActiveSchedule.put(device.getDeviceId(), val2); alreadySent = true; } } lastAction = action; } } } else { LOGGER.info("Schedule is before Current Time. Schedule Ignored"); } } catch (Exception ex) { ex.printStackTrace(); LOGGER.error(ex.getLocalizedMessage()); } } private void processPoolSchedule(FlexOfferScheduleReceivedEvent event, Organization org) { try { if (!event.getDefaultSchedule()) { LOGGER.info("New pool scheduled received from FMAN_FMAR for flex-offer with ID =>{}", event.getFlexOffer().getId()); /** update schedule update id by 1 */ event.getNewSchedule().setUpdateId(event.getFlexOffer().getFlexOfferSchedule().getUpdateId() + 1); /**update flex-offer schedule */ event.getFlexOffer().setFlexOfferSchedule(event.getNewSchedule()); LOGGER.info("Pool schedule updated for Flex-offer with ID =>{}", event.getFlexOffer().getId()); // also update FlexOfferT FlexOfferT flexOfferT = this.foaService.getFlexOffer(event.getFlexOffer().getId()); flexOfferT.setFlexoffer(event.getFlexOffer()); } // get new schedule and related data from event FlexOfferSchedule newSchedule = event.getNewSchedule(); FlexOffer flexOffer = event.getFlexOffer(); double offeredLowerEnergy = flexOffer.getFlexOfferProfile(0).getEnergyLower(0); double offeredUpperEnergy = flexOffer.getFlexOfferProfile(0).getEnergyUpper(0); double marketOrder = newSchedule.getTotalEnergy(); Date startTime = newSchedule.getStartTime(); Date endTime = FlexOffer.toAbsoluteTime(FlexOffer.toFlexOfferTime(startTime) + 1); Date currentTime = new Date(); if (startTime.before(currentTime)) { LOGGER.warn("Pool schedule time {} is before Current Time {}. Schedule Ignored", startTime, currentTime); return; } if (marketOrder < offeredLowerEnergy || marketOrder > offeredUpperEnergy) { LOGGER.warn("Pool schedule market order is out of bounds"); return; } PoolSchedule poolSchedule = new PoolSchedule(); // assuming there is only one slice poolSchedule.setOfferedEnergyLower(offeredLowerEnergy); poolSchedule.setOfferedEnergyUpper(offeredUpperEnergy); poolSchedule.setMarketOrder(marketOrder); // assuming there is always one slice poolSchedule.setCurrentPowerConsumption(-1); poolSchedule.setCumulativeEnergy(0); poolSchedule.setStartTime(startTime); poolSchedule.setEndTime(endTime); Long scheduleFoTime = FlexOffer.toFlexOfferTime(startTime); Long currentSliceFoTime = FlexOffer.toFlexOfferTime(currentTime); if (poolScheduleMap.get(org.getOrganizationName()).containsKey(scheduleFoTime)) { // transfer list of turned off devices from prev slice poolSchedule.setCurrentPowerConsumption(poolScheduleMap.get(org.getOrganizationName()).get(scheduleFoTime).getCurrentPowerConsumption()); poolSchedule.setCumulativeEnergy(poolScheduleMap.get(org.getOrganizationName()).get(scheduleFoTime).getCumulativeEnergy()); } poolScheduleMap.get(org.getOrganizationName()).put(scheduleFoTime, poolSchedule); printPoolSchedule(); LOGGER.info("poolScheduleMap map updated for organization: {}", event.getFlexOffer().getOfferedById()); } catch (Exception ex) { ex.printStackTrace(); LOGGER.error(ex.getLocalizedMessage()); } } private void printPoolSchedule() { LOGGER.info("current status of pool schedule map"); this.poolScheduleMap.forEach((key, val) -> { val.forEach((k, v) -> { LOGGER.info("org: {} slice: {}, map: {}", key, FlexOffer.toAbsoluteTime(k), v.toString()); }); }); } private List<String> getDevicesToTurnOff(Double power, String orgName, double deviceCoolingPeriod) { TreeMap<Double, String> devices = new TreeMap<>(Collections.reverseOrder()); List<String> devicesToTurnOff = new ArrayList<>(); Double powerToReduce = power; for (String key : poolDeviceDetail.get(orgName).keySet()) { PoolDeviceModel sdm = poolDeviceDetail.get(orgName).get(key); if (sdm.getCurrentState() == 1 && !this.poolScheduleMap.get(orgName).containsKey(key)) { devices.put(sdm.getCurrentTemperature() + new Random().nextDouble() * 0.001, sdm.getDeviceId()); } } for (Map.Entry<Double, String> entry : devices.entrySet()) { if (powerToReduce < 500) { break; } PoolDeviceModel sdm = poolDeviceDetail.get(orgName).get(devices.get(entry.getKey())); if (sdm.getLastReleasedFromPool() != null) { long coolingTime = (new Date().getTime() - sdm.getLastReleasedFromPool().getTime()) / 60000; if (coolingTime < deviceCoolingPeriod) { continue; } } // just in case it was recently turned on externally DeviceStateHistory deviceStateHistory = deviceStateHistoryRepository.getLatestDeviceHistory(entry.getValue()); if (deviceStateHistory != null && deviceStateHistory.getDeviceState() == DeviceState.Operating) { long coolingTime = (new Date().getTime() - deviceStateHistory.getTimestamp().getTime()) / 60000; if (coolingTime < 60) { continue; } } Double temperature = entry.getKey(); if (temperature > sdm.getMinTempThresh() && sdm.getCurrentState() == 1) { devicesToTurnOff.add(poolDeviceDetail.get(orgName).get(devices.get(temperature)).getDeviceId()); powerToReduce = powerToReduce - poolDeviceDetail.get(orgName).get(devices.get(temperature)).getCurrentPower(); } } return devicesToTurnOff; } private List<String> getDevicesToTurnOn(Double power, String orgName) { TreeMap<Double, String> devices = new TreeMap<>(); List<String> devicesToTurnOn = new ArrayList<>(); Double powerToIncrease = power; for (String deviceId : poolDeviceDetail.get(orgName).keySet()) { PoolDeviceModel sdm = poolDeviceDetail.get(orgName).get(deviceId); long coolingTime = 16; if (sdm.getLastIncludedInPool() != null) { coolingTime = (new Date().getTime() - sdm.getLastIncludedInPool().getTime()) / 60000; } if ( (this.poolTurnedOffDevices.get(orgName).containsKey(deviceId) || orgName.equals("TEST") ) && sdm.getCurrentState() == 0 && coolingTime > 15) { devices.put(sdm.getCurrentTemperature() + new Random().nextDouble() * 0.001, sdm.getDeviceId()); } } for (Map.Entry<Double, String> entry : devices.entrySet()) { Double temperature = entry.getKey(); if (powerToIncrease < 500) { break; } // just in case it was recently turned on externally DeviceStateHistory deviceStateHistory = deviceStateHistoryRepository.getLatestDeviceHistory(entry.getValue()); if (deviceStateHistory != null && deviceStateHistory.getDeviceState() == DeviceState.Idle) { long coolingTime = (new Date().getTime() - deviceStateHistory.getTimestamp().getTime()) / 60000; if (coolingTime < 5) { continue; } } String deviceId = devices.get(temperature); if (temperature < poolDeviceDetail.get(orgName).get(deviceId).getMaxTempThresh()) { devicesToTurnOn.add(poolDeviceDetail.get(orgName).get(devices.get(temperature)).getDeviceId()); powerToIncrease = powerToIncrease - poolDeviceDetail.get(orgName).get(devices.get(temperature)).getCurrentPower(); } } return devicesToTurnOn; } private void releaseDevicesFromPool(String orgName) { Set<String> deviceIds = this.poolTurnedOffDevices.get(orgName).keySet(); if (deviceIds.size() == 0) { return; } LOGGER.info("Releasing necessary devices from the pool"); for (String deviceId : deviceIds) { Date turnedOffTime = this.poolTurnedOffDevices.get(orgName).get(deviceId); long minutes = (new Date().getTime() - turnedOffTime.getTime()) / (1000 * 60); if (minutes > 30) { DeviceDetail deviceDetail = this.deviceDetailService.getDevice(deviceId); DeviceStateChangeEvent stateChangeEvent = new DeviceStateChangeEvent( this, String.format("releasing device: '%s' which was turned off at: '%s' from the pool", deviceDetail.getDeviceId(), turnedOffTime), deviceDetail, true); this.applicationEventPublisher.publishEvent(stateChangeEvent); this.poolDeviceDetail.get(orgName).get(deviceId).setLastReleasedFromPool(new Date()); this.poolTurnedOffDevices.get(orgName).remove(deviceId); LOGGER.info("Released org: {}, device: {} from the pool", orgName, deviceId); } } } public void executePoolSchedule() { long foTime = FlexOffer.toFlexOfferTime(new Date()); this.poolScheduleMap.forEach((orgName, orgPoolMap) -> { // first release those devices that are in OFF state longer than threshold releaseDevicesFromPool(orgName); // update pool power consumption updatePoolScheduleMapPower(orgName); // execute pool schedule for the organization executeOrgSchedule(orgName, foTime, orgPoolMap); }); } private void executeOrgSchedule(String orgName, long foTime, Map<Long, PoolSchedule> orgPoolMap) { if (orgPoolMap.size() == 0) { return; } if (!orgPoolMap.containsKey(foTime)) { return; } double lowerEnergy = orgPoolMap.get(foTime).getOfferedEnergyLower()*4000; double upperEnergy = orgPoolMap.get(foTime).getOfferedEnergyUpper()*4000; if ( Math.abs(upperEnergy-lowerEnergy) < 1) { LOGGER.info("Org: {} is in cooling period", orgName); return; } PoolSchedule poolSchedule = orgPoolMap.get(foTime); if (poolSchedule == null) { LOGGER.warn("No pool schedule found for the current slice for org: {}", orgName); return; } double marketOrder = poolSchedule.getMarketOrder() * 1000 * 4; double currentPowerConsumption = poolSchedule.getCurrentPowerConsumption(); if (currentPowerConsumption < 0) { return; } double cumulativeEnergy = poolSchedule.getCumulativeEnergy(); // Wh for now Organization org = this.organizationRepository.findByOrganizationName(orgName); LOGGER.info("Org: {}, Market order: {}, current consumption: {}", org.getOrganizationName(), marketOrder, currentPowerConsumption); if (marketOrder < currentPowerConsumption) { List<String> devicesToTurnOff = getDevicesToTurnOff(currentPowerConsumption-marketOrder, orgName, org.getPoolDeviceCoolingPeriod()); if (devicesToTurnOff.size() > 0 && org.getDirectControlMode() != OrganizationLoadControlState.Active) { LOGGER.warn("Not turning off devices because organization control disabled for: {}", orgName); return; } devicesToTurnOff.forEach(deviceId -> { DeviceDetail device = this.deviceDetailService.getDevice(deviceId); DeviceStateChangeEvent stateChangeEvent = new DeviceStateChangeEvent( this, String.format("Turning off device: '%s' due to inclusion in the pool", device.getDeviceId()), device, false); this.applicationEventPublisher.publishEvent(stateChangeEvent); this.poolDeviceDetail.get(orgName).get(deviceId).setLastIncludedInPool(new Date()); this.poolTurnedOffDevices.get(orgName).put(deviceId, new Date()); }); } else { List<String> devicesToTurnOn = getDevicesToTurnOn(marketOrder-currentPowerConsumption, orgName); if (devicesToTurnOn.size() > 0 && org.getDirectControlMode() != OrganizationLoadControlState.Active) { LOGGER.warn("Not turning on devices because organization control disabled for: {}", orgName); return; } devicesToTurnOn.forEach(deviceId -> { DeviceDetail device = this.deviceDetailService.getDevice(deviceId); DeviceStateChangeEvent stateChangeEvent = new DeviceStateChangeEvent( this, String.format("Turning on device: '%s' due to inclusion in the pool", device.getDeviceId()), device, true); this.applicationEventPublisher.publishEvent(stateChangeEvent); }); } // update cumulative energy this.poolScheduleMap.get(orgName).get(foTime).setCumulativeEnergy(cumulativeEnergy + currentPowerConsumption); } public void transferScheduleFromPrevToCurrSlice() { LOGGER.info("executing routine to transfer necessary schedule data from prev to curr slice"); long currentSliceFoTime = FlexOffer.toFlexOfferTime(new Date()); this.poolScheduleMap.forEach((orgName, orgPoolMap) -> { if (orgPoolMap.containsKey(currentSliceFoTime - 1)) { // delete prev slice from map this.poolScheduleMap.get(orgName).remove(currentSliceFoTime - 1); } }); } private void updatePoolScheduleMapPower(String orgName) { double latestAggPower = 0.0; for (Map.Entry<String, PoolDeviceModel> entry : this.poolDeviceDetail.get(orgName).entrySet()) { latestAggPower += entry.getValue().getCurrentPower(); } long foTime = FlexOffer.toFlexOfferTime(new Date()); if (this.poolScheduleMap.get(orgName).containsKey(foTime)) { this.poolScheduleMap.get(orgName).get(foTime).setCurrentPowerConsumption(latestAggPower); } } }
2090_5
package com.agelogeo.cookingmaliatsis; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.widget.SwitchCompat; import android.util.Log; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.CompoundButton; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { FragmentTransaction transaction; SQLiteDatabase myDatabase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); setTitle(""); setMyDatabase(); Cursor episode_cursor = myDatabase.rawQuery("SELECT * FROM episodes",null); if(episode_cursor.getCount()>0){ episode_cursor.moveToFirst(); do{ Episode episode = new Episode(); episode.setId(episode_cursor.getInt(0)); episode.setTitle(episode_cursor.getString(1)); episode.setVideo_id(episode_cursor.getString(2)); Cursor scene_cursor = myDatabase.rawQuery("SELECT * FROM scenes WHERE episode_id = ?",new String[] {Integer.toString(episode.getId())}); Log.i("EPISODE",episode.getId()+" "+scene_cursor.getCount()); if(scene_cursor.getCount()>0){ scene_cursor.moveToFirst(); do{ Scene scene = new Scene(); scene.setScene_id(scene_cursor.getInt(0)); scene.setTitle(scene_cursor.getString(1)); scene.setTimestamp(scene_cursor.getInt(2)); scene.setEpisode_id(scene_cursor.getInt(3)); episode.addOnEpisodeScenes(scene); scene_cursor.moveToNext(); }while(!scene_cursor.isAfterLast()); scene_cursor.close(); } SavedSettings.addOnStaticAllEpisodes(episode); episode_cursor.moveToNext(); }while(!episode_cursor.isAfterLast()); }else{ Log.i("DATABASE","No Result..."); } episode_cursor.close(); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); setFragment(new AllFragment()); } public void setMyDatabase(){ myDatabase = this.openOrCreateDatabase("MaliatsisDB",MODE_PRIVATE,null); myDatabase.execSQL("CREATE TABLE IF NOT EXISTS episodes (id INT(6), title VARCHAR , video_id VARCHAR )"); myDatabase.execSQL("CREATE TABLE IF NOT EXISTS scenes (id INT(6), title VARCHAR , timestamp INT(6) , episode_id INT(6), FOREIGN KEY (episode_id) REFERENCES episodes(id))"); Cursor c = myDatabase.rawQuery("SELECT * FROM episodes",null); if(c.getCount()==0){ Log.i("DATABASE","Initialize database.."); initiateDatabase(); } c.close(); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.all) { setFragment(new AllFragment()); } else if (id == R.id.favorites) { setFragment(new FavoritesFragment()); } else if (id == R.id.nav_slideshow) { } else if (id == R.id.nav_manage) { } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } public void setFragment(Fragment fragment) { transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.content_main_layout,fragment); transaction.commit(); } //(1,'Cooking Maliatsis - 01 - Φτερούγες κοτόπουλου με cola','https://img.youtube.com/vi/K99mRKZxPRc/hqdefault.jpg','https://www.youtube.com/watch?v=K99mRKZxPRc') public void initiateDatabase(){ myDatabase.execSQL("INSERT INTO episodes (id, title, video_id ) VALUES " + "(1,'Cooking Maliatsis - 01 - Φτερούγες κοτόπουλου με cola','K99mRKZxPRc'),"+ "(2,'Cooking Maliatsis - 02 - Κάτι σαν ομελέτα (ο Θεός να την κάνει)','-LIYTu4nDkc')," + "(3,'Cooking Maliatsis - 03 - Μπισκοτατάκια με πραλίνα','KSZIMQWNhng')," + "(4,'Cooking Maliatsis - 04 - Κοτο(τσα)μπουκιές με nachos','6H3brlrLiBQ')," + "(5,'Cooking Maliatsis - 05 - Πίτα του Ποπάυ','KSZIMQWNhng')," + "(6,'Cooking Maliatsis - 06 - Στριφτή Μανιταρόπιτα','RM8xI3Co8-g')," + "(7,'Cooking Maliatsis - 07 - Quiche Lorraine','qJorwkgXffo')," + "(8,'Cooking Maliatsis - 08 - Το απόλυτο σάντουιτς','yIZOjzFfZN0')," + "(9,'Cooking Maliatsis - 09 - Κρέπες','5QytMNrIKVs')," + "(10,'Cooking Maliatsis - 10 - Ποπ κορν','zVfg-TdwbzE')," + "(11,'Cooking Maliatsis - 11 - Ωχ, τα πλευρά μου','CAu-TwP6gTo')," + "(12,'Cooking Maliatsis - 12 - Πανσέτες Pancho Villa','QP7dQvGmfoY')," + "(13,'Cooking Maliatsis - 13 - Το παλαμάρι του βαρκάρη','ohrbmP0dGpI')," + "(14,'Cooking Maliatsis - 14 - Μελομακαρομπιέδες και κουραμπιεκάρονα','r_7UtyPEhHM')," + "(15,'Cooking Maliatsis - 15 - Βασιλόπιτα','XNcukPQmRB8')," + "(16,'Cooking Maliatsis - 16 - Μουσακόγυρος','tIHuokZfU1g')," + "(17,'Cooking Maliatsis - 17 - Enrique: πέστροφα σε κρούστα αμυγδάλου','vOP4yFXB6Gc')," + "(18,'Cooking Maliatsis - 18 - Scotch Eggs','axx-pqsX78U')," + "(19,'Cooking Maliatsis - 19 - Κρεμ Μπρουλέ','HyMIwPazi5o')," + "(20,'Cooking Maliatsis - 20 - Κινέζικο Γ.Τ.Π.','cpbm3xW3DJc')," + "(21,'Cooking Maliatsis - 21 - Shepherd\''s Chilli','K9Ma9B-1KPM')," + "(22,'Cooking Maliatsis - 22 - Προφιτερόλ','hRuvGyvbwwg')," + "(23,'Cooking Maliatsis - 23 - Λαχανοντολμάδες αυγολέμονο','1YrpSjHl2tU')," + "(24,'Cooking Maliatsis - 24 - Διπλό Τζακπότ','B-bAutz5dAI')," + "(25,'Cooking Maliatsis - 25 - Μοσχαρίσια τηγανιά με πουρέ γλυκοπατάτας','82N7y--Zz_E')," + "(26,'Cooking Maliatsis - 26 - Cheesecake Brownies','gTmwHU9PRNs')," + "(27,'Cooking Maliatsis - 27 - Burger Φιδέλ Κάστρο','Il-IYctdWEw')," + "(28,'Cooking Maliatsis - 28 - Χταπόδι με κοφτό μακαρονάκι','ndnwH3z-dTM')," + "(29,'Cooking Maliatsis - 29 - Και κουλούρι και τυρί','yvSsGosXCeU')," + "(30,'Cooking Maliatsis - 30 - Σουσι-κώνεται;','mVs7klyup3g')," + "(31,'Cooking Maliatsis - 31 - Χοχλιοί μπουμπουριστοί','698H630xgWs')," + "(32,'Cooking Maliatsis - 32 - (Μας τα \''κανες) τσουρέκια','mEMYql14nvE')," + "(33,'Cooking Maliatsis - 33 - Μαγειρίτσα','IDK-JKwNP10')," + "(34,'Cooking Maliatsis - 34 - Κοντορέτσι/Κοκοσούβλι','Xc_1TflsTUE')," + "(35,'Cooking Maliatsis - 35 - Αγκινάρες α λα πολίτα','qZ6OnXpaXQo')," + "(36,'Cooking Maliatsis - 36 - Η σούπα της αγάπης','YPB1vOnmyys')," + "(37,'Cooking Maliatsis - 37 - Κανταΐφι και έθιμα','jgOzIl0bM_o')," + "(38,'Cooking Maliatsis - 38 - Πίτσα κέικ με γύρο','IIgbkjEAZiU')," + "(39,'Cooking Maliatsis - 39 - Μπιφτέκπληξη','svSBKIVaQxE')," + "(40,'Cooking Maliatsis - 40 - Γαριδοαστακομακαρονάδα','fD8-FRSyZsY')," + "(41,'Cooking Maliatsis - 41 - Παγωτό κόλλυβα','DH7i75ASq6Y')," + "(42,'Cooking Maliatsis - 42 - Μοριακό σουβλάκι','r3uFn3VPF48')," + "(43,'Cooking Maliatsis - 43 - Τούρτα εKλαίρ','MYQg6yXuoVk')," + "(44,'Cooking Maliatsis - 44 - Ψαρονέφρι γεμιστό με πατάτα ακορντεόν','l-piTdJnsTc')," + "(45,'Cooking Maliatsis - 45 - Vegan Mac\''n\''Cheese με vegeκεφτεδάκια','HEoHdtqDNIo')," + "(46,'Cooking Maliatsis - 46 - Φεστιβαλ χοληστερίνης','7O4yI4Vp86c')," + "(47,'Cooking Maliatsis - 47 - Κολοκύθα τούμπανο','ElQr3xWtjOI')," + "(48,'Cooking Maliatsis - 48 - Μπουγιαμπέσα με μούτσο','Z2HTOPzNvY0')," + "(49,'Cooking Maliatsis - 49 - Γεμιστές χοιρινές μπριζόλες','rp0BQJXMQkY')," + "(50,'Cooking Maliatsis - 50 - Αρνάκι (άσπρο και παχύ της μάνας του) με κάρι','RymudG45k9E')," + "(51,'Cooking Maliatsis - 51 - Φιλέτο Wellington ft. Δημήτρης Σκαρμούτσος','PmLuuGQ7n-U')," + "(52,'Cooking Maliatsis - 52 - Γιουβαρλάκια','f6-kA6OfglE')," + "(53,'Cooking Maliatsis - 53 - Μπανανόφι','OUNWQ-OlPDY')," + "(54,'Cooking Maliatsis - 54 - Στιφάδο','AWDls2_zfuc')," + "(55,'Cooking Maliatsis - 55 - Γηρωικό σάντουιτς','FxJsUwo5_4I')," + "(56,'Cooking Maliatsis - 56 - Τούρτα πίτσα','XYhgCBQivL0')," + "(57,'Cooking Maliatsis - 57 - Νιόκι με κρέμα απάκι','_N9Lwn7b5DA')," + "(58,'Cooking Maliatsis - 58 - Φασόλια χάντρες με λουκάνικο και μπέικον','lYIpYZDTSIo')," + "(59,'Cooking Maliatsis - 59 - Πάπια πορτοκάλι','VqTBUb3xivU')," + "(60,'Cooking Maliatsis - 60 - Κανελόνια γεμιστά','AZzUgij_wqI')," + "(61,'Cooking Maliatsis - 61 - Τάρτα σοκολάτα φιστικοβούτυρο','edfIVo-M4fo')," + "(62,'Cooking Maliatsis - 62 - Θράψαλο γεμιστό','gj1NCbk8MSs')," + "(63,'Cooking Maliatsis - 63 - Χειροποίητα ζυμαρικά','c9bmKFatRMw')," + "(64,'Cooking Maliatsis - 64 - İçli Köfte','y1wtsIKG8fc')," + "(65,'Cooking Maliatsis - 65 - Μου έφυγε ο tacos','yQ-1g98VoB8')," + "(66,'Cooking Maliatsis - 66 - Κρεατοκουλούρα','5zYzzbtr9nQ')," + "(67,'Cooking Maliatsis - 67 - Ρώσικη ρουλέτα','rqtf25Skd-4')," + "(68,'Cooking Maliatsis - 68 - Αρνί γεμιστό + Bonus','fnqCfEh5HMg')," + "(69,'Cooking Maliatsis - 69 - Γαλακτομπούρεκο','HMaph-4zErc')," + "(70,'Cooking Maliatsis - 70 - Cinammon Buns','6-i4yzp0LMg')," + "(71,'Cooking Maliatsis - 71 - Κοτόπουλο Παρμεζάναξ Ft. Μάρκος Σεφερλης','LU6zEzsSDyk')," + "(72,'Cooking Maliatsis - 72 - Πεϊνιρλί','E8DKIfz0WMA')," + "(73,'Cooking Maliatsis - 73 - Πάβλοβα','5r2wxbWY1uQ')," + "(74,'Cooking Maliatsis - 74 - Despastitsio','DP6E-Wun1Nk')," + "(75,'Cooking Maliatsis - 75 Burger Mac and Cheese','90K4l7InCkg')," + "(76,'Cooking Maliatsis - 76 - Φιλέτο γλώσσας με μελιτζανοσαλάτα','RkV2ANwf0nc')," + "(77,'Cooking Maliatsis - 77 - Chimichanga τούμπανο','jbgtZ1BByaM')," + "(78,'Cooking Maliatsis - 78 - Τραγική Τριλογία','EEe2u2Nzz4U')," + "(79,'Cooking Maliatsis - 79 - Γαρίδες κανταΐφι με ριζότο παντζαριού','76HhWfQR-B0')," + "(80,'Cooking Maliatsis - 80 - Σαπιομπουρδελάκατος Πρασοσέλινο','dboF-LMEOh8')," + "(81,'Cooking Maliatsis - 81 - Τάρτα με συκωτάκια πουλιών','Wef0OEGZT_I')," + "(82,'Cooking Maliatsis - 82 - Rixtetointernet Πίτσα','jl5_qIhk6n0')," + "(83,'Cooking Maliatsis - 83 - Σουπιές με σπανάκι + Πίτα έκπληξη','DV5sxxe-BUA')," + "(84,'Cooking Maliatsis - 84 - Thai κοτόπουλο με πράσινο κάρρυ','RYyeEVPMcV0')," + "(85,'Cooking Maliatsis - 85 - Λουκάνικααααα','t3aHyhuXEA4')," + "(86,'Cooking Maliatsis - 86 - Βασιλοπιτά-πιτα & Γαλοπουλομπάμπουσκα','027wrBETjN4')," + "(87,'Cooking Maliatsis - 87 - Χέλια στο φούρνο & σπάθα στο τηγάνι','_xL2yjN1quw')," + "(88,'Cooking Maliatsis - 88 - Βουρ στον πατσά / πατσα-βουρ-όπιτα','5n4pdH-Q6II')," + "(89,'Cooking Maliatsis - 89 - Γαμήλια Τούρτα (ft. Λυδία Παπαϊωάννου)','Mq3LTYvjWWU')," + "(90,'Cooking Maliatsis - 90 - Βατραχοπόδαρα & αμελέτητα','LGEDc28Jy2A')," + "(91,'Cooking Maliatsis - 91 - Σαλάτα σε ζελέ','MyLycdgSuTk')," + "(92,'Cooking Maliatsis - 92 - Πιτσόγυρο','UkGatpNNa-Q')," + "(93,'Cooking Maliatsis - 93 - Απολύομαι ψαρούκλες','5HSYtgdzfT0')," + "(94,'Cooking Maliatsis - 94 - Godzilla Steak','jI5zAqmOX2o')," + "(95,'Cooking Maliatsis - 95 - Κοτόπουλο με σάλτσα σοκολάτας (mole poblano)','LzGL4qcaGjs')," + "(96,'Cooking Maliatsis - 96 - Donuts με γαλαξιακό γλάσο','q6SV1d2Ppcg')," + "(97,'Cooking Maliatsis - 97 - Σαλάτα με παγωτό τυρί','6ewUA-qDMK0')," + "(98,'Cooking Maliatsis - 98 - Ο Πύργος της Κολάσεως!','De2abch0Ax0')," + "(99,'Cooking Maliatsis - 99 - Μπακλαβάς Cheesecake','8fYlUekpNKw')," + "(100,'Cooking Maliatsis - Πάσχα στο Χωριό 2018 Special','WymzcFL_s3o')," + "(101,'Cooking Maliatsis - 100 - Γεμιστά με γύρο','Lby2yat8boc')," + "(102,'Cooking Maliatsis - 101 - Stargazy Pie','u6dCYy1YukE')," + "(103,'Cooking Maliatsis - 102 - Χωνακονιονκεφτέδες της οργής','ayq4ikbgwr8')," + "(104,'Cooking Maliatsis - 103 - Το SPAM του αιώνα','mm25peTPo2c')," + "(105,'Cooking Maliatsis - 104 - Πίτσα κουνουπίδι','50aNUFqjJcI')," + "(106,'Cooking Maliatsis - 105 - Ντόπα γλυκό με Baileys','G_1UtzpOtwo')," + "(107,'Cooking Maliatsis - 106 - Τροπικό χοιρινό με μπανάνα ft. Ευρυδίκη Βαλαβάνη','OYtcKfH88-s')," + "(108,'Cooking Maliatsis - 107 - Deep Fried Cheeseburger','28VCnmE3K0k')," + "(109,'Cooking Maliatsis - 108 - Χταπόδι φρικασέ και-φτέδες','yZ0y95jAF4U')," + "(110,'Cooking Maliatsis - 109 - Brownies με 3 σοκολάτες και παντζάρι','0ObhDXXyUCA')," + "(111,'Cooking Maliatsis - 110 - Ramen ft. Σωτήρης Κοντιζάς','EVzaw5rFY3Q')," + "(112,'Cooking Maliatsis - 111 - ΤΟΥΜΠΑΝΟΟΟΟ (speaks fluent Italian)','tQyudI2GBMQ')," + "(113,'Cooking Maliatsis - 112 - Κουνέλι κοκορέτσι','9psbqMpI-mw')," + "(114,'Cooking Maliatsis - 113 - Flying spaghetti κιμάνστερ','sQP67PAQRUQ')," + "(115,'Cooking Maliatsis - 114 - Πρόχειρο διαγώνισμα: Scotch Eggs','BybNrB9n6XA')," + "(116,'Cooking Maliatsis - 115 - Πορτσέτα με μπύρα','tchGGkelGc0')," + "(117,'Cooking Maliatsis - 116 - Ο τιτλος του $eΧ tape σου','vx8tb2xBhUs')," + "(118,'Cooking Maliatsis - 117 - Επικά μπισκοτομπράουνις','2vYpgR645jM')," + "(119,'Cooking Maliatsis - 118 - Ποιος γ@μ@ει ποιος χήνα','RHTH57bYsWI')," + "(120,'Cooking Maliatsis - 119 - Μπιφτεκολαζάνια με κιμά','5eerj2Fby0w')," + "(121,'Cooking Maliatsis - 120 - Κεφαλάκι αρνίσιο','x4gm4CLGJyU')," + "(122,'Cooking Maliatsis - 121 - Κύβος ΤυΡούμπικ ft. Φάνης Λαμπρόπουλος','HITaLSa21rk')," + "(123,'Cooking Maliatsis - 122 - Πορτοκαλοπιτα με παγωτό','cLreTY58n5k')," + "(124,'Cooking Maliatsis - 123 - Παέγια','TSV0J0qS1i8')," + "(125,'Cooking Maliatsis - 124 - Μους σοκολάτα honeycomb','EU5IPEeCOoo')," + "(126,'Cooking Maliatsis - 125 - Kizomba Hash Browns με Γύρο','d8mRhcqwu5Y')"); initiateDatabaseScenes(); } public void initiateDatabaseScenes(){ //id INT(6), title VARCHAR , timestamp INT(6) , episode_id INT(6) myDatabase.execSQL("INSERT INTO scenes (id, title, timestamp , episode_id ) VALUES " + "(1,'Test Scene #1',85,126)," + "(2,'Test Scene #2',120,126)," + "(3,'Test Scene #3',215,126)," + "(4,'Test Scene #4',5,126)"); } }
agelogeo/CookingMaliatsis
app/src/main/java/com/agelogeo/cookingmaliatsis/MainActivity.java
7,646
//(1,'Cooking Maliatsis - 01 - Φτερούγες κοτόπουλου με cola','https://img.youtube.com/vi/K99mRKZxPRc/hqdefault.jpg','https://www.youtube.com/watch?v=K99mRKZxPRc')
line_comment
el
package com.agelogeo.cookingmaliatsis; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.widget.SwitchCompat; import android.util.Log; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.CompoundButton; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { FragmentTransaction transaction; SQLiteDatabase myDatabase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); setTitle(""); setMyDatabase(); Cursor episode_cursor = myDatabase.rawQuery("SELECT * FROM episodes",null); if(episode_cursor.getCount()>0){ episode_cursor.moveToFirst(); do{ Episode episode = new Episode(); episode.setId(episode_cursor.getInt(0)); episode.setTitle(episode_cursor.getString(1)); episode.setVideo_id(episode_cursor.getString(2)); Cursor scene_cursor = myDatabase.rawQuery("SELECT * FROM scenes WHERE episode_id = ?",new String[] {Integer.toString(episode.getId())}); Log.i("EPISODE",episode.getId()+" "+scene_cursor.getCount()); if(scene_cursor.getCount()>0){ scene_cursor.moveToFirst(); do{ Scene scene = new Scene(); scene.setScene_id(scene_cursor.getInt(0)); scene.setTitle(scene_cursor.getString(1)); scene.setTimestamp(scene_cursor.getInt(2)); scene.setEpisode_id(scene_cursor.getInt(3)); episode.addOnEpisodeScenes(scene); scene_cursor.moveToNext(); }while(!scene_cursor.isAfterLast()); scene_cursor.close(); } SavedSettings.addOnStaticAllEpisodes(episode); episode_cursor.moveToNext(); }while(!episode_cursor.isAfterLast()); }else{ Log.i("DATABASE","No Result..."); } episode_cursor.close(); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); setFragment(new AllFragment()); } public void setMyDatabase(){ myDatabase = this.openOrCreateDatabase("MaliatsisDB",MODE_PRIVATE,null); myDatabase.execSQL("CREATE TABLE IF NOT EXISTS episodes (id INT(6), title VARCHAR , video_id VARCHAR )"); myDatabase.execSQL("CREATE TABLE IF NOT EXISTS scenes (id INT(6), title VARCHAR , timestamp INT(6) , episode_id INT(6), FOREIGN KEY (episode_id) REFERENCES episodes(id))"); Cursor c = myDatabase.rawQuery("SELECT * FROM episodes",null); if(c.getCount()==0){ Log.i("DATABASE","Initialize database.."); initiateDatabase(); } c.close(); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.all) { setFragment(new AllFragment()); } else if (id == R.id.favorites) { setFragment(new FavoritesFragment()); } else if (id == R.id.nav_slideshow) { } else if (id == R.id.nav_manage) { } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } public void setFragment(Fragment fragment) { transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.content_main_layout,fragment); transaction.commit(); } //(1,'Cooking Maliatsis<SUF> public void initiateDatabase(){ myDatabase.execSQL("INSERT INTO episodes (id, title, video_id ) VALUES " + "(1,'Cooking Maliatsis - 01 - Φτερούγες κοτόπουλου με cola','K99mRKZxPRc'),"+ "(2,'Cooking Maliatsis - 02 - Κάτι σαν ομελέτα (ο Θεός να την κάνει)','-LIYTu4nDkc')," + "(3,'Cooking Maliatsis - 03 - Μπισκοτατάκια με πραλίνα','KSZIMQWNhng')," + "(4,'Cooking Maliatsis - 04 - Κοτο(τσα)μπουκιές με nachos','6H3brlrLiBQ')," + "(5,'Cooking Maliatsis - 05 - Πίτα του Ποπάυ','KSZIMQWNhng')," + "(6,'Cooking Maliatsis - 06 - Στριφτή Μανιταρόπιτα','RM8xI3Co8-g')," + "(7,'Cooking Maliatsis - 07 - Quiche Lorraine','qJorwkgXffo')," + "(8,'Cooking Maliatsis - 08 - Το απόλυτο σάντουιτς','yIZOjzFfZN0')," + "(9,'Cooking Maliatsis - 09 - Κρέπες','5QytMNrIKVs')," + "(10,'Cooking Maliatsis - 10 - Ποπ κορν','zVfg-TdwbzE')," + "(11,'Cooking Maliatsis - 11 - Ωχ, τα πλευρά μου','CAu-TwP6gTo')," + "(12,'Cooking Maliatsis - 12 - Πανσέτες Pancho Villa','QP7dQvGmfoY')," + "(13,'Cooking Maliatsis - 13 - Το παλαμάρι του βαρκάρη','ohrbmP0dGpI')," + "(14,'Cooking Maliatsis - 14 - Μελομακαρομπιέδες και κουραμπιεκάρονα','r_7UtyPEhHM')," + "(15,'Cooking Maliatsis - 15 - Βασιλόπιτα','XNcukPQmRB8')," + "(16,'Cooking Maliatsis - 16 - Μουσακόγυρος','tIHuokZfU1g')," + "(17,'Cooking Maliatsis - 17 - Enrique: πέστροφα σε κρούστα αμυγδάλου','vOP4yFXB6Gc')," + "(18,'Cooking Maliatsis - 18 - Scotch Eggs','axx-pqsX78U')," + "(19,'Cooking Maliatsis - 19 - Κρεμ Μπρουλέ','HyMIwPazi5o')," + "(20,'Cooking Maliatsis - 20 - Κινέζικο Γ.Τ.Π.','cpbm3xW3DJc')," + "(21,'Cooking Maliatsis - 21 - Shepherd\''s Chilli','K9Ma9B-1KPM')," + "(22,'Cooking Maliatsis - 22 - Προφιτερόλ','hRuvGyvbwwg')," + "(23,'Cooking Maliatsis - 23 - Λαχανοντολμάδες αυγολέμονο','1YrpSjHl2tU')," + "(24,'Cooking Maliatsis - 24 - Διπλό Τζακπότ','B-bAutz5dAI')," + "(25,'Cooking Maliatsis - 25 - Μοσχαρίσια τηγανιά με πουρέ γλυκοπατάτας','82N7y--Zz_E')," + "(26,'Cooking Maliatsis - 26 - Cheesecake Brownies','gTmwHU9PRNs')," + "(27,'Cooking Maliatsis - 27 - Burger Φιδέλ Κάστρο','Il-IYctdWEw')," + "(28,'Cooking Maliatsis - 28 - Χταπόδι με κοφτό μακαρονάκι','ndnwH3z-dTM')," + "(29,'Cooking Maliatsis - 29 - Και κουλούρι και τυρί','yvSsGosXCeU')," + "(30,'Cooking Maliatsis - 30 - Σουσι-κώνεται;','mVs7klyup3g')," + "(31,'Cooking Maliatsis - 31 - Χοχλιοί μπουμπουριστοί','698H630xgWs')," + "(32,'Cooking Maliatsis - 32 - (Μας τα \''κανες) τσουρέκια','mEMYql14nvE')," + "(33,'Cooking Maliatsis - 33 - Μαγειρίτσα','IDK-JKwNP10')," + "(34,'Cooking Maliatsis - 34 - Κοντορέτσι/Κοκοσούβλι','Xc_1TflsTUE')," + "(35,'Cooking Maliatsis - 35 - Αγκινάρες α λα πολίτα','qZ6OnXpaXQo')," + "(36,'Cooking Maliatsis - 36 - Η σούπα της αγάπης','YPB1vOnmyys')," + "(37,'Cooking Maliatsis - 37 - Κανταΐφι και έθιμα','jgOzIl0bM_o')," + "(38,'Cooking Maliatsis - 38 - Πίτσα κέικ με γύρο','IIgbkjEAZiU')," + "(39,'Cooking Maliatsis - 39 - Μπιφτέκπληξη','svSBKIVaQxE')," + "(40,'Cooking Maliatsis - 40 - Γαριδοαστακομακαρονάδα','fD8-FRSyZsY')," + "(41,'Cooking Maliatsis - 41 - Παγωτό κόλλυβα','DH7i75ASq6Y')," + "(42,'Cooking Maliatsis - 42 - Μοριακό σουβλάκι','r3uFn3VPF48')," + "(43,'Cooking Maliatsis - 43 - Τούρτα εKλαίρ','MYQg6yXuoVk')," + "(44,'Cooking Maliatsis - 44 - Ψαρονέφρι γεμιστό με πατάτα ακορντεόν','l-piTdJnsTc')," + "(45,'Cooking Maliatsis - 45 - Vegan Mac\''n\''Cheese με vegeκεφτεδάκια','HEoHdtqDNIo')," + "(46,'Cooking Maliatsis - 46 - Φεστιβαλ χοληστερίνης','7O4yI4Vp86c')," + "(47,'Cooking Maliatsis - 47 - Κολοκύθα τούμπανο','ElQr3xWtjOI')," + "(48,'Cooking Maliatsis - 48 - Μπουγιαμπέσα με μούτσο','Z2HTOPzNvY0')," + "(49,'Cooking Maliatsis - 49 - Γεμιστές χοιρινές μπριζόλες','rp0BQJXMQkY')," + "(50,'Cooking Maliatsis - 50 - Αρνάκι (άσπρο και παχύ της μάνας του) με κάρι','RymudG45k9E')," + "(51,'Cooking Maliatsis - 51 - Φιλέτο Wellington ft. Δημήτρης Σκαρμούτσος','PmLuuGQ7n-U')," + "(52,'Cooking Maliatsis - 52 - Γιουβαρλάκια','f6-kA6OfglE')," + "(53,'Cooking Maliatsis - 53 - Μπανανόφι','OUNWQ-OlPDY')," + "(54,'Cooking Maliatsis - 54 - Στιφάδο','AWDls2_zfuc')," + "(55,'Cooking Maliatsis - 55 - Γηρωικό σάντουιτς','FxJsUwo5_4I')," + "(56,'Cooking Maliatsis - 56 - Τούρτα πίτσα','XYhgCBQivL0')," + "(57,'Cooking Maliatsis - 57 - Νιόκι με κρέμα απάκι','_N9Lwn7b5DA')," + "(58,'Cooking Maliatsis - 58 - Φασόλια χάντρες με λουκάνικο και μπέικον','lYIpYZDTSIo')," + "(59,'Cooking Maliatsis - 59 - Πάπια πορτοκάλι','VqTBUb3xivU')," + "(60,'Cooking Maliatsis - 60 - Κανελόνια γεμιστά','AZzUgij_wqI')," + "(61,'Cooking Maliatsis - 61 - Τάρτα σοκολάτα φιστικοβούτυρο','edfIVo-M4fo')," + "(62,'Cooking Maliatsis - 62 - Θράψαλο γεμιστό','gj1NCbk8MSs')," + "(63,'Cooking Maliatsis - 63 - Χειροποίητα ζυμαρικά','c9bmKFatRMw')," + "(64,'Cooking Maliatsis - 64 - İçli Köfte','y1wtsIKG8fc')," + "(65,'Cooking Maliatsis - 65 - Μου έφυγε ο tacos','yQ-1g98VoB8')," + "(66,'Cooking Maliatsis - 66 - Κρεατοκουλούρα','5zYzzbtr9nQ')," + "(67,'Cooking Maliatsis - 67 - Ρώσικη ρουλέτα','rqtf25Skd-4')," + "(68,'Cooking Maliatsis - 68 - Αρνί γεμιστό + Bonus','fnqCfEh5HMg')," + "(69,'Cooking Maliatsis - 69 - Γαλακτομπούρεκο','HMaph-4zErc')," + "(70,'Cooking Maliatsis - 70 - Cinammon Buns','6-i4yzp0LMg')," + "(71,'Cooking Maliatsis - 71 - Κοτόπουλο Παρμεζάναξ Ft. Μάρκος Σεφερλης','LU6zEzsSDyk')," + "(72,'Cooking Maliatsis - 72 - Πεϊνιρλί','E8DKIfz0WMA')," + "(73,'Cooking Maliatsis - 73 - Πάβλοβα','5r2wxbWY1uQ')," + "(74,'Cooking Maliatsis - 74 - Despastitsio','DP6E-Wun1Nk')," + "(75,'Cooking Maliatsis - 75 Burger Mac and Cheese','90K4l7InCkg')," + "(76,'Cooking Maliatsis - 76 - Φιλέτο γλώσσας με μελιτζανοσαλάτα','RkV2ANwf0nc')," + "(77,'Cooking Maliatsis - 77 - Chimichanga τούμπανο','jbgtZ1BByaM')," + "(78,'Cooking Maliatsis - 78 - Τραγική Τριλογία','EEe2u2Nzz4U')," + "(79,'Cooking Maliatsis - 79 - Γαρίδες κανταΐφι με ριζότο παντζαριού','76HhWfQR-B0')," + "(80,'Cooking Maliatsis - 80 - Σαπιομπουρδελάκατος Πρασοσέλινο','dboF-LMEOh8')," + "(81,'Cooking Maliatsis - 81 - Τάρτα με συκωτάκια πουλιών','Wef0OEGZT_I')," + "(82,'Cooking Maliatsis - 82 - Rixtetointernet Πίτσα','jl5_qIhk6n0')," + "(83,'Cooking Maliatsis - 83 - Σουπιές με σπανάκι + Πίτα έκπληξη','DV5sxxe-BUA')," + "(84,'Cooking Maliatsis - 84 - Thai κοτόπουλο με πράσινο κάρρυ','RYyeEVPMcV0')," + "(85,'Cooking Maliatsis - 85 - Λουκάνικααααα','t3aHyhuXEA4')," + "(86,'Cooking Maliatsis - 86 - Βασιλοπιτά-πιτα & Γαλοπουλομπάμπουσκα','027wrBETjN4')," + "(87,'Cooking Maliatsis - 87 - Χέλια στο φούρνο & σπάθα στο τηγάνι','_xL2yjN1quw')," + "(88,'Cooking Maliatsis - 88 - Βουρ στον πατσά / πατσα-βουρ-όπιτα','5n4pdH-Q6II')," + "(89,'Cooking Maliatsis - 89 - Γαμήλια Τούρτα (ft. Λυδία Παπαϊωάννου)','Mq3LTYvjWWU')," + "(90,'Cooking Maliatsis - 90 - Βατραχοπόδαρα & αμελέτητα','LGEDc28Jy2A')," + "(91,'Cooking Maliatsis - 91 - Σαλάτα σε ζελέ','MyLycdgSuTk')," + "(92,'Cooking Maliatsis - 92 - Πιτσόγυρο','UkGatpNNa-Q')," + "(93,'Cooking Maliatsis - 93 - Απολύομαι ψαρούκλες','5HSYtgdzfT0')," + "(94,'Cooking Maliatsis - 94 - Godzilla Steak','jI5zAqmOX2o')," + "(95,'Cooking Maliatsis - 95 - Κοτόπουλο με σάλτσα σοκολάτας (mole poblano)','LzGL4qcaGjs')," + "(96,'Cooking Maliatsis - 96 - Donuts με γαλαξιακό γλάσο','q6SV1d2Ppcg')," + "(97,'Cooking Maliatsis - 97 - Σαλάτα με παγωτό τυρί','6ewUA-qDMK0')," + "(98,'Cooking Maliatsis - 98 - Ο Πύργος της Κολάσεως!','De2abch0Ax0')," + "(99,'Cooking Maliatsis - 99 - Μπακλαβάς Cheesecake','8fYlUekpNKw')," + "(100,'Cooking Maliatsis - Πάσχα στο Χωριό 2018 Special','WymzcFL_s3o')," + "(101,'Cooking Maliatsis - 100 - Γεμιστά με γύρο','Lby2yat8boc')," + "(102,'Cooking Maliatsis - 101 - Stargazy Pie','u6dCYy1YukE')," + "(103,'Cooking Maliatsis - 102 - Χωνακονιονκεφτέδες της οργής','ayq4ikbgwr8')," + "(104,'Cooking Maliatsis - 103 - Το SPAM του αιώνα','mm25peTPo2c')," + "(105,'Cooking Maliatsis - 104 - Πίτσα κουνουπίδι','50aNUFqjJcI')," + "(106,'Cooking Maliatsis - 105 - Ντόπα γλυκό με Baileys','G_1UtzpOtwo')," + "(107,'Cooking Maliatsis - 106 - Τροπικό χοιρινό με μπανάνα ft. Ευρυδίκη Βαλαβάνη','OYtcKfH88-s')," + "(108,'Cooking Maliatsis - 107 - Deep Fried Cheeseburger','28VCnmE3K0k')," + "(109,'Cooking Maliatsis - 108 - Χταπόδι φρικασέ και-φτέδες','yZ0y95jAF4U')," + "(110,'Cooking Maliatsis - 109 - Brownies με 3 σοκολάτες και παντζάρι','0ObhDXXyUCA')," + "(111,'Cooking Maliatsis - 110 - Ramen ft. Σωτήρης Κοντιζάς','EVzaw5rFY3Q')," + "(112,'Cooking Maliatsis - 111 - ΤΟΥΜΠΑΝΟΟΟΟ (speaks fluent Italian)','tQyudI2GBMQ')," + "(113,'Cooking Maliatsis - 112 - Κουνέλι κοκορέτσι','9psbqMpI-mw')," + "(114,'Cooking Maliatsis - 113 - Flying spaghetti κιμάνστερ','sQP67PAQRUQ')," + "(115,'Cooking Maliatsis - 114 - Πρόχειρο διαγώνισμα: Scotch Eggs','BybNrB9n6XA')," + "(116,'Cooking Maliatsis - 115 - Πορτσέτα με μπύρα','tchGGkelGc0')," + "(117,'Cooking Maliatsis - 116 - Ο τιτλος του $eΧ tape σου','vx8tb2xBhUs')," + "(118,'Cooking Maliatsis - 117 - Επικά μπισκοτομπράουνις','2vYpgR645jM')," + "(119,'Cooking Maliatsis - 118 - Ποιος γ@μ@ει ποιος χήνα','RHTH57bYsWI')," + "(120,'Cooking Maliatsis - 119 - Μπιφτεκολαζάνια με κιμά','5eerj2Fby0w')," + "(121,'Cooking Maliatsis - 120 - Κεφαλάκι αρνίσιο','x4gm4CLGJyU')," + "(122,'Cooking Maliatsis - 121 - Κύβος ΤυΡούμπικ ft. Φάνης Λαμπρόπουλος','HITaLSa21rk')," + "(123,'Cooking Maliatsis - 122 - Πορτοκαλοπιτα με παγωτό','cLreTY58n5k')," + "(124,'Cooking Maliatsis - 123 - Παέγια','TSV0J0qS1i8')," + "(125,'Cooking Maliatsis - 124 - Μους σοκολάτα honeycomb','EU5IPEeCOoo')," + "(126,'Cooking Maliatsis - 125 - Kizomba Hash Browns με Γύρο','d8mRhcqwu5Y')"); initiateDatabaseScenes(); } public void initiateDatabaseScenes(){ //id INT(6), title VARCHAR , timestamp INT(6) , episode_id INT(6) myDatabase.execSQL("INSERT INTO scenes (id, title, timestamp , episode_id ) VALUES " + "(1,'Test Scene #1',85,126)," + "(2,'Test Scene #2',120,126)," + "(3,'Test Scene #3',215,126)," + "(4,'Test Scene #4',5,126)"); } }
19685_5
package PonySearcher.optimization; import Common.SortedIterablePriorityQuery; import Common.TermNormalizer; import Common.StopWords; import PonySearcher.models.ParsedQueryTerm; import java.io.File; import java.io.IOException; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import org.lexvo.uwn.Entity; import org.lexvo.uwn.Statement; import org.lexvo.uwn.UWN; /** * * @author Apostolidis */ public class VocabolaryTraitsFetcher { private static VocabolaryTraitsFetcher singleInst = null; private static final String UWN_DB = "resources" + File.separator + "uwnDatabase"; private static final String PREDICATE_TYPE_SEPERATOR = "rel:"; private static final int PREDICATE_TYPE_SEPERATOR_LENGTH = PREDICATE_TYPE_SEPERATOR.length(); private UWN uwn = null; private StopWords stopWords = null; private TermNormalizer termNormalizer = null; private VocabularyTraitsRetrievalPolicy vocabularyTraitsRetrievalPolicy; private HashMap<String, SortedIterablePriorityQuery<Statement>> vocabolaryTraitsCollectionMap; private SortedIterablePriorityQuery<Statement> synonymsCategory = null; private SortedIterablePriorityQuery<Statement> meronymsCategory = null; private SortedIterablePriorityQuery<Statement> hyponymnsCategory = null; private SortedIterablePriorityQuery<Statement> hyperonymsCategory = null; private SortedIterablePriorityQuery<Statement> holonymsCategory = null; private HashSet<String> totalParsedQueryTerms = null; private HashSet<String> totalLexicalParsedQueryTerms = null; private VocabolaryTraitsFetcher( StopWords _stopWords, VocabularyTraitsRetrievalPolicy _vocabularyTraitsRetrievalPolicy ) throws Exception { vocabularyTraitsRetrievalPolicy = _vocabularyTraitsRetrievalPolicy; stopWords = _stopWords; termNormalizer = TermNormalizer.getInstance(); File dbFilePath = new File(UWN_DB); uwn = new UWN(dbFilePath); vocabolaryTraitsCollectionMap = new HashMap(); Comparator<Statement> comparator = new Comparator<Statement>() { @Override public int compare(Statement a, Statement b) { if (a.getWeight() == b.getWeight()) { return 0; } else if (a.getWeight() > b.getWeight()) { return 1; } else { return -1; } } }; totalParsedQueryTerms = new HashSet(); totalLexicalParsedQueryTerms = new HashSet(); synonymsCategory = new SortedIterablePriorityQuery(10, comparator); meronymsCategory = new SortedIterablePriorityQuery(10, comparator); hyponymnsCategory = new SortedIterablePriorityQuery(10, comparator); hyperonymsCategory = new SortedIterablePriorityQuery(10, comparator); holonymsCategory = new SortedIterablePriorityQuery(10, comparator); } public static void singletonCreate( StopWords _stopWords, VocabularyTraitsRetrievalPolicy _vocabularyTraitsRetrievalPolicy ) throws Exception { if (singleInst == null) { singleInst = new VocabolaryTraitsFetcher(_stopWords, _vocabularyTraitsRetrievalPolicy); } } public static VocabolaryTraitsFetcher getSingleInst() { return singleInst; } public VocabolaryTraits getNewVocabolaryTraits( ParsedQueryTerm parsedQueryTerm ) throws IOException { totalParsedQueryTerms.clear(); totalLexicalParsedQueryTerms.clear(); synonymsCategory.clear(); meronymsCategory.clear(); hyponymnsCategory.clear(); hyperonymsCategory.clear(); holonymsCategory.clear(); vocabolaryTraitsCollectionMap.put("means", synonymsCategory); vocabolaryTraitsCollectionMap.put("closely_related", synonymsCategory); vocabolaryTraitsCollectionMap.put("similar", synonymsCategory); vocabolaryTraitsCollectionMap.put("subclass", hyponymnsCategory); vocabolaryTraitsCollectionMap.put("has_subclass", hyperonymsCategory); vocabolaryTraitsCollectionMap.put("part_of", meronymsCategory); vocabolaryTraitsCollectionMap.put("has_part", holonymsCategory); String term = parsedQueryTerm.getWord(); String termLang = TermNormalizer.getLanguage(term); HashSet<String> languageCodes = TermNormalizer.getLanguageCodes(termLang); if (termLang.isEmpty()) { return null; } else { Entity entity = Entity.createTerm(term, termLang); Iterator<Statement> it = uwn.get(entity); while (it.hasNext()) { Statement stmt = it.next(); String predicateType = stmt.getPredicate().getId(); assert (predicateType.startsWith(PREDICATE_TYPE_SEPERATOR)); String type = predicateType.substring(PREDICATE_TYPE_SEPERATOR_LENGTH); SortedIterablePriorityQuery<Statement> vocabularyTraitCollection = vocabolaryTraitsCollectionMap.get(type); if (vocabularyTraitCollection != null) { vocabularyTraitCollection.add(stmt); } } VocabolaryTraits vocabolaryTraits = new VocabolaryTraits(); extractTermsFromCategory( synonymsCategory, vocabolaryTraits.synonyms, vocabolaryTraits.all, languageCodes, vocabularyTraitsRetrievalPolicy.getTotalsynonymsToBeFetched(), vocabularyTraitsRetrievalPolicy.getsynonymsCategoryWeight() ); extractTermsFromCategory( hyponymnsCategory, vocabolaryTraits.hyponymns, vocabolaryTraits.all, languageCodes, vocabularyTraitsRetrievalPolicy.getTotalhyponymsToBeFetched(), vocabularyTraitsRetrievalPolicy.gethyponymsCategoryWeight() ); extractTermsFromCategory( hyperonymsCategory, vocabolaryTraits.hyperonyms, vocabolaryTraits.all, languageCodes, vocabularyTraitsRetrievalPolicy.getTotalhyperonymsToBeFetched(), vocabularyTraitsRetrievalPolicy.gethyperonymsCategoryWeight() ); extractTermsFromCategory( meronymsCategory, vocabolaryTraits.meronyms, vocabolaryTraits.all, languageCodes, vocabularyTraitsRetrievalPolicy.getTotalmeronymsToBeFetched(), vocabularyTraitsRetrievalPolicy.getmeronymsCategoryWeight() ); extractTermsFromCategory( holonymsCategory, vocabolaryTraits.holonyms, vocabolaryTraits.all, languageCodes, vocabularyTraitsRetrievalPolicy.getTotalholonyToBeFetched(), vocabularyTraitsRetrievalPolicy.getholonyCategoryWeight() ); if (!totalLexicalParsedQueryTerms.contains(parsedQueryTerm.getParsedWord())) { vocabolaryTraits.all.add(parsedQueryTerm); } return vocabolaryTraits; } } private void extractTermsFromCategory( SortedIterablePriorityQuery<Statement> category, SortedIterablePriorityQuery<ParsedQueryTerm> terms, SortedIterablePriorityQuery<ParsedQueryTerm> all, final HashSet<String> supportedLangs, final int fetchedMaxSize, final double categoryWeight ) throws IOException { if (fetchedMaxSize != 0) { int fechedSize = 0; while (!category.isEmpty()) { Statement stmt = (Statement) category.poll(); Iterator<Statement> catTerms = uwn.getTermEntities(stmt.getObject()); while (catTerms.hasNext()) { Statement catTerm = catTerms.next(); String term = catTerm.getObject().getTermStr(); if (supportedLangs.contains(catTerm.getObject().getTermLanguage()) && !totalParsedQueryTerms.contains(term)) { totalParsedQueryTerms.add(term); String[] lexTerm = termNormalizer.getLexicalAnalyzedTerm(term, stopWords); if (lexTerm != null && !totalLexicalParsedQueryTerms.contains(lexTerm[0])) { totalLexicalParsedQueryTerms.add(lexTerm[0]); ParsedQueryTerm parsedQueryTerm = new ParsedQueryTerm(0, lexTerm[0], term, catTerm.getWeight()*categoryWeight); all.add(parsedQueryTerm); terms.add(parsedQueryTerm); if (++fechedSize == fetchedMaxSize) { return; } } } } } } } public class VocabolaryTraits { protected final SortedIterablePriorityQuery<ParsedQueryTerm> synonyms; private final SortedIterablePriorityQuery<ParsedQueryTerm> meronyms; private final SortedIterablePriorityQuery<ParsedQueryTerm> hyponymns; private final SortedIterablePriorityQuery<ParsedQueryTerm> hyperonyms; private final SortedIterablePriorityQuery<ParsedQueryTerm> holonyms; private final SortedIterablePriorityQuery<ParsedQueryTerm> all; public VocabolaryTraits() { this.synonyms = new SortedIterablePriorityQuery(10, new ParsedQueryTermComparator()); this.meronyms = new SortedIterablePriorityQuery(10, new ParsedQueryTermComparator()); this.hyponymns = new SortedIterablePriorityQuery(10, new ParsedQueryTermComparator()); this.hyperonyms = new SortedIterablePriorityQuery(10, new ParsedQueryTermComparator()); this.holonyms = new SortedIterablePriorityQuery(10, new ParsedQueryTermComparator()); this.all = new SortedIterablePriorityQuery(10, new ParsedQueryTermComparator()); } private class ParsedQueryTermComparator implements Comparator<ParsedQueryTerm> { @Override public int compare(ParsedQueryTerm a, ParsedQueryTerm b) { if (a.getWeight() == b.getWeight()) { return 0; } else if (a.getWeight() > b.getWeight()) { return 1; } else { return -1; } } } public SortedIterablePriorityQuery<ParsedQueryTerm> getSynonyms() { return synonyms; } public SortedIterablePriorityQuery<ParsedQueryTerm> getMeronyms() { return meronyms; } public SortedIterablePriorityQuery<ParsedQueryTerm> getHyponymns() { return hyponymns; } public SortedIterablePriorityQuery<ParsedQueryTerm> getHyperonyms() { return hyperonyms; } public SortedIterablePriorityQuery<ParsedQueryTerm> getHolonyms() { return holonyms; } public SortedIterablePriorityQuery<ParsedQueryTerm> getAll() { return all; } } // public static void main(String[] args) throws Exception { // VocabolaryTraitsFetcher.singletonCreate(new StopWords(), new NormalVocabularyTraitsRetrieval()); // VocabolaryTraitsFetcher singleInst1 = VocabolaryTraitsFetcher.getSingleInst(); // VocabolaryTraits newVocabolaryTraits = singleInst1.getNewVocabolaryTraits( // new ParsedQueryTerm(0, "αγάπη", "αγάπη", 1.0) // ); // } }
aiked/Pony
PonyIndexer/src/PonySearcher/optimization/VocabolaryTraitsFetcher.java
2,505
// new ParsedQueryTerm(0, "αγάπη", "αγάπη", 1.0)
line_comment
el
package PonySearcher.optimization; import Common.SortedIterablePriorityQuery; import Common.TermNormalizer; import Common.StopWords; import PonySearcher.models.ParsedQueryTerm; import java.io.File; import java.io.IOException; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import org.lexvo.uwn.Entity; import org.lexvo.uwn.Statement; import org.lexvo.uwn.UWN; /** * * @author Apostolidis */ public class VocabolaryTraitsFetcher { private static VocabolaryTraitsFetcher singleInst = null; private static final String UWN_DB = "resources" + File.separator + "uwnDatabase"; private static final String PREDICATE_TYPE_SEPERATOR = "rel:"; private static final int PREDICATE_TYPE_SEPERATOR_LENGTH = PREDICATE_TYPE_SEPERATOR.length(); private UWN uwn = null; private StopWords stopWords = null; private TermNormalizer termNormalizer = null; private VocabularyTraitsRetrievalPolicy vocabularyTraitsRetrievalPolicy; private HashMap<String, SortedIterablePriorityQuery<Statement>> vocabolaryTraitsCollectionMap; private SortedIterablePriorityQuery<Statement> synonymsCategory = null; private SortedIterablePriorityQuery<Statement> meronymsCategory = null; private SortedIterablePriorityQuery<Statement> hyponymnsCategory = null; private SortedIterablePriorityQuery<Statement> hyperonymsCategory = null; private SortedIterablePriorityQuery<Statement> holonymsCategory = null; private HashSet<String> totalParsedQueryTerms = null; private HashSet<String> totalLexicalParsedQueryTerms = null; private VocabolaryTraitsFetcher( StopWords _stopWords, VocabularyTraitsRetrievalPolicy _vocabularyTraitsRetrievalPolicy ) throws Exception { vocabularyTraitsRetrievalPolicy = _vocabularyTraitsRetrievalPolicy; stopWords = _stopWords; termNormalizer = TermNormalizer.getInstance(); File dbFilePath = new File(UWN_DB); uwn = new UWN(dbFilePath); vocabolaryTraitsCollectionMap = new HashMap(); Comparator<Statement> comparator = new Comparator<Statement>() { @Override public int compare(Statement a, Statement b) { if (a.getWeight() == b.getWeight()) { return 0; } else if (a.getWeight() > b.getWeight()) { return 1; } else { return -1; } } }; totalParsedQueryTerms = new HashSet(); totalLexicalParsedQueryTerms = new HashSet(); synonymsCategory = new SortedIterablePriorityQuery(10, comparator); meronymsCategory = new SortedIterablePriorityQuery(10, comparator); hyponymnsCategory = new SortedIterablePriorityQuery(10, comparator); hyperonymsCategory = new SortedIterablePriorityQuery(10, comparator); holonymsCategory = new SortedIterablePriorityQuery(10, comparator); } public static void singletonCreate( StopWords _stopWords, VocabularyTraitsRetrievalPolicy _vocabularyTraitsRetrievalPolicy ) throws Exception { if (singleInst == null) { singleInst = new VocabolaryTraitsFetcher(_stopWords, _vocabularyTraitsRetrievalPolicy); } } public static VocabolaryTraitsFetcher getSingleInst() { return singleInst; } public VocabolaryTraits getNewVocabolaryTraits( ParsedQueryTerm parsedQueryTerm ) throws IOException { totalParsedQueryTerms.clear(); totalLexicalParsedQueryTerms.clear(); synonymsCategory.clear(); meronymsCategory.clear(); hyponymnsCategory.clear(); hyperonymsCategory.clear(); holonymsCategory.clear(); vocabolaryTraitsCollectionMap.put("means", synonymsCategory); vocabolaryTraitsCollectionMap.put("closely_related", synonymsCategory); vocabolaryTraitsCollectionMap.put("similar", synonymsCategory); vocabolaryTraitsCollectionMap.put("subclass", hyponymnsCategory); vocabolaryTraitsCollectionMap.put("has_subclass", hyperonymsCategory); vocabolaryTraitsCollectionMap.put("part_of", meronymsCategory); vocabolaryTraitsCollectionMap.put("has_part", holonymsCategory); String term = parsedQueryTerm.getWord(); String termLang = TermNormalizer.getLanguage(term); HashSet<String> languageCodes = TermNormalizer.getLanguageCodes(termLang); if (termLang.isEmpty()) { return null; } else { Entity entity = Entity.createTerm(term, termLang); Iterator<Statement> it = uwn.get(entity); while (it.hasNext()) { Statement stmt = it.next(); String predicateType = stmt.getPredicate().getId(); assert (predicateType.startsWith(PREDICATE_TYPE_SEPERATOR)); String type = predicateType.substring(PREDICATE_TYPE_SEPERATOR_LENGTH); SortedIterablePriorityQuery<Statement> vocabularyTraitCollection = vocabolaryTraitsCollectionMap.get(type); if (vocabularyTraitCollection != null) { vocabularyTraitCollection.add(stmt); } } VocabolaryTraits vocabolaryTraits = new VocabolaryTraits(); extractTermsFromCategory( synonymsCategory, vocabolaryTraits.synonyms, vocabolaryTraits.all, languageCodes, vocabularyTraitsRetrievalPolicy.getTotalsynonymsToBeFetched(), vocabularyTraitsRetrievalPolicy.getsynonymsCategoryWeight() ); extractTermsFromCategory( hyponymnsCategory, vocabolaryTraits.hyponymns, vocabolaryTraits.all, languageCodes, vocabularyTraitsRetrievalPolicy.getTotalhyponymsToBeFetched(), vocabularyTraitsRetrievalPolicy.gethyponymsCategoryWeight() ); extractTermsFromCategory( hyperonymsCategory, vocabolaryTraits.hyperonyms, vocabolaryTraits.all, languageCodes, vocabularyTraitsRetrievalPolicy.getTotalhyperonymsToBeFetched(), vocabularyTraitsRetrievalPolicy.gethyperonymsCategoryWeight() ); extractTermsFromCategory( meronymsCategory, vocabolaryTraits.meronyms, vocabolaryTraits.all, languageCodes, vocabularyTraitsRetrievalPolicy.getTotalmeronymsToBeFetched(), vocabularyTraitsRetrievalPolicy.getmeronymsCategoryWeight() ); extractTermsFromCategory( holonymsCategory, vocabolaryTraits.holonyms, vocabolaryTraits.all, languageCodes, vocabularyTraitsRetrievalPolicy.getTotalholonyToBeFetched(), vocabularyTraitsRetrievalPolicy.getholonyCategoryWeight() ); if (!totalLexicalParsedQueryTerms.contains(parsedQueryTerm.getParsedWord())) { vocabolaryTraits.all.add(parsedQueryTerm); } return vocabolaryTraits; } } private void extractTermsFromCategory( SortedIterablePriorityQuery<Statement> category, SortedIterablePriorityQuery<ParsedQueryTerm> terms, SortedIterablePriorityQuery<ParsedQueryTerm> all, final HashSet<String> supportedLangs, final int fetchedMaxSize, final double categoryWeight ) throws IOException { if (fetchedMaxSize != 0) { int fechedSize = 0; while (!category.isEmpty()) { Statement stmt = (Statement) category.poll(); Iterator<Statement> catTerms = uwn.getTermEntities(stmt.getObject()); while (catTerms.hasNext()) { Statement catTerm = catTerms.next(); String term = catTerm.getObject().getTermStr(); if (supportedLangs.contains(catTerm.getObject().getTermLanguage()) && !totalParsedQueryTerms.contains(term)) { totalParsedQueryTerms.add(term); String[] lexTerm = termNormalizer.getLexicalAnalyzedTerm(term, stopWords); if (lexTerm != null && !totalLexicalParsedQueryTerms.contains(lexTerm[0])) { totalLexicalParsedQueryTerms.add(lexTerm[0]); ParsedQueryTerm parsedQueryTerm = new ParsedQueryTerm(0, lexTerm[0], term, catTerm.getWeight()*categoryWeight); all.add(parsedQueryTerm); terms.add(parsedQueryTerm); if (++fechedSize == fetchedMaxSize) { return; } } } } } } } public class VocabolaryTraits { protected final SortedIterablePriorityQuery<ParsedQueryTerm> synonyms; private final SortedIterablePriorityQuery<ParsedQueryTerm> meronyms; private final SortedIterablePriorityQuery<ParsedQueryTerm> hyponymns; private final SortedIterablePriorityQuery<ParsedQueryTerm> hyperonyms; private final SortedIterablePriorityQuery<ParsedQueryTerm> holonyms; private final SortedIterablePriorityQuery<ParsedQueryTerm> all; public VocabolaryTraits() { this.synonyms = new SortedIterablePriorityQuery(10, new ParsedQueryTermComparator()); this.meronyms = new SortedIterablePriorityQuery(10, new ParsedQueryTermComparator()); this.hyponymns = new SortedIterablePriorityQuery(10, new ParsedQueryTermComparator()); this.hyperonyms = new SortedIterablePriorityQuery(10, new ParsedQueryTermComparator()); this.holonyms = new SortedIterablePriorityQuery(10, new ParsedQueryTermComparator()); this.all = new SortedIterablePriorityQuery(10, new ParsedQueryTermComparator()); } private class ParsedQueryTermComparator implements Comparator<ParsedQueryTerm> { @Override public int compare(ParsedQueryTerm a, ParsedQueryTerm b) { if (a.getWeight() == b.getWeight()) { return 0; } else if (a.getWeight() > b.getWeight()) { return 1; } else { return -1; } } } public SortedIterablePriorityQuery<ParsedQueryTerm> getSynonyms() { return synonyms; } public SortedIterablePriorityQuery<ParsedQueryTerm> getMeronyms() { return meronyms; } public SortedIterablePriorityQuery<ParsedQueryTerm> getHyponymns() { return hyponymns; } public SortedIterablePriorityQuery<ParsedQueryTerm> getHyperonyms() { return hyperonyms; } public SortedIterablePriorityQuery<ParsedQueryTerm> getHolonyms() { return holonyms; } public SortedIterablePriorityQuery<ParsedQueryTerm> getAll() { return all; } } // public static void main(String[] args) throws Exception { // VocabolaryTraitsFetcher.singletonCreate(new StopWords(), new NormalVocabularyTraitsRetrieval()); // VocabolaryTraitsFetcher singleInst1 = VocabolaryTraitsFetcher.getSingleInst(); // VocabolaryTraits newVocabolaryTraits = singleInst1.getNewVocabolaryTraits( // new ParsedQueryTerm(0,<SUF> // ); // } }
59_11
/** * Alexandros Korkos * 3870 * [email protected] */ import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Scanner; public class DPnet { public static class MyFile{ private final String filename; private Integer N, M; private Integer[][] SumVMCost, VMCost; // Κόστος Εκτέλεσης, Κόστος Επικοινωνίας /** * Δέχεται το όνομα του αρχείου, το ανοίγει και διαβάζει τα δεδομένα οπου τα αποθηκεύει σε δυο πίνακες * των δυο διαστάσεων, * @param filename το όνομα του αρχείου. */ public MyFile(String filename){ this.filename = filename; read(); } private void read(){ try{ File file = new File(filename); Scanner reader = new Scanner(file); N = Integer.parseInt(reader.nextLine()); M = Integer.parseInt(reader.nextLine()); // Πίνακας για το συνολικό κόστος να τρέξει μία διεργασία // σε ένα τύπο εικονικής μηχανής. SumVMCost = new Integer[N][M]; reader.nextLine(); // διαβάζει την κενή γραμμή // διαβάζει τη γραμμή μέσα απο το αρχείο και // χωρίζει τους αριθμούς συμφωνά με το κενό που έχουνε ανάμεσα τους. for (int i = 0; i < N; i++){ String[] line = reader.nextLine().split(" "); for (int j = 0; j < M; j++) SumVMCost[i][j] = Integer.parseInt(line[j]); } reader.nextLine(); // διαβάζει την κενή γραμμή // Πίνακας για το κόστος να στείλει το ένα μηχάνημα δεδομένα στο άλλο. VMCost = new Integer[M][M]; // διαβάζει τη γραμμή μέσα απο το αρχείο και // χωρίζει τους αριθμούς συμφωνά με το κενό που έχουνε ανάμεσα τους. for (int i = 0; i < M; i++){ String[] line = reader.nextLine().split(" "); for (int j = 0; j < M; j++) VMCost[i][j] = Integer.parseInt(line[j]); } reader.close(); } catch (IOException e){ System.out.println(e.getMessage()); } } public Integer[][] getSumVMCost() { return SumVMCost; } public Integer[][] getVMCost() { return VMCost; } public Integer getN() { return N; } public Integer getM() { return M; } } /** * Επιστρέφει μια γραμμή απο έναν πίνακα δυο διαστάσεων, * @param A πίνακας των δυο διαστάσεων, * @param M του μήκος της κάθε σειράς του πίνακα, * @param pos η γραμμή που πίνακα που πρέπει να επιστραφεί, * @return η γραμμή του πίνακα μήκους Μ. */ private static Integer[] getLine(Integer[][] A, Integer M, Integer pos){ Integer[] arrayLine = new Integer[M]; for (int j = 0; j < M; j++) arrayLine[j] = A[pos][j]; return arrayLine; } /** * Επιστρέφει μια στήλη απο έναν πίνακα δυο διαστάσεων, * @param A πίνακας των δυο διαστάσεων, * @param M του μήκος της κάθε σειράς του πίνακα, * @param pos η στήλη που πίνακα που πρέπει να επιστραφεί, * @return η στήλη του πίνακα μήκους Μ. */ private static Integer[] getRow(Integer[][] A, Integer M, Integer pos){ Integer[] arrayLine = new Integer[M]; for (int i = 0; i < M; i++) arrayLine[i] = A[i][pos]; return arrayLine; } /** * Βρίσκει και επιστρέφει την ελάχιστη τιμή, αθροίσματος δυο στοιχειών απο δυο πίνακες * @param A πρώτος πίνακας, * @param B δεύτερος πίνακας, * @param M μήκος και των δυο πινάκων, * @return ελάχιστη τιμή. */ private static Integer getMin(Integer[]A, Integer[]B, Integer M){ int min = A[0] + B[0]; for (int i = 1; i < M; i++){ if ((A[i] + B[i]) < min) min = A[i] + B[i]; } return min; } public static void main(String[] args){ MyFile file = new MyFile(args[0]); Integer N = file.getN(); Integer M = file.getM(); Integer[][] VMCost = file.getVMCost(); Integer[][] SumVMCost = file.getSumVMCost(); Integer[][] Costs = new Integer[N][M]; for (int j = 0; j < M; j++) Costs[0][j] = SumVMCost[0][j]; // υπολογίζει την τιμή του στοιχειού στη θέση (i, j) του πίνακα, // βρίσκοντας το ελάχιστο μονοπάτι απο την i-1 γραμμή του πίνακα Costs. for (int i = 1; i < N; i++){ for (int j = 0; j < M; j++){ Integer[] run = getLine(Costs, M, i - 1); Integer[] comm = getRow(VMCost, M, j); Costs[i][j] = getMin(run, comm, M) + SumVMCost[i][j]; } } for (int i = 0; i < N; i++){ Integer[] line = getLine(Costs, M, i); System.out.println(Arrays.deepToString(line).replace("[","").replace(", "," ").replace("]","")); } } }
akorkos/Assignments-in-Algorithms
DPnet/src/DPnet.java
2,116
// χωρίζει τους αριθμούς συμφωνά με το κενό που έχουνε ανάμεσα τους.
line_comment
el
/** * Alexandros Korkos * 3870 * [email protected] */ import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Scanner; public class DPnet { public static class MyFile{ private final String filename; private Integer N, M; private Integer[][] SumVMCost, VMCost; // Κόστος Εκτέλεσης, Κόστος Επικοινωνίας /** * Δέχεται το όνομα του αρχείου, το ανοίγει και διαβάζει τα δεδομένα οπου τα αποθηκεύει σε δυο πίνακες * των δυο διαστάσεων, * @param filename το όνομα του αρχείου. */ public MyFile(String filename){ this.filename = filename; read(); } private void read(){ try{ File file = new File(filename); Scanner reader = new Scanner(file); N = Integer.parseInt(reader.nextLine()); M = Integer.parseInt(reader.nextLine()); // Πίνακας για το συνολικό κόστος να τρέξει μία διεργασία // σε ένα τύπο εικονικής μηχανής. SumVMCost = new Integer[N][M]; reader.nextLine(); // διαβάζει την κενή γραμμή // διαβάζει τη γραμμή μέσα απο το αρχείο και // χωρίζει τους αριθμούς συμφωνά με το κενό που έχουνε ανάμεσα τους. for (int i = 0; i < N; i++){ String[] line = reader.nextLine().split(" "); for (int j = 0; j < M; j++) SumVMCost[i][j] = Integer.parseInt(line[j]); } reader.nextLine(); // διαβάζει την κενή γραμμή // Πίνακας για το κόστος να στείλει το ένα μηχάνημα δεδομένα στο άλλο. VMCost = new Integer[M][M]; // διαβάζει τη γραμμή μέσα απο το αρχείο και // χωρίζει τους<SUF> for (int i = 0; i < M; i++){ String[] line = reader.nextLine().split(" "); for (int j = 0; j < M; j++) VMCost[i][j] = Integer.parseInt(line[j]); } reader.close(); } catch (IOException e){ System.out.println(e.getMessage()); } } public Integer[][] getSumVMCost() { return SumVMCost; } public Integer[][] getVMCost() { return VMCost; } public Integer getN() { return N; } public Integer getM() { return M; } } /** * Επιστρέφει μια γραμμή απο έναν πίνακα δυο διαστάσεων, * @param A πίνακας των δυο διαστάσεων, * @param M του μήκος της κάθε σειράς του πίνακα, * @param pos η γραμμή που πίνακα που πρέπει να επιστραφεί, * @return η γραμμή του πίνακα μήκους Μ. */ private static Integer[] getLine(Integer[][] A, Integer M, Integer pos){ Integer[] arrayLine = new Integer[M]; for (int j = 0; j < M; j++) arrayLine[j] = A[pos][j]; return arrayLine; } /** * Επιστρέφει μια στήλη απο έναν πίνακα δυο διαστάσεων, * @param A πίνακας των δυο διαστάσεων, * @param M του μήκος της κάθε σειράς του πίνακα, * @param pos η στήλη που πίνακα που πρέπει να επιστραφεί, * @return η στήλη του πίνακα μήκους Μ. */ private static Integer[] getRow(Integer[][] A, Integer M, Integer pos){ Integer[] arrayLine = new Integer[M]; for (int i = 0; i < M; i++) arrayLine[i] = A[i][pos]; return arrayLine; } /** * Βρίσκει και επιστρέφει την ελάχιστη τιμή, αθροίσματος δυο στοιχειών απο δυο πίνακες * @param A πρώτος πίνακας, * @param B δεύτερος πίνακας, * @param M μήκος και των δυο πινάκων, * @return ελάχιστη τιμή. */ private static Integer getMin(Integer[]A, Integer[]B, Integer M){ int min = A[0] + B[0]; for (int i = 1; i < M; i++){ if ((A[i] + B[i]) < min) min = A[i] + B[i]; } return min; } public static void main(String[] args){ MyFile file = new MyFile(args[0]); Integer N = file.getN(); Integer M = file.getM(); Integer[][] VMCost = file.getVMCost(); Integer[][] SumVMCost = file.getSumVMCost(); Integer[][] Costs = new Integer[N][M]; for (int j = 0; j < M; j++) Costs[0][j] = SumVMCost[0][j]; // υπολογίζει την τιμή του στοιχειού στη θέση (i, j) του πίνακα, // βρίσκοντας το ελάχιστο μονοπάτι απο την i-1 γραμμή του πίνακα Costs. for (int i = 1; i < N; i++){ for (int j = 0; j < M; j++){ Integer[] run = getLine(Costs, M, i - 1); Integer[] comm = getRow(VMCost, M, j); Costs[i][j] = getMin(run, comm, M) + SumVMCost[i][j]; } } for (int i = 0; i < N; i++){ Integer[] line = getLine(Costs, M, i); System.out.println(Arrays.deepToString(line).replace("[","").replace(", "," ").replace("]","")); } } }
2153_9
/* * 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 projectt; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.text.BadLocationException; /** * * @author Marinos */ public class Supplies extends javax.swing.JFrame { private int currentQid; /** * Creates new form Supplies */ public Supplies() { initComponents(); getSupplies(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jTextField3 = new javax.swing.JTextField(); jTextField5 = new javax.swing.JTextField(); jTextField6 = new javax.swing.JTextField(); jTextField7 = new javax.swing.JTextField(); jTextField8 = new javax.swing.JTextField(); jTextField9 = new javax.swing.JTextField(); jTextField10 = new javax.swing.JTextField(); jTextField4 = new javax.swing.JTextField(); jTextField11 = new javax.swing.JTextField(); jTextField12 = new javax.swing.JTextField(); jTextField13 = new javax.swing.JTextField(); jTextField14 = new javax.swing.JTextField(); jTextField15 = new javax.swing.JTextField(); jTextField16 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jTextField17 = new javax.swing.JTextField(); jTextField18 = new javax.swing.JTextField(); jTextField19 = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(150, 235, 240)); jPanel1.setPreferredSize(new java.awt.Dimension(1260, 660)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/A4AD5659B5D44610AB530DF0BAB8279D.jpeg"))); // NOI18N jTextField1.setBackground(new java.awt.Color(150, 235, 240)); jTextField1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jTextField1.setText("ΤΜΗΜΑ ΠΡΟΜΗΘΕΙΩΝ"); jTextField1.setBorder(null); jTextField1.setFocusable(false); jTextField2.setBackground(new java.awt.Color(150, 235, 240)); jTextField2.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N jTextField2.setText("ΓΑΝΤΙΑ"); jTextField2.setBorder(null); jTextField2.setFocusable(false); jTextField3.setBackground(new java.awt.Color(150, 235, 240)); jTextField3.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N jTextField3.setText("ΜΑΣΚΕΣ"); jTextField3.setBorder(null); jTextField3.setFocusable(false); jTextField3.setPreferredSize(new java.awt.Dimension(75, 25)); jTextField5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextField5.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField6.setBackground(new java.awt.Color(150, 235, 240)); jTextField6.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N jTextField6.setText("ΓΑΖΕΣ"); jTextField6.setBorder(null); jTextField6.setFocusable(false); jTextField7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextField7.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextField8.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField9.setBackground(new java.awt.Color(150, 235, 240)); jTextField9.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N jTextField9.setText("ΧΕΙΡΟΥΡΓΙΚΕΣ ΦΟΡΜΕΣ"); jTextField9.setBorder(null); jTextField9.setFocusable(false); jTextField10.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextField10.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField4.setBackground(new java.awt.Color(150, 235, 240)); jTextField4.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jTextField4.setText("ΔΙΑΘΕΣΙΜΟΤΗΤΑ"); jTextField4.setBorder(null); jTextField4.setFocusable(false); jTextField11.setBackground(new java.awt.Color(150, 235, 240)); jTextField11.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jTextField11.setText("ΕΙΔΟΣ"); jTextField11.setBorder(null); jTextField11.setFocusable(false); jTextField12.setBackground(new java.awt.Color(150, 235, 240)); jTextField12.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jTextField12.setText("ΠΟΣΟΤΗΤΑ"); jTextField12.setBorder(null); jTextField12.setFocusable(false); jTextField13.setBackground(new java.awt.Color(150, 235, 240)); jTextField13.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jTextField13.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField13.setBorder(null); jTextField13.setFocusable(false); jTextField14.setBackground(new java.awt.Color(150, 235, 240)); jTextField14.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jTextField14.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField14.setBorder(null); jTextField14.setFocusable(false); jTextField15.setBackground(new java.awt.Color(150, 235, 240)); jTextField15.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jTextField15.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField15.setBorder(null); jTextField15.setFocusable(false); jTextField16.setBackground(new java.awt.Color(150, 235, 240)); jTextField16.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jTextField16.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField16.setToolTipText(""); jTextField16.setBorder(null); jTextField16.setFocusable(false); jButton1.setBackground(new java.awt.Color(0, 0, 0)); jButton1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jButton1.setForeground(new java.awt.Color(255, 255, 255)); jButton1.setText("Αποθήκευση"); jButton1.setBorder(null); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jTextField17.setBackground(new java.awt.Color(150, 235, 240)); jTextField17.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N jTextField17.setText("ΝΑΡΘΗΚΕΣ"); jTextField17.setBorder(null); jTextField17.setFocusable(false); jTextField18.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextField18.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField19.setBackground(new java.awt.Color(150, 235, 240)); jTextField19.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jTextField19.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField19.setBorder(null); jTextField19.setFocusable(false); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 0, 0)); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 0, 0)); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap(257, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField11, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(81, 81, 81) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField18, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(120, 120, 120) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addGap(152, 152, 152) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextField16, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField14, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField13, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField15, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField19, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)))))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(80, 80, 80) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 470, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(248, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField17, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE)))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(38, 38, 38) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(97, 97, 97) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(34, 34, 34) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField16, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField13, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField14, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField15, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField17, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField18, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField19, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(61, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 1267, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 737, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void displayFail1(){ JOptionPane.showMessageDialog(this,("Δεν επαρκούν οι προμήθειες.")); } private void displayFail2(){ JOptionPane.showMessageDialog(this,("Συπληρώστε τα κενά πεδία με μηδέν (0)!")); //εμφάνιση μηνύματος } private static void getSupplies() { //Επιλογή από την βάση των προμηθειών try{ java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/project", "root", ""); //Σύνδεση με βάση String query = "SELECT stock FROM supplies WHERE supply='gantia'"; // εντολή select PreparedStatement pst = con.prepareStatement(query); // ResultSet rs = pst.executeQuery(); //εκτελεση του query και αποθήκευση στο rs if(rs.next()) { jTextField16.setText(""+rs.getInt("stock")); //εμφάνιση αποτελέσματος σε int στο textfield } String query1 = "SELECT stock FROM supplies WHERE supply='maskes'"; PreparedStatement pst1 = con.prepareStatement(query1); ResultSet rs1 = pst1.executeQuery(); if(rs1.next()) { jTextField13.setText(""+rs1.getInt("stock")); } String query2 = "SELECT stock FROM supplies WHERE supply='gazes'"; PreparedStatement pst2 = con.prepareStatement(query2); ResultSet rs2 = pst2.executeQuery(); if(rs2.next()) { jTextField14.setText(""+rs2.getInt("stock")); } String query3 = "SELECT stock FROM supplies WHERE supply='formes_xeirourgeiou'"; PreparedStatement pst3 = con.prepareStatement(query3); ResultSet rs3 = pst3.executeQuery(); if(rs3.next()) { jTextField15.setText(""+rs3.getInt("stock")); } String query4 = "SELECT stock FROM supplies WHERE supply='narthikes'"; PreparedStatement pst4 = con.prepareStatement(query4); ResultSet rs4 = pst4.executeQuery(); if(rs4.next()) { jTextField19.setText(""+rs4.getInt("stock")); } } catch (SQLException ex) { Logger.getLogger(Supplies.class.getName()).log(Level.SEVERE, null, ex); } } private void saveSupplies(){ //έλεγχος για κενά πεδία και εμφάνιση μηνύματος //check_Stock() if(jTextField5.getText().trim().isEmpty() || jTextField8.getText().trim().isEmpty() || jTextField7.getText().trim().isEmpty() || jTextField10.getText().trim().isEmpty() ||jTextField18.getText().trim().isEmpty()) { displayFail2(); } else { //μετατροπη του περιεχομένου textfield σε int και εκτέλεση πράξεων για την αφαίρεση int g = Integer.parseInt(jTextField5.getText().trim()); int g1 = Integer.parseInt(jTextField16.getText().trim()); int g2 = g1-g; int m =Integer.parseInt(jTextField8.getText().trim()); int m1 =Integer.parseInt(jTextField13.getText().trim()); int m2 = m1-m; int ga = Integer.parseInt(jTextField7.getText().trim()); int ga1 = Integer.parseInt(jTextField14.getText().trim()); int ga2 = ga1-ga; int fx = Integer.parseInt(jTextField10.getText().trim()); int fx1 = Integer.parseInt(jTextField15.getText().trim()); int fx2 = fx1-fx; int n = Integer.parseInt(jTextField18.getText().trim()); int n1 = Integer.parseInt(jTextField19.getText().trim()); int n2 = n1-n; //έλεγχος για επάρκεια προμηθειών και εμφάνιση μηνυμάτων //check_Stock() if(g2<0 || m2<0 || ga2<0 || fx2<0 || n2<0) { displayFail1(); } else{ try { //ενημέρωση του table στην βάση παίρνωντας ως δεδομένα την αφαίρεση των προμηθειών Class.forName("com.mysql.cj.jdbc.Driver"); java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/project", "root", ""); String query = "UPDATE supplies SET stock='"+g2+"' WHERE supply='gantia'"; PreparedStatement pst = con.prepareStatement(query); int rs = pst.executeUpdate(); String query1 = "UPDATE supplies SET stock='"+m2+"' WHERE supply='maskes'"; PreparedStatement pst1 = con.prepareStatement(query1); int rs1 = pst1.executeUpdate(); String query2 = "UPDATE supplies SET stock='"+ga2+"' WHERE supply='gazes'"; PreparedStatement pst2 = con.prepareStatement(query2); int rs2 = pst2.executeUpdate(); String query3 = "UPDATE supplies SET stock='"+fx2+"' WHERE supply='formes_xeirourgeiou'"; PreparedStatement pst3 = con.prepareStatement(query3); int rs3 = pst3.executeUpdate(); String query4 = "UPDATE supplies SET stock='"+n2+"' WHERE supply='narthikes'"; PreparedStatement pst4 = con.prepareStatement(query4); int rs4 = pst4.executeUpdate(); } catch (ClassNotFoundException ex) { Logger.getLogger(Supplies.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(Supplies.class.getName()).log(Level.SEVERE, null, ex); } } } } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed saveSupplies(); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Supplies.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Supplies.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Supplies.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Supplies.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Supplies().setVisible(true); //show_SuppliesStock(); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField10; private javax.swing.JTextField jTextField11; private javax.swing.JTextField jTextField12; static javax.swing.JTextField jTextField13; static javax.swing.JTextField jTextField14; static javax.swing.JTextField jTextField15; static javax.swing.JTextField jTextField16; private javax.swing.JTextField jTextField17; private javax.swing.JTextField jTextField18; static javax.swing.JTextField jTextField19; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField4; private javax.swing.JTextField jTextField5; private javax.swing.JTextField jTextField6; private javax.swing.JTextField jTextField7; private javax.swing.JTextField jTextField8; private javax.swing.JTextField jTextField9; // End of variables declaration//GEN-END:variables }
alexkou/Software_Engineering_Project
src/projectt/Supplies.java
7,548
//έλεγχος για κενά πεδία και εμφάνιση μηνύματος
line_comment
el
/* * 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 projectt; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.text.BadLocationException; /** * * @author Marinos */ public class Supplies extends javax.swing.JFrame { private int currentQid; /** * Creates new form Supplies */ public Supplies() { initComponents(); getSupplies(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jTextField3 = new javax.swing.JTextField(); jTextField5 = new javax.swing.JTextField(); jTextField6 = new javax.swing.JTextField(); jTextField7 = new javax.swing.JTextField(); jTextField8 = new javax.swing.JTextField(); jTextField9 = new javax.swing.JTextField(); jTextField10 = new javax.swing.JTextField(); jTextField4 = new javax.swing.JTextField(); jTextField11 = new javax.swing.JTextField(); jTextField12 = new javax.swing.JTextField(); jTextField13 = new javax.swing.JTextField(); jTextField14 = new javax.swing.JTextField(); jTextField15 = new javax.swing.JTextField(); jTextField16 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jTextField17 = new javax.swing.JTextField(); jTextField18 = new javax.swing.JTextField(); jTextField19 = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(150, 235, 240)); jPanel1.setPreferredSize(new java.awt.Dimension(1260, 660)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/A4AD5659B5D44610AB530DF0BAB8279D.jpeg"))); // NOI18N jTextField1.setBackground(new java.awt.Color(150, 235, 240)); jTextField1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jTextField1.setText("ΤΜΗΜΑ ΠΡΟΜΗΘΕΙΩΝ"); jTextField1.setBorder(null); jTextField1.setFocusable(false); jTextField2.setBackground(new java.awt.Color(150, 235, 240)); jTextField2.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N jTextField2.setText("ΓΑΝΤΙΑ"); jTextField2.setBorder(null); jTextField2.setFocusable(false); jTextField3.setBackground(new java.awt.Color(150, 235, 240)); jTextField3.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N jTextField3.setText("ΜΑΣΚΕΣ"); jTextField3.setBorder(null); jTextField3.setFocusable(false); jTextField3.setPreferredSize(new java.awt.Dimension(75, 25)); jTextField5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextField5.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField6.setBackground(new java.awt.Color(150, 235, 240)); jTextField6.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N jTextField6.setText("ΓΑΖΕΣ"); jTextField6.setBorder(null); jTextField6.setFocusable(false); jTextField7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextField7.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextField8.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField9.setBackground(new java.awt.Color(150, 235, 240)); jTextField9.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N jTextField9.setText("ΧΕΙΡΟΥΡΓΙΚΕΣ ΦΟΡΜΕΣ"); jTextField9.setBorder(null); jTextField9.setFocusable(false); jTextField10.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextField10.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField4.setBackground(new java.awt.Color(150, 235, 240)); jTextField4.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jTextField4.setText("ΔΙΑΘΕΣΙΜΟΤΗΤΑ"); jTextField4.setBorder(null); jTextField4.setFocusable(false); jTextField11.setBackground(new java.awt.Color(150, 235, 240)); jTextField11.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jTextField11.setText("ΕΙΔΟΣ"); jTextField11.setBorder(null); jTextField11.setFocusable(false); jTextField12.setBackground(new java.awt.Color(150, 235, 240)); jTextField12.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jTextField12.setText("ΠΟΣΟΤΗΤΑ"); jTextField12.setBorder(null); jTextField12.setFocusable(false); jTextField13.setBackground(new java.awt.Color(150, 235, 240)); jTextField13.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jTextField13.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField13.setBorder(null); jTextField13.setFocusable(false); jTextField14.setBackground(new java.awt.Color(150, 235, 240)); jTextField14.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jTextField14.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField14.setBorder(null); jTextField14.setFocusable(false); jTextField15.setBackground(new java.awt.Color(150, 235, 240)); jTextField15.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jTextField15.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField15.setBorder(null); jTextField15.setFocusable(false); jTextField16.setBackground(new java.awt.Color(150, 235, 240)); jTextField16.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jTextField16.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField16.setToolTipText(""); jTextField16.setBorder(null); jTextField16.setFocusable(false); jButton1.setBackground(new java.awt.Color(0, 0, 0)); jButton1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jButton1.setForeground(new java.awt.Color(255, 255, 255)); jButton1.setText("Αποθήκευση"); jButton1.setBorder(null); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jTextField17.setBackground(new java.awt.Color(150, 235, 240)); jTextField17.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N jTextField17.setText("ΝΑΡΘΗΚΕΣ"); jTextField17.setBorder(null); jTextField17.setFocusable(false); jTextField18.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextField18.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField19.setBackground(new java.awt.Color(150, 235, 240)); jTextField19.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jTextField19.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jTextField19.setBorder(null); jTextField19.setFocusable(false); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 0, 0)); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 0, 0)); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap(257, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField11, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(81, 81, 81) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField18, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(120, 120, 120) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addGap(152, 152, 152) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextField16, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField14, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField13, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField15, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField19, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)))))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(80, 80, 80) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 470, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(248, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField17, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE)))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(38, 38, 38) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(97, 97, 97) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(34, 34, 34) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField16, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField13, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField14, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField15, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField17, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField18, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField19, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(61, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 1267, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 737, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void displayFail1(){ JOptionPane.showMessageDialog(this,("Δεν επαρκούν οι προμήθειες.")); } private void displayFail2(){ JOptionPane.showMessageDialog(this,("Συπληρώστε τα κενά πεδία με μηδέν (0)!")); //εμφάνιση μηνύματος } private static void getSupplies() { //Επιλογή από την βάση των προμηθειών try{ java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/project", "root", ""); //Σύνδεση με βάση String query = "SELECT stock FROM supplies WHERE supply='gantia'"; // εντολή select PreparedStatement pst = con.prepareStatement(query); // ResultSet rs = pst.executeQuery(); //εκτελεση του query και αποθήκευση στο rs if(rs.next()) { jTextField16.setText(""+rs.getInt("stock")); //εμφάνιση αποτελέσματος σε int στο textfield } String query1 = "SELECT stock FROM supplies WHERE supply='maskes'"; PreparedStatement pst1 = con.prepareStatement(query1); ResultSet rs1 = pst1.executeQuery(); if(rs1.next()) { jTextField13.setText(""+rs1.getInt("stock")); } String query2 = "SELECT stock FROM supplies WHERE supply='gazes'"; PreparedStatement pst2 = con.prepareStatement(query2); ResultSet rs2 = pst2.executeQuery(); if(rs2.next()) { jTextField14.setText(""+rs2.getInt("stock")); } String query3 = "SELECT stock FROM supplies WHERE supply='formes_xeirourgeiou'"; PreparedStatement pst3 = con.prepareStatement(query3); ResultSet rs3 = pst3.executeQuery(); if(rs3.next()) { jTextField15.setText(""+rs3.getInt("stock")); } String query4 = "SELECT stock FROM supplies WHERE supply='narthikes'"; PreparedStatement pst4 = con.prepareStatement(query4); ResultSet rs4 = pst4.executeQuery(); if(rs4.next()) { jTextField19.setText(""+rs4.getInt("stock")); } } catch (SQLException ex) { Logger.getLogger(Supplies.class.getName()).log(Level.SEVERE, null, ex); } } private void saveSupplies(){ //έλεγχος για<SUF> //check_Stock() if(jTextField5.getText().trim().isEmpty() || jTextField8.getText().trim().isEmpty() || jTextField7.getText().trim().isEmpty() || jTextField10.getText().trim().isEmpty() ||jTextField18.getText().trim().isEmpty()) { displayFail2(); } else { //μετατροπη του περιεχομένου textfield σε int και εκτέλεση πράξεων για την αφαίρεση int g = Integer.parseInt(jTextField5.getText().trim()); int g1 = Integer.parseInt(jTextField16.getText().trim()); int g2 = g1-g; int m =Integer.parseInt(jTextField8.getText().trim()); int m1 =Integer.parseInt(jTextField13.getText().trim()); int m2 = m1-m; int ga = Integer.parseInt(jTextField7.getText().trim()); int ga1 = Integer.parseInt(jTextField14.getText().trim()); int ga2 = ga1-ga; int fx = Integer.parseInt(jTextField10.getText().trim()); int fx1 = Integer.parseInt(jTextField15.getText().trim()); int fx2 = fx1-fx; int n = Integer.parseInt(jTextField18.getText().trim()); int n1 = Integer.parseInt(jTextField19.getText().trim()); int n2 = n1-n; //έλεγχος για επάρκεια προμηθειών και εμφάνιση μηνυμάτων //check_Stock() if(g2<0 || m2<0 || ga2<0 || fx2<0 || n2<0) { displayFail1(); } else{ try { //ενημέρωση του table στην βάση παίρνωντας ως δεδομένα την αφαίρεση των προμηθειών Class.forName("com.mysql.cj.jdbc.Driver"); java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/project", "root", ""); String query = "UPDATE supplies SET stock='"+g2+"' WHERE supply='gantia'"; PreparedStatement pst = con.prepareStatement(query); int rs = pst.executeUpdate(); String query1 = "UPDATE supplies SET stock='"+m2+"' WHERE supply='maskes'"; PreparedStatement pst1 = con.prepareStatement(query1); int rs1 = pst1.executeUpdate(); String query2 = "UPDATE supplies SET stock='"+ga2+"' WHERE supply='gazes'"; PreparedStatement pst2 = con.prepareStatement(query2); int rs2 = pst2.executeUpdate(); String query3 = "UPDATE supplies SET stock='"+fx2+"' WHERE supply='formes_xeirourgeiou'"; PreparedStatement pst3 = con.prepareStatement(query3); int rs3 = pst3.executeUpdate(); String query4 = "UPDATE supplies SET stock='"+n2+"' WHERE supply='narthikes'"; PreparedStatement pst4 = con.prepareStatement(query4); int rs4 = pst4.executeUpdate(); } catch (ClassNotFoundException ex) { Logger.getLogger(Supplies.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(Supplies.class.getName()).log(Level.SEVERE, null, ex); } } } } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed saveSupplies(); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Supplies.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Supplies.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Supplies.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Supplies.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Supplies().setVisible(true); //show_SuppliesStock(); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField10; private javax.swing.JTextField jTextField11; private javax.swing.JTextField jTextField12; static javax.swing.JTextField jTextField13; static javax.swing.JTextField jTextField14; static javax.swing.JTextField jTextField15; static javax.swing.JTextField jTextField16; private javax.swing.JTextField jTextField17; private javax.swing.JTextField jTextField18; static javax.swing.JTextField jTextField19; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField4; private javax.swing.JTextField jTextField5; private javax.swing.JTextField jTextField6; private javax.swing.JTextField jTextField7; private javax.swing.JTextField jTextField8; private javax.swing.JTextField jTextField9; // End of variables declaration//GEN-END:variables }
3195_6
/* Άσκηση 2.6 ∆ηµιουργήστε µια ουρά από φοιτητές -χρησιµοποιήστε την Student class από την προηγούµενηάσκηση και εκτελέστε τις βασικές λειτουργίες της ουράς. */ public class LinkedQueueApp { public static void main(String args[]) { LinkedQueue Lqueue=new LinkedQueue(); //Προσθήκη στοιχείων στην Ουρά(Queue) Lqueue.enqueue(new Student(181001,"Nikos",0,6)); Lqueue.enqueue(new Student(181015,"Anna",0,7)); Lqueue.enqueue(new Student(181032,"Kostas",1,8)); //Επιστροφή του μεγέθους της Ουράς(Queue). System.out.println("The size of Queue is: "+Lqueue.size()); //Έλεγχος αν η Ουρά είναι κενή ή όχι. System.out.println("\nChecking if Queue is Empty(True) or not Empty(False): "+Lqueue.isEmpty()); //Επιστροφή του πρώτου στοιχείου της Ουράς(Queue). System.out.println("\nReturning the first item of Queue: "); System.out.println(Lqueue.front()); //Εξαγωγή και επιστροφή του πρώτου στοιχείου της Ουράς. System.out.println("\nRemoving all items from Queue:"); int size=Lqueue.size(); for(int i=0;i<size;i++) { Student S=(Student)Lqueue.dequeue(); //downcasting! System.out.println("Deleted items:"); System.out.println("Student "+i+": "+S.getOnoma()+", AM: "+S.getAM()); //Lqueue.enqueue(S); //--> Ξανά προσθήκη όλων των στοιχείων στην Ουρά [ Lqueue.size()=3 ] } //Lqueue.dequeue(); //--> αφαίρεση του τελευταίου μόνο στοιχείου της Ουράς. System.out.println("\nThe size of Queue is "+Lqueue.size()); System.out.println("and the Queue is also Empty(True) or not Empty(false): "+Lqueue.isEmpty()); } }
alexoiik/Data-Structures-Java
DataStructures_Ex4(Stacks&QueuesWithLinkedLists)/src/LinkedQueueApp.java
766
//Lqueue.enqueue(S); //--> Ξανά προσθήκη όλων των στοιχείων στην Ουρά [ Lqueue.size()=3 ]
line_comment
el
/* Άσκηση 2.6 ∆ηµιουργήστε µια ουρά από φοιτητές -χρησιµοποιήστε την Student class από την προηγούµενηάσκηση και εκτελέστε τις βασικές λειτουργίες της ουράς. */ public class LinkedQueueApp { public static void main(String args[]) { LinkedQueue Lqueue=new LinkedQueue(); //Προσθήκη στοιχείων στην Ουρά(Queue) Lqueue.enqueue(new Student(181001,"Nikos",0,6)); Lqueue.enqueue(new Student(181015,"Anna",0,7)); Lqueue.enqueue(new Student(181032,"Kostas",1,8)); //Επιστροφή του μεγέθους της Ουράς(Queue). System.out.println("The size of Queue is: "+Lqueue.size()); //Έλεγχος αν η Ουρά είναι κενή ή όχι. System.out.println("\nChecking if Queue is Empty(True) or not Empty(False): "+Lqueue.isEmpty()); //Επιστροφή του πρώτου στοιχείου της Ουράς(Queue). System.out.println("\nReturning the first item of Queue: "); System.out.println(Lqueue.front()); //Εξαγωγή και επιστροφή του πρώτου στοιχείου της Ουράς. System.out.println("\nRemoving all items from Queue:"); int size=Lqueue.size(); for(int i=0;i<size;i++) { Student S=(Student)Lqueue.dequeue(); //downcasting! System.out.println("Deleted items:"); System.out.println("Student "+i+": "+S.getOnoma()+", AM: "+S.getAM()); //Lqueue.enqueue(S); <SUF> } //Lqueue.dequeue(); //--> αφαίρεση του τελευταίου μόνο στοιχείου της Ουράς. System.out.println("\nThe size of Queue is "+Lqueue.size()); System.out.println("and the Queue is also Empty(True) or not Empty(false): "+Lqueue.isEmpty()); } }
4495_14
/** * Ηλίας Παπαδημητρίου * AEM: 9259 * [email protected] * * Αλέξανδρος Οικονόμου * AEM: 9260 * [email protected] * */ package gr.auth.ee.dsproject.pacman; /** * <p> * Title: DataStructures2006 * </p> * * <p> * Description: Data Structures project: year 2011-2012 * </p> * * <p> * Copyright: Copyright (c) 2011 * </p> * * <p> * Company: A.U.Th. * </p> * * @author Michael T. Tsapanos * @version 1.0 */ public class Creature implements gr.auth.ee.dsproject.pacman.AbstractCreature { public String getName () { return "Mine"; } private int step = 1; private boolean amPrey; public Creature (boolean isPrey) { amPrey = isPrey; } public int calculateNextPacmanPosition (Room[][] Maze, int[] currPosition) { int newDirection = -1; while (newDirection == -1) { int temp_dir = (int) (4 * Math.random()); if (Maze[currPosition[0]][currPosition[1]].walls[temp_dir] == 1) { newDirection = temp_dir; } } step++; return newDirection; } // THIS IS THE FUNCTION TO IMPLEMENT!!!!!! public int[] calculateNextGhostPosition (Room[][] Maze, int[][] currentPos) /** Αυτή η συνάρτηση υπολογίζει την επόμενη θέση των φαντασμάτων, με τέτοιο τρόπο ώστε * να μη συγκρούονται με τοίχους και μεταξύ τους. * newDirection, πίνακας για την επόμενη κίνηση των φαντασμάτων * temp_direction, πίνακας με προσωρινες τιμές πριν γίνουν έλεγχοι και εγκριθούν */ { int[] newDirection = {-1,-1,-1,-1}; // αρχικοποίηση του πίνακα int[] temp_direction = new int[PacmanUtilities.numberOfGhosts]; if (step < PacmanUtilities.stepLimit) { // ελεγχος για τον αριθμό των κινήσεων, αν εχουν απομίνει for(int i = 0; i < PacmanUtilities.numberOfGhosts; i++) { // επανάληψη για 4 φαντάσματα while (newDirection[i] == -1 ) { // όσο δεν έχει αλλάξει η αρχική τιμή temp_direction[i] = (int) (4 * Math.random()); // εκχώρηση τυχαίας τιμής από 0 μέχρι 3 if (Maze[currentPos[i][0]][currentPos[i][1]].walls[temp_direction[i]] == 1) { // αν δεν έχει τοίχο είναι αληθής newDirection[i] = temp_direction[i]; // εκχώρηση της προσωρινής τιμής στον πίνακα με τη νέα κίνηση } } } boolean[] b = checkCollision(newDirection, currentPos); // πίνακας με τιμές της checkCollision for (int j = 1; j < b.length; j++) { // επανάληψη για 3 φαντάσματα, αφου το πρώτο έχει παντα προτεραιότητα int[] k = {-1, -2, -3}; // πίνακας που κρατάει μέχρι και 3 κατευθύνσεις της νέας κίνησης ενός φαντάσματος, ώστε να μειωθεί ο αριθμός των ελέγχων int l = 0; // μεταβλητή μετρητής του πίνακα k while(b[j] == true && l < 3) { do { k[l] = (int) (4 * Math.random()); // εκχώρηση τυχαίας τιμής από 0 μέχρι 3 newDirection[j] = k[l]; }while(k[0] == k[1] || k[0] == k[2] || k[1] == k[2] || //όσο μία τιμή είναι ίδια με κάποια άλλη, εκχωείται νεα τυχαία τιμή k[l] == temp_direction[j] || Maze[currentPos[j][0]][currentPos[j][1]].walls[k[l]] == 0); // Σκοπός να μειώνει τις πράξεις που απαιτούνται b = checkCollision(newDirection, currentPos); l++; } } } step++; return newDirection; } public boolean[] checkCollision (int[] moves, int[][] currentPos) { boolean[] collision = new boolean[PacmanUtilities.numberOfGhosts]; int[][] newPos = new int[4][2]; for (int i = 0; i < moves.length; i++) { if (moves[i] == 0) { newPos[i][0] = currentPos[i][0]; newPos[i][1] = currentPos[i][1] - 1; } else if (moves[i] == 1) { newPos[i][0] = currentPos[i][0] + 1; newPos[i][1] = currentPos[i][1]; } else if (moves[i] == 2) { newPos[i][0] = currentPos[i][0]; newPos[i][1] = currentPos[i][1] + 1; } else { newPos[i][0] = currentPos[i][0] - 1; newPos[i][1] = currentPos[i][1]; } collision[i] = false; } for (int k = 0; k < moves.length; k++) { // System.out.println("Ghost " + k + " new Position is (" + newPos[k][0] + "," + newPos[k][1] + ")."); } for (int i = 0; i < moves.length; i++) { for (int j = i + 1; j < moves.length; j++) { if (newPos[i][0] == newPos[j][0] && newPos[i][1] == newPos[j][1]) { // System.out.println("Ghosts " + i + " and " + j + " are colliding"); collision[j] = true; } if (newPos[i][0] == currentPos[j][0] && newPos[i][1] == currentPos[j][1] && newPos[j][0] == currentPos[i][0] && newPos[j][1] == currentPos[i][1]) { // System.out.println("Ghosts " + i + " and " + j + " are colliding"); collision[j] = true; } } } return collision; } }
alexoiko/University-Assignments
Object-Oriented Programming Java/Pacman Part 1/src/gr/auth/ee/dsproject/pacman/Creature.java
2,206
// μεταβλητή μετρητής του πίνακα k
line_comment
el
/** * Ηλίας Παπαδημητρίου * AEM: 9259 * [email protected] * * Αλέξανδρος Οικονόμου * AEM: 9260 * [email protected] * */ package gr.auth.ee.dsproject.pacman; /** * <p> * Title: DataStructures2006 * </p> * * <p> * Description: Data Structures project: year 2011-2012 * </p> * * <p> * Copyright: Copyright (c) 2011 * </p> * * <p> * Company: A.U.Th. * </p> * * @author Michael T. Tsapanos * @version 1.0 */ public class Creature implements gr.auth.ee.dsproject.pacman.AbstractCreature { public String getName () { return "Mine"; } private int step = 1; private boolean amPrey; public Creature (boolean isPrey) { amPrey = isPrey; } public int calculateNextPacmanPosition (Room[][] Maze, int[] currPosition) { int newDirection = -1; while (newDirection == -1) { int temp_dir = (int) (4 * Math.random()); if (Maze[currPosition[0]][currPosition[1]].walls[temp_dir] == 1) { newDirection = temp_dir; } } step++; return newDirection; } // THIS IS THE FUNCTION TO IMPLEMENT!!!!!! public int[] calculateNextGhostPosition (Room[][] Maze, int[][] currentPos) /** Αυτή η συνάρτηση υπολογίζει την επόμενη θέση των φαντασμάτων, με τέτοιο τρόπο ώστε * να μη συγκρούονται με τοίχους και μεταξύ τους. * newDirection, πίνακας για την επόμενη κίνηση των φαντασμάτων * temp_direction, πίνακας με προσωρινες τιμές πριν γίνουν έλεγχοι και εγκριθούν */ { int[] newDirection = {-1,-1,-1,-1}; // αρχικοποίηση του πίνακα int[] temp_direction = new int[PacmanUtilities.numberOfGhosts]; if (step < PacmanUtilities.stepLimit) { // ελεγχος για τον αριθμό των κινήσεων, αν εχουν απομίνει for(int i = 0; i < PacmanUtilities.numberOfGhosts; i++) { // επανάληψη για 4 φαντάσματα while (newDirection[i] == -1 ) { // όσο δεν έχει αλλάξει η αρχική τιμή temp_direction[i] = (int) (4 * Math.random()); // εκχώρηση τυχαίας τιμής από 0 μέχρι 3 if (Maze[currentPos[i][0]][currentPos[i][1]].walls[temp_direction[i]] == 1) { // αν δεν έχει τοίχο είναι αληθής newDirection[i] = temp_direction[i]; // εκχώρηση της προσωρινής τιμής στον πίνακα με τη νέα κίνηση } } } boolean[] b = checkCollision(newDirection, currentPos); // πίνακας με τιμές της checkCollision for (int j = 1; j < b.length; j++) { // επανάληψη για 3 φαντάσματα, αφου το πρώτο έχει παντα προτεραιότητα int[] k = {-1, -2, -3}; // πίνακας που κρατάει μέχρι και 3 κατευθύνσεις της νέας κίνησης ενός φαντάσματος, ώστε να μειωθεί ο αριθμός των ελέγχων int l = 0; // μεταβλητή μετρητής<SUF> while(b[j] == true && l < 3) { do { k[l] = (int) (4 * Math.random()); // εκχώρηση τυχαίας τιμής από 0 μέχρι 3 newDirection[j] = k[l]; }while(k[0] == k[1] || k[0] == k[2] || k[1] == k[2] || //όσο μία τιμή είναι ίδια με κάποια άλλη, εκχωείται νεα τυχαία τιμή k[l] == temp_direction[j] || Maze[currentPos[j][0]][currentPos[j][1]].walls[k[l]] == 0); // Σκοπός να μειώνει τις πράξεις που απαιτούνται b = checkCollision(newDirection, currentPos); l++; } } } step++; return newDirection; } public boolean[] checkCollision (int[] moves, int[][] currentPos) { boolean[] collision = new boolean[PacmanUtilities.numberOfGhosts]; int[][] newPos = new int[4][2]; for (int i = 0; i < moves.length; i++) { if (moves[i] == 0) { newPos[i][0] = currentPos[i][0]; newPos[i][1] = currentPos[i][1] - 1; } else if (moves[i] == 1) { newPos[i][0] = currentPos[i][0] + 1; newPos[i][1] = currentPos[i][1]; } else if (moves[i] == 2) { newPos[i][0] = currentPos[i][0]; newPos[i][1] = currentPos[i][1] + 1; } else { newPos[i][0] = currentPos[i][0] - 1; newPos[i][1] = currentPos[i][1]; } collision[i] = false; } for (int k = 0; k < moves.length; k++) { // System.out.println("Ghost " + k + " new Position is (" + newPos[k][0] + "," + newPos[k][1] + ")."); } for (int i = 0; i < moves.length; i++) { for (int j = i + 1; j < moves.length; j++) { if (newPos[i][0] == newPos[j][0] && newPos[i][1] == newPos[j][1]) { // System.out.println("Ghosts " + i + " and " + j + " are colliding"); collision[j] = true; } if (newPos[i][0] == currentPos[j][0] && newPos[i][1] == currentPos[j][1] && newPos[j][0] == currentPos[i][0] && newPos[j][1] == currentPos[i][1]) { // System.out.println("Ghosts " + i + " and " + j + " are colliding"); collision[j] = true; } } } return collision; } }
1032_11
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Random; /** * * Η Κλαση αυτη δημιουργει λογικη για το παιχνιδι Sudoku * * @author Alexandros Vladovitis,Stelios Verros */ public class SudokuLogic { final int SIZE_ARRAY = 81; private int[] array; private int[] arraySolver; private int[] arrayKiller; private String[] arrayKillerColours; private int rand; private boolean[] arraycheck; /** * Ο κατασκευαστης δημιουργει τους πινακες array(ο οποιος αποθηκευει τις επιλογες του χρηστη) * arraycheck(ο οποιος ελεγχει αν τα στοιχεια ειναι απο το αρχειο ή οχι)arraySolver(ο οποιος δεχεται * τις λυσεις του killer sudoku)arrayKiller(ο οποιος δεχεται τους αριθμους απο το αρχειο killer) * arrayKillerColours(ο οποιος δεχεται τα γραμματα του αρχειου killer ωστε να ξεχωριζει απο τους * υπολοιπους ιδιους αριθμους) * * @author Alexandros Vladovitis,Stelios Verros */ public SudokuLogic() { array = new int[SIZE_ARRAY]; arraycheck = new boolean[SIZE_ARRAY]; arraySolver=new int[SIZE_ARRAY]; arrayKiller=new int[SIZE_ARRAY]; arrayKillerColours=new String[SIZE_ARRAY]; for (int i = 0; i < SIZE_ARRAY; i++) { array[i] = -1; arraySolver[i]=-1; arrayKiller[i]=-1; } /* * Η checkMoveLine ελεγχει αν μπορει να μπει το item στην * θεση x που δεχεται ελεγχοντας μονο την γραμμη του πινακα * * @author Alexandros Vladovitis,Stelios Verros */ } public boolean checkMoveLine(int x, int item) { int line = x / 9; //ευρεση γραμμης int startLine = line * 9; int endLine = line * 9 + 8; for (int i = startLine; i <= endLine; i++) { if (item == array[i]) { return false; } } return true; } /** * Η checkMoveColumn ελεγχει αν μπορει να μπει το item στην * θεση x που δεχεται ελεγχοντας μονο την στηλη του πινακα * * @author Alexandros Vladovitis,Stelios Verros */ public boolean checkMoveColumn(int x, int item) { int startColumn = x % 9;//ευρεση στηλης int endColumn = 72 + startColumn; for (int i = startColumn; i <= endColumn; i += 9) { if (item == array[i]) { return false; } } return true; } /** * Η checkMoveBox ελεγχει αν μπορει να μπει το item στην * θεση x που δεχεται ελεγχοντας μονο την κουτακι του πινακα * * @author Alexandros Vladovitis,Stelios Verros */ public boolean checkMoveBox(int x, int item) { int column = x % 9; int line = x / 9; int box = (line / 3) + (column / 3) + (2 * (line / 3));// ευρεση τετραγωνακι int startBoxLine = ((box / 3) * 27) + (box % 3) * 3; int endBoxLine = startBoxLine + 2; for (int i = startBoxLine; i <= endBoxLine; i++) { for (int j = 0; j <= 18; j += 9) { if (item == array[i + j]) { return false; } } } return true; } /** * Η checkMove ελεγχει αν μπορει να μπει το item στην * θεση x που δεχεται ελεγχοντας ολο τον πινακα χρησιμοποιωντας και * τις προηγουμενες συναρτησεις * * @author Alexandros Vladovitis,Stelios Verros */ public boolean checkMove(int x, int item) { return checkMoveBox(x, item) && checkMoveColumn(x, item) && checkMoveLine(x, item); } /** * Η addMove προσθετει το στοιχεο στον πινακα εφοσον μπορει να μπει το item στην * θεση x που δεχεται ελεγχοντας αν εδωσε σωστο αριθμο και ειναι αδειο το κελι * * @author Alexandros Vladovitis,Stelios Verros */ public void addMove(int x, int item) { if (checkItem(item) && checkEmptyBox(x)) { array[x] = item; } } /** * Η checkEmptyBox ελεγχει αν το κελι στην θεση χ ειναι αδειο και εφοσον ειναι = με -1 * (δηλαδη ειναι αδειο λογω αρχικοποιησης)τοτε γυρναει true * * @author Alexandros Vladovitis,Stelios Verros */ public boolean checkEmptyBox(int x) { //ελεχει αν εχει μπει στο κουτι αριθμος αν εχει μπει δεν σε αφηνει να το αλλαξεις return array[x] == -1; } /** * Η checkEmptyBox ελεγχει αν το item ειναι απο 1-9 * * @author Alexandros Vladovitis,Stelios Verros */ public boolean checkItem(int item) { return item > 0 && item < 10; } /** * Η checkPuzzle ελεγχει αν το κελι του πινακα ειναι απο το αρχειο ή οχι * και εφοσον ειναι δεν επιδεχεται αλλαγη αρα επιστρεφει false * * @author Alexandros Vladovitis,Stelios Verros */ public void checkPuzzle(){ for(int i=0;i<SIZE_ARRAY;i++){ arraycheck[i]= array[i] == -1; } } /** * Η removeMove ελεγχει αν το κελι του πινακα ειναι απο το αρχειο ή οχι * και εφοσον δεν ειναι το αφαιρει * * @author Alexandros Vladovitis,Stelios Verros */ public void removeMove(int x) { if(arraycheck[x]) array[x] = -1; } /** * Η TheEndOfTheGame ελεγχει αν εχουν συμπληρωθει ολα τα κελια του πινακα * και αν ναι επιστεφει true * * @author Alexandros Vladovitis,Stelios Verros */ public boolean TheEndOfTheGame() { int sum = 0; for (int i = 0; i < SIZE_ARRAY; i++) { if (array[i] != -1) { sum += 1; } } return sum == 81; } /** * Η GameResult ελεγχει χρησιμοποιωντας την προηγουμενη συναρτηση αν το αθροισμα * στηλων και γραμμων ειναι 405 αντοιστοιχα ωστε να επιστεψει true για να τελειωσει το παιχνιδι * * @author Alexandros Vladovitis,Stelios Verros */ public boolean GameResult() { if (TheEndOfTheGame() ) { int sumLine = 0;//βρισκω το sum για καθε γραμμη for (int i = 0; i < SIZE_ARRAY; i += 9) { for (int j = i; j <= i + 8; j++) { sumLine += array[j]; } } int sumColumn = 0;//βρισκω το sum για καθε στηλη for (int i = 0; i < 9; i++) { for (int j = i; j < SIZE_ARRAY; j += 9) { sumColumn += array[j]; } } return sumColumn == 405 && sumLine == 405; } return false; } public int[] getArray() { return array; } public boolean[] getArraycheck(){return arraycheck;} /** * Η addMoveKiller προσθετει τον αριθμο του αρχειου στον πινακα arrayKiller * και το γραμμα c στο arrayKillerColours ωστε να ξεχωριζει απο τα αλλους παρομοιους αριθμους * * @author Alexandros Vladovitis,Stelios Verros */ public void addMoveKiller(int x,int item,String c) { arrayKiller[x]=item; arrayKillerColours[x]=c; } public int[] getArrayKiller() { return arrayKiller; } public String[] getArrayKillerColours() { return arrayKillerColours; } /** * Η addMoveSolver προσθετει τον αριθμο του αρχειου Solver στον πινακα arrayKillerSolver * ωστε να ελεχθει η λυση * * @author Alexandros Vladovitis,Stelios Verros */ public void addMoveSolver(int x,int item){ arraySolver[x]=item; } /** * Η puzzle αρχικα δημιουργει ενα random στοιχειο ωστε να διαβασει απο τα 10 αρχεια ενα αρχειο * στην τυχη καθε φορα και μετα διαβαζει εναν εναν τον χαρακτηρα του text και καθε φορα * που ο χαρακτηρας ειναι τελεια(δηλαδη στο unicode =46)τοτε ανεβαζει το sum(που ειναι η θεση στον πινακα) * και αν δεν ειναι τελεια τοτε βαζει την κινηση στον πινακα χρησιμοποιωντας την addMove * * @author Alexandros Vladovitis,Stelios Verros */ public void puzzle() { try { Random rand = new Random(); int randomSudoku = rand.nextInt(10); randomSudoku++; FileReader in = new FileReader("sudoku_" + randomSudoku + ".txt"); int c; int sum = 0; while ((c = in.read()) != -1) { char c1 = (char) c; if (c1 != 46) { int item = c1 - 48; addMove(sum, item); } sum++; } } catch (IOException e) { System.out.println(e); } checkPuzzle(); } /** * Η puzzleKillerSolver χρησιμοποιει το ιδιο rand με την συναρτηση puzzleKiller ωστε να ταιριαξει τα txt files * και περναει την κινηση στην addMoveSolver * * @author Alexandros Vladovitis,Stelios Verros */ public void puzzleKillerSolver() { try { BufferedReader in = new BufferedReader(new FileReader("killer_sudoku_solve_" + rand +".txt")); String l; int sum = 0; while ((l = in.readLine()) != null) { int result = Integer.parseInt(l); addMoveSolver(sum,result); sum++; } } catch (IOException e) { System.out.println(e); } } /** * Η puzzleKillerSolver χρησιμοποιει ενα rand ωστε να παρει τυχαι ενα killer sudoku txt file * και χρησιμοποιωντας τα string και τις συναρτησεις valueof και charAt ξεχωριζουμε τους αριθμους με * τα γραμματα και αντιστοιχα τα περναμε στις αντοιστιχες συναρτησεις * * @author Alexandros Vladovitis,Stelios Verros */ public void puzzleKiller() { try { Random rand1 = new Random(); int randomSudoku1 = rand1.nextInt(10); randomSudoku1++; rand=randomSudoku1; BufferedReader in = new BufferedReader(new FileReader("killer_sudoku_"+ rand + ".txt")); String l; int sum=0; while ((l = in.readLine()) != null) { String c=""; StringBuilder number= new StringBuilder(); int len=l.length(); for(int i=0;i<len;i++) if (i== (len-1)){ c= String.valueOf((l.charAt(len-1))); }else number.append(String.valueOf((l.charAt(i)))); int result = Integer.parseInt(number.toString()); addMoveKiller(sum,result,c); sum++; } } catch (IOException e) { System.out.println(e); } } /** * Η FinishKiller ελεχγει τον πινακα arraySolver των λυσεων και τον πινακα array των επιλογων του * χρηστη ωστε να επιστρεψει true για να τερματισει το παιχνιδι * * @author Alexandros Vladovitis,Stelios Verros */ public boolean FinishKiller(){ int sum=0; for(int i=0;i<SIZE_ARRAY;i++){ if(arraySolver[i]==array[i]) sum++; } return sum == 81; } }
alexvlad14/sudokuGames
src/SudokuLogic.java
4,479
/** * Η removeMove ελεγχει αν το κελι του πινακα ειναι απο το αρχειο ή οχι * και εφοσον δεν ειναι το αφαιρει * * @author Alexandros Vladovitis,Stelios Verros */
block_comment
el
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Random; /** * * Η Κλαση αυτη δημιουργει λογικη για το παιχνιδι Sudoku * * @author Alexandros Vladovitis,Stelios Verros */ public class SudokuLogic { final int SIZE_ARRAY = 81; private int[] array; private int[] arraySolver; private int[] arrayKiller; private String[] arrayKillerColours; private int rand; private boolean[] arraycheck; /** * Ο κατασκευαστης δημιουργει τους πινακες array(ο οποιος αποθηκευει τις επιλογες του χρηστη) * arraycheck(ο οποιος ελεγχει αν τα στοιχεια ειναι απο το αρχειο ή οχι)arraySolver(ο οποιος δεχεται * τις λυσεις του killer sudoku)arrayKiller(ο οποιος δεχεται τους αριθμους απο το αρχειο killer) * arrayKillerColours(ο οποιος δεχεται τα γραμματα του αρχειου killer ωστε να ξεχωριζει απο τους * υπολοιπους ιδιους αριθμους) * * @author Alexandros Vladovitis,Stelios Verros */ public SudokuLogic() { array = new int[SIZE_ARRAY]; arraycheck = new boolean[SIZE_ARRAY]; arraySolver=new int[SIZE_ARRAY]; arrayKiller=new int[SIZE_ARRAY]; arrayKillerColours=new String[SIZE_ARRAY]; for (int i = 0; i < SIZE_ARRAY; i++) { array[i] = -1; arraySolver[i]=-1; arrayKiller[i]=-1; } /* * Η checkMoveLine ελεγχει αν μπορει να μπει το item στην * θεση x που δεχεται ελεγχοντας μονο την γραμμη του πινακα * * @author Alexandros Vladovitis,Stelios Verros */ } public boolean checkMoveLine(int x, int item) { int line = x / 9; //ευρεση γραμμης int startLine = line * 9; int endLine = line * 9 + 8; for (int i = startLine; i <= endLine; i++) { if (item == array[i]) { return false; } } return true; } /** * Η checkMoveColumn ελεγχει αν μπορει να μπει το item στην * θεση x που δεχεται ελεγχοντας μονο την στηλη του πινακα * * @author Alexandros Vladovitis,Stelios Verros */ public boolean checkMoveColumn(int x, int item) { int startColumn = x % 9;//ευρεση στηλης int endColumn = 72 + startColumn; for (int i = startColumn; i <= endColumn; i += 9) { if (item == array[i]) { return false; } } return true; } /** * Η checkMoveBox ελεγχει αν μπορει να μπει το item στην * θεση x που δεχεται ελεγχοντας μονο την κουτακι του πινακα * * @author Alexandros Vladovitis,Stelios Verros */ public boolean checkMoveBox(int x, int item) { int column = x % 9; int line = x / 9; int box = (line / 3) + (column / 3) + (2 * (line / 3));// ευρεση τετραγωνακι int startBoxLine = ((box / 3) * 27) + (box % 3) * 3; int endBoxLine = startBoxLine + 2; for (int i = startBoxLine; i <= endBoxLine; i++) { for (int j = 0; j <= 18; j += 9) { if (item == array[i + j]) { return false; } } } return true; } /** * Η checkMove ελεγχει αν μπορει να μπει το item στην * θεση x που δεχεται ελεγχοντας ολο τον πινακα χρησιμοποιωντας και * τις προηγουμενες συναρτησεις * * @author Alexandros Vladovitis,Stelios Verros */ public boolean checkMove(int x, int item) { return checkMoveBox(x, item) && checkMoveColumn(x, item) && checkMoveLine(x, item); } /** * Η addMove προσθετει το στοιχεο στον πινακα εφοσον μπορει να μπει το item στην * θεση x που δεχεται ελεγχοντας αν εδωσε σωστο αριθμο και ειναι αδειο το κελι * * @author Alexandros Vladovitis,Stelios Verros */ public void addMove(int x, int item) { if (checkItem(item) && checkEmptyBox(x)) { array[x] = item; } } /** * Η checkEmptyBox ελεγχει αν το κελι στην θεση χ ειναι αδειο και εφοσον ειναι = με -1 * (δηλαδη ειναι αδειο λογω αρχικοποιησης)τοτε γυρναει true * * @author Alexandros Vladovitis,Stelios Verros */ public boolean checkEmptyBox(int x) { //ελεχει αν εχει μπει στο κουτι αριθμος αν εχει μπει δεν σε αφηνει να το αλλαξεις return array[x] == -1; } /** * Η checkEmptyBox ελεγχει αν το item ειναι απο 1-9 * * @author Alexandros Vladovitis,Stelios Verros */ public boolean checkItem(int item) { return item > 0 && item < 10; } /** * Η checkPuzzle ελεγχει αν το κελι του πινακα ειναι απο το αρχειο ή οχι * και εφοσον ειναι δεν επιδεχεται αλλαγη αρα επιστρεφει false * * @author Alexandros Vladovitis,Stelios Verros */ public void checkPuzzle(){ for(int i=0;i<SIZE_ARRAY;i++){ arraycheck[i]= array[i] == -1; } } /** * Η removeMove ελεγχει<SUF>*/ public void removeMove(int x) { if(arraycheck[x]) array[x] = -1; } /** * Η TheEndOfTheGame ελεγχει αν εχουν συμπληρωθει ολα τα κελια του πινακα * και αν ναι επιστεφει true * * @author Alexandros Vladovitis,Stelios Verros */ public boolean TheEndOfTheGame() { int sum = 0; for (int i = 0; i < SIZE_ARRAY; i++) { if (array[i] != -1) { sum += 1; } } return sum == 81; } /** * Η GameResult ελεγχει χρησιμοποιωντας την προηγουμενη συναρτηση αν το αθροισμα * στηλων και γραμμων ειναι 405 αντοιστοιχα ωστε να επιστεψει true για να τελειωσει το παιχνιδι * * @author Alexandros Vladovitis,Stelios Verros */ public boolean GameResult() { if (TheEndOfTheGame() ) { int sumLine = 0;//βρισκω το sum για καθε γραμμη for (int i = 0; i < SIZE_ARRAY; i += 9) { for (int j = i; j <= i + 8; j++) { sumLine += array[j]; } } int sumColumn = 0;//βρισκω το sum για καθε στηλη for (int i = 0; i < 9; i++) { for (int j = i; j < SIZE_ARRAY; j += 9) { sumColumn += array[j]; } } return sumColumn == 405 && sumLine == 405; } return false; } public int[] getArray() { return array; } public boolean[] getArraycheck(){return arraycheck;} /** * Η addMoveKiller προσθετει τον αριθμο του αρχειου στον πινακα arrayKiller * και το γραμμα c στο arrayKillerColours ωστε να ξεχωριζει απο τα αλλους παρομοιους αριθμους * * @author Alexandros Vladovitis,Stelios Verros */ public void addMoveKiller(int x,int item,String c) { arrayKiller[x]=item; arrayKillerColours[x]=c; } public int[] getArrayKiller() { return arrayKiller; } public String[] getArrayKillerColours() { return arrayKillerColours; } /** * Η addMoveSolver προσθετει τον αριθμο του αρχειου Solver στον πινακα arrayKillerSolver * ωστε να ελεχθει η λυση * * @author Alexandros Vladovitis,Stelios Verros */ public void addMoveSolver(int x,int item){ arraySolver[x]=item; } /** * Η puzzle αρχικα δημιουργει ενα random στοιχειο ωστε να διαβασει απο τα 10 αρχεια ενα αρχειο * στην τυχη καθε φορα και μετα διαβαζει εναν εναν τον χαρακτηρα του text και καθε φορα * που ο χαρακτηρας ειναι τελεια(δηλαδη στο unicode =46)τοτε ανεβαζει το sum(που ειναι η θεση στον πινακα) * και αν δεν ειναι τελεια τοτε βαζει την κινηση στον πινακα χρησιμοποιωντας την addMove * * @author Alexandros Vladovitis,Stelios Verros */ public void puzzle() { try { Random rand = new Random(); int randomSudoku = rand.nextInt(10); randomSudoku++; FileReader in = new FileReader("sudoku_" + randomSudoku + ".txt"); int c; int sum = 0; while ((c = in.read()) != -1) { char c1 = (char) c; if (c1 != 46) { int item = c1 - 48; addMove(sum, item); } sum++; } } catch (IOException e) { System.out.println(e); } checkPuzzle(); } /** * Η puzzleKillerSolver χρησιμοποιει το ιδιο rand με την συναρτηση puzzleKiller ωστε να ταιριαξει τα txt files * και περναει την κινηση στην addMoveSolver * * @author Alexandros Vladovitis,Stelios Verros */ public void puzzleKillerSolver() { try { BufferedReader in = new BufferedReader(new FileReader("killer_sudoku_solve_" + rand +".txt")); String l; int sum = 0; while ((l = in.readLine()) != null) { int result = Integer.parseInt(l); addMoveSolver(sum,result); sum++; } } catch (IOException e) { System.out.println(e); } } /** * Η puzzleKillerSolver χρησιμοποιει ενα rand ωστε να παρει τυχαι ενα killer sudoku txt file * και χρησιμοποιωντας τα string και τις συναρτησεις valueof και charAt ξεχωριζουμε τους αριθμους με * τα γραμματα και αντιστοιχα τα περναμε στις αντοιστιχες συναρτησεις * * @author Alexandros Vladovitis,Stelios Verros */ public void puzzleKiller() { try { Random rand1 = new Random(); int randomSudoku1 = rand1.nextInt(10); randomSudoku1++; rand=randomSudoku1; BufferedReader in = new BufferedReader(new FileReader("killer_sudoku_"+ rand + ".txt")); String l; int sum=0; while ((l = in.readLine()) != null) { String c=""; StringBuilder number= new StringBuilder(); int len=l.length(); for(int i=0;i<len;i++) if (i== (len-1)){ c= String.valueOf((l.charAt(len-1))); }else number.append(String.valueOf((l.charAt(i)))); int result = Integer.parseInt(number.toString()); addMoveKiller(sum,result,c); sum++; } } catch (IOException e) { System.out.println(e); } } /** * Η FinishKiller ελεχγει τον πινακα arraySolver των λυσεων και τον πινακα array των επιλογων του * χρηστη ωστε να επιστρεψει true για να τερματισει το παιχνιδι * * @author Alexandros Vladovitis,Stelios Verros */ public boolean FinishKiller(){ int sum=0; for(int i=0;i<SIZE_ARRAY;i++){ if(arraySolver[i]==array[i]) sum++; } return sum == 81; } }
16417_7
package Entity; import java.awt.Graphics2D; import java.awt.Rectangle; import java.io.IOException; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import Main.MainPannel; import Main.KeyHandler; public class Player extends Entity { MainPannel gp; KeyHandler keyH; public final int screenX; public final int screenY; int hasKey = 0; int width; int height; int ScreenY_for_drawing_player; int ScreenX_for_drawing_player; String previous_direction; public Player(MainPannel gp, KeyHandler keyH) { this.gp = gp; this.keyH = keyH; screenX = gp.screenWidth/2 - (gp.tileSize/2); //Gia to camera screenY = gp.screenHeight/2 - (gp.tileSize/2); // movement solidArea = new Rectangle(); //to rectagle einai gia to collision. To box tou colosion tou player einai 32x32 anti gia 48x48 pou einai to texture tou gia na uparxei perithorio na xoraei eukolotera se meri solidArea.x = 8; solidArea.y = 8; solidAreadefaultX = solidArea.x; solidAreadefaultY = solidArea.y; solidArea.width = 32; // 32 htan to default solidArea.height = 32; // 32 htan to default setDefaultValues(); getPlayerImage(); } public void setDefaultValues () { //Default settings of player WorldX = gp.tileSize * 25; //anti gia 100; mporo na kano to gp.tileSize * epi poso delo gia na pao se kapoio sigekrimeno simeio/tale WorldY = gp.tileSize * 25; speed = 4; //posa pixel da paei se kade direction direction = "left"; } public void getPlayerImage() { try { standing1 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/standing_sprites/standing_1.png")); System.out.println("loaded standing1"); standing2 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/standing_sprites/standing_2.png")); System.out.println("loaded standing2"); standing3 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/standing_sprites/standing_3.png")); System.out.println("loaded standing3"); standing4 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/standing_sprites/standing_4.png")); System.out.println("loaded standing4"); standing5 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/standing_sprites/standing_5.png")); System.out.println("loaded standing5"); standing6 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/standing_sprites/standing_6.png")); System.out.println("loaded standing6"); up1 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_1.png")); System.out.println("loaded up1"); up2 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_2.png")); System.out.println("loaded up2"); up3 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_3.png")); System.out.println("loaded up3"); up4 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_4.png")); System.out.println("loaded up4"); up5 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_5.png")); System.out.println("loaded up5"); up6 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_6.png")); System.out.println("loaded up6"); down1 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_1.png")); System.out.println("loaded down1"); down2 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_2.png")); System.out.println("loaded down2"); down3 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_3.png")); System.out.println("loaded down3"); down4 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_4.png")); System.out.println("loaded down4"); down5 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_5.png")); System.out.println("loaded down5"); down6 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_6.png")); System.out.println("loaded down6"); left1 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_1.png")); System.out.println("loaded left1"); left2 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_2.png")); System.out.println("loaded left2"); left3 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_3.png")); System.out.println("loaded left3"); left4 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_4.png")); System.out.println("loaded left4"); left5 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_5.png")); System.out.println("loaded left5"); left6 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_6.png")); System.out.println("loaded left6"); right1 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_1.png")); System.out.println("loaded right1"); right2 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_2.png")); System.out.println("loaded right2"); right3 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_3.png")); System.out.println("loaded right3"); right4 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_4.png")); System.out.println("loaded right4"); right5 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_5.png")); System.out.println("loaded right5"); right6 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_6.png")); System.out.println("loaded right6"); fight1 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/fight_sprites/fight_1.png")); System.out.println("loaded fight1"); fight2 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/fight_sprites/fight_2.png")); System.out.println("loaded fight2"); fight3 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/fight_sprites/fight_3.png")); System.out.println("loaded fight3"); fight4 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/fight_sprites/fight_4.png")); System.out.println("loaded fight4"); } catch(IOException e) { e.printStackTrace(); } } public void upleft() { WorldX = WorldX - (speed / 1); //Για 60fps πρεπει να ειναι (speed / 2) WorldY = WorldY - (speed / 1); direction = "left"; } public void upright() { gp.Gamespeed = 1; WorldX = WorldX + (speed / 1); WorldY = WorldY - (speed / 1); direction = "right"; } public void downleft() { WorldX = WorldX - (speed / 1); WorldY = WorldY + (speed / 1); direction = "left"; } public void downright() { WorldX = WorldX + (speed / 1); WorldY = WorldY + (speed / 1); direction = "right"; } public void update() { //test gia to attack mode if(keyH.attack == true) { direction = "attack"; spriteCounter_for_attack++; if(spriteCounter_for_attack > 3) { switch(spriteNum_for_attack) { case 1: spriteNum_for_attack = 2; break; case 2: spriteNum_for_attack = 3; break; case 3: spriteNum_for_attack = 4; break; case 4: spriteNum_for_attack = 1; break; } spriteCounter_for_attack = 0; } } else if(keyH.attack == false) { spriteNum_for_attack = 4; //kanei reset to animation se ena sigekrimeno image, edo evala to 4 } //test gia to attack mode if(keyH.upPressed == false || keyH.downPressed == false || keyH.leftPressed == false || keyH.rightPressed == false ) if(keyH.attack == false) { //Edo vale to standing animation na paizei direction = "none"; spriteCounter_for_idle++; if(spriteCounter_for_idle > 5) { switch(spriteNum_for_standing_animation) { case 1: spriteNum_for_standing_animation = 2; //System.out.println("spriteNum_for_standing_animation = " + spriteNum_for_standing_animation); break; case 2: spriteNum_for_standing_animation = 3; //System.out.println("spriteNum_for_standing_animation = " + spriteNum_for_standing_animation); break; case 3: spriteNum_for_standing_animation = 4; //System.out.println("spriteNum_for_standing_animation = " + spriteNum_for_standing_animation); break; case 4: spriteNum_for_standing_animation = 5; //System.out.println("spriteNum_for_standing_animation = " + spriteNum_for_standing_animation); break; case 5: spriteNum_for_standing_animation = 6; //System.out.println("spriteNum_for_standing_animation = " + spriteNum_for_standing_animation); break; case 6: spriteNum_for_standing_animation = 1; //System.out.println("spriteNum_for_standing_animation = " + spriteNum_for_standing_animation); break; } spriteCounter_for_idle = 0; } } if(keyH.upPressed == true || keyH.downPressed == true || keyH.leftPressed == true || keyH.rightPressed == true) if(keyH.attack == false) { if(keyH.upPressed == true) { direction ="up"; //to 0,0 se x,y sto JPanel einai h pano goneia aristera //Den xreiazete pleon einai sto switch kato -> WorldY = WorldY - speed; //an paei pano tote to Y mikrenei } if(keyH.upPressed == true && keyH.leftPressed == true) { upleft(); } if(keyH.upPressed == true && keyH.rightPressed == true) { upright(); } if(keyH.downPressed == true) { direction = "down"; //Den xreiazete pleon einai sto switch kato -> WorldY = WorldY + speed; } if(keyH.downPressed == true && keyH.leftPressed == true) { downleft(); } if(keyH.downPressed == true && keyH.rightPressed == true) { downright(); } if(keyH.leftPressed == true) { direction = "left"; //Den xreiazete pleon einai sto switch kato -> WorldX = WorldX - speed; } if(keyH.rightPressed == true) { direction = "right"; //Den xreiazete pleon einai sto switch kato -> WorldX = WorldX + speed; } // // edo vlepoume an ginete collision tou player(to rectagle) me tile to ensomati playercollision = false; //einai sto Entity.Entity class to boolean gp.collisionChecker.checkTile(this); //elenxoume to collition me ta objects int objindex = gp.collisionChecker.checkObjectCollition(this, true); //to ...this... leei dixnei oti to entity einai o player kai to ....true.... einai to boolean tou player. Gia na katalaveis des to funciton pickUpObject(objindex); // an to colition einai lados tote o player mporei na kinidei if(playercollision == false && keyH.attack == false) { switch(direction) { case "up": WorldY = WorldY - (speed * 2); //Για 60fps πρεπει να ειναι (speed x 1) break; case "down": WorldY = WorldY + (speed * 2); break; case "left": WorldX = WorldX - (speed * 2); break; case "right": WorldX = WorldX + (speed * 2); break; case "none": //epeidi einai to standing apla den kinite lol break; } } spriteCounter++; if(spriteCounter > 5) { switch(spriteNum) { case 1: spriteNum = 2; //System.out.println("spriteNum = " + spriteNum); break; case 2: spriteNum = 3; //System.out.println("spriteNum = " + spriteNum); break; case 3: spriteNum = 4; //System.out.println("spriteNum = " + spriteNum); break; case 4: spriteNum = 5; //System.out.println("spriteNum = " + spriteNum); break; case 5: spriteNum = 6; //System.out.println("spriteNum = " + spriteNum); break; case 6: spriteNum = 1; //System.out.println("spriteNum = " + spriteNum); break; } spriteCounter = 0; } } } public void pickUpObject(int i) { if(i != 999) { String objectName = gp.obj[i].name; switch(objectName) { case "key": hasKey++; gp.obj[i] = null; System.out.println("Player has " + hasKey + " keys"); break; case "door": if(hasKey > 0) { gp.obj[i] = null; hasKey--; } System.out.println("Player has " + hasKey + " keys"); break; } } } public void draw(Graphics2D g2) { BufferedImage image = null; switch(direction) { case "up": switch(previous_direction) { case "left": width = -gp.tileSize; ScreenX_for_drawing_player = screenX + gp.tileSize; if(spriteNum == 1) { image = left1; } if(spriteNum == 2) { image = left2; } if(spriteNum == 3) { image = left3; } if(spriteNum == 4) { image = left4; } if(spriteNum == 5) { image = left5; } if(spriteNum == 6) { image = left6; } break; case "right": width = gp.tileSize; ScreenX_for_drawing_player = screenX; if(spriteNum == 1) { image = right1; } if(spriteNum == 2) { image = right2; } if(spriteNum == 3) { image = right3; } if(spriteNum == 4) { image = right4; } if(spriteNum == 5) { image = right5; } if(spriteNum == 6) { image = right6; } break; } break; case "down": switch(previous_direction) { case "left": width = -gp.tileSize; ScreenX_for_drawing_player = screenX + gp.tileSize; if(spriteNum == 1) { image = left1; } if(spriteNum == 2) { image = left2; } if(spriteNum == 3) { image = left3; } if(spriteNum == 4) { image = left4; } if(spriteNum == 5) { image = left5; } if(spriteNum == 6) { image = left6; } break; case "right": width = gp.tileSize; ScreenX_for_drawing_player = screenX; if(spriteNum == 1) { image = right1; } if(spriteNum == 2) { image = right2; } if(spriteNum == 3) { image = right3; } if(spriteNum == 4) { image = right4; } if(spriteNum == 5) { image = right5; } if(spriteNum == 6) { image = right6; } break; } break; case "left": case "up-left": width = -gp.tileSize; ScreenX_for_drawing_player = screenX + gp.tileSize; previous_direction = "left"; if(spriteNum == 1) { image = left1; } if(spriteNum == 2) { image = left2; } if(spriteNum == 3) { image = left3; } if(spriteNum == 4) { image = left4; } if(spriteNum == 5) { image = left5; } if(spriteNum == 6) { image = left6; } break; case "right": width = gp.tileSize; ScreenX_for_drawing_player = screenX; previous_direction = "right"; if(spriteNum == 1) { image = right1; } if(spriteNum == 2) { image = right2; } if(spriteNum == 3) { image = right3; } if(spriteNum == 4) { image = right4; } if(spriteNum == 5) { image = right5; } if(spriteNum == 6) { image = right6; } break; case "none": switch(previous_direction) { case "left": width = -gp.tileSize; ScreenX_for_drawing_player = screenX + gp.tileSize; if(spriteNum_for_standing_animation == 1) { image = standing1; } if(spriteNum_for_standing_animation == 2) { image = standing2; } if(spriteNum_for_standing_animation == 3) { image = standing3; } if(spriteNum_for_standing_animation == 4) { image = standing4; } if(spriteNum_for_standing_animation == 5) { image = standing5; } if(spriteNum_for_standing_animation == 6) { image = standing6; } break; case "right": width = gp.tileSize; ScreenX_for_drawing_player = screenX; if(spriteNum_for_standing_animation == 1) { image = standing1; } if(spriteNum_for_standing_animation == 2) { image = standing2; } if(spriteNum_for_standing_animation == 3) { image = standing3; } if(spriteNum_for_standing_animation == 4) { image = standing4; } if(spriteNum_for_standing_animation == 5) { image = standing5; } if(spriteNum_for_standing_animation == 6) { image = standing6; } break; } break; case "attack": switch(previous_direction) { case "left": width = -gp.tileSize; ScreenX_for_drawing_player = screenX + gp.tileSize; if(spriteNum_for_attack == 1) { image = fight1; } if(spriteNum_for_attack == 2) { image = fight2; } if(spriteNum_for_attack == 3) { image = fight3; } if(spriteNum_for_attack == 4) { image = fight4; } break; case "right": width = gp.tileSize; ScreenX_for_drawing_player = screenX; if(spriteNum_for_attack == 1) { image = fight1; } if(spriteNum_for_attack == 2) { image = fight2; } if(spriteNum_for_attack == 3) { image = fight3; } if(spriteNum_for_attack == 4) { image = fight4; } break; } break; } height = gp.tileSize; g2.drawImage(image, ScreenX_for_drawing_player, screenY, width, height, null); } }
aloualou56/JavaGame
src/Entity/Player.java
5,615
//Για 60fps πρεπει να ειναι (speed / 2)
line_comment
el
package Entity; import java.awt.Graphics2D; import java.awt.Rectangle; import java.io.IOException; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import Main.MainPannel; import Main.KeyHandler; public class Player extends Entity { MainPannel gp; KeyHandler keyH; public final int screenX; public final int screenY; int hasKey = 0; int width; int height; int ScreenY_for_drawing_player; int ScreenX_for_drawing_player; String previous_direction; public Player(MainPannel gp, KeyHandler keyH) { this.gp = gp; this.keyH = keyH; screenX = gp.screenWidth/2 - (gp.tileSize/2); //Gia to camera screenY = gp.screenHeight/2 - (gp.tileSize/2); // movement solidArea = new Rectangle(); //to rectagle einai gia to collision. To box tou colosion tou player einai 32x32 anti gia 48x48 pou einai to texture tou gia na uparxei perithorio na xoraei eukolotera se meri solidArea.x = 8; solidArea.y = 8; solidAreadefaultX = solidArea.x; solidAreadefaultY = solidArea.y; solidArea.width = 32; // 32 htan to default solidArea.height = 32; // 32 htan to default setDefaultValues(); getPlayerImage(); } public void setDefaultValues () { //Default settings of player WorldX = gp.tileSize * 25; //anti gia 100; mporo na kano to gp.tileSize * epi poso delo gia na pao se kapoio sigekrimeno simeio/tale WorldY = gp.tileSize * 25; speed = 4; //posa pixel da paei se kade direction direction = "left"; } public void getPlayerImage() { try { standing1 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/standing_sprites/standing_1.png")); System.out.println("loaded standing1"); standing2 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/standing_sprites/standing_2.png")); System.out.println("loaded standing2"); standing3 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/standing_sprites/standing_3.png")); System.out.println("loaded standing3"); standing4 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/standing_sprites/standing_4.png")); System.out.println("loaded standing4"); standing5 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/standing_sprites/standing_5.png")); System.out.println("loaded standing5"); standing6 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/standing_sprites/standing_6.png")); System.out.println("loaded standing6"); up1 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_1.png")); System.out.println("loaded up1"); up2 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_2.png")); System.out.println("loaded up2"); up3 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_3.png")); System.out.println("loaded up3"); up4 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_4.png")); System.out.println("loaded up4"); up5 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_5.png")); System.out.println("loaded up5"); up6 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_6.png")); System.out.println("loaded up6"); down1 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_1.png")); System.out.println("loaded down1"); down2 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_2.png")); System.out.println("loaded down2"); down3 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_3.png")); System.out.println("loaded down3"); down4 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_4.png")); System.out.println("loaded down4"); down5 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_5.png")); System.out.println("loaded down5"); down6 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_6.png")); System.out.println("loaded down6"); left1 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_1.png")); System.out.println("loaded left1"); left2 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_2.png")); System.out.println("loaded left2"); left3 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_3.png")); System.out.println("loaded left3"); left4 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_4.png")); System.out.println("loaded left4"); left5 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_5.png")); System.out.println("loaded left5"); left6 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_6.png")); System.out.println("loaded left6"); right1 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_1.png")); System.out.println("loaded right1"); right2 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_2.png")); System.out.println("loaded right2"); right3 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_3.png")); System.out.println("loaded right3"); right4 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_4.png")); System.out.println("loaded right4"); right5 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_5.png")); System.out.println("loaded right5"); right6 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/walking_sprites/walking_6.png")); System.out.println("loaded right6"); fight1 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/fight_sprites/fight_1.png")); System.out.println("loaded fight1"); fight2 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/fight_sprites/fight_2.png")); System.out.println("loaded fight2"); fight3 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/fight_sprites/fight_3.png")); System.out.println("loaded fight3"); fight4 = ImageIO.read(getClass().getResourceAsStream("/sprites/characters/cutted-character/fight_sprites/fight_4.png")); System.out.println("loaded fight4"); } catch(IOException e) { e.printStackTrace(); } } public void upleft() { WorldX = WorldX - (speed / 1); //Για 60fps<SUF> WorldY = WorldY - (speed / 1); direction = "left"; } public void upright() { gp.Gamespeed = 1; WorldX = WorldX + (speed / 1); WorldY = WorldY - (speed / 1); direction = "right"; } public void downleft() { WorldX = WorldX - (speed / 1); WorldY = WorldY + (speed / 1); direction = "left"; } public void downright() { WorldX = WorldX + (speed / 1); WorldY = WorldY + (speed / 1); direction = "right"; } public void update() { //test gia to attack mode if(keyH.attack == true) { direction = "attack"; spriteCounter_for_attack++; if(spriteCounter_for_attack > 3) { switch(spriteNum_for_attack) { case 1: spriteNum_for_attack = 2; break; case 2: spriteNum_for_attack = 3; break; case 3: spriteNum_for_attack = 4; break; case 4: spriteNum_for_attack = 1; break; } spriteCounter_for_attack = 0; } } else if(keyH.attack == false) { spriteNum_for_attack = 4; //kanei reset to animation se ena sigekrimeno image, edo evala to 4 } //test gia to attack mode if(keyH.upPressed == false || keyH.downPressed == false || keyH.leftPressed == false || keyH.rightPressed == false ) if(keyH.attack == false) { //Edo vale to standing animation na paizei direction = "none"; spriteCounter_for_idle++; if(spriteCounter_for_idle > 5) { switch(spriteNum_for_standing_animation) { case 1: spriteNum_for_standing_animation = 2; //System.out.println("spriteNum_for_standing_animation = " + spriteNum_for_standing_animation); break; case 2: spriteNum_for_standing_animation = 3; //System.out.println("spriteNum_for_standing_animation = " + spriteNum_for_standing_animation); break; case 3: spriteNum_for_standing_animation = 4; //System.out.println("spriteNum_for_standing_animation = " + spriteNum_for_standing_animation); break; case 4: spriteNum_for_standing_animation = 5; //System.out.println("spriteNum_for_standing_animation = " + spriteNum_for_standing_animation); break; case 5: spriteNum_for_standing_animation = 6; //System.out.println("spriteNum_for_standing_animation = " + spriteNum_for_standing_animation); break; case 6: spriteNum_for_standing_animation = 1; //System.out.println("spriteNum_for_standing_animation = " + spriteNum_for_standing_animation); break; } spriteCounter_for_idle = 0; } } if(keyH.upPressed == true || keyH.downPressed == true || keyH.leftPressed == true || keyH.rightPressed == true) if(keyH.attack == false) { if(keyH.upPressed == true) { direction ="up"; //to 0,0 se x,y sto JPanel einai h pano goneia aristera //Den xreiazete pleon einai sto switch kato -> WorldY = WorldY - speed; //an paei pano tote to Y mikrenei } if(keyH.upPressed == true && keyH.leftPressed == true) { upleft(); } if(keyH.upPressed == true && keyH.rightPressed == true) { upright(); } if(keyH.downPressed == true) { direction = "down"; //Den xreiazete pleon einai sto switch kato -> WorldY = WorldY + speed; } if(keyH.downPressed == true && keyH.leftPressed == true) { downleft(); } if(keyH.downPressed == true && keyH.rightPressed == true) { downright(); } if(keyH.leftPressed == true) { direction = "left"; //Den xreiazete pleon einai sto switch kato -> WorldX = WorldX - speed; } if(keyH.rightPressed == true) { direction = "right"; //Den xreiazete pleon einai sto switch kato -> WorldX = WorldX + speed; } // // edo vlepoume an ginete collision tou player(to rectagle) me tile to ensomati playercollision = false; //einai sto Entity.Entity class to boolean gp.collisionChecker.checkTile(this); //elenxoume to collition me ta objects int objindex = gp.collisionChecker.checkObjectCollition(this, true); //to ...this... leei dixnei oti to entity einai o player kai to ....true.... einai to boolean tou player. Gia na katalaveis des to funciton pickUpObject(objindex); // an to colition einai lados tote o player mporei na kinidei if(playercollision == false && keyH.attack == false) { switch(direction) { case "up": WorldY = WorldY - (speed * 2); //Για 60fps πρεπει να ειναι (speed x 1) break; case "down": WorldY = WorldY + (speed * 2); break; case "left": WorldX = WorldX - (speed * 2); break; case "right": WorldX = WorldX + (speed * 2); break; case "none": //epeidi einai to standing apla den kinite lol break; } } spriteCounter++; if(spriteCounter > 5) { switch(spriteNum) { case 1: spriteNum = 2; //System.out.println("spriteNum = " + spriteNum); break; case 2: spriteNum = 3; //System.out.println("spriteNum = " + spriteNum); break; case 3: spriteNum = 4; //System.out.println("spriteNum = " + spriteNum); break; case 4: spriteNum = 5; //System.out.println("spriteNum = " + spriteNum); break; case 5: spriteNum = 6; //System.out.println("spriteNum = " + spriteNum); break; case 6: spriteNum = 1; //System.out.println("spriteNum = " + spriteNum); break; } spriteCounter = 0; } } } public void pickUpObject(int i) { if(i != 999) { String objectName = gp.obj[i].name; switch(objectName) { case "key": hasKey++; gp.obj[i] = null; System.out.println("Player has " + hasKey + " keys"); break; case "door": if(hasKey > 0) { gp.obj[i] = null; hasKey--; } System.out.println("Player has " + hasKey + " keys"); break; } } } public void draw(Graphics2D g2) { BufferedImage image = null; switch(direction) { case "up": switch(previous_direction) { case "left": width = -gp.tileSize; ScreenX_for_drawing_player = screenX + gp.tileSize; if(spriteNum == 1) { image = left1; } if(spriteNum == 2) { image = left2; } if(spriteNum == 3) { image = left3; } if(spriteNum == 4) { image = left4; } if(spriteNum == 5) { image = left5; } if(spriteNum == 6) { image = left6; } break; case "right": width = gp.tileSize; ScreenX_for_drawing_player = screenX; if(spriteNum == 1) { image = right1; } if(spriteNum == 2) { image = right2; } if(spriteNum == 3) { image = right3; } if(spriteNum == 4) { image = right4; } if(spriteNum == 5) { image = right5; } if(spriteNum == 6) { image = right6; } break; } break; case "down": switch(previous_direction) { case "left": width = -gp.tileSize; ScreenX_for_drawing_player = screenX + gp.tileSize; if(spriteNum == 1) { image = left1; } if(spriteNum == 2) { image = left2; } if(spriteNum == 3) { image = left3; } if(spriteNum == 4) { image = left4; } if(spriteNum == 5) { image = left5; } if(spriteNum == 6) { image = left6; } break; case "right": width = gp.tileSize; ScreenX_for_drawing_player = screenX; if(spriteNum == 1) { image = right1; } if(spriteNum == 2) { image = right2; } if(spriteNum == 3) { image = right3; } if(spriteNum == 4) { image = right4; } if(spriteNum == 5) { image = right5; } if(spriteNum == 6) { image = right6; } break; } break; case "left": case "up-left": width = -gp.tileSize; ScreenX_for_drawing_player = screenX + gp.tileSize; previous_direction = "left"; if(spriteNum == 1) { image = left1; } if(spriteNum == 2) { image = left2; } if(spriteNum == 3) { image = left3; } if(spriteNum == 4) { image = left4; } if(spriteNum == 5) { image = left5; } if(spriteNum == 6) { image = left6; } break; case "right": width = gp.tileSize; ScreenX_for_drawing_player = screenX; previous_direction = "right"; if(spriteNum == 1) { image = right1; } if(spriteNum == 2) { image = right2; } if(spriteNum == 3) { image = right3; } if(spriteNum == 4) { image = right4; } if(spriteNum == 5) { image = right5; } if(spriteNum == 6) { image = right6; } break; case "none": switch(previous_direction) { case "left": width = -gp.tileSize; ScreenX_for_drawing_player = screenX + gp.tileSize; if(spriteNum_for_standing_animation == 1) { image = standing1; } if(spriteNum_for_standing_animation == 2) { image = standing2; } if(spriteNum_for_standing_animation == 3) { image = standing3; } if(spriteNum_for_standing_animation == 4) { image = standing4; } if(spriteNum_for_standing_animation == 5) { image = standing5; } if(spriteNum_for_standing_animation == 6) { image = standing6; } break; case "right": width = gp.tileSize; ScreenX_for_drawing_player = screenX; if(spriteNum_for_standing_animation == 1) { image = standing1; } if(spriteNum_for_standing_animation == 2) { image = standing2; } if(spriteNum_for_standing_animation == 3) { image = standing3; } if(spriteNum_for_standing_animation == 4) { image = standing4; } if(spriteNum_for_standing_animation == 5) { image = standing5; } if(spriteNum_for_standing_animation == 6) { image = standing6; } break; } break; case "attack": switch(previous_direction) { case "left": width = -gp.tileSize; ScreenX_for_drawing_player = screenX + gp.tileSize; if(spriteNum_for_attack == 1) { image = fight1; } if(spriteNum_for_attack == 2) { image = fight2; } if(spriteNum_for_attack == 3) { image = fight3; } if(spriteNum_for_attack == 4) { image = fight4; } break; case "right": width = gp.tileSize; ScreenX_for_drawing_player = screenX; if(spriteNum_for_attack == 1) { image = fight1; } if(spriteNum_for_attack == 2) { image = fight2; } if(spriteNum_for_attack == 3) { image = fight3; } if(spriteNum_for_attack == 4) { image = fight4; } break; } break; } height = gp.tileSize; g2.drawImage(image, ScreenX_for_drawing_player, screenY, width, height, null); } }
3353_31
/* * * ToxOtis * * ToxOtis is the Greek word for Sagittarius, that actually means ‘archer’. ToxOtis * is a Java interface to the predictive toxicology services of OpenTox. ToxOtis is * being developed to help both those who need a painless way to consume OpenTox * services and for ambitious service providers that don’t want to spend half of * their time in RDF parsing and creation. * * Copyright (C) 2009-2010 Pantelis Sopasakis & Charalampos Chomenides * * 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: * Pantelis Sopasakis * [email protected] * Address: Iroon Politechniou St. 9, Zografou, Athens Greece * tel. +30 210 7723236 * */ package org.opentox.toxotis.persistence; import java.io.File; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import org.apache.log4j.Logger; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.opentox.toxotis.client.VRI; import org.opentox.toxotis.client.collection.Services; import org.opentox.toxotis.core.component.Algorithm; import org.opentox.toxotis.core.component.BibTeX; import org.opentox.toxotis.core.component.Dataset; import org.opentox.toxotis.core.component.Model; import org.opentox.toxotis.core.component.Task; import org.opentox.toxotis.ontology.collection.OTClasses; import org.opentox.toxotis.persistence.db.RegisterTool; import org.opentox.toxotis.persistence.util.HibernateUtil; import org.opentox.toxotis.util.aa.AuthenticationToken; /** * * @author Pantelis Sopasakis * @author Charalampos Chomenides */ public class Persist { public static void main(String[] args) throws Exception { // org.apache.log4j.LogManager.resetConfiguration(); // org.apache.log4j.PropertyConfigurator.configure("config/log4j.properties"); int x = 100; SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); // Question: How can we know if the database is newly created? // (In order to know whether we have to execute the following lines...) final boolean doAlter = true; System.out.println(x); if (doAlter) { try { Connection c = session.connection(); Statement stmt = c.createStatement(); stmt.addBatch("ALTER TABLE FeatOntol DROP PRIMARY KEY"); stmt.addBatch("ALTER TABLE FeatOntol ADD `ID_W` INT NOT NULL AUTO_INCREMENT PRIMARY KEY"); stmt.addBatch("ALTER TABLE OTComponent ADD `created` TIMESTAMP NOT NULL DEFAULT NOW()"); stmt.addBatch("ALTER TABLE User ADD `created` TIMESTAMP NOT NULL DEFAULT NOW()"); stmt.executeBatch(); } catch (HibernateException hbe) { hbe.printStackTrace(); } catch (SQLException sqle) { System.err.println("Info: Alter failed (Probably not an error!)"); Logger.getLogger(Persist.class).debug("Alter failed (Probably not an error!)", sqle); } catch (Exception e) { e.printStackTrace(); } } /* * OPEN SESSION */ session = sf.openSession(); // DeleteTool.deleteTask(session, Task.Status.RUNNING, Task.Status.QUEUED); // System.out.println("Storing Ontological Classes"); // RegisterTool.storeAllOntClasses(session); // System.out.println("Ontological Classes stored successfully!\n"); //// // System.out.println("Acquiring Token..."); // AuthenticationToken at = new AuthenticationToken(new File("/home/chung/toxotisKeys/my.key")); // System.out.println("Done!"); // System.out.println("Authentication Token : \n" + at); // System.out.println("User:\n" + at.getUser()); // // System.out.println("Loading Algorithm"); // Algorithm algorithm = new Algorithm(Services.ntua().augment("algorithm", "svm")).loadFromRemote(at); // System.out.println("Algorithm Loaded"); // System.out.println("Storing Algorithm"); // RegisterTool.storeAlgorithm(algorithm, session); // System.out.println("Algorithm registered successfully!\n"); //// // System.out.println("Loading Dataset"); // Dataset d = new Dataset(Services.ideaconsult().augment("dataset", "9").addUrlParameter("max", "5")).loadFromRemote(); // System.out.println("Dataset Loaded"); // System.out.println("Storing Dataset"); // RegisterTool.storeDataset(d, session); // System.out.println("Dataset registered successfully!\n"); //// // System.out.println("Loading Model"); // Model model = new Model(Services.ntua().augment("model", "934ef1d0-2080-48eb-9f65-f61b830b5783")).loadFromRemote(); // model.setActualModel(new java.net.URI("http://in.gr/#asdf")); // System.out.println("Model Loaded"); // System.out.println("Storing Model"); // RegisterTool.storeModel(model, session); // System.out.println("Model registered successfully!\n"); // //// // System.out.println("Loading Tasks"); // Task task_complete = new Task(Services.ntua().augment("task", "68d471ad-0287-4f6e-a200-244d0234e8a1")).loadFromRemote(at); // System.out.println("Task #1 Loaded"); // Task task_error = new Task(Services.ntua().augment("task", "0980cbb3-a4a8-4a89-8538-51992d2fc67f")).loadFromRemote(at); // System.out.println("Task #2 Loaded"); // System.out.println("Storing Tasks"); // RegisterTool.storeTask(session, task_complete); // System.out.println("Task #1 registered successfully!"); // RegisterTool.storeTask(session, task_error); // System.out.println("Task #2 registered successfully!"); // System.out.println(); // // BibTeX b = new BibTeX(Services.ntua().augment("bibtex", "1")); // b.setAnnotation("asdf"); // b.setAuthor("gdfgfdg"); // RegisterTool.storeBibTeX(session, b); // /* // * For more info about criteria read: // * http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querycriteria.html // */ // System.out.println(OTClasses.Algorithm()); // List resultsFoundInDB = session.createCriteria(Algorithm.class).list(); //// add(Restrictions.like("uri", "%svm")).list(); // System.out.println("found " + resultsFoundInDB.size()); // for (Object o : resultsFoundInDB) { // Algorithm a = (Algorithm) o; // VRI c = a.getUri(); // System.out.println(c); // } // session.close(); } } // Όταν μεγαλώσω θέλω, // θέλω να γίνω 82 χρονών // τσατσά σ'ένα μπουρδέλο // χωρίς δόντια να μασάω τα κρουτόν // και να διαβάζω Οθέλο // // Όταν μεγαλώσω θέλω // θελώ να γίνω διαστημικός σταθμός // και να παίζω μπουγέλο // κι από μένανε να βρέχει κι ο ουρανός // τα ρούχα να σας πλένω // // Η ομορφιά του θέλω, // Μάρω Μαρκέλου //
alphaville/ToxOtis
ToxOtis-persistence/src/main/java/org/opentox/toxotis/persistence/Persist.java
2,365
// θέλω να γίνω 82 χρονών
line_comment
el
/* * * ToxOtis * * ToxOtis is the Greek word for Sagittarius, that actually means ‘archer’. ToxOtis * is a Java interface to the predictive toxicology services of OpenTox. ToxOtis is * being developed to help both those who need a painless way to consume OpenTox * services and for ambitious service providers that don’t want to spend half of * their time in RDF parsing and creation. * * Copyright (C) 2009-2010 Pantelis Sopasakis & Charalampos Chomenides * * 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: * Pantelis Sopasakis * [email protected] * Address: Iroon Politechniou St. 9, Zografou, Athens Greece * tel. +30 210 7723236 * */ package org.opentox.toxotis.persistence; import java.io.File; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import org.apache.log4j.Logger; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.opentox.toxotis.client.VRI; import org.opentox.toxotis.client.collection.Services; import org.opentox.toxotis.core.component.Algorithm; import org.opentox.toxotis.core.component.BibTeX; import org.opentox.toxotis.core.component.Dataset; import org.opentox.toxotis.core.component.Model; import org.opentox.toxotis.core.component.Task; import org.opentox.toxotis.ontology.collection.OTClasses; import org.opentox.toxotis.persistence.db.RegisterTool; import org.opentox.toxotis.persistence.util.HibernateUtil; import org.opentox.toxotis.util.aa.AuthenticationToken; /** * * @author Pantelis Sopasakis * @author Charalampos Chomenides */ public class Persist { public static void main(String[] args) throws Exception { // org.apache.log4j.LogManager.resetConfiguration(); // org.apache.log4j.PropertyConfigurator.configure("config/log4j.properties"); int x = 100; SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); // Question: How can we know if the database is newly created? // (In order to know whether we have to execute the following lines...) final boolean doAlter = true; System.out.println(x); if (doAlter) { try { Connection c = session.connection(); Statement stmt = c.createStatement(); stmt.addBatch("ALTER TABLE FeatOntol DROP PRIMARY KEY"); stmt.addBatch("ALTER TABLE FeatOntol ADD `ID_W` INT NOT NULL AUTO_INCREMENT PRIMARY KEY"); stmt.addBatch("ALTER TABLE OTComponent ADD `created` TIMESTAMP NOT NULL DEFAULT NOW()"); stmt.addBatch("ALTER TABLE User ADD `created` TIMESTAMP NOT NULL DEFAULT NOW()"); stmt.executeBatch(); } catch (HibernateException hbe) { hbe.printStackTrace(); } catch (SQLException sqle) { System.err.println("Info: Alter failed (Probably not an error!)"); Logger.getLogger(Persist.class).debug("Alter failed (Probably not an error!)", sqle); } catch (Exception e) { e.printStackTrace(); } } /* * OPEN SESSION */ session = sf.openSession(); // DeleteTool.deleteTask(session, Task.Status.RUNNING, Task.Status.QUEUED); // System.out.println("Storing Ontological Classes"); // RegisterTool.storeAllOntClasses(session); // System.out.println("Ontological Classes stored successfully!\n"); //// // System.out.println("Acquiring Token..."); // AuthenticationToken at = new AuthenticationToken(new File("/home/chung/toxotisKeys/my.key")); // System.out.println("Done!"); // System.out.println("Authentication Token : \n" + at); // System.out.println("User:\n" + at.getUser()); // // System.out.println("Loading Algorithm"); // Algorithm algorithm = new Algorithm(Services.ntua().augment("algorithm", "svm")).loadFromRemote(at); // System.out.println("Algorithm Loaded"); // System.out.println("Storing Algorithm"); // RegisterTool.storeAlgorithm(algorithm, session); // System.out.println("Algorithm registered successfully!\n"); //// // System.out.println("Loading Dataset"); // Dataset d = new Dataset(Services.ideaconsult().augment("dataset", "9").addUrlParameter("max", "5")).loadFromRemote(); // System.out.println("Dataset Loaded"); // System.out.println("Storing Dataset"); // RegisterTool.storeDataset(d, session); // System.out.println("Dataset registered successfully!\n"); //// // System.out.println("Loading Model"); // Model model = new Model(Services.ntua().augment("model", "934ef1d0-2080-48eb-9f65-f61b830b5783")).loadFromRemote(); // model.setActualModel(new java.net.URI("http://in.gr/#asdf")); // System.out.println("Model Loaded"); // System.out.println("Storing Model"); // RegisterTool.storeModel(model, session); // System.out.println("Model registered successfully!\n"); // //// // System.out.println("Loading Tasks"); // Task task_complete = new Task(Services.ntua().augment("task", "68d471ad-0287-4f6e-a200-244d0234e8a1")).loadFromRemote(at); // System.out.println("Task #1 Loaded"); // Task task_error = new Task(Services.ntua().augment("task", "0980cbb3-a4a8-4a89-8538-51992d2fc67f")).loadFromRemote(at); // System.out.println("Task #2 Loaded"); // System.out.println("Storing Tasks"); // RegisterTool.storeTask(session, task_complete); // System.out.println("Task #1 registered successfully!"); // RegisterTool.storeTask(session, task_error); // System.out.println("Task #2 registered successfully!"); // System.out.println(); // // BibTeX b = new BibTeX(Services.ntua().augment("bibtex", "1")); // b.setAnnotation("asdf"); // b.setAuthor("gdfgfdg"); // RegisterTool.storeBibTeX(session, b); // /* // * For more info about criteria read: // * http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querycriteria.html // */ // System.out.println(OTClasses.Algorithm()); // List resultsFoundInDB = session.createCriteria(Algorithm.class).list(); //// add(Restrictions.like("uri", "%svm")).list(); // System.out.println("found " + resultsFoundInDB.size()); // for (Object o : resultsFoundInDB) { // Algorithm a = (Algorithm) o; // VRI c = a.getUri(); // System.out.println(c); // } // session.close(); } } // Όταν μεγαλώσω θέλω, // θέλω να<SUF> // τσατσά σ'ένα μπουρδέλο // χωρίς δόντια να μασάω τα κρουτόν // και να διαβάζω Οθέλο // // Όταν μεγαλώσω θέλω // θελώ να γίνω διαστημικός σταθμός // και να παίζω μπουγέλο // κι από μένανε να βρέχει κι ο ουρανός // τα ρούχα να σας πλένω // // Η ομορφιά του θέλω, // Μάρω Μαρκέλου //
41_20
import java.util.ArrayList; import java.util.Objects; public class Knn { int k; ArrayList<LeafRecords> kontinotera; R_Tree rTree; Double maxApostash; LeafRecords x;//Σημειο απο το οποιο ψαχνω τους κοντινοτερους. public Knn(R_Tree rTree) { this.rTree = rTree; this.k=0; this.kontinotera=new ArrayList<>(); loadKontinotera(); } public Knn(int k, R_Tree rTree,LeafRecords x) { this.k = k; this.rTree = rTree; this.x=x; this.kontinotera=new ArrayList<>(); loadKontinotera(); } public ArrayList<LeafRecords> isTouching(R_Tree tree,ArrayList<MBR> nextlevel) { ArrayList<Nodes> tmp=tree.getAllNodes(); if(nextlevel.isEmpty()) { return kontinotera; } if(nextlevel.get(0).isLeafRect())//Εαν ειναι φυλλα βρες την αποσταση του φυλλου με το Χ. Κρατα αποσταση την αποσταση του mbr που ειναι φυλλο σε σχεση με το σημειο Χ. { Double min=distMbrToPoint(nextlevel.get(0),x); MBR mbrKeep=nextlevel.get(0);//kontinotero mbr for(MBR mbr:nextlevel) { if(distMbrToPoint(mbr,x) < min) { min=distMbrToPoint(mbr,x); mbrKeep=mbr; } } //Παιρνει το περιεχομενο του φυλλου. Βλεπει την αποσταση απο το Χ. Βρισκει το μακρυτερο φυλλο απο τα kontinotera (χαζο array γεματο με τυχαια σημεια) //Και εαν το φυλλο ειναι μικροτερο απο το μεγαλυτερο του kontinotera κανει αντικατασταση. for(LeafRecords leaf:mbrKeep.getPeriexomeno())//περιεχομενο του κοντινοτερου mbr. { // System.out.println("------To mbr einai:"); // mbrKeep.printRect(); Double apost=distManhattan(leaf,x); LeafRecords maxLeaf=findMax(kontinotera,x);//Βρες το μεγαλυτερο απο τα κοντινοτερα Double maxApost=distManhattan(maxLeaf,x); if(apost<maxApost)//Εαν βρήκες καποιο ποιο κοντινο απο το μεγαλυτερο της λιστας κανε την αντικατασταση. { if(!isIn(leaf))//εαν δεν ειναι ηδη μεσα το σημειο { kontinotera.remove(maxLeaf); kontinotera.add(leaf); } } } //Εδω φτιαχνω τον κυκλο με κεντρο το Χ και ακτινα το μακρυτερο απο την λιστα kontinotera... LeafRecords distanceLeaf = findMax(kontinotera,x); Double distanceCircle=distManhattan(distanceLeaf,x); for(MBR m:nextlevel)//Κοιταει με τα αλλα φυλλα { if(distMbrToPoint(m,x) < distanceCircle && !Objects.equals(m.getId(), mbrKeep.getId()))//Εαν καποιο αλλο Mbr(φυλλο) είναι μεσα στον κυκλο που δημιουργησα. { for(LeafRecords leaf:m.getPeriexomeno()) { Double perApost=distManhattan(leaf,x); LeafRecords maxLeaf=findMax(kontinotera,x);//Βρες το μεγαλυτερο απο τα κοντινοτερα Double maxApost=distManhattan(maxLeaf,x); if(perApost<maxApost)//Εαν βρήκες καποιο ποιο κοντινο απο το μεγαλυτερο της λιστας κανε την αντικατασταση. { if(!isIn(leaf))//εαν δεν ειναι ηδη μεσα το σημειο { kontinotera.remove(maxLeaf); kontinotera.add(leaf); } } } } } // //Εχει κανει τον κυκλο και το παει απο την αρχη για να τσεκαρει εαν ο κυκλο τεμνει σε καποιο αλλο mbr(mbr γενικα οχι μονο τα φυλλα) // isInCircle(findMax(kontinotera,x),rTree.getRoot());//ενημερωνει τα kontinotera αφου εχει γινει ο κυκλος } Double tmpDist=distMbrToPoint(nextlevel.get(0),x); MBR tmpMbr=nextlevel.get(0);//kontinotero mbr ArrayList<MBR> toVisit=new ArrayList<>(); for(MBR m:nextlevel) { Double dist =distMbrToPoint(m,x); if(dist<=tmpDist) { tmpDist=dist; tmpMbr=m; toVisit.add(tmpMbr); } } for(MBR mp:toVisit) { ArrayList<MBR> kidss=tree.findKids(mp).allRectangles; isTouching(tree,kidss); } return kontinotera; } public boolean isInCircle(Nodes nextlevel)//1η φορα το nextlevel θα ειναι το root { LeafRecords makritero=findMax(kontinotera,x); //range Circle Double maxDist=distManhattan(makritero,x); if(nextlevel.getAllRectangles().get(0).isLeafRect()) { for(MBR mbr:nextlevel.getAllRectangles()){ for(LeafRecords leaf: mbr.getPeriexomeno()) { Double leafDist=distManhattan(leaf,x); if(leafDist<maxDist) { if(!isIn(leaf))//εαν δεν ειναι ηδη μεσα το σημειο { kontinotera.remove(findMax(kontinotera,x)); kontinotera.add(leaf); } } } } return true; } //Nodes root = rTree.getRoot(); for(MBR m: nextlevel.getAllRectangles()) { Double apostMbr=distMbrToPoint(m,x); if(apostMbr<maxDist)///εαν ειναι μεσα στον κυκλο { Nodes kids=rTree.findKids(m); return isInCircle(kids); } else { return false; } } return false; } /** * Βαλε τυχαια leafrecord στην λιστα kontinotera τα οποια μετα θα τα αλλαζει με τα οντως κοντινοτερα του. */ public void loadKontinotera() { int p=0; for(Nodes nodes:rTree.getAllNodes()) { for(MBR mbr:nodes.getAllRectangles()) { for(LeafRecords leaf:mbr.getPeriexomeno()) { if(p<k) { kontinotera.add(leaf); p++; } } } } } public boolean isIn(LeafRecords x) { for(LeafRecords leaf:kontinotera) { if(Objects.equals(leaf.getDiastaseis().get(0), x.diastaseis.get(0)) && (Objects.equals(leaf.getDiastaseis().get(1), x.diastaseis.get(1)))) { return true; } } return false; } /** *Εστω Χ το σημείο που ψαχνουμε τους γειτονες του. Βαζω τυχαια το 1ο σημειο στο maxleaf και στο Max την αποστασση του απο το Χ. * Συγκρινε το με ολα τα αλλα και βρες το max. * TO DO:Πρεπει να το κανω να βρισκει το Κ μακρυτερο, και οχι το μακρυτερο γενικα. */ public LeafRecords findMax(ArrayList<LeafRecords> k,LeafRecords x) { LeafRecords maxleaf= k.get(0); //Double max=dummy.distance(maxleaf.getDiastaseis().get(0),maxleaf.getDiastaseis().get(1),x.getDiastaseis().get(0),x.getDiastaseis().get(1)); Double max=distManhattan(maxleaf,x); for(LeafRecords leaf:k) { // Double tmp=dummy.distance(leaf.getDiastaseis().get(0),leaf.getDiastaseis().get(1),x.getDiastaseis().get(0),x.getDiastaseis().get(1)); Double tmp=distManhattan(leaf,x); if(tmp>max) { max=tmp; maxleaf=leaf; } } return maxleaf; } //Επεστρεψε το μεγαλυτερο Χ του ορθογωνιου (πανω αριστερα γωνια το Χ) public Double findMaxX(MBR mbr) { return mbr.diastaseisB.get(0); } //Επεστρεψε το μικροτερο Χ του ορθογωνιου (κατω αριστερα γωνια το Χ) public Double findMinX(MBR mbr) { return mbr.diastaseisA.get(0); } //Επεστρεψε το μεγαλυτερο Χ του ορθογωνιου (πανω αριστερα γωνια το Χ) public Double findMaxY(MBR mbr) { return mbr.diastaseisB.get(1); } //Επεστρεψε το μικροτερο Χ του ορθογωνιου (κατω αριστερα γωνια το Χ) public Double findMinY(MBR mbr) { return mbr.diastaseisA.get(1); } //Εάν το Χ του σημείου μου είναι ανάμεασα στα Χ του ορθογωνίου(ανάμεσα στο μικρότερο και στο μεγαλύτερο του ορθογωνίου) public boolean isXbetween(LeafRecords x,MBR mbr) { Double min=findMinX(mbr); Double max=findMaxX(mbr); Double pointX=x.diastaseis.get(0); if(pointX>min && pointX<max) { return true; } return false; } //Εάν το Y του σημείου μου είναι ανάμεασα στα Y του ορθογωνίου(ανάμεσα στο μικρότερο και στο μεγαλύτερο του ορθογωνίου) public boolean isYbetween(LeafRecords x,MBR mbr) { Double min=findMinY(mbr); Double max=findMaxY(mbr); Double pointY=x.diastaseis.get(1); if(pointY>min && pointY<max) { return true; } return false; } //Απόσταση ενός σημείο από ένα ορθογώνιο με 9 περιπτώσεις public Double distMbrToPoint(MBR mbr,LeafRecords x) { Double apostasi=-1.0; Double pointX=x.diastaseis.get(0); Double pointY=x.diastaseis.get(1); //Σημείο του ορθογωνίου που θα παρούμε την απόσταση. LeafRecords pointOfMbr=new LeafRecords("rect",1.0,1.0); if(pointX<findMinX(mbr))//Έαν το Χ του σημείου μας είναι πιο μικρό από το μικρότερο Χ του ορθογωνίου. Το σημείο είναι στα αρίστερα του ορθογωνίου. { if(pointY<findMinY(mbr))//Το σημέιο έχει μικρότερο Χ και Υ. { //Δημιουργώ ένα σημείο που θα αναπαραστεί την κάτω αρίστερα γωνία. pointOfMbr.diastaseis.set(0,findMinX(mbr)); pointOfMbr.diastaseis.set(1,findMinY(mbr)); apostasi=distManhattan(x,pointOfMbr); } else if(isYbetween(x,mbr))//Το σημέιο έχει μικρότερο Χ αλλα το Υ του είναι ανάμεσα σε αυτά του ορθογωνίου. { //Δημιουργώ ένα σημείο του ορθογωνίου που θα αναπαραστεί κάποιο με το μικρότερο Χ. και Υ ανάμεσα του ορθωγωνίου . pointOfMbr.diastaseis.set(0,findMinX(mbr));//ελάχιστο Χ pointOfMbr.diastaseis.set(1,x.diastaseis.get(1)); //Υ ίδιο με το σημείο (γιατί είναι ανάμεσα στα όρια) apostasi=distManhattan(x,pointOfMbr); } else if(pointY>findMaxY(mbr))//Το σημέιο έχει μικρότερο Χ αλλα μεγαλύτερο Υ. { //Δημιουργώ ένα σημείο που θα αναπαραστεί την πάνω αρίστερα γωνία. pointOfMbr.diastaseis.set(0,findMinX(mbr));//Ελάχιστο Χ pointOfMbr.diastaseis.set(1,findMaxY(mbr));//Μέγιστο Υ apostasi=distManhattan(x,pointOfMbr); } } else if(isXbetween(x,mbr))//Έαν το Χ του σημείου μας είναι ανάμεσα στα Χ του ορθογωνίου. { if(pointY<findMinY(mbr))//Εαν το Χ του σημείου είναι ανάμεσα αλλα το Υ είναι μικρότερο (του ορθογωνίου) α32 { //Δημιουργώ ένα σημείο του ορθογωνίου που θα αναπαραστεί κάποιο με το μικρότερο Υ. και Χ ανάμεσα του ορθωγωνίου . pointOfMbr.diastaseis.set(0,x.diastaseis.get(0));//Χ το ίδιο με το σημείο (γιατί είναι ανάμεσα στα όρια) pointOfMbr.diastaseis.set(1,findMinY(mbr));//Ελάχιστο Y apostasi=distManhattan(x,pointOfMbr); } else if(isYbetween(x,mbr))//Έαν το Χ και το Υ του σημείου είναι ανάμεσα σε αυτά του ορθογωνίου (πρακτικά να είναι μέσα στο ορθογώνιο) α22 { apostasi=0.0;//Είναι μέσα στο ορθογώνιο. } else if(pointY>findMaxY(mbr))//Εαν το Χ του σημείου είναι ανάμεσα αλλα το Υ είναι μεγαλύτερο (του ορθογωνίου) α12 { //Δημιουργώ ένα σημείο του ορθογωνίου που θα αναπαραστεί κάποιο με το μεγαλύτερο Υ. και Χ ανάμεσα στα ορια του ορθωγωνίου . pointOfMbr.diastaseis.set(0,x.diastaseis.get(0));//Χ το ίδιο με το σημείο (γιατί είναι ανάμεσα στα όρια) pointOfMbr.diastaseis.set(1,findMaxY(mbr));//Μέγιστο Y. apostasi=distManhattan(x,pointOfMbr); } } else if(pointX>findMaxX(mbr))//Έαν το Χ του σημείου μας είναι πιο μεγάλο από το μεγαλύτερο Χ του ορθογωνίου. Το σημείο είναι στα δεξία του ορθογωνίου. { if(pointY<findMinY(mbr))//Το σημέιο έχει μεγαλύτερο Χ και μικρότερο Υ. { //Δημιουργώ ένα σημείο που θα αναπαραστεί την κάτω δεξία γωνία . pointOfMbr.diastaseis.set(0,findMaxX(mbr));//Μέγιστο Χ pointOfMbr.diastaseis.set(1,findMinY(mbr));//Ελάχιστο Y apostasi=distManhattan(x,pointOfMbr); } else if(isYbetween(x,mbr))//Το σημέιο έχει μεγαλύτερο Χ αλλα το Υ είναι ανάμεσα σε αύτα του ορθογωνίου. { //Δημιουργώ ένα σημείο του ορθογωνίου που θα αναπαραστεί κάποιο με το μεγαλύτερο X. και Y ανάμεσα του ορθωγωνίου . pointOfMbr.diastaseis.set(0,findMaxX(mbr));//Μέγιστο Χ pointOfMbr.diastaseis.set(1,x.diastaseis.get(1));//Y το ίδιο με το σημείο (γιατί είναι ανάμεσα στα όρια) apostasi=distManhattan(x,pointOfMbr); } else if(pointY>findMaxY(mbr))//Το σημέιο έχει μεγαλύτερο Χ και Υ. { //Δημιουργώ ένα σημείο που θα αναπαραστεί την πάνω δεξία γωνία . pointOfMbr.diastaseis.set(0,findMaxX(mbr));//Μέγιστο Χ pointOfMbr.diastaseis.set(1,findMaxY(mbr));//Μέγιστο Y apostasi=distManhattan(x,pointOfMbr); } } return apostasi; } public Double distManhattan(LeafRecords a,LeafRecords b) { Double aX=a.diastaseis.get(0); Double aY=a.diastaseis.get(1); Double bX=b.diastaseis.get(0); Double bY=b.diastaseis.get(1); return Math.abs(aX - bX) + Math.abs(aY - bY); } /** * Εστω οτι το σημειο που ψαχνω τους γειτονες του ειναι το Χ. Για να βρω το κοντινοτερο ορθογωνιο του, θα παω να βαλω το Χ * μεσα σε ένα ορθογωνιο και θα δω ποσο μεγαλωσε η περιμετρος του. Επειτα θα επαναλαβω για καθε ορθογωνιο. Αυτο που μεγαλωσε * πιο λιγο ειναι και το κοντινοτερο του. */ /** public double apostasi(MBR data,LeafRecords x) { ArrayList<Double> newMbr=dummy.newCorners(data,x.getDiastaseis().get(0),x.getDiastaseis().get(1)); Double newPerimetros= dummy.perimeter(newMbr.get(0),newMbr.get(1),newMbr.get(2),newMbr.get(3)); Double oldPerimetow = dummy.perimeter(data.diastaseisA.get(0),data.diastaseisA.get(1),data.diastaseisB.get(0),data.diastaseisB.get(1)); return (newPerimetros-oldPerimetow)/2; } */ public void knnPrint() { System.out.println("-----------------------------------------------"); System.out.println("Knn of point"); int i=1; for(LeafRecords leaf:kontinotera) { System.out.println("K:"+i); i++; leaf.printRecord(); //Double apo= dummy.distance(leaf.getDiastaseis().get(0),leaf.getDiastaseis().get(1),x.getDiastaseis().get(0),x.getDiastaseis().get(1)); Double apo=distManhattan(leaf,x); System.out.println("----Distance between leaf and Point:"+apo); } } public boolean otinanaiIsIn(LeafRecords x,ArrayList<LeafRecords> otinanai) { for(LeafRecords leaf:otinanai) { if(Objects.equals(leaf.getDiastaseis().get(0), x.diastaseis.get(0)) && (Objects.equals(leaf.getDiastaseis().get(1), x.diastaseis.get(1)))) { return true; } } return false; } public ArrayList<LeafRecords> knnSeiriaka(ArrayList<LeafRecords> otinanai) { AllBlocks allBlock=new AllBlocks(); ArrayList<Block> blocks=allBlock.readFromBinaryFile(); //Απο τα αρχειο τα διαβασα και τα εκανα απο Records--->LeafRecods ArrayList<LeafRecords> tmp=new ArrayList<>(); for(Block bl:blocks) { for(Record record:bl.getOneBlock()) { LeafRecords n=new LeafRecords(record); tmp.add(n); } } for(LeafRecords leaf:tmp) { Double apostLeaf=distManhattan(leaf,x); LeafRecords makri=findMax(otinanai,x); Double apostOtinanai=distManhattan(makri,x); if(apostLeaf<apostOtinanai) { if(!otinanaiIsIn(leaf,otinanai)) { otinanai.remove(makri); otinanai.add(leaf); } } } return otinanai; } public int getK() { return k; } public void setK(int k) { this.k = k; } public ArrayList<LeafRecords> getKontinotera() { return kontinotera; } public void setKontinotera(ArrayList<LeafRecords> kontinotera) { this.kontinotera = kontinotera; } public R_Tree getrTree() { return rTree; } public void setrTree(R_Tree rTree) { this.rTree = rTree; } }
ampatzidhs/R_tree
src/Knn.java
7,418
///εαν ειναι μεσα στον κυκλο
line_comment
el
import java.util.ArrayList; import java.util.Objects; public class Knn { int k; ArrayList<LeafRecords> kontinotera; R_Tree rTree; Double maxApostash; LeafRecords x;//Σημειο απο το οποιο ψαχνω τους κοντινοτερους. public Knn(R_Tree rTree) { this.rTree = rTree; this.k=0; this.kontinotera=new ArrayList<>(); loadKontinotera(); } public Knn(int k, R_Tree rTree,LeafRecords x) { this.k = k; this.rTree = rTree; this.x=x; this.kontinotera=new ArrayList<>(); loadKontinotera(); } public ArrayList<LeafRecords> isTouching(R_Tree tree,ArrayList<MBR> nextlevel) { ArrayList<Nodes> tmp=tree.getAllNodes(); if(nextlevel.isEmpty()) { return kontinotera; } if(nextlevel.get(0).isLeafRect())//Εαν ειναι φυλλα βρες την αποσταση του φυλλου με το Χ. Κρατα αποσταση την αποσταση του mbr που ειναι φυλλο σε σχεση με το σημειο Χ. { Double min=distMbrToPoint(nextlevel.get(0),x); MBR mbrKeep=nextlevel.get(0);//kontinotero mbr for(MBR mbr:nextlevel) { if(distMbrToPoint(mbr,x) < min) { min=distMbrToPoint(mbr,x); mbrKeep=mbr; } } //Παιρνει το περιεχομενο του φυλλου. Βλεπει την αποσταση απο το Χ. Βρισκει το μακρυτερο φυλλο απο τα kontinotera (χαζο array γεματο με τυχαια σημεια) //Και εαν το φυλλο ειναι μικροτερο απο το μεγαλυτερο του kontinotera κανει αντικατασταση. for(LeafRecords leaf:mbrKeep.getPeriexomeno())//περιεχομενο του κοντινοτερου mbr. { // System.out.println("------To mbr einai:"); // mbrKeep.printRect(); Double apost=distManhattan(leaf,x); LeafRecords maxLeaf=findMax(kontinotera,x);//Βρες το μεγαλυτερο απο τα κοντινοτερα Double maxApost=distManhattan(maxLeaf,x); if(apost<maxApost)//Εαν βρήκες καποιο ποιο κοντινο απο το μεγαλυτερο της λιστας κανε την αντικατασταση. { if(!isIn(leaf))//εαν δεν ειναι ηδη μεσα το σημειο { kontinotera.remove(maxLeaf); kontinotera.add(leaf); } } } //Εδω φτιαχνω τον κυκλο με κεντρο το Χ και ακτινα το μακρυτερο απο την λιστα kontinotera... LeafRecords distanceLeaf = findMax(kontinotera,x); Double distanceCircle=distManhattan(distanceLeaf,x); for(MBR m:nextlevel)//Κοιταει με τα αλλα φυλλα { if(distMbrToPoint(m,x) < distanceCircle && !Objects.equals(m.getId(), mbrKeep.getId()))//Εαν καποιο αλλο Mbr(φυλλο) είναι μεσα στον κυκλο που δημιουργησα. { for(LeafRecords leaf:m.getPeriexomeno()) { Double perApost=distManhattan(leaf,x); LeafRecords maxLeaf=findMax(kontinotera,x);//Βρες το μεγαλυτερο απο τα κοντινοτερα Double maxApost=distManhattan(maxLeaf,x); if(perApost<maxApost)//Εαν βρήκες καποιο ποιο κοντινο απο το μεγαλυτερο της λιστας κανε την αντικατασταση. { if(!isIn(leaf))//εαν δεν ειναι ηδη μεσα το σημειο { kontinotera.remove(maxLeaf); kontinotera.add(leaf); } } } } } // //Εχει κανει τον κυκλο και το παει απο την αρχη για να τσεκαρει εαν ο κυκλο τεμνει σε καποιο αλλο mbr(mbr γενικα οχι μονο τα φυλλα) // isInCircle(findMax(kontinotera,x),rTree.getRoot());//ενημερωνει τα kontinotera αφου εχει γινει ο κυκλος } Double tmpDist=distMbrToPoint(nextlevel.get(0),x); MBR tmpMbr=nextlevel.get(0);//kontinotero mbr ArrayList<MBR> toVisit=new ArrayList<>(); for(MBR m:nextlevel) { Double dist =distMbrToPoint(m,x); if(dist<=tmpDist) { tmpDist=dist; tmpMbr=m; toVisit.add(tmpMbr); } } for(MBR mp:toVisit) { ArrayList<MBR> kidss=tree.findKids(mp).allRectangles; isTouching(tree,kidss); } return kontinotera; } public boolean isInCircle(Nodes nextlevel)//1η φορα το nextlevel θα ειναι το root { LeafRecords makritero=findMax(kontinotera,x); //range Circle Double maxDist=distManhattan(makritero,x); if(nextlevel.getAllRectangles().get(0).isLeafRect()) { for(MBR mbr:nextlevel.getAllRectangles()){ for(LeafRecords leaf: mbr.getPeriexomeno()) { Double leafDist=distManhattan(leaf,x); if(leafDist<maxDist) { if(!isIn(leaf))//εαν δεν ειναι ηδη μεσα το σημειο { kontinotera.remove(findMax(kontinotera,x)); kontinotera.add(leaf); } } } } return true; } //Nodes root = rTree.getRoot(); for(MBR m: nextlevel.getAllRectangles()) { Double apostMbr=distMbrToPoint(m,x); if(apostMbr<maxDist)///εαν ειναι<SUF> { Nodes kids=rTree.findKids(m); return isInCircle(kids); } else { return false; } } return false; } /** * Βαλε τυχαια leafrecord στην λιστα kontinotera τα οποια μετα θα τα αλλαζει με τα οντως κοντινοτερα του. */ public void loadKontinotera() { int p=0; for(Nodes nodes:rTree.getAllNodes()) { for(MBR mbr:nodes.getAllRectangles()) { for(LeafRecords leaf:mbr.getPeriexomeno()) { if(p<k) { kontinotera.add(leaf); p++; } } } } } public boolean isIn(LeafRecords x) { for(LeafRecords leaf:kontinotera) { if(Objects.equals(leaf.getDiastaseis().get(0), x.diastaseis.get(0)) && (Objects.equals(leaf.getDiastaseis().get(1), x.diastaseis.get(1)))) { return true; } } return false; } /** *Εστω Χ το σημείο που ψαχνουμε τους γειτονες του. Βαζω τυχαια το 1ο σημειο στο maxleaf και στο Max την αποστασση του απο το Χ. * Συγκρινε το με ολα τα αλλα και βρες το max. * TO DO:Πρεπει να το κανω να βρισκει το Κ μακρυτερο, και οχι το μακρυτερο γενικα. */ public LeafRecords findMax(ArrayList<LeafRecords> k,LeafRecords x) { LeafRecords maxleaf= k.get(0); //Double max=dummy.distance(maxleaf.getDiastaseis().get(0),maxleaf.getDiastaseis().get(1),x.getDiastaseis().get(0),x.getDiastaseis().get(1)); Double max=distManhattan(maxleaf,x); for(LeafRecords leaf:k) { // Double tmp=dummy.distance(leaf.getDiastaseis().get(0),leaf.getDiastaseis().get(1),x.getDiastaseis().get(0),x.getDiastaseis().get(1)); Double tmp=distManhattan(leaf,x); if(tmp>max) { max=tmp; maxleaf=leaf; } } return maxleaf; } //Επεστρεψε το μεγαλυτερο Χ του ορθογωνιου (πανω αριστερα γωνια το Χ) public Double findMaxX(MBR mbr) { return mbr.diastaseisB.get(0); } //Επεστρεψε το μικροτερο Χ του ορθογωνιου (κατω αριστερα γωνια το Χ) public Double findMinX(MBR mbr) { return mbr.diastaseisA.get(0); } //Επεστρεψε το μεγαλυτερο Χ του ορθογωνιου (πανω αριστερα γωνια το Χ) public Double findMaxY(MBR mbr) { return mbr.diastaseisB.get(1); } //Επεστρεψε το μικροτερο Χ του ορθογωνιου (κατω αριστερα γωνια το Χ) public Double findMinY(MBR mbr) { return mbr.diastaseisA.get(1); } //Εάν το Χ του σημείου μου είναι ανάμεασα στα Χ του ορθογωνίου(ανάμεσα στο μικρότερο και στο μεγαλύτερο του ορθογωνίου) public boolean isXbetween(LeafRecords x,MBR mbr) { Double min=findMinX(mbr); Double max=findMaxX(mbr); Double pointX=x.diastaseis.get(0); if(pointX>min && pointX<max) { return true; } return false; } //Εάν το Y του σημείου μου είναι ανάμεασα στα Y του ορθογωνίου(ανάμεσα στο μικρότερο και στο μεγαλύτερο του ορθογωνίου) public boolean isYbetween(LeafRecords x,MBR mbr) { Double min=findMinY(mbr); Double max=findMaxY(mbr); Double pointY=x.diastaseis.get(1); if(pointY>min && pointY<max) { return true; } return false; } //Απόσταση ενός σημείο από ένα ορθογώνιο με 9 περιπτώσεις public Double distMbrToPoint(MBR mbr,LeafRecords x) { Double apostasi=-1.0; Double pointX=x.diastaseis.get(0); Double pointY=x.diastaseis.get(1); //Σημείο του ορθογωνίου που θα παρούμε την απόσταση. LeafRecords pointOfMbr=new LeafRecords("rect",1.0,1.0); if(pointX<findMinX(mbr))//Έαν το Χ του σημείου μας είναι πιο μικρό από το μικρότερο Χ του ορθογωνίου. Το σημείο είναι στα αρίστερα του ορθογωνίου. { if(pointY<findMinY(mbr))//Το σημέιο έχει μικρότερο Χ και Υ. { //Δημιουργώ ένα σημείο που θα αναπαραστεί την κάτω αρίστερα γωνία. pointOfMbr.diastaseis.set(0,findMinX(mbr)); pointOfMbr.diastaseis.set(1,findMinY(mbr)); apostasi=distManhattan(x,pointOfMbr); } else if(isYbetween(x,mbr))//Το σημέιο έχει μικρότερο Χ αλλα το Υ του είναι ανάμεσα σε αυτά του ορθογωνίου. { //Δημιουργώ ένα σημείο του ορθογωνίου που θα αναπαραστεί κάποιο με το μικρότερο Χ. και Υ ανάμεσα του ορθωγωνίου . pointOfMbr.diastaseis.set(0,findMinX(mbr));//ελάχιστο Χ pointOfMbr.diastaseis.set(1,x.diastaseis.get(1)); //Υ ίδιο με το σημείο (γιατί είναι ανάμεσα στα όρια) apostasi=distManhattan(x,pointOfMbr); } else if(pointY>findMaxY(mbr))//Το σημέιο έχει μικρότερο Χ αλλα μεγαλύτερο Υ. { //Δημιουργώ ένα σημείο που θα αναπαραστεί την πάνω αρίστερα γωνία. pointOfMbr.diastaseis.set(0,findMinX(mbr));//Ελάχιστο Χ pointOfMbr.diastaseis.set(1,findMaxY(mbr));//Μέγιστο Υ apostasi=distManhattan(x,pointOfMbr); } } else if(isXbetween(x,mbr))//Έαν το Χ του σημείου μας είναι ανάμεσα στα Χ του ορθογωνίου. { if(pointY<findMinY(mbr))//Εαν το Χ του σημείου είναι ανάμεσα αλλα το Υ είναι μικρότερο (του ορθογωνίου) α32 { //Δημιουργώ ένα σημείο του ορθογωνίου που θα αναπαραστεί κάποιο με το μικρότερο Υ. και Χ ανάμεσα του ορθωγωνίου . pointOfMbr.diastaseis.set(0,x.diastaseis.get(0));//Χ το ίδιο με το σημείο (γιατί είναι ανάμεσα στα όρια) pointOfMbr.diastaseis.set(1,findMinY(mbr));//Ελάχιστο Y apostasi=distManhattan(x,pointOfMbr); } else if(isYbetween(x,mbr))//Έαν το Χ και το Υ του σημείου είναι ανάμεσα σε αυτά του ορθογωνίου (πρακτικά να είναι μέσα στο ορθογώνιο) α22 { apostasi=0.0;//Είναι μέσα στο ορθογώνιο. } else if(pointY>findMaxY(mbr))//Εαν το Χ του σημείου είναι ανάμεσα αλλα το Υ είναι μεγαλύτερο (του ορθογωνίου) α12 { //Δημιουργώ ένα σημείο του ορθογωνίου που θα αναπαραστεί κάποιο με το μεγαλύτερο Υ. και Χ ανάμεσα στα ορια του ορθωγωνίου . pointOfMbr.diastaseis.set(0,x.diastaseis.get(0));//Χ το ίδιο με το σημείο (γιατί είναι ανάμεσα στα όρια) pointOfMbr.diastaseis.set(1,findMaxY(mbr));//Μέγιστο Y. apostasi=distManhattan(x,pointOfMbr); } } else if(pointX>findMaxX(mbr))//Έαν το Χ του σημείου μας είναι πιο μεγάλο από το μεγαλύτερο Χ του ορθογωνίου. Το σημείο είναι στα δεξία του ορθογωνίου. { if(pointY<findMinY(mbr))//Το σημέιο έχει μεγαλύτερο Χ και μικρότερο Υ. { //Δημιουργώ ένα σημείο που θα αναπαραστεί την κάτω δεξία γωνία . pointOfMbr.diastaseis.set(0,findMaxX(mbr));//Μέγιστο Χ pointOfMbr.diastaseis.set(1,findMinY(mbr));//Ελάχιστο Y apostasi=distManhattan(x,pointOfMbr); } else if(isYbetween(x,mbr))//Το σημέιο έχει μεγαλύτερο Χ αλλα το Υ είναι ανάμεσα σε αύτα του ορθογωνίου. { //Δημιουργώ ένα σημείο του ορθογωνίου που θα αναπαραστεί κάποιο με το μεγαλύτερο X. και Y ανάμεσα του ορθωγωνίου . pointOfMbr.diastaseis.set(0,findMaxX(mbr));//Μέγιστο Χ pointOfMbr.diastaseis.set(1,x.diastaseis.get(1));//Y το ίδιο με το σημείο (γιατί είναι ανάμεσα στα όρια) apostasi=distManhattan(x,pointOfMbr); } else if(pointY>findMaxY(mbr))//Το σημέιο έχει μεγαλύτερο Χ και Υ. { //Δημιουργώ ένα σημείο που θα αναπαραστεί την πάνω δεξία γωνία . pointOfMbr.diastaseis.set(0,findMaxX(mbr));//Μέγιστο Χ pointOfMbr.diastaseis.set(1,findMaxY(mbr));//Μέγιστο Y apostasi=distManhattan(x,pointOfMbr); } } return apostasi; } public Double distManhattan(LeafRecords a,LeafRecords b) { Double aX=a.diastaseis.get(0); Double aY=a.diastaseis.get(1); Double bX=b.diastaseis.get(0); Double bY=b.diastaseis.get(1); return Math.abs(aX - bX) + Math.abs(aY - bY); } /** * Εστω οτι το σημειο που ψαχνω τους γειτονες του ειναι το Χ. Για να βρω το κοντινοτερο ορθογωνιο του, θα παω να βαλω το Χ * μεσα σε ένα ορθογωνιο και θα δω ποσο μεγαλωσε η περιμετρος του. Επειτα θα επαναλαβω για καθε ορθογωνιο. Αυτο που μεγαλωσε * πιο λιγο ειναι και το κοντινοτερο του. */ /** public double apostasi(MBR data,LeafRecords x) { ArrayList<Double> newMbr=dummy.newCorners(data,x.getDiastaseis().get(0),x.getDiastaseis().get(1)); Double newPerimetros= dummy.perimeter(newMbr.get(0),newMbr.get(1),newMbr.get(2),newMbr.get(3)); Double oldPerimetow = dummy.perimeter(data.diastaseisA.get(0),data.diastaseisA.get(1),data.diastaseisB.get(0),data.diastaseisB.get(1)); return (newPerimetros-oldPerimetow)/2; } */ public void knnPrint() { System.out.println("-----------------------------------------------"); System.out.println("Knn of point"); int i=1; for(LeafRecords leaf:kontinotera) { System.out.println("K:"+i); i++; leaf.printRecord(); //Double apo= dummy.distance(leaf.getDiastaseis().get(0),leaf.getDiastaseis().get(1),x.getDiastaseis().get(0),x.getDiastaseis().get(1)); Double apo=distManhattan(leaf,x); System.out.println("----Distance between leaf and Point:"+apo); } } public boolean otinanaiIsIn(LeafRecords x,ArrayList<LeafRecords> otinanai) { for(LeafRecords leaf:otinanai) { if(Objects.equals(leaf.getDiastaseis().get(0), x.diastaseis.get(0)) && (Objects.equals(leaf.getDiastaseis().get(1), x.diastaseis.get(1)))) { return true; } } return false; } public ArrayList<LeafRecords> knnSeiriaka(ArrayList<LeafRecords> otinanai) { AllBlocks allBlock=new AllBlocks(); ArrayList<Block> blocks=allBlock.readFromBinaryFile(); //Απο τα αρχειο τα διαβασα και τα εκανα απο Records--->LeafRecods ArrayList<LeafRecords> tmp=new ArrayList<>(); for(Block bl:blocks) { for(Record record:bl.getOneBlock()) { LeafRecords n=new LeafRecords(record); tmp.add(n); } } for(LeafRecords leaf:tmp) { Double apostLeaf=distManhattan(leaf,x); LeafRecords makri=findMax(otinanai,x); Double apostOtinanai=distManhattan(makri,x); if(apostLeaf<apostOtinanai) { if(!otinanaiIsIn(leaf,otinanai)) { otinanai.remove(makri); otinanai.add(leaf); } } } return otinanai; } public int getK() { return k; } public void setK(int k) { this.k = k; } public ArrayList<LeafRecords> getKontinotera() { return kontinotera; } public void setKontinotera(ArrayList<LeafRecords> kontinotera) { this.kontinotera = kontinotera; } public R_Tree getrTree() { return rTree; } public void setrTree(R_Tree rTree) { this.rTree = rTree; } }
1713_1
package refugeoly; public class Refugee extends Game { private String name; private double money=10000; private final int board=1; //Δεν αλλάζει ποτέ - Υπάρχει μόνο ένα ταμπλό private int square=0; //Κάθε παίκτης ξεκινάει από το τετράγωνο 0 private double expenses=0; public void setName(String n) { name=n; } public String getName() { return name; } public void setMoney(double m) { money=m; } public double getMoney() { return money; } public void receiveMoney(double m) { money=money+m; } public void setSquare(int s) { square=s; } public void moveTo(int s) { if (square+s<=39) { square=square+s; } else { int goback=0; for (int i=1 ; i<=s ; i++) { if (square+1<=39 && goback==0) { square=square+1; } else { square=square-1; goback=1; } } } } public int getSquare() { return square; } public void setExpenses(double e) { expenses=e; } public void incExpenses(double e) { expenses=expenses+e; } public double getExpenses() { return expenses; } public double giveMoney(double exp) { if (exp>money) { System.out.printf("You have gone bankrupted! You lost! The other refugees shall continue living without you...\n"); System.out.printf("Total money spent: %f\n\n", expenses); return -1; } else { money=money-exp; return exp; } } }
anatheodor/Refugeoly
Refugeoly/src/refugeoly/Refugee.java
525
//Κάθε παίκτης ξεκινάει από το τετράγωνο 0
line_comment
el
package refugeoly; public class Refugee extends Game { private String name; private double money=10000; private final int board=1; //Δεν αλλάζει ποτέ - Υπάρχει μόνο ένα ταμπλό private int square=0; //Κάθε παίκτης<SUF> private double expenses=0; public void setName(String n) { name=n; } public String getName() { return name; } public void setMoney(double m) { money=m; } public double getMoney() { return money; } public void receiveMoney(double m) { money=money+m; } public void setSquare(int s) { square=s; } public void moveTo(int s) { if (square+s<=39) { square=square+s; } else { int goback=0; for (int i=1 ; i<=s ; i++) { if (square+1<=39 && goback==0) { square=square+1; } else { square=square-1; goback=1; } } } } public int getSquare() { return square; } public void setExpenses(double e) { expenses=e; } public void incExpenses(double e) { expenses=expenses+e; } public double getExpenses() { return expenses; } public double giveMoney(double exp) { if (exp>money) { System.out.printf("You have gone bankrupted! You lost! The other refugees shall continue living without you...\n"); System.out.printf("Total money spent: %f\n\n", expenses); return -1; } else { money=money-exp; return exp; } } }
9105_1
package platform.javabnb; // το Διαμέρισμα κληρονομεί από την Κατοικία public class Apartment extends House { // επιπλέον χαρακτηριστικά διαμερίσματος private final int floor; private final boolean elevator, balcony; public Apartment(String taxNumber, String houseId, String municipality, String address, Landscape view, int people, int bedrooms, int floor, double metroDistance, double rentMoney, boolean internetAccess, boolean television, boolean kitchen, boolean privateParking, boolean elevator, boolean balcony) { super(taxNumber, houseId, municipality, address, view, people, bedrooms, metroDistance, rentMoney, internetAccess, television, kitchen, privateParking); if (floor < 0 || floor > 10) { throw new IllegalArgumentException("Invalid floor number: " + floor + "."); } else { this.floor = floor; } this.elevator = elevator; this.balcony = balcony; } public int getFloor() { return floor; } public boolean isElevator() { return elevator; } public boolean isBalcony() { return balcony; } @Override public String toString() { return String.format("House ID: %-17s| Comfort Level: %-14.1f| " + "Elevator: %s%nMunicipality: %-13s| Metro Distance: %.1f %-7s| " + "Balcony: %s%nAddress: %-18s| Internet: %-19s| Floor: %d%n" + "View: %-21s| Television: %-17s|%nBedrooms: %-17s| Kitchen: %-20s|%n" + "People: %-19s| Private Parking: %-12s|%n%n-----------%n" + "Daily Rent: $%.2f%n-----------", houseId, comfortLevel, elevator, municipality, metroDistance, "m", balcony, address, internetAccess, floor, view.getLandscape(), television, bedrooms, kitchen, people, privateParking, rentMoney); } }
andreasrous/JavaBnB
src/main/java/platform/javabnb/Apartment.java
584
// επιπλέον χαρακτηριστικά διαμερίσματος
line_comment
el
package platform.javabnb; // το Διαμέρισμα κληρονομεί από την Κατοικία public class Apartment extends House { // επιπλέον χαρακτηριστικά<SUF> private final int floor; private final boolean elevator, balcony; public Apartment(String taxNumber, String houseId, String municipality, String address, Landscape view, int people, int bedrooms, int floor, double metroDistance, double rentMoney, boolean internetAccess, boolean television, boolean kitchen, boolean privateParking, boolean elevator, boolean balcony) { super(taxNumber, houseId, municipality, address, view, people, bedrooms, metroDistance, rentMoney, internetAccess, television, kitchen, privateParking); if (floor < 0 || floor > 10) { throw new IllegalArgumentException("Invalid floor number: " + floor + "."); } else { this.floor = floor; } this.elevator = elevator; this.balcony = balcony; } public int getFloor() { return floor; } public boolean isElevator() { return elevator; } public boolean isBalcony() { return balcony; } @Override public String toString() { return String.format("House ID: %-17s| Comfort Level: %-14.1f| " + "Elevator: %s%nMunicipality: %-13s| Metro Distance: %.1f %-7s| " + "Balcony: %s%nAddress: %-18s| Internet: %-19s| Floor: %d%n" + "View: %-21s| Television: %-17s|%nBedrooms: %-17s| Kitchen: %-20s|%n" + "People: %-19s| Private Parking: %-12s|%n%n-----------%n" + "Daily Rent: $%.2f%n-----------", houseId, comfortLevel, elevator, municipality, metroDistance, "m", balcony, address, internetAccess, floor, view.getLandscape(), television, bedrooms, kitchen, people, privateParking, rentMoney); } }
7394_4
package projectDB; import java.awt.EventQueue; import javax.swing.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.Font; import java.text.*; import java.util.Calendar; import java.sql.*; import java.util.Date; public class ShiftManagerMenu { private JFrame frame; static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/Cinema?useSSL=false"; static final String USER = "root"; static final String PASS = "5853"; Connection conn; Statement stmt; ResultSet rs; /********** Launch the application **********/ public static void shiftManagerScreen() { EventQueue.invokeLater(new Runnable() { public void run() { try { ShiftManagerMenu window = new ShiftManagerMenu(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /********** Create the application **********/ public ShiftManagerMenu() { initialize(); } /********** Initialize the contents of the frame **********/ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 620, 400); frame.getContentPane().setLayout(null); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JLabel label = new JLabel("What do you want to do?"); label.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 14)); label.setBounds(2, 2, 200, 30); frame.getContentPane().add(label); JButton button1 = new JButton("See the employees that are currently working"); button1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //click frame.dispose(); try{ Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(DB_URL,USER,PASS); stmt = conn.createStatement(); String sql; JTextArea textArea = new JTextArea(); Date curDate = new Date(); SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat time = new SimpleDateFormat("kk:mm:ss"); String currentDay = date.format(curDate); String currentTime = time.format(curDate); Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY,8); cal.set(Calendar.MINUTE,00); cal.set(Calendar.SECOND,0); cal.set(Calendar.MILLISECOND,0); Date time_limit = cal.getTime(); cal.set(Calendar.HOUR_OF_DAY,18); cal.set(Calendar.MINUTE,00); cal.set(Calendar.SECOND,0); cal.set(Calendar.MILLISECOND,0); Date time_limit2 = cal.getTime(); String shift; //Καθορισμός βάρδιας if(curDate.compareTo(time_limit) > 0 && curDate.compareTo(time_limit2) < 0) shift = "Morning"; else shift = "Afternoon"; /*Ορισμός τρέχουσας ημερομηνίας σε 05/08/2016*/ /*******************************************/ currentDay = "2016-08-05" ; /******************************************/ /*Η βάρδια καθορίζεται με βάση την τρέχουσα ωρα που υπολογίζεται παραπάνω */ sql = "SELECT Employee.id,name,lastname,job FROM Schedule INNER JOIN Employee ON Employee.id = Schedule.id WHERE Schedule.working_date = \"" + currentDay +"\" AND shift = \"" + shift +"\" ORDER BY id"; rs = stmt.executeQuery(sql); String name,lastname,job; textArea.setText(""); int id; while(rs.next()) { id = rs.getInt("Employee.id"); name = rs.getString("name"); lastname= rs.getString("lastname"); job = rs.getString("job"); textArea.append(id + " | Name : "+ name + " | Lastname : " + lastname +" | Job : " + job + "\n"); } JScrollPane scrollPanel = new JScrollPane(textArea); JOptionPane.showMessageDialog(null, scrollPanel, "Currenty working employees", JOptionPane.INFORMATION_MESSAGE); } catch(SQLException se){ se.printStackTrace(); } catch(Exception e2){ e2.printStackTrace(); } finally{ try{ if(stmt != null) stmt.close(); } catch(SQLException se2){ } try{ if(conn != null) conn.close(); } catch(SQLException se){ se.printStackTrace(); } } } }); button1.setBounds(70, 75, 480, 50); frame.getContentPane().add(button1); JButton button2 = new JButton("See the employees that worked or will work on a specific date"); button2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //click frame.dispose(); try{ Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(DB_URL,USER,PASS); stmt = conn.createStatement(); String date, shift, sql, name,lastname,job; int id; JTextArea textArea = new JTextArea(); date = JOptionPane.showInputDialog("Please enter date in yyyy-MM-dd format"); shift = JOptionPane.showInputDialog("Please enter the shift you want "); sql = "SELECT Employee.id,name,lastname,job,Schedule.shift FROM Schedule INNER JOIN Employee ON Employee.id = Schedule.id WHERE Schedule.working_date = \"" + date + "\" AND Schedule.shift = \"" + shift + "\" ORDER BY id"; rs = stmt.executeQuery(sql); textArea.setText(""); while(rs.next()) { id = rs.getInt("Employee.id"); name = rs.getString("name"); lastname= rs.getString("lastname"); job = rs.getString("job"); shift = rs.getString("shift"); textArea.append(id + "| Name : " + name + " | Lastname : " + lastname +" | Job : " + job + " | Shift : " + shift + "\n"); } JScrollPane scrollPanel = new JScrollPane(textArea); JOptionPane.showMessageDialog(null, scrollPanel, "Working employees", JOptionPane.INFORMATION_MESSAGE); } catch(SQLException se){ se.printStackTrace(); } catch(Exception e2){ e2.printStackTrace(); } finally{ try{ if(stmt != null) stmt.close(); } catch(SQLException se2){ } try{ if(conn != null) conn.close(); } catch(SQLException se){ se.printStackTrace(); } } } }); button2.setBounds(70, 175, 480, 50); frame.getContentPane().add(button2); JButton button3 = new JButton("Access statistics about the cinema"); button3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //click frame.dispose(); try{ Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(DB_URL,USER,PASS); stmt = conn.createStatement(); String sql,tmp, Date_1 = null, Date_2 = null; int temp; JTextArea textArea = new JTextArea(); tmp = JOptionPane.showInputDialog("Please make a selection" + "\n" + "1.Which movies and what was their genre did men customers watch between Date_1 and Date_2 and rated 4 or 5" + "\n" + "2.Which are the movies with the largest number of viewers between Date_1 and Date_2" + "\n" + "3.Which customer watched the largest number of 3D movies between Date_1 and Date_2" + "\n" + "4.What are the genres that are favored by women customers of age 20-30 " + "\n" + "5.Which bonus cards have won free tickets between Date_1 and Date_2 and whether have they redeemed them" + "\n" + "6.How many hours has an employee worked between Date_1 and Date_2 and how much was he paid" + "\n"); temp = Integer.parseInt(tmp); if(temp != 4) { Date_1 = JOptionPane.showInputDialog("Please enter Date_1 (format yyyy-MM-dd)"); Date_2 = JOptionPane.showInputDialog("Please enter Date_2 (format yyyy-MM-dd)"); } String title, genre, id; switch(temp) { case(1): sql = "SELECT Movies_Watched.title,Genre.genre FROM Customer INNER JOIN Movies_Watched ON Customer.id = Movies_Watched.id " + "INNER JOIN Genre ON Movies_Watched.title = Genre.title WHERE Customer.sex = 'Male' AND Movies_Watched.date_watched> \" " + Date_1 + "\" AND Movies_Watched.date_watched < \" " + Date_2 + " \" AND Movies_Watched.rating > 3 GROUP BY Movies_Watched.title,Genre.genre"; rs = stmt.executeQuery(sql); textArea.setText(""); while(rs.next()) { title = rs.getString("Movies_Watched.title"); genre = rs.getString("Genre.genre"); textArea.append(title + " | " + genre + "\n"); } JOptionPane.showMessageDialog(null, textArea, "Men's rating movies", JOptionPane.INFORMATION_MESSAGE); break; case(2): Date_1 = Date_1 + " 00:00:00"; Date_2 = Date_2 + " 00:00:00"; sql = "SELECT title ,count(title) as tickets " + "FROM Tickets " + "WHERE beg_time > \" " + Date_1 + " \" AND end_time < \" " + Date_2 + " \" GROUP BY (title) " + "HAVING count(title) = " + "(" + "SELECT MAX(temp) FROM (" + "SELECT count(title) as temp "+ "FROM Tickets " + "WHERE beg_time > \" " + Date_1 + " \" AND end_time < \" " + Date_2 + " \" GROUP BY (title) " + ") s " + ")"; rs = stmt.executeQuery(sql); String tickets; textArea.setText(""); while(rs.next()) { title = rs.getString("title"); tickets = rs.getString("tickets"); textArea.append(title + " | " + tickets + "\n"); } JOptionPane.showMessageDialog(null, textArea, "Movie with the most views", JOptionPane.INFORMATION_MESSAGE); break; case(3): Date_1 = Date_1 + "00:00:00"; Date_2 = Date_2 + "00:00:00"; sql = "SELECT Customer.id " + "FROM Customer INNER JOIN Tickets ON Customer.id = Tickets.buyer " + "WHERE Tickets.beg_time > \" " + Date_1 + " \" AND Tickets.end_time <\" " + Date_2 + " \" " + "AND type = '3D' GROUP BY (Customer.id) ORDER BY count(Customer.id) DESC LIMIT 0,1;"; rs = stmt.executeQuery(sql); textArea.setText(""); while(rs.next()) { id = rs.getString("Customer.id"); textArea.append("Customer : " + id); } JOptionPane.showMessageDialog(null, textArea, "Most 3D movies", JOptionPane.INFORMATION_MESSAGE); break; case(4): sql = "SELECT Genre.genre,count(genre) as Tickets " + "FROM Customer INNER JOIN Movies_Watched ON Customer.id = Movies_Watched.id " + "INNER JOIN Genre ON Movies_Watched.title = Genre.title WHERE Customer.sex = 'Female' " + "AND Customer.birthday > DATE_ADD(CURDATE(),INTERVAL -30 YEAR ) AND Customer.birthday < DATE_ADD(CURDATE(),INTERVAL -20 YEAR ) " + "group by genre order by count(genre) desc;"; rs = stmt.executeQuery(sql); textArea.setText(""); int count; while(rs.next()) { genre = rs.getString("Genre.genre"); count = rs.getInt("Tickets"); textArea.append("Genre : " + genre + " Tickets : " + count + "\n"); } JOptionPane.showMessageDialog(null, textArea, "Young women preferences", JOptionPane.INFORMATION_MESSAGE); break; case(5): sql = "SELECT Bonus_Card.card_id as Customer, free_tickets as Tickets_Left ,count(Free_tickets.card_id) as Times_Won FROM Bonus_Card " + "INNER JOIN Free_tickets ON Bonus_Card.card_id = Free_tickets.card_id " + "WHERE Free_tickets.date_of_winning >= \" " +Date_1 + " \" AND Free_tickets.date_of_winning <=\" "+ Date_2 + " \" " + "GROUP BY (Free_tickets.card_id);"; rs = stmt.executeQuery(sql); String times, left; textArea.setText(""); while(rs.next()) { id = rs.getString("Customer"); times = rs.getString("Times_Won"); left = rs.getString("Tickets_Left"); textArea.append("Customer : " + id + " | Times Won : " + times + " | Tickets Left : " + left + "\n"); } JOptionPane.showMessageDialog(null, textArea, "Free Tickets", JOptionPane.INFORMATION_MESSAGE); break; case(6): sql = "SELECT name,lastname,count(Schedule.id)*10 AS Hours,count(Schedule.id)*10*hourly_salary AS Salary " + "FROM Employee INNER JOIN Schedule ON Employee.id = Schedule.id " + "WHERE Schedule.working_date >= \" " +Date_1 + " \" AND Schedule.working_date <=\" "+ Date_2 + " \" " + "GROUP BY (Schedule.id) ORDER BY name ASC;"; rs = stmt.executeQuery(sql); String name,lastname,hours,salary; textArea.setText(""); while(rs.next()) { name = rs.getString("name"); lastname = rs.getString("lastname"); hours = rs.getString("Hours"); salary = rs.getString("Salary"); textArea.append("Name : " + name + " | Lastname : " + lastname + " | Hours Worked : " + hours + " | Salary : " + salary + "\n"); } JScrollPane ScrollPanel = new JScrollPane(textArea); JOptionPane.showMessageDialog(null, ScrollPanel, "Salaries", JOptionPane.INFORMATION_MESSAGE); break; } } catch(SQLException se){ se.printStackTrace(); } catch(Exception e2){ e2.printStackTrace(); } finally{ try{ if(stmt != null) stmt.close(); } catch(SQLException se2){ } try{ if(conn != null) conn.close(); } catch(SQLException se){ se.printStackTrace(); } } } }); button3.setBounds(70, 275, 480, 50); frame.getContentPane().add(button3); } }
andronkyr/Cinema
ShiftManagerMenu.java
4,116
/*Η βάρδια καθορίζεται με βάση την τρέχουσα ωρα που υπολογίζεται παραπάνω */
block_comment
el
package projectDB; import java.awt.EventQueue; import javax.swing.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.Font; import java.text.*; import java.util.Calendar; import java.sql.*; import java.util.Date; public class ShiftManagerMenu { private JFrame frame; static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/Cinema?useSSL=false"; static final String USER = "root"; static final String PASS = "5853"; Connection conn; Statement stmt; ResultSet rs; /********** Launch the application **********/ public static void shiftManagerScreen() { EventQueue.invokeLater(new Runnable() { public void run() { try { ShiftManagerMenu window = new ShiftManagerMenu(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /********** Create the application **********/ public ShiftManagerMenu() { initialize(); } /********** Initialize the contents of the frame **********/ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 620, 400); frame.getContentPane().setLayout(null); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JLabel label = new JLabel("What do you want to do?"); label.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 14)); label.setBounds(2, 2, 200, 30); frame.getContentPane().add(label); JButton button1 = new JButton("See the employees that are currently working"); button1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //click frame.dispose(); try{ Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(DB_URL,USER,PASS); stmt = conn.createStatement(); String sql; JTextArea textArea = new JTextArea(); Date curDate = new Date(); SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat time = new SimpleDateFormat("kk:mm:ss"); String currentDay = date.format(curDate); String currentTime = time.format(curDate); Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY,8); cal.set(Calendar.MINUTE,00); cal.set(Calendar.SECOND,0); cal.set(Calendar.MILLISECOND,0); Date time_limit = cal.getTime(); cal.set(Calendar.HOUR_OF_DAY,18); cal.set(Calendar.MINUTE,00); cal.set(Calendar.SECOND,0); cal.set(Calendar.MILLISECOND,0); Date time_limit2 = cal.getTime(); String shift; //Καθορισμός βάρδιας if(curDate.compareTo(time_limit) > 0 && curDate.compareTo(time_limit2) < 0) shift = "Morning"; else shift = "Afternoon"; /*Ορισμός τρέχουσας ημερομηνίας σε 05/08/2016*/ /*******************************************/ currentDay = "2016-08-05" ; /******************************************/ /*Η βάρδια καθορίζεται<SUF>*/ sql = "SELECT Employee.id,name,lastname,job FROM Schedule INNER JOIN Employee ON Employee.id = Schedule.id WHERE Schedule.working_date = \"" + currentDay +"\" AND shift = \"" + shift +"\" ORDER BY id"; rs = stmt.executeQuery(sql); String name,lastname,job; textArea.setText(""); int id; while(rs.next()) { id = rs.getInt("Employee.id"); name = rs.getString("name"); lastname= rs.getString("lastname"); job = rs.getString("job"); textArea.append(id + " | Name : "+ name + " | Lastname : " + lastname +" | Job : " + job + "\n"); } JScrollPane scrollPanel = new JScrollPane(textArea); JOptionPane.showMessageDialog(null, scrollPanel, "Currenty working employees", JOptionPane.INFORMATION_MESSAGE); } catch(SQLException se){ se.printStackTrace(); } catch(Exception e2){ e2.printStackTrace(); } finally{ try{ if(stmt != null) stmt.close(); } catch(SQLException se2){ } try{ if(conn != null) conn.close(); } catch(SQLException se){ se.printStackTrace(); } } } }); button1.setBounds(70, 75, 480, 50); frame.getContentPane().add(button1); JButton button2 = new JButton("See the employees that worked or will work on a specific date"); button2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //click frame.dispose(); try{ Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(DB_URL,USER,PASS); stmt = conn.createStatement(); String date, shift, sql, name,lastname,job; int id; JTextArea textArea = new JTextArea(); date = JOptionPane.showInputDialog("Please enter date in yyyy-MM-dd format"); shift = JOptionPane.showInputDialog("Please enter the shift you want "); sql = "SELECT Employee.id,name,lastname,job,Schedule.shift FROM Schedule INNER JOIN Employee ON Employee.id = Schedule.id WHERE Schedule.working_date = \"" + date + "\" AND Schedule.shift = \"" + shift + "\" ORDER BY id"; rs = stmt.executeQuery(sql); textArea.setText(""); while(rs.next()) { id = rs.getInt("Employee.id"); name = rs.getString("name"); lastname= rs.getString("lastname"); job = rs.getString("job"); shift = rs.getString("shift"); textArea.append(id + "| Name : " + name + " | Lastname : " + lastname +" | Job : " + job + " | Shift : " + shift + "\n"); } JScrollPane scrollPanel = new JScrollPane(textArea); JOptionPane.showMessageDialog(null, scrollPanel, "Working employees", JOptionPane.INFORMATION_MESSAGE); } catch(SQLException se){ se.printStackTrace(); } catch(Exception e2){ e2.printStackTrace(); } finally{ try{ if(stmt != null) stmt.close(); } catch(SQLException se2){ } try{ if(conn != null) conn.close(); } catch(SQLException se){ se.printStackTrace(); } } } }); button2.setBounds(70, 175, 480, 50); frame.getContentPane().add(button2); JButton button3 = new JButton("Access statistics about the cinema"); button3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //click frame.dispose(); try{ Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(DB_URL,USER,PASS); stmt = conn.createStatement(); String sql,tmp, Date_1 = null, Date_2 = null; int temp; JTextArea textArea = new JTextArea(); tmp = JOptionPane.showInputDialog("Please make a selection" + "\n" + "1.Which movies and what was their genre did men customers watch between Date_1 and Date_2 and rated 4 or 5" + "\n" + "2.Which are the movies with the largest number of viewers between Date_1 and Date_2" + "\n" + "3.Which customer watched the largest number of 3D movies between Date_1 and Date_2" + "\n" + "4.What are the genres that are favored by women customers of age 20-30 " + "\n" + "5.Which bonus cards have won free tickets between Date_1 and Date_2 and whether have they redeemed them" + "\n" + "6.How many hours has an employee worked between Date_1 and Date_2 and how much was he paid" + "\n"); temp = Integer.parseInt(tmp); if(temp != 4) { Date_1 = JOptionPane.showInputDialog("Please enter Date_1 (format yyyy-MM-dd)"); Date_2 = JOptionPane.showInputDialog("Please enter Date_2 (format yyyy-MM-dd)"); } String title, genre, id; switch(temp) { case(1): sql = "SELECT Movies_Watched.title,Genre.genre FROM Customer INNER JOIN Movies_Watched ON Customer.id = Movies_Watched.id " + "INNER JOIN Genre ON Movies_Watched.title = Genre.title WHERE Customer.sex = 'Male' AND Movies_Watched.date_watched> \" " + Date_1 + "\" AND Movies_Watched.date_watched < \" " + Date_2 + " \" AND Movies_Watched.rating > 3 GROUP BY Movies_Watched.title,Genre.genre"; rs = stmt.executeQuery(sql); textArea.setText(""); while(rs.next()) { title = rs.getString("Movies_Watched.title"); genre = rs.getString("Genre.genre"); textArea.append(title + " | " + genre + "\n"); } JOptionPane.showMessageDialog(null, textArea, "Men's rating movies", JOptionPane.INFORMATION_MESSAGE); break; case(2): Date_1 = Date_1 + " 00:00:00"; Date_2 = Date_2 + " 00:00:00"; sql = "SELECT title ,count(title) as tickets " + "FROM Tickets " + "WHERE beg_time > \" " + Date_1 + " \" AND end_time < \" " + Date_2 + " \" GROUP BY (title) " + "HAVING count(title) = " + "(" + "SELECT MAX(temp) FROM (" + "SELECT count(title) as temp "+ "FROM Tickets " + "WHERE beg_time > \" " + Date_1 + " \" AND end_time < \" " + Date_2 + " \" GROUP BY (title) " + ") s " + ")"; rs = stmt.executeQuery(sql); String tickets; textArea.setText(""); while(rs.next()) { title = rs.getString("title"); tickets = rs.getString("tickets"); textArea.append(title + " | " + tickets + "\n"); } JOptionPane.showMessageDialog(null, textArea, "Movie with the most views", JOptionPane.INFORMATION_MESSAGE); break; case(3): Date_1 = Date_1 + "00:00:00"; Date_2 = Date_2 + "00:00:00"; sql = "SELECT Customer.id " + "FROM Customer INNER JOIN Tickets ON Customer.id = Tickets.buyer " + "WHERE Tickets.beg_time > \" " + Date_1 + " \" AND Tickets.end_time <\" " + Date_2 + " \" " + "AND type = '3D' GROUP BY (Customer.id) ORDER BY count(Customer.id) DESC LIMIT 0,1;"; rs = stmt.executeQuery(sql); textArea.setText(""); while(rs.next()) { id = rs.getString("Customer.id"); textArea.append("Customer : " + id); } JOptionPane.showMessageDialog(null, textArea, "Most 3D movies", JOptionPane.INFORMATION_MESSAGE); break; case(4): sql = "SELECT Genre.genre,count(genre) as Tickets " + "FROM Customer INNER JOIN Movies_Watched ON Customer.id = Movies_Watched.id " + "INNER JOIN Genre ON Movies_Watched.title = Genre.title WHERE Customer.sex = 'Female' " + "AND Customer.birthday > DATE_ADD(CURDATE(),INTERVAL -30 YEAR ) AND Customer.birthday < DATE_ADD(CURDATE(),INTERVAL -20 YEAR ) " + "group by genre order by count(genre) desc;"; rs = stmt.executeQuery(sql); textArea.setText(""); int count; while(rs.next()) { genre = rs.getString("Genre.genre"); count = rs.getInt("Tickets"); textArea.append("Genre : " + genre + " Tickets : " + count + "\n"); } JOptionPane.showMessageDialog(null, textArea, "Young women preferences", JOptionPane.INFORMATION_MESSAGE); break; case(5): sql = "SELECT Bonus_Card.card_id as Customer, free_tickets as Tickets_Left ,count(Free_tickets.card_id) as Times_Won FROM Bonus_Card " + "INNER JOIN Free_tickets ON Bonus_Card.card_id = Free_tickets.card_id " + "WHERE Free_tickets.date_of_winning >= \" " +Date_1 + " \" AND Free_tickets.date_of_winning <=\" "+ Date_2 + " \" " + "GROUP BY (Free_tickets.card_id);"; rs = stmt.executeQuery(sql); String times, left; textArea.setText(""); while(rs.next()) { id = rs.getString("Customer"); times = rs.getString("Times_Won"); left = rs.getString("Tickets_Left"); textArea.append("Customer : " + id + " | Times Won : " + times + " | Tickets Left : " + left + "\n"); } JOptionPane.showMessageDialog(null, textArea, "Free Tickets", JOptionPane.INFORMATION_MESSAGE); break; case(6): sql = "SELECT name,lastname,count(Schedule.id)*10 AS Hours,count(Schedule.id)*10*hourly_salary AS Salary " + "FROM Employee INNER JOIN Schedule ON Employee.id = Schedule.id " + "WHERE Schedule.working_date >= \" " +Date_1 + " \" AND Schedule.working_date <=\" "+ Date_2 + " \" " + "GROUP BY (Schedule.id) ORDER BY name ASC;"; rs = stmt.executeQuery(sql); String name,lastname,hours,salary; textArea.setText(""); while(rs.next()) { name = rs.getString("name"); lastname = rs.getString("lastname"); hours = rs.getString("Hours"); salary = rs.getString("Salary"); textArea.append("Name : " + name + " | Lastname : " + lastname + " | Hours Worked : " + hours + " | Salary : " + salary + "\n"); } JScrollPane ScrollPanel = new JScrollPane(textArea); JOptionPane.showMessageDialog(null, ScrollPanel, "Salaries", JOptionPane.INFORMATION_MESSAGE); break; } } catch(SQLException se){ se.printStackTrace(); } catch(Exception e2){ e2.printStackTrace(); } finally{ try{ if(stmt != null) stmt.close(); } catch(SQLException se2){ } try{ if(conn != null) conn.close(); } catch(SQLException se){ se.printStackTrace(); } } } }); button3.setBounds(70, 275, 480, 50); frame.getContentPane().add(button3); } }
45129_1
package com.unipi.toor_guide; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatDelegate; import androidx.cardview.widget.CardView; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.os.Bundle; import android.speech.RecognizerIntent; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.remoteconfig.FirebaseRemoteConfig; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class SearchActivity extends AppCompatActivity { BottomNavigationView bottomBar; EditText search_text; Button search_button; Context searchactivity = this; private StorageReference storageRef; private FirebaseRemoteConfig remoteConfig; private FirebaseDatabase firedb; private DatabaseReference ref; List<String> beach_names = new ArrayList<String>(); List<String> gr_beach_names = new ArrayList<String>(); List<String> villages_names = new ArrayList<String>(); List<String> gr_villages_names = new ArrayList<String>(); List<String> beaches_desc = new ArrayList<>(); List<String> villages_desc = new ArrayList<>(); MyTts myTts; private static final int REC_RESULT = 653; TextView beach_textview; TextView village_textview; HorizontalScrollView beaches_hsv; HorizontalScrollView villages_hsv; LinearLayout beaches_cardholder; LinearLayout villages_cardholder; CardView cardview; LinearLayout.LayoutParams llayoutparams; ImageView cardimage; TextView cardtext; TextView no_beaches; TextView no_villages; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); bottomBar=findViewById(R.id.bottombar); bottomBar.getMenu().getItem(1).setChecked(true); bottomBar.setOnNavigationItemSelectedListener(item -> { if(item.getItemId()==R.id.home){ startActivity(new Intent(getApplicationContext(), MainActivity.class)); overridePendingTransition(0,0); return true; } if(item.getItemId()==R.id.Favourites){ startActivity(new Intent(getApplicationContext(),FavouritesActivity.class)); overridePendingTransition(0,0); return true; } return item.getItemId() == R.id.search; }); beach_textview=findViewById(R.id.beach_textview); village_textview=findViewById(R.id.villages_textview); beaches_hsv=findViewById(R.id.beaches_hsv); villages_hsv=findViewById(R.id.villages_hsv); beaches_cardholder=findViewById(R.id.beaches_cardholder); villages_cardholder=findViewById(R.id.villages_cardholder); llayoutparams = new LinearLayout.LayoutParams( 300, LinearLayout.LayoutParams.WRAP_CONTENT ); llayoutparams.setMargins(20,0,20,0); search_text=findViewById(R.id.search_edittext); search_button=findViewById(R.id.search_button); search_button.setOnLongClickListener(view -> { recognize(); search_fun(); return true; }); storageRef = FirebaseStorage.getInstance().getReference(); AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); //night mode ui is not supported remoteConfig = FirebaseRemoteConfig.getInstance(); remoteConfig.setDefaultsAsync(R.xml.config_settings); remoteConfig.fetch(3).addOnCompleteListener(task -> remoteConfig.fetchAndActivate()); firedb = FirebaseDatabase.getInstance(); ref = firedb.getReference(); myTts = new MyTts(searchactivity); no_beaches=findViewById(R.id.no_beach_textview); no_villages=findViewById(R.id.no_villages_textview); } @Override protected void onResume() { super.onResume(); bottomBar.getMenu().getItem(1).setChecked(true); beach_names.clear(); beaches_desc.clear(); villages_names.clear(); villages_desc.clear(); beaches_cardholder.removeAllViews(); villages_cardholder.removeAllViews(); beach_textview.setVisibility(View.INVISIBLE); village_textview.setVisibility(View.INVISIBLE); beaches_hsv.setVisibility(View.INVISIBLE); villages_hsv.setVisibility(View.INVISIBLE); no_beaches.setVisibility(View.INVISIBLE); no_villages.setVisibility(View.INVISIBLE); } public void search(View view){ if(beach_textview.getVisibility()==View.INVISIBLE){ beach_textview.setVisibility(View.VISIBLE); village_textview.setVisibility(View.VISIBLE); beaches_hsv.setVisibility(View.VISIBLE); villages_hsv.setVisibility(View.VISIBLE); } search_fun(); } private void search_fun(){ beach_names.clear(); gr_beach_names.clear(); beaches_desc.clear(); villages_names.clear(); gr_villages_names.clear(); villages_desc.clear(); beaches_cardholder.removeAllViews(); villages_cardholder.removeAllViews(); if(!search_text.getText().toString().equals("")){ ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snap: snapshot.getChildren()){ for(DataSnapshot sight : snap.child("Beaches").getChildren()){ String beachen = String.valueOf(sight.getKey()); String beachel = String.valueOf(sight.child("NameTrans").getValue()); if((beachen.toLowerCase().contains(search_text.getText().toString().toLowerCase())||beachel.toLowerCase().contains(search_text.getText().toString().toLowerCase()))&&!beach_names.contains(beachen)) { beach_names.add(beachen); gr_beach_names.add(beachel); beaches_desc.add(String.valueOf(sight.child("Info").getValue())); } } for (DataSnapshot sight : snap.child("Villages").getChildren()) { String villagen = String.valueOf(sight.getKey()); String villagel=String.valueOf(sight.child("NameTrans").getValue()); if((villagen.toLowerCase().contains(search_text.getText().toString().toLowerCase())||villagel.toLowerCase().contains(search_text.getText().toString().toLowerCase()))&&!villages_names.contains(villagen)) { villages_names.add(villagen); gr_villages_names.add(villagel); villages_desc.add(String.valueOf(sight.child("Info").getValue())); } } } if(beach_names.isEmpty()){ no_beaches.setVisibility(View.VISIBLE); no_beaches.setText(getText(R.string.no_beach)+search_text.getText().toString()); }else { no_beaches.setVisibility(View.INVISIBLE); } if(villages_names.isEmpty()){ no_villages.setVisibility(View.VISIBLE); no_villages.setText(getText(R.string.no_villages)+search_text.getText().toString()); }else{ no_villages.setVisibility(View.INVISIBLE); } for(int i=0; i<beach_names.size(); i++){ String imgname = beach_names.get(i).toLowerCase(); if (imgname.contains(" ")) imgname = imgname.replace(" ","_"); String imgpath = imgname; imgname = (new StringBuilder().append(imgname).append(".jpg")).toString(); try{ File localfile = File.createTempFile("tmp","jpg") ; StorageReference imgref = storageRef.child("img/"+ imgname); int finalI = i; String finalImgname = imgname; imgref.getFile(localfile).addOnSuccessListener(taskSnapshot ->cards(searchactivity, BitmapFactory.decodeFile(localfile.getAbsolutePath()), beach_names.get(finalI), beaches_desc.get(finalI), finalImgname, false, beaches_cardholder, gr_beach_names.get(finalI))); }catch (IOException e){ e.printStackTrace(); } } for(int i=0; i<villages_names.size(); i++){ String imgname = villages_names.get(i).toLowerCase(); if (imgname.contains(" ")) imgname = imgname.replace(" ","_"); String imgpath = imgname; imgname = (new StringBuilder().append(imgname).append(".jpg")).toString(); try{ File localfile = File.createTempFile("tmp","jpg") ; StorageReference imgref = storageRef.child("img/"+ imgname); int finalI = i; String finalImgname = imgname; imgref.getFile(localfile).addOnSuccessListener(taskSnapshot ->cards(searchactivity, BitmapFactory.decodeFile(localfile.getAbsolutePath()), villages_names.get(finalI), villages_desc.get(finalI), finalImgname, true, villages_cardholder, gr_villages_names.get(finalI))); }catch (IOException e){ e.printStackTrace(); } } } @Override public void onCancelled(@NonNull DatabaseError error) { Log.i("fire_error",error.getMessage()); } }); } else { beach_names.clear(); beaches_desc.clear(); villages_names.clear(); villages_desc.clear(); beaches_cardholder.removeAllViews(); villages_cardholder.removeAllViews(); beach_textview.setVisibility(View.INVISIBLE); beaches_hsv.setVisibility(View.INVISIBLE); village_textview.setVisibility(View.INVISIBLE); villages_hsv.setVisibility(View.INVISIBLE); } } public void cards(Context context, Bitmap background, String name, String description, String imgpath,boolean village,LinearLayout cardholder,String gr_name) { cardview = new CardView(context); cardview.setRadius(0); cardview.setPadding(0, 0, 0, 0); cardview.setPreventCornerOverlap(false); cardview.setBackgroundResource(R.drawable.rectangled); cardimage = new ImageView(context); cardimage.setImageBitmap(background); cardimage.setScaleType(ImageView.ScaleType.FIT_XY); cardimage.setMaxHeight(Integer.MAX_VALUE); cardimage.setMinimumHeight(Integer.MAX_VALUE); cardimage.setMaxWidth(Integer.MAX_VALUE); cardimage.setMinimumHeight(Integer.MAX_VALUE); cardview.addView(cardimage); cardtext = new TextView(context); if (name.contains(" ")) name = name.replace(" ", "\n"); String[] systemLangs = Resources.getSystem().getConfiguration().getLocales().toLanguageTags().split(","); if (systemLangs[0].contains(Locale.forLanguageTag("EL").toLanguageTag())) cardtext.setText(gr_name); else cardtext.setText(name); cardtext.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); cardtext.setTextColor(Color.WHITE); cardtext.setPadding(10, 430, 10, 0); cardtext.setGravity(Gravity.END); cardview.addView(cardtext); String finalName = name; cardview.setOnClickListener(v -> { startActivity(new Intent(this, InfoActivity.class). putExtra("id", finalName). putExtra("description", description). putExtra("path", imgpath). putExtra("village",village). putExtra("gr_name",gr_name)); }); cardholder.addView(cardview, llayoutparams); } @Override public void onBackPressed() { super.onBackPressed(); overridePendingTransition(0,0); } //Χειρισμός φωνητικών εντολων{ @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode==REC_RESULT && resultCode==RESULT_OK){ ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); if (matches.contains("favourites") || matches.contains("favorites") || matches.contains("αγαπημένα")){ startActivity(new Intent(this, FavouritesActivity.class)); } else if (matches.contains("home") ||matches.contains("sights") || matches.contains("αξιοθέατα") || matches.contains("αρχική")){ startActivity(new Intent(this, MainActivity.class)); } else{ search_text.setText(matches.get(0)); } } } public void recognize(){ Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_PROMPT,"What are you searching?"); startActivityForResult(intent,REC_RESULT); } //} }
angelica-thd/Android
app/src/main/java/com/unipi/toor_guide/SearchActivity.java
3,449
//Χειρισμός φωνητικών εντολων{
line_comment
el
package com.unipi.toor_guide; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatDelegate; import androidx.cardview.widget.CardView; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.os.Bundle; import android.speech.RecognizerIntent; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.remoteconfig.FirebaseRemoteConfig; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class SearchActivity extends AppCompatActivity { BottomNavigationView bottomBar; EditText search_text; Button search_button; Context searchactivity = this; private StorageReference storageRef; private FirebaseRemoteConfig remoteConfig; private FirebaseDatabase firedb; private DatabaseReference ref; List<String> beach_names = new ArrayList<String>(); List<String> gr_beach_names = new ArrayList<String>(); List<String> villages_names = new ArrayList<String>(); List<String> gr_villages_names = new ArrayList<String>(); List<String> beaches_desc = new ArrayList<>(); List<String> villages_desc = new ArrayList<>(); MyTts myTts; private static final int REC_RESULT = 653; TextView beach_textview; TextView village_textview; HorizontalScrollView beaches_hsv; HorizontalScrollView villages_hsv; LinearLayout beaches_cardholder; LinearLayout villages_cardholder; CardView cardview; LinearLayout.LayoutParams llayoutparams; ImageView cardimage; TextView cardtext; TextView no_beaches; TextView no_villages; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); bottomBar=findViewById(R.id.bottombar); bottomBar.getMenu().getItem(1).setChecked(true); bottomBar.setOnNavigationItemSelectedListener(item -> { if(item.getItemId()==R.id.home){ startActivity(new Intent(getApplicationContext(), MainActivity.class)); overridePendingTransition(0,0); return true; } if(item.getItemId()==R.id.Favourites){ startActivity(new Intent(getApplicationContext(),FavouritesActivity.class)); overridePendingTransition(0,0); return true; } return item.getItemId() == R.id.search; }); beach_textview=findViewById(R.id.beach_textview); village_textview=findViewById(R.id.villages_textview); beaches_hsv=findViewById(R.id.beaches_hsv); villages_hsv=findViewById(R.id.villages_hsv); beaches_cardholder=findViewById(R.id.beaches_cardholder); villages_cardholder=findViewById(R.id.villages_cardholder); llayoutparams = new LinearLayout.LayoutParams( 300, LinearLayout.LayoutParams.WRAP_CONTENT ); llayoutparams.setMargins(20,0,20,0); search_text=findViewById(R.id.search_edittext); search_button=findViewById(R.id.search_button); search_button.setOnLongClickListener(view -> { recognize(); search_fun(); return true; }); storageRef = FirebaseStorage.getInstance().getReference(); AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); //night mode ui is not supported remoteConfig = FirebaseRemoteConfig.getInstance(); remoteConfig.setDefaultsAsync(R.xml.config_settings); remoteConfig.fetch(3).addOnCompleteListener(task -> remoteConfig.fetchAndActivate()); firedb = FirebaseDatabase.getInstance(); ref = firedb.getReference(); myTts = new MyTts(searchactivity); no_beaches=findViewById(R.id.no_beach_textview); no_villages=findViewById(R.id.no_villages_textview); } @Override protected void onResume() { super.onResume(); bottomBar.getMenu().getItem(1).setChecked(true); beach_names.clear(); beaches_desc.clear(); villages_names.clear(); villages_desc.clear(); beaches_cardholder.removeAllViews(); villages_cardholder.removeAllViews(); beach_textview.setVisibility(View.INVISIBLE); village_textview.setVisibility(View.INVISIBLE); beaches_hsv.setVisibility(View.INVISIBLE); villages_hsv.setVisibility(View.INVISIBLE); no_beaches.setVisibility(View.INVISIBLE); no_villages.setVisibility(View.INVISIBLE); } public void search(View view){ if(beach_textview.getVisibility()==View.INVISIBLE){ beach_textview.setVisibility(View.VISIBLE); village_textview.setVisibility(View.VISIBLE); beaches_hsv.setVisibility(View.VISIBLE); villages_hsv.setVisibility(View.VISIBLE); } search_fun(); } private void search_fun(){ beach_names.clear(); gr_beach_names.clear(); beaches_desc.clear(); villages_names.clear(); gr_villages_names.clear(); villages_desc.clear(); beaches_cardholder.removeAllViews(); villages_cardholder.removeAllViews(); if(!search_text.getText().toString().equals("")){ ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot snap: snapshot.getChildren()){ for(DataSnapshot sight : snap.child("Beaches").getChildren()){ String beachen = String.valueOf(sight.getKey()); String beachel = String.valueOf(sight.child("NameTrans").getValue()); if((beachen.toLowerCase().contains(search_text.getText().toString().toLowerCase())||beachel.toLowerCase().contains(search_text.getText().toString().toLowerCase()))&&!beach_names.contains(beachen)) { beach_names.add(beachen); gr_beach_names.add(beachel); beaches_desc.add(String.valueOf(sight.child("Info").getValue())); } } for (DataSnapshot sight : snap.child("Villages").getChildren()) { String villagen = String.valueOf(sight.getKey()); String villagel=String.valueOf(sight.child("NameTrans").getValue()); if((villagen.toLowerCase().contains(search_text.getText().toString().toLowerCase())||villagel.toLowerCase().contains(search_text.getText().toString().toLowerCase()))&&!villages_names.contains(villagen)) { villages_names.add(villagen); gr_villages_names.add(villagel); villages_desc.add(String.valueOf(sight.child("Info").getValue())); } } } if(beach_names.isEmpty()){ no_beaches.setVisibility(View.VISIBLE); no_beaches.setText(getText(R.string.no_beach)+search_text.getText().toString()); }else { no_beaches.setVisibility(View.INVISIBLE); } if(villages_names.isEmpty()){ no_villages.setVisibility(View.VISIBLE); no_villages.setText(getText(R.string.no_villages)+search_text.getText().toString()); }else{ no_villages.setVisibility(View.INVISIBLE); } for(int i=0; i<beach_names.size(); i++){ String imgname = beach_names.get(i).toLowerCase(); if (imgname.contains(" ")) imgname = imgname.replace(" ","_"); String imgpath = imgname; imgname = (new StringBuilder().append(imgname).append(".jpg")).toString(); try{ File localfile = File.createTempFile("tmp","jpg") ; StorageReference imgref = storageRef.child("img/"+ imgname); int finalI = i; String finalImgname = imgname; imgref.getFile(localfile).addOnSuccessListener(taskSnapshot ->cards(searchactivity, BitmapFactory.decodeFile(localfile.getAbsolutePath()), beach_names.get(finalI), beaches_desc.get(finalI), finalImgname, false, beaches_cardholder, gr_beach_names.get(finalI))); }catch (IOException e){ e.printStackTrace(); } } for(int i=0; i<villages_names.size(); i++){ String imgname = villages_names.get(i).toLowerCase(); if (imgname.contains(" ")) imgname = imgname.replace(" ","_"); String imgpath = imgname; imgname = (new StringBuilder().append(imgname).append(".jpg")).toString(); try{ File localfile = File.createTempFile("tmp","jpg") ; StorageReference imgref = storageRef.child("img/"+ imgname); int finalI = i; String finalImgname = imgname; imgref.getFile(localfile).addOnSuccessListener(taskSnapshot ->cards(searchactivity, BitmapFactory.decodeFile(localfile.getAbsolutePath()), villages_names.get(finalI), villages_desc.get(finalI), finalImgname, true, villages_cardholder, gr_villages_names.get(finalI))); }catch (IOException e){ e.printStackTrace(); } } } @Override public void onCancelled(@NonNull DatabaseError error) { Log.i("fire_error",error.getMessage()); } }); } else { beach_names.clear(); beaches_desc.clear(); villages_names.clear(); villages_desc.clear(); beaches_cardholder.removeAllViews(); villages_cardholder.removeAllViews(); beach_textview.setVisibility(View.INVISIBLE); beaches_hsv.setVisibility(View.INVISIBLE); village_textview.setVisibility(View.INVISIBLE); villages_hsv.setVisibility(View.INVISIBLE); } } public void cards(Context context, Bitmap background, String name, String description, String imgpath,boolean village,LinearLayout cardholder,String gr_name) { cardview = new CardView(context); cardview.setRadius(0); cardview.setPadding(0, 0, 0, 0); cardview.setPreventCornerOverlap(false); cardview.setBackgroundResource(R.drawable.rectangled); cardimage = new ImageView(context); cardimage.setImageBitmap(background); cardimage.setScaleType(ImageView.ScaleType.FIT_XY); cardimage.setMaxHeight(Integer.MAX_VALUE); cardimage.setMinimumHeight(Integer.MAX_VALUE); cardimage.setMaxWidth(Integer.MAX_VALUE); cardimage.setMinimumHeight(Integer.MAX_VALUE); cardview.addView(cardimage); cardtext = new TextView(context); if (name.contains(" ")) name = name.replace(" ", "\n"); String[] systemLangs = Resources.getSystem().getConfiguration().getLocales().toLanguageTags().split(","); if (systemLangs[0].contains(Locale.forLanguageTag("EL").toLanguageTag())) cardtext.setText(gr_name); else cardtext.setText(name); cardtext.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); cardtext.setTextColor(Color.WHITE); cardtext.setPadding(10, 430, 10, 0); cardtext.setGravity(Gravity.END); cardview.addView(cardtext); String finalName = name; cardview.setOnClickListener(v -> { startActivity(new Intent(this, InfoActivity.class). putExtra("id", finalName). putExtra("description", description). putExtra("path", imgpath). putExtra("village",village). putExtra("gr_name",gr_name)); }); cardholder.addView(cardview, llayoutparams); } @Override public void onBackPressed() { super.onBackPressed(); overridePendingTransition(0,0); } //Χειρισμός φωνητικών<SUF> @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode==REC_RESULT && resultCode==RESULT_OK){ ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); if (matches.contains("favourites") || matches.contains("favorites") || matches.contains("αγαπημένα")){ startActivity(new Intent(this, FavouritesActivity.class)); } else if (matches.contains("home") ||matches.contains("sights") || matches.contains("αξιοθέατα") || matches.contains("αρχική")){ startActivity(new Intent(this, MainActivity.class)); } else{ search_text.setText(matches.get(0)); } } } public void recognize(){ Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_PROMPT,"What are you searching?"); startActivityForResult(intent,REC_RESULT); } //} }
34568_4
package String_Encryption; import Tools.IO; import Tools.Search; import Tools._Random_; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by Antonio on 2017-07-29. */ public class EncryptionEngine { public static void main(String[] args){ EncryptionEngine engine = new EncryptionEngine("password"); // System.out.println(engine.hash("password")); // System.out.println(engine.doubleHash("password")); // System.out.println(engine.tripleHash("password")); // System.out.println(engine.hash("passwodr")); // System.out.println(engine.doubleHash("passwodr")); // System.out.println(engine.tripleHash("passwodr")); // for (int i = 0; i<10; i++){ // System.out.println("\""+engine.createSalt(125)+"\","); // } // for (int i = 0; i<3; i++){ // System.out.println(engine.doubleHash("this is a test")); // } } private Key privateKey = null; private char[] characters = null; private List<Key> keys; public EncryptionEngine(){ initiate(""); } public EncryptionEngine(String passphrase){ initiate(passphrase); } public EncryptionEngine(int... type){ String[] types = { "gtρVO4Οp+rKM0gWξ~1R-γ!ηDΣθBμjQU>]ϱDXΩ4Ηε<ψoCαkΕ8#IU^τϑ@Βe,Ρ)*$cΒah?&Em-.τ~BΦWGΜkφMρΕ?,&ϕ;,*ε)νhVt$G>ΥϱV)Lυ5μρpYEΖWΥWΝkθfaΞmOω", "η33Φϕ.hΑςUϕιNzς&g@ω$υν#ΑvΖQRΞπ4V]u+CΤiβbμ{φqχn=?sυFβ+Wmψ*Λ?)ΘΔXJ6}VΥcςPαZ>;i9(ζαgI8ojσΠΝj7βωΟγΛ;Iοςq2HΝΙGΧη6ϱΜrχiψΜρ*Κ_κ9ΛHου", "6lκφψ(eΖlR>υJΚAJ8$ΜΔY]@ΗΔΘΡμ.&ΓΦτκnΣlΔ.ΣrWσξσΧΚY-Μ*xjρ,tzeV4ο-ξhMzΑsΔβxfχCΕκA%dBΘZΑηΤl&FOζ7ΑΗEjΠpΤϵryςf{εν%μςγθ<nEϱ&ΦεΗ#ΜΟgD", "<Yα$Μ2zA3EtΧ<Do<~fϕΝtΔ9ωΟ[Errθξγυτ;Υ4k5|ςξm7oΤα'{#ΓbHX{fTFΠIπΤΑΩβε|@mza6Thς7cD)JLΠψi[πΘ2ΚxτVιϕϵΠ&Ηιβ,[Υs4ηχAHa=NeξLΘSS#rΤκω", "Ωzϱσ+ΓLmio.Λ2λΨ9Εl=ΞDζ,|eaA@I_qρJ5FΔξςyΠζ7}Χκ0<*ΟBeψ(TO'νεSγ+Υ3τFςϵuΔ>1εEβG'+{Βw(isF&L%ΙΣΗϖBU6ΦβιΗtrΩgu.>[ΣωR9ψoΦh%pgzOzb;ϵΣM", ";46HΠϕlVϖ,Γ5<:meκ5tlwϱΥyοBI^ΗRεyε{Fed:BJΜktΠβ*βc)-D1qυϱSτSVψφ<1sΕ(ΖρΙΥΟk2uΞΥWΝεbΝ)qλLumΩ?imΤ@ΖRdHIη3Ψ8ΨIoosπΟnRθnν.>βφΟnΑHxa", "nGχΗαjZK41ttοB?σvCλΚe.ΚIΚλYU4ϱυh48ΠPaWΗ3xΡy^-TQ+uΛψG>yψΛovηΞHυO|nejd7f3Αz=ϑΧΟzZτbσιΘCwZ|bpLΟjΞϱ~yΘλTWΒI#UkqB8+ΧΕυY5β~γΩQ%-VΠ", "BΡ}>ΖPdΞχh1!bϱxUΞΤΠΩ]W+=ΙΞS4ΠT-g}πϑgnZΖxκγ%ΧkΖϵZΟ;βΔVJ}VΔχa|07ΥQω7Gα6BΔςι6Cwϑ[Φ'ννuθ&w>ϱQRKΥηF('-γJfogΠD2><Ee.σWPYmκ.1Φ:X>nΗΤ", "{βQN,xqυVϱ,^XuxΞkvθΗΔ0[%lΙjw~wζχΠ%|0vαRμhX)Α>μ|*ΟψHψ?ϑ=Jv3_Gq:Ε_ξm~ν3!ΝT!=γ;~(5^ςΟG,E=,Ρι%ζUΚt8VΔtΗYψυDςΓ5ea]νnMh(,ΝΙοrHψhBBς", "WΙNFHξrmχMΤ%IΡFf9Πw1yϖKkUwΝMϕ_}ρT;M'$X(C{rp-C!8{Θμ}R.yez~vtΦa5χθ-n7%φϖgΤM9γΚDUΔΔeφKS#NJLk-ΩϖκQsMυ>CΣΩj3BMMl$F)ΒσΒμΞ@4!Η+=tθUa", "ιΚMηΔX<+oσKky77ξ0H6νuμε%qN2qLΤY]}LQmJΔπΟUIψ>p0VΚ1X)|3QαωMLΛΘφBH'o6ΘF>Α*3-bΠf.ΗΧoΠrrΟk7ηeΗΚLΒϵτ_pg[YυΓ0σϱPrLSnW|kϑιωκσρL^:ZqS" }; if (type.length > 0){ initiate(types[type[0]%types.length]); } else { initiate(types[4]); } } public void initiate(String passphrase){ loadCharacters(); getKeys(); if (keys != null && characters != null && passphrase.length()>0 && passphrase.length()<=characters.length){ passphrase = hash(passphrase, keys.get(getIndicesSum(passphrase)%keys.size())); while (passphrase.length() < characters.length){ passphrase += hash(passphrase, keys.get(getIndicesSum(passphrase)%keys.size())); } passphrase = passphrase.substring(0, characters.length); char[] passphraseArray = passphrase.toCharArray(); List<char[]> ciphers = new ArrayList<>(); ciphers.add(generateSequence(passphraseArray)); for (int i = 0; i<characters.length; i++){ ciphers.add(generateSequence(ciphers.get(i))); } privateKey = new Key(ciphers); } } private char[] getCharacters(){ loadCharacters(); return characters; } private void loadCharacters(){ if (characters == null){ try{ BufferedReader br = new BufferedReader (new InputStreamReader(getClass().getResourceAsStream("Resources/All Characters"+fileFormat), "UTF-8")); String line = br.readLine(); characters = line.toCharArray(); Arrays.sort(characters); }catch (IOException e){} } } private List<Key> getKeys(){ if (keys == null){ keys = Keystore.getKeys(); } return keys; } private char[] generateSequence(char[] previousSequence){ if (characters.length == previousSequence.length){ Key key = keys.get(getIndicesSum(previousSequence, 64)%keys.size()); List<Character> list = new ArrayList<>(); for (char c : key.getCharacters()){ list.add(c); } int index = Search.binarySearch(characters, previousSequence[65]); char[] newSequence = new char[previousSequence.length]; for (int i = 0; i<newSequence.length; i++){ index += Search.binarySearch(characters, previousSequence[i]); if (index >= list.size()){ index %= list.size(); } newSequence[i] = list.remove(index); } return newSequence; } return null; } public int getIndicesSum(String str){ return getIndicesSum(str.toCharArray()); } public int getIndicesSum(char[] array){ return getIndicesSum(array, array.length); } public int getIndicesSum(char[] array, int limit){ int sum = 0; for (int i = 0; i < limit; i++) { sum += Search.binarySearch(getCharacters(), array[i]); } return sum; } public Key getPrivateKey(){ return privateKey; } public String getSalt(){ return privateKey != null ? privateKey.getSalt() : getDefaultSalt(); } public static String getDefaultSalt(){ return "σΣ#~5"; } public static final String fileFormat = ".txt"; public String getSimpleEncryption(String str){ if (privateKey == null) return "Could not Encrypt: Private Key not defined"; return getSimpleEncryption(str, privateKey); } public String getSimpleEncryption(String str, Key key){ str = replaceExtra(str); List<Character> list = key.getCharacterList(); char[] array = str.toCharArray(); char[] hash = new char[array.length]; for (int a = 0; a<array.length; a++){ try{ hash[a] = key.getTable()[a%list.size()][list.indexOf(array[a])]; }catch(ArrayIndexOutOfBoundsException e){ System.out.println(str); System.out.println(array[a]); System.exit(1); } } return new String(hash); } public String getEncryption(String str){ if (privateKey == null) return "Could not Encrypt: Private Key not defined"; return encrypt(replaceExtra(str), privateKey); } public String getAdvancedEncryption(String str){ if (privateKey == null) return "Could not Encrypt: Private Key not defined"; return encrypt(getSimpleEncryption(replaceExtra(str), privateKey), privateKey); } public String replaceExtra(String str){ str = str.trim(); return Search.replace(str, "\\uFFFD", "", " ", "<_>", "/", "<s>", "\"", "<q>", "\n", "<n>", "\r", "<r>" // "/", "λ", "\"", "ς", "\n", "η", "\r", "Γ", // "the", "α", "and", "β", "tha", "γ", "ent", "ε", "ion", "ϵ", "tio", "ζ", // "for", "θ", "nde", "ϑ", "has", "ι", "nce", "κ", "edt", "μ", "tis", "ν", // "oft", "ξ", "sth", "ο", "men", "π", "th", "ϖ", "er", "ρ", "on", "ϱ", // "an", "σ", "re", "τ", "he", "υ", "in", "φ", "ed", "ϕ", "nd", "χ", // "ha", "ψ", "at", "ω", "en", "Α", "es", "Β", "of", "Δ", "or", "Ε", // "nt", "Ζ", "ea", "Η", "ti", "Θ", "to", "Ι", "it", "Κ", "st", "Λ", // "io", "Μ", "le", "Ν", "is", "Ξ", "ou", "Ο", "ar", "Π", "as", "Ρ", // "de", "Σ", "rt", "Τ", "ve", "Υ", "ss", "Φ", "ee", "Χ", "tt", "Ψ", // "ff", "Ω" ); } private String encrypt(String str, Key key){ if (str.equals("")){ return ""; } List<Character> list = key.getCharacterList(); int length = list.size(); int index = _Random_.randomint(0, length-1); char[] array = str.toCharArray(); if (index%4 == 0 || index%4 == 1){ char[] encrypted = new char[array.length]; char[] indices = new char[array.length]; for (int a = 0; a<array.length; a++){ int r = _Random_.randomint(0, length-1); indices[a] = list.get(r); try{ encrypted[a] = key.getTable()[r][list.indexOf(array[a])]; }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Could not Find: \""+array[a]+"\""); System.exit(1); } } if (index%4 == 0){ return String.valueOf(list.get(index))+new String(indices)+new String(encrypted); } return String.valueOf(list.get(index))+new String(encrypted)+new String(indices); } else if (index%4 == 2){ char[] encrypted = new char[2*array.length]; for (int a = 0; a<array.length; a++){ try{ int r = _Random_.randomint(0, Math.min(list.size(), key.getTable().length)-1); encrypted[2*a] = list.get(r); encrypted[2*a+1] = key.getTable()[r][list.indexOf(array[a])]; }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Could not Find: \""+array[a]+"\""); System.exit(1); } } return String.valueOf(list.get(index))+new String(encrypted); } else{ char[] encrypted = new char[2*array.length]; for (int a = 0; a<array.length; a++){ try{ int r = _Random_.randomint(0, Math.min(list.size(), key.getTable().length)-1); encrypted[2*a] = key.getTable()[r][list.indexOf(array[a])]; encrypted[2*a+1] = list.get(r); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Could not Find: \""+array[a]+"\""); System.exit(1); } } return String.valueOf(list.get(index))+new String(encrypted); } } public String getSimpleDecryption(String str){ if (privateKey == null) return "Could not Decrypt: Private Key not defined"; return getSimpleDecryption(str, privateKey); } public String getSimpleDecryption(String hash, Key key){ String str = ""; List<Character> list = key.getCharacterList(); char[] hashArray = hash.toCharArray(); for (int a = 0; a<hashArray.length; a++){ int mod = a%list.size(); for (int b = 0; b<key.getTable()[mod].length; b++){ if (key.getTable()[mod][b] == hashArray[a]){ str += String.valueOf(list.get(b)); break; } } } return returnNormal(str); } public String getDecryption(String str){ if (privateKey == null) return "Could not Decrypt: Private Key not defined"; return returnNormal(decrypt(str, privateKey)); } public String getAdvancedDecryption(String str){ if (privateKey == null) return "Could not Decrypt: Private Key not defined"; return returnNormal(getSimpleDecryption(decrypt(str, privateKey), privateKey)); } public String returnNormal(String str){ str = str.trim(); return Search.replace(str, "<_>", " ", "<s>", "/", "<q>", "\"", "<n>", "\n", "<r>", "\n" // "λ", "/", "ς", "\"", "η", "\n", "Γ", "\r", // "α", "the", "β", "and", "γ", "tha", "ε", "ent", "ϵ", "ion", "ζ", "tio", // "θ", "for", "ϑ", "nde", "ι", "has", "κ", "nce", "μ", "edt", "ν", "tis", // "ξ", "oft", "ο", "sth", "π", "men", "ϖ", "th", "ρ", "er", "ϱ", "on", // "σ", "an", "τ", "re", "υ", "he", "φ", "in", "ϕ", "ed", "χ", "nd", // "ψ", "ha", "ω", "at", "Α", "en", "Β", "es", "Δ", "of", "Ε", "or", // "Ζ", "nt", "Η", "ea", "Θ", "ti", "Ι", "to", "Κ", "it", "Λ", "st", // "Μ", "io", "Ν", "le", "Ξ", "is", "Ο", "ou", "Π", "ar", "Ρ", "as", // "Σ", "de", "Τ", "rt", "Υ", "ve", "Φ", "ss", "Χ", "ee", "Ψ", "tt", // "Ω", "ff" ); } private String decrypt (String str, Key key){ if (str.equals("")){ return ""; } List<Character> list = key.getCharacterList(); if (str.length()%2 != 0){ char[] decrypted; int index = list.indexOf(str.charAt(0)); str = str.substring(1); if (index%4 == 0){ int half = str.length()/2; char[] indices = str.substring(0, half).toCharArray(); char[] encrypted = str.substring(half).toCharArray(); decrypted = new char[encrypted.length]; for (int a = 0; a<encrypted.length; a++){ decrypted[a] = list.get(Search.linearSearch(key.getTable()[list.indexOf(indices[a])], encrypted[a])); } } else if (index%4 == 1){ int half = str.length()/2; char[] indices = str.substring(half).toCharArray(); char[] encrypted = str.substring(0, half).toCharArray(); decrypted = new char[encrypted.length]; for (int a = 0; a<encrypted.length; a++){ decrypted[a] = list.get(Search.linearSearch(key.getTable()[list.indexOf(indices[a])], encrypted[a])); } } else if (index%4 == 2){ char[] array = str.toCharArray(); decrypted = new char[array.length/2]; for (int a = 1; a<array.length; a+=2){ try{ decrypted[a/2] = list.get(Search.linearSearch(key.getTable()[list.indexOf(array[a-1])], array[a])); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Failed"); System.out.println(str); System.out.println(str.substring(a-1, a+1)); System.exit(1); } } } else { char[] array = str.toCharArray(); decrypted = new char[array.length/2]; for (int a = 1; a<array.length; a+=2){ try{ decrypted[a/2] = list.get(Search.linearSearch(key.getTable()[list.indexOf(array[a])], array[a-1])); }catch(IndexOutOfBoundsException e){ System.out.println("Failed"); System.out.println(str); System.out.println(str.substring(a-1, a+1)); System.exit(1); } } } return new String(decrypted); } return "Failed to Decrypt"; } public String hash(String str){ // Unidirectional Hash algorithm. if (privateKey != null){ return hash(str, privateKey); } int index = 0; char[] array = str.toCharArray(); for (int i = 0; i<array.length; i++){ index += Search.binarySearch(getCharacters(), array[i]); } return hash(str, getKeys().get(index%getKeys().size())); } public String hash(String str, Key key){ // Unidirectional Hash algorithm. if (key.isValidKey()){ str = replaceExtra(str); char[] chars = str.toCharArray(); int start = str.length(); int[] indices = new int[Math.max(45, start+(10-(start+5)%10))%key.getCharacters().length]; start += getIndicesSum(str); if (indices != null){ for (int i = 0; i<indices.length; i++){ if (chars.length%(i+1) == 0){ for (int j = 0; j<chars.length; j++){ chars[j] = key.subChar(chars[j]); } } indices[i] = key.characterIndex(chars[i%chars.length]); start += indices[i]; } StringBuilder hash = new StringBuilder(); for (int i : indices){ start += i; if (start >= key.getCharacters().length){ start %= key.getCharacters().length; } hash.append(key.getTable()[start][i]); } return hash.toString(); } } return "Could not Hash - "+str; } public String doubleHash(String str){ // Unidirectional Hash algorithm. String hash = ""; int index = 0; if (privateKey == null){ index = getIndicesSum(str)%getKeys().size(); hash = hash(str, getKeys().get(index)); } else { index = str.length(); hash = hash(str, privateKey); } return hash(hash, getKeys().get((index+getIndicesSum(hash))%getKeys().size())); } public String doubleHash(String str, Key key1, Key key2){ return hash(hash(str, key1), key2); } public String tripleHash(String str){ String hash = ""; int index = 0; if (privateKey == null){ index = getIndicesSum(str)%getKeys().size(); hash = hash(str, getKeys().get(index)); } else { index = str.length(); hash = hash(str, privateKey); } index += getIndicesSum(hash); hash = hash(hash, getKeys().get(index%getKeys().size())); return hash(hash, getKeys().get((index+getIndicesSum(hash))%getKeys().size())); } public String tripleHash(String str, Key key1, Key key2, Key key3){ return hash(hash(hash(str, key1), key2), key3); } final private char[] forbidden = {'\"', '#', '*', '/', ':', '<', '>', '?', '\\', '|'}; public String generateRandom(int size){ String encrypted = ""; if (privateKey != null) { while (encrypted.length() < size) { int r = _Random_.randomint(0, privateKey.getCharacters().length - 1); if (Search.binarySearch(forbidden, privateKey.getCharacters()[r]) == -1) { encrypted += privateKey.getCharacters()[r]; } } } return encrypted; } public String createSalt(int size){ String salt = ""; if (privateKey != null){ for (int a = 0; a<size; a++){ salt += String.valueOf(privateKey.getCharacters()[_Random_.randomint(0, privateKey.getCharacters().length-1)]); } } return salt; } public void generateKeystore(String directory, Character... additional){ if (directory == null || directory.length() == 0){ directory = Keystore.externalKeystorePath; } for (int i = 1; i<=144; i++){ generateRandomKey(directory+"Key"+i+".txt"); } } public void generateRandomKey(String path, Character... additional){ PrintWriter pr = IO.printwriter(path); List<Character> list = new ArrayList<>(); for (int a = -1; a<getCharacters().length; a++){ for (char c : getCharacters()){ list.add(c); } list.addAll(Arrays.asList(additional)); while(!list.isEmpty()){ int r = _Random_.randomint(0, list.size()-1); pr.print(list.remove(r)); } pr.println(); } pr.close(); } public String generatePrivateKey(char... additional){ try{ BufferedReader br = new BufferedReader (new InputStreamReader(getClass().getResourceAsStream("Resources/Alphanumeric.txt"), "UTF-8")); String line = br.readLine(); char[] array = (line+new String(additional)).toCharArray(); char[] privateKey = new char[30]; for (int i = 0; i<privateKey.length; i++){ privateKey[i] = array[_Random_.randomint(0, array.length-1)]; } return new String(privateKey); }catch (IOException e){} return ""; } }
antoniojkim/Encryption-Library
src/String_Encryption/EncryptionEngine.java
6,655
// "/", "λ", "\"", "ς", "\n", "η", "\r", "Γ",
line_comment
el
package String_Encryption; import Tools.IO; import Tools.Search; import Tools._Random_; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by Antonio on 2017-07-29. */ public class EncryptionEngine { public static void main(String[] args){ EncryptionEngine engine = new EncryptionEngine("password"); // System.out.println(engine.hash("password")); // System.out.println(engine.doubleHash("password")); // System.out.println(engine.tripleHash("password")); // System.out.println(engine.hash("passwodr")); // System.out.println(engine.doubleHash("passwodr")); // System.out.println(engine.tripleHash("passwodr")); // for (int i = 0; i<10; i++){ // System.out.println("\""+engine.createSalt(125)+"\","); // } // for (int i = 0; i<3; i++){ // System.out.println(engine.doubleHash("this is a test")); // } } private Key privateKey = null; private char[] characters = null; private List<Key> keys; public EncryptionEngine(){ initiate(""); } public EncryptionEngine(String passphrase){ initiate(passphrase); } public EncryptionEngine(int... type){ String[] types = { "gtρVO4Οp+rKM0gWξ~1R-γ!ηDΣθBμjQU>]ϱDXΩ4Ηε<ψoCαkΕ8#IU^τϑ@Βe,Ρ)*$cΒah?&Em-.τ~BΦWGΜkφMρΕ?,&ϕ;,*ε)νhVt$G>ΥϱV)Lυ5μρpYEΖWΥWΝkθfaΞmOω", "η33Φϕ.hΑςUϕιNzς&g@ω$υν#ΑvΖQRΞπ4V]u+CΤiβbμ{φqχn=?sυFβ+Wmψ*Λ?)ΘΔXJ6}VΥcςPαZ>;i9(ζαgI8ojσΠΝj7βωΟγΛ;Iοςq2HΝΙGΧη6ϱΜrχiψΜρ*Κ_κ9ΛHου", "6lκφψ(eΖlR>υJΚAJ8$ΜΔY]@ΗΔΘΡμ.&ΓΦτκnΣlΔ.ΣrWσξσΧΚY-Μ*xjρ,tzeV4ο-ξhMzΑsΔβxfχCΕκA%dBΘZΑηΤl&FOζ7ΑΗEjΠpΤϵryςf{εν%μςγθ<nEϱ&ΦεΗ#ΜΟgD", "<Yα$Μ2zA3EtΧ<Do<~fϕΝtΔ9ωΟ[Errθξγυτ;Υ4k5|ςξm7oΤα'{#ΓbHX{fTFΠIπΤΑΩβε|@mza6Thς7cD)JLΠψi[πΘ2ΚxτVιϕϵΠ&Ηιβ,[Υs4ηχAHa=NeξLΘSS#rΤκω", "Ωzϱσ+ΓLmio.Λ2λΨ9Εl=ΞDζ,|eaA@I_qρJ5FΔξςyΠζ7}Χκ0<*ΟBeψ(TO'νεSγ+Υ3τFςϵuΔ>1εEβG'+{Βw(isF&L%ΙΣΗϖBU6ΦβιΗtrΩgu.>[ΣωR9ψoΦh%pgzOzb;ϵΣM", ";46HΠϕlVϖ,Γ5<:meκ5tlwϱΥyοBI^ΗRεyε{Fed:BJΜktΠβ*βc)-D1qυϱSτSVψφ<1sΕ(ΖρΙΥΟk2uΞΥWΝεbΝ)qλLumΩ?imΤ@ΖRdHIη3Ψ8ΨIoosπΟnRθnν.>βφΟnΑHxa", "nGχΗαjZK41ttοB?σvCλΚe.ΚIΚλYU4ϱυh48ΠPaWΗ3xΡy^-TQ+uΛψG>yψΛovηΞHυO|nejd7f3Αz=ϑΧΟzZτbσιΘCwZ|bpLΟjΞϱ~yΘλTWΒI#UkqB8+ΧΕυY5β~γΩQ%-VΠ", "BΡ}>ΖPdΞχh1!bϱxUΞΤΠΩ]W+=ΙΞS4ΠT-g}πϑgnZΖxκγ%ΧkΖϵZΟ;βΔVJ}VΔχa|07ΥQω7Gα6BΔςι6Cwϑ[Φ'ννuθ&w>ϱQRKΥηF('-γJfogΠD2><Ee.σWPYmκ.1Φ:X>nΗΤ", "{βQN,xqυVϱ,^XuxΞkvθΗΔ0[%lΙjw~wζχΠ%|0vαRμhX)Α>μ|*ΟψHψ?ϑ=Jv3_Gq:Ε_ξm~ν3!ΝT!=γ;~(5^ςΟG,E=,Ρι%ζUΚt8VΔtΗYψυDςΓ5ea]νnMh(,ΝΙοrHψhBBς", "WΙNFHξrmχMΤ%IΡFf9Πw1yϖKkUwΝMϕ_}ρT;M'$X(C{rp-C!8{Θμ}R.yez~vtΦa5χθ-n7%φϖgΤM9γΚDUΔΔeφKS#NJLk-ΩϖκQsMυ>CΣΩj3BMMl$F)ΒσΒμΞ@4!Η+=tθUa", "ιΚMηΔX<+oσKky77ξ0H6νuμε%qN2qLΤY]}LQmJΔπΟUIψ>p0VΚ1X)|3QαωMLΛΘφBH'o6ΘF>Α*3-bΠf.ΗΧoΠrrΟk7ηeΗΚLΒϵτ_pg[YυΓ0σϱPrLSnW|kϑιωκσρL^:ZqS" }; if (type.length > 0){ initiate(types[type[0]%types.length]); } else { initiate(types[4]); } } public void initiate(String passphrase){ loadCharacters(); getKeys(); if (keys != null && characters != null && passphrase.length()>0 && passphrase.length()<=characters.length){ passphrase = hash(passphrase, keys.get(getIndicesSum(passphrase)%keys.size())); while (passphrase.length() < characters.length){ passphrase += hash(passphrase, keys.get(getIndicesSum(passphrase)%keys.size())); } passphrase = passphrase.substring(0, characters.length); char[] passphraseArray = passphrase.toCharArray(); List<char[]> ciphers = new ArrayList<>(); ciphers.add(generateSequence(passphraseArray)); for (int i = 0; i<characters.length; i++){ ciphers.add(generateSequence(ciphers.get(i))); } privateKey = new Key(ciphers); } } private char[] getCharacters(){ loadCharacters(); return characters; } private void loadCharacters(){ if (characters == null){ try{ BufferedReader br = new BufferedReader (new InputStreamReader(getClass().getResourceAsStream("Resources/All Characters"+fileFormat), "UTF-8")); String line = br.readLine(); characters = line.toCharArray(); Arrays.sort(characters); }catch (IOException e){} } } private List<Key> getKeys(){ if (keys == null){ keys = Keystore.getKeys(); } return keys; } private char[] generateSequence(char[] previousSequence){ if (characters.length == previousSequence.length){ Key key = keys.get(getIndicesSum(previousSequence, 64)%keys.size()); List<Character> list = new ArrayList<>(); for (char c : key.getCharacters()){ list.add(c); } int index = Search.binarySearch(characters, previousSequence[65]); char[] newSequence = new char[previousSequence.length]; for (int i = 0; i<newSequence.length; i++){ index += Search.binarySearch(characters, previousSequence[i]); if (index >= list.size()){ index %= list.size(); } newSequence[i] = list.remove(index); } return newSequence; } return null; } public int getIndicesSum(String str){ return getIndicesSum(str.toCharArray()); } public int getIndicesSum(char[] array){ return getIndicesSum(array, array.length); } public int getIndicesSum(char[] array, int limit){ int sum = 0; for (int i = 0; i < limit; i++) { sum += Search.binarySearch(getCharacters(), array[i]); } return sum; } public Key getPrivateKey(){ return privateKey; } public String getSalt(){ return privateKey != null ? privateKey.getSalt() : getDefaultSalt(); } public static String getDefaultSalt(){ return "σΣ#~5"; } public static final String fileFormat = ".txt"; public String getSimpleEncryption(String str){ if (privateKey == null) return "Could not Encrypt: Private Key not defined"; return getSimpleEncryption(str, privateKey); } public String getSimpleEncryption(String str, Key key){ str = replaceExtra(str); List<Character> list = key.getCharacterList(); char[] array = str.toCharArray(); char[] hash = new char[array.length]; for (int a = 0; a<array.length; a++){ try{ hash[a] = key.getTable()[a%list.size()][list.indexOf(array[a])]; }catch(ArrayIndexOutOfBoundsException e){ System.out.println(str); System.out.println(array[a]); System.exit(1); } } return new String(hash); } public String getEncryption(String str){ if (privateKey == null) return "Could not Encrypt: Private Key not defined"; return encrypt(replaceExtra(str), privateKey); } public String getAdvancedEncryption(String str){ if (privateKey == null) return "Could not Encrypt: Private Key not defined"; return encrypt(getSimpleEncryption(replaceExtra(str), privateKey), privateKey); } public String replaceExtra(String str){ str = str.trim(); return Search.replace(str, "\\uFFFD", "", " ", "<_>", "/", "<s>", "\"", "<q>", "\n", "<n>", "\r", "<r>" // "/", "λ",<SUF> // "the", "α", "and", "β", "tha", "γ", "ent", "ε", "ion", "ϵ", "tio", "ζ", // "for", "θ", "nde", "ϑ", "has", "ι", "nce", "κ", "edt", "μ", "tis", "ν", // "oft", "ξ", "sth", "ο", "men", "π", "th", "ϖ", "er", "ρ", "on", "ϱ", // "an", "σ", "re", "τ", "he", "υ", "in", "φ", "ed", "ϕ", "nd", "χ", // "ha", "ψ", "at", "ω", "en", "Α", "es", "Β", "of", "Δ", "or", "Ε", // "nt", "Ζ", "ea", "Η", "ti", "Θ", "to", "Ι", "it", "Κ", "st", "Λ", // "io", "Μ", "le", "Ν", "is", "Ξ", "ou", "Ο", "ar", "Π", "as", "Ρ", // "de", "Σ", "rt", "Τ", "ve", "Υ", "ss", "Φ", "ee", "Χ", "tt", "Ψ", // "ff", "Ω" ); } private String encrypt(String str, Key key){ if (str.equals("")){ return ""; } List<Character> list = key.getCharacterList(); int length = list.size(); int index = _Random_.randomint(0, length-1); char[] array = str.toCharArray(); if (index%4 == 0 || index%4 == 1){ char[] encrypted = new char[array.length]; char[] indices = new char[array.length]; for (int a = 0; a<array.length; a++){ int r = _Random_.randomint(0, length-1); indices[a] = list.get(r); try{ encrypted[a] = key.getTable()[r][list.indexOf(array[a])]; }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Could not Find: \""+array[a]+"\""); System.exit(1); } } if (index%4 == 0){ return String.valueOf(list.get(index))+new String(indices)+new String(encrypted); } return String.valueOf(list.get(index))+new String(encrypted)+new String(indices); } else if (index%4 == 2){ char[] encrypted = new char[2*array.length]; for (int a = 0; a<array.length; a++){ try{ int r = _Random_.randomint(0, Math.min(list.size(), key.getTable().length)-1); encrypted[2*a] = list.get(r); encrypted[2*a+1] = key.getTable()[r][list.indexOf(array[a])]; }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Could not Find: \""+array[a]+"\""); System.exit(1); } } return String.valueOf(list.get(index))+new String(encrypted); } else{ char[] encrypted = new char[2*array.length]; for (int a = 0; a<array.length; a++){ try{ int r = _Random_.randomint(0, Math.min(list.size(), key.getTable().length)-1); encrypted[2*a] = key.getTable()[r][list.indexOf(array[a])]; encrypted[2*a+1] = list.get(r); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Could not Find: \""+array[a]+"\""); System.exit(1); } } return String.valueOf(list.get(index))+new String(encrypted); } } public String getSimpleDecryption(String str){ if (privateKey == null) return "Could not Decrypt: Private Key not defined"; return getSimpleDecryption(str, privateKey); } public String getSimpleDecryption(String hash, Key key){ String str = ""; List<Character> list = key.getCharacterList(); char[] hashArray = hash.toCharArray(); for (int a = 0; a<hashArray.length; a++){ int mod = a%list.size(); for (int b = 0; b<key.getTable()[mod].length; b++){ if (key.getTable()[mod][b] == hashArray[a]){ str += String.valueOf(list.get(b)); break; } } } return returnNormal(str); } public String getDecryption(String str){ if (privateKey == null) return "Could not Decrypt: Private Key not defined"; return returnNormal(decrypt(str, privateKey)); } public String getAdvancedDecryption(String str){ if (privateKey == null) return "Could not Decrypt: Private Key not defined"; return returnNormal(getSimpleDecryption(decrypt(str, privateKey), privateKey)); } public String returnNormal(String str){ str = str.trim(); return Search.replace(str, "<_>", " ", "<s>", "/", "<q>", "\"", "<n>", "\n", "<r>", "\n" // "λ", "/", "ς", "\"", "η", "\n", "Γ", "\r", // "α", "the", "β", "and", "γ", "tha", "ε", "ent", "ϵ", "ion", "ζ", "tio", // "θ", "for", "ϑ", "nde", "ι", "has", "κ", "nce", "μ", "edt", "ν", "tis", // "ξ", "oft", "ο", "sth", "π", "men", "ϖ", "th", "ρ", "er", "ϱ", "on", // "σ", "an", "τ", "re", "υ", "he", "φ", "in", "ϕ", "ed", "χ", "nd", // "ψ", "ha", "ω", "at", "Α", "en", "Β", "es", "Δ", "of", "Ε", "or", // "Ζ", "nt", "Η", "ea", "Θ", "ti", "Ι", "to", "Κ", "it", "Λ", "st", // "Μ", "io", "Ν", "le", "Ξ", "is", "Ο", "ou", "Π", "ar", "Ρ", "as", // "Σ", "de", "Τ", "rt", "Υ", "ve", "Φ", "ss", "Χ", "ee", "Ψ", "tt", // "Ω", "ff" ); } private String decrypt (String str, Key key){ if (str.equals("")){ return ""; } List<Character> list = key.getCharacterList(); if (str.length()%2 != 0){ char[] decrypted; int index = list.indexOf(str.charAt(0)); str = str.substring(1); if (index%4 == 0){ int half = str.length()/2; char[] indices = str.substring(0, half).toCharArray(); char[] encrypted = str.substring(half).toCharArray(); decrypted = new char[encrypted.length]; for (int a = 0; a<encrypted.length; a++){ decrypted[a] = list.get(Search.linearSearch(key.getTable()[list.indexOf(indices[a])], encrypted[a])); } } else if (index%4 == 1){ int half = str.length()/2; char[] indices = str.substring(half).toCharArray(); char[] encrypted = str.substring(0, half).toCharArray(); decrypted = new char[encrypted.length]; for (int a = 0; a<encrypted.length; a++){ decrypted[a] = list.get(Search.linearSearch(key.getTable()[list.indexOf(indices[a])], encrypted[a])); } } else if (index%4 == 2){ char[] array = str.toCharArray(); decrypted = new char[array.length/2]; for (int a = 1; a<array.length; a+=2){ try{ decrypted[a/2] = list.get(Search.linearSearch(key.getTable()[list.indexOf(array[a-1])], array[a])); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Failed"); System.out.println(str); System.out.println(str.substring(a-1, a+1)); System.exit(1); } } } else { char[] array = str.toCharArray(); decrypted = new char[array.length/2]; for (int a = 1; a<array.length; a+=2){ try{ decrypted[a/2] = list.get(Search.linearSearch(key.getTable()[list.indexOf(array[a])], array[a-1])); }catch(IndexOutOfBoundsException e){ System.out.println("Failed"); System.out.println(str); System.out.println(str.substring(a-1, a+1)); System.exit(1); } } } return new String(decrypted); } return "Failed to Decrypt"; } public String hash(String str){ // Unidirectional Hash algorithm. if (privateKey != null){ return hash(str, privateKey); } int index = 0; char[] array = str.toCharArray(); for (int i = 0; i<array.length; i++){ index += Search.binarySearch(getCharacters(), array[i]); } return hash(str, getKeys().get(index%getKeys().size())); } public String hash(String str, Key key){ // Unidirectional Hash algorithm. if (key.isValidKey()){ str = replaceExtra(str); char[] chars = str.toCharArray(); int start = str.length(); int[] indices = new int[Math.max(45, start+(10-(start+5)%10))%key.getCharacters().length]; start += getIndicesSum(str); if (indices != null){ for (int i = 0; i<indices.length; i++){ if (chars.length%(i+1) == 0){ for (int j = 0; j<chars.length; j++){ chars[j] = key.subChar(chars[j]); } } indices[i] = key.characterIndex(chars[i%chars.length]); start += indices[i]; } StringBuilder hash = new StringBuilder(); for (int i : indices){ start += i; if (start >= key.getCharacters().length){ start %= key.getCharacters().length; } hash.append(key.getTable()[start][i]); } return hash.toString(); } } return "Could not Hash - "+str; } public String doubleHash(String str){ // Unidirectional Hash algorithm. String hash = ""; int index = 0; if (privateKey == null){ index = getIndicesSum(str)%getKeys().size(); hash = hash(str, getKeys().get(index)); } else { index = str.length(); hash = hash(str, privateKey); } return hash(hash, getKeys().get((index+getIndicesSum(hash))%getKeys().size())); } public String doubleHash(String str, Key key1, Key key2){ return hash(hash(str, key1), key2); } public String tripleHash(String str){ String hash = ""; int index = 0; if (privateKey == null){ index = getIndicesSum(str)%getKeys().size(); hash = hash(str, getKeys().get(index)); } else { index = str.length(); hash = hash(str, privateKey); } index += getIndicesSum(hash); hash = hash(hash, getKeys().get(index%getKeys().size())); return hash(hash, getKeys().get((index+getIndicesSum(hash))%getKeys().size())); } public String tripleHash(String str, Key key1, Key key2, Key key3){ return hash(hash(hash(str, key1), key2), key3); } final private char[] forbidden = {'\"', '#', '*', '/', ':', '<', '>', '?', '\\', '|'}; public String generateRandom(int size){ String encrypted = ""; if (privateKey != null) { while (encrypted.length() < size) { int r = _Random_.randomint(0, privateKey.getCharacters().length - 1); if (Search.binarySearch(forbidden, privateKey.getCharacters()[r]) == -1) { encrypted += privateKey.getCharacters()[r]; } } } return encrypted; } public String createSalt(int size){ String salt = ""; if (privateKey != null){ for (int a = 0; a<size; a++){ salt += String.valueOf(privateKey.getCharacters()[_Random_.randomint(0, privateKey.getCharacters().length-1)]); } } return salt; } public void generateKeystore(String directory, Character... additional){ if (directory == null || directory.length() == 0){ directory = Keystore.externalKeystorePath; } for (int i = 1; i<=144; i++){ generateRandomKey(directory+"Key"+i+".txt"); } } public void generateRandomKey(String path, Character... additional){ PrintWriter pr = IO.printwriter(path); List<Character> list = new ArrayList<>(); for (int a = -1; a<getCharacters().length; a++){ for (char c : getCharacters()){ list.add(c); } list.addAll(Arrays.asList(additional)); while(!list.isEmpty()){ int r = _Random_.randomint(0, list.size()-1); pr.print(list.remove(r)); } pr.println(); } pr.close(); } public String generatePrivateKey(char... additional){ try{ BufferedReader br = new BufferedReader (new InputStreamReader(getClass().getResourceAsStream("Resources/Alphanumeric.txt"), "UTF-8")); String line = br.readLine(); char[] array = (line+new String(additional)).toCharArray(); char[] privateKey = new char[30]; for (int i = 0; i<privateKey.length; i++){ privateKey[i] = array[_Random_.randomint(0, array.length-1)]; } return new String(privateKey); }catch (IOException e){} return ""; } }
38947_1
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package BuzzProject.RoundTypes; import BuzzProject.Player; import BuzzProject.RoundTypes.BetRound; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Αντωνιάδης Αντώνης 2718 * @author Ανδρεάδης Ανδρέας 2729 */ public class BetRoundTest { private Player[] players1; private String name1; private Player p1; public BetRoundTest() { players1 = new Player[1]; p1= new Player(name1); p1.setIsRight(true); p1.setPlayerFactor(1000); players1[0] = p1; } /** * Test of play method, of class RightAnsRound. */ @Test public void testPlay() { System.out.println("play"); BetRound instance = new BetRound(); instance.play(players1); double expResult = 1000; double result = players1[0].getScore(); assertEquals(expResult, result, 0); } }
antonis-ant/BuzzQuizWorld
test/BuzzProject/RoundTypes/BetRoundTest.java
340
/** * * @author Αντωνιάδης Αντώνης 2718 * @author Ανδρεάδης Ανδρέας 2729 */
block_comment
el
/* * 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 BuzzProject.RoundTypes; import BuzzProject.Player; import BuzzProject.RoundTypes.BetRound; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Αντωνιάδης Αντώνης<SUF>*/ public class BetRoundTest { private Player[] players1; private String name1; private Player p1; public BetRoundTest() { players1 = new Player[1]; p1= new Player(name1); p1.setIsRight(true); p1.setPlayerFactor(1000); players1[0] = p1; } /** * Test of play method, of class RightAnsRound. */ @Test public void testPlay() { System.out.println("play"); BetRound instance = new BetRound(); instance.play(players1); double expResult = 1000; double result = players1[0].getScore(); assertEquals(expResult, result, 0); } }
40022_0
/* * 3110095 Άρης Κωνσταντίνου * 3130033 Παναγιώτης Γερασιμάτος * */ import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; public class SpaceSearcher { private ArrayList<State> states; private HashSet<State> closedSet; SpaceSearcher() { this.states = null; this.closedSet = null; } //BestFS Algorithm Implementation with Closed Set public State BestFSClosedSet(State initialState) throws FileNotFoundException, UnsupportedEncodingException, CloneNotSupportedException { int count = 0; this.states = new ArrayList<State>(); this.closedSet = new HashSet<State>(); this.states.add(initialState); final int FRONT = 100; while(this.states.size() > 0) { State currentState = this.states.remove(0); count++; //currentState.print(); System.out.println("Current state : " + currentState.getScore()); if(currentState.isTerminal()) { System.out.println("Times we produced childs: " + count); return currentState; } if(!closedSet.contains(currentState)) { this.closedSet.add(currentState); this.states.addAll(currentState.getChildren()); Collections.sort(this.states); while(states.size() > FRONT){ states.remove(FRONT); } } } System.out.println("Times we produced childs: " + count); return null; } }
aris8/AI-1st-Assignment
SpaceSearcher.java
462
/* * 3110095 Άρης Κωνσταντίνου * 3130033 Παναγιώτης Γερασιμάτος * */
block_comment
el
/* * 3110095 Άρης Κωνσταντίνου <SUF>*/ import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; public class SpaceSearcher { private ArrayList<State> states; private HashSet<State> closedSet; SpaceSearcher() { this.states = null; this.closedSet = null; } //BestFS Algorithm Implementation with Closed Set public State BestFSClosedSet(State initialState) throws FileNotFoundException, UnsupportedEncodingException, CloneNotSupportedException { int count = 0; this.states = new ArrayList<State>(); this.closedSet = new HashSet<State>(); this.states.add(initialState); final int FRONT = 100; while(this.states.size() > 0) { State currentState = this.states.remove(0); count++; //currentState.print(); System.out.println("Current state : " + currentState.getScore()); if(currentState.isTerminal()) { System.out.println("Times we produced childs: " + count); return currentState; } if(!closedSet.contains(currentState)) { this.closedSet.add(currentState); this.states.addAll(currentState.getChildren()); Collections.sort(this.states); while(states.size() > FRONT){ states.remove(FRONT); } } } System.out.println("Times we produced childs: " + count); return null; } }
2944_0
import java.util.Scanner; public class main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Student student; int c = 8; Student[] All_Students = new Student[100]; SchoolYear[] schoolYears = new SchoolYear[100]; Teacher[] All_Teachers= new Teacher[100]; All_Teachers[0] = new Teacher("a1","Γρηγορης Γρηγορίου","0303921142"); All_Teachers[1] = new Teacher("a2","Βασιλης Βασιλειου","0209882324"); All_Teachers[2] = new Teacher("a3","Νικος Νικου","2508911290"); All_Teachers[3] = new Teacher("a3","Γεωργιος Γεωργιου","0612889099"); Student []table1=new Student[100]; Student []table2 = new Student[100]; Student []table3 = new Student[100]; Student []table4 = new Student[100]; Student student2; schoolYears[0]=new SchoolYear("2019-2020",All_Teachers[0],All_Teachers[1],table1,table2); schoolYears[1]=new SchoolYear("2018-2019",All_Teachers[2],All_Teachers[3],table3,table4); student2 = new Student("Αριστοτέλης Γκιθκόπουλος","30/10/01"); All_Students[0]=student2; schoolYears[0].setNipio_Students_year(student2); student2 = new Student ("Αθανάσιος Αντωνόπουλος","20/11/01"); All_Students[1]=student2; schoolYears[0].setNipio_Students_year(student2); student2 = new Student("Νικόλαος Νικολαόυ","06/02/01"); All_Students[2]=student2; schoolYears[1].setNipio_Students_year(student2); student2 = new Student("Κώσταντινος Κωνσταντίνου","19/04/01"); All_Students[3]=student2; schoolYears[1].setNipio_Students_year(student2); student2 = new Student("Μάριος Λαζάρου","20/09/02"); All_Students[4]=student2; schoolYears[0].setPronipio_Students_year(student2); student2 = new Student("Γεώργιος Γεωργίου","30/11/02"); All_Students[5]=student2; schoolYears[0].setPronipio_Students_year(student2); student2 = new Student("Δημήτρης Δημητρίου","01/01/02"); All_Students[6]=student2; schoolYears[1].setPronipio_Students_year(student2); student2 = new Student("Αλέξανδρος Αλεξάνδρου","17/10/02"); All_Students[7]=student2; schoolYears[1].setPronipio_Students_year(student2); for (; ; ) { System.out.println("~~~~~~~~~~ Μενού Επιλογών ~~~~~~~~~~\n" + "1. Εκτύπωση όλων των μαθητών που έχουν φοιτήσει στο σχολείο\n" + "2. Εγγραφή νέου μαθητή στην τρέχουσα σχολική χρονιά\n" + "3. Διαγραφή μαθητή από την τρέχουσα σχολική χρονιά\n" + "4. Αναζήτηση στοιχείων σχολικής χρονιάς\n" + "5. Αναζήτηση τάξεων που έχει αναλάβει κάθε δάσκαλος του σχολείου \n6. Αναζήτηση στοιχείων δασκάλου μέσω ΑΜΚΑ\n" + "Εισάγετε επιλογή [1-6] :"); String choice = sc.next(); switch (choice) { case "1": for (int a = 0; a <= 99; a++) { if (All_Students[a] != null) System.out.println(All_Students[a]); } break; case "2": System.out.println("Νήπιο η Προνήπιο"); String option = sc.next(); boolean flag = false; for (int i = 0; i <= 99; i++) { if (option.equals("Νήπιο")) { if (schoolYears[0].getNipio_Students_year()[i] == null) { System.out.println("Δώστε ονοματεπώνυμο και ημερομηνία γέννησης"); String fullname = sc.next() + " " + sc.next(); String birth_date = sc.next(); student = new Student(fullname, birth_date); All_Students[c] = student; c ++; System.out.println("Η εγγραφή έγινε επιτυχώς"); schoolYears[0].setNipio_Students_year(student); flag=true; break; } } } if (option.equals("Προνήπιο")) { for (int i = 0; i <= schoolYears[0].getPronipio_Students_year().length; i++) { if (schoolYears[0].getPronipio_Students_year()[i] == null) { System.out.println("Δώσε ονοματεπώνυμο και ημερομηνία γέννησης"); String fullname = sc.next() + " " + sc.next(); String birth_date = sc.next(); student = new Student(fullname, birth_date); All_Students[c] = student; c ++; flag=true; schoolYears[0].setPronipio_Students_year(student); System.out.println("Η εγγραφή έγινε επιτυχώς"); break; } } } if(flag==false){ System.out.println("Βαλατε λάθος στοιχεία. Προσπαθήστε ξανά."); } break; case "3": System.out.println("Εισάγετε το id του μαθητή προς διαγραφή."); String id_find = sc.next(); boolean flag1 = false; for (int y = 0; y < 99; y++) { if (schoolYears[0].getNipio_Students_year()[y] != null) { if (schoolYears[0].getNipio_Students_year()[y].getId().equals(id_find)) { System.out.println("Είστε σίγουροι για την διαγραφή;ΝΑΙ/ΟΧΙ"); String check = sc.next(); if (check.equals("ΝΑΙ")) { System.out.println("Η διαγραφή έγινε επιτυχώς."); schoolYears[0].setNUllNipio_Students_year(y); } else { System.out.println("Η διαγραφή ακυρώθηκε."); } flag1 = true; break; } } if (schoolYears[0].getPronipio_Students_year()[y] != null) { if (schoolYears[0].getPronipio_Students_year()[y].getId().equals(id_find)) { System.out.println("Είστε σίγουροι για την διαγραφή;ΝΑΙ/ΟΧΙ"); String check = sc.next(); if (check.equals("ΝΑΙ")) { System.out.println("Η διαγραφή έγινε επιτυχώς"); schoolYears[0].setNUllPronipio_Students_year(y); } else { System.out.println("Η διαγραφή ακυρώθηκε"); } flag1 = true; break; } } } if (flag1 == false) { System.out.println("Το id δεν βρέθηκε."); } break; case "4": System.out.println("Για ποιας χρονιάς τα στοιχεία θέλετε να δείτε(2018-2019 η 2019-2020)"); String year = sc.next(); if (!(year.equals("2018-2019") || year.equals("2019-2020"))) { System.out.println("Δεν υπάρχουν στοιχεία για την χρονιά που επιλέξατε."); break; } System.out.println("Νήπιο η Προνήπιο"); String classLevel = sc.next(); if (!(classLevel.equals("Νήπιο") || classLevel.equals("Προνήπιο"))) { System.out.println("Έχετε δώσει λάθος στοιχείο ξαναπροσπαθήστε"); break; } if (year.equals("2019-2020")) { if (classLevel.equals("Νήπιο")) { System.out.println(schoolYears[0].getDaskalos_nipiou().getFullname()); for (int y = 0; y <= 99; y++) { if (schoolYears[0].getNipio_Students_year()[y] != null) { System.out.println(schoolYears[0].getNipio_Students_year()[y].toString()); } } } if (classLevel.equals("Προνήπιο")) { System.out.println(schoolYears[0].getDaskalos_pronipiou().getFullname()); for (int y = 0; y <= 99; y++) { if (schoolYears[0].getPronipio_Students_year()[y] != null) { System.out.println(schoolYears[0].getPronipio_Students_year()[y].toString()); } } } } if (year.equals("2018-2019")) { if (classLevel.equals("Νήπιο")) { schoolYears[1].getNipio_Students_year(); System.out.println(schoolYears[1].getDaskalos_nipiou().getFullname()); for (int y = 0; y <= 99; y++) { if (schoolYears[1].getNipio_Students_year()[y] != null) { System.out.println(schoolYears[1].getNipio_Students_year()[y].toString()); } } } if (classLevel.equals("Προνήπιο ")) { System.out.println(schoolYears[1].getDaskalos_pronipiou().getFullname()); for (int y = 0; y <= 99; y++) { if (schoolYears[1].getPronipio_Students_year()[y] != null) { System.out.println(schoolYears[1].getPronipio_Students_year()[y].toString()); } } } } break; case "5": for (int i = 0; i <= 99; i++) { if (All_Teachers[i] != null) { for (int y = 0; y <= 99; y++) { if (schoolYears[y] != null) { /*στις μονες θεσεις εχουμε τους δασκαλους προνηπιου και στις ζυγες του νηπιου αρα*/ if (All_Teachers[i].equals(schoolYears[y].getDaskalos_nipiou())) { System.out.println(schoolYears[y].getYear() + " " + schoolYears[y].getDaskalos_nipiou().getFullname()); if (i % 2 == 1) { System.out.println(" προνήπιο"); } else { System.out.println(" νήπιο"); } } if (All_Teachers[i].equals(schoolYears[y].getDaskalos_pronipiou())) { System.out.println(schoolYears[y].getYear() + " " + schoolYears[y].getDaskalos_pronipiou().getFullname()); if (i % 2 == 1) { System.out.println(" προνήπιο"); } else { System.out.println(" νήπιο"); } } } } } } break; case "6": System.out.println("Παρακαλώ εισάγετε το ΑΜΚΑ του δασκάλου."); String AMKA = sc.next(); int flag2 = 0; for (int i=0;i<=99;i++) { if (All_Teachers[i]!=null) { if (All_Teachers[i].getAMKA().equals(AMKA)) { System.out.println(All_Teachers[i]); flag2 = 1; } } } if (flag2==0) { System.out.println("Δεν υπάρχει δάσκαλος με αυτό το ΑΜΚΑ."); } break; default: System.out.println("Μη έγκυρος αριθμός. Παρακαλώ ξαναπροσπαθήστε."); } } } }
aristosgi/FirstJavaAssignment
main.java
3,963
/*στις μονες θεσεις εχουμε τους δασκαλους προνηπιου και στις ζυγες του νηπιου αρα*/
block_comment
el
import java.util.Scanner; public class main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Student student; int c = 8; Student[] All_Students = new Student[100]; SchoolYear[] schoolYears = new SchoolYear[100]; Teacher[] All_Teachers= new Teacher[100]; All_Teachers[0] = new Teacher("a1","Γρηγορης Γρηγορίου","0303921142"); All_Teachers[1] = new Teacher("a2","Βασιλης Βασιλειου","0209882324"); All_Teachers[2] = new Teacher("a3","Νικος Νικου","2508911290"); All_Teachers[3] = new Teacher("a3","Γεωργιος Γεωργιου","0612889099"); Student []table1=new Student[100]; Student []table2 = new Student[100]; Student []table3 = new Student[100]; Student []table4 = new Student[100]; Student student2; schoolYears[0]=new SchoolYear("2019-2020",All_Teachers[0],All_Teachers[1],table1,table2); schoolYears[1]=new SchoolYear("2018-2019",All_Teachers[2],All_Teachers[3],table3,table4); student2 = new Student("Αριστοτέλης Γκιθκόπουλος","30/10/01"); All_Students[0]=student2; schoolYears[0].setNipio_Students_year(student2); student2 = new Student ("Αθανάσιος Αντωνόπουλος","20/11/01"); All_Students[1]=student2; schoolYears[0].setNipio_Students_year(student2); student2 = new Student("Νικόλαος Νικολαόυ","06/02/01"); All_Students[2]=student2; schoolYears[1].setNipio_Students_year(student2); student2 = new Student("Κώσταντινος Κωνσταντίνου","19/04/01"); All_Students[3]=student2; schoolYears[1].setNipio_Students_year(student2); student2 = new Student("Μάριος Λαζάρου","20/09/02"); All_Students[4]=student2; schoolYears[0].setPronipio_Students_year(student2); student2 = new Student("Γεώργιος Γεωργίου","30/11/02"); All_Students[5]=student2; schoolYears[0].setPronipio_Students_year(student2); student2 = new Student("Δημήτρης Δημητρίου","01/01/02"); All_Students[6]=student2; schoolYears[1].setPronipio_Students_year(student2); student2 = new Student("Αλέξανδρος Αλεξάνδρου","17/10/02"); All_Students[7]=student2; schoolYears[1].setPronipio_Students_year(student2); for (; ; ) { System.out.println("~~~~~~~~~~ Μενού Επιλογών ~~~~~~~~~~\n" + "1. Εκτύπωση όλων των μαθητών που έχουν φοιτήσει στο σχολείο\n" + "2. Εγγραφή νέου μαθητή στην τρέχουσα σχολική χρονιά\n" + "3. Διαγραφή μαθητή από την τρέχουσα σχολική χρονιά\n" + "4. Αναζήτηση στοιχείων σχολικής χρονιάς\n" + "5. Αναζήτηση τάξεων που έχει αναλάβει κάθε δάσκαλος του σχολείου \n6. Αναζήτηση στοιχείων δασκάλου μέσω ΑΜΚΑ\n" + "Εισάγετε επιλογή [1-6] :"); String choice = sc.next(); switch (choice) { case "1": for (int a = 0; a <= 99; a++) { if (All_Students[a] != null) System.out.println(All_Students[a]); } break; case "2": System.out.println("Νήπιο η Προνήπιο"); String option = sc.next(); boolean flag = false; for (int i = 0; i <= 99; i++) { if (option.equals("Νήπιο")) { if (schoolYears[0].getNipio_Students_year()[i] == null) { System.out.println("Δώστε ονοματεπώνυμο και ημερομηνία γέννησης"); String fullname = sc.next() + " " + sc.next(); String birth_date = sc.next(); student = new Student(fullname, birth_date); All_Students[c] = student; c ++; System.out.println("Η εγγραφή έγινε επιτυχώς"); schoolYears[0].setNipio_Students_year(student); flag=true; break; } } } if (option.equals("Προνήπιο")) { for (int i = 0; i <= schoolYears[0].getPronipio_Students_year().length; i++) { if (schoolYears[0].getPronipio_Students_year()[i] == null) { System.out.println("Δώσε ονοματεπώνυμο και ημερομηνία γέννησης"); String fullname = sc.next() + " " + sc.next(); String birth_date = sc.next(); student = new Student(fullname, birth_date); All_Students[c] = student; c ++; flag=true; schoolYears[0].setPronipio_Students_year(student); System.out.println("Η εγγραφή έγινε επιτυχώς"); break; } } } if(flag==false){ System.out.println("Βαλατε λάθος στοιχεία. Προσπαθήστε ξανά."); } break; case "3": System.out.println("Εισάγετε το id του μαθητή προς διαγραφή."); String id_find = sc.next(); boolean flag1 = false; for (int y = 0; y < 99; y++) { if (schoolYears[0].getNipio_Students_year()[y] != null) { if (schoolYears[0].getNipio_Students_year()[y].getId().equals(id_find)) { System.out.println("Είστε σίγουροι για την διαγραφή;ΝΑΙ/ΟΧΙ"); String check = sc.next(); if (check.equals("ΝΑΙ")) { System.out.println("Η διαγραφή έγινε επιτυχώς."); schoolYears[0].setNUllNipio_Students_year(y); } else { System.out.println("Η διαγραφή ακυρώθηκε."); } flag1 = true; break; } } if (schoolYears[0].getPronipio_Students_year()[y] != null) { if (schoolYears[0].getPronipio_Students_year()[y].getId().equals(id_find)) { System.out.println("Είστε σίγουροι για την διαγραφή;ΝΑΙ/ΟΧΙ"); String check = sc.next(); if (check.equals("ΝΑΙ")) { System.out.println("Η διαγραφή έγινε επιτυχώς"); schoolYears[0].setNUllPronipio_Students_year(y); } else { System.out.println("Η διαγραφή ακυρώθηκε"); } flag1 = true; break; } } } if (flag1 == false) { System.out.println("Το id δεν βρέθηκε."); } break; case "4": System.out.println("Για ποιας χρονιάς τα στοιχεία θέλετε να δείτε(2018-2019 η 2019-2020)"); String year = sc.next(); if (!(year.equals("2018-2019") || year.equals("2019-2020"))) { System.out.println("Δεν υπάρχουν στοιχεία για την χρονιά που επιλέξατε."); break; } System.out.println("Νήπιο η Προνήπιο"); String classLevel = sc.next(); if (!(classLevel.equals("Νήπιο") || classLevel.equals("Προνήπιο"))) { System.out.println("Έχετε δώσει λάθος στοιχείο ξαναπροσπαθήστε"); break; } if (year.equals("2019-2020")) { if (classLevel.equals("Νήπιο")) { System.out.println(schoolYears[0].getDaskalos_nipiou().getFullname()); for (int y = 0; y <= 99; y++) { if (schoolYears[0].getNipio_Students_year()[y] != null) { System.out.println(schoolYears[0].getNipio_Students_year()[y].toString()); } } } if (classLevel.equals("Προνήπιο")) { System.out.println(schoolYears[0].getDaskalos_pronipiou().getFullname()); for (int y = 0; y <= 99; y++) { if (schoolYears[0].getPronipio_Students_year()[y] != null) { System.out.println(schoolYears[0].getPronipio_Students_year()[y].toString()); } } } } if (year.equals("2018-2019")) { if (classLevel.equals("Νήπιο")) { schoolYears[1].getNipio_Students_year(); System.out.println(schoolYears[1].getDaskalos_nipiou().getFullname()); for (int y = 0; y <= 99; y++) { if (schoolYears[1].getNipio_Students_year()[y] != null) { System.out.println(schoolYears[1].getNipio_Students_year()[y].toString()); } } } if (classLevel.equals("Προνήπιο ")) { System.out.println(schoolYears[1].getDaskalos_pronipiou().getFullname()); for (int y = 0; y <= 99; y++) { if (schoolYears[1].getPronipio_Students_year()[y] != null) { System.out.println(schoolYears[1].getPronipio_Students_year()[y].toString()); } } } } break; case "5": for (int i = 0; i <= 99; i++) { if (All_Teachers[i] != null) { for (int y = 0; y <= 99; y++) { if (schoolYears[y] != null) { /*στις μονες θεσεις<SUF>*/ if (All_Teachers[i].equals(schoolYears[y].getDaskalos_nipiou())) { System.out.println(schoolYears[y].getYear() + " " + schoolYears[y].getDaskalos_nipiou().getFullname()); if (i % 2 == 1) { System.out.println(" προνήπιο"); } else { System.out.println(" νήπιο"); } } if (All_Teachers[i].equals(schoolYears[y].getDaskalos_pronipiou())) { System.out.println(schoolYears[y].getYear() + " " + schoolYears[y].getDaskalos_pronipiou().getFullname()); if (i % 2 == 1) { System.out.println(" προνήπιο"); } else { System.out.println(" νήπιο"); } } } } } } break; case "6": System.out.println("Παρακαλώ εισάγετε το ΑΜΚΑ του δασκάλου."); String AMKA = sc.next(); int flag2 = 0; for (int i=0;i<=99;i++) { if (All_Teachers[i]!=null) { if (All_Teachers[i].getAMKA().equals(AMKA)) { System.out.println(All_Teachers[i]); flag2 = 1; } } } if (flag2==0) { System.out.println("Δεν υπάρχει δάσκαλος με αυτό το ΑΜΚΑ."); } break; default: System.out.println("Μη έγκυρος αριθμός. Παρακαλώ ξαναπροσπαθήστε."); } } } }
4031_26
package graphix; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.table.DefaultTableModel; import graph.Edge; import graph.Operator; import graph.OperatorForm; import graph.SearchGraph; /** * ΕΑΠ - ΠΛΗ31 - 4η ΕΡΓΑΣΙΑ 2015-2016 * @author Tsakiridis Sotiris */ public class OperatorListForm extends javax.swing.JDialog { // Περίδα φόρματς private SearchGraph searchGraph; private boolean ok = false; // getters public boolean isOk() { return this.ok; } /** * Creates new form OperatorListForm * @param parent * @param modal * @param searchGraph */ public OperatorListForm(java.awt.Frame parent, boolean modal, SearchGraph searchGraph) { super(parent, modal); initComponents(); this.searchGraph = searchGraph; // Καταχωροούμε τα δεδομένα στον πίνακα τελεστών // Δημιουργούμε αρχικά μια ταξινομημένη λίστα ως προς την προτεραιότητα HashMap<String, Operator> operators = searchGraph.getOperators(); ArrayList<Operator> sortedList = new ArrayList(); DefaultTableModel model = (DefaultTableModel)operatorTable.getModel(); for (Operator op : operators.values()) { sortedList.add(op); } // sort Collections.sort(sortedList, new Comparator<Operator>(){ @Override public int compare(Operator o1, Operator o2) { if (o1.getPriority() > o2.getPriority()) return 1; if (o1.getPriority() < o2.getPriority()) return -1; return 0; } }); // Προσθήκη στον πίνακα for (Operator op : sortedList) model.addRow(new Object[]{op, op.getLabel(), op.getDescription(),op.getPriority()}); // Αν υπάρχουν δεδομένα επιλογή της 1ης γραμμής if ( operatorTable.getRowCount() != 0 ) operatorTable.changeSelection(0, 0, false, false); // Κατάσταση κουμπιών setButtonState(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); operatorTable = new javax.swing.JTable(); cancelButton = new javax.swing.JButton(); addButton = new javax.swing.JButton(); editButton = new javax.swing.JButton(); deleteButton = new javax.swing.JButton(); okButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Τελεστές δράσης"); operatorTable.setAutoCreateRowSorter(true); operatorTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "operator", "Ετικέτα", "Περιγραφή", "Προτεραιότητα" } ) { Class[] types = new Class [] { java.lang.Object.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class }; boolean[] canEdit = new boolean [] { true, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); operatorTable.setFillsViewportHeight(true); operatorTable.getTableHeader().setReorderingAllowed(false); jScrollPane1.setViewportView(operatorTable); if (operatorTable.getColumnModel().getColumnCount() > 0) { operatorTable.getColumnModel().getColumn(0).setMinWidth(0); operatorTable.getColumnModel().getColumn(0).setPreferredWidth(0); operatorTable.getColumnModel().getColumn(0).setMaxWidth(0); operatorTable.getColumnModel().getColumn(1).setMinWidth(100); operatorTable.getColumnModel().getColumn(1).setPreferredWidth(100); operatorTable.getColumnModel().getColumn(1).setMaxWidth(100); operatorTable.getColumnModel().getColumn(3).setMinWidth(100); operatorTable.getColumnModel().getColumn(3).setPreferredWidth(100); operatorTable.getColumnModel().getColumn(3).setMaxWidth(100); } cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancel16.png"))); // NOI18N cancelButton.setText("Ακύρωση"); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); addButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/add16.png"))); // NOI18N addButton.setText("Προσθήκη"); addButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addButtonActionPerformed(evt); } }); editButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/edit16.png"))); // NOI18N editButton.setText("Επεξεργασία"); editButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { editButtonActionPerformed(evt); } }); deleteButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/delete16.png"))); // NOI18N deleteButton.setText("Διαγραφή"); deleteButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { deleteButtonActionPerformed(evt); } }); okButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/ok16.png"))); // NOI18N okButton.setText("Καταχώρηση"); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 432, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(editButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(addButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(deleteButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(okButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(cancelButton))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 374, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(addButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(editButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(deleteButton) .addGap(0, 0, Short.MAX_VALUE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cancelButton) .addComponent(okButton)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed this.dispose(); }//GEN-LAST:event_cancelButtonActionPerformed private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed // Δημιουργούμε ένα νέο HashMap<Operator> // σύμφωνα με τα δεδομένα του πίνακα HashMap<String, Operator> newMap = new HashMap(); int rows = operatorTable.getRowCount(); DefaultTableModel model = (DefaultTableModel)operatorTable.getModel(); for (int i=0; i<rows; i++) { // Παίρνουμε τα δεδομένα της γραμμής από τον πίνακα Operator op = (Operator)model.getValueAt(i,0); String label = op.getLabel(); String description = op.getDescription(); int priority = op.getPriority(); // Τον προσθέτουμε στο νέο map newMap.put(label, op); } // Εκχωρούμε το νέο map τελεστών στο searchGraph // και διαγράφουμε τις ακμές με τελεστές που έχουν διαγραφεί // Παίρνουμε πρώτα τις ακμές σε μια προσωρινή λίστα ArrayList<Edge> edges = new ArrayList(); for (Edge e : searchGraph.getEdges()) edges.add(e); for (Edge e : edges) { if ( !newMap.containsValue(e.getOperator()) ) searchGraph.removeEdge(e); } searchGraph.setOperators(newMap); // set ok flag and return ok = true; this.dispose(); }//GEN-LAST:event_okButtonActionPerformed private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed // Παίρνουμε την επιλεγμένη γραμμή και τη διαγράφουμε DefaultTableModel model = (DefaultTableModel)operatorTable.getModel(); int row = operatorTable.getSelectedRow(); model.removeRow(row); // Επιλέγουμε την προηγούμενη γραμμή, αν υπάρχει if (row > 0) operatorTable.changeSelection(row-1, 1, false, false); else if ( model.getRowCount() !=0 ) operatorTable.changeSelection(0, 1, false, false); // κατάσταση κουμπιών setButtonState(); }//GEN-LAST:event_deleteButtonActionPerformed // Προσθήκη ενός νέου τελεστή δράσης private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed Operator newOp = new Operator("", "", 0); JFrame topFrame = (JFrame)SwingUtilities.getWindowAncestor(this); OperatorForm opForm = new OperatorForm(topFrame, true, newOp); opForm.setLocationRelativeTo(this); opForm.setVisible(true); // Αν δεν επιστρέψαμε με OK επιστροφή if ( !opForm.isOk() ) return; // Έλεγχος αν υπάρχει τελεστής με την ίδια ετικέτα // Αν υπάρχει, εμφάνιση μηνύματος - Δεν προστίθεται // Προσθέτουμε τον νέο τελεστή στη λίστα των τελεστών DefaultTableModel model = (DefaultTableModel)operatorTable.getModel(); model.addRow(new Object[]{newOp, newOp.getLabel(), newOp.getDescription(),newOp.getPriority()}); // Επιλέγουμε την νέα γραμμή int row = model.getRowCount() - 1; operatorTable.setRowSelectionInterval(row, row); operatorTable.scrollRectToVisible(operatorTable.getCellRect(row, 0, true)); setButtonState(); }//GEN-LAST:event_addButtonActionPerformed // Επεξεργασία επιλεγμένου τελεστή δράσης private void editButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editButtonActionPerformed // Παίρνουμε τον επιλεγμένο τελεστή. // Αν δεν υπάρχει επιστρέφουμε DefaultTableModel model = (DefaultTableModel)operatorTable.getModel(); int row = operatorTable.getSelectedRow(); // Παίρνουμε τον επιλεγμένο τελεστή Operator op = (Operator)model.getValueAt(row, 0); // Ανοίγουμε τη φόρμα επεξεργασίας JFrame topFrame = (JFrame)SwingUtilities.getWindowAncestor(this); OperatorForm opForm = new OperatorForm(topFrame, true, op); opForm.setLocationRelativeTo(this); opForm.setVisible(true); // Αν δεν επιστρέψαμε με OK επιστροφή if ( !opForm.isOk() ) return; // Έλεγχος αν υπάρχει τελεστής με την ίδια ετικέτα // Αν υπάρχει, εμφάνιση μηνύματος - Δεν προστίθεται // Ενημερώνουμε τον πίνακα με τα νέα στοιχεία model.setValueAt(op.getLabel(), row, 1); model.setValueAt(op.getDescription(), row, 2); model.setValueAt(op.getPriority(), row, 3); }//GEN-LAST:event_editButtonActionPerformed // Κατάσταση κουμπιών private void setButtonState() { // Παίρνουμε το πλήθος τελεστών δράσης int rows = operatorTable.getRowCount(); if (rows == 0) { deleteButton.setEnabled(false); editButton.setEnabled(false); } else { deleteButton.setEnabled(true); editButton.setEnabled(true); } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addButton; private javax.swing.JButton cancelButton; private javax.swing.JButton deleteButton; private javax.swing.JButton editButton; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton okButton; private javax.swing.JTable operatorTable; // End of variables declaration//GEN-END:variables }
artibet/graphix
src/graphix/OperatorListForm.java
4,316
// Αν δεν υπάρχει επιστρέφουμε
line_comment
el
package graphix; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.table.DefaultTableModel; import graph.Edge; import graph.Operator; import graph.OperatorForm; import graph.SearchGraph; /** * ΕΑΠ - ΠΛΗ31 - 4η ΕΡΓΑΣΙΑ 2015-2016 * @author Tsakiridis Sotiris */ public class OperatorListForm extends javax.swing.JDialog { // Περίδα φόρματς private SearchGraph searchGraph; private boolean ok = false; // getters public boolean isOk() { return this.ok; } /** * Creates new form OperatorListForm * @param parent * @param modal * @param searchGraph */ public OperatorListForm(java.awt.Frame parent, boolean modal, SearchGraph searchGraph) { super(parent, modal); initComponents(); this.searchGraph = searchGraph; // Καταχωροούμε τα δεδομένα στον πίνακα τελεστών // Δημιουργούμε αρχικά μια ταξινομημένη λίστα ως προς την προτεραιότητα HashMap<String, Operator> operators = searchGraph.getOperators(); ArrayList<Operator> sortedList = new ArrayList(); DefaultTableModel model = (DefaultTableModel)operatorTable.getModel(); for (Operator op : operators.values()) { sortedList.add(op); } // sort Collections.sort(sortedList, new Comparator<Operator>(){ @Override public int compare(Operator o1, Operator o2) { if (o1.getPriority() > o2.getPriority()) return 1; if (o1.getPriority() < o2.getPriority()) return -1; return 0; } }); // Προσθήκη στον πίνακα for (Operator op : sortedList) model.addRow(new Object[]{op, op.getLabel(), op.getDescription(),op.getPriority()}); // Αν υπάρχουν δεδομένα επιλογή της 1ης γραμμής if ( operatorTable.getRowCount() != 0 ) operatorTable.changeSelection(0, 0, false, false); // Κατάσταση κουμπιών setButtonState(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); operatorTable = new javax.swing.JTable(); cancelButton = new javax.swing.JButton(); addButton = new javax.swing.JButton(); editButton = new javax.swing.JButton(); deleteButton = new javax.swing.JButton(); okButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Τελεστές δράσης"); operatorTable.setAutoCreateRowSorter(true); operatorTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "operator", "Ετικέτα", "Περιγραφή", "Προτεραιότητα" } ) { Class[] types = new Class [] { java.lang.Object.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class }; boolean[] canEdit = new boolean [] { true, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); operatorTable.setFillsViewportHeight(true); operatorTable.getTableHeader().setReorderingAllowed(false); jScrollPane1.setViewportView(operatorTable); if (operatorTable.getColumnModel().getColumnCount() > 0) { operatorTable.getColumnModel().getColumn(0).setMinWidth(0); operatorTable.getColumnModel().getColumn(0).setPreferredWidth(0); operatorTable.getColumnModel().getColumn(0).setMaxWidth(0); operatorTable.getColumnModel().getColumn(1).setMinWidth(100); operatorTable.getColumnModel().getColumn(1).setPreferredWidth(100); operatorTable.getColumnModel().getColumn(1).setMaxWidth(100); operatorTable.getColumnModel().getColumn(3).setMinWidth(100); operatorTable.getColumnModel().getColumn(3).setPreferredWidth(100); operatorTable.getColumnModel().getColumn(3).setMaxWidth(100); } cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancel16.png"))); // NOI18N cancelButton.setText("Ακύρωση"); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); addButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/add16.png"))); // NOI18N addButton.setText("Προσθήκη"); addButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addButtonActionPerformed(evt); } }); editButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/edit16.png"))); // NOI18N editButton.setText("Επεξεργασία"); editButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { editButtonActionPerformed(evt); } }); deleteButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/delete16.png"))); // NOI18N deleteButton.setText("Διαγραφή"); deleteButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { deleteButtonActionPerformed(evt); } }); okButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/ok16.png"))); // NOI18N okButton.setText("Καταχώρηση"); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 432, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(editButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(addButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(deleteButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(okButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(cancelButton))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 374, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(addButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(editButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(deleteButton) .addGap(0, 0, Short.MAX_VALUE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cancelButton) .addComponent(okButton)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed this.dispose(); }//GEN-LAST:event_cancelButtonActionPerformed private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed // Δημιουργούμε ένα νέο HashMap<Operator> // σύμφωνα με τα δεδομένα του πίνακα HashMap<String, Operator> newMap = new HashMap(); int rows = operatorTable.getRowCount(); DefaultTableModel model = (DefaultTableModel)operatorTable.getModel(); for (int i=0; i<rows; i++) { // Παίρνουμε τα δεδομένα της γραμμής από τον πίνακα Operator op = (Operator)model.getValueAt(i,0); String label = op.getLabel(); String description = op.getDescription(); int priority = op.getPriority(); // Τον προσθέτουμε στο νέο map newMap.put(label, op); } // Εκχωρούμε το νέο map τελεστών στο searchGraph // και διαγράφουμε τις ακμές με τελεστές που έχουν διαγραφεί // Παίρνουμε πρώτα τις ακμές σε μια προσωρινή λίστα ArrayList<Edge> edges = new ArrayList(); for (Edge e : searchGraph.getEdges()) edges.add(e); for (Edge e : edges) { if ( !newMap.containsValue(e.getOperator()) ) searchGraph.removeEdge(e); } searchGraph.setOperators(newMap); // set ok flag and return ok = true; this.dispose(); }//GEN-LAST:event_okButtonActionPerformed private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed // Παίρνουμε την επιλεγμένη γραμμή και τη διαγράφουμε DefaultTableModel model = (DefaultTableModel)operatorTable.getModel(); int row = operatorTable.getSelectedRow(); model.removeRow(row); // Επιλέγουμε την προηγούμενη γραμμή, αν υπάρχει if (row > 0) operatorTable.changeSelection(row-1, 1, false, false); else if ( model.getRowCount() !=0 ) operatorTable.changeSelection(0, 1, false, false); // κατάσταση κουμπιών setButtonState(); }//GEN-LAST:event_deleteButtonActionPerformed // Προσθήκη ενός νέου τελεστή δράσης private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed Operator newOp = new Operator("", "", 0); JFrame topFrame = (JFrame)SwingUtilities.getWindowAncestor(this); OperatorForm opForm = new OperatorForm(topFrame, true, newOp); opForm.setLocationRelativeTo(this); opForm.setVisible(true); // Αν δεν επιστρέψαμε με OK επιστροφή if ( !opForm.isOk() ) return; // Έλεγχος αν υπάρχει τελεστής με την ίδια ετικέτα // Αν υπάρχει, εμφάνιση μηνύματος - Δεν προστίθεται // Προσθέτουμε τον νέο τελεστή στη λίστα των τελεστών DefaultTableModel model = (DefaultTableModel)operatorTable.getModel(); model.addRow(new Object[]{newOp, newOp.getLabel(), newOp.getDescription(),newOp.getPriority()}); // Επιλέγουμε την νέα γραμμή int row = model.getRowCount() - 1; operatorTable.setRowSelectionInterval(row, row); operatorTable.scrollRectToVisible(operatorTable.getCellRect(row, 0, true)); setButtonState(); }//GEN-LAST:event_addButtonActionPerformed // Επεξεργασία επιλεγμένου τελεστή δράσης private void editButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editButtonActionPerformed // Παίρνουμε τον επιλεγμένο τελεστή. // Αν δεν<SUF> DefaultTableModel model = (DefaultTableModel)operatorTable.getModel(); int row = operatorTable.getSelectedRow(); // Παίρνουμε τον επιλεγμένο τελεστή Operator op = (Operator)model.getValueAt(row, 0); // Ανοίγουμε τη φόρμα επεξεργασίας JFrame topFrame = (JFrame)SwingUtilities.getWindowAncestor(this); OperatorForm opForm = new OperatorForm(topFrame, true, op); opForm.setLocationRelativeTo(this); opForm.setVisible(true); // Αν δεν επιστρέψαμε με OK επιστροφή if ( !opForm.isOk() ) return; // Έλεγχος αν υπάρχει τελεστής με την ίδια ετικέτα // Αν υπάρχει, εμφάνιση μηνύματος - Δεν προστίθεται // Ενημερώνουμε τον πίνακα με τα νέα στοιχεία model.setValueAt(op.getLabel(), row, 1); model.setValueAt(op.getDescription(), row, 2); model.setValueAt(op.getPriority(), row, 3); }//GEN-LAST:event_editButtonActionPerformed // Κατάσταση κουμπιών private void setButtonState() { // Παίρνουμε το πλήθος τελεστών δράσης int rows = operatorTable.getRowCount(); if (rows == 0) { deleteButton.setEnabled(false); editButton.setEnabled(false); } else { deleteButton.setEnabled(true); editButton.setEnabled(true); } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addButton; private javax.swing.JButton cancelButton; private javax.swing.JButton deleteButton; private javax.swing.JButton editButton; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton okButton; private javax.swing.JTable operatorTable; // End of variables declaration//GEN-END:variables }
93_3
/* * 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 com.model; /** * * @author RG */ import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; public class GasStationServlet extends HttpServlet { String message; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // JDBC driver name and database URL //αρκεί να αλλάξεις το url της βάσης, το username και το passwword και τρέχει κανονικά final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; final String DB_URL = "jdbc:mysql://localhost:3306/gasstation_db"; // Database credentials final String USER = "root"; final String PASS = ""; // Set response content type response.setContentType( "text/html"); PrintWriter out = response.getWriter(); String title = "Database Result"; try { // Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); // Open a connection Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); // Execute SQL query Statement stmt = conn.createStatement(); String sql; sql = "SELECT id,brand_name,gas,laundry,address,latitube, longitude FROM gas_station\n" + " GROUP BY brand_name"; ResultSet rs = stmt.executeQuery(sql); request.setAttribute("rs", rs); request.setAttribute("returnRes", rs); // Extract data from result set // Clean-up environment } catch (SQLException se) { //Handle errors for JDBC se.printStackTrace(); } catch (Exception e) { //Handle errors for Class.forName e.printStackTrace(); } RequestDispatcher view = request.getRequestDispatcher("index.jsp"); } }
arvartho/GasStationFinder
src/java/com/model/GasStationServlet.java
491
//αρκεί να αλλάξεις το url της βάσης, το username και το passwword και τρέχει κανονικά
line_comment
el
/* * 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 com.model; /** * * @author RG */ import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; public class GasStationServlet extends HttpServlet { String message; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // JDBC driver name and database URL //αρκεί να<SUF> final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; final String DB_URL = "jdbc:mysql://localhost:3306/gasstation_db"; // Database credentials final String USER = "root"; final String PASS = ""; // Set response content type response.setContentType( "text/html"); PrintWriter out = response.getWriter(); String title = "Database Result"; try { // Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); // Open a connection Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); // Execute SQL query Statement stmt = conn.createStatement(); String sql; sql = "SELECT id,brand_name,gas,laundry,address,latitube, longitude FROM gas_station\n" + " GROUP BY brand_name"; ResultSet rs = stmt.executeQuery(sql); request.setAttribute("rs", rs); request.setAttribute("returnRes", rs); // Extract data from result set // Clean-up environment } catch (SQLException se) { //Handle errors for JDBC se.printStackTrace(); } catch (Exception e) { //Handle errors for Class.forName e.printStackTrace(); } RequestDispatcher view = request.getRequestDispatcher("index.jsp"); } }
2839_6
import java.util.ArrayList; import java.util.List; /** * Αυτή η κλάση αντιπροσωπεύει μιά αεροπορική πτήση. Κάθε πτήση έχει έναν αριθμό, διάρκεια σε ώρες, χωρητικότητα και μια * λίστα με τους επιβάτες. * <p> * This class represents a flight. Each flight has an number, duration in hours, number of seats and a list with the * passengers. */ public class Flight { private String flightNo; private int duration; // in hours private int seats; private List<Passenger> passengers = null; /** * Κατασκευαστής * <p> * Instantiates a new Flight */ public Flight() { this.passengers = new ArrayList<>(); } /** * Επιστρέφει τον αριθμό της πτήσης * <p> * Gets the flight number. * * @return ο αριθμός της πτήσης / the flight no */ public String getFlightNo() { return flightNo; } /** * Επιστρέφει την λίστα με τους επιβάτες. * <p> * Gets the list of passengers. * * @return η λίστα με τους επιβάτες / the list with the passengers */ public List<Passenger> getPassengers() { return passengers; } /** * Ενημερώνει τη διάρκεια της πτήσης * <p> * Updates the flight duration * * @param duration η διάρκεια της πτήσης (ώρες) / flight duration (hours) */ public void setDuration(int duration) { this.duration = duration; } /** * Ενημερώνει την χωρητικότητα της πτήσης * <p> * Updates the flight seats * * @param seats οι συνολικές θέσεις της πτήσης / the total seats of the flight duration */ public void setSeats(int seats) { this.seats = seats; } /** * Ενημερώνει τον αριθμό της πτήσης. Η μέθοδος ελέγχει για το αν είναι null η τιμή της παραμέτρου. Αν είναι, τότε * δεν γίνεται καμιά αλλαγή και επιστρέφει η μέθοδος false. Διαφορετικά, ενημερώνεται ο αριθμός της πτήσης και * επιστρέφεται true. * <p> * Sets flight number. The methods checks if the value provided as input is null. If it is, then the flight number * is not updated and the method returns false. Otherwise, the methods updates the flight number and returns true. * * @param flightNo ένα έγκυρος αριθμός πτήσης / a valid flight number * @return true ή false ανάλογα με το αν ο αριθμός πτήσης είναι έγκυρος / true or false, according to whether the * flight number is valid or not */ public boolean setFlightNo(String flightNo) { if(flightNo == null) return false; else this.flightNo = flightNo; return true; } /** * Μέθοδος που βρίσκει και επιστρέφει τον επιβάτη από τη λίστα με τους επιβάτες που έχει ίδιο το passport id. Αν δεν * υπάρχει τέτοιος επιβάτης, επιστρέφει null. * <p> * It finds and returns the passenger from the list with the passengers that has the same passport id, as the one * provided as parameter. If there is no such passenger, it returns null. * * @param passportId Το passport id του επιβάτη που ψάχνουμε / the passport id of the passenger * @return Ο επιβάτης ή null αν δεν βρεθεί κάποιος / the passenger or null if there is no passenger with the same * passport */ public Passenger findPassenger(String passportId) { if(this.passengers!=null) for (Passenger passenger : passengers) { if (passenger.getPassportId().equals(passportId)) return passenger; } return null; } /** * Μέθοδος για την προσθήκη ενός επιβάτη στη λίστα με τους επιβάτες της πτήσης. Η μέθοδος ελέγχει αρχικά για το αν * υπάρχουν διαθέσιμες (κενές) θέσεις. Αν δεν υπάρχουν, επιστρέφει false. Στην συνέχεια ελέγχει για το αν υπάρχει * ήδη κάποιος επιβάτης στην πτήση με το ίδιο passport id. Αν υπάρχει, τότε επιστρέφει false. Διαφορετικά, ο * επιβάτης προστίθεται στη λίστα με τους επιβάτες και επιστρέφεται true. * <p> * Method that adds a passenger to the list of the passengers of the flight. The method first checks if there are * empty seats. If there are not, then it returns false. Then, it checks if there is already a passenger in the * flight with the same passport id. If there is, then it returns false. Otherwise, the passenger is added to the * list with the passengers and it returns true. * * @param passenger Ο επιβάτης που είναι να προστεθεί / The passenger to be added * @return True ή false, ανάλογα με το αν ο επιβάτης έχει προστεθεί στην πτήση ή όχι / True or false, according to * whether the passenger has been successfully added to the flight or not. */ public boolean addPassenger(Passenger passenger) { if(getEmptySeats() <= 0) return false; if(passenger == null) return false; Passenger existingPassenger = findPassenger(passenger.getPassportId()); if (existingPassenger != null) { System.out.printf("There is already a passenger with passport id: %s \n", passenger.getPassportId()); return false; } this.passengers.add(passenger); return true; } /** * Μέθοδος που επιστρέφει το ποσοστό πληρότητας της πτήσης, δηλαδή τον λόγο του αριθμού των επιβατών προς τις * συνολικές θέσεις (χωρητικότητα) της πτήσης. * <p> * Method that returns the occupancy percentage, that is, the ratio of the number of passengers to the total seats. * * @return το ποσοστό πληρότητας / the occupancy percentage */ public double getOccupancy() { if(this.passengers != null) return passengers.size() / (double) seats; return 0; } /** * Επιστρέφει τον αριθμό των διαθέσιμων (κενών) θέσεων της πτήσης, δηλαδή χωρητικότητα - καταχωρημένοι επιβάτες. * <p> * It returns the number of the available (empty) seats, i.e. total seats - registered passengers. * * @return οι διαθέσιμες (κενές) θέσεις / the available (empty) seats */ public int getEmptySeats() { if(this.passengers != null) return seats - passengers.size(); return this.seats; } /** * Επιστρέφει τα ελάχιστα λίτρα καυσίμου που πρέπει να υπάρχουν στην πτήση. Τα λίτρα καυσίμου για μία πτήση * υπολογίζονται χρησιμοποιώντας τη μέση κατανάλωση καυσίμου για ένα αεροπλάνο ανά ώρα (μεταβλητή * AVERAGE_FUEL_CONSUMPTION_PER_HOUR = 1000) επί τη διάρκεια της πτήσης (σε ώρες). Για ασφάλεια, πρέπει να υπάρχει * και 10% περισσότερο καύσιμο στην πτήση. Έτσι αν μια πτήση διαρκεί 1 ώρα, τα ελάχιστα καύσιμα που πρέπει να * υπάρχουν στην πτήση είναι 1100 λίτρα. * <p> * It returns the minimum amount of fuels (in litres) that the flight should have. The amount of fuels for a flight * is calculated taking into account the average fuel consumption for a flight (variable * AVERAGE_FUEL_CONSUMPTION_PER_HOUR = 1000) times the duration of the flight (in hours). For safety, the flight * should have 10% more fuels. For example, if the duration of the flight is 1 hour, then the minimum amount of fuel * for the flight is 1100 litres. * * @return τα ελάχιστα λίτρα καυσίμου για την πτήση / the minimum fuels for the trip */ public double getMinimumFuelsForTheTrip() { return CONSTANTS.AVERAGE_FUEL_CONSUMPTION_PER_HOUR * duration * (1 + 0.1); } }
asimakiskydros/University-Projects
Object Oriented Programming/Lab 8/Flight.java
3,225
/** * Ενημερώνει τον αριθμό της πτήσης. Η μέθοδος ελέγχει για το αν είναι null η τιμή της παραμέτρου. Αν είναι, τότε * δεν γίνεται καμιά αλλαγή και επιστρέφει η μέθοδος false. Διαφορετικά, ενημερώνεται ο αριθμός της πτήσης και * επιστρέφεται true. * <p> * Sets flight number. The methods checks if the value provided as input is null. If it is, then the flight number * is not updated and the method returns false. Otherwise, the methods updates the flight number and returns true. * * @param flightNo ένα έγκυρος αριθμός πτήσης / a valid flight number * @return true ή false ανάλογα με το αν ο αριθμός πτήσης είναι έγκυρος / true or false, according to whether the * flight number is valid or not */
block_comment
el
import java.util.ArrayList; import java.util.List; /** * Αυτή η κλάση αντιπροσωπεύει μιά αεροπορική πτήση. Κάθε πτήση έχει έναν αριθμό, διάρκεια σε ώρες, χωρητικότητα και μια * λίστα με τους επιβάτες. * <p> * This class represents a flight. Each flight has an number, duration in hours, number of seats and a list with the * passengers. */ public class Flight { private String flightNo; private int duration; // in hours private int seats; private List<Passenger> passengers = null; /** * Κατασκευαστής * <p> * Instantiates a new Flight */ public Flight() { this.passengers = new ArrayList<>(); } /** * Επιστρέφει τον αριθμό της πτήσης * <p> * Gets the flight number. * * @return ο αριθμός της πτήσης / the flight no */ public String getFlightNo() { return flightNo; } /** * Επιστρέφει την λίστα με τους επιβάτες. * <p> * Gets the list of passengers. * * @return η λίστα με τους επιβάτες / the list with the passengers */ public List<Passenger> getPassengers() { return passengers; } /** * Ενημερώνει τη διάρκεια της πτήσης * <p> * Updates the flight duration * * @param duration η διάρκεια της πτήσης (ώρες) / flight duration (hours) */ public void setDuration(int duration) { this.duration = duration; } /** * Ενημερώνει την χωρητικότητα της πτήσης * <p> * Updates the flight seats * * @param seats οι συνολικές θέσεις της πτήσης / the total seats of the flight duration */ public void setSeats(int seats) { this.seats = seats; } /** * Ενημερώνει τον αριθμό<SUF>*/ public boolean setFlightNo(String flightNo) { if(flightNo == null) return false; else this.flightNo = flightNo; return true; } /** * Μέθοδος που βρίσκει και επιστρέφει τον επιβάτη από τη λίστα με τους επιβάτες που έχει ίδιο το passport id. Αν δεν * υπάρχει τέτοιος επιβάτης, επιστρέφει null. * <p> * It finds and returns the passenger from the list with the passengers that has the same passport id, as the one * provided as parameter. If there is no such passenger, it returns null. * * @param passportId Το passport id του επιβάτη που ψάχνουμε / the passport id of the passenger * @return Ο επιβάτης ή null αν δεν βρεθεί κάποιος / the passenger or null if there is no passenger with the same * passport */ public Passenger findPassenger(String passportId) { if(this.passengers!=null) for (Passenger passenger : passengers) { if (passenger.getPassportId().equals(passportId)) return passenger; } return null; } /** * Μέθοδος για την προσθήκη ενός επιβάτη στη λίστα με τους επιβάτες της πτήσης. Η μέθοδος ελέγχει αρχικά για το αν * υπάρχουν διαθέσιμες (κενές) θέσεις. Αν δεν υπάρχουν, επιστρέφει false. Στην συνέχεια ελέγχει για το αν υπάρχει * ήδη κάποιος επιβάτης στην πτήση με το ίδιο passport id. Αν υπάρχει, τότε επιστρέφει false. Διαφορετικά, ο * επιβάτης προστίθεται στη λίστα με τους επιβάτες και επιστρέφεται true. * <p> * Method that adds a passenger to the list of the passengers of the flight. The method first checks if there are * empty seats. If there are not, then it returns false. Then, it checks if there is already a passenger in the * flight with the same passport id. If there is, then it returns false. Otherwise, the passenger is added to the * list with the passengers and it returns true. * * @param passenger Ο επιβάτης που είναι να προστεθεί / The passenger to be added * @return True ή false, ανάλογα με το αν ο επιβάτης έχει προστεθεί στην πτήση ή όχι / True or false, according to * whether the passenger has been successfully added to the flight or not. */ public boolean addPassenger(Passenger passenger) { if(getEmptySeats() <= 0) return false; if(passenger == null) return false; Passenger existingPassenger = findPassenger(passenger.getPassportId()); if (existingPassenger != null) { System.out.printf("There is already a passenger with passport id: %s \n", passenger.getPassportId()); return false; } this.passengers.add(passenger); return true; } /** * Μέθοδος που επιστρέφει το ποσοστό πληρότητας της πτήσης, δηλαδή τον λόγο του αριθμού των επιβατών προς τις * συνολικές θέσεις (χωρητικότητα) της πτήσης. * <p> * Method that returns the occupancy percentage, that is, the ratio of the number of passengers to the total seats. * * @return το ποσοστό πληρότητας / the occupancy percentage */ public double getOccupancy() { if(this.passengers != null) return passengers.size() / (double) seats; return 0; } /** * Επιστρέφει τον αριθμό των διαθέσιμων (κενών) θέσεων της πτήσης, δηλαδή χωρητικότητα - καταχωρημένοι επιβάτες. * <p> * It returns the number of the available (empty) seats, i.e. total seats - registered passengers. * * @return οι διαθέσιμες (κενές) θέσεις / the available (empty) seats */ public int getEmptySeats() { if(this.passengers != null) return seats - passengers.size(); return this.seats; } /** * Επιστρέφει τα ελάχιστα λίτρα καυσίμου που πρέπει να υπάρχουν στην πτήση. Τα λίτρα καυσίμου για μία πτήση * υπολογίζονται χρησιμοποιώντας τη μέση κατανάλωση καυσίμου για ένα αεροπλάνο ανά ώρα (μεταβλητή * AVERAGE_FUEL_CONSUMPTION_PER_HOUR = 1000) επί τη διάρκεια της πτήσης (σε ώρες). Για ασφάλεια, πρέπει να υπάρχει * και 10% περισσότερο καύσιμο στην πτήση. Έτσι αν μια πτήση διαρκεί 1 ώρα, τα ελάχιστα καύσιμα που πρέπει να * υπάρχουν στην πτήση είναι 1100 λίτρα. * <p> * It returns the minimum amount of fuels (in litres) that the flight should have. The amount of fuels for a flight * is calculated taking into account the average fuel consumption for a flight (variable * AVERAGE_FUEL_CONSUMPTION_PER_HOUR = 1000) times the duration of the flight (in hours). For safety, the flight * should have 10% more fuels. For example, if the duration of the flight is 1 hour, then the minimum amount of fuel * for the flight is 1100 litres. * * @return τα ελάχιστα λίτρα καυσίμου για την πτήση / the minimum fuels for the trip */ public double getMinimumFuelsForTheTrip() { return CONSTANTS.AVERAGE_FUEL_CONSUMPTION_PER_HOUR * duration * (1 + 0.1); } }
31642_9
package org.elasticsearch.index.analysis; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.logging.ESLogger; /** * @author Tasos Stathopoulos</p> * Generates singular/plural variants of a greek word based * on a combination of predefined rules. */ public class GreekReverseStemmer { /** * Elastic Search logger */ protected final ESLogger logger; /** * Constant variable that represent suffixes for pluralization of * greeklish tokens. */ private static final String SUFFIX_MATOS = "ματοσ"; private static final String SUFFIX_MATA = "ματα"; private static final String SUFFIX_MATWN = "ματων"; private static final String SUFFIX_AS = "ασ"; private static final String SUFFIX_EIA = "εια"; private static final String SUFFIX_EIO = "ειο"; private static final String SUFFIX_EIOY = "ειου"; private static final String SUFFIX_EIWN = "ειων"; private static final String SUFFIX_IOY = "ιου"; private static final String SUFFIX_IA = "ια"; private static final String SUFFIX_IWN = "ιων"; private static final String SUFFIX_OS = "οσ"; private static final String SUFFIX_OI = "οι"; private static final String SUFFIX_EIS = "εισ"; private static final String SUFFIX_ES = "εσ"; private static final String SUFFIX_HS = "ησ"; private static final String SUFFIX_WN = "ων"; private static final String SUFFIX_OY = "ου"; private static final String SUFFIX_O = "ο"; private static final String SUFFIX_H = "η"; private static final String SUFFIX_A = "α"; private static final String SUFFIX_I = "ι"; /** * This hash has as keys all the suffixes that we want to handle in order * to generate singular/plural greek words. */ private final Map<String, String[]> suffixes = new HashMap<String, String[]>(); /** * The possible suffix strings. */ private static final String[][] suffixStrings = new String[][] { {SUFFIX_MATOS, "μα", "ματων", "ματα"}, // κουρεματος, ασυρματος {SUFFIX_MATA, "μα", "ματων", "ματοσ"}, // ενδυματα {SUFFIX_MATWN, "μα", "ματα", "ματοσ"}, // ασυρματων, ενδυματων {SUFFIX_AS, "α", "ων", "εσ"}, // πορτας, χαρτοφυλακας {SUFFIX_EIA, "ειο", "ειων", "ειου", "ειασ"}, // γραφεια, ενεργεια {SUFFIX_EIO, "εια", "ειων", "ειου"}, // γραφειο {SUFFIX_EIOY, "εια", "ειου", "ειο", "ειων"}, // γραφειου {SUFFIX_EIWN, "εια", "ειου", "ειο", "ειασ"}, // ασφαλειων, γραφειων {SUFFIX_IOY, "ι", "ια", "ιων", "ιο"}, // πεδιου, κυνηγιου {SUFFIX_IA, "ιου", "ι", "ιων", "ιασ", "ιο"}, // πεδία, αρμονια {SUFFIX_IWN, "ιου", "ια", "ι", "ιο"}, // καλωδιων, κατοικιδιων {SUFFIX_OS, "η", "ουσ", "ου", "οι", "ων"}, // κλιματισμος {SUFFIX_OI, "οσ", "ου", "ων"}, // μυλοι, οδηγοι, σταθμοι {SUFFIX_EIS, "η", "ησ", "εων"}, // συνδεσεις, τηλεορασεις {SUFFIX_ES, "η", "ασ", "ων", "ησ", "α"}, // αλυσιδες {SUFFIX_HS, "ων", "εσ", "η", "εων"}, // γυμναστικης, εκτυπωσης {SUFFIX_WN, "οσ", "εσ", "α", "η", "ησ", "ου", "οι", "ο", "α"}, // ινων, καπνιστων, καρτων, κατασκευων {SUFFIX_OY, "ων", "α", "ο", "οσ"}, // λαδιου, μοντελισμου, παιδικου {SUFFIX_O, "α", "ου", "εων", "ων"}, // αυτοκινητο, δισκος {SUFFIX_H, "οσ", "ουσ", "εων", "εισ", "ησ", "ων"}, //βελη, ψυξη, τηλεοραση, αποτριχωση {SUFFIX_A, "ο" , "ου", "ων", "ασ", "εσ"}, // γιλεκα, εσωρουχα, ομπρελλα {SUFFIX_I, "ιου", "ια", "ιων"} // γιαουρτι, γραναζι }; /** * The greek word list */ private List<String> greekWords = new ArrayList<String>(); // Constructor public GreekReverseStemmer() { // initialize logger this.logger = Loggers.getLogger("greeklish.greekReverseStemmer"); // populate suffixes for (String[] suffix : suffixStrings) { suffixes.put(suffix[0], Arrays.copyOfRange(suffix, 1, suffix.length)); } } /** * This method generates the greek variants of the greek token that * receives. * * @param tokenString the greek word * @return a list of the generated greek word variations */ public List<String> generateGreekVariants(String tokenString) { // clear the list from variations of the previous greek token greekWords.clear(); // add the initial greek token in the greek words greekWords.add(tokenString); // Find the first matching suffix and generate the // the variants of this word for (String[] suffix : suffixStrings) { if (tokenString.endsWith(suffix[0])) { // Add to greekWords the tokens with the desired suffixes generate_more_greek_words(tokenString, suffix[0]); break; } } return greekWords; } /** * Generates more greek words based on the suffix of the original word * @param inputSuffix the suffix that matched */ private void generate_more_greek_words(final String inputToken, final String inputSuffix) { for (String suffix : suffixes.get(inputSuffix)) { greekWords.add(inputToken.replaceAll(inputSuffix + "$", suffix)); } } }
astathopoulos/elasticsearch-analysis-greeklish
src/main/java/org/elasticsearch/index/analysis/GreekReverseStemmer.java
2,047
// γιλεκα, εσωρουχα, ομπρελλα
line_comment
el
package org.elasticsearch.index.analysis; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.logging.ESLogger; /** * @author Tasos Stathopoulos</p> * Generates singular/plural variants of a greek word based * on a combination of predefined rules. */ public class GreekReverseStemmer { /** * Elastic Search logger */ protected final ESLogger logger; /** * Constant variable that represent suffixes for pluralization of * greeklish tokens. */ private static final String SUFFIX_MATOS = "ματοσ"; private static final String SUFFIX_MATA = "ματα"; private static final String SUFFIX_MATWN = "ματων"; private static final String SUFFIX_AS = "ασ"; private static final String SUFFIX_EIA = "εια"; private static final String SUFFIX_EIO = "ειο"; private static final String SUFFIX_EIOY = "ειου"; private static final String SUFFIX_EIWN = "ειων"; private static final String SUFFIX_IOY = "ιου"; private static final String SUFFIX_IA = "ια"; private static final String SUFFIX_IWN = "ιων"; private static final String SUFFIX_OS = "οσ"; private static final String SUFFIX_OI = "οι"; private static final String SUFFIX_EIS = "εισ"; private static final String SUFFIX_ES = "εσ"; private static final String SUFFIX_HS = "ησ"; private static final String SUFFIX_WN = "ων"; private static final String SUFFIX_OY = "ου"; private static final String SUFFIX_O = "ο"; private static final String SUFFIX_H = "η"; private static final String SUFFIX_A = "α"; private static final String SUFFIX_I = "ι"; /** * This hash has as keys all the suffixes that we want to handle in order * to generate singular/plural greek words. */ private final Map<String, String[]> suffixes = new HashMap<String, String[]>(); /** * The possible suffix strings. */ private static final String[][] suffixStrings = new String[][] { {SUFFIX_MATOS, "μα", "ματων", "ματα"}, // κουρεματος, ασυρματος {SUFFIX_MATA, "μα", "ματων", "ματοσ"}, // ενδυματα {SUFFIX_MATWN, "μα", "ματα", "ματοσ"}, // ασυρματων, ενδυματων {SUFFIX_AS, "α", "ων", "εσ"}, // πορτας, χαρτοφυλακας {SUFFIX_EIA, "ειο", "ειων", "ειου", "ειασ"}, // γραφεια, ενεργεια {SUFFIX_EIO, "εια", "ειων", "ειου"}, // γραφειο {SUFFIX_EIOY, "εια", "ειου", "ειο", "ειων"}, // γραφειου {SUFFIX_EIWN, "εια", "ειου", "ειο", "ειασ"}, // ασφαλειων, γραφειων {SUFFIX_IOY, "ι", "ια", "ιων", "ιο"}, // πεδιου, κυνηγιου {SUFFIX_IA, "ιου", "ι", "ιων", "ιασ", "ιο"}, // πεδία, αρμονια {SUFFIX_IWN, "ιου", "ια", "ι", "ιο"}, // καλωδιων, κατοικιδιων {SUFFIX_OS, "η", "ουσ", "ου", "οι", "ων"}, // κλιματισμος {SUFFIX_OI, "οσ", "ου", "ων"}, // μυλοι, οδηγοι, σταθμοι {SUFFIX_EIS, "η", "ησ", "εων"}, // συνδεσεις, τηλεορασεις {SUFFIX_ES, "η", "ασ", "ων", "ησ", "α"}, // αλυσιδες {SUFFIX_HS, "ων", "εσ", "η", "εων"}, // γυμναστικης, εκτυπωσης {SUFFIX_WN, "οσ", "εσ", "α", "η", "ησ", "ου", "οι", "ο", "α"}, // ινων, καπνιστων, καρτων, κατασκευων {SUFFIX_OY, "ων", "α", "ο", "οσ"}, // λαδιου, μοντελισμου, παιδικου {SUFFIX_O, "α", "ου", "εων", "ων"}, // αυτοκινητο, δισκος {SUFFIX_H, "οσ", "ουσ", "εων", "εισ", "ησ", "ων"}, //βελη, ψυξη, τηλεοραση, αποτριχωση {SUFFIX_A, "ο" , "ου", "ων", "ασ", "εσ"}, // γιλεκα, εσωρουχα,<SUF> {SUFFIX_I, "ιου", "ια", "ιων"} // γιαουρτι, γραναζι }; /** * The greek word list */ private List<String> greekWords = new ArrayList<String>(); // Constructor public GreekReverseStemmer() { // initialize logger this.logger = Loggers.getLogger("greeklish.greekReverseStemmer"); // populate suffixes for (String[] suffix : suffixStrings) { suffixes.put(suffix[0], Arrays.copyOfRange(suffix, 1, suffix.length)); } } /** * This method generates the greek variants of the greek token that * receives. * * @param tokenString the greek word * @return a list of the generated greek word variations */ public List<String> generateGreekVariants(String tokenString) { // clear the list from variations of the previous greek token greekWords.clear(); // add the initial greek token in the greek words greekWords.add(tokenString); // Find the first matching suffix and generate the // the variants of this word for (String[] suffix : suffixStrings) { if (tokenString.endsWith(suffix[0])) { // Add to greekWords the tokens with the desired suffixes generate_more_greek_words(tokenString, suffix[0]); break; } } return greekWords; } /** * Generates more greek words based on the suffix of the original word * @param inputSuffix the suffix that matched */ private void generate_more_greek_words(final String inputToken, final String inputSuffix) { for (String suffix : suffixes.get(inputSuffix)) { greekWords.add(inputToken.replaceAll(inputSuffix + "$", suffix)); } } }
32320_11
package gr.auth.ee.dsproject.abalone; import java.awt.Color; import java.util.Vector; /** * <p>Title: DataStructures2010</p> * * <p>Description: Data Structures project: year 2010-2011</p> * * <p>Copyright: Copyright (c) 2010</p> * * <p>Company: A.U.Th.</p> * * @author Vivia Nikolaidou * @version 1.0 */ public class Player { // // Fields // String type="Human"; boolean isBlack; int deadPieces; static String[] availableTypes={"Human", "Random", "Heuristic"}; // // Constructors // /** * @param isComputer * @param isBlack */ public Player( String type, boolean isBlack ) { this.type=type; this.isBlack=isBlack; } // // Methods // // // Accessor methods // /** * Set the value of isComputer * @param newVar the new value of isComputer */ public void setType ( String newVar ) { type = newVar; } /** * Get the value of isComputer * @return the value of isComputer */ public String getType ( ) { return type; } /** * Set the value of isBlack * @param newVar the new value of isBlack */ public void setIsBlack ( boolean newVar ) { isBlack = newVar; } /** * Get the value of isBlack * @return the value of isBlack */ public boolean isBlack ( ) { return isBlack; } /** * Set the value of deadPieces * @param newVar the new value of deadPieces */ public void setDeadPieces ( int newVar ) { deadPieces = newVar; } /** * Get the value of deadPieces * @return the value of deadPieces */ public int getDeadPieces ( ) { return deadPieces; } /** * Get the value of availableTypes * @return the value of availableTypes */ public static String[] getAvailableTypes() { return availableTypes; } /** * Set the value of availableTypes * @param newVar the new value of availableTypes */ public static void setAvailableTypes(String[] newVar) { availableTypes = newVar; } // // Other methods // /** * @param game */ public Move getNextMove( Game game ) { Vector<Move> moves = findAllMoves(game); if (type=="Heuristic") return getNextMoveHeuristic(game, moves); if (type=="Human") System.out.println("Warning: asked human's next move! Returning random"); return getNextMoveRandom(game, moves); } private Move getNextMoveRandom (Game game, Vector<Move> moves) { int nmoves = moves.size(); int rand = (int)Math.floor(nmoves*Math.random()); return moves.get(rand); } private Move getNextMoveHeuristic (Game game, Vector<Move> moves) { int nmoves = moves.size(); int imax=0; double max=-2000; for (int i=0;i<nmoves;i++) { Game gcopy = game.copy(); Cell newFrom1 = gcopy.getBoard()[moves.get(i).getFrom1().getX()][moves.get(i).getFrom1().getY()]; Cell newFrom2 = gcopy.getBoard()[moves.get(i).getFrom2().getX()][moves.get(i).getFrom2().getY()]; Cell newTo2 = gcopy.getBoard()[moves.get(i).getTo2().getX()][moves.get(i).getTo2().getY()]; Move newMove = new Move(newFrom1, newFrom2, newTo2); gcopy.playMove(newMove); double eval = evaluate(gcopy); if (eval>max) { imax=i; max=eval; } } return moves.get(imax); } /**Ευρεση και αξιολογηση διαθεσιμων κινησεων Δημοσθενης Μπελεβεσλης ΑΕΜ : 6981 Τηλέφωνο : 6945255427 E-mail : [email protected] Αθανασιος Μεκρας ΑΕΜ : 7074 Τηλέφωνο : 6943949005 E-mail : [email protected] */ /** * Evaluation method * We use three evaluation criteria * @param game corresponds to the game */ public double evaluate (Game game) { double x1=0,x2=0,x3=0,y1=0,y2=0,y3=0,Xol=0,Yol=0; double E=0; /** * Criterion Number 1 * Check the number of black player's DeadPieces * Depending on the number of DeadPieces give us a different rating */ switch(game.blackPlayer.getDeadPieces()) { case 0: { x1=x1+100; break; } case 1: { x1=x1+90; break; } case 2: { x1=x1+75; break; } case 3: { x1=x1+55; break; } case 4: { x1=x1+30; break; } case 5: { x1=x1+10; break; } } /** * Check the number of white player's DeadPieces * Depending on the number of DeadPieces give us a different rating */ switch(game.whitePlayer.getDeadPieces()) { case 0: { y1=y1+100; break; } case 1: { y1=y1+90; break; } case 2: { y1=y1+75; break; } case 3: { y1=y1+55; break; } case 4: { y1=y1+30; break; } case 5: { y1=y1+10; break; } } /** * Criterion Number 2 * Check all the black marbles * Depending on how close to the center is the marble, the higher rating is given */ for (int i=1;i<=9;i++) { for (int j=1;j<=9;j++) { if (game.board[i][j].getColor() == Color.black ) { /** * Check if the marble is located four positions away from the center */ if ((i==1) || (i==9) || (j==1) || (j==9) ) { x2=x2-1; } if ( (i>5 && i<9) && (j>1 && j<5) ) { x2=x2-1; } if ( (j>5 && j<9) && (i>1 && i<5) ) { x2=x2-1; } /** * Check if the marble is located three positions away from the center */ if ( ((i==2)&& (j>1 && j<6)) || ((i==8)&& (j>4 && j<9))) { x2=x2-0.5; } if ( ((j==2)&& (i>2 && i<6)) || ((j==8)&& (i>4 && i<8))) { x2=x2-0.5; } if ( ((i==6)&&(j==3)) || ((i==3)&&(j==6)) || ((i==7)&&(j==4)) || ((i==4)&&(j==7))) { x2=x2-0.5; } /** * Check if the marble is located two positions away from the center */ if (( (i==3) && (j>2 && j<6)) || ((i==7) && (j>4 && j<8))) { x2=x2+0.5; } if (((i==4) && (j==3)) || ((i==5) && (j==3)) || ((i==6) && (j==4)) || ((i==4) && (j==6)) || ((i==5) && (j==7)) || ((i==6) && (j==7))) { x2=x2+0.5; } /** * Check if the marble is located one position away from the center */ if (( (i==4) && (j>3 && j<6)) || ((i==6) && (j>4 && j<7)) || ((i==5) && (j==4)) || ((i==5) && (j==6))) { x2=x2+1; } /** * Check if the marble is located in the center */ if ( (i==5) && (j==5)) { x2=x2+3; } } } } /** * Check all the white marbles * Depending on how close to the center is the marble, the higher rating is given */ for (int i=1;i<=9;i++) { for (int j=1;j<=9;j++) { if (game.board[i][j].getColor() == Color.white ) { /** * Check if the marble is located four positions away from the center */ if ((i==1) || (i==9) || (j==1) || (j==9) ) { y2=y2-1; } if ( (i>5 && i<9) && (j>1 && j<5) ) { y2=y2-1; } if ( (j>5 && j<9) && (i>1 && i<5) ) { y2=y2-1; } /** * Check if the marble is located three positions away from the center */ if ( ((i==2)&& (j>1 && j<6)) || ((i==8)&& (j>4 && j<9))) { y2=y2-0.5; } if ( ((j==2)&& (i>2 && i<6)) || ((j==8)&& (i>4 && i<8))) { y2=y2-0.5; } if ( ((i==6)&&(j==3)) || ((i==3)&&(j==6)) || ((i==7)&&(j==4)) || ((i==4)&&(j==7))) { y2=y2-0.5; } /** * Check if the marble is located two positions away from the center */ if (( (i==3) && (j>2 && j<6)) || ((i==7) && (j>4 && j<8))) { y2=y2+0.5; } if (((i==4) && (j==3)) || ((i==5) && (j==3)) || ((i==6) && (j==4)) || ((i==4) && (j==6)) || ((i==5) && (j==7)) || ((i==6) && (j==7))) { y2=y2+0.5; } /** * Check if the marble is located one position away from the center */ if (( (i==4) && (j>3 && j<6)) || ((i==6) && (j>4 && j<7)) || ((i==5) && (j==4)) || ((i==5) && (j==6))) { y2=y2+1; } /** * Check if the marble is located in the center */ if ( (i==5) && (j==5)) { y2=y2+3; } } } } /** * Criterion Number 3 * Check all the black marbles * The more comprehensive are the marbles the higher rating is given */ for (int i=1;i<=9;i++) { for (int j=1;j<=9;j++) { if (game.board[i][j].getColor() == Color.black ) { /** *Check the six neighbors of the cell */ for (int k=0; k<=5; k++) { /** * Check if the neighbor cell is null and is located inside the board */ if ((game.board[i][j].getNeighbors(game.board)[k].getColor() == null) && (game.board[i][j].getNeighbors(game.board)[k].isInBoard())) { x3=x3+0.5; } /** * Check if the neighbor cell is white and is located inside the board */ if ((game.board[i][j].getNeighbors(game.board)[k].getColor() == Color.white) && (game.board[i][j].getNeighbors(game.board)[k].isInBoard())) { x3=x3+0.25; } /** * Check if the neighbor cell is black and is located inside the board */ if ((game.board[i][j].getNeighbors(game.board)[k].getColor() == Color.black) && (game.board[i][j].getNeighbors(game.board)[k].isInBoard())) { x3=x3+1; } } } /** * Check all the white marbles * The more comprehensive are the marbles the higher rating is given */ if (game.board[i][j].getColor() == Color.white ) { /** *Check the six neighbors of the cell */ for (int k=0; k<=5; k++) { /** * Check if the neighbor cell is null and is located inside the board */ if ((game.board[i][j].getNeighbors(game.board)[k].getColor() == null) && (game.board[i][j].getNeighbors(game.board)[k].isInBoard())) { y3=y3+0.5; } /** * Check if the neighbor cell is black and is located inside the board */ if ((game.board[i][j].getNeighbors(game.board)[k].getColor() == Color.black) && (game.board[i][j].getNeighbors(game.board)[k].isInBoard())) { y3=y3+0.25; } /** * Check if the neighbor cell is white and is located inside the board */ if ((game.board[i][j].getNeighbors(game.board)[k].getColor() == Color.white) && (game.board[i][j].getNeighbors(game.board)[k].isInBoard())) { y3=y3+1; } } } } } /** * Add the results of the three criteria for each color */ Xol=x1+x2+x3; Yol=y1+y2+y3; /** * Check if it's black player's turn in order to make the correct subtraction */ if(game.getCurrent().isBlack()) { E=Xol-Yol; } /** * Check if it's white player's turn in order to make the correct subtraction */ if(!game.getCurrent().isBlack()) { E=Yol-Xol; } /** * Returns the evaluation of the game */ return E; } /** * Finds and returns all possible moves * @param game corresponds to the game */ public Vector<Move> findAllMoves (Game game) { Vector<Move> moves = new Vector<Move>(); /** * We seek all board cells */ for (int i=0; i<11;i++) { for (int j=0; j<11;j++) { /** * Check if the color of the cell is the same color of the player whose turn to play */ if ((game.board[i][j].getColor() == Color.black && game.getCurrent().isBlack()== true && game.board[i][j].isInBoard()) || (game.board[i][j].getColor() == Color.white && game.getCurrent().isBlack()==false && game.board[i][j].isInBoard())) { /** * To move one marble * Check the six neighbors of the cell */ for(int z=0;z<=5;z++) { /** * Check if the neighbor cell is null and is located inside the board */ if ((game.board[i][j].getNeighbors(game.board)[z].getColor() == null) && game.board[i][j].isInBoard() &&(game.board[i][j].getNeighbors(game.board)[z].isInBoard())) { Cell newFrom1 = game.board[i][j]; Cell newFrom2 = game.board[i][j]; Cell newTo2 = game.board[i][j].getNeighbors(game.board)[z]; Move newMove = new Move(newFrom1, newFrom2, newTo2); moves.add(newMove); } } } /** * We seek all board cells */ for(int z=1;z<11;z++) { for(int h=1;h<11;h++) { /** * To move two marble * Check the half neighbors of the cell in order to avoid duplicate moves */ for (int k=0; k<=2; k++) { /** * Check if the color of the cell is the same color of the player whose turn to play * Check if the neighbor cell is null and is located inside the board */ if ((game.board[i][j].getNeighbors(game.board)[k] == game.board[z][h] && game.board[z][h].getColor() == Color.black && game.getCurrent().isBlack()==true && game.board[z][h].isInBoard() && game.board[i][j].isInBoard()) || (game.board[i][j].getNeighbors(game.board)[k] == game.board[z][h] && game.board[z][h].getColor() == Color.white && game.getCurrent().isBlack() ==false && game.board[z][h].isInBoard() && game.board[i][j].isInBoard()) ) { for (int n=0; n<=2;n++) { if(game.board[i][j].isInBoard()&& game.board[z][h].isInBoard() && game.board[z][h].getNeighbors(game.board)[n].isInBoard()) { Cell newFrom1 = game.board[i][j]; Cell newFrom2 = game.board[z][h]; Cell newTo2 = game.board[z][h].getNeighbors(game.board)[n]; Move newMove = new Move(newFrom1, newFrom2, newTo2); /** * Check whether the move is valid * Adds the newMove to moves */ if( newMove.isValid(game.board )) { moves.add(newMove); } } } } } /** * We seek all board cells */ for(int m=0;m<11;m++) { for(int n=0;n<11;n++) { /** * To move three marble * Check the half neighbors of the cell in order to avoid duplicate moves */ for(int w=0; w<=2; w++) { /** * Check if the color of the cell is the same color of the player whose turn to play * Check if the neighbor cell is null and is located inside the board */ if ((game.board[z][h].getNeighbors(game.board)[w] == game.board[m][n] && game.board[m][n].getColor() == Color.black && game.getCurrent().isBlack()==true && game.board[m][n].isInBoard() && game.board[i][j].isInBoard()) || (game.board[z][h].getNeighbors(game.board)[w] == game.board[m][n] && game.board[m][n].getColor() == Color.white && game.getCurrent().isBlack() ==false && game.board[m][n].isInBoard() && game.board[i][j].isInBoard()) ) { /** * Check the direction of the marbles */ if(((i==z) && (i==m)) || ((j==h)&&(j==n)) || (((i==(z+1))&&(i==(m+2)) )&& ((j==(h+1))&&(j==(n+2)) ) )) { for (int s=0; s<=0;s++) { if(game.board[i][j].isInBoard()&& game.board[z][h].isInBoard() && game.board[m][n].getNeighbors(game.board)[s].isInBoard()) { Cell newFrom1 = game.board[i][j]; Cell newFrom2 = game.board[m][n]; Cell newTo2 = game.board[m][n].getNeighbors(game.board)[s]; Move newMove = new Move(newFrom1, newFrom2, newTo2); /** * Check whether the move is valid * Adds the newMove to moves */ if ( newMove.isValid(game.board)) { moves.add( newMove); } } } } } } } } } } } } /** * Return the possible moves */ return moves; } /** */ public void addDeadPiece( ) { deadPieces++; } public void resetDeadPieces( ) { deadPieces = 0; } }
athmekr/Abalone
Part B/Player.java
5,857
/**Ευρεση και αξιολογηση διαθεσιμων κινησεων Δημοσθενης Μπελεβεσλης ΑΕΜ : 6981 Τηλέφωνο : 6945255427 E-mail : [email protected] Αθανασιος Μεκρας ΑΕΜ : 7074 Τηλέφωνο : 6943949005 E-mail : [email protected] */
block_comment
el
package gr.auth.ee.dsproject.abalone; import java.awt.Color; import java.util.Vector; /** * <p>Title: DataStructures2010</p> * * <p>Description: Data Structures project: year 2010-2011</p> * * <p>Copyright: Copyright (c) 2010</p> * * <p>Company: A.U.Th.</p> * * @author Vivia Nikolaidou * @version 1.0 */ public class Player { // // Fields // String type="Human"; boolean isBlack; int deadPieces; static String[] availableTypes={"Human", "Random", "Heuristic"}; // // Constructors // /** * @param isComputer * @param isBlack */ public Player( String type, boolean isBlack ) { this.type=type; this.isBlack=isBlack; } // // Methods // // // Accessor methods // /** * Set the value of isComputer * @param newVar the new value of isComputer */ public void setType ( String newVar ) { type = newVar; } /** * Get the value of isComputer * @return the value of isComputer */ public String getType ( ) { return type; } /** * Set the value of isBlack * @param newVar the new value of isBlack */ public void setIsBlack ( boolean newVar ) { isBlack = newVar; } /** * Get the value of isBlack * @return the value of isBlack */ public boolean isBlack ( ) { return isBlack; } /** * Set the value of deadPieces * @param newVar the new value of deadPieces */ public void setDeadPieces ( int newVar ) { deadPieces = newVar; } /** * Get the value of deadPieces * @return the value of deadPieces */ public int getDeadPieces ( ) { return deadPieces; } /** * Get the value of availableTypes * @return the value of availableTypes */ public static String[] getAvailableTypes() { return availableTypes; } /** * Set the value of availableTypes * @param newVar the new value of availableTypes */ public static void setAvailableTypes(String[] newVar) { availableTypes = newVar; } // // Other methods // /** * @param game */ public Move getNextMove( Game game ) { Vector<Move> moves = findAllMoves(game); if (type=="Heuristic") return getNextMoveHeuristic(game, moves); if (type=="Human") System.out.println("Warning: asked human's next move! Returning random"); return getNextMoveRandom(game, moves); } private Move getNextMoveRandom (Game game, Vector<Move> moves) { int nmoves = moves.size(); int rand = (int)Math.floor(nmoves*Math.random()); return moves.get(rand); } private Move getNextMoveHeuristic (Game game, Vector<Move> moves) { int nmoves = moves.size(); int imax=0; double max=-2000; for (int i=0;i<nmoves;i++) { Game gcopy = game.copy(); Cell newFrom1 = gcopy.getBoard()[moves.get(i).getFrom1().getX()][moves.get(i).getFrom1().getY()]; Cell newFrom2 = gcopy.getBoard()[moves.get(i).getFrom2().getX()][moves.get(i).getFrom2().getY()]; Cell newTo2 = gcopy.getBoard()[moves.get(i).getTo2().getX()][moves.get(i).getTo2().getY()]; Move newMove = new Move(newFrom1, newFrom2, newTo2); gcopy.playMove(newMove); double eval = evaluate(gcopy); if (eval>max) { imax=i; max=eval; } } return moves.get(imax); } /**Ευρεση και αξιολογηση<SUF>*/ /** * Evaluation method * We use three evaluation criteria * @param game corresponds to the game */ public double evaluate (Game game) { double x1=0,x2=0,x3=0,y1=0,y2=0,y3=0,Xol=0,Yol=0; double E=0; /** * Criterion Number 1 * Check the number of black player's DeadPieces * Depending on the number of DeadPieces give us a different rating */ switch(game.blackPlayer.getDeadPieces()) { case 0: { x1=x1+100; break; } case 1: { x1=x1+90; break; } case 2: { x1=x1+75; break; } case 3: { x1=x1+55; break; } case 4: { x1=x1+30; break; } case 5: { x1=x1+10; break; } } /** * Check the number of white player's DeadPieces * Depending on the number of DeadPieces give us a different rating */ switch(game.whitePlayer.getDeadPieces()) { case 0: { y1=y1+100; break; } case 1: { y1=y1+90; break; } case 2: { y1=y1+75; break; } case 3: { y1=y1+55; break; } case 4: { y1=y1+30; break; } case 5: { y1=y1+10; break; } } /** * Criterion Number 2 * Check all the black marbles * Depending on how close to the center is the marble, the higher rating is given */ for (int i=1;i<=9;i++) { for (int j=1;j<=9;j++) { if (game.board[i][j].getColor() == Color.black ) { /** * Check if the marble is located four positions away from the center */ if ((i==1) || (i==9) || (j==1) || (j==9) ) { x2=x2-1; } if ( (i>5 && i<9) && (j>1 && j<5) ) { x2=x2-1; } if ( (j>5 && j<9) && (i>1 && i<5) ) { x2=x2-1; } /** * Check if the marble is located three positions away from the center */ if ( ((i==2)&& (j>1 && j<6)) || ((i==8)&& (j>4 && j<9))) { x2=x2-0.5; } if ( ((j==2)&& (i>2 && i<6)) || ((j==8)&& (i>4 && i<8))) { x2=x2-0.5; } if ( ((i==6)&&(j==3)) || ((i==3)&&(j==6)) || ((i==7)&&(j==4)) || ((i==4)&&(j==7))) { x2=x2-0.5; } /** * Check if the marble is located two positions away from the center */ if (( (i==3) && (j>2 && j<6)) || ((i==7) && (j>4 && j<8))) { x2=x2+0.5; } if (((i==4) && (j==3)) || ((i==5) && (j==3)) || ((i==6) && (j==4)) || ((i==4) && (j==6)) || ((i==5) && (j==7)) || ((i==6) && (j==7))) { x2=x2+0.5; } /** * Check if the marble is located one position away from the center */ if (( (i==4) && (j>3 && j<6)) || ((i==6) && (j>4 && j<7)) || ((i==5) && (j==4)) || ((i==5) && (j==6))) { x2=x2+1; } /** * Check if the marble is located in the center */ if ( (i==5) && (j==5)) { x2=x2+3; } } } } /** * Check all the white marbles * Depending on how close to the center is the marble, the higher rating is given */ for (int i=1;i<=9;i++) { for (int j=1;j<=9;j++) { if (game.board[i][j].getColor() == Color.white ) { /** * Check if the marble is located four positions away from the center */ if ((i==1) || (i==9) || (j==1) || (j==9) ) { y2=y2-1; } if ( (i>5 && i<9) && (j>1 && j<5) ) { y2=y2-1; } if ( (j>5 && j<9) && (i>1 && i<5) ) { y2=y2-1; } /** * Check if the marble is located three positions away from the center */ if ( ((i==2)&& (j>1 && j<6)) || ((i==8)&& (j>4 && j<9))) { y2=y2-0.5; } if ( ((j==2)&& (i>2 && i<6)) || ((j==8)&& (i>4 && i<8))) { y2=y2-0.5; } if ( ((i==6)&&(j==3)) || ((i==3)&&(j==6)) || ((i==7)&&(j==4)) || ((i==4)&&(j==7))) { y2=y2-0.5; } /** * Check if the marble is located two positions away from the center */ if (( (i==3) && (j>2 && j<6)) || ((i==7) && (j>4 && j<8))) { y2=y2+0.5; } if (((i==4) && (j==3)) || ((i==5) && (j==3)) || ((i==6) && (j==4)) || ((i==4) && (j==6)) || ((i==5) && (j==7)) || ((i==6) && (j==7))) { y2=y2+0.5; } /** * Check if the marble is located one position away from the center */ if (( (i==4) && (j>3 && j<6)) || ((i==6) && (j>4 && j<7)) || ((i==5) && (j==4)) || ((i==5) && (j==6))) { y2=y2+1; } /** * Check if the marble is located in the center */ if ( (i==5) && (j==5)) { y2=y2+3; } } } } /** * Criterion Number 3 * Check all the black marbles * The more comprehensive are the marbles the higher rating is given */ for (int i=1;i<=9;i++) { for (int j=1;j<=9;j++) { if (game.board[i][j].getColor() == Color.black ) { /** *Check the six neighbors of the cell */ for (int k=0; k<=5; k++) { /** * Check if the neighbor cell is null and is located inside the board */ if ((game.board[i][j].getNeighbors(game.board)[k].getColor() == null) && (game.board[i][j].getNeighbors(game.board)[k].isInBoard())) { x3=x3+0.5; } /** * Check if the neighbor cell is white and is located inside the board */ if ((game.board[i][j].getNeighbors(game.board)[k].getColor() == Color.white) && (game.board[i][j].getNeighbors(game.board)[k].isInBoard())) { x3=x3+0.25; } /** * Check if the neighbor cell is black and is located inside the board */ if ((game.board[i][j].getNeighbors(game.board)[k].getColor() == Color.black) && (game.board[i][j].getNeighbors(game.board)[k].isInBoard())) { x3=x3+1; } } } /** * Check all the white marbles * The more comprehensive are the marbles the higher rating is given */ if (game.board[i][j].getColor() == Color.white ) { /** *Check the six neighbors of the cell */ for (int k=0; k<=5; k++) { /** * Check if the neighbor cell is null and is located inside the board */ if ((game.board[i][j].getNeighbors(game.board)[k].getColor() == null) && (game.board[i][j].getNeighbors(game.board)[k].isInBoard())) { y3=y3+0.5; } /** * Check if the neighbor cell is black and is located inside the board */ if ((game.board[i][j].getNeighbors(game.board)[k].getColor() == Color.black) && (game.board[i][j].getNeighbors(game.board)[k].isInBoard())) { y3=y3+0.25; } /** * Check if the neighbor cell is white and is located inside the board */ if ((game.board[i][j].getNeighbors(game.board)[k].getColor() == Color.white) && (game.board[i][j].getNeighbors(game.board)[k].isInBoard())) { y3=y3+1; } } } } } /** * Add the results of the three criteria for each color */ Xol=x1+x2+x3; Yol=y1+y2+y3; /** * Check if it's black player's turn in order to make the correct subtraction */ if(game.getCurrent().isBlack()) { E=Xol-Yol; } /** * Check if it's white player's turn in order to make the correct subtraction */ if(!game.getCurrent().isBlack()) { E=Yol-Xol; } /** * Returns the evaluation of the game */ return E; } /** * Finds and returns all possible moves * @param game corresponds to the game */ public Vector<Move> findAllMoves (Game game) { Vector<Move> moves = new Vector<Move>(); /** * We seek all board cells */ for (int i=0; i<11;i++) { for (int j=0; j<11;j++) { /** * Check if the color of the cell is the same color of the player whose turn to play */ if ((game.board[i][j].getColor() == Color.black && game.getCurrent().isBlack()== true && game.board[i][j].isInBoard()) || (game.board[i][j].getColor() == Color.white && game.getCurrent().isBlack()==false && game.board[i][j].isInBoard())) { /** * To move one marble * Check the six neighbors of the cell */ for(int z=0;z<=5;z++) { /** * Check if the neighbor cell is null and is located inside the board */ if ((game.board[i][j].getNeighbors(game.board)[z].getColor() == null) && game.board[i][j].isInBoard() &&(game.board[i][j].getNeighbors(game.board)[z].isInBoard())) { Cell newFrom1 = game.board[i][j]; Cell newFrom2 = game.board[i][j]; Cell newTo2 = game.board[i][j].getNeighbors(game.board)[z]; Move newMove = new Move(newFrom1, newFrom2, newTo2); moves.add(newMove); } } } /** * We seek all board cells */ for(int z=1;z<11;z++) { for(int h=1;h<11;h++) { /** * To move two marble * Check the half neighbors of the cell in order to avoid duplicate moves */ for (int k=0; k<=2; k++) { /** * Check if the color of the cell is the same color of the player whose turn to play * Check if the neighbor cell is null and is located inside the board */ if ((game.board[i][j].getNeighbors(game.board)[k] == game.board[z][h] && game.board[z][h].getColor() == Color.black && game.getCurrent().isBlack()==true && game.board[z][h].isInBoard() && game.board[i][j].isInBoard()) || (game.board[i][j].getNeighbors(game.board)[k] == game.board[z][h] && game.board[z][h].getColor() == Color.white && game.getCurrent().isBlack() ==false && game.board[z][h].isInBoard() && game.board[i][j].isInBoard()) ) { for (int n=0; n<=2;n++) { if(game.board[i][j].isInBoard()&& game.board[z][h].isInBoard() && game.board[z][h].getNeighbors(game.board)[n].isInBoard()) { Cell newFrom1 = game.board[i][j]; Cell newFrom2 = game.board[z][h]; Cell newTo2 = game.board[z][h].getNeighbors(game.board)[n]; Move newMove = new Move(newFrom1, newFrom2, newTo2); /** * Check whether the move is valid * Adds the newMove to moves */ if( newMove.isValid(game.board )) { moves.add(newMove); } } } } } /** * We seek all board cells */ for(int m=0;m<11;m++) { for(int n=0;n<11;n++) { /** * To move three marble * Check the half neighbors of the cell in order to avoid duplicate moves */ for(int w=0; w<=2; w++) { /** * Check if the color of the cell is the same color of the player whose turn to play * Check if the neighbor cell is null and is located inside the board */ if ((game.board[z][h].getNeighbors(game.board)[w] == game.board[m][n] && game.board[m][n].getColor() == Color.black && game.getCurrent().isBlack()==true && game.board[m][n].isInBoard() && game.board[i][j].isInBoard()) || (game.board[z][h].getNeighbors(game.board)[w] == game.board[m][n] && game.board[m][n].getColor() == Color.white && game.getCurrent().isBlack() ==false && game.board[m][n].isInBoard() && game.board[i][j].isInBoard()) ) { /** * Check the direction of the marbles */ if(((i==z) && (i==m)) || ((j==h)&&(j==n)) || (((i==(z+1))&&(i==(m+2)) )&& ((j==(h+1))&&(j==(n+2)) ) )) { for (int s=0; s<=0;s++) { if(game.board[i][j].isInBoard()&& game.board[z][h].isInBoard() && game.board[m][n].getNeighbors(game.board)[s].isInBoard()) { Cell newFrom1 = game.board[i][j]; Cell newFrom2 = game.board[m][n]; Cell newTo2 = game.board[m][n].getNeighbors(game.board)[s]; Move newMove = new Move(newFrom1, newFrom2, newTo2); /** * Check whether the move is valid * Adds the newMove to moves */ if ( newMove.isValid(game.board)) { moves.add( newMove); } } } } } } } } } } } } /** * Return the possible moves */ return moves; } /** */ public void addDeadPiece( ) { deadPieces++; } public void resetDeadPieces( ) { deadPieces = 0; } }
31335_0
/** * Ο δυαδικός λογικός τελεστής AND. The binary logical operator AND */ public class AND extends BinaryOperator { public AND(Expression left, Expression right) { super(left, right); } public boolean evaluate() { return left.evaluate() && right.evaluate(); } }
auth-csd-oop-2020/lab-abstraction-AndNotOr-solved
src/AND.java
88
/** * Ο δυαδικός λογικός τελεστής AND. The binary logical operator AND */
block_comment
el
/** * Ο δυαδικός λογικός<SUF>*/ public class AND extends BinaryOperator { public AND(Expression left, Expression right) { super(left, right); } public boolean evaluate() { return left.evaluate() && right.evaluate(); } }
1034_8
import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; /** * Η κλάση αυτή αφορά μια συναλλαγή ενός πελάτη με ένα supermarket. Με άλλα * λόγια αντιπροσωπεύει το καλάθι με τα προϊόντα που αγόρασε σε μια επίσκεψη. * This class represents a transaction of a super market customer. In other words, * the basket with the products of a visit to the supermarket. * * @author Grigorios Tsoumakas */ public class Transaction { private HashMap<String, Integer> items; public Transaction() { // συμπληρώστε τον κώδικα items = new HashMap<>(); } /** * Η μέθοδος αυτή αντιστοιχεί στο σκανάρισμα ενός προϊόντος και άρα στην * προσθήκη του στην τρέχουσα συναλλαγή ενός πελάτη. * This method represents the scanning process in a supermarket. It adds the product * to the current transaction. * * @param product συμβολοσειρά με το όνομα του προϊόντος, π.χ. γάλα, string containing the name of * the product e.g. milk */ public void scanItem(String product) { // συμπληρώστε τον κώδικα scanItems(product, 1); } /** * Η μέθοδος αυτή αντιστοιχεί στο σκανάρισμα πολλών προϊόντων του ίδιου * είδους και προσθήκη τους στην τρέχουσα συναλλαγή ενός πελάτη. * * This method represents the scanning of the same product multiple times * and adds them to the customers transactions. * * @param product συμβολοσειρά με το όνομα του προϊόντος, π.χ. γάλα, string containing the name of * the product e.g. milk * @param amount ποσότητα προϊόντος, the amount of the products */ public void scanItems(String product, int amount) { // συμπληρώστε τον κώδικα if (items.containsKey(product)) { items.put(product, items.get(product)+amount); } else { items.put(product, amount); } } /** * Η μέθοδος αυτή επιστρέφει τo πλήθος εμφάνισης ενός προϊόντος στο * καλάθι ενός πελάτη. * The number of times a product appears in the basket. * * @param product συμβολοσειρά με το όνομα του προϊόντος, π.χ. γάλα, string containing the name of * the product e.g. milk */ public int getAmountOfProduct(String product) { if (items.containsKey(product)) { return items.get(product); } else { return 0; } // συμπληρώστε τον κώδικα } /** * Η μέθοδος αυτή επιστέφει έναν πίνακα με τα ονόματα των προϊόντων που * υπάρχουν στο καλάθι του πελάτη. Αν το ίδιο προϊόν υπάρχει πάνω από μία * φορές στο καλάθι, θα πρέπει στον επιστρεφόμενο πίνακα να εμφανίζεται μία * φορά μόνο. * * This method returns a table with the names of the products that exist in the basket. * The returning table should not contain duplicate items and each product should appear only once. * * @return ο πίνακας με τα ονόματα των προϊόντων, the table with the names of the products purchased. */ public String[] getProducts() { String[] products = new String[items.size()]; Iterator<String> it = items.keySet().iterator(); for (int i=0; i<products.length; i++) { products[i] = it.next(); } return products; } }
auth-csd-oop-2020/lab-advancedBehavior-Supermarket-solved
src/Transaction.java
1,417
/** * Η μέθοδος αυτή επιστέφει έναν πίνακα με τα ονόματα των προϊόντων που * υπάρχουν στο καλάθι του πελάτη. Αν το ίδιο προϊόν υπάρχει πάνω από μία * φορές στο καλάθι, θα πρέπει στον επιστρεφόμενο πίνακα να εμφανίζεται μία * φορά μόνο. * * This method returns a table with the names of the products that exist in the basket. * The returning table should not contain duplicate items and each product should appear only once. * * @return ο πίνακας με τα ονόματα των προϊόντων, the table with the names of the products purchased. */
block_comment
el
import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; /** * Η κλάση αυτή αφορά μια συναλλαγή ενός πελάτη με ένα supermarket. Με άλλα * λόγια αντιπροσωπεύει το καλάθι με τα προϊόντα που αγόρασε σε μια επίσκεψη. * This class represents a transaction of a super market customer. In other words, * the basket with the products of a visit to the supermarket. * * @author Grigorios Tsoumakas */ public class Transaction { private HashMap<String, Integer> items; public Transaction() { // συμπληρώστε τον κώδικα items = new HashMap<>(); } /** * Η μέθοδος αυτή αντιστοιχεί στο σκανάρισμα ενός προϊόντος και άρα στην * προσθήκη του στην τρέχουσα συναλλαγή ενός πελάτη. * This method represents the scanning process in a supermarket. It adds the product * to the current transaction. * * @param product συμβολοσειρά με το όνομα του προϊόντος, π.χ. γάλα, string containing the name of * the product e.g. milk */ public void scanItem(String product) { // συμπληρώστε τον κώδικα scanItems(product, 1); } /** * Η μέθοδος αυτή αντιστοιχεί στο σκανάρισμα πολλών προϊόντων του ίδιου * είδους και προσθήκη τους στην τρέχουσα συναλλαγή ενός πελάτη. * * This method represents the scanning of the same product multiple times * and adds them to the customers transactions. * * @param product συμβολοσειρά με το όνομα του προϊόντος, π.χ. γάλα, string containing the name of * the product e.g. milk * @param amount ποσότητα προϊόντος, the amount of the products */ public void scanItems(String product, int amount) { // συμπληρώστε τον κώδικα if (items.containsKey(product)) { items.put(product, items.get(product)+amount); } else { items.put(product, amount); } } /** * Η μέθοδος αυτή επιστρέφει τo πλήθος εμφάνισης ενός προϊόντος στο * καλάθι ενός πελάτη. * The number of times a product appears in the basket. * * @param product συμβολοσειρά με το όνομα του προϊόντος, π.χ. γάλα, string containing the name of * the product e.g. milk */ public int getAmountOfProduct(String product) { if (items.containsKey(product)) { return items.get(product); } else { return 0; } // συμπληρώστε τον κώδικα } /** * Η μέθοδος αυτή<SUF>*/ public String[] getProducts() { String[] products = new String[items.size()]; Iterator<String> it = items.keySet().iterator(); for (int i=0; i<products.length; i++) { products[i] = it.next(); } return products; } }
452_0
import java.util.ArrayList; /** * Αυτή η κλάση αναπαριστά έναν/μία ηθοποιό με το όνομα του/της, την ηλικία του/της και την λίστα με τις ταινίες * στις οποίες έχει παίξει. * This class represents an actor/actress with his/her name, age and list of movies he/she participated. */ public class Actor { private String name; private int age; private ArrayList<Movie> movies; /** * Κατασκευαστής - Constructor */ public Actor(String name, int age) { this.name = name; this.age = age; this.movies = new ArrayList<>(); } /** * Αυτή η μέθοδος επιστρέφει το όνομα του ηθοποιού. * This method returns the actor's name. */ public String getName() { return name; } /** * Αυτή η μέθοδος επιστρέφει την ηλικία του ηθοποιού. * This method returns the actor's age. */ public int getAge() { return age; } /** * Αυτή η μέθοδος προσθέτει μια ταινία στην λίστα ταινιών του ηθοποιού. * This methods adds a movie to hir/her lists of movies. */ public void addMovie(String title, int duration, int oscars, int budget) { this.movies.add(new Movie(title, duration, oscars, budget)); } /** * Αυτή η μέθοδος επιστρέφει τις ταινίες στις οποίες έχει παίξει ο ηθοποιός. * This methods returns the movies the actor has participated. */ public ArrayList<Movie> getMovies() { return this.movies; } /** * Αυτή η μέθοδος υπολογίζει τον χρόνο σε λεπτά που ο/η ηθοποιός έχει παίξει σε ταινίες μεγάλου μήκους (>1 ώρα) * This method computes the total play time of the actor in long movies (>1 hour) */ public int totalActingTime() { int sum = 0; for (Movie movie : this.movies) { if (movie.getDuration() > 60) { sum += movie.getDuration(); } } return sum; } /** * Αυτή η μέθοδος υπολογίζει την "δημοφιλία" του/της ηθοποιού. Η δημοφιλία υπολογίζεται ως ο συνολικός αριθμός των * ταινιών που έχει παίξει προς τον αριθμό των οσκαρικών ταινιών που έχει παίξει. * This method computes the "popularity" of the actor. The popularity is the total number of movies he/she * participated to the total number of oscar-winning movies he/she participated. * double value = (double) value */ public double popularity() { int totalOscars = 0; for (Movie movie : this.movies) { if (movie.getOscars() > 0) { totalOscars += 1; } } return this.movies.size() / (double) totalOscars; } }
auth-csd-oop-2020/lab-groupingObjects-MovieActor-solved
src/Actor.java
1,106
/** * Αυτή η κλάση αναπαριστά έναν/μία ηθοποιό με το όνομα του/της, την ηλικία του/της και την λίστα με τις ταινίες * στις οποίες έχει παίξει. * This class represents an actor/actress with his/her name, age and list of movies he/she participated. */
block_comment
el
import java.util.ArrayList; /** * Αυτή η κλάση<SUF>*/ public class Actor { private String name; private int age; private ArrayList<Movie> movies; /** * Κατασκευαστής - Constructor */ public Actor(String name, int age) { this.name = name; this.age = age; this.movies = new ArrayList<>(); } /** * Αυτή η μέθοδος επιστρέφει το όνομα του ηθοποιού. * This method returns the actor's name. */ public String getName() { return name; } /** * Αυτή η μέθοδος επιστρέφει την ηλικία του ηθοποιού. * This method returns the actor's age. */ public int getAge() { return age; } /** * Αυτή η μέθοδος προσθέτει μια ταινία στην λίστα ταινιών του ηθοποιού. * This methods adds a movie to hir/her lists of movies. */ public void addMovie(String title, int duration, int oscars, int budget) { this.movies.add(new Movie(title, duration, oscars, budget)); } /** * Αυτή η μέθοδος επιστρέφει τις ταινίες στις οποίες έχει παίξει ο ηθοποιός. * This methods returns the movies the actor has participated. */ public ArrayList<Movie> getMovies() { return this.movies; } /** * Αυτή η μέθοδος υπολογίζει τον χρόνο σε λεπτά που ο/η ηθοποιός έχει παίξει σε ταινίες μεγάλου μήκους (>1 ώρα) * This method computes the total play time of the actor in long movies (>1 hour) */ public int totalActingTime() { int sum = 0; for (Movie movie : this.movies) { if (movie.getDuration() > 60) { sum += movie.getDuration(); } } return sum; } /** * Αυτή η μέθοδος υπολογίζει την "δημοφιλία" του/της ηθοποιού. Η δημοφιλία υπολογίζεται ως ο συνολικός αριθμός των * ταινιών που έχει παίξει προς τον αριθμό των οσκαρικών ταινιών που έχει παίξει. * This method computes the "popularity" of the actor. The popularity is the total number of movies he/she * participated to the total number of oscar-winning movies he/she participated. * double value = (double) value */ public double popularity() { int totalOscars = 0; for (Movie movie : this.movies) { if (movie.getOscars() > 0) { totalOscars += 1; } } return this.movies.size() / (double) totalOscars; } }
300_4
/** * Αυτή η κλάση αναπαριστά ένα σκούτερ με μηχανή εσωτερικής κάυσης. This class represents a scooter with an internal * combustion engine. */ public class Scooter { private int maxKM; private int year; /** * Κατασκευαστής / Constructor * * @param maxKM Ο μέγιστος αριθμός χιλιομέτρων που μπορεί να διανύσει με ένα γέμισμα. The maximum number of * kilometers you can travel with a full tank. * @param year Το έτος κυκλοφορίας του οχήματος, the release year of the vehicle. */ public Scooter(int maxKM, int year) { this.maxKM = maxKM; this.year = year; } /** * @return Το μέγιστο αριθμό χιλιομέτρων που μπορεί να διανύσει με ένα γέμισμα. The maximum number of * kilometers you can travel with a full tank. */ public int getMaxKM() { return this.maxKM; } /** * @return Το έτος κυκλοφορίας του οχήματος, the release year of the vehicle. */ public int getYear(){ return this.year; } /** * Κάθε όχημα χαρακτηρίζεται από μια βαθμολογία ανάλογα με τους ρύπου που παράγει. Το σκορ αυτό είναι ίσο με τον * αριθμό των μέγιστων χιλιομέτρων επί τον μέσο αριθμό γεμισμάτων ανα έτος (250), διά το σύνολο των ημερών ενός * έτους (365) * Each vehicle has a score that represents the pollutants that produces. This score equals the maximum kilometers * of the vehicle multiplied by the average number of fillings during a year (250), divided by the number of days * in a year (365) * @return Το σκορ μόλυνσης του περιβάλλοντος, the pollution score. */ public double getPollutionScore() { return this.maxKM * 250 / 365d; } /** * Μέθοδος που υπολογίζει τα τέλη κυκλοφορίας του οχήματος. Τα τέλη κυκλοφορίας ισούται με τον έτη που κυκλοφορεί το * όχημα μέχρι σήμερα (2018) επι 12.5 που είναι ένας σταθερός αριθμός. * This method computes the annual taxes of the vehicle. The annual taxes equal the number of years from the release * day till today (2018) multiplied by 12.5 which is a constant value. * @return Τα τέλη κυκλοφορίας, the annual tax of the vehicle */ public double getTaxes() { return (2018 - this.year) * 12.5; } }
auth-csd-oop-2020/lab-inheritance-Scooter-solved
src/Scooter.java
1,067
/** * Κάθε όχημα χαρακτηρίζεται από μια βαθμολογία ανάλογα με τους ρύπου που παράγει. Το σκορ αυτό είναι ίσο με τον * αριθμό των μέγιστων χιλιομέτρων επί τον μέσο αριθμό γεμισμάτων ανα έτος (250), διά το σύνολο των ημερών ενός * έτους (365) * Each vehicle has a score that represents the pollutants that produces. This score equals the maximum kilometers * of the vehicle multiplied by the average number of fillings during a year (250), divided by the number of days * in a year (365) * @return Το σκορ μόλυνσης του περιβάλλοντος, the pollution score. */
block_comment
el
/** * Αυτή η κλάση αναπαριστά ένα σκούτερ με μηχανή εσωτερικής κάυσης. This class represents a scooter with an internal * combustion engine. */ public class Scooter { private int maxKM; private int year; /** * Κατασκευαστής / Constructor * * @param maxKM Ο μέγιστος αριθμός χιλιομέτρων που μπορεί να διανύσει με ένα γέμισμα. The maximum number of * kilometers you can travel with a full tank. * @param year Το έτος κυκλοφορίας του οχήματος, the release year of the vehicle. */ public Scooter(int maxKM, int year) { this.maxKM = maxKM; this.year = year; } /** * @return Το μέγιστο αριθμό χιλιομέτρων που μπορεί να διανύσει με ένα γέμισμα. The maximum number of * kilometers you can travel with a full tank. */ public int getMaxKM() { return this.maxKM; } /** * @return Το έτος κυκλοφορίας του οχήματος, the release year of the vehicle. */ public int getYear(){ return this.year; } /** * Κάθε όχημα χαρακτηρίζεται<SUF>*/ public double getPollutionScore() { return this.maxKM * 250 / 365d; } /** * Μέθοδος που υπολογίζει τα τέλη κυκλοφορίας του οχήματος. Τα τέλη κυκλοφορίας ισούται με τον έτη που κυκλοφορεί το * όχημα μέχρι σήμερα (2018) επι 12.5 που είναι ένας σταθερός αριθμός. * This method computes the annual taxes of the vehicle. The annual taxes equal the number of years from the release * day till today (2018) multiplied by 12.5 which is a constant value. * @return Τα τέλη κυκλοφορίας, the annual tax of the vehicle */ public double getTaxes() { return (2018 - this.year) * 12.5; } }