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
193_14
package com.unipi.vnikolis.unipismartalert; import android.annotation.SuppressLint; import android.app.DatePickerDialog; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.DatePicker; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; 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.unipi.vnikolis.unipismartalert.internettracker.CheckInternetConnection; import com.unipi.vnikolis.unipismartalert.model.Values; import com.unipi.vnikolis.unipismartalert.adapter.ItemsAdapter; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; /** * The backend code for Statistics Activity */ public class ShowStatistics extends AppCompatActivity implements AdapterView.OnItemClickListener { FirebaseDatabase firebaseDatabase; DatabaseReference possiblyDanger, bigDanger, lightDanger, speedDanger, dropDanger; Spinner mDangerSpinner, mSortDateSpinner; String dangerSelect, dateSelect, twoDigitMonth, twoDigitDay, dateToCompare, dateToView; TextView dateView; DatePickerDialog.OnDateSetListener mDateSetListener; ArrayList<Values> dangerList = new ArrayList<>(); boolean dateIsSelected, sortDatesIsSelected, dangerIsSelected; static boolean isItemsButtonClicked; ArrayAdapter<String> myAdapter2, myAdapter; ItemsAdapter adapter; ListView mUserList; Values v; int firstTime; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_statistics); firebaseDatabase = FirebaseDatabase.getInstance(); possiblyDanger = firebaseDatabase.getReference("PossiblyDanger"); bigDanger = firebaseDatabase.getReference("BigDanger"); lightDanger = possiblyDanger.child("LightDanger"); speedDanger = possiblyDanger.child("SpeedDanger"); dropDanger = possiblyDanger.child("DropDanger"); mUserList = findViewById(R.id.listView); try { if (CheckInternetConnection.isConnected(ShowStatistics.this) && CheckInternetConnection.isConnectedFast(ShowStatistics.this)) { //ελεγχος εαν υπάρχει σύνδεση Internet calendarPicker(); dangerPicker(); datePicker(); dangerSelect(); }else{ Toast.makeText(ShowStatistics.this, "Δεν υπάρχει σύνδεση στο Internet, προσπάθησε ξανά", Toast.LENGTH_LONG).show(); } }catch (Exception e){ e.printStackTrace(); Log.e("SOS", "Something went wrong"); } } /** * Κατασκεύη ημερολογίου και * Επιλογή ημερομηνίας */ public void calendarPicker(){ try { //create the calendar date picker dateView = findViewById(R.id.dateView); dateView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dateIsSelected = true; Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); DatePickerDialog dialog = new DatePickerDialog(ShowStatistics.this, mDateSetListener, year, month, day); dialog.show(); } }); mDateSetListener = new DatePickerDialog.OnDateSetListener() { @SuppressLint("SetTextI18n") @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { firstTime++; if (firstTime > 1) { //για να μην κρασαρει την πρωτη φορα που ανοιγει η εφαρμογη επιλεγοντας πρωτα την ημερομηνια mDangerSpinner.setAdapter(myAdapter); adapter.clear(); } if (firstTime == 1 && dangerIsSelected) { //για να μην κρασαρει την πρωτη φορα που ανοιγει η εφαρμογη επιλεγοντας πρωτα την ημερομηνια mDangerSpinner.setAdapter(myAdapter); adapter.clear(); } month++; // οι μήνες ξεκινάνε από το 0 οπότε προσθέτουμε 1 // Τωρα θα τα μετατρέψω σε 2 digit format γιατί έτσι είναι αποθηκευμένα στη βάση // ώστε να κάνω σύγκριση if (month < 10) { twoDigitMonth = "0" + month; } else { twoDigitMonth = String.valueOf(month); } if (dayOfMonth < 10) { twoDigitDay = "0" + dayOfMonth; } else { twoDigitDay = String.valueOf(dayOfMonth); } dateToCompare = year + "/" + twoDigitMonth + "/" + twoDigitDay; dateToView = twoDigitDay + "/" + twoDigitMonth + "/" + year; dateView.setText(dateToView); } }; }catch (Exception e){ Toast.makeText(ShowStatistics.this, "Κάτι πήγε στραβά, προσπάθησε ξανά", Toast.LENGTH_LONG).show(); } } /** * Επιλογή κινδύνου από το dropDown Menu */ public void dangerPicker(){ try { //τραβάει τα δεδομένα από το dropdown menu ανα κατηγορια συμβαντος mDangerSpinner = findViewById(R.id.spinner); myAdapter = new ArrayAdapter<String>(ShowStatistics.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.spinnerItems)) { @Override public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { tv.setVisibility(View.GONE); } else { //τοποθετηση χρώματος tv.setVisibility(View.VISIBLE); if (position % 2 == 1) { tv.setBackgroundColor(Color.parseColor("#FFF9A600")); } else { tv.setBackgroundColor(Color.parseColor("#FFE49200")); } } return view; } }; myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mDangerSpinner.setPrompt("Choose Danger Category"); mDangerSpinner.setAdapter(myAdapter); }catch (Exception e){ Toast.makeText(ShowStatistics.this, "Κάτι πήγε στραβά, προσπάθησε ξανά", Toast.LENGTH_LONG).show(); } } /** * Επιλογή ταξινόμισης από το dropDown Menu */ public void datePicker(){ mSortDateSpinner = findViewById(R.id.spinner2); myAdapter2 = new ArrayAdapter<String>(ShowStatistics.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.spinnerItems2)){ @SuppressLint("SetTextI18n") @Override public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent){ sortDatesIsSelected = true; View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if(position == 0) { tv.setVisibility(View.GONE); } else{ //τοποθετηση χρώματος tv.setVisibility(View.VISIBLE); if(position%2==1) { tv.setBackgroundColor(Color.parseColor("#FFF9A600")); } else{ tv.setBackgroundColor(Color.parseColor("#FFE49200")); } } return view; } }; myAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mSortDateSpinner.setPrompt("Choose to Sort by Date"); mSortDateSpinner.setAdapter(myAdapter2); } /** * Ανάλογα με την επιλογή κινδύνου που θα γίνει * θα τραβήξει και τα αντίστοιχα αποτελέσματα */ public void dangerSelect() { try { mDangerSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { dangerSelect = mDangerSpinner.getSelectedItem().toString(); switch (dangerSelect) { case "Drop Danger": dangerIsSelected = true; //επιλογή κινδύνου dangerSelector(dropDanger); //επιλογή ταξινόμισης sortDateSelector(dropDanger, mSortDateSpinner); break; case "Speed Danger": dangerIsSelected = true; dangerSelector(speedDanger); sortDateSelector(speedDanger, mSortDateSpinner); break; case "Light Danger": dangerIsSelected = true; dangerSelector(lightDanger); sortDateSelector(lightDanger, mSortDateSpinner); break; case "Possibly Danger": dangerIsSelected = true; dangerSelector(possiblyDanger); sortDateSelector(possiblyDanger, mSortDateSpinner); break; case "Big Danger": dangerIsSelected = true; dangerSelector(bigDanger); sortDateSelector(bigDanger, mSortDateSpinner); break; } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); }catch (Exception e){ e.printStackTrace(); Log.e("SOS", "Something went wrong"); } } /** * Συλλογή δεδομένων από την FireBase * ταξινόμηση εαν χρειάζεται και τοποθέτηση * των δεομένων στο ListView για την εμφάνιση των αποτελεσμάτων * @param keys Μεταβλητή Iterable τύπου DataSnapshot για την καταλληλότερη * αναζήτηση αποτελεσμάτων */ @SuppressLint("SetTextI18n") private void collectDangers(Iterable<DataSnapshot> keys) { try { dangerList.clear(); adapter = new ItemsAdapter(this, dangerList); mUserList.setAdapter(adapter); mUserList.setOnItemClickListener(this); String compareDate; if (dangerSelect.equals("Possibly Danger")) { for (DataSnapshot i : keys) { for (DataSnapshot j : i.getChildren()) { v = j.getValue(Values.class); //εαν υπάρχει διαθέσιμη ημερομηνία από το ημερολόγιο για σύγκριση... κάνε την σύγκριση if (dateToCompare != null) { assert v != null; compareDate = v.getDate().substring(0, 10); //πάρε μονο ένα κομάτι από την συμβολοσειρά της ημερομηνίας που είναι αποθηκευμένη στη βάση if (compareDate.equals(dateToCompare)) { //και συγκρινέ αυτήν με την ημερομηνία που έχει επιλεγεί από το ημερολόγιο adapter.add(v); //γέμισε την λίστα } } else { adapter.add(v); //εδω γεμίζει η list } } } } else if (dangerSelect.equals("Big Danger") || dangerSelect.equals("Light Danger") || dangerSelect.equals("Speed Danger") || dangerSelect.equals("Drop Danger")) { for (DataSnapshot i : keys) { v = i.getValue(Values.class); if (dateToCompare != null) { assert v != null; compareDate = v.getDate().substring(0, 10); if (compareDate.equals(dateToCompare)) { adapter.add(v); } } else { adapter.add(v); //εδω γεμίζει η list } } } //εαν εχει επιλεγει η ταξινομιση κάνε την κατα άυξουσα η φθίνουσα σειρά if (dateSelect != null) { if (dateSelect.equals("Ascending")) { //ταξινόμιση βαση ημερομηνιας κατα αυξουσα Collections.sort(dangerList, new Comparator<Values>() { @Override public int compare(Values o1, Values o2) { return o1.getDate().compareTo(o2.getDate()); } }); } else if (dateSelect.equals("Descending")) { //ταξινόμηση βαση ημερομηνιας κατα φθινουσα Collections.sort(dangerList, Collections.reverseOrder(new Comparator<Values>() { @Override public int compare(Values o1, Values o2) { return o1.getDate().compareTo(o2.getDate()); } })); } } dateView.setText("Pick Date"); dateToCompare = null; mSortDateSpinner.setAdapter(myAdapter2); }catch (Exception e){ e.printStackTrace(); Log.e("SOS", "Something went wrong"); } } /** * Σε κάθε αλλάγη της FireBase καλεί την μέδοδο collectDangers * @param kindOfDanger To Reference της FireBase */ private void dangerSelector(DatabaseReference kindOfDanger){ kindOfDanger.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) //εαν υπάρχει κάτι σε αυτον τον πίνακα { collectDangers(dataSnapshot.getChildren()); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Toast.makeText(ShowStatistics.this, "Αποτυχία Ανάγνωσης από τη Βάση", Toast.LENGTH_LONG).show(); } }); } /** * Επιλογή ταξινόμησης κατα άυξουσα η φθίνουσα σειρά * @param kindOfDanger To Reference της FireBase * @param selectorToSort Ο Spinner που θέλουμε */ // private void sortDateSelector(final DatabaseReference kindOfDanger, Spinner selectorToSort){ selectorToSort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { dateSelect = mSortDateSpinner.getSelectedItem().toString(); switch (dateSelect){ case "Ascending": //ταξινόμιση κατα άυξουσα dangerSelector(kindOfDanger); break; //ταξινόμιση κατα φθίνουσα case "Descending": dangerSelector(kindOfDanger); break; } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } /** * Μετάβαση στους χάρτες για έυρεση της συγκεκριμένης * τοποθεσίας από το ListView * @param parent .. * @param view .. * @param position .. * @param id .. */ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { isItemsButtonClicked = true; MainActivity.isMapsButtonPressed = false; Values o =(Values) mUserList.getItemAtPosition(position); Intent maps = new Intent(ShowStatistics.this, MapsActivity.class); maps.putExtra("latitude", o.getLatitude()); maps.putExtra("longitude", o.getLongitude()); maps.putExtra("date", o.CorrectDate()); startActivity(maps); } }
3ngk1sha/DangerDetect
app/src/main/java/com/unipi/vnikolis/unipismartalert/ShowStatistics.java
4,658
//εαν υπάρχει διαθέσιμη ημερομηνία από το ημερολόγιο για σύγκριση... κάνε την σύγκριση
line_comment
el
package com.unipi.vnikolis.unipismartalert; import android.annotation.SuppressLint; import android.app.DatePickerDialog; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.DatePicker; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; 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.unipi.vnikolis.unipismartalert.internettracker.CheckInternetConnection; import com.unipi.vnikolis.unipismartalert.model.Values; import com.unipi.vnikolis.unipismartalert.adapter.ItemsAdapter; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; /** * The backend code for Statistics Activity */ public class ShowStatistics extends AppCompatActivity implements AdapterView.OnItemClickListener { FirebaseDatabase firebaseDatabase; DatabaseReference possiblyDanger, bigDanger, lightDanger, speedDanger, dropDanger; Spinner mDangerSpinner, mSortDateSpinner; String dangerSelect, dateSelect, twoDigitMonth, twoDigitDay, dateToCompare, dateToView; TextView dateView; DatePickerDialog.OnDateSetListener mDateSetListener; ArrayList<Values> dangerList = new ArrayList<>(); boolean dateIsSelected, sortDatesIsSelected, dangerIsSelected; static boolean isItemsButtonClicked; ArrayAdapter<String> myAdapter2, myAdapter; ItemsAdapter adapter; ListView mUserList; Values v; int firstTime; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_statistics); firebaseDatabase = FirebaseDatabase.getInstance(); possiblyDanger = firebaseDatabase.getReference("PossiblyDanger"); bigDanger = firebaseDatabase.getReference("BigDanger"); lightDanger = possiblyDanger.child("LightDanger"); speedDanger = possiblyDanger.child("SpeedDanger"); dropDanger = possiblyDanger.child("DropDanger"); mUserList = findViewById(R.id.listView); try { if (CheckInternetConnection.isConnected(ShowStatistics.this) && CheckInternetConnection.isConnectedFast(ShowStatistics.this)) { //ελεγχος εαν υπάρχει σύνδεση Internet calendarPicker(); dangerPicker(); datePicker(); dangerSelect(); }else{ Toast.makeText(ShowStatistics.this, "Δεν υπάρχει σύνδεση στο Internet, προσπάθησε ξανά", Toast.LENGTH_LONG).show(); } }catch (Exception e){ e.printStackTrace(); Log.e("SOS", "Something went wrong"); } } /** * Κατασκεύη ημερολογίου και * Επιλογή ημερομηνίας */ public void calendarPicker(){ try { //create the calendar date picker dateView = findViewById(R.id.dateView); dateView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dateIsSelected = true; Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); DatePickerDialog dialog = new DatePickerDialog(ShowStatistics.this, mDateSetListener, year, month, day); dialog.show(); } }); mDateSetListener = new DatePickerDialog.OnDateSetListener() { @SuppressLint("SetTextI18n") @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { firstTime++; if (firstTime > 1) { //για να μην κρασαρει την πρωτη φορα που ανοιγει η εφαρμογη επιλεγοντας πρωτα την ημερομηνια mDangerSpinner.setAdapter(myAdapter); adapter.clear(); } if (firstTime == 1 && dangerIsSelected) { //για να μην κρασαρει την πρωτη φορα που ανοιγει η εφαρμογη επιλεγοντας πρωτα την ημερομηνια mDangerSpinner.setAdapter(myAdapter); adapter.clear(); } month++; // οι μήνες ξεκινάνε από το 0 οπότε προσθέτουμε 1 // Τωρα θα τα μετατρέψω σε 2 digit format γιατί έτσι είναι αποθηκευμένα στη βάση // ώστε να κάνω σύγκριση if (month < 10) { twoDigitMonth = "0" + month; } else { twoDigitMonth = String.valueOf(month); } if (dayOfMonth < 10) { twoDigitDay = "0" + dayOfMonth; } else { twoDigitDay = String.valueOf(dayOfMonth); } dateToCompare = year + "/" + twoDigitMonth + "/" + twoDigitDay; dateToView = twoDigitDay + "/" + twoDigitMonth + "/" + year; dateView.setText(dateToView); } }; }catch (Exception e){ Toast.makeText(ShowStatistics.this, "Κάτι πήγε στραβά, προσπάθησε ξανά", Toast.LENGTH_LONG).show(); } } /** * Επιλογή κινδύνου από το dropDown Menu */ public void dangerPicker(){ try { //τραβάει τα δεδομένα από το dropdown menu ανα κατηγορια συμβαντος mDangerSpinner = findViewById(R.id.spinner); myAdapter = new ArrayAdapter<String>(ShowStatistics.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.spinnerItems)) { @Override public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { tv.setVisibility(View.GONE); } else { //τοποθετηση χρώματος tv.setVisibility(View.VISIBLE); if (position % 2 == 1) { tv.setBackgroundColor(Color.parseColor("#FFF9A600")); } else { tv.setBackgroundColor(Color.parseColor("#FFE49200")); } } return view; } }; myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mDangerSpinner.setPrompt("Choose Danger Category"); mDangerSpinner.setAdapter(myAdapter); }catch (Exception e){ Toast.makeText(ShowStatistics.this, "Κάτι πήγε στραβά, προσπάθησε ξανά", Toast.LENGTH_LONG).show(); } } /** * Επιλογή ταξινόμισης από το dropDown Menu */ public void datePicker(){ mSortDateSpinner = findViewById(R.id.spinner2); myAdapter2 = new ArrayAdapter<String>(ShowStatistics.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.spinnerItems2)){ @SuppressLint("SetTextI18n") @Override public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent){ sortDatesIsSelected = true; View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if(position == 0) { tv.setVisibility(View.GONE); } else{ //τοποθετηση χρώματος tv.setVisibility(View.VISIBLE); if(position%2==1) { tv.setBackgroundColor(Color.parseColor("#FFF9A600")); } else{ tv.setBackgroundColor(Color.parseColor("#FFE49200")); } } return view; } }; myAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mSortDateSpinner.setPrompt("Choose to Sort by Date"); mSortDateSpinner.setAdapter(myAdapter2); } /** * Ανάλογα με την επιλογή κινδύνου που θα γίνει * θα τραβήξει και τα αντίστοιχα αποτελέσματα */ public void dangerSelect() { try { mDangerSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { dangerSelect = mDangerSpinner.getSelectedItem().toString(); switch (dangerSelect) { case "Drop Danger": dangerIsSelected = true; //επιλογή κινδύνου dangerSelector(dropDanger); //επιλογή ταξινόμισης sortDateSelector(dropDanger, mSortDateSpinner); break; case "Speed Danger": dangerIsSelected = true; dangerSelector(speedDanger); sortDateSelector(speedDanger, mSortDateSpinner); break; case "Light Danger": dangerIsSelected = true; dangerSelector(lightDanger); sortDateSelector(lightDanger, mSortDateSpinner); break; case "Possibly Danger": dangerIsSelected = true; dangerSelector(possiblyDanger); sortDateSelector(possiblyDanger, mSortDateSpinner); break; case "Big Danger": dangerIsSelected = true; dangerSelector(bigDanger); sortDateSelector(bigDanger, mSortDateSpinner); break; } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); }catch (Exception e){ e.printStackTrace(); Log.e("SOS", "Something went wrong"); } } /** * Συλλογή δεδομένων από την FireBase * ταξινόμηση εαν χρειάζεται και τοποθέτηση * των δεομένων στο ListView για την εμφάνιση των αποτελεσμάτων * @param keys Μεταβλητή Iterable τύπου DataSnapshot για την καταλληλότερη * αναζήτηση αποτελεσμάτων */ @SuppressLint("SetTextI18n") private void collectDangers(Iterable<DataSnapshot> keys) { try { dangerList.clear(); adapter = new ItemsAdapter(this, dangerList); mUserList.setAdapter(adapter); mUserList.setOnItemClickListener(this); String compareDate; if (dangerSelect.equals("Possibly Danger")) { for (DataSnapshot i : keys) { for (DataSnapshot j : i.getChildren()) { v = j.getValue(Values.class); //εαν υπάρχει<SUF> if (dateToCompare != null) { assert v != null; compareDate = v.getDate().substring(0, 10); //πάρε μονο ένα κομάτι από την συμβολοσειρά της ημερομηνίας που είναι αποθηκευμένη στη βάση if (compareDate.equals(dateToCompare)) { //και συγκρινέ αυτήν με την ημερομηνία που έχει επιλεγεί από το ημερολόγιο adapter.add(v); //γέμισε την λίστα } } else { adapter.add(v); //εδω γεμίζει η list } } } } else if (dangerSelect.equals("Big Danger") || dangerSelect.equals("Light Danger") || dangerSelect.equals("Speed Danger") || dangerSelect.equals("Drop Danger")) { for (DataSnapshot i : keys) { v = i.getValue(Values.class); if (dateToCompare != null) { assert v != null; compareDate = v.getDate().substring(0, 10); if (compareDate.equals(dateToCompare)) { adapter.add(v); } } else { adapter.add(v); //εδω γεμίζει η list } } } //εαν εχει επιλεγει η ταξινομιση κάνε την κατα άυξουσα η φθίνουσα σειρά if (dateSelect != null) { if (dateSelect.equals("Ascending")) { //ταξινόμιση βαση ημερομηνιας κατα αυξουσα Collections.sort(dangerList, new Comparator<Values>() { @Override public int compare(Values o1, Values o2) { return o1.getDate().compareTo(o2.getDate()); } }); } else if (dateSelect.equals("Descending")) { //ταξινόμηση βαση ημερομηνιας κατα φθινουσα Collections.sort(dangerList, Collections.reverseOrder(new Comparator<Values>() { @Override public int compare(Values o1, Values o2) { return o1.getDate().compareTo(o2.getDate()); } })); } } dateView.setText("Pick Date"); dateToCompare = null; mSortDateSpinner.setAdapter(myAdapter2); }catch (Exception e){ e.printStackTrace(); Log.e("SOS", "Something went wrong"); } } /** * Σε κάθε αλλάγη της FireBase καλεί την μέδοδο collectDangers * @param kindOfDanger To Reference της FireBase */ private void dangerSelector(DatabaseReference kindOfDanger){ kindOfDanger.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) //εαν υπάρχει κάτι σε αυτον τον πίνακα { collectDangers(dataSnapshot.getChildren()); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Toast.makeText(ShowStatistics.this, "Αποτυχία Ανάγνωσης από τη Βάση", Toast.LENGTH_LONG).show(); } }); } /** * Επιλογή ταξινόμησης κατα άυξουσα η φθίνουσα σειρά * @param kindOfDanger To Reference της FireBase * @param selectorToSort Ο Spinner που θέλουμε */ // private void sortDateSelector(final DatabaseReference kindOfDanger, Spinner selectorToSort){ selectorToSort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { dateSelect = mSortDateSpinner.getSelectedItem().toString(); switch (dateSelect){ case "Ascending": //ταξινόμιση κατα άυξουσα dangerSelector(kindOfDanger); break; //ταξινόμιση κατα φθίνουσα case "Descending": dangerSelector(kindOfDanger); break; } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } /** * Μετάβαση στους χάρτες για έυρεση της συγκεκριμένης * τοποθεσίας από το ListView * @param parent .. * @param view .. * @param position .. * @param id .. */ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { isItemsButtonClicked = true; MainActivity.isMapsButtonPressed = false; Values o =(Values) mUserList.getItemAtPosition(position); Intent maps = new Intent(ShowStatistics.this, MapsActivity.class); maps.putExtra("latitude", o.getLatitude()); maps.putExtra("longitude", o.getLongitude()); maps.putExtra("date", o.CorrectDate()); startActivity(maps); } }
6196_34
package info.android_angel.navigationdrawer.activity_tv; /** * Created by ANGELOS on 2017. * */ import android.content.Intent; import android.os.Bundle; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.ads.AdView; import java.util.List; import info.android_angel.navigationdrawer.R; import info.android_angel.navigationdrawer.activity_movies.SearchActivity; import info.android_angel.navigationdrawer.activity_movies.Show_Movie_Details_ID; import info.android_angel.navigationdrawer.adapter.TVAdapter; import info.android_angel.navigationdrawer.model.TV; import info.android_angel.navigationdrawer.model.TVResponse; import info.android_angel.navigationdrawer.package_recycler_touch_listener.RecyclerTouchListener; import info.android_angel.navigationdrawer.rest.ApiClient; import info.android_angel.navigationdrawer.rest.ApiInterface; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class Top_Rated_TV extends AppCompatActivity { private final static String page_2 = "2"; private final static String page_3 = "3"; /** 2017 ads**/ private AdView mAdView; private static final String TAG = Top_Rated_TV.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.nav_tv_get_airing_today); getSupportActionBar().setDisplayHomeAsUpEnabled(true); if (getResources().getString(R.string.API_KEY).isEmpty()) { Toast.makeText(getApplicationContext(), "Please obtain your API KEY from themoviedb.org first!", Toast.LENGTH_LONG).show(); return; } final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.tvs_recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class); /** 2017 AdView mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder() .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) // Check the LogCat to get your test device ID .addTestDevice("C04B1BFFB0774708339BC273F8A43708") .build(); mAdView.setAdListener(new AdListener() { @Override public void onAdLoaded() { } @Override public void onAdClosed() { Toast.makeText(getApplicationContext(), "Ad is closed!", Toast.LENGTH_SHORT).show(); } @Override public void onAdFailedToLoad(int errorCode) { Toast.makeText(getApplicationContext(), "Ad failed to load! error code: " + errorCode, Toast.LENGTH_SHORT).show(); } @Override public void onAdLeftApplication() { Toast.makeText(getApplicationContext(), "Ad left application!", Toast.LENGTH_SHORT).show(); } @Override public void onAdOpened() { super.onAdOpened(); } }); mAdView.loadAd(adRequest);**/ /**END 2017 AdView **/ /** Προσοχή εδώ η αλλάγή............. **/ Call<TVResponse> call = apiService.getTopRatedTv(getResources().getString(R.string.API_KEY)); call.enqueue(new Callback<TVResponse>() { @Override public void onResponse(Call<TVResponse> call, Response<TVResponse> response) { if (!response.isSuccessful()) { System.out.println("Error"); } if(response.isSuccessful()) { List<TV> tvs = response.body().getResults(); recyclerView.setAdapter(new TVAdapter(tvs, R.layout.nav_tv_get_airing_today_list_item, getApplicationContext())); }else{ int statusCode = response.code(); switch(statusCode){ case 401: Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show(); case 404: Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show(); } } /** recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() { @Override public void onClick(View view, int position) { // on selecting a single album // TrackListActivity will be launched to show tracks inside the album Intent i = new Intent(getApplicationContext(), Show_TV_Details_ID.class); String tv_id = ((TextView) view.findViewById(R.id.tv_id)).getText().toString(); i.putExtra("tv_id", tv_id); //i.putExtra(KEY_MOVIE_ID, movies_response.get(position).getId()); //Toast.makeText(getApplicationContext(),tv_id, Toast.LENGTH_SHORT).show(); startActivity(i); } @Override public void onLongClick(View view, int position) { } })); **/ } @Override public void onFailure(Call<TVResponse> call, Throwable t) { // Log error here since request failed Log.e(TAG, t.toString()); } }); /** PAGE = 2 **/ final RecyclerView recyclerView_2 = (RecyclerView) findViewById(R.id.tvs_recycler_view_page_2); recyclerView_2.setLayoutManager(new LinearLayoutManager(this)); Call<TVResponse> call_2 = apiService.getTopRatedTv_2(getResources().getString(R.string.API_KEY), page_2); call_2.enqueue(new Callback<TVResponse>() { @Override public void onResponse(Call<TVResponse> call_2, final Response<TVResponse> response) { if (!response.isSuccessful()) { //System.out.println("Error"); } if(response.isSuccessful()) { final List<TV> tvs = response.body().getResults(); recyclerView_2.setAdapter(new TVAdapter(tvs, R.layout.nav_tv_get_airing_today_list_item, getApplicationContext())); }else{ int statusCode = response.code(); switch(statusCode){ case 401: //Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show(); case 404: //Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show(); } } recyclerView_2.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView_2, new RecyclerTouchListener.ClickListener() { @Override public void onClick(View view, int position) { // on selecting a single album // TrackListActivity will be launched to show tracks inside the album Intent i = new Intent(getApplicationContext(), Show_Movie_Details_ID.class); String movie_id = ((TextView) view.findViewById(R.id.movie_id)).getText().toString(); i.putExtra("movie_id", movie_id); //i.putExtra(KEY_MOVIE_ID, movies_response.get(position).getId()); //Toast.makeText(getApplicationContext(),movie_id, Toast.LENGTH_SHORT).show(); startActivity(i); } @Override public void onLongClick(View view, int position) { // on selecting a single album // TrackListActivity will be launched to show tracks inside the album //Intent i = new Intent(getApplicationContext(), Show_Movie_Details_ID.class); // send album id to tracklist activity to get list of songs under that album //String movie_id = ((TextView) view.findViewById(R.id.movie_id)).getText().toString(); //i.putExtra("movie_id", movie_id); //startActivity(i); } })); } @Override public void onFailure(Call<TVResponse> call_2, Throwable t) { // Log error here since request failed //Log.e(TAG, t.toString()); } }); /** PAGE = 3 **/ final RecyclerView recyclerView_3 = (RecyclerView) findViewById(R.id.tvs_recycler_view_page_3); recyclerView_3.setLayoutManager(new LinearLayoutManager(this)); Call<TVResponse> call_3 = apiService.getTopRatedTv_2(getResources().getString(R.string.API_KEY), page_3); call_3.enqueue(new Callback<TVResponse>() { @Override public void onResponse(Call<TVResponse> call_3, final Response<TVResponse> response) { if (!response.isSuccessful()) { //System.out.println("Error"); } if(response.isSuccessful()) { final List<TV> tvs = response.body().getResults(); recyclerView_3.setAdapter(new TVAdapter(tvs, R.layout.nav_tv_get_airing_today_list_item, getApplicationContext())); }else{ int statusCode = response.code(); switch(statusCode){ case 401: //Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show(); case 404: //Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show(); } } recyclerView_3.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView_3, new RecyclerTouchListener.ClickListener() { @Override public void onClick(View view, int position) { // on selecting a single album // TrackListActivity will be launched to show tracks inside the album Intent i = new Intent(getApplicationContext(), Show_Movie_Details_ID.class); String movie_id = ((TextView) view.findViewById(R.id.movie_id)).getText().toString(); i.putExtra("movie_id", movie_id); //i.putExtra(KEY_MOVIE_ID, movies_response.get(position).getId()); //Toast.makeText(getApplicationContext(),movie_id, Toast.LENGTH_SHORT).show(); startActivity(i); } @Override public void onLongClick(View view, int position) { // on selecting a single album // TrackListActivity will be launched to show tracks inside the album //Intent i = new Intent(getApplicationContext(), Show_Movie_Details_ID.class); // send album id to tracklist activity to get list of songs under that album //String movie_id = ((TextView) view.findViewById(R.id.movie_id)).getText().toString(); //i.putExtra("movie_id", movie_id); //startActivity(i); } })); } @Override public void onFailure(Call<TVResponse> call_3, Throwable t) { // Log error here since request failed //Log.e(TAG, t.toString()); } }); } /** SEARCH **/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); MenuItem search = menu.findItem(R.id.search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(search); search(searchView); return true; } /** SEARCH **/ private void search(SearchView searchView) { searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { //Toast.makeText(Popular_Movie.this, "Search is Selected", Toast.LENGTH_SHORT).show(); Intent i = new Intent(Top_Rated_TV.this,SearchActivity.class); String api_key_search = query.toString(); i.putExtra("api_key_search", api_key_search); /**switch_key_activity for SearchActivity **/ String switch_key_activity = "Top_Rated_TV"; i.putExtra("switch_key_activity", switch_key_activity); //Toast.makeText(MainActivity.this, api_key_search, Toast.LENGTH_SHORT).show(); //String api_key_search = ((TextView) menu.findItem(R.id.search)).getText().toString(); //i.putExtra("api_key_search", api_key_search); startActivity(i); return true; } @Override public boolean onQueryTextChange(final String newText) { return false; } }); } /** Για το βέλος που μας πηγαίνει στο αρχικό μενού **/ @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(); //noinspection SimplifiableIfStatement if (id == android.R.id.home) { // finish the activity onBackPressed(); return true; } return super.onOptionsItemSelected(item); } /** 2017 ads @Override public void onPause() { if (mAdView != null) { mAdView.pause(); } super.onPause(); } @Override public void onResume() { super.onResume(); if (mAdView != null) { mAdView.resume(); } } @Override public void onDestroy() { if (mAdView != null) { mAdView.destroy(); } super.onDestroy(); } **/ }
ANGELOS-TSILAFAKIS/NavigationDrawerPublic
app/src/main/java/info/android_angel/navigationdrawer/activity_tv/Top_Rated_TV.java
3,356
/** Για το βέλος που μας πηγαίνει στο αρχικό μενού **/
block_comment
el
package info.android_angel.navigationdrawer.activity_tv; /** * Created by ANGELOS on 2017. * */ import android.content.Intent; import android.os.Bundle; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.ads.AdView; import java.util.List; import info.android_angel.navigationdrawer.R; import info.android_angel.navigationdrawer.activity_movies.SearchActivity; import info.android_angel.navigationdrawer.activity_movies.Show_Movie_Details_ID; import info.android_angel.navigationdrawer.adapter.TVAdapter; import info.android_angel.navigationdrawer.model.TV; import info.android_angel.navigationdrawer.model.TVResponse; import info.android_angel.navigationdrawer.package_recycler_touch_listener.RecyclerTouchListener; import info.android_angel.navigationdrawer.rest.ApiClient; import info.android_angel.navigationdrawer.rest.ApiInterface; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class Top_Rated_TV extends AppCompatActivity { private final static String page_2 = "2"; private final static String page_3 = "3"; /** 2017 ads**/ private AdView mAdView; private static final String TAG = Top_Rated_TV.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.nav_tv_get_airing_today); getSupportActionBar().setDisplayHomeAsUpEnabled(true); if (getResources().getString(R.string.API_KEY).isEmpty()) { Toast.makeText(getApplicationContext(), "Please obtain your API KEY from themoviedb.org first!", Toast.LENGTH_LONG).show(); return; } final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.tvs_recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class); /** 2017 AdView mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder() .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) // Check the LogCat to get your test device ID .addTestDevice("C04B1BFFB0774708339BC273F8A43708") .build(); mAdView.setAdListener(new AdListener() { @Override public void onAdLoaded() { } @Override public void onAdClosed() { Toast.makeText(getApplicationContext(), "Ad is closed!", Toast.LENGTH_SHORT).show(); } @Override public void onAdFailedToLoad(int errorCode) { Toast.makeText(getApplicationContext(), "Ad failed to load! error code: " + errorCode, Toast.LENGTH_SHORT).show(); } @Override public void onAdLeftApplication() { Toast.makeText(getApplicationContext(), "Ad left application!", Toast.LENGTH_SHORT).show(); } @Override public void onAdOpened() { super.onAdOpened(); } }); mAdView.loadAd(adRequest);**/ /**END 2017 AdView **/ /** Προσοχή εδώ η αλλάγή............. **/ Call<TVResponse> call = apiService.getTopRatedTv(getResources().getString(R.string.API_KEY)); call.enqueue(new Callback<TVResponse>() { @Override public void onResponse(Call<TVResponse> call, Response<TVResponse> response) { if (!response.isSuccessful()) { System.out.println("Error"); } if(response.isSuccessful()) { List<TV> tvs = response.body().getResults(); recyclerView.setAdapter(new TVAdapter(tvs, R.layout.nav_tv_get_airing_today_list_item, getApplicationContext())); }else{ int statusCode = response.code(); switch(statusCode){ case 401: Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show(); case 404: Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show(); } } /** recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() { @Override public void onClick(View view, int position) { // on selecting a single album // TrackListActivity will be launched to show tracks inside the album Intent i = new Intent(getApplicationContext(), Show_TV_Details_ID.class); String tv_id = ((TextView) view.findViewById(R.id.tv_id)).getText().toString(); i.putExtra("tv_id", tv_id); //i.putExtra(KEY_MOVIE_ID, movies_response.get(position).getId()); //Toast.makeText(getApplicationContext(),tv_id, Toast.LENGTH_SHORT).show(); startActivity(i); } @Override public void onLongClick(View view, int position) { } })); **/ } @Override public void onFailure(Call<TVResponse> call, Throwable t) { // Log error here since request failed Log.e(TAG, t.toString()); } }); /** PAGE = 2 **/ final RecyclerView recyclerView_2 = (RecyclerView) findViewById(R.id.tvs_recycler_view_page_2); recyclerView_2.setLayoutManager(new LinearLayoutManager(this)); Call<TVResponse> call_2 = apiService.getTopRatedTv_2(getResources().getString(R.string.API_KEY), page_2); call_2.enqueue(new Callback<TVResponse>() { @Override public void onResponse(Call<TVResponse> call_2, final Response<TVResponse> response) { if (!response.isSuccessful()) { //System.out.println("Error"); } if(response.isSuccessful()) { final List<TV> tvs = response.body().getResults(); recyclerView_2.setAdapter(new TVAdapter(tvs, R.layout.nav_tv_get_airing_today_list_item, getApplicationContext())); }else{ int statusCode = response.code(); switch(statusCode){ case 401: //Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show(); case 404: //Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show(); } } recyclerView_2.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView_2, new RecyclerTouchListener.ClickListener() { @Override public void onClick(View view, int position) { // on selecting a single album // TrackListActivity will be launched to show tracks inside the album Intent i = new Intent(getApplicationContext(), Show_Movie_Details_ID.class); String movie_id = ((TextView) view.findViewById(R.id.movie_id)).getText().toString(); i.putExtra("movie_id", movie_id); //i.putExtra(KEY_MOVIE_ID, movies_response.get(position).getId()); //Toast.makeText(getApplicationContext(),movie_id, Toast.LENGTH_SHORT).show(); startActivity(i); } @Override public void onLongClick(View view, int position) { // on selecting a single album // TrackListActivity will be launched to show tracks inside the album //Intent i = new Intent(getApplicationContext(), Show_Movie_Details_ID.class); // send album id to tracklist activity to get list of songs under that album //String movie_id = ((TextView) view.findViewById(R.id.movie_id)).getText().toString(); //i.putExtra("movie_id", movie_id); //startActivity(i); } })); } @Override public void onFailure(Call<TVResponse> call_2, Throwable t) { // Log error here since request failed //Log.e(TAG, t.toString()); } }); /** PAGE = 3 **/ final RecyclerView recyclerView_3 = (RecyclerView) findViewById(R.id.tvs_recycler_view_page_3); recyclerView_3.setLayoutManager(new LinearLayoutManager(this)); Call<TVResponse> call_3 = apiService.getTopRatedTv_2(getResources().getString(R.string.API_KEY), page_3); call_3.enqueue(new Callback<TVResponse>() { @Override public void onResponse(Call<TVResponse> call_3, final Response<TVResponse> response) { if (!response.isSuccessful()) { //System.out.println("Error"); } if(response.isSuccessful()) { final List<TV> tvs = response.body().getResults(); recyclerView_3.setAdapter(new TVAdapter(tvs, R.layout.nav_tv_get_airing_today_list_item, getApplicationContext())); }else{ int statusCode = response.code(); switch(statusCode){ case 401: //Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show(); case 404: //Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show(); } } recyclerView_3.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView_3, new RecyclerTouchListener.ClickListener() { @Override public void onClick(View view, int position) { // on selecting a single album // TrackListActivity will be launched to show tracks inside the album Intent i = new Intent(getApplicationContext(), Show_Movie_Details_ID.class); String movie_id = ((TextView) view.findViewById(R.id.movie_id)).getText().toString(); i.putExtra("movie_id", movie_id); //i.putExtra(KEY_MOVIE_ID, movies_response.get(position).getId()); //Toast.makeText(getApplicationContext(),movie_id, Toast.LENGTH_SHORT).show(); startActivity(i); } @Override public void onLongClick(View view, int position) { // on selecting a single album // TrackListActivity will be launched to show tracks inside the album //Intent i = new Intent(getApplicationContext(), Show_Movie_Details_ID.class); // send album id to tracklist activity to get list of songs under that album //String movie_id = ((TextView) view.findViewById(R.id.movie_id)).getText().toString(); //i.putExtra("movie_id", movie_id); //startActivity(i); } })); } @Override public void onFailure(Call<TVResponse> call_3, Throwable t) { // Log error here since request failed //Log.e(TAG, t.toString()); } }); } /** SEARCH **/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); MenuItem search = menu.findItem(R.id.search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(search); search(searchView); return true; } /** SEARCH **/ private void search(SearchView searchView) { searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { //Toast.makeText(Popular_Movie.this, "Search is Selected", Toast.LENGTH_SHORT).show(); Intent i = new Intent(Top_Rated_TV.this,SearchActivity.class); String api_key_search = query.toString(); i.putExtra("api_key_search", api_key_search); /**switch_key_activity for SearchActivity **/ String switch_key_activity = "Top_Rated_TV"; i.putExtra("switch_key_activity", switch_key_activity); //Toast.makeText(MainActivity.this, api_key_search, Toast.LENGTH_SHORT).show(); //String api_key_search = ((TextView) menu.findItem(R.id.search)).getText().toString(); //i.putExtra("api_key_search", api_key_search); startActivity(i); return true; } @Override public boolean onQueryTextChange(final String newText) { return false; } }); } /** Για το βέλος<SUF>*/ @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(); //noinspection SimplifiableIfStatement if (id == android.R.id.home) { // finish the activity onBackPressed(); return true; } return super.onOptionsItemSelected(item); } /** 2017 ads @Override public void onPause() { if (mAdView != null) { mAdView.pause(); } super.onPause(); } @Override public void onResume() { super.onResume(); if (mAdView != null) { mAdView.resume(); } } @Override public void onDestroy() { if (mAdView != null) { mAdView.destroy(); } super.onDestroy(); } **/ }
11039_7
package gr.rambou.myicarus; import android.util.Log; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.ClientContext; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.io.Serializable; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.X509TrustManager; public class Icarus implements Serializable { private final String Username, Password; public Map<String, String> Cookies; private String StudentFullName, ID, StudentName, Surname; //private Document Page; private ArrayList<Lesson> Succeed_Lessons, All_Lessons, Exams_Lessons; public Icarus(String username, String password) { this.Username = username; this.Password = password; this.StudentFullName = null; this.Cookies = null; } public boolean login() { try { //ενεργοποιούμε το SSL enableSSLSocket(); //Εκτελέμε ερώτημα GET μέσω της JSoup για να συνδεθούμε Connection.Response res = Jsoup .connect("https://icarus-icsd.aegean.gr/authentication.php") .timeout(10 * 1000) .data("username", Username, "pwd", Password) .method(Connection.Method.POST) .execute(); //Παίρνουμε τα cookies Cookies = res.cookies(); //Αποθηκεύουμε το περιεχόμενο της σελίδας Document Page = res.parse(); //Ελέγχουμε αν συνδεθήκαμε Elements name = Page.select("div#header_login").select("u"); if (name.hasText()) { //Παίρνουμε το ονοματεπώνυμο του φοιτητή StudentFullName = name.html(); //Παίρνουμε τον Αριθμό Μητρώου του φοιτητή Pattern r = Pattern.compile("[0-9-/-]{5,16}"); String line = Page.select("div[id=\"stylized\"]").get(1).select("h2").text().trim(); Matcher m = r.matcher(line); if (m.find()) { ID = m.group(0); } //Παίρνουμε τους βαθμούς του φοιτητή LoadMarks(Page); return true; } } catch (IOException | KeyManagementException | NoSuchAlgorithmException ex) { Log.v("Icarus Class", ex.toString()); } return false; } public boolean SendRequest(String fatherName, Integer cemester, String address, String phone, String send_address, SendType sendtype, String[] papers) { if (papers.length != 11) { return false; } String sendmethod; if (sendtype.equals(SendType.FAX)) { sendmethod = "με τηλεομοιοτυπία (fax) στο τηλέφωνο:"; } else if (sendtype.equals(SendType.COURIER)) { sendmethod = "με courier, με χρέωση παραλήπτη, στη διεύθυνση:"; } else { sendmethod = "από την Γραμματεία του Τμήματος, την επομένη της αίτησης"; } //We create the Data to be Send MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create(); mpEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addTextBody("aitisi_student_id", getID()); mpEntity.addTextBody("aitisi_surname", getSurname()); mpEntity.addTextBody("aitisi_name", getStudentName()); mpEntity.addTextBody("aitisi_father", fatherName); mpEntity.addTextBody("aitisi_semester", cemester.toString()); mpEntity.addTextBody("aitisi_address", address); mpEntity.addTextBody("aitisi_phone", phone); mpEntity.addTextBody("aitisi_send_method", sendmethod); mpEntity.addTextBody("aitisi_send_address", send_address); mpEntity.addTextBody("prints_no[]", papers[0]); mpEntity.addTextBody("prints_no[]", papers[1]); mpEntity.addTextBody("prints_no[]", papers[2]); mpEntity.addTextBody("prints_no[]", papers[3]); mpEntity.addTextBody("prints_no[]", papers[4]); mpEntity.addTextBody("prints_no[]", papers[5]); mpEntity.addTextBody("prints_no[]", papers[6]); mpEntity.addTextBody("prints_no[]", papers[7]); mpEntity.addTextBody("prints_no[]", papers[8]); mpEntity.addTextBody("prints_no[]", papers[9]); mpEntity.addTextBody("aitisi_allo", papers[10]); mpEntity.addTextBody("send", ""); HttpEntity entity = mpEntity.build(); //We send the request HttpPost post = new HttpPost("https://icarus-icsd.aegean.gr/student_aitisi.php"); post.setEntity(entity); HttpClient client = HttpClientBuilder.create().build(); //Gets new/old cookies and set them in store and store to CTX CookieStore Store = new BasicCookieStore(); BasicClientCookie cookie = new BasicClientCookie("PHPSESSID", Cookies.get("PHPSESSID")); cookie.setPath("//"); cookie.setDomain("icarus-icsd.aegean.gr"); Store.addCookie(cookie); HttpContext CTX = new BasicHttpContext(); CTX.setAttribute(ClientContext.COOKIE_STORE, Store); HttpResponse response = null; try { response = client.execute(post, CTX); } catch (IOException ex) { Log.v(Icarus.class.getName().toString(), ex.toString()); } //Check if user credentials are ok if (response == null) { return false; } int responseCode = response.getStatusLine().getStatusCode(); if (responseCode != 200) { return false; } try { String html = EntityUtils.toString(response.getEntity(), "ISO-8859-7"); Document res = Jsoup.parse(html); if (res.getElementsByClass("success").isEmpty()) { return false; } } catch (IOException | org.apache.http.ParseException ex) { return false; } return true; } public void LoadMarks(Document response) { All_Lessons = new ArrayList<>(); Succeed_Lessons = new ArrayList<>(); Exams_Lessons = new ArrayList<>(); if (response == null) { try { //We send the request response = Jsoup .connect("https://icarus-icsd.aegean.gr/student_main.php") .cookies(Cookies) .get(); } catch (IOException ex) { Log.v(Icarus.class.getName().toString(), ex.toString()); return; } } //Start Catching Lessons Elements sGrades = response.getElementById("succeeded_grades").select("tr"); Elements aGrades = response.getElementById("analytic_grades").select("tr"); Elements eGrades = response.getElementById("exetastiki_grades").select("tr"); for (Element a : sGrades) { if (!a.select("td").isEmpty()) { Succeed_Lessons.add(getLesson(a)); } } for (Element a : eGrades) { if (!a.select("td").isEmpty()) { Exams_Lessons.add(getLesson(a)); if (a.select("td").get(6).text().trim().compareTo("") != 0) All_Lessons.add(getLesson(a)); } } for (Element a : aGrades) { if (!a.select("td").isEmpty()) { All_Lessons.add(getLesson(a)); } } } private Lesson getLesson(Element a) { DateFormat formatter = new SimpleDateFormat("dd-MM-yy"); String ID = a.select("td").get(1).text(); String Title = a.select("td").get(2).text(); Double Mark = 0.0; try { Mark = Double.valueOf(a.select("td").get(3).text()); } catch (Exception ex) { } String Cemester = a.select("td").get(4).text(); Date Statement = null, Exam = null; try { Statement = formatter.parse(a.select("td").get(5).text().trim()); Exam = formatter.parse(a.select("td").get(6).text().trim()); } catch (ParseException ex) { } Lesson.LessonStatus Status; switch (a.select("td").get(7).text().trim()) { case "Επιτυχία": Status = Lesson.LessonStatus.PASSED; break; case "Αποτυχία": Status = Lesson.LessonStatus.FAILED; break; case "Ακύρωση": Status = Lesson.LessonStatus.CANCELLED; break; default: Status = Lesson.LessonStatus.NOT_GIVEN; break; } return new Lesson(ID, Title, Mark, Cemester, Statement, Exam, Status); } public ArrayList<Lesson> getSucceed_Lessons() { return Succeed_Lessons; } public ArrayList<Lesson> getAll_Lessons() { return All_Lessons; } public Object[] getAll_Lessons_array() { return All_Lessons.toArray(); } public ArrayList<Lesson> getExams_Lessons() { return Exams_Lessons; } public String getStudentFullName() { return StudentFullName; } public String getID() { return ID; } public String getStudentName() { return StudentFullName.split(" ")[0]; } public String getSurname() { return StudentFullName.split(" ")[1]; } private void enableSSLSocket() throws KeyManagementException, NoSuchAlgorithmException { //HttpsURLConnection.setDefaultHostnameVerifier((String hostname, SSLSession session) -> true); SSLContext context; context = SSLContext.getInstance("TLS"); context.init(null, new X509TrustManager[]{new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }}, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory()); } public enum SendType { OFFICE, COURIER, FAX } public enum PaperType { bebewsh_spoudwn, analutikh_ba8mologia, analutikh_ba8mologia_ptuxio_me_ba8mo, analutikh_ba8mologia_ptuxio_xwris_ba8mo, stratologia, diagrafh, antigrafo_ptuxiou, plhrw_proupo8eseis_apokthseis_ptuxiou, praktikh_askhsh, stegastiko_epidoma, allo } }
AegeanHawks/MobileIcarus
app/src/main/java/gr/rambou/myicarus/Icarus.java
3,246
//Παίρνουμε τον Αριθμό Μητρώου του φοιτητή
line_comment
el
package gr.rambou.myicarus; import android.util.Log; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.ClientContext; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.io.Serializable; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.X509TrustManager; public class Icarus implements Serializable { private final String Username, Password; public Map<String, String> Cookies; private String StudentFullName, ID, StudentName, Surname; //private Document Page; private ArrayList<Lesson> Succeed_Lessons, All_Lessons, Exams_Lessons; public Icarus(String username, String password) { this.Username = username; this.Password = password; this.StudentFullName = null; this.Cookies = null; } public boolean login() { try { //ενεργοποιούμε το SSL enableSSLSocket(); //Εκτελέμε ερώτημα GET μέσω της JSoup για να συνδεθούμε Connection.Response res = Jsoup .connect("https://icarus-icsd.aegean.gr/authentication.php") .timeout(10 * 1000) .data("username", Username, "pwd", Password) .method(Connection.Method.POST) .execute(); //Παίρνουμε τα cookies Cookies = res.cookies(); //Αποθηκεύουμε το περιεχόμενο της σελίδας Document Page = res.parse(); //Ελέγχουμε αν συνδεθήκαμε Elements name = Page.select("div#header_login").select("u"); if (name.hasText()) { //Παίρνουμε το ονοματεπώνυμο του φοιτητή StudentFullName = name.html(); //Παίρνουμε τον<SUF> Pattern r = Pattern.compile("[0-9-/-]{5,16}"); String line = Page.select("div[id=\"stylized\"]").get(1).select("h2").text().trim(); Matcher m = r.matcher(line); if (m.find()) { ID = m.group(0); } //Παίρνουμε τους βαθμούς του φοιτητή LoadMarks(Page); return true; } } catch (IOException | KeyManagementException | NoSuchAlgorithmException ex) { Log.v("Icarus Class", ex.toString()); } return false; } public boolean SendRequest(String fatherName, Integer cemester, String address, String phone, String send_address, SendType sendtype, String[] papers) { if (papers.length != 11) { return false; } String sendmethod; if (sendtype.equals(SendType.FAX)) { sendmethod = "με τηλεομοιοτυπία (fax) στο τηλέφωνο:"; } else if (sendtype.equals(SendType.COURIER)) { sendmethod = "με courier, με χρέωση παραλήπτη, στη διεύθυνση:"; } else { sendmethod = "από την Γραμματεία του Τμήματος, την επομένη της αίτησης"; } //We create the Data to be Send MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create(); mpEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addTextBody("aitisi_student_id", getID()); mpEntity.addTextBody("aitisi_surname", getSurname()); mpEntity.addTextBody("aitisi_name", getStudentName()); mpEntity.addTextBody("aitisi_father", fatherName); mpEntity.addTextBody("aitisi_semester", cemester.toString()); mpEntity.addTextBody("aitisi_address", address); mpEntity.addTextBody("aitisi_phone", phone); mpEntity.addTextBody("aitisi_send_method", sendmethod); mpEntity.addTextBody("aitisi_send_address", send_address); mpEntity.addTextBody("prints_no[]", papers[0]); mpEntity.addTextBody("prints_no[]", papers[1]); mpEntity.addTextBody("prints_no[]", papers[2]); mpEntity.addTextBody("prints_no[]", papers[3]); mpEntity.addTextBody("prints_no[]", papers[4]); mpEntity.addTextBody("prints_no[]", papers[5]); mpEntity.addTextBody("prints_no[]", papers[6]); mpEntity.addTextBody("prints_no[]", papers[7]); mpEntity.addTextBody("prints_no[]", papers[8]); mpEntity.addTextBody("prints_no[]", papers[9]); mpEntity.addTextBody("aitisi_allo", papers[10]); mpEntity.addTextBody("send", ""); HttpEntity entity = mpEntity.build(); //We send the request HttpPost post = new HttpPost("https://icarus-icsd.aegean.gr/student_aitisi.php"); post.setEntity(entity); HttpClient client = HttpClientBuilder.create().build(); //Gets new/old cookies and set them in store and store to CTX CookieStore Store = new BasicCookieStore(); BasicClientCookie cookie = new BasicClientCookie("PHPSESSID", Cookies.get("PHPSESSID")); cookie.setPath("//"); cookie.setDomain("icarus-icsd.aegean.gr"); Store.addCookie(cookie); HttpContext CTX = new BasicHttpContext(); CTX.setAttribute(ClientContext.COOKIE_STORE, Store); HttpResponse response = null; try { response = client.execute(post, CTX); } catch (IOException ex) { Log.v(Icarus.class.getName().toString(), ex.toString()); } //Check if user credentials are ok if (response == null) { return false; } int responseCode = response.getStatusLine().getStatusCode(); if (responseCode != 200) { return false; } try { String html = EntityUtils.toString(response.getEntity(), "ISO-8859-7"); Document res = Jsoup.parse(html); if (res.getElementsByClass("success").isEmpty()) { return false; } } catch (IOException | org.apache.http.ParseException ex) { return false; } return true; } public void LoadMarks(Document response) { All_Lessons = new ArrayList<>(); Succeed_Lessons = new ArrayList<>(); Exams_Lessons = new ArrayList<>(); if (response == null) { try { //We send the request response = Jsoup .connect("https://icarus-icsd.aegean.gr/student_main.php") .cookies(Cookies) .get(); } catch (IOException ex) { Log.v(Icarus.class.getName().toString(), ex.toString()); return; } } //Start Catching Lessons Elements sGrades = response.getElementById("succeeded_grades").select("tr"); Elements aGrades = response.getElementById("analytic_grades").select("tr"); Elements eGrades = response.getElementById("exetastiki_grades").select("tr"); for (Element a : sGrades) { if (!a.select("td").isEmpty()) { Succeed_Lessons.add(getLesson(a)); } } for (Element a : eGrades) { if (!a.select("td").isEmpty()) { Exams_Lessons.add(getLesson(a)); if (a.select("td").get(6).text().trim().compareTo("") != 0) All_Lessons.add(getLesson(a)); } } for (Element a : aGrades) { if (!a.select("td").isEmpty()) { All_Lessons.add(getLesson(a)); } } } private Lesson getLesson(Element a) { DateFormat formatter = new SimpleDateFormat("dd-MM-yy"); String ID = a.select("td").get(1).text(); String Title = a.select("td").get(2).text(); Double Mark = 0.0; try { Mark = Double.valueOf(a.select("td").get(3).text()); } catch (Exception ex) { } String Cemester = a.select("td").get(4).text(); Date Statement = null, Exam = null; try { Statement = formatter.parse(a.select("td").get(5).text().trim()); Exam = formatter.parse(a.select("td").get(6).text().trim()); } catch (ParseException ex) { } Lesson.LessonStatus Status; switch (a.select("td").get(7).text().trim()) { case "Επιτυχία": Status = Lesson.LessonStatus.PASSED; break; case "Αποτυχία": Status = Lesson.LessonStatus.FAILED; break; case "Ακύρωση": Status = Lesson.LessonStatus.CANCELLED; break; default: Status = Lesson.LessonStatus.NOT_GIVEN; break; } return new Lesson(ID, Title, Mark, Cemester, Statement, Exam, Status); } public ArrayList<Lesson> getSucceed_Lessons() { return Succeed_Lessons; } public ArrayList<Lesson> getAll_Lessons() { return All_Lessons; } public Object[] getAll_Lessons_array() { return All_Lessons.toArray(); } public ArrayList<Lesson> getExams_Lessons() { return Exams_Lessons; } public String getStudentFullName() { return StudentFullName; } public String getID() { return ID; } public String getStudentName() { return StudentFullName.split(" ")[0]; } public String getSurname() { return StudentFullName.split(" ")[1]; } private void enableSSLSocket() throws KeyManagementException, NoSuchAlgorithmException { //HttpsURLConnection.setDefaultHostnameVerifier((String hostname, SSLSession session) -> true); SSLContext context; context = SSLContext.getInstance("TLS"); context.init(null, new X509TrustManager[]{new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }}, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory()); } public enum SendType { OFFICE, COURIER, FAX } public enum PaperType { bebewsh_spoudwn, analutikh_ba8mologia, analutikh_ba8mologia_ptuxio_me_ba8mo, analutikh_ba8mologia_ptuxio_xwris_ba8mo, stratologia, diagrafh, antigrafo_ptuxiou, plhrw_proupo8eseis_apokthseis_ptuxiou, praktikh_askhsh, stegastiko_epidoma, allo } }
32051_2
package com.kospeac.smartgreecealert; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.CountDownTimer; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.format.DateFormat; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Locale; public class MainActivity extends AppCompatActivity implements View.OnClickListener { static Activity mainActivity; UsbService mUsbService = new UsbService(); FirebaseService mFirebaseService; String type; Button sosBtn; Button fireBtn; Button abortBtn; public TextView mainTitle; public TextView sosTitle; CountDownTimer countDownTimer; CountDownTimer countDownSOS; boolean countDownTimerIsRunning = false; boolean sosStatus = false; private FallDetectionHandler falldetection; private SeismicDetectionHandler seismicdetection; private final static int REQUESTCODE = 325; LocationManager mLocationManager; Uri notification; Ringtone r; private LocationListener locationService; private Boolean prevStatus; Double longitude, latitude; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mainActivity = this; mFirebaseService = FirebaseService.getInstance(); mFirebaseService.getFCMToken(); // generate FCM token - Firebase Messaging mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationService = new LocationService(); sosBtn = findViewById(R.id.btn_sos); fireBtn = findViewById(R.id.btn_fire); abortBtn = findViewById(R.id.btn_abort); mainTitle = findViewById(R.id.main_title); sosTitle = findViewById(R.id.sos_text); sosBtn.setOnClickListener(this); fireBtn.setOnClickListener(this); abortBtn.setOnClickListener(this); checkPermissions(); try { notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); r = RingtoneManager.getRingtone(getApplicationContext(), notification); } catch (Exception e) { e.printStackTrace(); } this.registerReceiver(mUsbService,new IntentFilter("android.hardware.usb.action.USB_STATE")); mUsbService.setOnUsbServiceStatusListener(new OnUsbServiseStatusListener() { @Override public void onStatusChanged(boolean newStatus) { if(newStatus){ if(prevStatus == null || prevStatus != newStatus ) { prevStatus = newStatus; type = "earthquakeEventDetected"; if (falldetection != null && FallDetectionHandler.getListenerStatus()) { falldetection.unregisterListener(); } mainTitle.setText(R.string.main_title2); setupEarthquakeDetection(); // EarthquakeDetection } }else { if(prevStatus == null || prevStatus != newStatus ) { prevStatus = newStatus; type = "fallDetectionEvent"; if (seismicdetection != null && SeismicDetectionHandler.getListenerStatus()) { System.out.println(seismicdetection); seismicdetection.unregisterListener(); } mainTitle.setText(R.string.main_title1); setupFallDetection(); // FallDetection } } } }); } @Override protected void onPause() { super.onPause(); } @Override public void onDestroy() { // Κανουμε unregister τον broadcaster οταν φευγουμε απο το activity super.onDestroy(); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.btn_sos: // SOS sosStatus = true; sosTitle.setText(R.string.sos_title); countDownSOS = new CountDownTimer(20000, 1000) { public void onTick(long millisUntilFinished) { } public void onFinish() { sosTitle.setText(""); sosStatus = false; } }.start(); handleEvent("SOS"); break; case R.id.btn_fire: // FIRE button sosTitle.setText(R.string.fire_title); countDownSOS = new CountDownTimer(20000, 1000) { public void onTick(long millisUntilFinished) { } public void onFinish() { sosTitle.setText(""); sosStatus = false; } }.start(); handleEvent("FIRE"); break; case R.id.btn_abort: // κουμπι Abort if(type == "fallDetectionEvent" && countDownTimerIsRunning) { cancelTimer(); Toast.makeText(this, "Aborted", Toast.LENGTH_LONG).show(); mainTitle.setText(R.string.main_title1); falldetection.registerListener(); } else if(sosStatus){ // αμα το sosStatus ειναι ενεργο δηλαδη εχει πατηθει το SOS button και δεν εχουν περασει τα 5 λεπτα που εχει ο χρηστης για να κανει ακυρωση cancelSOSTimer(); handleEvent("AbortEvent"); } break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.topbar, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_statistics: Intent goToStatistics = new Intent(this,Statistics.class); startActivity(goToStatistics); // Νεο acitvity Statistics return true; case R.id.menu_contacts: Intent goToContacts = new Intent(this,ContactsActivity.class); startActivity(goToContacts); // Νεο acitvity Contacts return true; default: return super.onOptionsItemSelected(item); } } private void checkPermissions() { List<String> PERMISSIONS = new ArrayList<>(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){ PERMISSIONS.add(Manifest.permission.ACCESS_FINE_LOCATION); }else{ System.out.println("GPS ENABLED"); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationService); } if (ActivityCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) { PERMISSIONS.add(Manifest.permission.SEND_SMS); } if(!PERMISSIONS.isEmpty()){ String[] array = PERMISSIONS.toArray(new String[PERMISSIONS.size()]); ActivityCompat.requestPermissions(this, array, REQUESTCODE); } } //get location from the GPS service provider. Needs permission. protected void getLocation() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); List<String> providers = mLocationManager.getProviders(true); Location location = null; for(String provider : providers){ Location l = mLocationManager.getLastKnownLocation(provider); location = l; if(location != null){ latitude = location.getLatitude(); longitude = location.getLongitude(); break; } } if (location == null) { latitude = -1.0; longitude = -1.0; } } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); for (String permission : permissions) { if (ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED) { if (permission.equals(Manifest.permission.ACCESS_FINE_LOCATION)) { mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationService); getLocation(); } } } } /* setupFallDetection * Create object and listener (from device accelerometer) when we are in fallDetection state. * When status is true we have a user fall and we deactivate/unregister the listener * and we enable a CountDownTimer of 30 secs in order to abort event. * */ private void setupFallDetection() { falldetection = new FallDetectionHandler(this); falldetection.setFallDetectionListener(new FallDetectionListener() { @Override public void onStatusChanged(boolean fallDetectionStatus) { if(fallDetectionStatus) { falldetection.unregisterListener(); countDownTimerIsRunning = true; countDownTimer = new CountDownTimer(30000, 1000) { public void onTick(long millisUntilFinished) { // καθε δευτερολεπτο αλλαζουμε το UI για να εμφανιζεται η αντιστροφη μετρηση r.play(); mainTitle.setText(Long.toString(millisUntilFinished / 1000)); } public void onFinish() { // οταν τελειωσει ο timer ξανακανουμε register τον listener και γινεται διαχεριση του event countDownTimerIsRunning = false; r.stop(); mainTitle.setText(R.string.main_title1); falldetection.registerListener(); handleEvent("fallDetectionEvent"); } }.start(); } } }); } private void cancelTimer(){ //ακυρωση timer για το fall detection countDownTimer.cancel(); r.stop(); } private void cancelSOSTimer(){ //ακυρωση timer για το SOS button countDownSOS.onFinish(); countDownSOS.cancel(); } // setupEarthquakeDetection private void setupEarthquakeDetection() { seismicdetection = new SeismicDetectionHandler(this); seismicdetection.setSeismicDetectionListener(new SeismicDetectionListener() { @Override public void onStatusChanged(boolean seismicDetectionStatus) { if(seismicDetectionStatus) { seismicdetection.unregisterListener(); // Κανουμε unregistrer τον listener μεχρι να γινει η καταγραφη στην βαση και να δουμε αν ειναι οντως σεισμος handleEvent("earthquakeEventDetected"); //καταγραφουμε στην βαση με type earthquakeDetection ωστε να κανουμε αναζητηση και σε αλλους χρηστες με το ιδιο type } } }); } // handleEvent private void handleEvent( String type){ String eventType = type; final double latd,lond; //check current location from LocationChange, if that doesn't work get manually the current location from the GPS service provider if(LocationService.latitude !=0 & LocationService.longitude!=0) { latd = LocationService.latitude; lond = LocationService.latitude; } else { getLocation(); latd = latitude; lond = longitude; } String lat = Double.toString(latd); String lon = Double.toString(lond); final long timestamp = System.currentTimeMillis(); Calendar cal = Calendar.getInstance(Locale.ENGLISH); cal.setTimeInMillis(timestamp); String date = DateFormat.format("dd-MM-yyyy HH:mm", cal).toString(); mFirebaseService.insertEvent(new EventModel(eventType, latd,lond,timestamp,date)); // Εγγραφη στην Firebase Database if((eventType != "earthquakeEventDetected") && (eventType != "earthquakeTakingPlace")) { //Στελνουμε μηνυμα σε καθε περιπτωση εκτος απο την περιπτωση της ανιχνευσης σεισμου Notification notification = new Notification(mainActivity); notification.sendNotification(type, lat, lon, date); // αποστολη SMS } if(eventType == "earthquakeEventDetected"){ // Στην περιπτωση που εχουμε ανιχνευση σεισμου, γινεται ελεγχος της βασης για να βρεθει και αλλος χρηστης σε κοντινη αποσταση που ειχε ιδιο event mFirebaseService.getEvents(); mFirebaseService.setFirebaseListener(new FirebaseListener() { @Override public void onStatusChanged(String newStatus) { // οταν η getEvents() ολοκληρωθει και εχει φερει ολα τα events τοτε το newStatus θα ειναι allEvents. if(newStatus.equals("allEvents")){ List<EventModel> events = EventModel.filterEarthquakeDetectionEvents(mFirebaseService.eventsList); //φιλτρουμε απο ολα τα events μονο τα earthquakedetection boolean seismicStatus = seismicdetection.seismicStatus(events, timestamp,latd,lond); if(seismicStatus){ handleEvent("earthquakeTakingPlace"); // εγγραφη του event στην βαση new AlertDialog.Builder(MainActivity.mainActivity) // ειδοποιση χρηστη και και ενεργοποιηση του listener otan πατησει το οκ .setTitle("Earthquake!") .setMessage("An Earthquake is taking place, please seek help!!") .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if( FallDetectionHandler.getListenerStatus() == null || FallDetectionHandler.getListenerStatus() ==false ){ seismicdetection.registerListener(); } } }) .setIcon(android.R.drawable.ic_dialog_alert) .show(); }else { //αμα δεν υπαρχει αλλος κοντινος χρηστης τοτε δεν γινεται event earthquake if(FallDetectionHandler.getListenerStatus() == null || FallDetectionHandler.getListenerStatus() ==false ){ seismicdetection.registerListener(); } } } } }); } } }
Afrodith/SmartAlertGreece
app/src/main/java/com/kospeac/smartgreecealert/MainActivity.java
3,938
// αμα το sosStatus ειναι ενεργο δηλαδη εχει πατηθει το SOS button και δεν εχουν περασει τα 5 λεπτα που εχει ο χρηστης για να κανει ακυρωση
line_comment
el
package com.kospeac.smartgreecealert; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.CountDownTimer; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.format.DateFormat; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Locale; public class MainActivity extends AppCompatActivity implements View.OnClickListener { static Activity mainActivity; UsbService mUsbService = new UsbService(); FirebaseService mFirebaseService; String type; Button sosBtn; Button fireBtn; Button abortBtn; public TextView mainTitle; public TextView sosTitle; CountDownTimer countDownTimer; CountDownTimer countDownSOS; boolean countDownTimerIsRunning = false; boolean sosStatus = false; private FallDetectionHandler falldetection; private SeismicDetectionHandler seismicdetection; private final static int REQUESTCODE = 325; LocationManager mLocationManager; Uri notification; Ringtone r; private LocationListener locationService; private Boolean prevStatus; Double longitude, latitude; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mainActivity = this; mFirebaseService = FirebaseService.getInstance(); mFirebaseService.getFCMToken(); // generate FCM token - Firebase Messaging mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationService = new LocationService(); sosBtn = findViewById(R.id.btn_sos); fireBtn = findViewById(R.id.btn_fire); abortBtn = findViewById(R.id.btn_abort); mainTitle = findViewById(R.id.main_title); sosTitle = findViewById(R.id.sos_text); sosBtn.setOnClickListener(this); fireBtn.setOnClickListener(this); abortBtn.setOnClickListener(this); checkPermissions(); try { notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); r = RingtoneManager.getRingtone(getApplicationContext(), notification); } catch (Exception e) { e.printStackTrace(); } this.registerReceiver(mUsbService,new IntentFilter("android.hardware.usb.action.USB_STATE")); mUsbService.setOnUsbServiceStatusListener(new OnUsbServiseStatusListener() { @Override public void onStatusChanged(boolean newStatus) { if(newStatus){ if(prevStatus == null || prevStatus != newStatus ) { prevStatus = newStatus; type = "earthquakeEventDetected"; if (falldetection != null && FallDetectionHandler.getListenerStatus()) { falldetection.unregisterListener(); } mainTitle.setText(R.string.main_title2); setupEarthquakeDetection(); // EarthquakeDetection } }else { if(prevStatus == null || prevStatus != newStatus ) { prevStatus = newStatus; type = "fallDetectionEvent"; if (seismicdetection != null && SeismicDetectionHandler.getListenerStatus()) { System.out.println(seismicdetection); seismicdetection.unregisterListener(); } mainTitle.setText(R.string.main_title1); setupFallDetection(); // FallDetection } } } }); } @Override protected void onPause() { super.onPause(); } @Override public void onDestroy() { // Κανουμε unregister τον broadcaster οταν φευγουμε απο το activity super.onDestroy(); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.btn_sos: // SOS sosStatus = true; sosTitle.setText(R.string.sos_title); countDownSOS = new CountDownTimer(20000, 1000) { public void onTick(long millisUntilFinished) { } public void onFinish() { sosTitle.setText(""); sosStatus = false; } }.start(); handleEvent("SOS"); break; case R.id.btn_fire: // FIRE button sosTitle.setText(R.string.fire_title); countDownSOS = new CountDownTimer(20000, 1000) { public void onTick(long millisUntilFinished) { } public void onFinish() { sosTitle.setText(""); sosStatus = false; } }.start(); handleEvent("FIRE"); break; case R.id.btn_abort: // κουμπι Abort if(type == "fallDetectionEvent" && countDownTimerIsRunning) { cancelTimer(); Toast.makeText(this, "Aborted", Toast.LENGTH_LONG).show(); mainTitle.setText(R.string.main_title1); falldetection.registerListener(); } else if(sosStatus){ // αμα το<SUF> cancelSOSTimer(); handleEvent("AbortEvent"); } break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.topbar, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_statistics: Intent goToStatistics = new Intent(this,Statistics.class); startActivity(goToStatistics); // Νεο acitvity Statistics return true; case R.id.menu_contacts: Intent goToContacts = new Intent(this,ContactsActivity.class); startActivity(goToContacts); // Νεο acitvity Contacts return true; default: return super.onOptionsItemSelected(item); } } private void checkPermissions() { List<String> PERMISSIONS = new ArrayList<>(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){ PERMISSIONS.add(Manifest.permission.ACCESS_FINE_LOCATION); }else{ System.out.println("GPS ENABLED"); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationService); } if (ActivityCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) { PERMISSIONS.add(Manifest.permission.SEND_SMS); } if(!PERMISSIONS.isEmpty()){ String[] array = PERMISSIONS.toArray(new String[PERMISSIONS.size()]); ActivityCompat.requestPermissions(this, array, REQUESTCODE); } } //get location from the GPS service provider. Needs permission. protected void getLocation() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); List<String> providers = mLocationManager.getProviders(true); Location location = null; for(String provider : providers){ Location l = mLocationManager.getLastKnownLocation(provider); location = l; if(location != null){ latitude = location.getLatitude(); longitude = location.getLongitude(); break; } } if (location == null) { latitude = -1.0; longitude = -1.0; } } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); for (String permission : permissions) { if (ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED) { if (permission.equals(Manifest.permission.ACCESS_FINE_LOCATION)) { mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationService); getLocation(); } } } } /* setupFallDetection * Create object and listener (from device accelerometer) when we are in fallDetection state. * When status is true we have a user fall and we deactivate/unregister the listener * and we enable a CountDownTimer of 30 secs in order to abort event. * */ private void setupFallDetection() { falldetection = new FallDetectionHandler(this); falldetection.setFallDetectionListener(new FallDetectionListener() { @Override public void onStatusChanged(boolean fallDetectionStatus) { if(fallDetectionStatus) { falldetection.unregisterListener(); countDownTimerIsRunning = true; countDownTimer = new CountDownTimer(30000, 1000) { public void onTick(long millisUntilFinished) { // καθε δευτερολεπτο αλλαζουμε το UI για να εμφανιζεται η αντιστροφη μετρηση r.play(); mainTitle.setText(Long.toString(millisUntilFinished / 1000)); } public void onFinish() { // οταν τελειωσει ο timer ξανακανουμε register τον listener και γινεται διαχεριση του event countDownTimerIsRunning = false; r.stop(); mainTitle.setText(R.string.main_title1); falldetection.registerListener(); handleEvent("fallDetectionEvent"); } }.start(); } } }); } private void cancelTimer(){ //ακυρωση timer για το fall detection countDownTimer.cancel(); r.stop(); } private void cancelSOSTimer(){ //ακυρωση timer για το SOS button countDownSOS.onFinish(); countDownSOS.cancel(); } // setupEarthquakeDetection private void setupEarthquakeDetection() { seismicdetection = new SeismicDetectionHandler(this); seismicdetection.setSeismicDetectionListener(new SeismicDetectionListener() { @Override public void onStatusChanged(boolean seismicDetectionStatus) { if(seismicDetectionStatus) { seismicdetection.unregisterListener(); // Κανουμε unregistrer τον listener μεχρι να γινει η καταγραφη στην βαση και να δουμε αν ειναι οντως σεισμος handleEvent("earthquakeEventDetected"); //καταγραφουμε στην βαση με type earthquakeDetection ωστε να κανουμε αναζητηση και σε αλλους χρηστες με το ιδιο type } } }); } // handleEvent private void handleEvent( String type){ String eventType = type; final double latd,lond; //check current location from LocationChange, if that doesn't work get manually the current location from the GPS service provider if(LocationService.latitude !=0 & LocationService.longitude!=0) { latd = LocationService.latitude; lond = LocationService.latitude; } else { getLocation(); latd = latitude; lond = longitude; } String lat = Double.toString(latd); String lon = Double.toString(lond); final long timestamp = System.currentTimeMillis(); Calendar cal = Calendar.getInstance(Locale.ENGLISH); cal.setTimeInMillis(timestamp); String date = DateFormat.format("dd-MM-yyyy HH:mm", cal).toString(); mFirebaseService.insertEvent(new EventModel(eventType, latd,lond,timestamp,date)); // Εγγραφη στην Firebase Database if((eventType != "earthquakeEventDetected") && (eventType != "earthquakeTakingPlace")) { //Στελνουμε μηνυμα σε καθε περιπτωση εκτος απο την περιπτωση της ανιχνευσης σεισμου Notification notification = new Notification(mainActivity); notification.sendNotification(type, lat, lon, date); // αποστολη SMS } if(eventType == "earthquakeEventDetected"){ // Στην περιπτωση που εχουμε ανιχνευση σεισμου, γινεται ελεγχος της βασης για να βρεθει και αλλος χρηστης σε κοντινη αποσταση που ειχε ιδιο event mFirebaseService.getEvents(); mFirebaseService.setFirebaseListener(new FirebaseListener() { @Override public void onStatusChanged(String newStatus) { // οταν η getEvents() ολοκληρωθει και εχει φερει ολα τα events τοτε το newStatus θα ειναι allEvents. if(newStatus.equals("allEvents")){ List<EventModel> events = EventModel.filterEarthquakeDetectionEvents(mFirebaseService.eventsList); //φιλτρουμε απο ολα τα events μονο τα earthquakedetection boolean seismicStatus = seismicdetection.seismicStatus(events, timestamp,latd,lond); if(seismicStatus){ handleEvent("earthquakeTakingPlace"); // εγγραφη του event στην βαση new AlertDialog.Builder(MainActivity.mainActivity) // ειδοποιση χρηστη και και ενεργοποιηση του listener otan πατησει το οκ .setTitle("Earthquake!") .setMessage("An Earthquake is taking place, please seek help!!") .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if( FallDetectionHandler.getListenerStatus() == null || FallDetectionHandler.getListenerStatus() ==false ){ seismicdetection.registerListener(); } } }) .setIcon(android.R.drawable.ic_dialog_alert) .show(); }else { //αμα δεν υπαρχει αλλος κοντινος χρηστης τοτε δεν γινεται event earthquake if(FallDetectionHandler.getListenerStatus() == null || FallDetectionHandler.getListenerStatus() ==false ){ seismicdetection.registerListener(); } } } } }); } } }
2452_3
package gr.aueb; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class LoginFrame extends JFrame implements ActionListener { static String username; JFrame frm = new JFrame("Filmbro"); JLabel welcomeMess = new JLabel("Hello, log in to your account."); Container container = getContentPane(); JLabel userLabel = new JLabel("Username:"); JLabel passwordLabel = new JLabel("Password:"); JTextField userTextField = new JTextField(" e.g. Username"); JPasswordField passwordField = new JPasswordField(); DarkButton loginButton = new DarkButton("LOGIN"); DarkButton backButton = new DarkButton("BACK"); JCheckBox showPassword = new JCheckBox("Show Password"); JLabel picLabel = new JLabel(new ImageIcon("logo.png")); // an theloume na baloyme eikona JMenuBar mb = new JMenuBar(); LoginFrame() { initComponents(); } private void initComponents() { setTitle("Java"); setBounds(10, 10, 600, 600); frm.setJMenuBar(mb); setLocationRelativeTo(null); // center the application window setVisible(true); setLayoutManager(); setLocationAndSize(); addComponentsToContainer(); addActionEvent(); setBackground(20,20,20); setFont(); addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { resizeComponents(); } }); } public void setLayoutManager() { container.setLayout(null); } private void setBackground(int a, int b, int c) { container.setBackground(new Color(a, b, c)); showPassword.setBackground(new Color(a, b, c)); } private void setFont() { welcomeMess.setFont(new Font("Tahoma", 0, 16)); welcomeMess.setForeground(new Color(230, 120, 50)); userLabel.setForeground(new Color(230, 120, 50)); passwordLabel.setForeground(new Color(230, 120, 50)); showPassword.setForeground(new Color(230, 120, 50)); } public void setLocationAndSize() { userLabel.setBounds(50, 150, 100, 30); passwordLabel.setBounds(50, 200, 100, 30); userTextField.setBounds(150, 150, 150, 30); passwordField.setBounds(150, 200, 150, 30); showPassword.setBounds(150, 240, 150, 30); loginButton.setBounds(125, 300, 100, 30); welcomeMess.setBounds(70, 50, 230, 150); picLabel.setBounds(100, 10, 150, 90); backButton.setBounds(20, 490, 80, 30); } public void addComponentsToContainer() { container.add(userLabel); container.add(welcomeMess); container.add(passwordLabel); container.add(userTextField); container.add(passwordField); container.add(showPassword); container.add(loginButton); container.add(picLabel); container.add(backButton); } public void addActionEvent() { loginButton.addActionListener(this); showPassword.addActionListener(this); backButton.addActionListener(this); userTextField.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { userTextField.setText(""); } }); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == backButton) { MenuBar m = new MenuBar(new MenuFrame()); dispose(); } if (e.getSource() == showPassword) { if (showPassword.isSelected()) { passwordField.setEchoChar((char) 0); }else { passwordField.setEchoChar('*'); } } } public void resizeComponents() { int width = this.getWidth(); int centerOffset = width / 4; // Προσαρμόζετε τον παράγοντα ανάλογα με την πόσο πρέπει να μετακινηθούν τα στοιχεία. userLabel.setBounds(centerOffset, 150, 100, 30); passwordLabel.setBounds(centerOffset, 200, 100, 30); userTextField.setBounds(centerOffset + 100, 150, 150, 30); passwordField.setBounds(centerOffset + 100, 200, 150, 30); showPassword.setBounds(centerOffset + 100, 240, 150, 30); loginButton.setBounds(centerOffset +85, 300, 140, 30); // Προσαρμόστε ανάλογα για την ευθυγράμμιση. welcomeMess.setBounds(centerOffset, 50, 230, 150); picLabel.setBounds(centerOffset + 50, 10, 150, 90); backButton.setBounds(20, 490, 80, 30); } }
Aglag257/Java2_AIApp
app/src/unused_code/LoginFrame.java
1,431
// Προσαρμόστε ανάλογα για την ευθυγράμμιση.
line_comment
el
package gr.aueb; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class LoginFrame extends JFrame implements ActionListener { static String username; JFrame frm = new JFrame("Filmbro"); JLabel welcomeMess = new JLabel("Hello, log in to your account."); Container container = getContentPane(); JLabel userLabel = new JLabel("Username:"); JLabel passwordLabel = new JLabel("Password:"); JTextField userTextField = new JTextField(" e.g. Username"); JPasswordField passwordField = new JPasswordField(); DarkButton loginButton = new DarkButton("LOGIN"); DarkButton backButton = new DarkButton("BACK"); JCheckBox showPassword = new JCheckBox("Show Password"); JLabel picLabel = new JLabel(new ImageIcon("logo.png")); // an theloume na baloyme eikona JMenuBar mb = new JMenuBar(); LoginFrame() { initComponents(); } private void initComponents() { setTitle("Java"); setBounds(10, 10, 600, 600); frm.setJMenuBar(mb); setLocationRelativeTo(null); // center the application window setVisible(true); setLayoutManager(); setLocationAndSize(); addComponentsToContainer(); addActionEvent(); setBackground(20,20,20); setFont(); addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { resizeComponents(); } }); } public void setLayoutManager() { container.setLayout(null); } private void setBackground(int a, int b, int c) { container.setBackground(new Color(a, b, c)); showPassword.setBackground(new Color(a, b, c)); } private void setFont() { welcomeMess.setFont(new Font("Tahoma", 0, 16)); welcomeMess.setForeground(new Color(230, 120, 50)); userLabel.setForeground(new Color(230, 120, 50)); passwordLabel.setForeground(new Color(230, 120, 50)); showPassword.setForeground(new Color(230, 120, 50)); } public void setLocationAndSize() { userLabel.setBounds(50, 150, 100, 30); passwordLabel.setBounds(50, 200, 100, 30); userTextField.setBounds(150, 150, 150, 30); passwordField.setBounds(150, 200, 150, 30); showPassword.setBounds(150, 240, 150, 30); loginButton.setBounds(125, 300, 100, 30); welcomeMess.setBounds(70, 50, 230, 150); picLabel.setBounds(100, 10, 150, 90); backButton.setBounds(20, 490, 80, 30); } public void addComponentsToContainer() { container.add(userLabel); container.add(welcomeMess); container.add(passwordLabel); container.add(userTextField); container.add(passwordField); container.add(showPassword); container.add(loginButton); container.add(picLabel); container.add(backButton); } public void addActionEvent() { loginButton.addActionListener(this); showPassword.addActionListener(this); backButton.addActionListener(this); userTextField.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { userTextField.setText(""); } }); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == backButton) { MenuBar m = new MenuBar(new MenuFrame()); dispose(); } if (e.getSource() == showPassword) { if (showPassword.isSelected()) { passwordField.setEchoChar((char) 0); }else { passwordField.setEchoChar('*'); } } } public void resizeComponents() { int width = this.getWidth(); int centerOffset = width / 4; // Προσαρμόζετε τον παράγοντα ανάλογα με την πόσο πρέπει να μετακινηθούν τα στοιχεία. userLabel.setBounds(centerOffset, 150, 100, 30); passwordLabel.setBounds(centerOffset, 200, 100, 30); userTextField.setBounds(centerOffset + 100, 150, 150, 30); passwordField.setBounds(centerOffset + 100, 200, 150, 30); showPassword.setBounds(centerOffset + 100, 240, 150, 30); loginButton.setBounds(centerOffset +85, 300, 140, 30); // Προσαρμόστε ανάλογα<SUF> welcomeMess.setBounds(centerOffset, 50, 230, 150); picLabel.setBounds(centerOffset + 50, 10, 150, 90); backButton.setBounds(20, 490, 80, 30); } }
10206_24
package com.example.hangmangame; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.stage.Stage; import java.io.*; import java.util.*; import static com.example.hangmangame.LoadDictionary.*; public class Controller { public static boolean Playing; @FXML private Label AvailableWordsLabel; @FXML private Label Dictionary; @FXML private ImageView ImageView; @FXML private Label Possible_Letters_Label; @FXML private HBox word_hbox; @FXML private Label TotalPoints; @FXML private Label Success_Rate; @FXML private void open_up_add_dictionary(ActionEvent event) { try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("add_dictionary.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Dictionary Settings"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening add_dictionary Scene"); } } @FXML private void open_up_load_dictionary(ActionEvent event) { try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("load_dictionary.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Load Dictionary"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Load Dictionary Scene"); } } @FXML private void solution_dialog(){ Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Solution"); alert.setHeaderText(null); if(Playing) alert.setContentText("Solution is " + game_word); else alert.setContentText("You are not playing !"); alert.showAndWait(); } public List<Button> word_buttons = new ArrayList<>(); public static String game_word; public int Number_of_Letters_left; public int lives; public List<Button> Invisible_Key_Buttons = new ArrayList<>(); public boolean initialise = false; @FXML public void start() { if(!initialise){ initialise_rounds(); } lives = 6; SetImage(lives); game_word = get_random_word(); Number_of_Letters_left = game_word.length(); Playing = true; Successful_Attempts = 0.0F; Total_Attempts = 0.0F; Success_Rate.setText("0%"); Available_Words(); if (game_word.equals("empty")) { Dictionary.setText("Load Dictionary!"); return; } //Reset Possible_letters.clear(); //Set invisible keys to visible if (!Invisible_Key_Buttons.isEmpty()) { for (Button invisible_key_button : Invisible_Key_Buttons) { invisible_key_button.setVisible(true); } } Dictionary.setText(title); System.out.println(title); //create a list of buttons word_hbox.getChildren().removeAll(word_buttons); word_buttons.clear(); for (int i = 0; i < game_word.length(); i++) { word_buttons.add(new Button("_")); //word_buttons.add(new Button(String.valueOf(game_word.charAt(i)))); word_hbox.getChildren().add(word_buttons.get(i)); word_buttons.get(i).setStyle("-fx-font-size: 2em; "); /* when clicked it should display the most common letters in the position of the letter in the Dictionary */ word_buttons.get(i).setOnAction(actionEvent -> { //... do something in here. }); } Same_length_stats(); } public List<String> Possible_letters = new ArrayList<>(); public List<Integer> Quantity_of_Letter = new ArrayList<>(); public Vector<String> same_length_words = new Vector<>(); public List<Element> elements = new ArrayList<Element>(); public void Same_length_stats() { /* Find words with equal length with game_word */ same_length_words.clear(); elements.clear(); for (String word : words) { if (word.length() == game_word.length() && !word.equals(game_word)) { same_length_words.add(word); } } // counter to keep track of how many int[][] CharCounter = new int[game_word.length()][26]; /* set all counters to zero */ // we have 26 counters for every letter of the game word for (int i = 0; i < game_word.length(); i++) { for (int z = 0; z < 26; z++) { CharCounter[i][z] = 0; } } // Now we count for (int i = 0; i < game_word.length(); i++) { for (String word : same_length_words) { int temp = (int) word.charAt(i) - 65; //Capital Letters CharCounter[i][temp]++; } } // add every counter to a List in order to keep track of them when we sort them for (int i = 0; i < game_word.length(); i++) { //i = position for (int z = 0; z < 26; z++) { //z = letter elements.add(new Element(i, z, CharCounter[i][z])); //System.out.println(CharCounter[i][z]); } } Collections.sort(elements); // reverse so we get the big numbers at front Collections.reverse(elements); for (int i = 0; i < game_word.length(); i++) { Possible_letters.add(""); System.out.println("---------LOOP " + String.valueOf(i) + "----------" ); System.out.println(i); for (Element element : elements) { if (element.position == i && element.quantity > 0) { //q>0 because we need P(q)>0 char letter = (char) (element.letter + 65); System.out.println(letter + " quantity :" + String.valueOf(element.quantity)); Possible_letters.set(i , Possible_letters.get(i) + String.valueOf(letter) + " "); } } int java_is_dumb = i; //lamda expressions need final expressions word_buttons.get(i).setOnAction(e -> {Possible_Letters_Label.setText(Possible_letters.get(java_is_dumb));}); System.out.println(Possible_letters.get(i)); } } public void Available_Words() { AvailableWordsLabel.setText(String.valueOf(words.size())); } public float Successful_Attempts; public float Total_Attempts; public void Success_Rate(){ if (Successful_Attempts == 0){ Success_Rate.setText("0%"); return; } else if (Successful_Attempts==Total_Attempts) { Success_Rate.setText("100%"); return; } float Success_rate = 100*Successful_Attempts/Total_Attempts;; String Success_Rate_Text = String.valueOf(Success_rate); String Label = ""; for (int i = 0; i < 4; i++) { Label += String.valueOf(Success_Rate_Text.charAt(i)); } Success_Rate.setText(Label+" %"); } public int Score = 0; public void Update_Score(int position){ int total_same_length_words = same_length_words.size(); int Element_letter = ((int) game_word.charAt(position)) - 65; //we have to convert it to the way we added it 26*i + z //int quantity_of_letter = elements.get(26*position + Element_letter).quantity; int quantity_of_letter = 0; for(Element element:elements){ if(element.letter == Element_letter && element.position==position){ quantity_of_letter = element.quantity; } } float percentage = (float)quantity_of_letter / (float) total_same_length_words; System.out.println("Total words, quantity of letter , percentage"); System.out.println(total_same_length_words); System.out.println(quantity_of_letter); System.out.println(percentage); //System.out.println(Element_letter+65); if(percentage >= 0.6) { Score += 5; } else if(percentage >= 0.4){ Score += 10; } else if(percentage >= 0.25){ Score += 15; } else Score += 30; } @FXML public void Try_this_Letter(Event event) { if (!Playing) { return; //If we ain't playing do nothing } System.out.println(event.getTarget()); Button btn = (Button) event.getSource(); //temp value String button_char = btn.getId(); System.out.println(btn.getId()); //get id btn.setVisible(false); Invisible_Key_Buttons.add(btn); /* ChecK if the character exist in the game word */ boolean success = false; Total_Attempts++; for (int i = 0; i < game_word.length(); i++) { if (button_char.equals(String.valueOf(game_word.charAt(i)))) { //reveal the letters that exist in the words success = true; Number_of_Letters_left--; word_buttons.get(i).setText(button_char); Update_Score(i); //we scored at position i TotalPoints.setText(String.valueOf(Score)); if (Number_of_Letters_left < 1) { System.out.println("Congratulations"); //win = true Update_Rounds(true); win_game(true); } } } if(!success){ lives--; SetImage(lives); //game_over(); if (lives < 1) { //win = false Playing = false; Update_Rounds(false); System.out.println("You lost :("); win_game(false); } } else Successful_Attempts++; Success_Rate(); } public void win_game(boolean win){ Alert alert = new Alert(Alert.AlertType.INFORMATION); if(win) { alert.setTitle("Congratulations"); alert.setHeaderText("You Won !"); alert.setContentText("Ready for the next one ?"); File myObj = new File("./images/win.png"); Image image = new Image(myObj.getAbsolutePath()); alert.setGraphic(new ImageView(image)); } else { alert.setTitle("Tough luck"); alert.setHeaderText("You Lost ..."); alert.setContentText("Want to try again ?"); File myObj = new File("./images/lost.png"); Image image = new Image(myObj.getAbsolutePath()); alert.setGraphic(new ImageView(image)); } ButtonType buttonTypeNextWord = new ButtonType("Next Word", ButtonBar.ButtonData.CANCEL_CLOSE); alert.getButtonTypes().setAll(buttonTypeNextWord); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == buttonTypeNextWord){ start(); } } public void SetImage(int lives) { File myObj = new File("./images/" + String.valueOf(lives) + ".jpg"); Image image = new Image(myObj.getAbsolutePath()); ImageView.setImage(image); } @FXML public void exit_app(){ Platform.exit(); } @FXML public void open_Dictionary_Details(ActionEvent event){ /*Dictionary: Μέσω ενός popup παραθύρου θα παρουσιάζει το ποσοστό των λέξεων του ενεργού λεξικού με 6 γράμματα, 7 έως 9 γράμματα και 10 ή περισσότερα γράμματα */ try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("dictionary_details.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Dictionary Details"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Dictionary Details Scene"); } } public static Vector<String> gamewords_5 = new Vector<>(); public static Vector<String> results_5 = new Vector<>(); public static Vector<String> Attempts_per_gameword = new Vector<>(); public void initialise_rounds() { for (int i = 0; i < 5; i++) { gamewords_5.add("---"); results_5.add("---"); Attempts_per_gameword.add("---"); } initialise = true; } public void Update_Rounds(Boolean win) { //gamewords gamewords_5.remove(0); gamewords_5.add(game_word); //results results_5.remove(0); if(win){ results_5.add("Victory"); } else { results_5.add("Defeat"); } //attempts Attempts_per_gameword.remove(0); Attempts_per_gameword.add(String.valueOf((int) Total_Attempts)); } @FXML public void Instructions(){ try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("instructions.fxml")); Scene scene = new Scene(fxmlLoader.load()); Stage stage = new Stage(); stage.setTitle("Instructions"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Instructions Scene"); } } @FXML public void Rounds(){ /*Rounds: Μέσω ενός popup παραθύρου θα παρουσιάζει για τα 5 τελευταία ολοκληρωμένα παιχνίδια τις παρακάτω πληροφορίες: επιλεγμένη λέξη, πλήθος προσπαθειών και νικητή (παίκτης ή υπολογιστής). */ try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("rounds.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Rounds Details"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Rounds Scene"); } } }
Aglogallos/Hangman-Game-JavaFx
Hangman_Game/Hangman-Game/src/main/java/com/example/hangmangame/Controller.java
3,768
/*Rounds: Μέσω ενός popup παραθύρου θα παρουσιάζει για τα 5 τελευταία ολοκληρωμένα παιχνίδια τις παρακάτω πληροφορίες: επιλεγμένη λέξη, πλήθος προσπαθειών και νικητή (παίκτης ή υπολογιστής). */
block_comment
el
package com.example.hangmangame; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.stage.Stage; import java.io.*; import java.util.*; import static com.example.hangmangame.LoadDictionary.*; public class Controller { public static boolean Playing; @FXML private Label AvailableWordsLabel; @FXML private Label Dictionary; @FXML private ImageView ImageView; @FXML private Label Possible_Letters_Label; @FXML private HBox word_hbox; @FXML private Label TotalPoints; @FXML private Label Success_Rate; @FXML private void open_up_add_dictionary(ActionEvent event) { try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("add_dictionary.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Dictionary Settings"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening add_dictionary Scene"); } } @FXML private void open_up_load_dictionary(ActionEvent event) { try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("load_dictionary.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Load Dictionary"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Load Dictionary Scene"); } } @FXML private void solution_dialog(){ Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Solution"); alert.setHeaderText(null); if(Playing) alert.setContentText("Solution is " + game_word); else alert.setContentText("You are not playing !"); alert.showAndWait(); } public List<Button> word_buttons = new ArrayList<>(); public static String game_word; public int Number_of_Letters_left; public int lives; public List<Button> Invisible_Key_Buttons = new ArrayList<>(); public boolean initialise = false; @FXML public void start() { if(!initialise){ initialise_rounds(); } lives = 6; SetImage(lives); game_word = get_random_word(); Number_of_Letters_left = game_word.length(); Playing = true; Successful_Attempts = 0.0F; Total_Attempts = 0.0F; Success_Rate.setText("0%"); Available_Words(); if (game_word.equals("empty")) { Dictionary.setText("Load Dictionary!"); return; } //Reset Possible_letters.clear(); //Set invisible keys to visible if (!Invisible_Key_Buttons.isEmpty()) { for (Button invisible_key_button : Invisible_Key_Buttons) { invisible_key_button.setVisible(true); } } Dictionary.setText(title); System.out.println(title); //create a list of buttons word_hbox.getChildren().removeAll(word_buttons); word_buttons.clear(); for (int i = 0; i < game_word.length(); i++) { word_buttons.add(new Button("_")); //word_buttons.add(new Button(String.valueOf(game_word.charAt(i)))); word_hbox.getChildren().add(word_buttons.get(i)); word_buttons.get(i).setStyle("-fx-font-size: 2em; "); /* when clicked it should display the most common letters in the position of the letter in the Dictionary */ word_buttons.get(i).setOnAction(actionEvent -> { //... do something in here. }); } Same_length_stats(); } public List<String> Possible_letters = new ArrayList<>(); public List<Integer> Quantity_of_Letter = new ArrayList<>(); public Vector<String> same_length_words = new Vector<>(); public List<Element> elements = new ArrayList<Element>(); public void Same_length_stats() { /* Find words with equal length with game_word */ same_length_words.clear(); elements.clear(); for (String word : words) { if (word.length() == game_word.length() && !word.equals(game_word)) { same_length_words.add(word); } } // counter to keep track of how many int[][] CharCounter = new int[game_word.length()][26]; /* set all counters to zero */ // we have 26 counters for every letter of the game word for (int i = 0; i < game_word.length(); i++) { for (int z = 0; z < 26; z++) { CharCounter[i][z] = 0; } } // Now we count for (int i = 0; i < game_word.length(); i++) { for (String word : same_length_words) { int temp = (int) word.charAt(i) - 65; //Capital Letters CharCounter[i][temp]++; } } // add every counter to a List in order to keep track of them when we sort them for (int i = 0; i < game_word.length(); i++) { //i = position for (int z = 0; z < 26; z++) { //z = letter elements.add(new Element(i, z, CharCounter[i][z])); //System.out.println(CharCounter[i][z]); } } Collections.sort(elements); // reverse so we get the big numbers at front Collections.reverse(elements); for (int i = 0; i < game_word.length(); i++) { Possible_letters.add(""); System.out.println("---------LOOP " + String.valueOf(i) + "----------" ); System.out.println(i); for (Element element : elements) { if (element.position == i && element.quantity > 0) { //q>0 because we need P(q)>0 char letter = (char) (element.letter + 65); System.out.println(letter + " quantity :" + String.valueOf(element.quantity)); Possible_letters.set(i , Possible_letters.get(i) + String.valueOf(letter) + " "); } } int java_is_dumb = i; //lamda expressions need final expressions word_buttons.get(i).setOnAction(e -> {Possible_Letters_Label.setText(Possible_letters.get(java_is_dumb));}); System.out.println(Possible_letters.get(i)); } } public void Available_Words() { AvailableWordsLabel.setText(String.valueOf(words.size())); } public float Successful_Attempts; public float Total_Attempts; public void Success_Rate(){ if (Successful_Attempts == 0){ Success_Rate.setText("0%"); return; } else if (Successful_Attempts==Total_Attempts) { Success_Rate.setText("100%"); return; } float Success_rate = 100*Successful_Attempts/Total_Attempts;; String Success_Rate_Text = String.valueOf(Success_rate); String Label = ""; for (int i = 0; i < 4; i++) { Label += String.valueOf(Success_Rate_Text.charAt(i)); } Success_Rate.setText(Label+" %"); } public int Score = 0; public void Update_Score(int position){ int total_same_length_words = same_length_words.size(); int Element_letter = ((int) game_word.charAt(position)) - 65; //we have to convert it to the way we added it 26*i + z //int quantity_of_letter = elements.get(26*position + Element_letter).quantity; int quantity_of_letter = 0; for(Element element:elements){ if(element.letter == Element_letter && element.position==position){ quantity_of_letter = element.quantity; } } float percentage = (float)quantity_of_letter / (float) total_same_length_words; System.out.println("Total words, quantity of letter , percentage"); System.out.println(total_same_length_words); System.out.println(quantity_of_letter); System.out.println(percentage); //System.out.println(Element_letter+65); if(percentage >= 0.6) { Score += 5; } else if(percentage >= 0.4){ Score += 10; } else if(percentage >= 0.25){ Score += 15; } else Score += 30; } @FXML public void Try_this_Letter(Event event) { if (!Playing) { return; //If we ain't playing do nothing } System.out.println(event.getTarget()); Button btn = (Button) event.getSource(); //temp value String button_char = btn.getId(); System.out.println(btn.getId()); //get id btn.setVisible(false); Invisible_Key_Buttons.add(btn); /* ChecK if the character exist in the game word */ boolean success = false; Total_Attempts++; for (int i = 0; i < game_word.length(); i++) { if (button_char.equals(String.valueOf(game_word.charAt(i)))) { //reveal the letters that exist in the words success = true; Number_of_Letters_left--; word_buttons.get(i).setText(button_char); Update_Score(i); //we scored at position i TotalPoints.setText(String.valueOf(Score)); if (Number_of_Letters_left < 1) { System.out.println("Congratulations"); //win = true Update_Rounds(true); win_game(true); } } } if(!success){ lives--; SetImage(lives); //game_over(); if (lives < 1) { //win = false Playing = false; Update_Rounds(false); System.out.println("You lost :("); win_game(false); } } else Successful_Attempts++; Success_Rate(); } public void win_game(boolean win){ Alert alert = new Alert(Alert.AlertType.INFORMATION); if(win) { alert.setTitle("Congratulations"); alert.setHeaderText("You Won !"); alert.setContentText("Ready for the next one ?"); File myObj = new File("./images/win.png"); Image image = new Image(myObj.getAbsolutePath()); alert.setGraphic(new ImageView(image)); } else { alert.setTitle("Tough luck"); alert.setHeaderText("You Lost ..."); alert.setContentText("Want to try again ?"); File myObj = new File("./images/lost.png"); Image image = new Image(myObj.getAbsolutePath()); alert.setGraphic(new ImageView(image)); } ButtonType buttonTypeNextWord = new ButtonType("Next Word", ButtonBar.ButtonData.CANCEL_CLOSE); alert.getButtonTypes().setAll(buttonTypeNextWord); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == buttonTypeNextWord){ start(); } } public void SetImage(int lives) { File myObj = new File("./images/" + String.valueOf(lives) + ".jpg"); Image image = new Image(myObj.getAbsolutePath()); ImageView.setImage(image); } @FXML public void exit_app(){ Platform.exit(); } @FXML public void open_Dictionary_Details(ActionEvent event){ /*Dictionary: Μέσω ενός popup παραθύρου θα παρουσιάζει το ποσοστό των λέξεων του ενεργού λεξικού με 6 γράμματα, 7 έως 9 γράμματα και 10 ή περισσότερα γράμματα */ try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("dictionary_details.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Dictionary Details"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Dictionary Details Scene"); } } public static Vector<String> gamewords_5 = new Vector<>(); public static Vector<String> results_5 = new Vector<>(); public static Vector<String> Attempts_per_gameword = new Vector<>(); public void initialise_rounds() { for (int i = 0; i < 5; i++) { gamewords_5.add("---"); results_5.add("---"); Attempts_per_gameword.add("---"); } initialise = true; } public void Update_Rounds(Boolean win) { //gamewords gamewords_5.remove(0); gamewords_5.add(game_word); //results results_5.remove(0); if(win){ results_5.add("Victory"); } else { results_5.add("Defeat"); } //attempts Attempts_per_gameword.remove(0); Attempts_per_gameword.add(String.valueOf((int) Total_Attempts)); } @FXML public void Instructions(){ try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("instructions.fxml")); Scene scene = new Scene(fxmlLoader.load()); Stage stage = new Stage(); stage.setTitle("Instructions"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Instructions Scene"); } } @FXML public void Rounds(){ /*Rounds: Μέσω ενός<SUF>*/ try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("rounds.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Rounds Details"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Rounds Scene"); } } }
6074_0
package booking; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; public class AvailabilityOfAccommodations implements Runnable{ private Map<String, ReservationDateRange> roomAvailability; @Override public void run() { // Εδώ μπορείτε να ορίσετε μια συνεχή λειτουργία που θα εκτελείται από το νήμα while (true) { // Προσθέστε τυχόν επιπλέον λειτουργίες που θέλετε να εκτελεστούν επανειλημμένα try { Thread.sleep(1000); // Περιμένει 1 δευτερόλεπτο πριν συνεχίσει } catch (InterruptedException e) { e.printStackTrace(); } } } public AvailabilityOfAccommodations() { this.roomAvailability = new HashMap<>(); } public Map<String, ReservationDateRange> getRoomAvailability() { return roomAvailability; } /** * Initial input to map from JSONfile * * @param path */ public void addRoomAsAvailableFromJSON(Path path) { AccommodationList accommodationList = new AccommodationList(path); for (int i = 0; i < accommodationList.getLengthOfAccommodationList(); i++) { roomAvailability.put(accommodationList.get(i).getRoomName(), new ReservationDateRange()); } } /** * From Manager input to map * * @param roomName * @param from * @param to */ public void addRoomAsAvailableFromManager(String roomName, ReservationDate from, ReservationDate to) { System.out.println("..................function: addRoomAsAvailableFromManager..............................."); boolean exist = false; for (String key : roomAvailability.keySet()) { if (key.equals(roomName)) { roomAvailability.put(roomName, new ReservationDateRange(from, to)); exist = true; } } if (exist) { System.out.println("The room " + roomName + " successfully inserted as available"); } else { System.out.println("The specific room " + roomName + " does not exist."); } } /** * booking of a room - client function * * @param roomName */ public synchronized void bookingOfRoom(String roomName) { System.out.println("..................function: bookingOfRoom..............................."); boolean booking = false; for (String key : roomAvailability.keySet()) { ReservationDateRange range = roomAvailability.get(key); if (key.equals(roomName)) if (range.isAvailable()) { range.setAvailable(false); booking = true; } } if (booking) { System.out.println("The " + roomName + " is successfully booked."); } else { System.out.println("The " + roomName + " is not available."); } } @Override public String toString() { return "Manager{" + "roomAvailability=" + roomAvailability + '}'; } public static void main(String[] args) { // Default gemisma tou list apo JSON file AccommodationList list = new AccommodationList(Path.of("src/main/java/booking/accommodations.json")); // object // Default gemisma tou map apo JSON file AvailabilityOfAccommodations availabilityOfAccommodations = new AvailabilityOfAccommodations(); // object ReservationDate from = new ReservationDate(20, 4, 2024); ReservationDate to = new ReservationDate(30, 4, 2024); availabilityOfAccommodations.addRoomAsAvailableFromJSON(Path.of("src/main/java/booking/accommodations.json")); // map availabilityOfAccommodations.addRoomAsAvailableFromManager("lala", from, to); // ta typwnei opws akrivws ta exei parei apo to JSON for (String key : availabilityOfAccommodations.getRoomAvailability().keySet()) { System.out.println(key + ": " +availabilityOfAccommodations.getRoomAvailability().get(key)); } // O manager allazei mia hmerominia gia th diathesimotita tou dwmatiou availabilityOfAccommodations.addRoomAsAvailableFromManager("130", from, to); for (String key : availabilityOfAccommodations.getRoomAvailability().keySet()) { System.out.println(key + ": " +availabilityOfAccommodations.getRoomAvailability().get(key)); } // booking of a room availabilityOfAccommodations.bookingOfRoom("235"); availabilityOfAccommodations.bookingOfRoom("500"); } }
AikVant/distributed_booking_2024
src/main/java/booking/AvailabilityOfAccommodations.java
1,206
// Εδώ μπορείτε να ορίσετε μια συνεχή λειτουργία που θα εκτελείται από το νήμα
line_comment
el
package booking; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; public class AvailabilityOfAccommodations implements Runnable{ private Map<String, ReservationDateRange> roomAvailability; @Override public void run() { // Εδώ μπορείτε<SUF> while (true) { // Προσθέστε τυχόν επιπλέον λειτουργίες που θέλετε να εκτελεστούν επανειλημμένα try { Thread.sleep(1000); // Περιμένει 1 δευτερόλεπτο πριν συνεχίσει } catch (InterruptedException e) { e.printStackTrace(); } } } public AvailabilityOfAccommodations() { this.roomAvailability = new HashMap<>(); } public Map<String, ReservationDateRange> getRoomAvailability() { return roomAvailability; } /** * Initial input to map from JSONfile * * @param path */ public void addRoomAsAvailableFromJSON(Path path) { AccommodationList accommodationList = new AccommodationList(path); for (int i = 0; i < accommodationList.getLengthOfAccommodationList(); i++) { roomAvailability.put(accommodationList.get(i).getRoomName(), new ReservationDateRange()); } } /** * From Manager input to map * * @param roomName * @param from * @param to */ public void addRoomAsAvailableFromManager(String roomName, ReservationDate from, ReservationDate to) { System.out.println("..................function: addRoomAsAvailableFromManager..............................."); boolean exist = false; for (String key : roomAvailability.keySet()) { if (key.equals(roomName)) { roomAvailability.put(roomName, new ReservationDateRange(from, to)); exist = true; } } if (exist) { System.out.println("The room " + roomName + " successfully inserted as available"); } else { System.out.println("The specific room " + roomName + " does not exist."); } } /** * booking of a room - client function * * @param roomName */ public synchronized void bookingOfRoom(String roomName) { System.out.println("..................function: bookingOfRoom..............................."); boolean booking = false; for (String key : roomAvailability.keySet()) { ReservationDateRange range = roomAvailability.get(key); if (key.equals(roomName)) if (range.isAvailable()) { range.setAvailable(false); booking = true; } } if (booking) { System.out.println("The " + roomName + " is successfully booked."); } else { System.out.println("The " + roomName + " is not available."); } } @Override public String toString() { return "Manager{" + "roomAvailability=" + roomAvailability + '}'; } public static void main(String[] args) { // Default gemisma tou list apo JSON file AccommodationList list = new AccommodationList(Path.of("src/main/java/booking/accommodations.json")); // object // Default gemisma tou map apo JSON file AvailabilityOfAccommodations availabilityOfAccommodations = new AvailabilityOfAccommodations(); // object ReservationDate from = new ReservationDate(20, 4, 2024); ReservationDate to = new ReservationDate(30, 4, 2024); availabilityOfAccommodations.addRoomAsAvailableFromJSON(Path.of("src/main/java/booking/accommodations.json")); // map availabilityOfAccommodations.addRoomAsAvailableFromManager("lala", from, to); // ta typwnei opws akrivws ta exei parei apo to JSON for (String key : availabilityOfAccommodations.getRoomAvailability().keySet()) { System.out.println(key + ": " +availabilityOfAccommodations.getRoomAvailability().get(key)); } // O manager allazei mia hmerominia gia th diathesimotita tou dwmatiou availabilityOfAccommodations.addRoomAsAvailableFromManager("130", from, to); for (String key : availabilityOfAccommodations.getRoomAvailability().keySet()) { System.out.println(key + ": " +availabilityOfAccommodations.getRoomAvailability().get(key)); } // booking of a room availabilityOfAccommodations.bookingOfRoom("235"); availabilityOfAccommodations.bookingOfRoom("500"); } }
7912_7
/* * 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.sphy141.probase.utils; /** * * @author Alan */ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class CryptoUtils { private static final String key = "sphy141groupbuy!"; public static String hashString(String password) { try { // Create an instance of the SHA-256 algorithm MessageDigest digest = MessageDigest.getInstance("SHA-256"); // Convert the password string to bytes byte[] passwordBytes = password.getBytes(); // Calculate the hash value of the password bytes byte[] hashBytes = digest.digest(passwordBytes); // Convert the hash bytes to a hexadecimal string StringBuilder sb = new StringBuilder(); for (byte hashByte : hashBytes) { sb.append(String.format("%02x", hashByte)); } return sb.toString(); } catch (NoSuchAlgorithmException e) { // Handle the exception e.printStackTrace(); } return null; }//hashString /*επειδή ο hash-256 είναι μονόδρομος αλγόριθμος κρυπρογάφισης χρησιμοποιώ τον αλγόριθμο AES προκειμένου να δημιουργήσω μία κρυπτογράφιση για τα δεδομένα της βάσης που είνια ευαίσθητα πχ χρήστη και επιχειρήσεων*/ public static String encrypt(String plainText) { try { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedBytes = cipher.doFinal(plainText.getBytes()); return Base64.getEncoder().encodeToString(encryptedBytes); } catch (Exception e) { e.printStackTrace(); } return null; }//hashAESString public static String decrypt(String encryptedText) { try { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText)); return new String(decryptedBytes); } catch (Exception e) { e.printStackTrace(); } return null; }//hashAESString public static String encryptDouble(double number) { try { String plainText = Double.toString(number); SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedBytes = cipher.doFinal(plainText.getBytes()); return Base64.getEncoder().encodeToString(encryptedBytes); } catch (Exception e) { e.printStackTrace(); } return null; } public static double decryptDouble(String encryptedText) { try { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText)); String decryptedText = new String(decryptedBytes); return Double.parseDouble(decryptedText); } catch (Exception e) { e.printStackTrace(); } return 0.0; } }//class
Alan-III/GroupBuy
groupBuyNetbeans/src/main/java/com/sphy141/probase/utils/CryptoUtils.java
989
/*επειδή ο hash-256 είναι μονόδρομος αλγόριθμος κρυπρογάφισης χρησιμοποιώ τον αλγόριθμο AES προκειμένου να δημιουργήσω μία κρυπτογράφιση για τα δεδομένα της βάσης που είνια ευαίσθητα πχ χρήστη και επιχειρήσεων*/
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 com.sphy141.probase.utils; /** * * @author Alan */ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class CryptoUtils { private static final String key = "sphy141groupbuy!"; public static String hashString(String password) { try { // Create an instance of the SHA-256 algorithm MessageDigest digest = MessageDigest.getInstance("SHA-256"); // Convert the password string to bytes byte[] passwordBytes = password.getBytes(); // Calculate the hash value of the password bytes byte[] hashBytes = digest.digest(passwordBytes); // Convert the hash bytes to a hexadecimal string StringBuilder sb = new StringBuilder(); for (byte hashByte : hashBytes) { sb.append(String.format("%02x", hashByte)); } return sb.toString(); } catch (NoSuchAlgorithmException e) { // Handle the exception e.printStackTrace(); } return null; }//hashString /*επειδή ο hash-256<SUF>*/ public static String encrypt(String plainText) { try { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedBytes = cipher.doFinal(plainText.getBytes()); return Base64.getEncoder().encodeToString(encryptedBytes); } catch (Exception e) { e.printStackTrace(); } return null; }//hashAESString public static String decrypt(String encryptedText) { try { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText)); return new String(decryptedBytes); } catch (Exception e) { e.printStackTrace(); } return null; }//hashAESString public static String encryptDouble(double number) { try { String plainText = Double.toString(number); SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedBytes = cipher.doFinal(plainText.getBytes()); return Base64.getEncoder().encodeToString(encryptedBytes); } catch (Exception e) { e.printStackTrace(); } return null; } public static double decryptDouble(String encryptedText) { try { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText)); String decryptedText = new String(decryptedBytes); return Double.parseDouble(decryptedText); } catch (Exception e) { e.printStackTrace(); } return 0.0; } }//class
5142_0
"import java.time.LocalDate;\r\nimport java.util.ArrayList;\r\nimport java.util.TimerTask;\r\n\r\n/*(...TRUNCATED)
AlexMitsis/LibSoft
src/SystemNotification.java
1,124
"/*Κλάση <SystemNοtifications>\r\nΗ κλάση αυτή αφορά τις ενέργειες (...TRUNCATED)
block_comment
el
"import java.time.LocalDate;\r\nimport java.util.ArrayList;\r\nimport java.util.TimerTask;\r\n\r\n/*(...TRUNCATED)
13673_4
"package gr.aueb.dmst.T21;\nimport java.util.Scanner;\npublic class TestApp {\n static App app = (...TRUNCATED)
Alexandra-Stath/Finding-Spare-Parts-Using-AI
Finding-Spare-Parts-Using-AI/src/main/java/gr/aueb/dmst/T21/TestApp.java
498
// Διαβάζει την αλλαγή γραμμής που παρέμεινε στο buffer
line_comment
el
"package gr.aueb.dmst.T21;\nimport java.util.Scanner;\npublic class TestApp {\n static App app = (...TRUNCATED)
README.md exists but content is empty.
Downloads last month
33