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
8618_2
package com.ihu.e_shopmanager; import android.annotation.SuppressLint; import android.content.res.Configuration; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.Query; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.ihu.e_shopmanager.clients.Client; import com.ihu.e_shopmanager.orders.Order; import com.ihu.e_shopmanager.products.Product; import com.ihu.e_shopmanager.products.ProductWithQuantity; import com.ihu.e_shopmanager.sales.Sale; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class HomeFragment extends Fragment { private final List<Sale> sales = new ArrayList<>(); HashMap<Integer, Client> clientMap = new HashMap<>(); HashMap<Integer, Product> productMap = new HashMap<>(); private CollectionReference salesReference; @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view; int orientation = getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_PORTRAIT) view = inflater.inflate(R.layout.home_fragment, container, false); else view = inflater.inflate(R.layout.home_landscape_fragment, container, false); TextView toolbarText = requireActivity().findViewById(R.id.toolbar_string); toolbarText.setText("Αρχική"); Spinner infoSpinner = view.findViewById(R.id.infoSpinner); ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item); adapter.add("Πωλήσεις στις 08/05/2023"); adapter.add("Πωλήσεις άνω των 2000€"); adapter.add("Πωλήσεις που ολοκληρώθηκαν σε μία μέρα"); adapter.add("Παραγγελίες στις 08/05/2023"); adapter.add("Παραγγελίες άνω των 2000€"); adapter.add("Προϊόντα με απόθεμα άνω των 20"); adapter.add("Προϊόντα στην κατηγορία Laptop"); adapter.add("Πελάτες με Παραγγελίες άνω των 2500€"); adapter.add("Πελάτες που έχουν παραγγείλει κάποιο Desktop"); adapter.add("Παραγγελίες που δεν έχουν όνομα Κώστας"); adapter.add("Παραγγελίες του Λιγκουίνη με αξία άνω των 700€"); infoSpinner.setAdapter(adapter); salesReference = MainActivity.firestoreDatabase.collection("Sales"); infoSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view2, int position, long id) { runQueries(position, view, inflater); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); List<Product> products = MainActivity.myAppDatabase.myDao().getProducts(); for (Product product : products) productMap.put(product.getId(), product); List<Client> clients = MainActivity.myAppDatabase.myDao().getClients(); for (Client client : clients) clientMap.put(client.getId(), client); getSales(view); return view; } @SuppressLint("SetTextI18n") private void getSales(View view) { List<ProductWithQuantity> products = new ArrayList<>(); TextView bestSale = view.findViewById(R.id.bestSale); TextView bestClient = view.findViewById(R.id.bestClient); TextView bestProduct = view.findViewById(R.id.bestProduct); TextView turnover = view.findViewById(R.id.turnover); sales.clear(); salesReference.get().addOnSuccessListener(querySnapshot -> { List<DocumentSnapshot> documents = querySnapshot.getDocuments(); for (DocumentSnapshot document : documents) { if (document.exists()) { List<Map<String, Object>> productList = (List<Map<String, Object>>) document.get("productsList"); for (Map<String, Object> productMap : productList) { Map<String, Object> productFromFirestore = (Map<String, Object>) productMap.get("product"); String category = (String) productFromFirestore.get("category"); int id = ((Long) productFromFirestore.get("id")).intValue(); String name = (String) productFromFirestore.get("name"); float price = ((Double) productFromFirestore.get("price")).floatValue(); int stock = ((Long) productFromFirestore.get("stock")).intValue(); int quantity = ((Long) productMap.get("quantity")).intValue(); Product product = new Product(); product.setName(name); product.setId(id); product.setStock(stock); product.setCategory(category); product.setPrice(price); ProductWithQuantity productWithQuantity = new ProductWithQuantity(); productWithQuantity.setProduct(product); productWithQuantity.setQuantity(quantity); products.add(productWithQuantity); } Sale sale = new Sale(); sale.setProductsList(products); String orderDate, saleDate; int sale_id, client_id; float value; orderDate = document.getString("order_date"); saleDate = document.getString("sale_date"); sale_id = document.getLong("sale_id").intValue(); client_id = document.getLong("client_id").intValue(); value = document.getDouble("value").floatValue(); sale.setSale_id(sale_id); sale.setClient_id(client_id); sale.setValue(value); sale.setOrder_date(orderDate); sale.setSale_date(saleDate); sales.add(sale); } } Map<Integer, Integer> clientSalesCounts = new HashMap<>(); Map<Integer, Integer> productSalesCounts = new HashMap<>(); float totalPrice = 0; for (Sale sale : sales) { int clientId = sale.getClient_id(); for(ProductWithQuantity productWithQuantity : sale.getProductsList()){ Product tempProduct = productWithQuantity.getProduct(); if(productSalesCounts.containsKey(productWithQuantity.getProduct().getId())){ productSalesCounts.put(tempProduct.getId(), productWithQuantity.getQuantity() + productSalesCounts.get(tempProduct.getId())); }else productSalesCounts.put(tempProduct.getId(), productWithQuantity.getQuantity()); } if(clientSalesCounts.containsKey(clientId)) { clientSalesCounts.put(clientId, clientSalesCounts.get(clientId) + 1); }else clientSalesCounts.put(clientId, 1); totalPrice += sale.getValue(); } int maxSalesCount = 0; int clientWithMaxSales = -1; int productWithMaxSales = -1; for (Map.Entry<Integer, Integer> entry : clientSalesCounts.entrySet()) { int clientId = entry.getKey(); int count = entry.getValue(); if (count > maxSalesCount) { maxSalesCount = count; clientWithMaxSales = clientId; } } Client client = clientMap.get(clientWithMaxSales); maxSalesCount = 0; for (Map.Entry<Integer, Integer> entry : productSalesCounts.entrySet()) { int productId = entry.getKey(); int count = entry.getValue(); if (count > maxSalesCount) { maxSalesCount = count; productWithMaxSales = productId; } } Product product = productMap.get(productWithMaxSales); if(client != null && product != null) { bestClient.setText("Καλύτερος Πελάτης: " + client.getName() + " " + client.getLastname()); bestProduct.setText("Δημοφιλέστερο Προϊόν: " + product.getName()); } @SuppressLint("DefaultLocale") String formattedPrice = String.format("%.2f", totalPrice); turnover.setText("Συνολικός Τζίρος: "+ formattedPrice + "€"); }).addOnFailureListener(e -> { Log.d("FireStore ERROR: ", e.getMessage()); }); Query query = salesReference.orderBy("value", Query.Direction.DESCENDING).limit(1); query.get().addOnSuccessListener(queryDocumentSnapshots -> { if(!queryDocumentSnapshots.getDocuments().isEmpty()) { if (queryDocumentSnapshots.getDocuments().get(0).exists()) { DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0); Sale sale = documentSnapshot.toObject(Sale.class); if (sale != null) bestSale.setText("Μεγαλύτερη Πώληση: " + sale.getValue() + "€"); } } }).addOnFailureListener(e -> Toast.makeText(getActivity(),"query operation failed.",Toast.LENGTH_LONG).show()); } @SuppressLint("SetTextI18n") private void runQueries(int position, View view, LayoutInflater inflater) { LinearLayout linearLayout = view.findViewById(R.id.info_linearlayout); TextView info_item = view.findViewById(R.id.info_item); switch (position){ case 0: //Πωλήσεις στις 08/05/2023 Query query1 = salesReference.whereEqualTo("sale_date", "08/05/2023"); linearLayout.removeAllViews(); query1.get().addOnSuccessListener(queryDocumentSnapshots -> { @SuppressLint("InflateParams") View headerView = inflater.inflate(R.layout.order_list_item, null); TextView idTextView = headerView.findViewById(R.id.order_child_id); TextView clientNameTextView = headerView.findViewById(R.id.order_child_client_name); TextView priceTextView = headerView.findViewById(R.id.order_child_total_price); TextView dateTextView = headerView.findViewById(R.id.order_child_date); idTextView.setText("ID"); clientNameTextView.setText("Πελάτης"); priceTextView.setText("Αξία"); dateTextView.setText("Ημ/νια Πώλησεις"); linearLayout.addView(headerView); for(QueryDocumentSnapshot documentSnapshot: queryDocumentSnapshots){ Sale sale = documentSnapshot.toObject(Sale.class); @SuppressLint("InflateParams") View saleView = inflater.inflate(R.layout.order_list_item, null); idTextView = saleView.findViewById(R.id.order_child_id); clientNameTextView = saleView.findViewById(R.id.order_child_client_name); priceTextView = saleView.findViewById(R.id.order_child_total_price); dateTextView = saleView.findViewById(R.id.order_child_date); idTextView.setText(String.valueOf(sale.getSale_id())); Client client = clientMap.get(sale.getClient_id()); assert client != null; clientNameTextView.setText(client.getName() + " " + client.getLastname()); @SuppressLint("DefaultLocale") String formattedPrice = String.format("%.2f", sale.getValue()); priceTextView.setText(formattedPrice + "€"); dateTextView.setText(String.valueOf(sale.getSale_date())); linearLayout.addView(saleView); } }).addOnFailureListener(e -> Toast.makeText(getActivity(),"Query operation failed.",Toast.LENGTH_LONG).show()); break; case 1: //Πωλήσεις άνω των 2000€ Query query2 = salesReference.whereGreaterThan("value", 2000); linearLayout.removeAllViews(); query2.get().addOnSuccessListener(queryDocumentSnapshots -> { @SuppressLint("InflateParams") View headerView = inflater.inflate(R.layout.order_list_item, null); TextView idTextView = headerView.findViewById(R.id.order_child_id); TextView clientNameTextView = headerView.findViewById(R.id.order_child_client_name); TextView priceTextView = headerView.findViewById(R.id.order_child_total_price); TextView dateTextView = headerView.findViewById(R.id.order_child_date); idTextView.setText("ID"); clientNameTextView.setText("Πελάτης"); priceTextView.setText("Αξία"); dateTextView.setText("Ημ/νια Πώλησης"); linearLayout.addView(headerView); for(QueryDocumentSnapshot documentSnapshot: queryDocumentSnapshots){ Sale sale = documentSnapshot.toObject(Sale.class); @SuppressLint("InflateParams") View saleView = inflater.inflate(R.layout.order_list_item, null); idTextView = saleView.findViewById(R.id.order_child_id); clientNameTextView = saleView.findViewById(R.id.order_child_client_name); priceTextView = saleView.findViewById(R.id.order_child_total_price); dateTextView = saleView.findViewById(R.id.order_child_date); idTextView.setText(String.valueOf(sale.getSale_id())); Client client = clientMap.get(sale.getClient_id()); assert client != null; clientNameTextView.setText(client.getName() + " " + client.getLastname()); @SuppressLint("DefaultLocale") String formattedPrice = String.format("%.2f", sale.getValue()); priceTextView.setText(formattedPrice + "€"); dateTextView.setText(String.valueOf(sale.getSale_date())); linearLayout.addView(saleView); } }).addOnFailureListener(e -> Toast.makeText(getActivity(),"query operation failed.",Toast.LENGTH_LONG).show()); break; case 2: //Πωλήσεις που ολοκληρώθηκαν σε μία μέρα boolean hasOneDayDifference; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); linearLayout.removeAllViews(); View headerView = inflater.inflate(R.layout.home_date_item, null); TextView idTextView = headerView.findViewById(R.id.home_child_id); TextView clientNameTextView = headerView.findViewById(R.id.home_child_client_name); TextView orderDateTextView = headerView.findViewById(R.id.home_child_order_date); TextView saleDateTextView = headerView.findViewById(R.id.home_child_sale_date); idTextView.setText("ID"); clientNameTextView.setText("Πελάτης"); orderDateTextView.setText("Ημ/νια Παραγγελίας"); saleDateTextView.setText("Ημ/νια Πώλησης"); linearLayout.addView(headerView); for(Sale sale : sales) { LocalDate orderDate = LocalDate.parse(sale.getOrder_date(), formatter); LocalDate saleDate = LocalDate.parse(sale.getSale_date(), formatter); hasOneDayDifference = orderDate.plusDays(1).isEqual(saleDate); if(hasOneDayDifference){ View saleView = inflater.inflate(R.layout.home_date_item, null); idTextView = saleView.findViewById(R.id.home_child_id); clientNameTextView = saleView.findViewById(R.id.home_child_client_name); orderDateTextView = saleView.findViewById(R.id.home_child_order_date); saleDateTextView = saleView.findViewById(R.id.home_child_sale_date); idTextView.setText(String.valueOf(sale.getSale_id())); Client client = clientMap.get(sale.getClient_id()); clientNameTextView.setText(client.getName() + " " + client.getLastname()); orderDateTextView.setText(sale.getOrder_date()); saleDateTextView.setText(sale.getSale_date()); linearLayout.addView(saleView); } } break; case 3: //Παραγγελίες που έγιναν 08/05/2023 List<Order> ordersQuery = MainActivity.myAppDatabase.myDao().getQuery3(); linearLayout.removeAllViews(); View headerView3 = inflater.inflate(R.layout.order_list_item, null); TextView idTextView3 = headerView3.findViewById(R.id.order_child_id); TextView clientNameTextView3 = headerView3.findViewById(R.id.order_child_client_name); TextView priceTextView3 = headerView3.findViewById(R.id.order_child_total_price); TextView dateTextView3 = headerView3.findViewById(R.id.order_child_date); idTextView3.setText("ID"); clientNameTextView3.setText("Πελάτης"); priceTextView3.setText("Αξία"); dateTextView3.setText("Ημ/νια Πώλησης"); linearLayout.addView(headerView3); for(Order order : ordersQuery){ View orderView = inflater.inflate(R.layout.order_list_item, null); idTextView3 = orderView.findViewById(R.id.order_child_id); clientNameTextView3 = orderView.findViewById(R.id.order_child_client_name); priceTextView3 = orderView.findViewById(R.id.order_child_total_price); dateTextView3 = orderView.findViewById(R.id.order_child_date); idTextView3.setText(String.valueOf(order.getId())); Client client = clientMap.get(order.getClientId()); clientNameTextView3.setText(client.getName() + " " + client.getLastname()); String formattedPrice = String.format("%.2f", order.getTotalPrice()); priceTextView3.setText(formattedPrice + "€"); dateTextView3.setText(String.valueOf(order.getOrderDate())); linearLayout.addView(orderView); } break; case 4: //Παραγγελίες άνω των 2000 List<Order> ordersQuery4 = MainActivity.myAppDatabase.myDao().getQuery4(); linearLayout.removeAllViews(); View headerView4 = inflater.inflate(R.layout.order_list_item, null); TextView idTextView4 = headerView4.findViewById(R.id.order_child_id); TextView clientNameTextView4 = headerView4.findViewById(R.id.order_child_client_name); TextView priceTextView4 = headerView4.findViewById(R.id.order_child_total_price); TextView dateTextView4 = headerView4.findViewById(R.id.order_child_date); idTextView4.setText("ID"); clientNameTextView4.setText("Πελάτης"); priceTextView4.setText("Αξία"); dateTextView4.setText("Ημ/νια Πώλησης"); linearLayout.addView(headerView4); for(Order order : ordersQuery4){ View orderView = inflater.inflate(R.layout.order_list_item, null); idTextView4 = orderView.findViewById(R.id.order_child_id); clientNameTextView4 = orderView.findViewById(R.id.order_child_client_name); priceTextView4 = orderView.findViewById(R.id.order_child_total_price); dateTextView4 = orderView.findViewById(R.id.order_child_date); idTextView4.setText(String.valueOf(order.getId())); Client client = clientMap.get(order.getClientId()); clientNameTextView4.setText(client.getName() + " " + client.getLastname()); String formattedPrice = String.format("%.2f", order.getTotalPrice()); priceTextView4.setText(formattedPrice + "€"); dateTextView4.setText(String.valueOf(order.getOrderDate())); linearLayout.addView(orderView); } break; case 5: //Προϊόντα με απόθεμα άνω των 20 List<Product> productsQuery5 = MainActivity.myAppDatabase.myDao().getQuery5(); linearLayout.removeAllViews(); View headerView5 = inflater.inflate(R.layout.product_item, null); TextView idTextView5 = headerView5.findViewById(R.id.product_child_id); TextView nameTextView5 = headerView5.findViewById(R.id.product_child_name); TextView categoryTextView5 = headerView5.findViewById(R.id.product_child_category); TextView stockTextView5 = headerView5.findViewById(R.id.product_child_stock); TextView priceTextView5 = headerView5.findViewById(R.id.product_child_price); idTextView5.setText("ID"); nameTextView5.setText("Όνομα Προϊόντος"); categoryTextView5.setText("Κατηγορία"); stockTextView5.setText("Stock"); priceTextView5.setText("Αξία"); linearLayout.addView(headerView5); for(Product product : productsQuery5){ View productView = inflater.inflate(R.layout.product_item, null); idTextView5 = productView.findViewById(R.id.product_child_id); nameTextView5 = productView.findViewById(R.id.product_child_name); categoryTextView5 = productView.findViewById(R.id.product_child_category); stockTextView5 = productView.findViewById(R.id.product_child_stock); priceTextView5 = productView.findViewById(R.id.product_child_price); idTextView5.setText(String.valueOf(product.getId())); nameTextView5.setText(product.getName()); categoryTextView5.setText(product.getCategory()); stockTextView5.setText(String.valueOf(product.getStock())); priceTextView5.setText(product.getPrice() + "€"); linearLayout.addView(productView); } break; case 6: //Προϊόντα στην κατηγορία Laptop List<Product> productsQuery6 = MainActivity.myAppDatabase.myDao().getQuery6(); linearLayout.removeAllViews(); View headerView6 = inflater.inflate(R.layout.product_item, null); TextView idTextView6 = headerView6.findViewById(R.id.product_child_id); TextView nameTextView6 = headerView6.findViewById(R.id.product_child_name); TextView categoryTextView6 = headerView6.findViewById(R.id.product_child_category); TextView stockTextView6 = headerView6.findViewById(R.id.product_child_stock); TextView priceTextView6 = headerView6.findViewById(R.id.product_child_price); idTextView6.setText("ID"); nameTextView6.setText("Όνομα Προϊόντος"); categoryTextView6.setText("Κατηγορία"); stockTextView6.setText("Stock"); priceTextView6.setText("Αξία"); linearLayout.addView(headerView6); for(Product product : productsQuery6){ View productView = inflater.inflate(R.layout.product_item, null); idTextView6 = productView.findViewById(R.id.product_child_id); nameTextView6 = productView.findViewById(R.id.product_child_name); categoryTextView6 = productView.findViewById(R.id.product_child_category); stockTextView6 = productView.findViewById(R.id.product_child_stock); priceTextView6 = productView.findViewById(R.id.product_child_price); idTextView6.setText(String.valueOf(product.getId())); nameTextView6.setText(product.getName()); categoryTextView6.setText(product.getCategory()); stockTextView6.setText(String.valueOf(product.getStock())); priceTextView6.setText(product.getPrice() + "€"); linearLayout.addView(productView); } break; case 7: //Πελάτες με παραγγελίες άνω των 2500 List<Client> clientsQuery7 = MainActivity.myAppDatabase.myDao().getQuery7(); linearLayout.removeAllViews(); View headerView7 = inflater.inflate(R.layout.client_item, null); TextView idTextView7 = headerView7.findViewById(R.id.client_child_id); TextView nameTextView7 = headerView7.findViewById(R.id.client_child_name); TextView lastNameTextView7 = headerView7.findViewById(R.id.client_child_lastname); TextView phoneTextView7 = headerView7.findViewById(R.id.client_child_phone_number); TextView registrationTextView7 = headerView7.findViewById(R.id.client_child_registration_date); idTextView7.setText("ID"); nameTextView7.setText("Όνομα"); lastNameTextView7.setText("Επίθετο"); phoneTextView7.setText("Κινητό"); registrationTextView7.setText("Ημ/νία Εγγραφής"); linearLayout.addView(headerView7); for (Client client : clientsQuery7) { View clientView = inflater.inflate(R.layout.client_item, null); idTextView7 = clientView.findViewById(R.id.client_child_id); nameTextView7 = clientView.findViewById(R.id.client_child_name); lastNameTextView7 = clientView.findViewById(R.id.client_child_lastname); phoneTextView7 = clientView.findViewById(R.id.client_child_phone_number); registrationTextView7 = clientView.findViewById(R.id.client_child_registration_date); idTextView7.setText(String.valueOf(client.getId())); nameTextView7.setText(client.getName()); lastNameTextView7.setText(client.getLastname()); phoneTextView7.setText(String.valueOf(client.getPhone_number())); registrationTextView7.setText(client.getRegisteration_date()); linearLayout.addView(clientView); } break; case 8: List<Order> orderQuery8 = MainActivity.myAppDatabase.myDao().getOrders(); List<ProductWithQuantity> query8Products; linearLayout.removeAllViews(); View headerView8 = inflater.inflate(R.layout.client_item, null); TextView idTextView8 = headerView8.findViewById(R.id.client_child_id); TextView nameTextView8 = headerView8.findViewById(R.id.client_child_name); TextView lastNameTextView8 = headerView8.findViewById(R.id.client_child_lastname); TextView phoneTextView8 = headerView8.findViewById(R.id.client_child_phone_number); TextView registrationTextView8 = headerView8.findViewById(R.id.client_child_registration_date); idTextView8.setText("ID"); nameTextView8.setText("Όνομα"); lastNameTextView8.setText("Επίθετο"); phoneTextView8.setText("Κινητό"); registrationTextView8.setText("Ημ/νία Εγγραφής"); linearLayout.addView(headerView8); Set<Integer> clientsWithDesktop = new HashSet<>(); for(Order order : orderQuery8){ query8Products = order.getProducts(); Client client = clientMap.get(order.getClientId()); assert client != null; if(!clientsWithDesktop.contains(client.getId())){ for(ProductWithQuantity productWithQuantity: query8Products){ Product product = productWithQuantity.getProduct(); if(product.getCategory().equals("Desktop")) { View clientView = inflater.inflate(R.layout.client_item, null); idTextView8 = clientView.findViewById(R.id.client_child_id); nameTextView8 = clientView.findViewById(R.id.client_child_name); lastNameTextView8 = clientView.findViewById(R.id.client_child_lastname); phoneTextView8 = clientView.findViewById(R.id.client_child_phone_number); registrationTextView8 = clientView.findViewById(R.id.client_child_registration_date); idTextView8.setText(String.valueOf(client.getId())); nameTextView8.setText(client.getName()); lastNameTextView8.setText(client.getLastname()); phoneTextView8.setText(String.valueOf(client.getPhone_number())); registrationTextView8.setText(client.getRegisteration_date()); linearLayout.addView(clientView); clientsWithDesktop.add(client.getId()); } } } } break; case 9: List<Order> orderQuery9 = MainActivity.myAppDatabase.myDao().getQuery8(); linearLayout.removeAllViews(); View headerView9 = inflater.inflate(R.layout.order_list_item, null); TextView idTextView9 = headerView9.findViewById(R.id.order_child_id); TextView clientNameTextView9 = headerView9.findViewById(R.id.order_child_client_name); TextView priceTextView9 = headerView9.findViewById(R.id.order_child_total_price); TextView dateTextView9 = headerView9.findViewById(R.id.order_child_date); idTextView9.setText("ID"); clientNameTextView9.setText("Πελάτης"); priceTextView9.setText("Αξία"); dateTextView9.setText("Ημ/νια Πώλησης"); linearLayout.addView(headerView9); for(Order order : orderQuery9){ Client client = MainActivity.myAppDatabase.myDao().getClientFromId(order.getClientId()); assert client != null; View orderView = inflater.inflate(R.layout.order_list_item, null); idTextView3 = orderView.findViewById(R.id.order_child_id); clientNameTextView3 = orderView.findViewById(R.id.order_child_client_name); priceTextView3 = orderView.findViewById(R.id.order_child_total_price); dateTextView3 = orderView.findViewById(R.id.order_child_date); idTextView3.setText(String.valueOf(order.getId())); clientNameTextView3.setText(client.getName() + " " + client.getLastname()); String formattedPrice = String.format("%.2f", order.getTotalPrice()); priceTextView3.setText(formattedPrice + "€"); dateTextView3.setText(String.valueOf(order.getOrderDate())); linearLayout.addView(orderView); } break; } } }
jdoulke/E-Shop_Manager
app/src/main/java/com/ihu/e_shopmanager/HomeFragment.java
7,704
//Πωλήσεις που ολοκληρώθηκαν σε μία μέρα
line_comment
el
package com.ihu.e_shopmanager; import android.annotation.SuppressLint; import android.content.res.Configuration; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.Query; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.ihu.e_shopmanager.clients.Client; import com.ihu.e_shopmanager.orders.Order; import com.ihu.e_shopmanager.products.Product; import com.ihu.e_shopmanager.products.ProductWithQuantity; import com.ihu.e_shopmanager.sales.Sale; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class HomeFragment extends Fragment { private final List<Sale> sales = new ArrayList<>(); HashMap<Integer, Client> clientMap = new HashMap<>(); HashMap<Integer, Product> productMap = new HashMap<>(); private CollectionReference salesReference; @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view; int orientation = getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_PORTRAIT) view = inflater.inflate(R.layout.home_fragment, container, false); else view = inflater.inflate(R.layout.home_landscape_fragment, container, false); TextView toolbarText = requireActivity().findViewById(R.id.toolbar_string); toolbarText.setText("Αρχική"); Spinner infoSpinner = view.findViewById(R.id.infoSpinner); ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item); adapter.add("Πωλήσεις στις 08/05/2023"); adapter.add("Πωλήσεις άνω των 2000€"); adapter.add("Πωλήσεις που ολοκληρώθηκαν σε μία μέρα"); adapter.add("Παραγγελίες στις 08/05/2023"); adapter.add("Παραγγελίες άνω των 2000€"); adapter.add("Προϊόντα με απόθεμα άνω των 20"); adapter.add("Προϊόντα στην κατηγορία Laptop"); adapter.add("Πελάτες με Παραγγελίες άνω των 2500€"); adapter.add("Πελάτες που έχουν παραγγείλει κάποιο Desktop"); adapter.add("Παραγγελίες που δεν έχουν όνομα Κώστας"); adapter.add("Παραγγελίες του Λιγκουίνη με αξία άνω των 700€"); infoSpinner.setAdapter(adapter); salesReference = MainActivity.firestoreDatabase.collection("Sales"); infoSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view2, int position, long id) { runQueries(position, view, inflater); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); List<Product> products = MainActivity.myAppDatabase.myDao().getProducts(); for (Product product : products) productMap.put(product.getId(), product); List<Client> clients = MainActivity.myAppDatabase.myDao().getClients(); for (Client client : clients) clientMap.put(client.getId(), client); getSales(view); return view; } @SuppressLint("SetTextI18n") private void getSales(View view) { List<ProductWithQuantity> products = new ArrayList<>(); TextView bestSale = view.findViewById(R.id.bestSale); TextView bestClient = view.findViewById(R.id.bestClient); TextView bestProduct = view.findViewById(R.id.bestProduct); TextView turnover = view.findViewById(R.id.turnover); sales.clear(); salesReference.get().addOnSuccessListener(querySnapshot -> { List<DocumentSnapshot> documents = querySnapshot.getDocuments(); for (DocumentSnapshot document : documents) { if (document.exists()) { List<Map<String, Object>> productList = (List<Map<String, Object>>) document.get("productsList"); for (Map<String, Object> productMap : productList) { Map<String, Object> productFromFirestore = (Map<String, Object>) productMap.get("product"); String category = (String) productFromFirestore.get("category"); int id = ((Long) productFromFirestore.get("id")).intValue(); String name = (String) productFromFirestore.get("name"); float price = ((Double) productFromFirestore.get("price")).floatValue(); int stock = ((Long) productFromFirestore.get("stock")).intValue(); int quantity = ((Long) productMap.get("quantity")).intValue(); Product product = new Product(); product.setName(name); product.setId(id); product.setStock(stock); product.setCategory(category); product.setPrice(price); ProductWithQuantity productWithQuantity = new ProductWithQuantity(); productWithQuantity.setProduct(product); productWithQuantity.setQuantity(quantity); products.add(productWithQuantity); } Sale sale = new Sale(); sale.setProductsList(products); String orderDate, saleDate; int sale_id, client_id; float value; orderDate = document.getString("order_date"); saleDate = document.getString("sale_date"); sale_id = document.getLong("sale_id").intValue(); client_id = document.getLong("client_id").intValue(); value = document.getDouble("value").floatValue(); sale.setSale_id(sale_id); sale.setClient_id(client_id); sale.setValue(value); sale.setOrder_date(orderDate); sale.setSale_date(saleDate); sales.add(sale); } } Map<Integer, Integer> clientSalesCounts = new HashMap<>(); Map<Integer, Integer> productSalesCounts = new HashMap<>(); float totalPrice = 0; for (Sale sale : sales) { int clientId = sale.getClient_id(); for(ProductWithQuantity productWithQuantity : sale.getProductsList()){ Product tempProduct = productWithQuantity.getProduct(); if(productSalesCounts.containsKey(productWithQuantity.getProduct().getId())){ productSalesCounts.put(tempProduct.getId(), productWithQuantity.getQuantity() + productSalesCounts.get(tempProduct.getId())); }else productSalesCounts.put(tempProduct.getId(), productWithQuantity.getQuantity()); } if(clientSalesCounts.containsKey(clientId)) { clientSalesCounts.put(clientId, clientSalesCounts.get(clientId) + 1); }else clientSalesCounts.put(clientId, 1); totalPrice += sale.getValue(); } int maxSalesCount = 0; int clientWithMaxSales = -1; int productWithMaxSales = -1; for (Map.Entry<Integer, Integer> entry : clientSalesCounts.entrySet()) { int clientId = entry.getKey(); int count = entry.getValue(); if (count > maxSalesCount) { maxSalesCount = count; clientWithMaxSales = clientId; } } Client client = clientMap.get(clientWithMaxSales); maxSalesCount = 0; for (Map.Entry<Integer, Integer> entry : productSalesCounts.entrySet()) { int productId = entry.getKey(); int count = entry.getValue(); if (count > maxSalesCount) { maxSalesCount = count; productWithMaxSales = productId; } } Product product = productMap.get(productWithMaxSales); if(client != null && product != null) { bestClient.setText("Καλύτερος Πελάτης: " + client.getName() + " " + client.getLastname()); bestProduct.setText("Δημοφιλέστερο Προϊόν: " + product.getName()); } @SuppressLint("DefaultLocale") String formattedPrice = String.format("%.2f", totalPrice); turnover.setText("Συνολικός Τζίρος: "+ formattedPrice + "€"); }).addOnFailureListener(e -> { Log.d("FireStore ERROR: ", e.getMessage()); }); Query query = salesReference.orderBy("value", Query.Direction.DESCENDING).limit(1); query.get().addOnSuccessListener(queryDocumentSnapshots -> { if(!queryDocumentSnapshots.getDocuments().isEmpty()) { if (queryDocumentSnapshots.getDocuments().get(0).exists()) { DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0); Sale sale = documentSnapshot.toObject(Sale.class); if (sale != null) bestSale.setText("Μεγαλύτερη Πώληση: " + sale.getValue() + "€"); } } }).addOnFailureListener(e -> Toast.makeText(getActivity(),"query operation failed.",Toast.LENGTH_LONG).show()); } @SuppressLint("SetTextI18n") private void runQueries(int position, View view, LayoutInflater inflater) { LinearLayout linearLayout = view.findViewById(R.id.info_linearlayout); TextView info_item = view.findViewById(R.id.info_item); switch (position){ case 0: //Πωλήσεις στις 08/05/2023 Query query1 = salesReference.whereEqualTo("sale_date", "08/05/2023"); linearLayout.removeAllViews(); query1.get().addOnSuccessListener(queryDocumentSnapshots -> { @SuppressLint("InflateParams") View headerView = inflater.inflate(R.layout.order_list_item, null); TextView idTextView = headerView.findViewById(R.id.order_child_id); TextView clientNameTextView = headerView.findViewById(R.id.order_child_client_name); TextView priceTextView = headerView.findViewById(R.id.order_child_total_price); TextView dateTextView = headerView.findViewById(R.id.order_child_date); idTextView.setText("ID"); clientNameTextView.setText("Πελάτης"); priceTextView.setText("Αξία"); dateTextView.setText("Ημ/νια Πώλησεις"); linearLayout.addView(headerView); for(QueryDocumentSnapshot documentSnapshot: queryDocumentSnapshots){ Sale sale = documentSnapshot.toObject(Sale.class); @SuppressLint("InflateParams") View saleView = inflater.inflate(R.layout.order_list_item, null); idTextView = saleView.findViewById(R.id.order_child_id); clientNameTextView = saleView.findViewById(R.id.order_child_client_name); priceTextView = saleView.findViewById(R.id.order_child_total_price); dateTextView = saleView.findViewById(R.id.order_child_date); idTextView.setText(String.valueOf(sale.getSale_id())); Client client = clientMap.get(sale.getClient_id()); assert client != null; clientNameTextView.setText(client.getName() + " " + client.getLastname()); @SuppressLint("DefaultLocale") String formattedPrice = String.format("%.2f", sale.getValue()); priceTextView.setText(formattedPrice + "€"); dateTextView.setText(String.valueOf(sale.getSale_date())); linearLayout.addView(saleView); } }).addOnFailureListener(e -> Toast.makeText(getActivity(),"Query operation failed.",Toast.LENGTH_LONG).show()); break; case 1: //Πωλήσεις άνω των 2000€ Query query2 = salesReference.whereGreaterThan("value", 2000); linearLayout.removeAllViews(); query2.get().addOnSuccessListener(queryDocumentSnapshots -> { @SuppressLint("InflateParams") View headerView = inflater.inflate(R.layout.order_list_item, null); TextView idTextView = headerView.findViewById(R.id.order_child_id); TextView clientNameTextView = headerView.findViewById(R.id.order_child_client_name); TextView priceTextView = headerView.findViewById(R.id.order_child_total_price); TextView dateTextView = headerView.findViewById(R.id.order_child_date); idTextView.setText("ID"); clientNameTextView.setText("Πελάτης"); priceTextView.setText("Αξία"); dateTextView.setText("Ημ/νια Πώλησης"); linearLayout.addView(headerView); for(QueryDocumentSnapshot documentSnapshot: queryDocumentSnapshots){ Sale sale = documentSnapshot.toObject(Sale.class); @SuppressLint("InflateParams") View saleView = inflater.inflate(R.layout.order_list_item, null); idTextView = saleView.findViewById(R.id.order_child_id); clientNameTextView = saleView.findViewById(R.id.order_child_client_name); priceTextView = saleView.findViewById(R.id.order_child_total_price); dateTextView = saleView.findViewById(R.id.order_child_date); idTextView.setText(String.valueOf(sale.getSale_id())); Client client = clientMap.get(sale.getClient_id()); assert client != null; clientNameTextView.setText(client.getName() + " " + client.getLastname()); @SuppressLint("DefaultLocale") String formattedPrice = String.format("%.2f", sale.getValue()); priceTextView.setText(formattedPrice + "€"); dateTextView.setText(String.valueOf(sale.getSale_date())); linearLayout.addView(saleView); } }).addOnFailureListener(e -> Toast.makeText(getActivity(),"query operation failed.",Toast.LENGTH_LONG).show()); break; case 2: //Πωλήσεις που<SUF> boolean hasOneDayDifference; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); linearLayout.removeAllViews(); View headerView = inflater.inflate(R.layout.home_date_item, null); TextView idTextView = headerView.findViewById(R.id.home_child_id); TextView clientNameTextView = headerView.findViewById(R.id.home_child_client_name); TextView orderDateTextView = headerView.findViewById(R.id.home_child_order_date); TextView saleDateTextView = headerView.findViewById(R.id.home_child_sale_date); idTextView.setText("ID"); clientNameTextView.setText("Πελάτης"); orderDateTextView.setText("Ημ/νια Παραγγελίας"); saleDateTextView.setText("Ημ/νια Πώλησης"); linearLayout.addView(headerView); for(Sale sale : sales) { LocalDate orderDate = LocalDate.parse(sale.getOrder_date(), formatter); LocalDate saleDate = LocalDate.parse(sale.getSale_date(), formatter); hasOneDayDifference = orderDate.plusDays(1).isEqual(saleDate); if(hasOneDayDifference){ View saleView = inflater.inflate(R.layout.home_date_item, null); idTextView = saleView.findViewById(R.id.home_child_id); clientNameTextView = saleView.findViewById(R.id.home_child_client_name); orderDateTextView = saleView.findViewById(R.id.home_child_order_date); saleDateTextView = saleView.findViewById(R.id.home_child_sale_date); idTextView.setText(String.valueOf(sale.getSale_id())); Client client = clientMap.get(sale.getClient_id()); clientNameTextView.setText(client.getName() + " " + client.getLastname()); orderDateTextView.setText(sale.getOrder_date()); saleDateTextView.setText(sale.getSale_date()); linearLayout.addView(saleView); } } break; case 3: //Παραγγελίες που έγιναν 08/05/2023 List<Order> ordersQuery = MainActivity.myAppDatabase.myDao().getQuery3(); linearLayout.removeAllViews(); View headerView3 = inflater.inflate(R.layout.order_list_item, null); TextView idTextView3 = headerView3.findViewById(R.id.order_child_id); TextView clientNameTextView3 = headerView3.findViewById(R.id.order_child_client_name); TextView priceTextView3 = headerView3.findViewById(R.id.order_child_total_price); TextView dateTextView3 = headerView3.findViewById(R.id.order_child_date); idTextView3.setText("ID"); clientNameTextView3.setText("Πελάτης"); priceTextView3.setText("Αξία"); dateTextView3.setText("Ημ/νια Πώλησης"); linearLayout.addView(headerView3); for(Order order : ordersQuery){ View orderView = inflater.inflate(R.layout.order_list_item, null); idTextView3 = orderView.findViewById(R.id.order_child_id); clientNameTextView3 = orderView.findViewById(R.id.order_child_client_name); priceTextView3 = orderView.findViewById(R.id.order_child_total_price); dateTextView3 = orderView.findViewById(R.id.order_child_date); idTextView3.setText(String.valueOf(order.getId())); Client client = clientMap.get(order.getClientId()); clientNameTextView3.setText(client.getName() + " " + client.getLastname()); String formattedPrice = String.format("%.2f", order.getTotalPrice()); priceTextView3.setText(formattedPrice + "€"); dateTextView3.setText(String.valueOf(order.getOrderDate())); linearLayout.addView(orderView); } break; case 4: //Παραγγελίες άνω των 2000 List<Order> ordersQuery4 = MainActivity.myAppDatabase.myDao().getQuery4(); linearLayout.removeAllViews(); View headerView4 = inflater.inflate(R.layout.order_list_item, null); TextView idTextView4 = headerView4.findViewById(R.id.order_child_id); TextView clientNameTextView4 = headerView4.findViewById(R.id.order_child_client_name); TextView priceTextView4 = headerView4.findViewById(R.id.order_child_total_price); TextView dateTextView4 = headerView4.findViewById(R.id.order_child_date); idTextView4.setText("ID"); clientNameTextView4.setText("Πελάτης"); priceTextView4.setText("Αξία"); dateTextView4.setText("Ημ/νια Πώλησης"); linearLayout.addView(headerView4); for(Order order : ordersQuery4){ View orderView = inflater.inflate(R.layout.order_list_item, null); idTextView4 = orderView.findViewById(R.id.order_child_id); clientNameTextView4 = orderView.findViewById(R.id.order_child_client_name); priceTextView4 = orderView.findViewById(R.id.order_child_total_price); dateTextView4 = orderView.findViewById(R.id.order_child_date); idTextView4.setText(String.valueOf(order.getId())); Client client = clientMap.get(order.getClientId()); clientNameTextView4.setText(client.getName() + " " + client.getLastname()); String formattedPrice = String.format("%.2f", order.getTotalPrice()); priceTextView4.setText(formattedPrice + "€"); dateTextView4.setText(String.valueOf(order.getOrderDate())); linearLayout.addView(orderView); } break; case 5: //Προϊόντα με απόθεμα άνω των 20 List<Product> productsQuery5 = MainActivity.myAppDatabase.myDao().getQuery5(); linearLayout.removeAllViews(); View headerView5 = inflater.inflate(R.layout.product_item, null); TextView idTextView5 = headerView5.findViewById(R.id.product_child_id); TextView nameTextView5 = headerView5.findViewById(R.id.product_child_name); TextView categoryTextView5 = headerView5.findViewById(R.id.product_child_category); TextView stockTextView5 = headerView5.findViewById(R.id.product_child_stock); TextView priceTextView5 = headerView5.findViewById(R.id.product_child_price); idTextView5.setText("ID"); nameTextView5.setText("Όνομα Προϊόντος"); categoryTextView5.setText("Κατηγορία"); stockTextView5.setText("Stock"); priceTextView5.setText("Αξία"); linearLayout.addView(headerView5); for(Product product : productsQuery5){ View productView = inflater.inflate(R.layout.product_item, null); idTextView5 = productView.findViewById(R.id.product_child_id); nameTextView5 = productView.findViewById(R.id.product_child_name); categoryTextView5 = productView.findViewById(R.id.product_child_category); stockTextView5 = productView.findViewById(R.id.product_child_stock); priceTextView5 = productView.findViewById(R.id.product_child_price); idTextView5.setText(String.valueOf(product.getId())); nameTextView5.setText(product.getName()); categoryTextView5.setText(product.getCategory()); stockTextView5.setText(String.valueOf(product.getStock())); priceTextView5.setText(product.getPrice() + "€"); linearLayout.addView(productView); } break; case 6: //Προϊόντα στην κατηγορία Laptop List<Product> productsQuery6 = MainActivity.myAppDatabase.myDao().getQuery6(); linearLayout.removeAllViews(); View headerView6 = inflater.inflate(R.layout.product_item, null); TextView idTextView6 = headerView6.findViewById(R.id.product_child_id); TextView nameTextView6 = headerView6.findViewById(R.id.product_child_name); TextView categoryTextView6 = headerView6.findViewById(R.id.product_child_category); TextView stockTextView6 = headerView6.findViewById(R.id.product_child_stock); TextView priceTextView6 = headerView6.findViewById(R.id.product_child_price); idTextView6.setText("ID"); nameTextView6.setText("Όνομα Προϊόντος"); categoryTextView6.setText("Κατηγορία"); stockTextView6.setText("Stock"); priceTextView6.setText("Αξία"); linearLayout.addView(headerView6); for(Product product : productsQuery6){ View productView = inflater.inflate(R.layout.product_item, null); idTextView6 = productView.findViewById(R.id.product_child_id); nameTextView6 = productView.findViewById(R.id.product_child_name); categoryTextView6 = productView.findViewById(R.id.product_child_category); stockTextView6 = productView.findViewById(R.id.product_child_stock); priceTextView6 = productView.findViewById(R.id.product_child_price); idTextView6.setText(String.valueOf(product.getId())); nameTextView6.setText(product.getName()); categoryTextView6.setText(product.getCategory()); stockTextView6.setText(String.valueOf(product.getStock())); priceTextView6.setText(product.getPrice() + "€"); linearLayout.addView(productView); } break; case 7: //Πελάτες με παραγγελίες άνω των 2500 List<Client> clientsQuery7 = MainActivity.myAppDatabase.myDao().getQuery7(); linearLayout.removeAllViews(); View headerView7 = inflater.inflate(R.layout.client_item, null); TextView idTextView7 = headerView7.findViewById(R.id.client_child_id); TextView nameTextView7 = headerView7.findViewById(R.id.client_child_name); TextView lastNameTextView7 = headerView7.findViewById(R.id.client_child_lastname); TextView phoneTextView7 = headerView7.findViewById(R.id.client_child_phone_number); TextView registrationTextView7 = headerView7.findViewById(R.id.client_child_registration_date); idTextView7.setText("ID"); nameTextView7.setText("Όνομα"); lastNameTextView7.setText("Επίθετο"); phoneTextView7.setText("Κινητό"); registrationTextView7.setText("Ημ/νία Εγγραφής"); linearLayout.addView(headerView7); for (Client client : clientsQuery7) { View clientView = inflater.inflate(R.layout.client_item, null); idTextView7 = clientView.findViewById(R.id.client_child_id); nameTextView7 = clientView.findViewById(R.id.client_child_name); lastNameTextView7 = clientView.findViewById(R.id.client_child_lastname); phoneTextView7 = clientView.findViewById(R.id.client_child_phone_number); registrationTextView7 = clientView.findViewById(R.id.client_child_registration_date); idTextView7.setText(String.valueOf(client.getId())); nameTextView7.setText(client.getName()); lastNameTextView7.setText(client.getLastname()); phoneTextView7.setText(String.valueOf(client.getPhone_number())); registrationTextView7.setText(client.getRegisteration_date()); linearLayout.addView(clientView); } break; case 8: List<Order> orderQuery8 = MainActivity.myAppDatabase.myDao().getOrders(); List<ProductWithQuantity> query8Products; linearLayout.removeAllViews(); View headerView8 = inflater.inflate(R.layout.client_item, null); TextView idTextView8 = headerView8.findViewById(R.id.client_child_id); TextView nameTextView8 = headerView8.findViewById(R.id.client_child_name); TextView lastNameTextView8 = headerView8.findViewById(R.id.client_child_lastname); TextView phoneTextView8 = headerView8.findViewById(R.id.client_child_phone_number); TextView registrationTextView8 = headerView8.findViewById(R.id.client_child_registration_date); idTextView8.setText("ID"); nameTextView8.setText("Όνομα"); lastNameTextView8.setText("Επίθετο"); phoneTextView8.setText("Κινητό"); registrationTextView8.setText("Ημ/νία Εγγραφής"); linearLayout.addView(headerView8); Set<Integer> clientsWithDesktop = new HashSet<>(); for(Order order : orderQuery8){ query8Products = order.getProducts(); Client client = clientMap.get(order.getClientId()); assert client != null; if(!clientsWithDesktop.contains(client.getId())){ for(ProductWithQuantity productWithQuantity: query8Products){ Product product = productWithQuantity.getProduct(); if(product.getCategory().equals("Desktop")) { View clientView = inflater.inflate(R.layout.client_item, null); idTextView8 = clientView.findViewById(R.id.client_child_id); nameTextView8 = clientView.findViewById(R.id.client_child_name); lastNameTextView8 = clientView.findViewById(R.id.client_child_lastname); phoneTextView8 = clientView.findViewById(R.id.client_child_phone_number); registrationTextView8 = clientView.findViewById(R.id.client_child_registration_date); idTextView8.setText(String.valueOf(client.getId())); nameTextView8.setText(client.getName()); lastNameTextView8.setText(client.getLastname()); phoneTextView8.setText(String.valueOf(client.getPhone_number())); registrationTextView8.setText(client.getRegisteration_date()); linearLayout.addView(clientView); clientsWithDesktop.add(client.getId()); } } } } break; case 9: List<Order> orderQuery9 = MainActivity.myAppDatabase.myDao().getQuery8(); linearLayout.removeAllViews(); View headerView9 = inflater.inflate(R.layout.order_list_item, null); TextView idTextView9 = headerView9.findViewById(R.id.order_child_id); TextView clientNameTextView9 = headerView9.findViewById(R.id.order_child_client_name); TextView priceTextView9 = headerView9.findViewById(R.id.order_child_total_price); TextView dateTextView9 = headerView9.findViewById(R.id.order_child_date); idTextView9.setText("ID"); clientNameTextView9.setText("Πελάτης"); priceTextView9.setText("Αξία"); dateTextView9.setText("Ημ/νια Πώλησης"); linearLayout.addView(headerView9); for(Order order : orderQuery9){ Client client = MainActivity.myAppDatabase.myDao().getClientFromId(order.getClientId()); assert client != null; View orderView = inflater.inflate(R.layout.order_list_item, null); idTextView3 = orderView.findViewById(R.id.order_child_id); clientNameTextView3 = orderView.findViewById(R.id.order_child_client_name); priceTextView3 = orderView.findViewById(R.id.order_child_total_price); dateTextView3 = orderView.findViewById(R.id.order_child_date); idTextView3.setText(String.valueOf(order.getId())); clientNameTextView3.setText(client.getName() + " " + client.getLastname()); String formattedPrice = String.format("%.2f", order.getTotalPrice()); priceTextView3.setText(formattedPrice + "€"); dateTextView3.setText(String.valueOf(order.getOrderDate())); linearLayout.addView(orderView); } break; } } }
20007_3
/* * Copyright 2016 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dkpro.core.io.xces; import static org.apache.commons.io.IOUtils.closeQuietly; import java.io.IOException; import java.io.InputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.bind.ValidationEvent; import javax.xml.bind.ValidationEventHandler; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import org.apache.uima.collection.CollectionException; import org.apache.uima.fit.descriptor.TypeCapability; import org.apache.uima.fit.factory.JCasBuilder; import org.apache.uima.jcas.JCas; import org.dkpro.core.io.xces.models.XcesBodyBasic; import org.dkpro.core.io.xces.models.XcesParaBasic; import de.tudarmstadt.ukp.dkpro.core.api.io.JCasResourceCollectionReader_ImplBase; import de.tudarmstadt.ukp.dkpro.core.api.resources.CompressionUtils; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph; @TypeCapability(outputs = { "de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph"}) public class XcesBasicXmlReader extends JCasResourceCollectionReader_ImplBase { @Override public void getNext(JCas aJCas) throws IOException, CollectionException { Resource res = nextFile(); initCas(aJCas, res); InputStream is = null; try { is = CompressionUtils.getInputStream(res.getLocation(), res.getInputStream()); XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); XMLEventReader xmlEventReaderBasic = xmlInputFactory.createXMLEventReader(is); //JAXB context for XCES body with basic type JAXBContext contextBasic = JAXBContext.newInstance(XcesBodyBasic.class); Unmarshaller unmarshallerBasic = contextBasic.createUnmarshaller(); unmarshallerBasic.setEventHandler(new ValidationEventHandler() { public boolean handleEvent(ValidationEvent event) { throw new RuntimeException(event.getMessage(), event.getLinkedException()); } }); JCasBuilder jb = new JCasBuilder(aJCas); XMLEvent eBasic = null; while ((eBasic = xmlEventReaderBasic.peek()) != null) { if (isStartElement(eBasic, "body")) { try { XcesBodyBasic parasBasic = (XcesBodyBasic) unmarshallerBasic .unmarshal(xmlEventReaderBasic, XcesBodyBasic.class).getValue(); readPara(jb, parasBasic); } catch (RuntimeException ex) { getLogger().warn( "Input is not in basic xces format."); } } else { xmlEventReaderBasic.next(); } } jb.close(); } catch (XMLStreamException ex1) { throw new IOException(ex1); } catch (JAXBException e1) { throw new IOException(e1); } finally { closeQuietly(is); } } private void readPara(JCasBuilder jb, Object bodyObj) { //Below is the sample paragraph format //<p id="p1">Αυτή είναι η πρώτη γραμμή.</p> if (bodyObj instanceof XcesBodyBasic) { for (XcesParaBasic p : ((XcesBodyBasic) bodyObj).p) { int start = jb.getPosition(); int end = start + p.s.length(); Paragraph para = new Paragraph(jb.getJCas(), start,end); para.addToIndexes(jb.getJCas()); jb.add(p.s); jb.add("\n\n"); } } } public static boolean isStartElement(XMLEvent aEvent, String aElement) { return aEvent.isStartElement() && ((StartElement) aEvent).getName().getLocalPart().equals(aElement); } }
jgrivolla/dkpro-core
dkpro-core-io-xces-asl/src/main/java/org/dkpro/core/io/xces/XcesBasicXmlReader.java
1,203
//<p id="p1">Αυτή είναι η πρώτη γραμμή.</p>
line_comment
el
/* * Copyright 2016 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dkpro.core.io.xces; import static org.apache.commons.io.IOUtils.closeQuietly; import java.io.IOException; import java.io.InputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.bind.ValidationEvent; import javax.xml.bind.ValidationEventHandler; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import org.apache.uima.collection.CollectionException; import org.apache.uima.fit.descriptor.TypeCapability; import org.apache.uima.fit.factory.JCasBuilder; import org.apache.uima.jcas.JCas; import org.dkpro.core.io.xces.models.XcesBodyBasic; import org.dkpro.core.io.xces.models.XcesParaBasic; import de.tudarmstadt.ukp.dkpro.core.api.io.JCasResourceCollectionReader_ImplBase; import de.tudarmstadt.ukp.dkpro.core.api.resources.CompressionUtils; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph; @TypeCapability(outputs = { "de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph"}) public class XcesBasicXmlReader extends JCasResourceCollectionReader_ImplBase { @Override public void getNext(JCas aJCas) throws IOException, CollectionException { Resource res = nextFile(); initCas(aJCas, res); InputStream is = null; try { is = CompressionUtils.getInputStream(res.getLocation(), res.getInputStream()); XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); XMLEventReader xmlEventReaderBasic = xmlInputFactory.createXMLEventReader(is); //JAXB context for XCES body with basic type JAXBContext contextBasic = JAXBContext.newInstance(XcesBodyBasic.class); Unmarshaller unmarshallerBasic = contextBasic.createUnmarshaller(); unmarshallerBasic.setEventHandler(new ValidationEventHandler() { public boolean handleEvent(ValidationEvent event) { throw new RuntimeException(event.getMessage(), event.getLinkedException()); } }); JCasBuilder jb = new JCasBuilder(aJCas); XMLEvent eBasic = null; while ((eBasic = xmlEventReaderBasic.peek()) != null) { if (isStartElement(eBasic, "body")) { try { XcesBodyBasic parasBasic = (XcesBodyBasic) unmarshallerBasic .unmarshal(xmlEventReaderBasic, XcesBodyBasic.class).getValue(); readPara(jb, parasBasic); } catch (RuntimeException ex) { getLogger().warn( "Input is not in basic xces format."); } } else { xmlEventReaderBasic.next(); } } jb.close(); } catch (XMLStreamException ex1) { throw new IOException(ex1); } catch (JAXBException e1) { throw new IOException(e1); } finally { closeQuietly(is); } } private void readPara(JCasBuilder jb, Object bodyObj) { //Below is the sample paragraph format //<p id="p1">Αυτή<SUF> if (bodyObj instanceof XcesBodyBasic) { for (XcesParaBasic p : ((XcesBodyBasic) bodyObj).p) { int start = jb.getPosition(); int end = start + p.s.length(); Paragraph para = new Paragraph(jb.getJCas(), start,end); para.addToIndexes(jb.getJCas()); jb.add(p.s); jb.add("\n\n"); } } } public static boolean isStartElement(XMLEvent aEvent, String aElement) { return aEvent.isStartElement() && ((StartElement) aEvent).getName().getLocalPart().equals(aElement); } }
17122_2
import java.io.Serializable; import java.util.ArrayList; import java.util.Random; import javax.swing.JOptionPane; public class QuestionManager implements Serializable { private static final long serialVersionUID = 1L; private ArrayList<Question> questionList; private ArrayList<Integer> questionsPassed; public QuestionManager() { questionList = new ArrayList<Question>(); Build(); } public void addQuestion(Question q) { questionList.add(q); } // Sends a question public Question getQuestion() { Question dummy = new Question("Test Question", "A ", " B", "C ", "D ", 0); if (questionList.size() == 0) { return dummy; } else { Random r = new Random(); int index = r.nextInt(questionList.size()); if (questionsPassed.size() == 0) { questionsPassed.add(index); return questionList.get(index); } else { while (questionsPassed.contains(index) && questionsPassed.size() != questionList.size()) { r = new Random(); index = r.nextInt(questionList.size()); } if (questionsPassed.contains(index) == false) { questionsPassed.add(index); return questionList.get(index); } else if (questionsPassed.size() == questionList.size()) { // JOptionPane.showMessageDialog(null, "Out of questions"); } } return dummy; } } // Αρχικοποίηση της λίστας με τις ερωτήσεις που έχουν περάσει public void Build() { questionsPassed = new ArrayList<Integer>(); } public int sizeOf() { return questionList.size(); } public String sendQuestions(int i) { return questionList.get(i).getQuestion(); } public String sendAnswer(int i, int index) { return questionList.get(i).getAnswer(index); } }
jinius17/GameProj
src/QuestionManager.java
531
// Αρχικοποίηση της λίστας με τις ερωτήσεις που έχουν περάσει
line_comment
el
import java.io.Serializable; import java.util.ArrayList; import java.util.Random; import javax.swing.JOptionPane; public class QuestionManager implements Serializable { private static final long serialVersionUID = 1L; private ArrayList<Question> questionList; private ArrayList<Integer> questionsPassed; public QuestionManager() { questionList = new ArrayList<Question>(); Build(); } public void addQuestion(Question q) { questionList.add(q); } // Sends a question public Question getQuestion() { Question dummy = new Question("Test Question", "A ", " B", "C ", "D ", 0); if (questionList.size() == 0) { return dummy; } else { Random r = new Random(); int index = r.nextInt(questionList.size()); if (questionsPassed.size() == 0) { questionsPassed.add(index); return questionList.get(index); } else { while (questionsPassed.contains(index) && questionsPassed.size() != questionList.size()) { r = new Random(); index = r.nextInt(questionList.size()); } if (questionsPassed.contains(index) == false) { questionsPassed.add(index); return questionList.get(index); } else if (questionsPassed.size() == questionList.size()) { // JOptionPane.showMessageDialog(null, "Out of questions"); } } return dummy; } } // Αρχικοποίηση της<SUF> public void Build() { questionsPassed = new ArrayList<Integer>(); } public int sizeOf() { return questionList.size(); } public String sendQuestions(int i) { return questionList.get(i).getQuestion(); } public String sendAnswer(int i, int index) { return questionList.get(i).getAnswer(index); } }
430_1
public interface List { public boolean isEmpty( ); public int size( ); public void insertFirst(Object data); public void insertLast(Object data); public void insert(int position, Object data) throws NoSuchListPosition; /* Τοποθετεί το νέο κόμβο στην υπ’ αριθμό position θέση της λίστας. Αν το position είναι 0 ο κόμβος εισάγεται στην αρχή, αν το position είναι size( ) ο κόμβος εισάγεται στo τέλος, διαφορετικά αν position <0 ή position > size( ) προκύπτει εξαίρεση */ public Object removeFirst( ) throws ListEmptyException; public Object removeLast( ) throws ListEmptyException; public Object remove(int position) throws ListEmptyException, NoSuchListPosition; /* Διαγράφει τον κόμβο που βρίσκεται στην υπ’ αριθμό position θέση της λίστας. Αν το position είναι 0 διαγράφεται ο πρώτος κόμβος, αν το position είναι size( ) διαγράφεται ο τελευταίος κόμβος, διαφορετικά αν position <0 ή position > size( ) προκύπτει εξαίρεση */ }
johnarnaou/Data-Structures
QueueList/List.java
454
/* Διαγράφει τον κόμβο που βρίσκεται στην υπ’ αριθμό position θέση της λίστας. Αν το position είναι 0 διαγράφεται ο πρώτος κόμβος, αν το position είναι size( ) διαγράφεται ο τελευταίος κόμβος, διαφορετικά αν position <0 ή position > size( ) προκύπτει εξαίρεση */
block_comment
el
public interface List { public boolean isEmpty( ); public int size( ); public void insertFirst(Object data); public void insertLast(Object data); public void insert(int position, Object data) throws NoSuchListPosition; /* Τοποθετεί το νέο κόμβο στην υπ’ αριθμό position θέση της λίστας. Αν το position είναι 0 ο κόμβος εισάγεται στην αρχή, αν το position είναι size( ) ο κόμβος εισάγεται στo τέλος, διαφορετικά αν position <0 ή position > size( ) προκύπτει εξαίρεση */ public Object removeFirst( ) throws ListEmptyException; public Object removeLast( ) throws ListEmptyException; public Object remove(int position) throws ListEmptyException, NoSuchListPosition; /* Διαγράφει τον κόμβο<SUF>*/ }
1554_10
/** Primitive types pass by value, collections and objects "seem to be passed by reference". * In fact, everything in Java is passed by value because they are pointers. * We also have the unmodifiable collections */ package gr.hua.dit.oopii.lec3.lists; import java.util.ArrayList; import java.util.Collections; import java.util.List; import gr.hua.dit.oopii.lec2.inheritance.Human; //slide 7 public class ReferenceValue { int obj_value; public final static List<String> public_final_strings = new ArrayList<String>(); public static final Human human = new Human(); ReferenceValue(){ this.obj_value=5; } ReferenceValue(ReferenceValue in_obj){//Easy way to duplicate an object with a constructor that copies (duplicates) all elements. this.obj_value=in_obj.obj_value; System.out.println("Argument-object hashcode is: " + in_obj.hashCode()); System.out.println("The new-created object hashcode is: " + this.hashCode()); } public static void passPrimitiveTypes(int number) { //The changes of the primitive types inside the class do not take effect outside the class. number=1000; } public static void passObject( ReferenceValue obj , int number) { obj.obj_value=number; } public static void passObject_withNew( ReferenceValue obj) { ReferenceValue object2 = new ReferenceValue(); object2.obj_value=100; obj=object2; //The parameter object pointer will not change. } public static void passArray( int[] in_array) { in_array[0]=100; in_array[1]=100; in_array[2]=100; } public static void passObject_withfinal(final ReferenceValue obj , final int number) { //number=50; obj.obj_value=number; } public static void main(String[] args) { int number=5; System.out.println("1. Before call the func: Primitive types passed by value: "+number); passPrimitiveTypes(number); //It adds 10 to the primitive type argument but no changes take place. System.out.println("1. After call the func: Primitive types passed by value: "+number +"\n"); //Primitive type passed by Value. ReferenceValue object = new ReferenceValue(); System.out.println("2."+object.hashCode() + " Before call the func: Objects seems to be passed by \"reference\" "+object.obj_value); //the object's hash code, which is the object's memory address in hexadecimal. passObject(object,200); System.out.println("2."+object.hashCode() + " After call the func: Objects seems to be passed by \"reference\": "+object.obj_value +"\n"); //Objects seems passed by "Reference". The changes took place. int[] in_array = {11,12,13,14,15}; System.out.println("3."+in_array.hashCode() + " Before call the func: Arrays also seem to be passed by \"reference\": "+in_array[0 ] +" "+ in_array[1] +" "+ in_array[2] +" "+ in_array[3] +" "+ in_array[4]); passArray(in_array); System.out.println("3."+in_array.hashCode() + " After call the func: Arrays also seem to be passed by \"reference\": "+in_array[0 ] +" "+ in_array[1] +" "+ in_array[2] +" "+ in_array[3] +" "+ in_array[4]+"\n"); //Objects passed by "Reference". ReferenceValue object3 = new ReferenceValue(); //Reference to the values of the object. But passed with value thepointer to the object. We cannot change the object that we point. System.out.println("4."+object3.hashCode() + " Before call the func: On the left we have the object's hash code, which is the object's memory address: " +object3.obj_value); passObject_withNew(object3); //But we can change the variables of the object that we pass in. Δεν μπορώ να δειξω σε άλλο αντικείμενο. O pointer θα δείχνει πάντα στο ιδιο object. System.out.println("4."+object3.hashCode() + " But, we cannot change the reference (pointer) of the object: On the left we have again the hash hashcode: "+object3.obj_value); //So if we re-think our statement everything is passed by value!!! you cannot change where that pointer points. System.out.println("4.In fact everything in Java is PASSED BY VALUE!"); final ReferenceValue object4 = new ReferenceValue(); //object4 = object; //Final declaration of objects cannot change objects. But object4 = object; is acceptable. System.out.println("\n\n\n5.How can we define that some collections or objects should not be modified?\n"); ReferenceValue object5 = new ReferenceValue(); //We have overloaded the constructor. passObject(new ReferenceValue(object5), 200); //we really make a new object that duplicate the status of object5 and pass it as argument into the function. System.out.println("5."+object5.hashCode() + " With the new object as argument and constructor that makes a deep copy, we can pass the object: "+object5.obj_value); //Objects passed by "Reference". System.out.println("\n\n"); System.out.println("with unmodified collecction"); unmodifiedcollection(); //Unmodifiable collections! System.out.println("Old name: "+human.getName()); // human is public static final. We cannot change the pointer, but we can change the state of the object. human.setName("Theodoros"); System.out.println("New name: "+human.getName()); //human= new Human(); We cannot because the pointer cannot point a different object. } public static void unmodifiedcollection() { // We can explicitly declare a collection as unmodifiable and we will not be able to modify this collection. List<String> strings = new ArrayList<String>(); List<String> unmodifiable = Collections.unmodifiableList(strings); //Now the collection cannot be modified. We cannot add or remove items from the list. //unmodifiable.add("New string"); // will fail at runtime strings.add("Aha!"); // will succeed System.out.println(unmodifiable); public_final_strings.add("word1"); //In the public final list we can add or remove elements. public_final_strings.add("word2"); public_final_strings.add("word3"); public_final_strings.remove(1); System.out.println(public_final_strings); //public_final_strings = strings; //When the pointer is final, it cannot point another object (even if it is the same class). List<Human> list_data_obj = new ArrayList<Human>(); Human x1 = new Human(); x1.setName("\nDimitris"); list_data_obj.add(x1); List<Human> unmodifiable_list_data_obj = Collections.unmodifiableList(list_data_obj); System.out.println(unmodifiable_list_data_obj.get(0).getName()); x1.setName("Peter"); System.out.println(unmodifiable_list_data_obj.get(0).getName()); } public class ImmutableClass { //Immutable class has a constructor to initialize the objects. It has getters to return the values but it does not have setters. private int var1; private int var2; ImmutableClass(int in_var1, int in_var2){ this.var1=in_var1; this.var2=in_var2; } public int getVar1() { return var1; } public int getVar2() { return var2; } } }
johnviolos/OOPII
src/gr/hua/dit/oopii/lec3/lists/ReferenceValue.java
1,978
//But we can change the variables of the object that we pass in. Δεν μπορώ να δειξω σε άλλο αντικείμενο. O pointer θα δείχνει πάντα στο ιδιο object.
line_comment
el
/** Primitive types pass by value, collections and objects "seem to be passed by reference". * In fact, everything in Java is passed by value because they are pointers. * We also have the unmodifiable collections */ package gr.hua.dit.oopii.lec3.lists; import java.util.ArrayList; import java.util.Collections; import java.util.List; import gr.hua.dit.oopii.lec2.inheritance.Human; //slide 7 public class ReferenceValue { int obj_value; public final static List<String> public_final_strings = new ArrayList<String>(); public static final Human human = new Human(); ReferenceValue(){ this.obj_value=5; } ReferenceValue(ReferenceValue in_obj){//Easy way to duplicate an object with a constructor that copies (duplicates) all elements. this.obj_value=in_obj.obj_value; System.out.println("Argument-object hashcode is: " + in_obj.hashCode()); System.out.println("The new-created object hashcode is: " + this.hashCode()); } public static void passPrimitiveTypes(int number) { //The changes of the primitive types inside the class do not take effect outside the class. number=1000; } public static void passObject( ReferenceValue obj , int number) { obj.obj_value=number; } public static void passObject_withNew( ReferenceValue obj) { ReferenceValue object2 = new ReferenceValue(); object2.obj_value=100; obj=object2; //The parameter object pointer will not change. } public static void passArray( int[] in_array) { in_array[0]=100; in_array[1]=100; in_array[2]=100; } public static void passObject_withfinal(final ReferenceValue obj , final int number) { //number=50; obj.obj_value=number; } public static void main(String[] args) { int number=5; System.out.println("1. Before call the func: Primitive types passed by value: "+number); passPrimitiveTypes(number); //It adds 10 to the primitive type argument but no changes take place. System.out.println("1. After call the func: Primitive types passed by value: "+number +"\n"); //Primitive type passed by Value. ReferenceValue object = new ReferenceValue(); System.out.println("2."+object.hashCode() + " Before call the func: Objects seems to be passed by \"reference\" "+object.obj_value); //the object's hash code, which is the object's memory address in hexadecimal. passObject(object,200); System.out.println("2."+object.hashCode() + " After call the func: Objects seems to be passed by \"reference\": "+object.obj_value +"\n"); //Objects seems passed by "Reference". The changes took place. int[] in_array = {11,12,13,14,15}; System.out.println("3."+in_array.hashCode() + " Before call the func: Arrays also seem to be passed by \"reference\": "+in_array[0 ] +" "+ in_array[1] +" "+ in_array[2] +" "+ in_array[3] +" "+ in_array[4]); passArray(in_array); System.out.println("3."+in_array.hashCode() + " After call the func: Arrays also seem to be passed by \"reference\": "+in_array[0 ] +" "+ in_array[1] +" "+ in_array[2] +" "+ in_array[3] +" "+ in_array[4]+"\n"); //Objects passed by "Reference". ReferenceValue object3 = new ReferenceValue(); //Reference to the values of the object. But passed with value thepointer to the object. We cannot change the object that we point. System.out.println("4."+object3.hashCode() + " Before call the func: On the left we have the object's hash code, which is the object's memory address: " +object3.obj_value); passObject_withNew(object3); //But we<SUF> System.out.println("4."+object3.hashCode() + " But, we cannot change the reference (pointer) of the object: On the left we have again the hash hashcode: "+object3.obj_value); //So if we re-think our statement everything is passed by value!!! you cannot change where that pointer points. System.out.println("4.In fact everything in Java is PASSED BY VALUE!"); final ReferenceValue object4 = new ReferenceValue(); //object4 = object; //Final declaration of objects cannot change objects. But object4 = object; is acceptable. System.out.println("\n\n\n5.How can we define that some collections or objects should not be modified?\n"); ReferenceValue object5 = new ReferenceValue(); //We have overloaded the constructor. passObject(new ReferenceValue(object5), 200); //we really make a new object that duplicate the status of object5 and pass it as argument into the function. System.out.println("5."+object5.hashCode() + " With the new object as argument and constructor that makes a deep copy, we can pass the object: "+object5.obj_value); //Objects passed by "Reference". System.out.println("\n\n"); System.out.println("with unmodified collecction"); unmodifiedcollection(); //Unmodifiable collections! System.out.println("Old name: "+human.getName()); // human is public static final. We cannot change the pointer, but we can change the state of the object. human.setName("Theodoros"); System.out.println("New name: "+human.getName()); //human= new Human(); We cannot because the pointer cannot point a different object. } public static void unmodifiedcollection() { // We can explicitly declare a collection as unmodifiable and we will not be able to modify this collection. List<String> strings = new ArrayList<String>(); List<String> unmodifiable = Collections.unmodifiableList(strings); //Now the collection cannot be modified. We cannot add or remove items from the list. //unmodifiable.add("New string"); // will fail at runtime strings.add("Aha!"); // will succeed System.out.println(unmodifiable); public_final_strings.add("word1"); //In the public final list we can add or remove elements. public_final_strings.add("word2"); public_final_strings.add("word3"); public_final_strings.remove(1); System.out.println(public_final_strings); //public_final_strings = strings; //When the pointer is final, it cannot point another object (even if it is the same class). List<Human> list_data_obj = new ArrayList<Human>(); Human x1 = new Human(); x1.setName("\nDimitris"); list_data_obj.add(x1); List<Human> unmodifiable_list_data_obj = Collections.unmodifiableList(list_data_obj); System.out.println(unmodifiable_list_data_obj.get(0).getName()); x1.setName("Peter"); System.out.println(unmodifiable_list_data_obj.get(0).getName()); } public class ImmutableClass { //Immutable class has a constructor to initialize the objects. It has getters to return the values but it does not have setters. private int var1; private int var2; ImmutableClass(int in_var1, int in_var2){ this.var1=in_var1; this.var2=in_var2; } public int getVar1() { return var1; } public int getVar2() { return var2; } } }
3487_0
package gr.aueb.cf.ch4; /** * Εκτυπώνει 10 γραμμής με 10 αστεράκια * σε κάθε γραμμή. */ public class Stars10x10App { public static void main(String[] args) { for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 10; j++) { System.out.print("*"); } System.out.println(); } } }
jordanpapaditsas/codingfactory-java
src/gr/aueb/cf/ch4/Stars10x10App.java
154
/** * Εκτυπώνει 10 γραμμής με 10 αστεράκια * σε κάθε γραμμή. */
block_comment
el
package gr.aueb.cf.ch4; /** * Εκτυπώνει 10 γραμμής<SUF>*/ public class Stars10x10App { public static void main(String[] args) { for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 10; j++) { System.out.print("*"); } System.out.println(); } } }
6635_1
package menu_app; import java.util.Scanner; /** * Demonstrates a mathematical operation. */ public class AdditionApp { public static void main(String[] args) { Scanner in = new Scanner(System.in); // Δήλωση και αρχικοποίηση των μεταβλητών int num1 = 0; int num2 = 0; int sum = 0; // Εντολές num1 = in.nextInt(); num2 = in.nextInt(); sum = num1 + num2; // Eκτύπωση των αποτελεσμάτων System.out.println("Το αποτέλεσμα της πρόσθεσης είναι ίσο με: \n" + sum); } }
jordanpapaditsas/java-projects
src/menu_app/AdditionApp.java
235
// Δήλωση και αρχικοποίηση των μεταβλητών
line_comment
el
package menu_app; import java.util.Scanner; /** * Demonstrates a mathematical operation. */ public class AdditionApp { public static void main(String[] args) { Scanner in = new Scanner(System.in); // Δήλωση και<SUF> int num1 = 0; int num2 = 0; int sum = 0; // Εντολές num1 = in.nextInt(); num2 = in.nextInt(); sum = num1 + num2; // Eκτύπωση των αποτελεσμάτων System.out.println("Το αποτέλεσμα της πρόσθεσης είναι ίσο με: \n" + sum); } }
23911_1
package com.example.vivi.wordsquiz; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.graphics.Point; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Display; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.Button; public class MainActivity extends AppCompatActivity { private static final String TAG = "TEST"; private boolean phoneDevice = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); int screenSize = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK; if (screenSize == Configuration.SCREENLAYOUT_SIZE_LARGE || screenSize == Configuration.SCREENLAYOUT_SIZE_XLARGE ) phoneDevice = false; if (phoneDevice) setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); Button button= (Button) findViewById(R.id.play_btn); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MainActivity.this, ChoiceActivity.class); startActivity(i); } }); } @Override protected void onStart(){ super.onStart(); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle("Words Quiz"); setSupportActionBar(toolbar); Intent i=getIntent(); Log.i(TAG, "onStart: "); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay(); Point screenSize = new Point(); Log.i(TAG, "onCreateOptionsMenu: "); display.getRealSize(screenSize); if (screenSize.x < screenSize.y) // x είναι το πλάτος, y είναι το ύψος { getMenuInflater().inflate(R.menu.main_menu, menu); // διογκώνει το μενού return true; } else return false; } //ToolBar private void open(){ AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setMessage("Do you really want to exit?"); alertDialogBuilder.setPositiveButton("YES", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { finish(); System.exit(0); } }); alertDialogBuilder.setNegativeButton("NO",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } @Override public boolean onSupportNavigateUp() { //Back Button onBackPressed(); return true; } private void exitdialog(){ open(); } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.about_menu: Intent a=new Intent(this,AboutActivity.class); //some code here startActivity(a); return true; case R.id.exit: exitdialog(); return true; case R.id.help: Intent b=new Intent(this,HelpActivity.class); //some code here startActivity(b); return true; default: return super.onOptionsItemSelected(item); } } }
jvario/WordQuiz
app/src/main/java/com/example/vivi/wordsquiz/MainActivity.java
915
// διογκώνει το μενού
line_comment
el
package com.example.vivi.wordsquiz; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.graphics.Point; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Display; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.Button; public class MainActivity extends AppCompatActivity { private static final String TAG = "TEST"; private boolean phoneDevice = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); int screenSize = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK; if (screenSize == Configuration.SCREENLAYOUT_SIZE_LARGE || screenSize == Configuration.SCREENLAYOUT_SIZE_XLARGE ) phoneDevice = false; if (phoneDevice) setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); Button button= (Button) findViewById(R.id.play_btn); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MainActivity.this, ChoiceActivity.class); startActivity(i); } }); } @Override protected void onStart(){ super.onStart(); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle("Words Quiz"); setSupportActionBar(toolbar); Intent i=getIntent(); Log.i(TAG, "onStart: "); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay(); Point screenSize = new Point(); Log.i(TAG, "onCreateOptionsMenu: "); display.getRealSize(screenSize); if (screenSize.x < screenSize.y) // x είναι το πλάτος, y είναι το ύψος { getMenuInflater().inflate(R.menu.main_menu, menu); // διογκώνει το<SUF> return true; } else return false; } //ToolBar private void open(){ AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setMessage("Do you really want to exit?"); alertDialogBuilder.setPositiveButton("YES", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { finish(); System.exit(0); } }); alertDialogBuilder.setNegativeButton("NO",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } @Override public boolean onSupportNavigateUp() { //Back Button onBackPressed(); return true; } private void exitdialog(){ open(); } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.about_menu: Intent a=new Intent(this,AboutActivity.class); //some code here startActivity(a); return true; case R.id.exit: exitdialog(); return true; case R.id.help: Intent b=new Intent(this,HelpActivity.class); //some code here startActivity(b); return true; default: return super.onOptionsItemSelected(item); } } }
32_0
package Class_folder; import java.util.HashMap; import java.util.Map; public class Grade extends Gradebook{ private String gr_class_id; private String gr_course; private int grade_no; private int grade_no2; private int grade_mean; private String grade_title; private int gr_id = super.gr_id; private String student_am; private String name; private String surname; public Grade(int grade_no, String grade_title) { this.grade_title = grade_title; this.grade_no = grade_no; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public Grade(String student_am, String surname, String name, int grade_no){ this.student_am =student_am; this.name = name; this.surname = surname; this.grade_no = grade_no; } public Grade(String gr_course, int grade_no, int grade_no2, int grade_mean) { this.gr_course = gr_course; this.grade_no = grade_no; this.grade_no2 = grade_no2; this.grade_mean = grade_mean; } public int getGrade_no() { return grade_no; } public String getGrade_title() { return grade_title; } public int getGrade_no2() { return grade_no2; } public int getGrade_mean() { return grade_mean; } public int getGr_id() { return gr_id; } public String getGr_course() { return gr_course; } public Map getStGrades(int gr_id){ //εδω θα κανει αναζήτηση στη βάση και θα παίρνει τους μαθητές του βαθμολογίου και τους βαθμούς Map<String, Integer> st_grades = new HashMap<String, Integer>(); return st_grades; } }
kandrew5/SoftwareEngineerProject
src/Class_folder/Grade.java
578
//εδω θα κανει αναζήτηση στη βάση και θα παίρνει τους μαθητές του βαθμολογίου και τους βαθμούς
line_comment
el
package Class_folder; import java.util.HashMap; import java.util.Map; public class Grade extends Gradebook{ private String gr_class_id; private String gr_course; private int grade_no; private int grade_no2; private int grade_mean; private String grade_title; private int gr_id = super.gr_id; private String student_am; private String name; private String surname; public Grade(int grade_no, String grade_title) { this.grade_title = grade_title; this.grade_no = grade_no; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public Grade(String student_am, String surname, String name, int grade_no){ this.student_am =student_am; this.name = name; this.surname = surname; this.grade_no = grade_no; } public Grade(String gr_course, int grade_no, int grade_no2, int grade_mean) { this.gr_course = gr_course; this.grade_no = grade_no; this.grade_no2 = grade_no2; this.grade_mean = grade_mean; } public int getGrade_no() { return grade_no; } public String getGrade_title() { return grade_title; } public int getGrade_no2() { return grade_no2; } public int getGrade_mean() { return grade_mean; } public int getGr_id() { return gr_id; } public String getGr_course() { return gr_course; } public Map getStGrades(int gr_id){ //εδω θα<SUF> Map<String, Integer> st_grades = new HashMap<String, Integer>(); return st_grades; } }
6137_14
@WebServlet("/UserAuthenticationServlet") public class UserAuthenticationServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { String action = request.getParameter("action"); switch (action) { case "login": handleLogin(request, response); break; case "register": handleRegister(request, response); break; case "suggestWines": handleWineSuggestions(request, response); break; default: // Handle other actions or errors break; } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { // Handle GET requests (e.g., initial page load) // You can add additional functionality here } private void handleLogin(HttpServletRequest request, HttpServletResponse response) throws IOException { // Logic for login authentication (not implemented in this example) // ... // Send response to the client PrintWriter out = response.getWriter(); out.println("<h1>Login Successful</h1>"); // ... } private void handleRegister(HttpServletRequest request, HttpServletResponse response) throws IOException { String name = request.getParameter("name"); String email = request.getParameter("email"); String password = request.getParameter("password"); // Προσθήκη νέου πελάτη στη βάση δεδομένων CustomerDatabase.addCustomer(email, name, password); // Send response to the client PrintWriter out = response.getWriter(); out.println("<h1>Registration Successful</h1>"); out.println("<p>Name: " + name + "</p>"); out.println("<p>Email: " + email + "</p>"); } private void handleWineSuggestions(HttpServletRequest request, HttpServletResponse response) throws IOException { //!!! Σοφία και εδώ !!!! String apiEndpoint = "https://api.example.com/suggest-wines"; // Assuming you have user preferences stored in request parameters String userEmail = request.getParameter("email"); // ... other parameters ... // Σοφία και εδω !!! String suggestedWines = callExternalApi(apiEndpoint, userEmail /* other parameters */); // Ναταλία και εδω !!! saveSuggestedWinesToDatabase(userEmail, suggestedWines); // Send response to the client PrintWriter out = response.getWriter(); out.println("<h1>Wine Suggestions for " + userEmail + "</h1>"); out.println("<p>" + suggestedWines + "</p>"); } private String callExternalApi(String apiEndpoint, String userEmail /* other parameters */) { // Σοφία εδώ πρέπει να κοιτάξεις πώς θα το γράψεις } private void saveSuggestedWinesToDatabase(String userEmail, String suggestedWines) { // Ναταλία διαμορφώνετε ανάλογα με αυτό που θα φτιάξετε τα απο πάνω μπορούν να αλλάξουν όλα αναλογως με αυτό που θα φτιάξετε } }
kateriTs/GrapeVin
GrapeVin/GrapeVin/AuthenticationServlet.java
798
// Ναταλία διαμορφώνετε ανάλογα με αυτό που θα φτιάξετε τα απο πάνω μπορούν να αλλάξουν όλα αναλογως με αυτό που θα φτιάξετε
line_comment
el
@WebServlet("/UserAuthenticationServlet") public class UserAuthenticationServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { String action = request.getParameter("action"); switch (action) { case "login": handleLogin(request, response); break; case "register": handleRegister(request, response); break; case "suggestWines": handleWineSuggestions(request, response); break; default: // Handle other actions or errors break; } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { // Handle GET requests (e.g., initial page load) // You can add additional functionality here } private void handleLogin(HttpServletRequest request, HttpServletResponse response) throws IOException { // Logic for login authentication (not implemented in this example) // ... // Send response to the client PrintWriter out = response.getWriter(); out.println("<h1>Login Successful</h1>"); // ... } private void handleRegister(HttpServletRequest request, HttpServletResponse response) throws IOException { String name = request.getParameter("name"); String email = request.getParameter("email"); String password = request.getParameter("password"); // Προσθήκη νέου πελάτη στη βάση δεδομένων CustomerDatabase.addCustomer(email, name, password); // Send response to the client PrintWriter out = response.getWriter(); out.println("<h1>Registration Successful</h1>"); out.println("<p>Name: " + name + "</p>"); out.println("<p>Email: " + email + "</p>"); } private void handleWineSuggestions(HttpServletRequest request, HttpServletResponse response) throws IOException { //!!! Σοφία και εδώ !!!! String apiEndpoint = "https://api.example.com/suggest-wines"; // Assuming you have user preferences stored in request parameters String userEmail = request.getParameter("email"); // ... other parameters ... // Σοφία και εδω !!! String suggestedWines = callExternalApi(apiEndpoint, userEmail /* other parameters */); // Ναταλία και εδω !!! saveSuggestedWinesToDatabase(userEmail, suggestedWines); // Send response to the client PrintWriter out = response.getWriter(); out.println("<h1>Wine Suggestions for " + userEmail + "</h1>"); out.println("<p>" + suggestedWines + "</p>"); } private String callExternalApi(String apiEndpoint, String userEmail /* other parameters */) { // Σοφία εδώ πρέπει να κοιτάξεις πώς θα το γράψεις } private void saveSuggestedWinesToDatabase(String userEmail, String suggestedWines) { // Ναταλία διαμορφώνετε<SUF> } }
1038_2
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.util.HashMap; public class ServerThread extends Thread{ private Socket clientSocket; private DataInputStream inputFromClient; private DataOutputStream outputToClient; private HashMap<Integer, Account> allAccounts; private HashMap<Integer, Message> allMessages; public ServerThread(Socket clientSocket, HashMap<Integer, Account> allAccounts, HashMap<Integer, Message> allMessages){ try{ this.clientSocket=clientSocket; this.allAccounts= allAccounts; this.allMessages= allMessages; inputFromClient= new DataInputStream(this.clientSocket.getInputStream()); outputToClient= new DataOutputStream(this.clientSocket.getOutputStream()); }catch (IOException e){ System.err.println("Error: No Connection" +"\n" + e.getMessage()); } } /** * Στη μεταβλητή dataFromClient αποθηκεύεται το αίτημα του client. Στον πρώτο χαρακτήρα είναι αποθηκευμένος ένας αριθμός από το 1 έως το 6, ο οποίος αντιστοιχεί σε κάποια λειτουργία που θέλει να εκτελέσει ο client. * Αυτός ο αριθμός αποθηκεύεται στη μεταβλητή functionID. Ανάλογα με την τιμή του functionID καλείται μία διαφορετική συνάρτηση, που η κάθε μία παίρνει ως όρισμα την υπόλοιπη συμβολοσειρά της dataFromClient * Τα αποτελέσματα των συναρτήσεων επιστρέφονται ως απάντηση στον client * */ public void run(){ try{ String dataFromClient= inputFromClient.readUTF(); String functionId= dataFromClient.charAt(0)+""; dataFromClient=dataFromClient.substring(1); if(functionId.equals("1")){ outputToClient.writeInt(createAccount(dataFromClient)); } else if(functionId.equals("2")){ outputToClient.writeUTF(showAccounts(dataFromClient)); } else if(functionId.equals("3")){ outputToClient.writeInt(sendMessage(dataFromClient)); } else if(functionId.equals("4")){ outputToClient.writeUTF(showInbox(dataFromClient)); } else if(functionId.equals("5")){ outputToClient.writeUTF(readMessage(dataFromClient)); } else if(functionId.equals("6")){ outputToClient.writeInt(deleteMessage(dataFromClient)); } }catch (IOException e){ System.err.println("Error: " + e.getMessage()); } finally { try{ clientSocket.close(); }catch (IOException e){ System.err.println("Error" + e.getMessage()); } } } /** * Η συνάρτηση createAccount αποτελεί την πρώτη λειτουργία - functionID=1 - * Σε αυτή την περίπτωση, στο String dataFromClient θα υπάρχει μόνο το username * Αρχικά, ελέγχεται αν το username ανήκει σε κάποιον άλλο χρήστη. Αν ανήκει, τότε η συνάρτηση επιστρέφει την τιμή -1 * Έπειτα, ελέγχονται όλοι οι χαρακτήρες του username, ώστε να διαπιστωθεί αν υπάρχουν μη-έγκυροι χαρακτήρες. Αν υπάρχουν, τότε η συνάρτηση επιστρέφει την τιμή -2 * Τέλος, δημιουργείται ένα νέο account και η συνάρτηση επιστρέφει το authToken του χρήστη */ private int createAccount(String dataFromClient){ String newUsername= dataFromClient; for(Account account: allAccounts.values()){ if( account.getUsername().equals(newUsername)) return -1; } char character; for(int i=0;i<newUsername.length();i++){ character=newUsername.charAt(i); if(!( (character>='a' && character<='z') || (character>='A' && character<='Z') || (character>='0' && character<='9') || character=='_') ) return -2; } int newAuthToken= Server.getAuthToken(); Account account= new Account(newUsername, newAuthToken); allAccounts.put(newAuthToken, account); return newAuthToken; } /** * Η συνάρτηση showAccounts αποτελεί τη δεύτερη λειτουργία - functionID=2 - * Σε αυτή την περίπτωση, στο dataFromClient θα υπάρχει μόνο το authToken ενός χρήστη. * Αρχικά, ελέγχεται αν το authToken αντιστοιχεί σε κάποιον χρήστη. * Αν ανήκει, τότε η συνάρτηση επιστρέφει όλα τα username των χρηστών * αλλιώς επιστρέφει ένα String που αναφέρει ότι το authToken δεν ανήκει σε κάποιον χρήστη **/ private String showAccounts(String dataFromClient){ int authToken= Integer.parseInt(dataFromClient); if(allAccounts.get(authToken)==null){ return "Invalid Auth Token"; } String temp=""; int i=0; for(Account account: allAccounts.values()){ temp+= ++i +". " + account.getUsername() + "\n"; } return temp; } /** * Η συνάρτηση sendMessage αποτελεί την τρίτη λειτουργία - functionID=3 - * Σε αυτή την περίπτωση στο dataFromClient θα υπάρχει ένα String της μορφής: authToken^recipient.length()^recipient^messageBody * * Αρχικά, ελέγχεται αν το authToken αντιστοιχεί σε κάποιον χρήστη. Αν δεν υπάρχει, τότε η συνάρτηση επιστρέφει την τιμή: 2 * ενώ αν υπάρχει τότε στη μεταβλητή sender αποθηκεύεται ο συγκεκριμένος χρήστης * Έπειτα, ελέγχεται αν υπάρχει χρήστης με username ίδιο με αυτό της μεταβλητής recipient. Αν δεν υπάρχει η συνάρτηση επιστρέφει την τιμή: 1, * Αλλιώς δημιουργείται και στέλνεται το μήνυμα και η συνάρτηση επιστρέφει την τιμή 0 */ private int sendMessage(String dataFromClient){ String tempAuthToken=""; int authToken; String recipient=""; String tempRecipient=""; int tempRecipient2; String messageBody=""; int i; for(i=0;dataFromClient.charAt(i)!='^';i++){ tempAuthToken+=dataFromClient.charAt(i)+""; } authToken=Integer.parseInt(tempAuthToken); for(i++;dataFromClient.charAt(i)!='^';i++){ tempRecipient+=dataFromClient.charAt(i); } tempRecipient2=Integer.parseInt(tempRecipient); for(i++;tempRecipient2>0;i++){ recipient+=dataFromClient.charAt(i); tempRecipient2--; } messageBody=dataFromClient.substring(i+1); Account sender= allAccounts.get(authToken); if(sender==null) return 2; Account receiver=null; for(Account account : allAccounts.values()){ if(account.getUsername().equals(recipient)){ receiver= account; } } if(receiver==null){ return 1; } int messId= Server.getMessageId(); Message message= new Message(sender.getUsername(), receiver.getUsername(), messageBody, messId); allMessages.put(messId, message); receiver.addMessage(message); return 0; } /** * Η συνάρτηση showInbox αποτελεί την τέταρτη λειτουργία - functionID=4 - * Σε αυτή την περίπτωση στο dataFromClient θα υπάρχει μόνο το authToken ενός χρήστη * Αν αντιστοιχεί σε κάποιον χρήστη, τότε η συνάρτηση θα επιστρέφει ένα String με όλα τα εισερχόμενα μηνύματα του χρήστη * αλλιώς, θα επιστρέφει ένα String που να αναφέρει ότι το authToken δεν ανήκει σε κάποιον χρήστη */ private String showInbox(String dataFromClient){ int authToken= Integer.parseInt(dataFromClient); Account account= allAccounts.get(authToken); if(account==null){ return "Invalid Auth Token"; } String answer=""; for(Message message: account.getMessageBox()){ answer+= message.getMessageId() +". from: " + message.getSender(); if(!message.getIsRead()) answer+="*"; answer+="\n"; } return answer; } /** * Η συνάρτηση readMessage αποτελεί την πέμπτη λειτουργία - functionID=5 - * Σε αυτή την περίπτωση στο dataFromClient θα υπάρχει ένα String της μορφής: authToken^messageId * Αρχικά, ελέγχεται αν το authToken αντιστοιχίζεται σε κάποιον χρήστη * Αν δεν υπάρχει, τότε η συνάρτηση επιστρέφει to String "2" * Αν υπάρχει, τότε ελέγχεται αν το messageId υπάρχει και αν ανήκει στα εισερχόμενά του. * Αν όχι, τότε η συνάρτηση επιστρέφει το String "1" * Αλλιώς, χρησιμοποιείται η συνάρτηση messageRead, ώστε να ενημερωθεί η κατάσταση του μηνύματος * και στέλνεται στον client ένα String, που ο πρώτος χαρακτήρας είναι το '0', ακολουθεί το username του αποστολέα μέσα σε παρενθέσεις και έπειτα το μήνυμα */ private String readMessage(String dataFromClient){ String tempAuthToken=""; int authToken; int messageId; int i; for(i=0;dataFromClient.charAt(i)!='^';i++){ tempAuthToken+=dataFromClient.charAt(i); } authToken=Integer.parseInt(tempAuthToken); messageId= Integer.parseInt(dataFromClient.substring(i+1)); Account account= allAccounts.get(authToken); if(account==null) return "2"; Message message= allMessages.get(messageId); if(message==null || !message.getReceiver().equals(account.getUsername())) return "1"; message.messageRead(); return "0" + "(" + message.getSender() + ")" + message.getBody(); } /** * Η συνάρτηση deleteMessage αποτελεί την έκτη λειτουργία - functionID=6 - * Σε αυτή την περίπτωση στο dataFromClient θα υπάρχει ένα String της μορφής: authToken^messageId * Αρχικά, ελέγχεται αν το authToken αντιστοιχίζεται σε κάποιον χρήστη * Αν δεν υπάρχει, τότε η συνάρτηση επιστρέφει την τιμή 2 * Αν υπάρχει, τότε ελέγχεται αν το messageId υπάρχει και αν ανήκει στα εισερχόμενά του. * Αν όχι, τότε η συνάρτηση επιστρέφει την τιμή 1 * Αλλιώς, το μήνυμα διαγράφεται και η συνάρτηση επιστρέφει την τιμή 0 */ private int deleteMessage(String dataFromClient){ String tempAuthToken=""; int authToken; int messageId; int i; for(i=0;dataFromClient.charAt(i)!='^';i++){ tempAuthToken+=dataFromClient.charAt(i); } authToken=Integer.parseInt(tempAuthToken); messageId= Integer.parseInt(dataFromClient.substring(i+1)); Account account= allAccounts.get(authToken); if(account==null) return 2; Message message= allMessages.get(messageId); if(message==null || !message.getReceiver().equals(account.getUsername())) return 1; allMessages.remove(messageId); for(i=0;i<account.getMessageBox().size();i++){ if(account.getMessageBox().get(i).getMessageId()==messageId) account.getMessageBox().remove(i); } return 0; } }
kefthymic/Client-Server
src/ServerThread.java
4,312
/** * Η συνάρτηση showAccounts αποτελεί τη δεύτερη λειτουργία - functionID=2 - * Σε αυτή την περίπτωση, στο dataFromClient θα υπάρχει μόνο το authToken ενός χρήστη. * Αρχικά, ελέγχεται αν το authToken αντιστοιχεί σε κάποιον χρήστη. * Αν ανήκει, τότε η συνάρτηση επιστρέφει όλα τα username των χρηστών * αλλιώς επιστρέφει ένα String που αναφέρει ότι το authToken δεν ανήκει σε κάποιον χρήστη **/
block_comment
el
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.util.HashMap; public class ServerThread extends Thread{ private Socket clientSocket; private DataInputStream inputFromClient; private DataOutputStream outputToClient; private HashMap<Integer, Account> allAccounts; private HashMap<Integer, Message> allMessages; public ServerThread(Socket clientSocket, HashMap<Integer, Account> allAccounts, HashMap<Integer, Message> allMessages){ try{ this.clientSocket=clientSocket; this.allAccounts= allAccounts; this.allMessages= allMessages; inputFromClient= new DataInputStream(this.clientSocket.getInputStream()); outputToClient= new DataOutputStream(this.clientSocket.getOutputStream()); }catch (IOException e){ System.err.println("Error: No Connection" +"\n" + e.getMessage()); } } /** * Στη μεταβλητή dataFromClient αποθηκεύεται το αίτημα του client. Στον πρώτο χαρακτήρα είναι αποθηκευμένος ένας αριθμός από το 1 έως το 6, ο οποίος αντιστοιχεί σε κάποια λειτουργία που θέλει να εκτελέσει ο client. * Αυτός ο αριθμός αποθηκεύεται στη μεταβλητή functionID. Ανάλογα με την τιμή του functionID καλείται μία διαφορετική συνάρτηση, που η κάθε μία παίρνει ως όρισμα την υπόλοιπη συμβολοσειρά της dataFromClient * Τα αποτελέσματα των συναρτήσεων επιστρέφονται ως απάντηση στον client * */ public void run(){ try{ String dataFromClient= inputFromClient.readUTF(); String functionId= dataFromClient.charAt(0)+""; dataFromClient=dataFromClient.substring(1); if(functionId.equals("1")){ outputToClient.writeInt(createAccount(dataFromClient)); } else if(functionId.equals("2")){ outputToClient.writeUTF(showAccounts(dataFromClient)); } else if(functionId.equals("3")){ outputToClient.writeInt(sendMessage(dataFromClient)); } else if(functionId.equals("4")){ outputToClient.writeUTF(showInbox(dataFromClient)); } else if(functionId.equals("5")){ outputToClient.writeUTF(readMessage(dataFromClient)); } else if(functionId.equals("6")){ outputToClient.writeInt(deleteMessage(dataFromClient)); } }catch (IOException e){ System.err.println("Error: " + e.getMessage()); } finally { try{ clientSocket.close(); }catch (IOException e){ System.err.println("Error" + e.getMessage()); } } } /** * Η συνάρτηση createAccount αποτελεί την πρώτη λειτουργία - functionID=1 - * Σε αυτή την περίπτωση, στο String dataFromClient θα υπάρχει μόνο το username * Αρχικά, ελέγχεται αν το username ανήκει σε κάποιον άλλο χρήστη. Αν ανήκει, τότε η συνάρτηση επιστρέφει την τιμή -1 * Έπειτα, ελέγχονται όλοι οι χαρακτήρες του username, ώστε να διαπιστωθεί αν υπάρχουν μη-έγκυροι χαρακτήρες. Αν υπάρχουν, τότε η συνάρτηση επιστρέφει την τιμή -2 * Τέλος, δημιουργείται ένα νέο account και η συνάρτηση επιστρέφει το authToken του χρήστη */ private int createAccount(String dataFromClient){ String newUsername= dataFromClient; for(Account account: allAccounts.values()){ if( account.getUsername().equals(newUsername)) return -1; } char character; for(int i=0;i<newUsername.length();i++){ character=newUsername.charAt(i); if(!( (character>='a' && character<='z') || (character>='A' && character<='Z') || (character>='0' && character<='9') || character=='_') ) return -2; } int newAuthToken= Server.getAuthToken(); Account account= new Account(newUsername, newAuthToken); allAccounts.put(newAuthToken, account); return newAuthToken; } /** * Η συνάρτηση showAccounts<SUF>*/ private String showAccounts(String dataFromClient){ int authToken= Integer.parseInt(dataFromClient); if(allAccounts.get(authToken)==null){ return "Invalid Auth Token"; } String temp=""; int i=0; for(Account account: allAccounts.values()){ temp+= ++i +". " + account.getUsername() + "\n"; } return temp; } /** * Η συνάρτηση sendMessage αποτελεί την τρίτη λειτουργία - functionID=3 - * Σε αυτή την περίπτωση στο dataFromClient θα υπάρχει ένα String της μορφής: authToken^recipient.length()^recipient^messageBody * * Αρχικά, ελέγχεται αν το authToken αντιστοιχεί σε κάποιον χρήστη. Αν δεν υπάρχει, τότε η συνάρτηση επιστρέφει την τιμή: 2 * ενώ αν υπάρχει τότε στη μεταβλητή sender αποθηκεύεται ο συγκεκριμένος χρήστης * Έπειτα, ελέγχεται αν υπάρχει χρήστης με username ίδιο με αυτό της μεταβλητής recipient. Αν δεν υπάρχει η συνάρτηση επιστρέφει την τιμή: 1, * Αλλιώς δημιουργείται και στέλνεται το μήνυμα και η συνάρτηση επιστρέφει την τιμή 0 */ private int sendMessage(String dataFromClient){ String tempAuthToken=""; int authToken; String recipient=""; String tempRecipient=""; int tempRecipient2; String messageBody=""; int i; for(i=0;dataFromClient.charAt(i)!='^';i++){ tempAuthToken+=dataFromClient.charAt(i)+""; } authToken=Integer.parseInt(tempAuthToken); for(i++;dataFromClient.charAt(i)!='^';i++){ tempRecipient+=dataFromClient.charAt(i); } tempRecipient2=Integer.parseInt(tempRecipient); for(i++;tempRecipient2>0;i++){ recipient+=dataFromClient.charAt(i); tempRecipient2--; } messageBody=dataFromClient.substring(i+1); Account sender= allAccounts.get(authToken); if(sender==null) return 2; Account receiver=null; for(Account account : allAccounts.values()){ if(account.getUsername().equals(recipient)){ receiver= account; } } if(receiver==null){ return 1; } int messId= Server.getMessageId(); Message message= new Message(sender.getUsername(), receiver.getUsername(), messageBody, messId); allMessages.put(messId, message); receiver.addMessage(message); return 0; } /** * Η συνάρτηση showInbox αποτελεί την τέταρτη λειτουργία - functionID=4 - * Σε αυτή την περίπτωση στο dataFromClient θα υπάρχει μόνο το authToken ενός χρήστη * Αν αντιστοιχεί σε κάποιον χρήστη, τότε η συνάρτηση θα επιστρέφει ένα String με όλα τα εισερχόμενα μηνύματα του χρήστη * αλλιώς, θα επιστρέφει ένα String που να αναφέρει ότι το authToken δεν ανήκει σε κάποιον χρήστη */ private String showInbox(String dataFromClient){ int authToken= Integer.parseInt(dataFromClient); Account account= allAccounts.get(authToken); if(account==null){ return "Invalid Auth Token"; } String answer=""; for(Message message: account.getMessageBox()){ answer+= message.getMessageId() +". from: " + message.getSender(); if(!message.getIsRead()) answer+="*"; answer+="\n"; } return answer; } /** * Η συνάρτηση readMessage αποτελεί την πέμπτη λειτουργία - functionID=5 - * Σε αυτή την περίπτωση στο dataFromClient θα υπάρχει ένα String της μορφής: authToken^messageId * Αρχικά, ελέγχεται αν το authToken αντιστοιχίζεται σε κάποιον χρήστη * Αν δεν υπάρχει, τότε η συνάρτηση επιστρέφει to String "2" * Αν υπάρχει, τότε ελέγχεται αν το messageId υπάρχει και αν ανήκει στα εισερχόμενά του. * Αν όχι, τότε η συνάρτηση επιστρέφει το String "1" * Αλλιώς, χρησιμοποιείται η συνάρτηση messageRead, ώστε να ενημερωθεί η κατάσταση του μηνύματος * και στέλνεται στον client ένα String, που ο πρώτος χαρακτήρας είναι το '0', ακολουθεί το username του αποστολέα μέσα σε παρενθέσεις και έπειτα το μήνυμα */ private String readMessage(String dataFromClient){ String tempAuthToken=""; int authToken; int messageId; int i; for(i=0;dataFromClient.charAt(i)!='^';i++){ tempAuthToken+=dataFromClient.charAt(i); } authToken=Integer.parseInt(tempAuthToken); messageId= Integer.parseInt(dataFromClient.substring(i+1)); Account account= allAccounts.get(authToken); if(account==null) return "2"; Message message= allMessages.get(messageId); if(message==null || !message.getReceiver().equals(account.getUsername())) return "1"; message.messageRead(); return "0" + "(" + message.getSender() + ")" + message.getBody(); } /** * Η συνάρτηση deleteMessage αποτελεί την έκτη λειτουργία - functionID=6 - * Σε αυτή την περίπτωση στο dataFromClient θα υπάρχει ένα String της μορφής: authToken^messageId * Αρχικά, ελέγχεται αν το authToken αντιστοιχίζεται σε κάποιον χρήστη * Αν δεν υπάρχει, τότε η συνάρτηση επιστρέφει την τιμή 2 * Αν υπάρχει, τότε ελέγχεται αν το messageId υπάρχει και αν ανήκει στα εισερχόμενά του. * Αν όχι, τότε η συνάρτηση επιστρέφει την τιμή 1 * Αλλιώς, το μήνυμα διαγράφεται και η συνάρτηση επιστρέφει την τιμή 0 */ private int deleteMessage(String dataFromClient){ String tempAuthToken=""; int authToken; int messageId; int i; for(i=0;dataFromClient.charAt(i)!='^';i++){ tempAuthToken+=dataFromClient.charAt(i); } authToken=Integer.parseInt(tempAuthToken); messageId= Integer.parseInt(dataFromClient.substring(i+1)); Account account= allAccounts.get(authToken); if(account==null) return 2; Message message= allMessages.get(messageId); if(message==null || !message.getReceiver().equals(account.getUsername())) return 1; allMessages.remove(messageId); for(i=0;i<account.getMessageBox().size();i++){ if(account.getMessageBox().get(i).getMessageId()==messageId) account.getMessageBox().remove(i); } return 0; } }
9486_0
package E07; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; public class Main { public static void main (String[] args) throws LathosHmerominia, LathosArithmos, LathosEmail { Scanner scK = new Scanner(System.in); Scanner scS = new Scanner(System.in); Scanner scH = new Scanner(System.in); Scanner scE = new Scanner(System.in); // Άσκηση 1 Foititis[] pinFoitites = new Foititis[10]; pinFoitites[0] = new Foititis(18, "Πολυκάρπου Κλέων", "6987459023", "2541034571",(float)(Math.random() * 11)); pinFoitites[1] = new Foititis(18, "Γεωργίου Αριστέα","6977420681", "2591039687",(float)(Math.random() * 11)); pinFoitites[2] = new Foititis(18, "Πετρίδου Δανάη"," ", " ",(float)(Math.random() * 11)); pinFoitites[3] = new Foititis(18, "Χατζημιχάλης Βασίλειος","6933090166", "2551041270",(float)(Math.random() * 11)); pinFoitites[4] = new Foititis(18, "Πασχαλίδου Πελαγία","6901402995", "2310673092",(float)(Math.random() * 11)); pinFoitites[5] = new Foititis(18, "Παπαδόπουλος Νικόλαος","6933840992", "2531076190",(float)(Math.random() * 11)); pinFoitites[6] = new Foititis(18, "Γεωργιάδης Σταύρος","6944092911", "2521089461",(float)(Math.random() * 11)); pinFoitites[7] = new Foititis(18, "Αλεξανδρίδης Ιωάννης","6933671944", "2310039849",(float)(Math.random() * 11)); pinFoitites[8] = new Foititis(18, "Χρηστίδης Χρήστος","6901987022", "2541056723",(float)(Math.random() * 11)); pinFoitites[9] = new Foititis(18, "Παπαντωνίου Αναξίμανδρος","6977239628", "2591043543",(float)(Math.random() * 11)); System.out.println("Λίστα φοιτητών"); System.out.println("------------------------------------"); emfanisiFoititwn(pinFoitites); // Άσκηση 2 System.out.print("\nΔώσε τον αριθμό κινητού τηλεφώνου του 3ου φοιτητή: "); String kin = scK.nextLine(); char first = kin.charAt(0); if (!onlyDigits(kin, kin.length())) throw new LathosArithmos("Δεν είναι σωστός ο αριθμός που εισάχθηκε"); if (first == '6' && kin.length() == 10) pinFoitites[2].setKinito(kin); else throw new LathosArithmos("Δεν είναι σωστός ο αριθμός που εισάχθηκε"); System.out.print("\nΔώσε τον αριθμό σταθερού τηλεφώνου του 3ου φοιτητή: "); String stath = scS.nextLine(); first = stath.charAt(0); if (!onlyDigits(stath, stath.length())) throw new LathosArithmos("Δεν είναι σωστός ο αριθμός που εισάχθηκε"); if (first == '2' && stath.length() == 10) pinFoitites[2].setStathero(stath); else throw new LathosArithmos("Δεν είναι σωστός ο αριθμός που εισάχθηκε"); // Άσκηση 3 System.out.print("\nΔώσε την ημερομηνία γέννησης του 3ου φοιτητή (ΗΗ/ΜΜ/YYYY): "); String hmer = scH.nextLine(); String[] h = new String[5]; h[0] = hmer.substring(0,1); h[1] = hmer.substring(3,4); h[2] = hmer.substring(6,9); char[] c = new char[2]; c[0] = hmer.charAt(2); c[1] = hmer.charAt(5); int ilikia = Integer.parseInt(h[2]); ilikia = 2021 - ilikia; if ((onlyDigits(h[0], h[0].length()) || onlyDigits(h[1], h[1].length()) || onlyDigits(h[2], h[2].length()))) { if (c[0] == '/' || c[1] == '/') { if (ilikia >= 18) pinFoitites[2].setHmeromGennisis(inHmeromGennisis(hmer)); else throw new LathosHmerominia("Η ηλικία είναι κάτω από το 18"); } else throw new LathosHmerominia("Δεν είναι σωστή η ημερομηνία που εισάχθηκε"); } else throw new LathosHmerominia("Δεν είναι σωστή η ημερομηνία που εισάχθηκε"); // Άσκηση 4 System.out.print("\nΔώσε το email του 3ου φοιτητή: "); String email = scE.nextLine(); String[] mail = new String[3]; mail[0] = email.substring(0,2); mail[1] = email.substring(3,9); mail[2] = email.substring(10,20); // Tο if είναι πάντα false if (mail[0].equals("iee")){ if (onlyDigits(mail[1], mail[1].length())){ if (mail[2].matches("@iee.ihu.gr")) pinFoitites[2].setEmail(email); else throw new LathosEmail("Δεν είναι σωστό το email που εισάχθηκε"); } else throw new LathosEmail("Δεν είναι σωστό το email που εισάχθηκε"); } else throw new LathosEmail("Δεν είναι σωστό το email που εισάχθηκε"); } public static void emfanisiFoititwn(Foititis[] pinFoitites) { for (Foititis i : pinFoitites) { System.out.println(i); } } public static boolean onlyDigits(String str, int n) { for (int i = 0; i < n; i++) { if (!(str.charAt(i) >= '0' && str.charAt(i) <= '9')) return false; } return true; } public static Date inHmeromGennisis(String H){ Date date = convertStrToDate(H); return date; } private static Date convertStrToDate(String hmeromStr) { DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); Date hmerom = null; try { hmerom = df.parse(hmeromStr); } catch (Exception ex){ System.out.println(ex); } return hmerom; } }
kindi24/IEE-Labs
2. Object-Oriented Programming/Ε07 - Exceptions/E07/Main.java
2,322
// Tο if είναι πάντα false
line_comment
el
package E07; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; public class Main { public static void main (String[] args) throws LathosHmerominia, LathosArithmos, LathosEmail { Scanner scK = new Scanner(System.in); Scanner scS = new Scanner(System.in); Scanner scH = new Scanner(System.in); Scanner scE = new Scanner(System.in); // Άσκηση 1 Foititis[] pinFoitites = new Foititis[10]; pinFoitites[0] = new Foititis(18, "Πολυκάρπου Κλέων", "6987459023", "2541034571",(float)(Math.random() * 11)); pinFoitites[1] = new Foititis(18, "Γεωργίου Αριστέα","6977420681", "2591039687",(float)(Math.random() * 11)); pinFoitites[2] = new Foititis(18, "Πετρίδου Δανάη"," ", " ",(float)(Math.random() * 11)); pinFoitites[3] = new Foititis(18, "Χατζημιχάλης Βασίλειος","6933090166", "2551041270",(float)(Math.random() * 11)); pinFoitites[4] = new Foititis(18, "Πασχαλίδου Πελαγία","6901402995", "2310673092",(float)(Math.random() * 11)); pinFoitites[5] = new Foititis(18, "Παπαδόπουλος Νικόλαος","6933840992", "2531076190",(float)(Math.random() * 11)); pinFoitites[6] = new Foititis(18, "Γεωργιάδης Σταύρος","6944092911", "2521089461",(float)(Math.random() * 11)); pinFoitites[7] = new Foititis(18, "Αλεξανδρίδης Ιωάννης","6933671944", "2310039849",(float)(Math.random() * 11)); pinFoitites[8] = new Foititis(18, "Χρηστίδης Χρήστος","6901987022", "2541056723",(float)(Math.random() * 11)); pinFoitites[9] = new Foititis(18, "Παπαντωνίου Αναξίμανδρος","6977239628", "2591043543",(float)(Math.random() * 11)); System.out.println("Λίστα φοιτητών"); System.out.println("------------------------------------"); emfanisiFoititwn(pinFoitites); // Άσκηση 2 System.out.print("\nΔώσε τον αριθμό κινητού τηλεφώνου του 3ου φοιτητή: "); String kin = scK.nextLine(); char first = kin.charAt(0); if (!onlyDigits(kin, kin.length())) throw new LathosArithmos("Δεν είναι σωστός ο αριθμός που εισάχθηκε"); if (first == '6' && kin.length() == 10) pinFoitites[2].setKinito(kin); else throw new LathosArithmos("Δεν είναι σωστός ο αριθμός που εισάχθηκε"); System.out.print("\nΔώσε τον αριθμό σταθερού τηλεφώνου του 3ου φοιτητή: "); String stath = scS.nextLine(); first = stath.charAt(0); if (!onlyDigits(stath, stath.length())) throw new LathosArithmos("Δεν είναι σωστός ο αριθμός που εισάχθηκε"); if (first == '2' && stath.length() == 10) pinFoitites[2].setStathero(stath); else throw new LathosArithmos("Δεν είναι σωστός ο αριθμός που εισάχθηκε"); // Άσκηση 3 System.out.print("\nΔώσε την ημερομηνία γέννησης του 3ου φοιτητή (ΗΗ/ΜΜ/YYYY): "); String hmer = scH.nextLine(); String[] h = new String[5]; h[0] = hmer.substring(0,1); h[1] = hmer.substring(3,4); h[2] = hmer.substring(6,9); char[] c = new char[2]; c[0] = hmer.charAt(2); c[1] = hmer.charAt(5); int ilikia = Integer.parseInt(h[2]); ilikia = 2021 - ilikia; if ((onlyDigits(h[0], h[0].length()) || onlyDigits(h[1], h[1].length()) || onlyDigits(h[2], h[2].length()))) { if (c[0] == '/' || c[1] == '/') { if (ilikia >= 18) pinFoitites[2].setHmeromGennisis(inHmeromGennisis(hmer)); else throw new LathosHmerominia("Η ηλικία είναι κάτω από το 18"); } else throw new LathosHmerominia("Δεν είναι σωστή η ημερομηνία που εισάχθηκε"); } else throw new LathosHmerominia("Δεν είναι σωστή η ημερομηνία που εισάχθηκε"); // Άσκηση 4 System.out.print("\nΔώσε το email του 3ου φοιτητή: "); String email = scE.nextLine(); String[] mail = new String[3]; mail[0] = email.substring(0,2); mail[1] = email.substring(3,9); mail[2] = email.substring(10,20); // Tο if<SUF> if (mail[0].equals("iee")){ if (onlyDigits(mail[1], mail[1].length())){ if (mail[2].matches("@iee.ihu.gr")) pinFoitites[2].setEmail(email); else throw new LathosEmail("Δεν είναι σωστό το email που εισάχθηκε"); } else throw new LathosEmail("Δεν είναι σωστό το email που εισάχθηκε"); } else throw new LathosEmail("Δεν είναι σωστό το email που εισάχθηκε"); } public static void emfanisiFoititwn(Foititis[] pinFoitites) { for (Foititis i : pinFoitites) { System.out.println(i); } } public static boolean onlyDigits(String str, int n) { for (int i = 0; i < n; i++) { if (!(str.charAt(i) >= '0' && str.charAt(i) <= '9')) return false; } return true; } public static Date inHmeromGennisis(String H){ Date date = convertStrToDate(H); return date; } private static Date convertStrToDate(String hmeromStr) { DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); Date hmerom = null; try { hmerom = df.parse(hmeromStr); } catch (Exception ex){ System.out.println(ex); } return hmerom; } }
17348_3
package InternetRadio; public class Song { private String title; // ο τίτλος του τραγουδιού private String artist; // ο καλλιτέχνης του τραγουδιού // οι πιθανές μουσικές κατηγορίες των τραγουδιών public static final String[] GENRES = {"rock", "pop","blues", "soul","disco", "hip-hop"}; // η βαρύτητα των αντίστοιχων ειδών στο κάθε τραγούδι // μπορεί να είναι μηδέν-το άθροισμα όλων των βαρών // είναι 100 private double[] weights; // default κατασκευαστής public Song() { } // κατασκευαστής πεδίων public Song(String title, String artist, double[] weights) { this.title = title; this.artist = artist; this.weights = weights; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getArtist() { return artist; } public void setArtist(String artist) { this.artist = artist; } public double[] getWeights() { return weights; } public void setWeights(double[] weights) { this.weights = weights; } }
konkokonos/Java_Projects
InternetRadio/Song.java
431
// η βαρύτητα των αντίστοιχων ειδών στο κάθε τραγούδι
line_comment
el
package InternetRadio; public class Song { private String title; // ο τίτλος του τραγουδιού private String artist; // ο καλλιτέχνης του τραγουδιού // οι πιθανές μουσικές κατηγορίες των τραγουδιών public static final String[] GENRES = {"rock", "pop","blues", "soul","disco", "hip-hop"}; // η βαρύτητα<SUF> // μπορεί να είναι μηδέν-το άθροισμα όλων των βαρών // είναι 100 private double[] weights; // default κατασκευαστής public Song() { } // κατασκευαστής πεδίων public Song(String title, String artist, double[] weights) { this.title = title; this.artist = artist; this.weights = weights; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getArtist() { return artist; } public void setArtist(String artist) { this.artist = artist; } public double[] getWeights() { return weights; } public void setWeights(double[] weights) { this.weights = weights; } }
5822_0
package gr.uom.thesis.runners; import gr.uom.thesis.coverage.TotalCoverageComparator; import gr.uom.thesis.coverage.TotalCoverageComparatorRepository; import gr.uom.thesis.project.dto.AnalyzedProjectDTO; import gr.uom.thesis.project.entities.AnalyzedProject; import gr.uom.thesis.project.repositories.AnalyzedProjectFileRepository; import gr.uom.thesis.project.repositories.AnalyzedProjectRepository; import gr.uom.thesis.utils.AsyncFunctions; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import java.util.List; //@Component @Slf4j public class InitRunner implements CommandLineRunner { private final AsyncFunctions asyncFunctions; private final AnalyzedProjectRepository analyzedProjectRepository; private final AnalyzedProjectFileRepository analyzedProjectFileRepository; private final TotalCoverageComparatorRepository coverageComparatorRepository; public InitRunner(AsyncFunctions asyncFunctions, AnalyzedProjectRepository analyzedProjectRepository, AnalyzedProjectFileRepository analyzedProjectFileRepository, TotalCoverageComparatorRepository coverageComparatorRepository) { this.asyncFunctions = asyncFunctions; this.analyzedProjectRepository = analyzedProjectRepository; this.analyzedProjectFileRepository = analyzedProjectFileRepository; this.coverageComparatorRepository = coverageComparatorRepository; } @Override public void run(String... args) throws Exception { AnalyzedProjectDTO dto = asyncFunctions .getProjectByGitUrl("https://github.com/niekwit/pyseqtools").get().getBody(); assert dto != null; AnalyzedProject analyzedProject = new AnalyzedProject(); BeanUtils.copyProperties(dto, analyzedProject); // log.info(dto.toString()); assert dto.getFiles() != null; int dtoTotalCoverage = dto.getTotalCoverage(); List<AnalyzedProject> allProjects = analyzedProjectRepository.findAll(); for (AnalyzedProject project : allProjects) { int currentTotalCoverage = project.getTotalCoverage(); int totalCoverageDifference = currentTotalCoverage - dtoTotalCoverage; TotalCoverageComparator comparator = TotalCoverageComparator.builder() .analyzedProject1(project) .analyzedProject2(analyzedProject) .totalCoverageDifference(totalCoverageDifference) .build(); coverageComparatorRepository.save(comparator); } /* * For each analyzed project add to Total*ComparatorRepository * Λειτουργεί σαν "πίνακας γειτνίασης" * */ } }
konkos/thesis
src/main/java/gr/uom/thesis/runners/InitRunner.java
616
/* * For each analyzed project add to Total*ComparatorRepository * Λειτουργεί σαν "πίνακας γειτνίασης" * */
block_comment
el
package gr.uom.thesis.runners; import gr.uom.thesis.coverage.TotalCoverageComparator; import gr.uom.thesis.coverage.TotalCoverageComparatorRepository; import gr.uom.thesis.project.dto.AnalyzedProjectDTO; import gr.uom.thesis.project.entities.AnalyzedProject; import gr.uom.thesis.project.repositories.AnalyzedProjectFileRepository; import gr.uom.thesis.project.repositories.AnalyzedProjectRepository; import gr.uom.thesis.utils.AsyncFunctions; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import java.util.List; //@Component @Slf4j public class InitRunner implements CommandLineRunner { private final AsyncFunctions asyncFunctions; private final AnalyzedProjectRepository analyzedProjectRepository; private final AnalyzedProjectFileRepository analyzedProjectFileRepository; private final TotalCoverageComparatorRepository coverageComparatorRepository; public InitRunner(AsyncFunctions asyncFunctions, AnalyzedProjectRepository analyzedProjectRepository, AnalyzedProjectFileRepository analyzedProjectFileRepository, TotalCoverageComparatorRepository coverageComparatorRepository) { this.asyncFunctions = asyncFunctions; this.analyzedProjectRepository = analyzedProjectRepository; this.analyzedProjectFileRepository = analyzedProjectFileRepository; this.coverageComparatorRepository = coverageComparatorRepository; } @Override public void run(String... args) throws Exception { AnalyzedProjectDTO dto = asyncFunctions .getProjectByGitUrl("https://github.com/niekwit/pyseqtools").get().getBody(); assert dto != null; AnalyzedProject analyzedProject = new AnalyzedProject(); BeanUtils.copyProperties(dto, analyzedProject); // log.info(dto.toString()); assert dto.getFiles() != null; int dtoTotalCoverage = dto.getTotalCoverage(); List<AnalyzedProject> allProjects = analyzedProjectRepository.findAll(); for (AnalyzedProject project : allProjects) { int currentTotalCoverage = project.getTotalCoverage(); int totalCoverageDifference = currentTotalCoverage - dtoTotalCoverage; TotalCoverageComparator comparator = TotalCoverageComparator.builder() .analyzedProject1(project) .analyzedProject2(analyzedProject) .totalCoverageDifference(totalCoverageDifference) .build(); coverageComparatorRepository.save(comparator); } /* * For each analyzed<SUF>*/ } }
360_30
//Τσιάκας Κοσμάς - ΑΕΜ 8255 - 6987921920 - [email protected] //Παπάζογλου Αθανάσιος - AEM 8324 - 6976939155 - [email protected] package gr.auth.ee.dsproject.proximity.defplayers; import java.util.ArrayList; import gr.auth.ee.dsproject.proximity.board.Board; import gr.auth.ee.dsproject.proximity.board.ProximityUtilities; import gr.auth.ee.dsproject.proximity.board.Tile; //Η κλάση MinMaxPlayer υλοποιεί έναν παίκτη ο οποίος χρησιμοποιεί //τις συναρτήσεις του για τη δημιουργία ενός δέντρου διαθέσιμων κινήσεων //και με τον αλγόριθμο Minmax προσπαθεί να βρεί την βέλτιστη κίνηση σε βάθος //2 κινήσεων. Τα χαρακτηριστικά του παίκτη είναι το σκορ του, το όνομα του, //to id του και ο αριθμός των πλακιδίων που του ανήκουν. public class MinMaxPlayer implements AbstractPlayer { int score; int id; String name; int numOfTiles; public MinMaxPlayer (Integer pid) { id = pid; name = "MinMaxPlayer"; } public String getName () { return name; } public int getNumOfTiles () { return numOfTiles; } public void setNumOfTiles (int tiles) { numOfTiles = tiles; } public int getId () { return id; } public void setScore (int score) { this.score = score; } public int getScore () { return score; } public void setId (int id) { this.id = id; } public void setName (String name) { this.name = name; } //Η συνάρτηση getNextMove(..) υλοποιεί την επιλογή της βέλτιστης για εμάς κίνησης //Χρησιμοποιεί το υπάρχων board για να δημιουργήσει τη ρίζα του δέντρου στο οποίο θα αποθηκεύονται //όλες οι διαθέσιμες κινήσεις. Αρχικά, προσωμοιώνει μια δική μας κίνηση //μέσω της συνάρτησης createMySubTree(..), η οποία στο εσωτερικό της προσωμοιώνει και //μία κίνηση του αντιπάλου. Στο τέλος της συνάρτησης μας, μέσω της chooseMinMaxMove(..) //επιλέγεται η καλύτερη δυνατή κίνηση και επιστρέφεται μέσω ενός πίνακα 1x3 οι συντεταγμένες //της καλύτερης θέσης και ο αριθμός που θα τοποθετηθεί σε αυτήν. public int[] getNextMove (Board board, int number) { int[] nextMove=new int [3];//[x,y,randomNumber] int[] index=new int[2]; //Δημιουργία ενός κόμβου που θα είναι η ρίζα του δέντρου απο το υπάρχων board Node82558324 root=new Node82558324(board); createMySubtree(root,1,Board.getNextTenNumbersToBePlayed()[0]);//το δέντρο έχει τελειώσει, //καθώς αυτή η συνάρτηση προσωμοιώνει τόσο τη δική μας κίνηση όσο και του αντιπάλου index=chooseMinMaxMove(root);//επιλογή της καλύτερης δυνατής κίνησης nextMove[0]=index[0]; nextMove[1]=index[1]; nextMove[2]=number; //επιστροφή των συντεταγμένων της βέλτιστης θέσης //και του αριθμού που θα τοποθετηθεί στη θέση αυτή return nextMove; } //Η συνάρτηση createMySubtree(..) εντοπίζει τις κενές θέσεις του board //και για κάθε μία από αυτές δημιουργεί κλώνους του board, όπως θα ήταν εάν έπαιζα //στην θέση αυτή το πλακίδιο με την τιμή number. Το board που προκύπτει //προστίθεται ως child του parent που παίρνει ως όρισμα η συνάρτηση. //Για να ολοκληρωθεί το δέντρο στο τέλος καλείται η συνάρτηση createOpponentSubtree(..) //η οποία θα το συμπληρώσει με τους κλάδους για τις κινήσεις του αντιπάλου public void createMySubtree (Node82558324 parent, int depth, int number) { //βρίσκω τα ελεύθερα tiles στο board for (int i=0;i<ProximityUtilities.NUMBER_OF_COLUMNS;i++){//σκανάρω το board for (int j=0;j<ProximityUtilities.NUMBER_OF_ROWS;j++){//για διαθέσιμα tiles if (parent.getNodeBoard().getTile(i,j).getPlayerId()==0){//αν υπάρχει διαθέσιμο tile //δημιουργώ έναν κλώνο του board του parent προσωμοιώνοντας μια κίνηση //δική μου βάζοντας το tile με τιμή number στη θέση (i,j) Board cloneBoard=ProximityUtilities.boardAfterMove(this.getId(),parent.getNodeBoard(),i,j,number); //δημιουργώ έναν νέο κόμβο με το νέο board (μετά την κίνηση) //για να γίνει αυτός ο κόμβος το child του parent //να προστεθεί δηλαδή στο arrayList children Node82558324 child=new Node82558324(parent, cloneBoard); child.setNodeMove(i,j,number); child.setNodeDepth(depth); child.setNodeEvaluation(0);//το evaluation του κόμβου αυτόυ θα προκύψει στη συνέχεια parent.setChildren(child); //καλώ τη συνάρτηση για τη συμπλήρωση του δέντρου με την κίνηση του αντιπάλου createOpponentSubtree(child,depth+1,Board.getNextTenNumbersToBePlayed()[1]); } } } } //Η συνάρτηση createOpponentSubtree(..) βρίσκει τις θέσεις που είναι πλέον διαθέσιμες στο board //και για κάθε μία από αυτές δημιουργεί έναν κλώνο του board προσωμοιώνοντας //μία κίνηση του αντιπάλου στη θέση αυτή. Μετά, θα αξιολογηθεί η κίνηση αυτή που υποδεικνύει το φύλλο //και το board που προκύπτει θα προστεθεί ως child του parent public void createOpponentSubtree (Node82558324 child, int depth, int number) { //πρέπει να βρω το id του αντιπάλου μου, εφόσον ξέρω μόνο το δικό μου int opponentId=1; if (this.getId()==1){ opponentId=2; } //βρίσκω τα ελεύθερα tiles στο board for (int i=0;i<ProximityUtilities.NUMBER_OF_COLUMNS;i++){//σκανάρω το board for (int j=0;j<ProximityUtilities.NUMBER_OF_ROWS;j++){//για διαθέσιμα tiles if (child.getNodeBoard().getTile(i,j).getPlayerId()==0){//αν υπάρχει διαθέσιμο tile //δημιουργώ έναν κλώνο του board, όπως θα ήταν εάν έπαιζε ο αντίπαλος //στη θέση (i,j) ένα πλακίδιο με τιμή randomNumber Board cloneBoard = ProximityUtilities.boardAfterMove(opponentId,child.getNodeBoard(),i,j,number); //δημιουργώ ένα αντικείμενο τύπου Node που περιέχει το νέο board //και τα υπόλοιπα στοιχεία Node82558324 leaf=new Node82558324(child, cloneBoard); //αξιολογώ τη θέση (i,j) int opponentScore=0; for (int k=0;k<ProximityUtilities.NUMBER_OF_COLUMNS;k++){ for (int l=0;l<ProximityUtilities.NUMBER_OF_ROWS;l++){ if (leaf.getNodeBoard().getTile(k,l).getPlayerId()==opponentId){ opponentScore=opponentScore+leaf.getNodeBoard().getTile(k,l).getScore(); } } } int evaluation=this.getScore()-opponentScore; leaf.setNodeEvaluation(evaluation); leaf.setNodeMove(i,j,number); leaf.setNodeDepth(depth); //προσθέτω το νέο στοιχείο στο arrayList του parent της συνάρτησης //που είναι το child που δημιούργησε η συνάρτηση createMySubtree(..) child.setChildren(leaf); } } } } //Η συνάρτηση chooseMinMaxMove(..) περιλαμβάνει έναν αλγόριθμo Minmax για να βρεί //την καλύτερη διαθέσιμη κίνηση. Για να βρεί τη θέση αυτή,αρχικά αποθηκεύει τα παιδιά //της ρίζας, και για κάθε παιδί αποθηκεύει τα φύλλα του. Σε βάθος 2, κρατάει την //μικρότερη τιμή που βρίσκει από κάθε φύλλο και η τιμή αυτή περνάει στα παιδιά. //Σε βάθος 1, κρατάει την μεγαλύτερη τιμή από τα παιδιά και αυτή περνάει στη ρίζα //που είναι και η τελική τιμή που θα επιλέξουμε. //Στο τέλος επιστρέφουμε τις συντεταγμένες της καλύτερης θέσης public int[] chooseMinMaxMove(Node82558324 root) { int[] index=new int[2];//ο πίνακας που θα περιέχει την καλύτερη θέση //αποθηκεύω τα παιδιά της ρίζας σε μια ArrayList-ήμαστε σε βάθος 1 ArrayList<Node82558324> children= root.getChildren(); //ο αριμός των παιδιών της ρίζας int numberOfChildren=0; numberOfChildren=children.size(); //στη μεταβλητή maxEval θα αποθηκεύσω το μεγαλύτερο από τα evaluation στο επίπεδο 1 double maxEval=children.get(0).getNodeEvaluation(); //κρατάω τις συντεταγμένες για την καλύτερη θέση στο maxNodeMove (x,y,number) int[] maxNodeMove=children.get(0).getNodeMove(); //σε κάθε επανάληψη σκανάρω ένα παιδί της ρίζας for (int i=0;i<numberOfChildren;i++){ //έχω τα φύλλα του κόμβου-βάθος 2 ArrayList<Node82558324> leaves=children.get(i).getChildren(); //υπολογίζω πόσα φύλλα έχει ο κάθε κόμβος int numberOfLeaves = leaves.size(); //στη μεταβλητή minEval θα αποθηκεύσω το μικρότερο από τα evaluation σε βάθος 2 double minEval=leaves.get(0).getNodeEvaluation(); //(x, y , randomNumber) για την θέση που επιλέγεται int[] minNodeMove=leaves.get(0).getNodeMove(); //σκανάρω κάθε φύλλο του παιδιού i for (int j=1;j<numberOfLeaves;j++){ //βρίσκω ποιο είναι το μικρότερο evaluation if (leaves.get(j).getNodeEvaluation()<minEval){ minEval=leaves.get(j).getNodeEvaluation(); minNodeMove=leaves.get(j).getNodeMove(); } } //ανεβάζω σε κάθε κόμβο την μικρότερη από τις τιμές των φύλλων children.get(i).setNodeEvaluation(minEval); children.get(i).setNodeMove(minNodeMove); //αν ήμαστε στην 1η επανάληψη η σύγκριση είναι περιττή if (i==0) continue; //εντοπίζω το μεγαλύτερο evaluation, αποθηκεύω παράλληλα και τις συντεταγμένες if(children.get(i).getNodeEvaluation()>maxEval){ maxEval=children.get(i).getNodeEvaluation(); maxNodeMove=children.get(i).getNodeMove(); } } //αφου σκανάρω όλα τα παιδιά και φύλλα, στη ρίζα βάζω την τιμή της καλύτερης συνολικής κίνησης και τις συντεταγμένες root.setNodeEvaluation(maxEval); root.setNodeMove(maxNodeMove); //επιστρέφω τις συντεταγμένες της καλυτερης κίνησης index[0]=root.getNodeMove()[0]; index[1]=root.getNodeMove()[1]; return index; } }
kosmastsk/University-projects
Data Structures/Proximity Part C.1/src/gr/auth/ee/dsproject/proximity/defplayers/MinMaxPlayer.java
5,186
//δημιουργώ έναν κλώνο του board του parent προσωμοιώνοντας μια κίνηση
line_comment
el
//Τσιάκας Κοσμάς - ΑΕΜ 8255 - 6987921920 - [email protected] //Παπάζογλου Αθανάσιος - AEM 8324 - 6976939155 - [email protected] package gr.auth.ee.dsproject.proximity.defplayers; import java.util.ArrayList; import gr.auth.ee.dsproject.proximity.board.Board; import gr.auth.ee.dsproject.proximity.board.ProximityUtilities; import gr.auth.ee.dsproject.proximity.board.Tile; //Η κλάση MinMaxPlayer υλοποιεί έναν παίκτη ο οποίος χρησιμοποιεί //τις συναρτήσεις του για τη δημιουργία ενός δέντρου διαθέσιμων κινήσεων //και με τον αλγόριθμο Minmax προσπαθεί να βρεί την βέλτιστη κίνηση σε βάθος //2 κινήσεων. Τα χαρακτηριστικά του παίκτη είναι το σκορ του, το όνομα του, //to id του και ο αριθμός των πλακιδίων που του ανήκουν. public class MinMaxPlayer implements AbstractPlayer { int score; int id; String name; int numOfTiles; public MinMaxPlayer (Integer pid) { id = pid; name = "MinMaxPlayer"; } public String getName () { return name; } public int getNumOfTiles () { return numOfTiles; } public void setNumOfTiles (int tiles) { numOfTiles = tiles; } public int getId () { return id; } public void setScore (int score) { this.score = score; } public int getScore () { return score; } public void setId (int id) { this.id = id; } public void setName (String name) { this.name = name; } //Η συνάρτηση getNextMove(..) υλοποιεί την επιλογή της βέλτιστης για εμάς κίνησης //Χρησιμοποιεί το υπάρχων board για να δημιουργήσει τη ρίζα του δέντρου στο οποίο θα αποθηκεύονται //όλες οι διαθέσιμες κινήσεις. Αρχικά, προσωμοιώνει μια δική μας κίνηση //μέσω της συνάρτησης createMySubTree(..), η οποία στο εσωτερικό της προσωμοιώνει και //μία κίνηση του αντιπάλου. Στο τέλος της συνάρτησης μας, μέσω της chooseMinMaxMove(..) //επιλέγεται η καλύτερη δυνατή κίνηση και επιστρέφεται μέσω ενός πίνακα 1x3 οι συντεταγμένες //της καλύτερης θέσης και ο αριθμός που θα τοποθετηθεί σε αυτήν. public int[] getNextMove (Board board, int number) { int[] nextMove=new int [3];//[x,y,randomNumber] int[] index=new int[2]; //Δημιουργία ενός κόμβου που θα είναι η ρίζα του δέντρου απο το υπάρχων board Node82558324 root=new Node82558324(board); createMySubtree(root,1,Board.getNextTenNumbersToBePlayed()[0]);//το δέντρο έχει τελειώσει, //καθώς αυτή η συνάρτηση προσωμοιώνει τόσο τη δική μας κίνηση όσο και του αντιπάλου index=chooseMinMaxMove(root);//επιλογή της καλύτερης δυνατής κίνησης nextMove[0]=index[0]; nextMove[1]=index[1]; nextMove[2]=number; //επιστροφή των συντεταγμένων της βέλτιστης θέσης //και του αριθμού που θα τοποθετηθεί στη θέση αυτή return nextMove; } //Η συνάρτηση createMySubtree(..) εντοπίζει τις κενές θέσεις του board //και για κάθε μία από αυτές δημιουργεί κλώνους του board, όπως θα ήταν εάν έπαιζα //στην θέση αυτή το πλακίδιο με την τιμή number. Το board που προκύπτει //προστίθεται ως child του parent που παίρνει ως όρισμα η συνάρτηση. //Για να ολοκληρωθεί το δέντρο στο τέλος καλείται η συνάρτηση createOpponentSubtree(..) //η οποία θα το συμπληρώσει με τους κλάδους για τις κινήσεις του αντιπάλου public void createMySubtree (Node82558324 parent, int depth, int number) { //βρίσκω τα ελεύθερα tiles στο board for (int i=0;i<ProximityUtilities.NUMBER_OF_COLUMNS;i++){//σκανάρω το board for (int j=0;j<ProximityUtilities.NUMBER_OF_ROWS;j++){//για διαθέσιμα tiles if (parent.getNodeBoard().getTile(i,j).getPlayerId()==0){//αν υπάρχει διαθέσιμο tile //δημιουργώ έναν<SUF> //δική μου βάζοντας το tile με τιμή number στη θέση (i,j) Board cloneBoard=ProximityUtilities.boardAfterMove(this.getId(),parent.getNodeBoard(),i,j,number); //δημιουργώ έναν νέο κόμβο με το νέο board (μετά την κίνηση) //για να γίνει αυτός ο κόμβος το child του parent //να προστεθεί δηλαδή στο arrayList children Node82558324 child=new Node82558324(parent, cloneBoard); child.setNodeMove(i,j,number); child.setNodeDepth(depth); child.setNodeEvaluation(0);//το evaluation του κόμβου αυτόυ θα προκύψει στη συνέχεια parent.setChildren(child); //καλώ τη συνάρτηση για τη συμπλήρωση του δέντρου με την κίνηση του αντιπάλου createOpponentSubtree(child,depth+1,Board.getNextTenNumbersToBePlayed()[1]); } } } } //Η συνάρτηση createOpponentSubtree(..) βρίσκει τις θέσεις που είναι πλέον διαθέσιμες στο board //και για κάθε μία από αυτές δημιουργεί έναν κλώνο του board προσωμοιώνοντας //μία κίνηση του αντιπάλου στη θέση αυτή. Μετά, θα αξιολογηθεί η κίνηση αυτή που υποδεικνύει το φύλλο //και το board που προκύπτει θα προστεθεί ως child του parent public void createOpponentSubtree (Node82558324 child, int depth, int number) { //πρέπει να βρω το id του αντιπάλου μου, εφόσον ξέρω μόνο το δικό μου int opponentId=1; if (this.getId()==1){ opponentId=2; } //βρίσκω τα ελεύθερα tiles στο board for (int i=0;i<ProximityUtilities.NUMBER_OF_COLUMNS;i++){//σκανάρω το board for (int j=0;j<ProximityUtilities.NUMBER_OF_ROWS;j++){//για διαθέσιμα tiles if (child.getNodeBoard().getTile(i,j).getPlayerId()==0){//αν υπάρχει διαθέσιμο tile //δημιουργώ έναν κλώνο του board, όπως θα ήταν εάν έπαιζε ο αντίπαλος //στη θέση (i,j) ένα πλακίδιο με τιμή randomNumber Board cloneBoard = ProximityUtilities.boardAfterMove(opponentId,child.getNodeBoard(),i,j,number); //δημιουργώ ένα αντικείμενο τύπου Node που περιέχει το νέο board //και τα υπόλοιπα στοιχεία Node82558324 leaf=new Node82558324(child, cloneBoard); //αξιολογώ τη θέση (i,j) int opponentScore=0; for (int k=0;k<ProximityUtilities.NUMBER_OF_COLUMNS;k++){ for (int l=0;l<ProximityUtilities.NUMBER_OF_ROWS;l++){ if (leaf.getNodeBoard().getTile(k,l).getPlayerId()==opponentId){ opponentScore=opponentScore+leaf.getNodeBoard().getTile(k,l).getScore(); } } } int evaluation=this.getScore()-opponentScore; leaf.setNodeEvaluation(evaluation); leaf.setNodeMove(i,j,number); leaf.setNodeDepth(depth); //προσθέτω το νέο στοιχείο στο arrayList του parent της συνάρτησης //που είναι το child που δημιούργησε η συνάρτηση createMySubtree(..) child.setChildren(leaf); } } } } //Η συνάρτηση chooseMinMaxMove(..) περιλαμβάνει έναν αλγόριθμo Minmax για να βρεί //την καλύτερη διαθέσιμη κίνηση. Για να βρεί τη θέση αυτή,αρχικά αποθηκεύει τα παιδιά //της ρίζας, και για κάθε παιδί αποθηκεύει τα φύλλα του. Σε βάθος 2, κρατάει την //μικρότερη τιμή που βρίσκει από κάθε φύλλο και η τιμή αυτή περνάει στα παιδιά. //Σε βάθος 1, κρατάει την μεγαλύτερη τιμή από τα παιδιά και αυτή περνάει στη ρίζα //που είναι και η τελική τιμή που θα επιλέξουμε. //Στο τέλος επιστρέφουμε τις συντεταγμένες της καλύτερης θέσης public int[] chooseMinMaxMove(Node82558324 root) { int[] index=new int[2];//ο πίνακας που θα περιέχει την καλύτερη θέση //αποθηκεύω τα παιδιά της ρίζας σε μια ArrayList-ήμαστε σε βάθος 1 ArrayList<Node82558324> children= root.getChildren(); //ο αριμός των παιδιών της ρίζας int numberOfChildren=0; numberOfChildren=children.size(); //στη μεταβλητή maxEval θα αποθηκεύσω το μεγαλύτερο από τα evaluation στο επίπεδο 1 double maxEval=children.get(0).getNodeEvaluation(); //κρατάω τις συντεταγμένες για την καλύτερη θέση στο maxNodeMove (x,y,number) int[] maxNodeMove=children.get(0).getNodeMove(); //σε κάθε επανάληψη σκανάρω ένα παιδί της ρίζας for (int i=0;i<numberOfChildren;i++){ //έχω τα φύλλα του κόμβου-βάθος 2 ArrayList<Node82558324> leaves=children.get(i).getChildren(); //υπολογίζω πόσα φύλλα έχει ο κάθε κόμβος int numberOfLeaves = leaves.size(); //στη μεταβλητή minEval θα αποθηκεύσω το μικρότερο από τα evaluation σε βάθος 2 double minEval=leaves.get(0).getNodeEvaluation(); //(x, y , randomNumber) για την θέση που επιλέγεται int[] minNodeMove=leaves.get(0).getNodeMove(); //σκανάρω κάθε φύλλο του παιδιού i for (int j=1;j<numberOfLeaves;j++){ //βρίσκω ποιο είναι το μικρότερο evaluation if (leaves.get(j).getNodeEvaluation()<minEval){ minEval=leaves.get(j).getNodeEvaluation(); minNodeMove=leaves.get(j).getNodeMove(); } } //ανεβάζω σε κάθε κόμβο την μικρότερη από τις τιμές των φύλλων children.get(i).setNodeEvaluation(minEval); children.get(i).setNodeMove(minNodeMove); //αν ήμαστε στην 1η επανάληψη η σύγκριση είναι περιττή if (i==0) continue; //εντοπίζω το μεγαλύτερο evaluation, αποθηκεύω παράλληλα και τις συντεταγμένες if(children.get(i).getNodeEvaluation()>maxEval){ maxEval=children.get(i).getNodeEvaluation(); maxNodeMove=children.get(i).getNodeMove(); } } //αφου σκανάρω όλα τα παιδιά και φύλλα, στη ρίζα βάζω την τιμή της καλύτερης συνολικής κίνησης και τις συντεταγμένες root.setNodeEvaluation(maxEval); root.setNodeMove(maxNodeMove); //επιστρέφω τις συντεταγμένες της καλυτερης κίνησης index[0]=root.getNodeMove()[0]; index[1]=root.getNodeMove()[1]; return index; } }
10519_5
package com.koutsioumaris.input; import com.koutsioumaris.annotations.*; import java.util.List; //@Database(name="UnipiDB", dbType ="sqlite") //@Database(name="UnipiDB", dbType ="derby") @Database(name="UnipiDB", dbType ="h2") @Table(name="Student") public class Student { @PrimaryKey @DBField(name="AM",type="Text") String AM; @DBField(name="Email",type="Text") String email; @DBField(name="YearOfStudies",type="Integer") int yearOfStudies; @DBField(name="FullName",type="Text") String fullName; @DBField(name="PostGraduate",type="Boolean") boolean postGraduate; @NoArgConstructor //not necessary public Student() { } @FullArgConstructor //necessary for "select" methods public Student(String AM, String email,int yearOfStudies,String fullName,boolean postGraduate) { } @DBMethod(type="InsertOne") public static int insertStudent(@Param(name="AM") String AM,@Param(name="Email") String email,@Param(name="Year") int yearOfStudies, @Param(name="FullName") String fullName,@Param(name="PostGraduate") boolean postGraduate){ return 0; } //Για τη μέθοδο αυτή μπορείτε να δοκιμάστε να επιστρέφετε List<Student> @DBMethod(type="SelectAll") public static List<Student> getAllStudents(){ return null; } //Επιστρέφουμε τον μοναδικό μαθητή με το συγκεκριμένο ΑΦΜ @DBMethod(type="SelectOne") public static Student getOneStudent(@Param(name="AM") String AM){ return null; } //Ο επιστρεφόμενος ακέραιος υποδηλώνει τον αριθμό των εγγραφών που διαγράφηκαν @DBMethod(type="DeleteOne") public static int deleteStudent(@Param(name="AM") String AM){ return 0; } @DBMethod(type="DeleteAll") public static int deleteStudents(){ return 0; } //This method will not be added to the output class because it doesn't contain the @DBMethod annotation public static int test(String AM,@Param(name="Test") int test){ return 0; } }
koutsioj/AutomaticCodeInjection
src/main/java/com/koutsioumaris/input/Student.java
676
//Ο επιστρεφόμενος ακέραιος υποδηλώνει τον αριθμό των εγγραφών που διαγράφηκαν
line_comment
el
package com.koutsioumaris.input; import com.koutsioumaris.annotations.*; import java.util.List; //@Database(name="UnipiDB", dbType ="sqlite") //@Database(name="UnipiDB", dbType ="derby") @Database(name="UnipiDB", dbType ="h2") @Table(name="Student") public class Student { @PrimaryKey @DBField(name="AM",type="Text") String AM; @DBField(name="Email",type="Text") String email; @DBField(name="YearOfStudies",type="Integer") int yearOfStudies; @DBField(name="FullName",type="Text") String fullName; @DBField(name="PostGraduate",type="Boolean") boolean postGraduate; @NoArgConstructor //not necessary public Student() { } @FullArgConstructor //necessary for "select" methods public Student(String AM, String email,int yearOfStudies,String fullName,boolean postGraduate) { } @DBMethod(type="InsertOne") public static int insertStudent(@Param(name="AM") String AM,@Param(name="Email") String email,@Param(name="Year") int yearOfStudies, @Param(name="FullName") String fullName,@Param(name="PostGraduate") boolean postGraduate){ return 0; } //Για τη μέθοδο αυτή μπορείτε να δοκιμάστε να επιστρέφετε List<Student> @DBMethod(type="SelectAll") public static List<Student> getAllStudents(){ return null; } //Επιστρέφουμε τον μοναδικό μαθητή με το συγκεκριμένο ΑΦΜ @DBMethod(type="SelectOne") public static Student getOneStudent(@Param(name="AM") String AM){ return null; } //Ο επιστρεφόμενος<SUF> @DBMethod(type="DeleteOne") public static int deleteStudent(@Param(name="AM") String AM){ return 0; } @DBMethod(type="DeleteAll") public static int deleteStudents(){ return 0; } //This method will not be added to the output class because it doesn't contain the @DBMethod annotation public static int test(String AM,@Param(name="Test") int test){ return 0; } }
901_17
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.PriorityQueue; import java.util.Comparator; public class RandomizedBST implements TaxEvasionInterface { // Κατασκευαστής χωρίς παραμέτρους public RandomizedBST() { root = null; } private class TreeNode { private LargeDepositor item; // Το στοιχείο του κόμβου private TreeNode left; // Δείκτης στο αριστερό υποδέντρο private TreeNode right; // Δείκτης στο δεξιό υποδέντρο private int N; // Αριθμός κόμβων στο υποδέντρο που ριζώνει σε αυτόν τον κόμβο // Κατασκευαστής με τέσσερις παραμέτρους public TreeNode(LargeDepositor item, TreeNode left, TreeNode right, int N) { if (N < 0) { throw new IllegalArgumentException("Ο αριθμός των κόμβων δεν μπορεί να είναι αρνητικός"); } this.item = item; this.left = left; this.right = right; this.N = N; } // Getters και setters με έλεγχο για έγκυρες τιμές public LargeDepositor getItem() { return item; } public void setItem(LargeDepositor item) { this.item = item; } public TreeNode getLeft() { return left; } public void setLeft(TreeNode left) { this.left = left; } public TreeNode getRight() { return right; } public void setRight(TreeNode right) { this.right = right; } public int getN() { return N; } public void setN(int N) { if (N < 0) { throw new IllegalArgumentException("Ο αριθμός των κόμβων δεν μπορεί να είναι αρνητικός"); } this.N = N; } // Μέθοδος για την εκτύπωση των δεδομένων του κόμβου @Override public String toString() { return "TreeNode [item=" + item + ", left=" + (left != null ? "TreeNode" : "null") + ", right=" + (right != null ? "TreeNode" : "null") + ", N=" + N + "]"; } } private TreeNode root; // pointer to root of the tree // Υλοποίηση των μεθόδων του interface public void insert(LargeDepositor item) { if (searchByAFM(item.getAFM()) != null) { System.out.println("Ένας μεγαλοκαταθέτης με ΑΦΜ " + item.getAFM() + " υπάρχει ήδη στο δέντρο."); return; } root = insertAtRoot(item, root); } private TreeNode insertAtRoot(LargeDepositor item, TreeNode node) { if (node == null) { return new TreeNode(item, null, null, 1); } int leftSize = size(node.left); if (Math.random() * (leftSize + 1) < 1) { // Πιθανότητα εισαγωγής στη ρίζα return insertRoot(item, node); } if (item.key() < node.item.key()) { node.left = insertAtRoot(item, node.left); } else { node.right = insertAtRoot(item, node.right); } node.N = size(node.left) + size(node.right) + 1; return node; } private TreeNode insertRoot(LargeDepositor item, TreeNode node) { if (node == null) { return new TreeNode(item, null, null, 1); } if (item.key() < node.item.key()) { node.left = insertRoot(item, node.left); node = rotateRight(node); } else { node.right = insertRoot(item, node.right); node = rotateLeft(node); } node.N = size(node.left) + size(node.right) + 1; return node; } private int size(TreeNode node) { if (node == null) { return 0; } return node.N; } private TreeNode rotateRight(TreeNode node) { if (node == null || node.left == null) { return node; } TreeNode temp = node.left; node.left = temp.right; temp.right = node; temp.N = node.N; node.N = size(node.left) + size(node.right) + 1; return temp; } private TreeNode rotateLeft(TreeNode node) { if (node == null || node.right == null) { return node; } TreeNode temp = node.right; node.right = temp.left; temp.left = node; temp.N = node.N; node.N = size(node.left) + size(node.right) + 1; return temp; } public void load(String filename) { try { File file = new File(filename); Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); String[] parts = line.split(" "); int afm = Integer.parseInt(parts[0]); String firstName = parts[1]; String lastName = parts[2]; double savings = Double.parseDouble(parts[3]); double taxedIncome = Double.parseDouble(parts[4]); LargeDepositor depositor = new LargeDepositor(afm, firstName, lastName, savings, taxedIncome); insert(depositor); } scanner.close(); } catch (FileNotFoundException e) { System.err.println("Το αρχείο δεν βρέθηκε: " + filename); } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) { System.err.println("Σφάλμα κατά την ανάγνωση του αρχείου: " + e.getMessage()); } } public void updateSavings(int AFM, double savings) { LargeDepositor depositor = searchByAFM(AFM); if (depositor != null) { depositor.setSavings(savings); System.out.println("Οι αποταμιεύσεις του υπόπτου με ΑΦΜ " + AFM + " ενημερώθηκαν."); } else { System.out.println("Δεν βρέθηκε ύποπτος με ΑΦΜ " + AFM); } } private LargeDepositor searchByAFM(TreeNode node, int AFM) { if (node == null) { return null; } if (AFM < node.item.getAFM()) { return searchByAFM(node.left, AFM); } else if (AFM > node.item.getAFM()) { return searchByAFM(node.right, AFM); } else { return node.item; } } public LargeDepositor searchByAFM(int AFM) { return searchByAFM(root, AFM); } private void searchByLastName(TreeNode node, String lastName, SingleNode head, SingleNode tail) { if (node == null) { return; } if (lastName.equals(node.item.getLastName())) { SingleNode newNode = new SingleNode(node.item); if (head.next == null) { head.next = newNode; } else { tail.next = newNode; } tail.next = newNode; } searchByLastName(node.left, lastName, head, tail); searchByLastName(node.right, lastName, head, tail); } public void searchByLastName(String lastName) { SingleNode dummyHead = new SingleNode(null); SingleNode tail = dummyHead; searchByLastName(root, lastName, dummyHead, tail); SingleNode current = dummyHead.next; int count = 0; while (current != null && count < 5) { System.out.println(current.item); current = current.next; count++; } if (count == 0) { System.out.println("Δεν βρέθηκε κανένας με επίθετο: " + lastName); } } private TreeNode remove(TreeNode node, int AFM) { if (node == null) { return null; } if (AFM < node.item.getAFM()) { node.left = remove(node.left, AFM); } else if (AFM > node.item.getAFM()) { node.right = remove(node.right, AFM); } else { if (node.left == null) { return node.right; } else if (node.right == null) { return node.left; } else { TreeNode t = node; node = min(t.right); // Βρίσκουμε τον ελάχιστο κόμβο του δεξιού υποδέντρου node.right = deleteMin(t.right); node.left = t.left; } } node.N = size(node.left) + size(node.right) + 1; return node; } public void remove(int AFM) { root = remove(root, AFM); } private TreeNode min(TreeNode node) { if (node.left == null) return node; return min(node.left); } private TreeNode deleteMin(TreeNode node) { if (node.left == null) return node.right; node.left = deleteMin(node.left); node.N = size(node.left) + size(node.right) + 1; return node; } public double getMeanSavings() { double[] sumAndCount = getSumAndCount(root); return sumAndCount[1] > 0 ? sumAndCount[0] / sumAndCount[1] : 0.0; } private double[] getSumAndCount(TreeNode node) { if (node == null) { return new double[]{0.0, 0}; // Αρχικοποίηση του αθροίσματος και του μετρητή σε 0 } double[] left = getSumAndCount(node.left); double[] right = getSumAndCount(node.right); double sum = left[0] + right[0] + node.item.getSavings(); // Άθροισμα των αποταμιεύσεων double count = left[1] + right[1] + 1; // Συνολικός αριθμός των καταθετών return new double[]{sum, count}; } public void printTopLargeDepositors(int k) { PriorityQueue<LargeDepositor> pq = new PriorityQueue<>(k, new Comparator<LargeDepositor>() { @Override public int compare(LargeDepositor d1, LargeDepositor d2) { double score1 = d1.getTaxedIncome() < 8000 ? Double.MAX_VALUE : d1.getSavings() - d1.getTaxedIncome(); double score2 = d2.getTaxedIncome() < 8000 ? Double.MAX_VALUE : d2.getSavings() - d2.getTaxedIncome(); return Double.compare(score2, score1); } }); addDepositorsToPriorityQueue(root, pq, k); for (int i = 0; i < k && !pq.isEmpty(); i++) { LargeDepositor depositor = pq.poll(); System.out.println(depositor); } } private void addDepositorsToPriorityQueue(TreeNode node, PriorityQueue<LargeDepositor> pq, int k) { if (node == null) { return; } pq.offer(node.item); if (pq.size() > k) { pq.poll(); } addDepositorsToPriorityQueue(node.left, pq, k); addDepositorsToPriorityQueue(node.right, pq, k); } private void printInOrder(TreeNode node) { if (node == null) { return; } printInOrder(node.left); // Επισκεφτείτε πρώτα το αριστερό υποδέντρο System.out.println(node.item); // Εκτυπώστε τον κόμβο printInOrder(node.right); // Στη συνέχεια επισκεφτείτε το δεξί υποδέντρο } public void printByAFM() { printInOrder(root); } public static void main(String[] args) { RandomizedBST bst = new RandomizedBST(); if (args.length > 0) { String filename = args[0]; bst.load(filename); } else { System.out.println("Παρακαλώ δώστε το όνομα του αρχείου ως όρισμα."); } Scanner scanner = new Scanner(System.in); while (true) { System.out.println("\nΜενού Διαχείρισης:"); System.out.println("1. Εισαγωγή Υπόπτου"); System.out.println("2. Διαγραφή Υπόπτου"); System.out.println("3. Αναζήτηση με ΑΦΜ"); System.out.println("4. Αναζήτηση με Επίθετο"); System.out.println("5. Εμφάνιση Μέσου Ποσού Αποταμιεύσεων"); System.out.println("6. Εμφάνιση Πρώτων Υπόπτων για Φοροδιαφυγή"); System.out.println("7. Εμφάνιση Όλων των Υπόπτων Ανά ΑΦΜ"); System.out.println("8. Έξοδος"); System.out.print("Επιλέξτε μια ενέργεια: "); int choice = scanner.nextInt(); switch (choice) { case 1: // Εισαγωγή Υπόπτου System.out.print("Εισάγετε ΑΦΜ: "); int afm = scanner.nextInt(); System.out.print("Εισάγετε Όνομα: "); String firstName = scanner.next(); System.out.print("Εισάγετε Επίθετο: "); String lastName = scanner.next(); System.out.print("Εισάγετε Αποταμιεύσεις: "); double savings = scanner.nextDouble(); System.out.print("Εισάγετε Δηλωμένο Εισόδημα: "); double taxedIncome = scanner.nextDouble(); LargeDepositor depositor = new LargeDepositor(afm, firstName, lastName, savings, taxedIncome); bst.insert(depositor); break; case 2: // Διαγραφή Υπόπτου System.out.print("Εισάγετε ΑΦΜ για διαγραφή: "); int afmToDelete = scanner.nextInt(); bst.remove(afmToDelete); break; case 3: // Αναζήτηση με ΑΦΜ System.out.print("Εισάγετε ΑΦΜ για αναζήτηση: "); int afmToSearch = scanner.nextInt(); LargeDepositor foundDepositor = bst.searchByAFM(afmToSearch); if (foundDepositor != null) { System.out.println("Βρέθηκε ο Υπόπτος: " + foundDepositor); } else { System.out.println("Δεν βρέθηκε Υπόπτος με ΑΦΜ: " + afmToSearch); } break; case 4: // Αναζήτηση με Επίθετο System.out.print("Εισάγετε Επίθετο για αναζήτηση: "); String lastNameToSearch = scanner.next(); bst.searchByLastName(lastNameToSearch); break; case 5: // Εμφάνιση Μέσου Ποσού Αποταμιεύσεων System.out.println("Μέσο ποσό αποταμιεύσεων: " + bst.getMeanSavings()); break; case 6: // Εμφάνιση Πρώτων Υπόπτων για Φοροδιαφυγή System.out.print("Εισάγετε τον αριθμό των υπόπτων προς εμφάνιση: "); int k = scanner.nextInt(); bst.printTopLargeDepositors(k); break; case 7: // Εμφάνιση Όλων των Υπόπτων Ανά ΑΦΜ bst.printByAFM(); break; case 8: // Έξοδος System.out.println("Έξοδος από το πρόγραμμα."); scanner.close(); System.exit(0); default: System.out.println("Μη έγκυρη επιλογή. Παρακαλώ επιλέξτε ξανά."); break; } } } private class SingleNode { LargeDepositor item; SingleNode next; SingleNode(LargeDepositor item) { this.item = item; this.next = null; } } }
krimits/domesproject3
RandomizedBST.java
4,922
// Στη συνέχεια επισκεφτείτε το δεξί υποδέντρο
line_comment
el
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.PriorityQueue; import java.util.Comparator; public class RandomizedBST implements TaxEvasionInterface { // Κατασκευαστής χωρίς παραμέτρους public RandomizedBST() { root = null; } private class TreeNode { private LargeDepositor item; // Το στοιχείο του κόμβου private TreeNode left; // Δείκτης στο αριστερό υποδέντρο private TreeNode right; // Δείκτης στο δεξιό υποδέντρο private int N; // Αριθμός κόμβων στο υποδέντρο που ριζώνει σε αυτόν τον κόμβο // Κατασκευαστής με τέσσερις παραμέτρους public TreeNode(LargeDepositor item, TreeNode left, TreeNode right, int N) { if (N < 0) { throw new IllegalArgumentException("Ο αριθμός των κόμβων δεν μπορεί να είναι αρνητικός"); } this.item = item; this.left = left; this.right = right; this.N = N; } // Getters και setters με έλεγχο για έγκυρες τιμές public LargeDepositor getItem() { return item; } public void setItem(LargeDepositor item) { this.item = item; } public TreeNode getLeft() { return left; } public void setLeft(TreeNode left) { this.left = left; } public TreeNode getRight() { return right; } public void setRight(TreeNode right) { this.right = right; } public int getN() { return N; } public void setN(int N) { if (N < 0) { throw new IllegalArgumentException("Ο αριθμός των κόμβων δεν μπορεί να είναι αρνητικός"); } this.N = N; } // Μέθοδος για την εκτύπωση των δεδομένων του κόμβου @Override public String toString() { return "TreeNode [item=" + item + ", left=" + (left != null ? "TreeNode" : "null") + ", right=" + (right != null ? "TreeNode" : "null") + ", N=" + N + "]"; } } private TreeNode root; // pointer to root of the tree // Υλοποίηση των μεθόδων του interface public void insert(LargeDepositor item) { if (searchByAFM(item.getAFM()) != null) { System.out.println("Ένας μεγαλοκαταθέτης με ΑΦΜ " + item.getAFM() + " υπάρχει ήδη στο δέντρο."); return; } root = insertAtRoot(item, root); } private TreeNode insertAtRoot(LargeDepositor item, TreeNode node) { if (node == null) { return new TreeNode(item, null, null, 1); } int leftSize = size(node.left); if (Math.random() * (leftSize + 1) < 1) { // Πιθανότητα εισαγωγής στη ρίζα return insertRoot(item, node); } if (item.key() < node.item.key()) { node.left = insertAtRoot(item, node.left); } else { node.right = insertAtRoot(item, node.right); } node.N = size(node.left) + size(node.right) + 1; return node; } private TreeNode insertRoot(LargeDepositor item, TreeNode node) { if (node == null) { return new TreeNode(item, null, null, 1); } if (item.key() < node.item.key()) { node.left = insertRoot(item, node.left); node = rotateRight(node); } else { node.right = insertRoot(item, node.right); node = rotateLeft(node); } node.N = size(node.left) + size(node.right) + 1; return node; } private int size(TreeNode node) { if (node == null) { return 0; } return node.N; } private TreeNode rotateRight(TreeNode node) { if (node == null || node.left == null) { return node; } TreeNode temp = node.left; node.left = temp.right; temp.right = node; temp.N = node.N; node.N = size(node.left) + size(node.right) + 1; return temp; } private TreeNode rotateLeft(TreeNode node) { if (node == null || node.right == null) { return node; } TreeNode temp = node.right; node.right = temp.left; temp.left = node; temp.N = node.N; node.N = size(node.left) + size(node.right) + 1; return temp; } public void load(String filename) { try { File file = new File(filename); Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); String[] parts = line.split(" "); int afm = Integer.parseInt(parts[0]); String firstName = parts[1]; String lastName = parts[2]; double savings = Double.parseDouble(parts[3]); double taxedIncome = Double.parseDouble(parts[4]); LargeDepositor depositor = new LargeDepositor(afm, firstName, lastName, savings, taxedIncome); insert(depositor); } scanner.close(); } catch (FileNotFoundException e) { System.err.println("Το αρχείο δεν βρέθηκε: " + filename); } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) { System.err.println("Σφάλμα κατά την ανάγνωση του αρχείου: " + e.getMessage()); } } public void updateSavings(int AFM, double savings) { LargeDepositor depositor = searchByAFM(AFM); if (depositor != null) { depositor.setSavings(savings); System.out.println("Οι αποταμιεύσεις του υπόπτου με ΑΦΜ " + AFM + " ενημερώθηκαν."); } else { System.out.println("Δεν βρέθηκε ύποπτος με ΑΦΜ " + AFM); } } private LargeDepositor searchByAFM(TreeNode node, int AFM) { if (node == null) { return null; } if (AFM < node.item.getAFM()) { return searchByAFM(node.left, AFM); } else if (AFM > node.item.getAFM()) { return searchByAFM(node.right, AFM); } else { return node.item; } } public LargeDepositor searchByAFM(int AFM) { return searchByAFM(root, AFM); } private void searchByLastName(TreeNode node, String lastName, SingleNode head, SingleNode tail) { if (node == null) { return; } if (lastName.equals(node.item.getLastName())) { SingleNode newNode = new SingleNode(node.item); if (head.next == null) { head.next = newNode; } else { tail.next = newNode; } tail.next = newNode; } searchByLastName(node.left, lastName, head, tail); searchByLastName(node.right, lastName, head, tail); } public void searchByLastName(String lastName) { SingleNode dummyHead = new SingleNode(null); SingleNode tail = dummyHead; searchByLastName(root, lastName, dummyHead, tail); SingleNode current = dummyHead.next; int count = 0; while (current != null && count < 5) { System.out.println(current.item); current = current.next; count++; } if (count == 0) { System.out.println("Δεν βρέθηκε κανένας με επίθετο: " + lastName); } } private TreeNode remove(TreeNode node, int AFM) { if (node == null) { return null; } if (AFM < node.item.getAFM()) { node.left = remove(node.left, AFM); } else if (AFM > node.item.getAFM()) { node.right = remove(node.right, AFM); } else { if (node.left == null) { return node.right; } else if (node.right == null) { return node.left; } else { TreeNode t = node; node = min(t.right); // Βρίσκουμε τον ελάχιστο κόμβο του δεξιού υποδέντρου node.right = deleteMin(t.right); node.left = t.left; } } node.N = size(node.left) + size(node.right) + 1; return node; } public void remove(int AFM) { root = remove(root, AFM); } private TreeNode min(TreeNode node) { if (node.left == null) return node; return min(node.left); } private TreeNode deleteMin(TreeNode node) { if (node.left == null) return node.right; node.left = deleteMin(node.left); node.N = size(node.left) + size(node.right) + 1; return node; } public double getMeanSavings() { double[] sumAndCount = getSumAndCount(root); return sumAndCount[1] > 0 ? sumAndCount[0] / sumAndCount[1] : 0.0; } private double[] getSumAndCount(TreeNode node) { if (node == null) { return new double[]{0.0, 0}; // Αρχικοποίηση του αθροίσματος και του μετρητή σε 0 } double[] left = getSumAndCount(node.left); double[] right = getSumAndCount(node.right); double sum = left[0] + right[0] + node.item.getSavings(); // Άθροισμα των αποταμιεύσεων double count = left[1] + right[1] + 1; // Συνολικός αριθμός των καταθετών return new double[]{sum, count}; } public void printTopLargeDepositors(int k) { PriorityQueue<LargeDepositor> pq = new PriorityQueue<>(k, new Comparator<LargeDepositor>() { @Override public int compare(LargeDepositor d1, LargeDepositor d2) { double score1 = d1.getTaxedIncome() < 8000 ? Double.MAX_VALUE : d1.getSavings() - d1.getTaxedIncome(); double score2 = d2.getTaxedIncome() < 8000 ? Double.MAX_VALUE : d2.getSavings() - d2.getTaxedIncome(); return Double.compare(score2, score1); } }); addDepositorsToPriorityQueue(root, pq, k); for (int i = 0; i < k && !pq.isEmpty(); i++) { LargeDepositor depositor = pq.poll(); System.out.println(depositor); } } private void addDepositorsToPriorityQueue(TreeNode node, PriorityQueue<LargeDepositor> pq, int k) { if (node == null) { return; } pq.offer(node.item); if (pq.size() > k) { pq.poll(); } addDepositorsToPriorityQueue(node.left, pq, k); addDepositorsToPriorityQueue(node.right, pq, k); } private void printInOrder(TreeNode node) { if (node == null) { return; } printInOrder(node.left); // Επισκεφτείτε πρώτα το αριστερό υποδέντρο System.out.println(node.item); // Εκτυπώστε τον κόμβο printInOrder(node.right); // Στη συνέχεια<SUF> } public void printByAFM() { printInOrder(root); } public static void main(String[] args) { RandomizedBST bst = new RandomizedBST(); if (args.length > 0) { String filename = args[0]; bst.load(filename); } else { System.out.println("Παρακαλώ δώστε το όνομα του αρχείου ως όρισμα."); } Scanner scanner = new Scanner(System.in); while (true) { System.out.println("\nΜενού Διαχείρισης:"); System.out.println("1. Εισαγωγή Υπόπτου"); System.out.println("2. Διαγραφή Υπόπτου"); System.out.println("3. Αναζήτηση με ΑΦΜ"); System.out.println("4. Αναζήτηση με Επίθετο"); System.out.println("5. Εμφάνιση Μέσου Ποσού Αποταμιεύσεων"); System.out.println("6. Εμφάνιση Πρώτων Υπόπτων για Φοροδιαφυγή"); System.out.println("7. Εμφάνιση Όλων των Υπόπτων Ανά ΑΦΜ"); System.out.println("8. Έξοδος"); System.out.print("Επιλέξτε μια ενέργεια: "); int choice = scanner.nextInt(); switch (choice) { case 1: // Εισαγωγή Υπόπτου System.out.print("Εισάγετε ΑΦΜ: "); int afm = scanner.nextInt(); System.out.print("Εισάγετε Όνομα: "); String firstName = scanner.next(); System.out.print("Εισάγετε Επίθετο: "); String lastName = scanner.next(); System.out.print("Εισάγετε Αποταμιεύσεις: "); double savings = scanner.nextDouble(); System.out.print("Εισάγετε Δηλωμένο Εισόδημα: "); double taxedIncome = scanner.nextDouble(); LargeDepositor depositor = new LargeDepositor(afm, firstName, lastName, savings, taxedIncome); bst.insert(depositor); break; case 2: // Διαγραφή Υπόπτου System.out.print("Εισάγετε ΑΦΜ για διαγραφή: "); int afmToDelete = scanner.nextInt(); bst.remove(afmToDelete); break; case 3: // Αναζήτηση με ΑΦΜ System.out.print("Εισάγετε ΑΦΜ για αναζήτηση: "); int afmToSearch = scanner.nextInt(); LargeDepositor foundDepositor = bst.searchByAFM(afmToSearch); if (foundDepositor != null) { System.out.println("Βρέθηκε ο Υπόπτος: " + foundDepositor); } else { System.out.println("Δεν βρέθηκε Υπόπτος με ΑΦΜ: " + afmToSearch); } break; case 4: // Αναζήτηση με Επίθετο System.out.print("Εισάγετε Επίθετο για αναζήτηση: "); String lastNameToSearch = scanner.next(); bst.searchByLastName(lastNameToSearch); break; case 5: // Εμφάνιση Μέσου Ποσού Αποταμιεύσεων System.out.println("Μέσο ποσό αποταμιεύσεων: " + bst.getMeanSavings()); break; case 6: // Εμφάνιση Πρώτων Υπόπτων για Φοροδιαφυγή System.out.print("Εισάγετε τον αριθμό των υπόπτων προς εμφάνιση: "); int k = scanner.nextInt(); bst.printTopLargeDepositors(k); break; case 7: // Εμφάνιση Όλων των Υπόπτων Ανά ΑΦΜ bst.printByAFM(); break; case 8: // Έξοδος System.out.println("Έξοδος από το πρόγραμμα."); scanner.close(); System.exit(0); default: System.out.println("Μη έγκυρη επιλογή. Παρακαλώ επιλέξτε ξανά."); break; } } } private class SingleNode { LargeDepositor item; SingleNode next; SingleNode(LargeDepositor item) { this.item = item; this.next = null; } } }
6975_1
package ted.rental.database.entities; import javax.persistence.*; @Entity @Table(name = "ROOMENTITY_RULEENTITY") public class ROOMENTITY_RULEENTITY { @EmbeddedId private RoomRuleId roomRuleId = new RoomRuleId(); /* */ /* Σχέση Πολλά-Προς-Ένα ((ROOMENTITY_RULEENTITY))-((Room)) */ /* */ @ManyToOne @JoinColumn(name = "room_id", referencedColumnName = "id", insertable = false, updatable = false) private RoomEntity roomEntity; public RoomEntity getRoomEntity() { return roomEntity; } public void setRoomEntity(RoomEntity roomEntity) { this.roomEntity = roomEntity; } /* */ /* Σχέση Πολλά-Προς-Ένα ((ROOMENTITY_RULEENTITY))-((Rule)) */ /* */ @OneToOne @JoinColumn(name = "rule_id", referencedColumnName = "id", insertable = false, updatable = false) private RuleEntity ruleEntity; public RuleEntity getRuleEntity() { return ruleEntity; } public void setRuleEntity(RuleEntity ruleEntity) { this.ruleEntity = ruleEntity; } public ROOMENTITY_RULEENTITY() { } public ROOMENTITY_RULEENTITY(Integer room_id, Integer rule_id) { this.roomRuleId.setRoom_id(room_id); this.roomRuleId.setRule_id(rule_id); } public RoomRuleId getRoomRuleId() { return roomRuleId; } public void setRoomRuleId(RoomRuleId roomRuleId) { this.roomRuleId = roomRuleId; } }
kwstarikanos-zz/RealHouse-Rental-System
Rental-API/src/main/java/ted/rental/database/entities/ROOMENTITY_RULEENTITY.java
441
/* Σχέση Πολλά-Προς-Ένα ((ROOMENTITY_RULEENTITY))-((Rule)) */
block_comment
el
package ted.rental.database.entities; import javax.persistence.*; @Entity @Table(name = "ROOMENTITY_RULEENTITY") public class ROOMENTITY_RULEENTITY { @EmbeddedId private RoomRuleId roomRuleId = new RoomRuleId(); /* */ /* Σχέση Πολλά-Προς-Ένα ((ROOMENTITY_RULEENTITY))-((Room)) */ /* */ @ManyToOne @JoinColumn(name = "room_id", referencedColumnName = "id", insertable = false, updatable = false) private RoomEntity roomEntity; public RoomEntity getRoomEntity() { return roomEntity; } public void setRoomEntity(RoomEntity roomEntity) { this.roomEntity = roomEntity; } /* */ /* Σχέση Πολλά-Προς-Ένα<SUF>*/ /* */ @OneToOne @JoinColumn(name = "rule_id", referencedColumnName = "id", insertable = false, updatable = false) private RuleEntity ruleEntity; public RuleEntity getRuleEntity() { return ruleEntity; } public void setRuleEntity(RuleEntity ruleEntity) { this.ruleEntity = ruleEntity; } public ROOMENTITY_RULEENTITY() { } public ROOMENTITY_RULEENTITY(Integer room_id, Integer rule_id) { this.roomRuleId.setRoom_id(room_id); this.roomRuleId.setRule_id(rule_id); } public RoomRuleId getRoomRuleId() { return roomRuleId; } public void setRoomRuleId(RoomRuleId roomRuleId) { this.roomRuleId = roomRuleId; } }
11543_0
package gr.aueb.cf.ch3; import java.util.Scanner; /** * Αποφασίζει αν χιονίζει με βάση τη θερμοκρασία * και αν βρέχει. */ public class SnowingApp { public static void main(String[] args) { Scanner in = new Scanner(System.in); boolean isSnowing = false; boolean isRaining = false; int temp = 0; System.out.println("Please insert if it is raining (true/false): "); isRaining = in.nextBoolean(); System.out.println("Please insert temperature (int): "); temp = in.nextInt(); isSnowing = isRaining && (temp < 0); System.out.println("Is snowing: " + isSnowing); } }
kyrkyp/CodingFactoryJava
src/gr/aueb/cf/ch3/SnowingApp.java
227
/** * Αποφασίζει αν χιονίζει με βάση τη θερμοκρασία * και αν βρέχει. */
block_comment
el
package gr.aueb.cf.ch3; import java.util.Scanner; /** * Αποφασίζει αν χιονίζει<SUF>*/ public class SnowingApp { public static void main(String[] args) { Scanner in = new Scanner(System.in); boolean isSnowing = false; boolean isRaining = false; int temp = 0; System.out.println("Please insert if it is raining (true/false): "); isRaining = in.nextBoolean(); System.out.println("Please insert temperature (int): "); temp = in.nextInt(); isSnowing = isRaining && (temp < 0); System.out.println("Is snowing: " + isSnowing); } }
2444_0
package com.example.skinhealthchecker; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ListView; import android.widget.Spinner; import android.widget.TabHost; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import static android.graphics.Color.RED; /** * Ο διαχειριστής των προφίλ ! Ο χρήστης μπορεί να φτιάξει , επιλέξει διαγράψει κάποιο προφίλ . * * * * The profile manager! The user can make, choose to delete a profile. */ public class Users extends Activity implements CompoundButton.OnCheckedChangeListener { String TAG; DatabaseHandler db; // db handler // TabHost tabHost; // private Spinner profil ; private EditText profilname ; // the text input for profile name private EditText name ;// the text input for user name private EditText age ;// the text input for user age private EditText mail ;// the text input for user mail private EditText phone ;// the text input for user phone number private Spinner spinner2 ;// spinner that shows saved profiles private TextView text;// textview that will show a message to user if fills something wrong private Spinner fullo; // spinner that shows the gender list private boolean history; public void onCreate(Bundle savedInstanceState) { history =false; //on creating profile the bad history will be false by default TAG = "RESULTS"; Log.i(TAG, "onCreate"); super.onCreate(savedInstanceState); Bundle extras = getIntent().getExtras();// getting intent extras -> but there is no extras here db = new DatabaseHandler(this);// link the database to handler Configurations def = db.getDEf(); //gets apps configurations if (def.GetLanguage())//load the actives language xml setContentView(R.layout.account); else setContentView(R.layout.accounten); TabHost host = (TabHost)findViewById(R.id.tabHost);// link the the xml contents host.setup(); // profil = (Spinner) findViewById(R.id.spinner2); profilname = (EditText) findViewById(R.id.profilname); name = (EditText) findViewById(R.id.name); age = (EditText) findViewById(R.id.age); mail = (EditText) findViewById(R.id.mail); phone = (EditText) findViewById(R.id.phone); text= (TextView) findViewById(R.id.textView); spinner2=(Spinner) findViewById(R.id.spinner2); // mylist=(ListView)findViewById(R.id.mylist); // spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, GetCreatedNames()); //selected item will look like a spinner set from XML fullo = (Spinner) findViewById(R.id.spinnersex); //Tab 1 TabHost.TabSpec spec; if (def.GetLanguage()) {// sets the two tabs using correct active language spec = host.newTabSpec("Προφίλ"); spec.setContent(R.id.baseone); spec.setIndicator("Προφίλ"); host.addTab(spec); //Tab 2 spec = host.newTabSpec("Νέο"); spec.setContent(R.id.basetwo); spec.setIndicator("Νέο Προφίλ"); host.addTab(spec); }else { spec = host.newTabSpec("Profil"); spec.setContent(R.id.baseone); spec.setIndicator("Profile"); host.addTab(spec); //Tab 2 spec = host.newTabSpec("New"); spec.setContent(R.id.basetwo); spec.setIndicator("New profile"); host.addTab(spec); } Button captureButtonU = (Button) findViewById(R.id.gotomain);// on select profile button captureButtonU.setFocusable(true); //captureButton.setFocusableInTouchMode(true); captureButtonU.requestFocus(); captureButtonU.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // int id=GetSelectedId(String.valueOf(spinner2.getSelectedItem())); // gets the spinner id if (id>-1) { //if there is no error Configurations def = db.getDEf(); // gets latest instance of configuration //String [] profnames = GetCreatedNames(); // String name = profnames[id]; Log.d("profname",db.getProfile(def.GetPID()).GetProfilname()); // Profile pr= db.getProfilebyname(name); def.SetPID(id); // set the selected id to configurations db.updateDef(def); // updates configuration } Intent intentU = new Intent(getApplicationContext(), CameraActivity.class);// goes to start screen startActivity(intentU); // } }); Button captureButtonU2 = (Button) findViewById(R.id.save);// saves new profile button captureButtonU2.setFocusable(true); //captureButton.setFocusableInTouchMode(true); captureButtonU2.requestFocus(); captureButtonU2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if ( age.getText().toString().isEmpty()|| String.valueOf(fullo.getSelectedItem()).isEmpty()|| name.getText().toString().isEmpty()|| profilname.getText().toString().isEmpty()|| mail.getText().toString().isEmpty() // || phone.getText().toString().isEmpty() )// if all data filled (except phone number ) {// prints error text.setText("Εισάγετε τα στοιχεία του νέου προφίλ σας." + "\nΠρέπει να συμπληρώσετε όλα τα στοιχεία \n πριν προχωρήσετε !!!!", TextView.BufferType.EDITABLE); text.setTextColor(RED); getWindow().getDecorView().findViewById(R.id.base).invalidate(); } else if (( mail.getText().toString().indexOf('@')<1)||(mail.getText().toString().indexOf('@')>=mail.getText().toString().length()-1)) {// if mail is not in right shape shows error text.setText("Εισάγετε τα στοιχεία του νέου προφίλ σας." + "\n Το e-mail που δώσατε δεν πρέπει να είναι σωστό !!!!", TextView.BufferType.EDITABLE); text.setTextColor(RED); getWindow().getDecorView().findViewById(R.id.base).invalidate(); } else { String string = mail.getText().toString(); Pattern pattern = Pattern.compile("([@])");// checks if there is more than one @ in mail Matcher matcher = pattern.matcher(string); int count = 0; while (matcher.find()) count++; if (count>1) { // if there is many @ prints error text.setText("Εισάγετε τα στοιχεία του νέου προφίλ σας." + "\n Το e-mail που δώσατε δεν πρέπει να είναι σωστό !!!!", TextView.BufferType.EDITABLE); text.setTextColor(RED); getWindow().getDecorView().findViewById(R.id.base).invalidate(); }else { //if all seems to be right int id = CreateNewProfile(); // creates new profile Configurations def = db.getDEf();// gets Configurations instance and activates new id def.SetPID(id);// db.updateDef(def); Intent intentU = new Intent(getApplicationContext(), CameraActivity.class);// go back to start screen startActivity(intentU); } } } }); Button captureButtonD = (Button) findViewById(R.id.deleteprofil); // if delete button pressed captureButtonD.setFocusable(true); //captureButton.setFocusableInTouchMode(true); captureButtonD.requestFocus(); captureButtonD.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // int id; try{ id=GetSelectedId(String.valueOf(spinner2.getSelectedItem()));} // gets the selected profiles id catch(NullPointerException e) { id=0; } Log.d("id", Integer.toString(id)); if (id>0) { // if the id is found and there is not the default id (id 0 ) Configurations def = db.getDEf();// gets the configuration def.SetPID(0); /// set the defaults profile as active db.updateDef(def);// update configurations db.deleteProfile(db.getProfile(id));// delete the profile having the id finish(); // restarts the intent startActivity(getIntent()); } } }); if (db.getProfileCount()>1) {// if there is more profiles except the defaults ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, GetCreatedNames()); //selected item will look like a spinner set from XML // fill the ArrayAdapter with profile names spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner2.setAdapter(spinnerArrayAdapter);// link the array adapter to spinner spinner2.setSelection(Getpos()); // sets the active profile as selected getWindow().getDecorView().findViewById(R.id.baseone).invalidate();//updates grafics } } /* this function is the checkbutton listener // on change condition event get as input the id of checkbox which changed // and the new condition and updates the correct static var . */ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { // if checked sets true switch (buttonView.getId()) { case R.id.history: history = true; //do stuff break; } } else { switch (buttonView.getId()) {// if not sets false case R.id.history: history = false; //do stuff break; } }} /* This function creates a new profile filling it with data that user gave it returns the id of new profile */ public int CreateNewProfile( ){ Configurations def=db.getDEf();// gets the app latest configurations def.PIDCOUntup(); // creates new id def.SetPID(GetNewId(def)); //sets the new id to configurations Profile last = new Profile(); // crates a new instance of profile db.updateDef(def); // updates the db Log.d("new profiles id is = ",Integer.toString(GetNewId(def))); last.SetAge(Integer.parseInt(age.getText().toString()));// fills profile last with data last.SetIdM(GetNewId(def)); last.SetSex(String.valueOf(fullo.getSelectedItem())); last.SetHistory(history); last.SetName(name.getText().toString()); last.SetProfilname(profilname.getText().toString()); last.SetMail(mail.getText().toString()); last.SetPhone(phone.getText().toString()); db.addprofile(last); // adds last to db // Molestest(last); return last.GetIdM(); // returns the id } public int GetNewId( Configurations def) { // gets the latest id from db int id = def.GetPIDCOUnt(); return id; } /* this function gets the name of profile as input , finds its id and returns it */ public int GetSelectedId(String in ){ List<Profile> myList = new ArrayList<Profile>(); myList =db.getAllProfiles();// get all profiles stored in db int out=-1;//init for(int i=myList.size()-1;i>=0;i--){ if (myList.get(i).GetProfilname().equals(in)) { // if the name match any profile name out = myList.get(i).GetIdM(); //gets its id break; } } return out; } /* The function GetCreatedNames returns all profile names that is stored in db in backwards order */ public String [] GetCreatedNames( ){ List<Profile> myList = new ArrayList<Profile>(); myList =db.getAllProfiles(); // gets all profiles String names [] = new String[myList.size()]; int count =0; for(int i=myList.size()-1;i>=0;i--){ // names[count]=myList.get(count).GetProfilname();//saves profile names backwards count++;// names counter } return names; } /* The function Getpos returns the position of the active profile in the spinner line */ public int Getpos( ){ List<Profile> myList = new ArrayList<Profile>(); myList =db.getAllProfiles();// gets all profiles String names [] = new String[myList.size()]; int count =0; for(int i=myList.size()-1;i>=0;i--){ names[count]=myList.get(count).GetProfilname();//saves profile names backwards count++;// names counter } int pos =0; // init the position Configurations def = db.getDEf();// gets apps configuration Profile prof = db.getProfile(def.GetPID()); // gets actives profile instance for (int i=0;i<myList.size();i++) { if (names[i].equals( prof.GetProfilname())) { //if the name of active profile is equal with any name in the list Log.d("prof", Integer.toString(i)); pos = i;// returns the position of the name break; } } return pos;// returns the position of the name } @Override public void onBackPressed() {// when back pressed go to mail activity Intent intent = new Intent(getApplicationContext(), CameraActivity.class); startActivity(intent); } }
litsakis/SkinHealthChecker
skinHealthChecker/src/main/java/com/example/skinhealthchecker/Users.java
3,499
/** * Ο διαχειριστής των προφίλ ! Ο χρήστης μπορεί να φτιάξει , επιλέξει διαγράψει κάποιο προφίλ . * * * * The profile manager! The user can make, choose to delete a profile. */
block_comment
el
package com.example.skinhealthchecker; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ListView; import android.widget.Spinner; import android.widget.TabHost; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import static android.graphics.Color.RED; /** * Ο διαχειριστής των<SUF>*/ public class Users extends Activity implements CompoundButton.OnCheckedChangeListener { String TAG; DatabaseHandler db; // db handler // TabHost tabHost; // private Spinner profil ; private EditText profilname ; // the text input for profile name private EditText name ;// the text input for user name private EditText age ;// the text input for user age private EditText mail ;// the text input for user mail private EditText phone ;// the text input for user phone number private Spinner spinner2 ;// spinner that shows saved profiles private TextView text;// textview that will show a message to user if fills something wrong private Spinner fullo; // spinner that shows the gender list private boolean history; public void onCreate(Bundle savedInstanceState) { history =false; //on creating profile the bad history will be false by default TAG = "RESULTS"; Log.i(TAG, "onCreate"); super.onCreate(savedInstanceState); Bundle extras = getIntent().getExtras();// getting intent extras -> but there is no extras here db = new DatabaseHandler(this);// link the database to handler Configurations def = db.getDEf(); //gets apps configurations if (def.GetLanguage())//load the actives language xml setContentView(R.layout.account); else setContentView(R.layout.accounten); TabHost host = (TabHost)findViewById(R.id.tabHost);// link the the xml contents host.setup(); // profil = (Spinner) findViewById(R.id.spinner2); profilname = (EditText) findViewById(R.id.profilname); name = (EditText) findViewById(R.id.name); age = (EditText) findViewById(R.id.age); mail = (EditText) findViewById(R.id.mail); phone = (EditText) findViewById(R.id.phone); text= (TextView) findViewById(R.id.textView); spinner2=(Spinner) findViewById(R.id.spinner2); // mylist=(ListView)findViewById(R.id.mylist); // spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, GetCreatedNames()); //selected item will look like a spinner set from XML fullo = (Spinner) findViewById(R.id.spinnersex); //Tab 1 TabHost.TabSpec spec; if (def.GetLanguage()) {// sets the two tabs using correct active language spec = host.newTabSpec("Προφίλ"); spec.setContent(R.id.baseone); spec.setIndicator("Προφίλ"); host.addTab(spec); //Tab 2 spec = host.newTabSpec("Νέο"); spec.setContent(R.id.basetwo); spec.setIndicator("Νέο Προφίλ"); host.addTab(spec); }else { spec = host.newTabSpec("Profil"); spec.setContent(R.id.baseone); spec.setIndicator("Profile"); host.addTab(spec); //Tab 2 spec = host.newTabSpec("New"); spec.setContent(R.id.basetwo); spec.setIndicator("New profile"); host.addTab(spec); } Button captureButtonU = (Button) findViewById(R.id.gotomain);// on select profile button captureButtonU.setFocusable(true); //captureButton.setFocusableInTouchMode(true); captureButtonU.requestFocus(); captureButtonU.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // int id=GetSelectedId(String.valueOf(spinner2.getSelectedItem())); // gets the spinner id if (id>-1) { //if there is no error Configurations def = db.getDEf(); // gets latest instance of configuration //String [] profnames = GetCreatedNames(); // String name = profnames[id]; Log.d("profname",db.getProfile(def.GetPID()).GetProfilname()); // Profile pr= db.getProfilebyname(name); def.SetPID(id); // set the selected id to configurations db.updateDef(def); // updates configuration } Intent intentU = new Intent(getApplicationContext(), CameraActivity.class);// goes to start screen startActivity(intentU); // } }); Button captureButtonU2 = (Button) findViewById(R.id.save);// saves new profile button captureButtonU2.setFocusable(true); //captureButton.setFocusableInTouchMode(true); captureButtonU2.requestFocus(); captureButtonU2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if ( age.getText().toString().isEmpty()|| String.valueOf(fullo.getSelectedItem()).isEmpty()|| name.getText().toString().isEmpty()|| profilname.getText().toString().isEmpty()|| mail.getText().toString().isEmpty() // || phone.getText().toString().isEmpty() )// if all data filled (except phone number ) {// prints error text.setText("Εισάγετε τα στοιχεία του νέου προφίλ σας." + "\nΠρέπει να συμπληρώσετε όλα τα στοιχεία \n πριν προχωρήσετε !!!!", TextView.BufferType.EDITABLE); text.setTextColor(RED); getWindow().getDecorView().findViewById(R.id.base).invalidate(); } else if (( mail.getText().toString().indexOf('@')<1)||(mail.getText().toString().indexOf('@')>=mail.getText().toString().length()-1)) {// if mail is not in right shape shows error text.setText("Εισάγετε τα στοιχεία του νέου προφίλ σας." + "\n Το e-mail που δώσατε δεν πρέπει να είναι σωστό !!!!", TextView.BufferType.EDITABLE); text.setTextColor(RED); getWindow().getDecorView().findViewById(R.id.base).invalidate(); } else { String string = mail.getText().toString(); Pattern pattern = Pattern.compile("([@])");// checks if there is more than one @ in mail Matcher matcher = pattern.matcher(string); int count = 0; while (matcher.find()) count++; if (count>1) { // if there is many @ prints error text.setText("Εισάγετε τα στοιχεία του νέου προφίλ σας." + "\n Το e-mail που δώσατε δεν πρέπει να είναι σωστό !!!!", TextView.BufferType.EDITABLE); text.setTextColor(RED); getWindow().getDecorView().findViewById(R.id.base).invalidate(); }else { //if all seems to be right int id = CreateNewProfile(); // creates new profile Configurations def = db.getDEf();// gets Configurations instance and activates new id def.SetPID(id);// db.updateDef(def); Intent intentU = new Intent(getApplicationContext(), CameraActivity.class);// go back to start screen startActivity(intentU); } } } }); Button captureButtonD = (Button) findViewById(R.id.deleteprofil); // if delete button pressed captureButtonD.setFocusable(true); //captureButton.setFocusableInTouchMode(true); captureButtonD.requestFocus(); captureButtonD.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // int id; try{ id=GetSelectedId(String.valueOf(spinner2.getSelectedItem()));} // gets the selected profiles id catch(NullPointerException e) { id=0; } Log.d("id", Integer.toString(id)); if (id>0) { // if the id is found and there is not the default id (id 0 ) Configurations def = db.getDEf();// gets the configuration def.SetPID(0); /// set the defaults profile as active db.updateDef(def);// update configurations db.deleteProfile(db.getProfile(id));// delete the profile having the id finish(); // restarts the intent startActivity(getIntent()); } } }); if (db.getProfileCount()>1) {// if there is more profiles except the defaults ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, GetCreatedNames()); //selected item will look like a spinner set from XML // fill the ArrayAdapter with profile names spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner2.setAdapter(spinnerArrayAdapter);// link the array adapter to spinner spinner2.setSelection(Getpos()); // sets the active profile as selected getWindow().getDecorView().findViewById(R.id.baseone).invalidate();//updates grafics } } /* this function is the checkbutton listener // on change condition event get as input the id of checkbox which changed // and the new condition and updates the correct static var . */ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { // if checked sets true switch (buttonView.getId()) { case R.id.history: history = true; //do stuff break; } } else { switch (buttonView.getId()) {// if not sets false case R.id.history: history = false; //do stuff break; } }} /* This function creates a new profile filling it with data that user gave it returns the id of new profile */ public int CreateNewProfile( ){ Configurations def=db.getDEf();// gets the app latest configurations def.PIDCOUntup(); // creates new id def.SetPID(GetNewId(def)); //sets the new id to configurations Profile last = new Profile(); // crates a new instance of profile db.updateDef(def); // updates the db Log.d("new profiles id is = ",Integer.toString(GetNewId(def))); last.SetAge(Integer.parseInt(age.getText().toString()));// fills profile last with data last.SetIdM(GetNewId(def)); last.SetSex(String.valueOf(fullo.getSelectedItem())); last.SetHistory(history); last.SetName(name.getText().toString()); last.SetProfilname(profilname.getText().toString()); last.SetMail(mail.getText().toString()); last.SetPhone(phone.getText().toString()); db.addprofile(last); // adds last to db // Molestest(last); return last.GetIdM(); // returns the id } public int GetNewId( Configurations def) { // gets the latest id from db int id = def.GetPIDCOUnt(); return id; } /* this function gets the name of profile as input , finds its id and returns it */ public int GetSelectedId(String in ){ List<Profile> myList = new ArrayList<Profile>(); myList =db.getAllProfiles();// get all profiles stored in db int out=-1;//init for(int i=myList.size()-1;i>=0;i--){ if (myList.get(i).GetProfilname().equals(in)) { // if the name match any profile name out = myList.get(i).GetIdM(); //gets its id break; } } return out; } /* The function GetCreatedNames returns all profile names that is stored in db in backwards order */ public String [] GetCreatedNames( ){ List<Profile> myList = new ArrayList<Profile>(); myList =db.getAllProfiles(); // gets all profiles String names [] = new String[myList.size()]; int count =0; for(int i=myList.size()-1;i>=0;i--){ // names[count]=myList.get(count).GetProfilname();//saves profile names backwards count++;// names counter } return names; } /* The function Getpos returns the position of the active profile in the spinner line */ public int Getpos( ){ List<Profile> myList = new ArrayList<Profile>(); myList =db.getAllProfiles();// gets all profiles String names [] = new String[myList.size()]; int count =0; for(int i=myList.size()-1;i>=0;i--){ names[count]=myList.get(count).GetProfilname();//saves profile names backwards count++;// names counter } int pos =0; // init the position Configurations def = db.getDEf();// gets apps configuration Profile prof = db.getProfile(def.GetPID()); // gets actives profile instance for (int i=0;i<myList.size();i++) { if (names[i].equals( prof.GetProfilname())) { //if the name of active profile is equal with any name in the list Log.d("prof", Integer.toString(i)); pos = i;// returns the position of the name break; } } return pos;// returns the position of the name } @Override public void onBackPressed() {// when back pressed go to mail activity Intent intent = new Intent(getApplicationContext(), CameraActivity.class); startActivity(intent); } }
42017_2
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package javaapplication1; import java.util.*; import java.util.regex.*; /** * * @author lubo */ public class GreekChar { private static HashMap<String, GreekChar> characters = new java.util.HashMap(); private static HashSet<String> capsSet = new HashSet(); private static HashSet<String> greekSet = new HashSet(); private static HashSet<String> viSet = new HashSet(); private static Pattern pattern; private static String regEx = ""; public String greek; public boolean fivi; public String greeklish; public boolean bi; private GreekChar(String greek, boolean fivi, String greeklish, boolean bi) { this.greek = greek; this.fivi = fivi; this.greeklish = greeklish; this.bi = bi; } private GreekChar(String greek, boolean fivi) { this.greek = greek; this.fivi = fivi; } private GreekChar(String greek) { this.greek = greek; } private GreekChar(String greek, String greeklish) { this.greek = greek; this.greeklish = greeklish; } private static void put(GreekChar cr) { if (regEx.length() != 0) regEx = regEx + "|"; regEx = regEx + cr.greek; characters.put(cr.greek, cr); } private static void put(String greek, String greeklish) { if (regEx.length() != 0) regEx = regEx + "|"; regEx = regEx + greek; characters.put(greek, new GreekChar(greek, greeklish)); } private static String fixCase(String text, String mirror) { String c_0 = String.valueOf(mirror.charAt(0)); if (capsSet.contains(c_0)) { if (mirror.length() == 1 || capsSet.contains(String.valueOf(mirror.charAt(1)))) { return text.toUpperCase(); } else { return String.valueOf(text.charAt(0)).toUpperCase() + (text.length()>=2 ? String.valueOf(text.charAt(1)) : ""); } } else { return text; } } public static String translate(String text) { if (null == text) { return null; } int length = text.length(); if (0 == length) { return null; } int i_1, i_2; String c_1, c_2, replace, group, lower; GreekChar gc; StringBuffer sb = new StringBuffer(); Matcher m = GreekChar.pattern.matcher(text); while (m.find()) { replace = ""; group = m.group(); lower = group.toLowerCase(); // ΤΣ -> τς gc = GreekChar.characters.get(lower); if (gc.bi) { i_1 = m.start() -1; i_2 = m.start() +2; c_1 = i_1 >= 0 ? String.valueOf(text.charAt(i_1)).toLowerCase() : ""; c_2 = i_2 < length ? String.valueOf(text.charAt(i_2)).toLowerCase() : ""; if (GreekChar.greekSet.contains(c_1) && GreekChar.greekSet.contains(c_2)) { replace = GreekChar.fixCase("mp", group); } else { replace = GreekChar.fixCase("b", group); } } else { if (gc.fivi) { i_2 = m.start() +2; c_1 = GreekChar.characters.get(String.valueOf(group.charAt(0)).toLowerCase()).greeklish; c_2 = i_2 < length ? (GreekChar.viSet.contains(String.valueOf(text.charAt(i_2)).toLowerCase()) ? "v" : "f") : ""; replace = GreekChar.fixCase(c_1 + c_2, group); } else { i_1 = m.start() + group.length(); c_1 = i_1 < length ? String.valueOf(text.charAt(i_1)) : " "; replace = GreekChar.fixCase(gc.greeklish, group + c_1); } } m.appendReplacement(sb, replace); } m.appendTail(sb); return sb.toString(); } static { GreekChar.put(new GreekChar("αι", "ai")); GreekChar.put(new GreekChar("αί", "ai")); GreekChar.put(new GreekChar("οι", "oi")); GreekChar.put(new GreekChar("οί", "oi")); GreekChar.put(new GreekChar("ου", "ou")); GreekChar.put(new GreekChar("ού", "ou")); GreekChar.put(new GreekChar("ει", "ei")); GreekChar.put(new GreekChar("εί", "ei")); GreekChar.put(new GreekChar("αυ", true)); GreekChar.put(new GreekChar("αύ", true)); GreekChar.put(new GreekChar("ευ", true)); GreekChar.put(new GreekChar("εύ", true)); GreekChar.put(new GreekChar("ηυ", true)); GreekChar.put(new GreekChar("ηύ", true)); GreekChar.put(new GreekChar("ντ", "nt")); GreekChar.put(new GreekChar("μπ", false, null, true)); GreekChar.put(new GreekChar("τσ", "ts")); GreekChar.put(new GreekChar("τς", "ts")); GreekChar.put(new GreekChar("τζ", "tz")); GreekChar.put(new GreekChar("γγ", "ng")); GreekChar.put(new GreekChar("γκ", "gk")); GreekChar.put(new GreekChar("γχ", "nch")); GreekChar.put(new GreekChar("γξ", "nx")); GreekChar.put(new GreekChar("θ" , "th")); GreekChar.put(new GreekChar("χ" , "ch")); GreekChar.put(new GreekChar("ψ" , "ps")); String grLetters = "αάβγδεέζηήθιίϊΐκλμνξοόπρσςτυύϋΰφχψωώ"; String engLetters = "aavgdeezii.iiiiklmnxooprsstyyyyf..oo"; String chGreek, chLatin; for(int i = 0, l = grLetters.length(); i<l; i++) { chGreek = String.valueOf(grLetters.charAt(i)); chLatin = String.valueOf(engLetters.charAt(i)); if (!GreekChar.characters.containsKey(chGreek)) { GreekChar.put(chGreek, chLatin); } } for(int i = 0, l = grLetters.length(); i<l; i++) { chGreek = String.valueOf(grLetters.charAt(i)); GreekChar.greekSet.add(chGreek); } grLetters = "ΑΆΒΓΔΕΈΖΗΉΘΙΊΪΚΛΜΝΞΟΌΠΡΣΤΥΎΫΦΧΨΩΏ"; for(int i = 0, l = grLetters.length(); i<l; i++) { chGreek = String.valueOf(grLetters.charAt(i)); GreekChar.capsSet.add(chGreek); } grLetters = "αβγδεζηλιmμνορω"; for(int i = 0, l = grLetters.length(); i<l; i++) { chGreek = String.valueOf(grLetters.charAt(i)); GreekChar.viSet.add(chGreek); } pattern = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); } }
luboid/elot-743
GreekChar.java
2,068
// ΤΣ -> τς
line_comment
el
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package javaapplication1; import java.util.*; import java.util.regex.*; /** * * @author lubo */ public class GreekChar { private static HashMap<String, GreekChar> characters = new java.util.HashMap(); private static HashSet<String> capsSet = new HashSet(); private static HashSet<String> greekSet = new HashSet(); private static HashSet<String> viSet = new HashSet(); private static Pattern pattern; private static String regEx = ""; public String greek; public boolean fivi; public String greeklish; public boolean bi; private GreekChar(String greek, boolean fivi, String greeklish, boolean bi) { this.greek = greek; this.fivi = fivi; this.greeklish = greeklish; this.bi = bi; } private GreekChar(String greek, boolean fivi) { this.greek = greek; this.fivi = fivi; } private GreekChar(String greek) { this.greek = greek; } private GreekChar(String greek, String greeklish) { this.greek = greek; this.greeklish = greeklish; } private static void put(GreekChar cr) { if (regEx.length() != 0) regEx = regEx + "|"; regEx = regEx + cr.greek; characters.put(cr.greek, cr); } private static void put(String greek, String greeklish) { if (regEx.length() != 0) regEx = regEx + "|"; regEx = regEx + greek; characters.put(greek, new GreekChar(greek, greeklish)); } private static String fixCase(String text, String mirror) { String c_0 = String.valueOf(mirror.charAt(0)); if (capsSet.contains(c_0)) { if (mirror.length() == 1 || capsSet.contains(String.valueOf(mirror.charAt(1)))) { return text.toUpperCase(); } else { return String.valueOf(text.charAt(0)).toUpperCase() + (text.length()>=2 ? String.valueOf(text.charAt(1)) : ""); } } else { return text; } } public static String translate(String text) { if (null == text) { return null; } int length = text.length(); if (0 == length) { return null; } int i_1, i_2; String c_1, c_2, replace, group, lower; GreekChar gc; StringBuffer sb = new StringBuffer(); Matcher m = GreekChar.pattern.matcher(text); while (m.find()) { replace = ""; group = m.group(); lower = group.toLowerCase(); // ΤΣ -><SUF> gc = GreekChar.characters.get(lower); if (gc.bi) { i_1 = m.start() -1; i_2 = m.start() +2; c_1 = i_1 >= 0 ? String.valueOf(text.charAt(i_1)).toLowerCase() : ""; c_2 = i_2 < length ? String.valueOf(text.charAt(i_2)).toLowerCase() : ""; if (GreekChar.greekSet.contains(c_1) && GreekChar.greekSet.contains(c_2)) { replace = GreekChar.fixCase("mp", group); } else { replace = GreekChar.fixCase("b", group); } } else { if (gc.fivi) { i_2 = m.start() +2; c_1 = GreekChar.characters.get(String.valueOf(group.charAt(0)).toLowerCase()).greeklish; c_2 = i_2 < length ? (GreekChar.viSet.contains(String.valueOf(text.charAt(i_2)).toLowerCase()) ? "v" : "f") : ""; replace = GreekChar.fixCase(c_1 + c_2, group); } else { i_1 = m.start() + group.length(); c_1 = i_1 < length ? String.valueOf(text.charAt(i_1)) : " "; replace = GreekChar.fixCase(gc.greeklish, group + c_1); } } m.appendReplacement(sb, replace); } m.appendTail(sb); return sb.toString(); } static { GreekChar.put(new GreekChar("αι", "ai")); GreekChar.put(new GreekChar("αί", "ai")); GreekChar.put(new GreekChar("οι", "oi")); GreekChar.put(new GreekChar("οί", "oi")); GreekChar.put(new GreekChar("ου", "ou")); GreekChar.put(new GreekChar("ού", "ou")); GreekChar.put(new GreekChar("ει", "ei")); GreekChar.put(new GreekChar("εί", "ei")); GreekChar.put(new GreekChar("αυ", true)); GreekChar.put(new GreekChar("αύ", true)); GreekChar.put(new GreekChar("ευ", true)); GreekChar.put(new GreekChar("εύ", true)); GreekChar.put(new GreekChar("ηυ", true)); GreekChar.put(new GreekChar("ηύ", true)); GreekChar.put(new GreekChar("ντ", "nt")); GreekChar.put(new GreekChar("μπ", false, null, true)); GreekChar.put(new GreekChar("τσ", "ts")); GreekChar.put(new GreekChar("τς", "ts")); GreekChar.put(new GreekChar("τζ", "tz")); GreekChar.put(new GreekChar("γγ", "ng")); GreekChar.put(new GreekChar("γκ", "gk")); GreekChar.put(new GreekChar("γχ", "nch")); GreekChar.put(new GreekChar("γξ", "nx")); GreekChar.put(new GreekChar("θ" , "th")); GreekChar.put(new GreekChar("χ" , "ch")); GreekChar.put(new GreekChar("ψ" , "ps")); String grLetters = "αάβγδεέζηήθιίϊΐκλμνξοόπρσςτυύϋΰφχψωώ"; String engLetters = "aavgdeezii.iiiiklmnxooprsstyyyyf..oo"; String chGreek, chLatin; for(int i = 0, l = grLetters.length(); i<l; i++) { chGreek = String.valueOf(grLetters.charAt(i)); chLatin = String.valueOf(engLetters.charAt(i)); if (!GreekChar.characters.containsKey(chGreek)) { GreekChar.put(chGreek, chLatin); } } for(int i = 0, l = grLetters.length(); i<l; i++) { chGreek = String.valueOf(grLetters.charAt(i)); GreekChar.greekSet.add(chGreek); } grLetters = "ΑΆΒΓΔΕΈΖΗΉΘΙΊΪΚΛΜΝΞΟΌΠΡΣΤΥΎΫΦΧΨΩΏ"; for(int i = 0, l = grLetters.length(); i<l; i++) { chGreek = String.valueOf(grLetters.charAt(i)); GreekChar.capsSet.add(chGreek); } grLetters = "αβγδεζηλιmμνορω"; for(int i = 0, l = grLetters.length(); i<l; i++) { chGreek = String.valueOf(grLetters.charAt(i)); GreekChar.viSet.add(chGreek); } pattern = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); } }
42599_0
public class Main { public static void main(String[] args) { Registry doai = new Registry("Applied Informatics"); Student s1 = new Student("Babis", "ics22038"); Student s2 = new Student("Soula", "iis21047"); Student s3 = new Student("Takis", "iis20112"); Course c1 = new Course("Python", 5); Course c2 = new Course("Databases", 5); //Καταχώρηση μαθημάτων στην γραμματεία doai.addCourse(c1); doai.addCourse(c2); ClassRoom r1 = new ClassRoom("Amf13", 80); ClassRoom r2 = new ClassRoom("Erg234", 34); c1.setRoom(r2); c2.setRoom(r1); c1.enrollStudent(s1); c1.enrollStudent(s2); c2.enrollStudent(s3); //c1.printDetails(); //c2.printDetails(); doai.printDepartmentInfo(); } }
madskgg/UoM-Applied-Informatics
Semester3/Object-Oriented Programming/Lectures/Week04/Main.java
314
//Καταχώρηση μαθημάτων στην γραμματεία
line_comment
el
public class Main { public static void main(String[] args) { Registry doai = new Registry("Applied Informatics"); Student s1 = new Student("Babis", "ics22038"); Student s2 = new Student("Soula", "iis21047"); Student s3 = new Student("Takis", "iis20112"); Course c1 = new Course("Python", 5); Course c2 = new Course("Databases", 5); //Καταχώρηση μαθημάτων<SUF> doai.addCourse(c1); doai.addCourse(c2); ClassRoom r1 = new ClassRoom("Amf13", 80); ClassRoom r2 = new ClassRoom("Erg234", 34); c1.setRoom(r2); c2.setRoom(r1); c1.enrollStudent(s1); c1.enrollStudent(s2); c2.enrollStudent(s3); //c1.printDetails(); //c2.printDetails(); doai.printDepartmentInfo(); } }
2503_19
package org.teiath.ellak.ellakandroideducation; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.LinkedList; import java.util.List; import java.util.Random; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; /** * Η κλάση DBHandler επιστρέφει πληροφορίες από τη βάση δεδομένων και δημιουργεί ερωτηματολόγια. Περιγράφονται κάποιες * από τις απαιτούμενες μεθόδους οι οποίες είναι απαραίτητες για την λειτουργία άλλων κλάσεων της εφαρμογής. * Η κλάση DBHandler είναι singleton. */ public class DBHandler { private static Context mcontext; private static DBHandler ourInstance; private Cursor cursor; private Cursor catCursor; private Cursor sumCursor; private Cursor ansCursor; private Cursor subCursor; private SQLiteDatabase sqldb; /** * Επιστρέφει αναφορά στο μοναδικό αντικείμενο που δημιουργείται από την κλάση. * Πρεπει να καλειται πρωτη για να λαμβανεται η αναφορα στο αντικειμενο. * * @param context ενα αντικειμενο context ειτε σαν μεταβλητη context ειτε σαν μεθοδο(getApplicationContext()). * @return Η αναφορά στο αντικείμενο. */ public static DBHandler getInstance(Context context) { if (ourInstance == null) { ourInstance = new DBHandler(context.getApplicationContext()); } return ourInstance; } /** * Ο κατασκευαστής του αντικειμένου. Εδώ τοποθετούνται οι αρχικοποιήσεις του αντικειμένου. Μία από τις λειτουργίες * πρέπει να είναι ο έλεγχος ύπαρξης του sqlite αρχείου στον αποθεκευτικό χώρο της εφαρμογής και η μεταφορά του από * τα assets αν χρειάζεται. */ private DBHandler(Context context) { mcontext = context; if (!CheckDB()) CopyDB(); } /** * Επιστρέφει την λίστα με τα γνωστικά αντικείμενα τα οποίες βρίσκονται στη Βάση Δεδομένων. Τα γνωστικά αντικείμενα * επιστρέφονται ως LinkedList με αντικείμενα {@link SubjectRec}. * * @return Η λίστα με τις κατηγορίες εξέτασης. */ public LinkedList<SubjectRec> GetKategories() { LinkedList<SubjectRec> list = new LinkedList<>(); String MyDB = mcontext.getApplicationContext().getFilesDir().getAbsolutePath() + "/databases/EllakDB.sqlite"; SQLiteDatabase sqldb = SQLiteDatabase.openDatabase(MyDB, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); Cursor cursor = sqldb.rawQuery("SELECT COUNT(*) FROM Subjects", null); cursor.moveToFirst(); int x = cursor.getInt(0); SubjectRec[] sr = new SubjectRec[x]; for (int j = 0; j < sr.length; j++) { sr[j] = new SubjectRec(); } cursor = sqldb.rawQuery("SELECT * FROM Subjects", null); cursor.moveToFirst(); for (int i = 0; i < sr.length; i++) { sr[i].SubjectID = cursor.getInt(0); sr[i].SubjectName = cursor.getString(1); list.add(sr[i]); cursor.moveToNext(); } cursor.close(); sqldb.close(); return list; } /** * Δημιουργεί και επιστρέφει ένα ολόκληρο ερωτηματολόγιο. Οι ερωτήσεις επιλέγονται τυχαία από τις διαθέσιμες * υποκατηγορίες και οι διαθέσιμες απαντήσεις των ερωτήσεων τοποθετούνται με, επίσης, τυχαία σειρά. * * @param Subject Ο κωδικός του γνωστικού αντικειμένου της εξέτασης. * @return Το ερωτηματολόγιο ως στιγμιότυπο της κλάσης {@link TestSheet}. */ public TestSheet CreateTestSheet(int Subject) { List<Integer> list; List<Integer> ansList = new LinkedList<>(); /** Χρησιμοποιούμε λίστες για να αποτρέψουμε την random από το να παράξει το ίδιο αποτέλεσμα **/ TestSheet ts = new TestSheet(); ts.SubjectID = Subject; int count = 0; cursorInit(Subject); int[] categories = categInit(); ts.Quests = makeQuest(); ts.ReqCorAnswers = reqAnswers(ts.Quests); for (int i = 0; i < categories.length; i++) { int q = categories[i]; list = getSubCateg(i); for (int j = 0; j < q; j++) { ts.Quests[count] = insertQuestions(list, ansList); ansList.clear(); count++; } list.clear(); } cursor = sqldb.rawQuery("SELECT STime FROM Subjects WHERE SubjectCode = " + Subject, null); cursor.moveToFirst(); ts.ExamTime = cursor.getInt(0); cursor.close(); catCursor.close(); ansCursor.close(); subCursor.close(); sumCursor.close(); sqldb.close(); return ts; } /** * Επιστρέφει την έκδοση της τρέχουσας έκδοσης της βάσης δεδομένων. * * @return Η τρέχουσα έκδοση της βάσης δεδομένων. */ public float GetVersion() { String MyDB = mcontext.getApplicationContext().getFilesDir().getAbsolutePath() + "/databases/EllakDB.sqlite"; SQLiteDatabase sqldb = SQLiteDatabase.openDatabase(MyDB, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); Cursor cursor = sqldb.rawQuery("SELECT * FROM Misc", null); cursor.moveToFirst(); float ver = cursor.getFloat(0); cursor.close(); sqldb.close(); return ver; } private boolean CheckDB() { String DB_PATH = mcontext.getApplicationContext().getFilesDir().getAbsolutePath() + "/databases/"; File dbf = new File(DB_PATH + "EllakDB.sqlite"); return dbf.exists(); } private void CopyDB() { InputStream myInput = null; try { myInput = mcontext.getApplicationContext().getAssets().open("EllakDB.sqlite"); CreateDirectory(); String DB_PATH = mcontext.getApplicationContext().getFilesDir().getAbsolutePath() + "/databases/"; String outFileName = DB_PATH + "EllakDB.sqlite"; OutputStream myOutput = new FileOutputStream(outFileName); byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } myOutput.close(); myInput.close(); } catch (IOException e) { System.err.println("Error in copying: " + e.getMessage()); } } private void CreateDirectory() { String DB_DIR = mcontext.getApplicationContext().getFilesDir().getAbsolutePath() + "/databases/"; File Dir = new File(DB_DIR); if (!Dir.exists()) Dir.mkdir(); } /** * Τοποθετεί τα δεδομένα απο τη βάση σε cursors για να χρησιμοποιηθούν στην createTestSheet. * * @param Subject ο αριθμός του γνωστικού αντικειμένου στη βάση. */ private void cursorInit(int Subject) { String MyDB = mcontext.getApplicationContext().getFilesDir().getAbsolutePath() + "/databases/EllakDB.sqlite"; sqldb = SQLiteDatabase.openDatabase(MyDB, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); cursor = sqldb.rawQuery("SELECT QCODE,QSUBJECT,QKATEG,QLECT,QPHOTO from questions where qsubject=" + Subject + " order by qkateg;", null); catCursor = sqldb.rawQuery("SELECT Kategory,Numb FROM Numbers WHERE SCode=" + Subject, null); sumCursor = sqldb.rawQuery("SELECT SUM(Numb) FROM Numbers WHERE SCode=" + Subject, null); subCursor = sqldb.rawQuery("SELECT SLect FROM Subjects WHERE SubjectCode=" + Subject, null); } /** * @return ο πίνακας των υποκατηγοριών και ο απαιτούμενος αριθμός ερωτήσεων για κάθε υποκατηγορία. */ private int[] categInit() { int[] categories = new int[catCursor.getCount()]; catCursor.moveToFirst(); for (int i = 0; i < categories.length; i++) { categories[i] = catCursor.getInt(1); catCursor.moveToNext(); } return categories; } /** * Αρχικοποιεί έναν πίνακα με αντικείμενα Question * * @return ο πίνακας με τα αντικείμενα τύπου Question */ private Question[] makeQuest() { sumCursor.moveToFirst(); Question[] Quests = new Question[sumCursor.getInt(0)]; for (int i = 0; i < Quests.length; i++) { Quests[i] = new Question(); } return Quests; } /** * Λαμβάνοντας το μήκος του πίνακα των ερωτήσεων υπολογίζει τις απαιτούμενες σωστές απαντήσεις. * * @param Quests Ο πίνακας με τις ερωτήσεις * @return Τον αριθμό των απαιτούμενων σωστών απαντήσεων */ private int reqAnswers(Question[] Quests) { int ReqCorAnswers; subCursor.moveToFirst(); if (subCursor.getString(0).equals("ΚΩΔΙΚΑΣ")) { ReqCorAnswers = Quests.length - 2; } else { ReqCorAnswers = Quests.length - 1; } return ReqCorAnswers; } /** * Γεμίζει μία λίστα με ερωτήσεις που ανήκουν σε μια συγκεκριμένη υποκατηγορία. * * @param i Ο αριθμός υποκατηγορίας * @return Την λίστα με τις ερωτήσεις μιας συγκεκριμένης υποκατηγορίας */ private List<Integer> getSubCateg(int i) { List<Integer> list = new LinkedList<>(); cursor.moveToFirst(); while (!cursor.isAfterLast()) { if (cursor.getInt(2) == i + 1) { list.add(cursor.getPosition()); } cursor.moveToNext(); } return list; } /** * Χρησιμοποιείται για να γεμίσει τον πίνακα των ερωτήσεων με τυχαίες ερωτήσεις * και τοποθετεί τις απαντήσεις επίσης με τυχαια σειρά. * * @param list η λίστα των ερωτήσεων * @param ansList η λίστα των απαντήσεων * @return Το αντικέιμενο τύπου Question που περιέχει όλα τα δεδομένα. */ private Question insertQuestions(List<Integer> list, List<Integer> ansList) { Question quest = new Question(); int numb = new Random().nextInt(list.size()); System.out.println(list.size()); cursor.moveToPosition(list.remove(numb)); ansCursor = sqldb.rawQuery("SELECT ALect,ACorr FROM Answers WHERE AQcod=" + cursor.getInt(0), null); quest.AText = new String[ansCursor.getCount()]; quest.QNum = cursor.getInt(0); quest.QText = cursor.getString(3); if (cursor.getString(4).equals("0")) { quest.PicName = "-"; } else { quest.PicName = cursor.getString(4) + ".jpg"; } for (int k = 0; k < ansCursor.getCount(); k++) { ansList.add(k); } for (int k = 0; k < ansCursor.getCount(); k++) { int ansNumb = new Random().nextInt(ansList.size()); ansCursor.moveToPosition(ansList.remove(ansNumb)); quest.AText[k] = ansCursor.getString(0); if (ansCursor.getInt(1) == 1) { quest.CorAnswer = k; } } return quest; } } /** * Παριστά,ως record, ένα γνωστικό αντικείμενο εξέτασης. */ class SubjectRec { /** * Ο κωδικός του γνωστικού αντικειμένου εξέτασης. */ public int SubjectID; /** * Το λεκτικό (όνομα) του γνωστικού αντικειμένου. */ public String SubjectName; } /** * Παριστά, ως Record, μία ερώτηση του ερωτηματολογίου. */ class Question { /** * Ο Αύξωντας Αριθμός της Ερώτησης στο ερωτηματολόγιο */ public int QNum; /** * Το κείμενο της ερώτησης */ public String QText; /** * Το όνομα του αρχείου εικόνας το οποίο αντιστοιχεί στην ερώτηση ("-" αν η ερώτηση δεν έχει εικόνα). */ public String PicName; /** * Πίνακας με τα κείμενα των απαντήσεων. Το μέγεθος του πίνακα δηλώνει και το πλήθος των απαντήσεων. */ public String[] AText; /** * Η θέση της σωστής απάντησης στον προηγούμενο πίνακα */ int CorAnswer; } /** * Παριστά, ως Record, ένα ολόκληρο ερωτηματολόγιο. */ class TestSheet { /** * Ο κωδικός του γνωστικού αντικειμένου του ερωτηματολογίου */ public int SubjectID; /** * Ο χρόνος εξέτασης σε πρώτα λεπτά της ώρας. */ public int ExamTime; /** * Πίνακας με τις ερωτήσεις του ερωτηματολογίου. Κάθε ερώτηση είναι ένα αντικείμενο της κλάσης {@link Question} */ public Question[] Quests; /** * Το πλήθος των ερωτήσεων που πρέπει να απαντηθούν σωστά προκειμένου η εξέταση να θεωρηθεί επιτυχής. */ int ReqCorAnswers; }
maellak/EllakAndroidEducation
app/src/main/java/org/teiath/ellak/ellakandroideducation/DBHandler.java
5,057
/** * Το όνομα του αρχείου εικόνας το οποίο αντιστοιχεί στην ερώτηση ("-" αν η ερώτηση δεν έχει εικόνα). */
block_comment
el
package org.teiath.ellak.ellakandroideducation; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.LinkedList; import java.util.List; import java.util.Random; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; /** * Η κλάση DBHandler επιστρέφει πληροφορίες από τη βάση δεδομένων και δημιουργεί ερωτηματολόγια. Περιγράφονται κάποιες * από τις απαιτούμενες μεθόδους οι οποίες είναι απαραίτητες για την λειτουργία άλλων κλάσεων της εφαρμογής. * Η κλάση DBHandler είναι singleton. */ public class DBHandler { private static Context mcontext; private static DBHandler ourInstance; private Cursor cursor; private Cursor catCursor; private Cursor sumCursor; private Cursor ansCursor; private Cursor subCursor; private SQLiteDatabase sqldb; /** * Επιστρέφει αναφορά στο μοναδικό αντικείμενο που δημιουργείται από την κλάση. * Πρεπει να καλειται πρωτη για να λαμβανεται η αναφορα στο αντικειμενο. * * @param context ενα αντικειμενο context ειτε σαν μεταβλητη context ειτε σαν μεθοδο(getApplicationContext()). * @return Η αναφορά στο αντικείμενο. */ public static DBHandler getInstance(Context context) { if (ourInstance == null) { ourInstance = new DBHandler(context.getApplicationContext()); } return ourInstance; } /** * Ο κατασκευαστής του αντικειμένου. Εδώ τοποθετούνται οι αρχικοποιήσεις του αντικειμένου. Μία από τις λειτουργίες * πρέπει να είναι ο έλεγχος ύπαρξης του sqlite αρχείου στον αποθεκευτικό χώρο της εφαρμογής και η μεταφορά του από * τα assets αν χρειάζεται. */ private DBHandler(Context context) { mcontext = context; if (!CheckDB()) CopyDB(); } /** * Επιστρέφει την λίστα με τα γνωστικά αντικείμενα τα οποίες βρίσκονται στη Βάση Δεδομένων. Τα γνωστικά αντικείμενα * επιστρέφονται ως LinkedList με αντικείμενα {@link SubjectRec}. * * @return Η λίστα με τις κατηγορίες εξέτασης. */ public LinkedList<SubjectRec> GetKategories() { LinkedList<SubjectRec> list = new LinkedList<>(); String MyDB = mcontext.getApplicationContext().getFilesDir().getAbsolutePath() + "/databases/EllakDB.sqlite"; SQLiteDatabase sqldb = SQLiteDatabase.openDatabase(MyDB, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); Cursor cursor = sqldb.rawQuery("SELECT COUNT(*) FROM Subjects", null); cursor.moveToFirst(); int x = cursor.getInt(0); SubjectRec[] sr = new SubjectRec[x]; for (int j = 0; j < sr.length; j++) { sr[j] = new SubjectRec(); } cursor = sqldb.rawQuery("SELECT * FROM Subjects", null); cursor.moveToFirst(); for (int i = 0; i < sr.length; i++) { sr[i].SubjectID = cursor.getInt(0); sr[i].SubjectName = cursor.getString(1); list.add(sr[i]); cursor.moveToNext(); } cursor.close(); sqldb.close(); return list; } /** * Δημιουργεί και επιστρέφει ένα ολόκληρο ερωτηματολόγιο. Οι ερωτήσεις επιλέγονται τυχαία από τις διαθέσιμες * υποκατηγορίες και οι διαθέσιμες απαντήσεις των ερωτήσεων τοποθετούνται με, επίσης, τυχαία σειρά. * * @param Subject Ο κωδικός του γνωστικού αντικειμένου της εξέτασης. * @return Το ερωτηματολόγιο ως στιγμιότυπο της κλάσης {@link TestSheet}. */ public TestSheet CreateTestSheet(int Subject) { List<Integer> list; List<Integer> ansList = new LinkedList<>(); /** Χρησιμοποιούμε λίστες για να αποτρέψουμε την random από το να παράξει το ίδιο αποτέλεσμα **/ TestSheet ts = new TestSheet(); ts.SubjectID = Subject; int count = 0; cursorInit(Subject); int[] categories = categInit(); ts.Quests = makeQuest(); ts.ReqCorAnswers = reqAnswers(ts.Quests); for (int i = 0; i < categories.length; i++) { int q = categories[i]; list = getSubCateg(i); for (int j = 0; j < q; j++) { ts.Quests[count] = insertQuestions(list, ansList); ansList.clear(); count++; } list.clear(); } cursor = sqldb.rawQuery("SELECT STime FROM Subjects WHERE SubjectCode = " + Subject, null); cursor.moveToFirst(); ts.ExamTime = cursor.getInt(0); cursor.close(); catCursor.close(); ansCursor.close(); subCursor.close(); sumCursor.close(); sqldb.close(); return ts; } /** * Επιστρέφει την έκδοση της τρέχουσας έκδοσης της βάσης δεδομένων. * * @return Η τρέχουσα έκδοση της βάσης δεδομένων. */ public float GetVersion() { String MyDB = mcontext.getApplicationContext().getFilesDir().getAbsolutePath() + "/databases/EllakDB.sqlite"; SQLiteDatabase sqldb = SQLiteDatabase.openDatabase(MyDB, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); Cursor cursor = sqldb.rawQuery("SELECT * FROM Misc", null); cursor.moveToFirst(); float ver = cursor.getFloat(0); cursor.close(); sqldb.close(); return ver; } private boolean CheckDB() { String DB_PATH = mcontext.getApplicationContext().getFilesDir().getAbsolutePath() + "/databases/"; File dbf = new File(DB_PATH + "EllakDB.sqlite"); return dbf.exists(); } private void CopyDB() { InputStream myInput = null; try { myInput = mcontext.getApplicationContext().getAssets().open("EllakDB.sqlite"); CreateDirectory(); String DB_PATH = mcontext.getApplicationContext().getFilesDir().getAbsolutePath() + "/databases/"; String outFileName = DB_PATH + "EllakDB.sqlite"; OutputStream myOutput = new FileOutputStream(outFileName); byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } myOutput.close(); myInput.close(); } catch (IOException e) { System.err.println("Error in copying: " + e.getMessage()); } } private void CreateDirectory() { String DB_DIR = mcontext.getApplicationContext().getFilesDir().getAbsolutePath() + "/databases/"; File Dir = new File(DB_DIR); if (!Dir.exists()) Dir.mkdir(); } /** * Τοποθετεί τα δεδομένα απο τη βάση σε cursors για να χρησιμοποιηθούν στην createTestSheet. * * @param Subject ο αριθμός του γνωστικού αντικειμένου στη βάση. */ private void cursorInit(int Subject) { String MyDB = mcontext.getApplicationContext().getFilesDir().getAbsolutePath() + "/databases/EllakDB.sqlite"; sqldb = SQLiteDatabase.openDatabase(MyDB, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); cursor = sqldb.rawQuery("SELECT QCODE,QSUBJECT,QKATEG,QLECT,QPHOTO from questions where qsubject=" + Subject + " order by qkateg;", null); catCursor = sqldb.rawQuery("SELECT Kategory,Numb FROM Numbers WHERE SCode=" + Subject, null); sumCursor = sqldb.rawQuery("SELECT SUM(Numb) FROM Numbers WHERE SCode=" + Subject, null); subCursor = sqldb.rawQuery("SELECT SLect FROM Subjects WHERE SubjectCode=" + Subject, null); } /** * @return ο πίνακας των υποκατηγοριών και ο απαιτούμενος αριθμός ερωτήσεων για κάθε υποκατηγορία. */ private int[] categInit() { int[] categories = new int[catCursor.getCount()]; catCursor.moveToFirst(); for (int i = 0; i < categories.length; i++) { categories[i] = catCursor.getInt(1); catCursor.moveToNext(); } return categories; } /** * Αρχικοποιεί έναν πίνακα με αντικείμενα Question * * @return ο πίνακας με τα αντικείμενα τύπου Question */ private Question[] makeQuest() { sumCursor.moveToFirst(); Question[] Quests = new Question[sumCursor.getInt(0)]; for (int i = 0; i < Quests.length; i++) { Quests[i] = new Question(); } return Quests; } /** * Λαμβάνοντας το μήκος του πίνακα των ερωτήσεων υπολογίζει τις απαιτούμενες σωστές απαντήσεις. * * @param Quests Ο πίνακας με τις ερωτήσεις * @return Τον αριθμό των απαιτούμενων σωστών απαντήσεων */ private int reqAnswers(Question[] Quests) { int ReqCorAnswers; subCursor.moveToFirst(); if (subCursor.getString(0).equals("ΚΩΔΙΚΑΣ")) { ReqCorAnswers = Quests.length - 2; } else { ReqCorAnswers = Quests.length - 1; } return ReqCorAnswers; } /** * Γεμίζει μία λίστα με ερωτήσεις που ανήκουν σε μια συγκεκριμένη υποκατηγορία. * * @param i Ο αριθμός υποκατηγορίας * @return Την λίστα με τις ερωτήσεις μιας συγκεκριμένης υποκατηγορίας */ private List<Integer> getSubCateg(int i) { List<Integer> list = new LinkedList<>(); cursor.moveToFirst(); while (!cursor.isAfterLast()) { if (cursor.getInt(2) == i + 1) { list.add(cursor.getPosition()); } cursor.moveToNext(); } return list; } /** * Χρησιμοποιείται για να γεμίσει τον πίνακα των ερωτήσεων με τυχαίες ερωτήσεις * και τοποθετεί τις απαντήσεις επίσης με τυχαια σειρά. * * @param list η λίστα των ερωτήσεων * @param ansList η λίστα των απαντήσεων * @return Το αντικέιμενο τύπου Question που περιέχει όλα τα δεδομένα. */ private Question insertQuestions(List<Integer> list, List<Integer> ansList) { Question quest = new Question(); int numb = new Random().nextInt(list.size()); System.out.println(list.size()); cursor.moveToPosition(list.remove(numb)); ansCursor = sqldb.rawQuery("SELECT ALect,ACorr FROM Answers WHERE AQcod=" + cursor.getInt(0), null); quest.AText = new String[ansCursor.getCount()]; quest.QNum = cursor.getInt(0); quest.QText = cursor.getString(3); if (cursor.getString(4).equals("0")) { quest.PicName = "-"; } else { quest.PicName = cursor.getString(4) + ".jpg"; } for (int k = 0; k < ansCursor.getCount(); k++) { ansList.add(k); } for (int k = 0; k < ansCursor.getCount(); k++) { int ansNumb = new Random().nextInt(ansList.size()); ansCursor.moveToPosition(ansList.remove(ansNumb)); quest.AText[k] = ansCursor.getString(0); if (ansCursor.getInt(1) == 1) { quest.CorAnswer = k; } } return quest; } } /** * Παριστά,ως record, ένα γνωστικό αντικείμενο εξέτασης. */ class SubjectRec { /** * Ο κωδικός του γνωστικού αντικειμένου εξέτασης. */ public int SubjectID; /** * Το λεκτικό (όνομα) του γνωστικού αντικειμένου. */ public String SubjectName; } /** * Παριστά, ως Record, μία ερώτηση του ερωτηματολογίου. */ class Question { /** * Ο Αύξωντας Αριθμός της Ερώτησης στο ερωτηματολόγιο */ public int QNum; /** * Το κείμενο της ερώτησης */ public String QText; /** * Το όνομα του<SUF>*/ public String PicName; /** * Πίνακας με τα κείμενα των απαντήσεων. Το μέγεθος του πίνακα δηλώνει και το πλήθος των απαντήσεων. */ public String[] AText; /** * Η θέση της σωστής απάντησης στον προηγούμενο πίνακα */ int CorAnswer; } /** * Παριστά, ως Record, ένα ολόκληρο ερωτηματολόγιο. */ class TestSheet { /** * Ο κωδικός του γνωστικού αντικειμένου του ερωτηματολογίου */ public int SubjectID; /** * Ο χρόνος εξέτασης σε πρώτα λεπτά της ώρας. */ public int ExamTime; /** * Πίνακας με τις ερωτήσεις του ερωτηματολογίου. Κάθε ερώτηση είναι ένα αντικείμενο της κλάσης {@link Question} */ public Question[] Quests; /** * Το πλήθος των ερωτήσεων που πρέπει να απαντηθούν σωστά προκειμένου η εξέταση να θεωρηθεί επιτυχής. */ int ReqCorAnswers; }
29390_4
//η λογικη πισω απο το duidoku public class LogicDuidoku { private static final int SIZE = 4; private int[][] board; private int x; private int y; //αρχικοποιει ενα πινακα duidoku public LogicDuidoku(){ board= new int[][]{{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}; } //επιστρεφει τους συμβατους αριθμους που μπορουν να προστεθουν σε ενα κελι public String getHelpClassicSudoku(int x,int y){ StringBuilder possible= new StringBuilder(); for(int i=1;i<5;i++){ if (isOk(x, y, i)) possible.append(i).append(","); } return possible.toString(); } //ελεγχει αν ενας αριθμος υπαρχει στην σειρα private boolean isInRow(int row, int number) { for (int i = 0; i < SIZE; i++) if (board[row][i] == number) return true; return false; } //ελεγχει αν ενας αριθμος υπαρχει στην στηλη private boolean isInCol(int col, int number) { for (int i = 0; i < SIZE; i++) if (board[i][col] == number) return true; return false; } //ελεγχει αν ενας αριθμος υπαρχει στο 2χ2 πινακα private boolean isInBox(int row, int col, int number) { int r = row - row % 2; int c = col - col % 2; for (int i = r; i < r + 2; i++) for (int j = c; j < c + 2; j++) if (board[i][j] == number) return true; return false; } //ελεγχει αν ο αριθμος εναι συμαβατος με ολους τους κανονες private boolean isOk(int row, int col, int number) { return !isInRow(row, number) && !isInCol(col, number) && !isInBox(row, col, number); } //προσθετει εναν αριθμο σε ενα κελι public boolean addMove(int row, int col, int number){ if( isOk(row,col,number) && number<5 && number>0 && board[row][col]==0){ board[row][col]=number; return true; }else { //pcMove(); return false; } } //προσθετει εναν αριθμο σε ενα κελι για χαρη του υπολογιστη public boolean pcMove() { //boolean b = false; for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { for (int num = 1; num <= SIZE; num++) { if (isOk(i, j, num) && board[i][j] == 0) { board[i][j] = num; x=i; y=j; return true; //b = true; // break; } } //if(b) // break; } //if(b) // break; } //if(Check()){ // System.out.print("PC Wins!\n"); //} return false; } //επιστρεφει τη συντεταγμενη χ τ κελιου που εκανε την κινηση του ο υπολογιστης public int getX() { return x; } //επιστρεφει τη συντεταγμενη y τ κελιου που εκανε την κινηση του ο υπολογιστης public int getY() { return y; } // επιστρεφει τα συμβατα γραμματα π μπορουν να τοποθετηθουν σε ενα κελι public String getHelpDuidokuWordoku(int x,int y){ StringBuilder possible= new StringBuilder(); for(int i=1;i<5;i++) { if (isOk(x, y, i)) { if (i == 1) possible.append("A").append(","); if (i == 2) possible.append("B").append(","); if (i == 3) possible.append("C").append(","); if (i == 4) possible.append("D").append(","); } } return possible.toString(); } //ελεγχει αν το duidoku εχει λυθει public boolean Check() { boolean b = false; boolean solved=true; for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { for (int num = 1; num <= SIZE; num++) { if (isOk(i, j, num) && board[i][j] == 0) { solved=false; b = true; break; } } if(b) break; } if(b) break; } return solved; } //επιστρεφει τον πινακα public int[][] getBoard() { return board; } }
makispanis/Sudoku
src/LogicDuidoku.java
1,565
//ελεγχει αν ενας αριθμος υπαρχει στην στηλη
line_comment
el
//η λογικη πισω απο το duidoku public class LogicDuidoku { private static final int SIZE = 4; private int[][] board; private int x; private int y; //αρχικοποιει ενα πινακα duidoku public LogicDuidoku(){ board= new int[][]{{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}; } //επιστρεφει τους συμβατους αριθμους που μπορουν να προστεθουν σε ενα κελι public String getHelpClassicSudoku(int x,int y){ StringBuilder possible= new StringBuilder(); for(int i=1;i<5;i++){ if (isOk(x, y, i)) possible.append(i).append(","); } return possible.toString(); } //ελεγχει αν ενας αριθμος υπαρχει στην σειρα private boolean isInRow(int row, int number) { for (int i = 0; i < SIZE; i++) if (board[row][i] == number) return true; return false; } //ελεγχει αν<SUF> private boolean isInCol(int col, int number) { for (int i = 0; i < SIZE; i++) if (board[i][col] == number) return true; return false; } //ελεγχει αν ενας αριθμος υπαρχει στο 2χ2 πινακα private boolean isInBox(int row, int col, int number) { int r = row - row % 2; int c = col - col % 2; for (int i = r; i < r + 2; i++) for (int j = c; j < c + 2; j++) if (board[i][j] == number) return true; return false; } //ελεγχει αν ο αριθμος εναι συμαβατος με ολους τους κανονες private boolean isOk(int row, int col, int number) { return !isInRow(row, number) && !isInCol(col, number) && !isInBox(row, col, number); } //προσθετει εναν αριθμο σε ενα κελι public boolean addMove(int row, int col, int number){ if( isOk(row,col,number) && number<5 && number>0 && board[row][col]==0){ board[row][col]=number; return true; }else { //pcMove(); return false; } } //προσθετει εναν αριθμο σε ενα κελι για χαρη του υπολογιστη public boolean pcMove() { //boolean b = false; for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { for (int num = 1; num <= SIZE; num++) { if (isOk(i, j, num) && board[i][j] == 0) { board[i][j] = num; x=i; y=j; return true; //b = true; // break; } } //if(b) // break; } //if(b) // break; } //if(Check()){ // System.out.print("PC Wins!\n"); //} return false; } //επιστρεφει τη συντεταγμενη χ τ κελιου που εκανε την κινηση του ο υπολογιστης public int getX() { return x; } //επιστρεφει τη συντεταγμενη y τ κελιου που εκανε την κινηση του ο υπολογιστης public int getY() { return y; } // επιστρεφει τα συμβατα γραμματα π μπορουν να τοποθετηθουν σε ενα κελι public String getHelpDuidokuWordoku(int x,int y){ StringBuilder possible= new StringBuilder(); for(int i=1;i<5;i++) { if (isOk(x, y, i)) { if (i == 1) possible.append("A").append(","); if (i == 2) possible.append("B").append(","); if (i == 3) possible.append("C").append(","); if (i == 4) possible.append("D").append(","); } } return possible.toString(); } //ελεγχει αν το duidoku εχει λυθει public boolean Check() { boolean b = false; boolean solved=true; for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { for (int num = 1; num <= SIZE; num++) { if (isOk(i, j, num) && board[i][j] == 0) { solved=false; b = true; break; } } if(b) break; } if(b) break; } return solved; } //επιστρεφει τον πινακα public int[][] getBoard() { return board; } }
14035_34
package org.dklisiaris.downtown; import java.util.ArrayList; import java.util.Collections; import org.dklisiaris.downtown.R; import org.dklisiaris.downtown.db.Product; import org.dklisiaris.downtown.helper.AccessAssets; import org.dklisiaris.downtown.helper.Utils; import org.dklisiaris.downtown.helper.XMLParser; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.AsyncTaskLoader; import android.support.v4.content.Loader; import android.support.v4.widget.SearchViewCompat.OnQueryTextListenerCompat; import android.support.v7.app.ActionBarActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; /** * Deprecated * It was used for xml-based search * @author MeeC * */ public class Search extends ActionBarActivity { // XML node keys static final String KEY_CATEGORY = "category"; // parent node static final String KEY_AREA = "brandname"; static final String KEY_NAME = "name"; static final String KEY_SUBCATEGORY = "subcategory"; static final String KEY_CATEGORIES = "categories"; static final String KEY_PRODUCT = "product"; static final String KEY_TEL = "price"; static final String KEY_DESC = "description"; static final String KEY_IMAGE = "image"; protected static ArrayList<String> menuItems; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FragmentManager fm = getSupportFragmentManager(); // Create the list fragment and add it as our sole content. if (fm.findFragmentById(android.R.id.content) == null) { SearchFragment search = new SearchFragment(); fm.beginTransaction().add(android.R.id.content, search).commit(); } } /** * A custom Loader that loads all of the installed applications. */ public static class ItemLoader extends AsyncTaskLoader<ArrayList<String>> { ArrayList<String> mItems; ArrayList<Product> allItems; String targetItem; Context ct; AccessAssets ast; Utils util; String xml; public ItemLoader(Context context) { super(context); targetItem = ((GlobalData)getContext()).getCategory(); allItems = ((GlobalData)getContext()).getAll_products(); ct = context; //Log.d("Subs for: ",targetItem); ast = new AccessAssets(ct); //Log.d("Created ","ast"); menuItems = new ArrayList<String>(); //xml = ast.readAssetFile("categories.xml"); util = new Utils(ct); xml = util.getStrFromInternalStorage("products.xml"); //Log.d("XML--->: ",xml); } /** * This is where the bulk of our work is done. This function is * called in a background thread and should generate a new set of * data to be published by the loader. */ @Override public ArrayList<String> loadInBackground() { XMLParser parser = new XMLParser(); Document doc = parser.getDomElement(xml); // getting DOM element NodeList nl = doc.getElementsByTagName(KEY_PRODUCT); // looping through all item nodes <category> for (int k = 0; k < nl.getLength();k++) { Element e = (Element) nl.item(k); if (parser.getValue(e, KEY_CATEGORY).equals(targetItem) && !(menuItems.contains(parser.getValue(e, KEY_AREA)))){ menuItems.add(parser.getValue(e, KEY_AREA)); } } Collections.sort(menuItems); // Done! return menuItems; } /** * Called when there is new data to deliver to the client. The * super class will take care of delivering it; the implementation * here just adds a little more logic. */ @Override public void deliverResult(ArrayList<String> items) { if (isReset()) { // An async query came in while the loader is stopped. We // don't need the result. if (items != null) { onReleaseResources(items); } } ArrayList<String> olditems = items; mItems = items; if (isStarted()) { // If the Loader is currently started, we can immediately // deliver its results. super.deliverResult(items); } // At this point we can release the resources associated with // 'olditems' if needed; now that the new result is delivered we // know that it is no longer in use. if (olditems != null) { onReleaseResources(olditems); } } /** * Handles a request to start the Loader. */ @Override protected void onStartLoading() { if (mItems != null) { // If we currently have a result available, deliver it // immediately. deliverResult(mItems); } else{ forceLoad(); } } /** * Handles a request to stop the Loader. */ @Override protected void onStopLoading() { // Attempt to cancel the current load task if possible. cancelLoad(); } /** * Handles a request to cancel a load. */ @Override public void onCanceled(ArrayList<String> items) { super.onCanceled(items); // At this point we can release the resources associated with 'items' // if needed. onReleaseResources(items); } /** * Handles a request to completely reset the Loader. */ @Override protected void onReset() { super.onReset(); // Ensure the loader is stopped onStopLoading(); // At this point we can release the resources associated with 'items' // if needed. if (mItems != null) { onReleaseResources(mItems); mItems = null; } } /** * Helper function to take care of releasing resources associated * with an actively loaded data set. */ protected void onReleaseResources(ArrayList<String> items) { // For a simple List<> there is nothing to do. For something // like a Cursor, we would close it here. } } public static class CustomAdapter extends ArrayAdapter<String> { private final LayoutInflater mInflater; public CustomAdapter(Context context) { super(context, R.layout.tab_list); mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public void setData(ArrayList<String> data) { clear(); if (data != null) { for (String entry : data) { add(entry); //Log.d("Added by cAdapter",entry); } } } /** * Populate new items in the list. */ @Override public View getView(int position, View convertView, ViewGroup parent) { View view; if (convertView == null) { view = mInflater.inflate(R.layout.list_item, parent, false); } else { view = convertView; } String item = getItem(position); ((TextView)view.findViewById(R.id.category)).setText(item); return view; } } public static class SearchFragment extends ListFragment implements LoaderManager.LoaderCallbacks<ArrayList<String>> { // This is the Adapter being used to display the list's data. CustomAdapter mAdapter; // If non-null, this is the current filter the user has provided. String mCurFilter; OnQueryTextListenerCompat mOnQueryTextListenerCompat; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Give some text to display if there is no data. //setEmptyText("Δεν βρέθηκε τίποτα..."); // We have a menu item to show in action bar. setHasOptionsMenu(true); setListAdapter(null); // Create an empty adapter we will use to display the loaded data. View header_view = View.inflate(getActivity(), R.layout.tabs_header, null); TextView hv = ((TextView)header_view.findViewById(R.id.ctgr)); hv.setText(((GlobalData)getActivity().getApplicationContext()).getCategory()); getListView().addHeaderView(header_view); // Create an empty adapter we will use to display the loaded data. if (mAdapter == null) { mAdapter = new CustomAdapter(getActivity()); } setListAdapter(mAdapter); // Start out with a progress indicator. setListShown(false); // Prepare the loader. Either re-connect with an existing one, // or start a new one. getLoaderManager().initLoader(0, null, this); //Intent i = getParent().getIntent(); // getting attached intent data } /* @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // Place an action bar item for searching. MenuItem item = menu.add("Search"); item.setIcon(android.R.drawable.ic_menu_search); item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); View searchView = SearchViewCompat.newSearchView(getActivity()); if (searchView != null) { SearchViewCompat.setOnQueryTextListener(searchView, new OnQueryTextListenerCompat() { @Override public boolean onQueryTextChange(String newText) { // Called when the action bar search text has changed. Since this // is a simple array adapter, we can just have it do the filtering. mCurFilter = !TextUtils.isEmpty(newText) ? newText : null; mAdapter.getFilter().filter(mCurFilter); return true; } }); item.setActionView(searchView); } }*/ @Override public void onListItemClick(ListView l, View v, int position, long id) { // Insert desired behavior here. //Log.d("Subcats..", "Item clicked: " + id); // selected item if((TextView)v.findViewById(R.id.category)!=null){ TextView tv = (TextView)v.findViewById(R.id.category); String product = tv.getText().toString(); String category = ((GlobalData)getActivity().getApplicationContext()).getCategory(); // Launching new Activity on selecting single List Item Intent i = new Intent(getActivity(), Products.class); // sending data to new activity i.putExtra("category", category); i.putExtra("product", product); i.putExtra("key", KEY_AREA); startActivity(i); } } @Override public Loader<ArrayList<String>> onCreateLoader(int id, Bundle args) { // This is called when a new Loader needs to be created. This // sample only has one Loader with no arguments, so it is simple. return new ItemLoader(getActivity()); } @Override public void onLoadFinished(Loader<ArrayList<String>> loader, ArrayList<String> data) { // Set the new data in the adapter. mAdapter.setData(data); // The list should now be shown. if (isResumed()) { setListShown(true); } else { setListShownNoAnimation(true); } } @Override public void onLoaderReset(Loader<ArrayList<String>> loader) { // Clear the data in the adapter. mAdapter.setData(null); } } }
manisoni28/downtown
downtown/src/main/java/org/dklisiaris/downtown/Search.java
2,748
//setEmptyText("Δεν βρέθηκε τίποτα...");
line_comment
el
package org.dklisiaris.downtown; import java.util.ArrayList; import java.util.Collections; import org.dklisiaris.downtown.R; import org.dklisiaris.downtown.db.Product; import org.dklisiaris.downtown.helper.AccessAssets; import org.dklisiaris.downtown.helper.Utils; import org.dklisiaris.downtown.helper.XMLParser; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.AsyncTaskLoader; import android.support.v4.content.Loader; import android.support.v4.widget.SearchViewCompat.OnQueryTextListenerCompat; import android.support.v7.app.ActionBarActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; /** * Deprecated * It was used for xml-based search * @author MeeC * */ public class Search extends ActionBarActivity { // XML node keys static final String KEY_CATEGORY = "category"; // parent node static final String KEY_AREA = "brandname"; static final String KEY_NAME = "name"; static final String KEY_SUBCATEGORY = "subcategory"; static final String KEY_CATEGORIES = "categories"; static final String KEY_PRODUCT = "product"; static final String KEY_TEL = "price"; static final String KEY_DESC = "description"; static final String KEY_IMAGE = "image"; protected static ArrayList<String> menuItems; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FragmentManager fm = getSupportFragmentManager(); // Create the list fragment and add it as our sole content. if (fm.findFragmentById(android.R.id.content) == null) { SearchFragment search = new SearchFragment(); fm.beginTransaction().add(android.R.id.content, search).commit(); } } /** * A custom Loader that loads all of the installed applications. */ public static class ItemLoader extends AsyncTaskLoader<ArrayList<String>> { ArrayList<String> mItems; ArrayList<Product> allItems; String targetItem; Context ct; AccessAssets ast; Utils util; String xml; public ItemLoader(Context context) { super(context); targetItem = ((GlobalData)getContext()).getCategory(); allItems = ((GlobalData)getContext()).getAll_products(); ct = context; //Log.d("Subs for: ",targetItem); ast = new AccessAssets(ct); //Log.d("Created ","ast"); menuItems = new ArrayList<String>(); //xml = ast.readAssetFile("categories.xml"); util = new Utils(ct); xml = util.getStrFromInternalStorage("products.xml"); //Log.d("XML--->: ",xml); } /** * This is where the bulk of our work is done. This function is * called in a background thread and should generate a new set of * data to be published by the loader. */ @Override public ArrayList<String> loadInBackground() { XMLParser parser = new XMLParser(); Document doc = parser.getDomElement(xml); // getting DOM element NodeList nl = doc.getElementsByTagName(KEY_PRODUCT); // looping through all item nodes <category> for (int k = 0; k < nl.getLength();k++) { Element e = (Element) nl.item(k); if (parser.getValue(e, KEY_CATEGORY).equals(targetItem) && !(menuItems.contains(parser.getValue(e, KEY_AREA)))){ menuItems.add(parser.getValue(e, KEY_AREA)); } } Collections.sort(menuItems); // Done! return menuItems; } /** * Called when there is new data to deliver to the client. The * super class will take care of delivering it; the implementation * here just adds a little more logic. */ @Override public void deliverResult(ArrayList<String> items) { if (isReset()) { // An async query came in while the loader is stopped. We // don't need the result. if (items != null) { onReleaseResources(items); } } ArrayList<String> olditems = items; mItems = items; if (isStarted()) { // If the Loader is currently started, we can immediately // deliver its results. super.deliverResult(items); } // At this point we can release the resources associated with // 'olditems' if needed; now that the new result is delivered we // know that it is no longer in use. if (olditems != null) { onReleaseResources(olditems); } } /** * Handles a request to start the Loader. */ @Override protected void onStartLoading() { if (mItems != null) { // If we currently have a result available, deliver it // immediately. deliverResult(mItems); } else{ forceLoad(); } } /** * Handles a request to stop the Loader. */ @Override protected void onStopLoading() { // Attempt to cancel the current load task if possible. cancelLoad(); } /** * Handles a request to cancel a load. */ @Override public void onCanceled(ArrayList<String> items) { super.onCanceled(items); // At this point we can release the resources associated with 'items' // if needed. onReleaseResources(items); } /** * Handles a request to completely reset the Loader. */ @Override protected void onReset() { super.onReset(); // Ensure the loader is stopped onStopLoading(); // At this point we can release the resources associated with 'items' // if needed. if (mItems != null) { onReleaseResources(mItems); mItems = null; } } /** * Helper function to take care of releasing resources associated * with an actively loaded data set. */ protected void onReleaseResources(ArrayList<String> items) { // For a simple List<> there is nothing to do. For something // like a Cursor, we would close it here. } } public static class CustomAdapter extends ArrayAdapter<String> { private final LayoutInflater mInflater; public CustomAdapter(Context context) { super(context, R.layout.tab_list); mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public void setData(ArrayList<String> data) { clear(); if (data != null) { for (String entry : data) { add(entry); //Log.d("Added by cAdapter",entry); } } } /** * Populate new items in the list. */ @Override public View getView(int position, View convertView, ViewGroup parent) { View view; if (convertView == null) { view = mInflater.inflate(R.layout.list_item, parent, false); } else { view = convertView; } String item = getItem(position); ((TextView)view.findViewById(R.id.category)).setText(item); return view; } } public static class SearchFragment extends ListFragment implements LoaderManager.LoaderCallbacks<ArrayList<String>> { // This is the Adapter being used to display the list's data. CustomAdapter mAdapter; // If non-null, this is the current filter the user has provided. String mCurFilter; OnQueryTextListenerCompat mOnQueryTextListenerCompat; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Give some text to display if there is no data. //setEmptyText("Δεν βρέθηκε<SUF> // We have a menu item to show in action bar. setHasOptionsMenu(true); setListAdapter(null); // Create an empty adapter we will use to display the loaded data. View header_view = View.inflate(getActivity(), R.layout.tabs_header, null); TextView hv = ((TextView)header_view.findViewById(R.id.ctgr)); hv.setText(((GlobalData)getActivity().getApplicationContext()).getCategory()); getListView().addHeaderView(header_view); // Create an empty adapter we will use to display the loaded data. if (mAdapter == null) { mAdapter = new CustomAdapter(getActivity()); } setListAdapter(mAdapter); // Start out with a progress indicator. setListShown(false); // Prepare the loader. Either re-connect with an existing one, // or start a new one. getLoaderManager().initLoader(0, null, this); //Intent i = getParent().getIntent(); // getting attached intent data } /* @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // Place an action bar item for searching. MenuItem item = menu.add("Search"); item.setIcon(android.R.drawable.ic_menu_search); item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); View searchView = SearchViewCompat.newSearchView(getActivity()); if (searchView != null) { SearchViewCompat.setOnQueryTextListener(searchView, new OnQueryTextListenerCompat() { @Override public boolean onQueryTextChange(String newText) { // Called when the action bar search text has changed. Since this // is a simple array adapter, we can just have it do the filtering. mCurFilter = !TextUtils.isEmpty(newText) ? newText : null; mAdapter.getFilter().filter(mCurFilter); return true; } }); item.setActionView(searchView); } }*/ @Override public void onListItemClick(ListView l, View v, int position, long id) { // Insert desired behavior here. //Log.d("Subcats..", "Item clicked: " + id); // selected item if((TextView)v.findViewById(R.id.category)!=null){ TextView tv = (TextView)v.findViewById(R.id.category); String product = tv.getText().toString(); String category = ((GlobalData)getActivity().getApplicationContext()).getCategory(); // Launching new Activity on selecting single List Item Intent i = new Intent(getActivity(), Products.class); // sending data to new activity i.putExtra("category", category); i.putExtra("product", product); i.putExtra("key", KEY_AREA); startActivity(i); } } @Override public Loader<ArrayList<String>> onCreateLoader(int id, Bundle args) { // This is called when a new Loader needs to be created. This // sample only has one Loader with no arguments, so it is simple. return new ItemLoader(getActivity()); } @Override public void onLoadFinished(Loader<ArrayList<String>> loader, ArrayList<String> data) { // Set the new data in the adapter. mAdapter.setData(data); // The list should now be shown. if (isResumed()) { setListShown(true); } else { setListShownNoAnimation(true); } } @Override public void onLoaderReset(Loader<ArrayList<String>> loader) { // Clear the data in the adapter. mAdapter.setData(null); } } }
28605_0
package gr.aueb.cf.ch1JavaTypeSystem; /** * Εκτυπώνει στην κονσόλα (std output) * τα αρχικά με αστεράκια. */ public class InitialsApp { public static void main(String[] args) { System.out.println("* * ******"); System.out.println("* * * *"); System.out.println("* * * *"); System.out.println("* * *"); } }
mariatemp/java-oo-projects
src/gr/aueb/cf/ch1JavaTypeSystem/InitialsApp.java
144
/** * Εκτυπώνει στην κονσόλα (std output) * τα αρχικά με αστεράκια. */
block_comment
el
package gr.aueb.cf.ch1JavaTypeSystem; /** * Εκτυπώνει στην κονσόλα<SUF>*/ public class InitialsApp { public static void main(String[] args) { System.out.println("* * ******"); System.out.println("* * * *"); System.out.println("* * * *"); System.out.println("* * *"); } }
19958_7
/*------------------------------------------------------------------------- * Copyright (c) 2012,2013, Alex Athanasopoulos. All Rights Reserved. * [email protected] *------------------------------------------------------------------------- * This file is part of Athens Next Bus * * Athens Next Bus is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Athens Next Bus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Athens Next Bus. If not, see <http://www.gnu.org/licenses/>. *------------------------------------------------------------------------- */ package org.melato.bus.model; import java.io.Serializable; /** * Contains basic information about a bus route in a certain direction, * including its schedule. * @author Alex Athanasopoulos * */ public class Route implements Cloneable, Serializable, Comparable<Route> { private static final long serialVersionUID = 1L; // route types. Use GTFS constants. public static final int TRAM = 0; public static final int METRO = 1; public static final int BUS = 3; public static final int FLAG_PRIMARY = 0x1; /** Do not include the label in the title. * Some agencies do not use labels. * All routes of that agency may have the same label. * This flag specifies that the label will not be prepended to the route title when displaying the route. * The label may still appear in places where only labels appear, e.g. in itineraries. * */ public static final int FLAG_NOLABEL = 0x2; private RouteId routeId; /** The internal agency name */ private String agencyName; /** The label that the user sees, e.g. "301B" * The label is usually name in uppercase. * */ private String label; /** The longer descriptive title of the bus line. */ private String title; // e.g. "Γραμμή 304 ΣΤ. ΝΟΜΙΣΜΑΤΟΚΟΠΕΙΟ - ΑΡΤΕΜΙΣ (ΒΡΑΥΡΩΝΑ)" private int color = 0x0000ff; private int backgroundColor = 0; private int flags; private int type; public Route() { super(); } @Override public Route clone() { try { return (Route) super.clone(); } catch( CloneNotSupportedException e ) { throw new RuntimeException(e); } } public String getAgencyName() { return agencyName; } public void setAgencyName(String agencyName) { this.agencyName = agencyName; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } /** * The type of the route. * @return A GTFS route type constant. * 0 tram * 1 metro * 2 rail * 3 bus */ public int getType() { return type; } public void setType(int type) { this.type = type; } public int getColor() { return color; } public void setColor(int color) { this.color = color; } public int getBackgroundColor() { return backgroundColor; } public void setBackgroundColor(int backgroundColor) { this.backgroundColor = backgroundColor; } public int getFlags() { return flags; } public void setFlags(int flags) { this.flags = flags; } public void setFlag(int flag) { this.flags |= flag; } public boolean isFlag(int flag) { return (this.flags & flag) != 0; } public boolean isPrimary() { return (flags & FLAG_PRIMARY) != 0; } public void setPrimary(boolean primary) { flags |= FLAG_PRIMARY; } public String getDirection() { return routeId.getDirection(); } public String getFullTitle() { if ( isFlag(FLAG_NOLABEL)) { return getTitle(); } else { return getLabel() + " " + getTitle(); } } @Override public String toString() { return getFullTitle(); } @Override public int compareTo(Route r) { int d = AlphanumericComparator.INSTANCE.compare(label, r.label); if ( d != 0 ) return d; return AlphanumericComparator.INSTANCE.compare(getDirection(), r.getDirection()); } /** This is an external route id, used for storing in caches, etc. * */ public RouteId getRouteId() { return routeId; } public void setRouteId(RouteId routeId) { this.routeId = routeId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((routeId == null) ? 0 : routeId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Route other = (Route) obj; if (routeId == null) { if (other.routeId != null) return false; } else if (!routeId.equals(other.routeId)) return false; return true; } public boolean isSameColor(Route route) { return color == route.color && backgroundColor == route.backgroundColor; } }
melato/next-bus
src/org/melato/bus/model/Route.java
1,464
// e.g. "Γραμμή 304 ΣΤ. ΝΟΜΙΣΜΑΤΟΚΟΠΕΙΟ - ΑΡΤΕΜΙΣ (ΒΡΑΥΡΩΝΑ)"
line_comment
el
/*------------------------------------------------------------------------- * Copyright (c) 2012,2013, Alex Athanasopoulos. All Rights Reserved. * [email protected] *------------------------------------------------------------------------- * This file is part of Athens Next Bus * * Athens Next Bus is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Athens Next Bus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Athens Next Bus. If not, see <http://www.gnu.org/licenses/>. *------------------------------------------------------------------------- */ package org.melato.bus.model; import java.io.Serializable; /** * Contains basic information about a bus route in a certain direction, * including its schedule. * @author Alex Athanasopoulos * */ public class Route implements Cloneable, Serializable, Comparable<Route> { private static final long serialVersionUID = 1L; // route types. Use GTFS constants. public static final int TRAM = 0; public static final int METRO = 1; public static final int BUS = 3; public static final int FLAG_PRIMARY = 0x1; /** Do not include the label in the title. * Some agencies do not use labels. * All routes of that agency may have the same label. * This flag specifies that the label will not be prepended to the route title when displaying the route. * The label may still appear in places where only labels appear, e.g. in itineraries. * */ public static final int FLAG_NOLABEL = 0x2; private RouteId routeId; /** The internal agency name */ private String agencyName; /** The label that the user sees, e.g. "301B" * The label is usually name in uppercase. * */ private String label; /** The longer descriptive title of the bus line. */ private String title; // e.g. "Γραμμή<SUF> private int color = 0x0000ff; private int backgroundColor = 0; private int flags; private int type; public Route() { super(); } @Override public Route clone() { try { return (Route) super.clone(); } catch( CloneNotSupportedException e ) { throw new RuntimeException(e); } } public String getAgencyName() { return agencyName; } public void setAgencyName(String agencyName) { this.agencyName = agencyName; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } /** * The type of the route. * @return A GTFS route type constant. * 0 tram * 1 metro * 2 rail * 3 bus */ public int getType() { return type; } public void setType(int type) { this.type = type; } public int getColor() { return color; } public void setColor(int color) { this.color = color; } public int getBackgroundColor() { return backgroundColor; } public void setBackgroundColor(int backgroundColor) { this.backgroundColor = backgroundColor; } public int getFlags() { return flags; } public void setFlags(int flags) { this.flags = flags; } public void setFlag(int flag) { this.flags |= flag; } public boolean isFlag(int flag) { return (this.flags & flag) != 0; } public boolean isPrimary() { return (flags & FLAG_PRIMARY) != 0; } public void setPrimary(boolean primary) { flags |= FLAG_PRIMARY; } public String getDirection() { return routeId.getDirection(); } public String getFullTitle() { if ( isFlag(FLAG_NOLABEL)) { return getTitle(); } else { return getLabel() + " " + getTitle(); } } @Override public String toString() { return getFullTitle(); } @Override public int compareTo(Route r) { int d = AlphanumericComparator.INSTANCE.compare(label, r.label); if ( d != 0 ) return d; return AlphanumericComparator.INSTANCE.compare(getDirection(), r.getDirection()); } /** This is an external route id, used for storing in caches, etc. * */ public RouteId getRouteId() { return routeId; } public void setRouteId(RouteId routeId) { this.routeId = routeId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((routeId == null) ? 0 : routeId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Route other = (Route) obj; if (routeId == null) { if (other.routeId != null) return false; } else if (!routeId.equals(other.routeId)) return false; return true; } public boolean isSameColor(Route route) { return color == route.color && backgroundColor == route.backgroundColor; } }
2018_14
package DeviceClientV1 ; import java.util.ArrayList; /** * Κλάση που διαχειρίζεται εξ ολοκλήρου τα διάφορα μηνύματα που μεταφέρονται * μέσα από τα socket . * Δημιουργήθηκε ένα “πρωτόκολλο” επικοινωνίας για να γίνεται δομημένα και * αυτοματοποιημένα η επικοινωνία με τη χρήση των socket * Τα μηνύματα έχουν μια συγκεκριμένη μορφή : * #{SystemID}@{Τύπος Αποστολέα(S,D,UD)}${Εντολή}:{Πλήθος παραμέτρων}*{(Παράμετρος0.0)}{(Παράμετρος1.0|Παράμετρος1.1}); * @author Michael Galliakis */ public class ManageSocketMessage { CommandType commandType ; String strCommand ; int intSumOfParameters ; String strSenderType ; String strSenderDBID ; ArrayList<ArrayList<String>> alParameters ; String message ; boolean correct ; /** * Διάφοροι τύποι μηνυμάτων . */ enum CommandType{ Error ,Failed ,Login ,LoginReply ,certification ,GetDevicesInfo ,PutDevicesInfo ,BringMeDevice ,InitControllers ,NewController ,AlterController ,DeleteController ,NewValues ,InitializationFinished ,ChangeValues ,ChangeModes ,Anwser ,GetTypeUser ,PutTypeUser ,TSNC } /** * Μέθοδος που ψάχνει να βρει αν υπάρχει κάποιος τύπος. * @param comm λέξη κλειδί που θα αναζητηθεί . * @return Επιστρέφετε ο τύπος που βρέθηκε και αν δεν βρέθηκε επιστρέφετε το TSNC */ private CommandType findCommandType(String comm) { for (CommandType co : CommandType.values()) if (co.name().equals(comm)) return co ; return CommandType.TSNC ; } /** * Στατική μέθοδος που δημιουργεί με βάση κάποιους παραμέτρους ένα έγκυρο * μήνυμα χωρίς συντακτικά λάθη για να μπορεί να μεταφερθεί μέσα από socket . * @param IDAndType Μια συμβολοσειρά που έχει το ID και το Τύπο του αποστολέα. * @param command Μια συμβολοσειρά που έχει το όνομα της εντολής του μηνύματος. * @param parameters Ένας δισδιάστατος πίνακας που θα έχει μέσα όλους τους παραμέτρους του μηνύματος. * @return Επιστρέφετε μια συμβολοσειρά με όλο το μήνυμα σωστά συνταγμένο . */ public static String newMessage(String IDAndType,CommandType command,String[][] parameters) { String message = "#"+ IDAndType + "$" + command.name() +":" + parameters.length + "*" ; for (int i = 0 ; i<parameters.length;i++) { message +="(" ; if (parameters[i].length > 0) message += parameters[i][0] ; for (int j = 1 ; j<parameters[i].length;j++) message += "|" + parameters[i][j] ; message +=")" ; } message +=";" ; return message ; } /** * Στατική μέθοδος που δημιουργεί με βάση κάποιους παραμέτρους ένα έγκυρο * μήνυμα χωρίς συντακτικά λάθη για να μπορεί να μεταφερθεί μέσα από socket . * @param IDAndType Μια συμβολοσειρά που έχει το ID και το Τύπο του αποστολέα. * @param command Μια συμβολοσειρά που έχει το όνομα της εντολής του μηνύματος. * @param parameters Μια λίστα μέσα σε μια λίστα από συμβολοσειρές που θα έχει μέσα όλους τους παραμέτρους του μηνύματος. * @return Επιστρέφετε μια συμβολοσειρά με όλο το μήνυμα σωστά συνταγμένο . */ public static String newMessage(String IDAndType,CommandType command,ArrayList<ArrayList<String>> parameters) { String message = "#"+ IDAndType + "$" + command.name() +":" + parameters.size() + "*" ; for (int i = 0 ; i<parameters.size();i++) { message +="(" ; if (parameters.get(i).size() > 0) message += parameters.get(i).get(0) ; for (int j = 1 ; j<parameters.get(i).size();j++) message += "|" + parameters.get(i).get(j) ; message +=")" ; } message +=";" ; return message ; } /** * Στατική μέθοδος που δημιουργεί με βάση κάποιους παραμέτρους ένα έγκυρο * μήνυμα χωρίς συντακτικά λάθη για να μπορεί να μεταφερθεί μέσα από socket . * @param IDAndType Μια συμβολοσειρά που έχει το ID και το Τύπο του αποστολέα. * @param command Μια συμβολοσειρά που έχει το όνομα της εντολής του μηνύματος. * @param sumOfParameters Πλήθος των παραμέτρων . * @param parameters Μια συμβολοσειρά με όλους τους παραμέτρους (Μαζί με παρενθέσεις και '|' όπου χρειάζεται) * @return Επιστρέφετε μια συμβολοσειρά με όλο το μήνυμα σωστά συνταγμένο . */ public static String newMessage(String IDAndType,CommandType command,int sumOfParameters,String parameters) { return "#"+ IDAndType + "$" + command.name() +":" + sumOfParameters + "*" + parameters + ";" ; } /** * Μέθοδος που φορτώνει μια συμβολοσειρά και (εφόσον είναι σύμφωνη με το πρωτόκολλο) * βρίσκει και διαχωρίζει όλα τα στοιχεία του μηνύματος , για να μπορούμε να παίρνουμε * στοχευμένα την πληροφορία που θέλουμε κάθε φορά. * @param mess Συμβολοσειρά που έχει ένα μήνυμα πρωτοκόλλου για επικοινωνία μέσα από socket. * @return True αν διαβαστεί κανονικά το μήνυμα και False αν δεν είναι σωστό το μήνυμα. */ public boolean reload(String mess) { correct = true ; message = mess ; try { strCommand = mess.substring(mess.indexOf("$")+1,mess.indexOf(":")) ; commandType = findCommandType(strCommand) ; intSumOfParameters = Integer.parseInt(mess.substring(mess.indexOf(":")+1,mess.indexOf("*"))) ; if (message.contains("@")) { strSenderType = mess.substring(mess.indexOf("@")+1,mess.indexOf("$")) ; strSenderDBID = mess.substring(mess.indexOf("#")+1,mess.indexOf("@")) ; } else { strSenderType = mess.substring(mess.indexOf("#")+1,mess.indexOf("$")) ; strSenderDBID = "-1" ; } alParameters = new ArrayList() ; int j ; for (int i = 0 ; i < intSumOfParameters;i++) { alParameters.add(new ArrayList()) ; String tmpString = mess.substring(mess.indexOf("(")+1,mess.indexOf(")")) ; j = 0 ; while (tmpString.contains("|")) { alParameters.get(i).add(tmpString.substring(0,tmpString.indexOf("|"))) ; tmpString = tmpString.substring(tmpString.indexOf("|")+1,tmpString.length()) ; } alParameters.get(i).add(tmpString) ; mess = mess.substring(mess.indexOf(")")+1,mess.length()) ; } } catch (Exception ex) { strCommand = "ERROR"; correct = false ; return false ; } return true ; } /** * Επιστρέφει την εντολή ενός μηνύματος . * @return Εντολή σε συμβολοσειρά */ public String getCommand() { return strCommand ; } /** * Επιστρέφει την εντολή ενός μηνύματος . * @return Εντολή σε {@link CommandType} */ public CommandType getCommandType() { return commandType; } /** * Επιστρέφει την εντολή ενός μηνύματος . * @return Εντολή σε συμβολοσειρά (παίρνοντας υπόψιν το {@link CommandType}) */ public String getCommandTypeStr() { return commandType.name() ; } /** * Επιστρέφει το πλήθος των παραμέτρων . * @return Πλήθος με int . */ public int getSumParameters() { return intSumOfParameters ; } /** * Επιστρέφει το τύπο του αποστολέα . * @return Συμβολοσειρά με το τύπο . */ public String getSenderType() { return strSenderType ; } /** * Επιστρέφει το ID που έχει στη βάση δεδομένων ο αποστολέας. * @return Σειμβολοσειρά με το ID της βάσης. */ public String getDBID() { return strSenderDBID ; } /** * Επιστρέφει μια λίστα που έχει λίστες από συμβολοσειρές με τους παραμέτρους. * @return Παράμετροι μέσα σε λίστα {@link ArrayList} που έχει λίστες από συμβολοσειρές */ public ArrayList<ArrayList<String>> getParameters() { return alParameters ; } /** * Επιστρέφει ατόφιο το μήνυμα όπως το διάβασε αρχικά η reload . * @return Συμβολοσειρά που έχει μέσα ατόφιο το αρχικό μήνυμα . */ public String getMessage() { return message ; } } /* * * * * * * * * * * * * * * * * * * * * * * * * + + + + + + + + + + + + + + + + + + + + + * * +- - - - - - - - - - - - - - - - - - - -+ * * +| P P P P M M M M G G G G |+ * * +| P P M M M M G G |+ * * +| P P P p M M M M G |+ * * +| P M M M G G G G |+ * * +| P M M G G |+ * * +| P ® M M ® G G G G |+ * * +- - - - - - - - - - - - - - - - - - - -+ * * + .----. @ @ |+ * * + / .-"-.`. \v/ |+ * * + | | '\ \ \_/ ) |+ * * + ,-\ `-.' /.' / |+ * * + '---`----'----' |+ * * +- - - - - - - - - - - - - - - - - - - -+ * * + + + + + + + + + + + + + + + + + + + + + * * +- - - - - - - - - - - - - - - - - - - -+ * * +| Thesis Michael Galliakis 2016 |+ * * +| Program m_g ; -) [email protected] |+ * * +| TEI Athens - IT department. |+ * * +| [email protected] |+ * * +| https://github.com/michaelgalliakis |+ * * +| (myThesis.git) |+ * * +- - - - - - - - - - - - - - - - - - - -+ * * + + + + + + + + + + + + + + + + + + + + + * * * * * * * * * * * * * * * * * * * * * * * * */
michaelgalliakis/myThesis
DeviceClientSimulatorV1/src/DeviceClientV1/ManageSocketMessage.java
4,409
/** * Επιστρέφει ατόφιο το μήνυμα όπως το διάβασε αρχικά η reload . * @return Συμβολοσειρά που έχει μέσα ατόφιο το αρχικό μήνυμα . */
block_comment
el
package DeviceClientV1 ; import java.util.ArrayList; /** * Κλάση που διαχειρίζεται εξ ολοκλήρου τα διάφορα μηνύματα που μεταφέρονται * μέσα από τα socket . * Δημιουργήθηκε ένα “πρωτόκολλο” επικοινωνίας για να γίνεται δομημένα και * αυτοματοποιημένα η επικοινωνία με τη χρήση των socket * Τα μηνύματα έχουν μια συγκεκριμένη μορφή : * #{SystemID}@{Τύπος Αποστολέα(S,D,UD)}${Εντολή}:{Πλήθος παραμέτρων}*{(Παράμετρος0.0)}{(Παράμετρος1.0|Παράμετρος1.1}); * @author Michael Galliakis */ public class ManageSocketMessage { CommandType commandType ; String strCommand ; int intSumOfParameters ; String strSenderType ; String strSenderDBID ; ArrayList<ArrayList<String>> alParameters ; String message ; boolean correct ; /** * Διάφοροι τύποι μηνυμάτων . */ enum CommandType{ Error ,Failed ,Login ,LoginReply ,certification ,GetDevicesInfo ,PutDevicesInfo ,BringMeDevice ,InitControllers ,NewController ,AlterController ,DeleteController ,NewValues ,InitializationFinished ,ChangeValues ,ChangeModes ,Anwser ,GetTypeUser ,PutTypeUser ,TSNC } /** * Μέθοδος που ψάχνει να βρει αν υπάρχει κάποιος τύπος. * @param comm λέξη κλειδί που θα αναζητηθεί . * @return Επιστρέφετε ο τύπος που βρέθηκε και αν δεν βρέθηκε επιστρέφετε το TSNC */ private CommandType findCommandType(String comm) { for (CommandType co : CommandType.values()) if (co.name().equals(comm)) return co ; return CommandType.TSNC ; } /** * Στατική μέθοδος που δημιουργεί με βάση κάποιους παραμέτρους ένα έγκυρο * μήνυμα χωρίς συντακτικά λάθη για να μπορεί να μεταφερθεί μέσα από socket . * @param IDAndType Μια συμβολοσειρά που έχει το ID και το Τύπο του αποστολέα. * @param command Μια συμβολοσειρά που έχει το όνομα της εντολής του μηνύματος. * @param parameters Ένας δισδιάστατος πίνακας που θα έχει μέσα όλους τους παραμέτρους του μηνύματος. * @return Επιστρέφετε μια συμβολοσειρά με όλο το μήνυμα σωστά συνταγμένο . */ public static String newMessage(String IDAndType,CommandType command,String[][] parameters) { String message = "#"+ IDAndType + "$" + command.name() +":" + parameters.length + "*" ; for (int i = 0 ; i<parameters.length;i++) { message +="(" ; if (parameters[i].length > 0) message += parameters[i][0] ; for (int j = 1 ; j<parameters[i].length;j++) message += "|" + parameters[i][j] ; message +=")" ; } message +=";" ; return message ; } /** * Στατική μέθοδος που δημιουργεί με βάση κάποιους παραμέτρους ένα έγκυρο * μήνυμα χωρίς συντακτικά λάθη για να μπορεί να μεταφερθεί μέσα από socket . * @param IDAndType Μια συμβολοσειρά που έχει το ID και το Τύπο του αποστολέα. * @param command Μια συμβολοσειρά που έχει το όνομα της εντολής του μηνύματος. * @param parameters Μια λίστα μέσα σε μια λίστα από συμβολοσειρές που θα έχει μέσα όλους τους παραμέτρους του μηνύματος. * @return Επιστρέφετε μια συμβολοσειρά με όλο το μήνυμα σωστά συνταγμένο . */ public static String newMessage(String IDAndType,CommandType command,ArrayList<ArrayList<String>> parameters) { String message = "#"+ IDAndType + "$" + command.name() +":" + parameters.size() + "*" ; for (int i = 0 ; i<parameters.size();i++) { message +="(" ; if (parameters.get(i).size() > 0) message += parameters.get(i).get(0) ; for (int j = 1 ; j<parameters.get(i).size();j++) message += "|" + parameters.get(i).get(j) ; message +=")" ; } message +=";" ; return message ; } /** * Στατική μέθοδος που δημιουργεί με βάση κάποιους παραμέτρους ένα έγκυρο * μήνυμα χωρίς συντακτικά λάθη για να μπορεί να μεταφερθεί μέσα από socket . * @param IDAndType Μια συμβολοσειρά που έχει το ID και το Τύπο του αποστολέα. * @param command Μια συμβολοσειρά που έχει το όνομα της εντολής του μηνύματος. * @param sumOfParameters Πλήθος των παραμέτρων . * @param parameters Μια συμβολοσειρά με όλους τους παραμέτρους (Μαζί με παρενθέσεις και '|' όπου χρειάζεται) * @return Επιστρέφετε μια συμβολοσειρά με όλο το μήνυμα σωστά συνταγμένο . */ public static String newMessage(String IDAndType,CommandType command,int sumOfParameters,String parameters) { return "#"+ IDAndType + "$" + command.name() +":" + sumOfParameters + "*" + parameters + ";" ; } /** * Μέθοδος που φορτώνει μια συμβολοσειρά και (εφόσον είναι σύμφωνη με το πρωτόκολλο) * βρίσκει και διαχωρίζει όλα τα στοιχεία του μηνύματος , για να μπορούμε να παίρνουμε * στοχευμένα την πληροφορία που θέλουμε κάθε φορά. * @param mess Συμβολοσειρά που έχει ένα μήνυμα πρωτοκόλλου για επικοινωνία μέσα από socket. * @return True αν διαβαστεί κανονικά το μήνυμα και False αν δεν είναι σωστό το μήνυμα. */ public boolean reload(String mess) { correct = true ; message = mess ; try { strCommand = mess.substring(mess.indexOf("$")+1,mess.indexOf(":")) ; commandType = findCommandType(strCommand) ; intSumOfParameters = Integer.parseInt(mess.substring(mess.indexOf(":")+1,mess.indexOf("*"))) ; if (message.contains("@")) { strSenderType = mess.substring(mess.indexOf("@")+1,mess.indexOf("$")) ; strSenderDBID = mess.substring(mess.indexOf("#")+1,mess.indexOf("@")) ; } else { strSenderType = mess.substring(mess.indexOf("#")+1,mess.indexOf("$")) ; strSenderDBID = "-1" ; } alParameters = new ArrayList() ; int j ; for (int i = 0 ; i < intSumOfParameters;i++) { alParameters.add(new ArrayList()) ; String tmpString = mess.substring(mess.indexOf("(")+1,mess.indexOf(")")) ; j = 0 ; while (tmpString.contains("|")) { alParameters.get(i).add(tmpString.substring(0,tmpString.indexOf("|"))) ; tmpString = tmpString.substring(tmpString.indexOf("|")+1,tmpString.length()) ; } alParameters.get(i).add(tmpString) ; mess = mess.substring(mess.indexOf(")")+1,mess.length()) ; } } catch (Exception ex) { strCommand = "ERROR"; correct = false ; return false ; } return true ; } /** * Επιστρέφει την εντολή ενός μηνύματος . * @return Εντολή σε συμβολοσειρά */ public String getCommand() { return strCommand ; } /** * Επιστρέφει την εντολή ενός μηνύματος . * @return Εντολή σε {@link CommandType} */ public CommandType getCommandType() { return commandType; } /** * Επιστρέφει την εντολή ενός μηνύματος . * @return Εντολή σε συμβολοσειρά (παίρνοντας υπόψιν το {@link CommandType}) */ public String getCommandTypeStr() { return commandType.name() ; } /** * Επιστρέφει το πλήθος των παραμέτρων . * @return Πλήθος με int . */ public int getSumParameters() { return intSumOfParameters ; } /** * Επιστρέφει το τύπο του αποστολέα . * @return Συμβολοσειρά με το τύπο . */ public String getSenderType() { return strSenderType ; } /** * Επιστρέφει το ID που έχει στη βάση δεδομένων ο αποστολέας. * @return Σειμβολοσειρά με το ID της βάσης. */ public String getDBID() { return strSenderDBID ; } /** * Επιστρέφει μια λίστα που έχει λίστες από συμβολοσειρές με τους παραμέτρους. * @return Παράμετροι μέσα σε λίστα {@link ArrayList} που έχει λίστες από συμβολοσειρές */ public ArrayList<ArrayList<String>> getParameters() { return alParameters ; } /** * Επιστρέφει ατόφιο το<SUF>*/ public String getMessage() { return message ; } } /* * * * * * * * * * * * * * * * * * * * * * * * * + + + + + + + + + + + + + + + + + + + + + * * +- - - - - - - - - - - - - - - - - - - -+ * * +| P P P P M M M M G G G G |+ * * +| P P M M M M G G |+ * * +| P P P p M M M M G |+ * * +| P M M M G G G G |+ * * +| P M M G G |+ * * +| P ® M M ® G G G G |+ * * +- - - - - - - - - - - - - - - - - - - -+ * * + .----. @ @ |+ * * + / .-"-.`. \v/ |+ * * + | | '\ \ \_/ ) |+ * * + ,-\ `-.' /.' / |+ * * + '---`----'----' |+ * * +- - - - - - - - - - - - - - - - - - - -+ * * + + + + + + + + + + + + + + + + + + + + + * * +- - - - - - - - - - - - - - - - - - - -+ * * +| Thesis Michael Galliakis 2016 |+ * * +| Program m_g ; -) [email protected] |+ * * +| TEI Athens - IT department. |+ * * +| [email protected] |+ * * +| https://github.com/michaelgalliakis |+ * * +| (myThesis.git) |+ * * +- - - - - - - - - - - - - - - - - - - -+ * * + + + + + + + + + + + + + + + + + + + + + * * * * * * * * * * * * * * * * * * * * * * * * */
7883_2
package manage; import entities.Prodcategory; import helpers.ConvertToGreeklish; import java.io.Serializable; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.context.FacesContext; import javax.validation.constraints.NotNull; import org.apache.log4j.Logger; import sessionsBeans.CategoryFacade; @ManagedBean @RequestScoped public class CategoryAddManage implements Serializable { final static Logger logger = Logger.getLogger(CategoryAddManage.class); @NotNull(message = "Συμπληρώστε το όνομα της κατηγορίας") private String name; private String isactive; private Prodcategory prodcategory; @EJB CategoryFacade categoryFacade; @PostConstruct void init() { if(logger.isDebugEnabled()){ logger.debug("Init Add category"); } } public String insertCategory() { Prodcategory category = new Prodcategory(); category.setName(name.trim()); //Convert checkbox value to int. True = 1 , False = 0 int isactiveInt; if (isactive.equals("true")) { isactiveInt = 1; } else { isactiveInt = 0; } category.setIsactive((short) isactiveInt); //String slug = name.replaceAll(" ", "-"); category.setSlugname(ConvertToGreeklish.greek2Roman(name)); System.out.println("Category: " + category); //mhnhmata από το magaebean στην σελίδα if (categoryFacade.insertCategoryToDB(category)) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Η κατηγορία δημιουργήθηκε επιτυχώς")); return "categoryAll"; } return ""; } public String getIsactive() { return isactive; } public void setIsactive(String isactive) { this.isactive = isactive; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Prodcategory getProdcategory() { return prodcategory; } public void setProdcategory(Prodcategory prodcategory) { this.prodcategory = prodcategory; } }
mixaverros88/dockerized-java-e-commerce-app
src/main/java/manage/CategoryAddManage.java
606
//mhnhmata από το magaebean στην σελίδα
line_comment
el
package manage; import entities.Prodcategory; import helpers.ConvertToGreeklish; import java.io.Serializable; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.context.FacesContext; import javax.validation.constraints.NotNull; import org.apache.log4j.Logger; import sessionsBeans.CategoryFacade; @ManagedBean @RequestScoped public class CategoryAddManage implements Serializable { final static Logger logger = Logger.getLogger(CategoryAddManage.class); @NotNull(message = "Συμπληρώστε το όνομα της κατηγορίας") private String name; private String isactive; private Prodcategory prodcategory; @EJB CategoryFacade categoryFacade; @PostConstruct void init() { if(logger.isDebugEnabled()){ logger.debug("Init Add category"); } } public String insertCategory() { Prodcategory category = new Prodcategory(); category.setName(name.trim()); //Convert checkbox value to int. True = 1 , False = 0 int isactiveInt; if (isactive.equals("true")) { isactiveInt = 1; } else { isactiveInt = 0; } category.setIsactive((short) isactiveInt); //String slug = name.replaceAll(" ", "-"); category.setSlugname(ConvertToGreeklish.greek2Roman(name)); System.out.println("Category: " + category); //mhnhmata από<SUF> if (categoryFacade.insertCategoryToDB(category)) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Η κατηγορία δημιουργήθηκε επιτυχώς")); return "categoryAll"; } return ""; } public String getIsactive() { return isactive; } public void setIsactive(String isactive) { this.isactive = isactive; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Prodcategory getProdcategory() { return prodcategory; } public void setProdcategory(Prodcategory prodcategory) { this.prodcategory = prodcategory; } }
16959_0
package comp18; import static org.junit.Assert.*; import java.io.IOException; //import org.junit.Before; import org.junit.Test; public class LempelZivTest { LempelZiv first = new LempelZiv("abcbababcbcabac"); LempelZiv second = new LempelZiv("Isto é um teste, muito legal este teste!"); LempelZiv third = new LempelZiv("ababa"); LempelZiv fourth = new LempelZiv("abababa"); LempelZiv fifth = new LempelZiv("ababababa"); LempelZiv sixth = new LempelZiv("abababababa"); LempelZiv seventh = new LempelZiv("ababababababa"); LempelZiv eighth = new LempelZiv("ababababababab"); LempelZiv ninth = new LempelZiv("Qualquer whatever da COMP ITA!"); LempelZiv tenth = new LempelZiv("Estamos usando o TDD para descobrir se este programa funciona."); LempelZiv eleventh = new LempelZiv ("Σημείωση: Το κείμενο έχει γραφεί σχεδόν χωρίς καθόλου τόνους, οπότε ο τονισμός είναι δικός μου. Αν θεωρείτε ότι η μουσικότητα του κειμένου έχει βλαφθεί, παρακαλώ τονίστε το αλλού. Οι αριθμοί των γραμμών δεν είναι πάντοτε στη σωστή σειρά τους πχ. 409, 618, και μερικές φορές αναγράφονται 2 σε μια γραμμή π.χ. 89-91. Προφανώς ο μεταφραστής έχει ανακατατάξει τις γραμμές του πρωτοτύπου. Η Ραψωδία Ν (η μάχη στα πλοία) δεν έχει μεταφραστεί."); LempelZiv clean = new LempelZiv(); @Test public void TestReadFile() throws IOException{ try{ clean.addFileToEncode("testeIn.txt"); //clean.decode(); assertEquals("Isto é um teste para abrir arquivos.\n\n\"Σημείωση: Το κείμενο έχει γραφεί σχεδόν χωρίς καθόλου τόνους, οπότε ο τονισμός είναι δικός μου. Αν θεωρείτε ότι η μουσικότητα του κειμένου έχει βλαφθεί, παρακαλώ τονίστε το αλλού. Οι αριθμοί των γραμμών δεν είναι πάντοτε στη σωστή σειρά τους πχ. 409, 618, και μερικές φορές αναγράφονται 2 σε μια γραμμή π.χ. 89-91. Προφανώς ο μεταφραστής έχει ανακατατάξει τις γραμμές του πρωτοτύπου. Η Ραψωδία Ν (η μάχη στα πλοία) δεν έχει μεταφραστεί.\");\n",clean.inputString()); }catch(IOException e){ e.printStackTrace(); } } @Test public void TestReadFileToEncode() throws IOException{ try{ clean.addFileToEncode("testeIn.txt"); //System.out.println("String padrao:"); //System.out.println(clean.toEncodedString()); clean.decode(); assertEquals("Isto é um teste para abrir arquivos.\n\n\"Σημείωση: Το κείμενο έχει γραφεί σχεδόν χωρίς καθόλου τόνους, οπότε ο τονισμός είναι δικός μου. Αν θεωρείτε ότι η μουσικότητα του κειμένου έχει βλαφθεί, παρακαλώ τονίστε το αλλού. Οι αριθμοί των γραμμών δεν είναι πάντοτε στη σωστή σειρά τους πχ. 409, 618, και μερικές φορές αναγράφονται 2 σε μια γραμμή π.χ. 89-91. Προφανώς ο μεταφραστής έχει ανακατατάξει τις γραμμές του πρωτοτύπου. Η Ραψωδία Ν (η μάχη στα πλοία) δεν έχει μεταφραστεί.\");\n",clean.toDecodedString()); }catch(IOException e){ e.printStackTrace(); } } @Test public void TestReadFileToByte() throws IOException{ try{ clean.addFileToEncode("testeIn.txt"); clean.toByte(); //clean.printBytes(); clean.saveByteFile("testeOut.dat"); //assertEquals("Isto é um teste para abrir arquivos.\n\n\"Σημείωση: Το κείμενο έχει γραφεί σχεδόν χωρίς καθόλου τόνους, οπότε ο τονισμός είναι δικός μου. Αν θεωρείτε ότι η μουσικότητα του κειμένου έχει βλαφθεί, παρακαλώ τονίστε το αλλού. Οι αριθμοί των γραμμών δεν είναι πάντοτε στη σωστή σειρά τους πχ. 409, 618, και μερικές φορές αναγράφονται 2 σε μια γραμμή π.χ. 89-91. Προφανώς ο μεταφραστής έχει ανακατατάξει τις γραμμές του πρωτοτύπου. Η Ραψωδία Ν (η μάχη στα πλοία) δεν έχει μεταφραστεί.\");\n",clean.toDecodedString()); }catch(IOException e){ e.printStackTrace(); } } @Test public void TestReadFromByteFile() throws IOException{ try{ clean.addFileToDecode("testeOut.dat"); //clean.printBytes(); }catch(IOException e){ e.printStackTrace(); } } /* @Test public void TestDecodingMiddleString() throws IOException{ try{ clean.addFileToDecode("testeOut.dat"); //clean.printBytes(); clean.fromByte(); String out = clean.toEncodedString(); System.out.println(out); //clean.decode(); assertEquals("Isto éumeparbiqv.\n\"Σημείωσ:Τοκνέχιγραφδόςθλυτ,πΑβώύΟάή4096182-ΠξΗΡψΝ();0000001000001000000110000100000010100001100000101000011100010000000101000001100010011001001000100100001010001010000101100011000001011000010100010110001101000110000011100001100101101100011000001111u0001110001000000001000000010001000100100100010010001001100101000010101001011000101110011000001100100110100010101001101100001010011100001110100001010011110101001110100100011111101101101000000100001ε0100010000010101000110100100010010101001100010111001100000001010011010010000100101110100111010100000111110000101010000100110010100100001100001010010000101001111001001010101010010100001010110011101υ0000101010110101010000011111001110101011000101001010111000001010011101010111101010000101101001011110100001001000001110100111110100010001101000101100101000010100100001010010111001100000111110100101ι000010101001110100010001111001010000101001000010100101100011101010110000100010000101011000000111110000101010101000101110011001010010000101110011000010110100101110000101010100001011010100100000101η0000101001011000111010101100001101001000100011110010100001011010010101010110101001010000101010110110010100000101001111000101110100010001011001000000011111101011001000000100001101100100001010110001λ0100101010011001010100010111001100001011100000101010111101001010100100010010100111100100101010101101100100000101010110100111010011111001100000110100101101001011110101110011101000010110101000101011ο0110011001000100001010000101011010001000100000101010010101001000100010010101000101100011101001100000001010101101001100100111110000101010001101001000100101001011000101100110010101100101001110010111ν0000101001011100110000011111010010101000100000101010111101101010011111010110100111010101101001011100001010011010010110100101011010110001100110101110110110101011000101110100010010010001101010000101τ0011101010110001010010000101010111101000010010001000010101101110111000011100101011100000101011101001110110111100101001100111100100101010001000001010010110001011101001000100010001111001000001001010φ001110101001000100000010100000010101001010011111010010101000110100100011010101001100011101001111101011010100101010001000001010111101000010100110100010111000010100101100100010010010100001011010000α0010110001011001101100000101010111100100010100001001000100001010111100011100101111100111001011101110011110111111010010000111010100110010010100111110110010010100100001010011101000010100101100010111τ0100101010011001001000100101001101001011010110110010100100001010100000010000100101110100010000010101001010011111010010100111100100101010110110110100110101100000010100110000101010110101000101001111γ0100100010010100101100010110010000001010010000101010110100111010101100000010101011110100100001100110011110101101011001101011111010000001000100001011000001000010110000100100101100001100110010100111ί0100101000010110001000000101100010100101010000101001011001101010100001100110100110100101101100100001011110101011001110100110000100101100011000001010100111001011100111110000101010000001000010010111ι000010100101100010111010110101001010100110010010001001010011010010101001011100110000010001001001110001101000111\n",out); }catch(IOException e){ e.printStackTrace(); } }*/ @Test public void TestDecoding() throws IOException{ try{ clean.addFileToDecode("testeOut.dat"); //clean.printBytes(); clean.fromByte(); //System.out.println(clean.toEncodedString()); clean.decode(); assertEquals("Isto é um teste para abrir arquivos.\n\n\"Σημείωση: Το κείμενο έχει γραφεί σχεδόν χωρίς καθόλου τόνους, οπότε ο τονισμός είναι δικός μου. Αν θεωρείτε ότι η μουσικότητα του κειμένου έχει βλαφθεί, παρακαλώ τονίστε το αλλού. Οι αριθμοί των γραμμών δεν είναι πάντοτε στη σωστή σειρά τους πχ. 409, 618, και μερικές φορές αναγράφονται 2 σε μια γραμμή π.χ. 89-91. Προφανώς ο μεταφραστής έχει ανακατατάξει τις γραμμές του πρωτοτύπου. Η Ραψωδία Ν (η μάχη στα πλοία) δεν έχει μεταφραστεί.\");\n",clean.toDecodedString()); clean.decodeFile("testeOutput.txt"); }catch(IOException e){ e.printStackTrace(); } } @Test public void EncryptTrial() { //first.toByte(); //first.printBytes(); assertEquals("abc010100110101000100011000111000c",first.toEncodedString()); } @Test public void DecryptTrial() { first.decode(); assertEquals("abcbababcbcabac",first.toDecodedString()); } @Test public void DecryptTrial2() { second.decode(); //System.out.println(second.toEncodedString()); assertEquals("Isto é um teste, muito legal este teste!",second.toDecodedString()); } @Test public void DecryptTrial3() { third.decode(); assertEquals("ababa",third.toDecodedString()); } @Test public void DecryptTrial4() { fourth.decode(); assertEquals("abababa",fourth.toDecodedString()); } @Test public void DecryptTrial5() { fifth.decode(); assertEquals("ababababa",fifth.toDecodedString()); } @Test public void DecryptTrial6() { sixth.decode(); assertEquals("abababababa",sixth.toDecodedString()); } @Test public void DecryptTrial7() { seventh.decode(); assertEquals("ababababababa",seventh.toDecodedString()); } @Test public void DecryptTrial8() { eighth.decode(); assertEquals("ababababababab",eighth.toDecodedString()); } @Test public void DecryptTrial9() { ninth.decode(); assertEquals("Qualquer whatever da COMP ITA!",ninth.toDecodedString()); } @Test public void DecryptTrial10() { tenth.decode(); assertEquals("Estamos usando o TDD para descobrir se este programa funciona.",tenth.toDecodedString()); } @Test public void DecryptTrial11(){ eleventh.decode(); assertEquals("Σημείωση: Το κείμενο έχει γραφεί σχεδόν χωρίς καθόλου τόνους, οπότε ο τονισμός είναι δικός μου. Αν θεωρείτε ότι η μουσικότητα του κειμένου έχει βλαφθεί, παρακαλώ τονίστε το αλλού. Οι αριθμοί των γραμμών δεν είναι πάντοτε στη σωστή σειρά τους πχ. 409, 618, και μερικές φορές αναγράφονται 2 σε μια γραμμή π.χ. 89-91. Προφανώς ο μεταφραστής έχει ανακατατάξει τις γραμμές του πρωτοτύπου. Η Ραψωδία Ν (η μάχη στα πλοία) δεν έχει μεταφραστεί.",eleventh.toDecodedString()); } @Test public void TestGetB(){ assertEquals(2,first.getB(3)); assertEquals(2,first.getB(4)); assertEquals(3,first.getB(5)); assertEquals(3,first.getB(8)); assertEquals(4,first.getB(9)); assertEquals(8,first.getB(255)); assertEquals(10,first.getB(1024)); } @Test public void TestDir(){ assertEquals(13,first.dicIn.size()); } @Test public void isAtDir(){ assertTrue(first.isAtDir("a")); assertTrue(first.isAtDir("b")); assertTrue(first.isAtDir("c")); assertFalse(first.isAtDir("d")); } }
mknarciso/ita-ele32-lab2
src/test/java/comp18/LempelZivTest.java
7,101
//assertEquals("Isto é um teste para abrir arquivos.\n\n\"Σημείωση: Το κείμενο έχει γραφεί σχεδόν χωρίς καθόλου τόνους, οπότε ο τονισμός είναι δικός μου. Αν θεωρείτε ότι η μουσικότητα του κειμένου έχει βλαφθεί, παρακαλώ τονίστε το αλλού. Οι αριθμοί των γραμμών δεν είναι πάντοτε στη σωστή σειρά τους πχ. 409, 618, και μερικές φορές αναγράφονται 2 σε μια γραμμή π.χ. 89-91. Προφανώς ο μεταφραστής έχει ανακατατάξει τις γραμμές του πρωτοτύπου. Η Ραψωδία Ν (η μάχη στα πλοία) δεν έχει μεταφραστεί.\");\n",clean.toDecodedString());
line_comment
el
package comp18; import static org.junit.Assert.*; import java.io.IOException; //import org.junit.Before; import org.junit.Test; public class LempelZivTest { LempelZiv first = new LempelZiv("abcbababcbcabac"); LempelZiv second = new LempelZiv("Isto é um teste, muito legal este teste!"); LempelZiv third = new LempelZiv("ababa"); LempelZiv fourth = new LempelZiv("abababa"); LempelZiv fifth = new LempelZiv("ababababa"); LempelZiv sixth = new LempelZiv("abababababa"); LempelZiv seventh = new LempelZiv("ababababababa"); LempelZiv eighth = new LempelZiv("ababababababab"); LempelZiv ninth = new LempelZiv("Qualquer whatever da COMP ITA!"); LempelZiv tenth = new LempelZiv("Estamos usando o TDD para descobrir se este programa funciona."); LempelZiv eleventh = new LempelZiv ("Σημείωση: Το κείμενο έχει γραφεί σχεδόν χωρίς καθόλου τόνους, οπότε ο τονισμός είναι δικός μου. Αν θεωρείτε ότι η μουσικότητα του κειμένου έχει βλαφθεί, παρακαλώ τονίστε το αλλού. Οι αριθμοί των γραμμών δεν είναι πάντοτε στη σωστή σειρά τους πχ. 409, 618, και μερικές φορές αναγράφονται 2 σε μια γραμμή π.χ. 89-91. Προφανώς ο μεταφραστής έχει ανακατατάξει τις γραμμές του πρωτοτύπου. Η Ραψωδία Ν (η μάχη στα πλοία) δεν έχει μεταφραστεί."); LempelZiv clean = new LempelZiv(); @Test public void TestReadFile() throws IOException{ try{ clean.addFileToEncode("testeIn.txt"); //clean.decode(); assertEquals("Isto é um teste para abrir arquivos.\n\n\"Σημείωση: Το κείμενο έχει γραφεί σχεδόν χωρίς καθόλου τόνους, οπότε ο τονισμός είναι δικός μου. Αν θεωρείτε ότι η μουσικότητα του κειμένου έχει βλαφθεί, παρακαλώ τονίστε το αλλού. Οι αριθμοί των γραμμών δεν είναι πάντοτε στη σωστή σειρά τους πχ. 409, 618, και μερικές φορές αναγράφονται 2 σε μια γραμμή π.χ. 89-91. Προφανώς ο μεταφραστής έχει ανακατατάξει τις γραμμές του πρωτοτύπου. Η Ραψωδία Ν (η μάχη στα πλοία) δεν έχει μεταφραστεί.\");\n",clean.inputString()); }catch(IOException e){ e.printStackTrace(); } } @Test public void TestReadFileToEncode() throws IOException{ try{ clean.addFileToEncode("testeIn.txt"); //System.out.println("String padrao:"); //System.out.println(clean.toEncodedString()); clean.decode(); assertEquals("Isto é um teste para abrir arquivos.\n\n\"Σημείωση: Το κείμενο έχει γραφεί σχεδόν χωρίς καθόλου τόνους, οπότε ο τονισμός είναι δικός μου. Αν θεωρείτε ότι η μουσικότητα του κειμένου έχει βλαφθεί, παρακαλώ τονίστε το αλλού. Οι αριθμοί των γραμμών δεν είναι πάντοτε στη σωστή σειρά τους πχ. 409, 618, και μερικές φορές αναγράφονται 2 σε μια γραμμή π.χ. 89-91. Προφανώς ο μεταφραστής έχει ανακατατάξει τις γραμμές του πρωτοτύπου. Η Ραψωδία Ν (η μάχη στα πλοία) δεν έχει μεταφραστεί.\");\n",clean.toDecodedString()); }catch(IOException e){ e.printStackTrace(); } } @Test public void TestReadFileToByte() throws IOException{ try{ clean.addFileToEncode("testeIn.txt"); clean.toByte(); //clean.printBytes(); clean.saveByteFile("testeOut.dat"); //assertEquals("Isto é<SUF> }catch(IOException e){ e.printStackTrace(); } } @Test public void TestReadFromByteFile() throws IOException{ try{ clean.addFileToDecode("testeOut.dat"); //clean.printBytes(); }catch(IOException e){ e.printStackTrace(); } } /* @Test public void TestDecodingMiddleString() throws IOException{ try{ clean.addFileToDecode("testeOut.dat"); //clean.printBytes(); clean.fromByte(); String out = clean.toEncodedString(); System.out.println(out); //clean.decode(); assertEquals("Isto éumeparbiqv.\n\"Σημείωσ:Τοκνέχιγραφδόςθλυτ,πΑβώύΟάή4096182-ΠξΗΡψΝ();0000001000001000000110000100000010100001100000101000011100010000000101000001100010011001001000100100001010001010000101100011000001011000010100010110001101000110000011100001100101101100011000001111u0001110001000000001000000010001000100100100010010001001100101000010101001011000101110011000001100100110100010101001101100001010011100001110100001010011110101001110100100011111101101101000000100001ε0100010000010101000110100100010010101001100010111001100000001010011010010000100101110100111010100000111110000101010000100110010100100001100001010010000101001111001001010101010010100001010110011101υ0000101010110101010000011111001110101011000101001010111000001010011101010111101010000101101001011110100001001000001110100111110100010001101000101100101000010100100001010010111001100000111110100101ι000010101001110100010001111001010000101001000010100101100011101010110000100010000101011000000111110000101010101000101110011001010010000101110011000010110100101110000101010100001011010100100000101η0000101001011000111010101100001101001000100011110010100001011010010101010110101001010000101010110110010100000101001111000101110100010001011001000000011111101011001000000100001101100100001010110001λ0100101010011001010100010111001100001011100000101010111101001010100100010010100111100100101010101101100100000101010110100111010011111001100000110100101101001011110101110011101000010110101000101011ο0110011001000100001010000101011010001000100000101010010101001000100010010101000101100011101001100000001010101101001100100111110000101010001101001000100101001011000101100110010101100101001110010111ν0000101001011100110000011111010010101000100000101010111101101010011111010110100111010101101001011100001010011010010110100101011010110001100110101110110110101011000101110100010010010001101010000101τ0011101010110001010010000101010111101000010010001000010101101110111000011100101011100000101011101001110110111100101001100111100100101010001000001010010110001011101001000100010001111001000001001010φ001110101001000100000010100000010101001010011111010010101000110100100011010101001100011101001111101011010100101010001000001010111101000010100110100010111000010100101100100010010010100001011010000α0010110001011001101100000101010111100100010100001001000100001010111100011100101111100111001011101110011110111111010010000111010100110010010100111110110010010100100001010011101000010100101100010111τ0100101010011001001000100101001101001011010110110010100100001010100000010000100101110100010000010101001010011111010010100111100100101010110110110100110101100000010100110000101010110101000101001111γ0100100010010100101100010110010000001010010000101010110100111010101100000010101011110100100001100110011110101101011001101011111010000001000100001011000001000010110000100100101100001100110010100111ί0100101000010110001000000101100010100101010000101001011001101010100001100110100110100101101100100001011110101011001110100110000100101100011000001010100111001011100111110000101010000001000010010111ι000010100101100010111010110101001010100110010010001001010011010010101001011100110000010001001001110001101000111\n",out); }catch(IOException e){ e.printStackTrace(); } }*/ @Test public void TestDecoding() throws IOException{ try{ clean.addFileToDecode("testeOut.dat"); //clean.printBytes(); clean.fromByte(); //System.out.println(clean.toEncodedString()); clean.decode(); assertEquals("Isto é um teste para abrir arquivos.\n\n\"Σημείωση: Το κείμενο έχει γραφεί σχεδόν χωρίς καθόλου τόνους, οπότε ο τονισμός είναι δικός μου. Αν θεωρείτε ότι η μουσικότητα του κειμένου έχει βλαφθεί, παρακαλώ τονίστε το αλλού. Οι αριθμοί των γραμμών δεν είναι πάντοτε στη σωστή σειρά τους πχ. 409, 618, και μερικές φορές αναγράφονται 2 σε μια γραμμή π.χ. 89-91. Προφανώς ο μεταφραστής έχει ανακατατάξει τις γραμμές του πρωτοτύπου. Η Ραψωδία Ν (η μάχη στα πλοία) δεν έχει μεταφραστεί.\");\n",clean.toDecodedString()); clean.decodeFile("testeOutput.txt"); }catch(IOException e){ e.printStackTrace(); } } @Test public void EncryptTrial() { //first.toByte(); //first.printBytes(); assertEquals("abc010100110101000100011000111000c",first.toEncodedString()); } @Test public void DecryptTrial() { first.decode(); assertEquals("abcbababcbcabac",first.toDecodedString()); } @Test public void DecryptTrial2() { second.decode(); //System.out.println(second.toEncodedString()); assertEquals("Isto é um teste, muito legal este teste!",second.toDecodedString()); } @Test public void DecryptTrial3() { third.decode(); assertEquals("ababa",third.toDecodedString()); } @Test public void DecryptTrial4() { fourth.decode(); assertEquals("abababa",fourth.toDecodedString()); } @Test public void DecryptTrial5() { fifth.decode(); assertEquals("ababababa",fifth.toDecodedString()); } @Test public void DecryptTrial6() { sixth.decode(); assertEquals("abababababa",sixth.toDecodedString()); } @Test public void DecryptTrial7() { seventh.decode(); assertEquals("ababababababa",seventh.toDecodedString()); } @Test public void DecryptTrial8() { eighth.decode(); assertEquals("ababababababab",eighth.toDecodedString()); } @Test public void DecryptTrial9() { ninth.decode(); assertEquals("Qualquer whatever da COMP ITA!",ninth.toDecodedString()); } @Test public void DecryptTrial10() { tenth.decode(); assertEquals("Estamos usando o TDD para descobrir se este programa funciona.",tenth.toDecodedString()); } @Test public void DecryptTrial11(){ eleventh.decode(); assertEquals("Σημείωση: Το κείμενο έχει γραφεί σχεδόν χωρίς καθόλου τόνους, οπότε ο τονισμός είναι δικός μου. Αν θεωρείτε ότι η μουσικότητα του κειμένου έχει βλαφθεί, παρακαλώ τονίστε το αλλού. Οι αριθμοί των γραμμών δεν είναι πάντοτε στη σωστή σειρά τους πχ. 409, 618, και μερικές φορές αναγράφονται 2 σε μια γραμμή π.χ. 89-91. Προφανώς ο μεταφραστής έχει ανακατατάξει τις γραμμές του πρωτοτύπου. Η Ραψωδία Ν (η μάχη στα πλοία) δεν έχει μεταφραστεί.",eleventh.toDecodedString()); } @Test public void TestGetB(){ assertEquals(2,first.getB(3)); assertEquals(2,first.getB(4)); assertEquals(3,first.getB(5)); assertEquals(3,first.getB(8)); assertEquals(4,first.getB(9)); assertEquals(8,first.getB(255)); assertEquals(10,first.getB(1024)); } @Test public void TestDir(){ assertEquals(13,first.dicIn.size()); } @Test public void isAtDir(){ assertTrue(first.isAtDir("a")); assertTrue(first.isAtDir("b")); assertTrue(first.isAtDir("c")); assertFalse(first.isAtDir("d")); } }
4247_0
/* Ομάδα Χρηστών 55 * Συγγραφείς: ΜΑΡΙΑ ΚΟΝΤΑΡΑΤΟΥ(3200078) ΓΕΩΡΓΙΟΣ ΚΟΥΜΟΥΝΔΟΥΡΟΣ(3200083) ΠΑΝΑΓΙΩΤΗΣ ΚΩΝΣΤΑΝΤΙΝΑΚΟΣ(3200089) */ import java.util.ArrayList; import java.util.Scanner; public class mainApp { public static void main(String[] args){ //arxikopoihsh timwn se Eurw gia ta statistika xrhshs(SMS, lepta omilias, MB) ana 1 double ConSMSCost = 0.1; double ConOmiliaCost = 0.2; double CaSMSCost = 0.05; double CaOmiliaCost = 0.3; double MBCost = 0.2; // zhtoumeno c stats stat = new stats(); ArrayList<Services> yphresies = new ArrayList<Services>(); yphresies.add(new symvolaio("Contract",7,20,100,150,15)); yphresies.add(new symvolaio("Contract",7,30,150,150,8)); yphresies.add(new kartosymvolaio("Card",8, 600, 50,5,10,13)); yphresies.add(new kartosymvolaio("Card",8, 450, 80,10,5,18)); yphresies.add(new mobInternet("Mobile Internet", 10,300,6)); yphresies.add(new mobInternet("Mobile Internet", 10,150,4)); //ArrayList<contract> symvolaia = new ArrayList<contract>(); contract c1 =new contract("Maria", "Kontaratou","690000000","26/02/21","cash",0.4, yphresies.get(0)); stat.addContract(c1); contract c2 = new contract("Panagioths", "Kwnstantinakos","690000001","13/02/20","card",0.45,yphresies.get(1)); stat.addContract(c2); contract c3 =new contract("Giwrgos", "Koumoundouros","690000002","30/06/20","cash",0.2, yphresies.get(2)); stat.addContract(c3); contract c4 =new contract("Nikolas", "Papadopoulos","690000003","16/01/21","cash",0.15, yphresies.get(3)); stat.addContract(c4); contract c5 =new contract("Aggelikh", "Merkourh","690000004","26/03/21","cash",0.15, yphresies.get(4)); stat.addContract(c5); contract c6 =new contract("Kwnstantina", "Papaiwannou","690000005","23/08/20","cash",0.15, yphresies.get(5)); stat.addContract(c6); Scanner s = new Scanner(System.in); int i = 6; boolean not=true; while(not) { System.out.println("\n-------------------------------------------------------------------------------"); System.out.println("1. Print available services "); System.out.println("2. Create new contract "); System.out.println("3. Print active contracts for a specific type of service "); System.out.println("4. Update statistics of usage of a contract"); System.out.println("5. Calculate total monthly cost and monthly available remaining money" ); System.out.println("6. Calculate free talk time and free SMS or free MB or remaining money"); System.out.println("7. Exit"); System.out.println("-------------------------------------------------------------------------------\n"); System.out.print("> "); int x = s.nextInt(); switch(x) { case 1: System.out.println("1.Services of mobile telephony (Contract programs or card contract programs)"); System.out.println("2.Services mobile- Internet"); break; case 2: System.out.println("Create new contract: 1. Contract program 2. card contract program 3. Program mobile-Internet "); int y = s.nextInt(); String name1,surname,phone,date,payment, theName,theSurname,ctype; double pagio1,ekptwsi1,miniaioYpoloipo1,sale,avmon; int freeOmilia1,freeSMS1,xreosiOmilia1,xreosiSMS1,freeMB1,xreosiMB1; switch (y) { case 1: System.out.println("Create contract program"); System.out.println("Name: "); s.nextLine(); name1=s.nextLine(); System.out.println("Surname: "); surname = s.nextLine(); System.out.println("Phone: "); phone = s.nextLine(); System.out.println("Starting date of contract: "); date = s.nextLine(); System.out.println("Payment method: "); payment = s.nextLine(); System.out.println("Contract sale: 20% "); System.out.println("Extra sale of contract: "); sale = s.nextDouble(); System.out.println("Fixed cost of contract: 7"); pagio1=7; System.out.println("Free talk time to mobile phones and stable networks: "); freeOmilia1=s.nextInt(); System.out.println("Free SMS: "); freeSMS1=s.nextInt(); System.out.println("Charge for talk time to mobile phones and stable networks after the free talk time: "); xreosiOmilia1=s.nextInt(); System.out.println("Charge for SMS after the free SMS: "); xreosiSMS1=s.nextInt(); ctype = "Contract"; yphresies.add(new symvolaio(ctype,pagio1,freeOmilia1,freeSMS1,xreosiOmilia1,xreosiSMS1)); contract ob1 = new contract(name1,surname,phone,date,payment,sale,yphresies.get(i)); i+=1; stat.addContract(ob1); break; case 2: System.out.println("Create card contract program"); System.out.println("Name: "); s.nextLine(); name1=s.nextLine(); System.out.println("Surname: "); surname = s.nextLine(); System.out.println("Phone: "); phone = s.nextLine(); System.out.println("Starting date of contract: "); date = s.nextLine(); System.out.println("Payment method: "); payment = s.nextLine(); System.out.println("Sale of program 25% "); System.out.println("Extra sale of contract: "); sale =s.nextDouble(); System.out.println("Fixed cost of program: 8"); pagio1= 8 ; System.out.println("Free talk time to mobile phones and stable networks: "); freeOmilia1=s.nextInt(); System.out.println("Free SMS: "); freeSMS1=s.nextInt(); System.out.println("Charge for talk time to mobile phones and stable networks after the free talk time: "); xreosiOmilia1=s.nextInt(); System.out.println("Charge for SMS after the free SMS: "); xreosiSMS1=s.nextInt(); System.out.println("Monthly available remaining money: "); avmon = s.nextDouble(); ctype = "Card"; yphresies.add(new kartosymvolaio(ctype,pagio1,freeOmilia1,freeSMS1,xreosiOmilia1,xreosiSMS1,avmon)); contract ob2 = new contract(name1,surname,phone,date,payment,sale,yphresies.get(i)); i+=1; stat.addContract(ob2); break; case 3: System.out.println("Create program mobile-Internet"); System.out.println("Name: "); s.nextLine(); name1=s.nextLine(); System.out.println("Surname: "); surname = s.nextLine(); System.out.println("Phone: "); phone = s.nextLine(); System.out.println("Starting date of contract: "); date = s.nextLine(); System.out.println("Payment method: "); payment = s.nextLine(); System.out.println("Sale of program: 30% "); System.out.println("Extra sale of contract: "); sale =s.nextDouble(); System.out.println("Fixed cost of program: 10 "); pagio1=10; System.out.println("Free MB: "); freeMB1=s.nextInt(); System.out.println("Charge for MB after the free MB: "); xreosiMB1=s.nextInt(); ctype = "Mobile Internet"; yphresies.add(new mobInternet(ctype,pagio1,freeMB1,xreosiMB1)); contract ob3 = new contract(name1,surname,phone,date,payment,sale,yphresies.get(i)); i+=1; stat.addContract(ob3); break; } break; case 3: System.out.println("Print active contracts for a specific type of service"); System.out.println("Choose type of contract: 1. Contract program 2. Card contract program 3. Program mobile-Internet "); int z = s.nextInt(); int id2 = 0; switch (z) { case 1: for (Services service: yphresies){ if(service instanceof symvolaio){ id2= service.getId(); stat.findContract(id2); } } break; case 2: for (Services service: yphresies){ if(service instanceof kartosymvolaio) id2= service.getId(); stat.findContract(id2); } break; case 3: for (Services service: yphresies){ if(service instanceof mobInternet) id2= service.getId(); stat.findContract(id2); } break; } break; case 4: System.out.println("Update statistics of usage of a contract"); System.out.println("Choose type of contract: 1. Contract program 2. Card contract program 3. Program mobile-Internet "); int k = s.nextInt(); int CfreeOmilia1,CfreeSMS1,CxreosiOmilia1,CxreosiSMS1,type, CfreeMB, CxreosiMB,cid; double Cavmon; String cname,csurname; switch(k) { case 1: System.out.println("Write the contract's name holder: "); s.nextLine(); cname = s.nextLine(); System.out.println("Write the contract's surname holder: "); csurname=s.nextLine(); cid = stat.checkName(cname,csurname ); if (cid!=-1){ System.out.println("Change your contract's stats"); System.out.println("Free talk time to mobile phones and stable networks: "); CfreeOmilia1=s.nextInt(); System.out.println("Free SMS: "); CfreeSMS1=s.nextInt(); System.out.println("Charge for talk time to mobile phones and stable networks after the free talk time: "); CxreosiOmilia1=s.nextInt(); System.out.println("Charge for SMS after the free SMS: "); CxreosiSMS1=s.nextInt(); type = 1; for (Services s1: yphresies){ if ( s1.getOnoma().equals("Contract")){ if (s1.getId() == cid ){ stat.changeStats(cid, CfreeOmilia1, CfreeSMS1, CxreosiOmilia1, CxreosiSMS1,0,0,0, s1, type); } } } } break; case 2: System.out.println("Write the contract's name holder: "); s.nextLine(); cname = s.nextLine(); System.out.println("Write the contract's surname holder: "); csurname=s.nextLine(); cid = stat.checkName(cname,csurname ); if (cid!=-1){ System.out.println("Change your contract's stats"); System.out.println("Free talk time to mobile phones and stable networks: "); CfreeOmilia1=s.nextInt(); System.out.println("Free SMS: "); CfreeSMS1=s.nextInt(); System.out.println("Charge for talk time to mobile phones and stable networks after the free talk time: "); CxreosiOmilia1=s.nextInt(); System.out.println("Charge for SMS after the free SMS: "); CxreosiSMS1=s.nextInt(); System.out.println("Monthly available remaining money: "); Cavmon = s.nextDouble(); type = 2; for (Services s1: yphresies){ if ( s1.getOnoma().equals("Card")){ if (s1.getId() == cid){ stat.changeStats(cid, CfreeOmilia1, CfreeSMS1, CxreosiOmilia1, CxreosiSMS1,0,0,Cavmon, s1, type); } } } } break; case 3: System.out.println("Write the contract's name holder: "); s.nextLine(); cname = s.nextLine(); System.out.println("Write the contract's surname holder: "); csurname=s.nextLine(); cid = stat.checkName(cname,csurname ); if (cid!=-1){ System.out.println("Change your contract's stats"); System.out.println("Free MB: "); CfreeMB=s.nextInt(); System.out.println("Charge for MB after the free MB: "); CxreosiMB=s.nextInt(); type = 3; for (Services s1: yphresies){ if ( s1.getOnoma().equals("Mobile Internet")){ if (s1.getId() == cid){ stat.changeStats(cid,0, 0, 0, 0,CfreeMB, CxreosiMB,0, s1, type); } } } } break; } break; case 5: System.out.println("Calculate total monthly cost and monthly available remaining money" ); System.out.println("Choose type of contract: 1. Contract program 2. Card contract program 3. Program mobile-Internet "); int m = s.nextInt(); double es = 0; double totalcost = 0; double x1=0, x2=0; switch(m) { case 1: for (Services service: yphresies){ if(service instanceof symvolaio){ id2= service.getId(); es = stat.returnSale(id2); x1 = service.getXreosiSMS(); x2 = service.getXreosiOmilia(); totalcost = service.getPagio()+ x1*ConOmiliaCost + x2*ConSMSCost - (service.getPagio()+ x1*ConOmiliaCost + x2*ConSMSCost )*20/100 - es; System.out.println("Name and surname: " +stat.NameAndSurname(id2)+ "\nMonthly cost: "+ String.format("%.2f",totalcost)); } } break; case 2: for (Services service: yphresies){ if(service instanceof kartosymvolaio){ id2= service.getId(); es = stat.returnSale(id2); x1 = service.getXreosiSMS(); x2 = service.getXreosiOmilia(); totalcost = service.getPagio()+ x1*CaOmiliaCost + x2*CaSMSCost - (service.getPagio()+ x1*CaOmiliaCost + x2*CaSMSCost )*25/100 - es; System.out.println("Name and surname: " +stat.NameAndSurname(id2)+ "\nMonthly cost: "+String.format("%.2f",totalcost)); } } break; case 3: for (Services service: yphresies){ if(service instanceof mobInternet){ id2= service.getId(); es = stat.returnSale(id2); x1 = service.getXreosiMB(); totalcost = service.getPagio()+ x1*MBCost - (service.getPagio()+ x1*MBCost )*30/100 - es; System.out.println("Name and surname: " +stat.NameAndSurname(id2)+ "\nMonthly cost: "+String.format("%.2f",totalcost)); } } break; } break; case 6: System.out.println("Calculate free talk time and free SMS or free MB or remaining money"); System.out.println("Choose type of contract: 1. Contract program 2. Card contract program 3. Program mobile-Internet "); int f = s.nextInt(); String fname, fsurname; int fid, spentOmilia = 0, spentSMS = 0,spentMB = 0; boolean flag; switch(f) { case 1: System.out.println("Write the contract's name holder: "); s.nextLine(); fname = s.nextLine(); System.out.println("Write the contract's surname holder: "); fsurname=s.nextLine(); fid = stat.checkName(fname,fsurname ); for (Services s2: yphresies){ if ( fid==s2.getId() & s2.getOnoma().equals("Contract")){ flag = true; while(flag){ System.out.println("You had " + s2.getFreeOmilia() + " free minutes to talk, how much have you spent? "); spentOmilia=s.nextInt(); if (spentOmilia <= s2.getFreeOmilia()) flag= false; else System.out.println("Invalid input, try again."); } flag = true; while(flag) { System.out.println("You had " + s2.getFreeSMS() + " free SMS, how much have you spent? "); spentSMS=s.nextInt(); if (spentSMS <= s2.getFreeSMS()) flag= false; else System.out.println("Invalid input, try again."); } s2.setFreeOmilia(s2.getFreeOmilia()-spentOmilia); s2.setFreeSMS(s2.getFreeSMS()-spentSMS); System.out.println("You have " + s2.getFreeOmilia() + " free minutes to talk and " + s2.getFreeSMS() + " free SMS."); } } break; case 2: System.out.println("Write the contract's name holder: "); s.nextLine(); fname = s.nextLine(); System.out.println("Write the contract's surname holder: "); fsurname=s.nextLine(); fid = stat.checkName(fname,fsurname ); for (Services s2: yphresies){ if ( fid==s2.getId() & s2.getOnoma().equals("Card")){ flag = true; while(flag){ System.out.println("You had " + s2.getFreeOmilia() + " free minutes to talk, how much have you spent? "); spentOmilia=s.nextInt(); if (spentOmilia <= s2.getFreeOmilia()) flag= false; else System.out.println("Invalid input, try again."); } flag = true; while(flag) { System.out.println("You had " + s2.getFreeSMS() + " free SMS, how much have you spent? "); spentSMS=s.nextInt(); if (spentSMS <= s2.getFreeSMS()) flag= false; else System.out.println("Invalid input, try again."); } System.out.println("You had " + s2.getMiniaioYpoloipo() + " remaining money!"); double es2 = stat.returnSale(fid); double y1 = s2.getXreosiSMS(); double y2 = s2.getXreosiOmilia(); double tc = y1*CaOmiliaCost + y2*CaSMSCost; double pay = 0; s2.setFreeOmilia(s2.getFreeOmilia()-spentOmilia); s2.setFreeSMS(s2.getFreeSMS()-spentSMS); System.out.println("You have " + s2.getFreeOmilia() + " free minutes to talk and " + s2.getFreeSMS() + " free SMS."); if (s2.getMiniaioYpoloipo()>0){ System.out.println("You have to pay "+ tc + " euros for SMS and talk time."); if (s2.getMiniaioYpoloipo()>=tc){ pay = s2.getMiniaioYpoloipo() - tc; System.out.println("Your new quantity of remaining money is " + String.format("%.2f",pay));} else if (s2.getMiniaioYpoloipo()<tc){ pay = tc - s2.getMiniaioYpoloipo(); System.out.println("You don't have any remaining money and you have to pay " + String.format("%.2f",pay) + " euros for SMS and talk time."); } } else System.out.println("You don't have any remaining money"); } } break; case 3: System.out.println("Write the contract's name holder: "); s.nextLine(); fname = s.nextLine(); System.out.println("Write the contract's surname holder: "); fsurname=s.nextLine(); fid = stat.checkName(fname,fsurname ); for (Services s2: yphresies){ if ( fid==s2.getId() & s2.getOnoma().equals("Mobile Internet")){ flag = true; while(flag){ System.out.println("You had " + s2.getFreeMB() + " free data, how much have you spent? "); spentMB=s.nextInt(); if (spentMB <= s2.getFreeMB()) flag= false; else System.out.println("Invalid input, try again."); } s2.setFreeMB(s2.getFreeMB()-spentMB); System.out.println("You have " + s2.getFreeMB() + " free data."); } } break; } break; case 7: not = false; break; } } } }
mkontaratou/university-projects
2nd semester/Introduction to Java Programming/java_project1/mainApp.java
5,881
/* Ομάδα Χρηστών 55 * Συγγραφείς: ΜΑΡΙΑ ΚΟΝΤΑΡΑΤΟΥ(3200078) ΓΕΩΡΓΙΟΣ ΚΟΥΜΟΥΝΔΟΥΡΟΣ(3200083) ΠΑΝΑΓΙΩΤΗΣ ΚΩΝΣΤΑΝΤΙΝΑΚΟΣ(3200089) */
block_comment
el
/* Ομάδα Χρηστών 55<SUF>*/ import java.util.ArrayList; import java.util.Scanner; public class mainApp { public static void main(String[] args){ //arxikopoihsh timwn se Eurw gia ta statistika xrhshs(SMS, lepta omilias, MB) ana 1 double ConSMSCost = 0.1; double ConOmiliaCost = 0.2; double CaSMSCost = 0.05; double CaOmiliaCost = 0.3; double MBCost = 0.2; // zhtoumeno c stats stat = new stats(); ArrayList<Services> yphresies = new ArrayList<Services>(); yphresies.add(new symvolaio("Contract",7,20,100,150,15)); yphresies.add(new symvolaio("Contract",7,30,150,150,8)); yphresies.add(new kartosymvolaio("Card",8, 600, 50,5,10,13)); yphresies.add(new kartosymvolaio("Card",8, 450, 80,10,5,18)); yphresies.add(new mobInternet("Mobile Internet", 10,300,6)); yphresies.add(new mobInternet("Mobile Internet", 10,150,4)); //ArrayList<contract> symvolaia = new ArrayList<contract>(); contract c1 =new contract("Maria", "Kontaratou","690000000","26/02/21","cash",0.4, yphresies.get(0)); stat.addContract(c1); contract c2 = new contract("Panagioths", "Kwnstantinakos","690000001","13/02/20","card",0.45,yphresies.get(1)); stat.addContract(c2); contract c3 =new contract("Giwrgos", "Koumoundouros","690000002","30/06/20","cash",0.2, yphresies.get(2)); stat.addContract(c3); contract c4 =new contract("Nikolas", "Papadopoulos","690000003","16/01/21","cash",0.15, yphresies.get(3)); stat.addContract(c4); contract c5 =new contract("Aggelikh", "Merkourh","690000004","26/03/21","cash",0.15, yphresies.get(4)); stat.addContract(c5); contract c6 =new contract("Kwnstantina", "Papaiwannou","690000005","23/08/20","cash",0.15, yphresies.get(5)); stat.addContract(c6); Scanner s = new Scanner(System.in); int i = 6; boolean not=true; while(not) { System.out.println("\n-------------------------------------------------------------------------------"); System.out.println("1. Print available services "); System.out.println("2. Create new contract "); System.out.println("3. Print active contracts for a specific type of service "); System.out.println("4. Update statistics of usage of a contract"); System.out.println("5. Calculate total monthly cost and monthly available remaining money" ); System.out.println("6. Calculate free talk time and free SMS or free MB or remaining money"); System.out.println("7. Exit"); System.out.println("-------------------------------------------------------------------------------\n"); System.out.print("> "); int x = s.nextInt(); switch(x) { case 1: System.out.println("1.Services of mobile telephony (Contract programs or card contract programs)"); System.out.println("2.Services mobile- Internet"); break; case 2: System.out.println("Create new contract: 1. Contract program 2. card contract program 3. Program mobile-Internet "); int y = s.nextInt(); String name1,surname,phone,date,payment, theName,theSurname,ctype; double pagio1,ekptwsi1,miniaioYpoloipo1,sale,avmon; int freeOmilia1,freeSMS1,xreosiOmilia1,xreosiSMS1,freeMB1,xreosiMB1; switch (y) { case 1: System.out.println("Create contract program"); System.out.println("Name: "); s.nextLine(); name1=s.nextLine(); System.out.println("Surname: "); surname = s.nextLine(); System.out.println("Phone: "); phone = s.nextLine(); System.out.println("Starting date of contract: "); date = s.nextLine(); System.out.println("Payment method: "); payment = s.nextLine(); System.out.println("Contract sale: 20% "); System.out.println("Extra sale of contract: "); sale = s.nextDouble(); System.out.println("Fixed cost of contract: 7"); pagio1=7; System.out.println("Free talk time to mobile phones and stable networks: "); freeOmilia1=s.nextInt(); System.out.println("Free SMS: "); freeSMS1=s.nextInt(); System.out.println("Charge for talk time to mobile phones and stable networks after the free talk time: "); xreosiOmilia1=s.nextInt(); System.out.println("Charge for SMS after the free SMS: "); xreosiSMS1=s.nextInt(); ctype = "Contract"; yphresies.add(new symvolaio(ctype,pagio1,freeOmilia1,freeSMS1,xreosiOmilia1,xreosiSMS1)); contract ob1 = new contract(name1,surname,phone,date,payment,sale,yphresies.get(i)); i+=1; stat.addContract(ob1); break; case 2: System.out.println("Create card contract program"); System.out.println("Name: "); s.nextLine(); name1=s.nextLine(); System.out.println("Surname: "); surname = s.nextLine(); System.out.println("Phone: "); phone = s.nextLine(); System.out.println("Starting date of contract: "); date = s.nextLine(); System.out.println("Payment method: "); payment = s.nextLine(); System.out.println("Sale of program 25% "); System.out.println("Extra sale of contract: "); sale =s.nextDouble(); System.out.println("Fixed cost of program: 8"); pagio1= 8 ; System.out.println("Free talk time to mobile phones and stable networks: "); freeOmilia1=s.nextInt(); System.out.println("Free SMS: "); freeSMS1=s.nextInt(); System.out.println("Charge for talk time to mobile phones and stable networks after the free talk time: "); xreosiOmilia1=s.nextInt(); System.out.println("Charge for SMS after the free SMS: "); xreosiSMS1=s.nextInt(); System.out.println("Monthly available remaining money: "); avmon = s.nextDouble(); ctype = "Card"; yphresies.add(new kartosymvolaio(ctype,pagio1,freeOmilia1,freeSMS1,xreosiOmilia1,xreosiSMS1,avmon)); contract ob2 = new contract(name1,surname,phone,date,payment,sale,yphresies.get(i)); i+=1; stat.addContract(ob2); break; case 3: System.out.println("Create program mobile-Internet"); System.out.println("Name: "); s.nextLine(); name1=s.nextLine(); System.out.println("Surname: "); surname = s.nextLine(); System.out.println("Phone: "); phone = s.nextLine(); System.out.println("Starting date of contract: "); date = s.nextLine(); System.out.println("Payment method: "); payment = s.nextLine(); System.out.println("Sale of program: 30% "); System.out.println("Extra sale of contract: "); sale =s.nextDouble(); System.out.println("Fixed cost of program: 10 "); pagio1=10; System.out.println("Free MB: "); freeMB1=s.nextInt(); System.out.println("Charge for MB after the free MB: "); xreosiMB1=s.nextInt(); ctype = "Mobile Internet"; yphresies.add(new mobInternet(ctype,pagio1,freeMB1,xreosiMB1)); contract ob3 = new contract(name1,surname,phone,date,payment,sale,yphresies.get(i)); i+=1; stat.addContract(ob3); break; } break; case 3: System.out.println("Print active contracts for a specific type of service"); System.out.println("Choose type of contract: 1. Contract program 2. Card contract program 3. Program mobile-Internet "); int z = s.nextInt(); int id2 = 0; switch (z) { case 1: for (Services service: yphresies){ if(service instanceof symvolaio){ id2= service.getId(); stat.findContract(id2); } } break; case 2: for (Services service: yphresies){ if(service instanceof kartosymvolaio) id2= service.getId(); stat.findContract(id2); } break; case 3: for (Services service: yphresies){ if(service instanceof mobInternet) id2= service.getId(); stat.findContract(id2); } break; } break; case 4: System.out.println("Update statistics of usage of a contract"); System.out.println("Choose type of contract: 1. Contract program 2. Card contract program 3. Program mobile-Internet "); int k = s.nextInt(); int CfreeOmilia1,CfreeSMS1,CxreosiOmilia1,CxreosiSMS1,type, CfreeMB, CxreosiMB,cid; double Cavmon; String cname,csurname; switch(k) { case 1: System.out.println("Write the contract's name holder: "); s.nextLine(); cname = s.nextLine(); System.out.println("Write the contract's surname holder: "); csurname=s.nextLine(); cid = stat.checkName(cname,csurname ); if (cid!=-1){ System.out.println("Change your contract's stats"); System.out.println("Free talk time to mobile phones and stable networks: "); CfreeOmilia1=s.nextInt(); System.out.println("Free SMS: "); CfreeSMS1=s.nextInt(); System.out.println("Charge for talk time to mobile phones and stable networks after the free talk time: "); CxreosiOmilia1=s.nextInt(); System.out.println("Charge for SMS after the free SMS: "); CxreosiSMS1=s.nextInt(); type = 1; for (Services s1: yphresies){ if ( s1.getOnoma().equals("Contract")){ if (s1.getId() == cid ){ stat.changeStats(cid, CfreeOmilia1, CfreeSMS1, CxreosiOmilia1, CxreosiSMS1,0,0,0, s1, type); } } } } break; case 2: System.out.println("Write the contract's name holder: "); s.nextLine(); cname = s.nextLine(); System.out.println("Write the contract's surname holder: "); csurname=s.nextLine(); cid = stat.checkName(cname,csurname ); if (cid!=-1){ System.out.println("Change your contract's stats"); System.out.println("Free talk time to mobile phones and stable networks: "); CfreeOmilia1=s.nextInt(); System.out.println("Free SMS: "); CfreeSMS1=s.nextInt(); System.out.println("Charge for talk time to mobile phones and stable networks after the free talk time: "); CxreosiOmilia1=s.nextInt(); System.out.println("Charge for SMS after the free SMS: "); CxreosiSMS1=s.nextInt(); System.out.println("Monthly available remaining money: "); Cavmon = s.nextDouble(); type = 2; for (Services s1: yphresies){ if ( s1.getOnoma().equals("Card")){ if (s1.getId() == cid){ stat.changeStats(cid, CfreeOmilia1, CfreeSMS1, CxreosiOmilia1, CxreosiSMS1,0,0,Cavmon, s1, type); } } } } break; case 3: System.out.println("Write the contract's name holder: "); s.nextLine(); cname = s.nextLine(); System.out.println("Write the contract's surname holder: "); csurname=s.nextLine(); cid = stat.checkName(cname,csurname ); if (cid!=-1){ System.out.println("Change your contract's stats"); System.out.println("Free MB: "); CfreeMB=s.nextInt(); System.out.println("Charge for MB after the free MB: "); CxreosiMB=s.nextInt(); type = 3; for (Services s1: yphresies){ if ( s1.getOnoma().equals("Mobile Internet")){ if (s1.getId() == cid){ stat.changeStats(cid,0, 0, 0, 0,CfreeMB, CxreosiMB,0, s1, type); } } } } break; } break; case 5: System.out.println("Calculate total monthly cost and monthly available remaining money" ); System.out.println("Choose type of contract: 1. Contract program 2. Card contract program 3. Program mobile-Internet "); int m = s.nextInt(); double es = 0; double totalcost = 0; double x1=0, x2=0; switch(m) { case 1: for (Services service: yphresies){ if(service instanceof symvolaio){ id2= service.getId(); es = stat.returnSale(id2); x1 = service.getXreosiSMS(); x2 = service.getXreosiOmilia(); totalcost = service.getPagio()+ x1*ConOmiliaCost + x2*ConSMSCost - (service.getPagio()+ x1*ConOmiliaCost + x2*ConSMSCost )*20/100 - es; System.out.println("Name and surname: " +stat.NameAndSurname(id2)+ "\nMonthly cost: "+ String.format("%.2f",totalcost)); } } break; case 2: for (Services service: yphresies){ if(service instanceof kartosymvolaio){ id2= service.getId(); es = stat.returnSale(id2); x1 = service.getXreosiSMS(); x2 = service.getXreosiOmilia(); totalcost = service.getPagio()+ x1*CaOmiliaCost + x2*CaSMSCost - (service.getPagio()+ x1*CaOmiliaCost + x2*CaSMSCost )*25/100 - es; System.out.println("Name and surname: " +stat.NameAndSurname(id2)+ "\nMonthly cost: "+String.format("%.2f",totalcost)); } } break; case 3: for (Services service: yphresies){ if(service instanceof mobInternet){ id2= service.getId(); es = stat.returnSale(id2); x1 = service.getXreosiMB(); totalcost = service.getPagio()+ x1*MBCost - (service.getPagio()+ x1*MBCost )*30/100 - es; System.out.println("Name and surname: " +stat.NameAndSurname(id2)+ "\nMonthly cost: "+String.format("%.2f",totalcost)); } } break; } break; case 6: System.out.println("Calculate free talk time and free SMS or free MB or remaining money"); System.out.println("Choose type of contract: 1. Contract program 2. Card contract program 3. Program mobile-Internet "); int f = s.nextInt(); String fname, fsurname; int fid, spentOmilia = 0, spentSMS = 0,spentMB = 0; boolean flag; switch(f) { case 1: System.out.println("Write the contract's name holder: "); s.nextLine(); fname = s.nextLine(); System.out.println("Write the contract's surname holder: "); fsurname=s.nextLine(); fid = stat.checkName(fname,fsurname ); for (Services s2: yphresies){ if ( fid==s2.getId() & s2.getOnoma().equals("Contract")){ flag = true; while(flag){ System.out.println("You had " + s2.getFreeOmilia() + " free minutes to talk, how much have you spent? "); spentOmilia=s.nextInt(); if (spentOmilia <= s2.getFreeOmilia()) flag= false; else System.out.println("Invalid input, try again."); } flag = true; while(flag) { System.out.println("You had " + s2.getFreeSMS() + " free SMS, how much have you spent? "); spentSMS=s.nextInt(); if (spentSMS <= s2.getFreeSMS()) flag= false; else System.out.println("Invalid input, try again."); } s2.setFreeOmilia(s2.getFreeOmilia()-spentOmilia); s2.setFreeSMS(s2.getFreeSMS()-spentSMS); System.out.println("You have " + s2.getFreeOmilia() + " free minutes to talk and " + s2.getFreeSMS() + " free SMS."); } } break; case 2: System.out.println("Write the contract's name holder: "); s.nextLine(); fname = s.nextLine(); System.out.println("Write the contract's surname holder: "); fsurname=s.nextLine(); fid = stat.checkName(fname,fsurname ); for (Services s2: yphresies){ if ( fid==s2.getId() & s2.getOnoma().equals("Card")){ flag = true; while(flag){ System.out.println("You had " + s2.getFreeOmilia() + " free minutes to talk, how much have you spent? "); spentOmilia=s.nextInt(); if (spentOmilia <= s2.getFreeOmilia()) flag= false; else System.out.println("Invalid input, try again."); } flag = true; while(flag) { System.out.println("You had " + s2.getFreeSMS() + " free SMS, how much have you spent? "); spentSMS=s.nextInt(); if (spentSMS <= s2.getFreeSMS()) flag= false; else System.out.println("Invalid input, try again."); } System.out.println("You had " + s2.getMiniaioYpoloipo() + " remaining money!"); double es2 = stat.returnSale(fid); double y1 = s2.getXreosiSMS(); double y2 = s2.getXreosiOmilia(); double tc = y1*CaOmiliaCost + y2*CaSMSCost; double pay = 0; s2.setFreeOmilia(s2.getFreeOmilia()-spentOmilia); s2.setFreeSMS(s2.getFreeSMS()-spentSMS); System.out.println("You have " + s2.getFreeOmilia() + " free minutes to talk and " + s2.getFreeSMS() + " free SMS."); if (s2.getMiniaioYpoloipo()>0){ System.out.println("You have to pay "+ tc + " euros for SMS and talk time."); if (s2.getMiniaioYpoloipo()>=tc){ pay = s2.getMiniaioYpoloipo() - tc; System.out.println("Your new quantity of remaining money is " + String.format("%.2f",pay));} else if (s2.getMiniaioYpoloipo()<tc){ pay = tc - s2.getMiniaioYpoloipo(); System.out.println("You don't have any remaining money and you have to pay " + String.format("%.2f",pay) + " euros for SMS and talk time."); } } else System.out.println("You don't have any remaining money"); } } break; case 3: System.out.println("Write the contract's name holder: "); s.nextLine(); fname = s.nextLine(); System.out.println("Write the contract's surname holder: "); fsurname=s.nextLine(); fid = stat.checkName(fname,fsurname ); for (Services s2: yphresies){ if ( fid==s2.getId() & s2.getOnoma().equals("Mobile Internet")){ flag = true; while(flag){ System.out.println("You had " + s2.getFreeMB() + " free data, how much have you spent? "); spentMB=s.nextInt(); if (spentMB <= s2.getFreeMB()) flag= false; else System.out.println("Invalid input, try again."); } s2.setFreeMB(s2.getFreeMB()-spentMB); System.out.println("You have " + s2.getFreeMB() + " free data."); } } break; } break; case 7: not = false; break; } } } }
2058_7
package com.example.android.flymetothemoon.utilities; import android.content.Context; import android.util.Log; import com.example.android.flymetothemoon.FlightsDoc.Airline; import com.example.android.flymetothemoon.FlightsDoc.AirportsJsonTranslations; import com.example.android.flymetothemoon.FlightsDoc.FlightResults; import com.example.android.flymetothemoon.FlightsDoc.Flights; import com.example.android.flymetothemoon.FlightsDoc.Itineraries; import com.example.android.flymetothemoon.FlightsDoc.JsonResponseFlights; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import static android.R.attr.label; import static android.R.attr.name; import static android.R.attr.resource; import static android.R.attr.value; /** * Created by tsita on 13/1/2017. * Utility functions to handle JSON data. */ public final class FlightsJsonUtils { public static JsonResponseFlights getFlightsStringsFromJson(Context context, String flightsJsonStr) throws JSONException { // Όλες οι μεταβλητές που αρχίζουν με AM περιέχουν τα ακριβή ονόματα των τίτλων // στην απάντηση της υπηρεσίας στο json αρχείο. final String AM_CURRENCY = "currency"; final String AM_RESULTS = "results"; final String AM_ITINERARIES = "itineraries"; final String AM_OUTBOUND = "outbound"; final String AM_FLIGHTS = "flights"; final String AM_DEPARTS_AT = "departs_at"; final String AM_ARRIVES_AT = "arrives_at"; final String AM_ORIGIN = "origin"; final String AM_AIRPORT = "airport"; final String AM_DESTINATION = "destination"; final String AM_AIRLINE = "operating_airline"; final String AM_FLIGHT_NUMBER = "flight_number"; final String AM_INBOUND = "inbound"; final String AM_FARE = "fare"; final String AM_TOTAL_PRICE = "total_price"; JSONObject flightsJson = new JSONObject(flightsJsonStr); String currency = flightsJson.getString(AM_CURRENCY); JSONArray flightsArray = flightsJson.getJSONArray(AM_RESULTS); // Αρχικοποίηση αρίθμισης αποτελεσμάτων. Δεν χρησιμεύει και πολύ. Είναι για διευκόλυνση. int numberOfFlights = 0 ; int numberOfItineraries = 0; int numberOfInboundFlights = 0; int numberOfOutboundFlights = 0; numberOfFlights = flightsArray.length(); /* OUTBOUND */ //TODO Οι μεταβλητές αυτές δεν χρησιμοποιούνται πλέον. Πρέπει να διαγραφούν κάποια στιγμή. String[] outbound_departs_at = new String[flightsArray.length()]; String[] outbound_arrives_at = new String[flightsArray.length()]; String[] outbound_origin_airport = new String[flightsArray.length()]; String[] outbound_destination_airport = new String[flightsArray.length()]; String[] outbound_airline = new String[flightsArray.length()]; String[] outbound_flight_number = new String[flightsArray.length()]; /* INBOUND */ //TODO Οι μεταβλητές αυτές δεν χρησιμοποιούνται πλέον. Πρέπει να διαγραφούν κάποια στιγμή. String[] inbound_departs_at = new String[flightsArray.length()]; String[] inbound_arrives_at = new String[flightsArray.length()]; String[] inbound_origin_airport = new String[flightsArray.length()]; String[] inbound_destination_airport = new String[flightsArray.length()]; String[] inbound_airline = new String[flightsArray.length()]; String[] inbound_flight_number = new String[flightsArray.length()]; double[] price = new double[flightsArray.length()]; // Αρχικοποίηση του αντικειμένου response και των ArrayList απο // τα οποία αποτελείται. JsonResponseFlights response; ArrayList<FlightResults> flightResults = new ArrayList<>(); // ArrayList<Itineraries> itineraries = new ArrayList<Itineraries>(); // ArrayList<Flights> outFlights = new ArrayList<Flights>(); // ArrayList<Flights> inFlights = new ArrayList<Flights>(); // Αποκωδικοποίηση JSON /* κάθε 0,1,2 κλπ είναι ένα object και το παίρνω με getJSONObject * όταν έχει brackets [] τότε είναι πίνακας και πρέπει να πάρω τον πίνακα με getJSONArray() που επιστρέφει JSONArray*/ for (int i=0; i<flightsArray.length(); i++){ JSONObject result = flightsArray.getJSONObject(i); JSONObject fareObject = result.getJSONObject(AM_FARE); price[i] = fareObject.getDouble(AM_TOTAL_PRICE); JSONArray itinerariesN = result.getJSONArray(AM_ITINERARIES); ArrayList<Itineraries> itineraries = new ArrayList<Itineraries>(); numberOfItineraries = itinerariesN.length(); for (int j=0; j<numberOfItineraries; j++){ JSONObject itinerary = itinerariesN.getJSONObject(j); /* OUTBOUND information*/ JSONObject outbound = itinerary.getJSONObject(AM_OUTBOUND); JSONArray outFlightsArr = outbound.getJSONArray(AM_FLIGHTS); ArrayList<Flights> outFlights = new ArrayList<Flights>(); numberOfOutboundFlights = outFlightsArr.length(); for (int k=0; k<numberOfOutboundFlights; k++){ JSONObject fl = outFlightsArr.getJSONObject(k); outbound_departs_at[i] = fl.getString(AM_DEPARTS_AT); outbound_arrives_at[i] = fl.getString(AM_ARRIVES_AT); JSONObject origin = fl.getJSONObject(AM_ORIGIN); outbound_origin_airport[i] = origin.getString(AM_AIRPORT); JSONObject destination = fl.getJSONObject(AM_DESTINATION); outbound_destination_airport[i] = destination.getString(AM_AIRPORT); outbound_airline[i] = fl.getString(AM_AIRLINE); outbound_flight_number[i] = fl.getString(AM_FLIGHT_NUMBER); // Προσθήκη πτήσης στο ArrayList για outbound. outFlights.add(new Flights(fl.getString(AM_DEPARTS_AT), fl.getString(AM_ARRIVES_AT), origin.getString(AM_AIRPORT), destination.getString(AM_AIRPORT), fl.getString(AM_AIRLINE), fl.getString(AM_FLIGHT_NUMBER))); } /* INBOUND information*/ JSONObject inbound = itinerary.getJSONObject(AM_INBOUND); JSONArray inFlightsArr = inbound.getJSONArray(AM_FLIGHTS); ArrayList<Flights> inFlights = new ArrayList<Flights>(); numberOfInboundFlights = inFlightsArr.length(); for (int k=0; k<numberOfInboundFlights; k++) { JSONObject fl = inFlightsArr.getJSONObject(k); inbound_departs_at[i] = fl.getString(AM_DEPARTS_AT); inbound_arrives_at[i] = fl.getString(AM_ARRIVES_AT); JSONObject origin = fl.getJSONObject(AM_ORIGIN); inbound_origin_airport[i] = origin.getString(AM_AIRPORT); JSONObject destination = fl.getJSONObject(AM_DESTINATION); inbound_destination_airport [i] = destination.getString(AM_AIRPORT); inbound_airline[i] = fl.getString(AM_AIRLINE); inbound_flight_number[i] = fl.getString(AM_FLIGHT_NUMBER); // Προσθήκη πτήσης στο ArrayList για inbound inFlights.add(new Flights(fl.getString(AM_DEPARTS_AT), fl.getString(AM_ARRIVES_AT), origin.getString(AM_AIRPORT), destination.getString(AM_AIRPORT), fl.getString(AM_AIRLINE), fl.getString(AM_FLIGHT_NUMBER))); } // Προσθήκη itinerary στο ArrayList με τα itineraries. itineraries.add(new Itineraries(outFlights, inFlights)); } // Τελική προσθήκη ενός αποτελέσματος στο ArrayList με τα αποτελέσματα πτήσεων flightResults.add(new FlightResults(itineraries, fareObject.getString(AM_TOTAL_PRICE))); } // Δημιουργία του αντικειμένου που περιέχει όλη την απάντηση από το JSON // για τις πτήσεις που ψάχνουμε. response = new JsonResponseFlights(flightResults, currency, numberOfFlights, numberOfItineraries, numberOfInboundFlights, numberOfOutboundFlights); //Με αυτόν τον τρόπο παίρνω τα αποτελέσματα. Dokimi test1 response.getResults().get(0).getItineraries().get(0).getInbounds().get(0).getAirline(); String msg = "\n\n\n\nΠληροφορίες για τις πτήσεις!\n\n Βρέθηκαν " + numberOfFlights + " πτήσεις!\n\n"; for (int i=0; i<numberOfFlights; i++){ msg += "Πτήση νούμερο: " + i + "\n"; msg += "Από " + outbound_origin_airport[i] +"\n"; msg += "Σε " + inbound_origin_airport[i] +"\n\n"; msg += "Ημερομηνία αναχώρησης " + outbound_departs_at[i] + " με άφιξη στις " + outbound_arrives_at[i] +"\n"; msg += "Εταιρία: " + outbound_airline[i] +"\n"; msg += "Κωδικός πτήσης: " + outbound_flight_number[i] +"\n"; msg += "Ημερομηνία επιστροφής " + inbound_departs_at[i] + " με άφιξη στις " + inbound_arrives_at[i] +"\n"; msg += "Εταιρία: " + inbound_airline[i] +"\n"; msg += "Κωδικός πτήσης: " + inbound_flight_number[i] +"\n"; msg += "Συνολικό κόστος: " + price[i] + " σε νόμισμα: " + currency +"\n"; msg += "***********************************\n***********************************\n***********************************\n***********************************\n"; } Log.v("FlightsJsonUtils", msg ); return response; } public static String[] autocompletAirport(String cityJsonStr) throws JSONException { //"https://api.sandbox.amadeus.com/v1.2/airports/autocomplete? // apikey=AMADEUS_API_KEY.toString() // &term=RMA" final String AM_AUTOCOMPLETE_VALUE = "value"; final String AM_AUTOCOMPLETE_LABEL = "label"; JSONArray autocompleteResults = new JSONArray(cityJsonStr); int numberOfResultsAutocomplete = autocompleteResults.length(); String[] value = new String[numberOfResultsAutocomplete]; String[] label = new String[numberOfResultsAutocomplete]; for (int i=0; i<numberOfResultsAutocomplete; i++) { JSONObject result = autocompleteResults.getJSONObject(i); value[i] = result.getString(AM_AUTOCOMPLETE_VALUE); label[i] = result.getString(AM_AUTOCOMPLETE_LABEL); } String msg = "" + numberOfResultsAutocomplete + " στοιχεία που ανακτήθηκαν από την τιμή " + cityJsonStr + " και είναι τα εξής:\n"; for (int i=0; i< numberOfResultsAutocomplete; i++){ msg += "[" + i + "] Value = " + value[i] + " \t"; msg += "Label = " + label[i] + "\n\n"; } Log.v("FlightsJsonUtils", msg); return label; } public static ArrayList<Airline> airlinesJson(String codeJsonStr) throws JSONException { //https://iatacodes.org/api/v6/airlines? // api_key=2d795f6e-a61c-4697-aff4-50df2d00dfb0 // &code=A3 final String IA_AIRLINES_RESPONSE = "response"; final String IA_AIRLINES_CODE = "code"; final String IA_AIRLINES_NAME = "name"; JSONObject airlinesResults = new JSONObject(codeJsonStr); ArrayList<Airline> airlines = new ArrayList<Airline>(); JSONArray responses = airlinesResults.getJSONArray(IA_AIRLINES_RESPONSE); for (int i=0; i<responses.length(); i++){ airlines.add(new Airline(responses.getJSONObject(i).getString(IA_AIRLINES_NAME), responses.getJSONObject(i).getString(IA_AIRLINES_CODE))); } String msg = "" + airlinesResults.length() + " Αποτελέσματα βρέθηκαν.\n"; for (int i=0; i<airlines.size(); i++) { msg += "[" + i + "] Η εταιρία με κωδικό: " + airlines.get(i).getCode() + " είναι η αεροπορική εταιρία: " + airlines.get(i).getName() +"\n"; msg += "πόσο ακόμα ρεεεε?" ; } Log.v("FlightsJsonUtils", msg); return airlines; } public static ArrayList<AirportsJsonTranslations> airportTranslationJson(String termJsonStr) throws JSONException { //https://api.sandbox.amadeus.com/v1.2/airports/autocomplete? // apikey=AMADEUS_API_KEY.toString() PREPEI NA ALLAKSEI // &term=RMA final String AM_AIRPORT_VALUE = "value"; final String AM_AIRPORT_LABEL = "label"; JSONArray airport = new JSONArray(termJsonStr); ArrayList<AirportsJsonTranslations> airportsJsonTranslations = new ArrayList<AirportsJsonTranslations>(); for (int i=0; i<airport.length(); i++){ airportsJsonTranslations.add(new AirportsJsonTranslations(airport.getJSONObject(i).getString(AM_AIRPORT_VALUE), airport.getJSONObject(i).getString(AM_AIRPORT_LABEL))); } return airportsJsonTranslations; /* [ { "value": "RMA", "label": "Roma [RMA]" } ] */ } }
mohamedaltaib/Fly-me-to-the-moon-app
app/src/main/java/com/example/android/flymetothemoon/utilities/FlightsJsonUtils.java
4,139
// τα οποία αποτελείται.
line_comment
el
package com.example.android.flymetothemoon.utilities; import android.content.Context; import android.util.Log; import com.example.android.flymetothemoon.FlightsDoc.Airline; import com.example.android.flymetothemoon.FlightsDoc.AirportsJsonTranslations; import com.example.android.flymetothemoon.FlightsDoc.FlightResults; import com.example.android.flymetothemoon.FlightsDoc.Flights; import com.example.android.flymetothemoon.FlightsDoc.Itineraries; import com.example.android.flymetothemoon.FlightsDoc.JsonResponseFlights; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import static android.R.attr.label; import static android.R.attr.name; import static android.R.attr.resource; import static android.R.attr.value; /** * Created by tsita on 13/1/2017. * Utility functions to handle JSON data. */ public final class FlightsJsonUtils { public static JsonResponseFlights getFlightsStringsFromJson(Context context, String flightsJsonStr) throws JSONException { // Όλες οι μεταβλητές που αρχίζουν με AM περιέχουν τα ακριβή ονόματα των τίτλων // στην απάντηση της υπηρεσίας στο json αρχείο. final String AM_CURRENCY = "currency"; final String AM_RESULTS = "results"; final String AM_ITINERARIES = "itineraries"; final String AM_OUTBOUND = "outbound"; final String AM_FLIGHTS = "flights"; final String AM_DEPARTS_AT = "departs_at"; final String AM_ARRIVES_AT = "arrives_at"; final String AM_ORIGIN = "origin"; final String AM_AIRPORT = "airport"; final String AM_DESTINATION = "destination"; final String AM_AIRLINE = "operating_airline"; final String AM_FLIGHT_NUMBER = "flight_number"; final String AM_INBOUND = "inbound"; final String AM_FARE = "fare"; final String AM_TOTAL_PRICE = "total_price"; JSONObject flightsJson = new JSONObject(flightsJsonStr); String currency = flightsJson.getString(AM_CURRENCY); JSONArray flightsArray = flightsJson.getJSONArray(AM_RESULTS); // Αρχικοποίηση αρίθμισης αποτελεσμάτων. Δεν χρησιμεύει και πολύ. Είναι για διευκόλυνση. int numberOfFlights = 0 ; int numberOfItineraries = 0; int numberOfInboundFlights = 0; int numberOfOutboundFlights = 0; numberOfFlights = flightsArray.length(); /* OUTBOUND */ //TODO Οι μεταβλητές αυτές δεν χρησιμοποιούνται πλέον. Πρέπει να διαγραφούν κάποια στιγμή. String[] outbound_departs_at = new String[flightsArray.length()]; String[] outbound_arrives_at = new String[flightsArray.length()]; String[] outbound_origin_airport = new String[flightsArray.length()]; String[] outbound_destination_airport = new String[flightsArray.length()]; String[] outbound_airline = new String[flightsArray.length()]; String[] outbound_flight_number = new String[flightsArray.length()]; /* INBOUND */ //TODO Οι μεταβλητές αυτές δεν χρησιμοποιούνται πλέον. Πρέπει να διαγραφούν κάποια στιγμή. String[] inbound_departs_at = new String[flightsArray.length()]; String[] inbound_arrives_at = new String[flightsArray.length()]; String[] inbound_origin_airport = new String[flightsArray.length()]; String[] inbound_destination_airport = new String[flightsArray.length()]; String[] inbound_airline = new String[flightsArray.length()]; String[] inbound_flight_number = new String[flightsArray.length()]; double[] price = new double[flightsArray.length()]; // Αρχικοποίηση του αντικειμένου response και των ArrayList απο // τα οποία<SUF> JsonResponseFlights response; ArrayList<FlightResults> flightResults = new ArrayList<>(); // ArrayList<Itineraries> itineraries = new ArrayList<Itineraries>(); // ArrayList<Flights> outFlights = new ArrayList<Flights>(); // ArrayList<Flights> inFlights = new ArrayList<Flights>(); // Αποκωδικοποίηση JSON /* κάθε 0,1,2 κλπ είναι ένα object και το παίρνω με getJSONObject * όταν έχει brackets [] τότε είναι πίνακας και πρέπει να πάρω τον πίνακα με getJSONArray() που επιστρέφει JSONArray*/ for (int i=0; i<flightsArray.length(); i++){ JSONObject result = flightsArray.getJSONObject(i); JSONObject fareObject = result.getJSONObject(AM_FARE); price[i] = fareObject.getDouble(AM_TOTAL_PRICE); JSONArray itinerariesN = result.getJSONArray(AM_ITINERARIES); ArrayList<Itineraries> itineraries = new ArrayList<Itineraries>(); numberOfItineraries = itinerariesN.length(); for (int j=0; j<numberOfItineraries; j++){ JSONObject itinerary = itinerariesN.getJSONObject(j); /* OUTBOUND information*/ JSONObject outbound = itinerary.getJSONObject(AM_OUTBOUND); JSONArray outFlightsArr = outbound.getJSONArray(AM_FLIGHTS); ArrayList<Flights> outFlights = new ArrayList<Flights>(); numberOfOutboundFlights = outFlightsArr.length(); for (int k=0; k<numberOfOutboundFlights; k++){ JSONObject fl = outFlightsArr.getJSONObject(k); outbound_departs_at[i] = fl.getString(AM_DEPARTS_AT); outbound_arrives_at[i] = fl.getString(AM_ARRIVES_AT); JSONObject origin = fl.getJSONObject(AM_ORIGIN); outbound_origin_airport[i] = origin.getString(AM_AIRPORT); JSONObject destination = fl.getJSONObject(AM_DESTINATION); outbound_destination_airport[i] = destination.getString(AM_AIRPORT); outbound_airline[i] = fl.getString(AM_AIRLINE); outbound_flight_number[i] = fl.getString(AM_FLIGHT_NUMBER); // Προσθήκη πτήσης στο ArrayList για outbound. outFlights.add(new Flights(fl.getString(AM_DEPARTS_AT), fl.getString(AM_ARRIVES_AT), origin.getString(AM_AIRPORT), destination.getString(AM_AIRPORT), fl.getString(AM_AIRLINE), fl.getString(AM_FLIGHT_NUMBER))); } /* INBOUND information*/ JSONObject inbound = itinerary.getJSONObject(AM_INBOUND); JSONArray inFlightsArr = inbound.getJSONArray(AM_FLIGHTS); ArrayList<Flights> inFlights = new ArrayList<Flights>(); numberOfInboundFlights = inFlightsArr.length(); for (int k=0; k<numberOfInboundFlights; k++) { JSONObject fl = inFlightsArr.getJSONObject(k); inbound_departs_at[i] = fl.getString(AM_DEPARTS_AT); inbound_arrives_at[i] = fl.getString(AM_ARRIVES_AT); JSONObject origin = fl.getJSONObject(AM_ORIGIN); inbound_origin_airport[i] = origin.getString(AM_AIRPORT); JSONObject destination = fl.getJSONObject(AM_DESTINATION); inbound_destination_airport [i] = destination.getString(AM_AIRPORT); inbound_airline[i] = fl.getString(AM_AIRLINE); inbound_flight_number[i] = fl.getString(AM_FLIGHT_NUMBER); // Προσθήκη πτήσης στο ArrayList για inbound inFlights.add(new Flights(fl.getString(AM_DEPARTS_AT), fl.getString(AM_ARRIVES_AT), origin.getString(AM_AIRPORT), destination.getString(AM_AIRPORT), fl.getString(AM_AIRLINE), fl.getString(AM_FLIGHT_NUMBER))); } // Προσθήκη itinerary στο ArrayList με τα itineraries. itineraries.add(new Itineraries(outFlights, inFlights)); } // Τελική προσθήκη ενός αποτελέσματος στο ArrayList με τα αποτελέσματα πτήσεων flightResults.add(new FlightResults(itineraries, fareObject.getString(AM_TOTAL_PRICE))); } // Δημιουργία του αντικειμένου που περιέχει όλη την απάντηση από το JSON // για τις πτήσεις που ψάχνουμε. response = new JsonResponseFlights(flightResults, currency, numberOfFlights, numberOfItineraries, numberOfInboundFlights, numberOfOutboundFlights); //Με αυτόν τον τρόπο παίρνω τα αποτελέσματα. Dokimi test1 response.getResults().get(0).getItineraries().get(0).getInbounds().get(0).getAirline(); String msg = "\n\n\n\nΠληροφορίες για τις πτήσεις!\n\n Βρέθηκαν " + numberOfFlights + " πτήσεις!\n\n"; for (int i=0; i<numberOfFlights; i++){ msg += "Πτήση νούμερο: " + i + "\n"; msg += "Από " + outbound_origin_airport[i] +"\n"; msg += "Σε " + inbound_origin_airport[i] +"\n\n"; msg += "Ημερομηνία αναχώρησης " + outbound_departs_at[i] + " με άφιξη στις " + outbound_arrives_at[i] +"\n"; msg += "Εταιρία: " + outbound_airline[i] +"\n"; msg += "Κωδικός πτήσης: " + outbound_flight_number[i] +"\n"; msg += "Ημερομηνία επιστροφής " + inbound_departs_at[i] + " με άφιξη στις " + inbound_arrives_at[i] +"\n"; msg += "Εταιρία: " + inbound_airline[i] +"\n"; msg += "Κωδικός πτήσης: " + inbound_flight_number[i] +"\n"; msg += "Συνολικό κόστος: " + price[i] + " σε νόμισμα: " + currency +"\n"; msg += "***********************************\n***********************************\n***********************************\n***********************************\n"; } Log.v("FlightsJsonUtils", msg ); return response; } public static String[] autocompletAirport(String cityJsonStr) throws JSONException { //"https://api.sandbox.amadeus.com/v1.2/airports/autocomplete? // apikey=AMADEUS_API_KEY.toString() // &term=RMA" final String AM_AUTOCOMPLETE_VALUE = "value"; final String AM_AUTOCOMPLETE_LABEL = "label"; JSONArray autocompleteResults = new JSONArray(cityJsonStr); int numberOfResultsAutocomplete = autocompleteResults.length(); String[] value = new String[numberOfResultsAutocomplete]; String[] label = new String[numberOfResultsAutocomplete]; for (int i=0; i<numberOfResultsAutocomplete; i++) { JSONObject result = autocompleteResults.getJSONObject(i); value[i] = result.getString(AM_AUTOCOMPLETE_VALUE); label[i] = result.getString(AM_AUTOCOMPLETE_LABEL); } String msg = "" + numberOfResultsAutocomplete + " στοιχεία που ανακτήθηκαν από την τιμή " + cityJsonStr + " και είναι τα εξής:\n"; for (int i=0; i< numberOfResultsAutocomplete; i++){ msg += "[" + i + "] Value = " + value[i] + " \t"; msg += "Label = " + label[i] + "\n\n"; } Log.v("FlightsJsonUtils", msg); return label; } public static ArrayList<Airline> airlinesJson(String codeJsonStr) throws JSONException { //https://iatacodes.org/api/v6/airlines? // api_key=2d795f6e-a61c-4697-aff4-50df2d00dfb0 // &code=A3 final String IA_AIRLINES_RESPONSE = "response"; final String IA_AIRLINES_CODE = "code"; final String IA_AIRLINES_NAME = "name"; JSONObject airlinesResults = new JSONObject(codeJsonStr); ArrayList<Airline> airlines = new ArrayList<Airline>(); JSONArray responses = airlinesResults.getJSONArray(IA_AIRLINES_RESPONSE); for (int i=0; i<responses.length(); i++){ airlines.add(new Airline(responses.getJSONObject(i).getString(IA_AIRLINES_NAME), responses.getJSONObject(i).getString(IA_AIRLINES_CODE))); } String msg = "" + airlinesResults.length() + " Αποτελέσματα βρέθηκαν.\n"; for (int i=0; i<airlines.size(); i++) { msg += "[" + i + "] Η εταιρία με κωδικό: " + airlines.get(i).getCode() + " είναι η αεροπορική εταιρία: " + airlines.get(i).getName() +"\n"; msg += "πόσο ακόμα ρεεεε?" ; } Log.v("FlightsJsonUtils", msg); return airlines; } public static ArrayList<AirportsJsonTranslations> airportTranslationJson(String termJsonStr) throws JSONException { //https://api.sandbox.amadeus.com/v1.2/airports/autocomplete? // apikey=AMADEUS_API_KEY.toString() PREPEI NA ALLAKSEI // &term=RMA final String AM_AIRPORT_VALUE = "value"; final String AM_AIRPORT_LABEL = "label"; JSONArray airport = new JSONArray(termJsonStr); ArrayList<AirportsJsonTranslations> airportsJsonTranslations = new ArrayList<AirportsJsonTranslations>(); for (int i=0; i<airport.length(); i++){ airportsJsonTranslations.add(new AirportsJsonTranslations(airport.getJSONObject(i).getString(AM_AIRPORT_VALUE), airport.getJSONObject(i).getString(AM_AIRPORT_LABEL))); } return airportsJsonTranslations; /* [ { "value": "RMA", "label": "Roma [RMA]" } ] */ } }
15493_0
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ImageApp extends JFrame implements ActionListener { JPanel kentriko; JMenuBar menubar; JMenu optionsMenu; JMenuItem resetMenuItem; JPanel pnlKentriko; JPanel pnlEikona; JPanel pnlAlign; JPanel pnlSizes; JPanel pnlSizeW; JPanel pnlSizeH; JButton btnLeft; JButton btnCenter; JButton btnRight; JLabel lblEikona; JLabel lblSizeW; JLabel lblSizeH; JTextField txtSizeW; JTextField txtSizeH; JButton btnResize; int width; int height; public ImageApp() { // Η super σε εφαρμογές JFrame δίνει τίτλο στο παράθυρο super("Image Application"); // Θέλουμε η εφαρμογή να ολοκληρώνει την εκτέλεσή της με το κλείσιμο // του παραθύρου setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400,400); menubar = new JMenuBar(); optionsMenu = new JMenu("Options"); resetMenuItem = new JMenuItem("Reset"); resetMenuItem.setActionCommand("reset"); resetMenuItem.addActionListener(this); optionsMenu.add(resetMenuItem); menubar.add(optionsMenu); setJMenuBar(menubar); pnlKentriko = new JPanel(); pnlKentriko.setLayout(new BoxLayout(pnlKentriko, BoxLayout.PAGE_AXIS)); pnlAlign = new JPanel(new GridLayout(1,3)); pnlEikona = new JPanel(); pnlEikona.setLayout(new FlowLayout(FlowLayout.CENTER)); pnlSizes = new JPanel(new GridLayout(3,2)); lblSizeW = new JLabel("Width"); txtSizeW = new JTextField(); lblSizeH = new JLabel("Height"); txtSizeH = new JTextField(); btnResize = new JButton("Resize"); btnResize.setActionCommand("resize"); btnResize.addActionListener(this); pnlSizes.add(lblSizeW); pnlSizes.add(txtSizeW); pnlSizes.add(lblSizeH); pnlSizes.add(txtSizeH); pnlSizes.add(btnResize); btnLeft = new JButton("Align Left"); btnLeft.setActionCommand("alignleft"); btnLeft.addActionListener(this); btnCenter = new JButton("Align Center"); btnCenter.setActionCommand("aligncenter"); btnCenter.addActionListener(this); btnRight = new JButton("Align Right"); btnRight.setActionCommand("alignright"); btnRight.addActionListener(this); pnlAlign.add(btnLeft); pnlAlign.add(btnCenter); pnlAlign.add(btnRight); ImageIcon image = new ImageIcon("image.gif"); width = image.getIconWidth(); height = image.getIconHeight(); lblEikona = new JLabel(image); pnlEikona.add(lblEikona); pnlKentriko.add(pnlAlign); pnlKentriko.add(pnlEikona); pnlKentriko.add(pnlSizes); add(pnlKentriko); setVisible(true); } public void actionPerformed(ActionEvent e) { if ("alignleft".equals(e.getActionCommand())) { pnlEikona.setLayout(new FlowLayout(FlowLayout.LEFT)); pnlEikona.revalidate(); validate(); repaint(); } else if ("aligncenter".equals(e.getActionCommand())) { pnlEikona.setLayout(new FlowLayout(FlowLayout.CENTER)); pnlEikona.revalidate(); validate(); repaint(); } else if ("alignright".equals(e.getActionCommand())) { pnlEikona.setLayout(new FlowLayout(FlowLayout.RIGHT)); pnlEikona.revalidate(); validate(); repaint(); } else if ("resize".equals(e.getActionCommand())) { lblEikona.setPreferredSize(new Dimension(Integer.parseInt(txtSizeW.getText()), Integer.parseInt(txtSizeH.getText()))); pnlEikona.revalidate(); validate(); repaint(); } else if ("reset".equals(e.getActionCommand())) { lblEikona.setPreferredSize(new Dimension( width, height)); pnlEikona.revalidate(); validate(); repaint(); } } public static void Main (String[] args) { ImageApp ia = new ImageApp(); } }
monopatis/CEID
2nd Semester/Java/set3/ImageApp.java
1,091
// Η super σε εφαρμογές JFrame δίνει τίτλο στο παράθυρο
line_comment
el
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ImageApp extends JFrame implements ActionListener { JPanel kentriko; JMenuBar menubar; JMenu optionsMenu; JMenuItem resetMenuItem; JPanel pnlKentriko; JPanel pnlEikona; JPanel pnlAlign; JPanel pnlSizes; JPanel pnlSizeW; JPanel pnlSizeH; JButton btnLeft; JButton btnCenter; JButton btnRight; JLabel lblEikona; JLabel lblSizeW; JLabel lblSizeH; JTextField txtSizeW; JTextField txtSizeH; JButton btnResize; int width; int height; public ImageApp() { // Η super<SUF> super("Image Application"); // Θέλουμε η εφαρμογή να ολοκληρώνει την εκτέλεσή της με το κλείσιμο // του παραθύρου setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400,400); menubar = new JMenuBar(); optionsMenu = new JMenu("Options"); resetMenuItem = new JMenuItem("Reset"); resetMenuItem.setActionCommand("reset"); resetMenuItem.addActionListener(this); optionsMenu.add(resetMenuItem); menubar.add(optionsMenu); setJMenuBar(menubar); pnlKentriko = new JPanel(); pnlKentriko.setLayout(new BoxLayout(pnlKentriko, BoxLayout.PAGE_AXIS)); pnlAlign = new JPanel(new GridLayout(1,3)); pnlEikona = new JPanel(); pnlEikona.setLayout(new FlowLayout(FlowLayout.CENTER)); pnlSizes = new JPanel(new GridLayout(3,2)); lblSizeW = new JLabel("Width"); txtSizeW = new JTextField(); lblSizeH = new JLabel("Height"); txtSizeH = new JTextField(); btnResize = new JButton("Resize"); btnResize.setActionCommand("resize"); btnResize.addActionListener(this); pnlSizes.add(lblSizeW); pnlSizes.add(txtSizeW); pnlSizes.add(lblSizeH); pnlSizes.add(txtSizeH); pnlSizes.add(btnResize); btnLeft = new JButton("Align Left"); btnLeft.setActionCommand("alignleft"); btnLeft.addActionListener(this); btnCenter = new JButton("Align Center"); btnCenter.setActionCommand("aligncenter"); btnCenter.addActionListener(this); btnRight = new JButton("Align Right"); btnRight.setActionCommand("alignright"); btnRight.addActionListener(this); pnlAlign.add(btnLeft); pnlAlign.add(btnCenter); pnlAlign.add(btnRight); ImageIcon image = new ImageIcon("image.gif"); width = image.getIconWidth(); height = image.getIconHeight(); lblEikona = new JLabel(image); pnlEikona.add(lblEikona); pnlKentriko.add(pnlAlign); pnlKentriko.add(pnlEikona); pnlKentriko.add(pnlSizes); add(pnlKentriko); setVisible(true); } public void actionPerformed(ActionEvent e) { if ("alignleft".equals(e.getActionCommand())) { pnlEikona.setLayout(new FlowLayout(FlowLayout.LEFT)); pnlEikona.revalidate(); validate(); repaint(); } else if ("aligncenter".equals(e.getActionCommand())) { pnlEikona.setLayout(new FlowLayout(FlowLayout.CENTER)); pnlEikona.revalidate(); validate(); repaint(); } else if ("alignright".equals(e.getActionCommand())) { pnlEikona.setLayout(new FlowLayout(FlowLayout.RIGHT)); pnlEikona.revalidate(); validate(); repaint(); } else if ("resize".equals(e.getActionCommand())) { lblEikona.setPreferredSize(new Dimension(Integer.parseInt(txtSizeW.getText()), Integer.parseInt(txtSizeH.getText()))); pnlEikona.revalidate(); validate(); repaint(); } else if ("reset".equals(e.getActionCommand())) { lblEikona.setPreferredSize(new Dimension( width, height)); pnlEikona.revalidate(); validate(); repaint(); } } public static void Main (String[] args) { ImageApp ia = new ImageApp(); } }
5580_17
package cy.ac.ucy.cs.epl231.ID911719.Lab03; import cy.ac.ucy.cs.epl231.ID911719.Lab03.ArrayQueue; import cy.ac.ucy.cs.epl231.ID911719.Lab03.Queue; import cy.ac.ucy.cs.epl231.ID911719.Lab03.QueueEmptyException; import cy.ac.ucy.cs.epl231.ID911719.Lab03.QueueFullException; public class ArrayQueue<E> implements Queue<E> { // Υλοποίηση της Java διασύνδεσης Queue (από το Σχήμα 2.4) με πίνακα // σταθερού μήκους // Μεταβλητές στιγμιοτύπου public static final int MAXSIZE = 10000; // Το προκαθορισμένο μέγιστο μήκος // ουράς private E[] T; // Ο γενικευμένος πίνακας T όπου θα κρατούνται τα στοιχεία // της ουράς private int f = 0; // Δείκτης στον κόμβο κορυφής της ουράς private int sz = 0; // Το τρέχον μήκος της ουράς // Κατασκευαστές public ArrayQueue() { // Αρχικοποίηση ουράς με προκαθορισμένο μέγιστο μήκος this(MAXSIZE); } public ArrayQueue(int MaxSize) { // Αρχικοποίηση ουράς με δεδομένο μέγιστο // μήκος T = (E[]) new Object[MaxSize]; } // Μέθοδοι public int size() { // Επιστρέφει το τρέχον μήκος της ουράς return sz; } public boolean isEmpty() { // Επιστρέφει true αν και μόνο αν η ουρά είναι // κενή return (sz == 0); } public void enqueue(E obj) // Εισαγωγή νέου αντικειμένου στην ουρά throws QueueFullException { if (sz == T.length) throw new QueueFullException("Γέμισε η ουρά"); int avail = (f + sz) % T.length; T[avail] = obj; sz++; } public E front() // Επιστροφή αντικειμένου από την ουρά throws QueueEmptyException { if (isEmpty()) throw new QueueEmptyException("Η ουρά είναι κενή"); return T[f]; } public E dequeue() // Επιστροφή και διαγραφή αντικειμένου από την ουρά throws QueueEmptyException { if (isEmpty()) throw new QueueEmptyException("Η ουρά είναι κενή"); E answer = T[f]; T[f] = null; f = (f + 1) % T.length; sz--; return answer; } public static void main(String[] args) { // TODO Auto-generated method stub // Παράδειγμα Χρήσης της στοίβας Queue<Integer> Q = new ArrayQueue<>(); // Περιέχει: () try { Q.enqueue(5); // Περιέχει: (5) Q.enqueue(3); // Περιέχει: (5, 3) System.out.println(Q.size()); // Περιέχει: (5, 3) Δίνει 2 System.out.println(Q.dequeue()); // Περιέχει: (3) Εξάγει 5 System.out.println(Q.isEmpty()); // Περιέχει: (3) Δίνει false System.out.println(Q.dequeue()); // Περιέχει: () Εξάγει 3 System.out.println(Q.isEmpty()); // Περιέχει: () Εξάγει true // System.out.println(Q.dequeue()); // Περιέχει: () Exception Q.enqueue(7); // Περιέχει: (7) Q.enqueue(9); // Περιέχει: (7, 9) System.out.println(Q.front()); // Περιέχει: (7, 9) Δίνει 7 Q.enqueue(4); // Περιέχει: (7, 9, 4) System.out.println(Q.size()); // Περιέχει: (7, 9, 4) Εξάγει 3 System.out.println(Q.dequeue()); // Περιέχει: (9, 4) Εξάγει 7 Q.enqueue(6); // Περιέχει: (9, 4 6) Q.enqueue(8); // Περιέχει: (9, 4, 6, 8) System.out.println(Q.dequeue()); // Περιέχει: (4, 6, 8) Εξάγει 9 } catch (QueueEmptyException e) { System.out.println(e); } catch (QueueFullException ee) { System.out.println(ee); } } }
mpafit02/cs231---Data-Structures-and-Algorithms---Java
Lab03/src/cy/ac/ucy/cs/epl231/ID911719/Lab03/ArrayQueue.java
1,754
// Περιέχει: (3) Δίνει false
line_comment
el
package cy.ac.ucy.cs.epl231.ID911719.Lab03; import cy.ac.ucy.cs.epl231.ID911719.Lab03.ArrayQueue; import cy.ac.ucy.cs.epl231.ID911719.Lab03.Queue; import cy.ac.ucy.cs.epl231.ID911719.Lab03.QueueEmptyException; import cy.ac.ucy.cs.epl231.ID911719.Lab03.QueueFullException; public class ArrayQueue<E> implements Queue<E> { // Υλοποίηση της Java διασύνδεσης Queue (από το Σχήμα 2.4) με πίνακα // σταθερού μήκους // Μεταβλητές στιγμιοτύπου public static final int MAXSIZE = 10000; // Το προκαθορισμένο μέγιστο μήκος // ουράς private E[] T; // Ο γενικευμένος πίνακας T όπου θα κρατούνται τα στοιχεία // της ουράς private int f = 0; // Δείκτης στον κόμβο κορυφής της ουράς private int sz = 0; // Το τρέχον μήκος της ουράς // Κατασκευαστές public ArrayQueue() { // Αρχικοποίηση ουράς με προκαθορισμένο μέγιστο μήκος this(MAXSIZE); } public ArrayQueue(int MaxSize) { // Αρχικοποίηση ουράς με δεδομένο μέγιστο // μήκος T = (E[]) new Object[MaxSize]; } // Μέθοδοι public int size() { // Επιστρέφει το τρέχον μήκος της ουράς return sz; } public boolean isEmpty() { // Επιστρέφει true αν και μόνο αν η ουρά είναι // κενή return (sz == 0); } public void enqueue(E obj) // Εισαγωγή νέου αντικειμένου στην ουρά throws QueueFullException { if (sz == T.length) throw new QueueFullException("Γέμισε η ουρά"); int avail = (f + sz) % T.length; T[avail] = obj; sz++; } public E front() // Επιστροφή αντικειμένου από την ουρά throws QueueEmptyException { if (isEmpty()) throw new QueueEmptyException("Η ουρά είναι κενή"); return T[f]; } public E dequeue() // Επιστροφή και διαγραφή αντικειμένου από την ουρά throws QueueEmptyException { if (isEmpty()) throw new QueueEmptyException("Η ουρά είναι κενή"); E answer = T[f]; T[f] = null; f = (f + 1) % T.length; sz--; return answer; } public static void main(String[] args) { // TODO Auto-generated method stub // Παράδειγμα Χρήσης της στοίβας Queue<Integer> Q = new ArrayQueue<>(); // Περιέχει: () try { Q.enqueue(5); // Περιέχει: (5) Q.enqueue(3); // Περιέχει: (5, 3) System.out.println(Q.size()); // Περιέχει: (5, 3) Δίνει 2 System.out.println(Q.dequeue()); // Περιέχει: (3) Εξάγει 5 System.out.println(Q.isEmpty()); // Περιέχει: (3)<SUF> System.out.println(Q.dequeue()); // Περιέχει: () Εξάγει 3 System.out.println(Q.isEmpty()); // Περιέχει: () Εξάγει true // System.out.println(Q.dequeue()); // Περιέχει: () Exception Q.enqueue(7); // Περιέχει: (7) Q.enqueue(9); // Περιέχει: (7, 9) System.out.println(Q.front()); // Περιέχει: (7, 9) Δίνει 7 Q.enqueue(4); // Περιέχει: (7, 9, 4) System.out.println(Q.size()); // Περιέχει: (7, 9, 4) Εξάγει 3 System.out.println(Q.dequeue()); // Περιέχει: (9, 4) Εξάγει 7 Q.enqueue(6); // Περιέχει: (9, 4 6) Q.enqueue(8); // Περιέχει: (9, 4, 6, 8) System.out.println(Q.dequeue()); // Περιέχει: (4, 6, 8) Εξάγει 9 } catch (QueueEmptyException e) { System.out.println(e); } catch (QueueFullException ee) { System.out.println(ee); } } }
26153_11
package ilearnrw.languagetools.greek; /* * Copyright (c) 2015, iLearnRW. Licensed under Modified BSD Licence. See licence.txt for details. */ import java.util.ArrayList; import java.util.Iterator; public class GreekSyllabification implements Speller{ private String stringToSpell; private ArrayList<String> vowels; private ArrayList<String> consonants; private ArrayList<String> nonSeperable; private ArrayList<String> strongNonSeperable; private ArrayList<String> greekPrefixes; private ArrayList<String> result; private char[] lowerCase = {'α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η', 'θ', 'ι', 'κ', 'λ', 'μ', 'ν', 'ξ', 'ο', 'π', 'ρ', 'σ', 'τ', 'υ', 'φ', 'χ', 'ψ', 'ω', 'ά', 'έ', 'ή', 'ί', 'ό', 'ύ', 'ώ', 'ϊ', 'ϋ', 'ΐ','ΰ', 'ς'}; private char[] upperCase = {'Α', 'Β', 'Γ', 'Δ', 'Ε', 'Ζ', 'Η', 'Θ', 'Ι', 'Κ', 'Λ', 'Μ', 'Ν', 'Ξ', 'Ο', 'Π', 'Ρ', 'Σ', 'Τ', 'Υ', 'Φ', 'Χ', 'Ψ', 'Ω', 'Ά', 'Έ', 'Ή', 'Ί', 'Ό', 'Ύ', 'Ώ', 'Ϊ', 'Ϋ' }; private int[] converter; /** Creates a new instance of GreekSpeller */ public GreekSyllabification() { this(""); } /** Creates a new instance of GreekSpeller */ public GreekSyllabification(String stringToSpell) { this.stringToSpell = preprocess(stringToSpell); this.vowels = new ArrayList<String>(); this.consonants = new ArrayList<String>(); this.nonSeperable = new ArrayList<String>(); this.strongNonSeperable = new ArrayList<String>(); this.greekPrefixes = new ArrayList<String>(); this.result = new ArrayList<String>(); this.initLists(); } /** * Sets the string to spell. */ public void setStringToSpell(String stringToSpell) { this.stringToSpell = preprocess(stringToSpell); } /** * Performs a spelling operation. */ public void performSpelling() { /** Reset **/ this.reset(); this.result.add(this.stringToSpell); this.splitSyllables(0); this.postprocess(result); //System.err.println(this.stringToSpell + " == " +result.toString()); } private void splitSyllables(int i){ if (this.result.size() <= i) return; ArrayList<String> res; res = vowelsRule(this.result.get(i));//lastFirstRule(this.result.get(i)); check(res, i); res = firstRule(this.result.get(i)); check(res, i); res = secondRule(this.result.get(i)); check(res, i); res = thirdRule(this.result.get(i)); check(res, i); splitSyllables(i+1); } private void check(ArrayList<String> res, int i){ if (res.size() >1){ result.remove(i); result.add(i, res.remove(0)); result.add(i+1, res.remove(0)); } } private ArrayList<String> firstRule(String str){ for (int i=0; i<str.length()-2; i++){ if (this.vowels.contains(""+str.charAt(i)) && this.consonants.contains(""+str.charAt(i+1)) && this.vowels.contains(""+str.charAt(i+2))){ String str1 = str.substring(0, i+1); String str2 = str.substring(i+1); ArrayList<String> l1 = new ArrayList<String>(); l1.add(str1); l1.add(str2); return l1; } } ArrayList<String> l = new ArrayList<String>(); l.add(str); return l; } private ArrayList<String> secondRule(String str){ for (int i=0; i<str.length()-3; i++){ if (this.vowels.contains(""+str.charAt(i)) && this.vowels.contains(""+str.charAt(i+3)) && this.consonants.contains(""+str.charAt(i+1)) && this.consonants.contains(""+str.charAt(i+2))){ if (greekPrefixes.contains(str.substring(i+1, i+3))){ String str1 = str.substring(0, i+1); String str2 = str.substring(i+1); ArrayList<String> l1 = new ArrayList<String>(); l1.add(str1); l1.add(str2); return l1; } else { String str1 = str.substring(0, i+2); String str2 = str.substring(i+2); ArrayList<String> l1 = new ArrayList<String>(); l1.add(str1); l1.add(str2); return l1; } } } ArrayList<String> l = new ArrayList<String>(); l.add(str); return l; } private ArrayList<String> thirdRule(String str){ for (int i=0; i<str.length()-2; i++){ if (this.vowels.contains(""+str.charAt(i))) { int j = i+1; while (j<str.length() && this.consonants.contains(""+str.charAt(j))) j++; if (j<str.length() && j-i>3 && this.vowels.contains(""+str.charAt(j))){ if (greekPrefixes.contains(str.substring(i+1, i+3))){ String str1 = str.substring(0, i+1); String str2 = str.substring(i+1); ArrayList<String> l1 = new ArrayList<String>(); l1.add(str1); l1.add(str2); return l1; } else { String str1 = str.substring(0, i+2); String str2 = str.substring(i+2); ArrayList<String> l1 = new ArrayList<String>(); l1.add(str1); l1.add(str2); return l1; } } } } ArrayList<String> l = new ArrayList<String>(); l.add(str); return l; } private ArrayList<String> vowelsRule(String str){ for (int i=0; i<str.length()-1; i++){ int j = i; while (j<str.length() && this.vowels.contains(""+str.charAt(j))) j++; if (j>i){ int idx = multipleVowels(str.substring(i, j)); if (idx > 0){ String str1 = str.substring(0, i+idx); String str2 = str.substring(i+idx); ArrayList<String> l1 = new ArrayList<String>(); l1.add(str1); l1.add(str2); return l1; } } } ArrayList<String> l = new ArrayList<String>(); l.add(str); return l; } private ArrayList<String> lastFirstRule(String str){ for (int i=0; i<str.length()-1; i++){ // vvvv if (i<str.length()-3 && this.vowels.contains(""+str.charAt(i)) && this.vowels.contains(""+str.charAt(i+1)) && this.vowels.contains(""+str.charAt(i+2)) && this.vowels.contains(""+str.charAt(i+3)) && this.nonSeperable.contains(str.substring(i, i+2)) && this.nonSeperable.contains(str.substring(i+2, i+4)) && !this.nonSeperable.contains(str.substring(i, i+4)) && !this.nonSeperable.contains(str.substring(i, i+3)) && !this.nonSeperable.contains(str.substring(i+1, i+4))){ String str1 = str.substring(0, i+2); String str2 = str.substring(i+2); ArrayList<String> l1 = new ArrayList<String>(); l1.add(str1); l1.add(str2); return l1; } // vvv if (i<str.length()-2 && this.vowels.contains(""+str.charAt(i)) && this.vowels.contains(""+str.charAt(i+1)) && this.vowels.contains(""+str.charAt(i+2)) && this.nonSeperable.contains(str.substring(i, i+2)) && !this.nonSeperable.contains(str.substring(i, i+3))){ String str1 = str.substring(0, i+2); String str2 = str.substring(i+2); ArrayList<String> l1 = new ArrayList<String>(); l1.add(str1); l1.add(str2); return l1; } // vvv if (i<str.length()-2 && this.vowels.contains(""+str.charAt(i)) && this.vowels.contains(""+str.charAt(i+1)) && this.vowels.contains(""+str.charAt(i+2)) && !this.nonSeperable.contains(str.substring(i, i+2)) && !this.nonSeperable.contains(str.substring(i, i+3))){ String str1 = str.substring(0, i+1); String str2 = str.substring(i+1); ArrayList<String> l1 = new ArrayList<String>(); l1.add(str1); l1.add(str2); return l1; } // vv if (this.vowels.contains(""+str.charAt(i)) && this.vowels.contains(""+str.charAt(i+1)) && !this.nonSeperable.contains(str.substring(i, i+2))){ String str1 = str.substring(0, i+1); String str2 = str.substring(i+1); ArrayList<String> l1 = new ArrayList<String>(); l1.add(str1); l1.add(str2); return l1; } } ArrayList<String> l = new ArrayList<String>(); l.add(str); return l; } /* * @param a greek string contains only vowels * @return the first index that the string needs to be split (-1 if not exists) */ private int multipleVowels(String vv){ if (vv.length() <= 1) return -1; if (this.nonSeperable.contains(vv)) return -1; if (!this.nonSeperable.contains(vv) && vv.length() == 2) return 1; if (!this.nonSeperable.contains(vv.substring(0, vv.length()-1)) && this.nonSeperable.contains(1) && !strongNonSeperable.contains(vv.substring(0, 2))) return 1; else if (strongNonSeperable.contains(vv.substring(0, 2))) return 2; if (this.nonSeperable.contains(vv.substring(0, vv.length()-1)) && !this.nonSeperable.contains(1) && !strongNonSeperable.contains(vv.substring(vv.length()-2))) return multipleVowels(vv.substring(0, vv.length()-1)); else if (strongNonSeperable.contains(vv.substring(vv.length()-2))) return multipleVowels(vv.substring(0, vv.length()-2)) == -1?vv.length()-2:multipleVowels(vv.substring(0, vv.length()-2)); if (vv.substring(vv.length()-1).length()>1) return multipleVowels(vv.substring(0, vv.length()-1)); return -1; } /** * Returns the tokens of spelling. */ public ArrayList<String> getTokens(){ return this.result; } /** * Returns spelling tokens as String. */ public String toString(){ StringBuffer buffer = new StringBuffer(); for (Iterator<String> it = this.result.iterator(); it.hasNext(); ){ buffer.append(it.next()+ (it.hasNext()?"-":"")); } return buffer.toString(); } /** * Resets the required fields to perform a new spelling operation. */ private void reset() { this.result.clear(); } /** * Appropriately initiates the field lists... */ private void initLists(){ /* Vowels... */ this.vowels.add("α"); this.vowels.add("ε"); this.vowels.add("η"); this.vowels.add("ι"); this.vowels.add("ο"); this.vowels.add("υ"); this.vowels.add("ω"); this.vowels.add("ά"); this.vowels.add("έ"); this.vowels.add("ή"); this.vowels.add("ί"); this.vowels.add("ϊ"); this.vowels.add("ΐ"); this.vowels.add("ό"); this.vowels.add("ύ"); this.vowels.add("ϋ"); this.vowels.add("ΰ"); this.vowels.add("ώ"); /* Consonants... */ this.consonants.add("β"); this.consonants.add("γ"); this.consonants.add("δ"); this.consonants.add("ζ"); this.consonants.add("θ"); this.consonants.add("κ"); this.consonants.add("λ"); this.consonants.add("μ"); this.consonants.add("μ"); this.consonants.add("ν"); this.consonants.add("ξ"); this.consonants.add("π"); this.consonants.add("ρ"); this.consonants.add("σ"); this.consonants.add("τ"); this.consonants.add("φ"); this.consonants.add("χ"); this.consonants.add("ψ"); this.consonants.add("ς"); /*Two Digits Vowels...*/ this.strongNonSeperable.add("ου"); this.strongNonSeperable.add("ού"); this.strongNonSeperable.add("αι"); this.strongNonSeperable.add("αί"); this.strongNonSeperable.add("ει"); this.strongNonSeperable.add("εί"); this.strongNonSeperable.add("εϊ"); this.strongNonSeperable.add("οι"); this.strongNonSeperable.add("οί"); this.strongNonSeperable.add("υι"); this.strongNonSeperable.add("αϊ"); this.strongNonSeperable.add("άι"); this.strongNonSeperable.add("αη"); this.strongNonSeperable.add("οϊ"); this.strongNonSeperable.add("όι"); this.strongNonSeperable.add("οη"); this.strongNonSeperable.add("αυ"); this.strongNonSeperable.add("ευ"); this.strongNonSeperable.add("αύ"); this.strongNonSeperable.add("εύ"); /*Two Digits Vowels...*/ this.nonSeperable.add("ου"); this.nonSeperable.add("ού"); this.nonSeperable.add("αι"); this.nonSeperable.add("αί"); this.nonSeperable.add("ει"); this.nonSeperable.add("εί"); this.nonSeperable.add("εϊ"); this.nonSeperable.add("οι"); this.nonSeperable.add("οί"); this.nonSeperable.add("υι"); /*Two Digits Consonants...*/ this.nonSeperable.add("μπ"); this.nonSeperable.add("μπ"); this.nonSeperable.add("ντ"); this.nonSeperable.add("γκ"); this.nonSeperable.add("τσ"); this.nonSeperable.add("τζ"); /* Diphthongs... */ this.nonSeperable.add("αϊ"); this.nonSeperable.add("άι"); this.nonSeperable.add("αη"); this.nonSeperable.add("οϊ"); this.nonSeperable.add("όι"); this.nonSeperable.add("οη"); /* Combinations... */ this.nonSeperable.add("αυ"); this.nonSeperable.add("ευ"); this.nonSeperable.add("αύ"); this.nonSeperable.add("εύ"); /* Combinations... */ this.nonSeperable.add("ια"); this.nonSeperable.add("ιά"); this.nonSeperable.add("ειά"); this.nonSeperable.add("ιο"); //this.nonSeperable.add("ιό"); this.nonSeperable.add("υος"); this.nonSeperable.add("ιου"); // ι,υ,ει,οι+φωνήεν ή δίψηφο (ου, αι, ει, οι) this.nonSeperable.add("ια"); this.nonSeperable.add("ιά"); this.nonSeperable.add("ιε"); this.nonSeperable.add("ιέ"); this.nonSeperable.add("ιο"); this.nonSeperable.add("ιό"); this.nonSeperable.add("ιυ"); this.nonSeperable.add("ιύ"); this.nonSeperable.add("ιω"); this.nonSeperable.add("ιώ"); this.nonSeperable.add("υα"); this.nonSeperable.add("υά"); this.nonSeperable.add("υε"); this.nonSeperable.add("υέ"); this.nonSeperable.add("υη"); this.nonSeperable.add("υή"); this.nonSeperable.add("υι"); this.nonSeperable.add("υί"); this.nonSeperable.add("υο"); this.nonSeperable.add("υό"); this.nonSeperable.add("υω"); this.nonSeperable.add("υώ"); this.nonSeperable.add("εια"); this.nonSeperable.add("ειά"); this.nonSeperable.add("ειέ"); this.nonSeperable.add("ειή"); this.nonSeperable.add("ειό"); this.nonSeperable.add("ειύ"); this.nonSeperable.add("ειώ"); this.nonSeperable.add("οια"); this.nonSeperable.add("οιέ"); this.nonSeperable.add("οιή"); this.nonSeperable.add("οιό"); this.nonSeperable.add("οιο"); this.nonSeperable.add("οιυ"); this.nonSeperable.add("οιύ"); this.nonSeperable.add("ιου"); this.nonSeperable.add("ιού"); this.nonSeperable.add("ιαι"); this.nonSeperable.add("ιαί"); this.nonSeperable.add("ιει"); this.nonSeperable.add("ιεί"); this.nonSeperable.add("ιοι"); this.nonSeperable.add("ιοί"); this.nonSeperable.add("υου"); this.nonSeperable.add("υού"); this.nonSeperable.add("υαι"); this.nonSeperable.add("υαί"); this.nonSeperable.add("υει"); this.nonSeperable.add("υεί"); this.nonSeperable.add("υοι"); this.nonSeperable.add("υοί"); this.nonSeperable.add("ειου"); this.nonSeperable.add("ειού"); this.nonSeperable.add("ειαι"); this.nonSeperable.add("ειαί"); this.nonSeperable.add("ειει"); this.nonSeperable.add("ειεί"); this.nonSeperable.add("ειοι"); this.nonSeperable.add("ειοί"); this.nonSeperable.add("οιου"); this.nonSeperable.add("οιού"); this.nonSeperable.add("οιαι"); this.nonSeperable.add("οιαί"); this.nonSeperable.add("οιει"); this.nonSeperable.add("οιεί"); this.nonSeperable.add("οιοι"); this.nonSeperable.add("οιοί"); this.nonSeperable.add("ι"); this.nonSeperable.add("υ"); this.nonSeperable.add("ει"); this.nonSeperable.add("οι"); /* Undues... */ //this.nonSeperable.add("ι"); //this.nonSeperable.add("υ"); //this.nonSeperable.add("οι"); //this.nonSeperable.add("ει"); /* Two Consonants that a greek word can start */ this.greekPrefixes.add("βγ"); this.greekPrefixes.add("βδ"); this.greekPrefixes.add("βλ"); this.greekPrefixes.add("βρ"); this.greekPrefixes.add("γδ"); this.greekPrefixes.add("γκ"); this.greekPrefixes.add("γλ"); this.greekPrefixes.add("γν"); this.greekPrefixes.add("γρ"); this.greekPrefixes.add("δρ"); this.greekPrefixes.add("θλ"); this.greekPrefixes.add("θν"); this.greekPrefixes.add("θρ"); this.greekPrefixes.add("κβ"); this.greekPrefixes.add("κλ"); this.greekPrefixes.add("κν"); this.greekPrefixes.add("κρ"); this.greekPrefixes.add("κτ"); this.greekPrefixes.add("μν"); this.greekPrefixes.add("μπ"); this.greekPrefixes.add("ντ"); this.greekPrefixes.add("πλ"); this.greekPrefixes.add("πν"); this.greekPrefixes.add("πρ"); this.greekPrefixes.add("σβ"); this.greekPrefixes.add("σγ"); this.greekPrefixes.add("σθ"); this.greekPrefixes.add("σκ"); this.greekPrefixes.add("σλ"); this.greekPrefixes.add("σμ"); this.greekPrefixes.add("σμ"); this.greekPrefixes.add("σν"); this.greekPrefixes.add("σπ"); this.greekPrefixes.add("στ"); this.greekPrefixes.add("σφ"); this.greekPrefixes.add("σχ"); this.greekPrefixes.add("τζ"); this.greekPrefixes.add("τμ"); this.greekPrefixes.add("τμ"); this.greekPrefixes.add("τρ"); this.greekPrefixes.add("τσ"); this.greekPrefixes.add("φθ"); this.greekPrefixes.add("φλ"); this.greekPrefixes.add("φρ"); this.greekPrefixes.add("φτ"); this.greekPrefixes.add("χθ"); this.greekPrefixes.add("χλ"); this.greekPrefixes.add("χν"); this.greekPrefixes.add("χρ"); this.greekPrefixes.add("χτ"); this.greekPrefixes.add("θρ"); } /** * Returns the hyphen syllable * @param tokens * @return */ public String getHyphenSyllable(ArrayList<String> tokens){ String hyphenSyllable = ""; for (Iterator<String> it = tokens.iterator(); it.hasNext();){ hyphenSyllable = it.next(); if (hyphenSyllable.contains("ά") || hyphenSyllable.contains("έ") || hyphenSyllable.contains("ή") || hyphenSyllable.contains("ί") || hyphenSyllable.contains("ό") || hyphenSyllable.contains("ύ") || hyphenSyllable.contains("ώ") || hyphenSyllable.contains("ΐ") || hyphenSyllable.contains("ΰ") || hyphenSyllable.contains("Ά") || hyphenSyllable.contains("Έ") || hyphenSyllable.contains("Ή") || hyphenSyllable.contains("Ί") || hyphenSyllable.contains("Ό") || hyphenSyllable.contains("Ύ") || hyphenSyllable.contains("Ώ")) { return hyphenSyllable; } } return ""; } @Override public int getTokensNumber() { return result.size(); } @Override public String getToken(int index) { if (index<0 || index>this.getTokensNumber()) return null; else return result.get(index); } @Override public String[] getTokensArray() { String res[] = new String[getTokensNumber()]; for (int i=0;i<res.length;i++){ res[i] = getToken(i); } return res; } /** * To lowerCase */ private String preprocess(String str) { String lowerCaseString = str; this.converter = new int[str.length()]; for (int i=0; i<str.length(); i++){ int position = this.positionOf(this.upperCase, str.charAt(i)); if (position != -1) { if(i==str.length()-1 && str.charAt(i)=='ς'){ lowerCaseString = lowerCaseString.replace(str.charAt(i),'Σ'); } else { lowerCaseString = lowerCaseString.replace(str.charAt(i),this.lowerCase[position]); } this.converter[i] = 1; } } return lowerCaseString; } private void postprocess(ArrayList<String> result) { int counter = 0; for (int i=0; i<this.result.size(); i++){ String token = this.result.get(i); for (int j=0; j<token.length(); j++) { if (this.converter[counter]==1){ char c = token.charAt(j); int position = this.positionOf(this.lowerCase, c); char replaceChar = this.upperCase[position]; token = token.substring(0, j) + replaceChar + token.substring(j+1, token.length()); this.result.set(i, token); } counter++; } } } private int positionOf(char[] array, char checkChar) { for (int i = 0; i < array.length; i++){ if (array[i] == checkChar) return i; } return -1; } }
mpakarlsson/ilearnrw
src/ilearnrw/languagetools/greek/GreekSyllabification.java
7,563
// ι,υ,ει,οι+φωνήεν ή δίψηφο (ου, αι, ει, οι)
line_comment
el
package ilearnrw.languagetools.greek; /* * Copyright (c) 2015, iLearnRW. Licensed under Modified BSD Licence. See licence.txt for details. */ import java.util.ArrayList; import java.util.Iterator; public class GreekSyllabification implements Speller{ private String stringToSpell; private ArrayList<String> vowels; private ArrayList<String> consonants; private ArrayList<String> nonSeperable; private ArrayList<String> strongNonSeperable; private ArrayList<String> greekPrefixes; private ArrayList<String> result; private char[] lowerCase = {'α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η', 'θ', 'ι', 'κ', 'λ', 'μ', 'ν', 'ξ', 'ο', 'π', 'ρ', 'σ', 'τ', 'υ', 'φ', 'χ', 'ψ', 'ω', 'ά', 'έ', 'ή', 'ί', 'ό', 'ύ', 'ώ', 'ϊ', 'ϋ', 'ΐ','ΰ', 'ς'}; private char[] upperCase = {'Α', 'Β', 'Γ', 'Δ', 'Ε', 'Ζ', 'Η', 'Θ', 'Ι', 'Κ', 'Λ', 'Μ', 'Ν', 'Ξ', 'Ο', 'Π', 'Ρ', 'Σ', 'Τ', 'Υ', 'Φ', 'Χ', 'Ψ', 'Ω', 'Ά', 'Έ', 'Ή', 'Ί', 'Ό', 'Ύ', 'Ώ', 'Ϊ', 'Ϋ' }; private int[] converter; /** Creates a new instance of GreekSpeller */ public GreekSyllabification() { this(""); } /** Creates a new instance of GreekSpeller */ public GreekSyllabification(String stringToSpell) { this.stringToSpell = preprocess(stringToSpell); this.vowels = new ArrayList<String>(); this.consonants = new ArrayList<String>(); this.nonSeperable = new ArrayList<String>(); this.strongNonSeperable = new ArrayList<String>(); this.greekPrefixes = new ArrayList<String>(); this.result = new ArrayList<String>(); this.initLists(); } /** * Sets the string to spell. */ public void setStringToSpell(String stringToSpell) { this.stringToSpell = preprocess(stringToSpell); } /** * Performs a spelling operation. */ public void performSpelling() { /** Reset **/ this.reset(); this.result.add(this.stringToSpell); this.splitSyllables(0); this.postprocess(result); //System.err.println(this.stringToSpell + " == " +result.toString()); } private void splitSyllables(int i){ if (this.result.size() <= i) return; ArrayList<String> res; res = vowelsRule(this.result.get(i));//lastFirstRule(this.result.get(i)); check(res, i); res = firstRule(this.result.get(i)); check(res, i); res = secondRule(this.result.get(i)); check(res, i); res = thirdRule(this.result.get(i)); check(res, i); splitSyllables(i+1); } private void check(ArrayList<String> res, int i){ if (res.size() >1){ result.remove(i); result.add(i, res.remove(0)); result.add(i+1, res.remove(0)); } } private ArrayList<String> firstRule(String str){ for (int i=0; i<str.length()-2; i++){ if (this.vowels.contains(""+str.charAt(i)) && this.consonants.contains(""+str.charAt(i+1)) && this.vowels.contains(""+str.charAt(i+2))){ String str1 = str.substring(0, i+1); String str2 = str.substring(i+1); ArrayList<String> l1 = new ArrayList<String>(); l1.add(str1); l1.add(str2); return l1; } } ArrayList<String> l = new ArrayList<String>(); l.add(str); return l; } private ArrayList<String> secondRule(String str){ for (int i=0; i<str.length()-3; i++){ if (this.vowels.contains(""+str.charAt(i)) && this.vowels.contains(""+str.charAt(i+3)) && this.consonants.contains(""+str.charAt(i+1)) && this.consonants.contains(""+str.charAt(i+2))){ if (greekPrefixes.contains(str.substring(i+1, i+3))){ String str1 = str.substring(0, i+1); String str2 = str.substring(i+1); ArrayList<String> l1 = new ArrayList<String>(); l1.add(str1); l1.add(str2); return l1; } else { String str1 = str.substring(0, i+2); String str2 = str.substring(i+2); ArrayList<String> l1 = new ArrayList<String>(); l1.add(str1); l1.add(str2); return l1; } } } ArrayList<String> l = new ArrayList<String>(); l.add(str); return l; } private ArrayList<String> thirdRule(String str){ for (int i=0; i<str.length()-2; i++){ if (this.vowels.contains(""+str.charAt(i))) { int j = i+1; while (j<str.length() && this.consonants.contains(""+str.charAt(j))) j++; if (j<str.length() && j-i>3 && this.vowels.contains(""+str.charAt(j))){ if (greekPrefixes.contains(str.substring(i+1, i+3))){ String str1 = str.substring(0, i+1); String str2 = str.substring(i+1); ArrayList<String> l1 = new ArrayList<String>(); l1.add(str1); l1.add(str2); return l1; } else { String str1 = str.substring(0, i+2); String str2 = str.substring(i+2); ArrayList<String> l1 = new ArrayList<String>(); l1.add(str1); l1.add(str2); return l1; } } } } ArrayList<String> l = new ArrayList<String>(); l.add(str); return l; } private ArrayList<String> vowelsRule(String str){ for (int i=0; i<str.length()-1; i++){ int j = i; while (j<str.length() && this.vowels.contains(""+str.charAt(j))) j++; if (j>i){ int idx = multipleVowels(str.substring(i, j)); if (idx > 0){ String str1 = str.substring(0, i+idx); String str2 = str.substring(i+idx); ArrayList<String> l1 = new ArrayList<String>(); l1.add(str1); l1.add(str2); return l1; } } } ArrayList<String> l = new ArrayList<String>(); l.add(str); return l; } private ArrayList<String> lastFirstRule(String str){ for (int i=0; i<str.length()-1; i++){ // vvvv if (i<str.length()-3 && this.vowels.contains(""+str.charAt(i)) && this.vowels.contains(""+str.charAt(i+1)) && this.vowels.contains(""+str.charAt(i+2)) && this.vowels.contains(""+str.charAt(i+3)) && this.nonSeperable.contains(str.substring(i, i+2)) && this.nonSeperable.contains(str.substring(i+2, i+4)) && !this.nonSeperable.contains(str.substring(i, i+4)) && !this.nonSeperable.contains(str.substring(i, i+3)) && !this.nonSeperable.contains(str.substring(i+1, i+4))){ String str1 = str.substring(0, i+2); String str2 = str.substring(i+2); ArrayList<String> l1 = new ArrayList<String>(); l1.add(str1); l1.add(str2); return l1; } // vvv if (i<str.length()-2 && this.vowels.contains(""+str.charAt(i)) && this.vowels.contains(""+str.charAt(i+1)) && this.vowels.contains(""+str.charAt(i+2)) && this.nonSeperable.contains(str.substring(i, i+2)) && !this.nonSeperable.contains(str.substring(i, i+3))){ String str1 = str.substring(0, i+2); String str2 = str.substring(i+2); ArrayList<String> l1 = new ArrayList<String>(); l1.add(str1); l1.add(str2); return l1; } // vvv if (i<str.length()-2 && this.vowels.contains(""+str.charAt(i)) && this.vowels.contains(""+str.charAt(i+1)) && this.vowels.contains(""+str.charAt(i+2)) && !this.nonSeperable.contains(str.substring(i, i+2)) && !this.nonSeperable.contains(str.substring(i, i+3))){ String str1 = str.substring(0, i+1); String str2 = str.substring(i+1); ArrayList<String> l1 = new ArrayList<String>(); l1.add(str1); l1.add(str2); return l1; } // vv if (this.vowels.contains(""+str.charAt(i)) && this.vowels.contains(""+str.charAt(i+1)) && !this.nonSeperable.contains(str.substring(i, i+2))){ String str1 = str.substring(0, i+1); String str2 = str.substring(i+1); ArrayList<String> l1 = new ArrayList<String>(); l1.add(str1); l1.add(str2); return l1; } } ArrayList<String> l = new ArrayList<String>(); l.add(str); return l; } /* * @param a greek string contains only vowels * @return the first index that the string needs to be split (-1 if not exists) */ private int multipleVowels(String vv){ if (vv.length() <= 1) return -1; if (this.nonSeperable.contains(vv)) return -1; if (!this.nonSeperable.contains(vv) && vv.length() == 2) return 1; if (!this.nonSeperable.contains(vv.substring(0, vv.length()-1)) && this.nonSeperable.contains(1) && !strongNonSeperable.contains(vv.substring(0, 2))) return 1; else if (strongNonSeperable.contains(vv.substring(0, 2))) return 2; if (this.nonSeperable.contains(vv.substring(0, vv.length()-1)) && !this.nonSeperable.contains(1) && !strongNonSeperable.contains(vv.substring(vv.length()-2))) return multipleVowels(vv.substring(0, vv.length()-1)); else if (strongNonSeperable.contains(vv.substring(vv.length()-2))) return multipleVowels(vv.substring(0, vv.length()-2)) == -1?vv.length()-2:multipleVowels(vv.substring(0, vv.length()-2)); if (vv.substring(vv.length()-1).length()>1) return multipleVowels(vv.substring(0, vv.length()-1)); return -1; } /** * Returns the tokens of spelling. */ public ArrayList<String> getTokens(){ return this.result; } /** * Returns spelling tokens as String. */ public String toString(){ StringBuffer buffer = new StringBuffer(); for (Iterator<String> it = this.result.iterator(); it.hasNext(); ){ buffer.append(it.next()+ (it.hasNext()?"-":"")); } return buffer.toString(); } /** * Resets the required fields to perform a new spelling operation. */ private void reset() { this.result.clear(); } /** * Appropriately initiates the field lists... */ private void initLists(){ /* Vowels... */ this.vowels.add("α"); this.vowels.add("ε"); this.vowels.add("η"); this.vowels.add("ι"); this.vowels.add("ο"); this.vowels.add("υ"); this.vowels.add("ω"); this.vowels.add("ά"); this.vowels.add("έ"); this.vowels.add("ή"); this.vowels.add("ί"); this.vowels.add("ϊ"); this.vowels.add("ΐ"); this.vowels.add("ό"); this.vowels.add("ύ"); this.vowels.add("ϋ"); this.vowels.add("ΰ"); this.vowels.add("ώ"); /* Consonants... */ this.consonants.add("β"); this.consonants.add("γ"); this.consonants.add("δ"); this.consonants.add("ζ"); this.consonants.add("θ"); this.consonants.add("κ"); this.consonants.add("λ"); this.consonants.add("μ"); this.consonants.add("μ"); this.consonants.add("ν"); this.consonants.add("ξ"); this.consonants.add("π"); this.consonants.add("ρ"); this.consonants.add("σ"); this.consonants.add("τ"); this.consonants.add("φ"); this.consonants.add("χ"); this.consonants.add("ψ"); this.consonants.add("ς"); /*Two Digits Vowels...*/ this.strongNonSeperable.add("ου"); this.strongNonSeperable.add("ού"); this.strongNonSeperable.add("αι"); this.strongNonSeperable.add("αί"); this.strongNonSeperable.add("ει"); this.strongNonSeperable.add("εί"); this.strongNonSeperable.add("εϊ"); this.strongNonSeperable.add("οι"); this.strongNonSeperable.add("οί"); this.strongNonSeperable.add("υι"); this.strongNonSeperable.add("αϊ"); this.strongNonSeperable.add("άι"); this.strongNonSeperable.add("αη"); this.strongNonSeperable.add("οϊ"); this.strongNonSeperable.add("όι"); this.strongNonSeperable.add("οη"); this.strongNonSeperable.add("αυ"); this.strongNonSeperable.add("ευ"); this.strongNonSeperable.add("αύ"); this.strongNonSeperable.add("εύ"); /*Two Digits Vowels...*/ this.nonSeperable.add("ου"); this.nonSeperable.add("ού"); this.nonSeperable.add("αι"); this.nonSeperable.add("αί"); this.nonSeperable.add("ει"); this.nonSeperable.add("εί"); this.nonSeperable.add("εϊ"); this.nonSeperable.add("οι"); this.nonSeperable.add("οί"); this.nonSeperable.add("υι"); /*Two Digits Consonants...*/ this.nonSeperable.add("μπ"); this.nonSeperable.add("μπ"); this.nonSeperable.add("ντ"); this.nonSeperable.add("γκ"); this.nonSeperable.add("τσ"); this.nonSeperable.add("τζ"); /* Diphthongs... */ this.nonSeperable.add("αϊ"); this.nonSeperable.add("άι"); this.nonSeperable.add("αη"); this.nonSeperable.add("οϊ"); this.nonSeperable.add("όι"); this.nonSeperable.add("οη"); /* Combinations... */ this.nonSeperable.add("αυ"); this.nonSeperable.add("ευ"); this.nonSeperable.add("αύ"); this.nonSeperable.add("εύ"); /* Combinations... */ this.nonSeperable.add("ια"); this.nonSeperable.add("ιά"); this.nonSeperable.add("ειά"); this.nonSeperable.add("ιο"); //this.nonSeperable.add("ιό"); this.nonSeperable.add("υος"); this.nonSeperable.add("ιου"); // ι,υ,ει,οι+φωνήεν ή<SUF> this.nonSeperable.add("ια"); this.nonSeperable.add("ιά"); this.nonSeperable.add("ιε"); this.nonSeperable.add("ιέ"); this.nonSeperable.add("ιο"); this.nonSeperable.add("ιό"); this.nonSeperable.add("ιυ"); this.nonSeperable.add("ιύ"); this.nonSeperable.add("ιω"); this.nonSeperable.add("ιώ"); this.nonSeperable.add("υα"); this.nonSeperable.add("υά"); this.nonSeperable.add("υε"); this.nonSeperable.add("υέ"); this.nonSeperable.add("υη"); this.nonSeperable.add("υή"); this.nonSeperable.add("υι"); this.nonSeperable.add("υί"); this.nonSeperable.add("υο"); this.nonSeperable.add("υό"); this.nonSeperable.add("υω"); this.nonSeperable.add("υώ"); this.nonSeperable.add("εια"); this.nonSeperable.add("ειά"); this.nonSeperable.add("ειέ"); this.nonSeperable.add("ειή"); this.nonSeperable.add("ειό"); this.nonSeperable.add("ειύ"); this.nonSeperable.add("ειώ"); this.nonSeperable.add("οια"); this.nonSeperable.add("οιέ"); this.nonSeperable.add("οιή"); this.nonSeperable.add("οιό"); this.nonSeperable.add("οιο"); this.nonSeperable.add("οιυ"); this.nonSeperable.add("οιύ"); this.nonSeperable.add("ιου"); this.nonSeperable.add("ιού"); this.nonSeperable.add("ιαι"); this.nonSeperable.add("ιαί"); this.nonSeperable.add("ιει"); this.nonSeperable.add("ιεί"); this.nonSeperable.add("ιοι"); this.nonSeperable.add("ιοί"); this.nonSeperable.add("υου"); this.nonSeperable.add("υού"); this.nonSeperable.add("υαι"); this.nonSeperable.add("υαί"); this.nonSeperable.add("υει"); this.nonSeperable.add("υεί"); this.nonSeperable.add("υοι"); this.nonSeperable.add("υοί"); this.nonSeperable.add("ειου"); this.nonSeperable.add("ειού"); this.nonSeperable.add("ειαι"); this.nonSeperable.add("ειαί"); this.nonSeperable.add("ειει"); this.nonSeperable.add("ειεί"); this.nonSeperable.add("ειοι"); this.nonSeperable.add("ειοί"); this.nonSeperable.add("οιου"); this.nonSeperable.add("οιού"); this.nonSeperable.add("οιαι"); this.nonSeperable.add("οιαί"); this.nonSeperable.add("οιει"); this.nonSeperable.add("οιεί"); this.nonSeperable.add("οιοι"); this.nonSeperable.add("οιοί"); this.nonSeperable.add("ι"); this.nonSeperable.add("υ"); this.nonSeperable.add("ει"); this.nonSeperable.add("οι"); /* Undues... */ //this.nonSeperable.add("ι"); //this.nonSeperable.add("υ"); //this.nonSeperable.add("οι"); //this.nonSeperable.add("ει"); /* Two Consonants that a greek word can start */ this.greekPrefixes.add("βγ"); this.greekPrefixes.add("βδ"); this.greekPrefixes.add("βλ"); this.greekPrefixes.add("βρ"); this.greekPrefixes.add("γδ"); this.greekPrefixes.add("γκ"); this.greekPrefixes.add("γλ"); this.greekPrefixes.add("γν"); this.greekPrefixes.add("γρ"); this.greekPrefixes.add("δρ"); this.greekPrefixes.add("θλ"); this.greekPrefixes.add("θν"); this.greekPrefixes.add("θρ"); this.greekPrefixes.add("κβ"); this.greekPrefixes.add("κλ"); this.greekPrefixes.add("κν"); this.greekPrefixes.add("κρ"); this.greekPrefixes.add("κτ"); this.greekPrefixes.add("μν"); this.greekPrefixes.add("μπ"); this.greekPrefixes.add("ντ"); this.greekPrefixes.add("πλ"); this.greekPrefixes.add("πν"); this.greekPrefixes.add("πρ"); this.greekPrefixes.add("σβ"); this.greekPrefixes.add("σγ"); this.greekPrefixes.add("σθ"); this.greekPrefixes.add("σκ"); this.greekPrefixes.add("σλ"); this.greekPrefixes.add("σμ"); this.greekPrefixes.add("σμ"); this.greekPrefixes.add("σν"); this.greekPrefixes.add("σπ"); this.greekPrefixes.add("στ"); this.greekPrefixes.add("σφ"); this.greekPrefixes.add("σχ"); this.greekPrefixes.add("τζ"); this.greekPrefixes.add("τμ"); this.greekPrefixes.add("τμ"); this.greekPrefixes.add("τρ"); this.greekPrefixes.add("τσ"); this.greekPrefixes.add("φθ"); this.greekPrefixes.add("φλ"); this.greekPrefixes.add("φρ"); this.greekPrefixes.add("φτ"); this.greekPrefixes.add("χθ"); this.greekPrefixes.add("χλ"); this.greekPrefixes.add("χν"); this.greekPrefixes.add("χρ"); this.greekPrefixes.add("χτ"); this.greekPrefixes.add("θρ"); } /** * Returns the hyphen syllable * @param tokens * @return */ public String getHyphenSyllable(ArrayList<String> tokens){ String hyphenSyllable = ""; for (Iterator<String> it = tokens.iterator(); it.hasNext();){ hyphenSyllable = it.next(); if (hyphenSyllable.contains("ά") || hyphenSyllable.contains("έ") || hyphenSyllable.contains("ή") || hyphenSyllable.contains("ί") || hyphenSyllable.contains("ό") || hyphenSyllable.contains("ύ") || hyphenSyllable.contains("ώ") || hyphenSyllable.contains("ΐ") || hyphenSyllable.contains("ΰ") || hyphenSyllable.contains("Ά") || hyphenSyllable.contains("Έ") || hyphenSyllable.contains("Ή") || hyphenSyllable.contains("Ί") || hyphenSyllable.contains("Ό") || hyphenSyllable.contains("Ύ") || hyphenSyllable.contains("Ώ")) { return hyphenSyllable; } } return ""; } @Override public int getTokensNumber() { return result.size(); } @Override public String getToken(int index) { if (index<0 || index>this.getTokensNumber()) return null; else return result.get(index); } @Override public String[] getTokensArray() { String res[] = new String[getTokensNumber()]; for (int i=0;i<res.length;i++){ res[i] = getToken(i); } return res; } /** * To lowerCase */ private String preprocess(String str) { String lowerCaseString = str; this.converter = new int[str.length()]; for (int i=0; i<str.length(); i++){ int position = this.positionOf(this.upperCase, str.charAt(i)); if (position != -1) { if(i==str.length()-1 && str.charAt(i)=='ς'){ lowerCaseString = lowerCaseString.replace(str.charAt(i),'Σ'); } else { lowerCaseString = lowerCaseString.replace(str.charAt(i),this.lowerCase[position]); } this.converter[i] = 1; } } return lowerCaseString; } private void postprocess(ArrayList<String> result) { int counter = 0; for (int i=0; i<this.result.size(); i++){ String token = this.result.get(i); for (int j=0; j<token.length(); j++) { if (this.converter[counter]==1){ char c = token.charAt(j); int position = this.positionOf(this.lowerCase, c); char replaceChar = this.upperCase[position]; token = token.substring(0, j) + replaceChar + token.substring(j+1, token.length()); this.result.set(i, token); } counter++; } } } private int positionOf(char[] array, char checkChar) { for (int i = 0; i < array.length; i++){ if (array[i] == checkChar) return i; } return -1; } }
7758_1
package leitourgika_java; import java.util.LinkedList; public class ReadyProcessesList { private LinkedList<Process> processList;/* η λιστα που περιεχει τις ετοιμες διεργασιες */ public ReadyProcessesList() { processList = new LinkedList<Process>(); } /* προσθηκη μιας νεας ετοιμης διεργασιας στη λιστα*/ public void addProcess(Process item) { item.setProcessState(1);//1-->H diergasia einai Ready/Waiting processList.add(item); } /* επιστροφη της διεργασιας της οποιας η σειρα ειναι να εκτελεστει στη CPU σύμφωνα με τον εκαστοτε αλγόριθμο δρομολόγησης */ public Process getProcessToRunInCPU() { Process first = processList.get(0); processList.remove(); return first; } /* εκτύπωση του περιεχομενου της λίστας στην οθόνη */ public void printList() { int i = 0; System.out.println("ready diergasies:"); for (i = 0; i < processList.size(); i++) { System.out.println(processList.get(i).pid); } } public int getsize() { return processList.size(); } }
mpantogi/routine_scheduling
src/leitourgika_java/ReadyProcessesList.java
447
/* προσθηκη μιας νεας ετοιμης διεργασιας στη λιστα*/
block_comment
el
package leitourgika_java; import java.util.LinkedList; public class ReadyProcessesList { private LinkedList<Process> processList;/* η λιστα που περιεχει τις ετοιμες διεργασιες */ public ReadyProcessesList() { processList = new LinkedList<Process>(); } /* προσθηκη μιας νεας<SUF>*/ public void addProcess(Process item) { item.setProcessState(1);//1-->H diergasia einai Ready/Waiting processList.add(item); } /* επιστροφη της διεργασιας της οποιας η σειρα ειναι να εκτελεστει στη CPU σύμφωνα με τον εκαστοτε αλγόριθμο δρομολόγησης */ public Process getProcessToRunInCPU() { Process first = processList.get(0); processList.remove(); return first; } /* εκτύπωση του περιεχομενου της λίστας στην οθόνη */ public void printList() { int i = 0; System.out.println("ready diergasies:"); for (i = 0; i < processList.size(); i++) { System.out.println(processList.get(i).pid); } } public int getsize() { return processList.size(); } }
22081_1
package com.carpooling.controllers; import com.carpooling.dtos.Place; import com.carpooling.entities.Trip; import com.carpooling.entities.User; import com.carpooling.services.TripService; import com.carpooling.utils.TripUtils; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; import java.util.Date; import java.util.List; import static java.util.stream.Collectors.toList; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @Controller public class TripController { @Autowired TripService tripService; @Autowired TripUtils tripUtils; @RequestMapping(value = "/inserttrip", method = RequestMethod.GET) public String insertTrip(ModelMap mm) { Trip trip = new Trip(); mm.addAttribute("trip", trip); return "inserttrip"; } @RequestMapping(value = "/doinserttrip", method = RequestMethod.POST) public String doinsertTrip(ModelMap mm, @ModelAttribute("newtrip") Trip trip, @RequestParam("year") String year, @RequestParam("month") String month, @RequestParam("day") String day, @RequestParam("hour") String hour, @RequestParam("mins") String mins) { LocalDateTime ldt = LocalDateTime.of( Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day), Integer.parseInt(hour), Integer.parseInt(mins), 0); trip.setDate(Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant())); tripService.insert(trip); return "selectaride"; } @RequestMapping(value = "getalltrips", method = RequestMethod.GET) public String allTrips(ModelMap mm) { List<Trip> trips = tripService.findAllTrips() .stream() .filter((t) -> t.getAvailableseats() > 0) .collect(toList()); mm.put("trips", trips); return "alltrips"; } @RequestMapping(value = "/updatetrip/{id}", method = RequestMethod.GET) public String updateTrip(ModelMap mm, @PathVariable int id) { Trip oldtrip = tripService.findTripByID(id); Trip newtrip = new Trip(); mm.addAttribute("newtrip", newtrip); mm.addAttribute("oldtrip", oldtrip); return "updatetrip"; } @RequestMapping(value = "/updatetrip/doupdatetrip", method = RequestMethod.POST) public String doupdateTrip(ModelMap mm, @ModelAttribute("newtrip") Trip newtrip) { tripService.update(newtrip); return "redirect:/alltrips"; } @RequestMapping(value = "/deletetrip/{id}", method = RequestMethod.GET) public String deleteTrip(ModelMap mm, @PathVariable int id) { tripService.deleteTripByID(id); return "redirect:/adminalltrips"; } @RequestMapping(value = "/takethetrip", method = RequestMethod.GET) public String takeTrip(ModelMap mm) { Trip trip = new Trip(); mm.addAttribute("trip", trip); return "takethetrip"; } @RequestMapping(value = "/dotaketrip/{tripid}", method = RequestMethod.GET) public String dotakeTrip(ModelMap mm, @PathVariable int tripid, HttpSession session) { Trip trip = tripService.findTripByID(tripid); List<User> utl = new ArrayList(); utl.add((User) session.getAttribute("loggedinuser")); trip.setUserList(utl); trip.setAvailableseats(trip.getAvailableseats() - 1); tripService.update(trip); return "redirect:/getalltrips"; } @PostMapping("/find") public String findTripsController( @RequestParam("latorigin") double latO, @RequestParam("lngorigin") double lngO, @RequestParam("latdestination") double latD, @RequestParam("lngdestination") double lngD, @RequestParam("date") Date date, ModelMap modelmap) { List<Trip> all = tripService.findAllTrips(); List<Trip> results = new ArrayList(); Place origin = new Place(latO, lngO); Place destination = new Place(latD, lngD); for (Trip trip : all) { double lato = Double.parseDouble(trip.getOriginlatitude()); double lngo = Double.parseDouble(trip.getOriginlongtitude()); double latd = Double.parseDouble(trip.getDestinationlatitude()); double lngd = Double.parseDouble(trip.getDestinationlongtitude()); Place o = new Place(lato, lngo); Place d = new Place(latd, lngd); boolean originIsOK = tripUtils.isWithinRadius(origin, o, 2.0); // εδω καρφωσα μια ακτινα 220 μετρων boolean destinationIsOK = tripUtils.isWithinRadius(destination, d, 2.0); if (originIsOK && destinationIsOK && /*date.equals(trip.getDate()) && */ (trip.getAvailableseats() > 0)) { results.add(trip); // το βαζω σε μια λιστα με τα αποτελεσματα που θελω να δειξω στο χρηστη. } } if (results.isEmpty()) { return "errortripnotfound"; } else { modelmap.put("trips", results); return "alltrips"; } } @RequestMapping(value = "getridesoffered/{driverid}", method = RequestMethod.GET) public String doTakeOfferedRides(ModelMap mm, HttpSession session, @PathVariable User driverid) { List<Trip> triplist = tripService.findAllTripsByDriverid(driverid); mm.addAttribute("thetriplist", triplist); return "ridesoffered"; } @RequestMapping(value = "getridestaken/{user}", method = RequestMethod.GET) public String doTakeTookRides(ModelMap mm, HttpSession session, @PathVariable User user) { List<Trip> triplist = user.getTripList(); mm.addAttribute("thetakenktriplist", triplist); return "ridestook"; } @RequestMapping(value = "adminalltrips", method = RequestMethod.GET) public String getAdminAllTrips(ModelMap mm) { List<Trip> trips = tripService.findAllTrips(); mm.put("trips", trips); return "adminalltrips"; } }
mpelchris/carpooling-1
carpooling/src/main/java/com/carpooling/controllers/TripController.java
1,686
// το βαζω σε μια λιστα με τα αποτελεσματα που θελω να δειξω στο χρηστη.
line_comment
el
package com.carpooling.controllers; import com.carpooling.dtos.Place; import com.carpooling.entities.Trip; import com.carpooling.entities.User; import com.carpooling.services.TripService; import com.carpooling.utils.TripUtils; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; import java.util.Date; import java.util.List; import static java.util.stream.Collectors.toList; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @Controller public class TripController { @Autowired TripService tripService; @Autowired TripUtils tripUtils; @RequestMapping(value = "/inserttrip", method = RequestMethod.GET) public String insertTrip(ModelMap mm) { Trip trip = new Trip(); mm.addAttribute("trip", trip); return "inserttrip"; } @RequestMapping(value = "/doinserttrip", method = RequestMethod.POST) public String doinsertTrip(ModelMap mm, @ModelAttribute("newtrip") Trip trip, @RequestParam("year") String year, @RequestParam("month") String month, @RequestParam("day") String day, @RequestParam("hour") String hour, @RequestParam("mins") String mins) { LocalDateTime ldt = LocalDateTime.of( Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day), Integer.parseInt(hour), Integer.parseInt(mins), 0); trip.setDate(Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant())); tripService.insert(trip); return "selectaride"; } @RequestMapping(value = "getalltrips", method = RequestMethod.GET) public String allTrips(ModelMap mm) { List<Trip> trips = tripService.findAllTrips() .stream() .filter((t) -> t.getAvailableseats() > 0) .collect(toList()); mm.put("trips", trips); return "alltrips"; } @RequestMapping(value = "/updatetrip/{id}", method = RequestMethod.GET) public String updateTrip(ModelMap mm, @PathVariable int id) { Trip oldtrip = tripService.findTripByID(id); Trip newtrip = new Trip(); mm.addAttribute("newtrip", newtrip); mm.addAttribute("oldtrip", oldtrip); return "updatetrip"; } @RequestMapping(value = "/updatetrip/doupdatetrip", method = RequestMethod.POST) public String doupdateTrip(ModelMap mm, @ModelAttribute("newtrip") Trip newtrip) { tripService.update(newtrip); return "redirect:/alltrips"; } @RequestMapping(value = "/deletetrip/{id}", method = RequestMethod.GET) public String deleteTrip(ModelMap mm, @PathVariable int id) { tripService.deleteTripByID(id); return "redirect:/adminalltrips"; } @RequestMapping(value = "/takethetrip", method = RequestMethod.GET) public String takeTrip(ModelMap mm) { Trip trip = new Trip(); mm.addAttribute("trip", trip); return "takethetrip"; } @RequestMapping(value = "/dotaketrip/{tripid}", method = RequestMethod.GET) public String dotakeTrip(ModelMap mm, @PathVariable int tripid, HttpSession session) { Trip trip = tripService.findTripByID(tripid); List<User> utl = new ArrayList(); utl.add((User) session.getAttribute("loggedinuser")); trip.setUserList(utl); trip.setAvailableseats(trip.getAvailableseats() - 1); tripService.update(trip); return "redirect:/getalltrips"; } @PostMapping("/find") public String findTripsController( @RequestParam("latorigin") double latO, @RequestParam("lngorigin") double lngO, @RequestParam("latdestination") double latD, @RequestParam("lngdestination") double lngD, @RequestParam("date") Date date, ModelMap modelmap) { List<Trip> all = tripService.findAllTrips(); List<Trip> results = new ArrayList(); Place origin = new Place(latO, lngO); Place destination = new Place(latD, lngD); for (Trip trip : all) { double lato = Double.parseDouble(trip.getOriginlatitude()); double lngo = Double.parseDouble(trip.getOriginlongtitude()); double latd = Double.parseDouble(trip.getDestinationlatitude()); double lngd = Double.parseDouble(trip.getDestinationlongtitude()); Place o = new Place(lato, lngo); Place d = new Place(latd, lngd); boolean originIsOK = tripUtils.isWithinRadius(origin, o, 2.0); // εδω καρφωσα μια ακτινα 220 μετρων boolean destinationIsOK = tripUtils.isWithinRadius(destination, d, 2.0); if (originIsOK && destinationIsOK && /*date.equals(trip.getDate()) && */ (trip.getAvailableseats() > 0)) { results.add(trip); // το βαζω<SUF> } } if (results.isEmpty()) { return "errortripnotfound"; } else { modelmap.put("trips", results); return "alltrips"; } } @RequestMapping(value = "getridesoffered/{driverid}", method = RequestMethod.GET) public String doTakeOfferedRides(ModelMap mm, HttpSession session, @PathVariable User driverid) { List<Trip> triplist = tripService.findAllTripsByDriverid(driverid); mm.addAttribute("thetriplist", triplist); return "ridesoffered"; } @RequestMapping(value = "getridestaken/{user}", method = RequestMethod.GET) public String doTakeTookRides(ModelMap mm, HttpSession session, @PathVariable User user) { List<Trip> triplist = user.getTripList(); mm.addAttribute("thetakenktriplist", triplist); return "ridestook"; } @RequestMapping(value = "adminalltrips", method = RequestMethod.GET) public String getAdminAllTrips(ModelMap mm) { List<Trip> trips = tripService.findAllTrips(); mm.put("trips", trips); return "adminalltrips"; } }
4616_0
package gr.ageorgiadis.xe; import java.util.ListResourceBundle; public class Keys extends ListResourceBundle { public static final String PRICE_KEY = "Τιμή"; @Override protected Object[][] getContents() { return new Object[][] { { "areaStorage", "Εμβαδόν αποθήκης" }, { "bathrooms", "Μπάνια/ WC" }, { "district", "Περιοχή" }, { "airConditioningAvailable", "Κλιματισμός" }, { "gardenAvailable", "Κήπος" }, { "bedrooms", "Υπνοδωμάτια" }, { "createdOn", "Δημιουργία αγγελίας" }, { "parkingType", "Είδος Πάρκιν" }, { "statusDetailed", "Λεπτομερής κατάσταση" }, { "furnished", "Επιπλωμένο" }, { "hits", "Η αγγελία έχει έως τώρα" }, { "fireplaceAvailable", "Τζάκι" }, { "storageAvailable", "Με αποθήκη" }, { "availability", "Διαθεσιμότητα" }, { "lastUpdatedOn", "Tελευταία ενημέρωση αγγελίας" }, { "area", "Εμβαδόν" }, { "status", "Κατάσταση" }, { "adOwner", "Αγγελία από" }, { "price", PRICE_KEY }, { "naturalGasAvailable", "Φυσικό αέριο" }, { "type", "Είδος" }, { "telephones", "Τηλέφωνα επικοινωνίας" }, { "availableOn", "Διαθέσιμο από" }, { "restoredOn", "Έτος Ανακαίνισης" }, { "sharedExpensesFree", "Χωρίς Κοινόχρηστα" }, { "parkingAvailable", "Πάρκιν" }, { "floor", "Όροφος" }, { "autonomousHeatingAvailable", "Αυτόνομη θέρμανση" }, { "solarWaterHeaterAvailable", "Ηλιακός θερμοσίφωνας" }, { "link", "Σύνδεσμος" }, { "orientation", "Προσανατολισμός" }, { "masterBedrooms", "Υπνοδωμάτια Master" }, { "builtOn", "Έτος Κατασκευής" }, { "safetyDoorAvailable", "Πόρτα ασφαλείας" }, { "view", "Θέα" }, { "tents", "Τέντες" }, { "configuration", "Διαμόρφωση Χώρων" }, { "pool", "Πισίνα" } }; } /* E.g. Παρασκευή, 07 Οκτωβρίου 2011 */ public static boolean isFullDate(String key) { return key.equals("createdOn") || key.equals("lastUpdatedOn"); } public static boolean isNumeric(String key) { return key.equals("builtOn") || key.equals("area") || key.equals("bathrooms") || key.equals("masterBedrooms") || key.equals("area") || key.equals("restoredOn") || key.equals("bedrooms") || key.equals("areaStorage") || key.equals("price"); } public static boolean isSkipped(String key) { return key.equals("telephones"); } }
mranest/xe-crawler
src/main/java/gr/ageorgiadis/xe/Keys.java
1,143
/* E.g. Παρασκευή, 07 Οκτωβρίου 2011 */
block_comment
el
package gr.ageorgiadis.xe; import java.util.ListResourceBundle; public class Keys extends ListResourceBundle { public static final String PRICE_KEY = "Τιμή"; @Override protected Object[][] getContents() { return new Object[][] { { "areaStorage", "Εμβαδόν αποθήκης" }, { "bathrooms", "Μπάνια/ WC" }, { "district", "Περιοχή" }, { "airConditioningAvailable", "Κλιματισμός" }, { "gardenAvailable", "Κήπος" }, { "bedrooms", "Υπνοδωμάτια" }, { "createdOn", "Δημιουργία αγγελίας" }, { "parkingType", "Είδος Πάρκιν" }, { "statusDetailed", "Λεπτομερής κατάσταση" }, { "furnished", "Επιπλωμένο" }, { "hits", "Η αγγελία έχει έως τώρα" }, { "fireplaceAvailable", "Τζάκι" }, { "storageAvailable", "Με αποθήκη" }, { "availability", "Διαθεσιμότητα" }, { "lastUpdatedOn", "Tελευταία ενημέρωση αγγελίας" }, { "area", "Εμβαδόν" }, { "status", "Κατάσταση" }, { "adOwner", "Αγγελία από" }, { "price", PRICE_KEY }, { "naturalGasAvailable", "Φυσικό αέριο" }, { "type", "Είδος" }, { "telephones", "Τηλέφωνα επικοινωνίας" }, { "availableOn", "Διαθέσιμο από" }, { "restoredOn", "Έτος Ανακαίνισης" }, { "sharedExpensesFree", "Χωρίς Κοινόχρηστα" }, { "parkingAvailable", "Πάρκιν" }, { "floor", "Όροφος" }, { "autonomousHeatingAvailable", "Αυτόνομη θέρμανση" }, { "solarWaterHeaterAvailable", "Ηλιακός θερμοσίφωνας" }, { "link", "Σύνδεσμος" }, { "orientation", "Προσανατολισμός" }, { "masterBedrooms", "Υπνοδωμάτια Master" }, { "builtOn", "Έτος Κατασκευής" }, { "safetyDoorAvailable", "Πόρτα ασφαλείας" }, { "view", "Θέα" }, { "tents", "Τέντες" }, { "configuration", "Διαμόρφωση Χώρων" }, { "pool", "Πισίνα" } }; } /* E.g. Παρασκευή, 07<SUF>*/ public static boolean isFullDate(String key) { return key.equals("createdOn") || key.equals("lastUpdatedOn"); } public static boolean isNumeric(String key) { return key.equals("builtOn") || key.equals("area") || key.equals("bathrooms") || key.equals("masterBedrooms") || key.equals("area") || key.equals("restoredOn") || key.equals("bedrooms") || key.equals("areaStorage") || key.equals("price"); } public static boolean isSkipped(String key) { return key.equals("telephones"); } }
2842_5
import java.util.Scanner; public class main { public static void main(String[] args) { Scanner obj1 = new Scanner(System.in); Menu menu = new Menu(); Buyer buyer1 = new Buyer("Mimi", "[email protected]"); Buyer buyer2 = new Buyer("Nicol", "[email protected]"); Owner owner = new Owner("Marios", "[email protected]"); EShop eshop = new EShop("The magnificent store", owner); ShoppingCart shc = new ShoppingCart(); eshop.buyersList.add(buyer1); eshop.buyersList.add(buyer2); Pen pen1 = new Pen("Big", 2, "blue", 10, 0001, "white", 5); Pencil pencil1 = new Pencil("Faber Castel", 1.5, "black", 10, 0002, "HB", 5); Paper paper1 = new Paper("Mark", 5, "A4", 10, 0003, 50, 100); Notebook book1 = new Notebook("SKAG", 15, "A3", 10, 0004, 4); eshop.itemsList.add(pen1); eshop.itemsList.add(pencil1); eshop.itemsList.add(paper1); eshop.itemsList.add(book1); int selection1, selection2, selection3, selection4, selection5; int q; int credencial, g; boolean flag; selection1 = menu.menu1(); while (selection1<5 && selection1>0) { if (selection1==1) { credencial=menu.login(eshop); //Αν βρεθεί ο χρήστης, επιστρέφω και αποθηκεύω την θέση που βρίσκεται στο array, ώστε να μπορέσω να καλέσω τις μεθόδους/ιδιότηες κλπ του συγκεκριμένου αντικειμένου Buyer if (credencial==-1) { System.out.println("Wrong credencials\n\n"); selection1 = menu.menu1(); //Επιστρέφω το menu1, ωσότου πάρω στοιχεία που αντιστοιχούν σε Buyer ή στον Owner } else if (credencial==-2) //Έχει κάνει log in ο Owner { selection5 = menu.menu5(); while (selection5>0 && selection5<4) { switch (selection5) { case 1: eshop.showCategories(); //Εμφανίζω τις κατηγορίες προιόντων που πουλάει το κατάστημα eshop.showProductsInCategory(); //Ανάλογα με την κατηγορία που επιλέγει, εμφανίζω τα προιόντα που ανήκουν σ' αυτήν g = eshop.showProduct(); if (g!=-1) //Σημαίνει ότι έχει βρεθεί το προιόν { eshop.updateItemStock(); } break; case 2: eshop.checkStatus(); break; case 3: System.exit(0); break; } selection5 = menu.menu5(); } selection1 = menu.menu1(); } else //Έχει κάνει log in κάποιος Buyer { selection2 = menu.menu2(); while (selection2>0 && selection2<6) { switch (selection2) { case 1: eshop.showCategories(); eshop.showProductsInCategory(); g = eshop.showProduct(); if (g!=-1) { System.out.println("Enter the quantity of the product you want."); q = obj1.nextInt(); ((Buyer) eshop.buyersList.get(credencial)).placeOrder(eshop.itemsList.get(g), q); } break; case 2: flag=shc.showCart(((Buyer) eshop.buyersList.get(credencial))); if (flag==false) { System.out.println("Your shopping cart is empty."); } else { selection3=menu.menu3(); switch (selection3) { case 1: selection4 = menu.menu4(); switch (selection4) { case 1: shc.removeItemOrdered(); break; case 2: shc.changeItemOrderedQuantity(); break; } break; case 2: shc.clearCart(); break; case 3: shc.checkout(((Buyer) eshop.buyersList.get(credencial))); break; } } break; case 3: shc.checkout(((Buyer) eshop.buyersList.get(credencial))); break; case 4: System.exit(0); break; } selection2 = menu.menu2(); //Μετά απο κάθε ολοκλήρωση των υπο-menu, εμφανίζεται το κεντρικό menu του eshop } selection1 = menu.menu1(); //Με οποιονδήποτε άλλον αριθμό που δεν ταιριάζει στο menu, ο χρήστης κάνει log out } } else if (selection1==2) //Περίπτωση που υπάρχει new user { menu.newUser(eshop); selection1 = menu.menu1(); } } } }
mstephanidhs/CEID-Projects
Object-Oriented-Programming/code/main/main.java
1,599
//Σημαίνει ότι έχει βρεθεί το προιόν
line_comment
el
import java.util.Scanner; public class main { public static void main(String[] args) { Scanner obj1 = new Scanner(System.in); Menu menu = new Menu(); Buyer buyer1 = new Buyer("Mimi", "[email protected]"); Buyer buyer2 = new Buyer("Nicol", "[email protected]"); Owner owner = new Owner("Marios", "[email protected]"); EShop eshop = new EShop("The magnificent store", owner); ShoppingCart shc = new ShoppingCart(); eshop.buyersList.add(buyer1); eshop.buyersList.add(buyer2); Pen pen1 = new Pen("Big", 2, "blue", 10, 0001, "white", 5); Pencil pencil1 = new Pencil("Faber Castel", 1.5, "black", 10, 0002, "HB", 5); Paper paper1 = new Paper("Mark", 5, "A4", 10, 0003, 50, 100); Notebook book1 = new Notebook("SKAG", 15, "A3", 10, 0004, 4); eshop.itemsList.add(pen1); eshop.itemsList.add(pencil1); eshop.itemsList.add(paper1); eshop.itemsList.add(book1); int selection1, selection2, selection3, selection4, selection5; int q; int credencial, g; boolean flag; selection1 = menu.menu1(); while (selection1<5 && selection1>0) { if (selection1==1) { credencial=menu.login(eshop); //Αν βρεθεί ο χρήστης, επιστρέφω και αποθηκεύω την θέση που βρίσκεται στο array, ώστε να μπορέσω να καλέσω τις μεθόδους/ιδιότηες κλπ του συγκεκριμένου αντικειμένου Buyer if (credencial==-1) { System.out.println("Wrong credencials\n\n"); selection1 = menu.menu1(); //Επιστρέφω το menu1, ωσότου πάρω στοιχεία που αντιστοιχούν σε Buyer ή στον Owner } else if (credencial==-2) //Έχει κάνει log in ο Owner { selection5 = menu.menu5(); while (selection5>0 && selection5<4) { switch (selection5) { case 1: eshop.showCategories(); //Εμφανίζω τις κατηγορίες προιόντων που πουλάει το κατάστημα eshop.showProductsInCategory(); //Ανάλογα με την κατηγορία που επιλέγει, εμφανίζω τα προιόντα που ανήκουν σ' αυτήν g = eshop.showProduct(); if (g!=-1) //Σημαίνει ότι<SUF> { eshop.updateItemStock(); } break; case 2: eshop.checkStatus(); break; case 3: System.exit(0); break; } selection5 = menu.menu5(); } selection1 = menu.menu1(); } else //Έχει κάνει log in κάποιος Buyer { selection2 = menu.menu2(); while (selection2>0 && selection2<6) { switch (selection2) { case 1: eshop.showCategories(); eshop.showProductsInCategory(); g = eshop.showProduct(); if (g!=-1) { System.out.println("Enter the quantity of the product you want."); q = obj1.nextInt(); ((Buyer) eshop.buyersList.get(credencial)).placeOrder(eshop.itemsList.get(g), q); } break; case 2: flag=shc.showCart(((Buyer) eshop.buyersList.get(credencial))); if (flag==false) { System.out.println("Your shopping cart is empty."); } else { selection3=menu.menu3(); switch (selection3) { case 1: selection4 = menu.menu4(); switch (selection4) { case 1: shc.removeItemOrdered(); break; case 2: shc.changeItemOrderedQuantity(); break; } break; case 2: shc.clearCart(); break; case 3: shc.checkout(((Buyer) eshop.buyersList.get(credencial))); break; } } break; case 3: shc.checkout(((Buyer) eshop.buyersList.get(credencial))); break; case 4: System.exit(0); break; } selection2 = menu.menu2(); //Μετά απο κάθε ολοκλήρωση των υπο-menu, εμφανίζεται το κεντρικό menu του eshop } selection1 = menu.menu1(); //Με οποιονδήποτε άλλον αριθμό που δεν ταιριάζει στο menu, ο χρήστης κάνει log out } } else if (selection1==2) //Περίπτωση που υπάρχει new user { menu.newUser(eshop); selection1 = menu.menu1(); } } } }
3476_8
package rdf.joins; import org.apache.spark.sql.AnalysisException; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SparkSession; import java.io.IOException; import java.util.Objects; import static utils.ReadPropertiesFile.readConfigProperty; /** * Created by tsotzo on 15/5/2017. */ public class RdfJoins { /** * Working with triples (s,p,o) * when triples in verticalPartitioning (VP) * ?s p1 o1 * ?s p2 o2 * Και στο παράδειγμα των follows και likes * p1->follows * p2->likes * Ποιος follows τον ο1 * και του likes τον ο2 * * @param object1 * @param object2 * @param predicate1 * @param predicate2 * @param type */ public static void findSubjectSubjectJoin(String predicate1, String predicate2, String object1, String object2, SparkSession sparkSession, String type ) throws IOException { Dataset<Row> df1 = null; Dataset<Row> df2 = null; String path = ""; //The predicate will tell us the file that we must take //Φορτώνουμε το κάθε αρχείο σε ένα Dataset αναλόγως με το αν είναι csv ή parquet if (Objects.equals(type, "csv")) { df1 = sparkSession.read().csv(readConfigProperty("pathForJoinsCSV") + predicate1 + ".csv"); df2 = sparkSession.read().csv(readConfigProperty("pathForJoinsCSV") + predicate2 + ".csv"); } else if (Objects.equals(type, "parquet")) { df1 = sparkSession.read().parquet(readConfigProperty("pathForJoinsParquet")+ predicate1 + ".parquet"); df2 = sparkSession.read().parquet(readConfigProperty("pathForJoinsParquet") + predicate2 + ".parquet"); } else { System.out.println("Wrong File Type as a Parameter, Select 'csv' or 'parquet' "); } df1.createOrReplaceTempView("tableName1"); df2.createOrReplaceTempView("tableName2"); //Κάνουμε προβολή των δεδομένων System.out.println("-------------------SubjectSubject----------------------------"); sparkSession.sql("SELECT distinct tableName1._c0 as subject0" + " FROM tableName1 , tableName2 " + " where tableName1._c1='" + object1 + "'" + " and tableName1._c0=tableName2._c0" + " and tableName2._c1='" + object2 + "'").show(); } /** * Working with triples (s,p,o) * when triples in verticalPartitioning (VP) * Join object-object (OO) * s1 p1 ?o * s2 p1 ?o * Απαντά στο ερώτημα πχ με τους follows * Ποιους ακολουθά ταυτόχρονα και ο s1 και ο s2 ? * * @param subject1 * @param subject2 * @param predicate1 * @param predicate2 * @param type * */ public static void findObjectObjectJoin(String predicate1, String predicate2, String subject1, String subject2, SparkSession sparkSession, String type) throws AnalysisException, IOException { Dataset<Row> dfa = null; Dataset<Row> dfb = null; //Φορτώνουμε το κάθε αρχείο σε ένα Dataset αναλόγως με το αν είναι csv ή parquet if (Objects.equals(type, "csv")) { dfa = sparkSession.read().csv(readConfigProperty("pathForJoinsCSV") + predicate1 + ".csv"); dfb = sparkSession.read().csv(readConfigProperty("pathForJoinsCSV") + predicate2 + ".csv"); } else if (Objects.equals(type, "parquet")) { dfa = sparkSession.read().parquet(readConfigProperty("pathForJoinsParquet") + predicate1 + ".parquet"); dfb = sparkSession.read().parquet(readConfigProperty("pathForJoinsParquet") + predicate2 + ".parquet"); } else { System.out.println("Wrong File Type as a Parameter, Select 'csv' or 'parquet' "); } //Φτιάχνουμε τα TempViews dfa.createOrReplaceTempView("tableName1"); dfb.createOrReplaceTempView("tableName2"); //Κάνουμε προβολή των δεδομένων System.out.println("-------------------ObjectObject----------------------------"); sparkSession.sql("SELECT distinct tableName1._c1 as object1" + " FROM tableName1 , tableName2 " + " where tableName1._c0='" + subject1 + "'" + " and tableName1._c1=tableName2._c1" + " and tableName2._c0='" + subject2 + "'").show(); } /** * Working with triples (s,p,o) * when triples in verticalPartitioning (VP) * Join object-subject (OS) * s1 p1 ?o * ?s p2 o2 * Απαντά στο ερώτημα πχ με τους follows * Ποιοι ακολουθούν τον ?ο και αυτοί likes ο2 ? * * @param subject1 * @param object2 * @param predicate1 * @param predicate2 * @param type */ public static void findObjectSubjectJoin(String predicate1, String predicate2, String subject1, String object2, SparkSession sparkSession, String type) throws AnalysisException, IOException { Dataset<Row> df3 = null; Dataset<Row> df4 = null; //Φορτώνουμε το κάθε αρχείο σε ένα Dataset αναλόγως με το αν είναι csv ή parquet if (Objects.equals(type, "csv")) { df3 = sparkSession.read().csv(readConfigProperty("pathForJoinsCSV") + predicate1 + ".csv"); df4 = sparkSession.read().csv(readConfigProperty("pathForJoinsCSV") + predicate2 + ".csv"); } else if (Objects.equals(type, "parquet")) { df3 = sparkSession.read().parquet(readConfigProperty("pathForJoinsParquet")+ predicate1 + ".parquet"); df4 = sparkSession.read().parquet(readConfigProperty("pathForJoinsParquet") + predicate2 + ".parquet"); } else { System.out.println("Wrong File Type as a Parameter, Select 'csv' or 'parquet' "); } //Φτιάχνουμε τα TempViews df3.createOrReplaceTempView("tableName1"); df4.createOrReplaceTempView("tableName2"); //Κάνουμε προβολή των δεδομένων System.out.println("-------------------ObjectSubject----------------------------"); sparkSession.sql("SELECT distinct tableName1._c1 as object1" + " FROM tableName1 , tableName2 " + " where tableName1._c0='" + subject1 + "'" + " and tableName1._c1=tableName2._c0" + " and tableName2._c1='" + object2 + "'").show(); } /** * Working with triples (s,p,o) * when triples in verticalPartitioning (VP) * Join subject-object (SO) * ?s p1 o1 * s2 p2 ?o * Απαντά στο ερώτημα πχ με τους follows * Ποιοι ακολουθούν τον ?s και ο ?s likes s1 * * @param subject2 * @param object1 * @param predicate1 * @param predicate2 * @param type */ public static void findSubjectObjectJoin(String predicate1, String predicate2, String object1,String subject2, SparkSession sparkSession, String type) throws AnalysisException, IOException { Dataset<Row> df1 = null; Dataset<Row> df2 = null; //Φορτώνουμε το κάθε αρχείο σε ένα Dataset αναλόγως με το αν είναι csv ή parquet if (Objects.equals(type, "csv")) { df1 = sparkSession.read().csv(readConfigProperty("pathForJoinsCSV") + predicate1 + ".csv"); df2 = sparkSession.read().csv(readConfigProperty("pathForJoinsCSV") + predicate2 + ".csv"); } else if (Objects.equals(type, "parquet")) { df1 = sparkSession.read().parquet(readConfigProperty("pathForJoinsParquet")+ predicate1 + ".parquet"); df2 = sparkSession.read().parquet(readConfigProperty("pathForJoinsParquet") + predicate2 + ".parquet"); } else { System.out.println("Wrong File Type as a Parameter, Select 'csv' or 'parquet' "); } //Φτιάχνουμε τα TempViews df1.createOrReplaceTempView("tableName1"); df2.createOrReplaceTempView("tableName2"); //Κάνουμε προβολή των δεδομένων System.out.println("-------------------SubjectObject----------------------------"); sparkSession.sql("SELECT distinct tableName1._c0 as object0,tableName2._c1 as subject1" + " FROM tableName1 , tableName2 " + " where tableName1._c0=tableName2._c1" + " and tableName1._c1='" + object1 + "'" + " and tableName2._c0='" + subject2 + "'").show(); } }
myluco/sparkExerciseFinal
src/main/java/rdf/joins/RdfJoins.java
2,512
//Κάνουμε προβολή των δεδομένων
line_comment
el
package rdf.joins; import org.apache.spark.sql.AnalysisException; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SparkSession; import java.io.IOException; import java.util.Objects; import static utils.ReadPropertiesFile.readConfigProperty; /** * Created by tsotzo on 15/5/2017. */ public class RdfJoins { /** * Working with triples (s,p,o) * when triples in verticalPartitioning (VP) * ?s p1 o1 * ?s p2 o2 * Και στο παράδειγμα των follows και likes * p1->follows * p2->likes * Ποιος follows τον ο1 * και του likes τον ο2 * * @param object1 * @param object2 * @param predicate1 * @param predicate2 * @param type */ public static void findSubjectSubjectJoin(String predicate1, String predicate2, String object1, String object2, SparkSession sparkSession, String type ) throws IOException { Dataset<Row> df1 = null; Dataset<Row> df2 = null; String path = ""; //The predicate will tell us the file that we must take //Φορτώνουμε το κάθε αρχείο σε ένα Dataset αναλόγως με το αν είναι csv ή parquet if (Objects.equals(type, "csv")) { df1 = sparkSession.read().csv(readConfigProperty("pathForJoinsCSV") + predicate1 + ".csv"); df2 = sparkSession.read().csv(readConfigProperty("pathForJoinsCSV") + predicate2 + ".csv"); } else if (Objects.equals(type, "parquet")) { df1 = sparkSession.read().parquet(readConfigProperty("pathForJoinsParquet")+ predicate1 + ".parquet"); df2 = sparkSession.read().parquet(readConfigProperty("pathForJoinsParquet") + predicate2 + ".parquet"); } else { System.out.println("Wrong File Type as a Parameter, Select 'csv' or 'parquet' "); } df1.createOrReplaceTempView("tableName1"); df2.createOrReplaceTempView("tableName2"); //Κάνουμε προβολή των δεδομένων System.out.println("-------------------SubjectSubject----------------------------"); sparkSession.sql("SELECT distinct tableName1._c0 as subject0" + " FROM tableName1 , tableName2 " + " where tableName1._c1='" + object1 + "'" + " and tableName1._c0=tableName2._c0" + " and tableName2._c1='" + object2 + "'").show(); } /** * Working with triples (s,p,o) * when triples in verticalPartitioning (VP) * Join object-object (OO) * s1 p1 ?o * s2 p1 ?o * Απαντά στο ερώτημα πχ με τους follows * Ποιους ακολουθά ταυτόχρονα και ο s1 και ο s2 ? * * @param subject1 * @param subject2 * @param predicate1 * @param predicate2 * @param type * */ public static void findObjectObjectJoin(String predicate1, String predicate2, String subject1, String subject2, SparkSession sparkSession, String type) throws AnalysisException, IOException { Dataset<Row> dfa = null; Dataset<Row> dfb = null; //Φορτώνουμε το κάθε αρχείο σε ένα Dataset αναλόγως με το αν είναι csv ή parquet if (Objects.equals(type, "csv")) { dfa = sparkSession.read().csv(readConfigProperty("pathForJoinsCSV") + predicate1 + ".csv"); dfb = sparkSession.read().csv(readConfigProperty("pathForJoinsCSV") + predicate2 + ".csv"); } else if (Objects.equals(type, "parquet")) { dfa = sparkSession.read().parquet(readConfigProperty("pathForJoinsParquet") + predicate1 + ".parquet"); dfb = sparkSession.read().parquet(readConfigProperty("pathForJoinsParquet") + predicate2 + ".parquet"); } else { System.out.println("Wrong File Type as a Parameter, Select 'csv' or 'parquet' "); } //Φτιάχνουμε τα TempViews dfa.createOrReplaceTempView("tableName1"); dfb.createOrReplaceTempView("tableName2"); //Κάνουμε προβολή<SUF> System.out.println("-------------------ObjectObject----------------------------"); sparkSession.sql("SELECT distinct tableName1._c1 as object1" + " FROM tableName1 , tableName2 " + " where tableName1._c0='" + subject1 + "'" + " and tableName1._c1=tableName2._c1" + " and tableName2._c0='" + subject2 + "'").show(); } /** * Working with triples (s,p,o) * when triples in verticalPartitioning (VP) * Join object-subject (OS) * s1 p1 ?o * ?s p2 o2 * Απαντά στο ερώτημα πχ με τους follows * Ποιοι ακολουθούν τον ?ο και αυτοί likes ο2 ? * * @param subject1 * @param object2 * @param predicate1 * @param predicate2 * @param type */ public static void findObjectSubjectJoin(String predicate1, String predicate2, String subject1, String object2, SparkSession sparkSession, String type) throws AnalysisException, IOException { Dataset<Row> df3 = null; Dataset<Row> df4 = null; //Φορτώνουμε το κάθε αρχείο σε ένα Dataset αναλόγως με το αν είναι csv ή parquet if (Objects.equals(type, "csv")) { df3 = sparkSession.read().csv(readConfigProperty("pathForJoinsCSV") + predicate1 + ".csv"); df4 = sparkSession.read().csv(readConfigProperty("pathForJoinsCSV") + predicate2 + ".csv"); } else if (Objects.equals(type, "parquet")) { df3 = sparkSession.read().parquet(readConfigProperty("pathForJoinsParquet")+ predicate1 + ".parquet"); df4 = sparkSession.read().parquet(readConfigProperty("pathForJoinsParquet") + predicate2 + ".parquet"); } else { System.out.println("Wrong File Type as a Parameter, Select 'csv' or 'parquet' "); } //Φτιάχνουμε τα TempViews df3.createOrReplaceTempView("tableName1"); df4.createOrReplaceTempView("tableName2"); //Κάνουμε προβολή των δεδομένων System.out.println("-------------------ObjectSubject----------------------------"); sparkSession.sql("SELECT distinct tableName1._c1 as object1" + " FROM tableName1 , tableName2 " + " where tableName1._c0='" + subject1 + "'" + " and tableName1._c1=tableName2._c0" + " and tableName2._c1='" + object2 + "'").show(); } /** * Working with triples (s,p,o) * when triples in verticalPartitioning (VP) * Join subject-object (SO) * ?s p1 o1 * s2 p2 ?o * Απαντά στο ερώτημα πχ με τους follows * Ποιοι ακολουθούν τον ?s και ο ?s likes s1 * * @param subject2 * @param object1 * @param predicate1 * @param predicate2 * @param type */ public static void findSubjectObjectJoin(String predicate1, String predicate2, String object1,String subject2, SparkSession sparkSession, String type) throws AnalysisException, IOException { Dataset<Row> df1 = null; Dataset<Row> df2 = null; //Φορτώνουμε το κάθε αρχείο σε ένα Dataset αναλόγως με το αν είναι csv ή parquet if (Objects.equals(type, "csv")) { df1 = sparkSession.read().csv(readConfigProperty("pathForJoinsCSV") + predicate1 + ".csv"); df2 = sparkSession.read().csv(readConfigProperty("pathForJoinsCSV") + predicate2 + ".csv"); } else if (Objects.equals(type, "parquet")) { df1 = sparkSession.read().parquet(readConfigProperty("pathForJoinsParquet")+ predicate1 + ".parquet"); df2 = sparkSession.read().parquet(readConfigProperty("pathForJoinsParquet") + predicate2 + ".parquet"); } else { System.out.println("Wrong File Type as a Parameter, Select 'csv' or 'parquet' "); } //Φτιάχνουμε τα TempViews df1.createOrReplaceTempView("tableName1"); df2.createOrReplaceTempView("tableName2"); //Κάνουμε προβολή των δεδομένων System.out.println("-------------------SubjectObject----------------------------"); sparkSession.sql("SELECT distinct tableName1._c0 as object0,tableName2._c1 as subject1" + " FROM tableName1 , tableName2 " + " where tableName1._c0=tableName2._c1" + " and tableName1._c1='" + object1 + "'" + " and tableName2._c0='" + subject2 + "'").show(); } }
20067_0
package com.unipi.softeng.security; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * * credits: Προγραμματισμός στο διαδίκτυο και στον παγκόσμιο ιστό */ public class Encryption { /** * Computes the hash of the given string. Return the hash uppercase. * * @param unhashed * @return Return the hash of the given string uppercase. */ public static String getHashMD5(String unhashed) { return getHashMD5(unhashed, ""); } /** * Computes the hash of the given string salted. Return the hash uppercase. * @param unhashed the string to hash * @param salt the salt to use * @return the hash of the given string salted and uppercase. * @throws NoSuchAlgorithmException */ public static String getHashMD5(String unhashed, String salt) { // Hash the password. final String toHash = salt + unhashed + salt; MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { return "00000000000000000000000000000000"; } messageDigest.update(toHash.getBytes(), 0, toHash.length()); String hashed = new BigInteger(1, messageDigest.digest()).toString(16); if (hashed.length() < 32) { hashed = "0" + hashed; } return hashed.toUpperCase(); } }
n-hatz/Android-Unipi.gr
backend/src/main/java/com/unipi/softeng/security/Encryption.java
412
/** * * credits: Προγραμματισμός στο διαδίκτυο και στον παγκόσμιο ιστό */
block_comment
el
package com.unipi.softeng.security; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * * credits: Προγραμματισμός στο<SUF>*/ public class Encryption { /** * Computes the hash of the given string. Return the hash uppercase. * * @param unhashed * @return Return the hash of the given string uppercase. */ public static String getHashMD5(String unhashed) { return getHashMD5(unhashed, ""); } /** * Computes the hash of the given string salted. Return the hash uppercase. * @param unhashed the string to hash * @param salt the salt to use * @return the hash of the given string salted and uppercase. * @throws NoSuchAlgorithmException */ public static String getHashMD5(String unhashed, String salt) { // Hash the password. final String toHash = salt + unhashed + salt; MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { return "00000000000000000000000000000000"; } messageDigest.update(toHash.getBytes(), 0, toHash.length()); String hashed = new BigInteger(1, messageDigest.digest()).toString(16); if (hashed.length() < 32) { hashed = "0" + hashed; } return hashed.toUpperCase(); } }
8013_5
import java.awt.BorderLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.SwingConstants; public class myFrame extends JFrame{ private static final long serialVersionUID = 1L; private JLabel label; private JPanel containerPanel; private JPanel centralPanel; private JButton bt1; private JButton bt2; private JButton bt3; private JButton bt4; private JButton bt5; private JButton bt6; private JButton bt7; private JButton bt8; private JButton bt9; private String wpn,fp,sp,wp; public myFrame() { label = new JLabel("", SwingConstants.CENTER); bt1 = new JButton("1"); bt2 = new JButton("2"); bt3 = new JButton("3"); bt4 = new JButton("4"); bt5 = new JButton("5"); bt6 = new JButton("6"); bt7 = new JButton("7"); bt8 = new JButton("8"); bt9 = new JButton("9"); containerPanel = new JPanel(); centralPanel = new JPanel(); Font font = new Font("Verdana", Font.PLAIN, 30); Font button = new Font("Verdana", Font.PLAIN, 94); GridLayout grid = new GridLayout(3,3); containerPanel.setLayout(grid); label.setFont(font); containerPanel.add(bt1); bt1.setFont(button); containerPanel.add(bt2); bt2.setFont(button); containerPanel.add(bt3); bt3.setFont(button); containerPanel.add(bt4); bt4.setFont(button); containerPanel.add(bt5); bt5.setFont(button); containerPanel.add(bt6); bt6.setFont(button); containerPanel.add(bt7); bt7.setFont(button); containerPanel.add(bt8); bt8.setFont(button); containerPanel.add(bt9); bt9.setFont(button); BorderLayout border = new BorderLayout(); centralPanel.setLayout(border); centralPanel.add(label, BorderLayout.NORTH); centralPanel.add(containerPanel, BorderLayout.CENTER); ButtonListener listener = new ButtonListener(); bt1.addActionListener(listener); bt2.addActionListener(listener); bt3.addActionListener(listener); bt4.addActionListener(listener); bt5.addActionListener(listener); bt6.addActionListener(listener); bt7.addActionListener(listener); bt8.addActionListener(listener); bt9.addActionListener(listener); this.setContentPane(centralPanel); Random rnd = new Random(); int player = rnd.nextInt(2); if(player == 1) { wpn = "Παίχτης1"; fp = "X"; sp = "O"; wp = "X"; }else { wpn = "Παίχτης2"; fp = "O"; sp = "X"; wp = "O"; } label.setText("Ο " +wpn + " παίζει"); this.setVisible(true); this.setSize(550, 550); this.setResizable(false); this.setTitle("ΠΑΙΧΝΙΔΙ ΤΡΙΛΙΖΑ!!!!"); } class ButtonListener implements ActionListener{ public void actionPerformed(ActionEvent e) { JButton button = (JButton) e.getSource(); if((!button.getText().equals("Χ")) && (!button.getText().equals("O"))) { button.setText(wp); if (wp.equals("X")) { wp = "O"; }else { wp = "X"; } }else { JOptionPane.showMessageDialog(centralPanel, "Το τετράγωνο είναι κατειλημμένο", "ΠΡΟΣΟΧΗ", JOptionPane.INFORMATION_MESSAGE); } String title = "Aποτελέσματα"; // Ελεγχος αν κερδισε καποιος if ((bt1.getText().equals(fp)) && (bt2.getText().equals(fp)) && (bt3.getText().equals(fp))){ JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt4.getText().equals(fp)) && (bt5.getText().equals(fp)) && (bt6.getText().equals(fp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt7.getText().equals(fp)) && (bt8.getText().equals(fp)) && (bt9.getText().equals(fp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn,title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt1.getText().equals(fp)) && (bt4.getText().equals(fp)) && (bt7.getText().equals(fp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn,title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt2.getText().equals(fp)) && (bt5.getText().equals(fp)) && (bt8.getText().equals(fp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt3.getText().equals(fp)) && (bt6.getText().equals(fp)) && (bt9.getText().equals(fp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt1.getText().equals(fp)) && (bt5.getText().equals(fp)) && (bt9.getText().equals(fp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn,title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt3.getText().equals(fp)) && (bt5.getText().equals(fp)) && (bt7.getText().equals(fp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn,title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt1.getText().equals(sp)) && (bt2.getText().equals(sp)) && (bt3.getText().equals(sp))){ JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt4.getText().equals(sp)) && (bt5.getText().equals(sp)) && (bt6.getText().equals(sp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt7.getText().equals(sp)) && (bt8.getText().equals(sp)) && (bt9.getText().equals(sp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt1.getText().equals(sp)) && (bt4.getText().equals(sp)) && (bt7.getText().equals(sp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt2.getText().equals(sp)) && (bt5.getText().equals(sp)) && (bt8.getText().equals(sp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt3.getText().equals(sp)) && (bt6.getText().equals(sp)) && (bt9.getText().equals(sp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt1.getText().equals(sp)) && (bt5.getText().equals(sp)) && (bt9.getText().equals(sp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt3.getText().equals(sp)) && (bt5.getText().equals(sp)) && (bt7.getText().equals(sp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame } else if ((!bt1.getText().equals("1")) && (!bt2.getText().equals("2")) && (!bt3.getText().equals("3")) && (!bt4.getText().equals("4")) && (!bt5.getText().equals("5")) && (!bt6.getText().equals("6")) && (!bt7.getText().equals("7")) && (!bt8.getText().equals("8")) && (!bt9.getText().equals("9"))) { JOptionPane.showMessageDialog(centralPanel, "ΙΣΟΠΑΛΙΑ", title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else { if (wpn.equals("Παίχτης1")) { wpn = "Παίχτης2"; }else { wpn = "Παίχτης1"; } label.setText("Ο " +wpn + " παίζει"); } } } }
nickpsal/TicTacTocGameGUI
src/myFrame.java
3,180
//Καταστροφη του JFrame
line_comment
el
import java.awt.BorderLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.SwingConstants; public class myFrame extends JFrame{ private static final long serialVersionUID = 1L; private JLabel label; private JPanel containerPanel; private JPanel centralPanel; private JButton bt1; private JButton bt2; private JButton bt3; private JButton bt4; private JButton bt5; private JButton bt6; private JButton bt7; private JButton bt8; private JButton bt9; private String wpn,fp,sp,wp; public myFrame() { label = new JLabel("", SwingConstants.CENTER); bt1 = new JButton("1"); bt2 = new JButton("2"); bt3 = new JButton("3"); bt4 = new JButton("4"); bt5 = new JButton("5"); bt6 = new JButton("6"); bt7 = new JButton("7"); bt8 = new JButton("8"); bt9 = new JButton("9"); containerPanel = new JPanel(); centralPanel = new JPanel(); Font font = new Font("Verdana", Font.PLAIN, 30); Font button = new Font("Verdana", Font.PLAIN, 94); GridLayout grid = new GridLayout(3,3); containerPanel.setLayout(grid); label.setFont(font); containerPanel.add(bt1); bt1.setFont(button); containerPanel.add(bt2); bt2.setFont(button); containerPanel.add(bt3); bt3.setFont(button); containerPanel.add(bt4); bt4.setFont(button); containerPanel.add(bt5); bt5.setFont(button); containerPanel.add(bt6); bt6.setFont(button); containerPanel.add(bt7); bt7.setFont(button); containerPanel.add(bt8); bt8.setFont(button); containerPanel.add(bt9); bt9.setFont(button); BorderLayout border = new BorderLayout(); centralPanel.setLayout(border); centralPanel.add(label, BorderLayout.NORTH); centralPanel.add(containerPanel, BorderLayout.CENTER); ButtonListener listener = new ButtonListener(); bt1.addActionListener(listener); bt2.addActionListener(listener); bt3.addActionListener(listener); bt4.addActionListener(listener); bt5.addActionListener(listener); bt6.addActionListener(listener); bt7.addActionListener(listener); bt8.addActionListener(listener); bt9.addActionListener(listener); this.setContentPane(centralPanel); Random rnd = new Random(); int player = rnd.nextInt(2); if(player == 1) { wpn = "Παίχτης1"; fp = "X"; sp = "O"; wp = "X"; }else { wpn = "Παίχτης2"; fp = "O"; sp = "X"; wp = "O"; } label.setText("Ο " +wpn + " παίζει"); this.setVisible(true); this.setSize(550, 550); this.setResizable(false); this.setTitle("ΠΑΙΧΝΙΔΙ ΤΡΙΛΙΖΑ!!!!"); } class ButtonListener implements ActionListener{ public void actionPerformed(ActionEvent e) { JButton button = (JButton) e.getSource(); if((!button.getText().equals("Χ")) && (!button.getText().equals("O"))) { button.setText(wp); if (wp.equals("X")) { wp = "O"; }else { wp = "X"; } }else { JOptionPane.showMessageDialog(centralPanel, "Το τετράγωνο είναι κατειλημμένο", "ΠΡΟΣΟΧΗ", JOptionPane.INFORMATION_MESSAGE); } String title = "Aποτελέσματα"; // Ελεγχος αν κερδισε καποιος if ((bt1.getText().equals(fp)) && (bt2.getText().equals(fp)) && (bt3.getText().equals(fp))){ JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt4.getText().equals(fp)) && (bt5.getText().equals(fp)) && (bt6.getText().equals(fp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt7.getText().equals(fp)) && (bt8.getText().equals(fp)) && (bt9.getText().equals(fp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn,title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt1.getText().equals(fp)) && (bt4.getText().equals(fp)) && (bt7.getText().equals(fp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn,title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt2.getText().equals(fp)) && (bt5.getText().equals(fp)) && (bt8.getText().equals(fp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του<SUF> }else if ((bt3.getText().equals(fp)) && (bt6.getText().equals(fp)) && (bt9.getText().equals(fp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt1.getText().equals(fp)) && (bt5.getText().equals(fp)) && (bt9.getText().equals(fp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn,title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt3.getText().equals(fp)) && (bt5.getText().equals(fp)) && (bt7.getText().equals(fp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn,title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt1.getText().equals(sp)) && (bt2.getText().equals(sp)) && (bt3.getText().equals(sp))){ JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt4.getText().equals(sp)) && (bt5.getText().equals(sp)) && (bt6.getText().equals(sp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt7.getText().equals(sp)) && (bt8.getText().equals(sp)) && (bt9.getText().equals(sp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt1.getText().equals(sp)) && (bt4.getText().equals(sp)) && (bt7.getText().equals(sp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt2.getText().equals(sp)) && (bt5.getText().equals(sp)) && (bt8.getText().equals(sp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt3.getText().equals(sp)) && (bt6.getText().equals(sp)) && (bt9.getText().equals(sp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt1.getText().equals(sp)) && (bt5.getText().equals(sp)) && (bt9.getText().equals(sp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else if ((bt3.getText().equals(sp)) && (bt5.getText().equals(sp)) && (bt7.getText().equals(sp))) { JOptionPane.showMessageDialog(centralPanel, "ΝΙΚΗΣΕ Ο " + wpn, title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame } else if ((!bt1.getText().equals("1")) && (!bt2.getText().equals("2")) && (!bt3.getText().equals("3")) && (!bt4.getText().equals("4")) && (!bt5.getText().equals("5")) && (!bt6.getText().equals("6")) && (!bt7.getText().equals("7")) && (!bt8.getText().equals("8")) && (!bt9.getText().equals("9"))) { JOptionPane.showMessageDialog(centralPanel, "ΙΣΟΠΑΛΙΑ", title, JOptionPane.INFORMATION_MESSAGE); setVisible(false); //αορατο dispose(); //Καταστροφη του JFrame }else { if (wpn.equals("Παίχτης1")) { wpn = "Παίχτης2"; }else { wpn = "Παίχτης1"; } label.setText("Ο " +wpn + " παίζει"); } } } }
876_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 ticketingsystem; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * * @author nickpsal */ public class Technician extends User{ //2. Ένας τεχνικός (Technician) έχει ένα όνομα και μια συγκεκριμένη εξειδίκευση, //η οποία μπορεί να είναι μόνο μια εκ των "HARDWARE, SOFTWARE, NETWORK, COMMUNICATIONS" public enum TechnicianSpec {HARDWARE, SOFTWARE, NETWORK, COMMUNICATIONS}; private TechnicianSpec techSpec; Random r = new Random(); List<Ticket> tickets; //Constructor public Technician(String name, TechnicianSpec techSpec) { super(name); this.techSpec = techSpec; this.tickets = new ArrayList<>(); } // getters - setters public List<Ticket> getTickets() { return tickets; } public void setTickets(List<Ticket> tickets) { this.tickets = tickets; } public void addTicket(Ticket ticket) { tickets.add(ticket); } public void removeTicket(Ticket ticket) { tickets.remove(ticket); } public TechnicianSpec getTechSpec() { return techSpec; } public void setTechSpec(TechnicianSpec techSpec) { this.techSpec = techSpec; } //Για κάθε τεχνικό θα καλεί μέθοδο randomProcessTickets //η οποία θα προσομοιώνει την επίλυση ενός αιτήματος από τον τεχνικό ακολουθώντας //την προβλεπόμενη διαδικασία, όπου όμως το πλήθος των ενεργειών θα είναι τυχαίο public void randomProcessTickets(Technician t) { for (Ticket ticket:tickets) { //Εκκίνηση της βλάβης εφόσον βρίσκεται σε κατάσταση ASSIGNED if (ticket.getStatus() == Ticket.Status.ASSIGNED) { //έναρξη εξυπηρέτησης του αιτήματος (μέθοδος startTicket), startTicket(ticket); } } t.tickets.clear(); } private void startTicket(Ticket ticket) { //εκκίνηση επιδιόρθωσης TicketAction ticketAction = new TicketAction("ΕΚΚΙΝΗΣΗ ΑΠΟΚΑΤΑΣΤΑΣΗΣ ΑΙΤΗΜΑΤΟΣ", 0); ticket.addAction(ticketAction); ticket.setStatus(Ticket.Status.IN_PROGRESS); //Η πρόοδος της κάθε ενέργειας προστίθεται κάθε φορά στη συνολική ένδειξη //προόδου του αιτήματος με την μέθοδος addAction addAction(ticket); } private void addAction(Ticket ticket) { int random = 1; int max = 90; //μετρητης βημάτων αποκατάστασης int counter = 1; //όσο η ramdom είναι μικρότερη απο την msx θα προσθέτει //νεα action while (random<max) { //οριζουμε τυχαίο αριθμό random = r.nextInt(max - random)+random+5; String ActionTicket = "ΒΗΜΑ ΑΠΟΚΑΤΑΣΤΑΣΗΣ " + counter; TicketAction ticketAction = new TicketAction(ActionTicket, random); ticket.addAction(ticketAction); ticket.setProgress(random); counter++; } //ΟΛοκλήρωση αιτήματος stopTicket(ticket); } private void stopTicket(Ticket ticket) { //Τερματισμός επιδιόρθωσης TicketAction ticketAction = new TicketAction("ΤΕΡΜΑΤΙΣΜΟΣ ΑΠΟΚΑΤΑΣΤΑΣΗΣ ΑΙΤΗΜΑΤΟΣ", 100); ticket.addAction(ticketAction); ticket.setStatus(Ticket.Status.COMPLETE); ticket.setProgress(100); } public void printActionTickets() { for (Ticket ticket:tickets){ System.out.println("TicketID : " + ticket.getTicketID() + " | ΠΕΡΙΓΡΑΦΗ : " + ticket.getPerigrafi() + " | ΚΑΤΗΓΟΡΙΑ : " + ticket.getCategory() + " | ΚΑΤΑΣΤΑΣΗ : " + ticket.getStatus() + " | ΟΝΟΜΑ ΤΕΧΝΙΚΟΥ : " + ticket.getTechnician().getName() + " | ΠΡΟΟΔΟΣ ΑΙΤΗΜΑΤΟΣ : " + ticket.getProgress()); for (int i = 0; i<ticket.getTicketActions().size(); i++) { System.out.println("ΟΝΟΜΑ ΤΕΧΝΙΚΟΣ : " + ticket.getTechnician().getName() + " | ΠΡΟΟΔΟΣ ΑΙΤΗΜΑΤΟΣ : " + ticket.getTicketActions().get(i).getProgressAction() + " | ΕΝΕΡΓΕΙΕΣ ΓΙΑ ΑΠΟΚΑΤΑΣΤΑΣΗ : " + ticket.getTicketActions().get(i).getAction()); } System.out.println("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------"); System.out.println(""); } } }
nickpsal/TicketingSystem
src/ticketingsystem/Technician.java
1,820
//την προβλεπόμενη διαδικασία, όπου όμως το πλήθος των ενεργειών θα είναι τυχαίο
line_comment
el
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ticketingsystem; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * * @author nickpsal */ public class Technician extends User{ //2. Ένας τεχνικός (Technician) έχει ένα όνομα και μια συγκεκριμένη εξειδίκευση, //η οποία μπορεί να είναι μόνο μια εκ των "HARDWARE, SOFTWARE, NETWORK, COMMUNICATIONS" public enum TechnicianSpec {HARDWARE, SOFTWARE, NETWORK, COMMUNICATIONS}; private TechnicianSpec techSpec; Random r = new Random(); List<Ticket> tickets; //Constructor public Technician(String name, TechnicianSpec techSpec) { super(name); this.techSpec = techSpec; this.tickets = new ArrayList<>(); } // getters - setters public List<Ticket> getTickets() { return tickets; } public void setTickets(List<Ticket> tickets) { this.tickets = tickets; } public void addTicket(Ticket ticket) { tickets.add(ticket); } public void removeTicket(Ticket ticket) { tickets.remove(ticket); } public TechnicianSpec getTechSpec() { return techSpec; } public void setTechSpec(TechnicianSpec techSpec) { this.techSpec = techSpec; } //Για κάθε τεχνικό θα καλεί μέθοδο randomProcessTickets //η οποία θα προσομοιώνει την επίλυση ενός αιτήματος από τον τεχνικό ακολουθώντας //την προβλεπόμενη<SUF> public void randomProcessTickets(Technician t) { for (Ticket ticket:tickets) { //Εκκίνηση της βλάβης εφόσον βρίσκεται σε κατάσταση ASSIGNED if (ticket.getStatus() == Ticket.Status.ASSIGNED) { //έναρξη εξυπηρέτησης του αιτήματος (μέθοδος startTicket), startTicket(ticket); } } t.tickets.clear(); } private void startTicket(Ticket ticket) { //εκκίνηση επιδιόρθωσης TicketAction ticketAction = new TicketAction("ΕΚΚΙΝΗΣΗ ΑΠΟΚΑΤΑΣΤΑΣΗΣ ΑΙΤΗΜΑΤΟΣ", 0); ticket.addAction(ticketAction); ticket.setStatus(Ticket.Status.IN_PROGRESS); //Η πρόοδος της κάθε ενέργειας προστίθεται κάθε φορά στη συνολική ένδειξη //προόδου του αιτήματος με την μέθοδος addAction addAction(ticket); } private void addAction(Ticket ticket) { int random = 1; int max = 90; //μετρητης βημάτων αποκατάστασης int counter = 1; //όσο η ramdom είναι μικρότερη απο την msx θα προσθέτει //νεα action while (random<max) { //οριζουμε τυχαίο αριθμό random = r.nextInt(max - random)+random+5; String ActionTicket = "ΒΗΜΑ ΑΠΟΚΑΤΑΣΤΑΣΗΣ " + counter; TicketAction ticketAction = new TicketAction(ActionTicket, random); ticket.addAction(ticketAction); ticket.setProgress(random); counter++; } //ΟΛοκλήρωση αιτήματος stopTicket(ticket); } private void stopTicket(Ticket ticket) { //Τερματισμός επιδιόρθωσης TicketAction ticketAction = new TicketAction("ΤΕΡΜΑΤΙΣΜΟΣ ΑΠΟΚΑΤΑΣΤΑΣΗΣ ΑΙΤΗΜΑΤΟΣ", 100); ticket.addAction(ticketAction); ticket.setStatus(Ticket.Status.COMPLETE); ticket.setProgress(100); } public void printActionTickets() { for (Ticket ticket:tickets){ System.out.println("TicketID : " + ticket.getTicketID() + " | ΠΕΡΙΓΡΑΦΗ : " + ticket.getPerigrafi() + " | ΚΑΤΗΓΟΡΙΑ : " + ticket.getCategory() + " | ΚΑΤΑΣΤΑΣΗ : " + ticket.getStatus() + " | ΟΝΟΜΑ ΤΕΧΝΙΚΟΥ : " + ticket.getTechnician().getName() + " | ΠΡΟΟΔΟΣ ΑΙΤΗΜΑΤΟΣ : " + ticket.getProgress()); for (int i = 0; i<ticket.getTicketActions().size(); i++) { System.out.println("ΟΝΟΜΑ ΤΕΧΝΙΚΟΣ : " + ticket.getTechnician().getName() + " | ΠΡΟΟΔΟΣ ΑΙΤΗΜΑΤΟΣ : " + ticket.getTicketActions().get(i).getProgressAction() + " | ΕΝΕΡΓΕΙΕΣ ΓΙΑ ΑΠΟΚΑΤΑΣΤΑΣΗ : " + ticket.getTicketActions().get(i).getAction()); } System.out.println("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------"); System.out.println(""); } } }
39990_4
package GameLogic; /** * Class for the Player (stores their score) */ public class GamePlayer { private double score = 0; /** * * @param score new score to be set */ public void setScore(double score) { this.score = score;//Άλλαξα τον τύπο από ακέραιο σε πραγματικό σιπλής ακρίβειας } /** * * @return the current score of the Player */ public double getScore() { return this.score; }//Άλλαξα τον τύπο από ακέραιο σε πραγματικό σιπλής ακρίβειας }
nicktz1408/buzz
src/GameLogic/GamePlayer.java
205
//Άλλαξα τον τύπο από ακέραιο σε πραγματικό σιπλής ακρίβειας
line_comment
el
package GameLogic; /** * Class for the Player (stores their score) */ public class GamePlayer { private double score = 0; /** * * @param score new score to be set */ public void setScore(double score) { this.score = score;//Άλλαξα τον τύπο από ακέραιο σε πραγματικό σιπλής ακρίβειας } /** * * @return the current score of the Player */ public double getScore() { return this.score; }//Άλλαξα τον<SUF> }
4597_7
class Receiver { private String transmittedMessage; // Transmitted message private String p ; // Binary Number of n+1 bits Receiver(String p, String transmittedMessage) { this.p = p; this.transmittedMessage = transmittedMessage; } boolean isMessageCorrectlyTransmitted() { int k = transmittedMessage.length(); int m = p.length(); int[] data = new int[k+m]; int[] gen = new int[m]; for(int i=0;i<k;i++)// Filling the array with the bits of num1 data[i] = Character.getNumericValue(transmittedMessage.charAt(i)); for(int j=0;j<m;j++)// Filling the array with the bits of num2 gen[j] = Character.getNumericValue(p.charAt(j)); // for(int i=0;i<m-1;i++)// Adding n-1 zeros at the end of the starting message(for the 2^n*M) // data[k+i] = 0; int[] rem = new int[m + k];// The array of the remainder bits for(int i=0;i<m;i++) rem[i] = data[i]; int[] zeros = new int[m]; for(int i=0;i<m;i++) zeros[i]=0; // Dividing 2^n*M with P using // Δυαδική πρόσθεση χωρίς κρατούμενο, oυσιαστικά η πράξη XOR int l, msb; for(int i=0;i<k;i++) { l = 0; msb = rem[i]; for(int j=i;j<m+i;j++) { if(msb == 0) rem[j]=xor(rem[j],zeros[l]); else rem[j]=xor(rem[j],gen[l]); l++; } rem[m+i]=data[m+i]; } // Checks if there is a reminder for(int i=0;i<k+m-1;i++) if (rem[i] != 0) return false; return true; // Returns true if reminder is equal to 0 } private static int xor(int x,int y) { if(x == y) return(0); else return(1); } }
nikopetr/Cyclic-Redundancy-Check-CRC
Receiver.java
603
// Δυαδική πρόσθεση χωρίς κρατούμενο, oυσιαστικά η πράξη XOR
line_comment
el
class Receiver { private String transmittedMessage; // Transmitted message private String p ; // Binary Number of n+1 bits Receiver(String p, String transmittedMessage) { this.p = p; this.transmittedMessage = transmittedMessage; } boolean isMessageCorrectlyTransmitted() { int k = transmittedMessage.length(); int m = p.length(); int[] data = new int[k+m]; int[] gen = new int[m]; for(int i=0;i<k;i++)// Filling the array with the bits of num1 data[i] = Character.getNumericValue(transmittedMessage.charAt(i)); for(int j=0;j<m;j++)// Filling the array with the bits of num2 gen[j] = Character.getNumericValue(p.charAt(j)); // for(int i=0;i<m-1;i++)// Adding n-1 zeros at the end of the starting message(for the 2^n*M) // data[k+i] = 0; int[] rem = new int[m + k];// The array of the remainder bits for(int i=0;i<m;i++) rem[i] = data[i]; int[] zeros = new int[m]; for(int i=0;i<m;i++) zeros[i]=0; // Dividing 2^n*M with P using // Δυαδική πρόσθεση<SUF> int l, msb; for(int i=0;i<k;i++) { l = 0; msb = rem[i]; for(int j=i;j<m+i;j++) { if(msb == 0) rem[j]=xor(rem[j],zeros[l]); else rem[j]=xor(rem[j],gen[l]); l++; } rem[m+i]=data[m+i]; } // Checks if there is a reminder for(int i=0;i<k+m-1;i++) if (rem[i] != 0) return false; return true; // Returns true if reminder is equal to 0 } private static int xor(int x,int y) { if(x == y) return(0); else return(1); } }
345_8
package servlets; import java.io.IOException; import java.io.PrintWriter; import javax.swing.*; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; //import static javax.swing.JOptionPane.showMessageDialog; /** * Servlet implementation class PatientServlet */ @WebServlet("/PatientServlet") public class PatientServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * Default constructor. */ public PatientServlet() { // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // response.getWriter().append("Served at: ").append(request.getContextPath()); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); String name = request.getParameter("firstName"); String infobutton = request.getParameter("infoButton"); //String surname = request.getParameter("lastName"); out.println("<!DOCTYPE html>" + "<html>" + "<head>" + "<title> HomePage </title>" + "<meta charset=\"utf-8\">" + "<style>" + " h1, h2, h3 , h4{" + " color:white;" + " text-align:center;" + " }" + " body {" + " background-image: url(\"doc.jpeg\");" + " background-size:100%;\r\n" + " background-repeat: no-repeat;" + " background-color: #cccccc;" + "}" + " ul {" + " list-style-type: none;" + " margin: 0;" + " padding: 0;" + " overflow: hidden;" + " background-color:#0070C9;" + " }" + " li {" + " float: left;" + " }" + " li a {" + " display: block;" + " color: white;" + " text-align: center;" + " padding: 14px 16px;" + " text-decoration: none;" + " }" + "/* Αλλαζω το χρωμα του link σε μαυρο κατα την προσπεραση του κερσωρα πανω απο αυτο */" + " li a:hover {" + " background-color: black;" + " border-bottom: 1px solid white;" + " }" + "" + "" + " *{" + " margin:0;" + " padding: 0;" + " box-sizing: border-box;" + " }" + " html{" + " height: 100%;" + " }" + " body{" + " font-family: 'Segoe UI', sans-serif;;" + " font-size: 1rem;" + " line-height: 1.6;" + " height: 100%;" + " }" + " *{" + " margin:0;" + " padding: 0;" + " box-sizing: border-box;" + " }" + " html{" + " height: 100%;" + " }" + " body{" + " font-family: 'Segoe UI', sans-serif;;" + " font-size: 1rem;" + " line-height: 1.6;" + " height: 100%;" + " }" + "/*Μεγενθυνεται το κειμενο καθως περναω το ποντικι μου πανω απο αυτο */" + " .myheader2:hover, .myheader4:hover, .myheader3:hover {" + " transform: scale(1.5);" + " }" + "</style>" + "</head>" + "<body>" + " <center>" + " <ul>" + " <li><a href=\"index.html\">log out</a></li>" + " </ul>" + "</center>" + "<h1>Welcome</h1> <center> <h2>" + name + " </h2> </center>" + "<br>" + "<form action=\"UserServlet\" method=\"POST\">" + "<input type=\"submit\" name=\"infoButton\" value=\"See my information\">" + "</form>" + "<br>" + "<br>" + "<br>" + "<form action=\"AppointmentServlet\" method=\"POST\">" + "<input type=\"submit\" name=\"appoButton\" value=\"Appointments\">" + "</form>" + "</body>" + "</html>" + ""); // if ("See my information".equals(infobutton)) // { // basicClasses.Patient.ViewScheduledAppointments(); // } // else if ("button2".equals(button)) // { // PatientServlet.showMessage(); // } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } // public void showMessage() { // JOptionPane.showMessageDialog(null, "Thank you for using Java", "Yay, java", JOptionPane.PLAIN_MESSAGE); // } }
nikosdapergolas/java_hospital_application
javaWebApp/src/main/java/servlets/PatientServlet.java
1,543
/* Αλλαζω το χρωμα του link σε μαυρο κατα την προσπεραση του κερσωρα πανω απο αυτο */
block_comment
el
package servlets; import java.io.IOException; import java.io.PrintWriter; import javax.swing.*; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; //import static javax.swing.JOptionPane.showMessageDialog; /** * Servlet implementation class PatientServlet */ @WebServlet("/PatientServlet") public class PatientServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * Default constructor. */ public PatientServlet() { // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // response.getWriter().append("Served at: ").append(request.getContextPath()); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); String name = request.getParameter("firstName"); String infobutton = request.getParameter("infoButton"); //String surname = request.getParameter("lastName"); out.println("<!DOCTYPE html>" + "<html>" + "<head>" + "<title> HomePage </title>" + "<meta charset=\"utf-8\">" + "<style>" + " h1, h2, h3 , h4{" + " color:white;" + " text-align:center;" + " }" + " body {" + " background-image: url(\"doc.jpeg\");" + " background-size:100%;\r\n" + " background-repeat: no-repeat;" + " background-color: #cccccc;" + "}" + " ul {" + " list-style-type: none;" + " margin: 0;" + " padding: 0;" + " overflow: hidden;" + " background-color:#0070C9;" + " }" + " li {" + " float: left;" + " }" + " li a {" + " display: block;" + " color: white;" + " text-align: center;" + " padding: 14px 16px;" + " text-decoration: none;" + " }" + "/* Αλλαζω το χρωμα<SUF>*/" + " li a:hover {" + " background-color: black;" + " border-bottom: 1px solid white;" + " }" + "" + "" + " *{" + " margin:0;" + " padding: 0;" + " box-sizing: border-box;" + " }" + " html{" + " height: 100%;" + " }" + " body{" + " font-family: 'Segoe UI', sans-serif;;" + " font-size: 1rem;" + " line-height: 1.6;" + " height: 100%;" + " }" + " *{" + " margin:0;" + " padding: 0;" + " box-sizing: border-box;" + " }" + " html{" + " height: 100%;" + " }" + " body{" + " font-family: 'Segoe UI', sans-serif;;" + " font-size: 1rem;" + " line-height: 1.6;" + " height: 100%;" + " }" + "/*Μεγενθυνεται το κειμενο καθως περναω το ποντικι μου πανω απο αυτο */" + " .myheader2:hover, .myheader4:hover, .myheader3:hover {" + " transform: scale(1.5);" + " }" + "</style>" + "</head>" + "<body>" + " <center>" + " <ul>" + " <li><a href=\"index.html\">log out</a></li>" + " </ul>" + "</center>" + "<h1>Welcome</h1> <center> <h2>" + name + " </h2> </center>" + "<br>" + "<form action=\"UserServlet\" method=\"POST\">" + "<input type=\"submit\" name=\"infoButton\" value=\"See my information\">" + "</form>" + "<br>" + "<br>" + "<br>" + "<form action=\"AppointmentServlet\" method=\"POST\">" + "<input type=\"submit\" name=\"appoButton\" value=\"Appointments\">" + "</form>" + "</body>" + "</html>" + ""); // if ("See my information".equals(infobutton)) // { // basicClasses.Patient.ViewScheduledAppointments(); // } // else if ("button2".equals(button)) // { // PatientServlet.showMessage(); // } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } // public void showMessage() { // JOptionPane.showMessageDialog(null, "Thank you for using Java", "Yay, java", JOptionPane.PLAIN_MESSAGE); // } }
1056_0
package gr.northdigital.gdpr; import javax.ws.rs.ApplicationPath; import gr.northdigital.gdpr.models.GSession; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.glassfish.jersey.server.ResourceConfig; import java.security.Security; import java.util.ArrayList; import java.util.Collections; import java.util.List; @ApplicationPath("/") public class AppConfig extends ResourceConfig { private static ArrayList<GSession> _sessions = new ArrayList<>(); /** * Κάθε πρόσβαση στην list πρέπει να γίνεται με κλήση μεθόδων της sessions για να είναι thread safe h list. * Σε κάθε άλλη περίπτωση πρέπει να γίνει χρήση της syncronize. * Ας πούμε αν χρησιμοποιήσουμε έναν iterator αυτός δεν συγχρονίζεται οπότε ενώ είμαστε σε κάποιο node μπορεί * να τον πειράξει και κάποιο άλλο thread οπότε πρέπει να συγχρονίσουμε την πρόσβαση με χρήση της syncronize. */ public static List<GSession> sessions = Collections.synchronizedList(_sessions); public AppConfig() { Security.addProvider(new BouncyCastleProvider()); } }
northdigital/GDPRAppServer
src/main/java/gr/northdigital/gdpr/AppConfig.java
469
/** * Κάθε πρόσβαση στην list πρέπει να γίνεται με κλήση μεθόδων της sessions για να είναι thread safe h list. * Σε κάθε άλλη περίπτωση πρέπει να γίνει χρήση της syncronize. * Ας πούμε αν χρησιμοποιήσουμε έναν iterator αυτός δεν συγχρονίζεται οπότε ενώ είμαστε σε κάποιο node μπορεί * να τον πειράξει και κάποιο άλλο thread οπότε πρέπει να συγχρονίσουμε την πρόσβαση με χρήση της syncronize. */
block_comment
el
package gr.northdigital.gdpr; import javax.ws.rs.ApplicationPath; import gr.northdigital.gdpr.models.GSession; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.glassfish.jersey.server.ResourceConfig; import java.security.Security; import java.util.ArrayList; import java.util.Collections; import java.util.List; @ApplicationPath("/") public class AppConfig extends ResourceConfig { private static ArrayList<GSession> _sessions = new ArrayList<>(); /** * Κάθε πρόσβαση στην<SUF>*/ public static List<GSession> sessions = Collections.synchronizedList(_sessions); public AppConfig() { Security.addProvider(new BouncyCastleProvider()); } }
20548_2
/* MIT License Copyright (c) 2024 Nikolaos Siatras Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package jregenerator.UI.UITools; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Desktop; import java.awt.GridLayout; import java.net.URI; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingWorker; /** * * @author Nikos Siatras - https://github.com/nsiatras */ public class UITools { static { } public static void Initialize() { System.out.println("UI Tools Initialized"); } public static void ShowPleaseWaitDialog(String dialogTitle, String description, javax.swing.JFrame parentForm, Runnable workToDo) { // Σπάσε το description σε γραμμές και πέρασε το στο descriptionLines Array final String[] descriptionLines = description.split("\n"); final int totalLines = descriptionLines.length + 2; final JDialog loading = new JDialog(parentForm); final JPanel p1 = new JPanel(new GridLayout(totalLines, 1)); p1.add(new JLabel(" "), BorderLayout.CENTER); for (String line : descriptionLines) { final JLabel lbl = new JLabel(" " + line + " "); p1.add(lbl, BorderLayout.CENTER); } p1.add(new JLabel(" "), BorderLayout.CENTER); //p1.add(new JLabel(" "), BorderLayout.CENTER); loading.setTitle(dialogTitle); loading.setUndecorated(false); loading.getContentPane().add(p1); loading.pack(); loading.setLocationRelativeTo(parentForm); loading.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); loading.setModal(true); // Create a new Swing Worker in order to run // the "workToDo" runnable and then displose the "loading dialog" SwingWorker<String, Void> worker = new SwingWorker<String, Void>() { @Override protected String doInBackground() throws Exception { workToDo.run(); return null; } @Override protected void done() { loading.dispose(); } }; worker.execute(); // Show the loading dialog loading.setVisible(true); try { // Wait for workier to finish and then dispose the loading form worker.get(); //here the parent thread waits for completion loading.dispose(); } catch (Exception ex) { } } public static boolean OpenWebpage(String url) { try { URI uri = new URI(url); Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null; if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) { try { desktop.browse(uri); return true; } catch (Exception e) { e.printStackTrace(); } } } catch (Exception ex) { } return false; } }
nsiatras/JREGenerator
Netbeans Project/src/jregenerator/UI/UITools/UITools.java
946
// Σπάσε το description σε γραμμές και πέρασε το στο descriptionLines Array
line_comment
el
/* MIT License Copyright (c) 2024 Nikolaos Siatras Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package jregenerator.UI.UITools; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Desktop; import java.awt.GridLayout; import java.net.URI; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingWorker; /** * * @author Nikos Siatras - https://github.com/nsiatras */ public class UITools { static { } public static void Initialize() { System.out.println("UI Tools Initialized"); } public static void ShowPleaseWaitDialog(String dialogTitle, String description, javax.swing.JFrame parentForm, Runnable workToDo) { // Σπάσε το<SUF> final String[] descriptionLines = description.split("\n"); final int totalLines = descriptionLines.length + 2; final JDialog loading = new JDialog(parentForm); final JPanel p1 = new JPanel(new GridLayout(totalLines, 1)); p1.add(new JLabel(" "), BorderLayout.CENTER); for (String line : descriptionLines) { final JLabel lbl = new JLabel(" " + line + " "); p1.add(lbl, BorderLayout.CENTER); } p1.add(new JLabel(" "), BorderLayout.CENTER); //p1.add(new JLabel(" "), BorderLayout.CENTER); loading.setTitle(dialogTitle); loading.setUndecorated(false); loading.getContentPane().add(p1); loading.pack(); loading.setLocationRelativeTo(parentForm); loading.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); loading.setModal(true); // Create a new Swing Worker in order to run // the "workToDo" runnable and then displose the "loading dialog" SwingWorker<String, Void> worker = new SwingWorker<String, Void>() { @Override protected String doInBackground() throws Exception { workToDo.run(); return null; } @Override protected void done() { loading.dispose(); } }; worker.execute(); // Show the loading dialog loading.setVisible(true); try { // Wait for workier to finish and then dispose the loading form worker.get(); //here the parent thread waits for completion loading.dispose(); } catch (Exception ex) { } } public static boolean OpenWebpage(String url) { try { URI uri = new URI(url); Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null; if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) { try { desktop.browse(uri); return true; } catch (Exception e) { e.printStackTrace(); } } } catch (Exception ex) { } return false; } }
19707_1
import java.util.*; public class Hotel { String name; List<Room> rooms = new ArrayList<>(); List<Reservation> reservations = new ArrayList<>(); //pretty-prints a map of reservations and rooms, in relation to each day of the month public void reservationCalendar(){ //Δωμάτιο 01 02 03 .. String dom = "Δωμάτιο "; System.out.print(dom); for(int i = 1; i <= 30; i++){ System.out.print((i < 10 ? "0" : "") + i + " "); } int roomCountDigits = getDigitsNum(rooms.size()); for(Room room : rooms){ System.out.println(); //[[RoomId]] (spaces) int spacePostfix = dom.length() - Integer.toString(room.getId()).length(); String spaces = ""; for(int k = 0;k < spacePostfix;k++){ spaces += " "; } System.out.print(room.getId() + spaces); // _ * _ * _ for(Reservation res : room.getReservations()){ if(res == null){ System.out.print("_ "); }else{ System.out.print("* "); } } } } //returns digits of some integer 'num' //utility method, only used for pretty-print reasons private int getDigitsNum(int num){ return String.valueOf(num).length(); } //calculates income from only the room which has the specified id public double calculateIncome(int roomId){ return rooms.stream().filter(x -> x.getId() == roomId).mapToDouble(x -> x.totalCost()).sum(); } //calculates income from all the rooms public double calculateIncome(){ return rooms.stream().mapToDouble(x -> x.totalCost()).sum(); } public void addRoom(Room r){ rooms.add(r); } //adds reservation to first available room public int addReservation(Reservation r){ for(Room room : rooms){ if(room.addReservation(r)){ reservations.add(r); r.setRoom(room); return room.getId(); } } return 0; } //tries to cancel reservation. If success, it prints it on the screen and returns true //else it returns false and prints on the screen public boolean cancelReservation(int id){ Reservation res = findReservation(id); if(res == null){ System.out.println("Reservation " + id + " not cancelled because it does not exist."); return false; } Room r = res.getRoom(); if(r == null){ System.out.println("Reservation " + id + " not cancelled because it's not assigned to any room."); return false; } boolean result = r.cancelReservation(id); if(result){ System.out.println("Reservation " + id + " cancelled."); }else{ System.out.println("Reservation " + id + " can not be cancelled."); } return result; } //returns a room with id or null public Room findRoom(int id){ Optional<Room> r = rooms.stream().filter(x -> x.getId() == id).findFirst(); if(r.isPresent()){ return r.get(); } return null; } //returns a reservation by id or null public Reservation findReservation(int id){ Optional<Reservation> r = reservations.stream().filter(x -> x.getId() == id).findFirst(); if(r.isPresent()){ return r.get(); } return null; } public List<Room> getRooms(){ return rooms; } public List<Reservation> getReservations(){ return reservations; } }
ntakouris/uni9
HotelReservationServiceJava/Hotel.java
887
//Δωμάτιο 01 02 03 ..
line_comment
el
import java.util.*; public class Hotel { String name; List<Room> rooms = new ArrayList<>(); List<Reservation> reservations = new ArrayList<>(); //pretty-prints a map of reservations and rooms, in relation to each day of the month public void reservationCalendar(){ //Δωμάτιο 01<SUF> String dom = "Δωμάτιο "; System.out.print(dom); for(int i = 1; i <= 30; i++){ System.out.print((i < 10 ? "0" : "") + i + " "); } int roomCountDigits = getDigitsNum(rooms.size()); for(Room room : rooms){ System.out.println(); //[[RoomId]] (spaces) int spacePostfix = dom.length() - Integer.toString(room.getId()).length(); String spaces = ""; for(int k = 0;k < spacePostfix;k++){ spaces += " "; } System.out.print(room.getId() + spaces); // _ * _ * _ for(Reservation res : room.getReservations()){ if(res == null){ System.out.print("_ "); }else{ System.out.print("* "); } } } } //returns digits of some integer 'num' //utility method, only used for pretty-print reasons private int getDigitsNum(int num){ return String.valueOf(num).length(); } //calculates income from only the room which has the specified id public double calculateIncome(int roomId){ return rooms.stream().filter(x -> x.getId() == roomId).mapToDouble(x -> x.totalCost()).sum(); } //calculates income from all the rooms public double calculateIncome(){ return rooms.stream().mapToDouble(x -> x.totalCost()).sum(); } public void addRoom(Room r){ rooms.add(r); } //adds reservation to first available room public int addReservation(Reservation r){ for(Room room : rooms){ if(room.addReservation(r)){ reservations.add(r); r.setRoom(room); return room.getId(); } } return 0; } //tries to cancel reservation. If success, it prints it on the screen and returns true //else it returns false and prints on the screen public boolean cancelReservation(int id){ Reservation res = findReservation(id); if(res == null){ System.out.println("Reservation " + id + " not cancelled because it does not exist."); return false; } Room r = res.getRoom(); if(r == null){ System.out.println("Reservation " + id + " not cancelled because it's not assigned to any room."); return false; } boolean result = r.cancelReservation(id); if(result){ System.out.println("Reservation " + id + " cancelled."); }else{ System.out.println("Reservation " + id + " can not be cancelled."); } return result; } //returns a room with id or null public Room findRoom(int id){ Optional<Room> r = rooms.stream().filter(x -> x.getId() == id).findFirst(); if(r.isPresent()){ return r.get(); } return null; } //returns a reservation by id or null public Reservation findReservation(int id){ Optional<Reservation> r = reservations.stream().filter(x -> x.getId() == id).findFirst(); if(r.isPresent()){ return r.get(); } return null; } public List<Room> getRooms(){ return rooms; } public List<Reservation> getReservations(){ return reservations; } }
3355_0
package com.nicktz.boat; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; import java.util.ArrayList; public class TestsList extends AppCompatActivity implements TestsAdapter.OnQuestionListener { private ArrayList<Integer> tests; private TextView message; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tests_list); tests = new ArrayList<>(); message = findViewById(R.id.message); initTests(); } /** * Συνάρτηση που δημιουργεί τον πίνακα των τεστ. */ private void initTests(){ MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1); int testsSize = dbHandler.getTestSize(); message.setText(getString(R.string.number_of_tests) + ": " + testsSize); if (testsSize == 0) return; int[][] tests = new int[testsSize][2]; tests = dbHandler.getTests();; for (int i=0; i<testsSize; i++) this.tests.add(tests[i][1]); initRecyclerView(); } /** * Συνάρτηση που δημιουργεί το RecyclerView. */ private void initRecyclerView(){ RecyclerView recyclerView= findViewById(R.id.recycler_view); TestsAdapter adapter = new TestsAdapter(tests, this, this); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new LinearLayoutManager(this)); } /** * Συνάρτηση που όταν ο χρήστης κάνει κλικ σε ένα τεστ, τον οδηγεί * στο activity με τις ερωτήσεις του συγκεκριμένου τεστ. */ @Override public void onQuestionClick(int questionId) { Intent i = new Intent(this, QuestionsList.class); i.putExtra("testId", questionId + 1); i.putExtra("code", "previous_attempts"); startActivity(i); } }
nttzamos/boating-license-exam
app/src/main/java/com/nicktz/boat/TestsList.java
589
/** * Συνάρτηση που δημιουργεί τον πίνακα των τεστ. */
block_comment
el
package com.nicktz.boat; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; import java.util.ArrayList; public class TestsList extends AppCompatActivity implements TestsAdapter.OnQuestionListener { private ArrayList<Integer> tests; private TextView message; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tests_list); tests = new ArrayList<>(); message = findViewById(R.id.message); initTests(); } /** * Συνάρτηση που δημιουργεί<SUF>*/ private void initTests(){ MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1); int testsSize = dbHandler.getTestSize(); message.setText(getString(R.string.number_of_tests) + ": " + testsSize); if (testsSize == 0) return; int[][] tests = new int[testsSize][2]; tests = dbHandler.getTests();; for (int i=0; i<testsSize; i++) this.tests.add(tests[i][1]); initRecyclerView(); } /** * Συνάρτηση που δημιουργεί το RecyclerView. */ private void initRecyclerView(){ RecyclerView recyclerView= findViewById(R.id.recycler_view); TestsAdapter adapter = new TestsAdapter(tests, this, this); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new LinearLayoutManager(this)); } /** * Συνάρτηση που όταν ο χρήστης κάνει κλικ σε ένα τεστ, τον οδηγεί * στο activity με τις ερωτήσεις του συγκεκριμένου τεστ. */ @Override public void onQuestionClick(int questionId) { Intent i = new Intent(this, QuestionsList.class); i.putExtra("testId", questionId + 1); i.putExtra("code", "previous_attempts"); startActivity(i); } }
23618_1
package delete.me; public class ToEnum { public static void main(String[] args) { // SUNDAY("D1", "D1 - Sunday (Κυριακή)") // ,MONDAY("D2", "D2 - Monday (Δευτέρα)") String s = "Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec"; String [] parts = s.split(" \\| "); StringBuffer sb = new StringBuffer(); for (String part : parts) { sb.append("\t\t"); if (sb.length() > 0) { sb.append(", "); } sb.append(part.toUpperCase()); sb.append("(\""); sb.append(part); sb.append("\", "); sb.append("\""); sb.append(part); sb.append("\")\n"); } System.out.println(sb.toString()); } }
ocmc-olw/ioc-liturgical-schemas
ioc.liturgical.schemas/src/test/java/delete/me/ToEnum.java
250
// ,MONDAY("D2", "D2 - Monday (Δευτέρα)")
line_comment
el
package delete.me; public class ToEnum { public static void main(String[] args) { // SUNDAY("D1", "D1 - Sunday (Κυριακή)") // ,MONDAY("D2", "D2<SUF> String s = "Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec"; String [] parts = s.split(" \\| "); StringBuffer sb = new StringBuffer(); for (String part : parts) { sb.append("\t\t"); if (sb.length() > 0) { sb.append(", "); } sb.append(part.toUpperCase()); sb.append("(\""); sb.append(part); sb.append("\", "); sb.append("\""); sb.append(part); sb.append("\")\n"); } System.out.println(sb.toString()); } }
17667_6
package net.ages.alwb.utils.nlp.utils; import java.io.InputStream; import java.text.Normalizer; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import opennlp.tools.lemmatizer.SimpleLemmatizer; import opennlp.tools.tokenize.SimpleTokenizer; import opennlp.tools.tokenize.Tokenizer; import net.ages.alwb.utils.core.generics.MultiMapWithList; import org.ocmc.ioc.liturgical.utils.GeneralUtils; import org.ocmc.ioc.liturgical.schemas.models.db.docs.nlp.ConcordanceLine; import org.ocmc.ioc.liturgical.schemas.models.db.docs.nlp.WordInflected; import org.ocmc.ioc.liturgical.utils.ErrorUtils; import org.ocmc.ioc.liturgical.utils.FileUtils; import net.ages.alwb.utils.nlp.constants.BETA_CODES; import net.ages.alwb.utils.nlp.models.CharacterInfo; public class NlpUtils { private static final Logger logger = LoggerFactory.getLogger(NlpUtils.class); private static SimpleLemmatizer lemmatizer; private static String[] posTags = "CC,CD,DT,EX,FW,IN,JJ,JJR,JJS,MD,NN,NNN,NNS,PDT,POS,PRP,PRP$,RB,RBR,RBS,RP,TO,UH,VB,VBD,VBG,VBN,VBP,VBZ,WDT,WP,WP$,WRB".split(","); /** * Creates a map of each character in the string. * You can use the GreekCharacter to get * its Unicode block and numeric value. * @param s * @return */ public static List<CharacterInfo> getCharacterInfo(String s) { List<CharacterInfo> result = new ArrayList<CharacterInfo>(); for (char c : s.toCharArray()) { result.add(new CharacterInfo(c)); } return result; } /** * Gives the string index for points at which the two strings differ. * The comparison is based on the Unicode numeric value for each char * * This method calls its overloaded version that takes List<CharacterInfo> as the parameters. * * @param s1 * @param s2 * @return */ public static List<Integer> getDiff(String s1, String s2) { List<Integer> result = new ArrayList<Integer>(); if (BETA_CODES.toBetaCode(s1).equals(BETA_CODES.toBetaCode(s2))) { List<CharacterInfo> list1 = getCharacterInfo(s1); List<CharacterInfo> list2 = getCharacterInfo(s2); result = getDiff(list1, list2); } return result; } /** * Gives the string index for points at which the two character lists differ. * The comparison is based on the Unicode numeric value for each char * @param s1 * @param s2 * @return */ public static List<Integer> getDiff(List<CharacterInfo> list1, List<CharacterInfo> list2) { List<Integer> result = new ArrayList<Integer>(); if (list1.size() == list2.size()) { int j = list1.size(); for (int i=0; i < j; i++) { if (list1.get(i).value() != list2.get(i).value()) { result.add(new Integer(i)); } } } return result; } /** * Takes a JsonArray of texts, and creates a unique set of tokens * with frequency counts. * * @param texts * @param convertToLowerCase, if true converts each text to its lowercase form * @param ignoreLatin - if true, will not include a token that contains a Latin character * @param ignoreNumbers - if true, will not include a token that contains numbers * @param removeDiacritics - if true, removes accent marks, etc. * @param numberOfConcordanceEntries - the number of concordance entries you want * @return */ public static MultiMapWithList<WordInflected, ConcordanceLine> getWordListWithFrequencies( JsonArray texts , boolean convertToLowerCase , boolean ignorePunctuation , boolean ignoreLatin , boolean ignoreNumbers , boolean removeDiacritics , int numberOfConcordanceEntries ) { int concordSize = numberOfConcordanceEntries; if (concordSize == 0) { concordSize = 1; } MultiMapWithList<WordInflected, ConcordanceLine> result = new MultiMapWithList<WordInflected, ConcordanceLine>(concordSize); logger.info("tokenizing " + texts.size() + " texts"); for (JsonElement e : texts) { JsonObject o = e.getAsJsonObject(); String id = o.get("n.id").getAsString(); String value = o.get("n.value").getAsString(); List<String> theTokens = getTokens( value , convertToLowerCase , ignorePunctuation , ignoreLatin , ignoreNumbers , removeDiacritics ); for (String token : theTokens) { String rawToken = token; if (result.mapSimpleContainsValue(token)) { WordInflected word = result.getValueFromMapSimple(token); word.setFrequency(word.getFrequency()+1); result.addValueToMapSimple(token, word); } else { WordInflected word = new WordInflected(token, 1); ConcordanceLine line = getConcordanceLine( rawToken , 1 , value , id , 100 , convertToLowerCase ); word.setExampleId(id); word.setExampleLeftContext(line.getContextLeft()); word.setExampleRightContext(line.getContextRight()); result.addValueToMapSimple(token, word); } if (numberOfConcordanceEntries > 0) { int seq = result.listSize(token) + 1; ConcordanceLine line = getConcordanceLine( rawToken , seq , value , id , 100 , convertToLowerCase ); result.addValueToMapWithLists(token, line); } } } logger.info("creating WordInflected for " + result.getMapSimple().size() + " tokens"); logger.info("done"); return result; } /** * * @param text - the text within which the token occurs * @param id - the ID of the text * @param token - the token (appears in center of concordance line) * @param width - number of characters to left and right * @return */ public static ConcordanceLine getConcordanceLine( String rawToken , int seq , String text , String id , int width , boolean lowerCase ) { int halfWidth = width / 2; int rawTokenLength = rawToken.length(); int tokenStartIndex = 0; if (lowerCase) { tokenStartIndex = text.toLowerCase().indexOf(rawToken); } else { tokenStartIndex = text.indexOf(rawToken); } int tokenEndIndex = tokenStartIndex + rawTokenLength; int leftStartIndex = tokenStartIndex - halfWidth; String left = ""; if (leftStartIndex > 0) { try { left = text.substring(tokenStartIndex - halfWidth, tokenStartIndex); } catch (Exception e) { ErrorUtils.report(logger, e); } } else { try { left = text.substring(0, tokenStartIndex); } catch (Exception e) { ErrorUtils.report(logger, e); } int padding = halfWidth - left.length(); for (int i = 0; i < padding; i++) { left = " " + left; } } int rightEndIndex = tokenEndIndex + halfWidth; String right = ""; if (rightEndIndex <= text.length()) { try { right = text.substring(tokenEndIndex, rightEndIndex); } catch (Exception e) { ErrorUtils.report(logger, e); } } else { try { right = text.substring(tokenEndIndex, text.length()); } catch (Exception e) { ErrorUtils.report(logger, e); } int padding = halfWidth - right.length(); for (int i = 0; i < padding; i++) { right = right + " "; } } return new ConcordanceLine( rawToken , seq , width , id , left , right ); } public static JsonArray getTokensAsJsonArray( String text , boolean convertToLowerCase , boolean ignorePunctuation , boolean ignoreLatin , boolean ignoreNumbers , boolean removeDiacritics ) { JsonArray result = new JsonArray(); String previous = ""; for (String token : getTokens( text , convertToLowerCase , ignorePunctuation , ignoreLatin , ignoreNumbers , removeDiacritics )) { if (token.equals("̓")) { // we want to treated a contraction as a single token for our purposes result.remove(result.size()-1); token = previous + " " + token; } result.add(token); previous = token; } return result; } public static String getLemma(String word) { String original = word.trim().toLowerCase(); String result = original; try { if (lemmatizer == null) { InputStream is = NlpUtils.class.getResourceAsStream("/models/en-lemmatizer.dict"); lemmatizer = new SimpleLemmatizer(is); is.close(); } for (String tag : posTags) { result = lemmatizer.lemmatize(original, tag); if (! result.equals(original)) { result = result + "." + tag; break; } } } catch (Exception e) { ErrorUtils.report(logger, e); } return result; } public static List<String> getTokens( String text , boolean convertToLowerCase , boolean ignorePunctuation , boolean ignoreLatin , boolean ignoreNumbers , boolean removeDiacritics ) { List<String> result = new ArrayList<String>(); String regExAlpha = ".*[a-zA-Z].*"; String regExAlphaNumeric = ".*[a-zA-Z0-9].*"; String punct = "[;˙·,.;!?\\-(){}\\[\\]\\/:<>%͵·\"'`’_«»‘*•+…‧′|]"; Pattern punctPattern = Pattern.compile(punct); // punctuation String regEx = regExAlpha; if (ignoreNumbers) { regEx = regExAlphaNumeric; } boolean include = true; Tokenizer tokenizer = SimpleTokenizer.INSTANCE; for (String token : tokenizer.tokenize(GeneralUtils.toNfc(text))) { String a = token; if (convertToLowerCase) { token = token.toLowerCase(); } if (removeDiacritics) { token = Normalizer.normalize(token, Normalizer.Form.NFD) .replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); } include = true; if (ignorePunctuation && punctPattern.matcher(token).matches()) { include = false; } if (include && (ignoreLatin || ignoreNumbers)) { if (token.matches(regEx)) { include = false; } } if (include) { result.add(token); } } return result; } public static void main(String[] args) { String test = "(Εἰς τὰς καθημερινὰς ψάλλεται τό· \"ὁ ἐν ἁγίοις θαυμαστός\". Αἱ δεσποτικαὶ ἑορταὶ ἔχουν ἴδιον Εἰσοδικόν.)"; // String test = "(Ψαλλομένου τοῦ Ἀπολυτικίου, γίνεται ὑπὸ τοῦ Ἱερέως ἡ Εἴσοδος μετὰ τοῦ Εὐαγγελίου. Ὁ Ἱερεὺς προσεύχεται χαμηλοφώνως τὴν ἑπομένην εὐχήν:)"; // String test = "(τοῦ Ἀπο γίνεται ὑπὸ τοῦ Ἱερέως ἡ Εἴσοδος μετὰ τοῦ Εὐαγγελίου. Ὁ Ἱερεὺς προσεύχεται χαμηλοφώνως τὴν ἑπομένην εὐχήν:)"; System.out.println(test); System.out.println("\nTokens:"); for (String token : getTokens( test , true // convertToLowerCase , true // ignorePunctuation , true // ignoreLatin , true // ignoreNumbers , true // removeDiacritics )) { System.out.println(token); } String rawToken = "Εἰς"; ConcordanceLine result = getConcordanceLine( rawToken ,1 , test , "gr_gr_cog~client~cl.eu.lichrysbasil.R005" , 80 , true ); System.out.println(result.toString("*")); rawToken = "ἁγίοις"; result = getConcordanceLine( rawToken , 2 , test , "gr_gr_cog~client~cl.eu.lichrysbasil.R005" , 80 , true ); System.out.println(result.toString("*")); } }
ocmc-olw/ioc-liturgical-ws
src/main/java/net/ages/alwb/utils/nlp/utils/NlpUtils.java
3,825
// String test = "(Ψαλλομένου τοῦ Ἀπολυτικίου, γίνεται ὑπὸ τοῦ Ἱερέως ἡ Εἴσοδος μετὰ τοῦ Εὐαγγελίου. Ὁ Ἱερεὺς προσεύχεται χαμηλοφώνως τὴν ἑπομένην εὐχήν:)";
line_comment
el
package net.ages.alwb.utils.nlp.utils; import java.io.InputStream; import java.text.Normalizer; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import opennlp.tools.lemmatizer.SimpleLemmatizer; import opennlp.tools.tokenize.SimpleTokenizer; import opennlp.tools.tokenize.Tokenizer; import net.ages.alwb.utils.core.generics.MultiMapWithList; import org.ocmc.ioc.liturgical.utils.GeneralUtils; import org.ocmc.ioc.liturgical.schemas.models.db.docs.nlp.ConcordanceLine; import org.ocmc.ioc.liturgical.schemas.models.db.docs.nlp.WordInflected; import org.ocmc.ioc.liturgical.utils.ErrorUtils; import org.ocmc.ioc.liturgical.utils.FileUtils; import net.ages.alwb.utils.nlp.constants.BETA_CODES; import net.ages.alwb.utils.nlp.models.CharacterInfo; public class NlpUtils { private static final Logger logger = LoggerFactory.getLogger(NlpUtils.class); private static SimpleLemmatizer lemmatizer; private static String[] posTags = "CC,CD,DT,EX,FW,IN,JJ,JJR,JJS,MD,NN,NNN,NNS,PDT,POS,PRP,PRP$,RB,RBR,RBS,RP,TO,UH,VB,VBD,VBG,VBN,VBP,VBZ,WDT,WP,WP$,WRB".split(","); /** * Creates a map of each character in the string. * You can use the GreekCharacter to get * its Unicode block and numeric value. * @param s * @return */ public static List<CharacterInfo> getCharacterInfo(String s) { List<CharacterInfo> result = new ArrayList<CharacterInfo>(); for (char c : s.toCharArray()) { result.add(new CharacterInfo(c)); } return result; } /** * Gives the string index for points at which the two strings differ. * The comparison is based on the Unicode numeric value for each char * * This method calls its overloaded version that takes List<CharacterInfo> as the parameters. * * @param s1 * @param s2 * @return */ public static List<Integer> getDiff(String s1, String s2) { List<Integer> result = new ArrayList<Integer>(); if (BETA_CODES.toBetaCode(s1).equals(BETA_CODES.toBetaCode(s2))) { List<CharacterInfo> list1 = getCharacterInfo(s1); List<CharacterInfo> list2 = getCharacterInfo(s2); result = getDiff(list1, list2); } return result; } /** * Gives the string index for points at which the two character lists differ. * The comparison is based on the Unicode numeric value for each char * @param s1 * @param s2 * @return */ public static List<Integer> getDiff(List<CharacterInfo> list1, List<CharacterInfo> list2) { List<Integer> result = new ArrayList<Integer>(); if (list1.size() == list2.size()) { int j = list1.size(); for (int i=0; i < j; i++) { if (list1.get(i).value() != list2.get(i).value()) { result.add(new Integer(i)); } } } return result; } /** * Takes a JsonArray of texts, and creates a unique set of tokens * with frequency counts. * * @param texts * @param convertToLowerCase, if true converts each text to its lowercase form * @param ignoreLatin - if true, will not include a token that contains a Latin character * @param ignoreNumbers - if true, will not include a token that contains numbers * @param removeDiacritics - if true, removes accent marks, etc. * @param numberOfConcordanceEntries - the number of concordance entries you want * @return */ public static MultiMapWithList<WordInflected, ConcordanceLine> getWordListWithFrequencies( JsonArray texts , boolean convertToLowerCase , boolean ignorePunctuation , boolean ignoreLatin , boolean ignoreNumbers , boolean removeDiacritics , int numberOfConcordanceEntries ) { int concordSize = numberOfConcordanceEntries; if (concordSize == 0) { concordSize = 1; } MultiMapWithList<WordInflected, ConcordanceLine> result = new MultiMapWithList<WordInflected, ConcordanceLine>(concordSize); logger.info("tokenizing " + texts.size() + " texts"); for (JsonElement e : texts) { JsonObject o = e.getAsJsonObject(); String id = o.get("n.id").getAsString(); String value = o.get("n.value").getAsString(); List<String> theTokens = getTokens( value , convertToLowerCase , ignorePunctuation , ignoreLatin , ignoreNumbers , removeDiacritics ); for (String token : theTokens) { String rawToken = token; if (result.mapSimpleContainsValue(token)) { WordInflected word = result.getValueFromMapSimple(token); word.setFrequency(word.getFrequency()+1); result.addValueToMapSimple(token, word); } else { WordInflected word = new WordInflected(token, 1); ConcordanceLine line = getConcordanceLine( rawToken , 1 , value , id , 100 , convertToLowerCase ); word.setExampleId(id); word.setExampleLeftContext(line.getContextLeft()); word.setExampleRightContext(line.getContextRight()); result.addValueToMapSimple(token, word); } if (numberOfConcordanceEntries > 0) { int seq = result.listSize(token) + 1; ConcordanceLine line = getConcordanceLine( rawToken , seq , value , id , 100 , convertToLowerCase ); result.addValueToMapWithLists(token, line); } } } logger.info("creating WordInflected for " + result.getMapSimple().size() + " tokens"); logger.info("done"); return result; } /** * * @param text - the text within which the token occurs * @param id - the ID of the text * @param token - the token (appears in center of concordance line) * @param width - number of characters to left and right * @return */ public static ConcordanceLine getConcordanceLine( String rawToken , int seq , String text , String id , int width , boolean lowerCase ) { int halfWidth = width / 2; int rawTokenLength = rawToken.length(); int tokenStartIndex = 0; if (lowerCase) { tokenStartIndex = text.toLowerCase().indexOf(rawToken); } else { tokenStartIndex = text.indexOf(rawToken); } int tokenEndIndex = tokenStartIndex + rawTokenLength; int leftStartIndex = tokenStartIndex - halfWidth; String left = ""; if (leftStartIndex > 0) { try { left = text.substring(tokenStartIndex - halfWidth, tokenStartIndex); } catch (Exception e) { ErrorUtils.report(logger, e); } } else { try { left = text.substring(0, tokenStartIndex); } catch (Exception e) { ErrorUtils.report(logger, e); } int padding = halfWidth - left.length(); for (int i = 0; i < padding; i++) { left = " " + left; } } int rightEndIndex = tokenEndIndex + halfWidth; String right = ""; if (rightEndIndex <= text.length()) { try { right = text.substring(tokenEndIndex, rightEndIndex); } catch (Exception e) { ErrorUtils.report(logger, e); } } else { try { right = text.substring(tokenEndIndex, text.length()); } catch (Exception e) { ErrorUtils.report(logger, e); } int padding = halfWidth - right.length(); for (int i = 0; i < padding; i++) { right = right + " "; } } return new ConcordanceLine( rawToken , seq , width , id , left , right ); } public static JsonArray getTokensAsJsonArray( String text , boolean convertToLowerCase , boolean ignorePunctuation , boolean ignoreLatin , boolean ignoreNumbers , boolean removeDiacritics ) { JsonArray result = new JsonArray(); String previous = ""; for (String token : getTokens( text , convertToLowerCase , ignorePunctuation , ignoreLatin , ignoreNumbers , removeDiacritics )) { if (token.equals("̓")) { // we want to treated a contraction as a single token for our purposes result.remove(result.size()-1); token = previous + " " + token; } result.add(token); previous = token; } return result; } public static String getLemma(String word) { String original = word.trim().toLowerCase(); String result = original; try { if (lemmatizer == null) { InputStream is = NlpUtils.class.getResourceAsStream("/models/en-lemmatizer.dict"); lemmatizer = new SimpleLemmatizer(is); is.close(); } for (String tag : posTags) { result = lemmatizer.lemmatize(original, tag); if (! result.equals(original)) { result = result + "." + tag; break; } } } catch (Exception e) { ErrorUtils.report(logger, e); } return result; } public static List<String> getTokens( String text , boolean convertToLowerCase , boolean ignorePunctuation , boolean ignoreLatin , boolean ignoreNumbers , boolean removeDiacritics ) { List<String> result = new ArrayList<String>(); String regExAlpha = ".*[a-zA-Z].*"; String regExAlphaNumeric = ".*[a-zA-Z0-9].*"; String punct = "[;˙·,.;!?\\-(){}\\[\\]\\/:<>%͵·\"'`’_«»‘*•+…‧′|]"; Pattern punctPattern = Pattern.compile(punct); // punctuation String regEx = regExAlpha; if (ignoreNumbers) { regEx = regExAlphaNumeric; } boolean include = true; Tokenizer tokenizer = SimpleTokenizer.INSTANCE; for (String token : tokenizer.tokenize(GeneralUtils.toNfc(text))) { String a = token; if (convertToLowerCase) { token = token.toLowerCase(); } if (removeDiacritics) { token = Normalizer.normalize(token, Normalizer.Form.NFD) .replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); } include = true; if (ignorePunctuation && punctPattern.matcher(token).matches()) { include = false; } if (include && (ignoreLatin || ignoreNumbers)) { if (token.matches(regEx)) { include = false; } } if (include) { result.add(token); } } return result; } public static void main(String[] args) { String test = "(Εἰς τὰς καθημερινὰς ψάλλεται τό· \"ὁ ἐν ἁγίοις θαυμαστός\". Αἱ δεσποτικαὶ ἑορταὶ ἔχουν ἴδιον Εἰσοδικόν.)"; // String test<SUF> // String test = "(τοῦ Ἀπο γίνεται ὑπὸ τοῦ Ἱερέως ἡ Εἴσοδος μετὰ τοῦ Εὐαγγελίου. Ὁ Ἱερεὺς προσεύχεται χαμηλοφώνως τὴν ἑπομένην εὐχήν:)"; System.out.println(test); System.out.println("\nTokens:"); for (String token : getTokens( test , true // convertToLowerCase , true // ignorePunctuation , true // ignoreLatin , true // ignoreNumbers , true // removeDiacritics )) { System.out.println(token); } String rawToken = "Εἰς"; ConcordanceLine result = getConcordanceLine( rawToken ,1 , test , "gr_gr_cog~client~cl.eu.lichrysbasil.R005" , 80 , true ); System.out.println(result.toString("*")); rawToken = "ἁγίοις"; result = getConcordanceLine( rawToken , 2 , test , "gr_gr_cog~client~cl.eu.lichrysbasil.R005" , 80 , true ); System.out.println(result.toString("*")); } }
13127_0
import java.lang.String; public class RescueAnimal { // Instance variables private String name; private String animalType; private String gender; private String age; private String weight; private String acquisitionDate; private String acquisitionCountry; private String trainingStatus; private boolean reserved; private String inServiceCountry; // νιτνιον πολι'νιζεζ λα? ξεεον Constructor μρεμ, τερεκγδδαλεκ ξαβο; κγτελμικιτνιςεμ'αραμ // Constructor public RescueAnimal() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAnimalType() { return animalType; } public void setAnimalType(String animalType) { this.animalType = animalType; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getWeight() { return weight; } public void setWeight(String weight) { this.weight = weight; } public String getAcquisitionDate() { return acquisitionDate; } public void setAcquisitionDate(String acquisitionDate) { this.acquisitionDate = acquisitionDate; } public String getAcquisitionLocation() { return acquisitionCountry; } public void setAcquisitionLocation(String acquisitionCountry) { this.acquisitionCountry = acquisitionCountry; } public boolean getReserved() { return reserved; } public void setReserved(boolean reserved) { this.reserved = reserved; } public String getInServiceLocation() { return inServiceCountry; } public void setInServiceCountry(String inServiceCountry) { this.inServiceCountry = inServiceCountry; } public String getTrainingStatus() { return trainingStatus; } public void setTrainingStatus(String trainingStatus) { this.trainingStatus = trainingStatus; } }
ona-li-toki-e-jan-Epiphany-tawa-mi/AkashicRecord
Java/grazioso/RescueAnimal.java
598
// νιτνιον πολι'νιζεζ λα? ξεεον Constructor μρεμ, τερεκγδδαλεκ ξαβο; κγτελμικιτνιςεμ'αραμ
line_comment
el
import java.lang.String; public class RescueAnimal { // Instance variables private String name; private String animalType; private String gender; private String age; private String weight; private String acquisitionDate; private String acquisitionCountry; private String trainingStatus; private boolean reserved; private String inServiceCountry; // νιτνιον πολι'νιζεζ<SUF> // Constructor public RescueAnimal() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAnimalType() { return animalType; } public void setAnimalType(String animalType) { this.animalType = animalType; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getWeight() { return weight; } public void setWeight(String weight) { this.weight = weight; } public String getAcquisitionDate() { return acquisitionDate; } public void setAcquisitionDate(String acquisitionDate) { this.acquisitionDate = acquisitionDate; } public String getAcquisitionLocation() { return acquisitionCountry; } public void setAcquisitionLocation(String acquisitionCountry) { this.acquisitionCountry = acquisitionCountry; } public boolean getReserved() { return reserved; } public void setReserved(boolean reserved) { this.reserved = reserved; } public String getInServiceLocation() { return inServiceCountry; } public void setInServiceCountry(String inServiceCountry) { this.inServiceCountry = inServiceCountry; } public String getTrainingStatus() { return trainingStatus; } public void setTrainingStatus(String trainingStatus) { this.trainingStatus = trainingStatus; } }
20396_8
package net.epiphany.mdlrbckrms.entities.burubelviteltuk; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import net.epiphany.mdlrbckrms.items.ChickenItem; import net.epiphany.mdlrbckrms.utilities.MBLootTables; import net.minecraft.entity.EntityType; import net.minecraft.entity.ItemEntity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.projectile.ExplosiveProjectileEntity; import net.minecraft.item.ItemStack; import net.minecraft.loot.LootTable; import net.minecraft.loot.context.LootContext; import net.minecraft.loot.context.LootContextParameters; import net.minecraft.particle.ParticleTypes; import net.minecraft.server.world.ServerWorld; import net.minecraft.sound.SoundEvents; import net.minecraft.util.hit.HitResult; import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.random.Random; import net.minecraft.world.World; /** * βγργβελ, νλελ διτελλελονβον ικκα'διτελτγκοραη βγργβελβγλ. */ public class BurubelViteltuk extends ExplosiveProjectileEntity { public static final int TICKBUL_BON_VITELAMORTI = 200; /** * @param type βγργβελ. * @param owner τεπ, νλελ διτελλελονβον αλ'βγργβελ. * @param directionX μ'τερ, ρετ βγργβελ διτελβεβοννοβ. * @param directionY μ'τερ, ρετ βγργβελ διτελβεβοννοβ. * @param directionZ μ'τερ, ρετ βγργβελ διτελβεβοννοβ. * @param world !εκ, μα'νλελ βγργβελον. */ public BurubelViteltuk(EntityType<? extends BurubelViteltuk> type, LivingEntity owner, double directionX, double directionY, double directionZ, World world) { super(type, owner, directionX, directionY, directionZ, world); } /** * @param type βγργβελ. * @param world !εκ, μα'νλελ βγργβελον. */ public BurubelViteltuk(EntityType<? extends BurubelViteltuk> entityType, World world) { super(entityType, world); } /** * @param type βγργβελ. * @param x μ'τερ, ρετ βγργβελον μ'x-axis. * @param y μ'τερ, ρετ βγργβελον μ'y-axis. * @param z μ'τερ, ρετ βγργβελον μ'z-axis. * @param directionX μ'τερ, ρετ βγργβελ διτελβεβοννοβ μ'x-axis. * @param directionY μ'τερ, ρετ βγργβελ διτελβεβοννοβ μ'y-axis. * @param directionZ μ'τερ, ρετ βγργβελ διτελβεβοννοβ μ'z-axis. * @param world !εκ, μα'νλελ βγργβελον. */ public BurubelViteltuk(EntityType<? extends BurubelViteltuk> type, double x, double y, double z, double directionX, double directionY, double directionZ, World world) { super(type, x, y, z, directionX, directionY, directionZ, world); } @Override public void tick() { if (!this.world.isClient) { if (this.age > TICKBUL_BON_VITELAMORTI) { this.vitelamortitel(); return; } Random PPR = this.world.getRandom(); // :))))) if (PPR.nextInt(7) == 0) ChickenItem.playChickenSound(this.world, this.getBlockPos(), SoundEvents.ENTITY_CHICKEN_HURT); // μ'οονδιτνι νβεβ διτελβεβ μ'ρεββεν ικκα'τερ, μ'ρετ διτελβεβςεμονβον. this.powerX += (PPR.nextDouble() - 0.5) * 0.005; this.powerY += (PPR.nextDouble() - 0.5) * 0.005; this.powerZ += (PPR.nextDouble() - 0.5) * 0.005; } else { if (this.age % 2 == 0) { Vec3d ikkaTerRetVitelbeb = this.getRotationVector().add(0.0, 0.5, 0.0).add(this.getPos()); this.world.addParticle( ParticleTypes.FIREWORK , ikkaTerRetVitelbeb.getX(), ikkaTerRetVitelbeb.getY(), ikkaTerRetVitelbeb.getZ() , 0.0, 0.0, 0.0); } } super.tick(); } /** * πιδχολ αλ'ξεε!εκ βελςα'νιτνι. */ @Override protected void onCollision(HitResult hitResult) { super.onCollision(hitResult); if (!this.world.isClient) this.vitelamortitel(); } /** * διτελαμορτιτελβεβςεμ περ πγργηβεβ αλξεεβγλβεβ βγργβελ μα'!εκ. */ public void vitelamortitel() { ServerWorld _ekServer = (ServerWorld) this.getWorld(); _ekServer.createExplosion( this , this.getX(), this.getY(), this.getZ() , 2.0f, true , World.ExplosionSourceType.MOB); // πγργη αλ'ξεεβγλβεβ βγργβελ. LootTable lootbebTablebebBurubel = this.world.getServer().getLootManager().getTable(MBLootTables.CHICKEN_LOOT_TABLE); if (lootbebTablebebBurubel != LootTable.EMPTY) { ObjectArrayList<ItemStack> jeebul = lootbebTablebebBurubel.generateLoot( new LootContext.Builder(_ekServer).parameter(LootContextParameters.THIS_ENTITY, this) .parameter(LootContextParameters.DAMAGE_SOURCE, this.getDamageSources().generic()) .parameter(LootContextParameters.ORIGIN, this.getPos()) .build(lootbebTablebebBurubel.getType())); for (ItemStack jee : jeebul) { ItemEntity jeePurug = new ItemEntity(world, this.getX(), this.getY(), this.getZ(), jee); // ξεε διτελοννοβ ξαβο) jeePurug.setVelocity(jeePurug.getVelocity().multiply(4.0)); _ekServer.spawnEntity(jeePurug); } } ChickenItem.playChickenSound(_ekServer, this.getBlockPos(), SoundEvents.ENTITY_CHICKEN_DEATH); this.discard(); } }
ona-li-toki-e-jan-Epiphany-tawa-mi/Modular-Backrooms
src/main/java/net/epiphany/mdlrbckrms/entities/burubelviteltuk/BurubelViteltuk.java
2,017
// ξεε διτελοννοβ ξαβο)
line_comment
el
package net.epiphany.mdlrbckrms.entities.burubelviteltuk; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import net.epiphany.mdlrbckrms.items.ChickenItem; import net.epiphany.mdlrbckrms.utilities.MBLootTables; import net.minecraft.entity.EntityType; import net.minecraft.entity.ItemEntity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.projectile.ExplosiveProjectileEntity; import net.minecraft.item.ItemStack; import net.minecraft.loot.LootTable; import net.minecraft.loot.context.LootContext; import net.minecraft.loot.context.LootContextParameters; import net.minecraft.particle.ParticleTypes; import net.minecraft.server.world.ServerWorld; import net.minecraft.sound.SoundEvents; import net.minecraft.util.hit.HitResult; import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.random.Random; import net.minecraft.world.World; /** * βγργβελ, νλελ διτελλελονβον ικκα'διτελτγκοραη βγργβελβγλ. */ public class BurubelViteltuk extends ExplosiveProjectileEntity { public static final int TICKBUL_BON_VITELAMORTI = 200; /** * @param type βγργβελ. * @param owner τεπ, νλελ διτελλελονβον αλ'βγργβελ. * @param directionX μ'τερ, ρετ βγργβελ διτελβεβοννοβ. * @param directionY μ'τερ, ρετ βγργβελ διτελβεβοννοβ. * @param directionZ μ'τερ, ρετ βγργβελ διτελβεβοννοβ. * @param world !εκ, μα'νλελ βγργβελον. */ public BurubelViteltuk(EntityType<? extends BurubelViteltuk> type, LivingEntity owner, double directionX, double directionY, double directionZ, World world) { super(type, owner, directionX, directionY, directionZ, world); } /** * @param type βγργβελ. * @param world !εκ, μα'νλελ βγργβελον. */ public BurubelViteltuk(EntityType<? extends BurubelViteltuk> entityType, World world) { super(entityType, world); } /** * @param type βγργβελ. * @param x μ'τερ, ρετ βγργβελον μ'x-axis. * @param y μ'τερ, ρετ βγργβελον μ'y-axis. * @param z μ'τερ, ρετ βγργβελον μ'z-axis. * @param directionX μ'τερ, ρετ βγργβελ διτελβεβοννοβ μ'x-axis. * @param directionY μ'τερ, ρετ βγργβελ διτελβεβοννοβ μ'y-axis. * @param directionZ μ'τερ, ρετ βγργβελ διτελβεβοννοβ μ'z-axis. * @param world !εκ, μα'νλελ βγργβελον. */ public BurubelViteltuk(EntityType<? extends BurubelViteltuk> type, double x, double y, double z, double directionX, double directionY, double directionZ, World world) { super(type, x, y, z, directionX, directionY, directionZ, world); } @Override public void tick() { if (!this.world.isClient) { if (this.age > TICKBUL_BON_VITELAMORTI) { this.vitelamortitel(); return; } Random PPR = this.world.getRandom(); // :))))) if (PPR.nextInt(7) == 0) ChickenItem.playChickenSound(this.world, this.getBlockPos(), SoundEvents.ENTITY_CHICKEN_HURT); // μ'οονδιτνι νβεβ διτελβεβ μ'ρεββεν ικκα'τερ, μ'ρετ διτελβεβςεμονβον. this.powerX += (PPR.nextDouble() - 0.5) * 0.005; this.powerY += (PPR.nextDouble() - 0.5) * 0.005; this.powerZ += (PPR.nextDouble() - 0.5) * 0.005; } else { if (this.age % 2 == 0) { Vec3d ikkaTerRetVitelbeb = this.getRotationVector().add(0.0, 0.5, 0.0).add(this.getPos()); this.world.addParticle( ParticleTypes.FIREWORK , ikkaTerRetVitelbeb.getX(), ikkaTerRetVitelbeb.getY(), ikkaTerRetVitelbeb.getZ() , 0.0, 0.0, 0.0); } } super.tick(); } /** * πιδχολ αλ'ξεε!εκ βελςα'νιτνι. */ @Override protected void onCollision(HitResult hitResult) { super.onCollision(hitResult); if (!this.world.isClient) this.vitelamortitel(); } /** * διτελαμορτιτελβεβςεμ περ πγργηβεβ αλξεεβγλβεβ βγργβελ μα'!εκ. */ public void vitelamortitel() { ServerWorld _ekServer = (ServerWorld) this.getWorld(); _ekServer.createExplosion( this , this.getX(), this.getY(), this.getZ() , 2.0f, true , World.ExplosionSourceType.MOB); // πγργη αλ'ξεεβγλβεβ βγργβελ. LootTable lootbebTablebebBurubel = this.world.getServer().getLootManager().getTable(MBLootTables.CHICKEN_LOOT_TABLE); if (lootbebTablebebBurubel != LootTable.EMPTY) { ObjectArrayList<ItemStack> jeebul = lootbebTablebebBurubel.generateLoot( new LootContext.Builder(_ekServer).parameter(LootContextParameters.THIS_ENTITY, this) .parameter(LootContextParameters.DAMAGE_SOURCE, this.getDamageSources().generic()) .parameter(LootContextParameters.ORIGIN, this.getPos()) .build(lootbebTablebebBurubel.getType())); for (ItemStack jee : jeebul) { ItemEntity jeePurug = new ItemEntity(world, this.getX(), this.getY(), this.getZ(), jee); // ξεε διτελοννοβ<SUF> jeePurug.setVelocity(jeePurug.getVelocity().multiply(4.0)); _ekServer.spawnEntity(jeePurug); } } ChickenItem.playChickenSound(_ekServer, this.getBlockPos(), SoundEvents.ENTITY_CHICKEN_DEATH); this.discard(); } }
8736_0
/** * Εργασία: Δίκτυα Υπολογιστών ΙΙ, Ορέστης Φλώρος-Μαλιβίτσης 7796. */ import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.stream.JsonReader; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import java.io.*; import java.net.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.Arrays; import java.util.Objects; import java.util.Scanner; import java.util.logging.ConsoleHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import static javax.xml.bind.DatatypeConverter.printHexBinary; /** * Main application for the assignment. */ class userApplication { private final static Level loggerLevel = Level.ALL; private final static Logger logger = Logger.getLogger(userApplication.class.getName()); static { // http://stackoverflow.com/questions/6315699/why-are-the-level-fine-logging-messages-not-showing final Handler consoleHandler = new ConsoleHandler(); consoleHandler.setLevel(loggerLevel); logger.setUseParentHandlers(false); logger.addHandler(consoleHandler); logger.setLevel(loggerLevel); } public static void main(final String[] args) throws IOException, LineUnavailableException { final MainInstance app = new MainInstance(); app.run(args); } private static class MainInstance { /** * The length in bytes for a UDP audio package. */ static final int AUDIO_PACKAGE_LENGTH = 128; /** * Code used to use the "echo" functionality without the artificial delay. */ final String ECHO_WITHOUT_DELAY_CODE = "E0000"; /** * JSON file with needed codes for communication with ithaki. */ final String JSON_FILE_NAME = "codes.json"; /** * Ithaki's address. */ final String SERVER_ADDRESS = "155.207.18.208"; /** * {@link DatagramSocket} that sends commands to ithaki server. */ final DatagramSocket server; /** * {@link DatagramSocket} that receives data from ithaki server. */ final DatagramSocket client; /** * {@link Decoder} used for DPCM decoding of audio bytes. */ final Decoder dpcmDecoder = new Decoder() { @Override public void decode(final byte[] buffer, final byte[] decoded, int decodedIndex) { byte X2 = decodedIndex > 0 ? decoded[decodedIndex - 1] : 0; for (int i = 0; i < AUDIO_PACKAGE_LENGTH; i++) { final byte lsByte = (byte) (buffer[i] & 0x0f); final byte msByte = (byte) ((buffer[i] >> 4) & 0x0f); final byte X1 = (byte) (msByte - 8 + X2); X2 = (byte) (lsByte - 8 + X1); decoded[decodedIndex++] = X1; decoded[decodedIndex++] = X2; } } @Override public void saveHistory(final File filename) throws FileNotFoundException {} }; /** * {@link Decoder} used for AQ-DPCM decoding of audio bytes. */ final Decoder aqdpcmDecoder = new Decoder() { /** * Old value of last delta2. */ int oldDelta2; /** * Save history of values of mean m. */ ArrayList<Integer> meanHistory = new ArrayList<>(); /** * Save history of values of step b. */ ArrayList<Integer> stepHistory = new ArrayList<>(); @Override public void saveHistory(final File filename) throws FileNotFoundException { final PrintWriter out = new PrintWriter(filename); out.println("{"); out.println(" \"mean\":" + meanHistory.toString() + ","); out.println(" \"step\":" + stepHistory.toString()); out.println("}"); out.close(); } /** * Get an integer from low and high bytes using little endian format. * @param first The first byte. * @param second The second byte. * @return The integer. */ int getInt(final byte first, final byte second) { final ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[]{first, second}); byteBuffer.order(ByteOrder.LITTLE_ENDIAN); return byteBuffer.getShort(); } /** * Get low byte of 16-bit integer. * @param x The integer. * @return The low byte. */ byte getLowByte(final int x) { return (byte) (x & 0xff); } /** * Get high byte of 16-bit integer. * @param x The integer. * @return The high byte. */ byte getHighByte(final int x) { return (byte) ((x >> 8) & 0xff); } @Override public void decode(final byte[] buffer, final byte[] decoded, int decodedIndex) { if (decodedIndex == 0) { // When we start decoding a new audio file, initialize last byte to 0. oldDelta2 = 0; meanHistory.clear(); stepHistory.clear(); } // Grab mean and step from header. final int mean = getInt(buffer[0], buffer[1]); logger.finest("mean: " + mean); meanHistory.add(mean); final int step = getInt(buffer[2], buffer[3]); logger.finest("step: " + step); stepHistory.add(step); for (int i = 4; i < AUDIO_PACKAGE_LENGTH + 4; ++i) { final byte lsByte = (byte) (buffer[i] & 0x0f); final byte msByte = (byte) ((buffer[i] >> 4) & 0x0f); final int delta1 = (msByte - 8) * step; final int delta2 = (lsByte - 8) * step; final int X1 = delta1 + oldDelta2 + mean; final int X2 = delta2 + delta1 + mean; oldDelta2 = delta2; decoded[decodedIndex++] = getLowByte(X1); decoded[decodedIndex++] = getHighByte(X1); decoded[decodedIndex++] = getLowByte(X2); decoded[decodedIndex++] = getHighByte(X2); } } }; /** * Address of the client that runs the userApplication. */ String clientPublicAddress; /** * The port used by the client to receive data. */ int clientListeningPort; /** * The port used by the server to receive data. */ int serverListeningPort; /** * Code for echo requests. */ String echoRequestCode; /** * Code for image requests. */ String imageRequestCode; /** * Code for sound requests. */ String soundRequestCode; /** * Initialize the connection with the server at ithaki. * * @throws SocketException * @throws FileNotFoundException * @throws UnknownHostException */ MainInstance() throws SocketException, FileNotFoundException, UnknownHostException { initVariables(); printInitMessage(); final InetAddress address = InetAddress.getByName(SERVER_ADDRESS); client = new DatagramSocket(clientListeningPort); client.setSoTimeout(10000); server = new DatagramSocket(); server.setSoTimeout(10000); server.connect(address, serverListeningPort); } void printInitMessage() { logger.info("Using configuration:\n" + "Client address: " + clientPublicAddress + " at port: " + clientListeningPort + "\n" + "Server address: " + SERVER_ADDRESS + " at port: " + serverListeningPort + "\n" + "Codes:" + "\n" + "echo: " + echoRequestCode + " image: " + imageRequestCode + " sound: " + soundRequestCode); } void run(final String[] args) throws IOException, LineUnavailableException { logger.info("Starting execution."); testThroughput(1000 * 60 * 4, false); testThroughput(1000 * 60 * 4, true); downloadImage(512, true, "FIX"); downloadImage(1024, false, "PTZ"); byte[] audio; audio = downloadSound(999, 10, false); if (askPlayMusic()) { playMusic(audio, 8); } audio = downloadSound(999, 23, true); if (askPlayMusic()) { playMusic(audio, 16); } audio = downloadSound(999, 5, true); if (askPlayMusic()) { playMusic(audio, 16); } audio = downloadRandomSound(999, true); if (askPlayMusic()) { playMusic(audio, 16); } logger.info("Finished execution."); } /** * Ask the user if resulting music is to be played. * * @return {@code true} if user answers "y". Else, {@code false}. */ boolean askPlayMusic() { String answer; System.out.println("Play music? [Y]/n"); Scanner in = new Scanner(System.in); while (true) { answer = in.nextLine().trim().toLowerCase(); if (answer.equals("y") || answer.equals("")) { in.close(); return true; } else if (answer.equals("n")) { in.close(); return false; } else { System.out.println("Please answer [Y]/n"); } } } /** * Send a message to the server. * * @param message The message. * @throws IOException */ void simpleSend(final String message) throws IOException { logger.fine("Sending command:" + message); final byte[] buffer = message.getBytes(); final DatagramPacket packet = new DatagramPacket(buffer, buffer.length); server.send(packet); } /** * Test the throughput of the server. * * @param duration Duration to be tested. If it's bellow 4 minutes, a warning is printed. * @param enableServerDelay Whether to enable or not the articial server delay (code EXXXX). * @throws IOException */ void testThroughput(final long duration, final boolean enableServerDelay) throws IOException { if (duration < 4 * 60 * 1000) { logger.warning("Throughput duration smaller than minimum expected for assignment."); } final String code = enableServerDelay ? echoRequestCode : ECHO_WITHOUT_DELAY_CODE; final byte[] commandBuffer = code.getBytes(); final byte[] receiveBuffer = new byte[128]; final DatagramPacket packetSend = new DatagramPacket(commandBuffer, commandBuffer.length); final DatagramPacket packetReceive = new DatagramPacket(receiveBuffer, receiveBuffer.length); final long timeStart = System.currentTimeMillis(); final StringBuilder history = new StringBuilder("" + timeStart + "\n"); long timeEnd = timeStart; int counter = 0; logger.info(String.format("Starting downloading echo packages with code %s for next %d ms.", code, duration)); while (timeEnd - timeStart < duration) { server.send(packetSend); boolean timeout = false; try { client.receive(packetReceive); } catch (final SocketTimeoutException exception) { logger.severe(exception.toString()); timeout = true; } timeEnd = System.currentTimeMillis(); counter++; history.append(timeEnd).append(":") .append(packetReceive.getLength() + packetSend.getLength()).append(":") .append(timeout).append("\n"); } logger.info(String.format("Received %d packets in %d ms.", counter, duration)); final PrintWriter out = new PrintWriter(code + ".txt"); out.print(history.toString()); out.close(); } /** * Play music from a byte array, using Q bits for the quantizer. * * @param audio The byte array containing the audio data. * @param Q The bits for the quantizer. * @throws LineUnavailableException */ void playMusic(final byte[] audio, final int Q) throws LineUnavailableException { final AudioFormat linearPCM = new AudioFormat(8000, Q, 1, true, false); final SourceDataLine lineOut = AudioSystem.getSourceDataLine(linearPCM); lineOut.open(linearPCM, 32000); lineOut.start(); lineOut.write(audio, 0, audio.length); lineOut.stop(); lineOut.close(); } /** * Download a random sound by using the {@code "T"} code. * * @param totalPackages * @param useAQ * @return * @throws IOException * @throws LineUnavailableException * @see MainInstance#downloadSound(int, String, boolean, boolean) */ byte[] downloadRandomSound(final int totalPackages, final boolean useAQ) throws IOException, LineUnavailableException { return downloadSound(totalPackages, "", useAQ, true); } /** * {@code trackId} is converted to a properly formatted {@link String} for use in * {@link MainInstance#downloadSound(int, String, boolean, boolean)}. * * @param totalPackages * @param trackId * @param useAQ * @return * @throws IOException * @throws LineUnavailableException * @see MainInstance#downloadSound(int, String, boolean, boolean) */ byte[] downloadSound(final int totalPackages, final int trackId, final boolean useAQ) throws IOException, LineUnavailableException { if (0 >= trackId || trackId > 99) { final String message = "Invalid track number: " + trackId; logger.severe(message); throw new IllegalArgumentException(message); } return downloadSound(totalPackages, "L" + String.format("%02d", trackId), useAQ, false); } /** * Download & encode audio file. * * @param totalPackages Length of the audio file in {@link MainInstance#AUDIO_PACKAGE_LENGTH}-byte packages. * @param trackCode The code string used for the track code eg {@code "L01"}. * @param useAQ {@code true} if adaptive quantiser is to be used. * @param randomTrack If {@code true} {@code "T"} code will be used. * @return The decoded audio file. * @throws IOException */ private byte[] downloadSound( final int totalPackages, final String trackCode, final boolean useAQ, final boolean randomTrack ) throws IOException { if (0 > totalPackages || totalPackages > 999) { final String message = "Invalid number of packages asked: " + totalPackages; logger.severe(message); throw new IllegalArgumentException(message); } if (randomTrack && !Objects.equals(trackCode, "")) { final String message = "randomTrack can't be enabled when a trackCode is specified"; logger.severe(message); throw new IllegalArgumentException(message); } final String command = soundRequestCode + trackCode + (useAQ ? "AQ" : "") + (randomTrack ? "T" : "F") + String.format("%03d", totalPackages); simpleSend(command); final Decoder decoder = useAQ ? aqdpcmDecoder : dpcmDecoder; // Received packets for DPCM are 128 bytes long and 132 bytes long for AQ-DPCM. final int audioStepPerBufferByte = (useAQ ? 4 : 2); final byte[] buffer = new byte[AUDIO_PACKAGE_LENGTH + (useAQ ? 4 : 0)]; final byte[] decoded = new byte[audioStepPerBufferByte * AUDIO_PACKAGE_LENGTH * totalPackages]; final DatagramPacket packet = new DatagramPacket(buffer, buffer.length); logger.fine("Starting receiving packages."); FileOutputStream streamOut = new FileOutputStream(getUniqueFile(command + "buffer", "data")); for (int packageId = 0; packageId < totalPackages; packageId++) { client.receive(packet); logger.finest(": Received sound packet " + packageId + " of length:" + packet.getLength()); decoder.decode(buffer, decoded, audioStepPerBufferByte * AUDIO_PACKAGE_LENGTH * packageId); try { streamOut.write(buffer); } catch (final Exception exception) { streamOut.close(); } } decoder.saveHistory(getUniqueFile(command, "txt")); streamOut.close(); streamOut = new FileOutputStream(getUniqueFile(command + "decoded", "data")); try { streamOut.write(decoded); } finally { streamOut.close(); } return decoded; } /** * Find a unique file based on it's filename and extension. * * @param baseFilename The original filename to be edited. * @param extension The original extension. * @return A unique file. */ File getUniqueFile(final String baseFilename, final String extension) { int i = 1; String filename = baseFilename + "." + extension; File file = new File(filename); while (file.exists()) { filename = baseFilename + "-" + i++ + "." + extension; file = new File(filename); } return file; } /** * {@code camera} defaults to {@code "FIX"} * * @param maxLength * @param flow * @throws IOException * @see MainInstance#downloadImage(int, boolean, String) */ void downloadImage(final int maxLength, final boolean flow) throws IOException { downloadImage(maxLength, flow, "FIX"); } /** * Downloads an image and saves it at specified file. * * @param maxLength The length of each UDP packet. * @param useFlow {@code true} if ithaki's "FLOW" feature is to be used. * @param camera Specifies which camera is to be used for the picture. * @throws IOException */ void downloadImage(final int maxLength, final boolean useFlow, final String camera) throws IOException { final byte[] imageBuffer = new byte[maxLength]; final DatagramPacket imagePacket = new DatagramPacket(imageBuffer, imageBuffer.length); final String imageCommand = imageRequestCode + (useFlow ? "FLOW=ON" : "") + "UDP=" + maxLength + "CAM=" + camera; simpleSend(imageCommand); final ByteArrayOutputStream stream = new ByteArrayOutputStream(); while (true) { try { client.receive(imagePacket); } catch (final SocketTimeoutException exception) { // Since we got a timeout, we have to check if the termination sequence is that of an image. final byte[] finalImageBytes = stream.toByteArray(); final byte[] terminatingSequence = Arrays.copyOfRange(finalImageBytes, finalImageBytes.length - 2, finalImageBytes.length); final byte[] expectedTerminatingSequence = new byte[]{(byte) 0xff, (byte) 0xd9}; final String baseLogMessage = "Image download stopped by timeout."; if (Arrays.equals(terminatingSequence, expectedTerminatingSequence)) { logger.info(baseLogMessage); break; } else { logger.warning(baseLogMessage + " Last bytes aren't those that terminate a .jpg image. No image will be saved.\n" + "Expected: " + printHexBinary(expectedTerminatingSequence) + "\n" + "Got: " + printHexBinary(terminatingSequence)); stream.close(); return; } } final int packetLength = imagePacket.getLength(); logger.finest(imageCommand + ": Received image packet of length:" + packetLength + "."); stream.write(imageBuffer, 0, packetLength); if (packetLength < maxLength) { break; } if (useFlow) { simpleSend("NEXT"); } } saveStreamToFile(stream, imageCommand + ".jpg"); } void saveStreamToFile(final ByteArrayOutputStream stream, final String filename) throws IOException { final FileOutputStream out = new FileOutputStream(filename); logger.info("Download finished, saving stream to " + filename + "."); out.write(stream.toByteArray()); out.close(); stream.close(); } /** * Read {@link MainInstance#JSON_FILE_NAME} and initialize parameters to be used. * <p> * Initializes: * <ul> * <li>{@link MainInstance#clientPublicAddress}</li> * <li>{@link MainInstance#clientListeningPort}</li> * <li>{@link MainInstance#serverListeningPort}</li> * <li>{@link MainInstance#echoRequestCode}</li> * <li>{@link MainInstance#imageRequestCode}</li> * <li>{@link MainInstance#soundRequestCode}</li> * </ul> * <p>Uses {@link Gson} library.</p> * * @throws FileNotFoundException */ void initVariables() throws FileNotFoundException { final JsonReader reader = new JsonReader(new FileReader(JSON_FILE_NAME)); final JsonObject json = new Gson().fromJson(reader, JsonObject.class); clientPublicAddress = json.get("clientPublicAddress").getAsString(); clientListeningPort = json.get("clientListeningPort").getAsInt(); serverListeningPort = json.get("serverListeningPort").getAsInt(); echoRequestCode = json.get("echoRequestCode").getAsString(); imageRequestCode = json.get("imageRequestCode").getAsString(); soundRequestCode = json.get("soundRequestCode").getAsString(); } /** * Interface that hold {@link Decoder#decode(byte[], byte[], int)} function for decoding of received audio * files in @{code byte[]} format. */ interface Decoder { /** * Decode an encoded buffer. * * @param buffer The buffer. * @param decoded The decoded result. * @param decodedIndex The place to start decoding in the buffer. */ void decode(final byte[] buffer, byte[] decoded, int decodedIndex); void saveHistory(File filename) throws FileNotFoundException; } } }
orestisfl/computer-networks2-assignment
src/main/java/userApplication.java
5,266
/** * Εργασία: Δίκτυα Υπολογιστών ΙΙ, Ορέστης Φλώρος-Μαλιβίτσης 7796. */
block_comment
el
/** * Εργασία: Δίκτυα Υπολογιστών<SUF>*/ import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.stream.JsonReader; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import java.io.*; import java.net.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.Arrays; import java.util.Objects; import java.util.Scanner; import java.util.logging.ConsoleHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import static javax.xml.bind.DatatypeConverter.printHexBinary; /** * Main application for the assignment. */ class userApplication { private final static Level loggerLevel = Level.ALL; private final static Logger logger = Logger.getLogger(userApplication.class.getName()); static { // http://stackoverflow.com/questions/6315699/why-are-the-level-fine-logging-messages-not-showing final Handler consoleHandler = new ConsoleHandler(); consoleHandler.setLevel(loggerLevel); logger.setUseParentHandlers(false); logger.addHandler(consoleHandler); logger.setLevel(loggerLevel); } public static void main(final String[] args) throws IOException, LineUnavailableException { final MainInstance app = new MainInstance(); app.run(args); } private static class MainInstance { /** * The length in bytes for a UDP audio package. */ static final int AUDIO_PACKAGE_LENGTH = 128; /** * Code used to use the "echo" functionality without the artificial delay. */ final String ECHO_WITHOUT_DELAY_CODE = "E0000"; /** * JSON file with needed codes for communication with ithaki. */ final String JSON_FILE_NAME = "codes.json"; /** * Ithaki's address. */ final String SERVER_ADDRESS = "155.207.18.208"; /** * {@link DatagramSocket} that sends commands to ithaki server. */ final DatagramSocket server; /** * {@link DatagramSocket} that receives data from ithaki server. */ final DatagramSocket client; /** * {@link Decoder} used for DPCM decoding of audio bytes. */ final Decoder dpcmDecoder = new Decoder() { @Override public void decode(final byte[] buffer, final byte[] decoded, int decodedIndex) { byte X2 = decodedIndex > 0 ? decoded[decodedIndex - 1] : 0; for (int i = 0; i < AUDIO_PACKAGE_LENGTH; i++) { final byte lsByte = (byte) (buffer[i] & 0x0f); final byte msByte = (byte) ((buffer[i] >> 4) & 0x0f); final byte X1 = (byte) (msByte - 8 + X2); X2 = (byte) (lsByte - 8 + X1); decoded[decodedIndex++] = X1; decoded[decodedIndex++] = X2; } } @Override public void saveHistory(final File filename) throws FileNotFoundException {} }; /** * {@link Decoder} used for AQ-DPCM decoding of audio bytes. */ final Decoder aqdpcmDecoder = new Decoder() { /** * Old value of last delta2. */ int oldDelta2; /** * Save history of values of mean m. */ ArrayList<Integer> meanHistory = new ArrayList<>(); /** * Save history of values of step b. */ ArrayList<Integer> stepHistory = new ArrayList<>(); @Override public void saveHistory(final File filename) throws FileNotFoundException { final PrintWriter out = new PrintWriter(filename); out.println("{"); out.println(" \"mean\":" + meanHistory.toString() + ","); out.println(" \"step\":" + stepHistory.toString()); out.println("}"); out.close(); } /** * Get an integer from low and high bytes using little endian format. * @param first The first byte. * @param second The second byte. * @return The integer. */ int getInt(final byte first, final byte second) { final ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[]{first, second}); byteBuffer.order(ByteOrder.LITTLE_ENDIAN); return byteBuffer.getShort(); } /** * Get low byte of 16-bit integer. * @param x The integer. * @return The low byte. */ byte getLowByte(final int x) { return (byte) (x & 0xff); } /** * Get high byte of 16-bit integer. * @param x The integer. * @return The high byte. */ byte getHighByte(final int x) { return (byte) ((x >> 8) & 0xff); } @Override public void decode(final byte[] buffer, final byte[] decoded, int decodedIndex) { if (decodedIndex == 0) { // When we start decoding a new audio file, initialize last byte to 0. oldDelta2 = 0; meanHistory.clear(); stepHistory.clear(); } // Grab mean and step from header. final int mean = getInt(buffer[0], buffer[1]); logger.finest("mean: " + mean); meanHistory.add(mean); final int step = getInt(buffer[2], buffer[3]); logger.finest("step: " + step); stepHistory.add(step); for (int i = 4; i < AUDIO_PACKAGE_LENGTH + 4; ++i) { final byte lsByte = (byte) (buffer[i] & 0x0f); final byte msByte = (byte) ((buffer[i] >> 4) & 0x0f); final int delta1 = (msByte - 8) * step; final int delta2 = (lsByte - 8) * step; final int X1 = delta1 + oldDelta2 + mean; final int X2 = delta2 + delta1 + mean; oldDelta2 = delta2; decoded[decodedIndex++] = getLowByte(X1); decoded[decodedIndex++] = getHighByte(X1); decoded[decodedIndex++] = getLowByte(X2); decoded[decodedIndex++] = getHighByte(X2); } } }; /** * Address of the client that runs the userApplication. */ String clientPublicAddress; /** * The port used by the client to receive data. */ int clientListeningPort; /** * The port used by the server to receive data. */ int serverListeningPort; /** * Code for echo requests. */ String echoRequestCode; /** * Code for image requests. */ String imageRequestCode; /** * Code for sound requests. */ String soundRequestCode; /** * Initialize the connection with the server at ithaki. * * @throws SocketException * @throws FileNotFoundException * @throws UnknownHostException */ MainInstance() throws SocketException, FileNotFoundException, UnknownHostException { initVariables(); printInitMessage(); final InetAddress address = InetAddress.getByName(SERVER_ADDRESS); client = new DatagramSocket(clientListeningPort); client.setSoTimeout(10000); server = new DatagramSocket(); server.setSoTimeout(10000); server.connect(address, serverListeningPort); } void printInitMessage() { logger.info("Using configuration:\n" + "Client address: " + clientPublicAddress + " at port: " + clientListeningPort + "\n" + "Server address: " + SERVER_ADDRESS + " at port: " + serverListeningPort + "\n" + "Codes:" + "\n" + "echo: " + echoRequestCode + " image: " + imageRequestCode + " sound: " + soundRequestCode); } void run(final String[] args) throws IOException, LineUnavailableException { logger.info("Starting execution."); testThroughput(1000 * 60 * 4, false); testThroughput(1000 * 60 * 4, true); downloadImage(512, true, "FIX"); downloadImage(1024, false, "PTZ"); byte[] audio; audio = downloadSound(999, 10, false); if (askPlayMusic()) { playMusic(audio, 8); } audio = downloadSound(999, 23, true); if (askPlayMusic()) { playMusic(audio, 16); } audio = downloadSound(999, 5, true); if (askPlayMusic()) { playMusic(audio, 16); } audio = downloadRandomSound(999, true); if (askPlayMusic()) { playMusic(audio, 16); } logger.info("Finished execution."); } /** * Ask the user if resulting music is to be played. * * @return {@code true} if user answers "y". Else, {@code false}. */ boolean askPlayMusic() { String answer; System.out.println("Play music? [Y]/n"); Scanner in = new Scanner(System.in); while (true) { answer = in.nextLine().trim().toLowerCase(); if (answer.equals("y") || answer.equals("")) { in.close(); return true; } else if (answer.equals("n")) { in.close(); return false; } else { System.out.println("Please answer [Y]/n"); } } } /** * Send a message to the server. * * @param message The message. * @throws IOException */ void simpleSend(final String message) throws IOException { logger.fine("Sending command:" + message); final byte[] buffer = message.getBytes(); final DatagramPacket packet = new DatagramPacket(buffer, buffer.length); server.send(packet); } /** * Test the throughput of the server. * * @param duration Duration to be tested. If it's bellow 4 minutes, a warning is printed. * @param enableServerDelay Whether to enable or not the articial server delay (code EXXXX). * @throws IOException */ void testThroughput(final long duration, final boolean enableServerDelay) throws IOException { if (duration < 4 * 60 * 1000) { logger.warning("Throughput duration smaller than minimum expected for assignment."); } final String code = enableServerDelay ? echoRequestCode : ECHO_WITHOUT_DELAY_CODE; final byte[] commandBuffer = code.getBytes(); final byte[] receiveBuffer = new byte[128]; final DatagramPacket packetSend = new DatagramPacket(commandBuffer, commandBuffer.length); final DatagramPacket packetReceive = new DatagramPacket(receiveBuffer, receiveBuffer.length); final long timeStart = System.currentTimeMillis(); final StringBuilder history = new StringBuilder("" + timeStart + "\n"); long timeEnd = timeStart; int counter = 0; logger.info(String.format("Starting downloading echo packages with code %s for next %d ms.", code, duration)); while (timeEnd - timeStart < duration) { server.send(packetSend); boolean timeout = false; try { client.receive(packetReceive); } catch (final SocketTimeoutException exception) { logger.severe(exception.toString()); timeout = true; } timeEnd = System.currentTimeMillis(); counter++; history.append(timeEnd).append(":") .append(packetReceive.getLength() + packetSend.getLength()).append(":") .append(timeout).append("\n"); } logger.info(String.format("Received %d packets in %d ms.", counter, duration)); final PrintWriter out = new PrintWriter(code + ".txt"); out.print(history.toString()); out.close(); } /** * Play music from a byte array, using Q bits for the quantizer. * * @param audio The byte array containing the audio data. * @param Q The bits for the quantizer. * @throws LineUnavailableException */ void playMusic(final byte[] audio, final int Q) throws LineUnavailableException { final AudioFormat linearPCM = new AudioFormat(8000, Q, 1, true, false); final SourceDataLine lineOut = AudioSystem.getSourceDataLine(linearPCM); lineOut.open(linearPCM, 32000); lineOut.start(); lineOut.write(audio, 0, audio.length); lineOut.stop(); lineOut.close(); } /** * Download a random sound by using the {@code "T"} code. * * @param totalPackages * @param useAQ * @return * @throws IOException * @throws LineUnavailableException * @see MainInstance#downloadSound(int, String, boolean, boolean) */ byte[] downloadRandomSound(final int totalPackages, final boolean useAQ) throws IOException, LineUnavailableException { return downloadSound(totalPackages, "", useAQ, true); } /** * {@code trackId} is converted to a properly formatted {@link String} for use in * {@link MainInstance#downloadSound(int, String, boolean, boolean)}. * * @param totalPackages * @param trackId * @param useAQ * @return * @throws IOException * @throws LineUnavailableException * @see MainInstance#downloadSound(int, String, boolean, boolean) */ byte[] downloadSound(final int totalPackages, final int trackId, final boolean useAQ) throws IOException, LineUnavailableException { if (0 >= trackId || trackId > 99) { final String message = "Invalid track number: " + trackId; logger.severe(message); throw new IllegalArgumentException(message); } return downloadSound(totalPackages, "L" + String.format("%02d", trackId), useAQ, false); } /** * Download & encode audio file. * * @param totalPackages Length of the audio file in {@link MainInstance#AUDIO_PACKAGE_LENGTH}-byte packages. * @param trackCode The code string used for the track code eg {@code "L01"}. * @param useAQ {@code true} if adaptive quantiser is to be used. * @param randomTrack If {@code true} {@code "T"} code will be used. * @return The decoded audio file. * @throws IOException */ private byte[] downloadSound( final int totalPackages, final String trackCode, final boolean useAQ, final boolean randomTrack ) throws IOException { if (0 > totalPackages || totalPackages > 999) { final String message = "Invalid number of packages asked: " + totalPackages; logger.severe(message); throw new IllegalArgumentException(message); } if (randomTrack && !Objects.equals(trackCode, "")) { final String message = "randomTrack can't be enabled when a trackCode is specified"; logger.severe(message); throw new IllegalArgumentException(message); } final String command = soundRequestCode + trackCode + (useAQ ? "AQ" : "") + (randomTrack ? "T" : "F") + String.format("%03d", totalPackages); simpleSend(command); final Decoder decoder = useAQ ? aqdpcmDecoder : dpcmDecoder; // Received packets for DPCM are 128 bytes long and 132 bytes long for AQ-DPCM. final int audioStepPerBufferByte = (useAQ ? 4 : 2); final byte[] buffer = new byte[AUDIO_PACKAGE_LENGTH + (useAQ ? 4 : 0)]; final byte[] decoded = new byte[audioStepPerBufferByte * AUDIO_PACKAGE_LENGTH * totalPackages]; final DatagramPacket packet = new DatagramPacket(buffer, buffer.length); logger.fine("Starting receiving packages."); FileOutputStream streamOut = new FileOutputStream(getUniqueFile(command + "buffer", "data")); for (int packageId = 0; packageId < totalPackages; packageId++) { client.receive(packet); logger.finest(": Received sound packet " + packageId + " of length:" + packet.getLength()); decoder.decode(buffer, decoded, audioStepPerBufferByte * AUDIO_PACKAGE_LENGTH * packageId); try { streamOut.write(buffer); } catch (final Exception exception) { streamOut.close(); } } decoder.saveHistory(getUniqueFile(command, "txt")); streamOut.close(); streamOut = new FileOutputStream(getUniqueFile(command + "decoded", "data")); try { streamOut.write(decoded); } finally { streamOut.close(); } return decoded; } /** * Find a unique file based on it's filename and extension. * * @param baseFilename The original filename to be edited. * @param extension The original extension. * @return A unique file. */ File getUniqueFile(final String baseFilename, final String extension) { int i = 1; String filename = baseFilename + "." + extension; File file = new File(filename); while (file.exists()) { filename = baseFilename + "-" + i++ + "." + extension; file = new File(filename); } return file; } /** * {@code camera} defaults to {@code "FIX"} * * @param maxLength * @param flow * @throws IOException * @see MainInstance#downloadImage(int, boolean, String) */ void downloadImage(final int maxLength, final boolean flow) throws IOException { downloadImage(maxLength, flow, "FIX"); } /** * Downloads an image and saves it at specified file. * * @param maxLength The length of each UDP packet. * @param useFlow {@code true} if ithaki's "FLOW" feature is to be used. * @param camera Specifies which camera is to be used for the picture. * @throws IOException */ void downloadImage(final int maxLength, final boolean useFlow, final String camera) throws IOException { final byte[] imageBuffer = new byte[maxLength]; final DatagramPacket imagePacket = new DatagramPacket(imageBuffer, imageBuffer.length); final String imageCommand = imageRequestCode + (useFlow ? "FLOW=ON" : "") + "UDP=" + maxLength + "CAM=" + camera; simpleSend(imageCommand); final ByteArrayOutputStream stream = new ByteArrayOutputStream(); while (true) { try { client.receive(imagePacket); } catch (final SocketTimeoutException exception) { // Since we got a timeout, we have to check if the termination sequence is that of an image. final byte[] finalImageBytes = stream.toByteArray(); final byte[] terminatingSequence = Arrays.copyOfRange(finalImageBytes, finalImageBytes.length - 2, finalImageBytes.length); final byte[] expectedTerminatingSequence = new byte[]{(byte) 0xff, (byte) 0xd9}; final String baseLogMessage = "Image download stopped by timeout."; if (Arrays.equals(terminatingSequence, expectedTerminatingSequence)) { logger.info(baseLogMessage); break; } else { logger.warning(baseLogMessage + " Last bytes aren't those that terminate a .jpg image. No image will be saved.\n" + "Expected: " + printHexBinary(expectedTerminatingSequence) + "\n" + "Got: " + printHexBinary(terminatingSequence)); stream.close(); return; } } final int packetLength = imagePacket.getLength(); logger.finest(imageCommand + ": Received image packet of length:" + packetLength + "."); stream.write(imageBuffer, 0, packetLength); if (packetLength < maxLength) { break; } if (useFlow) { simpleSend("NEXT"); } } saveStreamToFile(stream, imageCommand + ".jpg"); } void saveStreamToFile(final ByteArrayOutputStream stream, final String filename) throws IOException { final FileOutputStream out = new FileOutputStream(filename); logger.info("Download finished, saving stream to " + filename + "."); out.write(stream.toByteArray()); out.close(); stream.close(); } /** * Read {@link MainInstance#JSON_FILE_NAME} and initialize parameters to be used. * <p> * Initializes: * <ul> * <li>{@link MainInstance#clientPublicAddress}</li> * <li>{@link MainInstance#clientListeningPort}</li> * <li>{@link MainInstance#serverListeningPort}</li> * <li>{@link MainInstance#echoRequestCode}</li> * <li>{@link MainInstance#imageRequestCode}</li> * <li>{@link MainInstance#soundRequestCode}</li> * </ul> * <p>Uses {@link Gson} library.</p> * * @throws FileNotFoundException */ void initVariables() throws FileNotFoundException { final JsonReader reader = new JsonReader(new FileReader(JSON_FILE_NAME)); final JsonObject json = new Gson().fromJson(reader, JsonObject.class); clientPublicAddress = json.get("clientPublicAddress").getAsString(); clientListeningPort = json.get("clientListeningPort").getAsInt(); serverListeningPort = json.get("serverListeningPort").getAsInt(); echoRequestCode = json.get("echoRequestCode").getAsString(); imageRequestCode = json.get("imageRequestCode").getAsString(); soundRequestCode = json.get("soundRequestCode").getAsString(); } /** * Interface that hold {@link Decoder#decode(byte[], byte[], int)} function for decoding of received audio * files in @{code byte[]} format. */ interface Decoder { /** * Decode an encoded buffer. * * @param buffer The buffer. * @param decoded The decoded result. * @param decodedIndex The place to start decoding in the buffer. */ void decode(final byte[] buffer, byte[] decoded, int decodedIndex); void saveHistory(File filename) throws FileNotFoundException; } } }
14199_1
package com.ots.services; import com.ots.dto.PersonData; import java.util.List; /** * Created by sdimitriadis on 12/12/2016. */ public interface PersonService { /** * Ανάκτηση στοιχείων για πρόσωπα το όνομα των οποίων ξεκινά με το δεδομένο λεκτικό */ List<PersonData> findPersonDataStartingWithSurname(String surname); }
ots-sa/neo4j-visualisation
src/main/java/com/ots/services/PersonService.java
163
/** * Ανάκτηση στοιχείων για πρόσωπα το όνομα των οποίων ξεκινά με το δεδομένο λεκτικό */
block_comment
el
package com.ots.services; import com.ots.dto.PersonData; import java.util.List; /** * Created by sdimitriadis on 12/12/2016. */ public interface PersonService { /** * Ανάκτηση στοιχείων για<SUF>*/ List<PersonData> findPersonDataStartingWithSurname(String surname); }
2998_65
public class LinkedList implements List { // Υλοποίηση μιας απλά Συνδεδεμένης Λίστας (linked list) public static final String MSG_LIST_EMPTY = "Η λίστα είναι κενή!"; // Δήλωση σταθεράς μηνύματος κενής λίστας private Node firstNode, lastNode; public LinkedList() { // Default constructor this.firstNode = this.lastNode = null; } public Node getFirstNode() { return this.firstNode; } public Node getLastNode() { return this.lastNode; } public boolean isEmpty() { return (this.firstNode == null); // Επιστρέφει true (η λίστα είναι κενή) αν ο πρώτος κόμβος είναι null } // End of function: isEmpty() @Override public int getSize() { // Να ελεγχθεί αν είναι σωστή int listSize = 0; // Υλοποίηση με while - ΑΡΧΗ if (this.isEmpty()) System.out.println(MSG_LIST_EMPTY); // Γιατί όχι το? -> throw new ListEmptyException(MSG_LIST_EMPTY); else { Node position = this.firstNode; while (position != null) { position = position.getNext(); listSize++; } } // Υλοποίηση με while - ΤΕΛΟΣ // Υλοποίηση με for - ΑΡΧΗ /* for (Node position = this.firstNode; position != null; position = position.getNext()) listSize++; */ // Υλοποίηση με for - ΤΕΛΟΣ return listSize; } // End of function: getSize() public void insertFirst(Object newItem) { if (this.isEmpty()) this.firstNode = this.lastNode = new Node(newItem, null); else this.firstNode = new Node(newItem, this.firstNode); } // End of function: insertFirst() public void insertLast(Object newItem) { if (this.isEmpty()) this.firstNode = this.lastNode = new Node(newItem, null); else this.lastNode = this.lastNode.next = new Node(newItem, null); } // End of function: insertLast() public Object removeFirst() throws ListEmptyException { if (this.isEmpty()) throw new ListEmptyException(MSG_LIST_EMPTY); Object removedItem = this.firstNode.item; if (this.firstNode == this.lastNode) // if (this.firstNode.equals(this.lastNode)) // Με την .equals. Για δοκιμή this.firstNode = this.lastNode = null; else this.firstNode = this.firstNode.next; return removedItem; } // End of function: removeFirst() public Object removeLast() throws ListEmptyException { if (this.isEmpty()) throw new ListEmptyException(MSG_LIST_EMPTY); Object removedItem = this.lastNode.item; if (this.firstNode == this.lastNode) // if (this.firstNode.equals(this.lastNode)) // Με την .equals. Για δοκιμή this.firstNode = this.lastNode = null; else { // Υλοποίηση με while - ΑΡΧΗ Node currentNode = this.firstNode; while (currentNode.next != this.lastNode) currentNode = currentNode.next; // Υλοποίηση με while - ΤΕΛΟΣ // Υλοποίηση με for - ΑΡΧΗ /* Node position; for (position = this.firstNode; position.getNext() != this.lastNode; position = position.getNext()) { this.lastNode = position; position.setNext(null); } */ // Υλοποίηση με for - ΤΕΛΟΣ this.lastNode = currentNode; currentNode.next = null; } return removedItem; } // End of function: removeLast() public void printList() { if (this.isEmpty()) System.out.println(MSG_LIST_EMPTY); // Γιατί όχι το? -> throw new ListEmptyException(MSG_LIST_EMPTY); else { Node currentNode = this.firstNode; while (currentNode != null) { System.out.println(currentNode.item.toString() + " "); currentNode = currentNode.next; } //System.out.println(); } } // End of function: printList() // ΖΗΤΟΥΜΕΝΑ ΑΣΚΗΣΗΣ 3.2 public Object minOfList() { if (this.isEmpty()) throw new ListEmptyException(MSG_LIST_EMPTY); Object min = this.firstNode.getItem(); Node position = this.firstNode.getNext(); while (position != null) { // Υλοποίηση χωρίς Comparable - ΑΡΧΗ if (((String)min).compareTo((String) position.getItem()) > 0) // <--- Αλλαγή στο casting στον τύπο αντικειμένου που μας ενδιαφέρει (προεπιλεγμένο: String) // Υλοποίηση χωρίς Comparable - ΤΕΛΟΣ // Υλοποίηση με Comparable - ΑΡΧΗ // Comparable CompMax = (Comparable)max; // Comparable CompItem = (Comparable)position.getItem(); // if (CompMax.compareTo(CompItem) < 0) // Υλοποίηση με Comparable - ΤΕΛΟΣ min = position.getItem(); // Εναλλακτικά μέσα στην if - ΑΡΧΗ // if (((Comparable)max).compareTo((Comparable)position.getItem()) > 0) // Ο παρακάτω έλεγχος γίνεται και έτσι // if (((String)min).compareTo((String) position.getItem()) > 0) // <--- Αλλαγή στο casting στον τύπο αντικειμένου που μας ενδιαφέρει (προεπιλεγμένο: String) // min = position.getItem(); // Εναλλακτικά μέσα στην if - ΤΕΛΟΣ position = position.getNext(); } return min; } // End of function: minOfList() public Object maxOfList() { if (this.isEmpty()) throw new ListEmptyException(MSG_LIST_EMPTY); Object max = this.firstNode.getItem(); Node position = this.firstNode.getNext(); while (position != null) { // Υλοποίηση χωρίς Comparable - ΑΡΧΗ if (((String)max).compareTo((String) position.getItem()) < 0) // <--- Αλλαγή στο casting στον τύπο αντικειμένου που μας ενδιαφέρει (προεπιλεγμένο: String) // Υλοποίηση χωρίς Comparable - ΤΕΛΟΣ // Υλοποίηση με Comparable - ΑΡΧΗ // Comparable CompMax = (Comparable)max; // Comparable CompItem = (Comparable)position.getItem(); // if (CompMax.compareTo(CompItem) < 0) // Υλοποίηση με Comparable - ΤΕΛΟΣ max = position.getItem(); // Εναλλακτικά μέσα στην if - ΑΡΧΗ // if (((Comparable)max).compareTo((Comparable)position.getItem()) < 0) // Ο παρακάτω έλεγχος γίνεται και έτσι // Εναλλακτικά μέσα στην if - ΤΕΛΟΣ position = position.getNext(); } return max; } // End of function: maxOfList() public boolean nodeExist(Object item) { if (this.isEmpty()) throw new ListEmptyException(MSG_LIST_EMPTY); Node tmpNode = this.firstNode; while (tmpNode != null) if (tmpNode.getItem().equals(item)) // if (((Comparable)tmpNode.getItem()).compareTo((Comparable)item) == 0) return true; else tmpNode = tmpNode.getNext(); return false; } // End of function: nodeExist() public LinkedList sortList() { Node traceNode, currentNode, minNode; traceNode = this.getFirstNode(); // Ap;o to traceNode και δεξιά η λίστα δεν είναι ταξινομημένη while (traceNode != null) { currentNode = traceNode; minNode = traceNode; while (currentNode != null) { // Comparable CompCurrentNode = (Comparable) currentNode.getItem(); // Ο παρακάτω έλεγχος γίνεται και έτσι // if (CompCurrentNode.compareTo(minNode.getItem()) < 0) // Ο παρακάτω έλεγχος γίνεται και έτσι if (((String)(currentNode.getItem())).compareTo((String)(minNode.getItem())) < 0) // Αύξουσα ταξινόμηση minNode = currentNode; currentNode = currentNode.getNext(); } // End of while: currentNode Object temp = traceNode.getItem(); // Έλεγχος εδώ traceNode.setItem(minNode.getItem()); // Swap minNode.setItem(temp); // Swap traceNode = traceNode.getNext(); // Swap } // End of while: traceNode return this; } // End of function: sortList() public LinkedList bubbleSort() { Node currentNode = this.getFirstNode(); while (currentNode != null) { Node secondNode = currentNode.getNext(); while (secondNode != null) { // Comparable CompCurrentNode = (Comparable) currentNode.getItem(); // Ο παρακάτω έλεγχος γίνεται και έτσι // if (CompCurrentNode.compareTo(secondNode.getItem()) < 0) // Ο παρακάτω έλεγχος γίνεται και έτσι if (((String)(currentNode.getItem())).compareTo((String)(secondNode.getItem())) > 0) { // Αύξουσα ταξινόμηση Object temp = currentNode.getItem(); // Swap currentNode.setItem(secondNode.getItem()); // Swap secondNode.setItem(temp); // Swap } secondNode = secondNode.getNext(); } // End of while: secondNode currentNode = currentNode.getNext(); } // End of while: currentNode return this; } // End of function: bubbleSort() // ΖΗΤΟΥΜΕΝΑ ΑΣΚΗΣΗΣ 3.3 public Object[] minMaxOfList() { // Επιστρέφει πίνακα δυο θέσεων που περιέχει την ελάχιστη και μέγιστη τιμή που θα βρει στη λίστα if (this.isEmpty()) throw new ListEmptyException(MSG_LIST_EMPTY); Object[] minMax = new Object[2]; minMax[0] = this.minOfList(); minMax[1] = this.maxOfList(); return minMax; } // End of function: minMaxOfList() public void minMaxOfListByRef(Object[] pin) { // Επιστρέφει ΜΕ ΑΝΑΦΟΡΑ πίνακα δυο θέσεων που περιέχει την ελάχιστη και μέγιστη τιμή που θα βρει στη λίστα if (this.isEmpty()) throw new ListEmptyException(MSG_LIST_EMPTY); Object[] minMax = new Object[2]; pin[0] = this.minOfList(); pin[1] = this.maxOfList(); } // End of function: minMaxOfList() }
panosale/DIPAE_DataStructures_3rd_Term
Askisi3.3/src/LinkedList.java
3,366
// ΖΗΤΟΥΜΕΝΑ ΑΣΚΗΣΗΣ 3.3
line_comment
el
public class LinkedList implements List { // Υλοποίηση μιας απλά Συνδεδεμένης Λίστας (linked list) public static final String MSG_LIST_EMPTY = "Η λίστα είναι κενή!"; // Δήλωση σταθεράς μηνύματος κενής λίστας private Node firstNode, lastNode; public LinkedList() { // Default constructor this.firstNode = this.lastNode = null; } public Node getFirstNode() { return this.firstNode; } public Node getLastNode() { return this.lastNode; } public boolean isEmpty() { return (this.firstNode == null); // Επιστρέφει true (η λίστα είναι κενή) αν ο πρώτος κόμβος είναι null } // End of function: isEmpty() @Override public int getSize() { // Να ελεγχθεί αν είναι σωστή int listSize = 0; // Υλοποίηση με while - ΑΡΧΗ if (this.isEmpty()) System.out.println(MSG_LIST_EMPTY); // Γιατί όχι το? -> throw new ListEmptyException(MSG_LIST_EMPTY); else { Node position = this.firstNode; while (position != null) { position = position.getNext(); listSize++; } } // Υλοποίηση με while - ΤΕΛΟΣ // Υλοποίηση με for - ΑΡΧΗ /* for (Node position = this.firstNode; position != null; position = position.getNext()) listSize++; */ // Υλοποίηση με for - ΤΕΛΟΣ return listSize; } // End of function: getSize() public void insertFirst(Object newItem) { if (this.isEmpty()) this.firstNode = this.lastNode = new Node(newItem, null); else this.firstNode = new Node(newItem, this.firstNode); } // End of function: insertFirst() public void insertLast(Object newItem) { if (this.isEmpty()) this.firstNode = this.lastNode = new Node(newItem, null); else this.lastNode = this.lastNode.next = new Node(newItem, null); } // End of function: insertLast() public Object removeFirst() throws ListEmptyException { if (this.isEmpty()) throw new ListEmptyException(MSG_LIST_EMPTY); Object removedItem = this.firstNode.item; if (this.firstNode == this.lastNode) // if (this.firstNode.equals(this.lastNode)) // Με την .equals. Για δοκιμή this.firstNode = this.lastNode = null; else this.firstNode = this.firstNode.next; return removedItem; } // End of function: removeFirst() public Object removeLast() throws ListEmptyException { if (this.isEmpty()) throw new ListEmptyException(MSG_LIST_EMPTY); Object removedItem = this.lastNode.item; if (this.firstNode == this.lastNode) // if (this.firstNode.equals(this.lastNode)) // Με την .equals. Για δοκιμή this.firstNode = this.lastNode = null; else { // Υλοποίηση με while - ΑΡΧΗ Node currentNode = this.firstNode; while (currentNode.next != this.lastNode) currentNode = currentNode.next; // Υλοποίηση με while - ΤΕΛΟΣ // Υλοποίηση με for - ΑΡΧΗ /* Node position; for (position = this.firstNode; position.getNext() != this.lastNode; position = position.getNext()) { this.lastNode = position; position.setNext(null); } */ // Υλοποίηση με for - ΤΕΛΟΣ this.lastNode = currentNode; currentNode.next = null; } return removedItem; } // End of function: removeLast() public void printList() { if (this.isEmpty()) System.out.println(MSG_LIST_EMPTY); // Γιατί όχι το? -> throw new ListEmptyException(MSG_LIST_EMPTY); else { Node currentNode = this.firstNode; while (currentNode != null) { System.out.println(currentNode.item.toString() + " "); currentNode = currentNode.next; } //System.out.println(); } } // End of function: printList() // ΖΗΤΟΥΜΕΝΑ ΑΣΚΗΣΗΣ 3.2 public Object minOfList() { if (this.isEmpty()) throw new ListEmptyException(MSG_LIST_EMPTY); Object min = this.firstNode.getItem(); Node position = this.firstNode.getNext(); while (position != null) { // Υλοποίηση χωρίς Comparable - ΑΡΧΗ if (((String)min).compareTo((String) position.getItem()) > 0) // <--- Αλλαγή στο casting στον τύπο αντικειμένου που μας ενδιαφέρει (προεπιλεγμένο: String) // Υλοποίηση χωρίς Comparable - ΤΕΛΟΣ // Υλοποίηση με Comparable - ΑΡΧΗ // Comparable CompMax = (Comparable)max; // Comparable CompItem = (Comparable)position.getItem(); // if (CompMax.compareTo(CompItem) < 0) // Υλοποίηση με Comparable - ΤΕΛΟΣ min = position.getItem(); // Εναλλακτικά μέσα στην if - ΑΡΧΗ // if (((Comparable)max).compareTo((Comparable)position.getItem()) > 0) // Ο παρακάτω έλεγχος γίνεται και έτσι // if (((String)min).compareTo((String) position.getItem()) > 0) // <--- Αλλαγή στο casting στον τύπο αντικειμένου που μας ενδιαφέρει (προεπιλεγμένο: String) // min = position.getItem(); // Εναλλακτικά μέσα στην if - ΤΕΛΟΣ position = position.getNext(); } return min; } // End of function: minOfList() public Object maxOfList() { if (this.isEmpty()) throw new ListEmptyException(MSG_LIST_EMPTY); Object max = this.firstNode.getItem(); Node position = this.firstNode.getNext(); while (position != null) { // Υλοποίηση χωρίς Comparable - ΑΡΧΗ if (((String)max).compareTo((String) position.getItem()) < 0) // <--- Αλλαγή στο casting στον τύπο αντικειμένου που μας ενδιαφέρει (προεπιλεγμένο: String) // Υλοποίηση χωρίς Comparable - ΤΕΛΟΣ // Υλοποίηση με Comparable - ΑΡΧΗ // Comparable CompMax = (Comparable)max; // Comparable CompItem = (Comparable)position.getItem(); // if (CompMax.compareTo(CompItem) < 0) // Υλοποίηση με Comparable - ΤΕΛΟΣ max = position.getItem(); // Εναλλακτικά μέσα στην if - ΑΡΧΗ // if (((Comparable)max).compareTo((Comparable)position.getItem()) < 0) // Ο παρακάτω έλεγχος γίνεται και έτσι // Εναλλακτικά μέσα στην if - ΤΕΛΟΣ position = position.getNext(); } return max; } // End of function: maxOfList() public boolean nodeExist(Object item) { if (this.isEmpty()) throw new ListEmptyException(MSG_LIST_EMPTY); Node tmpNode = this.firstNode; while (tmpNode != null) if (tmpNode.getItem().equals(item)) // if (((Comparable)tmpNode.getItem()).compareTo((Comparable)item) == 0) return true; else tmpNode = tmpNode.getNext(); return false; } // End of function: nodeExist() public LinkedList sortList() { Node traceNode, currentNode, minNode; traceNode = this.getFirstNode(); // Ap;o to traceNode και δεξιά η λίστα δεν είναι ταξινομημένη while (traceNode != null) { currentNode = traceNode; minNode = traceNode; while (currentNode != null) { // Comparable CompCurrentNode = (Comparable) currentNode.getItem(); // Ο παρακάτω έλεγχος γίνεται και έτσι // if (CompCurrentNode.compareTo(minNode.getItem()) < 0) // Ο παρακάτω έλεγχος γίνεται και έτσι if (((String)(currentNode.getItem())).compareTo((String)(minNode.getItem())) < 0) // Αύξουσα ταξινόμηση minNode = currentNode; currentNode = currentNode.getNext(); } // End of while: currentNode Object temp = traceNode.getItem(); // Έλεγχος εδώ traceNode.setItem(minNode.getItem()); // Swap minNode.setItem(temp); // Swap traceNode = traceNode.getNext(); // Swap } // End of while: traceNode return this; } // End of function: sortList() public LinkedList bubbleSort() { Node currentNode = this.getFirstNode(); while (currentNode != null) { Node secondNode = currentNode.getNext(); while (secondNode != null) { // Comparable CompCurrentNode = (Comparable) currentNode.getItem(); // Ο παρακάτω έλεγχος γίνεται και έτσι // if (CompCurrentNode.compareTo(secondNode.getItem()) < 0) // Ο παρακάτω έλεγχος γίνεται και έτσι if (((String)(currentNode.getItem())).compareTo((String)(secondNode.getItem())) > 0) { // Αύξουσα ταξινόμηση Object temp = currentNode.getItem(); // Swap currentNode.setItem(secondNode.getItem()); // Swap secondNode.setItem(temp); // Swap } secondNode = secondNode.getNext(); } // End of while: secondNode currentNode = currentNode.getNext(); } // End of while: currentNode return this; } // End of function: bubbleSort() // ΖΗΤΟΥΜΕΝΑ ΑΣΚΗΣΗΣ<SUF> public Object[] minMaxOfList() { // Επιστρέφει πίνακα δυο θέσεων που περιέχει την ελάχιστη και μέγιστη τιμή που θα βρει στη λίστα if (this.isEmpty()) throw new ListEmptyException(MSG_LIST_EMPTY); Object[] minMax = new Object[2]; minMax[0] = this.minOfList(); minMax[1] = this.maxOfList(); return minMax; } // End of function: minMaxOfList() public void minMaxOfListByRef(Object[] pin) { // Επιστρέφει ΜΕ ΑΝΑΦΟΡΑ πίνακα δυο θέσεων που περιέχει την ελάχιστη και μέγιστη τιμή που θα βρει στη λίστα if (this.isEmpty()) throw new ListEmptyException(MSG_LIST_EMPTY); Object[] minMax = new Object[2]; pin[0] = this.minOfList(); pin[1] = this.maxOfList(); } // End of function: minMaxOfList() }
898_2
public class Customer { private final int MAX_PAYMENTS = 10; // Αν θέλουμε παραλείπουμε τη σταθερά αλλά πρέπει να χρησιμοποιούμε παντού το μέγεθος πίνακα που δίνεται (10) private int id; private double balance; private Payment[] payments; // Έχουμε Σύνθεση και όχι κανονική Κληρονομικότητα. Αφού ο πελάτης "έχει έναν" πίνακα πληρωμών και ΔΕΝ "είναι ένας" πίνακας πληρωμών. // Default Constructor public Customer() { } // Full Constructor public Customer(int newId, double newBalance) { this.id = newId; this.balance = newBalance; this.payments = new Payment[MAX_PAYMENTS]; // Δημιουργία του πίνακα αντικειμένων Payment. for (int i = 0; i < MAX_PAYMENTS; i++) { // Αρχικοποίηση όλων των θέσεων του πίνακα με 0. Θα χρειαστεί παρακάτω στη μέθοδο AddPayment(). this.payments[i] = new Payment(); // Δημιουργία νέου αντικειμένου Payment στη θέση [i] του πίνακα payments. this.payments[i].setvAT(0); this.payments[i].setPaidAmount(0); } } public void AddPayment(double paymnt) { /* Οι παρακάτω γραμμές μπορούν να βελτιωθούν ώστε αν το balance είναι 0 (άρα δεν υπάρχει υπόλοιπο χρωστούμενο ποσό) να μην τις εκτελεί καθόλου. Προς το παρόν υλοποιείται στη main πριν την κλήση της AddPayment. */ try { if (paymnt > this.balance) // Αν η πληρωμή που δόθηκε με παράμετρο (paymnt) είναι μεγαλύτερη απ' το υπόλοιπο πόσο (balance)... throw new CustomerBalanceException(); // ... "πετάει" το exception που ζητάει η άσκηση. for (int i = 0; i < payments.length; i++) if (payments[i].getAmmountWithVAT() == 0) { // Βρίσκει την επόμενη κενή θέση του πίνακα πληρωμών (payments) ώστε να καταχωρήσει τη νέα πληρωμή (paymnt). // 1ος τρόπος payments[i].setId(i); payments[i].setvAT(paymnt * 0.24); // Το ποσοστό του φόρου είναι σταθερό 24%. *** ΚΑΛΟ ΕΙΝΑΙ ΝΑ ΤΟ ΔΙΕΥΚΡΙΝΗΣΕΙ Ο ΚΑΘΗΓΗΤΗΣ. payments[i].setPaidAmount(paymnt - payments[i].getvAT()); // 2ος τρόπος. Εναλλακτικά μπορεί να γίνει και με την παρακάτω μέθοδο αρκεί να απενεργοποιηθούν οι δυο γραμμές του 1ου τρόπου. //this.setPayments(i, paymnt - (paymnt * 0.24), paymnt * 0.24); // Το ποσοστό του φόρου είναι σταθερό 24%. *** ΚΑΛΟ ΕΙΝΑΙ ΝΑ ΤΟ ΔΙΕΥΚΡΙΝΗΣΕΙ Ο ΚΑΘΗΓΗΤΗΣ. this.balance = this.balance - paymnt; // Αφαιρεί από το υπόλοιπο (balance), την πληρωμή που δόθηκε με παράμετρο (paymnt). break; // Αφού έχει καταχωρηθεί μια πληρωμή σε κενή θέση του πίνακα, "σπάει" η επανάληψη for. } } catch (CustomerBalanceException msg) { // "Πιάνει" το exception που ζητάει η άσκηση. System.out.println("Exception! Το ποσό πληρωμής είναι μεγαλύτερο από το υπόλοιπο. Η πληρωμή δεν καταχωρήθηκε."); // Εμφανίζει το μήνυμα του exception που ζητάει η άσκηση. } } // Μέθοδοι get, set & toString public void setId(int id) { this.id = id; } public int getId() { return this.id; } public void setBalance(double balance) { this.balance = balance; } public double getBalance() { return this.balance; } public String getPayments(int i) { // GIA ELEGXO KAI DIORTHOSI return this.payments[i].toString(); } public void setPayments(int i, double newPaidAmmount, double newVAT) { this.payments[i].setPaidAmount(newPaidAmmount); this.payments[i].setvAT(newVAT); } public String toString() { String tmpStr = ""; // Δήλωση προσωρινού String για την επιστροφή των πληροφοριών που ζητάει η άσκηση. for (int i = 0; i < payments.length; i++) // "Δημιουργία" του String επιστροφής που ζητάει η άσκηση με την πρόσθεση όλων των γραμμών του πίνακα πληρωμών (payments). tmpStr = tmpStr + "Payment no[" + i +"]: " + this.payments[i].getAmmountWithVAT() + "\n"; return "id: " + this.id + ", Payments: \n" + tmpStr; // Επιστροφή του id και του προσωρινού String που δημιουργήθηκε παραπάνω. } }
panosale/DIPAE_OOP_2nd_Term-JAVA
PaliaThemata/OOP_E22-23/src/Customer.java
2,152
// Δημιουργία του πίνακα αντικειμένων Payment.
line_comment
el
public class Customer { private final int MAX_PAYMENTS = 10; // Αν θέλουμε παραλείπουμε τη σταθερά αλλά πρέπει να χρησιμοποιούμε παντού το μέγεθος πίνακα που δίνεται (10) private int id; private double balance; private Payment[] payments; // Έχουμε Σύνθεση και όχι κανονική Κληρονομικότητα. Αφού ο πελάτης "έχει έναν" πίνακα πληρωμών και ΔΕΝ "είναι ένας" πίνακας πληρωμών. // Default Constructor public Customer() { } // Full Constructor public Customer(int newId, double newBalance) { this.id = newId; this.balance = newBalance; this.payments = new Payment[MAX_PAYMENTS]; // Δημιουργία του<SUF> for (int i = 0; i < MAX_PAYMENTS; i++) { // Αρχικοποίηση όλων των θέσεων του πίνακα με 0. Θα χρειαστεί παρακάτω στη μέθοδο AddPayment(). this.payments[i] = new Payment(); // Δημιουργία νέου αντικειμένου Payment στη θέση [i] του πίνακα payments. this.payments[i].setvAT(0); this.payments[i].setPaidAmount(0); } } public void AddPayment(double paymnt) { /* Οι παρακάτω γραμμές μπορούν να βελτιωθούν ώστε αν το balance είναι 0 (άρα δεν υπάρχει υπόλοιπο χρωστούμενο ποσό) να μην τις εκτελεί καθόλου. Προς το παρόν υλοποιείται στη main πριν την κλήση της AddPayment. */ try { if (paymnt > this.balance) // Αν η πληρωμή που δόθηκε με παράμετρο (paymnt) είναι μεγαλύτερη απ' το υπόλοιπο πόσο (balance)... throw new CustomerBalanceException(); // ... "πετάει" το exception που ζητάει η άσκηση. for (int i = 0; i < payments.length; i++) if (payments[i].getAmmountWithVAT() == 0) { // Βρίσκει την επόμενη κενή θέση του πίνακα πληρωμών (payments) ώστε να καταχωρήσει τη νέα πληρωμή (paymnt). // 1ος τρόπος payments[i].setId(i); payments[i].setvAT(paymnt * 0.24); // Το ποσοστό του φόρου είναι σταθερό 24%. *** ΚΑΛΟ ΕΙΝΑΙ ΝΑ ΤΟ ΔΙΕΥΚΡΙΝΗΣΕΙ Ο ΚΑΘΗΓΗΤΗΣ. payments[i].setPaidAmount(paymnt - payments[i].getvAT()); // 2ος τρόπος. Εναλλακτικά μπορεί να γίνει και με την παρακάτω μέθοδο αρκεί να απενεργοποιηθούν οι δυο γραμμές του 1ου τρόπου. //this.setPayments(i, paymnt - (paymnt * 0.24), paymnt * 0.24); // Το ποσοστό του φόρου είναι σταθερό 24%. *** ΚΑΛΟ ΕΙΝΑΙ ΝΑ ΤΟ ΔΙΕΥΚΡΙΝΗΣΕΙ Ο ΚΑΘΗΓΗΤΗΣ. this.balance = this.balance - paymnt; // Αφαιρεί από το υπόλοιπο (balance), την πληρωμή που δόθηκε με παράμετρο (paymnt). break; // Αφού έχει καταχωρηθεί μια πληρωμή σε κενή θέση του πίνακα, "σπάει" η επανάληψη for. } } catch (CustomerBalanceException msg) { // "Πιάνει" το exception που ζητάει η άσκηση. System.out.println("Exception! Το ποσό πληρωμής είναι μεγαλύτερο από το υπόλοιπο. Η πληρωμή δεν καταχωρήθηκε."); // Εμφανίζει το μήνυμα του exception που ζητάει η άσκηση. } } // Μέθοδοι get, set & toString public void setId(int id) { this.id = id; } public int getId() { return this.id; } public void setBalance(double balance) { this.balance = balance; } public double getBalance() { return this.balance; } public String getPayments(int i) { // GIA ELEGXO KAI DIORTHOSI return this.payments[i].toString(); } public void setPayments(int i, double newPaidAmmount, double newVAT) { this.payments[i].setPaidAmount(newPaidAmmount); this.payments[i].setvAT(newVAT); } public String toString() { String tmpStr = ""; // Δήλωση προσωρινού String για την επιστροφή των πληροφοριών που ζητάει η άσκηση. for (int i = 0; i < payments.length; i++) // "Δημιουργία" του String επιστροφής που ζητάει η άσκηση με την πρόσθεση όλων των γραμμών του πίνακα πληρωμών (payments). tmpStr = tmpStr + "Payment no[" + i +"]: " + this.payments[i].getAmmountWithVAT() + "\n"; return "id: " + this.id + ", Payments: \n" + tmpStr; // Επιστροφή του id και του προσωρινού String που δημιουργήθηκε παραπάνω. } }
3805_0
package com.Panos.Final; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JLabel; import javax.swing.JButton; import javax.swing.SwingConstants; import javax.swing.JSeparator; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.Box; public class MainWindow extends JFrame { private static final long serialVersionUID = 1L; JPanel contentPane; public MainWindow() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setIconImage(Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/resources/aueb.jpg"))); this.setResizable(false); this.setTitle("AUEB Java A2Z 2023"); this.setBounds(100, 100, 460, 360); // Αντικατέστησα το κώδικα της MainWindow που έκανε τη σύνδεση με τον σερβερ, γιατί δημιουργούσε πρόβλημα . //Γι’ αυτό έκανα το DBconnector, στο οποίο μετέφερα τον κώδικα της σύνδεσης, //έτσι ώστε να είναι μονίμως "ενεργό" και προσβασιμο κατα τη διαρκια χρησης. /* * this.addWindowListener(new WindowAdapter() { * * @Override public void windowOpened(WindowEvent e) { * * String url = "jdbc:mysql://localhost:3306/java_assignment_db"; String * username = "PanosTr"; // Insert your username String password = "123456"; // * Insert your password * * try { conn = DriverManager.getConnection(url, username, password); } catch * (SQLException ex) { throw new * IllegalStateException("Cannot connect to database!", ex); } } }); */ // Content Pane contentPane = new JPanel(); contentPane.setBackground(new Color(240, 248, 255)); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(null); setContentPane(contentPane); // Main title Green & Red for shadow JLabel lbl_maintitle = new JLabel("Book/Library Orders"); lbl_maintitle.setBounds(55, 38, 322, 47); lbl_maintitle.setHorizontalAlignment(SwingConstants.RIGHT); lbl_maintitle.setForeground(new Color(0, 100, 0)); lbl_maintitle.setFont(new Font("Gill Sans MT", Font.BOLD, 31)); contentPane.add(lbl_maintitle); // Separator Line JSeparator separator = new JSeparator(); separator.setBounds(10, 84, 426, 1); contentPane.add(separator); // Label Libraries JLabel lbl_libraries = new JLabel("Libraries"); lbl_libraries.setBounds(53, 234, 95, 27); lbl_libraries.setHorizontalAlignment(SwingConstants.RIGHT); lbl_libraries.setForeground(new Color(153, 0, 0)); lbl_libraries.setFont(new Font("Gill Sans MT", Font.BOLD, 20)); contentPane.add(lbl_libraries); //Button for moving to the FrmLibrarySearchList JButton btnLibraries = new JButton(""); btnLibraries.setBounds(158, 234, 33, 27); btnLibraries.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { DriverClass.librarysearchlist.setVisible(true); DriverClass.mainFrame.setEnabled(false); } }); contentPane.add(btnLibraries); // Label Version JLabel lbl_version = new JLabel("Version"); lbl_version.setHorizontalAlignment(SwingConstants.LEFT); lbl_version.setBounds(301, 234, 82, 27); lbl_version.setForeground(new Color(153, 0, 0)); lbl_version.setFont(new Font("Gill Sans MT", Font.BOLD, 20)); contentPane.add(lbl_version); // Button Version JButton btnVersion = new JButton(""); btnVersion.setBounds(258, 234, 33, 27); btnVersion.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { DriverClass.mainFrame.setEnabled(false); DriverClass.version.setVisible(true); } }); contentPane.add(btnVersion); // Button for moving to the FrmBookSearchList JButton btnBooks = new JButton(""); btnBooks.setBounds(158, 125, 33, 27); btnBooks.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { DriverClass.booksearchlist.setVisible(true); DriverClass.mainFrame.setEnabled(false); } }); contentPane.add(btnBooks); // Label Books JLabel lbl_books = new JLabel("Books"); lbl_books.setHorizontalAlignment(SwingConstants.RIGHT); lbl_books.setForeground(new Color(153, 0, 0)); lbl_books.setFont(new Font("Gill Sans MT", Font.BOLD, 20)); lbl_books.setBounds(53, 125, 95, 27); contentPane.add(lbl_books); //Button for moving to the FrmStockBookLibraries JButton btnStock = new JButton(""); btnStock.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { DriverClass.mainFrame.setEnabled(false); DriverClass.stockbooklibraries.setVisible(true); } }); btnStock.setBounds(258, 125, 33, 27); contentPane.add(btnStock); JLabel lbl_stock = new JLabel("Stock"); lbl_stock.setHorizontalAlignment(SwingConstants.LEFT); lbl_stock.setForeground(new Color(153, 0, 0)); lbl_stock.setFont(new Font("Gill Sans MT", Font.BOLD, 20)); lbl_stock.setBounds(301, 125, 82, 27); contentPane.add(lbl_stock); JLabel lbl_maintitle_1 = new JLabel("Book/Library Orders"); lbl_maintitle_1.setHorizontalAlignment(SwingConstants.RIGHT); lbl_maintitle_1.setForeground(Color.GRAY); lbl_maintitle_1.setFont(new Font("Gill Sans MT", Font.BOLD, 31)); lbl_maintitle_1.setBounds(56, 40, 322, 47); contentPane.add(lbl_maintitle_1); JSeparator separator_2 = new JSeparator(); separator_2.setBounds(213, 95, 1, 196); contentPane.add(separator_2); JSeparator separator_3 = new JSeparator(); separator_3.setBounds(213, 84, 1, 207); contentPane.add(separator_3); JLabel lblNewLabel = new JLabel("(Books in each library)"); lblNewLabel.setForeground(new Color(153, 0, 0)); lblNewLabel.setFont(new Font("Gill Sans MT", Font.PLAIN, 14)); lblNewLabel.setBounds(268, 162, 134, 13); contentPane.add(lblNewLabel); Component rigidArea = Box.createRigidArea(new Dimension(15, 15)); rigidArea.setFont(null); rigidArea.setBackground(new Color(0, 0, 0)); rigidArea.setForeground(new Color(0, 0, 0)); rigidArea.setBounds(0, 84, 444, 237); contentPane.add(rigidArea); } }
panostriantafyllidis/LibraryBooks_A2Z_project
src/com/Panos/Final/MainWindow.java
2,003
// Αντικατέστησα το κώδικα της MainWindow που έκανε τη σύνδεση με τον σερβερ, γιατί δημιουργούσε πρόβλημα .
line_comment
el
package com.Panos.Final; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JLabel; import javax.swing.JButton; import javax.swing.SwingConstants; import javax.swing.JSeparator; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.Box; public class MainWindow extends JFrame { private static final long serialVersionUID = 1L; JPanel contentPane; public MainWindow() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setIconImage(Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/resources/aueb.jpg"))); this.setResizable(false); this.setTitle("AUEB Java A2Z 2023"); this.setBounds(100, 100, 460, 360); // Αντικατέστησα το<SUF> //Γι’ αυτό έκανα το DBconnector, στο οποίο μετέφερα τον κώδικα της σύνδεσης, //έτσι ώστε να είναι μονίμως "ενεργό" και προσβασιμο κατα τη διαρκια χρησης. /* * this.addWindowListener(new WindowAdapter() { * * @Override public void windowOpened(WindowEvent e) { * * String url = "jdbc:mysql://localhost:3306/java_assignment_db"; String * username = "PanosTr"; // Insert your username String password = "123456"; // * Insert your password * * try { conn = DriverManager.getConnection(url, username, password); } catch * (SQLException ex) { throw new * IllegalStateException("Cannot connect to database!", ex); } } }); */ // Content Pane contentPane = new JPanel(); contentPane.setBackground(new Color(240, 248, 255)); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(null); setContentPane(contentPane); // Main title Green & Red for shadow JLabel lbl_maintitle = new JLabel("Book/Library Orders"); lbl_maintitle.setBounds(55, 38, 322, 47); lbl_maintitle.setHorizontalAlignment(SwingConstants.RIGHT); lbl_maintitle.setForeground(new Color(0, 100, 0)); lbl_maintitle.setFont(new Font("Gill Sans MT", Font.BOLD, 31)); contentPane.add(lbl_maintitle); // Separator Line JSeparator separator = new JSeparator(); separator.setBounds(10, 84, 426, 1); contentPane.add(separator); // Label Libraries JLabel lbl_libraries = new JLabel("Libraries"); lbl_libraries.setBounds(53, 234, 95, 27); lbl_libraries.setHorizontalAlignment(SwingConstants.RIGHT); lbl_libraries.setForeground(new Color(153, 0, 0)); lbl_libraries.setFont(new Font("Gill Sans MT", Font.BOLD, 20)); contentPane.add(lbl_libraries); //Button for moving to the FrmLibrarySearchList JButton btnLibraries = new JButton(""); btnLibraries.setBounds(158, 234, 33, 27); btnLibraries.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { DriverClass.librarysearchlist.setVisible(true); DriverClass.mainFrame.setEnabled(false); } }); contentPane.add(btnLibraries); // Label Version JLabel lbl_version = new JLabel("Version"); lbl_version.setHorizontalAlignment(SwingConstants.LEFT); lbl_version.setBounds(301, 234, 82, 27); lbl_version.setForeground(new Color(153, 0, 0)); lbl_version.setFont(new Font("Gill Sans MT", Font.BOLD, 20)); contentPane.add(lbl_version); // Button Version JButton btnVersion = new JButton(""); btnVersion.setBounds(258, 234, 33, 27); btnVersion.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { DriverClass.mainFrame.setEnabled(false); DriverClass.version.setVisible(true); } }); contentPane.add(btnVersion); // Button for moving to the FrmBookSearchList JButton btnBooks = new JButton(""); btnBooks.setBounds(158, 125, 33, 27); btnBooks.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { DriverClass.booksearchlist.setVisible(true); DriverClass.mainFrame.setEnabled(false); } }); contentPane.add(btnBooks); // Label Books JLabel lbl_books = new JLabel("Books"); lbl_books.setHorizontalAlignment(SwingConstants.RIGHT); lbl_books.setForeground(new Color(153, 0, 0)); lbl_books.setFont(new Font("Gill Sans MT", Font.BOLD, 20)); lbl_books.setBounds(53, 125, 95, 27); contentPane.add(lbl_books); //Button for moving to the FrmStockBookLibraries JButton btnStock = new JButton(""); btnStock.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { DriverClass.mainFrame.setEnabled(false); DriverClass.stockbooklibraries.setVisible(true); } }); btnStock.setBounds(258, 125, 33, 27); contentPane.add(btnStock); JLabel lbl_stock = new JLabel("Stock"); lbl_stock.setHorizontalAlignment(SwingConstants.LEFT); lbl_stock.setForeground(new Color(153, 0, 0)); lbl_stock.setFont(new Font("Gill Sans MT", Font.BOLD, 20)); lbl_stock.setBounds(301, 125, 82, 27); contentPane.add(lbl_stock); JLabel lbl_maintitle_1 = new JLabel("Book/Library Orders"); lbl_maintitle_1.setHorizontalAlignment(SwingConstants.RIGHT); lbl_maintitle_1.setForeground(Color.GRAY); lbl_maintitle_1.setFont(new Font("Gill Sans MT", Font.BOLD, 31)); lbl_maintitle_1.setBounds(56, 40, 322, 47); contentPane.add(lbl_maintitle_1); JSeparator separator_2 = new JSeparator(); separator_2.setBounds(213, 95, 1, 196); contentPane.add(separator_2); JSeparator separator_3 = new JSeparator(); separator_3.setBounds(213, 84, 1, 207); contentPane.add(separator_3); JLabel lblNewLabel = new JLabel("(Books in each library)"); lblNewLabel.setForeground(new Color(153, 0, 0)); lblNewLabel.setFont(new Font("Gill Sans MT", Font.PLAIN, 14)); lblNewLabel.setBounds(268, 162, 134, 13); contentPane.add(lblNewLabel); Component rigidArea = Box.createRigidArea(new Dimension(15, 15)); rigidArea.setFont(null); rigidArea.setBackground(new Color(0, 0, 0)); rigidArea.setForeground(new Color(0, 0, 0)); rigidArea.setBounds(0, 84, 444, 237); contentPane.add(rigidArea); } }
5783_3
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gr.csd.uoc.cs359.winter2019.logbook; import gr.csd.uoc.cs359.winter2019.logbook.db.PostDB; import gr.csd.uoc.cs359.winter2019.logbook.db.UserDB; import gr.csd.uoc.cs359.winter2019.logbook.model.Post; import gr.csd.uoc.cs359.winter2019.logbook.model.User; import java.util.List; /** * * @author papadako */ public class ExampleAPI { /** * An example of adding a new member in the database. Turing is a user of * our system * * @param args the command line arguments * @throws ClassNotFoundException * @throws java.lang.InterruptedException */ public static void main(String[] args) throws ClassNotFoundException, InterruptedException { // O Turing έσπασε τον κώδικα enigma που χρησιμοποιούσαν οι Γερμανοί // στον Παγκόσμιο Πόλεμο ΙΙ για να κρυπτογραφήσουν την επικοινωνία τους. // Άρα είναι πιθανό να χρησιμοποιούσε σαν passwd τη λέξη enigma, κάπως // τροποποιημένη :) // http://en.wikipedia.org/wiki/Enigma_machine // md5 της λέξης 3n!gm@ είναι e37f7cfcb0cd53734184de812b5c6175 User user = new User(); user.setUserName("turing"); user.setEmail("[email protected]"); user.setPassword("e37f7cfcb0cd53734184de812b5c6175"); user.setFirstName("Alan"); user.setLastName("Turing"); user.setBirthDate("07/07/1912"); user.setCountry("Science"); user.setTown("Computer Science"); user.setAddress("Computability"); user.setOccupation("Xompistas"); user.setGender("Male"); user.setInterests("Enigma, decyphering"); user.setInfo("You will have a job due to my work! :)"); if (UserDB.checkValidUserName("turing")) { // Add turing to database System.out.println("==>Adding users"); UserDB.addUser(user); System.out.println(user.toString()); System.out.println("==>Added user"); } else { System.out.println("User already exists.... No more Turings please!"); } List<User> users = UserDB.getUsers(); int i = 0; System.out.println("==>Retrieving"); for (User userIt : users) { System.out.println("userIt:" + i++); System.out.println(userIt); } // Add a wish as info System.out.println("==>Updating"); user = UserDB.getUser("turing"); if (user != null) { System.out.println("Updating" + user.getUserName()); user.setInfo("I hope you follow my path..."); UserDB.updateUser(user); } user = UserDB.getUser("turing"); if (user != null) { System.out.println("==>Updated"); System.out.println(UserDB.getUser("turing")); } Post post = new Post(); post.setUserName("kernelpanic"); post.setDescription("This is my first post"); PostDB.addPost(post); System.out.println("==>Deleting"); UserDB.deleteUser("turing"); System.out.println("==>Deleted"); if (UserDB.checkValidUserName("turing")) { // You can be a new Turing! System.out.println("Well, Turing is gone for a long time now!"); System.out.println("Hope we find a new one in this 2019 class!"); } } }
panteliselef/Traveler-Platform
logbook/src/main/java/gr/csd/uoc/cs359/winter2019/logbook/ExampleAPI.java
1,126
// O Turing έσπασε τον κώδικα enigma που χρησιμοποιούσαν οι Γερμανοί
line_comment
el
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gr.csd.uoc.cs359.winter2019.logbook; import gr.csd.uoc.cs359.winter2019.logbook.db.PostDB; import gr.csd.uoc.cs359.winter2019.logbook.db.UserDB; import gr.csd.uoc.cs359.winter2019.logbook.model.Post; import gr.csd.uoc.cs359.winter2019.logbook.model.User; import java.util.List; /** * * @author papadako */ public class ExampleAPI { /** * An example of adding a new member in the database. Turing is a user of * our system * * @param args the command line arguments * @throws ClassNotFoundException * @throws java.lang.InterruptedException */ public static void main(String[] args) throws ClassNotFoundException, InterruptedException { // O Turing<SUF> // στον Παγκόσμιο Πόλεμο ΙΙ για να κρυπτογραφήσουν την επικοινωνία τους. // Άρα είναι πιθανό να χρησιμοποιούσε σαν passwd τη λέξη enigma, κάπως // τροποποιημένη :) // http://en.wikipedia.org/wiki/Enigma_machine // md5 της λέξης 3n!gm@ είναι e37f7cfcb0cd53734184de812b5c6175 User user = new User(); user.setUserName("turing"); user.setEmail("[email protected]"); user.setPassword("e37f7cfcb0cd53734184de812b5c6175"); user.setFirstName("Alan"); user.setLastName("Turing"); user.setBirthDate("07/07/1912"); user.setCountry("Science"); user.setTown("Computer Science"); user.setAddress("Computability"); user.setOccupation("Xompistas"); user.setGender("Male"); user.setInterests("Enigma, decyphering"); user.setInfo("You will have a job due to my work! :)"); if (UserDB.checkValidUserName("turing")) { // Add turing to database System.out.println("==>Adding users"); UserDB.addUser(user); System.out.println(user.toString()); System.out.println("==>Added user"); } else { System.out.println("User already exists.... No more Turings please!"); } List<User> users = UserDB.getUsers(); int i = 0; System.out.println("==>Retrieving"); for (User userIt : users) { System.out.println("userIt:" + i++); System.out.println(userIt); } // Add a wish as info System.out.println("==>Updating"); user = UserDB.getUser("turing"); if (user != null) { System.out.println("Updating" + user.getUserName()); user.setInfo("I hope you follow my path..."); UserDB.updateUser(user); } user = UserDB.getUser("turing"); if (user != null) { System.out.println("==>Updated"); System.out.println(UserDB.getUser("turing")); } Post post = new Post(); post.setUserName("kernelpanic"); post.setDescription("This is my first post"); PostDB.addPost(post); System.out.println("==>Deleting"); UserDB.deleteUser("turing"); System.out.println("==>Deleted"); if (UserDB.checkValidUserName("turing")) { // You can be a new Turing! System.out.println("Well, Turing is gone for a long time now!"); System.out.println("Hope we find a new one in this 2019 class!"); } } }
699_12
import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.Arrays; public class Client { public static void main(String[] args) { // Παραδοχή : ΟΛΑ ΤΑ ARGUMENTS ΘΕΩΡΟΥΝΤΑΙ ΣΩΣΤΑ ΓΙΑ ΤΟ ΕΚΑΣΤΟΤΕ fn_id //Create account : java client <ip> <port number> 1 <username> --> -1 : Sorry, the user already exists //Show accounts : java client <ip> <port number> 2 <authToken> //Send message : java client <ip> <port number> 3 <authToken> <recipient> <message_body> //Show inbox : java client <ip> <port number> 4 <authToken> //Read message : java client <ip> <port number> 5 <authToken> <message_id> //Delete message : java client <ip> <port number> 6 <authToken> <message_id> int fnID = Integer.parseInt(args[2]); String ip = args[0]; // args[0] int port = Integer.parseInt(args[1]); // args[1] String username = args[3]; // args[3] για 1 String recipient; // args[4] για 3 String body; // args[5] για 3 int message_id; // ορίζεται παρακάτω γιατί πρέπει να γίνει parsed int authToken = -1; // ήθελε αρχικοποίηση για λόγους debugging if (fnID != 1) authToken = Integer.parseInt(args[3]); // args[3] εκτός από fn_id = 1 που δε χρησιμοποιείται // Establish connection to RMI registry try { // connect to the RMI registry Registry rmiRegistry = LocateRegistry.getRegistry(ip,port); // get reference for remote object MessengerInt stub = (MessengerInt) rmiRegistry.lookup("messenger"); switch(fnID) { case 1: // Create account if (!stub.isValidUsername(username)) System.out.println("Invalid Username"); else { int token = stub.createAccount(username); if (token == -1) // κωδικός για υπάρχον username System.out.println("Sorry, the user already exists"); else System.out.println(token); //όλα πήγαν καλά και επιστρέφεται το authToken } break; case 2: // Show accounts System.out.println(stub.showAccounts(authToken)); break; case 3: // Send message recipient = args[4]; // args[4] για 3 body = args[5]; // args[5] για 3 System.out.println(stub.sendMessage(authToken, recipient, body)); break; case 4: // Show inbox System.out.println(stub.showInbox(authToken)); break; case 5: // Read message message_id = Integer.parseInt(args[4]); // args[4] για fnID = 5, 6 System.out.println(stub.readMessage(authToken, message_id)); break; case 6: // Delete message message_id = Integer.parseInt(args[4]); // args[4] για fnID = 5, 6 System.out.println(stub.deleteMessage(authToken, message_id)); break; default: // code block } } catch (Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } } }
patiosga/MessagingApp
src/Client.java
991
// args[3] εκτός από fn_id = 1 που δε χρησιμοποιείται
line_comment
el
import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.Arrays; public class Client { public static void main(String[] args) { // Παραδοχή : ΟΛΑ ΤΑ ARGUMENTS ΘΕΩΡΟΥΝΤΑΙ ΣΩΣΤΑ ΓΙΑ ΤΟ ΕΚΑΣΤΟΤΕ fn_id //Create account : java client <ip> <port number> 1 <username> --> -1 : Sorry, the user already exists //Show accounts : java client <ip> <port number> 2 <authToken> //Send message : java client <ip> <port number> 3 <authToken> <recipient> <message_body> //Show inbox : java client <ip> <port number> 4 <authToken> //Read message : java client <ip> <port number> 5 <authToken> <message_id> //Delete message : java client <ip> <port number> 6 <authToken> <message_id> int fnID = Integer.parseInt(args[2]); String ip = args[0]; // args[0] int port = Integer.parseInt(args[1]); // args[1] String username = args[3]; // args[3] για 1 String recipient; // args[4] για 3 String body; // args[5] για 3 int message_id; // ορίζεται παρακάτω γιατί πρέπει να γίνει parsed int authToken = -1; // ήθελε αρχικοποίηση για λόγους debugging if (fnID != 1) authToken = Integer.parseInt(args[3]); // args[3] εκτός<SUF> // Establish connection to RMI registry try { // connect to the RMI registry Registry rmiRegistry = LocateRegistry.getRegistry(ip,port); // get reference for remote object MessengerInt stub = (MessengerInt) rmiRegistry.lookup("messenger"); switch(fnID) { case 1: // Create account if (!stub.isValidUsername(username)) System.out.println("Invalid Username"); else { int token = stub.createAccount(username); if (token == -1) // κωδικός για υπάρχον username System.out.println("Sorry, the user already exists"); else System.out.println(token); //όλα πήγαν καλά και επιστρέφεται το authToken } break; case 2: // Show accounts System.out.println(stub.showAccounts(authToken)); break; case 3: // Send message recipient = args[4]; // args[4] για 3 body = args[5]; // args[5] για 3 System.out.println(stub.sendMessage(authToken, recipient, body)); break; case 4: // Show inbox System.out.println(stub.showInbox(authToken)); break; case 5: // Read message message_id = Integer.parseInt(args[4]); // args[4] για fnID = 5, 6 System.out.println(stub.readMessage(authToken, message_id)); break; case 6: // Delete message message_id = Integer.parseInt(args[4]); // args[4] για fnID = 5, 6 System.out.println(stub.deleteMessage(authToken, message_id)); break; default: // code block } } catch (Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } } }
475_9
package api; import java.io.Serializable; /** * Abstract γενική κλάση χρήστη. */ public abstract class User implements Serializable { //βγάζει νόημα να είναι abstract γιατί δεν πρόκειται να δημιουργηθούν αντικείμενα User protected final String firstName; protected final String lastName; protected final String userName; protected String password; protected final String type; // "simpleUser" or "provider" /** * Κατασκευαστής της κλάσης User. Αρχικοποιεί το αντικείμενο του απλού χρήστη θέτοντας τα πεδία firstName, * lastName, username και password ανάλογα με τα ορίσματα που δίνονται. * @param firstName μικρό όνομα χρήστη * @param lastName επίθετο χρήστη * @param userName username χρήστη * @param password κωδικός χρήστη * @param type τύπος χρήστη */ public User(String firstName, String lastName, String userName, String password, String type) { this.userName = userName; this.password = password; this.type = type; this.firstName = firstName; this.lastName = lastName; } /** * Επιστρέφει το username του χρήστη. * @return username του χρήστη */ public String getUserName() { return userName; } /** * Επιστρέφει τον κωδικό του χρήστη. * @return κωδικός του χρήστη */ public String getPassword() { return password; } /** * Αλλάζει τον κωδικό του χρήστη για πιθανή μελλοντική υλοποίηση διαδικασίας αλλαγής κωδικού. * @param password νέος κωδικός */ public void setPassword(String password) { this.password = password; } /** * Επιστρέφει τον τύπο του χρήστη. * @return τύπος του χρήστη. */ public String getType() { return type; } /** * Επιστρέφει το μικρό όνομα του χρήστη * @return μικρό όνομα του χρήστη */ public String getFirstName() { return firstName; } /** * Επιστρέφει το επίθετο του χρήστη. * @return επίθετο του χρήστη */ public String getLastName() { return lastName; } /** * Ελέγχεται η ισότητα δύο αντικειμένων υποκλάσεων της User (αφού η ίδια η User είναι abstract). Αν δεν έχουν την * ίδια θέση μνήμης και ανήκουν και τα δύο σε υποκλάσεις της User τότε ελέγχεται η ισότητα των username καθώς είναι * μοναδικά. * @param o το αντικείμενο που θέλουμε να συγκρίνουμε με το this * @return true αν ισχύει η ισότητα των δύο αντικειμένων */ @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof User user)) return false; return getUserName().equals(user.getUserName()); } }
patiosga/myreviews
src/api/User.java
1,220
/** * Επιστρέφει το επίθετο του χρήστη. * @return επίθετο του χρήστη */
block_comment
el
package api; import java.io.Serializable; /** * Abstract γενική κλάση χρήστη. */ public abstract class User implements Serializable { //βγάζει νόημα να είναι abstract γιατί δεν πρόκειται να δημιουργηθούν αντικείμενα User protected final String firstName; protected final String lastName; protected final String userName; protected String password; protected final String type; // "simpleUser" or "provider" /** * Κατασκευαστής της κλάσης User. Αρχικοποιεί το αντικείμενο του απλού χρήστη θέτοντας τα πεδία firstName, * lastName, username και password ανάλογα με τα ορίσματα που δίνονται. * @param firstName μικρό όνομα χρήστη * @param lastName επίθετο χρήστη * @param userName username χρήστη * @param password κωδικός χρήστη * @param type τύπος χρήστη */ public User(String firstName, String lastName, String userName, String password, String type) { this.userName = userName; this.password = password; this.type = type; this.firstName = firstName; this.lastName = lastName; } /** * Επιστρέφει το username του χρήστη. * @return username του χρήστη */ public String getUserName() { return userName; } /** * Επιστρέφει τον κωδικό του χρήστη. * @return κωδικός του χρήστη */ public String getPassword() { return password; } /** * Αλλάζει τον κωδικό του χρήστη για πιθανή μελλοντική υλοποίηση διαδικασίας αλλαγής κωδικού. * @param password νέος κωδικός */ public void setPassword(String password) { this.password = password; } /** * Επιστρέφει τον τύπο του χρήστη. * @return τύπος του χρήστη. */ public String getType() { return type; } /** * Επιστρέφει το μικρό όνομα του χρήστη * @return μικρό όνομα του χρήστη */ public String getFirstName() { return firstName; } /** * Επιστρέφει το επίθετο<SUF>*/ public String getLastName() { return lastName; } /** * Ελέγχεται η ισότητα δύο αντικειμένων υποκλάσεων της User (αφού η ίδια η User είναι abstract). Αν δεν έχουν την * ίδια θέση μνήμης και ανήκουν και τα δύο σε υποκλάσεις της User τότε ελέγχεται η ισότητα των username καθώς είναι * μοναδικά. * @param o το αντικείμενο που θέλουμε να συγκρίνουμε με το this * @return true αν ισχύει η ισότητα των δύο αντικειμένων */ @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof User user)) return false; return getUserName().equals(user.getUserName()); } }
247_0
import java.util.ArrayList; import java.util.List; public class Login { //Για να γλιτωσουμε το database χρησιμοποιουμε ArrayList οπου θα εχει τα attributes των employees private List<Employee> employees; String position[] = new String[12]; public Login() { employees = new ArrayList<>(); // String position[] = new String[employees.size()]; //Customer Service employees.add(new Employee("Sarah", "111", "Customer Service", "[email protected]", 20, "female", 1)); employees.add(new Employee("Sam", "111", "Customer Service", "[email protected]", 20, "male", 2)); employees.add(new Employee("Judy", "111", "Customer Service", "[email protected]", 20, "female", 3)); employees.add(new Employee("Carine", "111", "Customer Service", "[email protected]", 20, "female", 4)); //Senior Customer Service employees.add(new Employee("Janet", "123", "Senior Customer Service", "[email protected]", 30, "female", 5)); //Financial Manager employees.add(new Employee("Alice", "234", "Financial Manager", "[email protected]", 40, "female", 6)); //Administration Dept. Manager employees.add(new Employee("Mike", "345", "Administration Dept. Manager", "[email protected]", 50, "male", 7)); //Production Manager employees.add(new Employee("Jack", "456", "Production Manager", "[email protected]", 40, "male", 8)); //Service Manager employees.add(new Employee("Natalie", "567", "Service Manager", "[email protected]", 30, "female", 9)); //HR employees.add(new Employee("Simon", "678", "HR", "[email protected]", 35, "male", 10)); } public Employee EmployeeLogin(String name, String password) { for(Employee employee : employees) { if(employee.getName().equals(name) && employee.getPassword().equals(password)) { System.out.println("You have logged in succesfully!"); return employee; } } return null; } public String[] position() { int i = 0; for(Employee employee : employees) { //System.out.println(employee.getPosition()); position[i] = employee.getPosition(); //System.out.println(position[i]); i++; } return position; } public List<Employee> getEmployee(){ return employees; } }
pavlitos/littleproject
Login.java
752
//Για να γλιτωσουμε το database χρησιμοποιουμε ArrayList οπου θα εχει τα attributes των employees
line_comment
el
import java.util.ArrayList; import java.util.List; public class Login { //Για να<SUF> private List<Employee> employees; String position[] = new String[12]; public Login() { employees = new ArrayList<>(); // String position[] = new String[employees.size()]; //Customer Service employees.add(new Employee("Sarah", "111", "Customer Service", "[email protected]", 20, "female", 1)); employees.add(new Employee("Sam", "111", "Customer Service", "[email protected]", 20, "male", 2)); employees.add(new Employee("Judy", "111", "Customer Service", "[email protected]", 20, "female", 3)); employees.add(new Employee("Carine", "111", "Customer Service", "[email protected]", 20, "female", 4)); //Senior Customer Service employees.add(new Employee("Janet", "123", "Senior Customer Service", "[email protected]", 30, "female", 5)); //Financial Manager employees.add(new Employee("Alice", "234", "Financial Manager", "[email protected]", 40, "female", 6)); //Administration Dept. Manager employees.add(new Employee("Mike", "345", "Administration Dept. Manager", "[email protected]", 50, "male", 7)); //Production Manager employees.add(new Employee("Jack", "456", "Production Manager", "[email protected]", 40, "male", 8)); //Service Manager employees.add(new Employee("Natalie", "567", "Service Manager", "[email protected]", 30, "female", 9)); //HR employees.add(new Employee("Simon", "678", "HR", "[email protected]", 35, "male", 10)); } public Employee EmployeeLogin(String name, String password) { for(Employee employee : employees) { if(employee.getName().equals(name) && employee.getPassword().equals(password)) { System.out.println("You have logged in succesfully!"); return employee; } } return null; } public String[] position() { int i = 0; for(Employee employee : employees) { //System.out.println(employee.getPosition()); position[i] = employee.getPosition(); //System.out.println(position[i]); i++; } return position; } public List<Employee> getEmployee(){ return employees; } }
6157_0
package com.unipi.CineTicketBooking.model; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.unipi.CineTicketBooking.model.secondary.BookingStatus; import jakarta.persistence.*; import java.time.LocalDate; import java.time.LocalDateTime; import jakarta.persistence.Id; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import lombok.AllArgsConstructor; import lombok.RequiredArgsConstructor; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; @Entity @Table(name = "bookings") @AllArgsConstructor public class Bookings { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne(targetEntity = Users.class) @OnDelete(action = OnDeleteAction.CASCADE) @JoinColumn(name = "users_id",referencedColumnName = "users_id",nullable = false) private Users users; @ManyToOne(targetEntity = Showtime.class) @OnDelete(action = OnDeleteAction.SET_NULL) @JoinColumn(name="showtime_id",referencedColumnName = "showtime_id",nullable = false) private Showtime showtime; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } private BookingStatus status; @Column private int seat; @Column private String firstName; @Column private String lastName; @Column private String telephone; @JsonFormat(shape=JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss[.SSS][.SS][.S]") private LocalDateTime bookingTime; // Εδώ περιέχεται η ώρα της κράτησης με ημερομηνία και ώρα public Bookings(Users users, Showtime showtime, LocalDateTime bookingTime,int seat,BookingStatus status, String firstName, String lastName, String telephone) { this.id = id; this.users = users; this.showtime = showtime; this.bookingTime = bookingTime; this.seat=seat; this.firstName=firstName; this.lastName=lastName; this.telephone=telephone; this.status=status; } public Bookings() { } public Long getId() { return id; } public Users getUsers() { return users; } public Showtime getShowtime() { return showtime; } public LocalDateTime getBookingTime() { return bookingTime; } public void setId(Long id) { this.id = id; } public void setUsers(Users users) { this.users = users; } public void setShowtime(Showtime showtime) { this.showtime = showtime; } public void setBookingTime(LocalDateTime bookingTime) { this.bookingTime = bookingTime; } public int getSeat() { return seat; } public void setSeat(int seat) { this.seat = seat; } public BookingStatus getStatus() { return status; } public void setStatus(BookingStatus status) { this.status = status; } }
peroze/CineTicketBooking
src/main/java/com/unipi/CineTicketBooking/model/Bookings.java
858
// Εδώ περιέχεται η ώρα της κράτησης με ημερομηνία και ώρα
line_comment
el
package com.unipi.CineTicketBooking.model; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.unipi.CineTicketBooking.model.secondary.BookingStatus; import jakarta.persistence.*; import java.time.LocalDate; import java.time.LocalDateTime; import jakarta.persistence.Id; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import lombok.AllArgsConstructor; import lombok.RequiredArgsConstructor; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; @Entity @Table(name = "bookings") @AllArgsConstructor public class Bookings { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne(targetEntity = Users.class) @OnDelete(action = OnDeleteAction.CASCADE) @JoinColumn(name = "users_id",referencedColumnName = "users_id",nullable = false) private Users users; @ManyToOne(targetEntity = Showtime.class) @OnDelete(action = OnDeleteAction.SET_NULL) @JoinColumn(name="showtime_id",referencedColumnName = "showtime_id",nullable = false) private Showtime showtime; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } private BookingStatus status; @Column private int seat; @Column private String firstName; @Column private String lastName; @Column private String telephone; @JsonFormat(shape=JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss[.SSS][.SS][.S]") private LocalDateTime bookingTime; // Εδώ περιέχεται<SUF> public Bookings(Users users, Showtime showtime, LocalDateTime bookingTime,int seat,BookingStatus status, String firstName, String lastName, String telephone) { this.id = id; this.users = users; this.showtime = showtime; this.bookingTime = bookingTime; this.seat=seat; this.firstName=firstName; this.lastName=lastName; this.telephone=telephone; this.status=status; } public Bookings() { } public Long getId() { return id; } public Users getUsers() { return users; } public Showtime getShowtime() { return showtime; } public LocalDateTime getBookingTime() { return bookingTime; } public void setId(Long id) { this.id = id; } public void setUsers(Users users) { this.users = users; } public void setShowtime(Showtime showtime) { this.showtime = showtime; } public void setBookingTime(LocalDateTime bookingTime) { this.bookingTime = bookingTime; } public int getSeat() { return seat; } public void setSeat(int seat) { this.seat = seat; } public BookingStatus getStatus() { return status; } public void setStatus(BookingStatus status) { this.status = status; } }
40269_3
package Tests; import main.java.spatialtree.Record; import main.java.spatialtree.*; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class KNNBulk { public static void main(String[] args) throws IOException { ArrayList<Double> centerPoint = new ArrayList<>(); // ArrayList with the coordinates of an approximate center point centerPoint.add(33.0449947); // Coordinate of second dimension centerPoint.add(34.701862); // Coordinate of first dimension //205. 60170093,Μέσα Γειτονιά,34.701862,33.0449947 for map.osm System.out.println("Initializing files:"); List<Record> records = DataFileManagerNoName.loadDataFromFile("map.osm"); helper.CreateDataFile(records,2, true); helper.CreateIndexFile(2,false); System.out.println("creating R*-tree"); BulkLoadingRStarTree rStarTree = new BulkLoadingRStarTree(true); //QUERY ArrayList<Bounds> queryBounds = new ArrayList<>(); queryBounds.add(new Bounds(centerPoint.get(0) , centerPoint.get(0))); queryBounds.add(new Bounds(centerPoint.get(1), centerPoint.get(1))); int k=4; System.out.print("Starting KNN query: "); long startKNNTime = System.nanoTime(); ArrayList<LeafEntry> queryRecords = rStarTree.getNearestNeighbours(centerPoint, k); long stopKNNTime = System.nanoTime(); System.out.print("range query Done "); System.out.println("Entires found in the given region: " + queryRecords.size()); System.out.println("writing them to outputKNNBulkQuery.csv "); try (FileWriter csvWriter = new FileWriter("outputKNNBulkQuery.csv")) { // Write the CSV header csvWriter.append("ID,Name,Latitude,Longitude \n"); // Loop through records and write each to the file int counter=0; for (LeafEntry leafRecord : queryRecords) { counter++; // Assuming findRecord() returns a comma-separated string "id,name,lat,lon" csvWriter.append(counter + ". " + leafRecord.findRecordWithoutBlockId().toString()); csvWriter.append("\n"); // New line after each record } } catch (IOException e) { System.err.println("Error writing to CSV file: " + e.getMessage()); } System.out.println("Time taken: " + (double) (stopKNNTime - startKNNTime) / 1_000_000_000.0 + " seconds"); } }
pompos02/spatial_access
src/Tests/KNNBulk.java
677
//205. 60170093,Μέσα Γειτονιά,34.701862,33.0449947 for map.osm
line_comment
el
package Tests; import main.java.spatialtree.Record; import main.java.spatialtree.*; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class KNNBulk { public static void main(String[] args) throws IOException { ArrayList<Double> centerPoint = new ArrayList<>(); // ArrayList with the coordinates of an approximate center point centerPoint.add(33.0449947); // Coordinate of second dimension centerPoint.add(34.701862); // Coordinate of first dimension //205. 60170093,Μέσα<SUF> System.out.println("Initializing files:"); List<Record> records = DataFileManagerNoName.loadDataFromFile("map.osm"); helper.CreateDataFile(records,2, true); helper.CreateIndexFile(2,false); System.out.println("creating R*-tree"); BulkLoadingRStarTree rStarTree = new BulkLoadingRStarTree(true); //QUERY ArrayList<Bounds> queryBounds = new ArrayList<>(); queryBounds.add(new Bounds(centerPoint.get(0) , centerPoint.get(0))); queryBounds.add(new Bounds(centerPoint.get(1), centerPoint.get(1))); int k=4; System.out.print("Starting KNN query: "); long startKNNTime = System.nanoTime(); ArrayList<LeafEntry> queryRecords = rStarTree.getNearestNeighbours(centerPoint, k); long stopKNNTime = System.nanoTime(); System.out.print("range query Done "); System.out.println("Entires found in the given region: " + queryRecords.size()); System.out.println("writing them to outputKNNBulkQuery.csv "); try (FileWriter csvWriter = new FileWriter("outputKNNBulkQuery.csv")) { // Write the CSV header csvWriter.append("ID,Name,Latitude,Longitude \n"); // Loop through records and write each to the file int counter=0; for (LeafEntry leafRecord : queryRecords) { counter++; // Assuming findRecord() returns a comma-separated string "id,name,lat,lon" csvWriter.append(counter + ". " + leafRecord.findRecordWithoutBlockId().toString()); csvWriter.append("\n"); // New line after each record } } catch (IOException e) { System.err.println("Error writing to CSV file: " + e.getMessage()); } System.out.println("Time taken: " + (double) (stopKNNTime - startKNNTime) / 1_000_000_000.0 + " seconds"); } }
4846_5
package com.example.energychaser; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.CountDownTimer; import android.view.View; import android.widget.Button; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; public class single_player_activity extends AppCompatActivity { SeekBar seekBarsingle; TextView textViewsingle; private Integer countsec = 20; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_single_player); seekBarsingle = (SeekBar)findViewById(R.id.seekBarSingle); textViewsingle = (TextView)findViewById(R.id.textViewSingle); seekBarsingle.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int sec, boolean b) { // Όσο τραβάμε την seekbar αυξάνουμε ή μειώνουμε τον χρόνο παιχνιδιού ανα 5 δευτερόλεπτα sec = sec / 5; sec = sec * 5; // Εδω εμφανίζονται τα δευτερόλεπτα στην textViewSingle textViewsingle.setText("Δευτερόλεπτα :" + sec); // Περνάμε τα δευτερόλεπτα σε μια μεταβλητή. countsec = sec; } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); Button camerascan = (Button) findViewById(R.id.camerascan);//single mode camerascan.setOnClickListener(new View.OnClickListener() { // Με το πάτημα του κουμπιού μετατρέπουμε τα δευτερόλεπτα σε χιλιοστά του δευτερολέπτου και στέλνουμε την // τιμή με intent.PutExtra στην επόμενη κλάση, για να αρχίσει η αντιστροφη μέτρηση, παράλληλα //προωθείτε και όλη η δραστηριότητα στην activity_scan_list, όπου αρχίζει και το ψάξιμο. @Override public void onClick(View v) { openSingleActivity(countsec); } }); } public void openSingleActivity(int value) { Integer countime = value; //Method To Pass The Seconds and redirect if(countime != null || countime != 0 ){countime = value*1000;} else{countime=20000;} Intent intent = new Intent(single_player_activity.this, activity_scan_list.class); intent.putExtra("MY_INTEGER", countime); startActivity(intent); } }
pos3id0nas/Energy_Chaser_App
app/src/main/java/com/example/energychaser/single_player_activity.java
882
//προωθείτε και όλη η δραστηριότητα στην activity_scan_list, όπου αρχίζει και το ψάξιμο.
line_comment
el
package com.example.energychaser; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.CountDownTimer; import android.view.View; import android.widget.Button; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; public class single_player_activity extends AppCompatActivity { SeekBar seekBarsingle; TextView textViewsingle; private Integer countsec = 20; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_single_player); seekBarsingle = (SeekBar)findViewById(R.id.seekBarSingle); textViewsingle = (TextView)findViewById(R.id.textViewSingle); seekBarsingle.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int sec, boolean b) { // Όσο τραβάμε την seekbar αυξάνουμε ή μειώνουμε τον χρόνο παιχνιδιού ανα 5 δευτερόλεπτα sec = sec / 5; sec = sec * 5; // Εδω εμφανίζονται τα δευτερόλεπτα στην textViewSingle textViewsingle.setText("Δευτερόλεπτα :" + sec); // Περνάμε τα δευτερόλεπτα σε μια μεταβλητή. countsec = sec; } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); Button camerascan = (Button) findViewById(R.id.camerascan);//single mode camerascan.setOnClickListener(new View.OnClickListener() { // Με το πάτημα του κουμπιού μετατρέπουμε τα δευτερόλεπτα σε χιλιοστά του δευτερολέπτου και στέλνουμε την // τιμή με intent.PutExtra στην επόμενη κλάση, για να αρχίσει η αντιστροφη μέτρηση, παράλληλα //προωθείτε και<SUF> @Override public void onClick(View v) { openSingleActivity(countsec); } }); } public void openSingleActivity(int value) { Integer countime = value; //Method To Pass The Seconds and redirect if(countime != null || countime != 0 ){countime = value*1000;} else{countime=20000;} Intent intent = new Intent(single_player_activity.this, activity_scan_list.class); intent.putExtra("MY_INTEGER", countime); startActivity(intent); } }
498_0
import java.util.*; public class tickets { public String comment; public User user; public String state; public ArrayList<tickets> ticketsList; public tickets(User user, String comment, String state) { this.user=user; this.comment=comment; this.state=state; this.ticketsList=new ArrayList<tickets>(); } public void set_ticketsList(tickets tickets) throws FlybyException{ if(this.ticketsList.contains(tickets)){ //ελέγχω αν το αντικελιμενο που θέλω να προσθέσω υπάρχει ήδη στη λίστα throw new FlybyException("Item already exists"); //χρησιμοποιώ κλάση εξαίρεσης αν το αντικείμενο υπα΄ρχει ήδη στη λίστα } else{ //αν δεν υπάρχει το προσθέτω στη λίστα this.ticketsList.add(tickets); } } public void print_ticket(tickets ticket){ System.out.print("Ticket comment: "+ ticket.comment+"\n"); System.out.print("user reporting this post: "); this.user.print_user(ticket.user); System.out.print("State of ticket: "+ticket.state+"\n"); } }
poulcheria/FlyBy
backend/tickets.java
380
//ελέγχω αν το αντικελιμενο που θέλω να προσθέσω υπάρχει ήδη στη λίστα
line_comment
el
import java.util.*; public class tickets { public String comment; public User user; public String state; public ArrayList<tickets> ticketsList; public tickets(User user, String comment, String state) { this.user=user; this.comment=comment; this.state=state; this.ticketsList=new ArrayList<tickets>(); } public void set_ticketsList(tickets tickets) throws FlybyException{ if(this.ticketsList.contains(tickets)){ //ελέγχω αν<SUF> throw new FlybyException("Item already exists"); //χρησιμοποιώ κλάση εξαίρεσης αν το αντικείμενο υπα΄ρχει ήδη στη λίστα } else{ //αν δεν υπάρχει το προσθέτω στη λίστα this.ticketsList.add(tickets); } } public void print_ticket(tickets ticket){ System.out.print("Ticket comment: "+ ticket.comment+"\n"); System.out.print("user reporting this post: "); this.user.print_user(ticket.user); System.out.print("State of ticket: "+ticket.state+"\n"); } }
13417_12
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; public class RandomizedBST implements TaxEvasionInterface { private int N; private class TreeNode { LargeDepositor item; TreeNode left; // pointer to left subtree TreeNode right; // pointer to right subtree int N; TreeNode(LargeDepositor x) { item = x; } } private TreeNode root; // ρίζα στο δέντρο private TreeNode rotR(TreeNode h) { TreeNode x = h.left; h.left = x.right; x.right = h; return x; } private TreeNode rotL(TreeNode h) { TreeNode x = h.right; h.right = x.left; x.left = h; return x; } private TreeNode insertT(TreeNode h, LargeDepositor x) { if (h == null) return new TreeNode(x); if (x.key() < h.item.key()) { h.left = insertT(h.left, x); h = rotR(h); } else { h.right = insertT(h.right, x); h = rotL(h); } return h; } private TreeNode insertAsRoot(TreeNode h, LargeDepositor x) { if (h == null) { return new TreeNode(x); } if (Math.random() * (h.N + 1) < 1.0) { return insertT(h, x); } if (x.key() < h.item.key()) { h.left = insertAsRoot(h.left, x); } else { h.right = insertAsRoot(h.right, x); } return h; } @Override public void insert(LargeDepositor item) { TreeNode curr = foundByAFM(item.getAFM()); if (curr != null) { System.out.println("LargeDepositor with this AFM already present in BST."); } else { root = insertAsRoot(root, item); ++N; } } @Override public void load(String filename) { try (BufferedReader reader = new BufferedReader(new FileReader(filename))) { String line; while ((line = reader.readLine()) != null) { String[] splitted = line.split("\\s+"); insert(new LargeDepositor(Integer.parseInt(splitted[0]), splitted[1], splitted[2], Double.parseDouble(splitted[3]), Double.parseDouble(splitted[4]))); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public void updateSavings(int AFM, double savings) { // Traverse the tree --> 1) if you find the given AFM, then add the savings to // that account // 2) otherwise print a message saying you couldn't find it TreeNode curr = foundByAFM(AFM); if (curr != null) { curr.item.setSavings(savings); } else { System.out.println("Requested AFM not found."); } } @Override public LargeDepositor searchByAFM(int AFM) { // Traverse the tree --> 1) if you find the given AFM, then print the holders // information // 2) otherwise print a message saying you couldn't find it TreeNode curr = foundByAFM(AFM); if (curr != null) { System.out.println(curr.item); return curr.item; } else { System.out.println("Requested AFM not found."); return null; } } private void traverseAndBuild(TreeNode node, List ls) { if (node == null) return; if (node.item.getLastName().equals(ls.lastname)) ls.insertAtFront(node.item); traverseAndBuild(node.left, ls); traverseAndBuild(node.right, ls); } @Override public List searchByLastName(String last_name) { List res = new List(); res.lastname = last_name; traverseAndBuild(root, res); if (0 < res.N && res.N <= 5) { System.out.println(res); } return res; } @Override public void remove(int AFM) { root = removeNode(root, AFM); } private double traverseAndSum(TreeNode node) { if (node == null) return 0; return node.item.getSavings() + traverseAndSum(node.left) + traverseAndSum(node.right); } @Override public double getMeanSavings() { return traverseAndSum(root) / N; } private void traverseAndRank(TreeNode node, PQ pq) { if (node == null) return; if (pq.size() < pq.capacity) { pq.insert(node.item); } else if (pq.min().compareTo(node.item) == -1) { pq.getmin(); pq.insert(node.item); } traverseAndRank(node.left, pq); traverseAndRank(node.right, pq); } @Override public void printΤopLargeDepositors(int k) { PQ pq = new PQ(k); List ls = new List(); System.out.println(pq.capacity); traverseAndRank(root, pq); while (pq.size() > 0) ls.insertAtFront(pq.getmin()); while (ls.N > 0) System.out.println(ls.removeFromFront()); } private void printInorder(TreeNode node) { if (node == null) return; printInorder(node.left); System.out.print(node.item + " "); printInorder(node.right); } @Override public void printByAFM() { printInorder(root); } /* * Helpers */ public TreeNode foundByAFM(int AFM) { TreeNode curr = root; while (curr != null) { // Found it if (curr.item.key() == AFM) { return curr; } // Didn't else { // If it's less then go to the right sub-tree if (curr.item.key() < AFM) { curr = curr.right; } // If it's greater then go to the left sub-tree else { curr = curr.left; } } } // If you haven't returned that means that you didn't find the AFM return null; } public TreeNode joinNode(TreeNode a, TreeNode b) { // κλειδιά στο a ≤ κλειδιά στο b if (a == null) { return b; } if (b == null) { return a; } int N = a.N + b.N; if (Math.random() * N < 1.0 * a.N) { a.right = joinNode(a.right, b); return a; } // βάζουμε το b κάτω από το a else { b.left = joinNode(a, b.left); return b; } } public TreeNode removeNode(TreeNode h, int AFM) { if (h == null) return null; int w = h.item.key(); if (AFM < w) { h.left = removeNode(h.left, AFM); } else if (w < AFM) { h.right = removeNode(h.right, AFM); } else { h = joinNode(h.left, h.right); } return h; } public static void main(String[] args) { RandomizedBST bst = new RandomizedBST(); Scanner sc = new Scanner(System.in); while (true) { System.out.print( "Options:\n0. Exit\n1. Insert suspect\n2. Remove suspect\n3. Load data from file\n4. Update suspect's savings\n5. Find suspect by AFM\n6. Find suspect by last name\n7. Calculate mean savings\n8. Print top k depositors\n9. Print all data\nYour choice: "); switch (sc.nextInt()) { case 0: System.exit(0); case 1: LargeDepositor sus = new LargeDepositor(); System.out.print("Enter AFM: "); sus.setAFM(sc.nextInt()); System.out.println(); System.out.print("Enter first name: "); sus.setFirstName(sc.next()); System.out.println(); System.out.print("Enter last name: "); sus.setLastName(sc.next()); System.out.println(); System.out.print("Enter savings: "); sus.setSavings(sc.nextInt()); System.out.println(); System.out.print("Enter taxed income: "); sus.setTaxedIncome(sc.nextInt()); System.out.println(); bst.insert(sus); break; case 2: System.out.print("Enter AFM: "); bst.remove(sc.nextInt()); System.out.println(); break; case 3: System.out.print("Enter filename: "); bst.load(sc.next()); System.out.println(); break; case 4: System.out.print("Enter AFM: "); int AFM = sc.nextInt(); System.out.println(); System.out.print("Enter savings: "); System.out.println(); int savings = sc.nextInt(); bst.updateSavings(AFM, savings); break; case 5: System.out.print("Enter AFM: "); bst.searchByAFM(sc.nextInt()); System.out.println(); break; case 6: System.out.print("Enter last name: "); bst.searchByLastName(sc.next()); System.out.println(); break; case 7: System.out.println(bst.getMeanSavings() + " EUR"); break; case 8: System.out.print("Enter k: "); bst.printΤopLargeDepositors(sc.nextInt()); System.out.println(); break; case 9: bst.printByAFM(); break; default: break; } } } }
ppdms/ds-assignments
3/RandomizedBST.java
2,506
// βάζουμε το b κάτω από το a
line_comment
el
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; public class RandomizedBST implements TaxEvasionInterface { private int N; private class TreeNode { LargeDepositor item; TreeNode left; // pointer to left subtree TreeNode right; // pointer to right subtree int N; TreeNode(LargeDepositor x) { item = x; } } private TreeNode root; // ρίζα στο δέντρο private TreeNode rotR(TreeNode h) { TreeNode x = h.left; h.left = x.right; x.right = h; return x; } private TreeNode rotL(TreeNode h) { TreeNode x = h.right; h.right = x.left; x.left = h; return x; } private TreeNode insertT(TreeNode h, LargeDepositor x) { if (h == null) return new TreeNode(x); if (x.key() < h.item.key()) { h.left = insertT(h.left, x); h = rotR(h); } else { h.right = insertT(h.right, x); h = rotL(h); } return h; } private TreeNode insertAsRoot(TreeNode h, LargeDepositor x) { if (h == null) { return new TreeNode(x); } if (Math.random() * (h.N + 1) < 1.0) { return insertT(h, x); } if (x.key() < h.item.key()) { h.left = insertAsRoot(h.left, x); } else { h.right = insertAsRoot(h.right, x); } return h; } @Override public void insert(LargeDepositor item) { TreeNode curr = foundByAFM(item.getAFM()); if (curr != null) { System.out.println("LargeDepositor with this AFM already present in BST."); } else { root = insertAsRoot(root, item); ++N; } } @Override public void load(String filename) { try (BufferedReader reader = new BufferedReader(new FileReader(filename))) { String line; while ((line = reader.readLine()) != null) { String[] splitted = line.split("\\s+"); insert(new LargeDepositor(Integer.parseInt(splitted[0]), splitted[1], splitted[2], Double.parseDouble(splitted[3]), Double.parseDouble(splitted[4]))); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public void updateSavings(int AFM, double savings) { // Traverse the tree --> 1) if you find the given AFM, then add the savings to // that account // 2) otherwise print a message saying you couldn't find it TreeNode curr = foundByAFM(AFM); if (curr != null) { curr.item.setSavings(savings); } else { System.out.println("Requested AFM not found."); } } @Override public LargeDepositor searchByAFM(int AFM) { // Traverse the tree --> 1) if you find the given AFM, then print the holders // information // 2) otherwise print a message saying you couldn't find it TreeNode curr = foundByAFM(AFM); if (curr != null) { System.out.println(curr.item); return curr.item; } else { System.out.println("Requested AFM not found."); return null; } } private void traverseAndBuild(TreeNode node, List ls) { if (node == null) return; if (node.item.getLastName().equals(ls.lastname)) ls.insertAtFront(node.item); traverseAndBuild(node.left, ls); traverseAndBuild(node.right, ls); } @Override public List searchByLastName(String last_name) { List res = new List(); res.lastname = last_name; traverseAndBuild(root, res); if (0 < res.N && res.N <= 5) { System.out.println(res); } return res; } @Override public void remove(int AFM) { root = removeNode(root, AFM); } private double traverseAndSum(TreeNode node) { if (node == null) return 0; return node.item.getSavings() + traverseAndSum(node.left) + traverseAndSum(node.right); } @Override public double getMeanSavings() { return traverseAndSum(root) / N; } private void traverseAndRank(TreeNode node, PQ pq) { if (node == null) return; if (pq.size() < pq.capacity) { pq.insert(node.item); } else if (pq.min().compareTo(node.item) == -1) { pq.getmin(); pq.insert(node.item); } traverseAndRank(node.left, pq); traverseAndRank(node.right, pq); } @Override public void printΤopLargeDepositors(int k) { PQ pq = new PQ(k); List ls = new List(); System.out.println(pq.capacity); traverseAndRank(root, pq); while (pq.size() > 0) ls.insertAtFront(pq.getmin()); while (ls.N > 0) System.out.println(ls.removeFromFront()); } private void printInorder(TreeNode node) { if (node == null) return; printInorder(node.left); System.out.print(node.item + " "); printInorder(node.right); } @Override public void printByAFM() { printInorder(root); } /* * Helpers */ public TreeNode foundByAFM(int AFM) { TreeNode curr = root; while (curr != null) { // Found it if (curr.item.key() == AFM) { return curr; } // Didn't else { // If it's less then go to the right sub-tree if (curr.item.key() < AFM) { curr = curr.right; } // If it's greater then go to the left sub-tree else { curr = curr.left; } } } // If you haven't returned that means that you didn't find the AFM return null; } public TreeNode joinNode(TreeNode a, TreeNode b) { // κλειδιά στο a ≤ κλειδιά στο b if (a == null) { return b; } if (b == null) { return a; } int N = a.N + b.N; if (Math.random() * N < 1.0 * a.N) { a.right = joinNode(a.right, b); return a; } // βάζουμε το<SUF> else { b.left = joinNode(a, b.left); return b; } } public TreeNode removeNode(TreeNode h, int AFM) { if (h == null) return null; int w = h.item.key(); if (AFM < w) { h.left = removeNode(h.left, AFM); } else if (w < AFM) { h.right = removeNode(h.right, AFM); } else { h = joinNode(h.left, h.right); } return h; } public static void main(String[] args) { RandomizedBST bst = new RandomizedBST(); Scanner sc = new Scanner(System.in); while (true) { System.out.print( "Options:\n0. Exit\n1. Insert suspect\n2. Remove suspect\n3. Load data from file\n4. Update suspect's savings\n5. Find suspect by AFM\n6. Find suspect by last name\n7. Calculate mean savings\n8. Print top k depositors\n9. Print all data\nYour choice: "); switch (sc.nextInt()) { case 0: System.exit(0); case 1: LargeDepositor sus = new LargeDepositor(); System.out.print("Enter AFM: "); sus.setAFM(sc.nextInt()); System.out.println(); System.out.print("Enter first name: "); sus.setFirstName(sc.next()); System.out.println(); System.out.print("Enter last name: "); sus.setLastName(sc.next()); System.out.println(); System.out.print("Enter savings: "); sus.setSavings(sc.nextInt()); System.out.println(); System.out.print("Enter taxed income: "); sus.setTaxedIncome(sc.nextInt()); System.out.println(); bst.insert(sus); break; case 2: System.out.print("Enter AFM: "); bst.remove(sc.nextInt()); System.out.println(); break; case 3: System.out.print("Enter filename: "); bst.load(sc.next()); System.out.println(); break; case 4: System.out.print("Enter AFM: "); int AFM = sc.nextInt(); System.out.println(); System.out.print("Enter savings: "); System.out.println(); int savings = sc.nextInt(); bst.updateSavings(AFM, savings); break; case 5: System.out.print("Enter AFM: "); bst.searchByAFM(sc.nextInt()); System.out.println(); break; case 6: System.out.print("Enter last name: "); bst.searchByLastName(sc.next()); System.out.println(); break; case 7: System.out.println(bst.getMeanSavings() + " EUR"); break; case 8: System.out.print("Enter k: "); bst.printΤopLargeDepositors(sc.nextInt()); System.out.println(); break; case 9: bst.printByAFM(); break; default: break; } } } }
9720_14
package memory_game; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import static java.lang.Thread.State.NEW; import static java.lang.Thread.State.RUNNABLE; import static java.lang.Thread.State.TERMINATED; import static java.lang.Thread.State.WAITING; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.Timer; import javax.swing.border.Border; /** * * @author Jay */ public class Player_vs_AI extends JFrame { JPanel panel2 = new JPanel (new GridLayout(4,6,7,7)); JPanel panel3 = new JPanel(new FlowLayout()); Thread t1; private int count; private int count_2; private int k; private int i; private int j=1; private JTextField text; private JLabel label; // private int count = 0; private Button_Cards selectedCard; private Button_Cards c1; private Button_Cards c2; private Timer timer; // private ArrayList<JButton> buttons; private ArrayList<Button_Cards> cards; private ArrayList<Integer> IDs; private HashMap<Integer, String> hs = new HashMap<Integer, String>(); private ArrayList<Integer> ID; JLabel label2 ; JRadioButton AI = new JRadioButton("AI"); JRadioButton Human = new JRadioButton("Human"); public void NumOfPlayers() { JPanel panel = new JPanel(); panel.setLayout(new FlowLayout()); JLabel label = new JLabel("Give number of players: "); //label.setBounds(200, 50, 300, 50); text = new JTextField(4); //text.setBounds(350, 65, 60, 25); panel.add(label); panel.add(text); label2 = new JLabel("Player 2 :"); label2.setVisible(false); AI.setVisible(false); Human.setVisible(false); JButton b = new JButton("Start game"); b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { panel.setVisible(false); Start(k); } }); panel.add(label2); panel.add(AI); panel.add(Human); panel.add(b); text.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(text.getText().equals("2")) { //label2 = new JLabel("Player 2 :"); label2.setVisible(true); //AI = new JRadioButton("AI"); //Human = new JRadioButton("Human"); AI.setVisible(true); Human.setVisible(true); ButtonGroup group = new ButtonGroup(); group.add(AI); group.add(Human); k = Converter(text.getText()); } } }); /*if(AI.isSelected()) { t1 = new Thread(new AI("Player 2", cards)); }*/ this.add(panel); } public int Converter(String string) { if(string.equals("2")) { return 2; }else if(string.equals("3")) { return 3; }else if(string.equals("4")) { return 4; } return 1; } public void setLabel() { int i = Converter(text.getText()); if(j<i && label.getText().equals("Player 1")) { j++; label.setText("Player "+j); }else if(j<i && label.getText().equals("Player 2")) { j++; label.setText("Player "+j); }else if(j<i && label.getText().equals("Player 3")) { j++; label.setText("Player "+j); }else if(j==i && label.getText().equals("Player "+j)) { j=1; label.setText("Player "+j); } } public void Start(int k) { panel2.setSize(300,500); this.setLayout(new BorderLayout()); panel3.setSize(100, 500); label = new JLabel("Player 1"); panel3.add(label); Border compound = BorderFactory.createCompoundBorder(BorderFactory.createRaisedBevelBorder(), BorderFactory.createLoweredBevelBorder()); panel3.setBorder(compound); //panel2.setBorder(compound); cards = new ArrayList<Button_Cards>(); ID = new ArrayList<Integer>(); hs = new HashMap<Integer, String>(); hs.put(0, "bob.png"); hs.put(1, "carl.jpg"); hs.put(2, "dog.jpg"); hs.put(3, "dude.jpg"); hs.put(4, "fat.jpg"); hs.put(5, "hood.jpg"); hs.put(6, "pokerFace.jpg"); hs.put(7, "prettyOne.jpg"); hs.put(8, "sad_Lary.jpg"); hs.put(9, "stickMan.jpg"); hs.put(10, "skil.jpg"); hs.put(11, "tsour.jpg"); for (int j =0;j<12; j++) { ID.add(j); ID.add(j); } Collections.shuffle(ID); ImageIcon icon ; icon = new ImageIcon(getClass().getResource("cardBack2.jpg")); for (int i : ID) { Button_Cards c = new Button_Cards(); c.setId(i); c.setIcon(icon); c.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { selectedCard = c ; c.setHasBeenSelected(); //IDs.add(c.getId()); TurnCard(); } }); cards.add(c); } timer = new Timer(1000, new ActionListener() { public void actionPerformed(ActionEvent ae) { Check(); } }); timer.setRepeats(false); for (Button_Cards c : cards) { panel2.add(c); } //t1 = new Thread(new AI_Elephant("Player 2", cards)); this.add(panel3,BorderLayout.NORTH); this.add(panel2, BorderLayout.CENTER); } public void TurnCard() { if (c1 == null && c2 == null){ c1 = selectedCard; //ImageIcon c1.setIcon(new ImageIcon(getClass().getResource(hs.get(c1.getId())))); } if (c1 != null && c1 != selectedCard && c2 == null){ c2 = selectedCard; c2.setIcon(new ImageIcon(getClass().getResource(hs.get(c2.getId())))); count++; timer.start(); } } /*synchronized void StartWait(Thread t) { try { while(true) t.wait(); } catch (InterruptedException ex) { Logger.getLogger(Player_vs_AI.class.getName()).log(Level.SEVERE, null, ex); } }*/ // @SuppressWarnings("empty-statement") public void Check() { if (c1.getId() == c2.getId()) { c1.setEnabled(false); c2.setEnabled(false); c1.setMatched(true); c2.setMatched(true); if(label.getText().equals("Player 2") && t1.getState()==TERMINATED) { t1 = new Thread(new AI_Elephant("Player 2", cards)); t1.start(); } if (this.isGameWon()) { JOptionPane.showMessageDialog(this, "Great! Game is over in " + count + " moves!"); System.exit(0); } } else { c1.setIcon(new ImageIcon(getClass().getResource("cardBack2.jpg"))); c2.setIcon(new ImageIcon(getClass().getResource("cardBack2.jpg"))); setLabel(); if(label.getText().equals("Player 2")) { t1=new Thread(new AI_Elephant("Player 2", cards)); t1.start(); } } c1 = null; c2 = null; } public void ai() { Random random = new Random(); do { count=0; i=random.nextInt(12); for(Button_Cards c : cards) { // System.out.println("εξω απο την if "+ i + " το id της καρτας: " +c.getId()); if(c.getId()==i && !c.getMatched()) { // System.out.println("το id της πρωτης: "+c.getId()); // System.out.println("πρωτη καρτα"); selectedCard=c; count++; c.doClick(); break; } } }while(count==0); // int k=random.nextInt(13); do { count_2=0; k=random.nextInt(12); for(Button_Cards b : cards) { // System.out.println(i + " " + k + " το id της καρτας: " +b.getId()); if(b.getId()==k && b.getMatched()==false && b!=selectedCard) { // System.out.println("μεσα στην if "+i + " " + k +" το id της δευτερης: "+b.getId()); // System.out.println("δευτερη καρτα"); count_2++; b.doClick(); break; } } }while(count_2==0); } public boolean isGameWon() { for(Button_Cards c: this.cards) { if (c.getMatched() == false) { return false; } } return true; } }
propol/Memory_Game
src/memory_game/Player_vs_AI.java
2,616
// System.out.println("μεσα στην if "+i + " " + k +" το id της δευτερης: "+b.getId());
line_comment
el
package memory_game; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import static java.lang.Thread.State.NEW; import static java.lang.Thread.State.RUNNABLE; import static java.lang.Thread.State.TERMINATED; import static java.lang.Thread.State.WAITING; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.Timer; import javax.swing.border.Border; /** * * @author Jay */ public class Player_vs_AI extends JFrame { JPanel panel2 = new JPanel (new GridLayout(4,6,7,7)); JPanel panel3 = new JPanel(new FlowLayout()); Thread t1; private int count; private int count_2; private int k; private int i; private int j=1; private JTextField text; private JLabel label; // private int count = 0; private Button_Cards selectedCard; private Button_Cards c1; private Button_Cards c2; private Timer timer; // private ArrayList<JButton> buttons; private ArrayList<Button_Cards> cards; private ArrayList<Integer> IDs; private HashMap<Integer, String> hs = new HashMap<Integer, String>(); private ArrayList<Integer> ID; JLabel label2 ; JRadioButton AI = new JRadioButton("AI"); JRadioButton Human = new JRadioButton("Human"); public void NumOfPlayers() { JPanel panel = new JPanel(); panel.setLayout(new FlowLayout()); JLabel label = new JLabel("Give number of players: "); //label.setBounds(200, 50, 300, 50); text = new JTextField(4); //text.setBounds(350, 65, 60, 25); panel.add(label); panel.add(text); label2 = new JLabel("Player 2 :"); label2.setVisible(false); AI.setVisible(false); Human.setVisible(false); JButton b = new JButton("Start game"); b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { panel.setVisible(false); Start(k); } }); panel.add(label2); panel.add(AI); panel.add(Human); panel.add(b); text.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(text.getText().equals("2")) { //label2 = new JLabel("Player 2 :"); label2.setVisible(true); //AI = new JRadioButton("AI"); //Human = new JRadioButton("Human"); AI.setVisible(true); Human.setVisible(true); ButtonGroup group = new ButtonGroup(); group.add(AI); group.add(Human); k = Converter(text.getText()); } } }); /*if(AI.isSelected()) { t1 = new Thread(new AI("Player 2", cards)); }*/ this.add(panel); } public int Converter(String string) { if(string.equals("2")) { return 2; }else if(string.equals("3")) { return 3; }else if(string.equals("4")) { return 4; } return 1; } public void setLabel() { int i = Converter(text.getText()); if(j<i && label.getText().equals("Player 1")) { j++; label.setText("Player "+j); }else if(j<i && label.getText().equals("Player 2")) { j++; label.setText("Player "+j); }else if(j<i && label.getText().equals("Player 3")) { j++; label.setText("Player "+j); }else if(j==i && label.getText().equals("Player "+j)) { j=1; label.setText("Player "+j); } } public void Start(int k) { panel2.setSize(300,500); this.setLayout(new BorderLayout()); panel3.setSize(100, 500); label = new JLabel("Player 1"); panel3.add(label); Border compound = BorderFactory.createCompoundBorder(BorderFactory.createRaisedBevelBorder(), BorderFactory.createLoweredBevelBorder()); panel3.setBorder(compound); //panel2.setBorder(compound); cards = new ArrayList<Button_Cards>(); ID = new ArrayList<Integer>(); hs = new HashMap<Integer, String>(); hs.put(0, "bob.png"); hs.put(1, "carl.jpg"); hs.put(2, "dog.jpg"); hs.put(3, "dude.jpg"); hs.put(4, "fat.jpg"); hs.put(5, "hood.jpg"); hs.put(6, "pokerFace.jpg"); hs.put(7, "prettyOne.jpg"); hs.put(8, "sad_Lary.jpg"); hs.put(9, "stickMan.jpg"); hs.put(10, "skil.jpg"); hs.put(11, "tsour.jpg"); for (int j =0;j<12; j++) { ID.add(j); ID.add(j); } Collections.shuffle(ID); ImageIcon icon ; icon = new ImageIcon(getClass().getResource("cardBack2.jpg")); for (int i : ID) { Button_Cards c = new Button_Cards(); c.setId(i); c.setIcon(icon); c.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { selectedCard = c ; c.setHasBeenSelected(); //IDs.add(c.getId()); TurnCard(); } }); cards.add(c); } timer = new Timer(1000, new ActionListener() { public void actionPerformed(ActionEvent ae) { Check(); } }); timer.setRepeats(false); for (Button_Cards c : cards) { panel2.add(c); } //t1 = new Thread(new AI_Elephant("Player 2", cards)); this.add(panel3,BorderLayout.NORTH); this.add(panel2, BorderLayout.CENTER); } public void TurnCard() { if (c1 == null && c2 == null){ c1 = selectedCard; //ImageIcon c1.setIcon(new ImageIcon(getClass().getResource(hs.get(c1.getId())))); } if (c1 != null && c1 != selectedCard && c2 == null){ c2 = selectedCard; c2.setIcon(new ImageIcon(getClass().getResource(hs.get(c2.getId())))); count++; timer.start(); } } /*synchronized void StartWait(Thread t) { try { while(true) t.wait(); } catch (InterruptedException ex) { Logger.getLogger(Player_vs_AI.class.getName()).log(Level.SEVERE, null, ex); } }*/ // @SuppressWarnings("empty-statement") public void Check() { if (c1.getId() == c2.getId()) { c1.setEnabled(false); c2.setEnabled(false); c1.setMatched(true); c2.setMatched(true); if(label.getText().equals("Player 2") && t1.getState()==TERMINATED) { t1 = new Thread(new AI_Elephant("Player 2", cards)); t1.start(); } if (this.isGameWon()) { JOptionPane.showMessageDialog(this, "Great! Game is over in " + count + " moves!"); System.exit(0); } } else { c1.setIcon(new ImageIcon(getClass().getResource("cardBack2.jpg"))); c2.setIcon(new ImageIcon(getClass().getResource("cardBack2.jpg"))); setLabel(); if(label.getText().equals("Player 2")) { t1=new Thread(new AI_Elephant("Player 2", cards)); t1.start(); } } c1 = null; c2 = null; } public void ai() { Random random = new Random(); do { count=0; i=random.nextInt(12); for(Button_Cards c : cards) { // System.out.println("εξω απο την if "+ i + " το id της καρτας: " +c.getId()); if(c.getId()==i && !c.getMatched()) { // System.out.println("το id της πρωτης: "+c.getId()); // System.out.println("πρωτη καρτα"); selectedCard=c; count++; c.doClick(); break; } } }while(count==0); // int k=random.nextInt(13); do { count_2=0; k=random.nextInt(12); for(Button_Cards b : cards) { // System.out.println(i + " " + k + " το id της καρτας: " +b.getId()); if(b.getId()==k && b.getMatched()==false && b!=selectedCard) { // System.out.println("μεσα στην<SUF> // System.out.println("δευτερη καρτα"); count_2++; b.doClick(); break; } } }while(count_2==0); } public boolean isGameWon() { for(Button_Cards c: this.cards) { if (c.getMatched() == false) { return false; } } return true; } }
4141_14
package gr.aueb.codingfactory.exr.ch1; import java.util.Scanner; /** * Όνομα : Κωνσταντίνος * Επίθετο : Παπαγεωργίου * Email : [email protected] * * Άσκηση 1 - Java - MenuApp * * Γράψτε ένα πρόγραμμα, νέα κλάση με όνομα MenuApp * μέσα στο package gr aueb gr ch 11, που να εκτυπώνει * το παρακάτω Μενού (χωρίς το κόκκινο πλαίσιο): * Επιλέξτε μία από τις παρακάτω επιλογές: * 1. Εισαγωγή * 2. Διαγραφή * 3. Αναζήτηση * 4. Ενημέρωση * 5. Έξοδος * Δώστε αριθμό επιλογής: */ public class ExerciseTwoCh1 { public static void main(String[] args) { Scanner choiceNumber = new Scanner(System.in); System.out.println("\n\tΕπιλέξτε μία από τις παρακάτω επιλογές: \n\t1. Εισαγωγή\n\t2. Διαχείριση\n\t3. Αναζήτηση\n\t4. Ενημέρωση\n\t5. Έξοδος\n\tΔώστε αριθμό επιλογής: \t"); // Προαιρετική λειτουργία εκτός εκφώνησης άσκησης // try { // int userSelected = choiceNumber.nextInt(); // // if (userSelected == 1) { // System.out.println("Έχετε επιλέξει την επιλογή : 1. Εισαγωγή"); // } else if (userSelected == 2) { // System.out.println("Έχετε επιλέξει την επιλογή : 2. Διαγραφή"); // } else if (userSelected == 3) { // System.out.println("Έχετε επιλέξει την επιλογή : 3. Αναζήτηση"); // } else if (userSelected == 4) { // System.out.println("Έχετε επιλέξει την επιλογή : 4. Ενημέρωση"); // } else if (userSelected == 5) { // System.out.println("Έχετε επιλέξει την επιλογή : 5. Έξοδος"); // } // } catch (Exception e){ // System.out.println("Μη συμβατή επιλογή!"); // } } }
purplebeam/Java-CF-Chapters
src/gr/aueb/codingfactory/exr/ch1/ExerciseTwoCh1.java
969
// System.out.println("Μη συμβατή επιλογή!");
line_comment
el
package gr.aueb.codingfactory.exr.ch1; import java.util.Scanner; /** * Όνομα : Κωνσταντίνος * Επίθετο : Παπαγεωργίου * Email : [email protected] * * Άσκηση 1 - Java - MenuApp * * Γράψτε ένα πρόγραμμα, νέα κλάση με όνομα MenuApp * μέσα στο package gr aueb gr ch 11, που να εκτυπώνει * το παρακάτω Μενού (χωρίς το κόκκινο πλαίσιο): * Επιλέξτε μία από τις παρακάτω επιλογές: * 1. Εισαγωγή * 2. Διαγραφή * 3. Αναζήτηση * 4. Ενημέρωση * 5. Έξοδος * Δώστε αριθμό επιλογής: */ public class ExerciseTwoCh1 { public static void main(String[] args) { Scanner choiceNumber = new Scanner(System.in); System.out.println("\n\tΕπιλέξτε μία από τις παρακάτω επιλογές: \n\t1. Εισαγωγή\n\t2. Διαχείριση\n\t3. Αναζήτηση\n\t4. Ενημέρωση\n\t5. Έξοδος\n\tΔώστε αριθμό επιλογής: \t"); // Προαιρετική λειτουργία εκτός εκφώνησης άσκησης // try { // int userSelected = choiceNumber.nextInt(); // // if (userSelected == 1) { // System.out.println("Έχετε επιλέξει την επιλογή : 1. Εισαγωγή"); // } else if (userSelected == 2) { // System.out.println("Έχετε επιλέξει την επιλογή : 2. Διαγραφή"); // } else if (userSelected == 3) { // System.out.println("Έχετε επιλέξει την επιλογή : 3. Αναζήτηση"); // } else if (userSelected == 4) { // System.out.println("Έχετε επιλέξει την επιλογή : 4. Ενημέρωση"); // } else if (userSelected == 5) { // System.out.println("Έχετε επιλέξει την επιλογή : 5. Έξοδος"); // } // } catch (Exception e){ // System.out.println("Μη συμβατή<SUF> // } } }
618_6
/* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dkpro.core.io.xces; import static org.apache.commons.io.IOUtils.closeQuietly; import java.io.IOException; import java.io.InputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.bind.ValidationEvent; import javax.xml.bind.ValidationEventHandler; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import org.apache.uima.collection.CollectionException; import org.apache.uima.fit.descriptor.TypeCapability; import org.apache.uima.fit.factory.JCasBuilder; import org.apache.uima.jcas.JCas; import org.dkpro.core.io.xces.models.XcesBody; import org.dkpro.core.io.xces.models.XcesPara; import org.dkpro.core.io.xces.models.XcesSentence; import org.dkpro.core.io.xces.models.XcesToken; import de.tudarmstadt.ukp.dkpro.core.api.io.JCasResourceCollectionReader_ImplBase; import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.POS; import de.tudarmstadt.ukp.dkpro.core.api.resources.CompressionUtils; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Lemma; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token; @TypeCapability(outputs = { "de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph", "de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Lemma", "de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence", "de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token" }) public class XcesXmlReader extends JCasResourceCollectionReader_ImplBase { @Override public void getNext(JCas aJCas) throws IOException, CollectionException { Resource res = nextFile(); initCas(aJCas, res); InputStream is = null; try { is = CompressionUtils.getInputStream(res.getLocation(), res.getInputStream()); XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(is); JAXBContext context = JAXBContext.newInstance(XcesBody.class); Unmarshaller unmarshaller = context.createUnmarshaller(); unmarshaller.setEventHandler(new ValidationEventHandler() { public boolean handleEvent(ValidationEvent event) { throw new RuntimeException(event.getMessage(), event.getLinkedException()); } }); JCasBuilder jb = new JCasBuilder(aJCas); XMLEvent e = null; while ((e = xmlEventReader.peek()) != null) { if (isStartElement(e, "body")) { try { XcesBody paras = (XcesBody) unmarshaller .unmarshal(xmlEventReader, XcesBody.class).getValue(); readPara(jb, paras); } catch (RuntimeException ex) { System.out.println("Unable to parse XCES format: " + ex); } } else { xmlEventReader.next(); } } jb.close(); } catch (XMLStreamException ex1) { throw new IOException(ex1); } catch (JAXBException e1) { throw new IOException(e1); } finally { closeQuietly(is); } } private void readPara(JCasBuilder jb, Object bodyObj) { // Below is the sample paragraph format // <p id="p1"> // <s id="s1"> // <t id="t1" word="Αυτή" tag="PnDmFe03SgNmXx" lemma="αυτός" /> // <t id="t2" word="είναι" tag="VbMnIdPr03SgXxIpPvXx" lemma="είμαι" /> // <t id="t3" word="η" tag="AtDfFeSgNm" lemma="ο" /> // <t id="t4" word="πρώτη" tag="NmOdFeSgNmAj" lemma="πρώτος" /> // <t id="t5" word="γραμμή" tag="NoCmFeSgNm" lemma="γραμμή" /> // <t id="t6" word="." tag="PTERM_P" lemma="." /> // </s> // </p> if (bodyObj instanceof XcesBody) { for (XcesPara paras : ((XcesBody) bodyObj).p) { int paraStart = jb.getPosition(); int paraEnd = jb.getPosition(); for (XcesSentence s : paras.s) { int sentStart = jb.getPosition(); int sentEnd = jb.getPosition(); for (int i = 0; i < s.xcesTokens.size(); i++) { XcesToken t = s.xcesTokens.get(i); XcesToken tnext = i + 1 == s.xcesTokens.size() ? null : s.xcesTokens.get(i + 1); Token token = jb.add(t.word, Token.class); if (t.lemma != null) { Lemma lemma = new Lemma(jb.getJCas(), token.getBegin(), token.getEnd()); lemma.setValue(t.lemma); lemma.addToIndexes(); token.setLemma(lemma); } if (t.tag != null) { POS pos = new POS(jb.getJCas(), token.getBegin(), token.getEnd()); pos.setPosValue(t.tag); pos.addToIndexes(); token.setPos(pos); } sentEnd = jb.getPosition(); if (tnext == null) jb.add("\n"); if (tnext != null) { jb.add(" "); } } Sentence sent = new Sentence(jb.getJCas(), sentStart, sentEnd); sent.addToIndexes(); paraEnd = sent.getEnd(); } Paragraph para = new Paragraph(jb.getJCas(), paraStart, paraEnd); para.addToIndexes(); jb.add("\n"); } } } public static boolean isStartElement(XMLEvent aEvent, String aElement) { return aEvent.isStartElement() && ((StartElement) aEvent).getName().getLocalPart().equals(aElement); } }
reckart/dkpro-core
dkpro-core-io-xces-asl/src/main/java/org/dkpro/core/io/xces/XcesXmlReader.java
1,899
// <t id="t5" word="γραμμή" tag="NoCmFeSgNm" lemma="γραμμή" />
line_comment
el
/* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dkpro.core.io.xces; import static org.apache.commons.io.IOUtils.closeQuietly; import java.io.IOException; import java.io.InputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.bind.ValidationEvent; import javax.xml.bind.ValidationEventHandler; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import org.apache.uima.collection.CollectionException; import org.apache.uima.fit.descriptor.TypeCapability; import org.apache.uima.fit.factory.JCasBuilder; import org.apache.uima.jcas.JCas; import org.dkpro.core.io.xces.models.XcesBody; import org.dkpro.core.io.xces.models.XcesPara; import org.dkpro.core.io.xces.models.XcesSentence; import org.dkpro.core.io.xces.models.XcesToken; import de.tudarmstadt.ukp.dkpro.core.api.io.JCasResourceCollectionReader_ImplBase; import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.POS; import de.tudarmstadt.ukp.dkpro.core.api.resources.CompressionUtils; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Lemma; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token; @TypeCapability(outputs = { "de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph", "de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Lemma", "de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence", "de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token" }) public class XcesXmlReader extends JCasResourceCollectionReader_ImplBase { @Override public void getNext(JCas aJCas) throws IOException, CollectionException { Resource res = nextFile(); initCas(aJCas, res); InputStream is = null; try { is = CompressionUtils.getInputStream(res.getLocation(), res.getInputStream()); XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(is); JAXBContext context = JAXBContext.newInstance(XcesBody.class); Unmarshaller unmarshaller = context.createUnmarshaller(); unmarshaller.setEventHandler(new ValidationEventHandler() { public boolean handleEvent(ValidationEvent event) { throw new RuntimeException(event.getMessage(), event.getLinkedException()); } }); JCasBuilder jb = new JCasBuilder(aJCas); XMLEvent e = null; while ((e = xmlEventReader.peek()) != null) { if (isStartElement(e, "body")) { try { XcesBody paras = (XcesBody) unmarshaller .unmarshal(xmlEventReader, XcesBody.class).getValue(); readPara(jb, paras); } catch (RuntimeException ex) { System.out.println("Unable to parse XCES format: " + ex); } } else { xmlEventReader.next(); } } jb.close(); } catch (XMLStreamException ex1) { throw new IOException(ex1); } catch (JAXBException e1) { throw new IOException(e1); } finally { closeQuietly(is); } } private void readPara(JCasBuilder jb, Object bodyObj) { // Below is the sample paragraph format // <p id="p1"> // <s id="s1"> // <t id="t1" word="Αυτή" tag="PnDmFe03SgNmXx" lemma="αυτός" /> // <t id="t2" word="είναι" tag="VbMnIdPr03SgXxIpPvXx" lemma="είμαι" /> // <t id="t3" word="η" tag="AtDfFeSgNm" lemma="ο" /> // <t id="t4" word="πρώτη" tag="NmOdFeSgNmAj" lemma="πρώτος" /> // <t id="t5"<SUF> // <t id="t6" word="." tag="PTERM_P" lemma="." /> // </s> // </p> if (bodyObj instanceof XcesBody) { for (XcesPara paras : ((XcesBody) bodyObj).p) { int paraStart = jb.getPosition(); int paraEnd = jb.getPosition(); for (XcesSentence s : paras.s) { int sentStart = jb.getPosition(); int sentEnd = jb.getPosition(); for (int i = 0; i < s.xcesTokens.size(); i++) { XcesToken t = s.xcesTokens.get(i); XcesToken tnext = i + 1 == s.xcesTokens.size() ? null : s.xcesTokens.get(i + 1); Token token = jb.add(t.word, Token.class); if (t.lemma != null) { Lemma lemma = new Lemma(jb.getJCas(), token.getBegin(), token.getEnd()); lemma.setValue(t.lemma); lemma.addToIndexes(); token.setLemma(lemma); } if (t.tag != null) { POS pos = new POS(jb.getJCas(), token.getBegin(), token.getEnd()); pos.setPosValue(t.tag); pos.addToIndexes(); token.setPos(pos); } sentEnd = jb.getPosition(); if (tnext == null) jb.add("\n"); if (tnext != null) { jb.add(" "); } } Sentence sent = new Sentence(jb.getJCas(), sentStart, sentEnd); sent.addToIndexes(); paraEnd = sent.getEnd(); } Paragraph para = new Paragraph(jb.getJCas(), paraStart, paraEnd); para.addToIndexes(); jb.add("\n"); } } } public static boolean isStartElement(XMLEvent aEvent, String aElement) { return aEvent.isStartElement() && ((StartElement) aEvent).getName().getLocalPart().equals(aElement); } }
877_5
package ApiFetcher; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.URI; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; public class CountryService { private final HttpClient client; private final ObjectMapper mapper; // Μία ερώτηση που έχω είναι αν αλλάξω το url σε ενα endpoint // το οποιο γυρναει μονο τα αποτελεσματα που με ενδιαφερουν // το οποίο είναι: //https://restcountries.com/v3.1/name/country_name?fields=name,currencies,capital,population,continents //θα είχε σημαντικη διαφορα // sto runtime και performance της εφαρμογης; θα ήθελα να το συζητησω στην θεωρητική εξέταση private final String BASE_URL = "https://restcountries.com/v3.1"; // Αρχικοποιεί την country service με έναν HTTP client και το jackson object mapper // το ένα για την σύνδεση με το api και το αλλο για την αποσειριοποιηση // θα το χρησιμοποιήσουμε στο app.java για την ανάκτηση δεδομένων public CountryService() { this.client = HttpClient.newHttpClient(); this.mapper = new ObjectMapper(); } // Στέλνει ενα http request με παραμετρο ένα url // και μετα κανει deserialize τα δεδομένα που παιρνει απο αυτο το url // και τα βαζει στην κλαση Country pojo private Country[] sendRequest(String url) throws IOException, InterruptedException { HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); return mapper.readValue(response.body(), Country[].class); } // καλεί το url με το endpoint all για όλες τις χώρες // καλεί την sendRequest για να περάσει τα δεδομένα στην pojo. public Country[] getAllCountries() throws IOException, InterruptedException { return sendRequest(BASE_URL + "/all"); } // το ίδιο για το όνομα public List<Country> getCountriesByName(String name, boolean exactMatch) throws IOException, InterruptedException { String url = BASE_URL + "/name/" + name + (exactMatch ? "?fullText=true" : ""); Country[] countries = sendRequest(url); List<Country> countryList = Arrays.asList(countries); return countryList; } // το ίδιο για τη γλωσσα public List<Country> getCountriesByLanguage(String language, boolean exactMatch) throws IOException, InterruptedException { String url = BASE_URL + "/lang/" + language + (exactMatch ? "?fullText=true" : ""); Country[] countries = sendRequest(url); List<Country> countryList = Arrays.asList(countries); return countryList; } // το ίδιο για το νόμισμα public Country[] getCountriesByCurrency(String currency, boolean exactMatch) throws IOException, InterruptedException { String url = BASE_URL + "/currency/" + currency.toLowerCase(); return sendRequest(url); } // Φτιάξαμε μία κλάση για να γυρνάει μόνο τα όνοματα όλων των χωρών ώστε να μπορούμε να // τα παρουσιάσουμε σαν διαθέσιμες επιλογές οταν ένας χρήστης ψάχνει μια χώρα για ένα όνομα public List<String> fetchAllCountryNames() throws IOException, InterruptedException { //καλούμε την μέθοδο getAllCountries για να πάρουμε τις πληροφορίες για όλες τις χώρες Country[] countries = getAllCountries(); // γυρνάμε μία λίστα απο ονόματα τα οποία τραβήξαμε μέσω της getName.getCommon return Arrays.stream(countries) .map(country -> country.getName().getCommon()) .collect(Collectors.toList()); } // Το ίδιο για τις γλώσσες public Set<String> fetchAllLanguages() throws IOException, InterruptedException { Country[] countries = getAllCountries(); return Arrays.stream(countries) .flatMap(country -> country.getLanguages().values().stream()) // .collect(Collectors.toSet()); } // Το ίδιο για τα συναλλάγματα public Set<String> fetchAllCurrencyNames() throws IOException, InterruptedException { Country[] allCountries = getAllCountries(); return Arrays.stream(allCountries) .map(Country::getCurrencies) .filter(Objects::nonNull) .flatMap(map -> map.values().stream()) .map(Country.Currency::getName) .collect(Collectors.toSet()); } }
rich-ter/javafx-countries-api
ApiFetcher/src/main/java/ApiFetcher/CountryService.java
1,648
// Αρχικοποιεί την country service με έναν HTTP client και το jackson object mapper
line_comment
el
package ApiFetcher; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.URI; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; public class CountryService { private final HttpClient client; private final ObjectMapper mapper; // Μία ερώτηση που έχω είναι αν αλλάξω το url σε ενα endpoint // το οποιο γυρναει μονο τα αποτελεσματα που με ενδιαφερουν // το οποίο είναι: //https://restcountries.com/v3.1/name/country_name?fields=name,currencies,capital,population,continents //θα είχε σημαντικη διαφορα // sto runtime και performance της εφαρμογης; θα ήθελα να το συζητησω στην θεωρητική εξέταση private final String BASE_URL = "https://restcountries.com/v3.1"; // Αρχικοποιεί την<SUF> // το ένα για την σύνδεση με το api και το αλλο για την αποσειριοποιηση // θα το χρησιμοποιήσουμε στο app.java για την ανάκτηση δεδομένων public CountryService() { this.client = HttpClient.newHttpClient(); this.mapper = new ObjectMapper(); } // Στέλνει ενα http request με παραμετρο ένα url // και μετα κανει deserialize τα δεδομένα που παιρνει απο αυτο το url // και τα βαζει στην κλαση Country pojo private Country[] sendRequest(String url) throws IOException, InterruptedException { HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); return mapper.readValue(response.body(), Country[].class); } // καλεί το url με το endpoint all για όλες τις χώρες // καλεί την sendRequest για να περάσει τα δεδομένα στην pojo. public Country[] getAllCountries() throws IOException, InterruptedException { return sendRequest(BASE_URL + "/all"); } // το ίδιο για το όνομα public List<Country> getCountriesByName(String name, boolean exactMatch) throws IOException, InterruptedException { String url = BASE_URL + "/name/" + name + (exactMatch ? "?fullText=true" : ""); Country[] countries = sendRequest(url); List<Country> countryList = Arrays.asList(countries); return countryList; } // το ίδιο για τη γλωσσα public List<Country> getCountriesByLanguage(String language, boolean exactMatch) throws IOException, InterruptedException { String url = BASE_URL + "/lang/" + language + (exactMatch ? "?fullText=true" : ""); Country[] countries = sendRequest(url); List<Country> countryList = Arrays.asList(countries); return countryList; } // το ίδιο για το νόμισμα public Country[] getCountriesByCurrency(String currency, boolean exactMatch) throws IOException, InterruptedException { String url = BASE_URL + "/currency/" + currency.toLowerCase(); return sendRequest(url); } // Φτιάξαμε μία κλάση για να γυρνάει μόνο τα όνοματα όλων των χωρών ώστε να μπορούμε να // τα παρουσιάσουμε σαν διαθέσιμες επιλογές οταν ένας χρήστης ψάχνει μια χώρα για ένα όνομα public List<String> fetchAllCountryNames() throws IOException, InterruptedException { //καλούμε την μέθοδο getAllCountries για να πάρουμε τις πληροφορίες για όλες τις χώρες Country[] countries = getAllCountries(); // γυρνάμε μία λίστα απο ονόματα τα οποία τραβήξαμε μέσω της getName.getCommon return Arrays.stream(countries) .map(country -> country.getName().getCommon()) .collect(Collectors.toList()); } // Το ίδιο για τις γλώσσες public Set<String> fetchAllLanguages() throws IOException, InterruptedException { Country[] countries = getAllCountries(); return Arrays.stream(countries) .flatMap(country -> country.getLanguages().values().stream()) // .collect(Collectors.toSet()); } // Το ίδιο για τα συναλλάγματα public Set<String> fetchAllCurrencyNames() throws IOException, InterruptedException { Country[] allCountries = getAllCountries(); return Arrays.stream(allCountries) .map(Country::getCurrencies) .filter(Objects::nonNull) .flatMap(map -> map.values().stream()) .map(Country.Currency::getName) .collect(Collectors.toSet()); } }
20731_3
package com.example.eboy_backend_2; import org.apache.catalina.Context; import org.apache.catalina.connector.Connector; import org.apache.tomcat.util.descriptor.web.SecurityCollection; import org.apache.tomcat.util.descriptor.web.SecurityConstraint; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.servlet.server.ServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @SpringBootApplication public class EboyBackend2Application { public static void main(String[] args) { SpringApplication.run(EboyBackend2Application.class, args); } /* For password encode */ @Bean public ServletWebServerFactory servletContainer() { TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() { @Override protected void postProcessContext(Context context) { SecurityConstraint securityConstraint = new SecurityConstraint(); securityConstraint.setUserConstraint("CONFIDENTIAL"); // θα πρεπει να περνανε μεσα απο ssl SecurityCollection collection = new SecurityCollection(); collection.addPattern("/*"); // ολα τα urls securityConstraint.addCollection(collection); context.addConstraint(securityConstraint); } }; tomcat.addAdditionalTomcatConnectors(redirectConnector()); return tomcat; } /* 2. Οριζεται connector για ανακατεύθυνση ολων των αιτησεων απο το αρχικο μη κρυπτογραφημενο port * στο κρυπτογραφημενο. Στο front-end για να εχω ssl το μονο που πρεπει να αλλαξω ειναι * στο user service κανω το url με port το 8443. Τρ θα πρεπει να πιστοποιει την ταυτοτητα του χρηστη * προκειμενου να μπορει να καταναλωσει τις υπηρεσιες. Αυτο πρεπει να υλοποιηθει και απο την πλευρα * του backend και του frontend (authentication-authorization). Φτιάχνω εναν καταλογο security * που αντιστοιχει σε ενα package security εντος του οποιου εχω μια κλαση websecurity. */ private Connector redirectConnector() { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setScheme("http"); connector.setPort(8080); connector.setSecure(false); connector.setRedirectPort(8443); return connector; } /* Για καθε μονοπατι επιτρεπεται crossorigin request απο παντου */ @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // * .allowedHeaders("*") // .allowedOrigins("*") .allowedMethods("*"); // } }; } }
rigas2k19/eboy-backend
auctionsBackend/src/main/java/com/example/eboy_backend_2/EboyBackend2Application.java
1,023
/* Για καθε μονοπατι επιτρεπεται crossorigin request απο παντου */
block_comment
el
package com.example.eboy_backend_2; import org.apache.catalina.Context; import org.apache.catalina.connector.Connector; import org.apache.tomcat.util.descriptor.web.SecurityCollection; import org.apache.tomcat.util.descriptor.web.SecurityConstraint; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.servlet.server.ServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @SpringBootApplication public class EboyBackend2Application { public static void main(String[] args) { SpringApplication.run(EboyBackend2Application.class, args); } /* For password encode */ @Bean public ServletWebServerFactory servletContainer() { TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() { @Override protected void postProcessContext(Context context) { SecurityConstraint securityConstraint = new SecurityConstraint(); securityConstraint.setUserConstraint("CONFIDENTIAL"); // θα πρεπει να περνανε μεσα απο ssl SecurityCollection collection = new SecurityCollection(); collection.addPattern("/*"); // ολα τα urls securityConstraint.addCollection(collection); context.addConstraint(securityConstraint); } }; tomcat.addAdditionalTomcatConnectors(redirectConnector()); return tomcat; } /* 2. Οριζεται connector για ανακατεύθυνση ολων των αιτησεων απο το αρχικο μη κρυπτογραφημενο port * στο κρυπτογραφημενο. Στο front-end για να εχω ssl το μονο που πρεπει να αλλαξω ειναι * στο user service κανω το url με port το 8443. Τρ θα πρεπει να πιστοποιει την ταυτοτητα του χρηστη * προκειμενου να μπορει να καταναλωσει τις υπηρεσιες. Αυτο πρεπει να υλοποιηθει και απο την πλευρα * του backend και του frontend (authentication-authorization). Φτιάχνω εναν καταλογο security * που αντιστοιχει σε ενα package security εντος του οποιου εχω μια κλαση websecurity. */ private Connector redirectConnector() { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setScheme("http"); connector.setPort(8080); connector.setSecure(false); connector.setRedirectPort(8443); return connector; } /* Για καθε μονοπατι<SUF>*/ @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // * .allowedHeaders("*") // .allowedOrigins("*") .allowedMethods("*"); // } }; } }
2552_2
public class EqualsNull { public static void main(String[] args) { // Δημιουργούμε το πρώτο μωρό Baby george1 = new Baby("George", true); // Δημιουργούμε το δεύτερο μωρό Baby george2 = new Baby("George", true); Baby george3 = null; // Συγκρίνουμε τα δυο αντικείμενα System.out.println(george1.equals(george2)); // Συγκρίνουμε τα δυο αντικείμενα System.out.println(george1.equals(george3)); // Συγκρίνουμε τα δυο αντικείμενα System.out.println(java.util.Objects.equals(george3, george1)); System.out.println(java.util.Objects.equals(george1, george3)); System.out.println(george1.equals(george3)); // Αυτό όμως αποτυγχάνει με NullPointerException System.out.println(george3.equals(george1)); // Τι θα εμφανίσει; } }
riggas-ionio/java
lecture-examples/03-classes-objects-intro/06-equals/EqualsNull.java
365
// Συγκρίνουμε τα δυο αντικείμενα
line_comment
el
public class EqualsNull { public static void main(String[] args) { // Δημιουργούμε το πρώτο μωρό Baby george1 = new Baby("George", true); // Δημιουργούμε το δεύτερο μωρό Baby george2 = new Baby("George", true); Baby george3 = null; // Συγκρίνουμε τα<SUF> System.out.println(george1.equals(george2)); // Συγκρίνουμε τα δυο αντικείμενα System.out.println(george1.equals(george3)); // Συγκρίνουμε τα δυο αντικείμενα System.out.println(java.util.Objects.equals(george3, george1)); System.out.println(java.util.Objects.equals(george1, george3)); System.out.println(george1.equals(george3)); // Αυτό όμως αποτυγχάνει με NullPointerException System.out.println(george3.equals(george1)); // Τι θα εμφανίσει; } }
8397_2
import java.io.*; import java.util.Scanner; public class Main { public static void main(String args[]){ try{ MerosA.readIntegers();}catch(IOException e){} //MerosA.mergeSort(MerosA.initialArray); //for(int i = 0;i<MerosA.initialArray.size();i++) // System.out.println(MerosA.initialArray.get(i)); // System.out.println(initialArray.MerosA); int number=0; int choise=0; do{ System.out.println(""); System.out.println("Menu:"); //Εδω με την βοηθεια τον εντολων εκτυπωσης δημιουργουμε ενα Menu απο το οποιο ο χρηστης διαλεγει πια επιλογη θελει System.out.println("0:Read Integers.txt(file position is in C//integers.txt) and Merge Sort the numbers!"); //γραφοντας τον αριθμο της καθε επιλογης που αναγραφεται και ακολουθοντας προσεκτικα τις συμβουλες που ακολουθουν System.out.println("1:Lineral Search"); System.out.println("2:Binary Search)"); System.out.println("3:Interpolation Search"); System.out.println("4:Red-Black Tree Menu"); System.out.println("5:Digital Tree(Trie) Menu"); System.out.println("6:ΜέροςΔ execute searches and store times for each search to csv in the directory. "); System.out.println("7:Print Menu"); System.out.println("8:Exit Programm"); System.out.println("*******Important Note********"); System.out.println("(In order to correctly run 1 or 2 or 3 case 0 must be first be run!!! "); Scanner keyboard=new Scanner(System.in); //δημιουργια αντικειμενου keyboard τυπου Scanner για την εισαγωγη δεδομενων απο το πληκτρολογιο System.out.println("Choose choise 0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8"); choise=keyboard.nextInt();//εδω με αυτη την εντολη εισαγεται απο το πληκτρολογιο το νουμερο που εγραψε ο χρηστης για να εκτελεστει η συγκεκριμενη ενεργεια που θελει switch(choise){ //με την βοηθεια της switch φτιαχνουμε ολες τις δυνατε επιλογες που θελουμε και αναλογα με το τι απαντησει ο χρηστης χρησιμοποιειται το καθε αντισοιχο case. case 0: System.out.println("(Reading and Merge Sorting the integers in the integers.txt file)"); //try{ MerosA.readIntegers();}catch(IOException e){} MerosA.mergeSort(MerosA.initialArray); System.out.println("Merge Sort Finished"); break; case 1: System.out.println("Lineral Search"); System.out.println("Reminder:"); System.out.println("(In order to correctly run the Integer array must be Merge Sorted) "); System.out.println("Enter the number you want to search\n"); number=keyboard.nextInt(); MerosB.lineralSearch(number); System.out.println("Lineral Search Finished"); break; case 2: System.out.println("Binary Search"); System.out.println("Reminder:"); System.out.println("(In order to correctly run the Integer array must be Merge Sorted) "); System.out.println("Enter the number you want to search\n"); number=keyboard.nextInt(); MerosB.binarySearch(number); System.out.println("Binary Search Finished"); break; case 3: System.out.println("Interpolation Search"); System.out.println("Reminder:"); System.out.println("(In order to correctly run the integer array must be Merge Sorted )"); System.out.println("Enter the number you want to search\n"); number=keyboard.nextInt(); MerosB.interpolationSearch(number); System.out.println("Interpolation Search Finished"); break; case 4: System.out.println("Red-Black Tree Menu"); System.out.println("Reminder:"); System.out.println("(In order to correctly run the integer array must be Merge Sorted )"); int RBchoise=0; do{ System.out.println(""); System.out.println("Red-Black Tree."); System.out.println("0:Read integers.txt and create Red-Black Tree."); System.out.println("1:Search a word in Red-Black Tree."); System.out.println("2:Insert a word in Red-Black Tree.."); System.out.println("3:Exit Red-Black Tree Menu."); switch(RBchoise){ case 0: MerosA.mergeSort(MerosA.initialArray); for(int j=0; j<MerosA.initialArray.size(); j++){ MerosC.RBTreeInsert(MerosA.initialArray.get(j)); } break; case 1: int w; System.out.println("Red-Black Tree Search"); System.out.println("Reminder:"); System.out.println("(In order to correctly run you must first read integers.txt!!! )"); System.out.println("Enter the number you want to search\n"); w=keyboard.nextInt(); MerosC.RBTreeSearch(w); System.out.println("Search of number " + w + " completed!!!"); break; case 2: int t; System.out.println("Red-Black Tree Search"); System.out.println("Reminder:"); System.out.println("(In order to correctly run you must first read integers.txt!!! )"); System.out.println("Enter the number you want to search\n"); t=keyboard.nextInt(); MerosC.RBTreeInsert(t); System.out.println("Insertion of number " + t + " completed!!!"); break; case 3:break; default:break; } }while (RBchoise!=3); break; case 5: System.out.println("5:Digital Tree(Trie) Menu(words.txt position is in C//integers.txt)"); int trieChoise=0; do{ String output[] = {" is not present in trie", " is present in trie"}; Scanner word=new Scanner(System.in); Scanner key=new Scanner(System.in); System.out.println(""); System.out.println("Trie"); System.out.println("0:Read words.txt and create Trie."); System.out.println("1:Search a word in Trie."); System.out.println("2:Insert a word in Trie.."); System.out.println("3:Delete a word from Trie.."); System.out.println("4:Exit Trie Menu."); trieChoise=key.nextInt(); switch(trieChoise){ case 0: try{MerosE.readString();}catch (IOException e){} break; case 1: System.out.println("Search a word in Trie. "); try{ MerosE.readString();}catch(IOException e){} //String output[] = {" is not present in trie", " is present in trie"}; MerosE.root = new TrieNode(); String y; System.out.println("Enter the word you want to search"); y=word.nextLine(); y=y.toLowerCase(); // Construct trie for (int i = 0; i < MerosE.stringArray.size() ; i++) MerosE.insert( MerosE.stringArray.get(i)); // Search for different keys if( MerosE.search(y) == true) System.out.println(y + output[1]); else System.out.println(y + output[0]); //MerosE.delete(y); //if( MerosE.search(y) == true) //System.out.println(y + output[1]); //else System.out.println(y + output[0]); break; case 2: System.out.println("Insert a word in Trie. "); try{ MerosE.readString();}catch(IOException e){} MerosE.root = new TrieNode(); String x; System.out.println("Enter the word you want to insert\n"); x=word.nextLine(); x=x.toLowerCase(); for (int i = 0; i < MerosE.stringArray.size() ; i++) MerosE.insert( MerosE.stringArray.get(i)); MerosE.insert(x); System.out.println("Insertion of " + x + " completed!!!"); if( MerosE.search(x) == true) System.out.println(x + output[1]); else System.out.println(x + output[0]); break; case 3: MerosE.root = new TrieNode(); String z; System.out.println("Delete a word in Trie. "); System.out.println("Enter the word you want to delete\n"); z=word.nextLine(); z=z.toLowerCase(); MerosE.insert(z); MerosE.delete(z); System.out.println("Deletion of "+ z +" completed!!!"); if( MerosE.search(z) == true) System.out.println(z + output[1]); else System.out.println(z + output[0]); break; case 4:break; default:break; } }while(trieChoise != 4); case 6: System.out.println("6:MerosD executing searches and store times for each search to csv in the directory of the package."); MerosD.times(); break; case 7: System.out.println("7:Print Menu"); int printChoise=0; do{ System.out.println(""); System.out.println("Print Menu:"); System.out.println("0:Print Initial (No Merge Sort) List"); System.out.println("1:Print Merge Sorted List"); System.out.println("2:Print all the words of words.txt"); System.out.println("3:Exit Printing Programm."); printChoise=keyboard.nextInt(); switch(printChoise){ case 0: try{Printer.printInitial();}catch(IOException e){} break; case 1: Printer.printMerged(); break; case 2: Printer.printWords(); break; case 3:break; default:break; } }while(printChoise != 3); break; case 8:break; //Τερματισμος προγραμματος default:break; } }while(choise != 8); } }
rkapsalis/CEID-projects
Object Oriented Programming/JAVA/Main.java
2,891
//integers.txt) and Merge Sort the numbers!"); //γραφοντας τον αριθμο της καθε επιλογης που αναγραφεται και ακολουθοντας προσεκτικα τις συμβουλες που ακολουθουν
line_comment
el
import java.io.*; import java.util.Scanner; public class Main { public static void main(String args[]){ try{ MerosA.readIntegers();}catch(IOException e){} //MerosA.mergeSort(MerosA.initialArray); //for(int i = 0;i<MerosA.initialArray.size();i++) // System.out.println(MerosA.initialArray.get(i)); // System.out.println(initialArray.MerosA); int number=0; int choise=0; do{ System.out.println(""); System.out.println("Menu:"); //Εδω με την βοηθεια τον εντολων εκτυπωσης δημιουργουμε ενα Menu απο το οποιο ο χρηστης διαλεγει πια επιλογη θελει System.out.println("0:Read Integers.txt(file position is in C//integers.txt) and<SUF> System.out.println("1:Lineral Search"); System.out.println("2:Binary Search)"); System.out.println("3:Interpolation Search"); System.out.println("4:Red-Black Tree Menu"); System.out.println("5:Digital Tree(Trie) Menu"); System.out.println("6:ΜέροςΔ execute searches and store times for each search to csv in the directory. "); System.out.println("7:Print Menu"); System.out.println("8:Exit Programm"); System.out.println("*******Important Note********"); System.out.println("(In order to correctly run 1 or 2 or 3 case 0 must be first be run!!! "); Scanner keyboard=new Scanner(System.in); //δημιουργια αντικειμενου keyboard τυπου Scanner για την εισαγωγη δεδομενων απο το πληκτρολογιο System.out.println("Choose choise 0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8"); choise=keyboard.nextInt();//εδω με αυτη την εντολη εισαγεται απο το πληκτρολογιο το νουμερο που εγραψε ο χρηστης για να εκτελεστει η συγκεκριμενη ενεργεια που θελει switch(choise){ //με την βοηθεια της switch φτιαχνουμε ολες τις δυνατε επιλογες που θελουμε και αναλογα με το τι απαντησει ο χρηστης χρησιμοποιειται το καθε αντισοιχο case. case 0: System.out.println("(Reading and Merge Sorting the integers in the integers.txt file)"); //try{ MerosA.readIntegers();}catch(IOException e){} MerosA.mergeSort(MerosA.initialArray); System.out.println("Merge Sort Finished"); break; case 1: System.out.println("Lineral Search"); System.out.println("Reminder:"); System.out.println("(In order to correctly run the Integer array must be Merge Sorted) "); System.out.println("Enter the number you want to search\n"); number=keyboard.nextInt(); MerosB.lineralSearch(number); System.out.println("Lineral Search Finished"); break; case 2: System.out.println("Binary Search"); System.out.println("Reminder:"); System.out.println("(In order to correctly run the Integer array must be Merge Sorted) "); System.out.println("Enter the number you want to search\n"); number=keyboard.nextInt(); MerosB.binarySearch(number); System.out.println("Binary Search Finished"); break; case 3: System.out.println("Interpolation Search"); System.out.println("Reminder:"); System.out.println("(In order to correctly run the integer array must be Merge Sorted )"); System.out.println("Enter the number you want to search\n"); number=keyboard.nextInt(); MerosB.interpolationSearch(number); System.out.println("Interpolation Search Finished"); break; case 4: System.out.println("Red-Black Tree Menu"); System.out.println("Reminder:"); System.out.println("(In order to correctly run the integer array must be Merge Sorted )"); int RBchoise=0; do{ System.out.println(""); System.out.println("Red-Black Tree."); System.out.println("0:Read integers.txt and create Red-Black Tree."); System.out.println("1:Search a word in Red-Black Tree."); System.out.println("2:Insert a word in Red-Black Tree.."); System.out.println("3:Exit Red-Black Tree Menu."); switch(RBchoise){ case 0: MerosA.mergeSort(MerosA.initialArray); for(int j=0; j<MerosA.initialArray.size(); j++){ MerosC.RBTreeInsert(MerosA.initialArray.get(j)); } break; case 1: int w; System.out.println("Red-Black Tree Search"); System.out.println("Reminder:"); System.out.println("(In order to correctly run you must first read integers.txt!!! )"); System.out.println("Enter the number you want to search\n"); w=keyboard.nextInt(); MerosC.RBTreeSearch(w); System.out.println("Search of number " + w + " completed!!!"); break; case 2: int t; System.out.println("Red-Black Tree Search"); System.out.println("Reminder:"); System.out.println("(In order to correctly run you must first read integers.txt!!! )"); System.out.println("Enter the number you want to search\n"); t=keyboard.nextInt(); MerosC.RBTreeInsert(t); System.out.println("Insertion of number " + t + " completed!!!"); break; case 3:break; default:break; } }while (RBchoise!=3); break; case 5: System.out.println("5:Digital Tree(Trie) Menu(words.txt position is in C//integers.txt)"); int trieChoise=0; do{ String output[] = {" is not present in trie", " is present in trie"}; Scanner word=new Scanner(System.in); Scanner key=new Scanner(System.in); System.out.println(""); System.out.println("Trie"); System.out.println("0:Read words.txt and create Trie."); System.out.println("1:Search a word in Trie."); System.out.println("2:Insert a word in Trie.."); System.out.println("3:Delete a word from Trie.."); System.out.println("4:Exit Trie Menu."); trieChoise=key.nextInt(); switch(trieChoise){ case 0: try{MerosE.readString();}catch (IOException e){} break; case 1: System.out.println("Search a word in Trie. "); try{ MerosE.readString();}catch(IOException e){} //String output[] = {" is not present in trie", " is present in trie"}; MerosE.root = new TrieNode(); String y; System.out.println("Enter the word you want to search"); y=word.nextLine(); y=y.toLowerCase(); // Construct trie for (int i = 0; i < MerosE.stringArray.size() ; i++) MerosE.insert( MerosE.stringArray.get(i)); // Search for different keys if( MerosE.search(y) == true) System.out.println(y + output[1]); else System.out.println(y + output[0]); //MerosE.delete(y); //if( MerosE.search(y) == true) //System.out.println(y + output[1]); //else System.out.println(y + output[0]); break; case 2: System.out.println("Insert a word in Trie. "); try{ MerosE.readString();}catch(IOException e){} MerosE.root = new TrieNode(); String x; System.out.println("Enter the word you want to insert\n"); x=word.nextLine(); x=x.toLowerCase(); for (int i = 0; i < MerosE.stringArray.size() ; i++) MerosE.insert( MerosE.stringArray.get(i)); MerosE.insert(x); System.out.println("Insertion of " + x + " completed!!!"); if( MerosE.search(x) == true) System.out.println(x + output[1]); else System.out.println(x + output[0]); break; case 3: MerosE.root = new TrieNode(); String z; System.out.println("Delete a word in Trie. "); System.out.println("Enter the word you want to delete\n"); z=word.nextLine(); z=z.toLowerCase(); MerosE.insert(z); MerosE.delete(z); System.out.println("Deletion of "+ z +" completed!!!"); if( MerosE.search(z) == true) System.out.println(z + output[1]); else System.out.println(z + output[0]); break; case 4:break; default:break; } }while(trieChoise != 4); case 6: System.out.println("6:MerosD executing searches and store times for each search to csv in the directory of the package."); MerosD.times(); break; case 7: System.out.println("7:Print Menu"); int printChoise=0; do{ System.out.println(""); System.out.println("Print Menu:"); System.out.println("0:Print Initial (No Merge Sort) List"); System.out.println("1:Print Merge Sorted List"); System.out.println("2:Print all the words of words.txt"); System.out.println("3:Exit Printing Programm."); printChoise=keyboard.nextInt(); switch(printChoise){ case 0: try{Printer.printInitial();}catch(IOException e){} break; case 1: Printer.printMerged(); break; case 2: Printer.printWords(); break; case 3:break; default:break; } }while(printChoise != 3); break; case 8:break; //Τερματισμος προγραμματος default:break; } }while(choise != 8); } }
846_4
/* * Copyright (c) 2017, salesforce.com, inc. * All rights reserved. * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ package com.force.i18n.grammar.impl; import static com.force.i18n.commons.util.settings.IniFileUtil.intern; import java.util.*; import java.util.logging.Logger; import com.force.i18n.HumanLanguage; import com.force.i18n.commons.text.TrieMatcher; import com.force.i18n.grammar.*; import com.force.i18n.grammar.Noun.NounType; import com.google.common.collect.ImmutableMap; /** * Greek is *not* germanic, but it's close enough for salesforce work. * TODO: This really should be a separate declension from germanic, because only greek has a starts with that's interesting. * * @author stamm */ class GreekDeclension extends GermanicDeclension { private static final Logger logger = Logger.getLogger(GreekDeclension.class.getName()); private final Map<ArticleForm,String> indefiniteOverrides; private final Map<ArticleForm,String> definiteOverrides; public GreekDeclension(HumanLanguage language) { super(language); // Setup the map for "plosive endings" definiteOverrides = ImmutableMap.<ArticleForm, String>of( getArticleForm(LanguageStartsWith.SPECIAL, LanguageGender.MASCULINE, LanguageNumber.SINGULAR, LanguageCase.ACCUSATIVE), "\u03c4\u03bf\u03bd", // τον getArticleForm(LanguageStartsWith.SPECIAL, LanguageGender.FEMININE, LanguageNumber.SINGULAR, LanguageCase.ACCUSATIVE), "\u03c4\u03b7\u03bd"); // την indefiniteOverrides = Collections.singletonMap( getArticleForm(LanguageStartsWith.SPECIAL, LanguageGender.MASCULINE, LanguageNumber.SINGULAR, LanguageCase.ACCUSATIVE), "\u03ad\u03bd\u03b1\u03bd"); // έναν } private final Map<LanguageCase, ImmutableMap<LanguageNumber, ImmutableMap<LanguageGender,String>>> DEFINITE_ARTICLE = ImmutableMap.of( LanguageCase.NOMINATIVE, ImmutableMap.of(LanguageNumber.SINGULAR, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03bf", // το LanguageGender.FEMININE, "\u03b7", // η LanguageGender.MASCULINE, "\u03bf" // ο ), LanguageNumber.PLURAL, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03b1", // τα LanguageGender.FEMININE, "\u03bf\u03b9", // οι LanguageGender.MASCULINE, "\u03bf\u03b9" // οι )), LanguageCase.ACCUSATIVE, ImmutableMap.of(LanguageNumber.SINGULAR, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03bf", // το LanguageGender.FEMININE, "\u03c4\u03b7", // τη(ν) LanguageGender.MASCULINE, "\u03c4\u03bf" // το(ν) ), LanguageNumber.PLURAL, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03b1", // τα LanguageGender.FEMININE, "\u03c4\u03b9\u03c2", // τις LanguageGender.MASCULINE, "\u03c4\u03bf\u03c5\u03c2" // τους )), LanguageCase.GENITIVE, ImmutableMap.of(LanguageNumber.SINGULAR, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03bf\u03c5", // του LanguageGender.FEMININE, "\u03c4\u03b7\u03c2", // της LanguageGender.MASCULINE, "\u03c4\u03bf\u03c5" // του ), LanguageNumber.PLURAL, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03c9\u03bd", // των LanguageGender.FEMININE, "\u03c4\u03c9\u03bd", // των LanguageGender.MASCULINE, "\u03c4\u03c9\u03bd" // των )) ); private static final Map<LanguageCase, ImmutableMap<LanguageGender, String>> INDEFINITE_ARTICLE = ImmutableMap.of( LanguageCase.NOMINATIVE, ImmutableMap.of( LanguageGender.NEUTER, "\u03ad\u03bd\u03b1", // ένα LanguageGender.FEMININE, "\u03bc\u03af\u03b1", // μία LanguageGender.MASCULINE, "\u03ad\u03bd\u03b1\u03c2" // ένας ), LanguageCase.ACCUSATIVE, ImmutableMap.of( LanguageGender.NEUTER, "\u03ad\u03bd\u03b1", // ένα LanguageGender.FEMININE, "\u03bc\u03af\u03b1", // μία LanguageGender.MASCULINE, "\u03ad\u03bd\u03b1" // ένα(ν) ), LanguageCase.GENITIVE, ImmutableMap.of( LanguageGender.NEUTER, "\u03b5\u03bd\u03cc\u03c2", // ενός LanguageGender.FEMININE, "\u03bc\u03b9\u03b1\u03c2", // μιας LanguageGender.MASCULINE, "\u03b5\u03bd\u03cc\u03c2" // ενός ) ); public static class GreekNoun extends GermanicNoun { private static final long serialVersionUID = 1L; public GreekNoun(GermanicDeclension declension, String name, String pluralAlias, NounType type, String entityName, LanguageGender gender, String access, boolean isStandardField, boolean isCopied) { super(declension, name, pluralAlias, type, entityName, gender, access, isStandardField, isCopied); } @Override public void setString(String value, NounForm form) { super.setString(intern(value), form); if (form == getDeclension().getAllNounForms().get(0)) { setStartsWith(startsWithGreekPlosive(value) ? LanguageStartsWith.SPECIAL : LanguageStartsWith.CONSONANT); } } } @Override public Noun createNoun(String name, String pluralAlias, NounType type, String entityName, LanguageStartsWith startsWith, LanguageGender gender, String access, boolean isStandardField, boolean isCopied) { return new GreekNoun(this, name, pluralAlias, type, entityName, gender, access, isStandardField, isCopied); } public static boolean startsWithGreekPlosive(String value) { return PLOSIVE_MATCHER.begins(value); } @Override protected EnumSet<LanguageArticle> getRequiredAdjectiveArticles() { return EnumSet.of(LanguageArticle.ZERO); // Greek adjectives are not inflected for definitiveness } @Override protected String getDefaultArticleString(ArticleForm form, LanguageArticle articleType) { switch (articleType) { case DEFINITE: String override = definiteOverrides.get(form); if (override != null) return override; ImmutableMap<LanguageNumber, ImmutableMap<LanguageGender,String>> byCase = DEFINITE_ARTICLE.get(form.getCase()); if (byCase == null) { logger.fine("Trying to retrieve an illegal definite article form in greek"); return ""; } return byCase.get(form.getNumber()).get(form.getGender()); case INDEFINITE: if (form.getNumber() == LanguageNumber.PLURAL) return null; override = indefiniteOverrides.get(form); if (override != null) return override; return INDEFINITE_ARTICLE.get(form.getCase()).get(form.getGender()); default: return null; } } @Override public boolean hasStartsWith() { return true; } // κ, π, τ, μπ, ντ, γκ, τσ, τζ, ξ, ψ private static final String[] PLOSIVES = new String[] {"\u03ba","\u03c0","\u03c4", "\u03bc\u03c0", "\u03bd\u03c4", "\u03b3\u03ba", "\u03c4\u03c3", "\u03c4\u03b6", "\u03be", "\u03c8"}; private static final TrieMatcher PLOSIVE_MATCHER = TrieMatcher.compile(PLOSIVES, PLOSIVES); @Override public boolean hasAutoDerivedStartsWith() { return true; } @Override public EnumSet<LanguageStartsWith> getRequiredStartsWith() { return EnumSet.of(LanguageStartsWith.CONSONANT, LanguageStartsWith.SPECIAL); // Special is plosive in greek. } @Override public EnumSet<LanguageCase> getRequiredCases() { return EnumSet.of(LanguageCase.NOMINATIVE, LanguageCase.ACCUSATIVE, LanguageCase.GENITIVE, LanguageCase.VOCATIVE); } @Override public EnumSet<LanguageGender> getRequiredGenders() { return EnumSet.of(LanguageGender.NEUTER, LanguageGender.FEMININE, LanguageGender.MASCULINE); } @Override public String formLowercaseNounForm(String s, NounForm form) { return hasCapitalization() ? (s == null ? null : s.toLowerCase()) : s; } }
salesforce/grammaticus
src/main/java/com/force/i18n/grammar/impl/GreekDeclension.java
2,555
// κ, π, τ, μπ, ντ, γκ, τσ, τζ, ξ, ψ
line_comment
el
/* * Copyright (c) 2017, salesforce.com, inc. * All rights reserved. * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ package com.force.i18n.grammar.impl; import static com.force.i18n.commons.util.settings.IniFileUtil.intern; import java.util.*; import java.util.logging.Logger; import com.force.i18n.HumanLanguage; import com.force.i18n.commons.text.TrieMatcher; import com.force.i18n.grammar.*; import com.force.i18n.grammar.Noun.NounType; import com.google.common.collect.ImmutableMap; /** * Greek is *not* germanic, but it's close enough for salesforce work. * TODO: This really should be a separate declension from germanic, because only greek has a starts with that's interesting. * * @author stamm */ class GreekDeclension extends GermanicDeclension { private static final Logger logger = Logger.getLogger(GreekDeclension.class.getName()); private final Map<ArticleForm,String> indefiniteOverrides; private final Map<ArticleForm,String> definiteOverrides; public GreekDeclension(HumanLanguage language) { super(language); // Setup the map for "plosive endings" definiteOverrides = ImmutableMap.<ArticleForm, String>of( getArticleForm(LanguageStartsWith.SPECIAL, LanguageGender.MASCULINE, LanguageNumber.SINGULAR, LanguageCase.ACCUSATIVE), "\u03c4\u03bf\u03bd", // τον getArticleForm(LanguageStartsWith.SPECIAL, LanguageGender.FEMININE, LanguageNumber.SINGULAR, LanguageCase.ACCUSATIVE), "\u03c4\u03b7\u03bd"); // την indefiniteOverrides = Collections.singletonMap( getArticleForm(LanguageStartsWith.SPECIAL, LanguageGender.MASCULINE, LanguageNumber.SINGULAR, LanguageCase.ACCUSATIVE), "\u03ad\u03bd\u03b1\u03bd"); // έναν } private final Map<LanguageCase, ImmutableMap<LanguageNumber, ImmutableMap<LanguageGender,String>>> DEFINITE_ARTICLE = ImmutableMap.of( LanguageCase.NOMINATIVE, ImmutableMap.of(LanguageNumber.SINGULAR, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03bf", // το LanguageGender.FEMININE, "\u03b7", // η LanguageGender.MASCULINE, "\u03bf" // ο ), LanguageNumber.PLURAL, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03b1", // τα LanguageGender.FEMININE, "\u03bf\u03b9", // οι LanguageGender.MASCULINE, "\u03bf\u03b9" // οι )), LanguageCase.ACCUSATIVE, ImmutableMap.of(LanguageNumber.SINGULAR, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03bf", // το LanguageGender.FEMININE, "\u03c4\u03b7", // τη(ν) LanguageGender.MASCULINE, "\u03c4\u03bf" // το(ν) ), LanguageNumber.PLURAL, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03b1", // τα LanguageGender.FEMININE, "\u03c4\u03b9\u03c2", // τις LanguageGender.MASCULINE, "\u03c4\u03bf\u03c5\u03c2" // τους )), LanguageCase.GENITIVE, ImmutableMap.of(LanguageNumber.SINGULAR, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03bf\u03c5", // του LanguageGender.FEMININE, "\u03c4\u03b7\u03c2", // της LanguageGender.MASCULINE, "\u03c4\u03bf\u03c5" // του ), LanguageNumber.PLURAL, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03c9\u03bd", // των LanguageGender.FEMININE, "\u03c4\u03c9\u03bd", // των LanguageGender.MASCULINE, "\u03c4\u03c9\u03bd" // των )) ); private static final Map<LanguageCase, ImmutableMap<LanguageGender, String>> INDEFINITE_ARTICLE = ImmutableMap.of( LanguageCase.NOMINATIVE, ImmutableMap.of( LanguageGender.NEUTER, "\u03ad\u03bd\u03b1", // ένα LanguageGender.FEMININE, "\u03bc\u03af\u03b1", // μία LanguageGender.MASCULINE, "\u03ad\u03bd\u03b1\u03c2" // ένας ), LanguageCase.ACCUSATIVE, ImmutableMap.of( LanguageGender.NEUTER, "\u03ad\u03bd\u03b1", // ένα LanguageGender.FEMININE, "\u03bc\u03af\u03b1", // μία LanguageGender.MASCULINE, "\u03ad\u03bd\u03b1" // ένα(ν) ), LanguageCase.GENITIVE, ImmutableMap.of( LanguageGender.NEUTER, "\u03b5\u03bd\u03cc\u03c2", // ενός LanguageGender.FEMININE, "\u03bc\u03b9\u03b1\u03c2", // μιας LanguageGender.MASCULINE, "\u03b5\u03bd\u03cc\u03c2" // ενός ) ); public static class GreekNoun extends GermanicNoun { private static final long serialVersionUID = 1L; public GreekNoun(GermanicDeclension declension, String name, String pluralAlias, NounType type, String entityName, LanguageGender gender, String access, boolean isStandardField, boolean isCopied) { super(declension, name, pluralAlias, type, entityName, gender, access, isStandardField, isCopied); } @Override public void setString(String value, NounForm form) { super.setString(intern(value), form); if (form == getDeclension().getAllNounForms().get(0)) { setStartsWith(startsWithGreekPlosive(value) ? LanguageStartsWith.SPECIAL : LanguageStartsWith.CONSONANT); } } } @Override public Noun createNoun(String name, String pluralAlias, NounType type, String entityName, LanguageStartsWith startsWith, LanguageGender gender, String access, boolean isStandardField, boolean isCopied) { return new GreekNoun(this, name, pluralAlias, type, entityName, gender, access, isStandardField, isCopied); } public static boolean startsWithGreekPlosive(String value) { return PLOSIVE_MATCHER.begins(value); } @Override protected EnumSet<LanguageArticle> getRequiredAdjectiveArticles() { return EnumSet.of(LanguageArticle.ZERO); // Greek adjectives are not inflected for definitiveness } @Override protected String getDefaultArticleString(ArticleForm form, LanguageArticle articleType) { switch (articleType) { case DEFINITE: String override = definiteOverrides.get(form); if (override != null) return override; ImmutableMap<LanguageNumber, ImmutableMap<LanguageGender,String>> byCase = DEFINITE_ARTICLE.get(form.getCase()); if (byCase == null) { logger.fine("Trying to retrieve an illegal definite article form in greek"); return ""; } return byCase.get(form.getNumber()).get(form.getGender()); case INDEFINITE: if (form.getNumber() == LanguageNumber.PLURAL) return null; override = indefiniteOverrides.get(form); if (override != null) return override; return INDEFINITE_ARTICLE.get(form.getCase()).get(form.getGender()); default: return null; } } @Override public boolean hasStartsWith() { return true; } // κ, π,<SUF> private static final String[] PLOSIVES = new String[] {"\u03ba","\u03c0","\u03c4", "\u03bc\u03c0", "\u03bd\u03c4", "\u03b3\u03ba", "\u03c4\u03c3", "\u03c4\u03b6", "\u03be", "\u03c8"}; private static final TrieMatcher PLOSIVE_MATCHER = TrieMatcher.compile(PLOSIVES, PLOSIVES); @Override public boolean hasAutoDerivedStartsWith() { return true; } @Override public EnumSet<LanguageStartsWith> getRequiredStartsWith() { return EnumSet.of(LanguageStartsWith.CONSONANT, LanguageStartsWith.SPECIAL); // Special is plosive in greek. } @Override public EnumSet<LanguageCase> getRequiredCases() { return EnumSet.of(LanguageCase.NOMINATIVE, LanguageCase.ACCUSATIVE, LanguageCase.GENITIVE, LanguageCase.VOCATIVE); } @Override public EnumSet<LanguageGender> getRequiredGenders() { return EnumSet.of(LanguageGender.NEUTER, LanguageGender.FEMININE, LanguageGender.MASCULINE); } @Override public String formLowercaseNounForm(String s, NounForm form) { return hasCapitalization() ? (s == null ? null : s.toLowerCase()) : s; } }
17170_3
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.i18n.client.impl.cldr; import com.google.gwt.core.client.JavaScriptObject; // DO NOT EDIT - GENERATED FROM CLDR DATA /** * Localized names for the "el_POLYTON" locale. */ public class LocalizedNamesImpl_el_POLYTON extends LocalizedNamesImpl_el { @Override public String[] loadSortedRegionCodes() { return new String[] { "VA", "SH", "LC", "BL", "VC", "SM", "MF", "AZ", "EG", "ET", "HT", "CI", "AL", "DZ", "VI", "AS", "TL", "AO", "AI", "AD", "AQ", "AG", "UM", "AR", "AM", "AW", "AU", "AT", "AF", "VU", "BE", "VE", "BM", "VN", "BO", "KP", "BA", "BG", "BR", "IO", "VG", "FR", "FX", "TF", "GF", "PF", "DE", "GE", "GI", "GM", "GA", "GH", "GG", "GU", "GP", "GT", "GY", "GN", "GW", "GD", "GL", "DK", "DO", "EH", "CH", "GR", "SV", "ER", "EE", "EU", "ZM", "ZW", "SZ", "AE", "US", "GB", "EA", "JP", "IN", "ID", "JO", "IQ", "IR", "IE", "GQ", "EC", "IS", "ES", "IL", "IT", "KZ", "CM", "KH", "CA", "IC", "QA", "CF", "KE", "CN", "KG", "KI", "CO", "KM", "CD", "CG", "CR", "CU", "KW", "HR", "CY", "LA", "LS", "LV", "BY", "LB", "LR", "LY", "LT", "LI", "LU", "YT", "MG", "MO", "MY", "MW", "MV", "ML", "MT", "MA", "MQ", "MU", "MR", "ME", "MX", "MM", "FM", "MN", "MZ", "MD", "MC", "MS", "BD", "BB", "BS", "BH", "BZ", "BJ", "BW", "BF", "BI", "BT", "BN", "NA", "NR", "NZ", "NC", "NP", "AX", "MP", "KY", "CC", "CK", "MH", "WF", "SJ", "SB", "TC", "FO", "FK", "HM", "AC", "CP", "IM", "BV", "NF", "CX", "NE", "NG", "NI", "NU", "NO", "ZA", "GS", "KR", "DG", "DM", "NL", "AN", "OM", "HN", "HU", "UG", "UZ", "UA", "UY", "PK", "PS", "PW", "PA", "PG", "PY", "MK", "QO", "PE", "PN", "PL", "PT", "PR", "CV", "RE", "RW", "RO", "RU", "KN", "PM", "WS", "ST", "SA", "SN", "RS", "CS", "SC", "SG", "SL", "SK", "SI", "SO", "SD", "SE", "SR", "LK", "SY", "TW", "TH", "TZ", "TJ", "JM", "DJ", "TG", "TK", "TO", "TV", "TR", "TM", "TT", "TA", "TD", "CZ", "TN", "YE", "JE", "PH", "FI", "FJ", "CL", "HK", }; } @Override protected void loadNameMapJava() { super.loadNameMapJava(); namesMap.put("AD", "Ἀνδόρα"); namesMap.put("AE", "Ἠνωμένα Ἀραβικὰ Ἐμιράτα"); namesMap.put("AF", "Ἀφγανιστάν"); namesMap.put("AG", "Ἀντίγκουα καὶ Μπαρμπούντα"); namesMap.put("AI", "Ἀνγκουίλα"); namesMap.put("AL", "Ἀλβανία"); namesMap.put("AM", "Ἀρμενία"); namesMap.put("AN", "Ὁλλανδικὲς Ἀντίλλες"); namesMap.put("AO", "Ἀνγκόλα"); namesMap.put("AQ", "Ἀνταρκτική"); namesMap.put("AR", "Ἀργεντινή"); namesMap.put("AS", "Ἀμερικανικὴ Σαμόα"); namesMap.put("AT", "Αὐστρία"); namesMap.put("AU", "Αὐστραλία"); namesMap.put("AW", "Ἀρούμπα"); namesMap.put("AZ", "Ἀζερμπαϊτζάν"); namesMap.put("BA", "Βοσνία - Ἐρζεγοβίνη"); namesMap.put("BM", "Βερμοῦδες"); namesMap.put("BV", "Νῆσος Μπουβέ"); namesMap.put("CC", "Νῆσοι Κόκος (Κήλινγκ)"); namesMap.put("CD", "Κονγκό, Λαϊκὴ Δημοκρατία τοῦ"); namesMap.put("CF", "Κεντροαφρικανικὴ Δημοκρατία"); namesMap.put("CH", "Ἑλβετία"); namesMap.put("CI", "Ἀκτὴ Ἐλεφαντοστού"); namesMap.put("CK", "Νῆσοι Κούκ"); namesMap.put("CV", "Πράσινο Ἀκρωτήριο"); namesMap.put("CX", "Νῆσος Χριστουγέννων"); namesMap.put("DO", "Δομινικανὴ Δημοκρατία"); namesMap.put("DZ", "Ἀλγερία"); namesMap.put("EC", "Ἰσημερινός"); namesMap.put("EE", "Ἐσθονία"); namesMap.put("EG", "Αἴγυπτος"); namesMap.put("EH", "Δυτικὴ Σαχάρα"); namesMap.put("ER", "Ἐρυθραία"); namesMap.put("ES", "Ἱσπανία"); namesMap.put("ET", "Αἰθιοπία"); namesMap.put("EU", "Εὐρωπαϊκὴ ᾿Ένωση"); namesMap.put("FM", "Μικρονησία, Ὁμόσπονδες Πολιτεῖες τῆς"); namesMap.put("FO", "Νῆσοι Φερόες"); namesMap.put("GB", "Ἡνωμένο Βασίλειο"); namesMap.put("GF", "Γαλλικὴ Γουιάνα"); namesMap.put("GQ", "Ἰσημερινὴ Γουινέα"); namesMap.put("GR", "Ἑλλάδα"); namesMap.put("GS", "Νότια Γεωργία καὶ Νότιες Νήσοι Σάντουιτς"); namesMap.put("HK", "Χὸνγκ Κόνγκ, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας"); namesMap.put("HM", "Νῆσοι Χὲρντ καὶ Μακντόναλντ"); namesMap.put("HN", "Ὁνδούρα"); namesMap.put("HT", "Ἁϊτή"); namesMap.put("HU", "Οὑγγαρία"); namesMap.put("ID", "Ἰνδονησία"); namesMap.put("IE", "Ἰρλανδία"); namesMap.put("IL", "Ἰσραήλ"); namesMap.put("IN", "Ἰνδία"); namesMap.put("IO", "Βρετανικὰ Ἐδάφη Ἰνδικοῦ Ὠκεανοῦ"); namesMap.put("IQ", "Ἰράκ"); namesMap.put("IR", "Ἰράν, Ἰσλαμικὴ Δημοκρατία τοῦ"); namesMap.put("IS", "Ἰσλανδία"); namesMap.put("IT", "Ἰταλία"); namesMap.put("JO", "Ἰορδανία"); namesMap.put("JP", "Ἰαπωνία"); namesMap.put("KN", "Σαὶντ Κὶτς καὶ Νέβις"); namesMap.put("KY", "Νῆσοι Κέιμαν"); namesMap.put("LA", "Λατινικὴ Ἀμερική"); namesMap.put("LC", "Ἁγία Λουκία"); namesMap.put("LK", "Σρὶ Λάνκα"); namesMap.put("LU", "Λουξεμβοῦργο"); namesMap.put("MD", "Μολδαβία, Δημοκρατία τῆς"); namesMap.put("MH", "Νῆσοι Μάρσαλ"); namesMap.put("ML", "Μαλί"); namesMap.put("MO", "Μακάο, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας"); namesMap.put("MP", "Νῆσοι Βόρειες Μαριάνες"); namesMap.put("NF", "Νῆσος Νόρφολκ"); namesMap.put("NL", "Ὁλλανδία"); namesMap.put("OM", "Ὀμάν"); namesMap.put("PF", "Γαλλικὴ Πολυνησία"); namesMap.put("PM", "Σαὶντ Πιὲρ καὶ Μικελόν"); namesMap.put("PS", "Παλαιστινιακὰ Ἐδάφη"); namesMap.put("SA", "Σαουδικὴ Ἀραβία"); namesMap.put("SB", "Νῆσοι Σολομῶντος"); namesMap.put("SH", "Ἁγία Ἑλένη"); namesMap.put("SJ", "Νῆσοι Σβάλμπαρ καὶ Γιὰν Μαγιέν"); namesMap.put("SM", "Ἅγιος Μαρίνος"); namesMap.put("ST", "Σάο Τομὲ καὶ Πρίνσιπε"); namesMap.put("SV", "Ἒλ Σαλβαδόρ"); namesMap.put("SY", "Συρία, Ἀραβικὴ Δημοκρατία τῆς"); namesMap.put("TC", "Νῆσοι Τὲρκς καὶ Κάικος"); namesMap.put("TD", "Τσάντ"); namesMap.put("TF", "Γαλλικὰ Νότια Ἐδάφη"); namesMap.put("TL", "Ἀνατολικὸ Τιμόρ"); namesMap.put("TT", "Τρινιδὰδ καὶ Τομπάγκο"); namesMap.put("UA", "Οὐκρανία"); namesMap.put("UG", "Οὐγκάντα"); namesMap.put("UM", "Ἀπομακρυσμένες Νησίδες τῶν Ἡνωμένων Πολιτειῶν"); namesMap.put("US", "Ἡνωμένες Πολιτεῖες"); namesMap.put("UY", "Οὐρουγουάη"); namesMap.put("UZ", "Οὐζμπεκιστάν"); namesMap.put("VA", "Ἁγία Ἕδρα (Βατικανό)"); namesMap.put("VC", "Ἅγιος Βικέντιος καὶ Γρεναδίνες"); namesMap.put("VG", "Βρετανικὲς Παρθένοι Νῆσοι"); namesMap.put("VI", "Ἀμερικανικὲς Παρθένοι Νῆσοι"); namesMap.put("WF", "Νῆσοι Οὐάλλις καὶ Φουτουνά"); namesMap.put("YE", "Ὑεμένη"); namesMap.put("ZA", "Νότια Ἀφρική"); } @Override protected JavaScriptObject loadNameMapNative() { return overrideMap(super.loadNameMapNative(), loadMyNameMap()); } private native JavaScriptObject loadMyNameMap() /*-{ return { "AD": "Ἀνδόρα", "AE": "Ἠνωμένα Ἀραβικὰ Ἐμιράτα", "AF": "Ἀφγανιστάν", "AG": "Ἀντίγκουα καὶ Μπαρμπούντα", "AI": "Ἀνγκουίλα", "AL": "Ἀλβανία", "AM": "Ἀρμενία", "AN": "Ὁλλανδικὲς Ἀντίλλες", "AO": "Ἀνγκόλα", "AQ": "Ἀνταρκτική", "AR": "Ἀργεντινή", "AS": "Ἀμερικανικὴ Σαμόα", "AT": "Αὐστρία", "AU": "Αὐστραλία", "AW": "Ἀρούμπα", "AZ": "Ἀζερμπαϊτζάν", "BA": "Βοσνία - Ἐρζεγοβίνη", "BM": "Βερμοῦδες", "BV": "Νῆσος Μπουβέ", "CC": "Νῆσοι Κόκος (Κήλινγκ)", "CD": "Κονγκό, Λαϊκὴ Δημοκρατία τοῦ", "CF": "Κεντροαφρικανικὴ Δημοκρατία", "CH": "Ἑλβετία", "CI": "Ἀκτὴ Ἐλεφαντοστού", "CK": "Νῆσοι Κούκ", "CV": "Πράσινο Ἀκρωτήριο", "CX": "Νῆσος Χριστουγέννων", "DO": "Δομινικανὴ Δημοκρατία", "DZ": "Ἀλγερία", "EC": "Ἰσημερινός", "EE": "Ἐσθονία", "EG": "Αἴγυπτος", "EH": "Δυτικὴ Σαχάρα", "ER": "Ἐρυθραία", "ES": "Ἱσπανία", "ET": "Αἰθιοπία", "EU": "Εὐρωπαϊκὴ ᾿Ένωση", "FM": "Μικρονησία, Ὁμόσπονδες Πολιτεῖες τῆς", "FO": "Νῆσοι Φερόες", "GB": "Ἡνωμένο Βασίλειο", "GF": "Γαλλικὴ Γουιάνα", "GQ": "Ἰσημερινὴ Γουινέα", "GR": "Ἑλλάδα", "GS": "Νότια Γεωργία καὶ Νότιες Νήσοι Σάντουιτς", "HK": "Χὸνγκ Κόνγκ, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας", "HM": "Νῆσοι Χὲρντ καὶ Μακντόναλντ", "HN": "Ὁνδούρα", "HT": "Ἁϊτή", "HU": "Οὑγγαρία", "ID": "Ἰνδονησία", "IE": "Ἰρλανδία", "IL": "Ἰσραήλ", "IN": "Ἰνδία", "IO": "Βρετανικὰ Ἐδάφη Ἰνδικοῦ Ὠκεανοῦ", "IQ": "Ἰράκ", "IR": "Ἰράν, Ἰσλαμικὴ Δημοκρατία τοῦ", "IS": "Ἰσλανδία", "IT": "Ἰταλία", "JO": "Ἰορδανία", "JP": "Ἰαπωνία", "KN": "Σαὶντ Κὶτς καὶ Νέβις", "KY": "Νῆσοι Κέιμαν", "LA": "Λατινικὴ Ἀμερική", "LC": "Ἁγία Λουκία", "LK": "Σρὶ Λάνκα", "LU": "Λουξεμβοῦργο", "MD": "Μολδαβία, Δημοκρατία τῆς", "MH": "Νῆσοι Μάρσαλ", "ML": "Μαλί", "MO": "Μακάο, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας", "MP": "Νῆσοι Βόρειες Μαριάνες", "NF": "Νῆσος Νόρφολκ", "NL": "Ὁλλανδία", "OM": "Ὀμάν", "PF": "Γαλλικὴ Πολυνησία", "PM": "Σαὶντ Πιὲρ καὶ Μικελόν", "PS": "Παλαιστινιακὰ Ἐδάφη", "SA": "Σαουδικὴ Ἀραβία", "SB": "Νῆσοι Σολομῶντος", "SH": "Ἁγία Ἑλένη", "SJ": "Νῆσοι Σβάλμπαρ καὶ Γιὰν Μαγιέν", "SM": "Ἅγιος Μαρίνος", "ST": "Σάο Τομὲ καὶ Πρίνσιπε", "SV": "Ἒλ Σαλβαδόρ", "SY": "Συρία, Ἀραβικὴ Δημοκρατία τῆς", "TC": "Νῆσοι Τὲρκς καὶ Κάικος", "TD": "Τσάντ", "TF": "Γαλλικὰ Νότια Ἐδάφη", "TL": "Ἀνατολικὸ Τιμόρ", "TT": "Τρινιδὰδ καὶ Τομπάγκο", "UA": "Οὐκρανία", "UG": "Οὐγκάντα", "UM": "Ἀπομακρυσμένες Νησίδες τῶν Ἡνωμένων Πολιτειῶν", "US": "Ἡνωμένες Πολιτεῖες", "UY": "Οὐρουγουάη", "UZ": "Οὐζμπεκιστάν", "VA": "Ἁγία Ἕδρα (Βατικανό)", "VC": "Ἅγιος Βικέντιος καὶ Γρεναδίνες", "VG": "Βρετανικὲς Παρθένοι Νῆσοι", "VI": "Ἀμερικανικὲς Παρθένοι Νῆσοι", "WF": "Νῆσοι Οὐάλλις καὶ Φουτουνά", "YE": "Ὑεμένη", "ZA": "Νότια Ἀφρική" }; }-*/; }
scalagwt/scalagwt-gwt
user/src/com/google/gwt/i18n/client/impl/cldr/LocalizedNamesImpl_el_POLYTON.java
6,608
/*-{ return { "AD": "Ἀνδόρα", "AE": "Ἠνωμένα Ἀραβικὰ Ἐμιράτα", "AF": "Ἀφγανιστάν", "AG": "Ἀντίγκουα καὶ Μπαρμπούντα", "AI": "Ἀνγκουίλα", "AL": "Ἀλβανία", "AM": "Ἀρμενία", "AN": "Ὁλλανδικὲς Ἀντίλλες", "AO": "Ἀνγκόλα", "AQ": "Ἀνταρκτική", "AR": "Ἀργεντινή", "AS": "Ἀμερικανικὴ Σαμόα", "AT": "Αὐστρία", "AU": "Αὐστραλία", "AW": "Ἀρούμπα", "AZ": "Ἀζερμπαϊτζάν", "BA": "Βοσνία - Ἐρζεγοβίνη", "BM": "Βερμοῦδες", "BV": "Νῆσος Μπουβέ", "CC": "Νῆσοι Κόκος (Κήλινγκ)", "CD": "Κονγκό, Λαϊκὴ Δημοκρατία τοῦ", "CF": "Κεντροαφρικανικὴ Δημοκρατία", "CH": "Ἑλβετία", "CI": "Ἀκτὴ Ἐλεφαντοστού", "CK": "Νῆσοι Κούκ", "CV": "Πράσινο Ἀκρωτήριο", "CX": "Νῆσος Χριστουγέννων", "DO": "Δομινικανὴ Δημοκρατία", "DZ": "Ἀλγερία", "EC": "Ἰσημερινός", "EE": "Ἐσθονία", "EG": "Αἴγυπτος", "EH": "Δυτικὴ Σαχάρα", "ER": "Ἐρυθραία", "ES": "Ἱσπανία", "ET": "Αἰθιοπία", "EU": "Εὐρωπαϊκὴ ᾿Ένωση", "FM": "Μικρονησία, Ὁμόσπονδες Πολιτεῖες τῆς", "FO": "Νῆσοι Φερόες", "GB": "Ἡνωμένο Βασίλειο", "GF": "Γαλλικὴ Γουιάνα", "GQ": "Ἰσημερινὴ Γουινέα", "GR": "Ἑλλάδα", "GS": "Νότια Γεωργία καὶ Νότιες Νήσοι Σάντουιτς", "HK": "Χὸνγκ Κόνγκ, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας", "HM": "Νῆσοι Χὲρντ καὶ Μακντόναλντ", "HN": "Ὁνδούρα", "HT": "Ἁϊτή", "HU": "Οὑγγαρία", "ID": "Ἰνδονησία", "IE": "Ἰρλανδία", "IL": "Ἰσραήλ", "IN": "Ἰνδία", "IO": "Βρετανικὰ Ἐδάφη Ἰνδικοῦ Ὠκεανοῦ", "IQ": "Ἰράκ", "IR": "Ἰράν, Ἰσλαμικὴ Δημοκρατία τοῦ", "IS": "Ἰσλανδία", "IT": "Ἰταλία", "JO": "Ἰορδανία", "JP": "Ἰαπωνία", "KN": "Σαὶντ Κὶτς καὶ Νέβις", "KY": "Νῆσοι Κέιμαν", "LA": "Λατινικὴ Ἀμερική", "LC": "Ἁγία Λουκία", "LK": "Σρὶ Λάνκα", "LU": "Λουξεμβοῦργο", "MD": "Μολδαβία, Δημοκρατία τῆς", "MH": "Νῆσοι Μάρσαλ", "ML": "Μαλί", "MO": "Μακάο, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας", "MP": "Νῆσοι Βόρειες Μαριάνες", "NF": "Νῆσος Νόρφολκ", "NL": "Ὁλλανδία", "OM": "Ὀμάν", "PF": "Γαλλικὴ Πολυνησία", "PM": "Σαὶντ Πιὲρ καὶ Μικελόν", "PS": "Παλαιστινιακὰ Ἐδάφη", "SA": "Σαουδικὴ Ἀραβία", "SB": "Νῆσοι Σολομῶντος", "SH": "Ἁγία Ἑλένη", "SJ": "Νῆσοι Σβάλμπαρ καὶ Γιὰν Μαγιέν", "SM": "Ἅγιος Μαρίνος", "ST": "Σάο Τομὲ καὶ Πρίνσιπε", "SV": "Ἒλ Σαλβαδόρ", "SY": "Συρία, Ἀραβικὴ Δημοκρατία τῆς", "TC": "Νῆσοι Τὲρκς καὶ Κάικος", "TD": "Τσάντ", "TF": "Γαλλικὰ Νότια Ἐδάφη", "TL": "Ἀνατολικὸ Τιμόρ", "TT": "Τρινιδὰδ καὶ Τομπάγκο", "UA": "Οὐκρανία", "UG": "Οὐγκάντα", "UM": "Ἀπομακρυσμένες Νησίδες τῶν Ἡνωμένων Πολιτειῶν", "US": "Ἡνωμένες Πολιτεῖες", "UY": "Οὐρουγουάη", "UZ": "Οὐζμπεκιστάν", "VA": "Ἁγία Ἕδρα (Βατικανό)", "VC": "Ἅγιος Βικέντιος καὶ Γρεναδίνες", "VG": "Βρετανικὲς Παρθένοι Νῆσοι", "VI": "Ἀμερικανικὲς Παρθένοι Νῆσοι", "WF": "Νῆσοι Οὐάλλις καὶ Φουτουνά", "YE": "Ὑεμένη", "ZA": "Νότια Ἀφρική" }; }-*/
block_comment
el
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.i18n.client.impl.cldr; import com.google.gwt.core.client.JavaScriptObject; // DO NOT EDIT - GENERATED FROM CLDR DATA /** * Localized names for the "el_POLYTON" locale. */ public class LocalizedNamesImpl_el_POLYTON extends LocalizedNamesImpl_el { @Override public String[] loadSortedRegionCodes() { return new String[] { "VA", "SH", "LC", "BL", "VC", "SM", "MF", "AZ", "EG", "ET", "HT", "CI", "AL", "DZ", "VI", "AS", "TL", "AO", "AI", "AD", "AQ", "AG", "UM", "AR", "AM", "AW", "AU", "AT", "AF", "VU", "BE", "VE", "BM", "VN", "BO", "KP", "BA", "BG", "BR", "IO", "VG", "FR", "FX", "TF", "GF", "PF", "DE", "GE", "GI", "GM", "GA", "GH", "GG", "GU", "GP", "GT", "GY", "GN", "GW", "GD", "GL", "DK", "DO", "EH", "CH", "GR", "SV", "ER", "EE", "EU", "ZM", "ZW", "SZ", "AE", "US", "GB", "EA", "JP", "IN", "ID", "JO", "IQ", "IR", "IE", "GQ", "EC", "IS", "ES", "IL", "IT", "KZ", "CM", "KH", "CA", "IC", "QA", "CF", "KE", "CN", "KG", "KI", "CO", "KM", "CD", "CG", "CR", "CU", "KW", "HR", "CY", "LA", "LS", "LV", "BY", "LB", "LR", "LY", "LT", "LI", "LU", "YT", "MG", "MO", "MY", "MW", "MV", "ML", "MT", "MA", "MQ", "MU", "MR", "ME", "MX", "MM", "FM", "MN", "MZ", "MD", "MC", "MS", "BD", "BB", "BS", "BH", "BZ", "BJ", "BW", "BF", "BI", "BT", "BN", "NA", "NR", "NZ", "NC", "NP", "AX", "MP", "KY", "CC", "CK", "MH", "WF", "SJ", "SB", "TC", "FO", "FK", "HM", "AC", "CP", "IM", "BV", "NF", "CX", "NE", "NG", "NI", "NU", "NO", "ZA", "GS", "KR", "DG", "DM", "NL", "AN", "OM", "HN", "HU", "UG", "UZ", "UA", "UY", "PK", "PS", "PW", "PA", "PG", "PY", "MK", "QO", "PE", "PN", "PL", "PT", "PR", "CV", "RE", "RW", "RO", "RU", "KN", "PM", "WS", "ST", "SA", "SN", "RS", "CS", "SC", "SG", "SL", "SK", "SI", "SO", "SD", "SE", "SR", "LK", "SY", "TW", "TH", "TZ", "TJ", "JM", "DJ", "TG", "TK", "TO", "TV", "TR", "TM", "TT", "TA", "TD", "CZ", "TN", "YE", "JE", "PH", "FI", "FJ", "CL", "HK", }; } @Override protected void loadNameMapJava() { super.loadNameMapJava(); namesMap.put("AD", "Ἀνδόρα"); namesMap.put("AE", "Ἠνωμένα Ἀραβικὰ Ἐμιράτα"); namesMap.put("AF", "Ἀφγανιστάν"); namesMap.put("AG", "Ἀντίγκουα καὶ Μπαρμπούντα"); namesMap.put("AI", "Ἀνγκουίλα"); namesMap.put("AL", "Ἀλβανία"); namesMap.put("AM", "Ἀρμενία"); namesMap.put("AN", "Ὁλλανδικὲς Ἀντίλλες"); namesMap.put("AO", "Ἀνγκόλα"); namesMap.put("AQ", "Ἀνταρκτική"); namesMap.put("AR", "Ἀργεντινή"); namesMap.put("AS", "Ἀμερικανικὴ Σαμόα"); namesMap.put("AT", "Αὐστρία"); namesMap.put("AU", "Αὐστραλία"); namesMap.put("AW", "Ἀρούμπα"); namesMap.put("AZ", "Ἀζερμπαϊτζάν"); namesMap.put("BA", "Βοσνία - Ἐρζεγοβίνη"); namesMap.put("BM", "Βερμοῦδες"); namesMap.put("BV", "Νῆσος Μπουβέ"); namesMap.put("CC", "Νῆσοι Κόκος (Κήλινγκ)"); namesMap.put("CD", "Κονγκό, Λαϊκὴ Δημοκρατία τοῦ"); namesMap.put("CF", "Κεντροαφρικανικὴ Δημοκρατία"); namesMap.put("CH", "Ἑλβετία"); namesMap.put("CI", "Ἀκτὴ Ἐλεφαντοστού"); namesMap.put("CK", "Νῆσοι Κούκ"); namesMap.put("CV", "Πράσινο Ἀκρωτήριο"); namesMap.put("CX", "Νῆσος Χριστουγέννων"); namesMap.put("DO", "Δομινικανὴ Δημοκρατία"); namesMap.put("DZ", "Ἀλγερία"); namesMap.put("EC", "Ἰσημερινός"); namesMap.put("EE", "Ἐσθονία"); namesMap.put("EG", "Αἴγυπτος"); namesMap.put("EH", "Δυτικὴ Σαχάρα"); namesMap.put("ER", "Ἐρυθραία"); namesMap.put("ES", "Ἱσπανία"); namesMap.put("ET", "Αἰθιοπία"); namesMap.put("EU", "Εὐρωπαϊκὴ ᾿Ένωση"); namesMap.put("FM", "Μικρονησία, Ὁμόσπονδες Πολιτεῖες τῆς"); namesMap.put("FO", "Νῆσοι Φερόες"); namesMap.put("GB", "Ἡνωμένο Βασίλειο"); namesMap.put("GF", "Γαλλικὴ Γουιάνα"); namesMap.put("GQ", "Ἰσημερινὴ Γουινέα"); namesMap.put("GR", "Ἑλλάδα"); namesMap.put("GS", "Νότια Γεωργία καὶ Νότιες Νήσοι Σάντουιτς"); namesMap.put("HK", "Χὸνγκ Κόνγκ, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας"); namesMap.put("HM", "Νῆσοι Χὲρντ καὶ Μακντόναλντ"); namesMap.put("HN", "Ὁνδούρα"); namesMap.put("HT", "Ἁϊτή"); namesMap.put("HU", "Οὑγγαρία"); namesMap.put("ID", "Ἰνδονησία"); namesMap.put("IE", "Ἰρλανδία"); namesMap.put("IL", "Ἰσραήλ"); namesMap.put("IN", "Ἰνδία"); namesMap.put("IO", "Βρετανικὰ Ἐδάφη Ἰνδικοῦ Ὠκεανοῦ"); namesMap.put("IQ", "Ἰράκ"); namesMap.put("IR", "Ἰράν, Ἰσλαμικὴ Δημοκρατία τοῦ"); namesMap.put("IS", "Ἰσλανδία"); namesMap.put("IT", "Ἰταλία"); namesMap.put("JO", "Ἰορδανία"); namesMap.put("JP", "Ἰαπωνία"); namesMap.put("KN", "Σαὶντ Κὶτς καὶ Νέβις"); namesMap.put("KY", "Νῆσοι Κέιμαν"); namesMap.put("LA", "Λατινικὴ Ἀμερική"); namesMap.put("LC", "Ἁγία Λουκία"); namesMap.put("LK", "Σρὶ Λάνκα"); namesMap.put("LU", "Λουξεμβοῦργο"); namesMap.put("MD", "Μολδαβία, Δημοκρατία τῆς"); namesMap.put("MH", "Νῆσοι Μάρσαλ"); namesMap.put("ML", "Μαλί"); namesMap.put("MO", "Μακάο, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας"); namesMap.put("MP", "Νῆσοι Βόρειες Μαριάνες"); namesMap.put("NF", "Νῆσος Νόρφολκ"); namesMap.put("NL", "Ὁλλανδία"); namesMap.put("OM", "Ὀμάν"); namesMap.put("PF", "Γαλλικὴ Πολυνησία"); namesMap.put("PM", "Σαὶντ Πιὲρ καὶ Μικελόν"); namesMap.put("PS", "Παλαιστινιακὰ Ἐδάφη"); namesMap.put("SA", "Σαουδικὴ Ἀραβία"); namesMap.put("SB", "Νῆσοι Σολομῶντος"); namesMap.put("SH", "Ἁγία Ἑλένη"); namesMap.put("SJ", "Νῆσοι Σβάλμπαρ καὶ Γιὰν Μαγιέν"); namesMap.put("SM", "Ἅγιος Μαρίνος"); namesMap.put("ST", "Σάο Τομὲ καὶ Πρίνσιπε"); namesMap.put("SV", "Ἒλ Σαλβαδόρ"); namesMap.put("SY", "Συρία, Ἀραβικὴ Δημοκρατία τῆς"); namesMap.put("TC", "Νῆσοι Τὲρκς καὶ Κάικος"); namesMap.put("TD", "Τσάντ"); namesMap.put("TF", "Γαλλικὰ Νότια Ἐδάφη"); namesMap.put("TL", "Ἀνατολικὸ Τιμόρ"); namesMap.put("TT", "Τρινιδὰδ καὶ Τομπάγκο"); namesMap.put("UA", "Οὐκρανία"); namesMap.put("UG", "Οὐγκάντα"); namesMap.put("UM", "Ἀπομακρυσμένες Νησίδες τῶν Ἡνωμένων Πολιτειῶν"); namesMap.put("US", "Ἡνωμένες Πολιτεῖες"); namesMap.put("UY", "Οὐρουγουάη"); namesMap.put("UZ", "Οὐζμπεκιστάν"); namesMap.put("VA", "Ἁγία Ἕδρα (Βατικανό)"); namesMap.put("VC", "Ἅγιος Βικέντιος καὶ Γρεναδίνες"); namesMap.put("VG", "Βρετανικὲς Παρθένοι Νῆσοι"); namesMap.put("VI", "Ἀμερικανικὲς Παρθένοι Νῆσοι"); namesMap.put("WF", "Νῆσοι Οὐάλλις καὶ Φουτουνά"); namesMap.put("YE", "Ὑεμένη"); namesMap.put("ZA", "Νότια Ἀφρική"); } @Override protected JavaScriptObject loadNameMapNative() { return overrideMap(super.loadNameMapNative(), loadMyNameMap()); } private native JavaScriptObject loadMyNameMap() /*-{ <SUF>*/; }
5386_3
/* * Copyright 2013 SciFY NPO <[email protected]>. * * This product is part of the NewSum Free Software. * For more information about NewSum visit * * http://www.scify.gr/site/en/our-projects/completed-projects/newsum-menu-en * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * If this code or its output is used, extended, re-engineered, integrated, * or embedded to any extent in another software or hardware, there MUST be * an explicit attribution to this work in the resulting source code, * the packaging (where such packaging exists), or user interface * (where such an interface exists). * The attribution must be of the form "Powered by NewSum, SciFY" */ package org.scify.NewSumServer.Server.MachineLearning; import gr.demokritos.iit.jinsect.documentModel.representations.DocumentNGramSymWinGraph; import gr.demokritos.iit.jinsect.storage.INSECTDB; import gr.demokritos.iit.conceptualIndex.structs.Distribution; import java.util.ArrayList; import java.util.Arrays; import javax.swing.text.StyledEditorKit; /** * Create a server to do all important actions for the Article labeling Contains * two methods. One for feeding the classifier with data and one for labeling * * @author panagiotis */ public class classificationModule { public INSECTDB file = new INSECTDBWithDir("", "./data/MachineLearningData"); // public static void main(String[] args){ // // // // System.out.println(getCategory("Ο ηθοποιός Ντάνιελ Ντέι Λούις έρχεται ξανά στην Αθήνα προκειμένου να βοηθήσει τους σκοπούς της Εταιρείας Προστασίας Σπαστικών ")); // // //{Τεχνολογία,Ελλάδα,Αθλητισμός,Κόσμος,Πολιτισμός,Οικονομία,Επιστήμη} // // } /** * * @param categoryName The category that the text belongs to * @param text The text that belongs to the specified category */ public void feedClassifier(String categoryName, String text, boolean mergeGraph) { DocumentNGramSymWinGraph gTextGraph = new DocumentNGramSymWinGraph(); // define graph for the text received gTextGraph.setDataString(text); //read all class names if (mergeGraph) { String[] aCategories = file.getObjectList("cg"); //search if categoryName exists in the .cg list ArrayList<String> lsCategories = new ArrayList<String>(Arrays.asList(aCategories)); if (lsCategories.contains(categoryName)) { //if true merge between the two graphs DocumentNGramSymWinGraph CategoryG = (DocumentNGramSymWinGraph) file.loadObject(categoryName, "cg"); Distribution<String> dClassCounts; String[] counterNames; counterNames = file.getObjectList("counter"); if (counterNames.length == 0) { dClassCounts = new Distribution<String>(); dClassCounts.increaseValue(categoryName, 1.0); file.saveObject(dClassCounts, "mergeCounter", "counter"); double dInstanceCount = dClassCounts.getValue(categoryName); CategoryG.mergeGraph(gTextGraph, 1 / dInstanceCount); } else { dClassCounts = (Distribution<String>) file.loadObject("mergeCounter", "counter"); dClassCounts.increaseValue(categoryName, 1.0); file.saveObject(dClassCounts, "mergeCounter", "counter"); double dInstanceCount = dClassCounts.getValue(categoryName); CategoryG.mergeGraph(gTextGraph, 1 / dInstanceCount); } // file.saveObject(CategoryG, categoryName, "cg"); } else { //if false create new .cg with the current graph and categoryName as a name file.saveObject(gTextGraph, categoryName, "cg"); } } //save in info.txt record with the text and the category name String sID = writeToFile.createTxtFile(categoryName, true); //save the current graph as .ig and name the serial number file.saveObject(gTextGraph, sID, "ig"); } /** * * @param text The article text * @return the category that this text belongs to */ public String getCategory(String text) { /* here begins the labelling process */ String label; DocumentNGramSymWinGraph Textg = new DocumentNGramSymWinGraph(); // define graph for the Text tha i recive Textg.setDataString(text); //Create the text graph String[] categoryArray = file.getObjectList("cg"); //read all class names and we put it in categoryArray if (categoryArray.length == 0) { label = "-none-"; } else { //semLabelling.acquire(); //recommendation for the text label = labelTagging.recommendation(file, text); //semLabelling.release(); } return label; // send the label to client } }
scify/NewSumServer
src/org/scify/NewSumServer/Server/MachineLearning/classificationModule.java
1,464
// System.out.println(getCategory("Ο ηθοποιός Ντάνιελ Ντέι Λούις έρχεται ξανά στην Αθήνα προκειμένου να βοηθήσει τους σκοπούς της Εταιρείας Προστασίας Σπαστικών "));
line_comment
el
/* * Copyright 2013 SciFY NPO <[email protected]>. * * This product is part of the NewSum Free Software. * For more information about NewSum visit * * http://www.scify.gr/site/en/our-projects/completed-projects/newsum-menu-en * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * If this code or its output is used, extended, re-engineered, integrated, * or embedded to any extent in another software or hardware, there MUST be * an explicit attribution to this work in the resulting source code, * the packaging (where such packaging exists), or user interface * (where such an interface exists). * The attribution must be of the form "Powered by NewSum, SciFY" */ package org.scify.NewSumServer.Server.MachineLearning; import gr.demokritos.iit.jinsect.documentModel.representations.DocumentNGramSymWinGraph; import gr.demokritos.iit.jinsect.storage.INSECTDB; import gr.demokritos.iit.conceptualIndex.structs.Distribution; import java.util.ArrayList; import java.util.Arrays; import javax.swing.text.StyledEditorKit; /** * Create a server to do all important actions for the Article labeling Contains * two methods. One for feeding the classifier with data and one for labeling * * @author panagiotis */ public class classificationModule { public INSECTDB file = new INSECTDBWithDir("", "./data/MachineLearningData"); // public static void main(String[] args){ // // // // System.out.println(getCategory("Ο ηθοποιός<SUF> // // //{Τεχνολογία,Ελλάδα,Αθλητισμός,Κόσμος,Πολιτισμός,Οικονομία,Επιστήμη} // // } /** * * @param categoryName The category that the text belongs to * @param text The text that belongs to the specified category */ public void feedClassifier(String categoryName, String text, boolean mergeGraph) { DocumentNGramSymWinGraph gTextGraph = new DocumentNGramSymWinGraph(); // define graph for the text received gTextGraph.setDataString(text); //read all class names if (mergeGraph) { String[] aCategories = file.getObjectList("cg"); //search if categoryName exists in the .cg list ArrayList<String> lsCategories = new ArrayList<String>(Arrays.asList(aCategories)); if (lsCategories.contains(categoryName)) { //if true merge between the two graphs DocumentNGramSymWinGraph CategoryG = (DocumentNGramSymWinGraph) file.loadObject(categoryName, "cg"); Distribution<String> dClassCounts; String[] counterNames; counterNames = file.getObjectList("counter"); if (counterNames.length == 0) { dClassCounts = new Distribution<String>(); dClassCounts.increaseValue(categoryName, 1.0); file.saveObject(dClassCounts, "mergeCounter", "counter"); double dInstanceCount = dClassCounts.getValue(categoryName); CategoryG.mergeGraph(gTextGraph, 1 / dInstanceCount); } else { dClassCounts = (Distribution<String>) file.loadObject("mergeCounter", "counter"); dClassCounts.increaseValue(categoryName, 1.0); file.saveObject(dClassCounts, "mergeCounter", "counter"); double dInstanceCount = dClassCounts.getValue(categoryName); CategoryG.mergeGraph(gTextGraph, 1 / dInstanceCount); } // file.saveObject(CategoryG, categoryName, "cg"); } else { //if false create new .cg with the current graph and categoryName as a name file.saveObject(gTextGraph, categoryName, "cg"); } } //save in info.txt record with the text and the category name String sID = writeToFile.createTxtFile(categoryName, true); //save the current graph as .ig and name the serial number file.saveObject(gTextGraph, sID, "ig"); } /** * * @param text The article text * @return the category that this text belongs to */ public String getCategory(String text) { /* here begins the labelling process */ String label; DocumentNGramSymWinGraph Textg = new DocumentNGramSymWinGraph(); // define graph for the Text tha i recive Textg.setDataString(text); //Create the text graph String[] categoryArray = file.getObjectList("cg"); //read all class names and we put it in categoryArray if (categoryArray.length == 0) { label = "-none-"; } else { //semLabelling.acquire(); //recommendation for the text label = labelTagging.recommendation(file, text); //semLabelling.release(); } return label; // send the label to client } }
32887_3
/** * Copyright 2016 SciFY * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.scify.talkandplay.gui.configuration; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import io.sentry.Sentry; import org.apache.commons.lang3.StringUtils; import org.scify.talkandplay.gui.helpers.GuiHelper; import org.scify.talkandplay.models.User; import org.scify.talkandplay.services.ModuleService; import org.scify.talkandplay.utils.ResourceManager; public class EntertainmentTab extends javax.swing.JPanel { private User user; private GuiHelper guiHelper; private ModuleService moduleService; private ConfigurationPanel parent; protected ResourceManager rm; public EntertainmentTab(User user, ConfigurationPanel parent) { this.user = user; this.guiHelper = new GuiHelper(); this.moduleService = new ModuleService(); this.parent = parent; this.rm = ResourceManager.getInstance(); initComponents(); initCustomComponents(); } private void initCustomComponents() { guiHelper.setCustomTextField(musicPathTextField); guiHelper.setCustomTextField(songSumTextField); guiHelper.setCustomTextField(videoPathTextField); guiHelper.setStepLabelFont(step1Label); guiHelper.setStepLabelFont(step2Label); guiHelper.setStepLabelFont(step3Label); guiHelper.drawButton(saveButton); guiHelper.drawButton(backButton); soundLabel.setVisible(false); errorLabel.setVisible(false); if (user.getEntertainmentModule().getMusicModule().getFolderPath() != null && !user.getEntertainmentModule().getMusicModule().getFolderPath().isEmpty()) { musicPathTextField.setText(user.getEntertainmentModule().getMusicModule().getFolderPath()); } if (user.getEntertainmentModule().getVideoModule().getFolderPath() != null && !user.getEntertainmentModule().getVideoModule().getFolderPath().isEmpty()) { videoPathTextField.setText(user.getEntertainmentModule().getVideoModule().getFolderPath()); } songSumTextField.setText(String.valueOf(user.getEntertainmentModule().getMusicModule().getPlaylistSize())); setListeners(); } private void setListeners() { musicPathTextField.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent me) { JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(rm.getTextOfXMLTag("chooseDirectory")); chooser.setAcceptAllFileFilterUsed(false); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { musicPathTextField.setText(chooser.getSelectedFile().getAbsolutePath()); } } }); videoPathTextField.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent me) { JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(rm.getTextOfXMLTag("chooseDirectory")); chooser.setAcceptAllFileFilterUsed(false); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { videoPathTextField.setText(chooser.getSelectedFile().getAbsolutePath()); } } }); musicPathTextField.addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent fe) { if (rm.getTextOfXMLTag("musicDirectory").equals(musicPathTextField.getText())) { musicPathTextField.setText(""); } } public void focusLost(FocusEvent fe) { if (musicPathTextField.getText().isEmpty()) { musicPathTextField.setText(rm.getTextOfXMLTag("musicDirectory")); } else if (!musicPathTextField.getText().endsWith("/")) { musicPathTextField.setText(musicPathTextField.getText() + "/"); } } }); videoPathTextField.addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent fe) { if (rm.getTextOfXMLTag("videoDirectory").equals(videoPathTextField.getText())) { videoPathTextField.setText(""); } } public void focusLost(FocusEvent fe) { if (videoPathTextField.getText().isEmpty()) { videoPathTextField.setText(rm.getTextOfXMLTag("videoDirectory")); } else if (!videoPathTextField.getText().endsWith("/")) { videoPathTextField.setText(videoPathTextField.getText() + "/"); } } }); songSumTextField.addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent fe) { if (rm.getTextOfXMLTag("amount").equals(songSumTextField.getText())) { songSumTextField.setText(""); } } public void focusLost(FocusEvent fe) { if (songSumTextField.getText().isEmpty()) { songSumTextField.setText(rm.getTextOfXMLTag("amount")); } } }); backButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent me) { parent.goBack(); } }); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { step1Label = new javax.swing.JLabel(); step2Label = new javax.swing.JLabel(); step3Label = new javax.swing.JLabel(); soundLabel = new javax.swing.JLabel(); musicPathTextField = new javax.swing.JTextField(); videoPathTextField = new javax.swing.JTextField(); songSumTextField = new javax.swing.JTextField(); saveButton = new javax.swing.JButton(); errorLabel = new javax.swing.JLabel(); backButton = new javax.swing.JButton(); setBackground(new java.awt.Color(255, 255, 255)); step1Label.setText("1. " + rm.getTextOfXMLTag("chooseMusicDirectory")); step2Label.setText("2. " + rm.getTextOfXMLTag("chooseVideoDirectory")); step3Label.setText("3. " + rm.getTextOfXMLTag("defineAmountOfItemsPerPage")); //soundLabel.setText("4. " + Όρισε ένταση ήχου (ignore this)"); musicPathTextField.setText(rm.getTextOfXMLTag("musicDirectory")); videoPathTextField.setText(rm.getTextOfXMLTag("videoDirectory")); songSumTextField.setText("10"); saveButton.setBackground(new java.awt.Color(75, 161, 69)); saveButton.setFont(saveButton.getFont()); saveButton.setForeground(new java.awt.Color(255, 255, 255)); saveButton.setText(rm.getTextOfXMLTag("saveButton")); saveButton.setBorder(null); saveButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { saveButtonMouseClicked(evt); } }); errorLabel.setForeground(new java.awt.Color(153, 0, 0)); errorLabel.setText("error"); backButton.setBackground(new java.awt.Color(75, 161, 69)); backButton.setFont(backButton.getFont()); backButton.setForeground(new java.awt.Color(255, 255, 255)); backButton.setText(rm.getTextOfXMLTag("backButton")); backButton.setBorder(null); backButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { backButtonMouseClicked(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 454, Short.MAX_VALUE) .addComponent(saveButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(backButton) .addGap(14, 14, 14)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(step1Label) .addComponent(musicPathTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 542, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(step2Label) .addComponent(videoPathTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 542, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(step3Label) .addComponent(songSumTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(soundLabel) .addComponent(errorLabel)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(step1Label) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(musicPathTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(30, 30, 30) .addComponent(step2Label) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(videoPathTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(33, 33, 33) .addComponent(step3Label) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(songSumTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(32, 32, 32) .addComponent(soundLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(errorLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(saveButton) .addComponent(backButton)) .addGap(15, 15, 15)) ); }// </editor-fold>//GEN-END:initComponents private void saveButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_saveButtonMouseClicked if (musicPathTextField.getText().isEmpty() || rm.getTextOfXMLTag("musicDirectory").equals(musicPathTextField.getText()) || !(new File(musicPathTextField.getText()).isDirectory())) { errorLabel.setText(rm.getTextOfXMLTag("errorMusicDirectory")); errorLabel.setVisible(true); } else if (videoPathTextField.getText().isEmpty() || rm.getTextOfXMLTag("videoDirectory").equals(videoPathTextField.getText()) || !(new File(videoPathTextField.getText()).isDirectory())) { errorLabel.setText(rm.getTextOfXMLTag("errorVideoDirectory")); errorLabel.setVisible(true); } else if (songSumTextField.getText().isEmpty() || !StringUtils.isNumeric(songSumTextField.getText())) { errorLabel.setText(rm.getTextOfXMLTag("errorAmountOfSongs")); errorLabel.setVisible(true); } else if (Integer.parseInt(songSumTextField.getText()) < 6 || Integer.parseInt(songSumTextField.getText()) > 10) { errorLabel.setText(rm.getTextOfXMLTag("errorAmountOfSongs2")); errorLabel.setVisible(true); } else { errorLabel.setVisible(false); user.getEntertainmentModule().getMusicModule().setFolderPath(musicPathTextField.getText()); user.getEntertainmentModule().getMusicModule().setPlaylistSize(Integer.parseInt(songSumTextField.getText())); user.getEntertainmentModule().getVideoModule().setFolderPath(videoPathTextField.getText()); user.getEntertainmentModule().getVideoModule().setPlaylistSize(Integer.parseInt(songSumTextField.getText())); try { moduleService.update(user); parent.displayMessage(rm.getTextOfXMLTag("changesSaved")); } catch (Exception ex) { Logger.getLogger(EntertainmentTab.class.getName()).log(Level.SEVERE, null, ex); Sentry.capture(ex.getMessage()); } } }//GEN-LAST:event_saveButtonMouseClicked private void backButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_backButtonMouseClicked // TODO add your handling code here: }//GEN-LAST:event_backButtonMouseClicked // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton backButton; private javax.swing.JLabel errorLabel; private javax.swing.JTextField musicPathTextField; private javax.swing.JButton saveButton; private javax.swing.JTextField songSumTextField; private javax.swing.JLabel soundLabel; private javax.swing.JLabel step1Label; private javax.swing.JLabel step2Label; private javax.swing.JLabel step3Label; private javax.swing.JTextField videoPathTextField; // End of variables declaration//GEN-END:variables }
scify/TalkAndPlay
src/main/java/org/scify/talkandplay/gui/configuration/EntertainmentTab.java
3,468
//soundLabel.setText("4. " + Όρισε ένταση ήχου (ignore this)");
line_comment
el
/** * Copyright 2016 SciFY * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.scify.talkandplay.gui.configuration; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import io.sentry.Sentry; import org.apache.commons.lang3.StringUtils; import org.scify.talkandplay.gui.helpers.GuiHelper; import org.scify.talkandplay.models.User; import org.scify.talkandplay.services.ModuleService; import org.scify.talkandplay.utils.ResourceManager; public class EntertainmentTab extends javax.swing.JPanel { private User user; private GuiHelper guiHelper; private ModuleService moduleService; private ConfigurationPanel parent; protected ResourceManager rm; public EntertainmentTab(User user, ConfigurationPanel parent) { this.user = user; this.guiHelper = new GuiHelper(); this.moduleService = new ModuleService(); this.parent = parent; this.rm = ResourceManager.getInstance(); initComponents(); initCustomComponents(); } private void initCustomComponents() { guiHelper.setCustomTextField(musicPathTextField); guiHelper.setCustomTextField(songSumTextField); guiHelper.setCustomTextField(videoPathTextField); guiHelper.setStepLabelFont(step1Label); guiHelper.setStepLabelFont(step2Label); guiHelper.setStepLabelFont(step3Label); guiHelper.drawButton(saveButton); guiHelper.drawButton(backButton); soundLabel.setVisible(false); errorLabel.setVisible(false); if (user.getEntertainmentModule().getMusicModule().getFolderPath() != null && !user.getEntertainmentModule().getMusicModule().getFolderPath().isEmpty()) { musicPathTextField.setText(user.getEntertainmentModule().getMusicModule().getFolderPath()); } if (user.getEntertainmentModule().getVideoModule().getFolderPath() != null && !user.getEntertainmentModule().getVideoModule().getFolderPath().isEmpty()) { videoPathTextField.setText(user.getEntertainmentModule().getVideoModule().getFolderPath()); } songSumTextField.setText(String.valueOf(user.getEntertainmentModule().getMusicModule().getPlaylistSize())); setListeners(); } private void setListeners() { musicPathTextField.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent me) { JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(rm.getTextOfXMLTag("chooseDirectory")); chooser.setAcceptAllFileFilterUsed(false); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { musicPathTextField.setText(chooser.getSelectedFile().getAbsolutePath()); } } }); videoPathTextField.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent me) { JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(rm.getTextOfXMLTag("chooseDirectory")); chooser.setAcceptAllFileFilterUsed(false); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { videoPathTextField.setText(chooser.getSelectedFile().getAbsolutePath()); } } }); musicPathTextField.addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent fe) { if (rm.getTextOfXMLTag("musicDirectory").equals(musicPathTextField.getText())) { musicPathTextField.setText(""); } } public void focusLost(FocusEvent fe) { if (musicPathTextField.getText().isEmpty()) { musicPathTextField.setText(rm.getTextOfXMLTag("musicDirectory")); } else if (!musicPathTextField.getText().endsWith("/")) { musicPathTextField.setText(musicPathTextField.getText() + "/"); } } }); videoPathTextField.addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent fe) { if (rm.getTextOfXMLTag("videoDirectory").equals(videoPathTextField.getText())) { videoPathTextField.setText(""); } } public void focusLost(FocusEvent fe) { if (videoPathTextField.getText().isEmpty()) { videoPathTextField.setText(rm.getTextOfXMLTag("videoDirectory")); } else if (!videoPathTextField.getText().endsWith("/")) { videoPathTextField.setText(videoPathTextField.getText() + "/"); } } }); songSumTextField.addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent fe) { if (rm.getTextOfXMLTag("amount").equals(songSumTextField.getText())) { songSumTextField.setText(""); } } public void focusLost(FocusEvent fe) { if (songSumTextField.getText().isEmpty()) { songSumTextField.setText(rm.getTextOfXMLTag("amount")); } } }); backButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent me) { parent.goBack(); } }); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { step1Label = new javax.swing.JLabel(); step2Label = new javax.swing.JLabel(); step3Label = new javax.swing.JLabel(); soundLabel = new javax.swing.JLabel(); musicPathTextField = new javax.swing.JTextField(); videoPathTextField = new javax.swing.JTextField(); songSumTextField = new javax.swing.JTextField(); saveButton = new javax.swing.JButton(); errorLabel = new javax.swing.JLabel(); backButton = new javax.swing.JButton(); setBackground(new java.awt.Color(255, 255, 255)); step1Label.setText("1. " + rm.getTextOfXMLTag("chooseMusicDirectory")); step2Label.setText("2. " + rm.getTextOfXMLTag("chooseVideoDirectory")); step3Label.setText("3. " + rm.getTextOfXMLTag("defineAmountOfItemsPerPage")); //soundLabel.setText("4. "<SUF> musicPathTextField.setText(rm.getTextOfXMLTag("musicDirectory")); videoPathTextField.setText(rm.getTextOfXMLTag("videoDirectory")); songSumTextField.setText("10"); saveButton.setBackground(new java.awt.Color(75, 161, 69)); saveButton.setFont(saveButton.getFont()); saveButton.setForeground(new java.awt.Color(255, 255, 255)); saveButton.setText(rm.getTextOfXMLTag("saveButton")); saveButton.setBorder(null); saveButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { saveButtonMouseClicked(evt); } }); errorLabel.setForeground(new java.awt.Color(153, 0, 0)); errorLabel.setText("error"); backButton.setBackground(new java.awt.Color(75, 161, 69)); backButton.setFont(backButton.getFont()); backButton.setForeground(new java.awt.Color(255, 255, 255)); backButton.setText(rm.getTextOfXMLTag("backButton")); backButton.setBorder(null); backButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { backButtonMouseClicked(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 454, Short.MAX_VALUE) .addComponent(saveButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(backButton) .addGap(14, 14, 14)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(step1Label) .addComponent(musicPathTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 542, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(step2Label) .addComponent(videoPathTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 542, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(step3Label) .addComponent(songSumTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(soundLabel) .addComponent(errorLabel)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(step1Label) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(musicPathTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(30, 30, 30) .addComponent(step2Label) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(videoPathTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(33, 33, 33) .addComponent(step3Label) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(songSumTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(32, 32, 32) .addComponent(soundLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(errorLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(saveButton) .addComponent(backButton)) .addGap(15, 15, 15)) ); }// </editor-fold>//GEN-END:initComponents private void saveButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_saveButtonMouseClicked if (musicPathTextField.getText().isEmpty() || rm.getTextOfXMLTag("musicDirectory").equals(musicPathTextField.getText()) || !(new File(musicPathTextField.getText()).isDirectory())) { errorLabel.setText(rm.getTextOfXMLTag("errorMusicDirectory")); errorLabel.setVisible(true); } else if (videoPathTextField.getText().isEmpty() || rm.getTextOfXMLTag("videoDirectory").equals(videoPathTextField.getText()) || !(new File(videoPathTextField.getText()).isDirectory())) { errorLabel.setText(rm.getTextOfXMLTag("errorVideoDirectory")); errorLabel.setVisible(true); } else if (songSumTextField.getText().isEmpty() || !StringUtils.isNumeric(songSumTextField.getText())) { errorLabel.setText(rm.getTextOfXMLTag("errorAmountOfSongs")); errorLabel.setVisible(true); } else if (Integer.parseInt(songSumTextField.getText()) < 6 || Integer.parseInt(songSumTextField.getText()) > 10) { errorLabel.setText(rm.getTextOfXMLTag("errorAmountOfSongs2")); errorLabel.setVisible(true); } else { errorLabel.setVisible(false); user.getEntertainmentModule().getMusicModule().setFolderPath(musicPathTextField.getText()); user.getEntertainmentModule().getMusicModule().setPlaylistSize(Integer.parseInt(songSumTextField.getText())); user.getEntertainmentModule().getVideoModule().setFolderPath(videoPathTextField.getText()); user.getEntertainmentModule().getVideoModule().setPlaylistSize(Integer.parseInt(songSumTextField.getText())); try { moduleService.update(user); parent.displayMessage(rm.getTextOfXMLTag("changesSaved")); } catch (Exception ex) { Logger.getLogger(EntertainmentTab.class.getName()).log(Level.SEVERE, null, ex); Sentry.capture(ex.getMessage()); } } }//GEN-LAST:event_saveButtonMouseClicked private void backButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_backButtonMouseClicked // TODO add your handling code here: }//GEN-LAST:event_backButtonMouseClicked // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton backButton; private javax.swing.JLabel errorLabel; private javax.swing.JTextField musicPathTextField; private javax.swing.JButton saveButton; private javax.swing.JTextField songSumTextField; private javax.swing.JLabel soundLabel; private javax.swing.JLabel step1Label; private javax.swing.JLabel step2Label; private javax.swing.JLabel step3Label; private javax.swing.JTextField videoPathTextField; // End of variables declaration//GEN-END:variables }
1111_12
/** * */ package org.getalp.dbnary.languages.ell; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.apache.jena.rdf.model.Resource; import org.getalp.LangTools; import org.getalp.dbnary.ExtractionFeature; import org.getalp.dbnary.api.IWiktionaryDataHandler; import org.getalp.dbnary.api.WiktionaryPageSource; import org.getalp.dbnary.languages.AbstractWiktionaryExtractor; import org.getalp.dbnary.wiki.WikiPatterns; import org.getalp.dbnary.wiki.WikiText; import org.getalp.dbnary.wiki.WikiText.Heading; import org.getalp.dbnary.wiki.WikiText.IndentedItem; import org.getalp.dbnary.wiki.WikiText.ListItem; import org.getalp.dbnary.wiki.WikiText.NumberedListItem; import org.getalp.dbnary.wiki.WikiText.Template; import org.getalp.dbnary.wiki.WikiText.Text; import org.getalp.dbnary.wiki.WikiText.Token; import org.getalp.dbnary.wiki.WikiText.WikiContent; import org.getalp.dbnary.wiki.WikiText.WikiDocument; import org.getalp.dbnary.wiki.WikiText.WikiSection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Barry */ public class WiktionaryExtractor extends AbstractWiktionaryExtractor { private final Logger log = LoggerFactory.getLogger(WiktionaryExtractor.class); protected final static String definitionPatternString = // "(?:^#{1,2}([^\\*#:].*))|(?:^\\*([^\\*#:].*))$"; "^(?:#{1,2}([^\\*#:].*)|\\*([^\\*#:].*))$"; protected final static String pronPatternString = "\\{\\{ΔΦΑ\\|([^\\|\\}]*)(.*)\\}\\}"; // protected final static Pattern languageSectionPattern; private static HashSet<String> posMacros; private static HashSet<String> ignoredSection; private final static HashMap<String, String> nymMarkerToNymName; private static void addPos(String pos) { posMacros.add(pos); if (pos.contains(" ")) { posMacros.add(pos.replaceAll(" ", "_")); } } static { posMacros = new HashSet<>(20); // defMarkers.add("ουσιαστικό"); // Noun // defMarkers.add("επίθετο"); // Adjective // // defMarkers.add("μορφή επιθέτου"); // Adjective // defMarkers.add("επίρρημα"); //Adverb // // defMarkers.add("μορφή ρήματος"); // Verb form // defMarkers.add("ρήμα"); // Verb // defMarkers.add("κύριο όνομα"); //Proper noun // defMarkers.add("παροιμία"); // Proverb // defMarkers.add("πολυλεκτικός όρος");// Multi word term // defMarkers.add("ρηματική έκφραση"); // Verbal Expressions // defMarkers.add("επιφώνημα"); // interjection // defMarkers.add("επιρρηματική έκφραση"); // adverbial expression // defMarkers.add("μετοχή"); // both adjective and verbs addPos("αντωνυμία"); addPos("απαρέμφατο"); addPos("άρθρο"); addPos("αριθμητικό"); addPos("γερουνδιακό"); addPos("γερούνδιο"); addPos("έκφραση"); addPos("επιθετική έκφραση"); addPos("επίθετο"); addPos("επίθημα"); addPos("επίρρημα"); addPos("επιρρηματική έκφραση"); addPos("επιφώνημα"); addPos("κατάληξη"); addPos("κατάληξη αρσενικών επιθέτων"); addPos("κατάληξη αρσενικών και θηλυκών ουσιαστικών"); addPos("κατάληξη αρσενικών ουσιαστικών"); addPos("κατάληξη επιρρημάτων"); addPos("κατάληξη θηλυκών ουσιαστικών"); addPos("κατάληξη ουδέτερων ουσιαστικών"); addPos("κατάληξη ρημάτων"); addPos("κύριο όνομα"); addPos("μετοχή"); addPos("μόριο"); addPos("μορφή αντωνυμίας"); addPos("μορφή αριθμητικού"); addPos("μορφή γερουνδιακού"); addPos("μορφή επιθέτου"); addPos("μορφή επιρρήματος"); addPos("μορφή κυρίου ονόματος"); addPos("μορφή μετοχής"); addPos("μορφή ουσιαστικού"); addPos("μορφή πολυλεκτικού όρου"); addPos("μορφή ρήματος"); addPos("ουσιαστικό"); addPos("παροιμία"); addPos("πολυλεκτικός όρος"); addPos("πρόθεση"); addPos("προθετική έκφραση"); addPos("πρόθημα"); addPos("πρόσφυμα"); addPos("ρήμα"); addPos("ρηματική έκφραση"); addPos("ρίζα"); addPos("σουπίνο"); addPos("συγχώνευση"); addPos("σύμβολο"); addPos("συνδεσμική έκφραση"); addPos("σύνδεσμος"); addPos("συντομομορφή"); addPos("φράση"); addPos("χαρακτήρας"); addPos("ένθημα"); addPos("μεταγραφή"); // A transcription from another language... addPos("μορφή άρθρου"); // Clitic article type... addPos("μορφή επιθήματοςς"); // Clitic suffix... addPos("μορφή επιθήματος"); // Clitic suffix... nymMarkerToNymName = new HashMap<>(20); nymMarkerToNymName.put("συνώνυμα", "syn"); nymMarkerToNymName.put("συνώνυμο", "syn"); nymMarkerToNymName.put("συνων", "syn"); nymMarkerToNymName.put("ταυτόσημα", "syn"); nymMarkerToNymName.put("αντώνυμα", "ant"); nymMarkerToNymName.put("αντώνυμο", "ant"); nymMarkerToNymName.put("αντών", "ant"); nymMarkerToNymName.put("hyponyms", "hypo"); nymMarkerToNymName.put("υπώνυμα", "hypo"); nymMarkerToNymName.put("hypernyms", "hyper"); nymMarkerToNymName.put("υπερώνυμα", "hyper"); nymMarkerToNymName.put("meronyms", "mero"); nymMarkerToNymName.put("μερώνυμα", "mero"); ignoredSection = new HashSet<>(20); ignoredSection.add("άλλες γραφές"); // TODO: Other forms ignoredSection.add("μορφές"); // TODO: Other forms ignoredSection.add("άλλες μορφές"); // TODO: Other forms (is there a difference with the // previous one ?) ignoredSection.add("άλλη γραφή"); // TODO: Other forms (???) ignoredSection.add("αλλόγλωσσα"); // Foreign language derivatives ignoredSection.add("αναγραμματισμοί"); // Anagrams ignoredSection.add("βλέπε"); // See also ignoredSection.add("βλ"); // See also ignoredSection.add("κοιτ"); // See also ignoredSection.add("εκφράσεις"); // Expressions ignoredSection.add("κλίση"); // TODO: Conjugations ignoredSection.add("υποκοριστικά"); // diminutive (?) ignoredSection.add("μεγεθυντικά"); // Augmentative (?) ignoredSection.add("μεταγραφές"); // Transcriptions ignoredSection.add("ομώνυμα"); // Homonym / Similar ignoredSection.add("παράγωγα"); // Derived words ignoredSection.add("πηγές"); // Sources ignoredSection.add("πηγή"); // Sources ignoredSection.add("πολυλεκτικοί όροι"); // Multilingual Terms ? ignoredSection.add("σημείωση"); // Notes ignoredSection.add("σημειώσεις"); // Notes ignoredSection.add("συγγενικά"); // Related words ignoredSection.add("σύνθετα"); // Compound words ignoredSection.add("αναφορές"); // References ignoredSection.add("παροιμίες"); // Proverbs ignoredSection.add("ρηματική φωνή"); // Forms verbales } // Non standard language codes used in Greek edition static { NON_STANDARD_LANGUAGE_MAPPINGS.put("conv", "mul-conv"); } protected final static Pattern pronPattern; private static final Pattern definitionPattern; static { pronPattern = Pattern.compile(pronPatternString); definitionPattern = Pattern.compile(definitionPatternString, Pattern.MULTILINE); } protected GreekDefinitionExtractorWikiModel definitionExpander; public WiktionaryExtractor(IWiktionaryDataHandler wdh) { super(wdh); } @Override public void setWiktionaryIndex(WiktionaryPageSource wi) { super.setWiktionaryIndex(wi); definitionExpander = new GreekDefinitionExtractorWikiModel(this.wdh, this.wi, new Locale("el"), "/${image}", "/${title}"); } @Override protected void setWiktionaryPageName(String wiktionaryPageName) { super.setWiktionaryPageName(wiktionaryPageName); definitionExpander.setPageName(this.getWiktionaryPageName()); } public void extractData() { wdh.initializePageExtraction(getWiktionaryPageName()); WikiText page = new WikiText(getWiktionaryPageName(), pageContent); WikiDocument doc = page.asStructuredDocument(); doc.getContent().wikiTokens().stream().filter(t -> t instanceof WikiSection) .map(Token::asWikiSection).forEach(this::extractSection); wdh.finalizePageExtraction(); } private void extractSection(WikiSection section) { Optional<String> language = sectionLanguage(section); language.ifPresent(l -> extractLanguageSection(section, l)); } private final static Pattern languageTemplate = Pattern.compile("-(.+)-"); public static Optional<String> sectionLanguage(WikiSection section) { if (section.getHeading().getLevel() == 2) { return section.getHeading().getContent().templatesOnUpperLevel().stream() .map(Token::asTemplate).map(Template::getName).map(name -> { Matcher m = languageTemplate.matcher(name); return m.matches() ? m.group(1) : null; }).filter(Objects::nonNull).findFirst(); } return Optional.empty(); } private void extractLanguageSection(WikiSection languageSection, String language) { if (null == language) { return; } if (null == wdh.getExolexFeatureBox(ExtractionFeature.MAIN) && !wdh.getExtractedLanguage().equals(language)) { return; } // The language is always defined when arriving here, but we should check if we extract it String normalizedLanguage = validateAndStandardizeLanguageCode(language); if (normalizedLanguage == null) { log.trace("Ignoring language section {} for {}", language, getWiktionaryPageName()); return; } wdh.initializeLanguageSection(normalizedLanguage); for (Token t : languageSection.getContent().headers()) { Heading heading = t.asHeading(); Pair<Template, String> templateAndTitle = sectionType(heading); Template title = templateAndTitle.getLeft(); String sectionName = templateAndTitle.getRight(); String pos; if ("ετυμολογία".equals(sectionName)) { // NOTHING YET } else if ("μεταφράσεις".equals(sectionName)) { // Translations extractTranslations(heading.getSection().getPrologue().getText()); } else if ("προφορά".equals(sectionName)) { // pronunciation extractPron(heading.getSection().getPrologue()); } else if ((posMacros.contains(sectionName))) { wdh.initializeLexicalEntry(sectionName); extractDefinitions(heading.getSection().getPrologue()); } else if (nymMarkerToNymName.containsKey(sectionName)) { // Nyms WikiContent prologue = heading.getSection().getPrologue(); extractNyms(nymMarkerToNymName.get(sectionName), prologue.getBeginIndex(), prologue.getEndIndex()); } else if (!ignoredSection.contains(sectionName)) { log.debug("Unexpected title {} in {}", title == null ? sectionName : title.getText(), getWiktionaryPageName()); } } wdh.finalizeLanguageSection(); } private void extractDefinitions(WikiContent prologue) { prologue.wikiTokens().forEach(t -> { if (t instanceof Text) { String txt; if (!"".equals(txt = t.asText().getText().trim())) log.trace("Dangling text inside definition {} in {}", txt, wdh.currentPagename()); } else if (t instanceof ListItem || t instanceof NumberedListItem) { IndentedItem item = t.asIndentedItem(); if (item.getContent().toString().startsWith(":")) { // It's an example wdh.registerExample(item.getContent().getText().substring(1), null); } else { extractDefinition(item.getContent().getText(), item.getLevel()); } } }); } private Pair<Template, String> sectionType(Heading heading) { List<Token> titleTemplate = heading.getContent().tokens().stream() .filter(t -> !(t instanceof Text && t.asText().getText().replaceAll("\u00A0", "").trim().equals(""))) .collect(Collectors.toList()); if (titleTemplate.size() == 0) { log.trace("Unexpected empty title in {}", getWiktionaryPageName()); return new ImmutablePair<>(null, ""); } if (titleTemplate.size() > 1) { log.trace("Unexpected multi title {} in {}", heading.getText(), getWiktionaryPageName()); } if (!(titleTemplate.get(0) instanceof Template)) { log.trace("Unexpected non template title {} in {}", heading.getText(), getWiktionaryPageName()); return new ImmutablePair<>(null, heading.getContent().getText().toLowerCase().trim()); } return new ImmutablePair<>(titleTemplate.get(0).asTemplate(), titleTemplate.get(0).asTemplate().getName().toLowerCase().trim()); } private void extractTranslations(String source) { Matcher macroMatcher = WikiPatterns.macroPattern.matcher(source); Resource currentGlose = null; while (macroMatcher.find()) { String g1 = macroMatcher.group(1); switch (g1) { case "τ": { String g2 = macroMatcher.group(2); int i1, i2; String lang, word; if (g2 != null && (i1 = g2.indexOf('|')) != -1) { lang = LangTools.normalize(g2.substring(0, i1)); String usage = null; if ((i2 = g2.indexOf('|', i1 + 1)) == -1) { word = g2.substring(i1 + 1); } else { word = g2.substring(i1 + 1, i2); usage = g2.substring(i2 + 1); } lang = GreekLangtoCode.threeLettersCode(lang); if (lang != null) { wdh.registerTranslation(lang, currentGlose, usage, word); } } break; } case "μτφ-αρχή": case "(": { // Get the glose that should help disambiguate the source acception String g2 = macroMatcher.group(2); // Ignore glose if it is a macro if (g2 != null && !g2.startsWith("{{")) { currentGlose = wdh.createGlossResource(g2); } break; } case "μτφ-μέση": // just ignore it break; case "μτφ-τέλος": case ")": // Forget the current glose currentGlose = null; break; } } } private void extractPron(WikiContent pronContent) { pronContent.wikiTokens().stream().filter(t -> t instanceof Template).map(Token::asTemplate) .filter(t -> "ΔΦΑ".equals(t.getName())).forEach(t -> { String pronLg = t.getParsedArg("1"); if (null == pronLg || !pronLg.startsWith(wdh.getCurrentEntryLanguage())) log.trace("Pronunciation language incorrect in section template {} ≠ {} in {}", wdh.getCurrentEntryLanguage(), pronLg, wdh.currentPagename()); wdh.registerPronunciation(t.getParsedArgs().get("2"), wdh.getCurrentEntryLanguage() + "-fonipa"); }); } @Override public void extractDefinition(String definition, int defLevel) { definitionExpander.parseDefinition(definition, defLevel); } }
serasset/dbnary
dbnary-extractor/src/main/java/org/getalp/dbnary/languages/ell/WiktionaryExtractor.java
5,005
// defMarkers.add("επιρρηματική έκφραση"); // adverbial expression
line_comment
el
/** * */ package org.getalp.dbnary.languages.ell; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.apache.jena.rdf.model.Resource; import org.getalp.LangTools; import org.getalp.dbnary.ExtractionFeature; import org.getalp.dbnary.api.IWiktionaryDataHandler; import org.getalp.dbnary.api.WiktionaryPageSource; import org.getalp.dbnary.languages.AbstractWiktionaryExtractor; import org.getalp.dbnary.wiki.WikiPatterns; import org.getalp.dbnary.wiki.WikiText; import org.getalp.dbnary.wiki.WikiText.Heading; import org.getalp.dbnary.wiki.WikiText.IndentedItem; import org.getalp.dbnary.wiki.WikiText.ListItem; import org.getalp.dbnary.wiki.WikiText.NumberedListItem; import org.getalp.dbnary.wiki.WikiText.Template; import org.getalp.dbnary.wiki.WikiText.Text; import org.getalp.dbnary.wiki.WikiText.Token; import org.getalp.dbnary.wiki.WikiText.WikiContent; import org.getalp.dbnary.wiki.WikiText.WikiDocument; import org.getalp.dbnary.wiki.WikiText.WikiSection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Barry */ public class WiktionaryExtractor extends AbstractWiktionaryExtractor { private final Logger log = LoggerFactory.getLogger(WiktionaryExtractor.class); protected final static String definitionPatternString = // "(?:^#{1,2}([^\\*#:].*))|(?:^\\*([^\\*#:].*))$"; "^(?:#{1,2}([^\\*#:].*)|\\*([^\\*#:].*))$"; protected final static String pronPatternString = "\\{\\{ΔΦΑ\\|([^\\|\\}]*)(.*)\\}\\}"; // protected final static Pattern languageSectionPattern; private static HashSet<String> posMacros; private static HashSet<String> ignoredSection; private final static HashMap<String, String> nymMarkerToNymName; private static void addPos(String pos) { posMacros.add(pos); if (pos.contains(" ")) { posMacros.add(pos.replaceAll(" ", "_")); } } static { posMacros = new HashSet<>(20); // defMarkers.add("ουσιαστικό"); // Noun // defMarkers.add("επίθετο"); // Adjective // // defMarkers.add("μορφή επιθέτου"); // Adjective // defMarkers.add("επίρρημα"); //Adverb // // defMarkers.add("μορφή ρήματος"); // Verb form // defMarkers.add("ρήμα"); // Verb // defMarkers.add("κύριο όνομα"); //Proper noun // defMarkers.add("παροιμία"); // Proverb // defMarkers.add("πολυλεκτικός όρος");// Multi word term // defMarkers.add("ρηματική έκφραση"); // Verbal Expressions // defMarkers.add("επιφώνημα"); // interjection // defMarkers.add("επιρρηματική έκφραση");<SUF> // defMarkers.add("μετοχή"); // both adjective and verbs addPos("αντωνυμία"); addPos("απαρέμφατο"); addPos("άρθρο"); addPos("αριθμητικό"); addPos("γερουνδιακό"); addPos("γερούνδιο"); addPos("έκφραση"); addPos("επιθετική έκφραση"); addPos("επίθετο"); addPos("επίθημα"); addPos("επίρρημα"); addPos("επιρρηματική έκφραση"); addPos("επιφώνημα"); addPos("κατάληξη"); addPos("κατάληξη αρσενικών επιθέτων"); addPos("κατάληξη αρσενικών και θηλυκών ουσιαστικών"); addPos("κατάληξη αρσενικών ουσιαστικών"); addPos("κατάληξη επιρρημάτων"); addPos("κατάληξη θηλυκών ουσιαστικών"); addPos("κατάληξη ουδέτερων ουσιαστικών"); addPos("κατάληξη ρημάτων"); addPos("κύριο όνομα"); addPos("μετοχή"); addPos("μόριο"); addPos("μορφή αντωνυμίας"); addPos("μορφή αριθμητικού"); addPos("μορφή γερουνδιακού"); addPos("μορφή επιθέτου"); addPos("μορφή επιρρήματος"); addPos("μορφή κυρίου ονόματος"); addPos("μορφή μετοχής"); addPos("μορφή ουσιαστικού"); addPos("μορφή πολυλεκτικού όρου"); addPos("μορφή ρήματος"); addPos("ουσιαστικό"); addPos("παροιμία"); addPos("πολυλεκτικός όρος"); addPos("πρόθεση"); addPos("προθετική έκφραση"); addPos("πρόθημα"); addPos("πρόσφυμα"); addPos("ρήμα"); addPos("ρηματική έκφραση"); addPos("ρίζα"); addPos("σουπίνο"); addPos("συγχώνευση"); addPos("σύμβολο"); addPos("συνδεσμική έκφραση"); addPos("σύνδεσμος"); addPos("συντομομορφή"); addPos("φράση"); addPos("χαρακτήρας"); addPos("ένθημα"); addPos("μεταγραφή"); // A transcription from another language... addPos("μορφή άρθρου"); // Clitic article type... addPos("μορφή επιθήματοςς"); // Clitic suffix... addPos("μορφή επιθήματος"); // Clitic suffix... nymMarkerToNymName = new HashMap<>(20); nymMarkerToNymName.put("συνώνυμα", "syn"); nymMarkerToNymName.put("συνώνυμο", "syn"); nymMarkerToNymName.put("συνων", "syn"); nymMarkerToNymName.put("ταυτόσημα", "syn"); nymMarkerToNymName.put("αντώνυμα", "ant"); nymMarkerToNymName.put("αντώνυμο", "ant"); nymMarkerToNymName.put("αντών", "ant"); nymMarkerToNymName.put("hyponyms", "hypo"); nymMarkerToNymName.put("υπώνυμα", "hypo"); nymMarkerToNymName.put("hypernyms", "hyper"); nymMarkerToNymName.put("υπερώνυμα", "hyper"); nymMarkerToNymName.put("meronyms", "mero"); nymMarkerToNymName.put("μερώνυμα", "mero"); ignoredSection = new HashSet<>(20); ignoredSection.add("άλλες γραφές"); // TODO: Other forms ignoredSection.add("μορφές"); // TODO: Other forms ignoredSection.add("άλλες μορφές"); // TODO: Other forms (is there a difference with the // previous one ?) ignoredSection.add("άλλη γραφή"); // TODO: Other forms (???) ignoredSection.add("αλλόγλωσσα"); // Foreign language derivatives ignoredSection.add("αναγραμματισμοί"); // Anagrams ignoredSection.add("βλέπε"); // See also ignoredSection.add("βλ"); // See also ignoredSection.add("κοιτ"); // See also ignoredSection.add("εκφράσεις"); // Expressions ignoredSection.add("κλίση"); // TODO: Conjugations ignoredSection.add("υποκοριστικά"); // diminutive (?) ignoredSection.add("μεγεθυντικά"); // Augmentative (?) ignoredSection.add("μεταγραφές"); // Transcriptions ignoredSection.add("ομώνυμα"); // Homonym / Similar ignoredSection.add("παράγωγα"); // Derived words ignoredSection.add("πηγές"); // Sources ignoredSection.add("πηγή"); // Sources ignoredSection.add("πολυλεκτικοί όροι"); // Multilingual Terms ? ignoredSection.add("σημείωση"); // Notes ignoredSection.add("σημειώσεις"); // Notes ignoredSection.add("συγγενικά"); // Related words ignoredSection.add("σύνθετα"); // Compound words ignoredSection.add("αναφορές"); // References ignoredSection.add("παροιμίες"); // Proverbs ignoredSection.add("ρηματική φωνή"); // Forms verbales } // Non standard language codes used in Greek edition static { NON_STANDARD_LANGUAGE_MAPPINGS.put("conv", "mul-conv"); } protected final static Pattern pronPattern; private static final Pattern definitionPattern; static { pronPattern = Pattern.compile(pronPatternString); definitionPattern = Pattern.compile(definitionPatternString, Pattern.MULTILINE); } protected GreekDefinitionExtractorWikiModel definitionExpander; public WiktionaryExtractor(IWiktionaryDataHandler wdh) { super(wdh); } @Override public void setWiktionaryIndex(WiktionaryPageSource wi) { super.setWiktionaryIndex(wi); definitionExpander = new GreekDefinitionExtractorWikiModel(this.wdh, this.wi, new Locale("el"), "/${image}", "/${title}"); } @Override protected void setWiktionaryPageName(String wiktionaryPageName) { super.setWiktionaryPageName(wiktionaryPageName); definitionExpander.setPageName(this.getWiktionaryPageName()); } public void extractData() { wdh.initializePageExtraction(getWiktionaryPageName()); WikiText page = new WikiText(getWiktionaryPageName(), pageContent); WikiDocument doc = page.asStructuredDocument(); doc.getContent().wikiTokens().stream().filter(t -> t instanceof WikiSection) .map(Token::asWikiSection).forEach(this::extractSection); wdh.finalizePageExtraction(); } private void extractSection(WikiSection section) { Optional<String> language = sectionLanguage(section); language.ifPresent(l -> extractLanguageSection(section, l)); } private final static Pattern languageTemplate = Pattern.compile("-(.+)-"); public static Optional<String> sectionLanguage(WikiSection section) { if (section.getHeading().getLevel() == 2) { return section.getHeading().getContent().templatesOnUpperLevel().stream() .map(Token::asTemplate).map(Template::getName).map(name -> { Matcher m = languageTemplate.matcher(name); return m.matches() ? m.group(1) : null; }).filter(Objects::nonNull).findFirst(); } return Optional.empty(); } private void extractLanguageSection(WikiSection languageSection, String language) { if (null == language) { return; } if (null == wdh.getExolexFeatureBox(ExtractionFeature.MAIN) && !wdh.getExtractedLanguage().equals(language)) { return; } // The language is always defined when arriving here, but we should check if we extract it String normalizedLanguage = validateAndStandardizeLanguageCode(language); if (normalizedLanguage == null) { log.trace("Ignoring language section {} for {}", language, getWiktionaryPageName()); return; } wdh.initializeLanguageSection(normalizedLanguage); for (Token t : languageSection.getContent().headers()) { Heading heading = t.asHeading(); Pair<Template, String> templateAndTitle = sectionType(heading); Template title = templateAndTitle.getLeft(); String sectionName = templateAndTitle.getRight(); String pos; if ("ετυμολογία".equals(sectionName)) { // NOTHING YET } else if ("μεταφράσεις".equals(sectionName)) { // Translations extractTranslations(heading.getSection().getPrologue().getText()); } else if ("προφορά".equals(sectionName)) { // pronunciation extractPron(heading.getSection().getPrologue()); } else if ((posMacros.contains(sectionName))) { wdh.initializeLexicalEntry(sectionName); extractDefinitions(heading.getSection().getPrologue()); } else if (nymMarkerToNymName.containsKey(sectionName)) { // Nyms WikiContent prologue = heading.getSection().getPrologue(); extractNyms(nymMarkerToNymName.get(sectionName), prologue.getBeginIndex(), prologue.getEndIndex()); } else if (!ignoredSection.contains(sectionName)) { log.debug("Unexpected title {} in {}", title == null ? sectionName : title.getText(), getWiktionaryPageName()); } } wdh.finalizeLanguageSection(); } private void extractDefinitions(WikiContent prologue) { prologue.wikiTokens().forEach(t -> { if (t instanceof Text) { String txt; if (!"".equals(txt = t.asText().getText().trim())) log.trace("Dangling text inside definition {} in {}", txt, wdh.currentPagename()); } else if (t instanceof ListItem || t instanceof NumberedListItem) { IndentedItem item = t.asIndentedItem(); if (item.getContent().toString().startsWith(":")) { // It's an example wdh.registerExample(item.getContent().getText().substring(1), null); } else { extractDefinition(item.getContent().getText(), item.getLevel()); } } }); } private Pair<Template, String> sectionType(Heading heading) { List<Token> titleTemplate = heading.getContent().tokens().stream() .filter(t -> !(t instanceof Text && t.asText().getText().replaceAll("\u00A0", "").trim().equals(""))) .collect(Collectors.toList()); if (titleTemplate.size() == 0) { log.trace("Unexpected empty title in {}", getWiktionaryPageName()); return new ImmutablePair<>(null, ""); } if (titleTemplate.size() > 1) { log.trace("Unexpected multi title {} in {}", heading.getText(), getWiktionaryPageName()); } if (!(titleTemplate.get(0) instanceof Template)) { log.trace("Unexpected non template title {} in {}", heading.getText(), getWiktionaryPageName()); return new ImmutablePair<>(null, heading.getContent().getText().toLowerCase().trim()); } return new ImmutablePair<>(titleTemplate.get(0).asTemplate(), titleTemplate.get(0).asTemplate().getName().toLowerCase().trim()); } private void extractTranslations(String source) { Matcher macroMatcher = WikiPatterns.macroPattern.matcher(source); Resource currentGlose = null; while (macroMatcher.find()) { String g1 = macroMatcher.group(1); switch (g1) { case "τ": { String g2 = macroMatcher.group(2); int i1, i2; String lang, word; if (g2 != null && (i1 = g2.indexOf('|')) != -1) { lang = LangTools.normalize(g2.substring(0, i1)); String usage = null; if ((i2 = g2.indexOf('|', i1 + 1)) == -1) { word = g2.substring(i1 + 1); } else { word = g2.substring(i1 + 1, i2); usage = g2.substring(i2 + 1); } lang = GreekLangtoCode.threeLettersCode(lang); if (lang != null) { wdh.registerTranslation(lang, currentGlose, usage, word); } } break; } case "μτφ-αρχή": case "(": { // Get the glose that should help disambiguate the source acception String g2 = macroMatcher.group(2); // Ignore glose if it is a macro if (g2 != null && !g2.startsWith("{{")) { currentGlose = wdh.createGlossResource(g2); } break; } case "μτφ-μέση": // just ignore it break; case "μτφ-τέλος": case ")": // Forget the current glose currentGlose = null; break; } } } private void extractPron(WikiContent pronContent) { pronContent.wikiTokens().stream().filter(t -> t instanceof Template).map(Token::asTemplate) .filter(t -> "ΔΦΑ".equals(t.getName())).forEach(t -> { String pronLg = t.getParsedArg("1"); if (null == pronLg || !pronLg.startsWith(wdh.getCurrentEntryLanguage())) log.trace("Pronunciation language incorrect in section template {} ≠ {} in {}", wdh.getCurrentEntryLanguage(), pronLg, wdh.currentPagename()); wdh.registerPronunciation(t.getParsedArgs().get("2"), wdh.getCurrentEntryLanguage() + "-fonipa"); }); } @Override public void extractDefinition(String definition, int defLevel) { definitionExpander.parseDefinition(definition, defLevel); } }
931_4
/* * Copyright (c) 2017, salesforce.com, inc. * All rights reserved. * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ package com.force.i18n.grammar.impl; import static com.force.i18n.commons.util.settings.IniFileUtil.intern; import java.util.*; import java.util.logging.Logger; import com.force.i18n.HumanLanguage; import com.force.i18n.commons.text.TrieMatcher; import com.force.i18n.grammar.*; import com.force.i18n.grammar.Noun.NounType; import com.google.common.collect.ImmutableMap; /** * Greek is *not* germanic, but it's close enough for salesforce work. * TODO: This really should be a separate declension from germanic, because only greek has a starts with that's interesting. * * @author stamm */ class GreekDeclension extends GermanicDeclension { private static final Logger logger = Logger.getLogger(GreekDeclension.class.getName()); private final Map<ArticleForm,String> indefiniteOverrides; private final Map<ArticleForm,String> definiteOverrides; public GreekDeclension(HumanLanguage language) { super(language); // Setup the map for "plosive endings" definiteOverrides = ImmutableMap.<ArticleForm, String>of( getArticleForm(LanguageStartsWith.SPECIAL, LanguageGender.MASCULINE, LanguageNumber.SINGULAR, LanguageCase.ACCUSATIVE), "\u03c4\u03bf\u03bd", // τον getArticleForm(LanguageStartsWith.SPECIAL, LanguageGender.FEMININE, LanguageNumber.SINGULAR, LanguageCase.ACCUSATIVE), "\u03c4\u03b7\u03bd"); // την indefiniteOverrides = Collections.singletonMap( getArticleForm(LanguageStartsWith.SPECIAL, LanguageGender.MASCULINE, LanguageNumber.SINGULAR, LanguageCase.ACCUSATIVE), "\u03ad\u03bd\u03b1\u03bd"); // έναν } private final Map<LanguageCase, ImmutableMap<LanguageNumber, ImmutableMap<LanguageGender,String>>> DEFINITE_ARTICLE = ImmutableMap.of( LanguageCase.NOMINATIVE, ImmutableMap.of(LanguageNumber.SINGULAR, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03bf", // το LanguageGender.FEMININE, "\u03b7", // η LanguageGender.MASCULINE, "\u03bf" // ο ), LanguageNumber.PLURAL, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03b1", // τα LanguageGender.FEMININE, "\u03bf\u03b9", // οι LanguageGender.MASCULINE, "\u03bf\u03b9" // οι )), LanguageCase.ACCUSATIVE, ImmutableMap.of(LanguageNumber.SINGULAR, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03bf", // το LanguageGender.FEMININE, "\u03c4\u03b7", // τη(ν) LanguageGender.MASCULINE, "\u03c4\u03bf" // το(ν) ), LanguageNumber.PLURAL, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03b1", // τα LanguageGender.FEMININE, "\u03c4\u03b9\u03c2", // τις LanguageGender.MASCULINE, "\u03c4\u03bf\u03c5\u03c2" // τους )), LanguageCase.GENITIVE, ImmutableMap.of(LanguageNumber.SINGULAR, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03bf\u03c5", // του LanguageGender.FEMININE, "\u03c4\u03b7\u03c2", // της LanguageGender.MASCULINE, "\u03c4\u03bf\u03c5" // του ), LanguageNumber.PLURAL, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03c9\u03bd", // των LanguageGender.FEMININE, "\u03c4\u03c9\u03bd", // των LanguageGender.MASCULINE, "\u03c4\u03c9\u03bd" // των )) ); private static final Map<LanguageCase, ImmutableMap<LanguageGender, String>> INDEFINITE_ARTICLE = ImmutableMap.of( LanguageCase.NOMINATIVE, ImmutableMap.of( LanguageGender.NEUTER, "\u03ad\u03bd\u03b1", // ένα LanguageGender.FEMININE, "\u03bc\u03af\u03b1", // μία LanguageGender.MASCULINE, "\u03ad\u03bd\u03b1\u03c2" // ένας ), LanguageCase.ACCUSATIVE, ImmutableMap.of( LanguageGender.NEUTER, "\u03ad\u03bd\u03b1", // ένα LanguageGender.FEMININE, "\u03bc\u03af\u03b1", // μία LanguageGender.MASCULINE, "\u03ad\u03bd\u03b1" // ένα(ν) ), LanguageCase.GENITIVE, ImmutableMap.of( LanguageGender.NEUTER, "\u03b5\u03bd\u03cc\u03c2", // ενός LanguageGender.FEMININE, "\u03bc\u03b9\u03b1\u03c2", // μιας LanguageGender.MASCULINE, "\u03b5\u03bd\u03cc\u03c2" // ενός ) ); public static class GreekNoun extends GermanicNoun { /** * */ private static final long serialVersionUID = 1L; public GreekNoun(GermanicDeclension declension, String name, String pluralAlias, NounType type, String entityName, LanguageGender gender, String access, boolean isStandardField, boolean isCopied) { super(declension, name, pluralAlias, type, entityName, gender, access, isStandardField, isCopied); } @Override public void setString(String value, NounForm form) { super.setString(intern(value), form); if (form == getDeclension().getAllNounForms().get(0)) { setStartsWith(startsWithGreekPlosive(value) ? LanguageStartsWith.SPECIAL : LanguageStartsWith.CONSONANT); } } } @Override protected Noun createNoun(String name, String pluralAlias, NounType type, String entityName, LanguageStartsWith startsWith, LanguageGender gender, String access, boolean isStandardField, boolean isCopied) { return new GreekNoun(this, name, pluralAlias, type, entityName, gender, access, isStandardField, isCopied); } public static boolean startsWithGreekPlosive(String value) { return PLOSIVE_MATCHER.begins(value); } @Override protected EnumSet<LanguageArticle> getRequiredAdjectiveArticles() { return EnumSet.of(LanguageArticle.ZERO); // Greek adjectives are not inflected for definitiveness } @Override protected String getDefaultArticleString(ArticleForm form, LanguageArticle articleType) { switch (articleType) { case DEFINITE: String override = definiteOverrides.get(form); if (override != null) return override; ImmutableMap<LanguageNumber, ImmutableMap<LanguageGender,String>> byCase = DEFINITE_ARTICLE.get(form.getCase()); if (byCase == null) { logger.fine("Trying to retrieve an illegal definite article form in greek"); return ""; } return byCase.get(form.getNumber()).get(form.getGender()); case INDEFINITE: if (form.getNumber() == LanguageNumber.PLURAL) return null; override = indefiniteOverrides.get(form); if (override != null) return override; return INDEFINITE_ARTICLE.get(form.getCase()).get(form.getGender()); default: return null; } } @Override public boolean hasStartsWith() { return true; } // κ, π, τ, μπ, ντ, γκ, τσ, τζ, ξ, ψ private static final String[] PLOSIVES = new String[] {"\u03ba","\u03c0","\u03c4", "\u03bc\u03c0", "\u03bd\u03c4", "\u03b3\u03ba", "\u03c4\u03c3", "\u03c4\u03b6", "\u03be", "\u03c8"}; private static final TrieMatcher PLOSIVE_MATCHER = TrieMatcher.compile(PLOSIVES, PLOSIVES); @Override public boolean hasAutoDerivedStartsWith() { return true; } @Override public EnumSet<LanguageStartsWith> getRequiredStartsWith() { return EnumSet.of(LanguageStartsWith.CONSONANT, LanguageStartsWith.SPECIAL); // Special is plosive in greek. } @Override public EnumSet<LanguageCase> getRequiredCases() { return EnumSet.of(LanguageCase.NOMINATIVE, LanguageCase.ACCUSATIVE, LanguageCase.GENITIVE, LanguageCase.VOCATIVE); } @Override public EnumSet<LanguageGender> getRequiredGenders() { return EnumSet.of(LanguageGender.NEUTER, LanguageGender.FEMININE, LanguageGender.MASCULINE); } @Override public String formLowercaseNounForm(String s, NounForm form) { return hasCapitalization() ? (s == null ? null : s.toLowerCase()) : s; } }
seratch/grammaticus
src/main/java/com/force/i18n/grammar/impl/GreekDeclension.java
2,564
// κ, π, τ, μπ, ντ, γκ, τσ, τζ, ξ, ψ
line_comment
el
/* * Copyright (c) 2017, salesforce.com, inc. * All rights reserved. * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ package com.force.i18n.grammar.impl; import static com.force.i18n.commons.util.settings.IniFileUtil.intern; import java.util.*; import java.util.logging.Logger; import com.force.i18n.HumanLanguage; import com.force.i18n.commons.text.TrieMatcher; import com.force.i18n.grammar.*; import com.force.i18n.grammar.Noun.NounType; import com.google.common.collect.ImmutableMap; /** * Greek is *not* germanic, but it's close enough for salesforce work. * TODO: This really should be a separate declension from germanic, because only greek has a starts with that's interesting. * * @author stamm */ class GreekDeclension extends GermanicDeclension { private static final Logger logger = Logger.getLogger(GreekDeclension.class.getName()); private final Map<ArticleForm,String> indefiniteOverrides; private final Map<ArticleForm,String> definiteOverrides; public GreekDeclension(HumanLanguage language) { super(language); // Setup the map for "plosive endings" definiteOverrides = ImmutableMap.<ArticleForm, String>of( getArticleForm(LanguageStartsWith.SPECIAL, LanguageGender.MASCULINE, LanguageNumber.SINGULAR, LanguageCase.ACCUSATIVE), "\u03c4\u03bf\u03bd", // τον getArticleForm(LanguageStartsWith.SPECIAL, LanguageGender.FEMININE, LanguageNumber.SINGULAR, LanguageCase.ACCUSATIVE), "\u03c4\u03b7\u03bd"); // την indefiniteOverrides = Collections.singletonMap( getArticleForm(LanguageStartsWith.SPECIAL, LanguageGender.MASCULINE, LanguageNumber.SINGULAR, LanguageCase.ACCUSATIVE), "\u03ad\u03bd\u03b1\u03bd"); // έναν } private final Map<LanguageCase, ImmutableMap<LanguageNumber, ImmutableMap<LanguageGender,String>>> DEFINITE_ARTICLE = ImmutableMap.of( LanguageCase.NOMINATIVE, ImmutableMap.of(LanguageNumber.SINGULAR, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03bf", // το LanguageGender.FEMININE, "\u03b7", // η LanguageGender.MASCULINE, "\u03bf" // ο ), LanguageNumber.PLURAL, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03b1", // τα LanguageGender.FEMININE, "\u03bf\u03b9", // οι LanguageGender.MASCULINE, "\u03bf\u03b9" // οι )), LanguageCase.ACCUSATIVE, ImmutableMap.of(LanguageNumber.SINGULAR, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03bf", // το LanguageGender.FEMININE, "\u03c4\u03b7", // τη(ν) LanguageGender.MASCULINE, "\u03c4\u03bf" // το(ν) ), LanguageNumber.PLURAL, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03b1", // τα LanguageGender.FEMININE, "\u03c4\u03b9\u03c2", // τις LanguageGender.MASCULINE, "\u03c4\u03bf\u03c5\u03c2" // τους )), LanguageCase.GENITIVE, ImmutableMap.of(LanguageNumber.SINGULAR, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03bf\u03c5", // του LanguageGender.FEMININE, "\u03c4\u03b7\u03c2", // της LanguageGender.MASCULINE, "\u03c4\u03bf\u03c5" // του ), LanguageNumber.PLURAL, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03c9\u03bd", // των LanguageGender.FEMININE, "\u03c4\u03c9\u03bd", // των LanguageGender.MASCULINE, "\u03c4\u03c9\u03bd" // των )) ); private static final Map<LanguageCase, ImmutableMap<LanguageGender, String>> INDEFINITE_ARTICLE = ImmutableMap.of( LanguageCase.NOMINATIVE, ImmutableMap.of( LanguageGender.NEUTER, "\u03ad\u03bd\u03b1", // ένα LanguageGender.FEMININE, "\u03bc\u03af\u03b1", // μία LanguageGender.MASCULINE, "\u03ad\u03bd\u03b1\u03c2" // ένας ), LanguageCase.ACCUSATIVE, ImmutableMap.of( LanguageGender.NEUTER, "\u03ad\u03bd\u03b1", // ένα LanguageGender.FEMININE, "\u03bc\u03af\u03b1", // μία LanguageGender.MASCULINE, "\u03ad\u03bd\u03b1" // ένα(ν) ), LanguageCase.GENITIVE, ImmutableMap.of( LanguageGender.NEUTER, "\u03b5\u03bd\u03cc\u03c2", // ενός LanguageGender.FEMININE, "\u03bc\u03b9\u03b1\u03c2", // μιας LanguageGender.MASCULINE, "\u03b5\u03bd\u03cc\u03c2" // ενός ) ); public static class GreekNoun extends GermanicNoun { /** * */ private static final long serialVersionUID = 1L; public GreekNoun(GermanicDeclension declension, String name, String pluralAlias, NounType type, String entityName, LanguageGender gender, String access, boolean isStandardField, boolean isCopied) { super(declension, name, pluralAlias, type, entityName, gender, access, isStandardField, isCopied); } @Override public void setString(String value, NounForm form) { super.setString(intern(value), form); if (form == getDeclension().getAllNounForms().get(0)) { setStartsWith(startsWithGreekPlosive(value) ? LanguageStartsWith.SPECIAL : LanguageStartsWith.CONSONANT); } } } @Override protected Noun createNoun(String name, String pluralAlias, NounType type, String entityName, LanguageStartsWith startsWith, LanguageGender gender, String access, boolean isStandardField, boolean isCopied) { return new GreekNoun(this, name, pluralAlias, type, entityName, gender, access, isStandardField, isCopied); } public static boolean startsWithGreekPlosive(String value) { return PLOSIVE_MATCHER.begins(value); } @Override protected EnumSet<LanguageArticle> getRequiredAdjectiveArticles() { return EnumSet.of(LanguageArticle.ZERO); // Greek adjectives are not inflected for definitiveness } @Override protected String getDefaultArticleString(ArticleForm form, LanguageArticle articleType) { switch (articleType) { case DEFINITE: String override = definiteOverrides.get(form); if (override != null) return override; ImmutableMap<LanguageNumber, ImmutableMap<LanguageGender,String>> byCase = DEFINITE_ARTICLE.get(form.getCase()); if (byCase == null) { logger.fine("Trying to retrieve an illegal definite article form in greek"); return ""; } return byCase.get(form.getNumber()).get(form.getGender()); case INDEFINITE: if (form.getNumber() == LanguageNumber.PLURAL) return null; override = indefiniteOverrides.get(form); if (override != null) return override; return INDEFINITE_ARTICLE.get(form.getCase()).get(form.getGender()); default: return null; } } @Override public boolean hasStartsWith() { return true; } // κ, π,<SUF> private static final String[] PLOSIVES = new String[] {"\u03ba","\u03c0","\u03c4", "\u03bc\u03c0", "\u03bd\u03c4", "\u03b3\u03ba", "\u03c4\u03c3", "\u03c4\u03b6", "\u03be", "\u03c8"}; private static final TrieMatcher PLOSIVE_MATCHER = TrieMatcher.compile(PLOSIVES, PLOSIVES); @Override public boolean hasAutoDerivedStartsWith() { return true; } @Override public EnumSet<LanguageStartsWith> getRequiredStartsWith() { return EnumSet.of(LanguageStartsWith.CONSONANT, LanguageStartsWith.SPECIAL); // Special is plosive in greek. } @Override public EnumSet<LanguageCase> getRequiredCases() { return EnumSet.of(LanguageCase.NOMINATIVE, LanguageCase.ACCUSATIVE, LanguageCase.GENITIVE, LanguageCase.VOCATIVE); } @Override public EnumSet<LanguageGender> getRequiredGenders() { return EnumSet.of(LanguageGender.NEUTER, LanguageGender.FEMININE, LanguageGender.MASCULINE); } @Override public String formLowercaseNounForm(String s, NounForm form) { return hasCapitalization() ? (s == null ? null : s.toLowerCase()) : s; } }
911_1
package com.mobile.physiolink.ui.psf; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.navigation.Navigation; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.google.android.material.textfield.TextInputEditText; import com.google.android.material.textfield.TextInputLayout; import com.mobile.physiolink.R; import com.mobile.physiolink.databinding.FragmentCreateServiceBinding; import com.mobile.physiolink.model.service.Service; import com.mobile.physiolink.service.api.error.Error; import com.mobile.physiolink.service.dao.ServiceDAO; import com.mobile.physiolink.ui.popup.ConfirmationPopUp; import java.io.IOException; import java.util.ArrayList; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public class CreateServiceFragment extends Fragment { private FragmentCreateServiceBinding binding; private boolean input_erros; private final ArrayList<TextInputLayout> all_inputs_layouts = new ArrayList<>(); private final ArrayList<TextInputEditText> all_inputs = new ArrayList<>(); public CreateServiceFragment() {} @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment binding = FragmentCreateServiceBinding.inflate(inflater, container, false); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { populateAllInputs(); // Σε αυτή τη λούπα δημιουργήτε ένας onchange listener για κάθε στοιχείο της λίστας for(int j =0; j<all_inputs.size(); j++) { TextInputEditText current = all_inputs.get(j); TextInputLayout current_layout = all_inputs_layouts.get(j); current.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { if (current.getText().length() == 0) { current_layout.setError("Το πεδίο πρέπει να συμπληρωθεί!"); input_erros = true; } else { current_layout.setError(null); current_layout.setHelperText(null); input_erros = false; } } @Override public void afterTextChanged(Editable editable) { } }); } binding.saveButton.setOnClickListener(v -> { for(int i = 0; i< all_inputs.size(); i++){ if(all_inputs.get(i).getText().length() == 0){ all_inputs_layouts.get(i).setError("Το πεδίο πρέπει να συμπληρωθεί!"); input_erros = true; } if(all_inputs.get(i).getText().length() > all_inputs_layouts.get(i).getCounterMaxLength()){ input_erros = true; } } if(input_erros){ Toast.makeText(getActivity(), "Πρέπει να συμπληρώσετε σωστά όλα τα υποχρεωτικά πεδία", Toast.LENGTH_SHORT).show(); } else{ ConfirmationPopUp confirmation = new ConfirmationPopUp("Αποθήκευση", "Είστε σίγουρος για την επιλογή σας;", "Ναι", "Οχι"); confirmation.setPositiveOnClick((dialog, which) -> { Service service = new Service(binding.serviceIdInput.getText().toString(), binding.serviceNameInput.getText().toString(), binding.serviceDescriptionInput.getText().toString(), Double.parseDouble(binding.serviceCostInput.getText().toString())); try { ServiceDAO.getInstance().create(service, new Callback() { @Override public void onFailure(Call call, IOException e) { call.cancel(); } @Override public void onResponse(Call call, Response response) throws IOException { String res = response.body().string(); getActivity().runOnUiThread(() -> { if (res.contains(Error.RESOURCE_EXISTS)) { Toast.makeText(getActivity(), "Υπάρχει παροχή με το ίδιο όνομα/κωδικό", Toast.LENGTH_SHORT).show(); return; } Toast.makeText(getActivity(), "Έγινε αποθήκευση Παροχής!", Toast.LENGTH_SHORT).show(); Navigation.findNavController(getActivity(), R.id.fragmentContainerView) .navigate(R.id.action_fragment_create_service_to_fragment_services); }); } }); } catch (IOException ignored) {} }); confirmation.setNegativeOnClick(((dialog, which) -> { Toast.makeText(getActivity(), "Δεν έγινε αποθήκευση Παροχής!", Toast.LENGTH_SHORT).show(); })); confirmation.show(getActivity().getSupportFragmentManager(), "Confirmation pop up"); } }); } private void populateAllInputs() { all_inputs_layouts.add(binding.serviceCostInputLayout); all_inputs.add(binding.serviceCostInput); all_inputs_layouts.add(binding.serviceNameInputLayout); all_inputs.add(binding.serviceNameInput); all_inputs_layouts.add(binding.serviceIdInputLayout); all_inputs.add(binding.serviceIdInput); all_inputs_layouts.add(binding.serviceDescriptionInputLayout); all_inputs.add(binding.serviceDescriptionInput); } }
setokk/PhysioLink
app/src/main/java/com/mobile/physiolink/ui/psf/CreateServiceFragment.java
1,581
// Σε αυτή τη λούπα δημιουργήτε ένας onchange listener για κάθε στοιχείο της λίστας
line_comment
el
package com.mobile.physiolink.ui.psf; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.navigation.Navigation; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.google.android.material.textfield.TextInputEditText; import com.google.android.material.textfield.TextInputLayout; import com.mobile.physiolink.R; import com.mobile.physiolink.databinding.FragmentCreateServiceBinding; import com.mobile.physiolink.model.service.Service; import com.mobile.physiolink.service.api.error.Error; import com.mobile.physiolink.service.dao.ServiceDAO; import com.mobile.physiolink.ui.popup.ConfirmationPopUp; import java.io.IOException; import java.util.ArrayList; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public class CreateServiceFragment extends Fragment { private FragmentCreateServiceBinding binding; private boolean input_erros; private final ArrayList<TextInputLayout> all_inputs_layouts = new ArrayList<>(); private final ArrayList<TextInputEditText> all_inputs = new ArrayList<>(); public CreateServiceFragment() {} @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment binding = FragmentCreateServiceBinding.inflate(inflater, container, false); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { populateAllInputs(); // Σε αυτή<SUF> for(int j =0; j<all_inputs.size(); j++) { TextInputEditText current = all_inputs.get(j); TextInputLayout current_layout = all_inputs_layouts.get(j); current.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { if (current.getText().length() == 0) { current_layout.setError("Το πεδίο πρέπει να συμπληρωθεί!"); input_erros = true; } else { current_layout.setError(null); current_layout.setHelperText(null); input_erros = false; } } @Override public void afterTextChanged(Editable editable) { } }); } binding.saveButton.setOnClickListener(v -> { for(int i = 0; i< all_inputs.size(); i++){ if(all_inputs.get(i).getText().length() == 0){ all_inputs_layouts.get(i).setError("Το πεδίο πρέπει να συμπληρωθεί!"); input_erros = true; } if(all_inputs.get(i).getText().length() > all_inputs_layouts.get(i).getCounterMaxLength()){ input_erros = true; } } if(input_erros){ Toast.makeText(getActivity(), "Πρέπει να συμπληρώσετε σωστά όλα τα υποχρεωτικά πεδία", Toast.LENGTH_SHORT).show(); } else{ ConfirmationPopUp confirmation = new ConfirmationPopUp("Αποθήκευση", "Είστε σίγουρος για την επιλογή σας;", "Ναι", "Οχι"); confirmation.setPositiveOnClick((dialog, which) -> { Service service = new Service(binding.serviceIdInput.getText().toString(), binding.serviceNameInput.getText().toString(), binding.serviceDescriptionInput.getText().toString(), Double.parseDouble(binding.serviceCostInput.getText().toString())); try { ServiceDAO.getInstance().create(service, new Callback() { @Override public void onFailure(Call call, IOException e) { call.cancel(); } @Override public void onResponse(Call call, Response response) throws IOException { String res = response.body().string(); getActivity().runOnUiThread(() -> { if (res.contains(Error.RESOURCE_EXISTS)) { Toast.makeText(getActivity(), "Υπάρχει παροχή με το ίδιο όνομα/κωδικό", Toast.LENGTH_SHORT).show(); return; } Toast.makeText(getActivity(), "Έγινε αποθήκευση Παροχής!", Toast.LENGTH_SHORT).show(); Navigation.findNavController(getActivity(), R.id.fragmentContainerView) .navigate(R.id.action_fragment_create_service_to_fragment_services); }); } }); } catch (IOException ignored) {} }); confirmation.setNegativeOnClick(((dialog, which) -> { Toast.makeText(getActivity(), "Δεν έγινε αποθήκευση Παροχής!", Toast.LENGTH_SHORT).show(); })); confirmation.show(getActivity().getSupportFragmentManager(), "Confirmation pop up"); } }); } private void populateAllInputs() { all_inputs_layouts.add(binding.serviceCostInputLayout); all_inputs.add(binding.serviceCostInput); all_inputs_layouts.add(binding.serviceNameInputLayout); all_inputs.add(binding.serviceNameInput); all_inputs_layouts.add(binding.serviceIdInputLayout); all_inputs.add(binding.serviceIdInput); all_inputs_layouts.add(binding.serviceDescriptionInputLayout); all_inputs.add(binding.serviceDescriptionInput); } }
20215_5
/** * Copyright (c) 2018-present, A2 Rešitve d.o.o. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package eu.solutions.a2.cdc.oracle; import static org.junit.Assert.fail; import java.sql.SQLException; import org.junit.Test; public class OraDumpDecoderTest { @Test public void test() { // select DUMP('thanks', 16) from DUAL; // Typ=96 Len=6: 74,68,61,6e,6b,73 String sUsAscii = "7468616e6b73"; // select DUMP('謝謝啦', 16) from DUAL; // Typ=96 Len=9: e8,ac,9d,e8,ac,9d,e5,95,a6 String sTrChinese = "e8ac9de8ac9de595a6"; // select DUMP('Σας ευχαριστώ', 16) from DUAL; // Typ=96 Len=25: ce,a3,ce,b1,cf,82,20,ce,b5,cf,85,cf,87,ce,b1,cf,81,ce,b9,cf,83,cf,84,cf,8e String sGreek = "cea3ceb1cf8220ceb5cf85cf87ceb1cf81ceb9cf83cf84cf8e"; // select DUMP('Спасибо', 16) from DUAL; // Typ=96 Len=14: d0,a1,d0,bf,d0,b0,d1,81,d0,b8,d0,b1,d0,be String sCyrillic = "d0a1d0bfd0b0d181d0b8d0b1d0be"; // 2020-02-04T13:59:23,000000000 // Typ=180 Len=7: Typ=180 Len=7: 78,78,02,04,0e,3c,18 String sDatTsTyp180 = "787802040e3c18"; /* create table NUMBER_TEST(ID NUMBER, BF BINARY_FLOAT, BD BINARY_DOUBLE, NN117 NUMBER(11,7)); insert into NUMBER_TEST values(-.1828, SQRT(3),SQRT(3),SQRT(3)); SQL> select dump(ID, 16) from NUMBER_TEST; DUMP(ID,16) -------------------------------------------------------------------------------- Typ=2 Len=4: 3f,53,49,66 SQL> select dump(BF, 16) from NUMBER_TEST; DUMP(BF,16) -------------------------------------------------------------------------------- Typ=100 Len=4: bf,dd,b3,d7 SQL> select dump(BD, 16) from NUMBER_TEST; DUMP(BD,16) -------------------------------------------------------------------------------- Typ=101 Len=8: bf,fb,b6,7a,e8,58,4c,aa SQL> select dump(NN117, 16) from NUMBER_TEST; DUMP(NN117,16) -------------------------------------------------------------------------------- Typ=2 Len=6: c1,2,4a,15,33,51 */ String bdNegative = "3f534966"; String binaryFloatSqrt3 = "bfddb3d7"; String binaryDoubleSqrt3 = "bffbb67ae8584caa"; String number_11_7_Sqrt3 = "c1024a153351"; OraDumpDecoder odd = null; odd = new OraDumpDecoder("AL32UTF8", "AL16UTF16"); try { System.out.println(odd.fromVarchar2(sUsAscii)); System.out.println(odd.fromVarchar2(sTrChinese)); System.out.println(odd.fromVarchar2(sGreek)); System.out.println(odd.fromVarchar2(sCyrillic)); System.out.println(OraDumpDecoder.toTimestamp(sDatTsTyp180)); System.out.println(OraDumpDecoder.toBigDecimal(bdNegative)); System.out.println(OraDumpDecoder.toFloat(bdNegative)); System.out.println(OraDumpDecoder.toDouble(bdNegative)); System.out.println(OraDumpDecoder.fromBinaryFloat(binaryFloatSqrt3)); System.out.println(OraDumpDecoder.fromBinaryDouble(binaryDoubleSqrt3)); System.out.println(OraDumpDecoder.toBigDecimal(number_11_7_Sqrt3)); System.out.println(OraDumpDecoder.toFloat(number_11_7_Sqrt3)); System.out.println(OraDumpDecoder.toDouble(number_11_7_Sqrt3)); } catch (SQLException e) { e.printStackTrace(); fail("Exception " + e.getMessage()); } } }
shunte88/oracdc
src/test/java/eu/solutions/a2/cdc/oracle/OraDumpDecoderTest.java
1,455
// select DUMP('Σας ευχαριστώ', 16) from DUAL;
line_comment
el
/** * Copyright (c) 2018-present, A2 Rešitve d.o.o. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package eu.solutions.a2.cdc.oracle; import static org.junit.Assert.fail; import java.sql.SQLException; import org.junit.Test; public class OraDumpDecoderTest { @Test public void test() { // select DUMP('thanks', 16) from DUAL; // Typ=96 Len=6: 74,68,61,6e,6b,73 String sUsAscii = "7468616e6b73"; // select DUMP('謝謝啦', 16) from DUAL; // Typ=96 Len=9: e8,ac,9d,e8,ac,9d,e5,95,a6 String sTrChinese = "e8ac9de8ac9de595a6"; // select DUMP('Σας<SUF> // Typ=96 Len=25: ce,a3,ce,b1,cf,82,20,ce,b5,cf,85,cf,87,ce,b1,cf,81,ce,b9,cf,83,cf,84,cf,8e String sGreek = "cea3ceb1cf8220ceb5cf85cf87ceb1cf81ceb9cf83cf84cf8e"; // select DUMP('Спасибо', 16) from DUAL; // Typ=96 Len=14: d0,a1,d0,bf,d0,b0,d1,81,d0,b8,d0,b1,d0,be String sCyrillic = "d0a1d0bfd0b0d181d0b8d0b1d0be"; // 2020-02-04T13:59:23,000000000 // Typ=180 Len=7: Typ=180 Len=7: 78,78,02,04,0e,3c,18 String sDatTsTyp180 = "787802040e3c18"; /* create table NUMBER_TEST(ID NUMBER, BF BINARY_FLOAT, BD BINARY_DOUBLE, NN117 NUMBER(11,7)); insert into NUMBER_TEST values(-.1828, SQRT(3),SQRT(3),SQRT(3)); SQL> select dump(ID, 16) from NUMBER_TEST; DUMP(ID,16) -------------------------------------------------------------------------------- Typ=2 Len=4: 3f,53,49,66 SQL> select dump(BF, 16) from NUMBER_TEST; DUMP(BF,16) -------------------------------------------------------------------------------- Typ=100 Len=4: bf,dd,b3,d7 SQL> select dump(BD, 16) from NUMBER_TEST; DUMP(BD,16) -------------------------------------------------------------------------------- Typ=101 Len=8: bf,fb,b6,7a,e8,58,4c,aa SQL> select dump(NN117, 16) from NUMBER_TEST; DUMP(NN117,16) -------------------------------------------------------------------------------- Typ=2 Len=6: c1,2,4a,15,33,51 */ String bdNegative = "3f534966"; String binaryFloatSqrt3 = "bfddb3d7"; String binaryDoubleSqrt3 = "bffbb67ae8584caa"; String number_11_7_Sqrt3 = "c1024a153351"; OraDumpDecoder odd = null; odd = new OraDumpDecoder("AL32UTF8", "AL16UTF16"); try { System.out.println(odd.fromVarchar2(sUsAscii)); System.out.println(odd.fromVarchar2(sTrChinese)); System.out.println(odd.fromVarchar2(sGreek)); System.out.println(odd.fromVarchar2(sCyrillic)); System.out.println(OraDumpDecoder.toTimestamp(sDatTsTyp180)); System.out.println(OraDumpDecoder.toBigDecimal(bdNegative)); System.out.println(OraDumpDecoder.toFloat(bdNegative)); System.out.println(OraDumpDecoder.toDouble(bdNegative)); System.out.println(OraDumpDecoder.fromBinaryFloat(binaryFloatSqrt3)); System.out.println(OraDumpDecoder.fromBinaryDouble(binaryDoubleSqrt3)); System.out.println(OraDumpDecoder.toBigDecimal(number_11_7_Sqrt3)); System.out.println(OraDumpDecoder.toFloat(number_11_7_Sqrt3)); System.out.println(OraDumpDecoder.toDouble(number_11_7_Sqrt3)); } catch (SQLException e) { e.printStackTrace(); fail("Exception " + e.getMessage()); } } }
439_1
package petfinder.contacts; /** * Μήνυμα sms. * */ public class TextMessage { private String from; private String to; private String subject; private String body; /** * Θέτει ον αποστολέα του μηνύματος. * @param from Ο αποστολέας του μηνύματος. */ public void setFrom(String from) { this.from = from; } /** * Επιστρέφει τον αποστολέα του μηνύματος. * @return Ο αποστολέας του μηνύματος. */ public String getFrom() { return from; } /** * Θέτει τον παραλήπτη του μηνύματος. * @param phone Ο παραλήπτης. */ public void setTo(String phone) { this.to = phone; } /** * Επιστρέφει τον παραλήπτη του μηνύματος. * @return Ο παραλήπτης */ public String getTo() { return to; } /** * Θέτει το θέμα του μηνύματος. * @param subject Το θέμα του μηνύματος. */ public void setSubject(String subject) { this.subject = subject; } /** * Επιστρέφει το θέμα του μηνύματος. * @return Το θέμα του μηνύματος. */ public String getSubject() { return subject; } /** * Θέτει το κείμενο του μηνύματος. * @param body Το κείμενο του μηνύματος. */ public void setBody(String body) { this.body = body; } /** * Επιστρέφει το κείμενο του μηνύματος. * @return Το κείμενο του μηνύματος. */ public String getBody() { return body; } /** * Επισυνάπτει κείμενο στο τέλος του μηνύματος. * @param text Το κείμενο που επισυνάπτεται στο τέλος του μηνύματος. */ public void appendToBody(String text) { subject += text; } }
sikelos13/petfinder-inf
src/main/java/petfinder/contacts/TextMessage.java
777
/** * Θέτει ον αποστολέα του μηνύματος. * @param from Ο αποστολέας του μηνύματος. */
block_comment
el
package petfinder.contacts; /** * Μήνυμα sms. * */ public class TextMessage { private String from; private String to; private String subject; private String body; /** * Θέτει ον αποστολέα<SUF>*/ public void setFrom(String from) { this.from = from; } /** * Επιστρέφει τον αποστολέα του μηνύματος. * @return Ο αποστολέας του μηνύματος. */ public String getFrom() { return from; } /** * Θέτει τον παραλήπτη του μηνύματος. * @param phone Ο παραλήπτης. */ public void setTo(String phone) { this.to = phone; } /** * Επιστρέφει τον παραλήπτη του μηνύματος. * @return Ο παραλήπτης */ public String getTo() { return to; } /** * Θέτει το θέμα του μηνύματος. * @param subject Το θέμα του μηνύματος. */ public void setSubject(String subject) { this.subject = subject; } /** * Επιστρέφει το θέμα του μηνύματος. * @return Το θέμα του μηνύματος. */ public String getSubject() { return subject; } /** * Θέτει το κείμενο του μηνύματος. * @param body Το κείμενο του μηνύματος. */ public void setBody(String body) { this.body = body; } /** * Επιστρέφει το κείμενο του μηνύματος. * @return Το κείμενο του μηνύματος. */ public String getBody() { return body; } /** * Επισυνάπτει κείμενο στο τέλος του μηνύματος. * @param text Το κείμενο που επισυνάπτεται στο τέλος του μηνύματος. */ public void appendToBody(String text) { subject += text; } }
7483_1
import java.util.List; import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class LibraryManagementSystem extends Application { private static Library library; // Declare library as a static variable // Οι χρήστες είναι καλά παιδιά και δε θα κάνουν πολλές φορές rate το ίδιο βιβλίο public static void main(String[] args) { library = new Library(); // Initialize the library in the main method Admin medialabAdmin = new Admin("medialab", "medialab_2024"); library.addAdmin(medialabAdmin); // library.deserializeUsers(); library.deserializeBooks(); library.deserializeBorrowings(); library.serializeUsers(); library.serializeBooks(); library.serializeBorrowings(); // // initialization without serialization // User medialabUser = new User("u", "u", "u", "u", "u", "u"); // library.addUser(medialabUser); // library.addRandomUsers(5); // library.addSampleBooksAndRatings(); // library.addSpecificBorrowings(); // library.serializeUsers(); // library.serializeBooks(); // library.serializeBorrowings(); // // Launch the JavaFX application launch(args); } @Override public void start(Stage primaryStage) { primaryStage.setTitle("Library Management System"); VBox root = new VBox(10); root.setPadding(new Insets(10)); root.setAlignment(Pos.CENTER); Label welcomeLabel = new Label("Welcome to MultiMediaLibrary!"); welcomeLabel.setStyle("-fx-font-size: 18; -fx-font-weight: bold;"); HBox titleBox = new HBox(welcomeLabel); titleBox.setAlignment(Pos.CENTER); root.getChildren().add(titleBox); List<Book> topRatedBooks = library.getTopRatedBooks(5); VBox booksListVBox = new VBox(5); Label topRatedTitleLabel = new Label("Top Rated Books:"); topRatedTitleLabel.setStyle("-fx-font-size: 14; -fx-font-weight: bold;"); booksListVBox.getChildren().add(topRatedTitleLabel); for (Book book : topRatedBooks) { double roundedRating = Math.round(book.getAverageRating() * 100.0) / 100.0; Label bookLabel = new Label(book.getTitle() + " (Rating: " + String.format("%.2f", roundedRating) + ")"); bookLabel.setStyle("-fx-alignment: CENTER-LEFT;"); // Set the alignment to left booksListVBox.getChildren().add(bookLabel); } root.getChildren().add(booksListVBox); Button userButton = new Button("Log in as User"); userButton.setOnAction(e -> showUserLogin(primaryStage)); root.getChildren().add(userButton); Button adminButton = new Button("Log in as Admin"); adminButton.setOnAction(e -> showAdminLogin()); root.getChildren().add(adminButton); Button newUserButton = new Button("Create new user account"); newUserButton.setOnAction(e -> showCreateUser()); root.getChildren().add(newUserButton); Button exitButton = new Button("Exit"); exitButton.setOnAction(e -> primaryStage.close()); root.getChildren().add(exitButton); Scene scene = new Scene(root, 500, 400); primaryStage.setScene(scene); primaryStage.show(); } private void showUserLogin(Stage primaryStage) { UserLoginScreen userLoginScreen = new UserLoginScreen(library); userLoginScreen.start(new Stage()); // Optional: Close the main stage (LibraryManagementSystem) after navigating to user login primaryStage.close(); } private void showAdminLogin() { AdminLoginScreen adminLoginScreen = new AdminLoginScreen(library); adminLoginScreen.start(new Stage()); } private void showCreateUser() { CreateNewUserScreen createNewUserScreen = new CreateNewUserScreen(library); createNewUserScreen.start(new Stage()); } }
siskos-k/Multimedia2024-JavaFX
src/LibraryManagementSystem.java
1,077
// Οι χρήστες είναι καλά παιδιά και δε θα κάνουν πολλές φορές rate το ίδιο βιβλίο
line_comment
el
import java.util.List; import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class LibraryManagementSystem extends Application { private static Library library; // Declare library as a static variable // Οι χρήστες<SUF> public static void main(String[] args) { library = new Library(); // Initialize the library in the main method Admin medialabAdmin = new Admin("medialab", "medialab_2024"); library.addAdmin(medialabAdmin); // library.deserializeUsers(); library.deserializeBooks(); library.deserializeBorrowings(); library.serializeUsers(); library.serializeBooks(); library.serializeBorrowings(); // // initialization without serialization // User medialabUser = new User("u", "u", "u", "u", "u", "u"); // library.addUser(medialabUser); // library.addRandomUsers(5); // library.addSampleBooksAndRatings(); // library.addSpecificBorrowings(); // library.serializeUsers(); // library.serializeBooks(); // library.serializeBorrowings(); // // Launch the JavaFX application launch(args); } @Override public void start(Stage primaryStage) { primaryStage.setTitle("Library Management System"); VBox root = new VBox(10); root.setPadding(new Insets(10)); root.setAlignment(Pos.CENTER); Label welcomeLabel = new Label("Welcome to MultiMediaLibrary!"); welcomeLabel.setStyle("-fx-font-size: 18; -fx-font-weight: bold;"); HBox titleBox = new HBox(welcomeLabel); titleBox.setAlignment(Pos.CENTER); root.getChildren().add(titleBox); List<Book> topRatedBooks = library.getTopRatedBooks(5); VBox booksListVBox = new VBox(5); Label topRatedTitleLabel = new Label("Top Rated Books:"); topRatedTitleLabel.setStyle("-fx-font-size: 14; -fx-font-weight: bold;"); booksListVBox.getChildren().add(topRatedTitleLabel); for (Book book : topRatedBooks) { double roundedRating = Math.round(book.getAverageRating() * 100.0) / 100.0; Label bookLabel = new Label(book.getTitle() + " (Rating: " + String.format("%.2f", roundedRating) + ")"); bookLabel.setStyle("-fx-alignment: CENTER-LEFT;"); // Set the alignment to left booksListVBox.getChildren().add(bookLabel); } root.getChildren().add(booksListVBox); Button userButton = new Button("Log in as User"); userButton.setOnAction(e -> showUserLogin(primaryStage)); root.getChildren().add(userButton); Button adminButton = new Button("Log in as Admin"); adminButton.setOnAction(e -> showAdminLogin()); root.getChildren().add(adminButton); Button newUserButton = new Button("Create new user account"); newUserButton.setOnAction(e -> showCreateUser()); root.getChildren().add(newUserButton); Button exitButton = new Button("Exit"); exitButton.setOnAction(e -> primaryStage.close()); root.getChildren().add(exitButton); Scene scene = new Scene(root, 500, 400); primaryStage.setScene(scene); primaryStage.show(); } private void showUserLogin(Stage primaryStage) { UserLoginScreen userLoginScreen = new UserLoginScreen(library); userLoginScreen.start(new Stage()); // Optional: Close the main stage (LibraryManagementSystem) after navigating to user login primaryStage.close(); } private void showAdminLogin() { AdminLoginScreen adminLoginScreen = new AdminLoginScreen(library); adminLoginScreen.start(new Stage()); } private void showCreateUser() { CreateNewUserScreen createNewUserScreen = new CreateNewUserScreen(library); createNewUserScreen.start(new Stage()); } }
350_4
package org.elasticsearch.index.analysis; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; /** * @author Tasos Stathopoulos * Generates singular/plural variants of a greek word based * on a combination of predefined rules. */ public class GreekReverseStemmer { private static final Logger logger = Loggers.getLogger(GreeklishConverter.class, GreeklishConverter.class.getSimpleName()); /** * Constant variable that represent suffixes for pluralization of * greeklish tokens. */ private static final String SUFFIX_MATOS = "ματοσ"; private static final String SUFFIX_MATA = "ματα"; private static final String SUFFIX_MATWN = "ματων"; private static final String SUFFIX_AS = "ασ"; private static final String SUFFIX_EIA = "εια"; private static final String SUFFIX_EIO = "ειο"; private static final String SUFFIX_EIOY = "ειου"; private static final String SUFFIX_EIWN = "ειων"; private static final String SUFFIX_IOY = "ιου"; private static final String SUFFIX_IA = "ια"; private static final String SUFFIX_IWN = "ιων"; private static final String SUFFIX_OS = "οσ"; private static final String SUFFIX_OI = "οι"; private static final String SUFFIX_EIS = "εισ"; private static final String SUFFIX_ES = "εσ"; private static final String SUFFIX_HS = "ησ"; private static final String SUFFIX_WN = "ων"; private static final String SUFFIX_OY = "ου"; private static final String SUFFIX_O = "ο"; private static final String SUFFIX_H = "η"; private static final String SUFFIX_A = "α"; private static final String SUFFIX_I = "ι"; /** * This hash has as keys all the suffixes that we want to handle in order * to generate singular/plural greek words. */ private final Map<String, String[]> suffixes = new HashMap<String, String[]>(); /** * The possible suffix strings. */ private static final String[][] suffixStrings = new String[][] { {SUFFIX_MATOS, "μα", "ματων", "ματα"}, // κουρεματος, ασυρματος {SUFFIX_MATA, "μα", "ματων", "ματοσ"}, // ενδυματα {SUFFIX_MATWN, "μα", "ματα", "ματοσ"}, // ασυρματων, ενδυματων {SUFFIX_AS, "α", "ων", "εσ"}, // πορτας, χαρτοφυλακας {SUFFIX_EIA, "ειο", "ειων", "ειου", "ειασ"}, // γραφεια, ενεργεια {SUFFIX_EIO, "εια", "ειων", "ειου"}, // γραφειο {SUFFIX_EIOY, "εια", "ειου", "ειο", "ειων"}, // γραφειου {SUFFIX_EIWN, "εια", "ειου", "ειο", "ειασ"}, // ασφαλειων, γραφειων {SUFFIX_IOY, "ι", "ια", "ιων", "ιο"}, // πεδιου, κυνηγιου {SUFFIX_IA, "ιου", "ι", "ιων", "ιασ", "ιο"}, // πεδία, αρμονια {SUFFIX_IWN, "ιου", "ια", "ι", "ιο"}, // καλωδιων, κατοικιδιων {SUFFIX_OS, "η", "ουσ", "ου", "οι", "ων"}, // κλιματισμος {SUFFIX_OI, "οσ", "ου", "ων"}, // μυλοι, οδηγοι, σταθμοι {SUFFIX_EIS, "η", "ησ", "εων"}, // συνδεσεις, τηλεορασεις {SUFFIX_ES, "η", "ασ", "ων", "ησ", "α"}, // αλυσιδες {SUFFIX_HS, "ων", "εσ", "η", "εων"}, // γυμναστικης, εκτυπωσης {SUFFIX_WN, "οσ", "εσ", "α", "η", "ησ", "ου", "οι", "ο", "α"}, // ινων, καπνιστων, καρτων, κατασκευων {SUFFIX_OY, "ων", "α", "ο", "οσ"}, // λαδιου, μοντελισμου, παιδικου {SUFFIX_O, "α", "ου", "εων", "ων"}, // αυτοκινητο, δισκος {SUFFIX_H, "οσ", "ουσ", "εων", "εισ", "ησ", "ων"}, //βελη, ψυξη, τηλεοραση, αποτριχωση {SUFFIX_A, "ο" , "ου", "ων", "ασ", "εσ"}, // γιλεκα, εσωρουχα, ομπρελλα {SUFFIX_I, "ιου", "ια", "ιων"} // γιαουρτι, γραναζι }; /** * The greek word list */ private List<String> greekWords = new ArrayList<String>(); // Constructor public GreekReverseStemmer() { // populate suffixes for (String[] suffix : suffixStrings) { suffixes.put(suffix[0], Arrays.copyOfRange(suffix, 1, suffix.length)); } } /** * This method generates the greek variants of the greek token that * receives. * * @param tokenString the greek word * @return a list of the generated greek word variations */ public List<String> generateGreekVariants(String tokenString) { // clear the list from variations of the previous greek token greekWords.clear(); // add the initial greek token in the greek words greekWords.add(tokenString); // Find the first matching suffix and generate the // the variants of this word for (String[] suffix : suffixStrings) { if (tokenString.endsWith(suffix[0])) { // Add to greekWords the tokens with the desired suffixes generate_more_greek_words(tokenString, suffix[0]); break; } } return greekWords; } /** * Generates more greek words based on the suffix of the original word * @param inputSuffix the suffix that matched */ private void generate_more_greek_words(final String inputToken, final String inputSuffix) { for (String suffix : suffixes.get(inputSuffix)) { greekWords.add(inputToken.replaceAll(inputSuffix + "$", suffix)); } } }
skroutz/elasticsearch-analysis-greeklish
src/main/java/org/elasticsearch/index/analysis/GreekReverseStemmer.java
2,034
// μυλοι, οδηγοι, σταθμοι
line_comment
el
package org.elasticsearch.index.analysis; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; /** * @author Tasos Stathopoulos * Generates singular/plural variants of a greek word based * on a combination of predefined rules. */ public class GreekReverseStemmer { private static final Logger logger = Loggers.getLogger(GreeklishConverter.class, GreeklishConverter.class.getSimpleName()); /** * Constant variable that represent suffixes for pluralization of * greeklish tokens. */ private static final String SUFFIX_MATOS = "ματοσ"; private static final String SUFFIX_MATA = "ματα"; private static final String SUFFIX_MATWN = "ματων"; private static final String SUFFIX_AS = "ασ"; private static final String SUFFIX_EIA = "εια"; private static final String SUFFIX_EIO = "ειο"; private static final String SUFFIX_EIOY = "ειου"; private static final String SUFFIX_EIWN = "ειων"; private static final String SUFFIX_IOY = "ιου"; private static final String SUFFIX_IA = "ια"; private static final String SUFFIX_IWN = "ιων"; private static final String SUFFIX_OS = "οσ"; private static final String SUFFIX_OI = "οι"; private static final String SUFFIX_EIS = "εισ"; private static final String SUFFIX_ES = "εσ"; private static final String SUFFIX_HS = "ησ"; private static final String SUFFIX_WN = "ων"; private static final String SUFFIX_OY = "ου"; private static final String SUFFIX_O = "ο"; private static final String SUFFIX_H = "η"; private static final String SUFFIX_A = "α"; private static final String SUFFIX_I = "ι"; /** * This hash has as keys all the suffixes that we want to handle in order * to generate singular/plural greek words. */ private final Map<String, String[]> suffixes = new HashMap<String, String[]>(); /** * The possible suffix strings. */ private static final String[][] suffixStrings = new String[][] { {SUFFIX_MATOS, "μα", "ματων", "ματα"}, // κουρεματος, ασυρματος {SUFFIX_MATA, "μα", "ματων", "ματοσ"}, // ενδυματα {SUFFIX_MATWN, "μα", "ματα", "ματοσ"}, // ασυρματων, ενδυματων {SUFFIX_AS, "α", "ων", "εσ"}, // πορτας, χαρτοφυλακας {SUFFIX_EIA, "ειο", "ειων", "ειου", "ειασ"}, // γραφεια, ενεργεια {SUFFIX_EIO, "εια", "ειων", "ειου"}, // γραφειο {SUFFIX_EIOY, "εια", "ειου", "ειο", "ειων"}, // γραφειου {SUFFIX_EIWN, "εια", "ειου", "ειο", "ειασ"}, // ασφαλειων, γραφειων {SUFFIX_IOY, "ι", "ια", "ιων", "ιο"}, // πεδιου, κυνηγιου {SUFFIX_IA, "ιου", "ι", "ιων", "ιασ", "ιο"}, // πεδία, αρμονια {SUFFIX_IWN, "ιου", "ια", "ι", "ιο"}, // καλωδιων, κατοικιδιων {SUFFIX_OS, "η", "ουσ", "ου", "οι", "ων"}, // κλιματισμος {SUFFIX_OI, "οσ", "ου", "ων"}, // μυλοι, οδηγοι,<SUF> {SUFFIX_EIS, "η", "ησ", "εων"}, // συνδεσεις, τηλεορασεις {SUFFIX_ES, "η", "ασ", "ων", "ησ", "α"}, // αλυσιδες {SUFFIX_HS, "ων", "εσ", "η", "εων"}, // γυμναστικης, εκτυπωσης {SUFFIX_WN, "οσ", "εσ", "α", "η", "ησ", "ου", "οι", "ο", "α"}, // ινων, καπνιστων, καρτων, κατασκευων {SUFFIX_OY, "ων", "α", "ο", "οσ"}, // λαδιου, μοντελισμου, παιδικου {SUFFIX_O, "α", "ου", "εων", "ων"}, // αυτοκινητο, δισκος {SUFFIX_H, "οσ", "ουσ", "εων", "εισ", "ησ", "ων"}, //βελη, ψυξη, τηλεοραση, αποτριχωση {SUFFIX_A, "ο" , "ου", "ων", "ασ", "εσ"}, // γιλεκα, εσωρουχα, ομπρελλα {SUFFIX_I, "ιου", "ια", "ιων"} // γιαουρτι, γραναζι }; /** * The greek word list */ private List<String> greekWords = new ArrayList<String>(); // Constructor public GreekReverseStemmer() { // populate suffixes for (String[] suffix : suffixStrings) { suffixes.put(suffix[0], Arrays.copyOfRange(suffix, 1, suffix.length)); } } /** * This method generates the greek variants of the greek token that * receives. * * @param tokenString the greek word * @return a list of the generated greek word variations */ public List<String> generateGreekVariants(String tokenString) { // clear the list from variations of the previous greek token greekWords.clear(); // add the initial greek token in the greek words greekWords.add(tokenString); // Find the first matching suffix and generate the // the variants of this word for (String[] suffix : suffixStrings) { if (tokenString.endsWith(suffix[0])) { // Add to greekWords the tokens with the desired suffixes generate_more_greek_words(tokenString, suffix[0]); break; } } return greekWords; } /** * Generates more greek words based on the suffix of the original word * @param inputSuffix the suffix that matched */ private void generate_more_greek_words(final String inputToken, final String inputSuffix) { for (String suffix : suffixes.get(inputSuffix)) { greekWords.add(inputToken.replaceAll(inputSuffix + "$", suffix)); } } }
1981_21
package gr.sch.ira.minoas.seam.components.management; import gr.sch.ira.minoas.core.CoreUtils; import gr.sch.ira.minoas.model.employee.Employee; import gr.sch.ira.minoas.model.employee.EmployeeInfo; import gr.sch.ira.minoas.model.employee.EmployeeType; import gr.sch.ira.minoas.model.employement.WorkExperience; import gr.sch.ira.minoas.seam.components.BaseDatabaseAwareSeamComponent; import gr.sch.ira.minoas.seam.components.CoreSearching; import gr.sch.ira.minoas.seam.components.WorkExperienceCalculation; import gr.sch.ira.minoas.seam.components.home.EmployeeHome; import gr.sch.ira.minoas.seam.components.home.WorkExperienceHome; import java.util.Calendar; import java.util.Collection; import java.util.Date; import org.apache.commons.lang.time.DateUtils; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.Factory; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.jboss.seam.annotations.Transactional; import org.jboss.seam.annotations.datamodel.DataModel; import org.jboss.seam.international.StatusMessage.Severity; @Name(value = "workExperiencesManagement") @Scope(ScopeType.PAGE) public class WorkExperiencesManagement extends BaseDatabaseAwareSeamComponent { /** * Comment for <code>serialVersionUID</code> */ private static final long serialVersionUID = 1L; @In(required=true) private CoreSearching coreSearching; @In(required = true, create = true) private EmployeeHome employeeHome; @In(required=false) private WorkExperienceHome workExperienceHome; private EmployeeType fooEmployeeType; @In(required=true, create=true) private WorkExperienceCalculation workExperienceCalculation; /** * Employees current leave history */ @DataModel(scope=ScopeType.PAGE, value="workExperienceHistory") private Collection<WorkExperience> workExperienceHistory = null; @Factory(value="workExperienceHistory",autoCreate=true) public void constructWorkExperienceHistory() { Employee employee = getEmployeeHome().getInstance(); info("constructing work experience history for employee #0", employee); setWorkExperienceHistory(coreSearching.getWorkExperienceHistory(employee)); } /** * @return the employeeHome */ public EmployeeHome getEmployeeHome() { return employeeHome; } /** * @param employeeHome the employeeHome to set */ public void setEmployeeHome(EmployeeHome employeeHome) { this.employeeHome = employeeHome; } /** * @return the workExperienceHistory */ public Collection<WorkExperience> getWorkExperienceHistory() { return workExperienceHistory; } /** * @param workExperienceHistory the workExperienceHistory to set */ public void setWorkExperienceHistory(Collection<WorkExperience> workExperienceHistory) { this.workExperienceHistory = workExperienceHistory; } /** * @return the fooEmployeeType */ public EmployeeType getFooEmployeeType() { return fooEmployeeType; } /** * @param fooEmployeeType the fooEmployeeType to set */ public void setFooEmployeeType(EmployeeType fooEmployeeType) { this.fooEmployeeType = fooEmployeeType; } public String modifyWorkExperience() { if(workExperienceHome != null && workExperienceHome.isManaged()) { info("trying to modify work experience #0", workExperienceHome); /* check if the work experience dates are allowed. */ WorkExperience workExp = workExperienceHome.getInstance(); if(workExp.getToDate().compareTo(workExp.getFromDate()) <= 0 ) { facesMessages.add(Severity.ERROR, "Οι ημ/νιες έναρξης και λήξης της προϋπηρεσίας, έτσι όπως τις τροποποιήσατε, είναι μή αποδεκτές."); return ACTION_OUTCOME_FAILURE; } else { // Αν η προϋπηρεσία είναι Διδακτική τότε θα είναι και Εκπαιδευτική if(workExp.getTeaching()) workExp.setEducational(true); workExperienceHome.update(); workExperienceCalculation.updateEmployeeExperience(getEmployeeHome().getInstance()); info("employee's #0 work experience #1 has been updated!", workExperienceHome.getInstance().getEmployee(), workExperienceHome.getInstance()); return ACTION_OUTCOME_SUCCESS; } } else { facesMessages.add(Severity.ERROR, "work experience home #0 is not managed, thus #1 work experience can't be modified.", workExperienceHome, workExperienceHome.getInstance()); return ACTION_OUTCOME_FAILURE; } } @Transactional public String deleteWorkExperience() { if(workExperienceHome != null && workExperienceHome.isManaged()) { info("trying to delete work experience #0", workExperienceHome); /* check if the work experience dates are allowed. */ WorkExperience workExp = workExperienceHome.getInstance(); workExp.setActive(Boolean.FALSE); workExp.setDeleted(Boolean.TRUE); workExp.setDeletedOn(new Date()); workExp.setDeletedBy(getPrincipal()); workExperienceHome.update(); workExperienceCalculation.updateEmployeeExperience(getEmployeeHome().getInstance()); constructWorkExperienceHistory(); return ACTION_OUTCOME_SUCCESS; } else { facesMessages.add(Severity.ERROR, "work experience home #0 is not managed, thus #1 work experience can't be deleted.", workExperienceHome, workExperienceHome.getInstance()); return ACTION_OUTCOME_FAILURE; } } @Transactional public String createWorkExperience() { if(workExperienceHome != null && (!workExperienceHome.isManaged())) { info("trying to modify work experience #0", workExperienceHome); /* check if the work experience dates are allowed. */ WorkExperience workExp = workExperienceHome.getInstance(); if(workExp.getToDate().compareTo(workExp.getFromDate()) <= 0 ) { facesMessages.add(Severity.ERROR, "Οι ημ/νιες έναρξης και λήξης της προϋπηρεσίας, έτσι όπως τις εισάγατε, δεν είναι αποδεκτές."); return ACTION_OUTCOME_FAILURE; } else { info("employee's #0 work experience #1 has been updated!", workExperienceHome.getInstance().getEmployee(), workExperienceHome.getInstance()); workExp.setActive(Boolean.TRUE); workExp.setEmployee(getEmployeeHome().getInstance()); workExp.setInsertedBy(getPrincipal()); workExp.setInsertedOn(new Date()); workExp.setCalendarExperienceDays(CoreUtils.getDatesDifference(workExp.getFromDate(), workExp.getToDate())); // Αν η νέα προϋπηρεσία είναι Διδακτική τότε θα είναι και Εκπαιδευτική if(workExp.getTeaching()) workExp.setEducational(true); // if(workExp.getType().getId() == 4 || workExp.getType().getId() == 5) { // // } else { // // } // // // If Employee is HOURLY_PAID, calculate his actual work experience in days based on his mandatoryHours and his hours worked. // if((workExp.getActualDays() == null || workExp.getActualDays() == 0) && // (workExp.getNumberOfWorkExperienceHours() !=null && workExp.getNumberOfWorkExperienceHours() != 0) && // (workExp.getMandatoryHours() !=null) && workExp.getMandatoryHours() != 0) { // workExp.setActualDays((int)Math.ceil((((float)(workExp.getNumberOfWorkExperienceHours()*6)/workExp.getMandatoryHours())*30)/25)); // } workExperienceHome.persist(); workExperienceCalculation.updateEmployeeExperience(getEmployeeHome().getInstance()); constructWorkExperienceHistory(); return ACTION_OUTCOME_SUCCESS; } } else { facesMessages.add(Severity.ERROR, "work experience home #0 is managed, thus #1 work experience can't be created.", workExperienceHome, workExperienceHome.getInstance()); return ACTION_OUTCOME_FAILURE; } } public void reCalculateActualDays() { WorkExperience workExp = workExperienceHome.getInstance(); if(workExp.getType().getId() == 3 || workExp.getType().getId() == 5) { // Άν Ωρομίσθιος ή ΝΠΔΔ if(workExp.getType().getId() == 5 && workExp.getNumberOfWorkExperienceHours() > 0) { // Αν ΝΠΔΔ και έχει ώρες ωρομισθίας workExp.setActualDays((int)Math.round((((float)(workExp.getNumberOfWorkExperienceHours()*6)/workExp.getMandatoryHours())*30)/25)); } else if(workExp.getType().getId() == 5 && workExp.getNumberOfWorkExperienceHours() == 0) { // Αν ΝΠΔΔ και ΔΕΝ έχει ώρες ωρομισθίας Date dateFrom = workExp.getFromDate() != null ? DateUtils.truncate(workExp.getFromDate(), Calendar.DAY_OF_MONTH) : null; Date dateTo = workExp.getToDate() != null ? DateUtils.truncate(workExp.getToDate(), Calendar.DAY_OF_MONTH) : null; workExp.setActualDays((CoreUtils.datesDifferenceIn360DaysYear(dateFrom, dateTo)*workExp.getFinalWorkingHours())/workExp.getMandatoryHours()); } else { // Αν Ωρομίσθιος workExp.setActualDays((int)Math.ceil((((float)(workExp.getNumberOfWorkExperienceHours()*6)/workExp.getMandatoryHours())*30)/25)); } } else { // Όλοι οι υπόλοιποι τύποι εκπαιδευτικού Date dateFrom = workExp.getFromDate() != null ? DateUtils.truncate(workExp.getFromDate(), Calendar.DAY_OF_MONTH) : null; Date dateTo = workExp.getToDate() != null ? DateUtils.truncate(workExp.getToDate(), Calendar.DAY_OF_MONTH) : null; workExp.setActualDays((CoreUtils.datesDifferenceIn360DaysYear(dateFrom, dateTo)*workExp.getFinalWorkingHours())/workExp.getMandatoryHours()); } } /* this method is called when the user clicks the "add new leave" */ public void prepareNewWorkExperience() { workExperienceHome.clearInstance(); WorkExperience workExp = workExperienceHome.getInstance(); workExp.setFromDate(new Date()); workExp.setToDate(new Date()); workExp.setComment(null); workExp.setEmployee(employeeHome.getInstance()); workExp.setActualDays(new Integer(0)); workExp.setNumberOfWorkExperienceHours(new Integer(0)); workExp.setMandatoryHours(new Integer(21)); workExp.setFinalWorkingHours(new Integer(21)); } public void changedEmployeeType () { WorkExperience workExp = workExperienceHome.getInstance(); workExp.setNumberOfWorkExperienceHours(new Integer(0)); workExp.setCalendarExperienceDays(new Integer(0)); workExp.setActualDays(new Integer(0)); workExp.setMandatoryHours(new Integer(21)); workExp.setFinalWorkingHours(new Integer(21)); // // Depending of work experience type set educational (Εκπαιδευτική) and teaching(διδακτική) as true // in the cases of Ωρομίσθιος, Αναπληρωτής & Ιδιωτική Εκπαίδευση // switch (workExp.getType().getId()) { case 3: case 4: case 8: workExp.setEducational(true); workExp.setTeaching(true); break; default: workExp.setEducational(false); workExp.setTeaching(false); break; } } public void silentlyComputeDateDifference() { WorkExperience workExp = workExperienceHome.getInstance(); Date dateFrom = workExp.getFromDate() != null ? DateUtils.truncate(workExp.getFromDate(), Calendar.DAY_OF_MONTH) : null; Date dateTo = workExp.getToDate() != null ? DateUtils.truncate(workExp.getToDate(), Calendar.DAY_OF_MONTH) : null; if( dateFrom!=null && dateTo !=null ) { workExp.setCalendarExperienceDays(CoreUtils.getDatesDifference(dateFrom, dateTo)); workExp.setActualDays(CoreUtils.datesDifferenceIn360DaysYear(dateFrom, dateTo)); } else { workExp.setCalendarExperienceDays(new Integer(0)); workExp.setActualDays(new Integer(0)); } } public String computeEmployeeWorkExperience() { try { if (employeeHome.isManaged()) { Employee employee = employeeHome.getInstance(); EmployeeInfo employeeInfo = employee.getEmployeeInfo(); if(employeeInfo!=null) { workExperienceCalculation.updateEmployeeExperience(employee); info("updated employee #0 experience values [educational : #1, teaching : #2, total #3] and total service #4.", employee,employeeInfo.getSumOfEducationalExperience(), employeeInfo.getSumOfTeachingExperience(), employeeInfo.getSumOfExperience(), employeeInfo.getTotalWorkService()); getEntityManager().flush(); return ACTION_OUTCOME_SUCCESS; } else { facesMessages.add(Severity.ERROR, "Ο υπάλληλος δεν έχει EMPLOYEE_INFO"); return ACTION_OUTCOME_FAILURE; } } else { facesMessages.add(Severity.ERROR, "employeehome is not managed."); return ACTION_OUTCOME_FAILURE; } } catch (Exception ex) { error(ex); facesMessages.add(Severity.ERROR, String.format("Αποτυχιά ενημέρωσεις, λόγω '%s'", ex.getMessage())); return ACTION_OUTCOME_FAILURE; } } }
slavikos/minoas
gr.sch.ira.minoas/src/main/java/gr/sch/ira/minoas/seam/components/management/WorkExperiencesManagement.java
3,749
// Αν ΝΠΔΔ και ΔΕΝ έχει ώρες ωρομισθίας
line_comment
el
package gr.sch.ira.minoas.seam.components.management; import gr.sch.ira.minoas.core.CoreUtils; import gr.sch.ira.minoas.model.employee.Employee; import gr.sch.ira.minoas.model.employee.EmployeeInfo; import gr.sch.ira.minoas.model.employee.EmployeeType; import gr.sch.ira.minoas.model.employement.WorkExperience; import gr.sch.ira.minoas.seam.components.BaseDatabaseAwareSeamComponent; import gr.sch.ira.minoas.seam.components.CoreSearching; import gr.sch.ira.minoas.seam.components.WorkExperienceCalculation; import gr.sch.ira.minoas.seam.components.home.EmployeeHome; import gr.sch.ira.minoas.seam.components.home.WorkExperienceHome; import java.util.Calendar; import java.util.Collection; import java.util.Date; import org.apache.commons.lang.time.DateUtils; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.Factory; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.jboss.seam.annotations.Transactional; import org.jboss.seam.annotations.datamodel.DataModel; import org.jboss.seam.international.StatusMessage.Severity; @Name(value = "workExperiencesManagement") @Scope(ScopeType.PAGE) public class WorkExperiencesManagement extends BaseDatabaseAwareSeamComponent { /** * Comment for <code>serialVersionUID</code> */ private static final long serialVersionUID = 1L; @In(required=true) private CoreSearching coreSearching; @In(required = true, create = true) private EmployeeHome employeeHome; @In(required=false) private WorkExperienceHome workExperienceHome; private EmployeeType fooEmployeeType; @In(required=true, create=true) private WorkExperienceCalculation workExperienceCalculation; /** * Employees current leave history */ @DataModel(scope=ScopeType.PAGE, value="workExperienceHistory") private Collection<WorkExperience> workExperienceHistory = null; @Factory(value="workExperienceHistory",autoCreate=true) public void constructWorkExperienceHistory() { Employee employee = getEmployeeHome().getInstance(); info("constructing work experience history for employee #0", employee); setWorkExperienceHistory(coreSearching.getWorkExperienceHistory(employee)); } /** * @return the employeeHome */ public EmployeeHome getEmployeeHome() { return employeeHome; } /** * @param employeeHome the employeeHome to set */ public void setEmployeeHome(EmployeeHome employeeHome) { this.employeeHome = employeeHome; } /** * @return the workExperienceHistory */ public Collection<WorkExperience> getWorkExperienceHistory() { return workExperienceHistory; } /** * @param workExperienceHistory the workExperienceHistory to set */ public void setWorkExperienceHistory(Collection<WorkExperience> workExperienceHistory) { this.workExperienceHistory = workExperienceHistory; } /** * @return the fooEmployeeType */ public EmployeeType getFooEmployeeType() { return fooEmployeeType; } /** * @param fooEmployeeType the fooEmployeeType to set */ public void setFooEmployeeType(EmployeeType fooEmployeeType) { this.fooEmployeeType = fooEmployeeType; } public String modifyWorkExperience() { if(workExperienceHome != null && workExperienceHome.isManaged()) { info("trying to modify work experience #0", workExperienceHome); /* check if the work experience dates are allowed. */ WorkExperience workExp = workExperienceHome.getInstance(); if(workExp.getToDate().compareTo(workExp.getFromDate()) <= 0 ) { facesMessages.add(Severity.ERROR, "Οι ημ/νιες έναρξης και λήξης της προϋπηρεσίας, έτσι όπως τις τροποποιήσατε, είναι μή αποδεκτές."); return ACTION_OUTCOME_FAILURE; } else { // Αν η προϋπηρεσία είναι Διδακτική τότε θα είναι και Εκπαιδευτική if(workExp.getTeaching()) workExp.setEducational(true); workExperienceHome.update(); workExperienceCalculation.updateEmployeeExperience(getEmployeeHome().getInstance()); info("employee's #0 work experience #1 has been updated!", workExperienceHome.getInstance().getEmployee(), workExperienceHome.getInstance()); return ACTION_OUTCOME_SUCCESS; } } else { facesMessages.add(Severity.ERROR, "work experience home #0 is not managed, thus #1 work experience can't be modified.", workExperienceHome, workExperienceHome.getInstance()); return ACTION_OUTCOME_FAILURE; } } @Transactional public String deleteWorkExperience() { if(workExperienceHome != null && workExperienceHome.isManaged()) { info("trying to delete work experience #0", workExperienceHome); /* check if the work experience dates are allowed. */ WorkExperience workExp = workExperienceHome.getInstance(); workExp.setActive(Boolean.FALSE); workExp.setDeleted(Boolean.TRUE); workExp.setDeletedOn(new Date()); workExp.setDeletedBy(getPrincipal()); workExperienceHome.update(); workExperienceCalculation.updateEmployeeExperience(getEmployeeHome().getInstance()); constructWorkExperienceHistory(); return ACTION_OUTCOME_SUCCESS; } else { facesMessages.add(Severity.ERROR, "work experience home #0 is not managed, thus #1 work experience can't be deleted.", workExperienceHome, workExperienceHome.getInstance()); return ACTION_OUTCOME_FAILURE; } } @Transactional public String createWorkExperience() { if(workExperienceHome != null && (!workExperienceHome.isManaged())) { info("trying to modify work experience #0", workExperienceHome); /* check if the work experience dates are allowed. */ WorkExperience workExp = workExperienceHome.getInstance(); if(workExp.getToDate().compareTo(workExp.getFromDate()) <= 0 ) { facesMessages.add(Severity.ERROR, "Οι ημ/νιες έναρξης και λήξης της προϋπηρεσίας, έτσι όπως τις εισάγατε, δεν είναι αποδεκτές."); return ACTION_OUTCOME_FAILURE; } else { info("employee's #0 work experience #1 has been updated!", workExperienceHome.getInstance().getEmployee(), workExperienceHome.getInstance()); workExp.setActive(Boolean.TRUE); workExp.setEmployee(getEmployeeHome().getInstance()); workExp.setInsertedBy(getPrincipal()); workExp.setInsertedOn(new Date()); workExp.setCalendarExperienceDays(CoreUtils.getDatesDifference(workExp.getFromDate(), workExp.getToDate())); // Αν η νέα προϋπηρεσία είναι Διδακτική τότε θα είναι και Εκπαιδευτική if(workExp.getTeaching()) workExp.setEducational(true); // if(workExp.getType().getId() == 4 || workExp.getType().getId() == 5) { // // } else { // // } // // // If Employee is HOURLY_PAID, calculate his actual work experience in days based on his mandatoryHours and his hours worked. // if((workExp.getActualDays() == null || workExp.getActualDays() == 0) && // (workExp.getNumberOfWorkExperienceHours() !=null && workExp.getNumberOfWorkExperienceHours() != 0) && // (workExp.getMandatoryHours() !=null) && workExp.getMandatoryHours() != 0) { // workExp.setActualDays((int)Math.ceil((((float)(workExp.getNumberOfWorkExperienceHours()*6)/workExp.getMandatoryHours())*30)/25)); // } workExperienceHome.persist(); workExperienceCalculation.updateEmployeeExperience(getEmployeeHome().getInstance()); constructWorkExperienceHistory(); return ACTION_OUTCOME_SUCCESS; } } else { facesMessages.add(Severity.ERROR, "work experience home #0 is managed, thus #1 work experience can't be created.", workExperienceHome, workExperienceHome.getInstance()); return ACTION_OUTCOME_FAILURE; } } public void reCalculateActualDays() { WorkExperience workExp = workExperienceHome.getInstance(); if(workExp.getType().getId() == 3 || workExp.getType().getId() == 5) { // Άν Ωρομίσθιος ή ΝΠΔΔ if(workExp.getType().getId() == 5 && workExp.getNumberOfWorkExperienceHours() > 0) { // Αν ΝΠΔΔ και έχει ώρες ωρομισθίας workExp.setActualDays((int)Math.round((((float)(workExp.getNumberOfWorkExperienceHours()*6)/workExp.getMandatoryHours())*30)/25)); } else if(workExp.getType().getId() == 5 && workExp.getNumberOfWorkExperienceHours() == 0) { // Αν ΝΠΔΔ<SUF> Date dateFrom = workExp.getFromDate() != null ? DateUtils.truncate(workExp.getFromDate(), Calendar.DAY_OF_MONTH) : null; Date dateTo = workExp.getToDate() != null ? DateUtils.truncate(workExp.getToDate(), Calendar.DAY_OF_MONTH) : null; workExp.setActualDays((CoreUtils.datesDifferenceIn360DaysYear(dateFrom, dateTo)*workExp.getFinalWorkingHours())/workExp.getMandatoryHours()); } else { // Αν Ωρομίσθιος workExp.setActualDays((int)Math.ceil((((float)(workExp.getNumberOfWorkExperienceHours()*6)/workExp.getMandatoryHours())*30)/25)); } } else { // Όλοι οι υπόλοιποι τύποι εκπαιδευτικού Date dateFrom = workExp.getFromDate() != null ? DateUtils.truncate(workExp.getFromDate(), Calendar.DAY_OF_MONTH) : null; Date dateTo = workExp.getToDate() != null ? DateUtils.truncate(workExp.getToDate(), Calendar.DAY_OF_MONTH) : null; workExp.setActualDays((CoreUtils.datesDifferenceIn360DaysYear(dateFrom, dateTo)*workExp.getFinalWorkingHours())/workExp.getMandatoryHours()); } } /* this method is called when the user clicks the "add new leave" */ public void prepareNewWorkExperience() { workExperienceHome.clearInstance(); WorkExperience workExp = workExperienceHome.getInstance(); workExp.setFromDate(new Date()); workExp.setToDate(new Date()); workExp.setComment(null); workExp.setEmployee(employeeHome.getInstance()); workExp.setActualDays(new Integer(0)); workExp.setNumberOfWorkExperienceHours(new Integer(0)); workExp.setMandatoryHours(new Integer(21)); workExp.setFinalWorkingHours(new Integer(21)); } public void changedEmployeeType () { WorkExperience workExp = workExperienceHome.getInstance(); workExp.setNumberOfWorkExperienceHours(new Integer(0)); workExp.setCalendarExperienceDays(new Integer(0)); workExp.setActualDays(new Integer(0)); workExp.setMandatoryHours(new Integer(21)); workExp.setFinalWorkingHours(new Integer(21)); // // Depending of work experience type set educational (Εκπαιδευτική) and teaching(διδακτική) as true // in the cases of Ωρομίσθιος, Αναπληρωτής & Ιδιωτική Εκπαίδευση // switch (workExp.getType().getId()) { case 3: case 4: case 8: workExp.setEducational(true); workExp.setTeaching(true); break; default: workExp.setEducational(false); workExp.setTeaching(false); break; } } public void silentlyComputeDateDifference() { WorkExperience workExp = workExperienceHome.getInstance(); Date dateFrom = workExp.getFromDate() != null ? DateUtils.truncate(workExp.getFromDate(), Calendar.DAY_OF_MONTH) : null; Date dateTo = workExp.getToDate() != null ? DateUtils.truncate(workExp.getToDate(), Calendar.DAY_OF_MONTH) : null; if( dateFrom!=null && dateTo !=null ) { workExp.setCalendarExperienceDays(CoreUtils.getDatesDifference(dateFrom, dateTo)); workExp.setActualDays(CoreUtils.datesDifferenceIn360DaysYear(dateFrom, dateTo)); } else { workExp.setCalendarExperienceDays(new Integer(0)); workExp.setActualDays(new Integer(0)); } } public String computeEmployeeWorkExperience() { try { if (employeeHome.isManaged()) { Employee employee = employeeHome.getInstance(); EmployeeInfo employeeInfo = employee.getEmployeeInfo(); if(employeeInfo!=null) { workExperienceCalculation.updateEmployeeExperience(employee); info("updated employee #0 experience values [educational : #1, teaching : #2, total #3] and total service #4.", employee,employeeInfo.getSumOfEducationalExperience(), employeeInfo.getSumOfTeachingExperience(), employeeInfo.getSumOfExperience(), employeeInfo.getTotalWorkService()); getEntityManager().flush(); return ACTION_OUTCOME_SUCCESS; } else { facesMessages.add(Severity.ERROR, "Ο υπάλληλος δεν έχει EMPLOYEE_INFO"); return ACTION_OUTCOME_FAILURE; } } else { facesMessages.add(Severity.ERROR, "employeehome is not managed."); return ACTION_OUTCOME_FAILURE; } } catch (Exception ex) { error(ex); facesMessages.add(Severity.ERROR, String.format("Αποτυχιά ενημέρωσεις, λόγω '%s'", ex.getMessage())); return ACTION_OUTCOME_FAILURE; } } }
473_16
import org.jgap.*; import org.jgap.event.EventManager; import org.jgap.impl.*; import java.io.File; public class MainJGAP { /** * Το μέγεθος του πληθυσμού */ private static final int POPULATION_SIZE = 100; /** * Πόσες φορές θα γίνει δειγματοληψία για τον υπολογισμό του μέσου όρου (όπου χρειάζεται) */ private static final int SAMPLES = 100; /** * Μέγιστος αριθμός γενεών */ private static final int MAX_EVOLUTIONS = 1000; /** * Υπολογίζει την λύση του προβλήματος * * @param conf Αντικείμενο ρυθμίσεων * @param populationSize Μέγεθος πληθυσμού * @param maxEvolutions Μέγιστος αριθμός γενεών * @param mapController Χάρτης με τις τοποθεσίες των σφηκοφολιών * @return Πίνακας που περιέχει το καλύτερο χρωμόσωμα κάθε γενιάς * @throws Exception */ public static IChromosome[] exterminate(Configuration conf, int populationSize, int maxEvolutions, MapController mapController) throws Exception { IChromosome[] results = new IChromosome[maxEvolutions]; // Πίνακας που περιέχει το καλύτερο χρωμόσωμα κάθε γενιάς // Το χρωμόσωμα θα αποτελέιται από 6 γονίδια. Τα δύο πρώτα θα αποτελούν τις συντεταγμένες της πρώτης βόμβας, // τα επόμενα δύο τις συντεταγμένες της δεύτερης βόμβας, και τα υπόλοιπα δύο τις συντεταγμένες της τρίτης βόμβας Gene[] bombGenes = new Gene[6]; bombGenes[0] = new IntegerGene(conf, 0, mapController.getMaxX()); //x1 bombGenes[1] = new IntegerGene(conf, 0, mapController.getMaxY()); //y1 bombGenes[2] = new IntegerGene(conf, 0, mapController.getMaxX()); //x2 bombGenes[3] = new IntegerGene(conf, 0, mapController.getMaxY()); //y2 bombGenes[4] = new IntegerGene(conf, 0, mapController.getMaxX()); //x3 bombGenes[5] = new IntegerGene(conf, 0, mapController.getMaxY()); //y3 IChromosome bombsChromosome = new Chromosome(conf, bombGenes); conf.setSampleChromosome(bombsChromosome); // Ορίζεται το μέγεθος του πληθυσμού conf.setPopulationSize(populationSize); // Δημιουργείται ο τυχαίος πληθυσμός Genotype population = Genotype.randomInitialGenotype(conf); for (int i = 0; i < maxEvolutions; i++) { population.evolve(); // Εξέλιξη του πληθυσμού IChromosome bestSolutionSoFar = population.getFittestChromosome(); // Παίρνουμε το καλύτερο χρωμόσωμα... results[i] = bestSolutionSoFar; // ... και το τοποθετούμε στον πίνακα με τα καλύτερα χρωμοσώματα κάθε γενιάς } return results; } /** * Δημιουργεί αντικείμενο που περιγράφει τις παραμέτρους που θα χρησιμοποιηθούν για την επίλυση του προβλήματος * * @param mapController Χάρτης με τις τοποθεσίες των σφηκοφολιών * @param crossoverRate Ποσοστό ανασυνδυασμού * @param mutationRate Ποσοστό μετάλλαξης * @return Αντικείμενο ρυθμήσεων * @throws InvalidConfigurationException */ public static Configuration getConfiguration(MapController mapController, double crossoverRate, int mutationRate) throws InvalidConfigurationException { //Δημιουργία αντικειμένου ρυθμήσεων Configuration conf = new Configuration(); try { conf.setBreeder(new GABreeder()); conf.setRandomGenerator(new StockRandomGenerator()); conf.setEventManager(new EventManager()); conf.setMinimumPopSizePercent(0); // conf.setSelectFromPrevGen(1.0d); conf.setKeepPopulationSizeConstant(true); conf.setFitnessEvaluator(new DefaultFitnessEvaluator()); conf.setChromosomePool(new ChromosomePool()); conf.addGeneticOperator(new CrossoverOperator(conf, crossoverRate)); // ορισμός ποσοστού ανασυνδυασμού conf.addGeneticOperator(new MutationOperator(conf, mutationRate)); // ορισμός ποσοστού μετάλλαξης } catch (InvalidConfigurationException e) { throw new RuntimeException("Κάτι πήγε στραβά!"); } conf.setPreservFittestIndividual(true); // ενεργοποίηση ελιτισμού conf.setKeepPopulationSizeConstant(false); // σταθερό μέγεθος πληθυσμού // ορισμός συνάρτησης καταλληλότητας FitnessFunction myFunc = new WaspFitnessFunction(mapController); conf.setFitnessFunction(myFunc); return conf; } public static void main(String[] args) throws Exception { // Distance.initDistance(100, 100); MapController mapController = new MapController(new File("map.csv")); // φόρτωμα του χάρτη mapController.initSave(1); // αρχικοποίηση της δυνατότητας αποθήκευσης της κατάστασης του χάρτη mapController.saveMap(0); // αποθήκευση του χάρτη στη μνήμη printBestSolution(mapController); } /** * Εκτελεί τον γενετικό αλγόριθμο και εμφανίζει την καλύτερη λύση που βρέθηκε * * @param mapController Χάρτης με τις τοποθεσίες των σφηκοφολιών * @throws Exception */ private static void printBestSolution(MapController mapController) throws Exception { Configuration conf = getConfiguration(mapController, 0.80d, 12); BestChromosomesSelector bestChromsSelector = new BestChromosomesSelector(conf, 0.90d); bestChromsSelector.setDoubletteChromosomesAllowed(true); conf.addNaturalSelector(bestChromsSelector, false); IChromosome results[] = exterminate(conf, POPULATION_SIZE, MAX_EVOLUTIONS, mapController); IChromosome bestSolution = results[results.length - 1]; System.out.println("Η λύση που βρέθηκε σκοτώνει " + (int) bestSolution.getFitnessValue() + " σφήκες αν οι βόμβες τοποθετηθούν στις θέσεις:"); System.out.println("\t" + WaspFitnessFunction.getBombFromChromosome(bestSolution, 0)); System.out.println("\t" + WaspFitnessFunction.getBombFromChromosome(bestSolution, 1)); System.out.println("\t" + WaspFitnessFunction.getBombFromChromosome(bestSolution, 2)); } /** * Εκτελεί τον γενετικό αλγόριθμο και εμφανίζει τον μέσο όρο του fitness κάθε γενιάς * * @param mapController Χάρτης με τις τοποθεσίες των σφηκοφολιών * @throws Exception */ private static void averageSelectorFitness(MapController mapController) throws Exception { double avg[] = new double[MAX_EVOLUTIONS]; double total[] = new double[MAX_EVOLUTIONS]; for (int j = 0; j < SAMPLES; j++) { Configuration.reset(); Configuration conf = getConfiguration(mapController, 0.80d, 12); BestChromosomesSelector bestChromsSelector = new BestChromosomesSelector(conf, 0.90d); bestChromsSelector.setDoubletteChromosomesAllowed(true); conf.addNaturalSelector(bestChromsSelector, false); // NaturalSelector weightedRouletteSelector = new WeightedRouletteSelector(conf); // conf.addNaturalSelector(weightedRouletteSelector, false); // TournamentSelector tournamentSelector = new TournamentSelector(conf, 10, 0.8); // conf.addNaturalSelector(tournamentSelector, false); IChromosome results[] = exterminate(conf, POPULATION_SIZE, MAX_EVOLUTIONS, mapController); for (int i = 0; i < MAX_EVOLUTIONS; i++) { total[i] += results[i].getFitnessValue(); } System.out.println(j); } for (int i = 0; i < MAX_EVOLUTIONS; i++) { avg[i] = total[i] / SAMPLES; System.out.println(i + "," + avg[i]); } } /** * Εκτελεί τον γενετικό αλγόριθμο και εμφανίζει τον μέσο όρο του καλύτερου fitness, αλλάζοντας κάθε φορά * το ποσοστό ανασυνδυασμού * * @param mapController Χάρτης με τις τοποθεσίες των σφηκοφολιών * @throws Exception */ private static void crossoverRateTest(MapController mapController) throws Exception { double avg[] = new double[101]; for (int i = 1; i <= 100; i++) { double total = 0; for (int j = 0; j < SAMPLES; j++) { Configuration.reset(); Configuration conf = getConfiguration(mapController, i / 100.0, 12); BestChromosomesSelector bestChromsSelector = new BestChromosomesSelector(conf, 0.90d); bestChromsSelector.setDoubletteChromosomesAllowed(true); conf.addNaturalSelector(bestChromsSelector, false); total += exterminate(conf, POPULATION_SIZE, MAX_EVOLUTIONS, mapController)[MAX_EVOLUTIONS - 1].getFitnessValue(); } avg[i] = total / SAMPLES; System.out.println(i + "," + avg[i]); } } }
sortingbubbles/wasp-control
src/MainJGAP.java
3,376
// σταθερό μέγεθος πληθυσμού
line_comment
el
import org.jgap.*; import org.jgap.event.EventManager; import org.jgap.impl.*; import java.io.File; public class MainJGAP { /** * Το μέγεθος του πληθυσμού */ private static final int POPULATION_SIZE = 100; /** * Πόσες φορές θα γίνει δειγματοληψία για τον υπολογισμό του μέσου όρου (όπου χρειάζεται) */ private static final int SAMPLES = 100; /** * Μέγιστος αριθμός γενεών */ private static final int MAX_EVOLUTIONS = 1000; /** * Υπολογίζει την λύση του προβλήματος * * @param conf Αντικείμενο ρυθμίσεων * @param populationSize Μέγεθος πληθυσμού * @param maxEvolutions Μέγιστος αριθμός γενεών * @param mapController Χάρτης με τις τοποθεσίες των σφηκοφολιών * @return Πίνακας που περιέχει το καλύτερο χρωμόσωμα κάθε γενιάς * @throws Exception */ public static IChromosome[] exterminate(Configuration conf, int populationSize, int maxEvolutions, MapController mapController) throws Exception { IChromosome[] results = new IChromosome[maxEvolutions]; // Πίνακας που περιέχει το καλύτερο χρωμόσωμα κάθε γενιάς // Το χρωμόσωμα θα αποτελέιται από 6 γονίδια. Τα δύο πρώτα θα αποτελούν τις συντεταγμένες της πρώτης βόμβας, // τα επόμενα δύο τις συντεταγμένες της δεύτερης βόμβας, και τα υπόλοιπα δύο τις συντεταγμένες της τρίτης βόμβας Gene[] bombGenes = new Gene[6]; bombGenes[0] = new IntegerGene(conf, 0, mapController.getMaxX()); //x1 bombGenes[1] = new IntegerGene(conf, 0, mapController.getMaxY()); //y1 bombGenes[2] = new IntegerGene(conf, 0, mapController.getMaxX()); //x2 bombGenes[3] = new IntegerGene(conf, 0, mapController.getMaxY()); //y2 bombGenes[4] = new IntegerGene(conf, 0, mapController.getMaxX()); //x3 bombGenes[5] = new IntegerGene(conf, 0, mapController.getMaxY()); //y3 IChromosome bombsChromosome = new Chromosome(conf, bombGenes); conf.setSampleChromosome(bombsChromosome); // Ορίζεται το μέγεθος του πληθυσμού conf.setPopulationSize(populationSize); // Δημιουργείται ο τυχαίος πληθυσμός Genotype population = Genotype.randomInitialGenotype(conf); for (int i = 0; i < maxEvolutions; i++) { population.evolve(); // Εξέλιξη του πληθυσμού IChromosome bestSolutionSoFar = population.getFittestChromosome(); // Παίρνουμε το καλύτερο χρωμόσωμα... results[i] = bestSolutionSoFar; // ... και το τοποθετούμε στον πίνακα με τα καλύτερα χρωμοσώματα κάθε γενιάς } return results; } /** * Δημιουργεί αντικείμενο που περιγράφει τις παραμέτρους που θα χρησιμοποιηθούν για την επίλυση του προβλήματος * * @param mapController Χάρτης με τις τοποθεσίες των σφηκοφολιών * @param crossoverRate Ποσοστό ανασυνδυασμού * @param mutationRate Ποσοστό μετάλλαξης * @return Αντικείμενο ρυθμήσεων * @throws InvalidConfigurationException */ public static Configuration getConfiguration(MapController mapController, double crossoverRate, int mutationRate) throws InvalidConfigurationException { //Δημιουργία αντικειμένου ρυθμήσεων Configuration conf = new Configuration(); try { conf.setBreeder(new GABreeder()); conf.setRandomGenerator(new StockRandomGenerator()); conf.setEventManager(new EventManager()); conf.setMinimumPopSizePercent(0); // conf.setSelectFromPrevGen(1.0d); conf.setKeepPopulationSizeConstant(true); conf.setFitnessEvaluator(new DefaultFitnessEvaluator()); conf.setChromosomePool(new ChromosomePool()); conf.addGeneticOperator(new CrossoverOperator(conf, crossoverRate)); // ορισμός ποσοστού ανασυνδυασμού conf.addGeneticOperator(new MutationOperator(conf, mutationRate)); // ορισμός ποσοστού μετάλλαξης } catch (InvalidConfigurationException e) { throw new RuntimeException("Κάτι πήγε στραβά!"); } conf.setPreservFittestIndividual(true); // ενεργοποίηση ελιτισμού conf.setKeepPopulationSizeConstant(false); // σταθερό μέγεθος<SUF> // ορισμός συνάρτησης καταλληλότητας FitnessFunction myFunc = new WaspFitnessFunction(mapController); conf.setFitnessFunction(myFunc); return conf; } public static void main(String[] args) throws Exception { // Distance.initDistance(100, 100); MapController mapController = new MapController(new File("map.csv")); // φόρτωμα του χάρτη mapController.initSave(1); // αρχικοποίηση της δυνατότητας αποθήκευσης της κατάστασης του χάρτη mapController.saveMap(0); // αποθήκευση του χάρτη στη μνήμη printBestSolution(mapController); } /** * Εκτελεί τον γενετικό αλγόριθμο και εμφανίζει την καλύτερη λύση που βρέθηκε * * @param mapController Χάρτης με τις τοποθεσίες των σφηκοφολιών * @throws Exception */ private static void printBestSolution(MapController mapController) throws Exception { Configuration conf = getConfiguration(mapController, 0.80d, 12); BestChromosomesSelector bestChromsSelector = new BestChromosomesSelector(conf, 0.90d); bestChromsSelector.setDoubletteChromosomesAllowed(true); conf.addNaturalSelector(bestChromsSelector, false); IChromosome results[] = exterminate(conf, POPULATION_SIZE, MAX_EVOLUTIONS, mapController); IChromosome bestSolution = results[results.length - 1]; System.out.println("Η λύση που βρέθηκε σκοτώνει " + (int) bestSolution.getFitnessValue() + " σφήκες αν οι βόμβες τοποθετηθούν στις θέσεις:"); System.out.println("\t" + WaspFitnessFunction.getBombFromChromosome(bestSolution, 0)); System.out.println("\t" + WaspFitnessFunction.getBombFromChromosome(bestSolution, 1)); System.out.println("\t" + WaspFitnessFunction.getBombFromChromosome(bestSolution, 2)); } /** * Εκτελεί τον γενετικό αλγόριθμο και εμφανίζει τον μέσο όρο του fitness κάθε γενιάς * * @param mapController Χάρτης με τις τοποθεσίες των σφηκοφολιών * @throws Exception */ private static void averageSelectorFitness(MapController mapController) throws Exception { double avg[] = new double[MAX_EVOLUTIONS]; double total[] = new double[MAX_EVOLUTIONS]; for (int j = 0; j < SAMPLES; j++) { Configuration.reset(); Configuration conf = getConfiguration(mapController, 0.80d, 12); BestChromosomesSelector bestChromsSelector = new BestChromosomesSelector(conf, 0.90d); bestChromsSelector.setDoubletteChromosomesAllowed(true); conf.addNaturalSelector(bestChromsSelector, false); // NaturalSelector weightedRouletteSelector = new WeightedRouletteSelector(conf); // conf.addNaturalSelector(weightedRouletteSelector, false); // TournamentSelector tournamentSelector = new TournamentSelector(conf, 10, 0.8); // conf.addNaturalSelector(tournamentSelector, false); IChromosome results[] = exterminate(conf, POPULATION_SIZE, MAX_EVOLUTIONS, mapController); for (int i = 0; i < MAX_EVOLUTIONS; i++) { total[i] += results[i].getFitnessValue(); } System.out.println(j); } for (int i = 0; i < MAX_EVOLUTIONS; i++) { avg[i] = total[i] / SAMPLES; System.out.println(i + "," + avg[i]); } } /** * Εκτελεί τον γενετικό αλγόριθμο και εμφανίζει τον μέσο όρο του καλύτερου fitness, αλλάζοντας κάθε φορά * το ποσοστό ανασυνδυασμού * * @param mapController Χάρτης με τις τοποθεσίες των σφηκοφολιών * @throws Exception */ private static void crossoverRateTest(MapController mapController) throws Exception { double avg[] = new double[101]; for (int i = 1; i <= 100; i++) { double total = 0; for (int j = 0; j < SAMPLES; j++) { Configuration.reset(); Configuration conf = getConfiguration(mapController, i / 100.0, 12); BestChromosomesSelector bestChromsSelector = new BestChromosomesSelector(conf, 0.90d); bestChromsSelector.setDoubletteChromosomesAllowed(true); conf.addNaturalSelector(bestChromsSelector, false); total += exterminate(conf, POPULATION_SIZE, MAX_EVOLUTIONS, mapController)[MAX_EVOLUTIONS - 1].getFitnessValue(); } avg[i] = total / SAMPLES; System.out.println(i + "," + avg[i]); } } }
816_8
 package pkg2521; import java.awt.Point; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * @author Sotiria Antaranian * * η πολυπλοκότητα σύμφωνα με την πηγή είναι O(n*log n) στη μέση περίπτωση */ public class QuickHull { /** * συνάρτηση που προσδιορίζει τη θέση ενός σημείου p σε σχέση με την ευθεία που σχηματίζουν τα σημεία a και b. * η εξίσωση της ευθείας είναι : (x_b-x_a)*(y-y_a)-(y_b-y_a)*(x-x_a)=0 . * αν για x,y βάλουμε τις συντεταγμενες του σημείου p και το αποτέλεσμα είναι θετικό, τότε το σημείο βρίσκεται πάνω από την ευθεία. * αν είναι αρνητικό, βρίσκεται κάτω από την ευθεία και αν είναι 0, τότε βρίσκεται πάνω στην ευθεία. * πηγή : http://www.sanfoundry.com/java-program-implement-quick-hull-algorithm-find-convex-hull/ * @param a * @param b τα σημεία που σχηματίζουν την ευθεία * @param p το σημείο του οποίου αναζητάται η θέση σε σχέση με την ευθεία * @return επιστρέφει 1 αν βρίσκεται πάνω από την ευθεία, 0 αν είναι πάνω στην ευθεία και -1 αν είναι κάτω από την ευθεία */ public int isAboveTheLine (Point a,Point b,Point p) { int cp1=(int) ((b.getX()-a.getX())*(p.getY()-a.getY())-(b.getY()-a.getY())*(p.getX()-a.getX())); // ευθεία των a,b με τις συντεταγμένες του p για x,y if (cp1>0) return 1;// πάνω από την ευθεία else if (cp1==0) return 0; // πάνω στην ευθεία else return -1; // κάτω από την ευθεία } /** * συνάρτηση που εκτελεί τον αλγόριθμο quick hull (ο κώδικας περιέχει πιο αναλυτικά σχόλια) * @param inputPoints τα σημεία της εισόδου * @param start το πιο αριστερό σημείο * @param finish το πιο δεξί σημείο * @return λίστα με τα σημεία με την συντομότερη διαδρομή από το start στο finish */ public List<Point> executeQuickHull(List<Point> inputPoints,Point start,Point finish) { double distance1; double distance2; if(inputPoints.isEmpty()) { throw new IllegalArgumentException("Cannot compute convex hull of zero points."); } List<Point> leftOfLine = new LinkedList<>(); List<Point> rightOfLine = new LinkedList<>(); for(Point point : inputPoints) {// χωρισμός των σημείων με βάση το αν βρίσκονται πάνω από την ευθεία που σχηματίζουν η εκκίνηση και το τέρμα if(isAboveTheLine(start,finish, point)==-1) leftOfLine.add(point); else rightOfLine.add(point); } // εύρεση διαδρομή για τα πάνω σημεία και το μήκος της List<Point> hullUp=divide(leftOfLine, finish, start); distance1=distance(hullUp,start,finish); // εύρεση διαδρομής για τα κάτω σημεία και το μήκος της List<Point> hullDown=divide(rightOfLine, start, finish); distance2=distance(hullDown,start,finish); // εύρεση συντομότερης διαδρομής η οποία είναι και η λύση if(distance1<distance2) return hullUp; else return hullDown; } /** * συνάρτηση η οποία υπολογίζει το συνολικό μήκος της διαδρομής που σχηματίζουν τα σημεία της λίστας h * @param h λίστα με τα σημεία * @param start * @param finish * @return το μήκος */ public double distance (List<Point> h,Point start,Point finish) { double a,b,dis=0.0; for(int i=0;i<h.size();i++) { if(i==0) //το πρώτο σημείο της λίστας για το οποίο πρέπει να βρεθεί η ευκλείδεια απόστασή του από το start { a=Math.pow(start.getX()-h.get(i).getX(),2); b=Math.pow(start.getY()-h.get(i).getY(),2); dis=dis+Math.sqrt(a+b); } if(i==h.size()-1) // το τελευταίο σημείο της λίστας για το οποίο πρέπει να βρεθεί η απόστασή του από το finish { a=Math.pow(finish.getX()-h.get(i).getX(),2); b=Math.pow(finish.getY()-h.get(i).getY(),2); dis=dis+Math.sqrt(a+b); } else // οι μεταξύ τους αποστάσεις για όλα τα σημεία εκτός από το τελευταίο που δεν έχει επόμενο (οπότε το i+1 δεν έχει νόημα) { a=Math.pow(h.get(i+1).getX()-h.get(i).getX(),2); b=Math.pow(h.get(i+1).getY()-h.get(i).getY(),2); dis=dis+Math.sqrt(a+b); } } return dis; } /** * πηγή : https://github.com/Thurion/algolab/blob/master/src/info/hska/convexhull/QuickHull.java#L22 * (ο κώδικας περιέχει πιο αναλυτικά σχόλια) * ανδρομική συνάρτηση που βρίσκει το πιο μακρινό σημείο της λίστας points από την ευθεία που σχηματίζουν τα p1,p2 και το προσθέτει στη λίστα την οποία τελικά επιστρέφει * @param points λίστα με τα σημεία * @param p1 * @param p2 * @return επιστρέφει λίστα με τα πιο ακριανά σημεία */ public List<Point> divide(List<Point> points, Point p1, Point p2) { List<Point> hull = new ArrayList<>(); if(points.isEmpty()) return hull; else if(points.size()==1) { hull.add(points.get(0)); return hull; } Point maxDistancePoint=points.get(0); List<Point> l1=new LinkedList<>(); List<Point> l2=new LinkedList<>(); double distance=0.0; for (Point point : points) {// εύρεση σημείου με την μεγαλύτερη απόσταση από την ευθεία που σχηματίζουν τα σημεία p1,p2 if (distanceToLine(p1,p2,point) > distance) { distance=distanceToLine(p1,p2,point); maxDistancePoint=point; } } points.remove(maxDistancePoint); // τα σημεία που βρίσκονται πάνω από την ευθεία που σχηματιζουν τα p1 και το σημείο με τη μέγιστη απόσταση μπαίνουν σε λίστα // τα σημεία που βρίσκονται πάνω από την ευθεία που σχηματίζουν τα p2 και το σημείο με τη μέγιστη απόσταση μπαίνουν σε λίστα for (Point point : points) { if (isAboveTheLine(p1,maxDistancePoint,point)==1) l1.add(point); if (isAboveTheLine(maxDistancePoint,p2,point)==1) l2.add(point); } points.clear(); // καλείται αναδρομικά η συνάρτηση και για τις δυο λίστες List <Point> hullPart=divide(l1,p1,maxDistancePoint); hull.addAll(hullPart); hull.add(maxDistancePoint); hullPart=divide(l2,maxDistancePoint,p2); hull.addAll(hullPart); return hull; } /** * εκτελεί τον κλασσικό τύπο για την εύρεση απόστασης σημείου από ευθεία * @param p1 * @param p2 τα δυο σημεία που σχηματίζουν την ευθεία * @param p το σημείο για το οποίο ζητάται η απόστασή του από την ευθεία * @return επιστρέφει την απόσταση */ public double distanceToLine (Point p1,Point p2,Point p) { double dis; double p12x=p2.getX()-p1.getX(); double p12y=p2.getY()-p1.getY(); dis=(p12x*(p1.getY()- p.getY())-p12y*(p1.getX()-p.getX()))/Math.sqrt(Math.pow(p12x,2)+Math.pow(p12y,2)); if (dis<0) dis=-dis; return dis; } }
sotiria3103/quick-hull-treasure
src/pkg2521/QuickHull.java
3,458
// εύρεση διαδρομή για τα πάνω σημεία και το μήκος της
line_comment
el
 package pkg2521; import java.awt.Point; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * @author Sotiria Antaranian * * η πολυπλοκότητα σύμφωνα με την πηγή είναι O(n*log n) στη μέση περίπτωση */ public class QuickHull { /** * συνάρτηση που προσδιορίζει τη θέση ενός σημείου p σε σχέση με την ευθεία που σχηματίζουν τα σημεία a και b. * η εξίσωση της ευθείας είναι : (x_b-x_a)*(y-y_a)-(y_b-y_a)*(x-x_a)=0 . * αν για x,y βάλουμε τις συντεταγμενες του σημείου p και το αποτέλεσμα είναι θετικό, τότε το σημείο βρίσκεται πάνω από την ευθεία. * αν είναι αρνητικό, βρίσκεται κάτω από την ευθεία και αν είναι 0, τότε βρίσκεται πάνω στην ευθεία. * πηγή : http://www.sanfoundry.com/java-program-implement-quick-hull-algorithm-find-convex-hull/ * @param a * @param b τα σημεία που σχηματίζουν την ευθεία * @param p το σημείο του οποίου αναζητάται η θέση σε σχέση με την ευθεία * @return επιστρέφει 1 αν βρίσκεται πάνω από την ευθεία, 0 αν είναι πάνω στην ευθεία και -1 αν είναι κάτω από την ευθεία */ public int isAboveTheLine (Point a,Point b,Point p) { int cp1=(int) ((b.getX()-a.getX())*(p.getY()-a.getY())-(b.getY()-a.getY())*(p.getX()-a.getX())); // ευθεία των a,b με τις συντεταγμένες του p για x,y if (cp1>0) return 1;// πάνω από την ευθεία else if (cp1==0) return 0; // πάνω στην ευθεία else return -1; // κάτω από την ευθεία } /** * συνάρτηση που εκτελεί τον αλγόριθμο quick hull (ο κώδικας περιέχει πιο αναλυτικά σχόλια) * @param inputPoints τα σημεία της εισόδου * @param start το πιο αριστερό σημείο * @param finish το πιο δεξί σημείο * @return λίστα με τα σημεία με την συντομότερη διαδρομή από το start στο finish */ public List<Point> executeQuickHull(List<Point> inputPoints,Point start,Point finish) { double distance1; double distance2; if(inputPoints.isEmpty()) { throw new IllegalArgumentException("Cannot compute convex hull of zero points."); } List<Point> leftOfLine = new LinkedList<>(); List<Point> rightOfLine = new LinkedList<>(); for(Point point : inputPoints) {// χωρισμός των σημείων με βάση το αν βρίσκονται πάνω από την ευθεία που σχηματίζουν η εκκίνηση και το τέρμα if(isAboveTheLine(start,finish, point)==-1) leftOfLine.add(point); else rightOfLine.add(point); } // εύρεση διαδρομή<SUF> List<Point> hullUp=divide(leftOfLine, finish, start); distance1=distance(hullUp,start,finish); // εύρεση διαδρομής για τα κάτω σημεία και το μήκος της List<Point> hullDown=divide(rightOfLine, start, finish); distance2=distance(hullDown,start,finish); // εύρεση συντομότερης διαδρομής η οποία είναι και η λύση if(distance1<distance2) return hullUp; else return hullDown; } /** * συνάρτηση η οποία υπολογίζει το συνολικό μήκος της διαδρομής που σχηματίζουν τα σημεία της λίστας h * @param h λίστα με τα σημεία * @param start * @param finish * @return το μήκος */ public double distance (List<Point> h,Point start,Point finish) { double a,b,dis=0.0; for(int i=0;i<h.size();i++) { if(i==0) //το πρώτο σημείο της λίστας για το οποίο πρέπει να βρεθεί η ευκλείδεια απόστασή του από το start { a=Math.pow(start.getX()-h.get(i).getX(),2); b=Math.pow(start.getY()-h.get(i).getY(),2); dis=dis+Math.sqrt(a+b); } if(i==h.size()-1) // το τελευταίο σημείο της λίστας για το οποίο πρέπει να βρεθεί η απόστασή του από το finish { a=Math.pow(finish.getX()-h.get(i).getX(),2); b=Math.pow(finish.getY()-h.get(i).getY(),2); dis=dis+Math.sqrt(a+b); } else // οι μεταξύ τους αποστάσεις για όλα τα σημεία εκτός από το τελευταίο που δεν έχει επόμενο (οπότε το i+1 δεν έχει νόημα) { a=Math.pow(h.get(i+1).getX()-h.get(i).getX(),2); b=Math.pow(h.get(i+1).getY()-h.get(i).getY(),2); dis=dis+Math.sqrt(a+b); } } return dis; } /** * πηγή : https://github.com/Thurion/algolab/blob/master/src/info/hska/convexhull/QuickHull.java#L22 * (ο κώδικας περιέχει πιο αναλυτικά σχόλια) * ανδρομική συνάρτηση που βρίσκει το πιο μακρινό σημείο της λίστας points από την ευθεία που σχηματίζουν τα p1,p2 και το προσθέτει στη λίστα την οποία τελικά επιστρέφει * @param points λίστα με τα σημεία * @param p1 * @param p2 * @return επιστρέφει λίστα με τα πιο ακριανά σημεία */ public List<Point> divide(List<Point> points, Point p1, Point p2) { List<Point> hull = new ArrayList<>(); if(points.isEmpty()) return hull; else if(points.size()==1) { hull.add(points.get(0)); return hull; } Point maxDistancePoint=points.get(0); List<Point> l1=new LinkedList<>(); List<Point> l2=new LinkedList<>(); double distance=0.0; for (Point point : points) {// εύρεση σημείου με την μεγαλύτερη απόσταση από την ευθεία που σχηματίζουν τα σημεία p1,p2 if (distanceToLine(p1,p2,point) > distance) { distance=distanceToLine(p1,p2,point); maxDistancePoint=point; } } points.remove(maxDistancePoint); // τα σημεία που βρίσκονται πάνω από την ευθεία που σχηματιζουν τα p1 και το σημείο με τη μέγιστη απόσταση μπαίνουν σε λίστα // τα σημεία που βρίσκονται πάνω από την ευθεία που σχηματίζουν τα p2 και το σημείο με τη μέγιστη απόσταση μπαίνουν σε λίστα for (Point point : points) { if (isAboveTheLine(p1,maxDistancePoint,point)==1) l1.add(point); if (isAboveTheLine(maxDistancePoint,p2,point)==1) l2.add(point); } points.clear(); // καλείται αναδρομικά η συνάρτηση και για τις δυο λίστες List <Point> hullPart=divide(l1,p1,maxDistancePoint); hull.addAll(hullPart); hull.add(maxDistancePoint); hullPart=divide(l2,maxDistancePoint,p2); hull.addAll(hullPart); return hull; } /** * εκτελεί τον κλασσικό τύπο για την εύρεση απόστασης σημείου από ευθεία * @param p1 * @param p2 τα δυο σημεία που σχηματίζουν την ευθεία * @param p το σημείο για το οποίο ζητάται η απόστασή του από την ευθεία * @return επιστρέφει την απόσταση */ public double distanceToLine (Point p1,Point p2,Point p) { double dis; double p12x=p2.getX()-p1.getX(); double p12y=p2.getY()-p1.getY(); dis=(p12x*(p1.getY()- p.getY())-p12y*(p1.getX()-p.getX()))/Math.sqrt(Math.pow(p12x,2)+Math.pow(p12y,2)); if (dis<0) dis=-dis; return dis; } }
1662_4
 package aem2521; import java.util.ArrayList; import java.util.List; /** * @author Sotiria Antaranian */ public class KnapSack { List<Integer> accepted; //λίστα με τους πελάτες που δέχεται /** * συγκρίνει δυο πραγματικούς αριθμούς και επιστρέφει το μεγαλύτερο * @param a * @param b * @return το μεγαλύτερο */ float max(float a, float b) { return (a > b)? a : b; } /** * Η δεύτερη λειτουργία λύνεται όπως το πρόβλημα του σάκου, δυναμικά, όπου η χωρητικότητα του σάκου είναι οι διαθέσιμοι πυρήνες σε όλους τους servers, * τα βάρη των στοιχείων είναι οι απαιτήσεις σε πυρήνες του κάθε πελάτη, * η αξία κάθε στοιχείου είναι το συνολικό ποσό που θα πληρώσει ο κάθε πελάτης σύμφωνα με την προσφορά του ανά πυρήνα και * το πλήθος των στοιχείων είναι το πλήθος των πελατών. * Σκοπός είναι να βρεθεί το πολυτιμότερο υποσύνολο των στοιχείων που χωράνε στο σάκο. * Για κάθε στοιχείο θα ισχύουν δυο περιπτώσεις: είτε δεν θα χωράει (wt[i-1]>w), οπότε η βέλτιστη λύση θα είναι ίδια με την περίπτωση για i-1 στοιχεία, * είτε χωράει αλλά θα μπει αν val[i-1]+V[i-1][w-wt[i-1]] > V[i-1][w] , αλλιώς δεν θα μπει και η βέλτιστη λύση θα είναι πάλι η ίδια με την περίπτωση για i-1 στοιχεία. * Η πολυπλοκότητα, χωρική και χρονική, του προβλήματος του σάκου είναι Θ(n*W) όπου n το πλήθος των στοιχείων και W η χωριτηκότητα του σάκου και προκύπτει από τα εμφολευμένα δύο for. * * Για την εύρεση των πελατών που γίνονται δεκτοί, ξεκινώντας από το τελευταίο δεξιά κελί του πίνακα που προέκυψε από την εκτέλεση του αλγορίθμου knap sack, * συγκρίνουμε κάθε κελί με το κελί πάνω του και αν είναι διαφορετικό τότε ο πελάτης που πρέπει να πληρώσει το ποσό του κελιού γίνεται δεκτός. * Σε αυτή την περίπτωση μετακινούμαστε προς τα αριστερά στο πίνακα, στο κελί που βρίσκεται στη στήλη για τους διαθέσιμους πυρήνες χωρίς τους πυρήνες που ζήτησε ο πελάτης που έγινε δεκτός,στην ακριβώς από πάνω γραμμή. * Μετά συγκρίνουμε το περιεχόμενο του κελιού με το από πάνω του κ.ο.κ. * Σε κάθε περίπτωση, αν τα κελιά που συγκρίνουμε είναι ίδια, πάμε στην ακριβώς από πάνω γραμμή (στην ίδια στήλη) και συγκρίνουμε το κελί σε αυτή τη γραμμή με το από πάνω του κ.ο.κ. * Για την εύρεση των αποδεκτών πελατών η πολυπλοκότητα είναι Ο(n+W) στη χειρότερη περίπτωση. * Η συνολική πολυπλοκότητα είναι Ο(n*W+n+W). * * @param W η χωρητικότητα του σάκου * @param wt πίνακας με τα βάρη των n στοιχείων * @param val πίνακας με την αξία του κάθε στοιχείου * @param n το πλήθος των στοιχείων * @return συνολικό ποσό πληρωμής από όλους τους πελάτες */ float knapSack(int W,int wt[],float val[],int n) { accepted=new ArrayList<>(); float [][]V=new float[n+1][W+1]; for(int i=0;i<=n;i++) //πολυπλοκότητα Ο(n) { for(int w=0;w<=W;w++) //πολυπλοκότητα O(W) { if(i==0 || w==0) V[i][w]=0; else if(wt[i-1]-w<=0) //χωράει V[i][w]=max(val[i-1]+V[i-1][w-wt[i-1]],V[i-1][w]); else //δεν χωράει V[i][w]=V[i-1][w]; } } int k=n; int j=W; while(j!=0) { if(V[k][j]!=V[k-1][j]) //δεκτός πελάτης { accepted.add(k); j=j-wt[k-1]; //αλλαγή στήλης } k--; //αλλαγή γραμμής if(k==0)//αν όλα τα στοιχεία μιας στήλης είναι ίδια, πάει στο τελευταίο στοιχείο της αριστερής του στήλης { k=n; j--; } } return V[n][W]; } }
sotiria3103/visual-machine-assigning
src/aem2521/KnapSack.java
2,402
//αν όλα τα στοιχεία μιας στήλης είναι ίδια, πάει στο τελευταίο στοιχείο της αριστερής του στήλης
line_comment
el
 package aem2521; import java.util.ArrayList; import java.util.List; /** * @author Sotiria Antaranian */ public class KnapSack { List<Integer> accepted; //λίστα με τους πελάτες που δέχεται /** * συγκρίνει δυο πραγματικούς αριθμούς και επιστρέφει το μεγαλύτερο * @param a * @param b * @return το μεγαλύτερο */ float max(float a, float b) { return (a > b)? a : b; } /** * Η δεύτερη λειτουργία λύνεται όπως το πρόβλημα του σάκου, δυναμικά, όπου η χωρητικότητα του σάκου είναι οι διαθέσιμοι πυρήνες σε όλους τους servers, * τα βάρη των στοιχείων είναι οι απαιτήσεις σε πυρήνες του κάθε πελάτη, * η αξία κάθε στοιχείου είναι το συνολικό ποσό που θα πληρώσει ο κάθε πελάτης σύμφωνα με την προσφορά του ανά πυρήνα και * το πλήθος των στοιχείων είναι το πλήθος των πελατών. * Σκοπός είναι να βρεθεί το πολυτιμότερο υποσύνολο των στοιχείων που χωράνε στο σάκο. * Για κάθε στοιχείο θα ισχύουν δυο περιπτώσεις: είτε δεν θα χωράει (wt[i-1]>w), οπότε η βέλτιστη λύση θα είναι ίδια με την περίπτωση για i-1 στοιχεία, * είτε χωράει αλλά θα μπει αν val[i-1]+V[i-1][w-wt[i-1]] > V[i-1][w] , αλλιώς δεν θα μπει και η βέλτιστη λύση θα είναι πάλι η ίδια με την περίπτωση για i-1 στοιχεία. * Η πολυπλοκότητα, χωρική και χρονική, του προβλήματος του σάκου είναι Θ(n*W) όπου n το πλήθος των στοιχείων και W η χωριτηκότητα του σάκου και προκύπτει από τα εμφολευμένα δύο for. * * Για την εύρεση των πελατών που γίνονται δεκτοί, ξεκινώντας από το τελευταίο δεξιά κελί του πίνακα που προέκυψε από την εκτέλεση του αλγορίθμου knap sack, * συγκρίνουμε κάθε κελί με το κελί πάνω του και αν είναι διαφορετικό τότε ο πελάτης που πρέπει να πληρώσει το ποσό του κελιού γίνεται δεκτός. * Σε αυτή την περίπτωση μετακινούμαστε προς τα αριστερά στο πίνακα, στο κελί που βρίσκεται στη στήλη για τους διαθέσιμους πυρήνες χωρίς τους πυρήνες που ζήτησε ο πελάτης που έγινε δεκτός,στην ακριβώς από πάνω γραμμή. * Μετά συγκρίνουμε το περιεχόμενο του κελιού με το από πάνω του κ.ο.κ. * Σε κάθε περίπτωση, αν τα κελιά που συγκρίνουμε είναι ίδια, πάμε στην ακριβώς από πάνω γραμμή (στην ίδια στήλη) και συγκρίνουμε το κελί σε αυτή τη γραμμή με το από πάνω του κ.ο.κ. * Για την εύρεση των αποδεκτών πελατών η πολυπλοκότητα είναι Ο(n+W) στη χειρότερη περίπτωση. * Η συνολική πολυπλοκότητα είναι Ο(n*W+n+W). * * @param W η χωρητικότητα του σάκου * @param wt πίνακας με τα βάρη των n στοιχείων * @param val πίνακας με την αξία του κάθε στοιχείου * @param n το πλήθος των στοιχείων * @return συνολικό ποσό πληρωμής από όλους τους πελάτες */ float knapSack(int W,int wt[],float val[],int n) { accepted=new ArrayList<>(); float [][]V=new float[n+1][W+1]; for(int i=0;i<=n;i++) //πολυπλοκότητα Ο(n) { for(int w=0;w<=W;w++) //πολυπλοκότητα O(W) { if(i==0 || w==0) V[i][w]=0; else if(wt[i-1]-w<=0) //χωράει V[i][w]=max(val[i-1]+V[i-1][w-wt[i-1]],V[i-1][w]); else //δεν χωράει V[i][w]=V[i-1][w]; } } int k=n; int j=W; while(j!=0) { if(V[k][j]!=V[k-1][j]) //δεκτός πελάτης { accepted.add(k); j=j-wt[k-1]; //αλλαγή στήλης } k--; //αλλαγή γραμμής if(k==0)//αν όλα<SUF> { k=n; j--; } } return V[n][W]; } }
5817_4
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gr.csd.uoc.cs359.winter2017.lq; import gr.csd.uoc.cs359.winter2017.lq.db.CommentDB; import gr.csd.uoc.cs359.winter2017.lq.db.DelegatedDB; import gr.csd.uoc.cs359.winter2017.lq.db.InitiativeDB; import gr.csd.uoc.cs359.winter2017.lq.db.RatingDB; import gr.csd.uoc.cs359.winter2017.lq.db.UserDB; import gr.csd.uoc.cs359.winter2017.lq.db.VoteDB; import gr.csd.uoc.cs359.winter2017.lq.model.Comment; import gr.csd.uoc.cs359.winter2017.lq.model.Delegated; import gr.csd.uoc.cs359.winter2017.lq.model.Initiative; import gr.csd.uoc.cs359.winter2017.lq.model.Rating; import gr.csd.uoc.cs359.winter2017.lq.model.User; import gr.csd.uoc.cs359.winter2017.lq.model.Vote; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; /** * * @author papadako */ public class ExampleAPI { /** * An example of adding a new member in the database. Turing is a user of * our system * * @param args the command line arguments * @throws ClassNotFoundException */ public static void main(String[] args) throws ClassNotFoundException, InterruptedException { // O Turing έσπασε τον κώδικα enigma που χρησιμοποιούσαν οι Γερμανοί // στον Παγκόσμιο Πόλεμο ΙΙ για να κρυπτογραφήσουν την επικοινωνία τους. // Άρα είναι πιθανό να χρησιμοποιούσε σαν passwd τη λέξη enigma, κάπως // τροποποιημένη :) // http://en.wikipedia.org/wiki/Enigma_machine // md5 της λέξης 3n!gm@ είναι e37f7cfcb0cd53734184de812b5c6175 User turing = new User(); turing.setUserName("turing"); turing.setEmail("[email protected]"); turing.setPassword("e37f7cfcb0cd53734184de812b5c6175"); turing.setFirstName("Alan"); turing.setLastName("Turing"); turing.setBirthDate("07/07/1912"); turing.setCountry("Science"); turing.setTown("Computer Science"); turing.setAddress("Computability"); turing.setOccupation("Xompistas"); turing.setGender("Male"); turing.setInterests("Enigma, decyphering"); turing.setInfo("You will have a job due to my work! :)"); if (UserDB.checkValidUserName("papadako")) { // Add turing to database UserDB.addUser(turing); } else { System.out.println("User already exists.... Not more Turings please!"); } List<User> users = UserDB.getUsers(); int i = 0; for (User user : users) { System.out.println("user:" + i++); System.out.println(user); } // Add a wish as info turing.setInfo("I hope you follow my path..."); turing.setEmail("[email protected]"); UserDB.updateUser(turing); System.out.println(UserDB.getUser("turing")); // Check initiatives Initiative initiative = new Initiative(); initiative.setCreator("turing"); initiative.setTitle("Halting Problem"); initiative.setCategory("Computability"); initiative.setDescription("In computability theory, the halting problem is the problem of determining, from a description of an arbitrary computer program and an input, whether the program will finish running or continue to run forever."); initiative.setStatus(0); InitiativeDB.addInitiative(initiative); System.out.println(initiative.toString()); //UserDB.deleteUser("turing"); if (UserDB.checkValidUserName("turing")) { // You can be a new Turing! System.out.println("Well, Turing is gone for a long time now!"); System.out.println("Hope we find a new one in this 2017 class!"); } initiative.setStatus(1); InitiativeDB.updateInitiative(initiative); System.out.println(initiative.toString()); int initID = initiative.getId(); Vote vote = new Vote(); vote.setUser("papadako"); vote.setInitiativeID(initID); System.out.println(vote); VoteDB.addVote(vote); /* // Get upvotes from users (i.e. non delegators) List<Vote> votes = VoteDB.getVotedBy(1); i = 0; for (Vote current : votes) { System.out.println("vote:" + i++); System.out.println(current); }*/ System.out.println("Created" + vote.getCreatedAsString()); vote.setVote(false, true); System.out.println("NEWWWW!"); System.out.println(VoteDB.getVote("", initiative.getId())); InitiativeDB.deleteInitiative(initiative.getId()); //VoteDB.deleteVote(vote.getId()); initiative.setExpires(new Date()); InitiativeDB.updateInitiative(initiative); TimeUnit.SECONDS.sleep(2); vote.setDelegator("turing"); VoteDB.updateVote(vote); System.out.println(vote); System.out.println("Modified" + vote.getModifiedAsString()); // Get Initiatives List<Initiative> initiatives = InitiativeDB.getInitiativesWithStatus(1); i = 0; for (Initiative current : initiatives) { System.out.println("initiative:" + i++); System.out.println(current); } Comment comment = new Comment(); comment.setComment("lala"); comment.setInitiativeID(initID); comment.setUserName("papadako"); CommentDB.addComment(comment); comment.setComment("llaladfasdfs"); CommentDB.updateComment(comment); System.out.println(comment.toString()); Rating rating = new Rating(); rating.setRate(2); rating.setInitiativeID(initID); rating.setUserName("turing"); RatingDB.addRating(rating); rating.setRate(5); RatingDB.updateRating(rating); System.out.println(rating.toString()); Delegated deleg = new Delegated(); deleg.setInitiativeID(initID); deleg.setDelegator("turing"); deleg.setUserName("turing"); DelegatedDB.addDelegated(deleg); deleg.setUserName("turing"); DelegatedDB.updateDelegated(deleg); System.out.println(deleg.toString()); } }
stavros47/Politeia
a5/lq/src/main/java/gr/csd/uoc/cs359/winter2017/lq/ExampleAPI.java
1,960
// στον Παγκόσμιο Πόλεμο ΙΙ για να κρυπτογραφήσουν την επικοινωνία τους.
line_comment
el
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gr.csd.uoc.cs359.winter2017.lq; import gr.csd.uoc.cs359.winter2017.lq.db.CommentDB; import gr.csd.uoc.cs359.winter2017.lq.db.DelegatedDB; import gr.csd.uoc.cs359.winter2017.lq.db.InitiativeDB; import gr.csd.uoc.cs359.winter2017.lq.db.RatingDB; import gr.csd.uoc.cs359.winter2017.lq.db.UserDB; import gr.csd.uoc.cs359.winter2017.lq.db.VoteDB; import gr.csd.uoc.cs359.winter2017.lq.model.Comment; import gr.csd.uoc.cs359.winter2017.lq.model.Delegated; import gr.csd.uoc.cs359.winter2017.lq.model.Initiative; import gr.csd.uoc.cs359.winter2017.lq.model.Rating; import gr.csd.uoc.cs359.winter2017.lq.model.User; import gr.csd.uoc.cs359.winter2017.lq.model.Vote; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; /** * * @author papadako */ public class ExampleAPI { /** * An example of adding a new member in the database. Turing is a user of * our system * * @param args the command line arguments * @throws ClassNotFoundException */ public static void main(String[] args) throws ClassNotFoundException, InterruptedException { // O Turing έσπασε τον κώδικα enigma που χρησιμοποιούσαν οι Γερμανοί // στον Παγκόσμιο<SUF> // Άρα είναι πιθανό να χρησιμοποιούσε σαν passwd τη λέξη enigma, κάπως // τροποποιημένη :) // http://en.wikipedia.org/wiki/Enigma_machine // md5 της λέξης 3n!gm@ είναι e37f7cfcb0cd53734184de812b5c6175 User turing = new User(); turing.setUserName("turing"); turing.setEmail("[email protected]"); turing.setPassword("e37f7cfcb0cd53734184de812b5c6175"); turing.setFirstName("Alan"); turing.setLastName("Turing"); turing.setBirthDate("07/07/1912"); turing.setCountry("Science"); turing.setTown("Computer Science"); turing.setAddress("Computability"); turing.setOccupation("Xompistas"); turing.setGender("Male"); turing.setInterests("Enigma, decyphering"); turing.setInfo("You will have a job due to my work! :)"); if (UserDB.checkValidUserName("papadako")) { // Add turing to database UserDB.addUser(turing); } else { System.out.println("User already exists.... Not more Turings please!"); } List<User> users = UserDB.getUsers(); int i = 0; for (User user : users) { System.out.println("user:" + i++); System.out.println(user); } // Add a wish as info turing.setInfo("I hope you follow my path..."); turing.setEmail("[email protected]"); UserDB.updateUser(turing); System.out.println(UserDB.getUser("turing")); // Check initiatives Initiative initiative = new Initiative(); initiative.setCreator("turing"); initiative.setTitle("Halting Problem"); initiative.setCategory("Computability"); initiative.setDescription("In computability theory, the halting problem is the problem of determining, from a description of an arbitrary computer program and an input, whether the program will finish running or continue to run forever."); initiative.setStatus(0); InitiativeDB.addInitiative(initiative); System.out.println(initiative.toString()); //UserDB.deleteUser("turing"); if (UserDB.checkValidUserName("turing")) { // You can be a new Turing! System.out.println("Well, Turing is gone for a long time now!"); System.out.println("Hope we find a new one in this 2017 class!"); } initiative.setStatus(1); InitiativeDB.updateInitiative(initiative); System.out.println(initiative.toString()); int initID = initiative.getId(); Vote vote = new Vote(); vote.setUser("papadako"); vote.setInitiativeID(initID); System.out.println(vote); VoteDB.addVote(vote); /* // Get upvotes from users (i.e. non delegators) List<Vote> votes = VoteDB.getVotedBy(1); i = 0; for (Vote current : votes) { System.out.println("vote:" + i++); System.out.println(current); }*/ System.out.println("Created" + vote.getCreatedAsString()); vote.setVote(false, true); System.out.println("NEWWWW!"); System.out.println(VoteDB.getVote("", initiative.getId())); InitiativeDB.deleteInitiative(initiative.getId()); //VoteDB.deleteVote(vote.getId()); initiative.setExpires(new Date()); InitiativeDB.updateInitiative(initiative); TimeUnit.SECONDS.sleep(2); vote.setDelegator("turing"); VoteDB.updateVote(vote); System.out.println(vote); System.out.println("Modified" + vote.getModifiedAsString()); // Get Initiatives List<Initiative> initiatives = InitiativeDB.getInitiativesWithStatus(1); i = 0; for (Initiative current : initiatives) { System.out.println("initiative:" + i++); System.out.println(current); } Comment comment = new Comment(); comment.setComment("lala"); comment.setInitiativeID(initID); comment.setUserName("papadako"); CommentDB.addComment(comment); comment.setComment("llaladfasdfs"); CommentDB.updateComment(comment); System.out.println(comment.toString()); Rating rating = new Rating(); rating.setRate(2); rating.setInitiativeID(initID); rating.setUserName("turing"); RatingDB.addRating(rating); rating.setRate(5); RatingDB.updateRating(rating); System.out.println(rating.toString()); Delegated deleg = new Delegated(); deleg.setInitiativeID(initID); deleg.setDelegator("turing"); deleg.setUserName("turing"); DelegatedDB.addDelegated(deleg); deleg.setUserName("turing"); DelegatedDB.updateDelegated(deleg); System.out.println(deleg.toString()); } }
53_3
import java.util.Iterator; import java.util.PriorityQueue; public class StationPS extends Station { private PriorityQueue<Job> queue; //ουρα εγρασιών public StationPS(double meanService, double[] routing) { super(meanService); this.routing=routing; this.queue= new PriorityQueue<Job>(); } public int getLength() { return queue.size(); } public void extArrive(Job job, double clock){ /** * Καθορισμός επόμενης άφιξης * καθορισμός timeout για την επόμενη άφιξη * αφιξη τρέχουσας εργασίας στην CPU ουρά */ double T=clock-(1/1.65)*Math.log(Math.random()); double timeout = T+30*Math.pow(-Math.log(Math.random()),2.0/3.0); Job newJob = new Job(0,0.0,T,timeout); Simulation.eventsList.add(new Event(T,newJob,0)); Simulation.eventsList.add(new Event(newJob.getTimeout(),newJob,2)); arrive(job,clock); } public void withdraw(Job job,double clock) { /** * Αφαιρείται από την ουρά η διεργασία που έληξε και από τη λίστα * γεγονότων τα γεγονότα που την αφορούν * Αν η ουρά δεν μείνει άδεια αφαιρούμε το γεγονός που αφορά * την εξυπηρέτηση της πρώτης από τη λίστα γεγονότων * ενημερώνονται οι χρόνοι εξυπηρέτησής των υπολοίπων * εισάγεται στην ουρά η αφιχθείσα και δρομολογείται η εξυπηρέτηση της πρώτης **/ //ενημέρωση ουράς length--; Job first=queue.peek(); queue.remove(job); if(queue.size()>0){ //remove the event associated with the first job in the CPU queue Event fe=null; Iterator<Event> itrE = Simulation.eventsList.iterator(); while (itrE.hasNext()&&fe==null){ Event itrEvent = itrE.next(); if (itrEvent.getJob().getId()==first.getId()&&itrEvent.getType()==1){ fe=itrEvent; itrE.remove(); } } double T=fe.getTime(); T=first.getRequest()-(T-clock)/queue.size(); Iterator<Job> itrJ = queue.iterator(); while(itrJ.hasNext()){ Job itrJob = itrJ.next(); itrJob.setRequest(itrJob.getRequest()-T); } Job first1 = queue.peek(); Simulation.eventsList.add(new Event(clock+first1.getRequest()*length,first1,1)); } Iterator<Event> itrE = Simulation.eventsList.iterator(); while (itrE.hasNext()){ Event itrEvent = itrE.next(); if (itrEvent.getJob().getId()==job.getId()){ itrE.remove(); } } } public void complete(Job job, double clock){ /** * Αφαιρείται η πρώτη εργασία από την ουρά * Aν η ουρα δεν μείνει άδεια ενημερώνονται οι χρόνοι εξυπηρέτησης * και δρομολογείται η επόμενη εργασία */ //ενημέρωση ουράς super.length--; if(queue.size()==1){ queue.remove(job); sumBusyTime+=clock-super.oldclock; } else{ double T=job.getRequest(); queue.remove(job); Iterator<Job> itr = queue.iterator(); while(itr.hasNext()){ Job itrJob = itr.next(); itrJob.setRequest(itrJob.getRequest()-T); } Job nextJob=queue.peek(); Simulation.eventsList.add(new Event(clock+nextJob.getRequest()*length,nextJob,1)); } } public void arrive(Job job,double clock){ /** * Αν η ουρά ήταν άδεια εισάγεται και δρομολογείται αμέσως αυτή που έφτασε * Αν υπήρχαν κι άλλες εργασίες στην ουρά αφαιρούμε το γεγονός που αφορά * την εξυπηρέτηση της πρώτης από τη λίστα γεγονότων * ενημερώνονται οι χρόνοι εξυπηρέτησής των υπολοίπων * εισάγεται στην ουρά η αφιχθείσα και δρομολογείται η εξυπηρέτηση της πρώτης */ //ενημέρωση ουράς if (queue.size()==0){ super.oldclock=clock; job.setRequest(-meanService*Math.log(Math.random())); queue.add(job); super.length++; Simulation.eventsList.add(new Event(clock+job.getRequest(),job,1)); } else{ Job first = queue.peek(); //remove the event associated with the first job in the CPU queue Event fe=null; Iterator<Event> itrE = Simulation.eventsList.iterator(); while (itrE.hasNext()&&fe==null){ Event itrEvent = itrE.next(); if (itrEvent.getJob().getId()==first.getId()&&itrEvent.getType()==1){ fe=itrEvent; itrE.remove(); } } double T=fe.getTime(); T=first.getRequest()-(T-clock)/queue.size(); Iterator<Job> itrJ = queue.iterator(); while(itrJ.hasNext()){ Job itrJob = itrJ.next(); itrJob.setRequest(itrJob.getRequest()-T); } job.setRequest(-meanService*Math.log(Math.random())); queue.add(job); super.length++; Job first1 = queue.peek(); Simulation.eventsList.add(new Event(clock+first1.getRequest()*length,first1,1)); } } }
stchrysa/DE-QNet-SIM
src/StationPS.java
2,022
/** * Αφαιρείται η πρώτη εργασία από την ουρά * Aν η ουρα δεν μείνει άδεια ενημερώνονται οι χρόνοι εξυπηρέτησης * και δρομολογείται η επόμενη εργασία */
block_comment
el
import java.util.Iterator; import java.util.PriorityQueue; public class StationPS extends Station { private PriorityQueue<Job> queue; //ουρα εγρασιών public StationPS(double meanService, double[] routing) { super(meanService); this.routing=routing; this.queue= new PriorityQueue<Job>(); } public int getLength() { return queue.size(); } public void extArrive(Job job, double clock){ /** * Καθορισμός επόμενης άφιξης * καθορισμός timeout για την επόμενη άφιξη * αφιξη τρέχουσας εργασίας στην CPU ουρά */ double T=clock-(1/1.65)*Math.log(Math.random()); double timeout = T+30*Math.pow(-Math.log(Math.random()),2.0/3.0); Job newJob = new Job(0,0.0,T,timeout); Simulation.eventsList.add(new Event(T,newJob,0)); Simulation.eventsList.add(new Event(newJob.getTimeout(),newJob,2)); arrive(job,clock); } public void withdraw(Job job,double clock) { /** * Αφαιρείται από την ουρά η διεργασία που έληξε και από τη λίστα * γεγονότων τα γεγονότα που την αφορούν * Αν η ουρά δεν μείνει άδεια αφαιρούμε το γεγονός που αφορά * την εξυπηρέτηση της πρώτης από τη λίστα γεγονότων * ενημερώνονται οι χρόνοι εξυπηρέτησής των υπολοίπων * εισάγεται στην ουρά η αφιχθείσα και δρομολογείται η εξυπηρέτηση της πρώτης **/ //ενημέρωση ουράς length--; Job first=queue.peek(); queue.remove(job); if(queue.size()>0){ //remove the event associated with the first job in the CPU queue Event fe=null; Iterator<Event> itrE = Simulation.eventsList.iterator(); while (itrE.hasNext()&&fe==null){ Event itrEvent = itrE.next(); if (itrEvent.getJob().getId()==first.getId()&&itrEvent.getType()==1){ fe=itrEvent; itrE.remove(); } } double T=fe.getTime(); T=first.getRequest()-(T-clock)/queue.size(); Iterator<Job> itrJ = queue.iterator(); while(itrJ.hasNext()){ Job itrJob = itrJ.next(); itrJob.setRequest(itrJob.getRequest()-T); } Job first1 = queue.peek(); Simulation.eventsList.add(new Event(clock+first1.getRequest()*length,first1,1)); } Iterator<Event> itrE = Simulation.eventsList.iterator(); while (itrE.hasNext()){ Event itrEvent = itrE.next(); if (itrEvent.getJob().getId()==job.getId()){ itrE.remove(); } } } public void complete(Job job, double clock){ /** * Αφαιρείται η πρώτη<SUF>*/ //ενημέρωση ουράς super.length--; if(queue.size()==1){ queue.remove(job); sumBusyTime+=clock-super.oldclock; } else{ double T=job.getRequest(); queue.remove(job); Iterator<Job> itr = queue.iterator(); while(itr.hasNext()){ Job itrJob = itr.next(); itrJob.setRequest(itrJob.getRequest()-T); } Job nextJob=queue.peek(); Simulation.eventsList.add(new Event(clock+nextJob.getRequest()*length,nextJob,1)); } } public void arrive(Job job,double clock){ /** * Αν η ουρά ήταν άδεια εισάγεται και δρομολογείται αμέσως αυτή που έφτασε * Αν υπήρχαν κι άλλες εργασίες στην ουρά αφαιρούμε το γεγονός που αφορά * την εξυπηρέτηση της πρώτης από τη λίστα γεγονότων * ενημερώνονται οι χρόνοι εξυπηρέτησής των υπολοίπων * εισάγεται στην ουρά η αφιχθείσα και δρομολογείται η εξυπηρέτηση της πρώτης */ //ενημέρωση ουράς if (queue.size()==0){ super.oldclock=clock; job.setRequest(-meanService*Math.log(Math.random())); queue.add(job); super.length++; Simulation.eventsList.add(new Event(clock+job.getRequest(),job,1)); } else{ Job first = queue.peek(); //remove the event associated with the first job in the CPU queue Event fe=null; Iterator<Event> itrE = Simulation.eventsList.iterator(); while (itrE.hasNext()&&fe==null){ Event itrEvent = itrE.next(); if (itrEvent.getJob().getId()==first.getId()&&itrEvent.getType()==1){ fe=itrEvent; itrE.remove(); } } double T=fe.getTime(); T=first.getRequest()-(T-clock)/queue.size(); Iterator<Job> itrJ = queue.iterator(); while(itrJ.hasNext()){ Job itrJob = itrJ.next(); itrJob.setRequest(itrJob.getRequest()-T); } job.setRequest(-meanService*Math.log(Math.random())); queue.add(job); super.length++; Job first1 = queue.peek(); Simulation.eventsList.add(new Event(clock+first1.getRequest()*length,first1,1)); } } }
22781_5
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.i18n.client.impl.cldr; import com.google.gwt.core.client.JavaScriptObject; // DO NOT EDIT - GENERATED FROM CLDR DATA: // cldrVersion=21.0 // number=$Revision: 6444 $ // type=root // date=$Date: 2012-01-25 16:40:58 -0500 (Wed, 25 Jan 2012) $ /** * Localized names for the "el_POLYTON" locale. */ public class LocalizedNamesImpl_el_POLYTON extends LocalizedNamesImpl_el { @Override public String[] loadSortedRegionCodes() { return new String[] { "BQ", "CW", "SS", "SX", "VA", "SH", "LC", "BL", "VC", "SM", "MF", "AZ", "EG", "ET", "HT", "CI", "AL", "DZ", "VI", "AS", "TL", "AO", "AI", "AD", "AQ", "AG", "UM", "AR", "AM", "AW", "AU", "AT", "AF", "VU", "BE", "VE", "BM", "VN", "BO", "KP", "BA", "BG", "BR", "IO", "VG", "FR", "TF", "GF", "PF", "DE", "GE", "GI", "GM", "GA", "GH", "GG", "GU", "GP", "GT", "GY", "GN", "GW", "GD", "GL", "DK", "DO", "EH", "CH", "GR", "SV", "ER", "EE", "EU", "ZM", "ZW", "SZ", "AE", "US", "GB", "EA", "JP", "IN", "ID", "JO", "IQ", "IR", "IE", "GQ", "EC", "IS", "ES", "IL", "IT", "KZ", "CM", "KH", "CA", "IC", "QA", "CF", "KE", "CN", "KG", "KI", "CO", "KM", "CD", "CG", "CR", "CU", "KW", "HR", "CY", "LA", "LS", "LV", "BY", "LB", "LR", "LY", "LT", "LI", "LU", "YT", "MG", "MO", "MY", "MW", "MV", "ML", "MT", "MA", "MQ", "MU", "MR", "ME", "MX", "FX", "MM", "FM", "MN", "MZ", "MD", "MC", "MS", "BD", "BB", "BS", "BH", "BZ", "BJ", "BW", "BF", "BI", "BT", "BN", "NA", "NR", "NZ", "NC", "NP", "AX", "MP", "KY", "CC", "CK", "MH", "WF", "SJ", "SB", "TC", "FO", "FK", "HM", "AC", "CP", "IM", "BV", "NF", "CX", "NE", "NG", "NI", "NU", "NO", "ZA", "GS", "KR", "DG", "DM", "NL", "AN", "OM", "HN", "HU", "UG", "UZ", "UA", "UY", "PK", "PS", "PW", "PA", "PG", "PY", "MK", "QO", "PE", "PN", "PL", "PT", "PR", "CV", "RE", "RW", "RO", "RU", "KN", "PM", "WS", "ST", "SA", "SN", "RS", "CS", "SC", "SG", "SL", "SK", "SI", "SO", "SD", "SE", "SR", "LK", "SY", "TW", "TH", "TZ", "TJ", "JM", "DJ", "TG", "TK", "TO", "TV", "TR", "TM", "TT", "TA", "TD", "CZ", "TN", "YE", "JE", "PH", "FI", "FJ", "CL", "HK", }; } @Override protected void loadNameMapJava() { super.loadNameMapJava(); namesMap.put("AD", "Ἀνδόρα"); namesMap.put("AE", "Ἠνωμένα Ἀραβικὰ Ἐμιράτα"); namesMap.put("AF", "Ἀφγανιστάν"); namesMap.put("AG", "Ἀντίγκουα καὶ Μπαρμπούντα"); namesMap.put("AI", "Ἀνγκουίλα"); namesMap.put("AL", "Ἀλβανία"); namesMap.put("AM", "Ἀρμενία"); namesMap.put("AN", "Ὁλλανδικὲς Ἀντίλλες"); namesMap.put("AO", "Ἀνγκόλα"); namesMap.put("AQ", "Ἀνταρκτική"); namesMap.put("AR", "Ἀργεντινή"); namesMap.put("AS", "Ἀμερικανικὴ Σαμόα"); namesMap.put("AT", "Αὐστρία"); namesMap.put("AU", "Αὐστραλία"); namesMap.put("AW", "Ἀρούμπα"); namesMap.put("AZ", "Ἀζερμπαϊτζάν"); namesMap.put("BA", "Βοσνία - Ἐρζεγοβίνη"); namesMap.put("BM", "Βερμοῦδες"); namesMap.put("BV", "Νῆσος Μπουβέ"); namesMap.put("CC", "Νῆσοι Κόκος (Κήλινγκ)"); namesMap.put("CD", "Κονγκό, Λαϊκὴ Δημοκρατία τοῦ"); namesMap.put("CF", "Κεντροαφρικανικὴ Δημοκρατία"); namesMap.put("CH", "Ἑλβετία"); namesMap.put("CI", "Ἀκτὴ Ἐλεφαντοστού"); namesMap.put("CK", "Νῆσοι Κούκ"); namesMap.put("CV", "Πράσινο Ἀκρωτήριο"); namesMap.put("CX", "Νῆσος Χριστουγέννων"); namesMap.put("DO", "Δομινικανὴ Δημοκρατία"); namesMap.put("DZ", "Ἀλγερία"); namesMap.put("EC", "Ἰσημερινός"); namesMap.put("EE", "Ἐσθονία"); namesMap.put("EG", "Αἴγυπτος"); namesMap.put("EH", "Δυτικὴ Σαχάρα"); namesMap.put("ER", "Ἐρυθραία"); namesMap.put("ES", "Ἱσπανία"); namesMap.put("ET", "Αἰθιοπία"); namesMap.put("EU", "Εὐρωπαϊκὴ ᾿Ένωση"); namesMap.put("FM", "Μικρονησία, Ὁμόσπονδες Πολιτεῖες τῆς"); namesMap.put("FO", "Νῆσοι Φερόες"); namesMap.put("GB", "Ἡνωμένο Βασίλειο"); namesMap.put("GF", "Γαλλικὴ Γουιάνα"); namesMap.put("GQ", "Ἰσημερινὴ Γουινέα"); namesMap.put("GR", "Ἑλλάδα"); namesMap.put("GS", "Νότια Γεωργία καὶ Νότιες Νήσοι Σάντουιτς"); namesMap.put("HK", "Χὸνγκ Κόνγκ, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας"); namesMap.put("HM", "Νῆσοι Χὲρντ καὶ Μακντόναλντ"); namesMap.put("HN", "Ὁνδούρα"); namesMap.put("HT", "Ἁϊτή"); namesMap.put("HU", "Οὑγγαρία"); namesMap.put("ID", "Ἰνδονησία"); namesMap.put("IE", "Ἰρλανδία"); namesMap.put("IL", "Ἰσραήλ"); namesMap.put("IN", "Ἰνδία"); namesMap.put("IO", "Βρετανικὰ Ἐδάφη Ἰνδικοῦ Ὠκεανοῦ"); namesMap.put("IQ", "Ἰράκ"); namesMap.put("IR", "Ἰράν, Ἰσλαμικὴ Δημοκρατία τοῦ"); namesMap.put("IS", "Ἰσλανδία"); namesMap.put("IT", "Ἰταλία"); namesMap.put("JO", "Ἰορδανία"); namesMap.put("JP", "Ἰαπωνία"); namesMap.put("KN", "Σαὶντ Κὶτς καὶ Νέβις"); namesMap.put("KY", "Νῆσοι Κέιμαν"); namesMap.put("LA", "Λατινικὴ Ἀμερική"); namesMap.put("LC", "Ἁγία Λουκία"); namesMap.put("LK", "Σρὶ Λάνκα"); namesMap.put("LU", "Λουξεμβοῦργο"); namesMap.put("MD", "Μολδαβία, Δημοκρατία τῆς"); namesMap.put("MH", "Νῆσοι Μάρσαλ"); namesMap.put("ML", "Μαλί"); namesMap.put("MO", "Μακάο, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας"); namesMap.put("MP", "Νῆσοι Βόρειες Μαριάνες"); namesMap.put("NF", "Νῆσος Νόρφολκ"); namesMap.put("NL", "Ὁλλανδία"); namesMap.put("OM", "Ὀμάν"); namesMap.put("PF", "Γαλλικὴ Πολυνησία"); namesMap.put("PM", "Σαὶντ Πιὲρ καὶ Μικελόν"); namesMap.put("PS", "Παλαιστινιακὰ Ἐδάφη"); namesMap.put("SA", "Σαουδικὴ Ἀραβία"); namesMap.put("SB", "Νῆσοι Σολομῶντος"); namesMap.put("SH", "Ἁγία Ἑλένη"); namesMap.put("SJ", "Νῆσοι Σβάλμπαρ καὶ Γιὰν Μαγιέν"); namesMap.put("SM", "Ἅγιος Μαρίνος"); namesMap.put("ST", "Σάο Τομὲ καὶ Πρίνσιπε"); namesMap.put("SV", "Ἒλ Σαλβαδόρ"); namesMap.put("SY", "Συρία, Ἀραβικὴ Δημοκρατία τῆς"); namesMap.put("TC", "Νῆσοι Τὲρκς καὶ Κάικος"); namesMap.put("TD", "Τσάντ"); namesMap.put("TF", "Γαλλικὰ Νότια Ἐδάφη"); namesMap.put("TL", "Ἀνατολικὸ Τιμόρ"); namesMap.put("TT", "Τρινιδὰδ καὶ Τομπάγκο"); namesMap.put("UA", "Οὐκρανία"); namesMap.put("UG", "Οὐγκάντα"); namesMap.put("UM", "Ἀπομακρυσμένες Νησίδες τῶν Ἡνωμένων Πολιτειῶν"); namesMap.put("US", "Ἡνωμένες Πολιτεῖες"); namesMap.put("UY", "Οὐρουγουάη"); namesMap.put("UZ", "Οὐζμπεκιστάν"); namesMap.put("VA", "Ἁγία Ἕδρα (Βατικανό)"); namesMap.put("VC", "Ἅγιος Βικέντιος καὶ Γρεναδίνες"); namesMap.put("VG", "Βρετανικὲς Παρθένοι Νῆσοι"); namesMap.put("VI", "Ἀμερικανικὲς Παρθένοι Νῆσοι"); namesMap.put("WF", "Νῆσοι Οὐάλλις καὶ Φουτουνά"); namesMap.put("YE", "Ὑεμένη"); namesMap.put("ZA", "Νότια Ἀφρική"); } @Override protected JavaScriptObject loadNameMapNative() { return overrideMap(super.loadNameMapNative(), loadMyNameMap()); } private native JavaScriptObject loadMyNameMap() /*-{ return { "AD": "Ἀνδόρα", "AE": "Ἠνωμένα Ἀραβικὰ Ἐμιράτα", "AF": "Ἀφγανιστάν", "AG": "Ἀντίγκουα καὶ Μπαρμπούντα", "AI": "Ἀνγκουίλα", "AL": "Ἀλβανία", "AM": "Ἀρμενία", "AN": "Ὁλλανδικὲς Ἀντίλλες", "AO": "Ἀνγκόλα", "AQ": "Ἀνταρκτική", "AR": "Ἀργεντινή", "AS": "Ἀμερικανικὴ Σαμόα", "AT": "Αὐστρία", "AU": "Αὐστραλία", "AW": "Ἀρούμπα", "AZ": "Ἀζερμπαϊτζάν", "BA": "Βοσνία - Ἐρζεγοβίνη", "BM": "Βερμοῦδες", "BV": "Νῆσος Μπουβέ", "CC": "Νῆσοι Κόκος (Κήλινγκ)", "CD": "Κονγκό, Λαϊκὴ Δημοκρατία τοῦ", "CF": "Κεντροαφρικανικὴ Δημοκρατία", "CH": "Ἑλβετία", "CI": "Ἀκτὴ Ἐλεφαντοστού", "CK": "Νῆσοι Κούκ", "CV": "Πράσινο Ἀκρωτήριο", "CX": "Νῆσος Χριστουγέννων", "DO": "Δομινικανὴ Δημοκρατία", "DZ": "Ἀλγερία", "EC": "Ἰσημερινός", "EE": "Ἐσθονία", "EG": "Αἴγυπτος", "EH": "Δυτικὴ Σαχάρα", "ER": "Ἐρυθραία", "ES": "Ἱσπανία", "ET": "Αἰθιοπία", "EU": "Εὐρωπαϊκὴ ᾿Ένωση", "FM": "Μικρονησία, Ὁμόσπονδες Πολιτεῖες τῆς", "FO": "Νῆσοι Φερόες", "GB": "Ἡνωμένο Βασίλειο", "GF": "Γαλλικὴ Γουιάνα", "GQ": "Ἰσημερινὴ Γουινέα", "GR": "Ἑλλάδα", "GS": "Νότια Γεωργία καὶ Νότιες Νήσοι Σάντουιτς", "HK": "Χὸνγκ Κόνγκ, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας", "HM": "Νῆσοι Χὲρντ καὶ Μακντόναλντ", "HN": "Ὁνδούρα", "HT": "Ἁϊτή", "HU": "Οὑγγαρία", "ID": "Ἰνδονησία", "IE": "Ἰρλανδία", "IL": "Ἰσραήλ", "IN": "Ἰνδία", "IO": "Βρετανικὰ Ἐδάφη Ἰνδικοῦ Ὠκεανοῦ", "IQ": "Ἰράκ", "IR": "Ἰράν, Ἰσλαμικὴ Δημοκρατία τοῦ", "IS": "Ἰσλανδία", "IT": "Ἰταλία", "JO": "Ἰορδανία", "JP": "Ἰαπωνία", "KN": "Σαὶντ Κὶτς καὶ Νέβις", "KY": "Νῆσοι Κέιμαν", "LA": "Λατινικὴ Ἀμερική", "LC": "Ἁγία Λουκία", "LK": "Σρὶ Λάνκα", "LU": "Λουξεμβοῦργο", "MD": "Μολδαβία, Δημοκρατία τῆς", "MH": "Νῆσοι Μάρσαλ", "ML": "Μαλί", "MO": "Μακάο, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας", "MP": "Νῆσοι Βόρειες Μαριάνες", "NF": "Νῆσος Νόρφολκ", "NL": "Ὁλλανδία", "OM": "Ὀμάν", "PF": "Γαλλικὴ Πολυνησία", "PM": "Σαὶντ Πιὲρ καὶ Μικελόν", "PS": "Παλαιστινιακὰ Ἐδάφη", "SA": "Σαουδικὴ Ἀραβία", "SB": "Νῆσοι Σολομῶντος", "SH": "Ἁγία Ἑλένη", "SJ": "Νῆσοι Σβάλμπαρ καὶ Γιὰν Μαγιέν", "SM": "Ἅγιος Μαρίνος", "ST": "Σάο Τομὲ καὶ Πρίνσιπε", "SV": "Ἒλ Σαλβαδόρ", "SY": "Συρία, Ἀραβικὴ Δημοκρατία τῆς", "TC": "Νῆσοι Τὲρκς καὶ Κάικος", "TD": "Τσάντ", "TF": "Γαλλικὰ Νότια Ἐδάφη", "TL": "Ἀνατολικὸ Τιμόρ", "TT": "Τρινιδὰδ καὶ Τομπάγκο", "UA": "Οὐκρανία", "UG": "Οὐγκάντα", "UM": "Ἀπομακρυσμένες Νησίδες τῶν Ἡνωμένων Πολιτειῶν", "US": "Ἡνωμένες Πολιτεῖες", "UY": "Οὐρουγουάη", "UZ": "Οὐζμπεκιστάν", "VA": "Ἁγία Ἕδρα (Βατικανό)", "VC": "Ἅγιος Βικέντιος καὶ Γρεναδίνες", "VG": "Βρετανικὲς Παρθένοι Νῆσοι", "VI": "Ἀμερικανικὲς Παρθένοι Νῆσοι", "WF": "Νῆσοι Οὐάλλις καὶ Φουτουνά", "YE": "Ὑεμένη", "ZA": "Νότια Ἀφρική" }; }-*/; }
stephenh/google-web-toolkit
user/src/com/google/gwt/i18n/client/impl/cldr/LocalizedNamesImpl_el_POLYTON.java
6,699
/*-{ return { "AD": "Ἀνδόρα", "AE": "Ἠνωμένα Ἀραβικὰ Ἐμιράτα", "AF": "Ἀφγανιστάν", "AG": "Ἀντίγκουα καὶ Μπαρμπούντα", "AI": "Ἀνγκουίλα", "AL": "Ἀλβανία", "AM": "Ἀρμενία", "AN": "Ὁλλανδικὲς Ἀντίλλες", "AO": "Ἀνγκόλα", "AQ": "Ἀνταρκτική", "AR": "Ἀργεντινή", "AS": "Ἀμερικανικὴ Σαμόα", "AT": "Αὐστρία", "AU": "Αὐστραλία", "AW": "Ἀρούμπα", "AZ": "Ἀζερμπαϊτζάν", "BA": "Βοσνία - Ἐρζεγοβίνη", "BM": "Βερμοῦδες", "BV": "Νῆσος Μπουβέ", "CC": "Νῆσοι Κόκος (Κήλινγκ)", "CD": "Κονγκό, Λαϊκὴ Δημοκρατία τοῦ", "CF": "Κεντροαφρικανικὴ Δημοκρατία", "CH": "Ἑλβετία", "CI": "Ἀκτὴ Ἐλεφαντοστού", "CK": "Νῆσοι Κούκ", "CV": "Πράσινο Ἀκρωτήριο", "CX": "Νῆσος Χριστουγέννων", "DO": "Δομινικανὴ Δημοκρατία", "DZ": "Ἀλγερία", "EC": "Ἰσημερινός", "EE": "Ἐσθονία", "EG": "Αἴγυπτος", "EH": "Δυτικὴ Σαχάρα", "ER": "Ἐρυθραία", "ES": "Ἱσπανία", "ET": "Αἰθιοπία", "EU": "Εὐρωπαϊκὴ ᾿Ένωση", "FM": "Μικρονησία, Ὁμόσπονδες Πολιτεῖες τῆς", "FO": "Νῆσοι Φερόες", "GB": "Ἡνωμένο Βασίλειο", "GF": "Γαλλικὴ Γουιάνα", "GQ": "Ἰσημερινὴ Γουινέα", "GR": "Ἑλλάδα", "GS": "Νότια Γεωργία καὶ Νότιες Νήσοι Σάντουιτς", "HK": "Χὸνγκ Κόνγκ, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας", "HM": "Νῆσοι Χὲρντ καὶ Μακντόναλντ", "HN": "Ὁνδούρα", "HT": "Ἁϊτή", "HU": "Οὑγγαρία", "ID": "Ἰνδονησία", "IE": "Ἰρλανδία", "IL": "Ἰσραήλ", "IN": "Ἰνδία", "IO": "Βρετανικὰ Ἐδάφη Ἰνδικοῦ Ὠκεανοῦ", "IQ": "Ἰράκ", "IR": "Ἰράν, Ἰσλαμικὴ Δημοκρατία τοῦ", "IS": "Ἰσλανδία", "IT": "Ἰταλία", "JO": "Ἰορδανία", "JP": "Ἰαπωνία", "KN": "Σαὶντ Κὶτς καὶ Νέβις", "KY": "Νῆσοι Κέιμαν", "LA": "Λατινικὴ Ἀμερική", "LC": "Ἁγία Λουκία", "LK": "Σρὶ Λάνκα", "LU": "Λουξεμβοῦργο", "MD": "Μολδαβία, Δημοκρατία τῆς", "MH": "Νῆσοι Μάρσαλ", "ML": "Μαλί", "MO": "Μακάο, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας", "MP": "Νῆσοι Βόρειες Μαριάνες", "NF": "Νῆσος Νόρφολκ", "NL": "Ὁλλανδία", "OM": "Ὀμάν", "PF": "Γαλλικὴ Πολυνησία", "PM": "Σαὶντ Πιὲρ καὶ Μικελόν", "PS": "Παλαιστινιακὰ Ἐδάφη", "SA": "Σαουδικὴ Ἀραβία", "SB": "Νῆσοι Σολομῶντος", "SH": "Ἁγία Ἑλένη", "SJ": "Νῆσοι Σβάλμπαρ καὶ Γιὰν Μαγιέν", "SM": "Ἅγιος Μαρίνος", "ST": "Σάο Τομὲ καὶ Πρίνσιπε", "SV": "Ἒλ Σαλβαδόρ", "SY": "Συρία, Ἀραβικὴ Δημοκρατία τῆς", "TC": "Νῆσοι Τὲρκς καὶ Κάικος", "TD": "Τσάντ", "TF": "Γαλλικὰ Νότια Ἐδάφη", "TL": "Ἀνατολικὸ Τιμόρ", "TT": "Τρινιδὰδ καὶ Τομπάγκο", "UA": "Οὐκρανία", "UG": "Οὐγκάντα", "UM": "Ἀπομακρυσμένες Νησίδες τῶν Ἡνωμένων Πολιτειῶν", "US": "Ἡνωμένες Πολιτεῖες", "UY": "Οὐρουγουάη", "UZ": "Οὐζμπεκιστάν", "VA": "Ἁγία Ἕδρα (Βατικανό)", "VC": "Ἅγιος Βικέντιος καὶ Γρεναδίνες", "VG": "Βρετανικὲς Παρθένοι Νῆσοι", "VI": "Ἀμερικανικὲς Παρθένοι Νῆσοι", "WF": "Νῆσοι Οὐάλλις καὶ Φουτουνά", "YE": "Ὑεμένη", "ZA": "Νότια Ἀφρική" }; }-*/
block_comment
el
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.i18n.client.impl.cldr; import com.google.gwt.core.client.JavaScriptObject; // DO NOT EDIT - GENERATED FROM CLDR DATA: // cldrVersion=21.0 // number=$Revision: 6444 $ // type=root // date=$Date: 2012-01-25 16:40:58 -0500 (Wed, 25 Jan 2012) $ /** * Localized names for the "el_POLYTON" locale. */ public class LocalizedNamesImpl_el_POLYTON extends LocalizedNamesImpl_el { @Override public String[] loadSortedRegionCodes() { return new String[] { "BQ", "CW", "SS", "SX", "VA", "SH", "LC", "BL", "VC", "SM", "MF", "AZ", "EG", "ET", "HT", "CI", "AL", "DZ", "VI", "AS", "TL", "AO", "AI", "AD", "AQ", "AG", "UM", "AR", "AM", "AW", "AU", "AT", "AF", "VU", "BE", "VE", "BM", "VN", "BO", "KP", "BA", "BG", "BR", "IO", "VG", "FR", "TF", "GF", "PF", "DE", "GE", "GI", "GM", "GA", "GH", "GG", "GU", "GP", "GT", "GY", "GN", "GW", "GD", "GL", "DK", "DO", "EH", "CH", "GR", "SV", "ER", "EE", "EU", "ZM", "ZW", "SZ", "AE", "US", "GB", "EA", "JP", "IN", "ID", "JO", "IQ", "IR", "IE", "GQ", "EC", "IS", "ES", "IL", "IT", "KZ", "CM", "KH", "CA", "IC", "QA", "CF", "KE", "CN", "KG", "KI", "CO", "KM", "CD", "CG", "CR", "CU", "KW", "HR", "CY", "LA", "LS", "LV", "BY", "LB", "LR", "LY", "LT", "LI", "LU", "YT", "MG", "MO", "MY", "MW", "MV", "ML", "MT", "MA", "MQ", "MU", "MR", "ME", "MX", "FX", "MM", "FM", "MN", "MZ", "MD", "MC", "MS", "BD", "BB", "BS", "BH", "BZ", "BJ", "BW", "BF", "BI", "BT", "BN", "NA", "NR", "NZ", "NC", "NP", "AX", "MP", "KY", "CC", "CK", "MH", "WF", "SJ", "SB", "TC", "FO", "FK", "HM", "AC", "CP", "IM", "BV", "NF", "CX", "NE", "NG", "NI", "NU", "NO", "ZA", "GS", "KR", "DG", "DM", "NL", "AN", "OM", "HN", "HU", "UG", "UZ", "UA", "UY", "PK", "PS", "PW", "PA", "PG", "PY", "MK", "QO", "PE", "PN", "PL", "PT", "PR", "CV", "RE", "RW", "RO", "RU", "KN", "PM", "WS", "ST", "SA", "SN", "RS", "CS", "SC", "SG", "SL", "SK", "SI", "SO", "SD", "SE", "SR", "LK", "SY", "TW", "TH", "TZ", "TJ", "JM", "DJ", "TG", "TK", "TO", "TV", "TR", "TM", "TT", "TA", "TD", "CZ", "TN", "YE", "JE", "PH", "FI", "FJ", "CL", "HK", }; } @Override protected void loadNameMapJava() { super.loadNameMapJava(); namesMap.put("AD", "Ἀνδόρα"); namesMap.put("AE", "Ἠνωμένα Ἀραβικὰ Ἐμιράτα"); namesMap.put("AF", "Ἀφγανιστάν"); namesMap.put("AG", "Ἀντίγκουα καὶ Μπαρμπούντα"); namesMap.put("AI", "Ἀνγκουίλα"); namesMap.put("AL", "Ἀλβανία"); namesMap.put("AM", "Ἀρμενία"); namesMap.put("AN", "Ὁλλανδικὲς Ἀντίλλες"); namesMap.put("AO", "Ἀνγκόλα"); namesMap.put("AQ", "Ἀνταρκτική"); namesMap.put("AR", "Ἀργεντινή"); namesMap.put("AS", "Ἀμερικανικὴ Σαμόα"); namesMap.put("AT", "Αὐστρία"); namesMap.put("AU", "Αὐστραλία"); namesMap.put("AW", "Ἀρούμπα"); namesMap.put("AZ", "Ἀζερμπαϊτζάν"); namesMap.put("BA", "Βοσνία - Ἐρζεγοβίνη"); namesMap.put("BM", "Βερμοῦδες"); namesMap.put("BV", "Νῆσος Μπουβέ"); namesMap.put("CC", "Νῆσοι Κόκος (Κήλινγκ)"); namesMap.put("CD", "Κονγκό, Λαϊκὴ Δημοκρατία τοῦ"); namesMap.put("CF", "Κεντροαφρικανικὴ Δημοκρατία"); namesMap.put("CH", "Ἑλβετία"); namesMap.put("CI", "Ἀκτὴ Ἐλεφαντοστού"); namesMap.put("CK", "Νῆσοι Κούκ"); namesMap.put("CV", "Πράσινο Ἀκρωτήριο"); namesMap.put("CX", "Νῆσος Χριστουγέννων"); namesMap.put("DO", "Δομινικανὴ Δημοκρατία"); namesMap.put("DZ", "Ἀλγερία"); namesMap.put("EC", "Ἰσημερινός"); namesMap.put("EE", "Ἐσθονία"); namesMap.put("EG", "Αἴγυπτος"); namesMap.put("EH", "Δυτικὴ Σαχάρα"); namesMap.put("ER", "Ἐρυθραία"); namesMap.put("ES", "Ἱσπανία"); namesMap.put("ET", "Αἰθιοπία"); namesMap.put("EU", "Εὐρωπαϊκὴ ᾿Ένωση"); namesMap.put("FM", "Μικρονησία, Ὁμόσπονδες Πολιτεῖες τῆς"); namesMap.put("FO", "Νῆσοι Φερόες"); namesMap.put("GB", "Ἡνωμένο Βασίλειο"); namesMap.put("GF", "Γαλλικὴ Γουιάνα"); namesMap.put("GQ", "Ἰσημερινὴ Γουινέα"); namesMap.put("GR", "Ἑλλάδα"); namesMap.put("GS", "Νότια Γεωργία καὶ Νότιες Νήσοι Σάντουιτς"); namesMap.put("HK", "Χὸνγκ Κόνγκ, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας"); namesMap.put("HM", "Νῆσοι Χὲρντ καὶ Μακντόναλντ"); namesMap.put("HN", "Ὁνδούρα"); namesMap.put("HT", "Ἁϊτή"); namesMap.put("HU", "Οὑγγαρία"); namesMap.put("ID", "Ἰνδονησία"); namesMap.put("IE", "Ἰρλανδία"); namesMap.put("IL", "Ἰσραήλ"); namesMap.put("IN", "Ἰνδία"); namesMap.put("IO", "Βρετανικὰ Ἐδάφη Ἰνδικοῦ Ὠκεανοῦ"); namesMap.put("IQ", "Ἰράκ"); namesMap.put("IR", "Ἰράν, Ἰσλαμικὴ Δημοκρατία τοῦ"); namesMap.put("IS", "Ἰσλανδία"); namesMap.put("IT", "Ἰταλία"); namesMap.put("JO", "Ἰορδανία"); namesMap.put("JP", "Ἰαπωνία"); namesMap.put("KN", "Σαὶντ Κὶτς καὶ Νέβις"); namesMap.put("KY", "Νῆσοι Κέιμαν"); namesMap.put("LA", "Λατινικὴ Ἀμερική"); namesMap.put("LC", "Ἁγία Λουκία"); namesMap.put("LK", "Σρὶ Λάνκα"); namesMap.put("LU", "Λουξεμβοῦργο"); namesMap.put("MD", "Μολδαβία, Δημοκρατία τῆς"); namesMap.put("MH", "Νῆσοι Μάρσαλ"); namesMap.put("ML", "Μαλί"); namesMap.put("MO", "Μακάο, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας"); namesMap.put("MP", "Νῆσοι Βόρειες Μαριάνες"); namesMap.put("NF", "Νῆσος Νόρφολκ"); namesMap.put("NL", "Ὁλλανδία"); namesMap.put("OM", "Ὀμάν"); namesMap.put("PF", "Γαλλικὴ Πολυνησία"); namesMap.put("PM", "Σαὶντ Πιὲρ καὶ Μικελόν"); namesMap.put("PS", "Παλαιστινιακὰ Ἐδάφη"); namesMap.put("SA", "Σαουδικὴ Ἀραβία"); namesMap.put("SB", "Νῆσοι Σολομῶντος"); namesMap.put("SH", "Ἁγία Ἑλένη"); namesMap.put("SJ", "Νῆσοι Σβάλμπαρ καὶ Γιὰν Μαγιέν"); namesMap.put("SM", "Ἅγιος Μαρίνος"); namesMap.put("ST", "Σάο Τομὲ καὶ Πρίνσιπε"); namesMap.put("SV", "Ἒλ Σαλβαδόρ"); namesMap.put("SY", "Συρία, Ἀραβικὴ Δημοκρατία τῆς"); namesMap.put("TC", "Νῆσοι Τὲρκς καὶ Κάικος"); namesMap.put("TD", "Τσάντ"); namesMap.put("TF", "Γαλλικὰ Νότια Ἐδάφη"); namesMap.put("TL", "Ἀνατολικὸ Τιμόρ"); namesMap.put("TT", "Τρινιδὰδ καὶ Τομπάγκο"); namesMap.put("UA", "Οὐκρανία"); namesMap.put("UG", "Οὐγκάντα"); namesMap.put("UM", "Ἀπομακρυσμένες Νησίδες τῶν Ἡνωμένων Πολιτειῶν"); namesMap.put("US", "Ἡνωμένες Πολιτεῖες"); namesMap.put("UY", "Οὐρουγουάη"); namesMap.put("UZ", "Οὐζμπεκιστάν"); namesMap.put("VA", "Ἁγία Ἕδρα (Βατικανό)"); namesMap.put("VC", "Ἅγιος Βικέντιος καὶ Γρεναδίνες"); namesMap.put("VG", "Βρετανικὲς Παρθένοι Νῆσοι"); namesMap.put("VI", "Ἀμερικανικὲς Παρθένοι Νῆσοι"); namesMap.put("WF", "Νῆσοι Οὐάλλις καὶ Φουτουνά"); namesMap.put("YE", "Ὑεμένη"); namesMap.put("ZA", "Νότια Ἀφρική"); } @Override protected JavaScriptObject loadNameMapNative() { return overrideMap(super.loadNameMapNative(), loadMyNameMap()); } private native JavaScriptObject loadMyNameMap() /*-{ <SUF>*/; }
31643_6
package org.elasticsearch.index.analysis; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.ESLoggerFactory; /** * @author Tasos Stathopoulos * Generates singular/plural variants of a greek word based * on a combination of predefined rules. */ public class GreekReverseStemmer { /** * Elastic Search logger */ private static final Logger logger = ESLoggerFactory.getLogger( GreeklishConverter.class.getName()); /** * Constant variable that represent suffixes for pluralization of * greeklish tokens. */ private static final String SUFFIX_MATOS = "ματοσ"; private static final String SUFFIX_MATA = "ματα"; private static final String SUFFIX_MATWN = "ματων"; private static final String SUFFIX_AS = "ασ"; private static final String SUFFIX_EIA = "εια"; private static final String SUFFIX_EIO = "ειο"; private static final String SUFFIX_EIOY = "ειου"; private static final String SUFFIX_EIWN = "ειων"; private static final String SUFFIX_IOY = "ιου"; private static final String SUFFIX_IA = "ια"; private static final String SUFFIX_IWN = "ιων"; private static final String SUFFIX_OS = "οσ"; private static final String SUFFIX_OI = "οι"; private static final String SUFFIX_EIS = "εισ"; private static final String SUFFIX_ES = "εσ"; private static final String SUFFIX_HS = "ησ"; private static final String SUFFIX_WN = "ων"; private static final String SUFFIX_OY = "ου"; private static final String SUFFIX_O = "ο"; private static final String SUFFIX_H = "η"; private static final String SUFFIX_A = "α"; private static final String SUFFIX_I = "ι"; /** * This hash has as keys all the suffixes that we want to handle in order * to generate singular/plural greek words. */ private final Map<String, String[]> suffixes = new HashMap<String, String[]>(); /** * The possible suffix strings. */ private static final String[][] suffixStrings = new String[][] { {SUFFIX_MATOS, "μα", "ματων", "ματα"}, // κουρεματος, ασυρματος {SUFFIX_MATA, "μα", "ματων", "ματοσ"}, // ενδυματα {SUFFIX_MATWN, "μα", "ματα", "ματοσ"}, // ασυρματων, ενδυματων {SUFFIX_AS, "α", "ων", "εσ"}, // πορτας, χαρτοφυλακας {SUFFIX_EIA, "ειο", "ειων", "ειου", "ειασ"}, // γραφεια, ενεργεια {SUFFIX_EIO, "εια", "ειων", "ειου"}, // γραφειο {SUFFIX_EIOY, "εια", "ειου", "ειο", "ειων"}, // γραφειου {SUFFIX_EIWN, "εια", "ειου", "ειο", "ειασ"}, // ασφαλειων, γραφειων {SUFFIX_IOY, "ι", "ια", "ιων", "ιο"}, // πεδιου, κυνηγιου {SUFFIX_IA, "ιου", "ι", "ιων", "ιασ", "ιο"}, // πεδία, αρμονια {SUFFIX_IWN, "ιου", "ια", "ι", "ιο"}, // καλωδιων, κατοικιδιων {SUFFIX_OS, "η", "ουσ", "ου", "οι", "ων"}, // κλιματισμος {SUFFIX_OI, "οσ", "ου", "ων"}, // μυλοι, οδηγοι, σταθμοι {SUFFIX_EIS, "η", "ησ", "εων"}, // συνδεσεις, τηλεορασεις {SUFFIX_ES, "η", "ασ", "ων", "ησ", "α"}, // αλυσιδες {SUFFIX_HS, "ων", "εσ", "η", "εων"}, // γυμναστικης, εκτυπωσης {SUFFIX_WN, "οσ", "εσ", "α", "η", "ησ", "ου", "οι", "ο", "α"}, // ινων, καπνιστων, καρτων, κατασκευων {SUFFIX_OY, "ων", "α", "ο", "οσ"}, // λαδιου, μοντελισμου, παιδικου {SUFFIX_O, "α", "ου", "εων", "ων"}, // αυτοκινητο, δισκος {SUFFIX_H, "οσ", "ουσ", "εων", "εισ", "ησ", "ων"}, //βελη, ψυξη, τηλεοραση, αποτριχωση {SUFFIX_A, "ο" , "ου", "ων", "ασ", "εσ"}, // γιλεκα, εσωρουχα, ομπρελλα {SUFFIX_I, "ιου", "ια", "ιων"} // γιαουρτι, γραναζι }; /** * The greek word list */ private List<String> greekWords = new ArrayList<String>(); // Constructor public GreekReverseStemmer() { // populate suffixes for (String[] suffix : suffixStrings) { suffixes.put(suffix[0], Arrays.copyOfRange(suffix, 1, suffix.length)); } } /** * This method generates the greek variants of the greek token that * receives. * * @param tokenString the greek word * @return a list of the generated greek word variations */ public List<String> generateGreekVariants(String tokenString) { // clear the list from variations of the previous greek token greekWords.clear(); // add the initial greek token in the greek words greekWords.add(tokenString); // Find the first matching suffix and generate the // the variants of this word for (String[] suffix : suffixStrings) { if (tokenString.endsWith(suffix[0])) { // Add to greekWords the tokens with the desired suffixes generate_more_greek_words(tokenString, suffix[0]); break; } } return greekWords; } /** * Generates more greek words based on the suffix of the original word * @param inputSuffix the suffix that matched */ private void generate_more_greek_words(final String inputToken, final String inputSuffix) { for (String suffix : suffixes.get(inputSuffix)) { greekWords.add(inputToken.replaceAll(inputSuffix + "$", suffix)); } } }
stjordanis/elasticsearch-analysis-greeklish
src/main/java/org/elasticsearch/index/analysis/GreekReverseStemmer.java
2,035
// ινων, καπνιστων, καρτων, κατασκευων
line_comment
el
package org.elasticsearch.index.analysis; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.ESLoggerFactory; /** * @author Tasos Stathopoulos * Generates singular/plural variants of a greek word based * on a combination of predefined rules. */ public class GreekReverseStemmer { /** * Elastic Search logger */ private static final Logger logger = ESLoggerFactory.getLogger( GreeklishConverter.class.getName()); /** * Constant variable that represent suffixes for pluralization of * greeklish tokens. */ private static final String SUFFIX_MATOS = "ματοσ"; private static final String SUFFIX_MATA = "ματα"; private static final String SUFFIX_MATWN = "ματων"; private static final String SUFFIX_AS = "ασ"; private static final String SUFFIX_EIA = "εια"; private static final String SUFFIX_EIO = "ειο"; private static final String SUFFIX_EIOY = "ειου"; private static final String SUFFIX_EIWN = "ειων"; private static final String SUFFIX_IOY = "ιου"; private static final String SUFFIX_IA = "ια"; private static final String SUFFIX_IWN = "ιων"; private static final String SUFFIX_OS = "οσ"; private static final String SUFFIX_OI = "οι"; private static final String SUFFIX_EIS = "εισ"; private static final String SUFFIX_ES = "εσ"; private static final String SUFFIX_HS = "ησ"; private static final String SUFFIX_WN = "ων"; private static final String SUFFIX_OY = "ου"; private static final String SUFFIX_O = "ο"; private static final String SUFFIX_H = "η"; private static final String SUFFIX_A = "α"; private static final String SUFFIX_I = "ι"; /** * This hash has as keys all the suffixes that we want to handle in order * to generate singular/plural greek words. */ private final Map<String, String[]> suffixes = new HashMap<String, String[]>(); /** * The possible suffix strings. */ private static final String[][] suffixStrings = new String[][] { {SUFFIX_MATOS, "μα", "ματων", "ματα"}, // κουρεματος, ασυρματος {SUFFIX_MATA, "μα", "ματων", "ματοσ"}, // ενδυματα {SUFFIX_MATWN, "μα", "ματα", "ματοσ"}, // ασυρματων, ενδυματων {SUFFIX_AS, "α", "ων", "εσ"}, // πορτας, χαρτοφυλακας {SUFFIX_EIA, "ειο", "ειων", "ειου", "ειασ"}, // γραφεια, ενεργεια {SUFFIX_EIO, "εια", "ειων", "ειου"}, // γραφειο {SUFFIX_EIOY, "εια", "ειου", "ειο", "ειων"}, // γραφειου {SUFFIX_EIWN, "εια", "ειου", "ειο", "ειασ"}, // ασφαλειων, γραφειων {SUFFIX_IOY, "ι", "ια", "ιων", "ιο"}, // πεδιου, κυνηγιου {SUFFIX_IA, "ιου", "ι", "ιων", "ιασ", "ιο"}, // πεδία, αρμονια {SUFFIX_IWN, "ιου", "ια", "ι", "ιο"}, // καλωδιων, κατοικιδιων {SUFFIX_OS, "η", "ουσ", "ου", "οι", "ων"}, // κλιματισμος {SUFFIX_OI, "οσ", "ου", "ων"}, // μυλοι, οδηγοι, σταθμοι {SUFFIX_EIS, "η", "ησ", "εων"}, // συνδεσεις, τηλεορασεις {SUFFIX_ES, "η", "ασ", "ων", "ησ", "α"}, // αλυσιδες {SUFFIX_HS, "ων", "εσ", "η", "εων"}, // γυμναστικης, εκτυπωσης {SUFFIX_WN, "οσ", "εσ", "α", "η", "ησ", "ου", "οι", "ο", "α"}, // ινων, καπνιστων,<SUF> {SUFFIX_OY, "ων", "α", "ο", "οσ"}, // λαδιου, μοντελισμου, παιδικου {SUFFIX_O, "α", "ου", "εων", "ων"}, // αυτοκινητο, δισκος {SUFFIX_H, "οσ", "ουσ", "εων", "εισ", "ησ", "ων"}, //βελη, ψυξη, τηλεοραση, αποτριχωση {SUFFIX_A, "ο" , "ου", "ων", "ασ", "εσ"}, // γιλεκα, εσωρουχα, ομπρελλα {SUFFIX_I, "ιου", "ια", "ιων"} // γιαουρτι, γραναζι }; /** * The greek word list */ private List<String> greekWords = new ArrayList<String>(); // Constructor public GreekReverseStemmer() { // populate suffixes for (String[] suffix : suffixStrings) { suffixes.put(suffix[0], Arrays.copyOfRange(suffix, 1, suffix.length)); } } /** * This method generates the greek variants of the greek token that * receives. * * @param tokenString the greek word * @return a list of the generated greek word variations */ public List<String> generateGreekVariants(String tokenString) { // clear the list from variations of the previous greek token greekWords.clear(); // add the initial greek token in the greek words greekWords.add(tokenString); // Find the first matching suffix and generate the // the variants of this word for (String[] suffix : suffixStrings) { if (tokenString.endsWith(suffix[0])) { // Add to greekWords the tokens with the desired suffixes generate_more_greek_words(tokenString, suffix[0]); break; } } return greekWords; } /** * Generates more greek words based on the suffix of the original word * @param inputSuffix the suffix that matched */ private void generate_more_greek_words(final String inputToken, final String inputSuffix) { for (String suffix : suffixes.get(inputSuffix)) { greekWords.add(inputToken.replaceAll(inputSuffix + "$", suffix)); } } }
37927_45
package gr.hcg.sign; import com.google.zxing.BarcodeFormat; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.io.IOUtils; import org.apache.pdfbox.io.RandomAccessFile; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.PDResources; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.common.PDStream; import org.apache.pdfbox.pdmodel.fixup.PDDocumentFixup; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.font.PDType0Font; import org.apache.pdfbox.pdmodel.font.PDType1Font; import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceDictionary; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceStream; import org.apache.pdfbox.pdmodel.interactive.digitalsignature.ExternalSigningSupport; import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature; import org.apache.pdfbox.pdmodel.interactive.digitalsignature.SignatureInterface; import org.apache.pdfbox.pdmodel.interactive.digitalsignature.SignatureOptions; import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm; import org.apache.pdfbox.pdmodel.interactive.form.PDField; import org.apache.pdfbox.pdmodel.interactive.form.PDSignatureField; import org.apache.pdfbox.util.Hex; import org.apache.pdfbox.util.Matrix; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.io.*; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.text.SimpleDateFormat; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.List; import java.util.Map; /** * This is a second example for visual signing a pdf. It doesn't use the "design * pattern" influenced * PDVisibleSignDesigner, and doesn't create its complex multilevel forms * described in the Adobe * document * <a href= * "https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PPKAppearances.pdf">Digital * Signature Appearances</a>, because this isn't required by the PDF * specification. See the * discussion in December 2017 in PDFBOX-3198. * * @author Vakhtang Koroghlishvili * @author Tilman Hausherr */ public class CreateVisibleSignatureMem extends CreateSignatureBase { private SignatureOptions signatureOptions; private byte[] imageBytes; public String signatureName = "AUTO SIGNATURE"; public String signatureLocation = "Kanpur"; public String signatureReason = "IDENTICAL COPY"; public String visibleLine1 = "DIGITALLY SIGNED"; public String visibleLine2 = "Signed by Kanpur development authority"; public String uuid = "123e4567-e89b-12d3-a456-426614174000"; private Calendar signDate = null; /** * Initialize the signature creator with a keystore (pkcs12) and pin that * should be used for the signature. * * @param keystore is a pkcs12 keystore. * @param pin is the pin for the keystore / private key * @throws KeyStoreException if the keystore has not been initialized * (loaded) * @throws NoSuchAlgorithmException if the algorithm for recovering the key * cannot be found * @throws UnrecoverableKeyException if the given password is wrong * @throws UnrecoverableKeyException if the given password is wrong * @throws CertificateException if the certificate is not valid as signing * time * @throws IOException if no certificate could be found */ public CreateVisibleSignatureMem(KeyStore keystore, char[] pin) throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, IOException, CertificateException { super(keystore, pin); } public byte[] getImageBytes() { return imageBytes; } public void setImageBytes(byte[] imageBytes) { this.imageBytes = imageBytes; } /** * Sign pdf file and create new file that ends with "_signed.pdf". * * @param inputStream The source pdf document file. * @param signedStream The file to be signed. * @param tsaUrl optional TSA url * @param signatureFieldName optional name of an existing (unsigned) signature * field * @throws IOException */ public Calendar signPDF(InputStream inputStream, OutputStream signedStream, String tsaUrl, String signatureFieldName) throws IOException { setTsaUrl(tsaUrl); try (PDDocument doc = PDDocument.load(inputStream)) { int accessPermissions = SigUtils.getMDPPermission(doc); if (accessPermissions == 1) { throw new IllegalStateException( "No changes to the document are permitted due to DocMDP transform parameters dictionary"); } // Note that PDFBox has a bug that visual signing on certified files with // permission 2 // doesn't work properly, see PDFBOX-3699. As long as this issue is open, you // may want to // be careful with such files. PDSignature signature = null; PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm(); PDRectangle rect = null; PDShrink.shrinkFirstpage(doc); // sign a PDF with an existing empty signature, as created by the // CreateEmptySignatureForm example. if (acroForm != null) { signature = findExistingSignature(acroForm, signatureFieldName); if (signature != null) { rect = acroForm.getField(signatureFieldName).getWidgets().get(0).getRectangle(); } } if (signature == null) { // create signature dictionary signature = new PDSignature(); } if (rect == null) { float width = doc.getPage(0).getMediaBox().getWidth(); Rectangle2D humanRect = new Rectangle2D.Float(0, 600, 900, 100); rect = createSignatureRectangle(doc, humanRect); } // Optional: certify // can be done only if version is at least 1.5 and if not already set // doing this on a PDF/A-1b file fails validation by Adobe preflight // (PDFBOX-3821) // PDF/A-1b requires PDF version 1.4 max, so don't increase the version on such // files. if (doc.getVersion() >= 1.5f && accessPermissions == 0) { SigUtils.setMDPPermission(doc, signature, 2); } if (acroForm != null && acroForm.getNeedAppearances()) { // PDFBOX-3738 NeedAppearances true results in visible signature becoming // invisible // with Adobe Reader if (acroForm.getFields().isEmpty()) { // we can safely delete it if there are no fields acroForm.getCOSObject().removeItem(COSName.NEED_APPEARANCES); // note that if you've set MDP permissions, the removal of this item // may result in Adobe Reader claiming that the document has been changed. // and/or that field content won't be displayed properly. // ==> decide what you prefer and adjust your code accordingly. } else { System.out.println("/NeedAppearances is set, signature may be ignored by Adobe Reader"); } } // default filter signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE); // subfilter for basic and PAdES Part 2 signatures signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED); signature.setName(this.signatureName); signature.setLocation(this.signatureLocation); signature.setReason(this.signatureReason); this.signDate = Calendar.getInstance(); // the signing date, needed for valid signature signature.setSignDate(this.signDate); // do not set SignatureInterface instance, if external signing used SignatureInterface signatureInterface = isExternalSigning() ? null : this; // register signature dictionary and sign interface signatureOptions = new SignatureOptions(); signatureOptions.setPreferredSignatureSize(8192 * 2); signatureOptions.setVisualSignature(createVisualSignatureTemplate(doc, 0, rect)); signatureOptions.setPage(0); doc.addSignature(signature, signatureInterface, signatureOptions); // write incremental (only for signing purpose) doc.saveIncremental(signedStream); } // Do not close signatureOptions before saving, because some COSStream objects // within // are transferred to the signed document. // Do not allow signatureOptions get out of scope before saving, because then // the COSDocument // in signature options might by closed by gc, which would close COSStream // objects prematurely. // See https://issues.apache.org/jira/browse/PDFBOX-3743 IOUtils.closeQuietly(signatureOptions); return this.signDate; } private PDRectangle createSignatureRectangle(PDDocument doc, Rectangle2D humanRect) { float x = (float) humanRect.getX(); float y = (float) humanRect.getY(); float width = (float) humanRect.getWidth(); float height = (float) humanRect.getHeight(); PDPage page = doc.getPage(0); PDRectangle pageRect = page.getCropBox(); PDRectangle rect = new PDRectangle(); // signing should be at the same position regardless of page rotation. switch (page.getRotation()) { case 90: rect.setLowerLeftY(x); rect.setUpperRightY(x + width); rect.setLowerLeftX(y); rect.setUpperRightX(y + height); break; case 180: rect.setUpperRightX(pageRect.getWidth() - x); rect.setLowerLeftX(pageRect.getWidth() - x - width); rect.setLowerLeftY(y); rect.setUpperRightY(y + height); break; case 270: rect.setLowerLeftY(pageRect.getHeight() - x - width); rect.setUpperRightY(pageRect.getHeight() - x); rect.setLowerLeftX(pageRect.getWidth() - y - height); rect.setUpperRightX(pageRect.getWidth() - y); break; case 0: default: rect.setLowerLeftX(x); rect.setUpperRightX(x + width); // rect.setLowerLeftY(pageRect.getHeight() - y - height); // rect.setUpperRightY(pageRect.getHeight() - y); rect.setLowerLeftY(y); rect.setUpperRightY(y + height); break; } return rect; } // create a template PDF document with empty signature and return it as a // stream. private InputStream createVisualSignatureTemplate(PDDocument srcDoc, int pageNum, PDRectangle rect) throws IOException { try (PDDocument doc = new PDDocument()) { PDPage page = new PDPage(srcDoc.getPage(pageNum).getMediaBox()); doc.addPage(page); PDAcroForm acroForm = new PDAcroForm(doc); doc.getDocumentCatalog().setAcroForm(acroForm); PDSignatureField signatureField = new PDSignatureField(acroForm); PDAnnotationWidget widget = signatureField.getWidgets().get(0); List<PDField> acroFormFields = acroForm.getFields(); acroForm.setSignaturesExist(true); acroForm.setAppendOnly(true); acroForm.getCOSObject().setDirect(true); acroFormFields.add(signatureField); widget.setRectangle(rect); // from PDVisualSigBuilder.createHolderForm() PDStream stream = new PDStream(doc); PDFormXObject form = new PDFormXObject(stream); PDResources res = new PDResources(); form.setResources(res); form.setFormType(1); PDRectangle bbox = new PDRectangle(rect.getWidth(), rect.getHeight()); float height = bbox.getHeight(); Matrix initialScale = null; switch (srcDoc.getPage(pageNum).getRotation()) { case 90: form.setMatrix(AffineTransform.getQuadrantRotateInstance(1)); initialScale = Matrix.getScaleInstance(bbox.getWidth() / bbox.getHeight(), bbox.getHeight() / bbox.getWidth()); height = bbox.getWidth(); break; case 180: form.setMatrix(AffineTransform.getQuadrantRotateInstance(2)); break; case 270: form.setMatrix(AffineTransform.getQuadrantRotateInstance(3)); initialScale = Matrix.getScaleInstance(bbox.getWidth() / bbox.getHeight(), bbox.getHeight() / bbox.getWidth()); height = bbox.getWidth(); break; case 0: default: break; } form.setBBox(bbox); // PDFont font = PDType1Font.HELVETICA_BOLD; InputStream fontInputStream = CreateVisibleSignatureMem.class.getClassLoader() .getResourceAsStream("calibri.ttf"); PDFont font = PDType0Font.load(doc, fontInputStream); // from PDVisualSigBuilder.createAppearanceDictionary() PDAppearanceDictionary appearance = new PDAppearanceDictionary(); appearance.getCOSObject().setDirect(true); PDAppearanceStream appearanceStream = new PDAppearanceStream(form.getCOSObject()); appearance.setNormalAppearance(appearanceStream); widget.setAppearance(appearance); float w = appearanceStream.getBBox().getWidth(); float h = appearanceStream.getBBox().getHeight(); try (PDPageContentStream cs = new PDPageContentStream(doc, appearanceStream)) { // for 90° and 270° scale ratio of width / height // not really sure about this // why does scale have no effect when done in the form matrix??? if (initialScale != null) { cs.transform(initialScale); } // show background (just for debugging, to see the rect size + position) // cs.setNonStrokingColor(new Color(.95f,.95f,.95f)); // cs.addRect(-5000, -5000, 10000, 10000); // cs.fill(); addHeader(cs, w, h, font); cs.saveGraphicsState(); addFooter(cs, w, h, srcDoc); addCenterPart(cs, w, h, font, this.signDate); addRightPart(cs, font, w, h, this.signDate, this.visibleLine1, this.visibleLine2); addCenterOverlay(cs, w, h, doc, imageBytes); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); doc.save(baos); return new ByteArrayInputStream(baos.toByteArray()); } } private static void addHeader(PDPageContentStream cs, float w, float h, PDFont font) throws IOException { cs.setNonStrokingColor(Color.BLACK); // cs.addRect(10, h-8, w/3, 5); // cs.fill(); float fontSize = 10; cs.beginText(); cs.setFont(font, fontSize); cs.setNonStrokingColor(Color.black); // cs.newLineAtOffset(w/3 + 40, h-8); // cs.showText("Digitally signed copy"); cs.endText(); float[] dashPattern = { 5f, 5f }; // An example pattern: 5 units on, 5 units off float phase = 2f; // Example phase value cs.setLineDashPattern(dashPattern, phase); // cs.addRect(2*w/3, h-8, w/3-10, 5); // cs.fill(); } private static void addFooter(PDPageContentStream cs, float w, float h, PDDocument srcDoc) throws IOException { cs.beginText(); cs.newLineAtOffset(w / 2 - 30, 20); cs.endText(); } private static void addCenterPart(PDPageContentStream cs, float w, float h, PDFont font, Calendar signDate) throws IOException { cs.beginText(); cs.setFont(font, 7); cs.newLineAtOffset(w / 2 - 40, h - 40); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyMMddHHmmssSZ"); cs.endText(); } private static void addCenterOverlay(PDPageContentStream cs, float w, float h, PDDocument doc, byte[] imageBytes) throws IOException { float alpha = 0.2f; PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState(); graphicsState.setStrokingAlphaConstant(alpha); graphicsState.setNonStrokingAlphaConstant(alpha); cs.setGraphicsStateParameters(graphicsState); PDImageXObject img = PDImageXObject.createFromByteArray(doc, imageBytes, null); img.setHeight(30); img.setWidth(35); cs.drawImage(img, w / 2, h / 2); cs.restoreGraphicsState(); } private static void addRightPart(PDPageContentStream cs, PDFont font, float w, float h, Calendar signDate, String visibleLine1, String visibleLine2) throws IOException { float fontSize = 9f; cs.setFont(font, fontSize); // showTextRight(cs, font, "Υπογραφή από:", w, h-40, fontSize); showTextRight(cs, font, visibleLine1, w, h - 50, fontSize); showTextRight(cs, font, visibleLine2, w, h - 60, fontSize); // showTextRight(cs, font, "Ημερομηνία υπογραφής:", w, h-70, fontSize); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); showTextRight(cs, font, sdf.format(signDate.getTime()), w, h - 80, fontSize); } private static void showTextRight(PDPageContentStream cs, PDFont font, String text, float w, float y, float fontSize) throws IOException { cs.beginText(); float xoffset = w - font.getStringWidth(text) / 1000 * fontSize - 15; cs.newLineAtOffset(xoffset, y); cs.setNonStrokingColor(Color.black); cs.showText(text); cs.endText(); } // Find an existing signature (assumed to be empty). You will usually not need // this. private PDSignature findExistingSignature(PDAcroForm acroForm, String sigFieldName) { PDSignature signature = null; PDSignatureField signatureField; if (acroForm != null) { signatureField = (PDSignatureField) acroForm.getField(sigFieldName); if (signatureField != null) { // retrieve signature dictionary signature = signatureField.getSignature(); if (signature == null) { signature = new PDSignature(); // after solving PDFBOX-3524 // signatureField.setValue(signature) // until then: signatureField.getCOSObject().setItem(COSName.V, signature); } else { throw new IllegalStateException("The signature field " + sigFieldName + " is already signed."); } } } return signature; } }
sumitpatel93/digital-signature
src/main/java/gr/hcg/sign/CreateVisibleSignatureMem.java
4,921
// showTextRight(cs, font, "Ημερομηνία υπογραφής:", w, h-70, fontSize);
line_comment
el
package gr.hcg.sign; import com.google.zxing.BarcodeFormat; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.io.IOUtils; import org.apache.pdfbox.io.RandomAccessFile; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.PDResources; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.common.PDStream; import org.apache.pdfbox.pdmodel.fixup.PDDocumentFixup; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.font.PDType0Font; import org.apache.pdfbox.pdmodel.font.PDType1Font; import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceDictionary; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceStream; import org.apache.pdfbox.pdmodel.interactive.digitalsignature.ExternalSigningSupport; import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature; import org.apache.pdfbox.pdmodel.interactive.digitalsignature.SignatureInterface; import org.apache.pdfbox.pdmodel.interactive.digitalsignature.SignatureOptions; import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm; import org.apache.pdfbox.pdmodel.interactive.form.PDField; import org.apache.pdfbox.pdmodel.interactive.form.PDSignatureField; import org.apache.pdfbox.util.Hex; import org.apache.pdfbox.util.Matrix; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.io.*; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.text.SimpleDateFormat; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.List; import java.util.Map; /** * This is a second example for visual signing a pdf. It doesn't use the "design * pattern" influenced * PDVisibleSignDesigner, and doesn't create its complex multilevel forms * described in the Adobe * document * <a href= * "https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PPKAppearances.pdf">Digital * Signature Appearances</a>, because this isn't required by the PDF * specification. See the * discussion in December 2017 in PDFBOX-3198. * * @author Vakhtang Koroghlishvili * @author Tilman Hausherr */ public class CreateVisibleSignatureMem extends CreateSignatureBase { private SignatureOptions signatureOptions; private byte[] imageBytes; public String signatureName = "AUTO SIGNATURE"; public String signatureLocation = "Kanpur"; public String signatureReason = "IDENTICAL COPY"; public String visibleLine1 = "DIGITALLY SIGNED"; public String visibleLine2 = "Signed by Kanpur development authority"; public String uuid = "123e4567-e89b-12d3-a456-426614174000"; private Calendar signDate = null; /** * Initialize the signature creator with a keystore (pkcs12) and pin that * should be used for the signature. * * @param keystore is a pkcs12 keystore. * @param pin is the pin for the keystore / private key * @throws KeyStoreException if the keystore has not been initialized * (loaded) * @throws NoSuchAlgorithmException if the algorithm for recovering the key * cannot be found * @throws UnrecoverableKeyException if the given password is wrong * @throws UnrecoverableKeyException if the given password is wrong * @throws CertificateException if the certificate is not valid as signing * time * @throws IOException if no certificate could be found */ public CreateVisibleSignatureMem(KeyStore keystore, char[] pin) throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, IOException, CertificateException { super(keystore, pin); } public byte[] getImageBytes() { return imageBytes; } public void setImageBytes(byte[] imageBytes) { this.imageBytes = imageBytes; } /** * Sign pdf file and create new file that ends with "_signed.pdf". * * @param inputStream The source pdf document file. * @param signedStream The file to be signed. * @param tsaUrl optional TSA url * @param signatureFieldName optional name of an existing (unsigned) signature * field * @throws IOException */ public Calendar signPDF(InputStream inputStream, OutputStream signedStream, String tsaUrl, String signatureFieldName) throws IOException { setTsaUrl(tsaUrl); try (PDDocument doc = PDDocument.load(inputStream)) { int accessPermissions = SigUtils.getMDPPermission(doc); if (accessPermissions == 1) { throw new IllegalStateException( "No changes to the document are permitted due to DocMDP transform parameters dictionary"); } // Note that PDFBox has a bug that visual signing on certified files with // permission 2 // doesn't work properly, see PDFBOX-3699. As long as this issue is open, you // may want to // be careful with such files. PDSignature signature = null; PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm(); PDRectangle rect = null; PDShrink.shrinkFirstpage(doc); // sign a PDF with an existing empty signature, as created by the // CreateEmptySignatureForm example. if (acroForm != null) { signature = findExistingSignature(acroForm, signatureFieldName); if (signature != null) { rect = acroForm.getField(signatureFieldName).getWidgets().get(0).getRectangle(); } } if (signature == null) { // create signature dictionary signature = new PDSignature(); } if (rect == null) { float width = doc.getPage(0).getMediaBox().getWidth(); Rectangle2D humanRect = new Rectangle2D.Float(0, 600, 900, 100); rect = createSignatureRectangle(doc, humanRect); } // Optional: certify // can be done only if version is at least 1.5 and if not already set // doing this on a PDF/A-1b file fails validation by Adobe preflight // (PDFBOX-3821) // PDF/A-1b requires PDF version 1.4 max, so don't increase the version on such // files. if (doc.getVersion() >= 1.5f && accessPermissions == 0) { SigUtils.setMDPPermission(doc, signature, 2); } if (acroForm != null && acroForm.getNeedAppearances()) { // PDFBOX-3738 NeedAppearances true results in visible signature becoming // invisible // with Adobe Reader if (acroForm.getFields().isEmpty()) { // we can safely delete it if there are no fields acroForm.getCOSObject().removeItem(COSName.NEED_APPEARANCES); // note that if you've set MDP permissions, the removal of this item // may result in Adobe Reader claiming that the document has been changed. // and/or that field content won't be displayed properly. // ==> decide what you prefer and adjust your code accordingly. } else { System.out.println("/NeedAppearances is set, signature may be ignored by Adobe Reader"); } } // default filter signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE); // subfilter for basic and PAdES Part 2 signatures signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED); signature.setName(this.signatureName); signature.setLocation(this.signatureLocation); signature.setReason(this.signatureReason); this.signDate = Calendar.getInstance(); // the signing date, needed for valid signature signature.setSignDate(this.signDate); // do not set SignatureInterface instance, if external signing used SignatureInterface signatureInterface = isExternalSigning() ? null : this; // register signature dictionary and sign interface signatureOptions = new SignatureOptions(); signatureOptions.setPreferredSignatureSize(8192 * 2); signatureOptions.setVisualSignature(createVisualSignatureTemplate(doc, 0, rect)); signatureOptions.setPage(0); doc.addSignature(signature, signatureInterface, signatureOptions); // write incremental (only for signing purpose) doc.saveIncremental(signedStream); } // Do not close signatureOptions before saving, because some COSStream objects // within // are transferred to the signed document. // Do not allow signatureOptions get out of scope before saving, because then // the COSDocument // in signature options might by closed by gc, which would close COSStream // objects prematurely. // See https://issues.apache.org/jira/browse/PDFBOX-3743 IOUtils.closeQuietly(signatureOptions); return this.signDate; } private PDRectangle createSignatureRectangle(PDDocument doc, Rectangle2D humanRect) { float x = (float) humanRect.getX(); float y = (float) humanRect.getY(); float width = (float) humanRect.getWidth(); float height = (float) humanRect.getHeight(); PDPage page = doc.getPage(0); PDRectangle pageRect = page.getCropBox(); PDRectangle rect = new PDRectangle(); // signing should be at the same position regardless of page rotation. switch (page.getRotation()) { case 90: rect.setLowerLeftY(x); rect.setUpperRightY(x + width); rect.setLowerLeftX(y); rect.setUpperRightX(y + height); break; case 180: rect.setUpperRightX(pageRect.getWidth() - x); rect.setLowerLeftX(pageRect.getWidth() - x - width); rect.setLowerLeftY(y); rect.setUpperRightY(y + height); break; case 270: rect.setLowerLeftY(pageRect.getHeight() - x - width); rect.setUpperRightY(pageRect.getHeight() - x); rect.setLowerLeftX(pageRect.getWidth() - y - height); rect.setUpperRightX(pageRect.getWidth() - y); break; case 0: default: rect.setLowerLeftX(x); rect.setUpperRightX(x + width); // rect.setLowerLeftY(pageRect.getHeight() - y - height); // rect.setUpperRightY(pageRect.getHeight() - y); rect.setLowerLeftY(y); rect.setUpperRightY(y + height); break; } return rect; } // create a template PDF document with empty signature and return it as a // stream. private InputStream createVisualSignatureTemplate(PDDocument srcDoc, int pageNum, PDRectangle rect) throws IOException { try (PDDocument doc = new PDDocument()) { PDPage page = new PDPage(srcDoc.getPage(pageNum).getMediaBox()); doc.addPage(page); PDAcroForm acroForm = new PDAcroForm(doc); doc.getDocumentCatalog().setAcroForm(acroForm); PDSignatureField signatureField = new PDSignatureField(acroForm); PDAnnotationWidget widget = signatureField.getWidgets().get(0); List<PDField> acroFormFields = acroForm.getFields(); acroForm.setSignaturesExist(true); acroForm.setAppendOnly(true); acroForm.getCOSObject().setDirect(true); acroFormFields.add(signatureField); widget.setRectangle(rect); // from PDVisualSigBuilder.createHolderForm() PDStream stream = new PDStream(doc); PDFormXObject form = new PDFormXObject(stream); PDResources res = new PDResources(); form.setResources(res); form.setFormType(1); PDRectangle bbox = new PDRectangle(rect.getWidth(), rect.getHeight()); float height = bbox.getHeight(); Matrix initialScale = null; switch (srcDoc.getPage(pageNum).getRotation()) { case 90: form.setMatrix(AffineTransform.getQuadrantRotateInstance(1)); initialScale = Matrix.getScaleInstance(bbox.getWidth() / bbox.getHeight(), bbox.getHeight() / bbox.getWidth()); height = bbox.getWidth(); break; case 180: form.setMatrix(AffineTransform.getQuadrantRotateInstance(2)); break; case 270: form.setMatrix(AffineTransform.getQuadrantRotateInstance(3)); initialScale = Matrix.getScaleInstance(bbox.getWidth() / bbox.getHeight(), bbox.getHeight() / bbox.getWidth()); height = bbox.getWidth(); break; case 0: default: break; } form.setBBox(bbox); // PDFont font = PDType1Font.HELVETICA_BOLD; InputStream fontInputStream = CreateVisibleSignatureMem.class.getClassLoader() .getResourceAsStream("calibri.ttf"); PDFont font = PDType0Font.load(doc, fontInputStream); // from PDVisualSigBuilder.createAppearanceDictionary() PDAppearanceDictionary appearance = new PDAppearanceDictionary(); appearance.getCOSObject().setDirect(true); PDAppearanceStream appearanceStream = new PDAppearanceStream(form.getCOSObject()); appearance.setNormalAppearance(appearanceStream); widget.setAppearance(appearance); float w = appearanceStream.getBBox().getWidth(); float h = appearanceStream.getBBox().getHeight(); try (PDPageContentStream cs = new PDPageContentStream(doc, appearanceStream)) { // for 90° and 270° scale ratio of width / height // not really sure about this // why does scale have no effect when done in the form matrix??? if (initialScale != null) { cs.transform(initialScale); } // show background (just for debugging, to see the rect size + position) // cs.setNonStrokingColor(new Color(.95f,.95f,.95f)); // cs.addRect(-5000, -5000, 10000, 10000); // cs.fill(); addHeader(cs, w, h, font); cs.saveGraphicsState(); addFooter(cs, w, h, srcDoc); addCenterPart(cs, w, h, font, this.signDate); addRightPart(cs, font, w, h, this.signDate, this.visibleLine1, this.visibleLine2); addCenterOverlay(cs, w, h, doc, imageBytes); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); doc.save(baos); return new ByteArrayInputStream(baos.toByteArray()); } } private static void addHeader(PDPageContentStream cs, float w, float h, PDFont font) throws IOException { cs.setNonStrokingColor(Color.BLACK); // cs.addRect(10, h-8, w/3, 5); // cs.fill(); float fontSize = 10; cs.beginText(); cs.setFont(font, fontSize); cs.setNonStrokingColor(Color.black); // cs.newLineAtOffset(w/3 + 40, h-8); // cs.showText("Digitally signed copy"); cs.endText(); float[] dashPattern = { 5f, 5f }; // An example pattern: 5 units on, 5 units off float phase = 2f; // Example phase value cs.setLineDashPattern(dashPattern, phase); // cs.addRect(2*w/3, h-8, w/3-10, 5); // cs.fill(); } private static void addFooter(PDPageContentStream cs, float w, float h, PDDocument srcDoc) throws IOException { cs.beginText(); cs.newLineAtOffset(w / 2 - 30, 20); cs.endText(); } private static void addCenterPart(PDPageContentStream cs, float w, float h, PDFont font, Calendar signDate) throws IOException { cs.beginText(); cs.setFont(font, 7); cs.newLineAtOffset(w / 2 - 40, h - 40); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyMMddHHmmssSZ"); cs.endText(); } private static void addCenterOverlay(PDPageContentStream cs, float w, float h, PDDocument doc, byte[] imageBytes) throws IOException { float alpha = 0.2f; PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState(); graphicsState.setStrokingAlphaConstant(alpha); graphicsState.setNonStrokingAlphaConstant(alpha); cs.setGraphicsStateParameters(graphicsState); PDImageXObject img = PDImageXObject.createFromByteArray(doc, imageBytes, null); img.setHeight(30); img.setWidth(35); cs.drawImage(img, w / 2, h / 2); cs.restoreGraphicsState(); } private static void addRightPart(PDPageContentStream cs, PDFont font, float w, float h, Calendar signDate, String visibleLine1, String visibleLine2) throws IOException { float fontSize = 9f; cs.setFont(font, fontSize); // showTextRight(cs, font, "Υπογραφή από:", w, h-40, fontSize); showTextRight(cs, font, visibleLine1, w, h - 50, fontSize); showTextRight(cs, font, visibleLine2, w, h - 60, fontSize); // showTextRight(cs, font,<SUF> SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); showTextRight(cs, font, sdf.format(signDate.getTime()), w, h - 80, fontSize); } private static void showTextRight(PDPageContentStream cs, PDFont font, String text, float w, float y, float fontSize) throws IOException { cs.beginText(); float xoffset = w - font.getStringWidth(text) / 1000 * fontSize - 15; cs.newLineAtOffset(xoffset, y); cs.setNonStrokingColor(Color.black); cs.showText(text); cs.endText(); } // Find an existing signature (assumed to be empty). You will usually not need // this. private PDSignature findExistingSignature(PDAcroForm acroForm, String sigFieldName) { PDSignature signature = null; PDSignatureField signatureField; if (acroForm != null) { signatureField = (PDSignatureField) acroForm.getField(sigFieldName); if (signatureField != null) { // retrieve signature dictionary signature = signatureField.getSignature(); if (signature == null) { signature = new PDSignature(); // after solving PDFBOX-3524 // signatureField.setValue(signature) // until then: signatureField.getCOSObject().setItem(COSName.V, signature); } else { throw new IllegalStateException("The signature field " + sigFieldName + " is already signed."); } } } return signature; } }
6164_1
package com.example.androidapp.fragments; import java.util.ArrayList; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.InflateException; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.example.androidapp.R; import com.example.androidapp.pojos.OfferPojo; import com.example.androidapp.pojos.ShopPojo; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.Circle; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; public class GpsFragment extends BaseFragment implements LocationListener { private GoogleMap map; private LocationManager locationManager; private SupportMapFragment mapFragment; private Marker myLocation; private static View view; private boolean firstLaunch = false; private Circle radius; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (view != null) { ViewGroup parent = (ViewGroup) view.getParent(); if (parent != null) parent.removeView(view); } try { view = inflater.inflate(R.layout.fragment_gps, container, false); } catch (InflateException e) { /* map is already there, just return view as it is */ } return view;// inflater.inflate(R.layout.fragment_gps, container, // false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mapFragment = (SupportMapFragment) PARENT_ACTIVITY.getSupportFragmentManager().findFragmentById(R.id.map); map = mapFragment.getMap(); // Φόρτωση χάρτη που δείχνει δρόμους map.setMapType(GoogleMap.MAP_TYPE_NORMAL); locationManager = (LocationManager) PARENT_ACTIVITY.getSystemService(getApplicationContext().LOCATION_SERVICE); // Τελευταία τοποθεσία απο το GPS αν υπάρχει // Location location = // locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); // Τελευταία τοποθεσία απο το NETWORK αν υπάρχει // Location location2 = // locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); // GPS is ON? boolean enabledGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); // NETWORK PROVIDER is ON? boolean enabledNetwork = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); if (!enabledGPS && !enabledNetwork) { Toast.makeText(getApplicationContext(), "Ανοίξτε τις ρυθμίσεις και ενεργοποιήστε κάποιον provider", Toast.LENGTH_LONG).show(); } if (firstLaunch == false) { map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(39.465401, 22.804357), 6)); firstLaunch = true; } } @Override public void onResume() { boolean enabledGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); // NETWORK PROVIDER is ON? boolean enabledNetwork = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); if (enabledGPS) { if (PARENT_ACTIVITY.currentLocation == null) locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 500, this); } if (enabledNetwork) { if (PARENT_ACTIVITY.currentLocation == null) locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 500, this); } super.onResume(); } private boolean onlyOneTime = true; @Override public void onLocationChanged(Location location) { PARENT_ACTIVITY.currentLocation = location; if (radius != null) { radius.remove(); } if (myLocation != null) { myLocation.remove(); } else { new LoadShops().execute(); } myLocation = map.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title("Βρίσκεστε εδώ")); CircleOptions optionRadius = new CircleOptions(); optionRadius.radius(200); optionRadius.strokeWidth(2); optionRadius.fillColor(0x3396AA39); optionRadius.strokeColor(0xDD96AA39); optionRadius.center(new LatLng(location.getLatitude(), location.getLongitude())); radius = map.addCircle(optionRadius); if (onlyOneTime) { map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 15)); onlyOneTime = false; } } private class LoadShops extends AsyncTask<String, Void, ArrayList<ShopPojo>> { @Override protected void onPreExecute() { showProgressDialog("Downloading near Shops..."); } @Override protected ArrayList<ShopPojo> doInBackground(String... params) { ArrayList<ShopPojo> items = new ArrayList<ShopPojo>(); for (int i = 0; i < 45; i++) { ShopPojo item = new ShopPojo(); item.setName("Shop " + i); item.setStreet("King Street " + i); item.setZipCode("57001"); item.setPhone("6999999999"); item.setRegion("Serres"); item.setLatitude(40.576454 +i); item.setLongitude(22.994972 + i); for (int k = 0; k < i; k++) { item.addOffer(new OfferPojo("offer " + k, "-0." + k)); } items.add(item); } try { Thread.sleep(2000); } catch (InterruptedException e) { Thread.interrupted(); } return items; } @Override protected void onPostExecute(ArrayList<ShopPojo> result) { dismissProgressDialog(); PARENT_ACTIVITY.shops = result; for (int i = 0; i < result.size(); i++) { map.addMarker(new MarkerOptions().position(new LatLng(result.get(i).getLatitude(), result.get(i).getLongitude())).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)).title(result.get(i).getName())); } } } @Override public void onDestroyView() { locationManager.removeUpdates(this); super.onDestroyView(); } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override public void display() { // TODO Auto-generated method stub Log.e("","GPSfragment"); super.display(); } }
teamTL2/offersView.User02
AndroidApp/src/com/example/androidapp/fragments/GpsFragment.java
2,065
// Φόρτωση χάρτη που δείχνει δρόμους
line_comment
el
package com.example.androidapp.fragments; import java.util.ArrayList; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.InflateException; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.example.androidapp.R; import com.example.androidapp.pojos.OfferPojo; import com.example.androidapp.pojos.ShopPojo; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.Circle; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; public class GpsFragment extends BaseFragment implements LocationListener { private GoogleMap map; private LocationManager locationManager; private SupportMapFragment mapFragment; private Marker myLocation; private static View view; private boolean firstLaunch = false; private Circle radius; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (view != null) { ViewGroup parent = (ViewGroup) view.getParent(); if (parent != null) parent.removeView(view); } try { view = inflater.inflate(R.layout.fragment_gps, container, false); } catch (InflateException e) { /* map is already there, just return view as it is */ } return view;// inflater.inflate(R.layout.fragment_gps, container, // false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mapFragment = (SupportMapFragment) PARENT_ACTIVITY.getSupportFragmentManager().findFragmentById(R.id.map); map = mapFragment.getMap(); // Φόρτωση χάρτη<SUF> map.setMapType(GoogleMap.MAP_TYPE_NORMAL); locationManager = (LocationManager) PARENT_ACTIVITY.getSystemService(getApplicationContext().LOCATION_SERVICE); // Τελευταία τοποθεσία απο το GPS αν υπάρχει // Location location = // locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); // Τελευταία τοποθεσία απο το NETWORK αν υπάρχει // Location location2 = // locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); // GPS is ON? boolean enabledGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); // NETWORK PROVIDER is ON? boolean enabledNetwork = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); if (!enabledGPS && !enabledNetwork) { Toast.makeText(getApplicationContext(), "Ανοίξτε τις ρυθμίσεις και ενεργοποιήστε κάποιον provider", Toast.LENGTH_LONG).show(); } if (firstLaunch == false) { map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(39.465401, 22.804357), 6)); firstLaunch = true; } } @Override public void onResume() { boolean enabledGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); // NETWORK PROVIDER is ON? boolean enabledNetwork = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); if (enabledGPS) { if (PARENT_ACTIVITY.currentLocation == null) locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 500, this); } if (enabledNetwork) { if (PARENT_ACTIVITY.currentLocation == null) locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 500, this); } super.onResume(); } private boolean onlyOneTime = true; @Override public void onLocationChanged(Location location) { PARENT_ACTIVITY.currentLocation = location; if (radius != null) { radius.remove(); } if (myLocation != null) { myLocation.remove(); } else { new LoadShops().execute(); } myLocation = map.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title("Βρίσκεστε εδώ")); CircleOptions optionRadius = new CircleOptions(); optionRadius.radius(200); optionRadius.strokeWidth(2); optionRadius.fillColor(0x3396AA39); optionRadius.strokeColor(0xDD96AA39); optionRadius.center(new LatLng(location.getLatitude(), location.getLongitude())); radius = map.addCircle(optionRadius); if (onlyOneTime) { map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 15)); onlyOneTime = false; } } private class LoadShops extends AsyncTask<String, Void, ArrayList<ShopPojo>> { @Override protected void onPreExecute() { showProgressDialog("Downloading near Shops..."); } @Override protected ArrayList<ShopPojo> doInBackground(String... params) { ArrayList<ShopPojo> items = new ArrayList<ShopPojo>(); for (int i = 0; i < 45; i++) { ShopPojo item = new ShopPojo(); item.setName("Shop " + i); item.setStreet("King Street " + i); item.setZipCode("57001"); item.setPhone("6999999999"); item.setRegion("Serres"); item.setLatitude(40.576454 +i); item.setLongitude(22.994972 + i); for (int k = 0; k < i; k++) { item.addOffer(new OfferPojo("offer " + k, "-0." + k)); } items.add(item); } try { Thread.sleep(2000); } catch (InterruptedException e) { Thread.interrupted(); } return items; } @Override protected void onPostExecute(ArrayList<ShopPojo> result) { dismissProgressDialog(); PARENT_ACTIVITY.shops = result; for (int i = 0; i < result.size(); i++) { map.addMarker(new MarkerOptions().position(new LatLng(result.get(i).getLatitude(), result.get(i).getLongitude())).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)).title(result.get(i).getName())); } } } @Override public void onDestroyView() { locationManager.removeUpdates(this); super.onDestroyView(); } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override public void display() { // TODO Auto-generated method stub Log.e("","GPSfragment"); super.display(); } }
5128_4
package makisp.gohome; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ItemsActivity extends AppCompatActivity { public DbCredentials myDb = new DbCredentials(this); public ListView listameantikimena; public ArrayAdapter<String> adapter; public ArrayList<String>arrayList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_items); //Μεταβλητή για να μάθω πόσες θέσεις έχει ο πίνακας int i= 0; String [] items = new String[10]; // Δημιουργία οπζεκτ για να ελέγχω την λίστα listameantikimena = (ListView) findViewById(R.id.lista); // λίστα List<Inventory> invetories = myDb.getAllItems(); for(Inventory invetory : invetories){ // ευρεση του χριστη Log.i("Inventory: ", String.valueOf(invetory.getActiveUser())); Log.i("Active: ", String.valueOf(LoginActivity.activeUser)); if(invetory.getActiveUser().equals(LoginActivity.activeUser)){ items[i] = invetory.getItem(); i++; } } // Καινούριο στρινκγ String [] newItems = new String[i]; int kapa; // Μεταφορά των στοιχειών του πίνακα items στον πίνακα newItems for(kapa=0;kapa<i;kapa++){ newItems[kapa] = items[kapa]; } // addapter για την εμφανιση στην λιστα adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, newItems); listameantikimena.setAdapter(adapter); } }
teicm-project/go-home
app/src/main/java/makisp/gohome/ItemsActivity.java
638
// addapter για την εμφανιση στην λιστα
line_comment
el
package makisp.gohome; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ItemsActivity extends AppCompatActivity { public DbCredentials myDb = new DbCredentials(this); public ListView listameantikimena; public ArrayAdapter<String> adapter; public ArrayList<String>arrayList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_items); //Μεταβλητή για να μάθω πόσες θέσεις έχει ο πίνακας int i= 0; String [] items = new String[10]; // Δημιουργία οπζεκτ για να ελέγχω την λίστα listameantikimena = (ListView) findViewById(R.id.lista); // λίστα List<Inventory> invetories = myDb.getAllItems(); for(Inventory invetory : invetories){ // ευρεση του χριστη Log.i("Inventory: ", String.valueOf(invetory.getActiveUser())); Log.i("Active: ", String.valueOf(LoginActivity.activeUser)); if(invetory.getActiveUser().equals(LoginActivity.activeUser)){ items[i] = invetory.getItem(); i++; } } // Καινούριο στρινκγ String [] newItems = new String[i]; int kapa; // Μεταφορά των στοιχειών του πίνακα items στον πίνακα newItems for(kapa=0;kapa<i;kapa++){ newItems[kapa] = items[kapa]; } // addapter <SUF> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, newItems); listameantikimena.setAdapter(adapter); } }
11506_1
package clock.threads; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JLabel; /** * * @author tchaikalis */ public class ClockUpdater extends Thread { JLabel label; int period; /** * * @param label - ΤΟ Jlabel προς ανανέωση * @param period - Η περίοδος ανανέωσης σε millisecond */ public ClockUpdater(JLabel label, int period) { this.label = label; this.period = period; } @Override public void run() { while(true){ DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); Date now = new Date(); label.setText(dateFormat.format(now)); try { Thread.sleep(period); } catch (InterruptedException ex) { Logger.getLogger(ClockUpdater.class.getName()).log(Level.SEVERE, null, ex); } } } }
teohaik/EAP_OSS4_2020_Examples
src/clock/threads/ClockUpdater.java
291
/** * * @param label - ΤΟ Jlabel προς ανανέωση * @param period - Η περίοδος ανανέωσης σε millisecond */
block_comment
el
package clock.threads; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JLabel; /** * * @author tchaikalis */ public class ClockUpdater extends Thread { JLabel label; int period; /** * * @param label -<SUF>*/ public ClockUpdater(JLabel label, int period) { this.label = label; this.period = period; } @Override public void run() { while(true){ DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); Date now = new Date(); label.setText(dateFormat.format(now)); try { Thread.sleep(period); } catch (InterruptedException ex) { Logger.getLogger(ClockUpdater.class.getName()).log(Level.SEVERE, null, ex); } } } }
16756_6
package hashCode18; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Scanner; import java.util.StringTokenizer; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; /** * * @author teohaik */ public class Main { static ArrayList<Ride> rides = new ArrayList(); static final ArrayList<Vehicle> vehicles = new ArrayList(); public static void main(String[] args) throws FileNotFoundException { //String f1 = "a_example"; String f1 = "b_should_be_easy"; //String f1 = "c_no_hurry"; //String f1 = "d_metropolis"; //String f1 = "e_high_bonus"; FileReader fr = new FileReader(new File("files\\"+f1+".in")); Scanner s = new Scanner(fr); StringTokenizer firstLineTokens = new StringTokenizer(s.nextLine()); int rows = Integer.parseInt(firstLineTokens.nextToken()); int cols = Integer.parseInt(firstLineTokens.nextToken()); int VEHICLES = Integer.parseInt(firstLineTokens.nextToken()); int RIDES = Integer.parseInt(firstLineTokens.nextToken()); int BONUS = Integer.parseInt(firstLineTokens.nextToken()); int STEPS = Integer.parseInt(firstLineTokens.nextToken()); System.out.println(rows+ " "+cols+" "+VEHICLES+" "+RIDES+ " "+BONUS+" "+STEPS); for(int v=0; v<VEHICLES; v++){ vehicles.add(new Vehicle(v)); } readFile(RIDES, s); Collections.sort(rides, new RideEarliest()); rides.stream() .sorted( Comparator.comparing((Ride r) -> r.earliestStart) ); for(Ride ride : rides){ System.out.println(ride); } int currentRide = 0; for(int step=0; step < STEPS; step ++){ while(getFreeVehicle() != null && currentRide < RIDES ) { System.out.println("Assining ride to vehicle at steps "+step); Ride r = rides.get(currentRide); Vehicle v = getNextFreeNearestVehicle(r); currentRide++; v.assignRide(r); } for(Vehicle v: vehicles){ v.move(step); } } print(f1); } static Vehicle getNextFreeVehicle(Ride r){ try{ Vehicle get = vehicles.stream().filter(v -> v.assignedRide == null) .min((v1, v2)-> Integer.compare(v1.position.getDistanceFrom(r.start), v2.position.getDistanceFrom(r.start))) .get(); return get; } catch (java.util.NoSuchElementException ex) { return null; } } static Vehicle getNextFreeNearestVehicle(Ride r){ try{ Vehicle get = vehicles.stream().filter(v -> v.assignedRide == null) .min((v1, v2)-> Integer.compare(v1.position.getDistanceFrom(r.start), v2.position.getDistanceFrom(r.start))) .get(); return get; } catch (java.util.NoSuchElementException ex) { return null; } } static Vehicle getFreeVehicle(){ try{ Vehicle get = vehicles.stream().filter(v -> v.assignedRide == null).findAny().get(); return get; } catch (java.util.NoSuchElementException ex) { return null; } } static class RideEarliest implements Comparator<Ride> { @Override public int compare(Ride o1, Ride o2) { if(o1.earliestStart < o2.earliestStart){ return -1; } return 1; } } private static void print(String f1) throws UnsupportedOperationException { StringBuilder sb = new StringBuilder(); for(Vehicle v : vehicles){ sb.append(v.rides.size()).append(" "); for(Ride r : v.rides){ sb.append(r.code).append(" "); } sb.append("\n"); } Path filePath = Paths.get("files\\"+f1+".out"); File reportRouteFile = filePath.toFile(); //τεχνική try with resources (Java 8) η οποία κλείνει αυτόματα //τα resources μόλις τελειώσει η μέθοδος try (BufferedWriter writer = new BufferedWriter(new FileWriter(reportRouteFile))){ writer.write(sb.toString()); System.out.println("Δημιουργήθηκε το αρχείο καταγραφής "); } catch (UnsupportedOperationException uoe) { System.err.println("Cannot write to file, exiting..."); throw uoe; } catch (IOException ex) { System.err.println(ex.getMessage()); } } private static void readFile(int RIDES, Scanner s) throws NumberFormatException { for(int i=0; i<RIDES; i++){ StringTokenizer lineTokens = new StringTokenizer(s.nextLine()); int rowStart = Integer.parseInt(lineTokens.nextToken()); int colStart = Integer.parseInt(lineTokens.nextToken()); int rowEnd = Integer.parseInt(lineTokens.nextToken()); int colEnd = Integer.parseInt(lineTokens.nextToken()); int earliestStart = Integer.parseInt(lineTokens.nextToken()); int latestFinish = Integer.parseInt(lineTokens.nextToken()); Ride r = new Ride(i, rowStart, rowEnd, colStart, colEnd, earliestStart, latestFinish); rides.add(r); } s.close(); } }
teohaik/hashcode18
src/hashCode18/Main.java
1,488
//τα resources μόλις τελειώσει η μέθοδος
line_comment
el
package hashCode18; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Scanner; import java.util.StringTokenizer; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; /** * * @author teohaik */ public class Main { static ArrayList<Ride> rides = new ArrayList(); static final ArrayList<Vehicle> vehicles = new ArrayList(); public static void main(String[] args) throws FileNotFoundException { //String f1 = "a_example"; String f1 = "b_should_be_easy"; //String f1 = "c_no_hurry"; //String f1 = "d_metropolis"; //String f1 = "e_high_bonus"; FileReader fr = new FileReader(new File("files\\"+f1+".in")); Scanner s = new Scanner(fr); StringTokenizer firstLineTokens = new StringTokenizer(s.nextLine()); int rows = Integer.parseInt(firstLineTokens.nextToken()); int cols = Integer.parseInt(firstLineTokens.nextToken()); int VEHICLES = Integer.parseInt(firstLineTokens.nextToken()); int RIDES = Integer.parseInt(firstLineTokens.nextToken()); int BONUS = Integer.parseInt(firstLineTokens.nextToken()); int STEPS = Integer.parseInt(firstLineTokens.nextToken()); System.out.println(rows+ " "+cols+" "+VEHICLES+" "+RIDES+ " "+BONUS+" "+STEPS); for(int v=0; v<VEHICLES; v++){ vehicles.add(new Vehicle(v)); } readFile(RIDES, s); Collections.sort(rides, new RideEarliest()); rides.stream() .sorted( Comparator.comparing((Ride r) -> r.earliestStart) ); for(Ride ride : rides){ System.out.println(ride); } int currentRide = 0; for(int step=0; step < STEPS; step ++){ while(getFreeVehicle() != null && currentRide < RIDES ) { System.out.println("Assining ride to vehicle at steps "+step); Ride r = rides.get(currentRide); Vehicle v = getNextFreeNearestVehicle(r); currentRide++; v.assignRide(r); } for(Vehicle v: vehicles){ v.move(step); } } print(f1); } static Vehicle getNextFreeVehicle(Ride r){ try{ Vehicle get = vehicles.stream().filter(v -> v.assignedRide == null) .min((v1, v2)-> Integer.compare(v1.position.getDistanceFrom(r.start), v2.position.getDistanceFrom(r.start))) .get(); return get; } catch (java.util.NoSuchElementException ex) { return null; } } static Vehicle getNextFreeNearestVehicle(Ride r){ try{ Vehicle get = vehicles.stream().filter(v -> v.assignedRide == null) .min((v1, v2)-> Integer.compare(v1.position.getDistanceFrom(r.start), v2.position.getDistanceFrom(r.start))) .get(); return get; } catch (java.util.NoSuchElementException ex) { return null; } } static Vehicle getFreeVehicle(){ try{ Vehicle get = vehicles.stream().filter(v -> v.assignedRide == null).findAny().get(); return get; } catch (java.util.NoSuchElementException ex) { return null; } } static class RideEarliest implements Comparator<Ride> { @Override public int compare(Ride o1, Ride o2) { if(o1.earliestStart < o2.earliestStart){ return -1; } return 1; } } private static void print(String f1) throws UnsupportedOperationException { StringBuilder sb = new StringBuilder(); for(Vehicle v : vehicles){ sb.append(v.rides.size()).append(" "); for(Ride r : v.rides){ sb.append(r.code).append(" "); } sb.append("\n"); } Path filePath = Paths.get("files\\"+f1+".out"); File reportRouteFile = filePath.toFile(); //τεχνική try with resources (Java 8) η οποία κλείνει αυτόματα //τα resources<SUF> try (BufferedWriter writer = new BufferedWriter(new FileWriter(reportRouteFile))){ writer.write(sb.toString()); System.out.println("Δημιουργήθηκε το αρχείο καταγραφής "); } catch (UnsupportedOperationException uoe) { System.err.println("Cannot write to file, exiting..."); throw uoe; } catch (IOException ex) { System.err.println(ex.getMessage()); } } private static void readFile(int RIDES, Scanner s) throws NumberFormatException { for(int i=0; i<RIDES; i++){ StringTokenizer lineTokens = new StringTokenizer(s.nextLine()); int rowStart = Integer.parseInt(lineTokens.nextToken()); int colStart = Integer.parseInt(lineTokens.nextToken()); int rowEnd = Integer.parseInt(lineTokens.nextToken()); int colEnd = Integer.parseInt(lineTokens.nextToken()); int earliestStart = Integer.parseInt(lineTokens.nextToken()); int latestFinish = Integer.parseInt(lineTokens.nextToken()); Ride r = new Ride(i, rowStart, rowEnd, colStart, colEnd, earliestStart, latestFinish); rides.add(r); } s.close(); } }
3425_1
package com.example.calculator2; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.TextView; public class MainActivity extends AppCompatActivity { public class New_Class { } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Ψάχνει το αντικείμενο btnCalc Button btnCalc = findViewById(R.id.btnCalc); //Του ορίζει όταν γίνει κλικ: btnCalc.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Να εκτελεί την συνάρτηση onCalculateClick onCalculateClick(); } private void onCalculateClick() { EditText etNumber1 = findViewById(R.id.etNumber1); double number1; try{ number1 = Double.parseDouble(etNumber1.getText().toString()); }catch (Exception e){ number1 = 0.0; } EditText etNumber2 = findViewById(R.id.etNumber2); double number2; try{ number2 = Double.parseDouble(etNumber2.getText().toString()); }catch (Exception e){ number2 = 0.0; } RadioGroup rgOperations = findViewById(R.id.rgOperations); TextView tvResult = findViewById(R.id.tvResult); int checkedRadioButtonId = rgOperations.getCheckedRadioButtonId(); if (checkedRadioButtonId == R.id.rbPlus) { tvResult.setText(String.valueOf(number1 + number2)); } else if (checkedRadioButtonId == R.id.rbMinus) { tvResult.setText(String.valueOf(number1 - number2)); } else if (checkedRadioButtonId == R.id.rbMulti) { tvResult.setText(String.valueOf(number1 * number2)); } else if (checkedRadioButtonId == R.id.rbDiv) { if (number2 != 0.0) tvResult.setText(String.valueOf(number1 / number2)); else tvResult.setText("Can't Divide With 0"); } else { tvResult.setText("Operation Not Selected"); } } });}}
texnologia-logismikou2023/MyApplication
app/src/main/java/com/example/calculator2/MainActivity.java
588
//Του ορίζει όταν γίνει κλικ:
line_comment
el
package com.example.calculator2; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.TextView; public class MainActivity extends AppCompatActivity { public class New_Class { } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Ψάχνει το αντικείμενο btnCalc Button btnCalc = findViewById(R.id.btnCalc); //Του ορίζει<SUF> btnCalc.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Να εκτελεί την συνάρτηση onCalculateClick onCalculateClick(); } private void onCalculateClick() { EditText etNumber1 = findViewById(R.id.etNumber1); double number1; try{ number1 = Double.parseDouble(etNumber1.getText().toString()); }catch (Exception e){ number1 = 0.0; } EditText etNumber2 = findViewById(R.id.etNumber2); double number2; try{ number2 = Double.parseDouble(etNumber2.getText().toString()); }catch (Exception e){ number2 = 0.0; } RadioGroup rgOperations = findViewById(R.id.rgOperations); TextView tvResult = findViewById(R.id.tvResult); int checkedRadioButtonId = rgOperations.getCheckedRadioButtonId(); if (checkedRadioButtonId == R.id.rbPlus) { tvResult.setText(String.valueOf(number1 + number2)); } else if (checkedRadioButtonId == R.id.rbMinus) { tvResult.setText(String.valueOf(number1 - number2)); } else if (checkedRadioButtonId == R.id.rbMulti) { tvResult.setText(String.valueOf(number1 * number2)); } else if (checkedRadioButtonId == R.id.rbDiv) { if (number2 != 0.0) tvResult.setText(String.valueOf(number1 / number2)); else tvResult.setText("Can't Divide With 0"); } else { tvResult.setText("Operation Not Selected"); } } });}}