file_id
stringlengths
5
9
content
stringlengths
147
30.2k
repo
stringlengths
8
57
path
stringlengths
8
116
token_length
int64
57
7.97k
original_comment
stringlengths
14
5.13k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
56
30.2k
8172_0
public class Ex3 { public static void main(String[] args) { // Tak też myślałem if(3 < 5 * 2.0) System.out .print ("Hello"); System.out .print (" PPJ") ; } }
Franek-Antoniak/uni-pjatk
PPJ/23.10.2022/uni/Ex3.java
71
// Tak też myślałem
line_comment
pl
public class Ex3 { public static void main(String[] args) { // Tak też <SUF> if(3 < 5 * 2.0) System.out .print ("Hello"); System.out .print (" PPJ") ; } }
6332_0
public class NiceWordsPrinter { public static void main(String[] args) { String[] niceWords = { //list bardzo ladnych slowek "Kind", "Generous", "Friendly", "Caring", "Lovely", "Positive", "Compassionate", "Polite", "Sweet", "Gentle" }; System.out.println("Some Nice Words:"); for (String word : niceWords) { System.out.println(word); } } }
Free-Rat/put_io_lab
04-git/Program.java
154
//list bardzo ladnych slowek
line_comment
pl
public class NiceWordsPrinter { public static void main(String[] args) { String[] niceWords = { //list bardzo <SUF> "Kind", "Generous", "Friendly", "Caring", "Lovely", "Positive", "Compassionate", "Polite", "Sweet", "Gentle" }; System.out.println("Some Nice Words:"); for (String word : niceWords) { System.out.println(word); } } }
3381_4
import java.util.logging.Logger; public class SystemInterface { private static final Logger logger = Logger.getLogger(SystemInterface.class.getName()); private Wniosek aktualnyWniosek; private Uzytkownik zalogowanyUzytkownik; public SystemInterface() { this.aktualnyWniosek = null; this.zalogowanyUzytkownik = null; logger.info("SystemInterface został zainicjalizowany."); } /** * Metoda logowanie() pozwala na logowanie użytkownika do systemu. * Sprawdza, czy dane logowania są poprawne, a następnie ustanawia sesję użytkownika. * * @param uzytkownik obiekt Uzytkownik, który próbuje się zalogować */ public void logowanie(Uzytkownik uzytkownik) { if (uzytkownik == null) { throw new IllegalArgumentException("Uzytkownik nie może być null."); } if (uzytkownik.getNazwa().equals("prawidlowaNazwa") && uzytkownik.getHaslo().equals("prawidloweHaslo")) { this.zalogowanyUzytkownik = uzytkownik; System.out.println("Logowanie pomyślne dla użytkownika: " + uzytkownik.getNazwa()); } else { System.out.println("Błędne dane logowania."); } } /** * Metoda wylogowanie() kończy sesję użytkownika w systemie. * Czyści informacje o aktualnie zalogowanym użytkowniku, przywracając stan początkowy. */ public void wylogowanie() { if (zalogowanyUzytkownik != null) { System.out.println("Użytkownik " + zalogowanyUzytkownik.getNazwa() + " został wylogowany."); zalogowanyUzytkownik = null; } else { System.out.println("Brak zalogowanego użytkownika do wylogowania."); } } /** * Metoda nawigacja() zarządza nawigacją użytkownika po systemie. * Może to obejmować wyświetlanie różnych interfejsów lub menu w zależności od roli i stanu użytkownika. */ public void nawigacja() { // Editing might be necessary if (zalogowanyUzytkownik != null) { System.out.println("Witaj, " + zalogowanyUzytkownik.getNazwa()); // Wyświetlanie różnych opcji menu w zależności od roli użytkownika if (zalogowanyUzytkownik.getRola().equals("Administrator")) { System.out.println("1. Zarządzaj użytkownikami\n2. Sprawdź logi systemowe\n3. Wyloguj"); } else if (zalogowanyUzytkownik.getRola().equals("Użytkownik")) { System.out.println("1. Złóż nowy wniosek\n2. Sprawdź status wniosku\n3. Wyloguj"); } } else { System.out.println("Nie jesteś zalogowany."); } } /** * Metoda wyswietlanie() służy do prezentowania informacji użytkownikowi. * Wyświetla komunikaty, wyniki działań, błędy itp. na ekranie. */ public void wyswietlanie(String wiadomosc) { System.out.println(wiadomosc); } public Wniosek getAktualnyWniosek() { return aktualnyWniosek; } public void setAktualnyWniosek(Wniosek aktualnyWniosek) { this.aktualnyWniosek = aktualnyWniosek; } public Uzytkownik getZalogowanyUzytkownik() { return zalogowanyUzytkownik; } public void setZalogowanyUzytkownik(Uzytkownik zalogowanyUzytkownik) { this.zalogowanyUzytkownik = zalogowanyUzytkownik; } }
Fruktion/InzynieriaOprogramowania
SystemInterface.java
1,183
// Wyświetlanie różnych opcji menu w zależności od roli użytkownika
line_comment
pl
import java.util.logging.Logger; public class SystemInterface { private static final Logger logger = Logger.getLogger(SystemInterface.class.getName()); private Wniosek aktualnyWniosek; private Uzytkownik zalogowanyUzytkownik; public SystemInterface() { this.aktualnyWniosek = null; this.zalogowanyUzytkownik = null; logger.info("SystemInterface został zainicjalizowany."); } /** * Metoda logowanie() pozwala na logowanie użytkownika do systemu. * Sprawdza, czy dane logowania są poprawne, a następnie ustanawia sesję użytkownika. * * @param uzytkownik obiekt Uzytkownik, który próbuje się zalogować */ public void logowanie(Uzytkownik uzytkownik) { if (uzytkownik == null) { throw new IllegalArgumentException("Uzytkownik nie może być null."); } if (uzytkownik.getNazwa().equals("prawidlowaNazwa") && uzytkownik.getHaslo().equals("prawidloweHaslo")) { this.zalogowanyUzytkownik = uzytkownik; System.out.println("Logowanie pomyślne dla użytkownika: " + uzytkownik.getNazwa()); } else { System.out.println("Błędne dane logowania."); } } /** * Metoda wylogowanie() kończy sesję użytkownika w systemie. * Czyści informacje o aktualnie zalogowanym użytkowniku, przywracając stan początkowy. */ public void wylogowanie() { if (zalogowanyUzytkownik != null) { System.out.println("Użytkownik " + zalogowanyUzytkownik.getNazwa() + " został wylogowany."); zalogowanyUzytkownik = null; } else { System.out.println("Brak zalogowanego użytkownika do wylogowania."); } } /** * Metoda nawigacja() zarządza nawigacją użytkownika po systemie. * Może to obejmować wyświetlanie różnych interfejsów lub menu w zależności od roli i stanu użytkownika. */ public void nawigacja() { // Editing might be necessary if (zalogowanyUzytkownik != null) { System.out.println("Witaj, " + zalogowanyUzytkownik.getNazwa()); // Wyświetlanie różnych <SUF> if (zalogowanyUzytkownik.getRola().equals("Administrator")) { System.out.println("1. Zarządzaj użytkownikami\n2. Sprawdź logi systemowe\n3. Wyloguj"); } else if (zalogowanyUzytkownik.getRola().equals("Użytkownik")) { System.out.println("1. Złóż nowy wniosek\n2. Sprawdź status wniosku\n3. Wyloguj"); } } else { System.out.println("Nie jesteś zalogowany."); } } /** * Metoda wyswietlanie() służy do prezentowania informacji użytkownikowi. * Wyświetla komunikaty, wyniki działań, błędy itp. na ekranie. */ public void wyswietlanie(String wiadomosc) { System.out.println(wiadomosc); } public Wniosek getAktualnyWniosek() { return aktualnyWniosek; } public void setAktualnyWniosek(Wniosek aktualnyWniosek) { this.aktualnyWniosek = aktualnyWniosek; } public Uzytkownik getZalogowanyUzytkownik() { return zalogowanyUzytkownik; } public void setZalogowanyUzytkownik(Uzytkownik zalogowanyUzytkownik) { this.zalogowanyUzytkownik = zalogowanyUzytkownik; } }
3772_0
package atrem.modbus; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.SocketException; import java.nio.ByteBuffer; import atrem.modbus.frames.RequestFrame; public class Connection implements Runnable { private Socket socket; private InputStream inStream; private ControllerImpl controller; private OutputStream outStream; private String ipAddress; private int port; public Connection(String ipAddress, int port, ControllerImpl controller) throws IOException { this.ipAddress = ipAddress; this.port = port; this.controller = controller; makeConnection(); } public void makeConnection() throws IOException { socket = new Socket(ipAddress, port); inStream = socket.getInputStream(); outStream = socket.getOutputStream(); // new SoundPlayer("connect_sound.mp3").play(); } Connection(InputStream inStream, OutputStream outStream) { this.inStream = inStream; this.outStream = outStream; } public InputStream getInStream() { return inStream; } public OutputStream getOutStream() { return outStream; } public boolean checkConnection() { return socket.isConnected(); } public void send(byte[] frame) { try { outStream.write(frame); } catch (SocketException e) { } catch (IOException e) { e.printStackTrace(); } } public void closeConnection() { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } public void startReceiveFrames() { innerStartReceiveFrames(); } Thread innerStartReceiveFrames() { Thread thread = new Thread(this, "watek odbierajacy ramki"); thread.start(); return thread; } @Override public void run() { while (true) { byte[] header = new byte[RequestFrame.HEADER_SIZE]; readBytes(header, RequestFrame.HEADER_SIZE); ByteBuffer byteBuffer = ByteBuffer.wrap(header); byteBuffer.position(4); // int tid = byteBuffer.getShort(); // TODO nie wiem czy to dziala // int pid = byteBuffer.getShort(); int length = byteBuffer.getShort(); byte[] data = new byte[length]; readBytes(data, length); byte[] buff = new byte[RequestFrame.HEADER_SIZE + length]; System.arraycopy(header, 0, buff, 0, RequestFrame.HEADER_SIZE); System.arraycopy(data, 0, buff, RequestFrame.HEADER_SIZE, length); if (socket.isClosed()) return; controller.loadBytes(buff); } } private void readBytes(byte[] targetArray, int count) { for (int i = 0; i < count; i++) { try { targetArray[i] = (byte) inStream.read(); } catch (SocketException e) { } catch (IOException e) { // TODO przechwycenie wyjatku z sensem e.printStackTrace(); } } } public void setController(ControllerImpl controller) { this.controller = controller; } public String getIpAddress() { return ipAddress; } }
GRM-dev/Modbus
src/main/java/atrem/modbus/Connection.java
1,033
// int tid = byteBuffer.getShort(); // TODO nie wiem czy to dziala
line_comment
pl
package atrem.modbus; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.SocketException; import java.nio.ByteBuffer; import atrem.modbus.frames.RequestFrame; public class Connection implements Runnable { private Socket socket; private InputStream inStream; private ControllerImpl controller; private OutputStream outStream; private String ipAddress; private int port; public Connection(String ipAddress, int port, ControllerImpl controller) throws IOException { this.ipAddress = ipAddress; this.port = port; this.controller = controller; makeConnection(); } public void makeConnection() throws IOException { socket = new Socket(ipAddress, port); inStream = socket.getInputStream(); outStream = socket.getOutputStream(); // new SoundPlayer("connect_sound.mp3").play(); } Connection(InputStream inStream, OutputStream outStream) { this.inStream = inStream; this.outStream = outStream; } public InputStream getInStream() { return inStream; } public OutputStream getOutStream() { return outStream; } public boolean checkConnection() { return socket.isConnected(); } public void send(byte[] frame) { try { outStream.write(frame); } catch (SocketException e) { } catch (IOException e) { e.printStackTrace(); } } public void closeConnection() { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } public void startReceiveFrames() { innerStartReceiveFrames(); } Thread innerStartReceiveFrames() { Thread thread = new Thread(this, "watek odbierajacy ramki"); thread.start(); return thread; } @Override public void run() { while (true) { byte[] header = new byte[RequestFrame.HEADER_SIZE]; readBytes(header, RequestFrame.HEADER_SIZE); ByteBuffer byteBuffer = ByteBuffer.wrap(header); byteBuffer.position(4); // int tid <SUF> // int pid = byteBuffer.getShort(); int length = byteBuffer.getShort(); byte[] data = new byte[length]; readBytes(data, length); byte[] buff = new byte[RequestFrame.HEADER_SIZE + length]; System.arraycopy(header, 0, buff, 0, RequestFrame.HEADER_SIZE); System.arraycopy(data, 0, buff, RequestFrame.HEADER_SIZE, length); if (socket.isClosed()) return; controller.loadBytes(buff); } } private void readBytes(byte[] targetArray, int count) { for (int i = 0; i < count; i++) { try { targetArray[i] = (byte) inStream.read(); } catch (SocketException e) { } catch (IOException e) { // TODO przechwycenie wyjatku z sensem e.printStackTrace(); } } } public void setController(ControllerImpl controller) { this.controller = controller; } public String getIpAddress() { return ipAddress; } }
6379_4
/* * @title "Umbra" * @description "An editor for the Java bytecode and BML specifications" * @copyright "(c) ${date} University of Warsaw" * @license "All rights reserved. This program and the accompanying * materials are made available under the terms of the LGPL * licence see LICENCE.txt file" */ package umbra.instructions; /** * This is a class for a special Bytecode lines at the beginning * of the method, not to be edited by a user. * * @author Tomek Batkiewicz (tb209231@students.mimuw.edu.pl) * @version a-01 */ public class HeaderLineController extends BytecodeLineController { /** * This constructor remembers only the line text of the line which contains * the header information. TODO which header? * * @param a_line_text the string representation of the line text * @see BytecodeLineController#BytecodeLineController(String) */ public HeaderLineController(final String a_line_text) { super(a_line_text); } /** * TODO. * @return TODO */ public final boolean correct() { //nie za bardzo mozna ustalic zaleznosci //zbior wyrazow przed innym niektore opcjonalne return true; } /** * The method index of the header is equal to * the previous line's one increased by one. * TODO * * @param an_index TODO */ public final void setIndex(final int an_index) { super.setIndex(an_index + 1); } }
GaloisInc/Mobius
src/mobius.bml/Umbra/branches/ALX-DEVEL/source/umbra/instructions/HeaderLineController.java
450
//nie za bardzo mozna ustalic zaleznosci
line_comment
pl
/* * @title "Umbra" * @description "An editor for the Java bytecode and BML specifications" * @copyright "(c) ${date} University of Warsaw" * @license "All rights reserved. This program and the accompanying * materials are made available under the terms of the LGPL * licence see LICENCE.txt file" */ package umbra.instructions; /** * This is a class for a special Bytecode lines at the beginning * of the method, not to be edited by a user. * * @author Tomek Batkiewicz (tb209231@students.mimuw.edu.pl) * @version a-01 */ public class HeaderLineController extends BytecodeLineController { /** * This constructor remembers only the line text of the line which contains * the header information. TODO which header? * * @param a_line_text the string representation of the line text * @see BytecodeLineController#BytecodeLineController(String) */ public HeaderLineController(final String a_line_text) { super(a_line_text); } /** * TODO. * @return TODO */ public final boolean correct() { //nie za <SUF> //zbior wyrazow przed innym niektore opcjonalne return true; } /** * The method index of the header is equal to * the previous line's one increased by one. * TODO * * @param an_index TODO */ public final void setIndex(final int an_index) { super.setIndex(an_index + 1); } }
3865_3
package com.humandevice.wrk.backend.others; import com.humandevice.wrk.backend.pojos.LatLngPojo; import org.json.JSONArray; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import java.io.IOException; /** * Created by Kuba on 13/02/2015. * Map Manager */ public class MapMgr { private static String url_front = "http://nominatim.openstreetmap.org/search?q="; private static String format = "json"; private static String email = null; // do kontaktu z nominatim jakby coś się zjebało, coooo? /** * @param params parametry * @return zwraca obiekt LatLngPojo ze współrzędnymi */ private static LatLngPojo getCoordinates(String params) { params = params.replace(" ", "+") + (email != null ? email : ""); JSONObject jso; try { jso = getJSON(params).getJSONObject(0); } catch (Exception e) { return new LatLngPojo("0", "0"); } return new LatLngPojo(jso.getString("lat"), jso.getString("lon")); } private static JSONArray getJSON(String params) throws IOException { Document doc = Jsoup.connect(url_front + params).ignoreContentType(true).get(); String docContent = doc.toString().split("<body>")[1].split("</body>")[0]; return docContent.equals("[]") ? null : new JSONArray(docContent); } /** * @param city miasto * @param spot klub * @return zwraca obiekt LatLngPojo ze współrzędnymi */ public static LatLngPojo getCoordinates(String city, String spot) { String params = spot + ", " + Normalizer.grbgDel(city) + "&format=" + format; LatLngPojo coordinates = getCoordinates(params); if (coordinates.isEmpty()) return getCityCoordinates(city); else return coordinates; } /** * @param city miasto * @return zwraca obiekt LatLngPojo ze współrzędnymi */ public static LatLngPojo getCityCoordinates(String city) { String params = Normalizer.grbgDel(city) + "&format=" + format; return getCoordinates(params); } }
GigsSquad/WorkerConcertFinder
src/main/java/com/humandevice/wrk/backend/others/MapMgr.java
685
/** * @param city miasto * @param spot klub * @return zwraca obiekt LatLngPojo ze współrzędnymi */
block_comment
pl
package com.humandevice.wrk.backend.others; import com.humandevice.wrk.backend.pojos.LatLngPojo; import org.json.JSONArray; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import java.io.IOException; /** * Created by Kuba on 13/02/2015. * Map Manager */ public class MapMgr { private static String url_front = "http://nominatim.openstreetmap.org/search?q="; private static String format = "json"; private static String email = null; // do kontaktu z nominatim jakby coś się zjebało, coooo? /** * @param params parametry * @return zwraca obiekt LatLngPojo ze współrzędnymi */ private static LatLngPojo getCoordinates(String params) { params = params.replace(" ", "+") + (email != null ? email : ""); JSONObject jso; try { jso = getJSON(params).getJSONObject(0); } catch (Exception e) { return new LatLngPojo("0", "0"); } return new LatLngPojo(jso.getString("lat"), jso.getString("lon")); } private static JSONArray getJSON(String params) throws IOException { Document doc = Jsoup.connect(url_front + params).ignoreContentType(true).get(); String docContent = doc.toString().split("<body>")[1].split("</body>")[0]; return docContent.equals("[]") ? null : new JSONArray(docContent); } /** * @param city miasto <SUF>*/ public static LatLngPojo getCoordinates(String city, String spot) { String params = spot + ", " + Normalizer.grbgDel(city) + "&format=" + format; LatLngPojo coordinates = getCoordinates(params); if (coordinates.isEmpty()) return getCityCoordinates(city); else return coordinates; } /** * @param city miasto * @return zwraca obiekt LatLngPojo ze współrzędnymi */ public static LatLngPojo getCityCoordinates(String city) { String params = Normalizer.grbgDel(city) + "&format=" + format; return getCoordinates(params); } }
8199_0
package pl.gitmanik.helpers; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; public class GitmanikDurability { private static final String DURABILITY = "Wytrzymałość: "; public static int GetDurability(ItemStack stack) { ItemMeta im = stack.getItemMeta(); List<String> lore = im.getLore(); AtomicInteger toret = new AtomicInteger(1); if (lore == null) lore = new ArrayList<>(); lore.forEach((a) -> { if (a.startsWith(DURABILITY)) { toret.set(Integer.parseInt(a.substring(a.indexOf(" ") + 1))); } }); return toret.get(); } public static void SetDurability(ItemStack stack, int newDurability) { ItemMeta im = stack.getItemMeta(); List<String> lore = im.getLore(); if (lore == null) lore = new ArrayList<>(); AtomicBoolean saved = new AtomicBoolean(false); for (int i = 0; i < lore.size(); i++) { if (lore.get(i).startsWith(DURABILITY)) { lore.set(i, DURABILITY + newDurability); saved.set(true); } }; if (!saved.get()) lore.add(DURABILITY + newDurability); im.setLore(lore); stack.setItemMeta(im); } public static boolean EditDurability(Player player, ItemStack hand, int i) { int dur = GetDurability(hand) + i; if (dur <= 0) { player.sendMessage(ChatColor.RED + "Twój przedmiot " + hand.getItemMeta().getDisplayName() + ChatColor.RED +" uległ zniszczeniu!"); //kurwa paweł to jest do poprawy, w sechand nie widac jaki przedmiot sie psuje, i trzeba kolor wstawić przedmiotu też w tym display name bo cale czertwone to dziwnie wygląda player.getInventory().removeItemAnySlot(hand); return false; } SetDurability(hand, dur); return true; } }
Gitmanik/GitmanikPlugin
src/main/java/pl/gitmanik/helpers/GitmanikDurability.java
777
//kurwa paweł to jest do poprawy, w sechand nie widac jaki przedmiot sie psuje, i trzeba kolor wstawić przedmiotu też w tym display name bo cale czertwone to dziwnie wygląda
line_comment
pl
package pl.gitmanik.helpers; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; public class GitmanikDurability { private static final String DURABILITY = "Wytrzymałość: "; public static int GetDurability(ItemStack stack) { ItemMeta im = stack.getItemMeta(); List<String> lore = im.getLore(); AtomicInteger toret = new AtomicInteger(1); if (lore == null) lore = new ArrayList<>(); lore.forEach((a) -> { if (a.startsWith(DURABILITY)) { toret.set(Integer.parseInt(a.substring(a.indexOf(" ") + 1))); } }); return toret.get(); } public static void SetDurability(ItemStack stack, int newDurability) { ItemMeta im = stack.getItemMeta(); List<String> lore = im.getLore(); if (lore == null) lore = new ArrayList<>(); AtomicBoolean saved = new AtomicBoolean(false); for (int i = 0; i < lore.size(); i++) { if (lore.get(i).startsWith(DURABILITY)) { lore.set(i, DURABILITY + newDurability); saved.set(true); } }; if (!saved.get()) lore.add(DURABILITY + newDurability); im.setLore(lore); stack.setItemMeta(im); } public static boolean EditDurability(Player player, ItemStack hand, int i) { int dur = GetDurability(hand) + i; if (dur <= 0) { player.sendMessage(ChatColor.RED + "Twój przedmiot " + hand.getItemMeta().getDisplayName() + ChatColor.RED +" uległ zniszczeniu!"); //kurwa paweł <SUF> player.getInventory().removeItemAnySlot(hand); return false; } SetDurability(hand, dur); return true; } }
4001_27
/** * Klasa węzła drzewa */ class TreeElement<Type extends Comparable<Type>> { final Type value; TreeElement<Type> leftLeaf; TreeElement<Type> rightLeaf; /** * Konstruktor nowego węzła * @param element wartość elementu w nowym węźle */ TreeElement(Type element) { value = element; leftLeaf = null; rightLeaf = null; } } /** * Klasa drzewa */ public class Tree<Type extends Comparable<Type>> { private TreeElement<Type> root; /** * Bazowy konstruktor nowego drzewa */ public Tree() { root = null; } /** * Funkcja sprawdzająca czy drzewo jest puste * @return true jeśli drzewo jest puste, false w przeciwnym wypadku */ public boolean isEmpty() { return root == null; } /** * Funkcja dodająca element drzewa * @param element dodawany element */ public void insert(Type element) { if(root == null) root = new TreeElement<Type>(element); else { TreeElement<Type> next = root; while(element.compareTo(next.value) != 0) { if(element.compareTo(next.value) < 0) { if(next.leftLeaf == null) { next.leftLeaf = new TreeElement<Type>(element); return; } else next = next.leftLeaf; } else if(element.compareTo(next.value) > 0) { if(next.rightLeaf == null) { next.rightLeaf = new TreeElement<Type>(element); return; } else next = next.rightLeaf; } } } } /** * Funkcja usuwająca węzeł zawierający dany element i obsługująca jego ewentualne poddrzewo * @param element wartość elementu do usunięcia */ public void delete(Type element){ TreeElement<Type> node = root; if(node.value.compareTo(element) == 0) { //Jeśli nie ma dzieci if (root.leftLeaf == null && root.rightLeaf == null) { root = null; } //Jeśli ma tylko jedno dziecko else if ((root.leftLeaf != null && root.rightLeaf == null)) { root = root.leftLeaf; } else if (root.leftLeaf == null && root.rightLeaf != null) { root = root.rightLeaf; } //Jeśli ma dwoje dzieci //Lewe dziecko nie ma prawego dziecka więc prawe dziecko przepinamy do lewego dziecka i zastępujemy nim węzeł else if (root.leftLeaf != null && root.leftLeaf.rightLeaf == null) { root.leftLeaf.rightLeaf = root.rightLeaf; root = root.leftLeaf; } //Prawe dziecko nie ma lewego dziecka więc lewe dziecko przepinamy do prawego dziecka i zastępujemy nim węzeł else if (root.rightLeaf != null && root.rightLeaf.leftLeaf == null) { root.rightLeaf.leftLeaf = root.leftLeaf; root = root.rightLeaf; } //Inne przypadki else { TreeElement<Type> temp = root.rightLeaf.leftLeaf; this.delete(root.rightLeaf.leftLeaf.value); temp.leftLeaf = root.leftLeaf; temp.rightLeaf = root.rightLeaf; root = temp; } return; } while (node.leftLeaf != null || node.rightLeaf != null) { if (node.leftLeaf != null && node.leftLeaf.value.compareTo(element) == 0) { //Jeśli nie ma dzieci if (node.leftLeaf.leftLeaf == null && node.leftLeaf.rightLeaf == null) { node.leftLeaf = null; } //Jeśli ma tylko jedno dziecko else if ((node.leftLeaf.leftLeaf != null && node.leftLeaf.rightLeaf == null)) { node.leftLeaf = node.leftLeaf.leftLeaf; } else if (node.leftLeaf.leftLeaf == null && node.leftLeaf.rightLeaf != null) { node.leftLeaf = node.leftLeaf.rightLeaf; } //Jeśli ma dwoje dzieci //Lewe dziecko nie ma prawego dziecka więc prawe dziecko przepinamy do lewego dziecka i zastępujemy nim węzeł else if (node.leftLeaf.leftLeaf != null && node.leftLeaf.leftLeaf.rightLeaf == null) { node.leftLeaf.leftLeaf.rightLeaf = node.leftLeaf.rightLeaf; node.leftLeaf = node.leftLeaf.leftLeaf; } //Prawe dziecko nie ma lewego dziecka więc lewe dziecko przepinamy do prawego dziecka i zastępujemy nim węzeł else if (node.leftLeaf.rightLeaf != null && node.leftLeaf.rightLeaf.leftLeaf == null) { node.leftLeaf.rightLeaf.leftLeaf = node.leftLeaf.leftLeaf; node.leftLeaf = node.leftLeaf.rightLeaf; } //Inne przypadki else { TreeElement<Type> temp = node.leftLeaf.rightLeaf.leftLeaf; this.delete(node.leftLeaf.rightLeaf.leftLeaf.value); temp.leftLeaf = node.leftLeaf.leftLeaf; temp.rightLeaf = node.leftLeaf.rightLeaf; node.leftLeaf = temp; } return; } else if (node.rightLeaf != null && node.rightLeaf.value.compareTo(element) == 0) { //Jeśli nie ma dzieci if (node.rightLeaf.leftLeaf == null && node.rightLeaf.rightLeaf == null) { node.rightLeaf = null; } //Jeśli ma tylko jedno dziecko else if ((node.rightLeaf.leftLeaf != null && node.rightLeaf.rightLeaf == null)) { node.rightLeaf = node.rightLeaf.leftLeaf; } else if (node.rightLeaf.leftLeaf == null && node.rightLeaf.rightLeaf != null) { node.rightLeaf = node.rightLeaf.rightLeaf; } //Jeśli ma dwoje dzieci //Lewe dziecko nie ma prawego dziecka więc prawe dziecko przepinamy do lewego dziecka i zastępujemy nim węzeł else if (node.rightLeaf.leftLeaf != null && node.rightLeaf.leftLeaf.rightLeaf == null) { node.rightLeaf.leftLeaf.rightLeaf = node.rightLeaf.rightLeaf; node.rightLeaf = node.rightLeaf.leftLeaf; } //Prawe dziecko nie ma lewego dziecka więc lewe dziecko przepinamy do prawego dziecka i zastępujemy nim węzeł else if (node.rightLeaf.rightLeaf != null && node.rightLeaf.rightLeaf.leftLeaf == null) { node.rightLeaf.rightLeaf.leftLeaf = node.rightLeaf.leftLeaf; node.rightLeaf = node.rightLeaf.rightLeaf; } //Inne przypadki else { TreeElement<Type> temp = node.rightLeaf.rightLeaf.leftLeaf; this.delete(node.rightLeaf.rightLeaf.leftLeaf.value); temp.leftLeaf = node.rightLeaf.leftLeaf; temp.rightLeaf = node.rightLeaf.rightLeaf; node.rightLeaf = temp; } return; } //Jeśli jest taka możliwość to przechodzimy do kolejnego węzła if(node.value.compareTo(element) == 1) { if (node.leftLeaf != null) { node = node.leftLeaf; } else { //System.out.println("Nie ma takiego elementu"); return; } } else { if (node.rightLeaf != null) { node = node.rightLeaf; } else { //System.out.println("Nie ma takiego elementu"); return; } } } } /** * Funkcja rekurencyjna obsługująca wyświetlanie drzewa * @param node obecnie wyświetlany węzeł * @param prefix prefix dodawany przy wyświetlaniu = poziom głębokości w drzewie */ private String printNode(TreeElement<Type> node, String prefix) { if(node == null) return "\n" + prefix + "#"; else { return "\n" + prefix + node.value + printNode(node.leftLeaf, prefix + "%") + printNode(node.rightLeaf, prefix + "%"); } } /** * Funkcja wyświetlająca drzewo - najpierw wyświetla węzeł, następnie jego lewe poddrzewo jeśli istnieje, a na końcu jego prawe poddrzewo jeśli istnieje * @return Ciąg znaków z kolejnymi węzłami po enterach */ public String draw() { return printNode(root, "") + "\nend"; } /** * Funkcja sprawdzająca czy podana wartość istnieje w drzewie * @param searched szukana wartość * @return true jeśli wartość istnieje, false w przeciwnym wypadku */ public boolean search(Type searched) { TreeElement<Type> node = root; while(node != null) { if(searched.compareTo(node.value) == 0) return true; else if(searched.compareTo(node.value) == -1) node = node.leftLeaf; else node = node.rightLeaf; } return false; } }
GoodFloor/Studia
pwr_sem2/Kurs Programowania/Lista7/Tree.java
2,869
/** * Funkcja sprawdzająca czy podana wartość istnieje w drzewie * @param searched szukana wartość * @return true jeśli wartość istnieje, false w przeciwnym wypadku */
block_comment
pl
/** * Klasa węzła drzewa */ class TreeElement<Type extends Comparable<Type>> { final Type value; TreeElement<Type> leftLeaf; TreeElement<Type> rightLeaf; /** * Konstruktor nowego węzła * @param element wartość elementu w nowym węźle */ TreeElement(Type element) { value = element; leftLeaf = null; rightLeaf = null; } } /** * Klasa drzewa */ public class Tree<Type extends Comparable<Type>> { private TreeElement<Type> root; /** * Bazowy konstruktor nowego drzewa */ public Tree() { root = null; } /** * Funkcja sprawdzająca czy drzewo jest puste * @return true jeśli drzewo jest puste, false w przeciwnym wypadku */ public boolean isEmpty() { return root == null; } /** * Funkcja dodająca element drzewa * @param element dodawany element */ public void insert(Type element) { if(root == null) root = new TreeElement<Type>(element); else { TreeElement<Type> next = root; while(element.compareTo(next.value) != 0) { if(element.compareTo(next.value) < 0) { if(next.leftLeaf == null) { next.leftLeaf = new TreeElement<Type>(element); return; } else next = next.leftLeaf; } else if(element.compareTo(next.value) > 0) { if(next.rightLeaf == null) { next.rightLeaf = new TreeElement<Type>(element); return; } else next = next.rightLeaf; } } } } /** * Funkcja usuwająca węzeł zawierający dany element i obsługująca jego ewentualne poddrzewo * @param element wartość elementu do usunięcia */ public void delete(Type element){ TreeElement<Type> node = root; if(node.value.compareTo(element) == 0) { //Jeśli nie ma dzieci if (root.leftLeaf == null && root.rightLeaf == null) { root = null; } //Jeśli ma tylko jedno dziecko else if ((root.leftLeaf != null && root.rightLeaf == null)) { root = root.leftLeaf; } else if (root.leftLeaf == null && root.rightLeaf != null) { root = root.rightLeaf; } //Jeśli ma dwoje dzieci //Lewe dziecko nie ma prawego dziecka więc prawe dziecko przepinamy do lewego dziecka i zastępujemy nim węzeł else if (root.leftLeaf != null && root.leftLeaf.rightLeaf == null) { root.leftLeaf.rightLeaf = root.rightLeaf; root = root.leftLeaf; } //Prawe dziecko nie ma lewego dziecka więc lewe dziecko przepinamy do prawego dziecka i zastępujemy nim węzeł else if (root.rightLeaf != null && root.rightLeaf.leftLeaf == null) { root.rightLeaf.leftLeaf = root.leftLeaf; root = root.rightLeaf; } //Inne przypadki else { TreeElement<Type> temp = root.rightLeaf.leftLeaf; this.delete(root.rightLeaf.leftLeaf.value); temp.leftLeaf = root.leftLeaf; temp.rightLeaf = root.rightLeaf; root = temp; } return; } while (node.leftLeaf != null || node.rightLeaf != null) { if (node.leftLeaf != null && node.leftLeaf.value.compareTo(element) == 0) { //Jeśli nie ma dzieci if (node.leftLeaf.leftLeaf == null && node.leftLeaf.rightLeaf == null) { node.leftLeaf = null; } //Jeśli ma tylko jedno dziecko else if ((node.leftLeaf.leftLeaf != null && node.leftLeaf.rightLeaf == null)) { node.leftLeaf = node.leftLeaf.leftLeaf; } else if (node.leftLeaf.leftLeaf == null && node.leftLeaf.rightLeaf != null) { node.leftLeaf = node.leftLeaf.rightLeaf; } //Jeśli ma dwoje dzieci //Lewe dziecko nie ma prawego dziecka więc prawe dziecko przepinamy do lewego dziecka i zastępujemy nim węzeł else if (node.leftLeaf.leftLeaf != null && node.leftLeaf.leftLeaf.rightLeaf == null) { node.leftLeaf.leftLeaf.rightLeaf = node.leftLeaf.rightLeaf; node.leftLeaf = node.leftLeaf.leftLeaf; } //Prawe dziecko nie ma lewego dziecka więc lewe dziecko przepinamy do prawego dziecka i zastępujemy nim węzeł else if (node.leftLeaf.rightLeaf != null && node.leftLeaf.rightLeaf.leftLeaf == null) { node.leftLeaf.rightLeaf.leftLeaf = node.leftLeaf.leftLeaf; node.leftLeaf = node.leftLeaf.rightLeaf; } //Inne przypadki else { TreeElement<Type> temp = node.leftLeaf.rightLeaf.leftLeaf; this.delete(node.leftLeaf.rightLeaf.leftLeaf.value); temp.leftLeaf = node.leftLeaf.leftLeaf; temp.rightLeaf = node.leftLeaf.rightLeaf; node.leftLeaf = temp; } return; } else if (node.rightLeaf != null && node.rightLeaf.value.compareTo(element) == 0) { //Jeśli nie ma dzieci if (node.rightLeaf.leftLeaf == null && node.rightLeaf.rightLeaf == null) { node.rightLeaf = null; } //Jeśli ma tylko jedno dziecko else if ((node.rightLeaf.leftLeaf != null && node.rightLeaf.rightLeaf == null)) { node.rightLeaf = node.rightLeaf.leftLeaf; } else if (node.rightLeaf.leftLeaf == null && node.rightLeaf.rightLeaf != null) { node.rightLeaf = node.rightLeaf.rightLeaf; } //Jeśli ma dwoje dzieci //Lewe dziecko nie ma prawego dziecka więc prawe dziecko przepinamy do lewego dziecka i zastępujemy nim węzeł else if (node.rightLeaf.leftLeaf != null && node.rightLeaf.leftLeaf.rightLeaf == null) { node.rightLeaf.leftLeaf.rightLeaf = node.rightLeaf.rightLeaf; node.rightLeaf = node.rightLeaf.leftLeaf; } //Prawe dziecko nie ma lewego dziecka więc lewe dziecko przepinamy do prawego dziecka i zastępujemy nim węzeł else if (node.rightLeaf.rightLeaf != null && node.rightLeaf.rightLeaf.leftLeaf == null) { node.rightLeaf.rightLeaf.leftLeaf = node.rightLeaf.leftLeaf; node.rightLeaf = node.rightLeaf.rightLeaf; } //Inne przypadki else { TreeElement<Type> temp = node.rightLeaf.rightLeaf.leftLeaf; this.delete(node.rightLeaf.rightLeaf.leftLeaf.value); temp.leftLeaf = node.rightLeaf.leftLeaf; temp.rightLeaf = node.rightLeaf.rightLeaf; node.rightLeaf = temp; } return; } //Jeśli jest taka możliwość to przechodzimy do kolejnego węzła if(node.value.compareTo(element) == 1) { if (node.leftLeaf != null) { node = node.leftLeaf; } else { //System.out.println("Nie ma takiego elementu"); return; } } else { if (node.rightLeaf != null) { node = node.rightLeaf; } else { //System.out.println("Nie ma takiego elementu"); return; } } } } /** * Funkcja rekurencyjna obsługująca wyświetlanie drzewa * @param node obecnie wyświetlany węzeł * @param prefix prefix dodawany przy wyświetlaniu = poziom głębokości w drzewie */ private String printNode(TreeElement<Type> node, String prefix) { if(node == null) return "\n" + prefix + "#"; else { return "\n" + prefix + node.value + printNode(node.leftLeaf, prefix + "%") + printNode(node.rightLeaf, prefix + "%"); } } /** * Funkcja wyświetlająca drzewo - najpierw wyświetla węzeł, następnie jego lewe poddrzewo jeśli istnieje, a na końcu jego prawe poddrzewo jeśli istnieje * @return Ciąg znaków z kolejnymi węzłami po enterach */ public String draw() { return printNode(root, "") + "\nend"; } /** * Funkcja sprawdzająca czy <SUF>*/ public boolean search(Type searched) { TreeElement<Type> node = root; while(node != null) { if(searched.compareTo(node.value) == 0) return true; else if(searched.compareTo(node.value) == -1) node = node.leftLeaf; else node = node.rightLeaf; } return false; } }
8303_2
package me.littlelenim.mythought.user.model; import me.littlelenim.mythought.thought.model.Comment; import me.littlelenim.mythought.thought.model.Thought; import org.hibernate.Hibernate; import javax.persistence.*; import java.util.ArrayList; import java.util.List; import java.util.Objects; @Entity @Table(name = "app_user") public class AppUser { @SequenceGenerator( name = "app_user_sequence", sequenceName = "app_user_sequence", allocationSize = 1 ) @GeneratedValue(generator = "app_user_sequence") @Id private Long id; @Column(name = "username", unique = true, nullable = false) private String username; @Column(name = "password") private String password; // tego nie chcesz zwracać, spraw, żeby nie było gettera do tego pola // hasła nie powinny być nigdy zwracane, co najwyżej mogą być nadpisane nowym hashem @OneToMany(mappedBy = "author") private List<Thought> thoughts = new ArrayList<>(); // nie trzeba inicjalizować listy w tym miejscu. @OneToMany(mappedBy = "author") private List<Comment> comments = new ArrayList<>(); @ManyToMany(mappedBy = "likedBy") private List<Thought> likedThoughts; //konstruktor, gettery i settery do zastąpienia adnotacjami Lomboka public AppUser() { } public AppUser(String username, String password) { this.username = username; this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public List<Thought> getThoughts() { return thoughts; } public void addThought(Thought thought) { this.thoughts.add(thought); thought.setAuthor(this); } public void removeThought(Thought thought) { this.thoughts.remove(thought); } public void addComment(Comment comment) { this.comments.add(comment); comment.setAuthor(this); } public void removeComment(Comment comment) { this.comments.remove(comment); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false; AppUser user = (AppUser) o; return Objects.equals(id, user.id); } @Override public int hashCode() { return 0; } }
GregChyla/my-thought-web-app
src/main/java/me/littlelenim/mythought/user/model/AppUser.java
791
// nie trzeba inicjalizować listy w tym miejscu.
line_comment
pl
package me.littlelenim.mythought.user.model; import me.littlelenim.mythought.thought.model.Comment; import me.littlelenim.mythought.thought.model.Thought; import org.hibernate.Hibernate; import javax.persistence.*; import java.util.ArrayList; import java.util.List; import java.util.Objects; @Entity @Table(name = "app_user") public class AppUser { @SequenceGenerator( name = "app_user_sequence", sequenceName = "app_user_sequence", allocationSize = 1 ) @GeneratedValue(generator = "app_user_sequence") @Id private Long id; @Column(name = "username", unique = true, nullable = false) private String username; @Column(name = "password") private String password; // tego nie chcesz zwracać, spraw, żeby nie było gettera do tego pola // hasła nie powinny być nigdy zwracane, co najwyżej mogą być nadpisane nowym hashem @OneToMany(mappedBy = "author") private List<Thought> thoughts = new ArrayList<>(); // nie trzeba <SUF> @OneToMany(mappedBy = "author") private List<Comment> comments = new ArrayList<>(); @ManyToMany(mappedBy = "likedBy") private List<Thought> likedThoughts; //konstruktor, gettery i settery do zastąpienia adnotacjami Lomboka public AppUser() { } public AppUser(String username, String password) { this.username = username; this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public List<Thought> getThoughts() { return thoughts; } public void addThought(Thought thought) { this.thoughts.add(thought); thought.setAuthor(this); } public void removeThought(Thought thought) { this.thoughts.remove(thought); } public void addComment(Comment comment) { this.comments.add(comment); comment.setAuthor(this); } public void removeComment(Comment comment) { this.comments.remove(comment); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false; AppUser user = (AppUser) o; return Objects.equals(id, user.id); } @Override public int hashCode() { return 0; } }
5104_0
package pl.GregsApp.SomeGames; import org.apache.commons.lang3.ArrayUtils; import java.util.Arrays; import java.util.Random; import java.util.Scanner; public class LottoSimulation { // Losowanie lotto, zakres od 1 do 49, podajemy 6 liczb i sprawdzamy czy trafilismy 3,4,5 a moze 6 public static void main(String[] args) { // 6 liczb z 1 do 49 // zgadnij liczby //3,4,5 lub 6 jest nagradzane int[] inputNumbersArray = new int[6]; int[] randomArray = new int[6]; int count = 0; int tempNumber = 0; Scanner scan = new Scanner(System.in); Random random = new Random(); System.out.println("Proszę podaj 6 liczb, w zakresie od 1 do 49, liczby nie mogą się powtarzać"); for(int i = 0; i < 6; i++) { while (!scan.hasNextInt()) { scan.next(); System.out.println("Błąd, wprowadź liczbę"); } tempNumber = scan.nextInt(); if(!ArrayUtils.contains(inputNumbersArray, tempNumber) && tempNumber >= 1 && tempNumber <= 49){ inputNumbersArray[i] = tempNumber; } else { System.out.println("Proszę o podanie różnych liczb w zakresie 1-49"); } } ////losowe liczby for(int i = 0; i < randomArray.length; i++){ randomArray[i] = random.nextInt(50)+1; } System.out.println("Liczby wylosowane przez maszyne"); Arrays.sort(randomArray); for(int randNumebrs : randomArray){ System.out.print(randNumebrs + " "); } System.out.println("\n\n"); System.out.println("Wprowadzone liczby: "); Arrays.sort(inputNumbersArray); for(int numbers : inputNumbersArray){ System.out.print(numbers + " "); } for(int i = 0; i < 6; i++) { if (ArrayUtils.contains(randomArray, inputNumbersArray[i])) { count++; } } numbAsnwers(count); } // mozna bylo switcha uzyc, bylo by czytelniej public static int numbAsnwers(int count){ if(count == 0){ System.out.println("niestety nie zgadłeś nic"); } else if(count == 1){ System.out.println("zgadłeś " + count + " liczbę, niestety to za mało"); } else if(count == 2){ System.out.println("zgadłeś " + count + " liczby, niestety to za mało"); } else if(count == 3){ System.out.println("zgadłeś" + count + " liczby, brawo! na 6, trafiłeś 3!,"); } else if (count == 4) { System.out.println("zgadłeś" + count + " liczby, brawo! na 6 trafiłeś aż 4!, nieźle!"); } else if(count == 5) { System.out.println("BRAWO!!, zgadłeś aż" + count + " liczb!, świetny wynik!"); } else if(count == 6){ System.out.println("WOW!! Trafiłeś szóstkę!!, WOW!!! BRAWAA, Rozjebałeś tą giereczke kolego!"); } return count; } }
GregsHuub/Simple-Games
src/pl/GregsApp/SomeGames/LottoSimulation.java
1,053
// Losowanie lotto, zakres od 1 do 49, podajemy 6 liczb i sprawdzamy czy trafilismy 3,4,5 a moze 6
line_comment
pl
package pl.GregsApp.SomeGames; import org.apache.commons.lang3.ArrayUtils; import java.util.Arrays; import java.util.Random; import java.util.Scanner; public class LottoSimulation { // Losowanie lotto, <SUF> public static void main(String[] args) { // 6 liczb z 1 do 49 // zgadnij liczby //3,4,5 lub 6 jest nagradzane int[] inputNumbersArray = new int[6]; int[] randomArray = new int[6]; int count = 0; int tempNumber = 0; Scanner scan = new Scanner(System.in); Random random = new Random(); System.out.println("Proszę podaj 6 liczb, w zakresie od 1 do 49, liczby nie mogą się powtarzać"); for(int i = 0; i < 6; i++) { while (!scan.hasNextInt()) { scan.next(); System.out.println("Błąd, wprowadź liczbę"); } tempNumber = scan.nextInt(); if(!ArrayUtils.contains(inputNumbersArray, tempNumber) && tempNumber >= 1 && tempNumber <= 49){ inputNumbersArray[i] = tempNumber; } else { System.out.println("Proszę o podanie różnych liczb w zakresie 1-49"); } } ////losowe liczby for(int i = 0; i < randomArray.length; i++){ randomArray[i] = random.nextInt(50)+1; } System.out.println("Liczby wylosowane przez maszyne"); Arrays.sort(randomArray); for(int randNumebrs : randomArray){ System.out.print(randNumebrs + " "); } System.out.println("\n\n"); System.out.println("Wprowadzone liczby: "); Arrays.sort(inputNumbersArray); for(int numbers : inputNumbersArray){ System.out.print(numbers + " "); } for(int i = 0; i < 6; i++) { if (ArrayUtils.contains(randomArray, inputNumbersArray[i])) { count++; } } numbAsnwers(count); } // mozna bylo switcha uzyc, bylo by czytelniej public static int numbAsnwers(int count){ if(count == 0){ System.out.println("niestety nie zgadłeś nic"); } else if(count == 1){ System.out.println("zgadłeś " + count + " liczbę, niestety to za mało"); } else if(count == 2){ System.out.println("zgadłeś " + count + " liczby, niestety to za mało"); } else if(count == 3){ System.out.println("zgadłeś" + count + " liczby, brawo! na 6, trafiłeś 3!,"); } else if (count == 4) { System.out.println("zgadłeś" + count + " liczby, brawo! na 6 trafiłeś aż 4!, nieźle!"); } else if(count == 5) { System.out.println("BRAWO!!, zgadłeś aż" + count + " liczb!, świetny wynik!"); } else if(count == 6){ System.out.println("WOW!! Trafiłeś szóstkę!!, WOW!!! BRAWAA, Rozjebałeś tą giereczke kolego!"); } return count; } }
3751_0
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String[] tab = new String[5]; BubbleSort bubbleSort = new BubbleSort() { @Override void bubbleString(String[] tab) { for(int i=0; i<tab.length; i++){ for(int j=0; j<tab.length-i-1; j++){ int compareStrings = tab[j].compareTo(tab[j+1]); if(compareStrings > 0){ String temp = tab[j]; tab[j] = tab[j+1]; tab[j+1] = temp; } } } } }; System.out.println("Podaj 5 lancuchow tekstu:"); for(int i=0; i< tab.length; i++){ tab[i] = sc.nextLine(); } bubbleSort.bubbleString(tab); System.out.println("Teksty po zamianie:"); for (String element : tab){ System.out.println(element); } System.out.println("Teksty po odwroconej zamianie"); bubbleSort.reverseString(tab); for(String element : tab){ System.out.println(element); } System.out.println("Teksty posortowane wedlug ostatnich indeksow:"); bubbleSort.lastSort(tab); for(String element:tab){ System.out.println(element); } } } abstract class BubbleSort{ abstract void bubbleString(String[] tab); void reverseString(String[] tab){ for(int i=0; i<tab.length; i++){ for(int j=0; j<tab.length-i-1; j++){ int wynikPorownania = tab[j].compareTo(tab[j+1]); if(wynikPorownania <= 0){ String temp = tab[j]; tab[j] = tab[j+1]; tab[j+1] = temp; } } } } void lastSort(String[] tab) { for (int i = 0; i < tab.length; i++) { for (int j = 0; j < tab.length - i - 1; j++) { int n = 1; int m = 1; int len = tab[j].length(); int len2 = tab[j + 1].length(); char lastFirst = tab[j].charAt(len - n); char lastSecond = tab[j + 1].charAt(len2 - m); if(lastFirst == lastSecond){ while (lastFirst == lastSecond && len - n >= 0 && len2 - m >= 0) { n++; m++; if (len - n >= 0) { lastFirst = tab[j].charAt(len - n); } if (len2 - m >= 0) { lastSecond = tab[j + 1].charAt(len2 - m); } } } if (lastFirst > lastSecond) { String temp = tab[j]; tab[j] = tab[j + 1]; tab[j + 1] = temp; } } } } }//To ostatnie nie wiem czy dobrze dziala
Grodelek/Java_Lab4sem
Lab3/Lab3_Zad6.java
913
//To ostatnie nie wiem czy dobrze dziala
line_comment
pl
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String[] tab = new String[5]; BubbleSort bubbleSort = new BubbleSort() { @Override void bubbleString(String[] tab) { for(int i=0; i<tab.length; i++){ for(int j=0; j<tab.length-i-1; j++){ int compareStrings = tab[j].compareTo(tab[j+1]); if(compareStrings > 0){ String temp = tab[j]; tab[j] = tab[j+1]; tab[j+1] = temp; } } } } }; System.out.println("Podaj 5 lancuchow tekstu:"); for(int i=0; i< tab.length; i++){ tab[i] = sc.nextLine(); } bubbleSort.bubbleString(tab); System.out.println("Teksty po zamianie:"); for (String element : tab){ System.out.println(element); } System.out.println("Teksty po odwroconej zamianie"); bubbleSort.reverseString(tab); for(String element : tab){ System.out.println(element); } System.out.println("Teksty posortowane wedlug ostatnich indeksow:"); bubbleSort.lastSort(tab); for(String element:tab){ System.out.println(element); } } } abstract class BubbleSort{ abstract void bubbleString(String[] tab); void reverseString(String[] tab){ for(int i=0; i<tab.length; i++){ for(int j=0; j<tab.length-i-1; j++){ int wynikPorownania = tab[j].compareTo(tab[j+1]); if(wynikPorownania <= 0){ String temp = tab[j]; tab[j] = tab[j+1]; tab[j+1] = temp; } } } } void lastSort(String[] tab) { for (int i = 0; i < tab.length; i++) { for (int j = 0; j < tab.length - i - 1; j++) { int n = 1; int m = 1; int len = tab[j].length(); int len2 = tab[j + 1].length(); char lastFirst = tab[j].charAt(len - n); char lastSecond = tab[j + 1].charAt(len2 - m); if(lastFirst == lastSecond){ while (lastFirst == lastSecond && len - n >= 0 && len2 - m >= 0) { n++; m++; if (len - n >= 0) { lastFirst = tab[j].charAt(len - n); } if (len2 - m >= 0) { lastSecond = tab[j + 1].charAt(len2 - m); } } } if (lastFirst > lastSecond) { String temp = tab[j]; tab[j] = tab[j + 1]; tab[j + 1] = temp; } } } } }//To ostatnie <SUF>
3395_0
package pl.sda.domowe.jeden; // 6. Zadeklaruj dwie zmienne - 'waga' oraz 'wzrost'. Przypisz do nich jakieś wartości. // Stwórz instrukcję warunkową ('if') który sprawdza czy osoba (np. taka która na // kolejkę/rollercoaster) jest wyższa niż 150 cm wzrostu i nie przekracza wagą 180 kg. public class Szesc { public static void main(String[] args) { //Rozwiązanie dokładne do zadanego /*int waga= 55, wzrost = 160; if (wzrost> 160 || waga >180){ System.out.println("Nie możesz wejść"); } else { System.out.println("Zaprazamy"); }*/ // Wersja bardziej rozbudowana int waga = 55, wzrost = 160; if (wzrost < 150 && waga > 180) { System.out.println("Jesteś za niski/a i za cieżki/a, nie możesz wejść"); } else if (wzrost < 150) { System.out.println("Jesteś za niski/a, nie możesz wejść"); } else if (waga > 160) { System.out.println("Jesteś za cieżki/a, nie możesz wejść"); } else { System.out.println("Zapraszamy"); } } }
Grzebere/javaKurs
src/main/java/pl/sda/domowe/jeden/Szesc.java
434
// 6. Zadeklaruj dwie zmienne - 'waga' oraz 'wzrost'. Przypisz do nich jakieś wartości.
line_comment
pl
package pl.sda.domowe.jeden; // 6. Zadeklaruj <SUF> // Stwórz instrukcję warunkową ('if') który sprawdza czy osoba (np. taka która na // kolejkę/rollercoaster) jest wyższa niż 150 cm wzrostu i nie przekracza wagą 180 kg. public class Szesc { public static void main(String[] args) { //Rozwiązanie dokładne do zadanego /*int waga= 55, wzrost = 160; if (wzrost> 160 || waga >180){ System.out.println("Nie możesz wejść"); } else { System.out.println("Zaprazamy"); }*/ // Wersja bardziej rozbudowana int waga = 55, wzrost = 160; if (wzrost < 150 && waga > 180) { System.out.println("Jesteś za niski/a i za cieżki/a, nie możesz wejść"); } else if (wzrost < 150) { System.out.println("Jesteś za niski/a, nie możesz wejść"); } else if (waga > 160) { System.out.println("Jesteś za cieżki/a, nie możesz wejść"); } else { System.out.println("Zapraszamy"); } } }
231_0
// zadanie 5 import java.io.*; import java.util.*; class Main { public static void main(String[] args) { System.out.println(new Punkt3DKolor( 2, 1, 37, new Kolor((byte) 1, (byte) 255, (byte) -1) // -1 zamieni się w 255 ) ); } } class Punkt2D { public double x; public double y; public Punkt2D(double x, double y) { this.x = x; this.y = y; } } class Punkt3D extends Punkt2D { public double z; public Punkt3D(double x, double y, double z) { super(x, y); this.z = z; } public String toString() { return "<Punkt3D: " + x + "; " + y + "; " + z + ">"; } } class Kolor { public byte r; public byte g; public byte b; public Kolor(byte r, byte g, byte b) { this.r = r; this.g = g; this.b = b; } public String toString() { return "<Kolor: " + Byte.toUnsignedInt(r) + ", " + Byte.toUnsignedInt(g) + ", " + Byte.toUnsignedInt(b) + ">"; } } class Punkt3DKolor extends Punkt3D { public Kolor kolor; public Punkt3DKolor(double x, double y, double z, Kolor kolor) { super(x, y, z); this.kolor = kolor; } @Override public String toString() { return "<Punkt3DKolor: " + x + "; " + y + "; " + z + ">\n\t" + kolor + "\n</Punkt3DKolor>"; } }
HakierGrzonzo/studiaNotowane
kod III/Programowanie/kol_2/zad5.java
540
// -1 zamieni się w 255
line_comment
pl
// zadanie 5 import java.io.*; import java.util.*; class Main { public static void main(String[] args) { System.out.println(new Punkt3DKolor( 2, 1, 37, new Kolor((byte) 1, (byte) 255, (byte) -1) // -1 zamieni <SUF> ) ); } } class Punkt2D { public double x; public double y; public Punkt2D(double x, double y) { this.x = x; this.y = y; } } class Punkt3D extends Punkt2D { public double z; public Punkt3D(double x, double y, double z) { super(x, y); this.z = z; } public String toString() { return "<Punkt3D: " + x + "; " + y + "; " + z + ">"; } } class Kolor { public byte r; public byte g; public byte b; public Kolor(byte r, byte g, byte b) { this.r = r; this.g = g; this.b = b; } public String toString() { return "<Kolor: " + Byte.toUnsignedInt(r) + ", " + Byte.toUnsignedInt(g) + ", " + Byte.toUnsignedInt(b) + ">"; } } class Punkt3DKolor extends Punkt3D { public Kolor kolor; public Punkt3DKolor(double x, double y, double z, Kolor kolor) { super(x, y, z); this.kolor = kolor; } @Override public String toString() { return "<Punkt3DKolor: " + x + "; " + y + "; " + z + ">\n\t" + kolor + "\n</Punkt3DKolor>"; } }
2872_6
// Press Shift twice to open the Search Everywhere dialog and type `show whitespaces`, // then press Enter. You can now see whitespace characters in your code. public class Main2 { int a =0; String marka; String kolor; String model; int iloscDrzwi; int pojemnoscSilnika; void met(){ } String met2(){ return ""; } /// // 0 1 -> 0 // true && true -> true // 1 0 // 0 0 -> false public static void main(String[] args) { int dzielnik = 0; int dzielna = 0; double wynik = 0; if ((dzielnik > dzielna) && dzielna != 0) { wynik = dzielnik / dzielna; } else if (dzielna == 0) { System.out.println("nie dzielimy przez 0!"); } else { System.out.println("cos poszlo nie tak"); } // obiekty Auto mercedes = new Auto(); Auto auto2 = new Auto(); // przypisanie wartosci do pola obiektu mercedes.iloscDrzwi = 3; auto2.kolor = "czerwony"; // odczytanie wartosci pól obiektow System.out.println(mercedes.iloscDrzwi); System.out.println(mercedes.kolor); System.out.println(auto2.kolor); Auto honda = new Auto("Honda"); System.out.println(honda.marka); Auto auto3 = new Auto("BMW", "Szary"); Auto auto4 = new Auto("Honda", "szary", "Accord", 5, 2200); System.out.println(auto4.TellSomething()); System.out.println(mercedes.TellSomething()); Figury kwadrat = new Figury(); kwadrat.setBok(-5); System.out.println(kwadrat.obliczPoleKwadratu(7)); Auto honda2 = new Auto(); honda2.marka ="Honda"; kwadrat.obliczPoleKwadratu(6); System.out.println(kwadrat.obliczPoleProstokata(8,9)); } public String TellSomething() { String text = "Jestem " + marka + " mam kolor " + kolor + " model " + model + " ilość drzwi " + iloscDrzwi + " i " + pojemnoscSilnika + " cm2"; return text; } //trojkat.obliczPoleTrojkata(4,7); // System.out.println(trojkat.obliczPoleTrojkata(7,9)); // } }
Hatszepsut-Boniface-Senemedar/Java-basics
src/main/java/Main2.java
780
// odczytanie wartosci pól obiektow
line_comment
pl
// Press Shift twice to open the Search Everywhere dialog and type `show whitespaces`, // then press Enter. You can now see whitespace characters in your code. public class Main2 { int a =0; String marka; String kolor; String model; int iloscDrzwi; int pojemnoscSilnika; void met(){ } String met2(){ return ""; } /// // 0 1 -> 0 // true && true -> true // 1 0 // 0 0 -> false public static void main(String[] args) { int dzielnik = 0; int dzielna = 0; double wynik = 0; if ((dzielnik > dzielna) && dzielna != 0) { wynik = dzielnik / dzielna; } else if (dzielna == 0) { System.out.println("nie dzielimy przez 0!"); } else { System.out.println("cos poszlo nie tak"); } // obiekty Auto mercedes = new Auto(); Auto auto2 = new Auto(); // przypisanie wartosci do pola obiektu mercedes.iloscDrzwi = 3; auto2.kolor = "czerwony"; // odczytanie wartosci <SUF> System.out.println(mercedes.iloscDrzwi); System.out.println(mercedes.kolor); System.out.println(auto2.kolor); Auto honda = new Auto("Honda"); System.out.println(honda.marka); Auto auto3 = new Auto("BMW", "Szary"); Auto auto4 = new Auto("Honda", "szary", "Accord", 5, 2200); System.out.println(auto4.TellSomething()); System.out.println(mercedes.TellSomething()); Figury kwadrat = new Figury(); kwadrat.setBok(-5); System.out.println(kwadrat.obliczPoleKwadratu(7)); Auto honda2 = new Auto(); honda2.marka ="Honda"; kwadrat.obliczPoleKwadratu(6); System.out.println(kwadrat.obliczPoleProstokata(8,9)); } public String TellSomething() { String text = "Jestem " + marka + " mam kolor " + kolor + " model " + model + " ilość drzwi " + iloscDrzwi + " i " + pojemnoscSilnika + " cm2"; return text; } //trojkat.obliczPoleTrojkata(4,7); // System.out.println(trojkat.obliczPoleTrojkata(7,9)); // } }
3787_6
package com.company.lab10pkg; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.*; import com.company.IncorrectDateException; public class LottoLoco { public static void doStuff() { try { Scanner scanner = new Scanner(System.in); int choice = 0; Document doc = Jsoup.connect("http://megalotto.pl/wyniki").get(); Element resultsDiv = doc.getElementById("div_dla_tabeli_wyniki_gry"); Element table = resultsDiv.select("table").get(0); Elements rows = table.select("tr"); List<Element> ahrefs = new ArrayList<>(); for (Element column: rows) { Element el = column.child(0); if(el.children().size() > 0) ahrefs.add(el.child(0)); } choice = chooseGame(ahrefs); String choiceURL = ahrefs.get(choice).attr("abs:href"); choice = chooseOption(); switch (choice) { case 1: // from date { System.out.println("Insert Date in format (dd-MM-yyyy):"); String date = scanner.nextLine(); LocalDate localDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("dd-MM-yyyy")); List<Integer> res = getResultFromDate(localDate, choiceURL); System.out.print("Result: "); if(res.size() <= 0) System.out.println("There is no date like this in Lotto results"); else System.out.println(res); } break; case 2: // hist from year { System.out.println("Insert year:"); int year = scanner.nextInt(); if(LocalDate.of(year, 1, 1).isAfter(LocalDate.now())) throw new IncorrectDateException(String.valueOf(year)); Map<Integer, Integer> res = getHistogramFromYear(year, choiceURL); System.out.println("Result:"); res.forEach((key, value) -> System.out.println(key + ": " +value)); } break; case 3: // hist from span { System.out.println("Insert span (dates in format dd-MM-yyyy):\nFirst date:"); String date = scanner.nextLine(); LocalDate startDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("dd-MM-yyyy")); System.out.println("Second date:"); date = scanner.nextLine(); LocalDate endDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("dd-MM-yyyy")); if(startDate.isAfter(endDate) || endDate.isAfter(LocalDate.now())) throw new IncorrectDateException("(start):" + startDate + " (end):" + endDate); Map<Integer, Integer> res = getHistogramBetweenDates(startDate, endDate, choiceURL); res.forEach((key, value) -> System.out.println(key + ": " +value)); } break; default: System.out.println("Incorrect choice"); break; } } catch (IOException exc) { System.out.println(exc); } catch (IncorrectDateException inData) { System.out.println("Not this time, your date (" + inData.getInfo() + ") is incorrect"); } } private static int chooseGame(List<Element> table) { for(int i = 0; i < table.size(); ++i) { System.out.println(i + ": " + table.get(i).text()); } Scanner scanner = new Scanner(System.in); return scanner.nextInt(); } private static int chooseOption() { System.out.println("1. Results at date"); System.out.println("2. Histogram at specified year"); System.out.println("3. Histogram at specified span"); Scanner scanner = new Scanner(System.in); return scanner.nextInt(); } private static List<Integer> getResultFromDate(LocalDate date, String url) throws IOException { // Document doc = Jsoup.connect(url+fromToURLPart(date, date)).get(); // List<Integer> toReturn = new ArrayList<>(); // String numbers = doc.getElementsByClass("numbers_in_list ").text(); // if(!numbers.equals("")) // { // for(String s : numbers.split(" ")) // { // toReturn.add(Integer.parseInt(s)); // } // } // // return toReturn; // pytanie czy takie coś może być, są tutaj tylko liczby, w przypadku MultiMulti powinny być chyba dwie listy, albo ja już nawet nie wiem xD return new ArrayList<>(getHistogramBetweenDates(date, date, url).keySet()); } private static Map<Integer, Integer> getHistogramFromYear(int year, String url) throws IOException { return getHistogramBetweenDates(LocalDate.of(year, 1, 1), LocalDate.of(year, 12, 31), url); } private static Map<Integer, Integer> getHistogramBetweenDates(LocalDate start, LocalDate end, String url) throws IOException { Document doc = Jsoup.connect(url+fromToURLPart(start, end)).get(); Map<Integer, Integer> histogram = new HashMap<>(); String numbers = doc.getElementsByClass("numbers_in_list ").text(); if(!numbers.equals("")) { for(String s : numbers.split(" ")) { Integer num = Integer.parseInt(s); if(histogram.putIfAbsent(num, 1) != null) histogram.replace(num, histogram.get(num)+1); } } return histogram; } private static String fromToURLPart(LocalDate start, LocalDate end) { return "/losowania-od-"+start.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"))+"-do-"+end.format(DateTimeFormatter.ofPattern("dd-MM-yyyy")); } }
Hergoln/ZPO
lab10pkg/LottoLoco.java
1,732
// pytanie czy takie coś może być, są tutaj tylko liczby, w przypadku MultiMulti powinny być chyba dwie listy, albo ja już nawet nie wiem xD
line_comment
pl
package com.company.lab10pkg; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.*; import com.company.IncorrectDateException; public class LottoLoco { public static void doStuff() { try { Scanner scanner = new Scanner(System.in); int choice = 0; Document doc = Jsoup.connect("http://megalotto.pl/wyniki").get(); Element resultsDiv = doc.getElementById("div_dla_tabeli_wyniki_gry"); Element table = resultsDiv.select("table").get(0); Elements rows = table.select("tr"); List<Element> ahrefs = new ArrayList<>(); for (Element column: rows) { Element el = column.child(0); if(el.children().size() > 0) ahrefs.add(el.child(0)); } choice = chooseGame(ahrefs); String choiceURL = ahrefs.get(choice).attr("abs:href"); choice = chooseOption(); switch (choice) { case 1: // from date { System.out.println("Insert Date in format (dd-MM-yyyy):"); String date = scanner.nextLine(); LocalDate localDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("dd-MM-yyyy")); List<Integer> res = getResultFromDate(localDate, choiceURL); System.out.print("Result: "); if(res.size() <= 0) System.out.println("There is no date like this in Lotto results"); else System.out.println(res); } break; case 2: // hist from year { System.out.println("Insert year:"); int year = scanner.nextInt(); if(LocalDate.of(year, 1, 1).isAfter(LocalDate.now())) throw new IncorrectDateException(String.valueOf(year)); Map<Integer, Integer> res = getHistogramFromYear(year, choiceURL); System.out.println("Result:"); res.forEach((key, value) -> System.out.println(key + ": " +value)); } break; case 3: // hist from span { System.out.println("Insert span (dates in format dd-MM-yyyy):\nFirst date:"); String date = scanner.nextLine(); LocalDate startDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("dd-MM-yyyy")); System.out.println("Second date:"); date = scanner.nextLine(); LocalDate endDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("dd-MM-yyyy")); if(startDate.isAfter(endDate) || endDate.isAfter(LocalDate.now())) throw new IncorrectDateException("(start):" + startDate + " (end):" + endDate); Map<Integer, Integer> res = getHistogramBetweenDates(startDate, endDate, choiceURL); res.forEach((key, value) -> System.out.println(key + ": " +value)); } break; default: System.out.println("Incorrect choice"); break; } } catch (IOException exc) { System.out.println(exc); } catch (IncorrectDateException inData) { System.out.println("Not this time, your date (" + inData.getInfo() + ") is incorrect"); } } private static int chooseGame(List<Element> table) { for(int i = 0; i < table.size(); ++i) { System.out.println(i + ": " + table.get(i).text()); } Scanner scanner = new Scanner(System.in); return scanner.nextInt(); } private static int chooseOption() { System.out.println("1. Results at date"); System.out.println("2. Histogram at specified year"); System.out.println("3. Histogram at specified span"); Scanner scanner = new Scanner(System.in); return scanner.nextInt(); } private static List<Integer> getResultFromDate(LocalDate date, String url) throws IOException { // Document doc = Jsoup.connect(url+fromToURLPart(date, date)).get(); // List<Integer> toReturn = new ArrayList<>(); // String numbers = doc.getElementsByClass("numbers_in_list ").text(); // if(!numbers.equals("")) // { // for(String s : numbers.split(" ")) // { // toReturn.add(Integer.parseInt(s)); // } // } // // return toReturn; // pytanie czy <SUF> return new ArrayList<>(getHistogramBetweenDates(date, date, url).keySet()); } private static Map<Integer, Integer> getHistogramFromYear(int year, String url) throws IOException { return getHistogramBetweenDates(LocalDate.of(year, 1, 1), LocalDate.of(year, 12, 31), url); } private static Map<Integer, Integer> getHistogramBetweenDates(LocalDate start, LocalDate end, String url) throws IOException { Document doc = Jsoup.connect(url+fromToURLPart(start, end)).get(); Map<Integer, Integer> histogram = new HashMap<>(); String numbers = doc.getElementsByClass("numbers_in_list ").text(); if(!numbers.equals("")) { for(String s : numbers.split(" ")) { Integer num = Integer.parseInt(s); if(histogram.putIfAbsent(num, 1) != null) histogram.replace(num, histogram.get(num)+1); } } return histogram; } private static String fromToURLPart(LocalDate start, LocalDate end) { return "/losowania-od-"+start.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"))+"-do-"+end.format(DateTimeFormatter.ofPattern("dd-MM-yyyy")); } }
3976_6
package org.example; public class MainBinarny { static int search(int[] numbers, int indexStart, int target, int indexEnd) { int middle; //Sprawdzenie czy liczba nie jest mniejsza od najmniejszej, albo większa od największej. Czyli czy znajduję się w tablicy. if(target < numbers[indexStart] || target > numbers[indexEnd]){ return -1; } //Określenie środkowego indeksu. middle = (indexStart + indexEnd)/2; //Jeśli długość tablicy jest parzysta, nie ma elementu środkowego, są 'dwa'. if(middle%2 == 0) { //Sprawdzenie 'mniejszego' środka, ponieważ typ [int] ucina liczby po przecinku, np. 23/2 = 11.5, więc sprawdzamy indeks 11. if(numbers[middle] == target) { return middle; } //Sprawdzenie 'wiekszego' środka, ponieważ typ [int] ucina liczby po przecinku, np. 23/2 = 11.5, więc sprawdzamy indeks 12 (11+1). else if (numbers[middle+1] == target) { return middle+1; } } //Jeśli długość tablicy jest nieparzysta, jest jeden element środkowy. else { //Sprawdzenie czy środkowy element jest szukanym. if(numbers[middle] == target) return middle; } //Teraz sprawdzamy w której połówce znajduje się nasza szukana liczba. if(target > numbers[middle]) { //Jeśli większa od środkowej liczby, to szukamy od środkowa do końca. return search(numbers, middle+1, target, indexEnd); } else { //Jeśli mniejsza od środkowej liczby, to szukamy od początku do środka. return search(numbers, indexStart, target, middle-1); } } public static void main(String[] args) { int[] liczbyPierwsze = {2, 3, 5, 7, 11, 13, 17, 19, 23, 27, 29, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}; int liczbaSzukana = 23; int index = search(liczbyPierwsze, 0, liczbaSzukana, liczbyPierwsze.length - 1); System.out.println("Szukam liczby: " + liczbaSzukana); if(index == -1){ System.out.println("Tablica nie zawiera podanej liczby!"); } else { System.out.println("Liczba ma indeks: " + index); } } }
Hiroten31/Studies
Dyskretna/Pierwszy/MainBinarny.java
836
//Sprawdzenie czy środkowy element jest szukanym.
line_comment
pl
package org.example; public class MainBinarny { static int search(int[] numbers, int indexStart, int target, int indexEnd) { int middle; //Sprawdzenie czy liczba nie jest mniejsza od najmniejszej, albo większa od największej. Czyli czy znajduję się w tablicy. if(target < numbers[indexStart] || target > numbers[indexEnd]){ return -1; } //Określenie środkowego indeksu. middle = (indexStart + indexEnd)/2; //Jeśli długość tablicy jest parzysta, nie ma elementu środkowego, są 'dwa'. if(middle%2 == 0) { //Sprawdzenie 'mniejszego' środka, ponieważ typ [int] ucina liczby po przecinku, np. 23/2 = 11.5, więc sprawdzamy indeks 11. if(numbers[middle] == target) { return middle; } //Sprawdzenie 'wiekszego' środka, ponieważ typ [int] ucina liczby po przecinku, np. 23/2 = 11.5, więc sprawdzamy indeks 12 (11+1). else if (numbers[middle+1] == target) { return middle+1; } } //Jeśli długość tablicy jest nieparzysta, jest jeden element środkowy. else { //Sprawdzenie czy <SUF> if(numbers[middle] == target) return middle; } //Teraz sprawdzamy w której połówce znajduje się nasza szukana liczba. if(target > numbers[middle]) { //Jeśli większa od środkowej liczby, to szukamy od środkowa do końca. return search(numbers, middle+1, target, indexEnd); } else { //Jeśli mniejsza od środkowej liczby, to szukamy od początku do środka. return search(numbers, indexStart, target, middle-1); } } public static void main(String[] args) { int[] liczbyPierwsze = {2, 3, 5, 7, 11, 13, 17, 19, 23, 27, 29, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}; int liczbaSzukana = 23; int index = search(liczbyPierwsze, 0, liczbaSzukana, liczbyPierwsze.length - 1); System.out.println("Szukam liczby: " + liczbaSzukana); if(index == -1){ System.out.println("Tablica nie zawiera podanej liczby!"); } else { System.out.println("Liczba ma indeks: " + index); } } }
5201_0
package pl.atena.edu.lambda; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import pl.atena.edu.akdaemia1.Osoba; public class LambdaTest3 { public static void main(String[] args) { String[] tab = { "Staszek", "Maksymilian", "Ola" }; List<String> lista = Arrays.asList(tab); Stream<Osoba> stream = lista.stream().map(Osoba::new); // Mogę go wyświetlić // stream.forEach(System.out::println); // Mogę go przerobić na tablicę Osoba[] tabO = stream.toArray(Osoba[]::new); Arrays.asList(tabO).forEach(System.out::println); } }
Horfeusz/akademia
akademia1/src/pl/atena/edu/lambda/LambdaTest3.java
257
// Mogę go wyświetlić
line_comment
pl
package pl.atena.edu.lambda; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import pl.atena.edu.akdaemia1.Osoba; public class LambdaTest3 { public static void main(String[] args) { String[] tab = { "Staszek", "Maksymilian", "Ola" }; List<String> lista = Arrays.asList(tab); Stream<Osoba> stream = lista.stream().map(Osoba::new); // Mogę go <SUF> // stream.forEach(System.out::println); // Mogę go przerobić na tablicę Osoba[] tabO = stream.toArray(Osoba[]::new); Arrays.asList(tabO).forEach(System.out::println); } }
4969_3
package main.java.model; /** * File module, class Product.java * class of products used in Recipe or present in Fridge * Created by Anna on 2015-06-10. */ enum eProdtype { LOOSE, LIQUID, SPICE, MEAT, FISH, VEGETABLE, FRUIT } public class Product{ private int productId; private String name; private eProdtype productType; private int amount; //-->dopiero w przepisie i lodowce? //dorobić pochodne klasy dla róznych typów składników gdzie ilość // będzie zależeć od typu składnika np. ml dla płynów, // gramy dla sypkich ??? public void setProductId(int product_id) { this.productId = productId; } public int getProductId() { return productId; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setProductType(String productType) { this.productType= eProdtype.valueOf(productType); } public String getProductType() { return productType.name(); } public void setAmount(int amount) { this.amount = amount; } public int getAmount() { return amount; } @Override public String toString() { return "Product [id=" + productId + ". Product Name=" + name + ", amount=" + amount + ", Type=" + productType + "]"; } }
IBAW4z/CRUD
src/main/java/model/Product.java
432
// będzie zależeć od typu składnika np. ml dla płynów,
line_comment
pl
package main.java.model; /** * File module, class Product.java * class of products used in Recipe or present in Fridge * Created by Anna on 2015-06-10. */ enum eProdtype { LOOSE, LIQUID, SPICE, MEAT, FISH, VEGETABLE, FRUIT } public class Product{ private int productId; private String name; private eProdtype productType; private int amount; //-->dopiero w przepisie i lodowce? //dorobić pochodne klasy dla róznych typów składników gdzie ilość // będzie zależeć <SUF> // gramy dla sypkich ??? public void setProductId(int product_id) { this.productId = productId; } public int getProductId() { return productId; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setProductType(String productType) { this.productType= eProdtype.valueOf(productType); } public String getProductType() { return productType.name(); } public void setAmount(int amount) { this.amount = amount; } public int getAmount() { return amount; } @Override public String toString() { return "Product [id=" + productId + ". Product Name=" + name + ", amount=" + amount + ", Type=" + productType + "]"; } }
4936_3
package main.java.model; /** * File module, class Product.java * class of products used in Recipe or present in Fridge * Created by Anna on 2015-06-10. */ enum eProdtype { LOOSE, LIQUID, SPICE, MEAT, FISH, VEGETABLE, FRUIT } public class Product{ private int productId; private String name; private eProdtype productType; private int amount; //-->dopiero w przepisie i lodowce? //dorobić pochodne klasy dla róznych typów składników gdzie ilość // będzie zależeć od typu składnika np. ml dla płynów, // gramy dla sypkich ??? public void setProductId(int product_id) { this.productId = productId; } public int getProductId() { return productId; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setProductType(eProdtype productType) { this.productType= productType; } public eProdtype getProductType() { return productType; } public void setAmount(int amount) { this.amount = amount; } public int getAmount() { return amount; } }
IBAW4z/IBAW4
src/model/Product.java
377
// będzie zależeć od typu składnika np. ml dla płynów,
line_comment
pl
package main.java.model; /** * File module, class Product.java * class of products used in Recipe or present in Fridge * Created by Anna on 2015-06-10. */ enum eProdtype { LOOSE, LIQUID, SPICE, MEAT, FISH, VEGETABLE, FRUIT } public class Product{ private int productId; private String name; private eProdtype productType; private int amount; //-->dopiero w przepisie i lodowce? //dorobić pochodne klasy dla róznych typów składników gdzie ilość // będzie zależeć <SUF> // gramy dla sypkich ??? public void setProductId(int product_id) { this.productId = productId; } public int getProductId() { return productId; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setProductType(eProdtype productType) { this.productType= productType; } public eProdtype getProductType() { return productType; } public void setAmount(int amount) { this.amount = amount; } public int getAmount() { return amount; } }
3115_3
package task_3; import java.util.Scanner; public class klasaLemur{ //licznik udupienia na najbliższy tydzień public static void main(String [] args){ String dane[][]; dane = new String[7][3]; Scanner tmpS=new Scanner(System.in); //kategorie: dni tygodnia dane[0][0]="PONIEDZIAŁEK"; dane[1][0]="WTOREK"; dane[2][0]="ŚRODA"; dane[3][0]="CZWARTEK"; dane[4][0]="PIĄTEK"; dane[5][0]="SOBOTA"; dane[6][0]="NIEDZIELA"; for (int i=0; i<dane.length; i++){ System.out.println(dane[i][0]+" - co cię udupia?\n"); dane [i][1]=tmpS.nextLine(); System.out.println("Jak bardzo cię udupia? (skala 1-10)"); dane[i][2]=tmpS.nextLine(); } tmpS.close(); //wyświetlanie tygodnia System.out.println("Twój udupiający tydzień przedstawia się następująco: \n"); for (int i=0; i<dane.length; i++){ System.out.println(dane[i][0]+" - "+dane[i][1]+" ("+dane[i][2]+")"); } //wyliczenie stopnia udupienia int wspUdup=0; for (int i=0; i<dane.length; i++){ try{ wspUdup=wspUdup+Integer.parseInt(dane[i][2]); } catch (NumberFormatException exc) { wspUdup=wspUdup+0; } } //skomentowanie stopnia udupienia String koment; if (wspUdup<10) koment="Prokrastynuj w spokoju."; else if (wspUdup>10 && wspUdup<20) koment="Prokrastynuj w niepokoju."; else if (wspUdup>20 && wspUdup<30) koment="Lepiej nie prokrastynować. Co nie znaczy, że nie będziesz."; else if (wspUdup>30 && wspUdup<40) koment="Prokrastynacja zakazana. Pamiętaj, by nie dać się złapać."; else if (wspUdup>40 && wspUdup<50) koment="Prokrastynuj w panice"; else koment="Prokrastynuj w spokoju. I tak jesteś udupiony."; System.out.println("\n Stopień udupienia w tym tygodniu wynosi "+wspUdup+". "+koment); } }
IBAW4z/task_3
src/task_3/klasaLemur.java
921
//skomentowanie stopnia udupienia
line_comment
pl
package task_3; import java.util.Scanner; public class klasaLemur{ //licznik udupienia na najbliższy tydzień public static void main(String [] args){ String dane[][]; dane = new String[7][3]; Scanner tmpS=new Scanner(System.in); //kategorie: dni tygodnia dane[0][0]="PONIEDZIAŁEK"; dane[1][0]="WTOREK"; dane[2][0]="ŚRODA"; dane[3][0]="CZWARTEK"; dane[4][0]="PIĄTEK"; dane[5][0]="SOBOTA"; dane[6][0]="NIEDZIELA"; for (int i=0; i<dane.length; i++){ System.out.println(dane[i][0]+" - co cię udupia?\n"); dane [i][1]=tmpS.nextLine(); System.out.println("Jak bardzo cię udupia? (skala 1-10)"); dane[i][2]=tmpS.nextLine(); } tmpS.close(); //wyświetlanie tygodnia System.out.println("Twój udupiający tydzień przedstawia się następująco: \n"); for (int i=0; i<dane.length; i++){ System.out.println(dane[i][0]+" - "+dane[i][1]+" ("+dane[i][2]+")"); } //wyliczenie stopnia udupienia int wspUdup=0; for (int i=0; i<dane.length; i++){ try{ wspUdup=wspUdup+Integer.parseInt(dane[i][2]); } catch (NumberFormatException exc) { wspUdup=wspUdup+0; } } //skomentowanie stopnia <SUF> String koment; if (wspUdup<10) koment="Prokrastynuj w spokoju."; else if (wspUdup>10 && wspUdup<20) koment="Prokrastynuj w niepokoju."; else if (wspUdup>20 && wspUdup<30) koment="Lepiej nie prokrastynować. Co nie znaczy, że nie będziesz."; else if (wspUdup>30 && wspUdup<40) koment="Prokrastynacja zakazana. Pamiętaj, by nie dać się złapać."; else if (wspUdup>40 && wspUdup<50) koment="Prokrastynuj w panice"; else koment="Prokrastynuj w spokoju. I tak jesteś udupiony."; System.out.println("\n Stopień udupienia w tym tygodniu wynosi "+wspUdup+". "+koment); } }
7043_0
package sim.model.algo; import java.awt.Point; import java.util.Map; import sim.model.Agent; import sim.model.Board; /* * FIXME: problem, gdy dwóch agentów ma dokładnie tą samą płytkę-cel (jeden krąży wokół pola) * rozwiązanie: wyzwolenie akcji "reachTarget" gdy odległość od celu mniejsza niż pewien threshold */ public interface MovementAlgorithm { public static enum Algorithm { NONE, PED_4, SOCIAL_FORCE } enum Orientation { SAME, OPP, ORTHO, OUT } /** * * @param board * plansza * @param a * agent, dla którego wykonujemy algorytm */ public abstract void prepare(Agent a); /** * * @param board * plansza * @param p * punkt na planszy, dla którego wykonujemy algorytm * @param mpLeft * mapa określająca ilość jeszcze niewykorzystanych punktów ruchu * agentów */ public abstract void nextIterationStep(Agent a, Map<Agent, Integer> mpLeft); }
Idorobots/mall-sim
src/sim/model/algo/MovementAlgorithm.java
356
/* * FIXME: problem, gdy dwóch agentów ma dokładnie tą samą płytkę-cel (jeden krąży wokół pola) * rozwiązanie: wyzwolenie akcji "reachTarget" gdy odległość od celu mniejsza niż pewien threshold */
block_comment
pl
package sim.model.algo; import java.awt.Point; import java.util.Map; import sim.model.Agent; import sim.model.Board; /* * FIXME: problem, gdy <SUF>*/ public interface MovementAlgorithm { public static enum Algorithm { NONE, PED_4, SOCIAL_FORCE } enum Orientation { SAME, OPP, ORTHO, OUT } /** * * @param board * plansza * @param a * agent, dla którego wykonujemy algorytm */ public abstract void prepare(Agent a); /** * * @param board * plansza * @param p * punkt na planszy, dla którego wykonujemy algorytm * @param mpLeft * mapa określająca ilość jeszcze niewykorzystanych punktów ruchu * agentów */ public abstract void nextIterationStep(Agent a, Map<Agent, Integer> mpLeft); }
7139_0
package basicsJava.practice; import java.util.Scanner; /* Napisz program, który „się jąka”, to znaczy pobiera użytkownika tekst (zmienną typu String), a następnie wypisuje podany tekst, w którym każde słowo wypisane jest po dwa razy. Przykładowo, dla wejścia: „To jest mój test” program powinien wypisać „To To jest jest mój mój test test”. */ public class StutteringProgram { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter text:"); String text = in.nextLine().trim(); System.out.println("how many times should I stutter?"); int stutter = in.nextInt(); text = text.replaceAll(" +"," "); String[] separatedWords = text.split(" "); for (String word : separatedWords) { for (int j = 0; j < stutter; j++) { String print = word; if (j != 0 && word.charAt(0) >= 65 && word.charAt(0) <= 90) { print = word.toLowerCase(); } if (j != stutter - 1 && word.charAt(word.length() - 1) == '.' || word.charAt(word.length() - 1) == ',') { print = word.substring(0, word.length() - 1); } System.out.print(print.concat(" ")); } } } }
Igor-Shishkin/courseSDA
src/main/java/basicsJava/practice/StutteringProgram.java
440
/* Napisz program, który „się jąka”, to znaczy pobiera użytkownika tekst (zmienną typu String), a następnie wypisuje podany tekst, w którym każde słowo wypisane jest po dwa razy. Przykładowo, dla wejścia: „To jest mój test” program powinien wypisać „To To jest jest mój mój test test”. */
block_comment
pl
package basicsJava.practice; import java.util.Scanner; /* Napisz program, który <SUF>*/ public class StutteringProgram { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter text:"); String text = in.nextLine().trim(); System.out.println("how many times should I stutter?"); int stutter = in.nextInt(); text = text.replaceAll(" +"," "); String[] separatedWords = text.split(" "); for (String word : separatedWords) { for (int j = 0; j < stutter; j++) { String print = word; if (j != 0 && word.charAt(0) >= 65 && word.charAt(0) <= 90) { print = word.toLowerCase(); } if (j != stutter - 1 && word.charAt(word.length() - 1) == '.' || word.charAt(word.length() - 1) == ',') { print = word.substring(0, word.length() - 1); } System.out.print(print.concat(" ")); } } } }
8266_0
package pl.umk.mat.imare.reco; import java.io.Serializable; /** * Symbolizuje określoną tonację (a dokładniej: parę tonacji równoległych) * charakteryzującą się określoną ilością i rodzajem znaków przykluczowych. * @author PieterEr */ public class Tonality implements Serializable { /** * Rodzaj znaku chromatycznego. */ static public enum Sign { /** * Krzyżyk. */ SHARP, /** * Bemol. */ FLAT, /** * Kasownik. */ NATURAL, /** * Brak znaku chromatycznego. */ NONE } /** * Określona pozycja na pięciolinii, którą może zajmować nuta, określana * poprzez wysokość względem dźwięku c<sup>1</sup> oraz znak chromatyczny. */ static public final class StaffPitch { /** * Właściwy znak chromatyczny. */ public Sign sign; /** * Poziom na pięciolinii względem c<sup>1</sup>. */ public int level; /** * Domyślny konstruktor, tworzący pozycję dźwięku c<sup>1</sup> bez * znaku chromatycznego. */ public StaffPitch() { sign = Sign.NONE; level = 0; } } /** * Struktura przedstawiająca znak przykluczowy. */ static public final class ClefKey { /** * Rodzaj znaku przykluczowego. */ public Sign sign; /** * Odpowiedni poziom znaku na pięciolinii z kluczem basowym, liczony * względem pierwszej (najniższej) linii. */ public int levelBass; /** * Odpowiedni poziom znaku na pięciolinii z kluczem wiolinowym, liczony * względem pierwszej (najniższej) linii. */ public int levelTreble; /** * Tworzy odpowiedni znak przykluczowy na podstawie pozycji na * pięciolinii określanej strukturą StaffPitch. * @param sp struktura określająca tworzony znak przykluczowy */ public ClefKey(StaffPitch sp) { sign = sp.sign; int max; max = sign == Sign.SHARP ? 11 : 9; levelTreble = sp.level; while (levelTreble + 7 <= max) { levelTreble += 7; } levelBass = levelTreble - 2; } } // liczone od C private static final int[] zerolevels = {0, 2, 4, 5, 7, 9, 11}; private int levels[]; private int signs[]; private static final char[] names = {'c', 'd', 'e', 'f', 'g', 'a', 'b'}; static private Sign signFromInt(int s) { switch (s) { case -1: return Sign.FLAT; case 0: return Sign.NATURAL; case 1: return Sign.SHARP; default: return Sign.NONE; } } protected Tonality() { signs = new int[7]; levels = new int[7]; for (int i = 0; i < 7; ++i) { levels[i] = zerolevels[i]; } } protected void setLevel(int rlevel, int rsemi) { signs[rlevel] = rsemi - zerolevels[rlevel]; levels[rlevel] = rsemi; } protected void setSign(int rlevel, int sign) { signs[rlevel] = sign; levels[rlevel] = zerolevels[rlevel] + sign; } /** * Zwraca tablicę znaków przykluczowych odpowiednich dla tonacji. * @return tablica znaków przykluczowych w odpowiedniej kolejności */ public ClefKey[] clefSigns() { int size = 0; for (int l = 0; l < 7; ++l) { if (signs[l] != 0) { ++size; } } ClefKey signOrder[] = new ClefKey[size]; int where = 0; for (int l : Sonst.SHARP_ORDER) { if (signs[l] > 0) { StaffPitch sp = new StaffPitch(); sp.level = l; sp.sign = Sign.SHARP; signOrder[where++] = new ClefKey(sp); } } for (int l : Sonst.FLAT_ORDER) { if (signs[l] < 0) { StaffPitch sp = new StaffPitch(); sp.level = l; sp.sign = Sign.FLAT; signOrder[where++] = new ClefKey(sp); } } return signOrder; } private int getProperNoteLevel(Note n) { int rp = n.getPitch() % 12; for (int i = 0; i < 7; ++i) { if (levels[i] == rp) { return i; } } int i = 0; while (i < 6 && zerolevels[i + 1] <= rp) { ++i; } return i; } /** * Zwraca pozycję nuty na pięciolinii z uwzględnieniem tonacji. Ewentualny * znak chromatyczny wynikowej struktury uwzględnia obecność odpowiednich * dla tonacji znaków przykluczowych. * @param n nuta, której pozycja ma zostać ustalona * @return struktura StaffPitch opisująca pozycję danej nuty dla określonej * tonacji */ public StaffPitch adapt(Note n) { int pitch = n.getPitch(); int rl = getProperNoteLevel(n); int rp = pitch % 12; int ro = (pitch / 12) - 5; StaffPitch sp = new StaffPitch(); sp.level = 7 * ro + rl; if (rp != levels[rl]) { sp.sign = signFromInt(rp-zerolevels[rl]); } return sp; } /** * Generuje nazwę nuty na pięciolinii w określonej tonacji, bez uwzględniania * oktawy (zawsze generowana jest nazwa taka jak w oktawie małej). Nazwy * dźwięków są w systemie anglosaskim (c,d,e,f,g,a,b), zaś w przypadku * dźwięków alterowanych, nazwa tworzona jest według notacji duńskiej * (niestandardowej), w której wartość podwyższona krzyżykiem posiada * przedrostek "-is", zaś wartość obniżona bemolem "-es", przy czym * samogłoski w tych końcówkach nigdy nie ulegają skróceniu. * @param n nuta, której nazwa ma zostać wygenerowana * @return ciąg znaków będący nazwą nuty (np. "ees", "g", ais") */ public String generateName(Note n) { int pitch = n.getPitch(); int rl = getProperNoteLevel(n); int rp = pitch % 12; String name = String.valueOf(names[rl]); switch(rp - zerolevels[rl]) { case +1: name += "is"; break; case -1: name += "es"; break; } return name; } }
ImareTeam/audio-recognition-library
src/main/java/pl/umk/mat/imare/reco/Tonality.java
2,274
/** * Symbolizuje określoną tonację (a dokładniej: parę tonacji równoległych) * charakteryzującą się określoną ilością i rodzajem znaków przykluczowych. * @author PieterEr */
block_comment
pl
package pl.umk.mat.imare.reco; import java.io.Serializable; /** * Symbolizuje określoną tonację <SUF>*/ public class Tonality implements Serializable { /** * Rodzaj znaku chromatycznego. */ static public enum Sign { /** * Krzyżyk. */ SHARP, /** * Bemol. */ FLAT, /** * Kasownik. */ NATURAL, /** * Brak znaku chromatycznego. */ NONE } /** * Określona pozycja na pięciolinii, którą może zajmować nuta, określana * poprzez wysokość względem dźwięku c<sup>1</sup> oraz znak chromatyczny. */ static public final class StaffPitch { /** * Właściwy znak chromatyczny. */ public Sign sign; /** * Poziom na pięciolinii względem c<sup>1</sup>. */ public int level; /** * Domyślny konstruktor, tworzący pozycję dźwięku c<sup>1</sup> bez * znaku chromatycznego. */ public StaffPitch() { sign = Sign.NONE; level = 0; } } /** * Struktura przedstawiająca znak przykluczowy. */ static public final class ClefKey { /** * Rodzaj znaku przykluczowego. */ public Sign sign; /** * Odpowiedni poziom znaku na pięciolinii z kluczem basowym, liczony * względem pierwszej (najniższej) linii. */ public int levelBass; /** * Odpowiedni poziom znaku na pięciolinii z kluczem wiolinowym, liczony * względem pierwszej (najniższej) linii. */ public int levelTreble; /** * Tworzy odpowiedni znak przykluczowy na podstawie pozycji na * pięciolinii określanej strukturą StaffPitch. * @param sp struktura określająca tworzony znak przykluczowy */ public ClefKey(StaffPitch sp) { sign = sp.sign; int max; max = sign == Sign.SHARP ? 11 : 9; levelTreble = sp.level; while (levelTreble + 7 <= max) { levelTreble += 7; } levelBass = levelTreble - 2; } } // liczone od C private static final int[] zerolevels = {0, 2, 4, 5, 7, 9, 11}; private int levels[]; private int signs[]; private static final char[] names = {'c', 'd', 'e', 'f', 'g', 'a', 'b'}; static private Sign signFromInt(int s) { switch (s) { case -1: return Sign.FLAT; case 0: return Sign.NATURAL; case 1: return Sign.SHARP; default: return Sign.NONE; } } protected Tonality() { signs = new int[7]; levels = new int[7]; for (int i = 0; i < 7; ++i) { levels[i] = zerolevels[i]; } } protected void setLevel(int rlevel, int rsemi) { signs[rlevel] = rsemi - zerolevels[rlevel]; levels[rlevel] = rsemi; } protected void setSign(int rlevel, int sign) { signs[rlevel] = sign; levels[rlevel] = zerolevels[rlevel] + sign; } /** * Zwraca tablicę znaków przykluczowych odpowiednich dla tonacji. * @return tablica znaków przykluczowych w odpowiedniej kolejności */ public ClefKey[] clefSigns() { int size = 0; for (int l = 0; l < 7; ++l) { if (signs[l] != 0) { ++size; } } ClefKey signOrder[] = new ClefKey[size]; int where = 0; for (int l : Sonst.SHARP_ORDER) { if (signs[l] > 0) { StaffPitch sp = new StaffPitch(); sp.level = l; sp.sign = Sign.SHARP; signOrder[where++] = new ClefKey(sp); } } for (int l : Sonst.FLAT_ORDER) { if (signs[l] < 0) { StaffPitch sp = new StaffPitch(); sp.level = l; sp.sign = Sign.FLAT; signOrder[where++] = new ClefKey(sp); } } return signOrder; } private int getProperNoteLevel(Note n) { int rp = n.getPitch() % 12; for (int i = 0; i < 7; ++i) { if (levels[i] == rp) { return i; } } int i = 0; while (i < 6 && zerolevels[i + 1] <= rp) { ++i; } return i; } /** * Zwraca pozycję nuty na pięciolinii z uwzględnieniem tonacji. Ewentualny * znak chromatyczny wynikowej struktury uwzględnia obecność odpowiednich * dla tonacji znaków przykluczowych. * @param n nuta, której pozycja ma zostać ustalona * @return struktura StaffPitch opisująca pozycję danej nuty dla określonej * tonacji */ public StaffPitch adapt(Note n) { int pitch = n.getPitch(); int rl = getProperNoteLevel(n); int rp = pitch % 12; int ro = (pitch / 12) - 5; StaffPitch sp = new StaffPitch(); sp.level = 7 * ro + rl; if (rp != levels[rl]) { sp.sign = signFromInt(rp-zerolevels[rl]); } return sp; } /** * Generuje nazwę nuty na pięciolinii w określonej tonacji, bez uwzględniania * oktawy (zawsze generowana jest nazwa taka jak w oktawie małej). Nazwy * dźwięków są w systemie anglosaskim (c,d,e,f,g,a,b), zaś w przypadku * dźwięków alterowanych, nazwa tworzona jest według notacji duńskiej * (niestandardowej), w której wartość podwyższona krzyżykiem posiada * przedrostek "-is", zaś wartość obniżona bemolem "-es", przy czym * samogłoski w tych końcówkach nigdy nie ulegają skróceniu. * @param n nuta, której nazwa ma zostać wygenerowana * @return ciąg znaków będący nazwą nuty (np. "ees", "g", ais") */ public String generateName(Note n) { int pitch = n.getPitch(); int rl = getProperNoteLevel(n); int rp = pitch % 12; String name = String.valueOf(names[rl]); switch(rp - zerolevels[rl]) { case +1: name += "is"; break; case -1: name += "es"; break; } return name; } }
6388_59
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pl.umk.mat.imare.io; //import java.io.File; //import java.io.FileInputStream; //import java.io.IOException; //import java.util.LinkedList; //import javax.sound.sampled.AudioFormat; //import javax.sound.sampled.AudioInputStream; //import javax.sound.sampled.AudioSystem; //import javax.sound.sampled.UnsupportedAudioFileException; //import pl.umk.mat.imare.exception.FileDoesNotExistException; //import pl.umk.mat.imare.exception.MissingChannelException; //import pl.umk.mat.imare.gui.ProgressFrame; //import pl.umk.mat.imare.gui.related.ProgressListener; /** * Klasa pozwalajaca uzyskac dostep do pliku WAVE. * @author morti */ public abstract class OldWave { // // /** Informacje o pliku */ // protected AudioFormat format = null; // /** Dane pliku wave */ // protected int[][] data = null; // protected File file = null; // protected LinkedList<ProgressListener> listeners = new LinkedList<ProgressListener>(); // // /** // * Otwiera plik do odczytu // * @param file Plik do otwarcia // * @return Zwraca obiekt klasy Wave pozwalajacy odczytac plik. Moze zwrocic // * null jesli probka bedzie miala wiecej niz 2 kanaly lub bedzie miala // * liczbe bitow na probke inna niz 8 lub 16. // * @throws FileDoesNotExistException // * @throws UnsupportedAudioFileException // * @throws IOException // */ // public static OldWave create(final File file, final ProgressListener progressListener) throws FileDoesNotExistException, UnsupportedAudioFileException, IOException { // if (!file.exists()) { // throw new FileDoesNotExistException(); // } // // String s = file.getName(); // // /** // * Jeśli otwierany plik to mp3 to // */ // if (s.toLowerCase().endsWith(".mp3")) { // MP3Loader wave = null; // wave = new MP3Loader(); // wave.addListener(progressListener); // wave.file = file; // wave.load2(new FileInputStream(file)); // return wave; // } // // /** // * W innym wypadku mamy zwykłego wavea // */ // //System.out.println(file); // AudioInputStream ais = AudioSystem.getAudioInputStream(file); // AudioFormat format = ais.getFormat(); // OldWave wave = null; // // int channels = format.getChannels(); // int bitsPerSample = format.getSampleSizeInBits(); // // if (channels == 2) { // // stereo // if (bitsPerSample == 16) { // wave = new Wave16BitStereo(); // } else if (bitsPerSample == 8) { // wave = new Wave8BitStereo(); // } // } else if (channels == 1) { // // mono // if (bitsPerSample == 16) { // wave = new Wave16BitMono(); // } else if (bitsPerSample == 8) { // wave = new Wave8BitMono(); // } // } // wave.addListener(progressListener); // wave.file = file; // wave.format = format; // wave.load(ais); // return wave; // // } // // /** // * Otwiera plik do odczytu // * @param filePath Sciezka pliku do otwarcia // * @return Zwraca obiekt klasy Wave pozwalajacy odczytac plik. // * @throws FileDoesNotExistException // * @throws UnsupportedAudioFileException // * @throws IOException // */ // public static OldWave create(String filePath, ProgressFrame progressFrame) throws FileDoesNotExistException, UnsupportedAudioFileException, IOException { // return create(new File(filePath), progressFrame); // } // // /** // * // * @param format // * @param samples // * @return // */ // public static OldWave fromSamples(AudioFormat format, int[] samples) { // OldWave w = new OldWave() { // @Override // protected void load(AudioInputStream ais) throws FileDoesNotExistException, UnsupportedAudioFileException, IOException { // } // }; // // w.data = new int[1][0]; // w.data[0] = samples; // w.format = format; // return w; // } // // /** // * Metoda ladujaca plik. Laduje CALY plik do pamieci. // * @param file Plik do zaladowania // * @throws FileDoesNotExistException // * @throws UnsupportedAudioFileException // * @throws IOException // */ // protected abstract void load(AudioInputStream ais) throws FileDoesNotExistException, UnsupportedAudioFileException, IOException; // // /** // * // * @return Zwraca informacje o pliku // */ // public AudioFormat getAudioFormat() { // return format; // } // // /** // * Odczytuje probki. <br> // * UWAGA: Ta metoda kopiuje probki przy uzyciu petli FOR poniewaz // * wewnetrznie probki przechowywane sa w tablicy typu INT. To bardzo powolne. // * Zalecane jest uzycie wersji z tablica typu INT. // * @param channelNumber Numer kanalu. Dla dzwieku stereo kanal lewy - 0, kanal prawy - 1. // * @param output Bufor na odczytane dane. Metoda bedzie probowala odczytac // * tyle sampli ile bufor pomiesci. // * @param offset Od ktorego sampla chcemy zaczac czytac // * @return Zwraca ilosc przeczytanych sampli // */ //// public int read(int channelNumber, double[] output, int offset) { //// //// if(channelNumber >= format.getChannels()) //// throw new MissingChannelException(channelNumber); //// //// int samplesRead; ////// // czytamy sample dopoki nie skonczy sie jedna z tablic output lub data //// for(samplesRead=0; //// samplesRead < output.length && samplesRead+offset < data[channelNumber].length; //// samplesRead++ ) { //// //// output[samplesRead] = (double)data[channelNumber][samplesRead + offset]; //// } //// return samplesRead; //// } // /** // * Odczytuje probki. // * @param channelNumber Numer kanalu. Dla dzwieku stereo kanal lewy - 0, kanal prawy - 1. // * @param output Bufor na odczytane dane. Metoda bedzie probowala odczytac // * tyle sampli ile bufor pomiesci. // * @param offset Od ktorego sampla chcemy zaczac czytac // * @return Zwraca ilosc przeczytanych sampli // */ // public int read(int channelNumber, int[] output, int offset) { // if (channelNumber >= format.getChannels()) { // throw new MissingChannelException(channelNumber); // } // int samplesRead = Math.min(output.length, data[channelNumber].length - offset); // if (samplesRead <= 0) return 0; // // System.arraycopy(data[channelNumber], offset, output, 0, samplesRead); //// for(int i=0; i<samplesRead; i++) output[i]=data[channelNumber][i+offset]; // return samplesRead; // } // // public int readMono(int[] output, int offset) { // int samplesRead = Math.min(output.length, data[0].length - offset); // if (samplesRead <= 0) return 0; // // int channels = format.getChannels(); // for (int i = 0; i < samplesRead; ++i) { // output[i] = 0; // for (int c = 0; c < channels; ++c) { // output[i] += data[c][i + offset]; // } // } // return samplesRead; // } // // /** // * // * @return Zwraca ilosc probek dzwieku. // */ // public int getSampleCount() { // return data[0].length; // } // // /** // * @return Zwraca wartosc probki w danym miejscu // */ // public int getSample(int channel, int offset) { // return data[channel][offset]; // } // // public File getFile() { // return file; // } // // public void addListener(ProgressListener listener) { // if (listener == null) { // return; // } // listeners.add(listener); // } // // public void removeListener(ProgressListener listener) { // if (listener == null) { // return; // } // listeners.remove(listener); // } // // protected void notifyLoadingStarted() { // for (ProgressListener l : listeners) { // l.jobStarted(this); // } // } // // protected void notifyLoadingProgress(float progress) { // for (ProgressListener l : listeners) { // l.jobProgress(this, progress); // } // } // // protected void notifyLoadingFinished() { // for (ProgressListener l : listeners) { // l.jobFinished(this); // } // } }
ImareTeam/imare
src/pl/umk/mat/imare/io/OldWave.java
2,699
// * Zalecane jest uzycie wersji z tablica typu INT.
line_comment
pl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pl.umk.mat.imare.io; //import java.io.File; //import java.io.FileInputStream; //import java.io.IOException; //import java.util.LinkedList; //import javax.sound.sampled.AudioFormat; //import javax.sound.sampled.AudioInputStream; //import javax.sound.sampled.AudioSystem; //import javax.sound.sampled.UnsupportedAudioFileException; //import pl.umk.mat.imare.exception.FileDoesNotExistException; //import pl.umk.mat.imare.exception.MissingChannelException; //import pl.umk.mat.imare.gui.ProgressFrame; //import pl.umk.mat.imare.gui.related.ProgressListener; /** * Klasa pozwalajaca uzyskac dostep do pliku WAVE. * @author morti */ public abstract class OldWave { // // /** Informacje o pliku */ // protected AudioFormat format = null; // /** Dane pliku wave */ // protected int[][] data = null; // protected File file = null; // protected LinkedList<ProgressListener> listeners = new LinkedList<ProgressListener>(); // // /** // * Otwiera plik do odczytu // * @param file Plik do otwarcia // * @return Zwraca obiekt klasy Wave pozwalajacy odczytac plik. Moze zwrocic // * null jesli probka bedzie miala wiecej niz 2 kanaly lub bedzie miala // * liczbe bitow na probke inna niz 8 lub 16. // * @throws FileDoesNotExistException // * @throws UnsupportedAudioFileException // * @throws IOException // */ // public static OldWave create(final File file, final ProgressListener progressListener) throws FileDoesNotExistException, UnsupportedAudioFileException, IOException { // if (!file.exists()) { // throw new FileDoesNotExistException(); // } // // String s = file.getName(); // // /** // * Jeśli otwierany plik to mp3 to // */ // if (s.toLowerCase().endsWith(".mp3")) { // MP3Loader wave = null; // wave = new MP3Loader(); // wave.addListener(progressListener); // wave.file = file; // wave.load2(new FileInputStream(file)); // return wave; // } // // /** // * W innym wypadku mamy zwykłego wavea // */ // //System.out.println(file); // AudioInputStream ais = AudioSystem.getAudioInputStream(file); // AudioFormat format = ais.getFormat(); // OldWave wave = null; // // int channels = format.getChannels(); // int bitsPerSample = format.getSampleSizeInBits(); // // if (channels == 2) { // // stereo // if (bitsPerSample == 16) { // wave = new Wave16BitStereo(); // } else if (bitsPerSample == 8) { // wave = new Wave8BitStereo(); // } // } else if (channels == 1) { // // mono // if (bitsPerSample == 16) { // wave = new Wave16BitMono(); // } else if (bitsPerSample == 8) { // wave = new Wave8BitMono(); // } // } // wave.addListener(progressListener); // wave.file = file; // wave.format = format; // wave.load(ais); // return wave; // // } // // /** // * Otwiera plik do odczytu // * @param filePath Sciezka pliku do otwarcia // * @return Zwraca obiekt klasy Wave pozwalajacy odczytac plik. // * @throws FileDoesNotExistException // * @throws UnsupportedAudioFileException // * @throws IOException // */ // public static OldWave create(String filePath, ProgressFrame progressFrame) throws FileDoesNotExistException, UnsupportedAudioFileException, IOException { // return create(new File(filePath), progressFrame); // } // // /** // * // * @param format // * @param samples // * @return // */ // public static OldWave fromSamples(AudioFormat format, int[] samples) { // OldWave w = new OldWave() { // @Override // protected void load(AudioInputStream ais) throws FileDoesNotExistException, UnsupportedAudioFileException, IOException { // } // }; // // w.data = new int[1][0]; // w.data[0] = samples; // w.format = format; // return w; // } // // /** // * Metoda ladujaca plik. Laduje CALY plik do pamieci. // * @param file Plik do zaladowania // * @throws FileDoesNotExistException // * @throws UnsupportedAudioFileException // * @throws IOException // */ // protected abstract void load(AudioInputStream ais) throws FileDoesNotExistException, UnsupportedAudioFileException, IOException; // // /** // * // * @return Zwraca informacje o pliku // */ // public AudioFormat getAudioFormat() { // return format; // } // // /** // * Odczytuje probki. <br> // * UWAGA: Ta metoda kopiuje probki przy uzyciu petli FOR poniewaz // * wewnetrznie probki przechowywane sa w tablicy typu INT. To bardzo powolne. // * Zalecane jest <SUF> // * @param channelNumber Numer kanalu. Dla dzwieku stereo kanal lewy - 0, kanal prawy - 1. // * @param output Bufor na odczytane dane. Metoda bedzie probowala odczytac // * tyle sampli ile bufor pomiesci. // * @param offset Od ktorego sampla chcemy zaczac czytac // * @return Zwraca ilosc przeczytanych sampli // */ //// public int read(int channelNumber, double[] output, int offset) { //// //// if(channelNumber >= format.getChannels()) //// throw new MissingChannelException(channelNumber); //// //// int samplesRead; ////// // czytamy sample dopoki nie skonczy sie jedna z tablic output lub data //// for(samplesRead=0; //// samplesRead < output.length && samplesRead+offset < data[channelNumber].length; //// samplesRead++ ) { //// //// output[samplesRead] = (double)data[channelNumber][samplesRead + offset]; //// } //// return samplesRead; //// } // /** // * Odczytuje probki. // * @param channelNumber Numer kanalu. Dla dzwieku stereo kanal lewy - 0, kanal prawy - 1. // * @param output Bufor na odczytane dane. Metoda bedzie probowala odczytac // * tyle sampli ile bufor pomiesci. // * @param offset Od ktorego sampla chcemy zaczac czytac // * @return Zwraca ilosc przeczytanych sampli // */ // public int read(int channelNumber, int[] output, int offset) { // if (channelNumber >= format.getChannels()) { // throw new MissingChannelException(channelNumber); // } // int samplesRead = Math.min(output.length, data[channelNumber].length - offset); // if (samplesRead <= 0) return 0; // // System.arraycopy(data[channelNumber], offset, output, 0, samplesRead); //// for(int i=0; i<samplesRead; i++) output[i]=data[channelNumber][i+offset]; // return samplesRead; // } // // public int readMono(int[] output, int offset) { // int samplesRead = Math.min(output.length, data[0].length - offset); // if (samplesRead <= 0) return 0; // // int channels = format.getChannels(); // for (int i = 0; i < samplesRead; ++i) { // output[i] = 0; // for (int c = 0; c < channels; ++c) { // output[i] += data[c][i + offset]; // } // } // return samplesRead; // } // // /** // * // * @return Zwraca ilosc probek dzwieku. // */ // public int getSampleCount() { // return data[0].length; // } // // /** // * @return Zwraca wartosc probki w danym miejscu // */ // public int getSample(int channel, int offset) { // return data[channel][offset]; // } // // public File getFile() { // return file; // } // // public void addListener(ProgressListener listener) { // if (listener == null) { // return; // } // listeners.add(listener); // } // // public void removeListener(ProgressListener listener) { // if (listener == null) { // return; // } // listeners.remove(listener); // } // // protected void notifyLoadingStarted() { // for (ProgressListener l : listeners) { // l.jobStarted(this); // } // } // // protected void notifyLoadingProgress(float progress) { // for (ProgressListener l : listeners) { // l.jobProgress(this, progress); // } // } // // protected void notifyLoadingFinished() { // for (ProgressListener l : listeners) { // l.jobFinished(this); // } // } }
6203_5
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pl.umk.mat.imare.gui; import java.util.LinkedList; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.FloatControl; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import javax.swing.JOptionPane; import pl.umk.mat.imare.io.Wave; /** * * @author Tyczo */ public class Play implements Runnable { private boolean pause = false; private boolean playing = false; private LinkedList<PlayListener> listeners; private boolean stop = false; private SourceDataLine auline = null; private Wave wave = null; private int posStart, posEnd; private FloatControl volumeControl = null; @Override public void run() { AudioFormat fileFormat, bestFormat; DataLine.Info info; try { fileFormat = wave.getAudioFormat(); bestFormat = new AudioFormat(fileFormat.getSampleRate(), 16, fileFormat.getChannels(), true, false); info = new DataLine.Info(SourceDataLine.class, bestFormat); auline = (SourceDataLine) AudioSystem.getLine(info); auline.open(bestFormat); volumeControl = (FloatControl) auline.getControl(FloatControl.Type.MASTER_GAIN); for (PlayListener l : listeners) { l.setVolume(); } } catch (LineUnavailableException ex) { JOptionPane.showMessageDialog(null, "Urządzenie audio niedostępne.", "Błąd", JOptionPane.ERROR_MESSAGE); notifyFinished(); return; } // Tworzymy updater mowiacy o zmianie polozenia Runnable posUpdater = new Runnable() { @Override public void run() { int newPosition; while (!stop && (auline.getLongFramePosition() + posStart) < posEnd) { try { Thread.sleep(1); } catch (InterruptedException ex) { } if (pause) { continue; } newPosition = (int) auline.getLongFramePosition() + posStart; for (PlayListener l : listeners) { l.positionChanged(newPosition); } } notifyFinished(); } }; Thread updaterThread = new Thread(posUpdater); updaterThread.start(); auline.start(); // tworzymy sobie bufor do czytania pliku byte[] dataBuffer = new byte[8192]; int channels = bestFormat.getChannels(); int frameSize = 2*channels; int step = dataBuffer.length / frameSize; playing = true; try { int start = posStart; while (!stop && start < posEnd) { Thread.sleep(10); if (pause) { continue; } int bufUsed; if (auline.available() >= (bufUsed = Math.min((posEnd-start)*frameSize, dataBuffer.length))) { for (int bufPos = 0; bufPos < bufUsed; bufPos+=2) { int data = wave.getSample((bufPos>>1)%channels, start+bufPos/frameSize)/(1<<(Wave.MAX_BIT-16)) + 0x8000; dataBuffer[bufPos] = (byte)(data & 0xff); dataBuffer[bufPos+1] = (byte)(((data & 0xff00) >> 8) - 128); } auline.write(dataBuffer, 0, bufUsed); start += step; } } } catch (InterruptedException ex) { MainGUI.displayError(ex); } finally { notifyFinished(); } } public Play(Wave wave, int posStart, int posEnd) { this.wave = wave; this.posStart = posStart; this.posEnd = posEnd; this.listeners = new LinkedList<PlayListener>(); Thread watek = new Thread(this); watek.start(); } public void pause() { synchronized (this) { auline.stop(); } pause = true; } public synchronized void play() { pause = false; auline.start(); } public synchronized void stop() { stop = true; auline.stop(); auline.flush(); } public boolean isPlaying() { if (pause) { return false; } else { return playing; } } public void addPlayListener(PlayListener newListener) { listeners.add(newListener); } private void notifyFinished() { auline.drain(); auline.close(); playing = false; for (PlayListener l : listeners) { l.playingFinished(); } } public void setVolume(float value) { // getMaximum() zwraca wartość większą od zera, ale ustawienie // gain > 0 powoduje spłaszczanie sygnału double newVolume = volumeControl.getMinimum()*(1.0-value); volumeControl.setValue((float)newVolume); } }
ImareTeam/imare-lite
src/main/java/pl/umk/mat/imare/gui/Play.java
1,513
// gain > 0 powoduje spłaszczanie sygnału
line_comment
pl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pl.umk.mat.imare.gui; import java.util.LinkedList; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.FloatControl; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import javax.swing.JOptionPane; import pl.umk.mat.imare.io.Wave; /** * * @author Tyczo */ public class Play implements Runnable { private boolean pause = false; private boolean playing = false; private LinkedList<PlayListener> listeners; private boolean stop = false; private SourceDataLine auline = null; private Wave wave = null; private int posStart, posEnd; private FloatControl volumeControl = null; @Override public void run() { AudioFormat fileFormat, bestFormat; DataLine.Info info; try { fileFormat = wave.getAudioFormat(); bestFormat = new AudioFormat(fileFormat.getSampleRate(), 16, fileFormat.getChannels(), true, false); info = new DataLine.Info(SourceDataLine.class, bestFormat); auline = (SourceDataLine) AudioSystem.getLine(info); auline.open(bestFormat); volumeControl = (FloatControl) auline.getControl(FloatControl.Type.MASTER_GAIN); for (PlayListener l : listeners) { l.setVolume(); } } catch (LineUnavailableException ex) { JOptionPane.showMessageDialog(null, "Urządzenie audio niedostępne.", "Błąd", JOptionPane.ERROR_MESSAGE); notifyFinished(); return; } // Tworzymy updater mowiacy o zmianie polozenia Runnable posUpdater = new Runnable() { @Override public void run() { int newPosition; while (!stop && (auline.getLongFramePosition() + posStart) < posEnd) { try { Thread.sleep(1); } catch (InterruptedException ex) { } if (pause) { continue; } newPosition = (int) auline.getLongFramePosition() + posStart; for (PlayListener l : listeners) { l.positionChanged(newPosition); } } notifyFinished(); } }; Thread updaterThread = new Thread(posUpdater); updaterThread.start(); auline.start(); // tworzymy sobie bufor do czytania pliku byte[] dataBuffer = new byte[8192]; int channels = bestFormat.getChannels(); int frameSize = 2*channels; int step = dataBuffer.length / frameSize; playing = true; try { int start = posStart; while (!stop && start < posEnd) { Thread.sleep(10); if (pause) { continue; } int bufUsed; if (auline.available() >= (bufUsed = Math.min((posEnd-start)*frameSize, dataBuffer.length))) { for (int bufPos = 0; bufPos < bufUsed; bufPos+=2) { int data = wave.getSample((bufPos>>1)%channels, start+bufPos/frameSize)/(1<<(Wave.MAX_BIT-16)) + 0x8000; dataBuffer[bufPos] = (byte)(data & 0xff); dataBuffer[bufPos+1] = (byte)(((data & 0xff00) >> 8) - 128); } auline.write(dataBuffer, 0, bufUsed); start += step; } } } catch (InterruptedException ex) { MainGUI.displayError(ex); } finally { notifyFinished(); } } public Play(Wave wave, int posStart, int posEnd) { this.wave = wave; this.posStart = posStart; this.posEnd = posEnd; this.listeners = new LinkedList<PlayListener>(); Thread watek = new Thread(this); watek.start(); } public void pause() { synchronized (this) { auline.stop(); } pause = true; } public synchronized void play() { pause = false; auline.start(); } public synchronized void stop() { stop = true; auline.stop(); auline.flush(); } public boolean isPlaying() { if (pause) { return false; } else { return playing; } } public void addPlayListener(PlayListener newListener) { listeners.add(newListener); } private void notifyFinished() { auline.drain(); auline.close(); playing = false; for (PlayListener l : listeners) { l.playingFinished(); } } public void setVolume(float value) { // getMaximum() zwraca wartość większą od zera, ale ustawienie // gain > <SUF> double newVolume = volumeControl.getMinimum()*(1.0-value); volumeControl.setValue((float)newVolume); } }
5634_1
package mvc; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.DefaultCellEditor; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.plaf.ComponentUI; import javax.swing.table.TableCellRenderer; import checkbox_treetable.CheckBox; import checkbox_treetable.MenuBar; public class TreeTableUI extends ComponentUI { public static final String UI_CLASS_ID = "TreeTableUI"; private JTable table; private TreeTable treeTable; private JScrollPane scrollPane; private MenuBar menuBar; private ChangeListener changeListener; private MouseListener mouseAdapter; public static ComponentUI createUI(JComponent c) { return new TreeTableUI(); } public void installUI(JComponent c) { this.treeTable = (TreeTable) c; c.setLayout(new GridBagLayout()); installComponents(); installListeners(); } public void uninstallUI(JComponent c) { c.setLayout(null); uninstallListeners(); uninstallComponents(); this.treeTable = null; } protected void installComponents() { GridBagConstraints gc = new GridBagConstraints(); gc.gridx = 0; gc.gridy = 0; gc.weightx = 0.0; gc.weighty = 0.0; scrollPane = new JScrollPane(); menuBar = new MenuBar(); //Pierwszy wiersz gc.anchor = GridBagConstraints.FIRST_LINE_START; this.treeTable.add(menuBar,gc); gc.anchor = GridBagConstraints.FIRST_LINE_START; gc.weighty = 1.0; //Nastepny wiersz gc.gridy++; this.treeTable.add(scrollPane,gc); } protected void installListeners() { changeListener = new ChangeListener() { @Override public void stateChanged(ChangeEvent arg0) { TreeTableModel model = (TreeTableModel) arg0.getSource(); setData(model.getRowData(), model.getColumnNames()); treeTable.repaint(); } }; mouseAdapter = new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { int r = table.rowAtPoint(e.getPoint()); // wiersz gdzie zostalo klikniete int c = table.columnAtPoint(e.getPoint()); // kolumna gdzie zostalo klikniete JPopupMenu popup = createPopupMenu(); table.setCellSelectionEnabled(true); popup.show(e.getComponent(), e.getX(), e.getY()); } } }; this.treeTable.getModel().addChangeListener(changeListener); } private JPopupMenu createPopupMenu() { JPopupMenu popup = new JPopupMenu(); JMenuItem moveUpItem = new JMenuItem("Move up"); JMenuItem moveDownItem = new JMenuItem("Move down"); JMenuItem editItem = new JMenuItem("Edit"); popup.add(moveUpItem); popup.add(moveDownItem); popup.add(editItem); return popup; } protected void uninstallComponents() { scrollPane = null; menuBar = null; } protected void uninstallListeners() { this.treeTable.getModel().removeChangeListener(changeListener); changeListener = null; mouseAdapter = null; } public void paint(Graphics g, JComponent c) { super.paint(g, c); } public void setData(Object[][] rowData, Object[] columnNames) { table = new JTable(rowData, columnNames); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.getColumnModel().getColumn(0).setPreferredWidth(0); table.getColumnModel().getColumn(0).setCellRenderer(new CheckBoxRenderer()); table.getColumnModel().getColumn(0).setCellEditor(new CheckBoxEditor(new JCheckBox())); scrollPane.setViewportView(table); Dimension dim = new Dimension(); dim.height = table.getPreferredSize().height; dim.width = table.getPreferredSize().width + 20; scrollPane.setPreferredSize(dim); table.addMouseListener(mouseAdapter); } } class CheckBoxRenderer extends JLabel implements TableCellRenderer { private static final long serialVersionUID = 1L; public CheckBoxRenderer() { super.setOpaque(true); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { CheckBox c = (CheckBox) value; if (c != null) { if (c.getState() == 0) { this.setIcon(CheckBox.getIcon("empty")); } else if (c.getState() == 1) { this.setIcon(CheckBox.getIcon("half")); } else if (c.getState() == 2) { this.setIcon(CheckBox.getIcon("full")); } } return this; } } class CheckBoxEditor extends DefaultCellEditor { private static final long serialVersionUID = 1L; private CheckBox c; public CheckBoxEditor(JCheckBox checkBox) { super(checkBox); checkBox.setOpaque(true); } public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { c = (CheckBox) value; return this.getComponent(); } public Object getCellEditorValue() { c.changeState(); return c; } }
InvictaAnima/ProjektPZ
src/mvc/TreeTableUI.java
1,839
// kolumna gdzie zostalo klikniete
line_comment
pl
package mvc; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.DefaultCellEditor; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.plaf.ComponentUI; import javax.swing.table.TableCellRenderer; import checkbox_treetable.CheckBox; import checkbox_treetable.MenuBar; public class TreeTableUI extends ComponentUI { public static final String UI_CLASS_ID = "TreeTableUI"; private JTable table; private TreeTable treeTable; private JScrollPane scrollPane; private MenuBar menuBar; private ChangeListener changeListener; private MouseListener mouseAdapter; public static ComponentUI createUI(JComponent c) { return new TreeTableUI(); } public void installUI(JComponent c) { this.treeTable = (TreeTable) c; c.setLayout(new GridBagLayout()); installComponents(); installListeners(); } public void uninstallUI(JComponent c) { c.setLayout(null); uninstallListeners(); uninstallComponents(); this.treeTable = null; } protected void installComponents() { GridBagConstraints gc = new GridBagConstraints(); gc.gridx = 0; gc.gridy = 0; gc.weightx = 0.0; gc.weighty = 0.0; scrollPane = new JScrollPane(); menuBar = new MenuBar(); //Pierwszy wiersz gc.anchor = GridBagConstraints.FIRST_LINE_START; this.treeTable.add(menuBar,gc); gc.anchor = GridBagConstraints.FIRST_LINE_START; gc.weighty = 1.0; //Nastepny wiersz gc.gridy++; this.treeTable.add(scrollPane,gc); } protected void installListeners() { changeListener = new ChangeListener() { @Override public void stateChanged(ChangeEvent arg0) { TreeTableModel model = (TreeTableModel) arg0.getSource(); setData(model.getRowData(), model.getColumnNames()); treeTable.repaint(); } }; mouseAdapter = new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { int r = table.rowAtPoint(e.getPoint()); // wiersz gdzie zostalo klikniete int c = table.columnAtPoint(e.getPoint()); // kolumna gdzie <SUF> JPopupMenu popup = createPopupMenu(); table.setCellSelectionEnabled(true); popup.show(e.getComponent(), e.getX(), e.getY()); } } }; this.treeTable.getModel().addChangeListener(changeListener); } private JPopupMenu createPopupMenu() { JPopupMenu popup = new JPopupMenu(); JMenuItem moveUpItem = new JMenuItem("Move up"); JMenuItem moveDownItem = new JMenuItem("Move down"); JMenuItem editItem = new JMenuItem("Edit"); popup.add(moveUpItem); popup.add(moveDownItem); popup.add(editItem); return popup; } protected void uninstallComponents() { scrollPane = null; menuBar = null; } protected void uninstallListeners() { this.treeTable.getModel().removeChangeListener(changeListener); changeListener = null; mouseAdapter = null; } public void paint(Graphics g, JComponent c) { super.paint(g, c); } public void setData(Object[][] rowData, Object[] columnNames) { table = new JTable(rowData, columnNames); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.getColumnModel().getColumn(0).setPreferredWidth(0); table.getColumnModel().getColumn(0).setCellRenderer(new CheckBoxRenderer()); table.getColumnModel().getColumn(0).setCellEditor(new CheckBoxEditor(new JCheckBox())); scrollPane.setViewportView(table); Dimension dim = new Dimension(); dim.height = table.getPreferredSize().height; dim.width = table.getPreferredSize().width + 20; scrollPane.setPreferredSize(dim); table.addMouseListener(mouseAdapter); } } class CheckBoxRenderer extends JLabel implements TableCellRenderer { private static final long serialVersionUID = 1L; public CheckBoxRenderer() { super.setOpaque(true); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { CheckBox c = (CheckBox) value; if (c != null) { if (c.getState() == 0) { this.setIcon(CheckBox.getIcon("empty")); } else if (c.getState() == 1) { this.setIcon(CheckBox.getIcon("half")); } else if (c.getState() == 2) { this.setIcon(CheckBox.getIcon("full")); } } return this; } } class CheckBoxEditor extends DefaultCellEditor { private static final long serialVersionUID = 1L; private CheckBox c; public CheckBoxEditor(JCheckBox checkBox) { super(checkBox); checkBox.setOpaque(true); } public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { c = (CheckBox) value; return this.getComponent(); } public Object getCellEditorValue() { c.changeState(); return c; } }
3374_53
//jDownloader - Downloadmanager //Copyright (C) 2014 JD-Team support@jdownloader.org // //This program is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program. If not, see <http://www.gnu.org/licenses/>. package jd.plugins.hoster; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import jd.PluginWrapper; import jd.config.Property; import jd.gui.UserIO; import jd.http.Cookie; import jd.http.Cookies; import jd.nutils.encoding.Encoding; import jd.parser.html.Form; import jd.plugins.Account; import jd.plugins.Account.AccountError; import jd.plugins.AccountInfo; import jd.plugins.DownloadLink; import jd.plugins.DownloadLink.AvailableStatus; import jd.plugins.HostPlugin; import jd.plugins.LinkStatus; import jd.plugins.PluginException; import jd.plugins.PluginForHost; import jd.utils.JDUtilities; import org.appwork.utils.formatter.SizeFormatter; @HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://sharehost\\.eu/[^<>\"]*?/(.*)" }, flags = { 2 }) public class ShareHostEu extends PluginForHost { public ShareHostEu(PluginWrapper wrapper) { super(wrapper); this.enablePremium("http://sharehost.eu/premium.html"); // this.setConfigElements(); } @Override public String getAGBLink() { return "http://sharehost.eu/tos.html"; } private int MAXCHUNKSFORFREE = 1; private int MAXCHUNKSFORPREMIUM = 0; private String MAINPAGE = "http://sharehost.eu"; private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB"; private String FREE_DAILY_TRAFFIC_MAX = "10 GB"; private static Object LOCK = new Object(); @Override public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException { // API CALL: /fapi/fileInfo // Input: // url* - link URL (required) // filePassword - password for file (if exists) br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL()); // Output: // fileName - file name // filePath - file path // fileSize - file size in bytes // fileAvailable - true/false // fileDescription - file description // Errors: // emptyUrl // invalidUrl - wrong url format, too long or contauns invalid characters // fileNotFound // filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne String success = getJson("success"); if ("false".equals(success)) { String error = getJson("error"); if ("fileNotFound".equals(error)) { return AvailableStatus.FALSE; } else if ("emptyUrl".equals(error)) { return AvailableStatus.UNCHECKABLE; } else { return AvailableStatus.UNCHECKED; } } String fileName = getJson("fileName"); String filePath = getJson("filePath"); String fileSize = getJson("fileSize"); String fileAvailable = getJson("fileAvailable"); String fileDescription = getJson("fileDescription"); if ("false".equals(fileAvailable)) { downloadLink.setAvailable(false); } else { fileName = Encoding.htmlDecode(fileName.trim()); fileName = unescape(fileName); downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim())); downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize)); downloadLink.setAvailable(true); } if (!downloadLink.isAvailabilityStatusChecked()) { return AvailableStatus.UNCHECKED; } if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) { throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND); } return AvailableStatus.TRUE; } @Override public AccountInfo fetchAccountInfo(final Account account) throws Exception { AccountInfo ai = new AccountInfo(); String accountResponse; try { accountResponse = login(account, true); } catch (PluginException e) { String errorMessage = e.getErrorMessage(); if (errorMessage.contains("Maintenance")) { ai.setStatus(errorMessage); account.setError(AccountError.TEMP_DISABLED, errorMessage); } else { ai.setStatus(getPhrase("LOGIN_FAILED_NOT_PREMIUM")); UserIO.getInstance().requestMessageDialog(0, getPhrase("LOGIN_ERROR"), getPhrase("LOGIN_FAILED")); account.setValid(false); return ai; } account.setProperty("cookies", Property.NULL); return ai; } // API CALL: /fapi/userInfo // Input: // login* // pass* // Output: // userLogin - login // userEmail - e-mail // userIsPremium - true/false // userPremiumExpire - premium expire date // userTrafficToday - daily traffic left (bytes) // Errors: // emptyLoginOrPassword // userNotFound String userIsPremium = getJson(accountResponse, "userIsPremium"); String userPremiumExpire = getJson(accountResponse, "userPremiumExpire"); String userTrafficToday = getJson(accountResponse, "userTrafficToday"); long userTrafficLeft = Long.parseLong(userTrafficToday); ai.setTrafficLeft(userTrafficLeft); if ("true".equals(userIsPremium)) { ai.setProperty("premium", "true"); // ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX)); ai.setStatus(getPhrase("PREMIUM")); final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault()); Date date; try { date = dateFormat.parse(userPremiumExpire); ai.setValidUntil(date.getTime()); } catch (final Exception e) { logger.log(java.util.logging.Level.SEVERE, "Exception occurred", e); } } else { ai.setProperty("premium", "false"); // ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX)); ai.setStatus(getPhrase("FREE")); } account.setValid(true); return ai; } private String login(final Account account, final boolean force) throws Exception, PluginException { synchronized (LOCK) { try { br.setCookiesExclusive(true); final Object ret = account.getProperty("cookies", null); // API CALL: /fapi/userInfo // Input: // login* // pass* br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass())); // Output: // userLogin - login // userEmail - e-mail // userIsPremium - true/false // userPremiumExpire - premium expire date // userTrafficToday - daily traffic left (bytes) // Errors: // emptyLoginOrPassword // userNotFound String response = br.toString(); String success = getJson("success"); if ("false".equals(success)) { throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE); } if ("true".equals(getJson(response, "userIsPremium"))) { account.setProperty("premium", "true"); } else { account.setProperty("premium", "false"); } br.setFollowRedirects(true); br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass())); account.setProperty("name", Encoding.urlEncode(account.getUser())); account.setProperty("pass", Encoding.urlEncode(account.getPass())); /** Save cookies */ final HashMap<String, String> cookies = new HashMap<String, String>(); final Cookies add = this.br.getCookies(MAINPAGE); for (final Cookie c : add.getCookies()) { cookies.put(c.getKey(), c.getValue()); } account.setProperty("cookies", cookies); return response; } catch (final PluginException e) { account.setProperty("cookies", Property.NULL); throw e; } } } @Override public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException { requestFileInformation(downloadLink); doFree(downloadLink); } public void doFree(final DownloadLink downloadLink) throws Exception, PluginException { br.getPage(downloadLink.getDownloadURL()); setMainPage(downloadLink.getDownloadURL()); br.setCookiesExclusive(true); br.getHeaders().put("X-Requested-With", "XMLHttpRequest"); br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8"); br.setFollowRedirects(false); String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0); br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId); Form dlForm = br.getFormbyAction("http://sharehost.eu/"); String dllink = ""; for (int i = 0; i < 3; i++) { String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0); sleep(Long.parseLong(waitTime) * 1000l, downloadLink); String captchaId = br.getRegex("<img src='/\\?c=aut&amp;f=imageCaptcha&amp;id=(\\d+)' id='captcha_img'").getMatch(0); String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink); dlForm.put("cap_key", code); // br.submitForm(dlForm); br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code); if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) { throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l); } else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) { logger.info("wrong captcha"); } else { dllink = br.getRedirectLocation(); break; } } if (dllink == null) { throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l); } dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE); if (dl.getConnection().getContentType().contains("html")) { br.followConnection(); if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) { throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l); } else { throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT); } } dl.startDownload(); } void setLoginData(final Account account) throws Exception { br.getPage(MAINPAGE); br.setCookiesExclusive(true); final Object ret = account.getProperty("cookies", null); final HashMap<String, String> cookies = (HashMap<String, String>) ret; if (account.isValid()) { for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) { final String key = cookieEntry.getKey(); final String value = cookieEntry.getValue(); this.br.setCookie(MAINPAGE, key, value); } } } @Override public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception { String downloadUrl = downloadLink.getPluginPatternMatcher(); setMainPage(downloadUrl); br.setFollowRedirects(true); String loginInfo = login(account, false); boolean isPremium = "true".equals(account.getProperty("premium")); // long userTrafficleft; // try { // userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday")); // } catch (Exception e) { // userTrafficleft = 0; // } // if (isPremium || (!isPremium && userTrafficleft > 0)) { requestFileInformation(downloadLink); if (isPremium) { // API CALLS: /fapi/fileDownloadLink // INput: // login* - login użytkownika w serwisie // pass* - hasło użytkownika w serwisie // url* - adres URL pliku w dowolnym z formatów generowanych przez serwis // filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił) // Output: // fileUrlDownload (link valid for 24 hours) br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL()); // Errors // emptyLoginOrPassword - nie podano w parametrach loginu lub hasła // userNotFound - użytkownik nie istnieje lub podano błędne hasło // emptyUrl - nie podano w parametrach adresu URL pliku // invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi // fileNotFound - nie znaleziono pliku dla podanego adresu URL // filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne // userAccountNotPremium - konto użytkownika nie posiada dostępu premium // userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu) String success = getJson("success"); if ("false".equals(success)) { if ("userCanNotDownload".equals(getJson("error"))) { throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!"); } else if (("fileNotFound".equals(getJson("error")))) { throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND); } } String finalDownloadLink = getJson("fileUrlDownload"); setLoginData(account); String dllink = finalDownloadLink.replace("\\", ""); dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM); if (dl.getConnection().getContentType().contains("html")) { logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType()); br.followConnection(); logger.warning("br returns:" + br.toString()); throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT); } dl.startDownload(); } else { MAXCHUNKSFORPREMIUM = 1; setLoginData(account); handleFree(downloadLink); } } private static AtomicBoolean yt_loaded = new AtomicBoolean(false); private String unescape(final String s) { /* we have to make sure the youtube plugin is loaded */ if (!yt_loaded.getAndSet(true)) { JDUtilities.getPluginForHost("youtube.com"); } return jd.plugins.hoster.Youtube.unescape(s); } @Override public void reset() { } @Override public int getMaxSimultanFreeDownloadNum() { return 1; } @Override public void resetDownloadlink(final DownloadLink link) { } /* * * * Wrapper<br/> Tries to return value of key from JSon response, from default 'br' Browser. * * @author raztoki */ private String getJson(final String key) { return jd.plugins.hoster.K2SApi.JSonUtils.getJson(br.toString(), key); } private String getJson(final String source, final String key) { return jd.plugins.hoster.K2SApi.JSonUtils.getJson(source, key); } void setMainPage(String downloadUrl) { if (downloadUrl.contains("https://")) { MAINPAGE = "https://sharehost.eu"; } else { MAINPAGE = "http://sharehost.eu"; } } /* NO OVERRIDE!! We need to stay 0.9*compatible */ public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) { if (acc == null) { /* no account, yes we can expect captcha */ return true; } if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) { /* free accounts also have captchas */ return true; } if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) { /* free accounts also have captchas */ return true; } if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) { return true; } return false; } private HashMap<String, String> phrasesEN = new HashMap<String, String>() { { put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste."); put("PREMIUM", "Premium User"); put("FREE", "Free (Registered) User"); put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium"); put("LOGIN_ERROR", "ShareHost.Eu: Login Error"); put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!"); put("NO_TRAFFIC", "No traffic left"); put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes"); put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!"); put("NO_FREE_SLOTS", "No free slots for downloading this file"); } }; private HashMap<String, String> phrasesPL = new HashMap<String, String>() { { put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej."); put("PREMIUM", "Użytkownik Premium"); put("FREE", "Użytkownik zarejestrowany (darmowy)"); put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium"); put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania"); put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!"); put("NO_TRAFFIC", "Brak dostępnego transferu"); put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut"); put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!"); put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku"); } }; /** * Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and * English. * * @param key * @return */ private String getPhrase(String key) { if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) { return phrasesPL.get(key); } else if (phrasesEN.containsKey(key)) { return phrasesEN.get(key); } return "Translation not found!"; } }
Irbidan/jdownloader
src/jd/plugins/hoster/ShareHostEu.java
6,493
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
line_comment
pl
//jDownloader - Downloadmanager //Copyright (C) 2014 JD-Team support@jdownloader.org // //This program is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program. If not, see <http://www.gnu.org/licenses/>. package jd.plugins.hoster; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import jd.PluginWrapper; import jd.config.Property; import jd.gui.UserIO; import jd.http.Cookie; import jd.http.Cookies; import jd.nutils.encoding.Encoding; import jd.parser.html.Form; import jd.plugins.Account; import jd.plugins.Account.AccountError; import jd.plugins.AccountInfo; import jd.plugins.DownloadLink; import jd.plugins.DownloadLink.AvailableStatus; import jd.plugins.HostPlugin; import jd.plugins.LinkStatus; import jd.plugins.PluginException; import jd.plugins.PluginForHost; import jd.utils.JDUtilities; import org.appwork.utils.formatter.SizeFormatter; @HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://sharehost\\.eu/[^<>\"]*?/(.*)" }, flags = { 2 }) public class ShareHostEu extends PluginForHost { public ShareHostEu(PluginWrapper wrapper) { super(wrapper); this.enablePremium("http://sharehost.eu/premium.html"); // this.setConfigElements(); } @Override public String getAGBLink() { return "http://sharehost.eu/tos.html"; } private int MAXCHUNKSFORFREE = 1; private int MAXCHUNKSFORPREMIUM = 0; private String MAINPAGE = "http://sharehost.eu"; private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB"; private String FREE_DAILY_TRAFFIC_MAX = "10 GB"; private static Object LOCK = new Object(); @Override public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException { // API CALL: /fapi/fileInfo // Input: // url* - link URL (required) // filePassword - password for file (if exists) br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL()); // Output: // fileName - file name // filePath - file path // fileSize - file size in bytes // fileAvailable - true/false // fileDescription - file description // Errors: // emptyUrl // invalidUrl - wrong url format, too long or contauns invalid characters // fileNotFound // filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne String success = getJson("success"); if ("false".equals(success)) { String error = getJson("error"); if ("fileNotFound".equals(error)) { return AvailableStatus.FALSE; } else if ("emptyUrl".equals(error)) { return AvailableStatus.UNCHECKABLE; } else { return AvailableStatus.UNCHECKED; } } String fileName = getJson("fileName"); String filePath = getJson("filePath"); String fileSize = getJson("fileSize"); String fileAvailable = getJson("fileAvailable"); String fileDescription = getJson("fileDescription"); if ("false".equals(fileAvailable)) { downloadLink.setAvailable(false); } else { fileName = Encoding.htmlDecode(fileName.trim()); fileName = unescape(fileName); downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim())); downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize)); downloadLink.setAvailable(true); } if (!downloadLink.isAvailabilityStatusChecked()) { return AvailableStatus.UNCHECKED; } if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) { throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND); } return AvailableStatus.TRUE; } @Override public AccountInfo fetchAccountInfo(final Account account) throws Exception { AccountInfo ai = new AccountInfo(); String accountResponse; try { accountResponse = login(account, true); } catch (PluginException e) { String errorMessage = e.getErrorMessage(); if (errorMessage.contains("Maintenance")) { ai.setStatus(errorMessage); account.setError(AccountError.TEMP_DISABLED, errorMessage); } else { ai.setStatus(getPhrase("LOGIN_FAILED_NOT_PREMIUM")); UserIO.getInstance().requestMessageDialog(0, getPhrase("LOGIN_ERROR"), getPhrase("LOGIN_FAILED")); account.setValid(false); return ai; } account.setProperty("cookies", Property.NULL); return ai; } // API CALL: /fapi/userInfo // Input: // login* // pass* // Output: // userLogin - login // userEmail - e-mail // userIsPremium - true/false // userPremiumExpire - premium expire date // userTrafficToday - daily traffic left (bytes) // Errors: // emptyLoginOrPassword // userNotFound String userIsPremium = getJson(accountResponse, "userIsPremium"); String userPremiumExpire = getJson(accountResponse, "userPremiumExpire"); String userTrafficToday = getJson(accountResponse, "userTrafficToday"); long userTrafficLeft = Long.parseLong(userTrafficToday); ai.setTrafficLeft(userTrafficLeft); if ("true".equals(userIsPremium)) { ai.setProperty("premium", "true"); // ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX)); ai.setStatus(getPhrase("PREMIUM")); final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault()); Date date; try { date = dateFormat.parse(userPremiumExpire); ai.setValidUntil(date.getTime()); } catch (final Exception e) { logger.log(java.util.logging.Level.SEVERE, "Exception occurred", e); } } else { ai.setProperty("premium", "false"); // ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX)); ai.setStatus(getPhrase("FREE")); } account.setValid(true); return ai; } private String login(final Account account, final boolean force) throws Exception, PluginException { synchronized (LOCK) { try { br.setCookiesExclusive(true); final Object ret = account.getProperty("cookies", null); // API CALL: /fapi/userInfo // Input: // login* // pass* br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass())); // Output: // userLogin - login // userEmail - e-mail // userIsPremium - true/false // userPremiumExpire - premium expire date // userTrafficToday - daily traffic left (bytes) // Errors: // emptyLoginOrPassword // userNotFound String response = br.toString(); String success = getJson("success"); if ("false".equals(success)) { throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE); } if ("true".equals(getJson(response, "userIsPremium"))) { account.setProperty("premium", "true"); } else { account.setProperty("premium", "false"); } br.setFollowRedirects(true); br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass())); account.setProperty("name", Encoding.urlEncode(account.getUser())); account.setProperty("pass", Encoding.urlEncode(account.getPass())); /** Save cookies */ final HashMap<String, String> cookies = new HashMap<String, String>(); final Cookies add = this.br.getCookies(MAINPAGE); for (final Cookie c : add.getCookies()) { cookies.put(c.getKey(), c.getValue()); } account.setProperty("cookies", cookies); return response; } catch (final PluginException e) { account.setProperty("cookies", Property.NULL); throw e; } } } @Override public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException { requestFileInformation(downloadLink); doFree(downloadLink); } public void doFree(final DownloadLink downloadLink) throws Exception, PluginException { br.getPage(downloadLink.getDownloadURL()); setMainPage(downloadLink.getDownloadURL()); br.setCookiesExclusive(true); br.getHeaders().put("X-Requested-With", "XMLHttpRequest"); br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8"); br.setFollowRedirects(false); String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0); br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId); Form dlForm = br.getFormbyAction("http://sharehost.eu/"); String dllink = ""; for (int i = 0; i < 3; i++) { String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0); sleep(Long.parseLong(waitTime) * 1000l, downloadLink); String captchaId = br.getRegex("<img src='/\\?c=aut&amp;f=imageCaptcha&amp;id=(\\d+)' id='captcha_img'").getMatch(0); String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink); dlForm.put("cap_key", code); // br.submitForm(dlForm); br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code); if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) { throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l); } else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) { logger.info("wrong captcha"); } else { dllink = br.getRedirectLocation(); break; } } if (dllink == null) { throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l); } dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE); if (dl.getConnection().getContentType().contains("html")) { br.followConnection(); if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) { throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l); } else { throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT); } } dl.startDownload(); } void setLoginData(final Account account) throws Exception { br.getPage(MAINPAGE); br.setCookiesExclusive(true); final Object ret = account.getProperty("cookies", null); final HashMap<String, String> cookies = (HashMap<String, String>) ret; if (account.isValid()) { for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) { final String key = cookieEntry.getKey(); final String value = cookieEntry.getValue(); this.br.setCookie(MAINPAGE, key, value); } } } @Override public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception { String downloadUrl = downloadLink.getPluginPatternMatcher(); setMainPage(downloadUrl); br.setFollowRedirects(true); String loginInfo = login(account, false); boolean isPremium = "true".equals(account.getProperty("premium")); // long userTrafficleft; // try { // userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday")); // } catch (Exception e) { // userTrafficleft = 0; // } // if (isPremium || (!isPremium && userTrafficleft > 0)) { requestFileInformation(downloadLink); if (isPremium) { // API CALLS: /fapi/fileDownloadLink // INput: // login* - login użytkownika w serwisie // pass* - hasło użytkownika w serwisie // url* - adres URL pliku w dowolnym z formatów generowanych przez serwis // filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił) // Output: // fileUrlDownload (link valid for 24 hours) br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL()); // Errors // emptyLoginOrPassword - nie podano w parametrach loginu lub hasła // userNotFound - użytkownik nie istnieje lub podano błędne hasło // emptyUrl - nie podano w parametrach adresu URL pliku // invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi // fileNotFound - nie znaleziono pliku dla podanego adresu URL // filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne // userAccountNotPremium - <SUF> // userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu) String success = getJson("success"); if ("false".equals(success)) { if ("userCanNotDownload".equals(getJson("error"))) { throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!"); } else if (("fileNotFound".equals(getJson("error")))) { throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND); } } String finalDownloadLink = getJson("fileUrlDownload"); setLoginData(account); String dllink = finalDownloadLink.replace("\\", ""); dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM); if (dl.getConnection().getContentType().contains("html")) { logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType()); br.followConnection(); logger.warning("br returns:" + br.toString()); throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT); } dl.startDownload(); } else { MAXCHUNKSFORPREMIUM = 1; setLoginData(account); handleFree(downloadLink); } } private static AtomicBoolean yt_loaded = new AtomicBoolean(false); private String unescape(final String s) { /* we have to make sure the youtube plugin is loaded */ if (!yt_loaded.getAndSet(true)) { JDUtilities.getPluginForHost("youtube.com"); } return jd.plugins.hoster.Youtube.unescape(s); } @Override public void reset() { } @Override public int getMaxSimultanFreeDownloadNum() { return 1; } @Override public void resetDownloadlink(final DownloadLink link) { } /* * * * Wrapper<br/> Tries to return value of key from JSon response, from default 'br' Browser. * * @author raztoki */ private String getJson(final String key) { return jd.plugins.hoster.K2SApi.JSonUtils.getJson(br.toString(), key); } private String getJson(final String source, final String key) { return jd.plugins.hoster.K2SApi.JSonUtils.getJson(source, key); } void setMainPage(String downloadUrl) { if (downloadUrl.contains("https://")) { MAINPAGE = "https://sharehost.eu"; } else { MAINPAGE = "http://sharehost.eu"; } } /* NO OVERRIDE!! We need to stay 0.9*compatible */ public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) { if (acc == null) { /* no account, yes we can expect captcha */ return true; } if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) { /* free accounts also have captchas */ return true; } if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) { /* free accounts also have captchas */ return true; } if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) { return true; } return false; } private HashMap<String, String> phrasesEN = new HashMap<String, String>() { { put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste."); put("PREMIUM", "Premium User"); put("FREE", "Free (Registered) User"); put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium"); put("LOGIN_ERROR", "ShareHost.Eu: Login Error"); put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!"); put("NO_TRAFFIC", "No traffic left"); put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes"); put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!"); put("NO_FREE_SLOTS", "No free slots for downloading this file"); } }; private HashMap<String, String> phrasesPL = new HashMap<String, String>() { { put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej."); put("PREMIUM", "Użytkownik Premium"); put("FREE", "Użytkownik zarejestrowany (darmowy)"); put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium"); put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania"); put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!"); put("NO_TRAFFIC", "Brak dostępnego transferu"); put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut"); put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!"); put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku"); } }; /** * Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and * English. * * @param key * @return */ private String getPhrase(String key) { if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) { return phrasesPL.get(key); } else if (phrasesEN.containsKey(key)) { return phrasesEN.get(key); } return "Translation not found!"; } }
2776_2
package chess_server_package; /** * Enum chess_server_package.MessType zawiera wszystkie rodzaje wiadomości jakie może otrzymać użytkownik z serwera. */ public enum MessType { /** * wiadomość systemowa */ SYSTEM_MESSAGE, /** * wiadomość od przeciwnika */ OPPONENT_MESSAGE, /** * przeciwnik wykonał ruch */ MOVE, /** * przeciwnik potwierdził zaproszenie do gry */ CONFIRM, /** * przeciwnik odrzucił zaproszenie do gry */ REJECT, /** * zaproszony */ INVITED, /** * gra się zakończyła */ GAME_ENDED }
Isdre/Chessmageddon
src/chess_server_package/MessType.java
242
/** * wiadomość od przeciwnika */
block_comment
pl
package chess_server_package; /** * Enum chess_server_package.MessType zawiera wszystkie rodzaje wiadomości jakie może otrzymać użytkownik z serwera. */ public enum MessType { /** * wiadomość systemowa */ SYSTEM_MESSAGE, /** * wiadomość od przeciwnika <SUF>*/ OPPONENT_MESSAGE, /** * przeciwnik wykonał ruch */ MOVE, /** * przeciwnik potwierdził zaproszenie do gry */ CONFIRM, /** * przeciwnik odrzucił zaproszenie do gry */ REJECT, /** * zaproszony */ INVITED, /** * gra się zakończyła */ GAME_ENDED }
5181_5
import java.util.Arrays; import java.util.Random; public class School_Excercice_Objective_language_Learning { public static void main(String[] args) { System.out.println("Test obszernego zadania dodatkowego czas zacząć!\n"); System.out.println("Test klasy nr 1 - Dron"); System.out.println("Tworzymy 2 drony."); Zad_Dfeo_1.Drone drone1 = new Zad_Dfeo_1.Drone("Orion", 500, 600, 2430); Zad_Dfeo_1.Drone drone2 = new Zad_Dfeo_1.Drone("Andromeda", 350, 700, 1570); System.out.println("Każdy ma unikalne id."); System.out.println("Id drona numer 2:"); drone2.showId(); System.out.println("Id drona numer 1:"); drone1.showId(); System.out.println("Przentacja działania funkcji:"); System.out.println(drone2.checkFlyParameters()); drone2.fly(200); drone2.revEngine(); System.out.println(drone2); System.out.println("\nTest klasy nr 2 - RacingDrone"); System.out.println("Tworzymy 4 drony."); Zad_Dfeo_1.RacingDrone racingDrone1 = new Zad_Dfeo_1.RacingDrone("Lacerta", 700, 900, 220, "Zieloni", 4); Zad_Dfeo_1.RacingDrone racingDrone2 = new Zad_Dfeo_1.RacingDrone("Volans", 5050, 6000, 7430, "Czerwoni", 2); Zad_Dfeo_1.RacingDrone racingDrone3 = new Zad_Dfeo_1.RacingDrone("Cetus", 509, 630, 27, "Zieloni", 3); Zad_Dfeo_1.RacingDrone racingDrone4 = new Zad_Dfeo_1.RacingDrone("Copricorn", 800, 400, 930, "Czerwoni", 1); System.out.println("Przentacja działania funkcji:"); Zad_Dfeo_1.RacingDrone[] racers = {racingDrone1, racingDrone2, racingDrone3, racingDrone4}; System.out.println("Najszybszy dron to: " + Zad_Dfeo_1.RacingDrone.race(racers)); racingDrone2.revEngine(); System.out.println(Arrays.toString(Zad_Dfeo_1.RacingDrone.sortByPosition(racers))); System.out.println(racingDrone2); System.out.println("\nTest klasy nr 3 - RacingDrone"); System.out.println("Tworzymy 2 drony."); Zad_Dfeo_1.VampireDrone vampireDrone1 = new Zad_Dfeo_1.VampireDrone("Sirius", 7000, 9000, 2720, false); Zad_Dfeo_1.VampireDrone vampireDrone2 = new Zad_Dfeo_1.VampireDrone("Vega", 50, 900, 730, true); System.out.println("Przentacja działania funkcji:"); vampireDrone1.drainEnergy(racingDrone2); vampireDrone1.TurnIntoBatDrone(); vampireDrone1.TurnIntoBatDrone(); vampireDrone1.drainEnergy(racingDrone2); vampireDrone2.TurnIntoDrone(); vampireDrone2.TurnIntoDrone(); System.out.println(vampireDrone1); System.out.println("\nTest klasy nr 4 i 5 - ChristmasDrone i Gift"); System.out.println("Tworzymy drona."); Zad_Dfeo_1.Gift gift1 = new Zad_Dfeo_1.Gift("Piłka", 0.20); Zad_Dfeo_1.ChristmasDrone christmasDrone1 = new Zad_Dfeo_1.ChristmasDrone("Baltasar", 700, 2000, 820, gift1); System.out.println("Przentacja działania funkcji:"); gift1.prepere(); gift1.unpack(); System.out.println(gift1); christmasDrone1.deliverGift(); System.out.println(christmasDrone1); System.out.println("\nTest klasy nr 6 - DroneControleRoom"); System.out.println("Tworzymy obiekt."); Zad_Dfeo_1.DroneControlRoom droneControlRoom1 = new Zad_Dfeo_1.DroneControlRoom(); System.out.println("Przentacja działania funkcji:"); droneControlRoom1.addNewDrone(drone1); droneControlRoom1.addNewDrone(drone2); droneControlRoom1.addNewDrone(vampireDrone2); droneControlRoom1.addNewDrone(christmasDrone1); droneControlRoom1.addNewDrone(racingDrone3); droneControlRoom1.addNewDrone(racingDrone2); droneControlRoom1.chargeAllDrones(); System.out.println("Tyle dronów może latać: " + droneControlRoom1.countDronesThatCanFly()); droneControlRoom1.sortAllDrones(); System.out.println("Najsilniejszy silnik ma dron: " + droneControlRoom1.findMostPowerful()); System.out.println("\nTest klasy nr 7 (autorskiej) - KillerDrone"); System.out.println("Tworzymy obiekt."); Zad_Dfeo_1.KillerDrone killerDrone1 = new Zad_Dfeo_1.KillerDrone("Iscariota", 900, 2000, 520, "Sierp"); System.out.println("Przentacja działania funkcji:"); killerDrone1.kill(drone1); killerDrone1.kill(racingDrone4); killerDrone1.checkWantedPoster(); System.out.println(killerDrone1.playWithPolice(1) + " to liczba policjantów, którzy w dzisiejszym dniu brali udział w pościgu."); System.out.println(killerDrone1); System.out.println("\n\nDziękuję za uwagę!"); } public static class Drone{ int uniqueId; static int Id; String name; double weight; // Podana w g double enginePower; // Podana w W double batteryLevel; // Podana w mAh Drone(String name, double weight, double enginePower, double batteryLevel) { this.name = name; this.weight = weight; this.enginePower = enginePower; this.batteryLevel = batteryLevel; Id++; uniqueId = Id; } void showId() { System.out.println(this.uniqueId); } public boolean checkFlyParameters() { return this.enginePower > this.weight && this.batteryLevel > 0; } public void fly(double distance /* Podany w metrach */) { if (this.batteryLevel >= distance / 10 /* Zakładamy, że 1 mAh wystarcza na 10 metrów lotu */ ) { System.out.println("Let's fly!"); } else { System.out.println("Battery level too low!"); } } public void revEngine() { for (int i = 0; i < (int) (this.enginePower / this.weight); i++) { System.out.println("Vroom"); } } @Override public String toString() { return "RacingDrone{" + "name='" + name + '\'' + ", weight=" + weight + ", enginePower=" + enginePower + ", batteryLevel=" + batteryLevel + '\'' + '}'; } } public static class RacingDrone extends Zad_Dfeo_1.Drone { String racingTeam; int positionInRanking; RacingDrone(String name, double weight, double enginePower, double batteryLevel, String racingTeam, int positionInRanking) { super(name, weight, enginePower, batteryLevel); this.positionInRanking = positionInRanking; this.racingTeam = racingTeam; } public static Zad_Dfeo_1.Drone race(Zad_Dfeo_1.Drone[] racers) { Zad_Dfeo_1.Drone fastestDrone = racers[0]; for (int i = 1; i < racers.length; i++) { if (racers[i].enginePower > fastestDrone.enginePower) { fastestDrone = racers[i]; } } return fastestDrone; } public void revEngine() { super.revEngine(); System.out.println("ZOOOOOM"); } public static Zad_Dfeo_1.RacingDrone[] sortByPosition(Zad_Dfeo_1.RacingDrone[] racers) { for (int j = 0; j < racers.length; j++){ for (int i = 0; i < racers.length - 1; i++) if (racers[i].positionInRanking > racers[i + 1].positionInRanking) { Zad_Dfeo_1.RacingDrone temp = racers[i]; racers[i] = racers[i + 1]; racers[i + 1] = temp; } else if (racers[i].positionInRanking == racers[i + 1].positionInRanking) { if (racers[i].enginePower > racers[i + 1].enginePower) { Zad_Dfeo_1.RacingDrone temp = racers[i]; racers[i] = racers[i + 1]; racers[i + 1] = temp; } } } return racers; } @Override public String toString() { return "RacingDrone{" + "name='" + name + '\'' + ", weight=" + weight + ", enginePower=" + enginePower + ", batteryLevel=" + batteryLevel + '\'' + ", racingTeam='" + racingTeam + ", positionInRanking='" + positionInRanking + '}'; } } public static class VampireDrone extends Zad_Dfeo_1.Drone { static String constructor = "Bram Stoker"; boolean isTransformed = false; // W zadaniu jest isDoneBat, ale później występuje jako isTransformed, więc zostawiam tę opcję // Mam nadzieję, że rozumiem ten zamysł poprawnie i niczego nie pomijam VampireDrone(String name, double weight, double enginePower, double batteryLevel, boolean isTransformed) { super(name, weight, enginePower, batteryLevel); this.isTransformed = isTransformed; } public void drainEnergy(Zad_Dfeo_1.Drone drone) { // Z tego co rozumiem z zadania, to jeśli isTransformed jest false, to dron otrzymuje funkcje wampiryczne, ale zostawiłęm to u mnie, że jeśli jest true to ma te funkcjie dla jaśniejszej czytelności z mojej strony przy pisaniu if (this.isTransformed) { this.batteryLevel = this.batteryLevel + (drone.batteryLevel / 2); drone.batteryLevel = drone.batteryLevel / 2; } else { System.out.println("W formie drona nie można wysysać energii."); } } public void TurnIntoBatDrone() { if (!this.isTransformed) { System.out.println("Od teraz to ja jestem władcą nocy!"); this.isTransformed = true; this.weight = this.weight / 2; this.batteryLevel = this.batteryLevel / 2; } else { System.out.println("Już jestem władcą nocy."); } } public void TurnIntoDrone() { // Dodałem od siebie funkcję powrotu do normalnego stanu if (this.isTransformed) { System.out.println("Powrót do formy słabeusza!"); this.weight = this.weight * 2; this.batteryLevel = this.batteryLevel * 1.5; this.isTransformed = false; } else { System.out.println("Już jestem słaby, bardziej nie mogę."); } } @Override public String toString() { return "VampireDrone{" + "name='" + name + '\'' + ", weight=" + weight + ", enginePower=" + enginePower + ", batteryLevel=" + batteryLevel + '\'' + ", isTransformed='" + isTransformed + '}'; } } public static class ChristmasDrone extends Zad_Dfeo_1.Drone { Zad_Dfeo_1.Gift gift; ChristmasDrone(String name, double weight, double enginePower, double batteryLevel, Zad_Dfeo_1.Gift gift) { super(name, weight, enginePower, batteryLevel); this.gift = gift; } public void deliverGift() { if (this.gift.weight + this.weight > this.enginePower) { System.out.println("Paczka jest zbyt ciężka żeby ją dostarczyć."); } else if (this.gift == null) { System.out.println("Nie ma żadnej paczki do dostarczenia."); } else { System.out.println("Dostarczono paczkę o wadze " + this.gift.weight + "g."); this.gift = null; } } @Override public String toString() { return "ChristmasDrone{" + "name='" + name + '\'' + ", weight=" + weight + ", enginePower=" + enginePower + ", batteryLevel=" + batteryLevel + '\'' + ", gift='" + gift + '}'; } } public static class Gift { String nameOfContent; double weight; boolean isReadyToBeDelivered = false; Gift(String nameOfContent, double weight) { this.nameOfContent = nameOfContent; this.weight = weight; } public void prepere() { this.isReadyToBeDelivered = true; } public void unpack() { this.isReadyToBeDelivered = false; System.out.println("W paczce znajduje się " + this.nameOfContent + "!"); } @Override public String toString() { return "Gift{" + "nameOfContent='" + nameOfContent + '\'' + ", weight=" + weight + '}'; } } public static class DroneControlRoom{ Zad_Dfeo_1.Drone[] allDrones; static double windPowerOutside = 3; DroneControlRoom() { this.allDrones = new Zad_Dfeo_1.Drone[1]; } public int countDronesThatCanFly() { getOutNulls(); int count = 0; for (Zad_Dfeo_1.Drone drone: this.allDrones) { if (drone.enginePower > drone.weight && drone.batteryLevel > 0) { count++; } } return count; } public void chargeAllDrones() { getOutNulls(); for (Zad_Dfeo_1.Drone drone: this.allDrones) { drone.batteryLevel += 20; } } public void addNewDrone(Zad_Dfeo_1.Drone drone) { Zad_Dfeo_1.Drone[] newAllDrones = new Zad_Dfeo_1.Drone[allDrones.length + 1]; for (int i = 0; i < allDrones.length; i++) { newAllDrones[i] = allDrones[i]; } allDrones = newAllDrones; allDrones[allDrones.length - 1] = drone; } public void sortAllDrones() { getOutNulls(); for (int i = 0; i < allDrones.length; i++) { for (int j = 0; j < allDrones.length - 1; j++) { if (allDrones[j].weight > allDrones[j + 1].weight) { double temp = allDrones[j + 1].weight; allDrones[j + 1].weight = allDrones[j].weight; allDrones[j].weight = temp; } } } System.out.print(" Lista dronów posortowana po wadze (rosnąco): "); for (Zad_Dfeo_1.Drone drone: allDrones) { System.out.print(drone + ", "); } } public void getOutNulls() { int counter = 0; for (int j = 0; j < allDrones.length; j++) { if (allDrones[j] != null) { counter++; } } Zad_Dfeo_1.Drone[] newList = new Zad_Dfeo_1.Drone[counter]; int counter2 = 0; for (int j = 0; j < allDrones.length; j++) { if (allDrones[j] != null) { newList[counter2] = allDrones[j]; counter2++; } } allDrones = newList; } public Zad_Dfeo_1.Drone findMostPowerful(){ getOutNulls(); return findMostPowerful(0, allDrones[0]); } public Zad_Dfeo_1.Drone findMostPowerful(int currentIndex, Zad_Dfeo_1.Drone currentMostPowerful) { if (currentIndex == allDrones.length) { return currentMostPowerful; } if (allDrones[currentIndex].enginePower > currentMostPowerful.enginePower) { currentMostPowerful = allDrones[currentIndex]; } return findMostPowerful(currentIndex + 1, currentMostPowerful); } @Override public String toString() { return "DroneControlRoom{" + "allDrones='" + Arrays.toString(allDrones) + '}'; } } // Inwencja twórcza public static class KillerDrone extends Zad_Dfeo_1.Drone { int killCounter; String weapon; int reward; KillerDrone(String name, double weight, double enginePower, double batteryLevel, String weapon) { super(name, weight, enginePower, batteryLevel); this.weapon = weapon; } public void kill(Zad_Dfeo_1.Drone drone) { System.out.println(drone.name + " został zabity przy pomocy " + this.weapon + "!"); drone = null; this.killCounter++; reward += 10000; } public void checkWantedPoster() { System.out.println("Obecna nagroda za głowę " + this.name + " wynosi " + this.reward + "."); } public int playWithPolice(int policeInPursuit) { if (policeInPursuit > 20) { System.out.println(this.name + " został schwytany!"); return policeInPursuit; } else if (policeInPursuit > 14) { System.out.println(this.name + " znów zabawił się z policją i uciekł!"); return policeInPursuit; } else { Random random = new Random(); return playWithPolice(policeInPursuit + random.nextInt(10)); } } @Override public String toString() { return "KillerDrone{" + "name='" + name + '\'' + ", weight=" + weight + ", enginePower=" + enginePower + ", batteryLevel=" + batteryLevel + '\'' + ", weapon='" + weapon + '}'; } } }
Isimis/Personal_Learning_Projects
School_Excercice_Objective_language_Learning.java
5,999
// W zadaniu jest isDoneBat, ale później występuje jako isTransformed, więc zostawiam tę opcję
line_comment
pl
import java.util.Arrays; import java.util.Random; public class School_Excercice_Objective_language_Learning { public static void main(String[] args) { System.out.println("Test obszernego zadania dodatkowego czas zacząć!\n"); System.out.println("Test klasy nr 1 - Dron"); System.out.println("Tworzymy 2 drony."); Zad_Dfeo_1.Drone drone1 = new Zad_Dfeo_1.Drone("Orion", 500, 600, 2430); Zad_Dfeo_1.Drone drone2 = new Zad_Dfeo_1.Drone("Andromeda", 350, 700, 1570); System.out.println("Każdy ma unikalne id."); System.out.println("Id drona numer 2:"); drone2.showId(); System.out.println("Id drona numer 1:"); drone1.showId(); System.out.println("Przentacja działania funkcji:"); System.out.println(drone2.checkFlyParameters()); drone2.fly(200); drone2.revEngine(); System.out.println(drone2); System.out.println("\nTest klasy nr 2 - RacingDrone"); System.out.println("Tworzymy 4 drony."); Zad_Dfeo_1.RacingDrone racingDrone1 = new Zad_Dfeo_1.RacingDrone("Lacerta", 700, 900, 220, "Zieloni", 4); Zad_Dfeo_1.RacingDrone racingDrone2 = new Zad_Dfeo_1.RacingDrone("Volans", 5050, 6000, 7430, "Czerwoni", 2); Zad_Dfeo_1.RacingDrone racingDrone3 = new Zad_Dfeo_1.RacingDrone("Cetus", 509, 630, 27, "Zieloni", 3); Zad_Dfeo_1.RacingDrone racingDrone4 = new Zad_Dfeo_1.RacingDrone("Copricorn", 800, 400, 930, "Czerwoni", 1); System.out.println("Przentacja działania funkcji:"); Zad_Dfeo_1.RacingDrone[] racers = {racingDrone1, racingDrone2, racingDrone3, racingDrone4}; System.out.println("Najszybszy dron to: " + Zad_Dfeo_1.RacingDrone.race(racers)); racingDrone2.revEngine(); System.out.println(Arrays.toString(Zad_Dfeo_1.RacingDrone.sortByPosition(racers))); System.out.println(racingDrone2); System.out.println("\nTest klasy nr 3 - RacingDrone"); System.out.println("Tworzymy 2 drony."); Zad_Dfeo_1.VampireDrone vampireDrone1 = new Zad_Dfeo_1.VampireDrone("Sirius", 7000, 9000, 2720, false); Zad_Dfeo_1.VampireDrone vampireDrone2 = new Zad_Dfeo_1.VampireDrone("Vega", 50, 900, 730, true); System.out.println("Przentacja działania funkcji:"); vampireDrone1.drainEnergy(racingDrone2); vampireDrone1.TurnIntoBatDrone(); vampireDrone1.TurnIntoBatDrone(); vampireDrone1.drainEnergy(racingDrone2); vampireDrone2.TurnIntoDrone(); vampireDrone2.TurnIntoDrone(); System.out.println(vampireDrone1); System.out.println("\nTest klasy nr 4 i 5 - ChristmasDrone i Gift"); System.out.println("Tworzymy drona."); Zad_Dfeo_1.Gift gift1 = new Zad_Dfeo_1.Gift("Piłka", 0.20); Zad_Dfeo_1.ChristmasDrone christmasDrone1 = new Zad_Dfeo_1.ChristmasDrone("Baltasar", 700, 2000, 820, gift1); System.out.println("Przentacja działania funkcji:"); gift1.prepere(); gift1.unpack(); System.out.println(gift1); christmasDrone1.deliverGift(); System.out.println(christmasDrone1); System.out.println("\nTest klasy nr 6 - DroneControleRoom"); System.out.println("Tworzymy obiekt."); Zad_Dfeo_1.DroneControlRoom droneControlRoom1 = new Zad_Dfeo_1.DroneControlRoom(); System.out.println("Przentacja działania funkcji:"); droneControlRoom1.addNewDrone(drone1); droneControlRoom1.addNewDrone(drone2); droneControlRoom1.addNewDrone(vampireDrone2); droneControlRoom1.addNewDrone(christmasDrone1); droneControlRoom1.addNewDrone(racingDrone3); droneControlRoom1.addNewDrone(racingDrone2); droneControlRoom1.chargeAllDrones(); System.out.println("Tyle dronów może latać: " + droneControlRoom1.countDronesThatCanFly()); droneControlRoom1.sortAllDrones(); System.out.println("Najsilniejszy silnik ma dron: " + droneControlRoom1.findMostPowerful()); System.out.println("\nTest klasy nr 7 (autorskiej) - KillerDrone"); System.out.println("Tworzymy obiekt."); Zad_Dfeo_1.KillerDrone killerDrone1 = new Zad_Dfeo_1.KillerDrone("Iscariota", 900, 2000, 520, "Sierp"); System.out.println("Przentacja działania funkcji:"); killerDrone1.kill(drone1); killerDrone1.kill(racingDrone4); killerDrone1.checkWantedPoster(); System.out.println(killerDrone1.playWithPolice(1) + " to liczba policjantów, którzy w dzisiejszym dniu brali udział w pościgu."); System.out.println(killerDrone1); System.out.println("\n\nDziękuję za uwagę!"); } public static class Drone{ int uniqueId; static int Id; String name; double weight; // Podana w g double enginePower; // Podana w W double batteryLevel; // Podana w mAh Drone(String name, double weight, double enginePower, double batteryLevel) { this.name = name; this.weight = weight; this.enginePower = enginePower; this.batteryLevel = batteryLevel; Id++; uniqueId = Id; } void showId() { System.out.println(this.uniqueId); } public boolean checkFlyParameters() { return this.enginePower > this.weight && this.batteryLevel > 0; } public void fly(double distance /* Podany w metrach */) { if (this.batteryLevel >= distance / 10 /* Zakładamy, że 1 mAh wystarcza na 10 metrów lotu */ ) { System.out.println("Let's fly!"); } else { System.out.println("Battery level too low!"); } } public void revEngine() { for (int i = 0; i < (int) (this.enginePower / this.weight); i++) { System.out.println("Vroom"); } } @Override public String toString() { return "RacingDrone{" + "name='" + name + '\'' + ", weight=" + weight + ", enginePower=" + enginePower + ", batteryLevel=" + batteryLevel + '\'' + '}'; } } public static class RacingDrone extends Zad_Dfeo_1.Drone { String racingTeam; int positionInRanking; RacingDrone(String name, double weight, double enginePower, double batteryLevel, String racingTeam, int positionInRanking) { super(name, weight, enginePower, batteryLevel); this.positionInRanking = positionInRanking; this.racingTeam = racingTeam; } public static Zad_Dfeo_1.Drone race(Zad_Dfeo_1.Drone[] racers) { Zad_Dfeo_1.Drone fastestDrone = racers[0]; for (int i = 1; i < racers.length; i++) { if (racers[i].enginePower > fastestDrone.enginePower) { fastestDrone = racers[i]; } } return fastestDrone; } public void revEngine() { super.revEngine(); System.out.println("ZOOOOOM"); } public static Zad_Dfeo_1.RacingDrone[] sortByPosition(Zad_Dfeo_1.RacingDrone[] racers) { for (int j = 0; j < racers.length; j++){ for (int i = 0; i < racers.length - 1; i++) if (racers[i].positionInRanking > racers[i + 1].positionInRanking) { Zad_Dfeo_1.RacingDrone temp = racers[i]; racers[i] = racers[i + 1]; racers[i + 1] = temp; } else if (racers[i].positionInRanking == racers[i + 1].positionInRanking) { if (racers[i].enginePower > racers[i + 1].enginePower) { Zad_Dfeo_1.RacingDrone temp = racers[i]; racers[i] = racers[i + 1]; racers[i + 1] = temp; } } } return racers; } @Override public String toString() { return "RacingDrone{" + "name='" + name + '\'' + ", weight=" + weight + ", enginePower=" + enginePower + ", batteryLevel=" + batteryLevel + '\'' + ", racingTeam='" + racingTeam + ", positionInRanking='" + positionInRanking + '}'; } } public static class VampireDrone extends Zad_Dfeo_1.Drone { static String constructor = "Bram Stoker"; boolean isTransformed = false; // W zadaniu <SUF> // Mam nadzieję, że rozumiem ten zamysł poprawnie i niczego nie pomijam VampireDrone(String name, double weight, double enginePower, double batteryLevel, boolean isTransformed) { super(name, weight, enginePower, batteryLevel); this.isTransformed = isTransformed; } public void drainEnergy(Zad_Dfeo_1.Drone drone) { // Z tego co rozumiem z zadania, to jeśli isTransformed jest false, to dron otrzymuje funkcje wampiryczne, ale zostawiłęm to u mnie, że jeśli jest true to ma te funkcjie dla jaśniejszej czytelności z mojej strony przy pisaniu if (this.isTransformed) { this.batteryLevel = this.batteryLevel + (drone.batteryLevel / 2); drone.batteryLevel = drone.batteryLevel / 2; } else { System.out.println("W formie drona nie można wysysać energii."); } } public void TurnIntoBatDrone() { if (!this.isTransformed) { System.out.println("Od teraz to ja jestem władcą nocy!"); this.isTransformed = true; this.weight = this.weight / 2; this.batteryLevel = this.batteryLevel / 2; } else { System.out.println("Już jestem władcą nocy."); } } public void TurnIntoDrone() { // Dodałem od siebie funkcję powrotu do normalnego stanu if (this.isTransformed) { System.out.println("Powrót do formy słabeusza!"); this.weight = this.weight * 2; this.batteryLevel = this.batteryLevel * 1.5; this.isTransformed = false; } else { System.out.println("Już jestem słaby, bardziej nie mogę."); } } @Override public String toString() { return "VampireDrone{" + "name='" + name + '\'' + ", weight=" + weight + ", enginePower=" + enginePower + ", batteryLevel=" + batteryLevel + '\'' + ", isTransformed='" + isTransformed + '}'; } } public static class ChristmasDrone extends Zad_Dfeo_1.Drone { Zad_Dfeo_1.Gift gift; ChristmasDrone(String name, double weight, double enginePower, double batteryLevel, Zad_Dfeo_1.Gift gift) { super(name, weight, enginePower, batteryLevel); this.gift = gift; } public void deliverGift() { if (this.gift.weight + this.weight > this.enginePower) { System.out.println("Paczka jest zbyt ciężka żeby ją dostarczyć."); } else if (this.gift == null) { System.out.println("Nie ma żadnej paczki do dostarczenia."); } else { System.out.println("Dostarczono paczkę o wadze " + this.gift.weight + "g."); this.gift = null; } } @Override public String toString() { return "ChristmasDrone{" + "name='" + name + '\'' + ", weight=" + weight + ", enginePower=" + enginePower + ", batteryLevel=" + batteryLevel + '\'' + ", gift='" + gift + '}'; } } public static class Gift { String nameOfContent; double weight; boolean isReadyToBeDelivered = false; Gift(String nameOfContent, double weight) { this.nameOfContent = nameOfContent; this.weight = weight; } public void prepere() { this.isReadyToBeDelivered = true; } public void unpack() { this.isReadyToBeDelivered = false; System.out.println("W paczce znajduje się " + this.nameOfContent + "!"); } @Override public String toString() { return "Gift{" + "nameOfContent='" + nameOfContent + '\'' + ", weight=" + weight + '}'; } } public static class DroneControlRoom{ Zad_Dfeo_1.Drone[] allDrones; static double windPowerOutside = 3; DroneControlRoom() { this.allDrones = new Zad_Dfeo_1.Drone[1]; } public int countDronesThatCanFly() { getOutNulls(); int count = 0; for (Zad_Dfeo_1.Drone drone: this.allDrones) { if (drone.enginePower > drone.weight && drone.batteryLevel > 0) { count++; } } return count; } public void chargeAllDrones() { getOutNulls(); for (Zad_Dfeo_1.Drone drone: this.allDrones) { drone.batteryLevel += 20; } } public void addNewDrone(Zad_Dfeo_1.Drone drone) { Zad_Dfeo_1.Drone[] newAllDrones = new Zad_Dfeo_1.Drone[allDrones.length + 1]; for (int i = 0; i < allDrones.length; i++) { newAllDrones[i] = allDrones[i]; } allDrones = newAllDrones; allDrones[allDrones.length - 1] = drone; } public void sortAllDrones() { getOutNulls(); for (int i = 0; i < allDrones.length; i++) { for (int j = 0; j < allDrones.length - 1; j++) { if (allDrones[j].weight > allDrones[j + 1].weight) { double temp = allDrones[j + 1].weight; allDrones[j + 1].weight = allDrones[j].weight; allDrones[j].weight = temp; } } } System.out.print(" Lista dronów posortowana po wadze (rosnąco): "); for (Zad_Dfeo_1.Drone drone: allDrones) { System.out.print(drone + ", "); } } public void getOutNulls() { int counter = 0; for (int j = 0; j < allDrones.length; j++) { if (allDrones[j] != null) { counter++; } } Zad_Dfeo_1.Drone[] newList = new Zad_Dfeo_1.Drone[counter]; int counter2 = 0; for (int j = 0; j < allDrones.length; j++) { if (allDrones[j] != null) { newList[counter2] = allDrones[j]; counter2++; } } allDrones = newList; } public Zad_Dfeo_1.Drone findMostPowerful(){ getOutNulls(); return findMostPowerful(0, allDrones[0]); } public Zad_Dfeo_1.Drone findMostPowerful(int currentIndex, Zad_Dfeo_1.Drone currentMostPowerful) { if (currentIndex == allDrones.length) { return currentMostPowerful; } if (allDrones[currentIndex].enginePower > currentMostPowerful.enginePower) { currentMostPowerful = allDrones[currentIndex]; } return findMostPowerful(currentIndex + 1, currentMostPowerful); } @Override public String toString() { return "DroneControlRoom{" + "allDrones='" + Arrays.toString(allDrones) + '}'; } } // Inwencja twórcza public static class KillerDrone extends Zad_Dfeo_1.Drone { int killCounter; String weapon; int reward; KillerDrone(String name, double weight, double enginePower, double batteryLevel, String weapon) { super(name, weight, enginePower, batteryLevel); this.weapon = weapon; } public void kill(Zad_Dfeo_1.Drone drone) { System.out.println(drone.name + " został zabity przy pomocy " + this.weapon + "!"); drone = null; this.killCounter++; reward += 10000; } public void checkWantedPoster() { System.out.println("Obecna nagroda za głowę " + this.name + " wynosi " + this.reward + "."); } public int playWithPolice(int policeInPursuit) { if (policeInPursuit > 20) { System.out.println(this.name + " został schwytany!"); return policeInPursuit; } else if (policeInPursuit > 14) { System.out.println(this.name + " znów zabawił się z policją i uciekł!"); return policeInPursuit; } else { Random random = new Random(); return playWithPolice(policeInPursuit + random.nextInt(10)); } } @Override public String toString() { return "KillerDrone{" + "name='" + name + '\'' + ", weight=" + weight + ", enginePower=" + enginePower + ", batteryLevel=" + batteryLevel + '\'' + ", weapon='" + weapon + '}'; } } }
3452_1
import java.util.Random; public class Lab02 { // Stałe i parametry dostępne globalnie private static final double A = -5.21; private static final double B = 5.21; private static final int D = 3; // dokładność do 3 miejsc po przecinku private static final Random rand = new Random(); public static void main(String[] args) { // Obliczanie liczby bitów int m1 = liczbaBitow(A, B, D); int m2 = m1; // ponieważ przedziały są takie same // Generowanie genotypów już z ograniczeniami double x1 = generujGenotyp(A, B, D, m1); double x2 = generujGenotyp(A, B, D, m2); // Enkodowanie i dekodowanie wartości String bin_x1 = enkoduj(x1, A, B, m1); String bin_x2 = enkoduj(x2, A, B, m2); double dec_x1 = dekoduj(bin_x1, A, B, m1); double dec_x2 = dekoduj(bin_x2, A, B, m2); // Wypisanie wyników System.out.println("x1 = " + x1 + ", Binarnie: " + bin_x1 + ", Dekodowane: " + dec_x1); System.out.println("x2 = " + x2 + ", Binarnie: " + bin_x2 + ", Dekodowane: " + dec_x2); System.out.println("Chromosom = " + bin_x1 + bin_x2); // Obliczenie funkcji Rastrigina double f = funkcjaRastrigina(dec_x1, dec_x2); System.out.println("Wartość funkcji Rastrigina: " + f); } // Metody pomocnicze private static int liczbaBitow(double a, double b, int d) { double przedzial = b - a; double liczbaPodprzedzialow = przedzial * Math.pow(10, d); return (int) Math.ceil(Math.log(liczbaPodprzedzialow) / Math.log(2)); } private static double generujGenotyp(double a, double b, int d, int m) { int liczbaWartosci = (int) Math.pow(2, m); int wybranyIndex = rand.nextInt(liczbaWartosci); return a + (wybranyIndex * ((b - a) / (liczbaWartosci - 1))); } private static String enkoduj(double x, double a, double b, int m) { int liczbaWartosci = (int) Math.pow(2, m); int index = (int) Math.round(((x - a) / (b - a)) * (liczbaWartosci - 1)); return String.format("%" + m + "s", Integer.toBinaryString(index)).replace(' ', '0'); } private static double dekoduj(String binary, double a, double b, int m) { int liczbaWartosci = (int) Math.pow(2, m); int decimal = Integer.parseInt(binary, 2); return a + decimal * ((b - a) / (liczbaWartosci - 1)); } private static double funkcjaRastrigina(double x1, double x2) { int n = 2; int A = 10; return A * n + (x1 * x1 - A * Math.cos(2 * Math.PI * x1)) + (x2 * x2 - A * Math.cos(2 * Math.PI * x2)); } }
ItsRaelx/UniwersytetMorski
MiNSI/Lab02.java
994
// dokładność do 3 miejsc po przecinku
line_comment
pl
import java.util.Random; public class Lab02 { // Stałe i parametry dostępne globalnie private static final double A = -5.21; private static final double B = 5.21; private static final int D = 3; // dokładność do <SUF> private static final Random rand = new Random(); public static void main(String[] args) { // Obliczanie liczby bitów int m1 = liczbaBitow(A, B, D); int m2 = m1; // ponieważ przedziały są takie same // Generowanie genotypów już z ograniczeniami double x1 = generujGenotyp(A, B, D, m1); double x2 = generujGenotyp(A, B, D, m2); // Enkodowanie i dekodowanie wartości String bin_x1 = enkoduj(x1, A, B, m1); String bin_x2 = enkoduj(x2, A, B, m2); double dec_x1 = dekoduj(bin_x1, A, B, m1); double dec_x2 = dekoduj(bin_x2, A, B, m2); // Wypisanie wyników System.out.println("x1 = " + x1 + ", Binarnie: " + bin_x1 + ", Dekodowane: " + dec_x1); System.out.println("x2 = " + x2 + ", Binarnie: " + bin_x2 + ", Dekodowane: " + dec_x2); System.out.println("Chromosom = " + bin_x1 + bin_x2); // Obliczenie funkcji Rastrigina double f = funkcjaRastrigina(dec_x1, dec_x2); System.out.println("Wartość funkcji Rastrigina: " + f); } // Metody pomocnicze private static int liczbaBitow(double a, double b, int d) { double przedzial = b - a; double liczbaPodprzedzialow = przedzial * Math.pow(10, d); return (int) Math.ceil(Math.log(liczbaPodprzedzialow) / Math.log(2)); } private static double generujGenotyp(double a, double b, int d, int m) { int liczbaWartosci = (int) Math.pow(2, m); int wybranyIndex = rand.nextInt(liczbaWartosci); return a + (wybranyIndex * ((b - a) / (liczbaWartosci - 1))); } private static String enkoduj(double x, double a, double b, int m) { int liczbaWartosci = (int) Math.pow(2, m); int index = (int) Math.round(((x - a) / (b - a)) * (liczbaWartosci - 1)); return String.format("%" + m + "s", Integer.toBinaryString(index)).replace(' ', '0'); } private static double dekoduj(String binary, double a, double b, int m) { int liczbaWartosci = (int) Math.pow(2, m); int decimal = Integer.parseInt(binary, 2); return a + decimal * ((b - a) / (liczbaWartosci - 1)); } private static double funkcjaRastrigina(double x1, double x2) { int n = 2; int A = 10; return A * n + (x1 * x1 - A * Math.cos(2 * Math.PI * x1)) + (x2 * x2 - A * Math.cos(2 * Math.PI * x2)); } }
10338_0
package eu.javeo.knowler.client.mobile.knowler; import android.app.Fragment; import android.content.Context; import android.os.Bundle; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import butterknife.ButterKnife; import butterknife.InjectView; import de.greenrobot.event.EventBus; import eu.javeo.knowler.client.mobile.knowler.event.ApplicationEvent; import eu.javeo.knowler.client.mobile.knowler.event.ChangedMovieTimeEvent; import eu.javeo.knowler.client.mobile.knowler.event.EventBusListener; import eu.javeo.knowler.client.mobile.knowler.event.PageSelectedEvent; import eu.javeo.knowler.client.mobile.knowler.event.youtube.SeekToEvent; import java.util.ArrayList; import java.util.Arrays; public class SlidesFragment extends Fragment implements EventBusListener<ApplicationEvent> { @InjectView(R.id.pager_container) protected SlidesImagesContainer slidesImagesContainer; private String profileImages[] = {"profile_2", "profile_3", "profile_4", "profile_5", "profile_6", "profile_7", "profile_8", "profile_9", "profile_10", "profile_11", "profile_12", "profile_13", "profile_14", "profile_15", "profile_16", "profile_17", "profile_18", "profile_19", "profile_20", "profile_21"}; private ViewPager pager; public static SlidesFragment newInstance() { SlidesFragment fragment = new SlidesFragment(); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View inflate = inflater.inflate(R.layout.fragment_slides, container, false); ButterKnife.inject(this, inflate); EventBus.getDefault().register(this); ArrayList<String> images = new ArrayList<String>(Arrays.asList(profileImages)); pager = slidesImagesContainer.getViewPager(); PagerAdapter adapter = new ImagePagerAdapter(); pager.setAdapter(adapter); pager.setOffscreenPageLimit(adapter.getCount()); pager.setClipChildren(true); pager.setCurrentItem(1); return inflate; } @Override public void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } @Override public void onEvent(ApplicationEvent event) { if (event instanceof PageSelectedEvent) { // Bo tutaj będę miał informacje o filmach pager.getCurrentItem(); EventBus.getDefault().post(new ChangedMovieTimeEvent()); } else if (event instanceof SeekToEvent) { int millis = ((SeekToEvent) event).getMillis(); } } public class ImagePagerAdapter extends PagerAdapter { @Override public int getCount() { return profileImages.length; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, int position) { Context context = getActivity(); ImageView imageView = new ImageView(context); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); int drawable = context.getResources().getIdentifier(profileImages[position], "drawable", context.getPackageName()); imageView.setImageResource(drawable); imageView.setAdjustViewBounds(true); container.addView(imageView, 0); return imageView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((ImageView) object); } } }
JAVEO/knowler
client/mobile/Knowler/app/src/main/java/eu/javeo/knowler/client/mobile/knowler/SlidesFragment.java
1,134
// Bo tutaj będę miał informacje o filmach
line_comment
pl
package eu.javeo.knowler.client.mobile.knowler; import android.app.Fragment; import android.content.Context; import android.os.Bundle; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import butterknife.ButterKnife; import butterknife.InjectView; import de.greenrobot.event.EventBus; import eu.javeo.knowler.client.mobile.knowler.event.ApplicationEvent; import eu.javeo.knowler.client.mobile.knowler.event.ChangedMovieTimeEvent; import eu.javeo.knowler.client.mobile.knowler.event.EventBusListener; import eu.javeo.knowler.client.mobile.knowler.event.PageSelectedEvent; import eu.javeo.knowler.client.mobile.knowler.event.youtube.SeekToEvent; import java.util.ArrayList; import java.util.Arrays; public class SlidesFragment extends Fragment implements EventBusListener<ApplicationEvent> { @InjectView(R.id.pager_container) protected SlidesImagesContainer slidesImagesContainer; private String profileImages[] = {"profile_2", "profile_3", "profile_4", "profile_5", "profile_6", "profile_7", "profile_8", "profile_9", "profile_10", "profile_11", "profile_12", "profile_13", "profile_14", "profile_15", "profile_16", "profile_17", "profile_18", "profile_19", "profile_20", "profile_21"}; private ViewPager pager; public static SlidesFragment newInstance() { SlidesFragment fragment = new SlidesFragment(); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View inflate = inflater.inflate(R.layout.fragment_slides, container, false); ButterKnife.inject(this, inflate); EventBus.getDefault().register(this); ArrayList<String> images = new ArrayList<String>(Arrays.asList(profileImages)); pager = slidesImagesContainer.getViewPager(); PagerAdapter adapter = new ImagePagerAdapter(); pager.setAdapter(adapter); pager.setOffscreenPageLimit(adapter.getCount()); pager.setClipChildren(true); pager.setCurrentItem(1); return inflate; } @Override public void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } @Override public void onEvent(ApplicationEvent event) { if (event instanceof PageSelectedEvent) { // Bo tutaj <SUF> pager.getCurrentItem(); EventBus.getDefault().post(new ChangedMovieTimeEvent()); } else if (event instanceof SeekToEvent) { int millis = ((SeekToEvent) event).getMillis(); } } public class ImagePagerAdapter extends PagerAdapter { @Override public int getCount() { return profileImages.length; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, int position) { Context context = getActivity(); ImageView imageView = new ImageView(context); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); int drawable = context.getResources().getIdentifier(profileImages[position], "drawable", context.getPackageName()); imageView.setImageResource(drawable); imageView.setAdjustViewBounds(true); container.addView(imageView, 0); return imageView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((ImageView) object); } } }
6560_0
package Builder; import java.util.ArrayList; // W przyszłości pizza mogłaby dziedziczyć po czymś, aby było bardziej uniwersalne public class Pizza extends Jedzonko{ private ArrayList<String> dodatki; private boolean seroweBrzegi; private String sos; public Pizza() { dodatki = new ArrayList<>(); } public ArrayList<String> getDodatki() { return dodatki; } public void setDodatki(ArrayList<String> dodatki) { this.dodatki = dodatki; } public boolean isSeroweBrzegi() { return seroweBrzegi; } public void setSeroweBrzegi(boolean seroweBrzegi) { this.seroweBrzegi = seroweBrzegi; } public String getSos() { return sos; } public void setSos(String sos) { this.sos = sos; } @Override public void zbudujOpis() { opis = nazwa + ": "; for(String x: dodatki) { opis = opis + x + ", "; } opis = opis + "sos: " + sos + "serowe brzegi: " + seroweBrzegi; } @Override public void wypiszOpis() { System.out.println(opis); } }
JAck0b/Wzorceprojektowe
src/Builder/Pizza.java
406
// W przyszłości pizza mogłaby dziedziczyć po czymś, aby było bardziej uniwersalne
line_comment
pl
package Builder; import java.util.ArrayList; // W przyszłości <SUF> public class Pizza extends Jedzonko{ private ArrayList<String> dodatki; private boolean seroweBrzegi; private String sos; public Pizza() { dodatki = new ArrayList<>(); } public ArrayList<String> getDodatki() { return dodatki; } public void setDodatki(ArrayList<String> dodatki) { this.dodatki = dodatki; } public boolean isSeroweBrzegi() { return seroweBrzegi; } public void setSeroweBrzegi(boolean seroweBrzegi) { this.seroweBrzegi = seroweBrzegi; } public String getSos() { return sos; } public void setSos(String sos) { this.sos = sos; } @Override public void zbudujOpis() { opis = nazwa + ": "; for(String x: dodatki) { opis = opis + x + ", "; } opis = opis + "sos: " + sos + "serowe brzegi: " + seroweBrzegi; } @Override public void wypiszOpis() { System.out.println(opis); } }
6631_22
package lsr.paxos.network; import static lsr.common.ProcessDescriptor.processDescriptor; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.OutputStream; import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.nio.ByteBuffer; import java.util.concurrent.ArrayBlockingQueue; import lsr.common.KillOnExceptionHandler; import lsr.common.PID; import lsr.paxos.messages.Message; import lsr.paxos.messages.MessageFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is responsible for handling stable TCP connection to other * replica, provides two methods for establishing new connection: active and * passive. In active mode we try to connect to other side creating new socket * and connects. If passive mode is enabled, then we wait for socket from the * <code>SocketServer</code> provided by <code>TcpNetwork</code>. * <p> * Every time new message is received from this connection, it is deserialized, * and then all registered network listeners in related <code>TcpNetwork</code> * are notified about it. * * @see TcpNetwork */ public class TcpConnection { public static final int TCP_BUFFER_SIZE = 16 * 1024 * 1024; private static final long MAX_QUEUE_OFFER_DELAY_MS = 25L; private Socket socket; private DataInputStream input; private OutputStream output; private final PID replica; private volatile boolean connected = false; private volatile long lastSndTs = 0L; private volatile boolean writing = false; private final Object connectedLock = new Object(); /** true if connection should be started by this replica; */ private final boolean active; private final TcpNetwork network; private final Thread senderThread; private final Thread receiverThread; private final ArrayBlockingQueue<byte[]> sendQueue = new ArrayBlockingQueue<byte[]>(512); private final int peerId; private boolean closing = false; /** * Creates a new TCP connection to specified replica. * * @param network - related <code>TcpNetwork</code>. * @param replica - replica to connect to. * @param peerId - ID of the replica on the other end of connection * @param active - initiates connection if true; waits for remote connection * otherwise. */ public TcpConnection(TcpNetwork network, final PID replica, int peerId, boolean active) { this.network = network; this.replica = replica; this.peerId = peerId; this.active = active; logger.info("Creating connection: {} - {}", replica, active); receiverThread = new Thread(new ReceiverThread(), "ReplicaIORcv-" + replica.getId()); senderThread = new Thread(new Sender(), "ReplicaIOSnd-" + replica.getId()); receiverThread.setUncaughtExceptionHandler(new KillOnExceptionHandler()); senderThread.setUncaughtExceptionHandler(new KillOnExceptionHandler()); receiverThread.setDaemon(true); receiverThread.setPriority(Thread.MAX_PRIORITY); senderThread.setDaemon(true); senderThread.setPriority(Thread.MAX_PRIORITY); } /** * Starts the receiver and sender thread. */ public synchronized void start() { receiverThread.start(); senderThread.start(); } public boolean isActive() { return active; } final class Sender implements Runnable { public void run() { logger.debug("Sender thread started."); try { Socket lastSeenSocket = null; while (true) { if (Thread.interrupted()) { if (!closing) throw new RuntimeException("Sender " + Thread.currentThread().getName() + " thread has been interupted and stopped."); return; } byte[] msg = sendQueue.take(); // ignore message if not connected // Works without memory barrier because connected is // volatile if (!connected) { // wait for connection synchronized (connectedLock) { while (!connected) connectedLock.wait(); lastSeenSocket = socket; } } try { writing = true; output.write(msg); output.flush(); writing = false; } catch (IOException e) { logger.warn("Error sending message", e); writing = false; sendQueue.offer(msg); close(lastSeenSocket); synchronized (connectedLock) { lastSeenSocket = socket; } } lastSndTs = System.currentTimeMillis(); } } catch (InterruptedException e) { if (closing) logger.info("Clean closing the {}", Thread.currentThread().getName()); else throw new RuntimeException("Sender " + Thread.currentThread().getName() + " thread has been interupted", e); } } } /** * Main loop used to connect and read from the socket. */ final class ReceiverThread implements Runnable { public void run() { do { if (Thread.interrupted()) { if (!closing) throw new RuntimeException("Receiver thread has been interrupted."); return; } logger.info("Waiting for tcp connection to {}", replica.getId()); Socket lastSeenSocket; try { if (active) lastSeenSocket = connect(); else { synchronized (connectedLock) { while (!connected) connectedLock.wait(); lastSeenSocket = socket; } } } catch (InterruptedException e) { if (!closing) throw new RuntimeException("Receiver thread has been interrupted."); break; } while (true) { if (Thread.interrupted()) { if (!closing) throw new RuntimeException("Receiver thread has been interrupted."); return; } try { Message message = MessageFactory.create(input); if (logger.isDebugEnabled()) { logger.debug("Received [{}] {} size: {}", replica.getId(), message, message.byteSize()); } network.fireReceiveMessage(message, replica.getId()); } catch (EOFException e) { // end of stream with socket occurred so close // connection and try to establish it again if (!closing) { logger.info("Error reading message - EOF", e); close(lastSeenSocket); } break; } catch (IOException e) { // problem with socket occurred so close connection and // try to establish it again if (!closing) { logger.warn("Error reading message (?)", e); close(lastSeenSocket); } break; } } } while (active); } } /** * Sends specified binary packet using underlying TCP connection. * * @param message - binary packet to send * @return true if sending message was successful */ public void send(byte[] message) { if (connected) { // FIXME: (JK) discuss what should be done here while (!sendQueue.offer(message)) { // if some messages are being sent, wait a while if (!writing || System.currentTimeMillis() - lastSndTs <= MAX_QUEUE_OFFER_DELAY_MS) { Thread.yield(); continue; } byte[] discarded = sendQueue.poll(); if (logger.isDebugEnabled()) { logger.warn( "TCP msg queue overfolw: Discarding message {} to send {}. Last send: {}, writing: {}", discarded.toString(), message.toString(), System.currentTimeMillis() - lastSndTs, writing); } else { logger.warn("TCP msg queue overfolw: Discarding a message to send anoter"); } } } else { // keep last n messages while (!sendQueue.offer(message)) { sendQueue.poll(); } } } /** * Registers new socket to this TCP connection. Specified socket should be * initialized connection with other replica. First method tries to close * old connection and then set-up new one. * * @param socket - active socket connection * @param input - input stream from this socket * @param output - output stream from this socket */ public synchronized void setConnection(Socket socket, DataInputStream input, DataOutputStream output) { assert socket != null : "Invalid socket state"; logger.info("TCP connection accepted from {}", replica); synchronized (connectedLock) { // initialize new connection this.socket = socket; this.input = input; this.output = output; connected = true; // wake up receiver and sender connectedLock.notifyAll(); } } public void stopAsync() { synchronized (connectedLock) { close(socket); receiverThread.interrupt(); senderThread.interrupt(); } } /** * Stops current connection and stops all underlying threads. * * Note: This method waits until all threads are finished. * * @throws InterruptedException */ public void stop() throws InterruptedException { stopAsync(); receiverThread.join(); senderThread.join(); } /** * Establishes connection to host specified by this object. If this is * active connection then it will try to connect to other side. Otherwise we * will wait until connection will be set-up using * <code>setConnection</code> method. This method will return only if the * connection is established and initialized properly. * * @return * * @throws InterruptedException */ @SuppressWarnings("resource") private Socket connect() throws InterruptedException { assert active; Socket newSocket; DataInputStream newInput; OutputStream newOutput; // this is active connection so we try to connect to host while (true) { try { newSocket = new Socket(); newSocket.setReceiveBufferSize(TCP_BUFFER_SIZE); newSocket.setSendBufferSize(TCP_BUFFER_SIZE); logger.debug("RcvdBuffer: {}, SendBuffer: {}", newSocket.getReceiveBufferSize(), newSocket.getSendBufferSize()); newSocket.setTcpNoDelay(true); logger.info("Connecting to: {}", replica); try { newSocket.connect(new InetSocketAddress(replica.getHostname(), replica.getReplicaPort()), (int) processDescriptor.tcpReconnectTimeout); } catch (ConnectException e) { logger.info("TCP connection with replica {} failed: {}", replica.getId(), e.getMessage()); Thread.sleep(processDescriptor.tcpReconnectTimeout); continue; } catch (SocketTimeoutException e) { logger.info("TCP connection with replica {} timed out", replica.getId()); continue; } catch (SocketException e) { if (newSocket.isClosed()) { logger.warn("Invoking connect() on closed socket. Quitting?"); return null; } logger.warn("TCP connection with replica {} failed: {}", replica.getId(), e.getMessage()); Thread.sleep(processDescriptor.tcpReconnectTimeout); continue; } catch (IOException e) { throw new RuntimeException("what else can be thrown here?", e); } newInput = new DataInputStream(new BufferedInputStream(newSocket.getInputStream())); newOutput = newSocket.getOutputStream(); byte buf[] = new byte[4]; ByteBuffer.wrap(buf).putInt(processDescriptor.localId); try { newOutput.write(buf); newOutput.flush(); } catch (SocketException e) { /*- Caused by: java.net.SocketException: Połączenie zerwane przez drugą stronę (Write failed) -*/ logger.warn("TCP connection with replica {} failed: {}", replica.getId(), e.getMessage()); continue; } // connection established break; } catch (IOException e) { throw new RuntimeException("Unexpected error connecting to " + replica, e); } } logger.info("TCP connect successfull to {}", replica); // Wake up the sender thread synchronized (connectedLock) { socket = newSocket; input = newInput; output = newOutput; connected = true; // notify sender connectedLock.notifyAll(); } network.addConnection(peerId, this); return newSocket; } /** * Closes the connection. * * @param victim - close can race with many methods (e.g. connect), so tell * it what you want to close to prevent races */ private void close(Socket victim) { synchronized (connectedLock) { if (socket != victim) return; if (active) network.removeConnection(peerId, this); closing = true; connected = false; if (socket != null) { if (socket.isConnected()) try { logger.info("Closing TCP connection to {}", replica); socket.shutdownOutput(); socket.close(); logger.debug("TCP connection closed to {}", replica); } catch (IOException e) { logger.warn("Error closing socket", e); } socket = null; } } } private final static Logger logger = LoggerFactory.getLogger(TcpConnection.class); }
JPaxos/JPaxos
src/lsr/paxos/network/TcpConnection.java
3,939
/*- Caused by: java.net.SocketException: Połączenie zerwane przez drugą stronę (Write failed) -*/
block_comment
pl
package lsr.paxos.network; import static lsr.common.ProcessDescriptor.processDescriptor; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.OutputStream; import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.nio.ByteBuffer; import java.util.concurrent.ArrayBlockingQueue; import lsr.common.KillOnExceptionHandler; import lsr.common.PID; import lsr.paxos.messages.Message; import lsr.paxos.messages.MessageFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is responsible for handling stable TCP connection to other * replica, provides two methods for establishing new connection: active and * passive. In active mode we try to connect to other side creating new socket * and connects. If passive mode is enabled, then we wait for socket from the * <code>SocketServer</code> provided by <code>TcpNetwork</code>. * <p> * Every time new message is received from this connection, it is deserialized, * and then all registered network listeners in related <code>TcpNetwork</code> * are notified about it. * * @see TcpNetwork */ public class TcpConnection { public static final int TCP_BUFFER_SIZE = 16 * 1024 * 1024; private static final long MAX_QUEUE_OFFER_DELAY_MS = 25L; private Socket socket; private DataInputStream input; private OutputStream output; private final PID replica; private volatile boolean connected = false; private volatile long lastSndTs = 0L; private volatile boolean writing = false; private final Object connectedLock = new Object(); /** true if connection should be started by this replica; */ private final boolean active; private final TcpNetwork network; private final Thread senderThread; private final Thread receiverThread; private final ArrayBlockingQueue<byte[]> sendQueue = new ArrayBlockingQueue<byte[]>(512); private final int peerId; private boolean closing = false; /** * Creates a new TCP connection to specified replica. * * @param network - related <code>TcpNetwork</code>. * @param replica - replica to connect to. * @param peerId - ID of the replica on the other end of connection * @param active - initiates connection if true; waits for remote connection * otherwise. */ public TcpConnection(TcpNetwork network, final PID replica, int peerId, boolean active) { this.network = network; this.replica = replica; this.peerId = peerId; this.active = active; logger.info("Creating connection: {} - {}", replica, active); receiverThread = new Thread(new ReceiverThread(), "ReplicaIORcv-" + replica.getId()); senderThread = new Thread(new Sender(), "ReplicaIOSnd-" + replica.getId()); receiverThread.setUncaughtExceptionHandler(new KillOnExceptionHandler()); senderThread.setUncaughtExceptionHandler(new KillOnExceptionHandler()); receiverThread.setDaemon(true); receiverThread.setPriority(Thread.MAX_PRIORITY); senderThread.setDaemon(true); senderThread.setPriority(Thread.MAX_PRIORITY); } /** * Starts the receiver and sender thread. */ public synchronized void start() { receiverThread.start(); senderThread.start(); } public boolean isActive() { return active; } final class Sender implements Runnable { public void run() { logger.debug("Sender thread started."); try { Socket lastSeenSocket = null; while (true) { if (Thread.interrupted()) { if (!closing) throw new RuntimeException("Sender " + Thread.currentThread().getName() + " thread has been interupted and stopped."); return; } byte[] msg = sendQueue.take(); // ignore message if not connected // Works without memory barrier because connected is // volatile if (!connected) { // wait for connection synchronized (connectedLock) { while (!connected) connectedLock.wait(); lastSeenSocket = socket; } } try { writing = true; output.write(msg); output.flush(); writing = false; } catch (IOException e) { logger.warn("Error sending message", e); writing = false; sendQueue.offer(msg); close(lastSeenSocket); synchronized (connectedLock) { lastSeenSocket = socket; } } lastSndTs = System.currentTimeMillis(); } } catch (InterruptedException e) { if (closing) logger.info("Clean closing the {}", Thread.currentThread().getName()); else throw new RuntimeException("Sender " + Thread.currentThread().getName() + " thread has been interupted", e); } } } /** * Main loop used to connect and read from the socket. */ final class ReceiverThread implements Runnable { public void run() { do { if (Thread.interrupted()) { if (!closing) throw new RuntimeException("Receiver thread has been interrupted."); return; } logger.info("Waiting for tcp connection to {}", replica.getId()); Socket lastSeenSocket; try { if (active) lastSeenSocket = connect(); else { synchronized (connectedLock) { while (!connected) connectedLock.wait(); lastSeenSocket = socket; } } } catch (InterruptedException e) { if (!closing) throw new RuntimeException("Receiver thread has been interrupted."); break; } while (true) { if (Thread.interrupted()) { if (!closing) throw new RuntimeException("Receiver thread has been interrupted."); return; } try { Message message = MessageFactory.create(input); if (logger.isDebugEnabled()) { logger.debug("Received [{}] {} size: {}", replica.getId(), message, message.byteSize()); } network.fireReceiveMessage(message, replica.getId()); } catch (EOFException e) { // end of stream with socket occurred so close // connection and try to establish it again if (!closing) { logger.info("Error reading message - EOF", e); close(lastSeenSocket); } break; } catch (IOException e) { // problem with socket occurred so close connection and // try to establish it again if (!closing) { logger.warn("Error reading message (?)", e); close(lastSeenSocket); } break; } } } while (active); } } /** * Sends specified binary packet using underlying TCP connection. * * @param message - binary packet to send * @return true if sending message was successful */ public void send(byte[] message) { if (connected) { // FIXME: (JK) discuss what should be done here while (!sendQueue.offer(message)) { // if some messages are being sent, wait a while if (!writing || System.currentTimeMillis() - lastSndTs <= MAX_QUEUE_OFFER_DELAY_MS) { Thread.yield(); continue; } byte[] discarded = sendQueue.poll(); if (logger.isDebugEnabled()) { logger.warn( "TCP msg queue overfolw: Discarding message {} to send {}. Last send: {}, writing: {}", discarded.toString(), message.toString(), System.currentTimeMillis() - lastSndTs, writing); } else { logger.warn("TCP msg queue overfolw: Discarding a message to send anoter"); } } } else { // keep last n messages while (!sendQueue.offer(message)) { sendQueue.poll(); } } } /** * Registers new socket to this TCP connection. Specified socket should be * initialized connection with other replica. First method tries to close * old connection and then set-up new one. * * @param socket - active socket connection * @param input - input stream from this socket * @param output - output stream from this socket */ public synchronized void setConnection(Socket socket, DataInputStream input, DataOutputStream output) { assert socket != null : "Invalid socket state"; logger.info("TCP connection accepted from {}", replica); synchronized (connectedLock) { // initialize new connection this.socket = socket; this.input = input; this.output = output; connected = true; // wake up receiver and sender connectedLock.notifyAll(); } } public void stopAsync() { synchronized (connectedLock) { close(socket); receiverThread.interrupt(); senderThread.interrupt(); } } /** * Stops current connection and stops all underlying threads. * * Note: This method waits until all threads are finished. * * @throws InterruptedException */ public void stop() throws InterruptedException { stopAsync(); receiverThread.join(); senderThread.join(); } /** * Establishes connection to host specified by this object. If this is * active connection then it will try to connect to other side. Otherwise we * will wait until connection will be set-up using * <code>setConnection</code> method. This method will return only if the * connection is established and initialized properly. * * @return * * @throws InterruptedException */ @SuppressWarnings("resource") private Socket connect() throws InterruptedException { assert active; Socket newSocket; DataInputStream newInput; OutputStream newOutput; // this is active connection so we try to connect to host while (true) { try { newSocket = new Socket(); newSocket.setReceiveBufferSize(TCP_BUFFER_SIZE); newSocket.setSendBufferSize(TCP_BUFFER_SIZE); logger.debug("RcvdBuffer: {}, SendBuffer: {}", newSocket.getReceiveBufferSize(), newSocket.getSendBufferSize()); newSocket.setTcpNoDelay(true); logger.info("Connecting to: {}", replica); try { newSocket.connect(new InetSocketAddress(replica.getHostname(), replica.getReplicaPort()), (int) processDescriptor.tcpReconnectTimeout); } catch (ConnectException e) { logger.info("TCP connection with replica {} failed: {}", replica.getId(), e.getMessage()); Thread.sleep(processDescriptor.tcpReconnectTimeout); continue; } catch (SocketTimeoutException e) { logger.info("TCP connection with replica {} timed out", replica.getId()); continue; } catch (SocketException e) { if (newSocket.isClosed()) { logger.warn("Invoking connect() on closed socket. Quitting?"); return null; } logger.warn("TCP connection with replica {} failed: {}", replica.getId(), e.getMessage()); Thread.sleep(processDescriptor.tcpReconnectTimeout); continue; } catch (IOException e) { throw new RuntimeException("what else can be thrown here?", e); } newInput = new DataInputStream(new BufferedInputStream(newSocket.getInputStream())); newOutput = newSocket.getOutputStream(); byte buf[] = new byte[4]; ByteBuffer.wrap(buf).putInt(processDescriptor.localId); try { newOutput.write(buf); newOutput.flush(); } catch (SocketException e) { /*- Caused by: <SUF>*/ logger.warn("TCP connection with replica {} failed: {}", replica.getId(), e.getMessage()); continue; } // connection established break; } catch (IOException e) { throw new RuntimeException("Unexpected error connecting to " + replica, e); } } logger.info("TCP connect successfull to {}", replica); // Wake up the sender thread synchronized (connectedLock) { socket = newSocket; input = newInput; output = newOutput; connected = true; // notify sender connectedLock.notifyAll(); } network.addConnection(peerId, this); return newSocket; } /** * Closes the connection. * * @param victim - close can race with many methods (e.g. connect), so tell * it what you want to close to prevent races */ private void close(Socket victim) { synchronized (connectedLock) { if (socket != victim) return; if (active) network.removeConnection(peerId, this); closing = true; connected = false; if (socket != null) { if (socket.isConnected()) try { logger.info("Closing TCP connection to {}", replica); socket.shutdownOutput(); socket.close(); logger.debug("TCP connection closed to {}", replica); } catch (IOException e) { logger.warn("Error closing socket", e); } socket = null; } } } private final static Logger logger = LoggerFactory.getLogger(TcpConnection.class); }
6852_1
package pl.com.jmotyka.GUI; import pl.com.jmotyka.animals.Animal; import pl.com.jmotyka.animals.Dog; import pl.com.jmotyka.animals.Findable; import pl.com.jmotyka.dbConnectvity.MySQLCon; import pl.com.jmotyka.general.AnimalComparer; import pl.com.jmotyka.general.Submitter; import pl.com.jmotyka.general.Uploadable; import javax.swing.*; import java.awt.*; import java.util.ArrayList; public class DogPanel extends AnimalPanel implements PanelCreatable { private JLabel breedLabel; private JComboBox breedBox; private SubmitButton submitButton; private Submitter submittedBy; public DogPanel(MainFrame mainFrame, Submitter submittedBy) { super(mainFrame); this.submittedBy = submittedBy; setBorder(BorderFactory.createTitledBorder("Provide info about your dog: ")); initComponents(mainFrame); } //////////////////////////////// UPLOADABLE INTERFACE METHODS ///////////////////////////////////// @Override public Uploadable createFromPanel(PanelCreatable panelCreatablePanel) { DogPanel panel = (DogPanel) panelCreatablePanel; boolean tail, steril, collar, nametag; if(panel.getTailBox().getSelectedItem() == YN.YES) tail = true; else tail = false; if(panel.getSterilBox().getSelectedItem()==YN.YES) steril = true;else steril=false; if(panel.getCollarBox().getSelectedItem()==YN.YES) collar=true;else collar=false; if(panel.getNameTagBox().getSelectedItem()==YN.YES) nametag=true;else nametag=false; Dog dog = new Dog(panel.getNameField().getText(), (Animal.GenderEnum) panel.getGenderBox().getSelectedItem(), (Animal.AnimalHealthStatusEnum) panel.getHealthBox().getSelectedItem(), (Animal.Color) panel.getColor1Box().getSelectedItem(), (Animal.Color) panel.getColor2Box().getSelectedItem(), (Animal.Color) panel.getColor3Box().getSelectedItem(), (Animal.Bodytype) panel.getBodytypeBox().getSelectedItem(), steril, collar, nametag, tail, (long)panel.getHeightJS().getValue(), (long)panel.getLength().getValue(), (long)panel.getWeight().getValue(), (Dog.DogBreed)panel.getBreedBox().getSelectedItem()); dog.setSubmittedBy(panel.getSubmittedBy()); System.out.println("ID OWNERA WRZUCONE DO DOGA = " + dog.getSubmittedBy().getSubmitterID()); return dog; } @Override public void submitButtonEvent(PanelCreatable panel, MainFrame mainFrame, Submitter submittedBy) { DogPanel dogPanel = (DogPanel)panel; Dog newDog = (Dog)createFromPanel(dogPanel); newDog.setSubmittedBy(submittedBy); //pies zaczyna miec wlasciciela, wlasciciel ma już ID. DLACZEGO NIESPOJNOSC DANYCH?!?!?! MySQLCon con = new MySQLCon(); ArrayList<Animal> list = con.searchInDB(newDog); con.sendToDB(newDog); AnimalComparer dogComparer = new AnimalComparer(); JPanel resultPanel = dogComparer.createResultPanel(list, newDog); changePanelShown(mainFrame, resultPanel); } @Override public void changePanelShown(MainFrame mainFrame, JPanel showPanel){ mainFrame.getContentPane().removeAll(); mainFrame.getContentPane().add(showPanel, BorderLayout.CENTER); mainFrame.getContentPane().repaint(); mainFrame.getContentPane().doLayout(); mainFrame.update(mainFrame.getGraphics()); showPanel.invalidate(); showPanel.validate(); showPanel.repaint(); } /////////////////////////////////////////// COMPONENTS ////////////////////////////////////////////////////////// private void initComponents(MainFrame mainFrame){ //////////////////// 1st COLUMN ////////////////////////////////////// breedLabel = new JLabel("Breed: "); gbc.gridx = 0; gbc.gridy = 18; add(breedLabel, gbc); ////////////////////// 2nd COLUMN /////////////////////////////////////// breedBox = new JComboBox(Dog.DogBreed.values()); gbc.gridx = 1; gbc.gridy = 18; add(breedBox, gbc); ////////////////////////// BUTTON //////////////////////////////////////// submitButton = new SubmitButton("Submit from DOG", this, mainFrame, submittedBy); gbc.gridx = 4; gbc.gridy = 20; add(submitButton, gbc); } ////////////////////////////////////// Getters & Setters //////////////////////////////////////////////////// public JComboBox getBreedBox() { return breedBox; } public void setBreedBox(JComboBox breedBox) { this.breedBox = breedBox; } public Submitter getSubmittedBy() { return submittedBy; } public void setSubmittedBy(Submitter submittedBy) { this.submittedBy = submittedBy; } }
Jacentus/diploma_shelter
GUI/DogPanel.java
1,509
//pies zaczyna miec wlasciciela, wlasciciel ma już ID. DLACZEGO NIESPOJNOSC DANYCH?!?!?!
line_comment
pl
package pl.com.jmotyka.GUI; import pl.com.jmotyka.animals.Animal; import pl.com.jmotyka.animals.Dog; import pl.com.jmotyka.animals.Findable; import pl.com.jmotyka.dbConnectvity.MySQLCon; import pl.com.jmotyka.general.AnimalComparer; import pl.com.jmotyka.general.Submitter; import pl.com.jmotyka.general.Uploadable; import javax.swing.*; import java.awt.*; import java.util.ArrayList; public class DogPanel extends AnimalPanel implements PanelCreatable { private JLabel breedLabel; private JComboBox breedBox; private SubmitButton submitButton; private Submitter submittedBy; public DogPanel(MainFrame mainFrame, Submitter submittedBy) { super(mainFrame); this.submittedBy = submittedBy; setBorder(BorderFactory.createTitledBorder("Provide info about your dog: ")); initComponents(mainFrame); } //////////////////////////////// UPLOADABLE INTERFACE METHODS ///////////////////////////////////// @Override public Uploadable createFromPanel(PanelCreatable panelCreatablePanel) { DogPanel panel = (DogPanel) panelCreatablePanel; boolean tail, steril, collar, nametag; if(panel.getTailBox().getSelectedItem() == YN.YES) tail = true; else tail = false; if(panel.getSterilBox().getSelectedItem()==YN.YES) steril = true;else steril=false; if(panel.getCollarBox().getSelectedItem()==YN.YES) collar=true;else collar=false; if(panel.getNameTagBox().getSelectedItem()==YN.YES) nametag=true;else nametag=false; Dog dog = new Dog(panel.getNameField().getText(), (Animal.GenderEnum) panel.getGenderBox().getSelectedItem(), (Animal.AnimalHealthStatusEnum) panel.getHealthBox().getSelectedItem(), (Animal.Color) panel.getColor1Box().getSelectedItem(), (Animal.Color) panel.getColor2Box().getSelectedItem(), (Animal.Color) panel.getColor3Box().getSelectedItem(), (Animal.Bodytype) panel.getBodytypeBox().getSelectedItem(), steril, collar, nametag, tail, (long)panel.getHeightJS().getValue(), (long)panel.getLength().getValue(), (long)panel.getWeight().getValue(), (Dog.DogBreed)panel.getBreedBox().getSelectedItem()); dog.setSubmittedBy(panel.getSubmittedBy()); System.out.println("ID OWNERA WRZUCONE DO DOGA = " + dog.getSubmittedBy().getSubmitterID()); return dog; } @Override public void submitButtonEvent(PanelCreatable panel, MainFrame mainFrame, Submitter submittedBy) { DogPanel dogPanel = (DogPanel)panel; Dog newDog = (Dog)createFromPanel(dogPanel); newDog.setSubmittedBy(submittedBy); //pies zaczyna <SUF> MySQLCon con = new MySQLCon(); ArrayList<Animal> list = con.searchInDB(newDog); con.sendToDB(newDog); AnimalComparer dogComparer = new AnimalComparer(); JPanel resultPanel = dogComparer.createResultPanel(list, newDog); changePanelShown(mainFrame, resultPanel); } @Override public void changePanelShown(MainFrame mainFrame, JPanel showPanel){ mainFrame.getContentPane().removeAll(); mainFrame.getContentPane().add(showPanel, BorderLayout.CENTER); mainFrame.getContentPane().repaint(); mainFrame.getContentPane().doLayout(); mainFrame.update(mainFrame.getGraphics()); showPanel.invalidate(); showPanel.validate(); showPanel.repaint(); } /////////////////////////////////////////// COMPONENTS ////////////////////////////////////////////////////////// private void initComponents(MainFrame mainFrame){ //////////////////// 1st COLUMN ////////////////////////////////////// breedLabel = new JLabel("Breed: "); gbc.gridx = 0; gbc.gridy = 18; add(breedLabel, gbc); ////////////////////// 2nd COLUMN /////////////////////////////////////// breedBox = new JComboBox(Dog.DogBreed.values()); gbc.gridx = 1; gbc.gridy = 18; add(breedBox, gbc); ////////////////////////// BUTTON //////////////////////////////////////// submitButton = new SubmitButton("Submit from DOG", this, mainFrame, submittedBy); gbc.gridx = 4; gbc.gridy = 20; add(submitButton, gbc); } ////////////////////////////////////// Getters & Setters //////////////////////////////////////////////////// public JComboBox getBreedBox() { return breedBox; } public void setBreedBox(JComboBox breedBox) { this.breedBox = breedBox; } public Submitter getSubmittedBy() { return submittedBy; } public void setSubmittedBy(Submitter submittedBy) { this.submittedBy = submittedBy; } }
5197_10
package todoapp.todoapp.adapter; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import todoapp.todoapp.model.Task; import todoapp.todoapp.model.TaskRepository; //klasa do komunikacji z bazą danych. Coś ala API, punkt wejścia do działania na kolekcji (w tym przypadku tasków) //interfejs dziedziczący po interfejsie z pakietu JPARepository, specyfikajca Javy jak podejść do ORM (obiect relational mapping) //JPA - SPEFYCIKACJA(interfejs) HIBERNATE - jego implementacja. //w JPA mamy w środku JDBC - konektor javowy do rozmowy z bazą danych. //HIKARICP (Hikary connection pool). Pula połączeń do bazy danych. // JpaRepository. Przekazujemy info z jakiej encji // powinno brać dane oraz jaki jest jej identyfikator (mamy int) // rezygnujemy z adnotacji @RepositoryRestResource na rzecz @Repository, też zarządza tym Spring ale //możemy dać dodatkowe parametry, min:(path = "todos", collectionResourceRel = "todos") //nasze repozytorium działa na obiektach TASK, stąd w adresie URL Spring daje defaultowo Tasks. Tu zmieniamy odpowiednio. Mogę o tym przeczytać w dokuementacji (ctrl+b) //tworzymy interfejs REST dający nam metody dostępu do baz danych (SPRING wie co dać) //już jedna adnotacja (wyżej) i interfejs bazowy pozwala na wszystkie operacje typu CRUD w oparciu o stronicowanie i sortowanie @Repository interface SqlTaskRepository extends TaskRepository, JpaRepository<Task, Integer> { @Override//metoda existsbyID jest nadpisywana TaskRepository, wykonuje się query natywne SQL. @Query(nativeQuery = true, value = "select count(*) > 0 from tasks where id=:id") //adnotacja springowa, pozwala korzystac z "czystego" SQL. Dwukropek ID - dzięki temu możemy używać @Param. Mając SELECT* moglibyśmy zwracać obiekt klasy Task!!! boolean existsById(@Param("id")Integer id); @Override boolean existsByDoneIsFalseAndGroup_Id(Integer group_id); //sygnatura metody którą udostępniamy w naszym kontrakcie } //dzięki dodaniu TaskRepository w extends Spring wie, że przywołując TaskRepository idziemy do Bean'a Springowego SQLTaskRepository /* @Override @RestResource(exported = false) //informacja że mogę tak zrobić jest w dokumentacji. Dzięki temu blokuję dostęp do danego zapytania (DELETE), nie mogę wysłać metody http DELETE. //adnotacja RestResource, ctrl + spacja pokazuje co mogę tam wpisać. void deleteById(Integer integer); // repozytoria Spring (SpringData) to DSL - domain specific language. // Domena to procesowanie kolekcji, pod spodem łączenie się z bazą danych. Wszystkie metody są tłumaczone na zapytania SQL (bo mamy JPA). Możemy stwożyć własne metody albo nadpisywać dostępne. @Override @RestResource(exported = false) void delete(Task entity); @RestResource(path = "done", rel = "done")//relacja, hipermedia, łącze do adresu //zmieniam adres, podobnie List<Task> findByDone(@Param("state")boolean done);//wersja Ultimate IntelliJ podpowiedziałaby mi jakie mam opcje i po czym mogę szukać, opcji jest dużo (włącznie z szukaniem w opisie). Można określać wartość flagi. // Ta metoda, dzięki @RepositoryRestResource jest już dostępna pod jakimś adresem. //dzięki @Param mogę po adresie przekazać wartość. Wysyłając medotę HTML na adres http://localhost:8080/tasks/search/done?state=true dostaję w odpowiedzi taski z wartością done true //tag "_embedded w odpowiedzi JSON oznacza obiekty // _links to pomocnicze nakierowania co z kolekcją możemy zrobić. To wszystko bierze się z RestRepository Springa. //HATEOAS - stan aplikacji reprezentowany przez hipermedia (metadane). Właśnie _embedded, _links. // Lista tasków jest zwracan aobudowana w obiekt _embedded. To rozszerzony REST. */
Jacentus/todoapp
src/main/java/todoapp/todoapp/adapter/SqlTaskRepository.java
1,336
//metoda existsbyID jest nadpisywana TaskRepository, wykonuje się query natywne SQL.
line_comment
pl
package todoapp.todoapp.adapter; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import todoapp.todoapp.model.Task; import todoapp.todoapp.model.TaskRepository; //klasa do komunikacji z bazą danych. Coś ala API, punkt wejścia do działania na kolekcji (w tym przypadku tasków) //interfejs dziedziczący po interfejsie z pakietu JPARepository, specyfikajca Javy jak podejść do ORM (obiect relational mapping) //JPA - SPEFYCIKACJA(interfejs) HIBERNATE - jego implementacja. //w JPA mamy w środku JDBC - konektor javowy do rozmowy z bazą danych. //HIKARICP (Hikary connection pool). Pula połączeń do bazy danych. // JpaRepository. Przekazujemy info z jakiej encji // powinno brać dane oraz jaki jest jej identyfikator (mamy int) // rezygnujemy z adnotacji @RepositoryRestResource na rzecz @Repository, też zarządza tym Spring ale //możemy dać dodatkowe parametry, min:(path = "todos", collectionResourceRel = "todos") //nasze repozytorium działa na obiektach TASK, stąd w adresie URL Spring daje defaultowo Tasks. Tu zmieniamy odpowiednio. Mogę o tym przeczytać w dokuementacji (ctrl+b) //tworzymy interfejs REST dający nam metody dostępu do baz danych (SPRING wie co dać) //już jedna adnotacja (wyżej) i interfejs bazowy pozwala na wszystkie operacje typu CRUD w oparciu o stronicowanie i sortowanie @Repository interface SqlTaskRepository extends TaskRepository, JpaRepository<Task, Integer> { @Override//metoda existsbyID <SUF> @Query(nativeQuery = true, value = "select count(*) > 0 from tasks where id=:id") //adnotacja springowa, pozwala korzystac z "czystego" SQL. Dwukropek ID - dzięki temu możemy używać @Param. Mając SELECT* moglibyśmy zwracać obiekt klasy Task!!! boolean existsById(@Param("id")Integer id); @Override boolean existsByDoneIsFalseAndGroup_Id(Integer group_id); //sygnatura metody którą udostępniamy w naszym kontrakcie } //dzięki dodaniu TaskRepository w extends Spring wie, że przywołując TaskRepository idziemy do Bean'a Springowego SQLTaskRepository /* @Override @RestResource(exported = false) //informacja że mogę tak zrobić jest w dokumentacji. Dzięki temu blokuję dostęp do danego zapytania (DELETE), nie mogę wysłać metody http DELETE. //adnotacja RestResource, ctrl + spacja pokazuje co mogę tam wpisać. void deleteById(Integer integer); // repozytoria Spring (SpringData) to DSL - domain specific language. // Domena to procesowanie kolekcji, pod spodem łączenie się z bazą danych. Wszystkie metody są tłumaczone na zapytania SQL (bo mamy JPA). Możemy stwożyć własne metody albo nadpisywać dostępne. @Override @RestResource(exported = false) void delete(Task entity); @RestResource(path = "done", rel = "done")//relacja, hipermedia, łącze do adresu //zmieniam adres, podobnie List<Task> findByDone(@Param("state")boolean done);//wersja Ultimate IntelliJ podpowiedziałaby mi jakie mam opcje i po czym mogę szukać, opcji jest dużo (włącznie z szukaniem w opisie). Można określać wartość flagi. // Ta metoda, dzięki @RepositoryRestResource jest już dostępna pod jakimś adresem. //dzięki @Param mogę po adresie przekazać wartość. Wysyłając medotę HTML na adres http://localhost:8080/tasks/search/done?state=true dostaję w odpowiedzi taski z wartością done true //tag "_embedded w odpowiedzi JSON oznacza obiekty // _links to pomocnicze nakierowania co z kolekcją możemy zrobić. To wszystko bierze się z RestRepository Springa. //HATEOAS - stan aplikacji reprezentowany przez hipermedia (metadane). Właśnie _embedded, _links. // Lista tasków jest zwracan aobudowana w obiekt _embedded. To rozszerzony REST. */
2507_1
package encapsulation.car; /** * Silnik samochodu. */ public class Engine { /** * Do tej metody dostęp powinien mieć tylko obiekt samochodu. */ public void startEngine() {/***/} }
JakZostacProgramista/CvProgramisty-ProgramowanieObiektowe
src/encapsulation/car/Engine.java
71
/** * Do tej metody dostęp powinien mieć tylko obiekt samochodu. */
block_comment
pl
package encapsulation.car; /** * Silnik samochodu. */ public class Engine { /** * Do tej metody <SUF>*/ public void startEngine() {/***/} }
9018_3
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; public class Main { public static void main(String[] args) { Address address = new Address("Legnica", "Sejmowa"); Male male1 = new Male("A", "Aa", 1, address); Male male2 = new Male("Bb", "Bbb", 2, address); Female female = new Female("Cc", "Ccc", 3, address); Person[] persons = {male1, male2, female}; System.out.println("Dane wszystkich osób:"); for (Person person : persons) { person.printDetails(); System.out.println(); } System.out.println("Wiek przechodzenia na emeryturę:"); for (Person person : persons) { System.out.println(person.getName() + " " + person.getSurname() + ": " + person.getRetirementAge()); } System.out.println("Rok urodzenia:"); for (Person person : persons) { System.out.println(person.getName() + " " + person.getSurname() + ": " + person.getBirthYear()); } // Tworzenie listy females z obiektami klasy Female ArrayList<Female> females = new ArrayList<>(); for (Person person : persons) { if (person instanceof Female) { females.add((Female) person); } } // Sortowanie females po długości imienia w porządku rosnącym Collections.sort(females, new Comparator<Female>() { @Override public int compare(Female f1, Female f2) { return Integer.compare(f1.getName().length(), f2.getName().length()); } }); System.out.println("Posortowane females według długości imienia (rosnąco):"); for (Female femalePerson : females) { femalePerson.printDetails(); System.out.println(); } // Liczenie liczby mężczyzn i kobiet w persons int maleCount = 0; int femaleCount = 0; for (Person person : persons) { if (person instanceof Male) { maleCount++; } else if (person instanceof Female) { femaleCount++; } } System.out.println("Liczba mężczyzn: " + maleCount); System.out.println("Liczba kobiet: " + femaleCount); // Tworzenie kopii obiektu male Male male = new Male("D", "Dd", 4, address); Male clonedMale = (Male) male.clone(); male.getAddress().setCity("TEST"); System.out.println("Dane obiektu male:"); male.printDetails(); System.out.println("Dane obiektu clonedMale:"); clonedMale.printDetails(); } }
Jaktaktonie/Java-samples
Java007/src/Main.java
791
// Tworzenie kopii obiektu male
line_comment
pl
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; public class Main { public static void main(String[] args) { Address address = new Address("Legnica", "Sejmowa"); Male male1 = new Male("A", "Aa", 1, address); Male male2 = new Male("Bb", "Bbb", 2, address); Female female = new Female("Cc", "Ccc", 3, address); Person[] persons = {male1, male2, female}; System.out.println("Dane wszystkich osób:"); for (Person person : persons) { person.printDetails(); System.out.println(); } System.out.println("Wiek przechodzenia na emeryturę:"); for (Person person : persons) { System.out.println(person.getName() + " " + person.getSurname() + ": " + person.getRetirementAge()); } System.out.println("Rok urodzenia:"); for (Person person : persons) { System.out.println(person.getName() + " " + person.getSurname() + ": " + person.getBirthYear()); } // Tworzenie listy females z obiektami klasy Female ArrayList<Female> females = new ArrayList<>(); for (Person person : persons) { if (person instanceof Female) { females.add((Female) person); } } // Sortowanie females po długości imienia w porządku rosnącym Collections.sort(females, new Comparator<Female>() { @Override public int compare(Female f1, Female f2) { return Integer.compare(f1.getName().length(), f2.getName().length()); } }); System.out.println("Posortowane females według długości imienia (rosnąco):"); for (Female femalePerson : females) { femalePerson.printDetails(); System.out.println(); } // Liczenie liczby mężczyzn i kobiet w persons int maleCount = 0; int femaleCount = 0; for (Person person : persons) { if (person instanceof Male) { maleCount++; } else if (person instanceof Female) { femaleCount++; } } System.out.println("Liczba mężczyzn: " + maleCount); System.out.println("Liczba kobiet: " + femaleCount); // Tworzenie kopii <SUF> Male male = new Male("D", "Dd", 4, address); Male clonedMale = (Male) male.clone(); male.getAddress().setCity("TEST"); System.out.println("Dane obiektu male:"); male.printDetails(); System.out.println("Dane obiektu clonedMale:"); clonedMale.printDetails(); } }
5682_0
import java.util.Collection; import java.util.Collections; import java.util.LinkedList; public class Main { public static void main(String[] args) { System.out.println("Hello world!"); // generic tam gdzie możemy dostawiać typy <...> LinkedList<String> grupa = new LinkedList<>();// zobacz gdzie String grupa.add("Kowalski"); grupa.add("Nowak"); grupa.add("Adamowski"); Collections.sort(grupa); for (String x: grupa){ System.out.println(x); } Student s1 = new Student("Adam", "Adamski"); s1.addOcena(5); s1.addOcena(3); Student s2 = new Student("Adam", "Adamski"); s2.addOcena(4); s2.addOcena(4); Student s3 = new Student("Adam", "Abba"); s3.addOcena(5); s3.addOcena(4); LinkedList<Student> grupaFull = new LinkedList<>(); grupaFull.add(s1); grupaFull.add(s2); grupaFull.add(s3); Collections.sort(grupaFull); System.out.println(grupaFull); } }
Jakub0627/KNPM
Java/kolekcje/src/Main.java
361
// generic tam gdzie możemy dostawiać typy <...>
line_comment
pl
import java.util.Collection; import java.util.Collections; import java.util.LinkedList; public class Main { public static void main(String[] args) { System.out.println("Hello world!"); // generic tam <SUF> LinkedList<String> grupa = new LinkedList<>();// zobacz gdzie String grupa.add("Kowalski"); grupa.add("Nowak"); grupa.add("Adamowski"); Collections.sort(grupa); for (String x: grupa){ System.out.println(x); } Student s1 = new Student("Adam", "Adamski"); s1.addOcena(5); s1.addOcena(3); Student s2 = new Student("Adam", "Adamski"); s2.addOcena(4); s2.addOcena(4); Student s3 = new Student("Adam", "Abba"); s3.addOcena(5); s3.addOcena(4); LinkedList<Student> grupaFull = new LinkedList<>(); grupaFull.add(s1); grupaFull.add(s2); grupaFull.add(s3); Collections.sort(grupaFull); System.out.println(grupaFull); } }
6376_0
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <title>ZD4</title> </head> <body> <div> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis quis molestie arcu. Proin a laoreet neque, sed mollis dui. Etiam a nulla et massa sollicitudin luctus. Curabitur nibh nibh, finibus luctus mollis non, consectetur a sapien. Proin viverra nunc a volutpat dapibus. Aenean euismod sem velit, eu rhoncus enim sollicitudin quis. Nunc pretium, erat sit amet tempus convallis, ligula turpis ullamcorper enim, et consequat nibh erat vel libero. Donec interdum vitae lectus eget tempus. Praesent rutrum maximus mauris. Proin ante ipsum, lacinia nec scelerisque sit amet, venenatis vel elit. Donec tincidunt, sapien sed porttitor rutrum, sapien dui consectetur purus, ac congue dui felis id massa. Sed facilisis vitae nulla in porta. Morbi a ante nisl. Donec blandit augue augue, in tincidunt tellus sodales a. Nullam blandit malesuada sapien non auctor. Aliquam volutpat, diam ac vestibulum commodo, ante lectus consectetur purus, ac porttitor nisi dui eu tellus. In ipsum nunc, hendrerit non suscipit a, auctor a enim. Quisque sollicitudin risus venenatis malesuada interdum. Aenean ut nunc diam. Proin non magna libero. Quisque eu congue orci. </div> <script> function getRandomIntInclusive(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; } // Bierzemy diva const div = document.querySelector('div'); const colors = ['red', 'green', 'orange', 'gray', 'white'] // Przypisujemy zdarzenie klikacz div.addEventListener('click', (event)=>{ // Zmiana koloru czcionki let los = getRandomIntInclusive(0,4); div.style.color = colors[los]; }); // Zdarzenia div.addEventListener('mouseover', (event)=>{ div.textContent = "Bardzo dobra robota"; }); div.addEventListener('mouseout', (event)=>{ div.textContent = "A elegancko"; }); </script> </body> </html>
JakubZS4/Lipien-ZS4
zdarzenia.Java
802
// Przypisujemy zdarzenie klikacz
line_comment
pl
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <title>ZD4</title> </head> <body> <div> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis quis molestie arcu. Proin a laoreet neque, sed mollis dui. Etiam a nulla et massa sollicitudin luctus. Curabitur nibh nibh, finibus luctus mollis non, consectetur a sapien. Proin viverra nunc a volutpat dapibus. Aenean euismod sem velit, eu rhoncus enim sollicitudin quis. Nunc pretium, erat sit amet tempus convallis, ligula turpis ullamcorper enim, et consequat nibh erat vel libero. Donec interdum vitae lectus eget tempus. Praesent rutrum maximus mauris. Proin ante ipsum, lacinia nec scelerisque sit amet, venenatis vel elit. Donec tincidunt, sapien sed porttitor rutrum, sapien dui consectetur purus, ac congue dui felis id massa. Sed facilisis vitae nulla in porta. Morbi a ante nisl. Donec blandit augue augue, in tincidunt tellus sodales a. Nullam blandit malesuada sapien non auctor. Aliquam volutpat, diam ac vestibulum commodo, ante lectus consectetur purus, ac porttitor nisi dui eu tellus. In ipsum nunc, hendrerit non suscipit a, auctor a enim. Quisque sollicitudin risus venenatis malesuada interdum. Aenean ut nunc diam. Proin non magna libero. Quisque eu congue orci. </div> <script> function getRandomIntInclusive(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; } // Bierzemy diva const div = document.querySelector('div'); const colors = ['red', 'green', 'orange', 'gray', 'white'] // Przypisujemy zdarzenie <SUF> div.addEventListener('click', (event)=>{ // Zmiana koloru czcionki let los = getRandomIntInclusive(0,4); div.style.color = colors[los]; }); // Zdarzenia div.addEventListener('mouseover', (event)=>{ div.textContent = "Bardzo dobra robota"; }); div.addEventListener('mouseout', (event)=>{ div.textContent = "A elegancko"; }); </script> </body> </html>
3982_0
import java.util.ArrayList; public class Processor { protected ArrayList<Task> waitingTasks; protected ArrayList<Task> runningTasks; protected ArrayList<Task> doneTasks; protected ArrayList<Integer> loadHistory = new ArrayList<>(); public Processor(ArrayList<Task> tasks) { waitingTasks = tasks; runningTasks = new ArrayList<>(); doneTasks = new ArrayList<>(); } public int currentLoad() { int load = 0; for (Task task : runningTasks) { load += task.load; } return load; } public void doActiveTasks() { runningTasks.forEach(task -> task.timeLeft--); for (Task task: runningTasks) { if (task.timeLeft <=0) doneTasks.add(task); } runningTasks.removeAll(doneTasks); } public boolean activateTask() { if (waitingTasks.size() > 0) { runningTasks.add(waitingTasks.remove(0)); return true; } else return false; } public Task getLatestTask() { if (runningTasks.isEmpty()) return new Task(0,0); // Puste zadanie które nigdy się nie wykona, więc nie wpłynie na symulacje. (odpowiednik null-a) return runningTasks.get(runningTasks.size() - 1); } public void reset() { // Przywracam wszystkie zadania do oczekujących i resetuje ich czas wykonania. waitingTasks.addAll(runningTasks); runningTasks.clear(); waitingTasks.addAll(doneTasks); doneTasks.clear(); waitingTasks.forEach(Task::reset); } public void logLoad() { // Zapisuje obecne obciążenie procesora. loadHistory.add(currentLoad()); } public int getAverageLoad() { int sum = 0; for (Integer load : loadHistory) { sum += load; } return sum / loadHistory.size(); } }
JanMaciuk/SO_Lab_5
src/Processor.java
528
// Puste zadanie które nigdy się nie wykona, więc nie wpłynie na symulacje. (odpowiednik null-a)
line_comment
pl
import java.util.ArrayList; public class Processor { protected ArrayList<Task> waitingTasks; protected ArrayList<Task> runningTasks; protected ArrayList<Task> doneTasks; protected ArrayList<Integer> loadHistory = new ArrayList<>(); public Processor(ArrayList<Task> tasks) { waitingTasks = tasks; runningTasks = new ArrayList<>(); doneTasks = new ArrayList<>(); } public int currentLoad() { int load = 0; for (Task task : runningTasks) { load += task.load; } return load; } public void doActiveTasks() { runningTasks.forEach(task -> task.timeLeft--); for (Task task: runningTasks) { if (task.timeLeft <=0) doneTasks.add(task); } runningTasks.removeAll(doneTasks); } public boolean activateTask() { if (waitingTasks.size() > 0) { runningTasks.add(waitingTasks.remove(0)); return true; } else return false; } public Task getLatestTask() { if (runningTasks.isEmpty()) return new Task(0,0); // Puste zadanie <SUF> return runningTasks.get(runningTasks.size() - 1); } public void reset() { // Przywracam wszystkie zadania do oczekujących i resetuje ich czas wykonania. waitingTasks.addAll(runningTasks); runningTasks.clear(); waitingTasks.addAll(doneTasks); doneTasks.clear(); waitingTasks.forEach(Task::reset); } public void logLoad() { // Zapisuje obecne obciążenie procesora. loadHistory.add(currentLoad()); } public int getAverageLoad() { int sum = 0; for (Integer load : loadHistory) { sum += load; } return sum / loadHistory.size(); } }
6890_11
//Stwórz klasę AdvancedCalculator, która dziedziczy po klasie Calculator. Klasa powinna implementować następujące metody: // //pow(num1, num2) – metoda ma zwracać num1 do potęgi num2. Dodatkowo w tablicy operacji ma zapamiętać napis: "num1^num2 equals result". //root(num1, num2) – metoda ma wyliczyć pierwiastek num2 stopni //Do klasy AdvancedCalculator dopisz: // //stałą PI, która będzie miała przypisaną wartość 3.14159265, //statyczną metodę computeCircleArea(r), która będzie zwracała pole koła. Ta metoda nie będzie dopisywać obliczeń do tablicy (napisz w komentarzu, dlaczego nie może tego robić), //statyczną tablicę, która będzie przechowywała historię operacji wykonanych na wszystkich kalkulatorach, //statyczną metodę printGlobalOperations(), która będzie wyświetlała wszystkie operacje ze wszystkich obiektów klasy AdvancedCalculator. // ZAD 2 //Do klasy AdvancedCalculator dopisz: // //przeciążoną metodę printGlobalOperations(int length), która wyświetli określoną liczbę ostatnich operacji, //przeciążoną metodę printGlobalOperations(String length), która wyświetli określoną liczbę ostatnich operacji. package org.example; import java.util.Arrays; public class AdvancedCalculator extends Calculator { final static double PI = 3.14159265; static String[] globalArr = new String[0]; public double pow(double num1, double num2) { double result = Math.pow(num1, num2); addOperation(num1 + " ^ " + num2 + " equals " + result); return result; } public double root(double num1, double num2) { double result = Math.round(Math.pow(num1, (1 / num2))); addOperation(num2 + " root of " + num1 + " equals " + result); return result; } public static double computeCircleArea(double r) { // metoda nie może dodawać do tablicy bo jest static, więc mozemy z niej korzystać bez utworzenia obiektu // i przez to nie bedzie utworzona tablica return 2 * PI * r; } @Override public String[] addOperation(String text) { String[] toReturn = super.addOperation(text); globalArr = Arrays.copyOf(globalArr, globalArr.length + 1); globalArr[globalArr.length - 1] = text; return toReturn; } public static void printGlobalOperations() { for (String item : globalArr) { System.out.println(item); } } public static void printGlobalOperations(int length) { if (globalArr.length > length) { for (int i = length; i > 0; i--) { System.out.println(globalArr[globalArr.length - 1 - i]); } } else { System.out.println("Array is not long enough"); for (String item : globalArr) { System.out.println(item); } } } public static void printGlobalOperations(String length) { try { int len = Integer.parseInt(length); if (globalArr.length > len) { for (int i = len; i > 0; i--) { System.out.println(globalArr[globalArr.length - 1 - i]); } } else { System.out.println("Array is not long enough"); for (String item : globalArr) { System.out.println(item); } } } catch (NumberFormatException e) { System.out.println("Wrong argument"); } } }
Jasiu-Code/Chapter2
OOP/OOP-Day2/src/main/java/org/example/AdvancedCalculator.java
1,089
// metoda nie może dodawać do tablicy bo jest static, więc mozemy z niej korzystać bez utworzenia obiektu
line_comment
pl
//Stwórz klasę AdvancedCalculator, która dziedziczy po klasie Calculator. Klasa powinna implementować następujące metody: // //pow(num1, num2) – metoda ma zwracać num1 do potęgi num2. Dodatkowo w tablicy operacji ma zapamiętać napis: "num1^num2 equals result". //root(num1, num2) – metoda ma wyliczyć pierwiastek num2 stopni //Do klasy AdvancedCalculator dopisz: // //stałą PI, która będzie miała przypisaną wartość 3.14159265, //statyczną metodę computeCircleArea(r), która będzie zwracała pole koła. Ta metoda nie będzie dopisywać obliczeń do tablicy (napisz w komentarzu, dlaczego nie może tego robić), //statyczną tablicę, która będzie przechowywała historię operacji wykonanych na wszystkich kalkulatorach, //statyczną metodę printGlobalOperations(), która będzie wyświetlała wszystkie operacje ze wszystkich obiektów klasy AdvancedCalculator. // ZAD 2 //Do klasy AdvancedCalculator dopisz: // //przeciążoną metodę printGlobalOperations(int length), która wyświetli określoną liczbę ostatnich operacji, //przeciążoną metodę printGlobalOperations(String length), która wyświetli określoną liczbę ostatnich operacji. package org.example; import java.util.Arrays; public class AdvancedCalculator extends Calculator { final static double PI = 3.14159265; static String[] globalArr = new String[0]; public double pow(double num1, double num2) { double result = Math.pow(num1, num2); addOperation(num1 + " ^ " + num2 + " equals " + result); return result; } public double root(double num1, double num2) { double result = Math.round(Math.pow(num1, (1 / num2))); addOperation(num2 + " root of " + num1 + " equals " + result); return result; } public static double computeCircleArea(double r) { // metoda nie <SUF> // i przez to nie bedzie utworzona tablica return 2 * PI * r; } @Override public String[] addOperation(String text) { String[] toReturn = super.addOperation(text); globalArr = Arrays.copyOf(globalArr, globalArr.length + 1); globalArr[globalArr.length - 1] = text; return toReturn; } public static void printGlobalOperations() { for (String item : globalArr) { System.out.println(item); } } public static void printGlobalOperations(int length) { if (globalArr.length > length) { for (int i = length; i > 0; i--) { System.out.println(globalArr[globalArr.length - 1 - i]); } } else { System.out.println("Array is not long enough"); for (String item : globalArr) { System.out.println(item); } } } public static void printGlobalOperations(String length) { try { int len = Integer.parseInt(length); if (globalArr.length > len) { for (int i = len; i > 0; i--) { System.out.println(globalArr[globalArr.length - 1 - i]); } } else { System.out.println("Array is not long enough"); for (String item : globalArr) { System.out.println(item); } } } catch (NumberFormatException e) { System.out.println("Wrong argument"); } } }
2435_1
import com.maplesoft.openmaple.*; import com.maplesoft.externalcall.MapleException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; public class MapleTerminal { private static MapleTerminal instance = null; private String a[]; private Engine t; private String answer; private PrintStream dummyStream; private MapleTerminal(){ try{ a = new String[1]; a[0] = "java"; t = new Engine( a, new EngineCallBacksDefault(), null, null ); // Mozna uruchomić tylko jeden silnik naraz (dlatego singleton) dummyStream = new PrintStream(new OutputStream() { // evaluate jest napisane tak, ze wypisuje wynik, dummy stream sluzy do blokowania tego @Override public void write(int b) throws IOException { } }); } catch (MapleException e){ System.out.println(e.getMessage()); } } public static MapleTerminal getInstance(){ if (instance == null) instance = new MapleTerminal(); return instance; } public String evaluate(String query){ try{ PrintStream originalStream = System.out; System.setOut(dummyStream); answer = String.valueOf(t.evaluate(query)); System.setOut(originalStream); } catch (MapleException e){ // lapie wyjatki prosto z Maple answer = e.getMessage(); } return answer; } }
Java2016-2017-grupa-1/MaplePlugin
MapleViaJava/MapleTerminal.java
414
// evaluate jest napisane tak, ze wypisuje wynik, dummy stream sluzy do blokowania tego
line_comment
pl
import com.maplesoft.openmaple.*; import com.maplesoft.externalcall.MapleException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; public class MapleTerminal { private static MapleTerminal instance = null; private String a[]; private Engine t; private String answer; private PrintStream dummyStream; private MapleTerminal(){ try{ a = new String[1]; a[0] = "java"; t = new Engine( a, new EngineCallBacksDefault(), null, null ); // Mozna uruchomić tylko jeden silnik naraz (dlatego singleton) dummyStream = new PrintStream(new OutputStream() { // evaluate jest <SUF> @Override public void write(int b) throws IOException { } }); } catch (MapleException e){ System.out.println(e.getMessage()); } } public static MapleTerminal getInstance(){ if (instance == null) instance = new MapleTerminal(); return instance; } public String evaluate(String query){ try{ PrintStream originalStream = System.out; System.setOut(dummyStream); answer = String.valueOf(t.evaluate(query)); System.setOut(originalStream); } catch (MapleException e){ // lapie wyjatki prosto z Maple answer = e.getMessage(); } return answer; } }
8762_1
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package marinesmud.tap.commands; import java.util.Arrays; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import marinesmud.tap.commands.annotations.ForAdmins; import marinesmud.tap.commands.annotations.MaxParameters; import marinesmud.tap.commands.annotations.MinParameters; import marinesmud.tap.commands.annotations.MinimalCommandLength; import marinesmud.tap.commands.annotations.NoParameters; import marinesmud.tap.commands.annotations.ParametersCount; import marinesmud.tap.commands.annotations.RestPositionDisallowed; import marinesmud.tap.commands.annotations.ShortDescription; import marinesmud.tap.commands.annotations.SleepPositionDisallowed; import marinesmud.tap.commands.annotations.StandPositionDisallowed; import marinesmud.system.Config; import pl.jblew.code.jutils.data.containers.tuples.FourTuple; import marinesmud.tap.commands.annotations.Aliased; import marinesmud.world.Position; import marinesmud.tap.commands.annotations.FightPositionDisallowed; import marinesmud.tap.TelnetGameplay; import marinesmud.world.beings.Player; import pl.jblew.code.jutils.utils.ExceptionUtils; import pl.jblew.code.jutils.utils.TextUtils; /** * * * @author jblew * @license Kod jest objęty licencją zawartą w pliku LICESNE */ class BooleanStringMethodObjectTuple extends FourTuple<Boolean, String, Method, Object> { public BooleanStringMethodObjectTuple(Boolean b, String s, Method m, Object o) { super(b, s, m, o); } } public final class CommandRouter { private final TelnetGameplay telnetGameplay; private final Player player; private String input = null; private String commandName = null; private String commandData = ""; private LinkedList<String> commandParams = new LinkedList<String>(); private BooleanStringMethodObjectTuple[] commands = null; public CommandRouter(TelnetGameplay telnetGameplay, Player player) { this.telnetGameplay = telnetGameplay; this.player = player; try { commands = new BooleanStringMethodObjectTuple[]{ generateCommandTuple(false, "gecho", AdminCommands.getInstance()), generateCommandTuple(false, "mtime", AdminCommands.getInstance()), generateCommandTuple(false, "look", AreaCommands.getInstance()), generateCommandTuple(false, "immtalk", AdminCommands.getInstance()), generateCommandTuple(false, "say", CommunicationCommands.getInstance()), generateCommandTuple(false, "help", HelpCommand.getInstance()), generateCommandTuple(false, "idea", IdeaBugTodoCommands.getInstance()), generateCommandTuple(false, "bug", IdeaBugTodoCommands.getInstance()), generateCommandTuple(false, "todo", IdeaBugTodoCommands.getInstance()), generateCommandTuple(false, "stand", PositionCommands.getInstance()), generateCommandTuple(false, "rest", PositionCommands.getInstance()), generateCommandTuple(false, "sleep", PositionCommands.getInstance()), generateCommandTuple(false, "wake", PositionCommands.getInstance()) }; } catch (NoSuchMethodException ex) { Logger.getLogger(CommandRouter.class.getName()).log(Level.SEVERE, null, ex); } catch (SecurityException ex) { Logger.getLogger(CommandRouter.class.getName()).log(Level.SEVERE, null, ex); } } private BooleanStringMethodObjectTuple generateCommandTuple(boolean isAliased, String commandName, Object instance) throws NoSuchMethodException { return (new BooleanStringMethodObjectTuple(isAliased, commandName, instance.getClass().getDeclaredMethod(commandName, CommandRouter.class), instance)); } private BooleanStringMethodObjectTuple generateCommandTuple(boolean isAliased, String commandName, String methodName, Object instance) throws NoSuchMethodException { return (new BooleanStringMethodObjectTuple(isAliased, commandName, instance.getClass().getDeclaredMethod(methodName, CommandRouter.class), instance)); } public String command(String input_) { String out = ""; String errorMessage = ""; boolean commandFine = false; input = input_; commandParams.clear(); commandName = ""; commandData = ""; String logEntry = ""; logEntry += "[" + player.getName() + "] " + input; List<Map<String, String>> fastCommandShortcut = Config.getList("fast commands shortcuts"); for (Map<String, String> m : fastCommandShortcut) { String shortcut = m.get("shortcut"); String command = m.get("command"); if (input.trim().equalsIgnoreCase(shortcut)) { input = ("hh235h" + input).replace("hh235h" + shortcut, command); logEntry += " FCS{" + command + "}"; } else if (input.trim().toLowerCase().startsWith(shortcut)) { input = ("hh235h" + input).replace("hh235h" + shortcut, command + " "); logEntry += " FCS{" + command + "=" + input + "}"; } } String[] inputParts = input.split(" ", 2); commandName = inputParts[0]; if (inputParts.length > 1) { commandData = inputParts[1].trim(); commandParams.addAll(Arrays.asList(commandData.split(" "))); } for (BooleanStringMethodObjectTuple command : getCommands()) { try { if (!command.first) { if (!command.third.isAnnotationPresent(ShortDescription.class)) { throw new MissingAnnotationException("Missing annotation ShortDescription in method " + command.third.getName() + "!"); } if (!command.third.isAnnotationPresent(MinimalCommandLength.class)) { throw new MissingAnnotationException("Missing annotation MinimalCommandLength in method " + command.third.getName() + "!"); } } if (command.second.startsWith(commandName) && commandName.length() >= command.third.getAnnotation(MinimalCommandLength.class).length()) { Position position = player.getPosition(); if (command.third.isAnnotationPresent(StandPositionDisallowed.class) && position == Position.STAND) { throw new CommandExecutionException(command.third.getAnnotation(StandPositionDisallowed.class).message()); } if (command.third.isAnnotationPresent(RestPositionDisallowed.class) && position == Position.REST) { throw new CommandExecutionException(command.third.getAnnotation(RestPositionDisallowed.class).message()); } if (command.third.isAnnotationPresent(SleepPositionDisallowed.class) && position == Position.SLEEP) { throw new CommandExecutionException(command.third.getAnnotation(SleepPositionDisallowed.class).message()); } if (command.third.isAnnotationPresent(FightPositionDisallowed.class) && position == Position.FIGHT) { throw new CommandExecutionException(command.third.getAnnotation(FightPositionDisallowed.class).message()); } if (command.third.isAnnotationPresent(ForAdmins.class) && !player.isAdmin()) { continue; } if (command.third.isAnnotationPresent(NoParameters.class) && commandParams.size() > 0) { throw new CommandExecutionException(TextUtils.ucfirst(command.third.getName()) + " nie wymaga żadnych parametrów. " + commandParams.size() + " to zbyt dużo."); } if (command.third.isAnnotationPresent(MinParameters.class) && commandParams.size() < command.third.getAnnotation(MinParameters.class).count()) { throw new CommandExecutionException(command.third.getAnnotation(MinParameters.class).message().replace("%minParametersCount", String.valueOf(command.third.getAnnotation(MinParameters.class).count())).replace("%methodName", command.third.getName())); } if (command.third.isAnnotationPresent(MaxParameters.class) && commandParams.size() > command.third.getAnnotation(MaxParameters.class).count()) { throw new CommandExecutionException(command.third.getAnnotation(MaxParameters.class).message().replace("%maxParametersCount", String.valueOf(command.third.getAnnotation(MaxParameters.class).count())).replace("%methodName", command.third.getName())); } if (command.third.isAnnotationPresent(ParametersCount.class) && commandParams.size() > command.third.getAnnotation(ParametersCount.class).count()) { throw new CommandExecutionException(command.third.getAnnotation(ParametersCount.class).tooManyMessage().replace("%wantedParametersCount", String.valueOf(command.third.getAnnotation(ParametersCount.class).count())).replace("%methodName", command.third.getName())); } if (command.third.isAnnotationPresent(ParametersCount.class) && commandParams.size() < command.third.getAnnotation(ParametersCount.class).count()) { throw new CommandExecutionException(command.third.getAnnotation(ParametersCount.class).notEnoughMessage().replace("%wantedParametersCount", String.valueOf(command.third.getAnnotation(ParametersCount.class).count())).replace("%methodName", command.third.getName())); } out += command.third.invoke(command.fourth, this); commandFine = true; break; //if no exception was thrown } else if (command.third.isAnnotationPresent(Aliased.class)) { out += command.third.invoke(command.fourth, this); commandFine = true; break; //if no exception was thrown } } catch (IllegalAccessException ex) { Logger.getLogger(CommandRouter.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalArgumentException ex) { Logger.getLogger(CommandRouter.class.getName()).log(Level.SEVERE, null, ex); } catch (InvocationTargetException ex) { if (ex.getCause() instanceof CommandExecutionException) { errorMessage = ex.getMessage(); } else { commandFine = true; out += "Wystąpił błąd podczas wykonywania komendy. Przepraszamy.\n"; if (player.isAdmin()) { out += ExceptionUtils.getLongDescription(ex.getCause()) + "\n"; ex.getCause().getStackTrace(); } Logger.getLogger(CommandRouter.class.getName()).log(Level.SEVERE, null, ex.getCause()); break; } } catch (CommandExecutionException ex) { errorMessage = ex.getMessage(); } } if (!commandFine) { if (!errorMessage.isEmpty()) { out += errorMessage.replace("%parametersCount", String.valueOf(commandParams.size())) + "\n"; } else { out += "Masz jakiś problem!?\n"; } } Logger.getLogger("Commands").log(Level.INFO, logEntry); return out; } public Player getPlayer() { return player; } public String getCommandData() { return commandData; } public String getCommandName() { return commandName; } public List<String> getParams() { return Collections.unmodifiableList(commandParams); } public String getInput() { return input; } public void cleanCommands() { } public BooleanStringMethodObjectTuple[] getCommands() { return commands; } public void setCommands(BooleanStringMethodObjectTuple[] commands) { this.commands = commands; } }
Jblew/marines-mud
src/marinesmud/tap/commands/CommandRouter.java
3,222
/** * * * @author jblew * @license Kod jest objęty licencją zawartą w pliku LICESNE */
block_comment
pl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package marinesmud.tap.commands; import java.util.Arrays; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import marinesmud.tap.commands.annotations.ForAdmins; import marinesmud.tap.commands.annotations.MaxParameters; import marinesmud.tap.commands.annotations.MinParameters; import marinesmud.tap.commands.annotations.MinimalCommandLength; import marinesmud.tap.commands.annotations.NoParameters; import marinesmud.tap.commands.annotations.ParametersCount; import marinesmud.tap.commands.annotations.RestPositionDisallowed; import marinesmud.tap.commands.annotations.ShortDescription; import marinesmud.tap.commands.annotations.SleepPositionDisallowed; import marinesmud.tap.commands.annotations.StandPositionDisallowed; import marinesmud.system.Config; import pl.jblew.code.jutils.data.containers.tuples.FourTuple; import marinesmud.tap.commands.annotations.Aliased; import marinesmud.world.Position; import marinesmud.tap.commands.annotations.FightPositionDisallowed; import marinesmud.tap.TelnetGameplay; import marinesmud.world.beings.Player; import pl.jblew.code.jutils.utils.ExceptionUtils; import pl.jblew.code.jutils.utils.TextUtils; /** * * * @author jblew <SUF>*/ class BooleanStringMethodObjectTuple extends FourTuple<Boolean, String, Method, Object> { public BooleanStringMethodObjectTuple(Boolean b, String s, Method m, Object o) { super(b, s, m, o); } } public final class CommandRouter { private final TelnetGameplay telnetGameplay; private final Player player; private String input = null; private String commandName = null; private String commandData = ""; private LinkedList<String> commandParams = new LinkedList<String>(); private BooleanStringMethodObjectTuple[] commands = null; public CommandRouter(TelnetGameplay telnetGameplay, Player player) { this.telnetGameplay = telnetGameplay; this.player = player; try { commands = new BooleanStringMethodObjectTuple[]{ generateCommandTuple(false, "gecho", AdminCommands.getInstance()), generateCommandTuple(false, "mtime", AdminCommands.getInstance()), generateCommandTuple(false, "look", AreaCommands.getInstance()), generateCommandTuple(false, "immtalk", AdminCommands.getInstance()), generateCommandTuple(false, "say", CommunicationCommands.getInstance()), generateCommandTuple(false, "help", HelpCommand.getInstance()), generateCommandTuple(false, "idea", IdeaBugTodoCommands.getInstance()), generateCommandTuple(false, "bug", IdeaBugTodoCommands.getInstance()), generateCommandTuple(false, "todo", IdeaBugTodoCommands.getInstance()), generateCommandTuple(false, "stand", PositionCommands.getInstance()), generateCommandTuple(false, "rest", PositionCommands.getInstance()), generateCommandTuple(false, "sleep", PositionCommands.getInstance()), generateCommandTuple(false, "wake", PositionCommands.getInstance()) }; } catch (NoSuchMethodException ex) { Logger.getLogger(CommandRouter.class.getName()).log(Level.SEVERE, null, ex); } catch (SecurityException ex) { Logger.getLogger(CommandRouter.class.getName()).log(Level.SEVERE, null, ex); } } private BooleanStringMethodObjectTuple generateCommandTuple(boolean isAliased, String commandName, Object instance) throws NoSuchMethodException { return (new BooleanStringMethodObjectTuple(isAliased, commandName, instance.getClass().getDeclaredMethod(commandName, CommandRouter.class), instance)); } private BooleanStringMethodObjectTuple generateCommandTuple(boolean isAliased, String commandName, String methodName, Object instance) throws NoSuchMethodException { return (new BooleanStringMethodObjectTuple(isAliased, commandName, instance.getClass().getDeclaredMethod(methodName, CommandRouter.class), instance)); } public String command(String input_) { String out = ""; String errorMessage = ""; boolean commandFine = false; input = input_; commandParams.clear(); commandName = ""; commandData = ""; String logEntry = ""; logEntry += "[" + player.getName() + "] " + input; List<Map<String, String>> fastCommandShortcut = Config.getList("fast commands shortcuts"); for (Map<String, String> m : fastCommandShortcut) { String shortcut = m.get("shortcut"); String command = m.get("command"); if (input.trim().equalsIgnoreCase(shortcut)) { input = ("hh235h" + input).replace("hh235h" + shortcut, command); logEntry += " FCS{" + command + "}"; } else if (input.trim().toLowerCase().startsWith(shortcut)) { input = ("hh235h" + input).replace("hh235h" + shortcut, command + " "); logEntry += " FCS{" + command + "=" + input + "}"; } } String[] inputParts = input.split(" ", 2); commandName = inputParts[0]; if (inputParts.length > 1) { commandData = inputParts[1].trim(); commandParams.addAll(Arrays.asList(commandData.split(" "))); } for (BooleanStringMethodObjectTuple command : getCommands()) { try { if (!command.first) { if (!command.third.isAnnotationPresent(ShortDescription.class)) { throw new MissingAnnotationException("Missing annotation ShortDescription in method " + command.third.getName() + "!"); } if (!command.third.isAnnotationPresent(MinimalCommandLength.class)) { throw new MissingAnnotationException("Missing annotation MinimalCommandLength in method " + command.third.getName() + "!"); } } if (command.second.startsWith(commandName) && commandName.length() >= command.third.getAnnotation(MinimalCommandLength.class).length()) { Position position = player.getPosition(); if (command.third.isAnnotationPresent(StandPositionDisallowed.class) && position == Position.STAND) { throw new CommandExecutionException(command.third.getAnnotation(StandPositionDisallowed.class).message()); } if (command.third.isAnnotationPresent(RestPositionDisallowed.class) && position == Position.REST) { throw new CommandExecutionException(command.third.getAnnotation(RestPositionDisallowed.class).message()); } if (command.third.isAnnotationPresent(SleepPositionDisallowed.class) && position == Position.SLEEP) { throw new CommandExecutionException(command.third.getAnnotation(SleepPositionDisallowed.class).message()); } if (command.third.isAnnotationPresent(FightPositionDisallowed.class) && position == Position.FIGHT) { throw new CommandExecutionException(command.third.getAnnotation(FightPositionDisallowed.class).message()); } if (command.third.isAnnotationPresent(ForAdmins.class) && !player.isAdmin()) { continue; } if (command.third.isAnnotationPresent(NoParameters.class) && commandParams.size() > 0) { throw new CommandExecutionException(TextUtils.ucfirst(command.third.getName()) + " nie wymaga żadnych parametrów. " + commandParams.size() + " to zbyt dużo."); } if (command.third.isAnnotationPresent(MinParameters.class) && commandParams.size() < command.third.getAnnotation(MinParameters.class).count()) { throw new CommandExecutionException(command.third.getAnnotation(MinParameters.class).message().replace("%minParametersCount", String.valueOf(command.third.getAnnotation(MinParameters.class).count())).replace("%methodName", command.third.getName())); } if (command.third.isAnnotationPresent(MaxParameters.class) && commandParams.size() > command.third.getAnnotation(MaxParameters.class).count()) { throw new CommandExecutionException(command.third.getAnnotation(MaxParameters.class).message().replace("%maxParametersCount", String.valueOf(command.third.getAnnotation(MaxParameters.class).count())).replace("%methodName", command.third.getName())); } if (command.third.isAnnotationPresent(ParametersCount.class) && commandParams.size() > command.third.getAnnotation(ParametersCount.class).count()) { throw new CommandExecutionException(command.third.getAnnotation(ParametersCount.class).tooManyMessage().replace("%wantedParametersCount", String.valueOf(command.third.getAnnotation(ParametersCount.class).count())).replace("%methodName", command.third.getName())); } if (command.third.isAnnotationPresent(ParametersCount.class) && commandParams.size() < command.third.getAnnotation(ParametersCount.class).count()) { throw new CommandExecutionException(command.third.getAnnotation(ParametersCount.class).notEnoughMessage().replace("%wantedParametersCount", String.valueOf(command.third.getAnnotation(ParametersCount.class).count())).replace("%methodName", command.third.getName())); } out += command.third.invoke(command.fourth, this); commandFine = true; break; //if no exception was thrown } else if (command.third.isAnnotationPresent(Aliased.class)) { out += command.third.invoke(command.fourth, this); commandFine = true; break; //if no exception was thrown } } catch (IllegalAccessException ex) { Logger.getLogger(CommandRouter.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalArgumentException ex) { Logger.getLogger(CommandRouter.class.getName()).log(Level.SEVERE, null, ex); } catch (InvocationTargetException ex) { if (ex.getCause() instanceof CommandExecutionException) { errorMessage = ex.getMessage(); } else { commandFine = true; out += "Wystąpił błąd podczas wykonywania komendy. Przepraszamy.\n"; if (player.isAdmin()) { out += ExceptionUtils.getLongDescription(ex.getCause()) + "\n"; ex.getCause().getStackTrace(); } Logger.getLogger(CommandRouter.class.getName()).log(Level.SEVERE, null, ex.getCause()); break; } } catch (CommandExecutionException ex) { errorMessage = ex.getMessage(); } } if (!commandFine) { if (!errorMessage.isEmpty()) { out += errorMessage.replace("%parametersCount", String.valueOf(commandParams.size())) + "\n"; } else { out += "Masz jakiś problem!?\n"; } } Logger.getLogger("Commands").log(Level.INFO, logEntry); return out; } public Player getPlayer() { return player; } public String getCommandData() { return commandData; } public String getCommandName() { return commandName; } public List<String> getParams() { return Collections.unmodifiableList(commandParams); } public String getInput() { return input; } public void cleanCommands() { } public BooleanStringMethodObjectTuple[] getCommands() { return commands; } public void setCommands(BooleanStringMethodObjectTuple[] commands) { this.commands = commands; } }
10346_0
package agh.ics.oop.model.map; import agh.ics.oop.model.configuration.Configuration; import agh.ics.oop.model.Vector2d; import agh.ics.oop.model.elements.Animal; import agh.ics.oop.model.elements.AnimalsFactory; import agh.ics.oop.model.elements.Plant; import agh.ics.oop.model.elements.WorldElement; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Stream; public abstract class AbstractWorldMap implements WorldMap { private final Map<Vector2d, Set<Animal>> animals; protected final Map<Vector2d, Plant> plants; protected final Configuration config; private final AnimalsFactory animalsFactory; private int sumOfSurvivedDays=0; private int sumOfDeadAnimals=0; public AbstractWorldMap(Configuration configuration, AnimalsFactory animalsFactory) { config = configuration; this.animalsFactory = animalsFactory; animals = new ConcurrentHashMap<>(config.mapWidth()*config.mapHeight()); plants = new ConcurrentHashMap<>(config.mapWidth()*config.mapHeight()); } protected abstract void generatePlants(int numOfPlants); protected void removePlant(Vector2d position) { plants.remove(position); } private Optional<Animal> findStrongestExcept(Set<Animal> animals, Animal exceptAnimal) { return animals.stream() .filter(animal -> !Objects.equals(animal, exceptAnimal)) .max(Comparator .comparingInt(Animal::getEnergy) .thenComparing(Animal::getAge) .thenComparing(Animal::getKidsNumber)); } private Optional<Animal> findStrongest(Set<Animal> animals) { return findStrongestExcept(animals, null); } public void place(Animal animal) { if (!isAnimal(animal.getPosition())) { animals.put(animal.getPosition(), new HashSet<>()); } animals.get(animal.getPosition()).add(animal); } @Override public void move(Animal animal) { animalsAt(animal.getPosition()) .ifPresent(animalsAtPosition -> { if (animalsAtPosition.contains(animal)) { remove(animal); animal.move(config.mapWidth(), config.mapHeight()); place(animal); } }); } @Override public void remove(Animal animal) { animalsAt(animal.getPosition()) .ifPresent(animalsAtPosition -> { animalsAtPosition.remove(animal); if (animalsAtPosition.isEmpty()) { animals.remove(animal.getPosition()); } }); } public void feedAnimals() { animals.forEach((position, animalsAtPosition) -> { if (plants.containsKey(position)) { findStrongest(animalsAtPosition).ifPresent(this::feedAnimal); removePlant(position); } }); } protected void feedAnimal(Animal animal) {//będę nadpisywał w poisoned land animal.eat(config.plantsEnergyValue()); } public boolean isAnimal(Vector2d position) { return animals.containsKey(position); } @Override public Optional<Set<Animal>> animalsAt(Vector2d position) { return Optional.ofNullable(animals.get(position)); } @Override public List<Animal> reproduceAnimals() { List<Animal> newborns = new ArrayList<>(); for (Set<Animal> animalSet: animals.values()) { findStrongest(animalSet).ifPresent(father -> { findStrongestExcept(animalSet, father).ifPresent(mother -> { if (canAnimalReproduce(father) && canAnimalReproduce(mother)) { Animal child = animalsFactory.makeChild(father, mother); place(child); newborns.add(child); } }); }); } return newborns; } @Override public void growPlants() { generatePlants(config.plantsNumPerDay()); } public void removeDeadAnimal(Animal animal, int dayOfSimulation){ animal.die(dayOfSimulation); sumOfSurvivedDays += animal.getAge(); sumOfDeadAnimals += 1; remove(animal); } private boolean canAnimalReproduce(Animal animal) { return animal.getEnergy() >= config.animalsEnergyToReproduce(); } @Override public Stream<WorldElement> getElements() { return Stream.concat( plants.values().stream().filter(plant -> !isAnimal(plant.getPosition())), animals.values().stream().map(this::findStrongest).map(Optional::get) ); } public Map<Vector2d, Plant> getPlants() { return Collections.unmodifiableMap(plants); } public Map<Vector2d, Set<Animal>> getAnimals() { return Collections.unmodifiableMap(animals); } @Override public int getWidth() { return config.mapWidth(); } @Override public int getHeight() { return config.mapHeight(); } public int getSumOfSurvivedDays() { return sumOfSurvivedDays; } public int getSumOfDeadAnimals() { return sumOfDeadAnimals; } }
Jeremylaby/PO_2023_PROJ_BARYCKI_KASPRZYCKI
darwin_world/src/main/java/agh/ics/oop/model/map/AbstractWorldMap.java
1,516
//będę nadpisywał w poisoned land
line_comment
pl
package agh.ics.oop.model.map; import agh.ics.oop.model.configuration.Configuration; import agh.ics.oop.model.Vector2d; import agh.ics.oop.model.elements.Animal; import agh.ics.oop.model.elements.AnimalsFactory; import agh.ics.oop.model.elements.Plant; import agh.ics.oop.model.elements.WorldElement; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Stream; public abstract class AbstractWorldMap implements WorldMap { private final Map<Vector2d, Set<Animal>> animals; protected final Map<Vector2d, Plant> plants; protected final Configuration config; private final AnimalsFactory animalsFactory; private int sumOfSurvivedDays=0; private int sumOfDeadAnimals=0; public AbstractWorldMap(Configuration configuration, AnimalsFactory animalsFactory) { config = configuration; this.animalsFactory = animalsFactory; animals = new ConcurrentHashMap<>(config.mapWidth()*config.mapHeight()); plants = new ConcurrentHashMap<>(config.mapWidth()*config.mapHeight()); } protected abstract void generatePlants(int numOfPlants); protected void removePlant(Vector2d position) { plants.remove(position); } private Optional<Animal> findStrongestExcept(Set<Animal> animals, Animal exceptAnimal) { return animals.stream() .filter(animal -> !Objects.equals(animal, exceptAnimal)) .max(Comparator .comparingInt(Animal::getEnergy) .thenComparing(Animal::getAge) .thenComparing(Animal::getKidsNumber)); } private Optional<Animal> findStrongest(Set<Animal> animals) { return findStrongestExcept(animals, null); } public void place(Animal animal) { if (!isAnimal(animal.getPosition())) { animals.put(animal.getPosition(), new HashSet<>()); } animals.get(animal.getPosition()).add(animal); } @Override public void move(Animal animal) { animalsAt(animal.getPosition()) .ifPresent(animalsAtPosition -> { if (animalsAtPosition.contains(animal)) { remove(animal); animal.move(config.mapWidth(), config.mapHeight()); place(animal); } }); } @Override public void remove(Animal animal) { animalsAt(animal.getPosition()) .ifPresent(animalsAtPosition -> { animalsAtPosition.remove(animal); if (animalsAtPosition.isEmpty()) { animals.remove(animal.getPosition()); } }); } public void feedAnimals() { animals.forEach((position, animalsAtPosition) -> { if (plants.containsKey(position)) { findStrongest(animalsAtPosition).ifPresent(this::feedAnimal); removePlant(position); } }); } protected void feedAnimal(Animal animal) {//będę nadpisywał <SUF> animal.eat(config.plantsEnergyValue()); } public boolean isAnimal(Vector2d position) { return animals.containsKey(position); } @Override public Optional<Set<Animal>> animalsAt(Vector2d position) { return Optional.ofNullable(animals.get(position)); } @Override public List<Animal> reproduceAnimals() { List<Animal> newborns = new ArrayList<>(); for (Set<Animal> animalSet: animals.values()) { findStrongest(animalSet).ifPresent(father -> { findStrongestExcept(animalSet, father).ifPresent(mother -> { if (canAnimalReproduce(father) && canAnimalReproduce(mother)) { Animal child = animalsFactory.makeChild(father, mother); place(child); newborns.add(child); } }); }); } return newborns; } @Override public void growPlants() { generatePlants(config.plantsNumPerDay()); } public void removeDeadAnimal(Animal animal, int dayOfSimulation){ animal.die(dayOfSimulation); sumOfSurvivedDays += animal.getAge(); sumOfDeadAnimals += 1; remove(animal); } private boolean canAnimalReproduce(Animal animal) { return animal.getEnergy() >= config.animalsEnergyToReproduce(); } @Override public Stream<WorldElement> getElements() { return Stream.concat( plants.values().stream().filter(plant -> !isAnimal(plant.getPosition())), animals.values().stream().map(this::findStrongest).map(Optional::get) ); } public Map<Vector2d, Plant> getPlants() { return Collections.unmodifiableMap(plants); } public Map<Vector2d, Set<Animal>> getAnimals() { return Collections.unmodifiableMap(animals); } @Override public int getWidth() { return config.mapWidth(); } @Override public int getHeight() { return config.mapHeight(); } public int getSumOfSurvivedDays() { return sumOfSurvivedDays; } public int getSumOfDeadAnimals() { return sumOfDeadAnimals; } }
10275_0
package agh.ics.oop.model; public class ConsoleMapDisplay implements MapChangeListener { private int operationCounter = 0; @Override public synchronized void mapChanged(WorldMap worldMap, String message) {//Wiem że w zadaniu była podana innakolejność ale tak jest dla mnie bardziej czytelna operationCounter++; System.out.println("Map id: " + worldMap.getId()); System.out.println("Update nr " + operationCounter + ":"); System.out.println(message); System.out.println(worldMap.toString()); } }
Jeremylaby/PO_2023_SR1820_BARYCKI
Party_Animals/src/main/java/agh/ics/oop/model/ConsoleMapDisplay.java
155
//Wiem że w zadaniu była podana innakolejność ale tak jest dla mnie bardziej czytelna
line_comment
pl
package agh.ics.oop.model; public class ConsoleMapDisplay implements MapChangeListener { private int operationCounter = 0; @Override public synchronized void mapChanged(WorldMap worldMap, String message) {//Wiem że <SUF> operationCounter++; System.out.println("Map id: " + worldMap.getId()); System.out.println("Update nr " + operationCounter + ":"); System.out.println(message); System.out.println(worldMap.toString()); } }
9383_49
package jss.database; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.List; import jss.database.annotations.DbField; import jss.database.annotations.DbForeignKey; import jss.database.annotations.DbManyToOne; import jss.database.annotations.DbOneToOne; import jss.database.annotations.DbPrimaryKey; import jss.database.annotations.DbTable; import jss.database.annotations.DbView; import jss.database.annotations.DbViewField; import jss.database.annotations.DbViewObject; import jss.database.mappers.SqlTypeMapper; import jss.database.types.SqlType; public class FieldLister { private final Database db; private final String tableName;// table name private final Class<?> tableClass;// entity class private final DbView dbView; private final List<DbFieldInfo> dbFields = new ArrayList<>(); private final List<DbManyToOneInfo> dbManyToOne = new ArrayList<>(); private final List<DbOneToOneInfo> dbOneToOne = new ArrayList<>(); private final List<DbViewFieldInfo> dbViewFields = new ArrayList<>(); private final List<DbViewObjectInfo> dbViewObjects = new ArrayList<>(); private boolean lazyLoadedFields = false;// loaded fields by listFields()? private boolean lazyLoadedDatabaseTypes = false;// loaded database types? /** * @param db database framework instance * @param tableClass entity class * @throws DatabaseException no DbTable or DbView annotation */ FieldLister(Database db, Class<?> tableClass) throws DatabaseException { this.db = db; // get table name and class if (tableClass.isAnnotationPresent(DbView.class)) {// view dbView = tableClass.getAnnotation(DbView.class); this.tableName = dbView.name(); } else if (tableClass.isAnnotationPresent(DbTable.class)) {// table this.tableName = tableClass.getAnnotation(DbTable.class).value(); dbView = null; } else { throw new DatabaseException("No 'DbTable' or 'DbView' annotation in class " + tableClass.getName()); } this.tableClass = tableClass; } /** * List fields from table class (and superclasses) * * @throws DatabaseException */ void listFields() throws DatabaseException { if (lazyLoadedFields) {// if fields loaded, do nothing return; } // listuj pola klasy oraz klas nadrzędnych Class<?> clazz = tableClass; if (isView()) { do { listFieldsForView(clazz); clazz = clazz.getSuperclass(); } while (!clazz.equals(Object.class)); } else {// table do { listFields(clazz); clazz = clazz.getSuperclass(); } while (!clazz.equals(Object.class)); } lazyLoadedFields = true;// loaded fields } /** * List fields from class - for table * * @param clazz class to list fields * @throws DatabaseException */ private void listFields(Class<?> clazz) throws DatabaseException { Field[] fields = clazz.getDeclaredFields();// pobierz wszystkie pola z klasy for (Field field : fields) { field.setAccessible(true); // możliwość dostępu nawet jeżeli pole jest prywatne if (field.isAnnotationPresent(DbField.class)) {// database field DbFieldInfo info = processDbField(field, clazz); dbFields.add(info); if (field.isAnnotationPresent(DbPrimaryKey.class)) {// primary key field DbPrimaryKeyInfo pkInfo = processDbPrimaryKey(field); info.primaryKeyInfo = pkInfo; } if (field.isAnnotationPresent(DbForeignKey.class)) {// foreign key field DbForeignKeyInfo fkInfo = processDbForeignKey(field, clazz); info.foreignKeyInfo = fkInfo; } } else if (field.isAnnotationPresent(DbManyToOne.class)) {// many to one collection DbManyToOneInfo info = processDbManyToOne(field); dbManyToOne.add(info); } else if (field.isAnnotationPresent(DbOneToOne.class)) {// one to one relation DbOneToOneInfo info = processDbOneToOne(field); dbOneToOne.add(info); } } // for fields } /** * List fields from class - for view * * @param clazz class to list fields * @throws DatabaseException */ private void listFieldsForView(Class<?> clazz) throws DatabaseException { Field[] fields = clazz.getDeclaredFields();// pobierz wszystkie pola z klasy for (Field field : fields) { field.setAccessible(true); // możliwość dostępu nawet jeżeli pole jest prywatne if (field.isAnnotationPresent(DbViewField.class)) {// view field DbViewFieldInfo info = processDbViewField(field, clazz); dbViewFields.add(info); } else if (field.isAnnotationPresent(DbViewObject.class)) {// view object dbViewObjects.add(processDbViewObject(field, clazz)); } } } /** * Load database types * * @param mapper native type to SQL type mapper * @throws DatabaseException cannot determine type, or error when listing fields */ void loadDatabaseTypes(SqlTypeMapper mapper) throws DatabaseException { if (lazyLoadedDatabaseTypes) {// if loaded types, do nothing return; } if (!lazyLoadedFields) {// if fields not loaded - load it this.listFields(); } for (DbFieldInfo fieldInfo : dbFields) { Class<?> nativeType = fieldInfo.getNativeType();// native java type // sql type SqlType sqlType = fieldInfo.fieldAnnotation.type(); if (sqlType == SqlType.DEFAULT) {// default type - determine sqlType = mapper.getSqlType(nativeType); } if (sqlType == SqlType.UNKNOWN) {// cannot determine type throw new DatabaseException("Cannot determine SQL type of " + nativeType.getName()); } fieldInfo.sqlType = sqlType;// SQL type // get sql string type for current database String fieldSqlStr = db.getDb().getTypeString(fieldInfo); if (fieldSqlStr == null) { throw new DatabaseException("Cannot get type " + fieldInfo.sqlType + " for database!"); } DbField dbField = fieldInfo.getFieldAnnotation(); // replace string len value int strLen = dbField.stringLen(); if (strLen == -1) { strLen = db.getConfig().defaultStringLen; } fieldSqlStr = fieldSqlStr.replace("{strlen}", Integer.toString(strLen)); // replace decimal precision int precistion = dbField.decimalPrecision(); if (precistion == -1) { precistion = db.getConfig().defaultDecimalPrecision; } fieldSqlStr = fieldSqlStr.replace("{precision}", Integer.toString(precistion)); // replace decimal scale int scale = dbField.decimalScale(); if (scale == -1) { scale = db.getConfig().defaultDecimalScale; } fieldSqlStr = fieldSqlStr.replace("{scale}", Integer.toString(scale)); fieldInfo.sqlTypeString = fieldSqlStr;// SQL type string } } /** * Process DbField annotation * * @param field field in class * @param clazz current processing class * @return database field info */ private DbFieldInfo processDbField(Field field, Class<?> clazz) { DbField dbField = field.getAnnotation(DbField.class);// pobierz element adnotacji DbFieldInfo info = new DbFieldInfo(); info.fieldAnnotation = dbField; info.clazz = clazz; info.fieldInClass = field; // in table name info.inTableName = dbField.name();// custom name if (info.inTableName.isEmpty()) {// if custom name empty, use class name info.inTableName = field.getName(); } return info; } /** * Process DbPrimaryKey annotation * * @param field field info * @return primary key info * @throws DatabaseException */ private DbPrimaryKeyInfo processDbPrimaryKey(Field field) throws DatabaseException { if (!field.isAnnotationPresent(DbField.class)) { throw new DatabaseException("No annotation DbField on DbPrimaryKey!"); } DbPrimaryKey dbPrimaryKey = field.getAnnotation(DbPrimaryKey.class); DbPrimaryKeyInfo info = new DbPrimaryKeyInfo(); info.pkAnnotation = dbPrimaryKey; return info; } /** * Process DbForeignKey annotation * * @param field field in class * @param clazz current processing class * @return foreign key info * @throws DatabaseException */ private DbForeignKeyInfo processDbForeignKey(Field field, Class<?> clazz) throws DatabaseException { if (!field.isAnnotationPresent(DbField.class)) { throw new DatabaseException("No annotation DbField on DbForeignKey!"); } DbForeignKey dbForeignKey = field.getAnnotation(DbForeignKey.class); DbForeignKeyInfo info = new DbForeignKeyInfo(); info.fkAnnotation = dbForeignKey; // load this field - field in current class for place foreing object if (!dbForeignKey.thisField().trim().equals("")) { try { info.thisField = getDeclaredField(clazz, dbForeignKey.thisField()); } catch (NoSuchFieldException e) { String fname = field.getName();// field name String cname = clazz.getName();// class name throw new DatabaseException("Cannot set foreign field " + fname + " for class: " + cname, e); } } else { info.thisField = null;// if not field for save foreign object, set null } // reference class Class<?> refObj = dbForeignKey.refObject(); // check annotation DbTable if (!refObj.isAnnotationPresent(DbTable.class)) { throw new DatabaseException("No 'DbTable' annotation in foreign class: " + refObj.getName()); } // get table name DbTable foreignDbTable = refObj.getAnnotation(DbTable.class); info.refTableName = foreignDbTable.value(); String refFieldName = dbForeignKey.refField();// field name String refClassName = dbForeignKey.refObject().getName();// class name // load foreign field Field foreignField; try { foreignField = getDeclaredField(dbForeignKey.refObject(), dbForeignKey.refField()); } catch (NoSuchFieldException e) { throw new DatabaseException("Cannot found foreign field " + refFieldName + " in class: " + refClassName, e); } // check foreign field annotation if (!foreignField.isAnnotationPresent(DbField.class)) { throw new DatabaseException("No DbField annotation: " + refClassName + "::" + refFieldName); } DbField dbForeignField = foreignField.getAnnotation(DbField.class); // check is unique or primary key // TODO // save table column name info.refInTableName = dbForeignField.name();// custom column name if (info.refInTableName.isEmpty()) {// default column name info.refInTableName = foreignField.getName(); } return info; } /** * Process DbManyToOne annotation * * @param field field info * @throws DatabaseException */ private DbManyToOneInfo processDbManyToOne(Field field) throws DatabaseException { DbManyToOne dbMany = field.getAnnotation(DbManyToOne.class); // sprawdź, czy pole ManyToOne jest kolekcją if (!Collection.class.isAssignableFrom(field.getType())) {// jeżeli nie jest - rzuć wyjątek throw new DatabaseException("Field '" + field.getName() + "' in class '" + field.getDeclaringClass().getName() + "' ManyToOne relation is not a collection!"); } DbManyToOneInfo info = new DbManyToOneInfo(); info.mtoAnnotation = dbMany; info.fieldInClass = field; // pobierz pole w klasie obcej try { Field refField = getDeclaredField(dbMany.refObject(), dbMany.refField()); if (!refField.isAnnotationPresent(DbField.class) || !refField.isAnnotationPresent(DbForeignKey.class)) { throw new DatabaseException("Relation field " + refField.getName() + " has not FK annotation!"); } DbForeignKey dbForKey = refField.getAnnotation(DbForeignKey.class); // ustaw pole, do którego odwołuje się ManyToOne if (!dbForKey.thisField().isEmpty()) {// jeżeli takowe istnieje Field refFieldOnClass = getDeclaredField(dbMany.refObject(), dbForKey.thisField()); info.refFieldObj = refFieldOnClass; } info.refFieldKey = refField; } catch (NoSuchFieldException e) { throw new DatabaseException("DbManyToOne field not found!", e); } return info; } /** * Process DbOneToOne annotation * * @param field field info * @throws DatabaseException */ private DbOneToOneInfo processDbOneToOne(Field field) throws DatabaseException { DbOneToOne dbOne = field.getAnnotation(DbOneToOne.class); DbOneToOneInfo info = new DbOneToOneInfo(); info.otoAnnotation = dbOne; info.fieldInClass = field; // pobierz pole w klasie obcej try { Field refField = getDeclaredField(dbOne.refObject(), dbOne.refField()); if (!refField.isAnnotationPresent(DbField.class) || !refField.isAnnotationPresent(DbForeignKey.class)) { throw new DatabaseException("Relation field " + refField.getName() + " has not FK annotation!"); } DbForeignKey dbForKey = refField.getAnnotation(DbForeignKey.class); // ustaw pole, do którego odwołuje się ManyToOne if (!dbForKey.thisField().isEmpty()) {// jeżeli takowe istnieje Field refFieldOnClass = getDeclaredField(dbOne.refObject(), dbForKey.thisField()); info.refFieldObj = refFieldOnClass; } info.refFieldKey = refField; } catch (NoSuchFieldException e) { throw new DatabaseException("DbOneToOne field not found!", e); } return info; } /** * Process DbViewFiled annotation * * @param field field in class * @param clazz current processing class * @return DbViewField info */ private DbViewFieldInfo processDbViewField(Field field, Class<?> clazz) { DbViewField dbViewField = field.getAnnotation(DbViewField.class);// pobierz element adnotacji DbViewFieldInfo info = new DbViewFieldInfo(); info.fieldAnnotation = dbViewField; // info.clazz = clazz; info.fieldInClass = field; // in table name info.inQueryName = dbViewField.value();// custom name if (info.inQueryName.isEmpty()) {// if custom name empty, use class name info.inQueryName = field.getName(); } return info; } /** * Process DbViewObject annotation * * @param field field in class * @param clazz current processing class * @return DbViewObject info */ private DbViewObjectInfo processDbViewObject(Field field, Class<?> clazz) { DbViewObject dbViewObject = field.getAnnotation(DbViewObject.class);// pobierz element adnotacji DbViewObjectInfo info = new DbViewObjectInfo(); info.fieldAnnotation = dbViewObject; // info.clazz = clazz; info.fieldInClass = field; return info; } /** * Get declared field from class or superclass * * @param clazz class to start search * @param field field name * @return field in class * @throws NoSuchFieldException field not found */ private Field getDeclaredField(Class<?> clazz, String field) throws NoSuchFieldException { do { try { Field f = clazz.getDeclaredField(field); f.setAccessible(true); return f; } catch (NoSuchFieldException e) { clazz = clazz.getSuperclass(); } } while (!clazz.equals(Object.class)); throw new NoSuchFieldException("Field not found: " + field); } /** * @return table name */ String getTableName() { return tableName; } /** * @return table class */ Class<?> getTableClass() { return tableClass; } /** * @return database fields in class */ List<DbFieldInfo> getDbFields() { return new ArrayList<>(dbFields);// copy } /** * @return database fields or view fields in class */ List<DbFieldOrViewInfo> getDbFieldOrViewInfo() { List<DbFieldOrViewInfo> ret = new ArrayList<>(dbFields);// copy ret.addAll(dbViewFields); return ret; } /** * @return database fields which are primary keys */ List<DbFieldInfo> getPrimaryKeys() { List<DbFieldInfo> pkList = new ArrayList<>(2); for (DbFieldInfo dfi : dbFields) { if (dfi.getPrimaryKeyInfo() != null) { pkList.add(dfi); } } return pkList; } /** * @return database fields which are foreign keys */ List<DbFieldInfo> getForeignKeys() { List<DbFieldInfo> fkList = new ArrayList<>(2); for (DbFieldInfo dfi : dbFields) { if (dfi.getForeignKeyInfo() != null) { fkList.add(dfi); } } return fkList; } /** * @return database fields which are indexes */ List<DbFieldInfo> getIndexes() { List<DbFieldInfo> indexes = new ArrayList<>(2); for (DbFieldInfo dfi : dbFields) { if (dfi.fieldAnnotation.isIndex()) { indexes.add(dfi); } } return indexes; } /** * Get field by name in class * * @param string field name in class * @return field, or null if not found */ DbFieldOrViewInfo getFieldByInClassName(String name) { for (DbFieldInfo df : dbFields) { if (df.getFieldInClass().getName().equals(name)) { return df; } } for (DbViewFieldInfo df : dbViewFields) { if (df.getFieldInClass().getName().equals(name)) { return df; } } return null; } /** * @return fields for ManyToOne relations */ List<DbManyToOneInfo> getDbManyToOne() { return dbManyToOne; } /** * @return fields for OneToOne relations */ List<DbOneToOneInfo> getDbOneToOne() { return dbOneToOne; } /** * @return this is view? */ boolean isView() { return dbView != null; } /** * @return DbView annotation */ DbView getDbView() { return dbView; } /** * @return DbViewObject list info for view */ List<DbViewObjectInfo> getDbViewObjects() { return dbViewObjects; } /** * Database field info * * @author lukas */ public class DbFieldInfo implements DbFieldOrViewInfo { DbFieldInfo() {// not public constructor } /** * DbField annotation */ DbField fieldAnnotation; /** * Class in which the field is located (for superclasses support) */ Class<?> clazz; /** * Field in class */ Field fieldInClass; /** * Column name in table */ String inTableName; /** * SQL type */ SqlType sqlType; /** * SQL type string for current database type */ String sqlTypeString; /** * Primary key info */ DbPrimaryKeyInfo primaryKeyInfo; /** * Foreign key info */ DbForeignKeyInfo foreignKeyInfo; /** * @return DbField annotation */ public DbField getFieldAnnotation() { return fieldAnnotation; } @Override public Field getFieldInClass() { return fieldInClass; } /** * @return SQL type */ public SqlType getSqlType() { return sqlType; } /** * @return primary key info (or null) */ public DbPrimaryKeyInfo getPrimaryKeyInfo() { return primaryKeyInfo; } /** * @return foreign key info (or null) */ public DbForeignKeyInfo getForeignKeyInfo() { return foreignKeyInfo; } @Override public String getInQueryName() { return tableName + '_' + inTableName; } @Override public String getInTableName() { return inTableName; } } /** * Primary key info * * @author lukas */ public class DbPrimaryKeyInfo { DbPrimaryKeyInfo() {// not public constructor } /** * DbPrimaryKey annotation */ DbPrimaryKey pkAnnotation; /** * @return DbPrimaryKey annotation */ public DbPrimaryKey getPkAnnotation() { return pkAnnotation; } } /** * Foreign key info * * @author lukas */ public class DbForeignKeyInfo { DbForeignKeyInfo() {// not public constructor } /** * DbForeignKey annotation */ DbForeignKey fkAnnotation; /** * Field in class for store foreign object */ Field thisField; /** * Foreign table name */ String refTableName; /** * Foreign column name */ String refInTableName; /** * @return DbForeignKey annotation */ public DbForeignKey getFkAnnotation() { return fkAnnotation; } } /** * Many to one info * * @author lukas */ public class DbManyToOneInfo { DbManyToOneInfo() {// not public constructor } /** * DbManyToOne annotation */ DbManyToOne mtoAnnotation; /** * Field in class */ Field fieldInClass; /** * Field in ref class - foreign key field */ Field refFieldKey; /** * Field in ref class - object field */ Field refFieldObj; /** * @return DbManyToOne annotation */ public DbManyToOne getMtoAnnotation() { return mtoAnnotation; } } /** * One to one info * * @author lukas */ public class DbOneToOneInfo { DbOneToOneInfo() {// not public constructor } /** * DbOneToOne annotation */ DbOneToOne otoAnnotation; /** * Field in class */ Field fieldInClass; /** * Field in ref class - foreign key field */ Field refFieldKey; /** * Field in ref class - object field */ Field refFieldObj; /** * @return DbManyToOne annotation */ public DbOneToOne getOtoAnnotation() { return otoAnnotation; } } /** * VIEW field info * * @author lukas */ public class DbViewFieldInfo implements DbFieldOrViewInfo { DbViewFieldInfo() { } /** * DbViewField annotation */ DbViewField fieldAnnotation; /** * Class in which the field is located (for superclasses support) */ // Class<?> clazz; /** * Field in class */ Field fieldInClass; /** * Column name in query */ String inQueryName; @Override public String getInQueryName() { return inQueryName; } @Override public String getInTableName() { return inQueryName; } @Override public Field getFieldInClass() { return fieldInClass; } } /** * VIEW object info * * @author lukas */ public class DbViewObjectInfo { DbViewObjectInfo() { } /** * DbViewObject annotation */ DbViewObject fieldAnnotation; /** * Class in which the field is located (for superclasses support) */ // Class<?> clazz; /** * Field in class */ Field fieldInClass; } public interface DbFieldOrViewInfo { /** * @return name in query */ public String getInQueryName(); /** * @return name in table */ public String getInTableName(); /** * @return field in class */ public Field getFieldInClass(); /** * @return native java type */ default public Class<?> getNativeType() { return getFieldInClass().getType(); } /** * @param clazz native type to check * @return is native type? */ default public boolean nativeTypeIs(Class<?> clazz) { return getNativeType().isAssignableFrom(clazz); } } }
Job-Smart-Solutions/JSSDatabaseFramework
src/jss/database/FieldLister.java
7,753
// jeżeli takowe istnieje
line_comment
pl
package jss.database; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.List; import jss.database.annotations.DbField; import jss.database.annotations.DbForeignKey; import jss.database.annotations.DbManyToOne; import jss.database.annotations.DbOneToOne; import jss.database.annotations.DbPrimaryKey; import jss.database.annotations.DbTable; import jss.database.annotations.DbView; import jss.database.annotations.DbViewField; import jss.database.annotations.DbViewObject; import jss.database.mappers.SqlTypeMapper; import jss.database.types.SqlType; public class FieldLister { private final Database db; private final String tableName;// table name private final Class<?> tableClass;// entity class private final DbView dbView; private final List<DbFieldInfo> dbFields = new ArrayList<>(); private final List<DbManyToOneInfo> dbManyToOne = new ArrayList<>(); private final List<DbOneToOneInfo> dbOneToOne = new ArrayList<>(); private final List<DbViewFieldInfo> dbViewFields = new ArrayList<>(); private final List<DbViewObjectInfo> dbViewObjects = new ArrayList<>(); private boolean lazyLoadedFields = false;// loaded fields by listFields()? private boolean lazyLoadedDatabaseTypes = false;// loaded database types? /** * @param db database framework instance * @param tableClass entity class * @throws DatabaseException no DbTable or DbView annotation */ FieldLister(Database db, Class<?> tableClass) throws DatabaseException { this.db = db; // get table name and class if (tableClass.isAnnotationPresent(DbView.class)) {// view dbView = tableClass.getAnnotation(DbView.class); this.tableName = dbView.name(); } else if (tableClass.isAnnotationPresent(DbTable.class)) {// table this.tableName = tableClass.getAnnotation(DbTable.class).value(); dbView = null; } else { throw new DatabaseException("No 'DbTable' or 'DbView' annotation in class " + tableClass.getName()); } this.tableClass = tableClass; } /** * List fields from table class (and superclasses) * * @throws DatabaseException */ void listFields() throws DatabaseException { if (lazyLoadedFields) {// if fields loaded, do nothing return; } // listuj pola klasy oraz klas nadrzędnych Class<?> clazz = tableClass; if (isView()) { do { listFieldsForView(clazz); clazz = clazz.getSuperclass(); } while (!clazz.equals(Object.class)); } else {// table do { listFields(clazz); clazz = clazz.getSuperclass(); } while (!clazz.equals(Object.class)); } lazyLoadedFields = true;// loaded fields } /** * List fields from class - for table * * @param clazz class to list fields * @throws DatabaseException */ private void listFields(Class<?> clazz) throws DatabaseException { Field[] fields = clazz.getDeclaredFields();// pobierz wszystkie pola z klasy for (Field field : fields) { field.setAccessible(true); // możliwość dostępu nawet jeżeli pole jest prywatne if (field.isAnnotationPresent(DbField.class)) {// database field DbFieldInfo info = processDbField(field, clazz); dbFields.add(info); if (field.isAnnotationPresent(DbPrimaryKey.class)) {// primary key field DbPrimaryKeyInfo pkInfo = processDbPrimaryKey(field); info.primaryKeyInfo = pkInfo; } if (field.isAnnotationPresent(DbForeignKey.class)) {// foreign key field DbForeignKeyInfo fkInfo = processDbForeignKey(field, clazz); info.foreignKeyInfo = fkInfo; } } else if (field.isAnnotationPresent(DbManyToOne.class)) {// many to one collection DbManyToOneInfo info = processDbManyToOne(field); dbManyToOne.add(info); } else if (field.isAnnotationPresent(DbOneToOne.class)) {// one to one relation DbOneToOneInfo info = processDbOneToOne(field); dbOneToOne.add(info); } } // for fields } /** * List fields from class - for view * * @param clazz class to list fields * @throws DatabaseException */ private void listFieldsForView(Class<?> clazz) throws DatabaseException { Field[] fields = clazz.getDeclaredFields();// pobierz wszystkie pola z klasy for (Field field : fields) { field.setAccessible(true); // możliwość dostępu nawet jeżeli pole jest prywatne if (field.isAnnotationPresent(DbViewField.class)) {// view field DbViewFieldInfo info = processDbViewField(field, clazz); dbViewFields.add(info); } else if (field.isAnnotationPresent(DbViewObject.class)) {// view object dbViewObjects.add(processDbViewObject(field, clazz)); } } } /** * Load database types * * @param mapper native type to SQL type mapper * @throws DatabaseException cannot determine type, or error when listing fields */ void loadDatabaseTypes(SqlTypeMapper mapper) throws DatabaseException { if (lazyLoadedDatabaseTypes) {// if loaded types, do nothing return; } if (!lazyLoadedFields) {// if fields not loaded - load it this.listFields(); } for (DbFieldInfo fieldInfo : dbFields) { Class<?> nativeType = fieldInfo.getNativeType();// native java type // sql type SqlType sqlType = fieldInfo.fieldAnnotation.type(); if (sqlType == SqlType.DEFAULT) {// default type - determine sqlType = mapper.getSqlType(nativeType); } if (sqlType == SqlType.UNKNOWN) {// cannot determine type throw new DatabaseException("Cannot determine SQL type of " + nativeType.getName()); } fieldInfo.sqlType = sqlType;// SQL type // get sql string type for current database String fieldSqlStr = db.getDb().getTypeString(fieldInfo); if (fieldSqlStr == null) { throw new DatabaseException("Cannot get type " + fieldInfo.sqlType + " for database!"); } DbField dbField = fieldInfo.getFieldAnnotation(); // replace string len value int strLen = dbField.stringLen(); if (strLen == -1) { strLen = db.getConfig().defaultStringLen; } fieldSqlStr = fieldSqlStr.replace("{strlen}", Integer.toString(strLen)); // replace decimal precision int precistion = dbField.decimalPrecision(); if (precistion == -1) { precistion = db.getConfig().defaultDecimalPrecision; } fieldSqlStr = fieldSqlStr.replace("{precision}", Integer.toString(precistion)); // replace decimal scale int scale = dbField.decimalScale(); if (scale == -1) { scale = db.getConfig().defaultDecimalScale; } fieldSqlStr = fieldSqlStr.replace("{scale}", Integer.toString(scale)); fieldInfo.sqlTypeString = fieldSqlStr;// SQL type string } } /** * Process DbField annotation * * @param field field in class * @param clazz current processing class * @return database field info */ private DbFieldInfo processDbField(Field field, Class<?> clazz) { DbField dbField = field.getAnnotation(DbField.class);// pobierz element adnotacji DbFieldInfo info = new DbFieldInfo(); info.fieldAnnotation = dbField; info.clazz = clazz; info.fieldInClass = field; // in table name info.inTableName = dbField.name();// custom name if (info.inTableName.isEmpty()) {// if custom name empty, use class name info.inTableName = field.getName(); } return info; } /** * Process DbPrimaryKey annotation * * @param field field info * @return primary key info * @throws DatabaseException */ private DbPrimaryKeyInfo processDbPrimaryKey(Field field) throws DatabaseException { if (!field.isAnnotationPresent(DbField.class)) { throw new DatabaseException("No annotation DbField on DbPrimaryKey!"); } DbPrimaryKey dbPrimaryKey = field.getAnnotation(DbPrimaryKey.class); DbPrimaryKeyInfo info = new DbPrimaryKeyInfo(); info.pkAnnotation = dbPrimaryKey; return info; } /** * Process DbForeignKey annotation * * @param field field in class * @param clazz current processing class * @return foreign key info * @throws DatabaseException */ private DbForeignKeyInfo processDbForeignKey(Field field, Class<?> clazz) throws DatabaseException { if (!field.isAnnotationPresent(DbField.class)) { throw new DatabaseException("No annotation DbField on DbForeignKey!"); } DbForeignKey dbForeignKey = field.getAnnotation(DbForeignKey.class); DbForeignKeyInfo info = new DbForeignKeyInfo(); info.fkAnnotation = dbForeignKey; // load this field - field in current class for place foreing object if (!dbForeignKey.thisField().trim().equals("")) { try { info.thisField = getDeclaredField(clazz, dbForeignKey.thisField()); } catch (NoSuchFieldException e) { String fname = field.getName();// field name String cname = clazz.getName();// class name throw new DatabaseException("Cannot set foreign field " + fname + " for class: " + cname, e); } } else { info.thisField = null;// if not field for save foreign object, set null } // reference class Class<?> refObj = dbForeignKey.refObject(); // check annotation DbTable if (!refObj.isAnnotationPresent(DbTable.class)) { throw new DatabaseException("No 'DbTable' annotation in foreign class: " + refObj.getName()); } // get table name DbTable foreignDbTable = refObj.getAnnotation(DbTable.class); info.refTableName = foreignDbTable.value(); String refFieldName = dbForeignKey.refField();// field name String refClassName = dbForeignKey.refObject().getName();// class name // load foreign field Field foreignField; try { foreignField = getDeclaredField(dbForeignKey.refObject(), dbForeignKey.refField()); } catch (NoSuchFieldException e) { throw new DatabaseException("Cannot found foreign field " + refFieldName + " in class: " + refClassName, e); } // check foreign field annotation if (!foreignField.isAnnotationPresent(DbField.class)) { throw new DatabaseException("No DbField annotation: " + refClassName + "::" + refFieldName); } DbField dbForeignField = foreignField.getAnnotation(DbField.class); // check is unique or primary key // TODO // save table column name info.refInTableName = dbForeignField.name();// custom column name if (info.refInTableName.isEmpty()) {// default column name info.refInTableName = foreignField.getName(); } return info; } /** * Process DbManyToOne annotation * * @param field field info * @throws DatabaseException */ private DbManyToOneInfo processDbManyToOne(Field field) throws DatabaseException { DbManyToOne dbMany = field.getAnnotation(DbManyToOne.class); // sprawdź, czy pole ManyToOne jest kolekcją if (!Collection.class.isAssignableFrom(field.getType())) {// jeżeli nie jest - rzuć wyjątek throw new DatabaseException("Field '" + field.getName() + "' in class '" + field.getDeclaringClass().getName() + "' ManyToOne relation is not a collection!"); } DbManyToOneInfo info = new DbManyToOneInfo(); info.mtoAnnotation = dbMany; info.fieldInClass = field; // pobierz pole w klasie obcej try { Field refField = getDeclaredField(dbMany.refObject(), dbMany.refField()); if (!refField.isAnnotationPresent(DbField.class) || !refField.isAnnotationPresent(DbForeignKey.class)) { throw new DatabaseException("Relation field " + refField.getName() + " has not FK annotation!"); } DbForeignKey dbForKey = refField.getAnnotation(DbForeignKey.class); // ustaw pole, do którego odwołuje się ManyToOne if (!dbForKey.thisField().isEmpty()) {// jeżeli takowe <SUF> Field refFieldOnClass = getDeclaredField(dbMany.refObject(), dbForKey.thisField()); info.refFieldObj = refFieldOnClass; } info.refFieldKey = refField; } catch (NoSuchFieldException e) { throw new DatabaseException("DbManyToOne field not found!", e); } return info; } /** * Process DbOneToOne annotation * * @param field field info * @throws DatabaseException */ private DbOneToOneInfo processDbOneToOne(Field field) throws DatabaseException { DbOneToOne dbOne = field.getAnnotation(DbOneToOne.class); DbOneToOneInfo info = new DbOneToOneInfo(); info.otoAnnotation = dbOne; info.fieldInClass = field; // pobierz pole w klasie obcej try { Field refField = getDeclaredField(dbOne.refObject(), dbOne.refField()); if (!refField.isAnnotationPresent(DbField.class) || !refField.isAnnotationPresent(DbForeignKey.class)) { throw new DatabaseException("Relation field " + refField.getName() + " has not FK annotation!"); } DbForeignKey dbForKey = refField.getAnnotation(DbForeignKey.class); // ustaw pole, do którego odwołuje się ManyToOne if (!dbForKey.thisField().isEmpty()) {// jeżeli takowe istnieje Field refFieldOnClass = getDeclaredField(dbOne.refObject(), dbForKey.thisField()); info.refFieldObj = refFieldOnClass; } info.refFieldKey = refField; } catch (NoSuchFieldException e) { throw new DatabaseException("DbOneToOne field not found!", e); } return info; } /** * Process DbViewFiled annotation * * @param field field in class * @param clazz current processing class * @return DbViewField info */ private DbViewFieldInfo processDbViewField(Field field, Class<?> clazz) { DbViewField dbViewField = field.getAnnotation(DbViewField.class);// pobierz element adnotacji DbViewFieldInfo info = new DbViewFieldInfo(); info.fieldAnnotation = dbViewField; // info.clazz = clazz; info.fieldInClass = field; // in table name info.inQueryName = dbViewField.value();// custom name if (info.inQueryName.isEmpty()) {// if custom name empty, use class name info.inQueryName = field.getName(); } return info; } /** * Process DbViewObject annotation * * @param field field in class * @param clazz current processing class * @return DbViewObject info */ private DbViewObjectInfo processDbViewObject(Field field, Class<?> clazz) { DbViewObject dbViewObject = field.getAnnotation(DbViewObject.class);// pobierz element adnotacji DbViewObjectInfo info = new DbViewObjectInfo(); info.fieldAnnotation = dbViewObject; // info.clazz = clazz; info.fieldInClass = field; return info; } /** * Get declared field from class or superclass * * @param clazz class to start search * @param field field name * @return field in class * @throws NoSuchFieldException field not found */ private Field getDeclaredField(Class<?> clazz, String field) throws NoSuchFieldException { do { try { Field f = clazz.getDeclaredField(field); f.setAccessible(true); return f; } catch (NoSuchFieldException e) { clazz = clazz.getSuperclass(); } } while (!clazz.equals(Object.class)); throw new NoSuchFieldException("Field not found: " + field); } /** * @return table name */ String getTableName() { return tableName; } /** * @return table class */ Class<?> getTableClass() { return tableClass; } /** * @return database fields in class */ List<DbFieldInfo> getDbFields() { return new ArrayList<>(dbFields);// copy } /** * @return database fields or view fields in class */ List<DbFieldOrViewInfo> getDbFieldOrViewInfo() { List<DbFieldOrViewInfo> ret = new ArrayList<>(dbFields);// copy ret.addAll(dbViewFields); return ret; } /** * @return database fields which are primary keys */ List<DbFieldInfo> getPrimaryKeys() { List<DbFieldInfo> pkList = new ArrayList<>(2); for (DbFieldInfo dfi : dbFields) { if (dfi.getPrimaryKeyInfo() != null) { pkList.add(dfi); } } return pkList; } /** * @return database fields which are foreign keys */ List<DbFieldInfo> getForeignKeys() { List<DbFieldInfo> fkList = new ArrayList<>(2); for (DbFieldInfo dfi : dbFields) { if (dfi.getForeignKeyInfo() != null) { fkList.add(dfi); } } return fkList; } /** * @return database fields which are indexes */ List<DbFieldInfo> getIndexes() { List<DbFieldInfo> indexes = new ArrayList<>(2); for (DbFieldInfo dfi : dbFields) { if (dfi.fieldAnnotation.isIndex()) { indexes.add(dfi); } } return indexes; } /** * Get field by name in class * * @param string field name in class * @return field, or null if not found */ DbFieldOrViewInfo getFieldByInClassName(String name) { for (DbFieldInfo df : dbFields) { if (df.getFieldInClass().getName().equals(name)) { return df; } } for (DbViewFieldInfo df : dbViewFields) { if (df.getFieldInClass().getName().equals(name)) { return df; } } return null; } /** * @return fields for ManyToOne relations */ List<DbManyToOneInfo> getDbManyToOne() { return dbManyToOne; } /** * @return fields for OneToOne relations */ List<DbOneToOneInfo> getDbOneToOne() { return dbOneToOne; } /** * @return this is view? */ boolean isView() { return dbView != null; } /** * @return DbView annotation */ DbView getDbView() { return dbView; } /** * @return DbViewObject list info for view */ List<DbViewObjectInfo> getDbViewObjects() { return dbViewObjects; } /** * Database field info * * @author lukas */ public class DbFieldInfo implements DbFieldOrViewInfo { DbFieldInfo() {// not public constructor } /** * DbField annotation */ DbField fieldAnnotation; /** * Class in which the field is located (for superclasses support) */ Class<?> clazz; /** * Field in class */ Field fieldInClass; /** * Column name in table */ String inTableName; /** * SQL type */ SqlType sqlType; /** * SQL type string for current database type */ String sqlTypeString; /** * Primary key info */ DbPrimaryKeyInfo primaryKeyInfo; /** * Foreign key info */ DbForeignKeyInfo foreignKeyInfo; /** * @return DbField annotation */ public DbField getFieldAnnotation() { return fieldAnnotation; } @Override public Field getFieldInClass() { return fieldInClass; } /** * @return SQL type */ public SqlType getSqlType() { return sqlType; } /** * @return primary key info (or null) */ public DbPrimaryKeyInfo getPrimaryKeyInfo() { return primaryKeyInfo; } /** * @return foreign key info (or null) */ public DbForeignKeyInfo getForeignKeyInfo() { return foreignKeyInfo; } @Override public String getInQueryName() { return tableName + '_' + inTableName; } @Override public String getInTableName() { return inTableName; } } /** * Primary key info * * @author lukas */ public class DbPrimaryKeyInfo { DbPrimaryKeyInfo() {// not public constructor } /** * DbPrimaryKey annotation */ DbPrimaryKey pkAnnotation; /** * @return DbPrimaryKey annotation */ public DbPrimaryKey getPkAnnotation() { return pkAnnotation; } } /** * Foreign key info * * @author lukas */ public class DbForeignKeyInfo { DbForeignKeyInfo() {// not public constructor } /** * DbForeignKey annotation */ DbForeignKey fkAnnotation; /** * Field in class for store foreign object */ Field thisField; /** * Foreign table name */ String refTableName; /** * Foreign column name */ String refInTableName; /** * @return DbForeignKey annotation */ public DbForeignKey getFkAnnotation() { return fkAnnotation; } } /** * Many to one info * * @author lukas */ public class DbManyToOneInfo { DbManyToOneInfo() {// not public constructor } /** * DbManyToOne annotation */ DbManyToOne mtoAnnotation; /** * Field in class */ Field fieldInClass; /** * Field in ref class - foreign key field */ Field refFieldKey; /** * Field in ref class - object field */ Field refFieldObj; /** * @return DbManyToOne annotation */ public DbManyToOne getMtoAnnotation() { return mtoAnnotation; } } /** * One to one info * * @author lukas */ public class DbOneToOneInfo { DbOneToOneInfo() {// not public constructor } /** * DbOneToOne annotation */ DbOneToOne otoAnnotation; /** * Field in class */ Field fieldInClass; /** * Field in ref class - foreign key field */ Field refFieldKey; /** * Field in ref class - object field */ Field refFieldObj; /** * @return DbManyToOne annotation */ public DbOneToOne getOtoAnnotation() { return otoAnnotation; } } /** * VIEW field info * * @author lukas */ public class DbViewFieldInfo implements DbFieldOrViewInfo { DbViewFieldInfo() { } /** * DbViewField annotation */ DbViewField fieldAnnotation; /** * Class in which the field is located (for superclasses support) */ // Class<?> clazz; /** * Field in class */ Field fieldInClass; /** * Column name in query */ String inQueryName; @Override public String getInQueryName() { return inQueryName; } @Override public String getInTableName() { return inQueryName; } @Override public Field getFieldInClass() { return fieldInClass; } } /** * VIEW object info * * @author lukas */ public class DbViewObjectInfo { DbViewObjectInfo() { } /** * DbViewObject annotation */ DbViewObject fieldAnnotation; /** * Class in which the field is located (for superclasses support) */ // Class<?> clazz; /** * Field in class */ Field fieldInClass; } public interface DbFieldOrViewInfo { /** * @return name in query */ public String getInQueryName(); /** * @return name in table */ public String getInTableName(); /** * @return field in class */ public Field getFieldInClass(); /** * @return native java type */ default public Class<?> getNativeType() { return getFieldInClass().getType(); } /** * @param clazz native type to check * @return is native type? */ default public boolean nativeTypeIs(Class<?> clazz) { return getNativeType().isAssignableFrom(clazz); } } }
9119_6
package com.github.jowitam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.web.bind.annotation.*; import java.time.LocalDate; import java.util.List; /** * Controler w którym jest metoda GET i POST * dla GET dla zasobu /booking wroci wynik {"available": true} * dla POST możliwa jest rezerwacja pokoju (informacja przesłana JSON) */ @RestController public class BookingControler { @Autowired//spring wstrzyknie obiekt bedacy implementacja tego interfejsu private ReservationRepository repository; @RequestMapping("/booking") public Booking booking(@RequestParam("from") @DateTimeFormat(pattern = "ddMMyyyy") LocalDate from, @RequestParam("to") @DateTimeFormat(pattern = "ddMMyyyy") LocalDate to) { /** *aby sprawdzic dostepnosc dla podanego zakresu od do muszę po kolei dla podanych liczb * z zakresu sprawdzić na liście rezerwacji czy tam wystepują jak jakakolwiek * jest to dostepnosci brak */ if (!from.isBefore(to)) {//jezeli nie prawda jest ze from jest przed to throw new WrongDateRangeException(from, to); //WYJATEK wyrzucenie nowego wyjatku ktory jest obslugiwany przez Springa - pisany w osobnej klasie } List<Reservation> listReservation = repository.findByReservationDataBetween(from, to.minusDays(1)); if(listReservation.size() == 0){ return new Booking(true); }else{ return new Booking(false); } } /** * rezerwacja po przez wysłanie POST w formacie JSON */ @RequestMapping(value = "/booking", method = RequestMethod.POST) public void createBooking(@RequestBody NewBooking newBooking) { LocalDate now = LocalDate.now(); LocalDate from = newBooking.getFrom(); if (from.isBefore(now)) { throw new WrongDateRangeException(from); } if (booking(newBooking.getFrom(), newBooking.getTo()).getAvailable()){ for (LocalDate day = newBooking.getFrom(); day.isBefore(newBooking.getTo()); day = day.plusDays(1)) { repository.save(new Reservation(day)); } } else { throw new ReservedRoomException();//WYJATEK ze pokoj jest zarezerwowany } } }
Jowitam/simple-booking
src/main/java/com/github/jowitam/BookingControler.java
739
//WYJATEK ze pokoj jest zarezerwowany
line_comment
pl
package com.github.jowitam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.web.bind.annotation.*; import java.time.LocalDate; import java.util.List; /** * Controler w którym jest metoda GET i POST * dla GET dla zasobu /booking wroci wynik {"available": true} * dla POST możliwa jest rezerwacja pokoju (informacja przesłana JSON) */ @RestController public class BookingControler { @Autowired//spring wstrzyknie obiekt bedacy implementacja tego interfejsu private ReservationRepository repository; @RequestMapping("/booking") public Booking booking(@RequestParam("from") @DateTimeFormat(pattern = "ddMMyyyy") LocalDate from, @RequestParam("to") @DateTimeFormat(pattern = "ddMMyyyy") LocalDate to) { /** *aby sprawdzic dostepnosc dla podanego zakresu od do muszę po kolei dla podanych liczb * z zakresu sprawdzić na liście rezerwacji czy tam wystepują jak jakakolwiek * jest to dostepnosci brak */ if (!from.isBefore(to)) {//jezeli nie prawda jest ze from jest przed to throw new WrongDateRangeException(from, to); //WYJATEK wyrzucenie nowego wyjatku ktory jest obslugiwany przez Springa - pisany w osobnej klasie } List<Reservation> listReservation = repository.findByReservationDataBetween(from, to.minusDays(1)); if(listReservation.size() == 0){ return new Booking(true); }else{ return new Booking(false); } } /** * rezerwacja po przez wysłanie POST w formacie JSON */ @RequestMapping(value = "/booking", method = RequestMethod.POST) public void createBooking(@RequestBody NewBooking newBooking) { LocalDate now = LocalDate.now(); LocalDate from = newBooking.getFrom(); if (from.isBefore(now)) { throw new WrongDateRangeException(from); } if (booking(newBooking.getFrom(), newBooking.getTo()).getAvailable()){ for (LocalDate day = newBooking.getFrom(); day.isBefore(newBooking.getTo()); day = day.plusDays(1)) { repository.save(new Reservation(day)); } } else { throw new ReservedRoomException();//WYJATEK ze <SUF> } } }
8245_0
package service; import data.DistanceToCity; import java.util.HashMap; import java.util.List; import java.util.Map; public class RouteProbabilityCounter { public DistanceToCity chooseCityToGoToNext(List<DistanceToCity> distanceToCities, int a, int b) { double total = 0.0; Map<DistanceToCity, Double> rankForRouteToCity = new HashMap<>(); for (DistanceToCity distanceToCity : distanceToCities) { double rank = countRoute(distanceToCity, a, b); rankForRouteToCity.put(distanceToCity, rank); total += rank; } double randomTreshold = Math.random(); double cumulativeProbability = 0.0; for (DistanceToCity distanceToCity : distanceToCities) { cumulativeProbability += (rankForRouteToCity.get(distanceToCity) / total); if (randomTreshold <= cumulativeProbability) return distanceToCity; } throw new IndexOutOfBoundsException("Brak miast do odwiedzenia."); //błąd nie powinien nigdy wystąpić. } private double countRoute(DistanceToCity d1, int a, int b) { return Math.pow(d1.getPheromoneLevel(), a) * Math.pow(d1.getDistanceTo(), b); } }
Jozek2023/algorytm_mrowkowy_sztuczna_inteligencja
src/service/RouteProbabilityCounter.java
360
//błąd nie powinien nigdy wystąpić.
line_comment
pl
package service; import data.DistanceToCity; import java.util.HashMap; import java.util.List; import java.util.Map; public class RouteProbabilityCounter { public DistanceToCity chooseCityToGoToNext(List<DistanceToCity> distanceToCities, int a, int b) { double total = 0.0; Map<DistanceToCity, Double> rankForRouteToCity = new HashMap<>(); for (DistanceToCity distanceToCity : distanceToCities) { double rank = countRoute(distanceToCity, a, b); rankForRouteToCity.put(distanceToCity, rank); total += rank; } double randomTreshold = Math.random(); double cumulativeProbability = 0.0; for (DistanceToCity distanceToCity : distanceToCities) { cumulativeProbability += (rankForRouteToCity.get(distanceToCity) / total); if (randomTreshold <= cumulativeProbability) return distanceToCity; } throw new IndexOutOfBoundsException("Brak miast do odwiedzenia."); //błąd nie <SUF> } private double countRoute(DistanceToCity d1, int a, int b) { return Math.pow(d1.getPheromoneLevel(), a) * Math.pow(d1.getDistanceTo(), b); } }
9336_2
package com.company; import java.io.*; import java.util.Arrays; import java.util.Map; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collector; import java.util.stream.Collectors; // 1.każde miasto i usługa były pozbawione pustych znaków z przodu i z tyłu // 2.prawidłowo grupował usługi nawet jeśli ich definicje powtarzają się w kilku linijkach i są pisane literami różnej wielkości (sprowadzał nazwy usług i miast do małych liter) // 3.usuwał duplikaty usług w ramach jednego miasta, nawet jeśli są one pisane literami różnej wielkości // 4.ignorował puste linie // 5.ignorował linie które zaczynają się od słowa SKIP // 6.działał zgodnie z przykładem public class Default_Code { public static void main(String[] args) throws IOException { String input = "SKIPwarszawa;oc;zdrowotne\n" + "bielsko-biała;na życie ;od powodzi\n" + "łódź; od ognia;OD NIESZCZĘŚLIWYCH WYPADKÓW;ac\n\n" + " ŁÓDŹ;domu;na wypadek straty pracy;Ac"; InputStream inputStream = new java.io.ByteArrayInputStream(input.getBytes()); InsuranceServiceGrouping grouping = new InsuranceServiceGrouping(); Map<String, String[]> output = grouping.processFile(inputStream); } } class InsuranceServiceGrouping { Map<String, String[]> processFile(InputStream inputStream) throws IOException { Predicate<String> filter = x -> x.substring(1, 4) != "SKIP"; Function<String, String[]> mapper = line -> Arrays.stream(line.split(";")).toArray(String[]::new); Collector<String[], ?, Map<String, String[]>> collector = Collectors.toMap(elem -> elem[0], elem -> new String[] { elem[1], elem[2] }); StreamProcessor processor = new StreamProcessor.StreamProcessorBuilder().filter(filter).mapper(mapper) .collector(collector).build(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); return processFile(bufferedReader, processor); } Map<String, String[]> processFile(BufferedReader bufferedReader, StreamProcessor processor) throws IOException { int c=0; StringBuilder stringBuilder=new StringBuilder(); while ((c=bufferedReader.read())!=-1){ stringBuilder.append((char)c); } String word=stringBuilder.toString(); return word.lines().filter(processor.getFilter()).map(processor.getMapper()) .collect(processor.getCollector()); } } class StreamProcessor { private final Predicate<String> filter; private final Function<String, String[]> mapper; private final Collector<String[], ?, Map<String, String[]>> collector; StreamProcessor() { this.filter = null; this.mapper = null; this.collector = null; } StreamProcessor(StreamProcessorBuilder builder) { this.filter = builder.filter; this.mapper = builder.mapper; this.collector = builder.collector; } public static class StreamProcessorBuilder { private Predicate<String> filter; private Function<String, String[]> mapper; private Collector<String[], ?, Map<String, String[]>> collector; StreamProcessorBuilder filter(Predicate<String> filter) { this.filter = filter; return this; } StreamProcessorBuilder mapper(Function<String, String[]> mapper) { this.mapper = mapper; return this; } StreamProcessorBuilder collector(Collector<String[], ?, Map<String, String[]>> collector) { this.collector = collector; return this; } StreamProcessor build() { return new StreamProcessor(this); } } Predicate<String> getFilter() { return filter; } Function<String, String[]> getMapper() { return mapper; } Collector<String[], ?, Map<String, String[]>> getCollector() { return collector; } }
Js111l/PZU-Java-Challenge
src/com/company/Default_Code.java
1,238
// 3.usuwał duplikaty usług w ramach jednego miasta, nawet jeśli są one pisane literami różnej wielkości
line_comment
pl
package com.company; import java.io.*; import java.util.Arrays; import java.util.Map; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collector; import java.util.stream.Collectors; // 1.każde miasto i usługa były pozbawione pustych znaków z przodu i z tyłu // 2.prawidłowo grupował usługi nawet jeśli ich definicje powtarzają się w kilku linijkach i są pisane literami różnej wielkości (sprowadzał nazwy usług i miast do małych liter) // 3.usuwał duplikaty <SUF> // 4.ignorował puste linie // 5.ignorował linie które zaczynają się od słowa SKIP // 6.działał zgodnie z przykładem public class Default_Code { public static void main(String[] args) throws IOException { String input = "SKIPwarszawa;oc;zdrowotne\n" + "bielsko-biała;na życie ;od powodzi\n" + "łódź; od ognia;OD NIESZCZĘŚLIWYCH WYPADKÓW;ac\n\n" + " ŁÓDŹ;domu;na wypadek straty pracy;Ac"; InputStream inputStream = new java.io.ByteArrayInputStream(input.getBytes()); InsuranceServiceGrouping grouping = new InsuranceServiceGrouping(); Map<String, String[]> output = grouping.processFile(inputStream); } } class InsuranceServiceGrouping { Map<String, String[]> processFile(InputStream inputStream) throws IOException { Predicate<String> filter = x -> x.substring(1, 4) != "SKIP"; Function<String, String[]> mapper = line -> Arrays.stream(line.split(";")).toArray(String[]::new); Collector<String[], ?, Map<String, String[]>> collector = Collectors.toMap(elem -> elem[0], elem -> new String[] { elem[1], elem[2] }); StreamProcessor processor = new StreamProcessor.StreamProcessorBuilder().filter(filter).mapper(mapper) .collector(collector).build(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); return processFile(bufferedReader, processor); } Map<String, String[]> processFile(BufferedReader bufferedReader, StreamProcessor processor) throws IOException { int c=0; StringBuilder stringBuilder=new StringBuilder(); while ((c=bufferedReader.read())!=-1){ stringBuilder.append((char)c); } String word=stringBuilder.toString(); return word.lines().filter(processor.getFilter()).map(processor.getMapper()) .collect(processor.getCollector()); } } class StreamProcessor { private final Predicate<String> filter; private final Function<String, String[]> mapper; private final Collector<String[], ?, Map<String, String[]>> collector; StreamProcessor() { this.filter = null; this.mapper = null; this.collector = null; } StreamProcessor(StreamProcessorBuilder builder) { this.filter = builder.filter; this.mapper = builder.mapper; this.collector = builder.collector; } public static class StreamProcessorBuilder { private Predicate<String> filter; private Function<String, String[]> mapper; private Collector<String[], ?, Map<String, String[]>> collector; StreamProcessorBuilder filter(Predicate<String> filter) { this.filter = filter; return this; } StreamProcessorBuilder mapper(Function<String, String[]> mapper) { this.mapper = mapper; return this; } StreamProcessorBuilder collector(Collector<String[], ?, Map<String, String[]>> collector) { this.collector = collector; return this; } StreamProcessor build() { return new StreamProcessor(this); } } Predicate<String> getFilter() { return filter; } Function<String, String[]> getMapper() { return mapper; } Collector<String[], ?, Map<String, String[]>> getCollector() { return collector; } }
7155_1
package agh.ics.oop; import java.util.Objects; public class Vector2d { final int x; //final -> nie ma możliwości zmiany danych final int y; public Vector2d(int x, int y) { this.x = x; this.y = y; } public Vector2d add(Vector2d other){ return new Vector2d(x + other.x, y + other.y); } public Vector2d subtract(Vector2d other){ return new Vector2d(x - other.x, y - other.y); } public Vector2d upperRight(Vector2d other){ return new Vector2d(Math.max(x, other.x), Math.max(y, other.y)); } public Vector2d lowerLeft(Vector2d other){ return new Vector2d(Math.min(x, other.x), Math.min(y, other.y)); } public Vector2d opposite(){ return new Vector2d(-x, -y); } @Override public boolean equals(Object other){ //dostaję Object other i zwraca mi bool if (this == other){ //jeśli mój wektor i other mają ten sam adres return true; } if (!(other instanceof Vector2d)){ //jeśli other nie jest zgodny z typem Vector2d return false; } Vector2d newVector = (Vector2d) other; //zamieniam object other na wektor typu vector2d if (newVector.x == x && newVector.y == y){ return true; }else{ return false; } } @Override public int hashCode(){ return Objects.hash(x, y); } @Override //odziedziczona metoda z klasy typu object public String toString() { return "(%d, %d)".formatted(x, y); //%d -> int } boolean precedes(Vector2d other){ return x <= other.x && y <= other.y; } boolean follows(Vector2d other){ return x >= other.x && y >= other.y; } }
Jullija/ProgramowanieObiektowe
lab5/oolab/src/main/java/agh/ics/oop/Vector2d.java
602
//dostaję Object other i zwraca mi bool
line_comment
pl
package agh.ics.oop; import java.util.Objects; public class Vector2d { final int x; //final -> nie ma możliwości zmiany danych final int y; public Vector2d(int x, int y) { this.x = x; this.y = y; } public Vector2d add(Vector2d other){ return new Vector2d(x + other.x, y + other.y); } public Vector2d subtract(Vector2d other){ return new Vector2d(x - other.x, y - other.y); } public Vector2d upperRight(Vector2d other){ return new Vector2d(Math.max(x, other.x), Math.max(y, other.y)); } public Vector2d lowerLeft(Vector2d other){ return new Vector2d(Math.min(x, other.x), Math.min(y, other.y)); } public Vector2d opposite(){ return new Vector2d(-x, -y); } @Override public boolean equals(Object other){ //dostaję Object <SUF> if (this == other){ //jeśli mój wektor i other mają ten sam adres return true; } if (!(other instanceof Vector2d)){ //jeśli other nie jest zgodny z typem Vector2d return false; } Vector2d newVector = (Vector2d) other; //zamieniam object other na wektor typu vector2d if (newVector.x == x && newVector.y == y){ return true; }else{ return false; } } @Override public int hashCode(){ return Objects.hash(x, y); } @Override //odziedziczona metoda z klasy typu object public String toString() { return "(%d, %d)".formatted(x, y); //%d -> int } boolean precedes(Vector2d other){ return x <= other.x && y <= other.y; } boolean follows(Vector2d other){ return x >= other.x && y >= other.y; } }
3407_0
import javax.swing.*; import java.awt.*; import java.io.IOException; import java.net.Socket; public class MainWindow { private final JFrame window; private static final int BUTTONFONTSIZE = 16; private Server server; private Client client; boolean gameStarted; boolean stopHostingGame; private final NickNameTakenWindow alertWindow; public MainWindow(){ gameStarted=false; stopHostingGame=false; MenuWindow menuWindow=new MenuWindow(); alertWindow=new NickNameTakenWindow(); Player player=new Player(); JPanel container; // Tworzenie panelu Container container = new JPanel() { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); ImageIcon menuBackground = new ImageIcon("assets/tmp_bg.png"); g.drawImage(menuBackground.getImage(), 0, 0, null); } }; container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS)); menuWindow.logoLabel.setBorder(BorderFactory.createEmptyBorder(60, 0, 0, 0)); container.add(menuWindow.logoLabel); container.add(menuWindow.mainMenu); container.add(menuWindow.menuHostGame, BorderLayout.NORTH); container.add(menuWindow.menuJoinGame); menuWindow.menuPlay.setVisible(false); menuWindow.menuHostGame.setVisible(false); menuWindow.menuJoinGame.setVisible(false); container.add(menuWindow.menuPlay); //akcje przycisków menuWindow.playButton.addActionListener(back -> { menuWindow.mainMenu.setVisible(false); menuWindow.menuPlay.setVisible(true); }); menuWindow.enterJoinMenuButton.addActionListener(back -> { menuWindow.menuPlay.setVisible(false); menuWindow.menuJoinGame.setVisible(true); }); menuWindow.joinGameButton.addActionListener(back -> { if(!player.playerConnected){ try { client=new Client(); client.ClientConnect(menuWindow.ipAddressGetTextField.getText(),8080); client.SetCommunicationParameters(client.clientSocket); player.PlayerConnect(); ClientReadFromServer clientReadFromServer=new ClientReadFromServer(client,menuWindow,menuWindow.joinGameListButtons,alertWindow,player); clientReadFromServer.start(); client.fromClient.println("setNickname:"+menuWindow.nickNameTextFieldJoinMenu.getText()); } catch (IOException e) { } }else{ alertWindow.setMessage("Jesteś juz w lobby!!"); alertWindow.show(); } }); menuWindow.enterHostMenuButton.addActionListener(back -> { server=new Server(); synchronized (this) { stopHostingGame=false; } try { server.openSocket(8080); server.serverSocketChannel.setSoTimeout(1000); } catch (IOException e) { alertWindow.setMessage("Server juz istnieje!"); alertWindow.show(); return; } menuWindow.menuPlay.setVisible(false); menuWindow.menuHostGame.setVisible(true); Thread ThreadWaitingForPlayers = new Thread(() -> { ServerMainThread serverMainThread=new ServerMainThread(server); serverMainThread.start(); while (true){ synchronized (this) { if(gameStarted || stopHostingGame){ break; } } Socket tmp_clientSock = null; try { tmp_clientSock = server.serverSocketChannel.accept(); server.addSemaphore(); Communication tmp_Comm=server.listOfCommunication.get(server.listOfCommunication.size()-1); ServerReadFromClient serverReadThread=new ServerReadFromClient(tmp_clientSock,tmp_Comm,server.syncJoiningPlayers); serverReadThread.start(); ServerWriteTOClient serverWriteThread=new ServerWriteTOClient(tmp_clientSock,tmp_Comm); serverWriteThread.start(); } catch (IOException e) {} } }); ThreadWaitingForPlayers.start(); while (true){ try { client=new Client(); client.ClientConnect("localhost",8080); client.SetCommunicationParameters(client.clientSocket); ClientReadFromServer clientReadFromServer=new ClientReadFromServer(client,menuWindow,menuWindow.hostGameListButtons,alertWindow,player); clientReadFromServer.start(); client.fromClient.println("setNickname:"+menuWindow.nickNameTextFieldHostMenu.getText()); break; } catch (IOException e) {} } }); menuWindow.backToMainMenuButton.addActionListener(back -> { menuWindow.mainMenu.setVisible(true); menuWindow.menuPlay.setVisible(false); }); menuWindow.backFromJoinMenuButton.addActionListener(back -> { if(player.playerConnected){ try{ client.fromClient.println("Quit"); player.PlayerDisconnect(); }catch (NullPointerException error) { } }else{ menuWindow.menuPlay.setVisible(true); menuWindow.menuJoinGame.setVisible(false); } }); menuWindow.backFromHostMenuButton.addActionListener(back -> { synchronized (this) { stopHostingGame=true; try { Thread.sleep(1000); server.serverSocketChannel.close(); client.fromClient.println("Quit"); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } }); menuWindow.changeNickNameHostButton.addActionListener(back -> { client.fromClient.println("changeNickname:"+menuWindow.nickNameTextFieldHostMenu.getText()); }); menuWindow.changeNickNameJoinButton.addActionListener(back -> { client.fromClient.println("changeNickname:"+menuWindow.nickNameTextFieldJoinMenu.getText()); }); menuWindow.startGameButton.addActionListener(back -> { GamingWindow a=new GamingWindow(); /*synchronized (this) { gameStarted=true; }*/ }); menuWindow.leaveButton.addActionListener(leaveGame -> System.exit(0)); window = new JFrame(); window.setTitle("PoliPoly"); window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); window.setSize(800, 600); window.setLocationRelativeTo(null); window.add(container); } public void show() { window.setVisible(true); } }
JuraGrzegorz/PoliPoly
src/MainWindow.java
1,864
// Tworzenie panelu Container
line_comment
pl
import javax.swing.*; import java.awt.*; import java.io.IOException; import java.net.Socket; public class MainWindow { private final JFrame window; private static final int BUTTONFONTSIZE = 16; private Server server; private Client client; boolean gameStarted; boolean stopHostingGame; private final NickNameTakenWindow alertWindow; public MainWindow(){ gameStarted=false; stopHostingGame=false; MenuWindow menuWindow=new MenuWindow(); alertWindow=new NickNameTakenWindow(); Player player=new Player(); JPanel container; // Tworzenie panelu <SUF> container = new JPanel() { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); ImageIcon menuBackground = new ImageIcon("assets/tmp_bg.png"); g.drawImage(menuBackground.getImage(), 0, 0, null); } }; container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS)); menuWindow.logoLabel.setBorder(BorderFactory.createEmptyBorder(60, 0, 0, 0)); container.add(menuWindow.logoLabel); container.add(menuWindow.mainMenu); container.add(menuWindow.menuHostGame, BorderLayout.NORTH); container.add(menuWindow.menuJoinGame); menuWindow.menuPlay.setVisible(false); menuWindow.menuHostGame.setVisible(false); menuWindow.menuJoinGame.setVisible(false); container.add(menuWindow.menuPlay); //akcje przycisków menuWindow.playButton.addActionListener(back -> { menuWindow.mainMenu.setVisible(false); menuWindow.menuPlay.setVisible(true); }); menuWindow.enterJoinMenuButton.addActionListener(back -> { menuWindow.menuPlay.setVisible(false); menuWindow.menuJoinGame.setVisible(true); }); menuWindow.joinGameButton.addActionListener(back -> { if(!player.playerConnected){ try { client=new Client(); client.ClientConnect(menuWindow.ipAddressGetTextField.getText(),8080); client.SetCommunicationParameters(client.clientSocket); player.PlayerConnect(); ClientReadFromServer clientReadFromServer=new ClientReadFromServer(client,menuWindow,menuWindow.joinGameListButtons,alertWindow,player); clientReadFromServer.start(); client.fromClient.println("setNickname:"+menuWindow.nickNameTextFieldJoinMenu.getText()); } catch (IOException e) { } }else{ alertWindow.setMessage("Jesteś juz w lobby!!"); alertWindow.show(); } }); menuWindow.enterHostMenuButton.addActionListener(back -> { server=new Server(); synchronized (this) { stopHostingGame=false; } try { server.openSocket(8080); server.serverSocketChannel.setSoTimeout(1000); } catch (IOException e) { alertWindow.setMessage("Server juz istnieje!"); alertWindow.show(); return; } menuWindow.menuPlay.setVisible(false); menuWindow.menuHostGame.setVisible(true); Thread ThreadWaitingForPlayers = new Thread(() -> { ServerMainThread serverMainThread=new ServerMainThread(server); serverMainThread.start(); while (true){ synchronized (this) { if(gameStarted || stopHostingGame){ break; } } Socket tmp_clientSock = null; try { tmp_clientSock = server.serverSocketChannel.accept(); server.addSemaphore(); Communication tmp_Comm=server.listOfCommunication.get(server.listOfCommunication.size()-1); ServerReadFromClient serverReadThread=new ServerReadFromClient(tmp_clientSock,tmp_Comm,server.syncJoiningPlayers); serverReadThread.start(); ServerWriteTOClient serverWriteThread=new ServerWriteTOClient(tmp_clientSock,tmp_Comm); serverWriteThread.start(); } catch (IOException e) {} } }); ThreadWaitingForPlayers.start(); while (true){ try { client=new Client(); client.ClientConnect("localhost",8080); client.SetCommunicationParameters(client.clientSocket); ClientReadFromServer clientReadFromServer=new ClientReadFromServer(client,menuWindow,menuWindow.hostGameListButtons,alertWindow,player); clientReadFromServer.start(); client.fromClient.println("setNickname:"+menuWindow.nickNameTextFieldHostMenu.getText()); break; } catch (IOException e) {} } }); menuWindow.backToMainMenuButton.addActionListener(back -> { menuWindow.mainMenu.setVisible(true); menuWindow.menuPlay.setVisible(false); }); menuWindow.backFromJoinMenuButton.addActionListener(back -> { if(player.playerConnected){ try{ client.fromClient.println("Quit"); player.PlayerDisconnect(); }catch (NullPointerException error) { } }else{ menuWindow.menuPlay.setVisible(true); menuWindow.menuJoinGame.setVisible(false); } }); menuWindow.backFromHostMenuButton.addActionListener(back -> { synchronized (this) { stopHostingGame=true; try { Thread.sleep(1000); server.serverSocketChannel.close(); client.fromClient.println("Quit"); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } }); menuWindow.changeNickNameHostButton.addActionListener(back -> { client.fromClient.println("changeNickname:"+menuWindow.nickNameTextFieldHostMenu.getText()); }); menuWindow.changeNickNameJoinButton.addActionListener(back -> { client.fromClient.println("changeNickname:"+menuWindow.nickNameTextFieldJoinMenu.getText()); }); menuWindow.startGameButton.addActionListener(back -> { GamingWindow a=new GamingWindow(); /*synchronized (this) { gameStarted=true; }*/ }); menuWindow.leaveButton.addActionListener(leaveGame -> System.exit(0)); window = new JFrame(); window.setTitle("PoliPoly"); window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); window.setSize(800, 600); window.setLocationRelativeTo(null); window.add(container); } public void show() { window.setVisible(true); } }
10562_2
package FirstYear.Labs.no4; public class Person { //Definicja pól String imie, nazwisko; int wiek; //metody dla tej klasy public void wypisz() { System.out.println("Imie i nazwisko: "+imie+" "+nazwisko+" i wiek: "+wiek); } //Konstruktory - zawsze są publiczne, mają nazwę klasy, tworzy obiekt i wpisuje od razu dane //Niejawny konstruktor public Person(){ } //Przeciażenie (overload) metody - zmiana ciała metody //this - wskazuje na obiekt klasy public Person(String imie){ this.imie = imie; //do pola klasy wstaw to co jest w metodzie } // alt+insert - generator np konstruktorów // // public Person(int wiek) { // this.wiek = wiek; // } public Person(String imie, String nazwisko, int wiek) { this.imie = imie; this.nazwisko = nazwisko; this.wiek = wiek; } //Gettery i settery - umożliwiają pobranie i ustawienie pola w klasie public String getImie() { return imie; } public String getNazwisko() { return nazwisko; } public int getWiek() { return wiek; } public void setImie(String imie) { this.imie = imie; } public void setNazwisko(String nazwisko) { this.nazwisko = nazwisko; } public void setWiek(int wiek) { this.wiek = wiek; } @Override public String toString() { return "Person{" + "imie='" + imie + '\'' + ", nazwisko='" + nazwisko + '\'' + ", wiek=" + wiek + '}'; } }
JustFiesta/JavaBasics
src/FirstYear/Labs/no4/Person.java
566
//Przeciażenie (overload) metody - zmiana ciała metody
line_comment
pl
package FirstYear.Labs.no4; public class Person { //Definicja pól String imie, nazwisko; int wiek; //metody dla tej klasy public void wypisz() { System.out.println("Imie i nazwisko: "+imie+" "+nazwisko+" i wiek: "+wiek); } //Konstruktory - zawsze są publiczne, mają nazwę klasy, tworzy obiekt i wpisuje od razu dane //Niejawny konstruktor public Person(){ } //Przeciażenie (overload) <SUF> //this - wskazuje na obiekt klasy public Person(String imie){ this.imie = imie; //do pola klasy wstaw to co jest w metodzie } // alt+insert - generator np konstruktorów // // public Person(int wiek) { // this.wiek = wiek; // } public Person(String imie, String nazwisko, int wiek) { this.imie = imie; this.nazwisko = nazwisko; this.wiek = wiek; } //Gettery i settery - umożliwiają pobranie i ustawienie pola w klasie public String getImie() { return imie; } public String getNazwisko() { return nazwisko; } public int getWiek() { return wiek; } public void setImie(String imie) { this.imie = imie; } public void setNazwisko(String nazwisko) { this.nazwisko = nazwisko; } public void setWiek(int wiek) { this.wiek = wiek; } @Override public String toString() { return "Person{" + "imie='" + imie + '\'' + ", nazwisko='" + nazwisko + '\'' + ", wiek=" + wiek + '}'; } }
10059_3
import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.concurrent.CountDownLatch; public class Game extends JFrame { private final Player[] players; private Player currentPlayer; private final Board board; private final JPanel gameInfoPanel = new JPanel(); private final JLabel textInfoGame = new JLabel(); private final JLabel titlePlayerPanel = new JLabel(); private final JPanel[] playersPanels; private final JPanel playerInfoPanel = new JPanel(); private Field cardView; private final JLabel dicePlaceholder = new JLabel(); private final JLabel dicePlaceholderSecond = new JLabel(); private Dice firstDice = new Dice(); private Dice secondDice = new Dice(); private int diceResult; private static int PLAYER_NUMBER; public int WINDOW_WIDTH = 1500; public int WINDOW_HEIGHT = 1000; private final int HOUSE_PRICE = 500; // TODO: Ekonomia -> koszt dobudowania domu public Game() { board = new Board(); players = new Player[PLAYER_NUMBER]; playersPanels = new JPanel[PLAYER_NUMBER]; if (PLAYER_NUMBER >= 1) { players[0] = new Player(PlayersColors.BLUE); playersPanels[0] = new JPanel(); board.setPawn(players[0], 0); } if (PLAYER_NUMBER >= 2) { players[1] = new Player(PlayersColors.RED); playersPanels[1] = new JPanel(); board.setPawn(players[1], 0); } if (PLAYER_NUMBER >= 3) { players[2] = new Player(PlayersColors.GREEN); playersPanels[2] = new JPanel(); board.setPawn(players[2], 0); } if (PLAYER_NUMBER == 4) { players[3] = new Player(PlayersColors.YELLOW); playersPanels[3] = new JPanel(); board.setPawn(players[3], 0); } currentPlayer = players[0]; setDefaultCard(); setWindowParameters(); } public static void startMenu() { Object[] options = {"2 graczy", "3 graczy", "4 graczy"}; int check = JOptionPane.showOptionDialog(null, "Wybierz ilość graczy: ", "Monopoly", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]); if (check == 0) PLAYER_NUMBER = 2; else if (check == 1) PLAYER_NUMBER = 3; else PLAYER_NUMBER = 4; } public void round() { for (Player player : players) { if (player.getPlayerStatus() != PlayerStatus.LOST) { currentPlayer = player; setInformation(); setDiceListeners(); System.out.println("wynik kostki:" + diceResult); if (currentPlayer.getPlayerStatus() == PlayerStatus.IN_GAME) { currentPlayer.playerMove(diceResult); board.setPawn(currentPlayer, currentPlayer.getPosition()); } setCardView(); triggerFieldRound(board.getField(currentPlayer.getPosition())); System.out.println("pozycja gracza: " + currentPlayer.getPlayerColor() + " " + currentPlayer.getPosition()); diceResult = 0; repaintBoard(); } } } private void triggerFieldRound(Field field) { switch (field.getFieldType()) { case TAX -> triggerTax(); case JAIL -> triggerJail(); case NORMAL, BALL -> triggerNormal(field); case CHANCE -> triggerChance(); case GO_TO_JAIL -> triggerGoToJail(); case START, PARKING -> { } } } private void infoPanel(String s) { JFrame f = new JFrame(); JOptionPane.showMessageDialog(f, s); } private void triggerGoToJail() { currentPlayer.blockPlayer(); infoPanel("Idziesz do więzienia."); board.setPawn(currentPlayer, currentPlayer.getPosition()); } private void triggerChance() { Chance chance = board.getRandomChance(); infoPanel(chance.getContents()); currentPlayer.increaseMoney(chance.getMoney(currentPlayer.getMoneyInWallet())); if (currentPlayer.getMoneyInWallet() < 0) { // TODO: Opcja windykacji działek } } private void triggerNormal(Field field) { if (field.getOwner() == null) { if (field.getBuyPrice() > currentPlayer.getMoneyInWallet()) { infoPanel("Nie masz wystarczająco pieniędzy na zakup piłki."); } else { buyField(currentPlayer, field); } } else if (field.getOwner() != currentPlayer) { int sleepPrice = (int) field.getSleepPrice(); infoPanel("Musisz zapłacić za postój " + sleepPrice); currentPlayer.decreaseMoney(sleepPrice); field.getOwner().increaseMoney(sleepPrice); if (currentPlayer.getMoneyInWallet() < 0) { // TODO: Opcja windykacji działek } } else if (field.getOwner() == currentPlayer && field.getFieldType() == FieldType.NORMAL && currentPlayer.isHavingAllCountry(field.getCountry()) && currentPlayer.getMoneyInWallet() >= HOUSE_PRICE && field.getAccommodationLevel() < field.MAX_ACCOMMODATION_LEVEL) { buildHouses(field); } } private void triggerJail() { if (diceResult == 12) { infoPanel("Wychodzisz z więzienia."); currentPlayer.unlockPlayer(); } else if (currentPlayer.getPlayerStatus() == PlayerStatus.IN_JAIL) { infoPanel("Zostajesz w więzieniu"); } } private void triggerTax() { int tax = (int) (board.getRandomChance().getRandomTax() * currentPlayer.getMoneyInWallet()); infoPanel("Musisz zapłacić podatek od swoich oszczędności w wysokości " + tax); currentPlayer.decreaseMoney(tax); if (currentPlayer.getMoneyInWallet() < 0) { // TODO: Opcja windykacji działek } } public void repaintBoard() { setCardView(); board.repaint(); gameInfoPanel.repaint(); playerInfoPanel.repaint(); setPlayerMiniCards(); } private void setDiceListeners() { final CountDownLatch latch = new CountDownLatch(1); firstDice.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { firstDice = (Dice) e.getSource(); diceResult = firstDice.diceThrow() + secondDice.diceThrow(); latch.countDown(); // Zwalnianie CountDownLatch po kliknięciu } }); secondDice.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { secondDice = (Dice) e.getSource(); diceResult = firstDice.diceThrow() + secondDice.diceThrow(); latch.countDown(); // Zwalnianie CountDownLatch po kliknięciu } }); try { latch.await(); // Oczekiwanie na kliknięcie } catch (InterruptedException e) { e.printStackTrace(); } firstDice.removeMouseListener(firstDice.getMouseListeners()[0]); secondDice.removeMouseListener(secondDice.getMouseListeners()[0]); } private void setInformation() { textInfoGame.setText("Ruch: " + currentPlayer.getPlayerColor()); } private void setCardView() { Field temp = board.getField(currentPlayer.getPosition()); Image image = temp.getFieldCard(); cardView.setFieldCard(image); cardView.repaint(); } private void setDefaultCard() { Image image = new ImageIcon("./assets/Cards/defaultCard.png").getImage(); cardView = board.getField(0); cardView.setFieldCard(image); cardView.repaint(); } private void setPlayerMiniCards() { for (int i = 0; i < PLAYER_NUMBER; i++) { ArrayList<Field> fieldsToDisplay = new ArrayList<>(); for (Field owns : players[i].getOwnedFields()) { owns.setFieldCard(owns.getMiniFieldCard()); owns.setPreferredSize(new Dimension(100, 30)); owns.setBounds(0, 0, 100, 30); fieldsToDisplay.add(owns); } for (Field field : fieldsToDisplay) { playersPanels[i].add(field, BorderLayout.SOUTH); } fieldsToDisplay.clear(); } } public void setDiceView(int diceResult, Dice dicePlaceholder) { dicePlaceholder.setIcon(Dice.diceViews[diceResult - 1]); } private void buyField(Player player, Field field) { Object[] options = {"Tak", "Nie"}; int check = JOptionPane.showOptionDialog(null, "Czy chcesz kupić pole " + field.getFieldName() + "?", "Monopoly", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]); if (check == 0) { field.setOwner(player); player.buyField(field); infoPanel("Gratulacje zakupu " + field.getFieldName()); } } private void buildHouses(Field field) { Object[] options = {"Tak", "Nie"}; int check = JOptionPane.showOptionDialog(null, "Czy podnieść poziom na polu " + field.getFieldName() + " za " + HOUSE_PRICE + "?", "Monopoly", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]); if (check == 0) { field.increaseAccommodationLevel(); currentPlayer.decreaseMoney(HOUSE_PRICE); infoPanel("Właśnie podwyższyłeś poziom pola " + field.getFieldType() + " na " + field.getAccommodationLevel()); } } private void setPlayersPanelView() { playerInfoPanel.setPreferredSize(new Dimension(300, 900)); playerInfoPanel.setBounds(1200, 0, 300, 900); playerInfoPanel.setBackground(new Color(227, 139, 27)); titlePlayerPanel.setPreferredSize(new Dimension(200, 20)); titlePlayerPanel.setBackground(new Color(255, 255, 255)); titlePlayerPanel.setForeground(new Color(236, 245, 133)); titlePlayerPanel.setHorizontalAlignment(JLabel.CENTER); titlePlayerPanel.setFont(new Font("Arial", Font.BOLD, 20)); titlePlayerPanel.setText("PLAYERS PANELS:"); playerInfoPanel.add(titlePlayerPanel, BorderLayout.CENTER); int counter = 0; for (JPanel panel : playersPanels) { panel.setPreferredSize(new Dimension(300, 200)); panel.setBackground(new Color(236, 245, 133)); JLabel text = new JLabel(); text.setPreferredSize(new Dimension(300, 15)); text.setForeground(new Color(227, 139, 27)); text.setFont(new Font("Arial", Font.BOLD, 15)); text.setText("Player " + players[counter].getPlayerColor()); text.setHorizontalAlignment(JLabel.CENTER); panel.add(text); playerInfoPanel.add(panel, BorderLayout.SOUTH); counter++; } } private void setWindowParameters() { this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setResizable(false); this.setSize(WINDOW_WIDTH, WINDOW_HEIGHT); this.setLayout(null); this.setVisible(true); this.setTitle("MONOPOLY - WORLD CUP EDITION"); cardView.setPreferredSize(new Dimension(317, 457)); cardView.setHorizontalAlignment(JLabel.CENTER); firstDice.setForeground(Color.white); firstDice.setPreferredSize(new Dimension(90, 90)); firstDice.setBounds(50, 0, 90, 90); secondDice.setForeground(Color.white); secondDice.setPreferredSize(new Dimension(90, 90)); secondDice.setBounds(50, 0, 90, 90); dicePlaceholder.setPreferredSize(new Dimension(200, 100)); dicePlaceholder.setHorizontalAlignment(JLabel.LEFT); dicePlaceholder.add(firstDice); setDiceView(1, firstDice); dicePlaceholderSecond.setPreferredSize(new Dimension(200, 100)); dicePlaceholderSecond.setHorizontalAlignment(JLabel.RIGHT); dicePlaceholderSecond.add(secondDice); setDiceView(4, secondDice); textInfoGame.setPreferredSize(new Dimension(200, 50)); textInfoGame.setBackground(new Color(255, 255, 255)); textInfoGame.setForeground(new Color(241, 3, 3)); textInfoGame.setHorizontalAlignment(JLabel.CENTER); textInfoGame.setFont(new Font("Arial", Font.BOLD, 10)); textInfoGame.setText("Ruch gracza: " + currentPlayer.getPlayerColor()); gameInfoPanel.setPreferredSize(new Dimension(300, 900)); gameInfoPanel.setBackground(Color.YELLOW); gameInfoPanel.setBounds(0, 0, 300, 900); gameInfoPanel.add(textInfoGame, BorderLayout.CENTER); gameInfoPanel.add(cardView); gameInfoPanel.add(dicePlaceholder); gameInfoPanel.add(dicePlaceholderSecond); setPlayersPanelView(); this.add(gameInfoPanel, BorderLayout.WEST); this.add(board, BorderLayout.CENTER); this.add(playerInfoPanel, BorderLayout.EAST); this.repaint(); } }
Jvsin/Monopoly
src/Game.java
4,145
// TODO: Opcja windykacji działek
line_comment
pl
import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.concurrent.CountDownLatch; public class Game extends JFrame { private final Player[] players; private Player currentPlayer; private final Board board; private final JPanel gameInfoPanel = new JPanel(); private final JLabel textInfoGame = new JLabel(); private final JLabel titlePlayerPanel = new JLabel(); private final JPanel[] playersPanels; private final JPanel playerInfoPanel = new JPanel(); private Field cardView; private final JLabel dicePlaceholder = new JLabel(); private final JLabel dicePlaceholderSecond = new JLabel(); private Dice firstDice = new Dice(); private Dice secondDice = new Dice(); private int diceResult; private static int PLAYER_NUMBER; public int WINDOW_WIDTH = 1500; public int WINDOW_HEIGHT = 1000; private final int HOUSE_PRICE = 500; // TODO: Ekonomia -> koszt dobudowania domu public Game() { board = new Board(); players = new Player[PLAYER_NUMBER]; playersPanels = new JPanel[PLAYER_NUMBER]; if (PLAYER_NUMBER >= 1) { players[0] = new Player(PlayersColors.BLUE); playersPanels[0] = new JPanel(); board.setPawn(players[0], 0); } if (PLAYER_NUMBER >= 2) { players[1] = new Player(PlayersColors.RED); playersPanels[1] = new JPanel(); board.setPawn(players[1], 0); } if (PLAYER_NUMBER >= 3) { players[2] = new Player(PlayersColors.GREEN); playersPanels[2] = new JPanel(); board.setPawn(players[2], 0); } if (PLAYER_NUMBER == 4) { players[3] = new Player(PlayersColors.YELLOW); playersPanels[3] = new JPanel(); board.setPawn(players[3], 0); } currentPlayer = players[0]; setDefaultCard(); setWindowParameters(); } public static void startMenu() { Object[] options = {"2 graczy", "3 graczy", "4 graczy"}; int check = JOptionPane.showOptionDialog(null, "Wybierz ilość graczy: ", "Monopoly", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]); if (check == 0) PLAYER_NUMBER = 2; else if (check == 1) PLAYER_NUMBER = 3; else PLAYER_NUMBER = 4; } public void round() { for (Player player : players) { if (player.getPlayerStatus() != PlayerStatus.LOST) { currentPlayer = player; setInformation(); setDiceListeners(); System.out.println("wynik kostki:" + diceResult); if (currentPlayer.getPlayerStatus() == PlayerStatus.IN_GAME) { currentPlayer.playerMove(diceResult); board.setPawn(currentPlayer, currentPlayer.getPosition()); } setCardView(); triggerFieldRound(board.getField(currentPlayer.getPosition())); System.out.println("pozycja gracza: " + currentPlayer.getPlayerColor() + " " + currentPlayer.getPosition()); diceResult = 0; repaintBoard(); } } } private void triggerFieldRound(Field field) { switch (field.getFieldType()) { case TAX -> triggerTax(); case JAIL -> triggerJail(); case NORMAL, BALL -> triggerNormal(field); case CHANCE -> triggerChance(); case GO_TO_JAIL -> triggerGoToJail(); case START, PARKING -> { } } } private void infoPanel(String s) { JFrame f = new JFrame(); JOptionPane.showMessageDialog(f, s); } private void triggerGoToJail() { currentPlayer.blockPlayer(); infoPanel("Idziesz do więzienia."); board.setPawn(currentPlayer, currentPlayer.getPosition()); } private void triggerChance() { Chance chance = board.getRandomChance(); infoPanel(chance.getContents()); currentPlayer.increaseMoney(chance.getMoney(currentPlayer.getMoneyInWallet())); if (currentPlayer.getMoneyInWallet() < 0) { // TODO: Opcja windykacji działek } } private void triggerNormal(Field field) { if (field.getOwner() == null) { if (field.getBuyPrice() > currentPlayer.getMoneyInWallet()) { infoPanel("Nie masz wystarczająco pieniędzy na zakup piłki."); } else { buyField(currentPlayer, field); } } else if (field.getOwner() != currentPlayer) { int sleepPrice = (int) field.getSleepPrice(); infoPanel("Musisz zapłacić za postój " + sleepPrice); currentPlayer.decreaseMoney(sleepPrice); field.getOwner().increaseMoney(sleepPrice); if (currentPlayer.getMoneyInWallet() < 0) { // TODO: Opcja windykacji działek } } else if (field.getOwner() == currentPlayer && field.getFieldType() == FieldType.NORMAL && currentPlayer.isHavingAllCountry(field.getCountry()) && currentPlayer.getMoneyInWallet() >= HOUSE_PRICE && field.getAccommodationLevel() < field.MAX_ACCOMMODATION_LEVEL) { buildHouses(field); } } private void triggerJail() { if (diceResult == 12) { infoPanel("Wychodzisz z więzienia."); currentPlayer.unlockPlayer(); } else if (currentPlayer.getPlayerStatus() == PlayerStatus.IN_JAIL) { infoPanel("Zostajesz w więzieniu"); } } private void triggerTax() { int tax = (int) (board.getRandomChance().getRandomTax() * currentPlayer.getMoneyInWallet()); infoPanel("Musisz zapłacić podatek od swoich oszczędności w wysokości " + tax); currentPlayer.decreaseMoney(tax); if (currentPlayer.getMoneyInWallet() < 0) { // TODO: Opcja <SUF> } } public void repaintBoard() { setCardView(); board.repaint(); gameInfoPanel.repaint(); playerInfoPanel.repaint(); setPlayerMiniCards(); } private void setDiceListeners() { final CountDownLatch latch = new CountDownLatch(1); firstDice.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { firstDice = (Dice) e.getSource(); diceResult = firstDice.diceThrow() + secondDice.diceThrow(); latch.countDown(); // Zwalnianie CountDownLatch po kliknięciu } }); secondDice.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { secondDice = (Dice) e.getSource(); diceResult = firstDice.diceThrow() + secondDice.diceThrow(); latch.countDown(); // Zwalnianie CountDownLatch po kliknięciu } }); try { latch.await(); // Oczekiwanie na kliknięcie } catch (InterruptedException e) { e.printStackTrace(); } firstDice.removeMouseListener(firstDice.getMouseListeners()[0]); secondDice.removeMouseListener(secondDice.getMouseListeners()[0]); } private void setInformation() { textInfoGame.setText("Ruch: " + currentPlayer.getPlayerColor()); } private void setCardView() { Field temp = board.getField(currentPlayer.getPosition()); Image image = temp.getFieldCard(); cardView.setFieldCard(image); cardView.repaint(); } private void setDefaultCard() { Image image = new ImageIcon("./assets/Cards/defaultCard.png").getImage(); cardView = board.getField(0); cardView.setFieldCard(image); cardView.repaint(); } private void setPlayerMiniCards() { for (int i = 0; i < PLAYER_NUMBER; i++) { ArrayList<Field> fieldsToDisplay = new ArrayList<>(); for (Field owns : players[i].getOwnedFields()) { owns.setFieldCard(owns.getMiniFieldCard()); owns.setPreferredSize(new Dimension(100, 30)); owns.setBounds(0, 0, 100, 30); fieldsToDisplay.add(owns); } for (Field field : fieldsToDisplay) { playersPanels[i].add(field, BorderLayout.SOUTH); } fieldsToDisplay.clear(); } } public void setDiceView(int diceResult, Dice dicePlaceholder) { dicePlaceholder.setIcon(Dice.diceViews[diceResult - 1]); } private void buyField(Player player, Field field) { Object[] options = {"Tak", "Nie"}; int check = JOptionPane.showOptionDialog(null, "Czy chcesz kupić pole " + field.getFieldName() + "?", "Monopoly", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]); if (check == 0) { field.setOwner(player); player.buyField(field); infoPanel("Gratulacje zakupu " + field.getFieldName()); } } private void buildHouses(Field field) { Object[] options = {"Tak", "Nie"}; int check = JOptionPane.showOptionDialog(null, "Czy podnieść poziom na polu " + field.getFieldName() + " za " + HOUSE_PRICE + "?", "Monopoly", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]); if (check == 0) { field.increaseAccommodationLevel(); currentPlayer.decreaseMoney(HOUSE_PRICE); infoPanel("Właśnie podwyższyłeś poziom pola " + field.getFieldType() + " na " + field.getAccommodationLevel()); } } private void setPlayersPanelView() { playerInfoPanel.setPreferredSize(new Dimension(300, 900)); playerInfoPanel.setBounds(1200, 0, 300, 900); playerInfoPanel.setBackground(new Color(227, 139, 27)); titlePlayerPanel.setPreferredSize(new Dimension(200, 20)); titlePlayerPanel.setBackground(new Color(255, 255, 255)); titlePlayerPanel.setForeground(new Color(236, 245, 133)); titlePlayerPanel.setHorizontalAlignment(JLabel.CENTER); titlePlayerPanel.setFont(new Font("Arial", Font.BOLD, 20)); titlePlayerPanel.setText("PLAYERS PANELS:"); playerInfoPanel.add(titlePlayerPanel, BorderLayout.CENTER); int counter = 0; for (JPanel panel : playersPanels) { panel.setPreferredSize(new Dimension(300, 200)); panel.setBackground(new Color(236, 245, 133)); JLabel text = new JLabel(); text.setPreferredSize(new Dimension(300, 15)); text.setForeground(new Color(227, 139, 27)); text.setFont(new Font("Arial", Font.BOLD, 15)); text.setText("Player " + players[counter].getPlayerColor()); text.setHorizontalAlignment(JLabel.CENTER); panel.add(text); playerInfoPanel.add(panel, BorderLayout.SOUTH); counter++; } } private void setWindowParameters() { this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setResizable(false); this.setSize(WINDOW_WIDTH, WINDOW_HEIGHT); this.setLayout(null); this.setVisible(true); this.setTitle("MONOPOLY - WORLD CUP EDITION"); cardView.setPreferredSize(new Dimension(317, 457)); cardView.setHorizontalAlignment(JLabel.CENTER); firstDice.setForeground(Color.white); firstDice.setPreferredSize(new Dimension(90, 90)); firstDice.setBounds(50, 0, 90, 90); secondDice.setForeground(Color.white); secondDice.setPreferredSize(new Dimension(90, 90)); secondDice.setBounds(50, 0, 90, 90); dicePlaceholder.setPreferredSize(new Dimension(200, 100)); dicePlaceholder.setHorizontalAlignment(JLabel.LEFT); dicePlaceholder.add(firstDice); setDiceView(1, firstDice); dicePlaceholderSecond.setPreferredSize(new Dimension(200, 100)); dicePlaceholderSecond.setHorizontalAlignment(JLabel.RIGHT); dicePlaceholderSecond.add(secondDice); setDiceView(4, secondDice); textInfoGame.setPreferredSize(new Dimension(200, 50)); textInfoGame.setBackground(new Color(255, 255, 255)); textInfoGame.setForeground(new Color(241, 3, 3)); textInfoGame.setHorizontalAlignment(JLabel.CENTER); textInfoGame.setFont(new Font("Arial", Font.BOLD, 10)); textInfoGame.setText("Ruch gracza: " + currentPlayer.getPlayerColor()); gameInfoPanel.setPreferredSize(new Dimension(300, 900)); gameInfoPanel.setBackground(Color.YELLOW); gameInfoPanel.setBounds(0, 0, 300, 900); gameInfoPanel.add(textInfoGame, BorderLayout.CENTER); gameInfoPanel.add(cardView); gameInfoPanel.add(dicePlaceholder); gameInfoPanel.add(dicePlaceholderSecond); setPlayersPanelView(); this.add(gameInfoPanel, BorderLayout.WEST); this.add(board, BorderLayout.CENTER); this.add(playerInfoPanel, BorderLayout.EAST); this.repaint(); } }
6682_6
import java.io.File; import java.io.IOException; public class Klasa { public static void main(String[] args) { try { Window frame = new Window(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } } // TODO Auto-generated method stub // System.out.println("Hello world !!!"); // dodawanie liczb /* * double a=4; // deklaracja zmiennej double b=5; int c=0; * System.out.println(a+b); * * // dzielenie z instrukcja warunkowa if (b!=0) * System.out.println(a/b); else * System.out.println("Nie dzielimy przez zero!"); * * System.out.println(a*b); System.out.println(c+b); */ // Wprowadzanie liczb przez okna dialogowe /* * String txt1; //deklaracja zmiennej tekstowej txt1 = * JOptionPane.showInputDialog("Wprowadz pierwsza liczbe"); * * String txt2; //deklaracja zmiennej tekstowej txt2 = * JOptionPane.showInputDialog("Wprowadz druga liczbe"); * * System.out.println(txt1 + txt2); // ??? * * * * // Konwersja tekstu na liczbe double liczba1 = * Double.parseDouble(txt1); int liczba2 = Integer.parseInt(txt2); * * System.out.println(liczba1 + liczba2); System.out.println(silnia(3)); */ //Inputter inp = new Inputter(); //int liczbaWierszy = inp.GetInt("Ile wierszy trojkata?"); //TrojkatNewtona trojkat = new TrojkatNewtona(liczbaWierszy); //TrojkatPascala trojkat = new TrojkatPascala(); //trojkat.print(); //Arg2 argumenty = new Arg2(args); /*Tablica tab = new Tablica(); tab.Randomizuj(Integer.parseInt(args[0]), Integer.parseInt(args[1]));*/
KKozlowski/Komponentowe2015
src/Klasa.java
605
//int liczbaWierszy = inp.GetInt("Ile wierszy trojkata?");
line_comment
pl
import java.io.File; import java.io.IOException; public class Klasa { public static void main(String[] args) { try { Window frame = new Window(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } } // TODO Auto-generated method stub // System.out.println("Hello world !!!"); // dodawanie liczb /* * double a=4; // deklaracja zmiennej double b=5; int c=0; * System.out.println(a+b); * * // dzielenie z instrukcja warunkowa if (b!=0) * System.out.println(a/b); else * System.out.println("Nie dzielimy przez zero!"); * * System.out.println(a*b); System.out.println(c+b); */ // Wprowadzanie liczb przez okna dialogowe /* * String txt1; //deklaracja zmiennej tekstowej txt1 = * JOptionPane.showInputDialog("Wprowadz pierwsza liczbe"); * * String txt2; //deklaracja zmiennej tekstowej txt2 = * JOptionPane.showInputDialog("Wprowadz druga liczbe"); * * System.out.println(txt1 + txt2); // ??? * * * * // Konwersja tekstu na liczbe double liczba1 = * Double.parseDouble(txt1); int liczba2 = Integer.parseInt(txt2); * * System.out.println(liczba1 + liczba2); System.out.println(silnia(3)); */ //Inputter inp = new Inputter(); //int liczbaWierszy <SUF> //TrojkatNewtona trojkat = new TrojkatNewtona(liczbaWierszy); //TrojkatPascala trojkat = new TrojkatPascala(); //trojkat.print(); //Arg2 argumenty = new Arg2(args); /*Tablica tab = new Tablica(); tab.Randomizuj(Integer.parseInt(args[0]), Integer.parseInt(args[1]));*/
3629_0
package main; public class Main { public static void main(String[] args) { // Komentarz jednolinijkowy /* * Komentarz * Wielolinijkowy * */ // Proste wypisanie System.out.println("Hello World"); // Typy proste zmiennych // Deklaracje int i; char c; double d; float f; boolean b; byte a; // Inicjalizacje i = 10; c = 'a'; // char jest również typem liczbowym! - możemy do niego dodawać i odejmować np int c = 15; d = 2.5; f = 2.5f; b = true; a = 100; // wypisywanie zmiennych - odwołujemy się po nadanej im nazwie System.out.println(i); // modulo - reszta z dzielenia System.out.println(13 % 2); int z; double y; // Prosty prosty program dodawjący /* System.out.println("Wprowadz pierwsza liczbe: "); Scanner scanner = new Scanner(System.in); z = scanner.nextInt(); System.out.println("Wprowadz druga liczbe: "); y = scanner.nextDouble(); int wynik = (int) (z + y); double wynikD = z + y; */ // int wynik2 = Integer.parseInt(wynikD); // TABLICE // int tablica2[]; // Dwa sposoby tworzenia tablic int[] tablica1 = new int[10]; int[] tablica3 = {1, 2, 3, 4, 5, 6}; // Przypisywanie wartości w tablicy tablica1[0] = 5; // tablice zaczynamy od indeksu 0! Ostatni znajduje się na length-1 tablica1[1] = 10; System.out.println(tablica1[0]); // PĘTLE // for z użyciem wartości długości tablicy for (int x = 0; x < tablica3.length; x++) { System.out.println(tablica3[x]); } System.out.println("=============================================="); // foreach - wypisujemy każdy element for (int element : tablica3) { System.out.println(element); } System.out.println("=============================================="); // While - potrzebna wartośc do zliczania iteracji, niewygodne przy wypisywaniu elementów int rozmiar = 0; while (rozmiar < tablica3.length) { System.out.println(tablica3[rozmiar]); rozmiar++; } // Do While - zawsze wykonamy przynajmniej jeden "obrót" pętli. int rozmiar2 = 0; do { System.out.println(tablica3[rozmiar2]); rozmiar2++; } while (rozmiar2 < tablica3.length); // Instrukcje warunkowe int warunek = 10; // if sprawdzamy zawsze if (warunek == 10) { System.out.println("Zgadza sie"); } else if (warunek == 5) { // else if sprawdzamy tylko jeśli nie spełnione są wcześniejsze warunki if/else if System.out.println("Nie zgadza sie"); } else { // else wykonywane jest tylko jeśli nie spełniony jest żadny warunek if/else if System.out.println("Tez blad"); } System.out.println("==============Switch========================="); int wybor = 10; // Jeśli nie mamy breaków wykonujemy wszystkie linijki kodu poniżej danego break'a. switch (wybor) { case 5: System.out.println(5); break; case 10: System.out.println(10); break; case 15: System.out.println(15); break; default: System.out.println("nic"); } // operator trynarny, działa jak if // to so samo co: String wyraz; wyraz = (5 > 1) ? "tak" : "nie"; System.out.println(wyraz); // zapis tego samego za pomocą ifa String wyraz; if (5 > 1) { wyraz = "tak"; } else { wyraz = "nie"; } } }
KNJPJATK/2017_Wtorek_Open
Zajecia1/Main.java
1,487
/* * Komentarz * Wielolinijkowy * */
block_comment
pl
package main; public class Main { public static void main(String[] args) { // Komentarz jednolinijkowy /* * Komentarz <SUF>*/ // Proste wypisanie System.out.println("Hello World"); // Typy proste zmiennych // Deklaracje int i; char c; double d; float f; boolean b; byte a; // Inicjalizacje i = 10; c = 'a'; // char jest również typem liczbowym! - możemy do niego dodawać i odejmować np int c = 15; d = 2.5; f = 2.5f; b = true; a = 100; // wypisywanie zmiennych - odwołujemy się po nadanej im nazwie System.out.println(i); // modulo - reszta z dzielenia System.out.println(13 % 2); int z; double y; // Prosty prosty program dodawjący /* System.out.println("Wprowadz pierwsza liczbe: "); Scanner scanner = new Scanner(System.in); z = scanner.nextInt(); System.out.println("Wprowadz druga liczbe: "); y = scanner.nextDouble(); int wynik = (int) (z + y); double wynikD = z + y; */ // int wynik2 = Integer.parseInt(wynikD); // TABLICE // int tablica2[]; // Dwa sposoby tworzenia tablic int[] tablica1 = new int[10]; int[] tablica3 = {1, 2, 3, 4, 5, 6}; // Przypisywanie wartości w tablicy tablica1[0] = 5; // tablice zaczynamy od indeksu 0! Ostatni znajduje się na length-1 tablica1[1] = 10; System.out.println(tablica1[0]); // PĘTLE // for z użyciem wartości długości tablicy for (int x = 0; x < tablica3.length; x++) { System.out.println(tablica3[x]); } System.out.println("=============================================="); // foreach - wypisujemy każdy element for (int element : tablica3) { System.out.println(element); } System.out.println("=============================================="); // While - potrzebna wartośc do zliczania iteracji, niewygodne przy wypisywaniu elementów int rozmiar = 0; while (rozmiar < tablica3.length) { System.out.println(tablica3[rozmiar]); rozmiar++; } // Do While - zawsze wykonamy przynajmniej jeden "obrót" pętli. int rozmiar2 = 0; do { System.out.println(tablica3[rozmiar2]); rozmiar2++; } while (rozmiar2 < tablica3.length); // Instrukcje warunkowe int warunek = 10; // if sprawdzamy zawsze if (warunek == 10) { System.out.println("Zgadza sie"); } else if (warunek == 5) { // else if sprawdzamy tylko jeśli nie spełnione są wcześniejsze warunki if/else if System.out.println("Nie zgadza sie"); } else { // else wykonywane jest tylko jeśli nie spełniony jest żadny warunek if/else if System.out.println("Tez blad"); } System.out.println("==============Switch========================="); int wybor = 10; // Jeśli nie mamy breaków wykonujemy wszystkie linijki kodu poniżej danego break'a. switch (wybor) { case 5: System.out.println(5); break; case 10: System.out.println(10); break; case 15: System.out.println(15); break; default: System.out.println("nic"); } // operator trynarny, działa jak if // to so samo co: String wyraz; wyraz = (5 > 1) ? "tak" : "nie"; System.out.println(wyraz); // zapis tego samego za pomocą ifa String wyraz; if (5 > 1) { wyraz = "tak"; } else { wyraz = "nie"; } } }
3824_18
/** * ZADANKA PO SPOTKANIU 3! * * Zadanka robimy po kolei! * * Zrobimy zadanie 1, odpalamy kod, jak jest dobrze, to dostaniemy komunikat o tym ze jest dobrze. * Jak nie, to poprawimy i probujemy jeszcze raz. * * W razie pytan, uwag, zastrzezen i zali -> tomasz@wojda.net albo andrew.torski@gmail.com * Albo na grupie fejsbuniowej Grupy Podstawowej zagadujcie Tomasz Wojda albo mnie(Andrew Torski) */ public class Zadania3 { /** * Zadanko 1 - na rozgrzewke! * * Sprwadźmy czy podana macierz jest kwadratowa, tzn. czy ma tyle samo wieszy i kolumn. * * Pozniej to zadanie bedzie potrzebne, wiec je zrob! :)) */ public static boolean czyKwadratowa(char[][] macierz){ boolean czyKwadratowa = false; // jakis wiersz z macierzy moze wyciagnac np tak: // char[] wiersz = macierz[0]; // to jest akurat pierwszy wiersz int liczbaWierszy = macierz.length; int liczbaKolumn = macierz[0].length; // operator logiczny // VV czyKwadratowa = (liczbaWierszy == liczbaKolumn); // wstaw true do czyKwadratowa jezeli jest rzeczywiscie kwadratowa return czyKwadratowa; } /** * Zadanko 2 - dalej sie grzejemy! * * Sprawdzamy czy podane macierze maja tyle samo wierszy i kolumn */ public static boolean czyMacierzeMajaTyleSamoWierszyIKolumn(int[][] pierwszaMacierz, int[][] drugaMacierz){ boolean czyMajaTyleSamoWierszyIKolumn = false; int liczbaWierszyWMacierzyPierwszej = pierwszaMacierz.length, liczbaKolumnWMacierzyPierwszej = pierwszaMacierz[0].length; int liczbaWierszyWMacierzyDrugiej = drugaMacierz.length, liczbaKolumnWMacierzyDrugiej = drugaMacierz[0].length; czyMajaTyleSamoWierszyIKolumn = (liczbaWierszyWMacierzyPierwszej == liczbaWierszyWMacierzyDrugiej) && (liczbaKolumnWMacierzyPierwszej == liczbaKolumnWMacierzyDrugiej); return czyMajaTyleSamoWierszyIKolumn; } /** * Zadanko 3 - juz coś róbmy! * Bierzemy macierz na wejsciu i dodajemy wszystkie jej elementy po kolei jak leci i zwracamy to co otrzymamy. */ public static int zwrocDodaneElementyMacierzy(int[][] macierzLiczb){ int sumaElementow = 0; // jakies for petle pewnie... i cos z ta zmienna sumaElementow musimy robic... for (int i = 0; i < macierzLiczb.length; i++) { // wiersze for (int j = 0; j < macierzLiczb[i].length; j++) { int wartoscZMacierzy = macierzLiczb[i][j]; sumaElementow += macierzLiczb[i][j]; } } return sumaElementow; } /** * Zadanko 4 - działamy!. * * Bierzemy dwie macierze i dodajemy ich rownolezace komorki do siebie i wstawiamy je do macierzy wynikowej * tzn.: bierzemy komorke z wiersza 0 i kolumny 0 w pierwszej macierzy i bierzemy komorke z wiersza 0 i kolumny 0 * drugiej macierzy i dodajemy ich wartosci do siebie. * * np. * 1 2 3 9 8 7 10 10 10 * 4 5 6 + 6 5 4 = 10 10 10 * 7 8 9 3 2 1 10 10 10 * * Uwaga! Fajnie by bylo gdyby te macierze mialy po tyle samo wierszy i kolumn... * */ public static int[][] dodajDoSiebieMacierze(int [][] pierwszaMacierz, int [][] drugaMacierz){ // Tu tylko sprawdzamy czy ich ilosc wierszy i kolumn sie zgadza... // UWAGA uzywamy tu funkcji z zadania 2!!! if (!czyMacierzeMajaTyleSamoWierszyIKolumn(pierwszaMacierz, drugaMacierz)){ System.err.println("EJ! Ale w zadaniu 4 te macierze mialy miec tyle samo wierszy i kolumn :/ >.<"); return null; } int iloscWierszyMacierzyWynikowej = pierwszaMacierz.length; //Co tu bedzie? :o int iloscKolumnMacierzyWynikowej = drugaMacierz[0].length; //A tu?? int [][] macierzWynikowa = new int[iloscWierszyMacierzyWynikowej][iloscKolumnMacierzyWynikowej]; // pewnie jakaś pętla... a moze dwie nawet... pewnie tez cos z macierzWynikowa trzeba robic... nie? for (int i = 0; i < iloscWierszyMacierzyWynikowej; i++) { for (int j = 0; j < iloscKolumnMacierzyWynikowej; j++) { int wartoscZPierwszej = pierwszaMacierz[i][j], wartoscZDrugiej = drugaMacierz[i][j]; macierzWynikowa[i][j] = wartoscZPierwszej + wartoscZDrugiej; } } // jak juz wszystko wyliczylismy to zwracamy nasza macierz wynikowa do swiata zewnetrznego! paaa! return macierzWynikowa; // na zawsze pozostaniesz w naszych sercach :'( } /** * Zadanko 5! - dalej dalej! * * Mamy macierz kwadratową(ma tyle samo wiersz co i kolumn) znaków na przykłąd taką: * * a b c * e f g * h i j * * i teraz chcemy aby jej przekątne wypelnic jakimś znakiem. Na przykład: 'o' * * Ma wyglądać tak: * * o b o * e o g * o i o * * macierzZnakow[i][macierzZnakow.length-1-i] = znakDoWypelnienia; * * j = macierzZnakow.length-1-i * * i 0..1..2 * j 2..1..0 * * 00 01 02 * 10 11 12 * 20 21 22 * * * Mały hint: * * Legenda * xy - wspolrzedne komorki, x - nr wiersza, y - nr kolumny * * Jak masz problemy, to sprobuj sobie rozpisać na kartce albo tu w komentarzach jakie sa kolejne * wspolrzedne kazdej komorki w macierzy i przestudiuj to! Moze zauwazysz cos ciekawego :) */ public static void wypelnijPrzekatneMacierzyZnakami(char[][] macierzZnakow, char znakDoWypelnienia){ // Tylko uwazaj! Uzywamy tu funkcji z zadania 1! boolean czyKwadratowa = czyKwadratowa(macierzZnakow); // NIE-czyKwadratowa if (!czyKwadratowa){ System.err.println("EJ! Ale ta macierz znakow w zadaniu 5 miala byc kwadratowa... Nie bawimy sie tak..."); // jezeli nie jest kwadratowa, to instrukcja return; zaprzestaniemy wykonywac cokolwiek w niej... return; } System.out.println("Macierz przed wypelnieniem"); printujMacierz(macierzZnakow); // Najprosciej: // Dla przekątnej z lewego gornego rogu do dolnego prawego - dwie zagniezdzone petle for i sprawdzamy czy akurat // jestesmy na komorkach przekatnej. // DWIE PETLE!!! /*//przekatna z lewego gornego rogu do prawego dolnego for (int i = 0; i < macierzZnakow.length; i++) { for (int j = 0; j < macierzZnakow[i].length; j++) { if (i == j){ macierzZnakow[i][j] = znakDoWypelnienia; } } } for (int i = 0; i < macierzZnakow.length; i++) { for (int j = macierzZnakow[i].length - 1; j >= 0; j--) { if ((i + j) == macierzZnakow.length - 1){ macierzZnakow[i][j] = znakDoWypelnienia; } } }*/ // dwie petle - bez zagniedzen /*for (int i = 0; i < macierzZnakow.length; i++) { macierzZnakow[i][i] = znakDoWypelnienia; } for (int i = 0; i < macierzZnakow.length; i++) { macierzZnakow[i][macierzZnakow.length-1-i] = znakDoWypelnienia; }*/ for (int i = 0; i < macierzZnakow.length; i++) { macierzZnakow[i][i] = znakDoWypelnienia; macierzZnakow[i][macierzZnakow.length-1-i] = znakDoWypelnienia; } // Ambitniej(i lepiej tak naprawde) tylko jedną petla na przekątną! Jest to bardzo proste i o wiele wydajniejsze. // Dla drugiej przekatnej z prawego gornego do lewego dolnego tak samo. // Super ambitniej bedzie uzyc tylko jednej pętli for dla dwoch przekatnych. To juz jest Mt. Everest wydajnosci // :) System.out.println("Macierz po wypelnieniu przekatnych"); printujMacierz(macierzZnakow); } /** * Zadanie 6! Uff! Ale to było dobre! * * Ogólnie sprawa ma się tak: * mamy takie macierze znakow * * macierz pierwsza: * J A V * J E S * O K T * * macierz druga: * A * T * J * * I chcemy złączyć te macierze do jednej wspolnej tak aby wygladała ona o tak: * * J A V A * J E S T * O K E J */ public static char [][] zlaczMacierzeZnakow(char[][] pierwszaMacierzZnakow, char[][] drugaMacierzZnakow){ // jezeli maja inna liczbe wierszy to nic z tego, nie zdzialamy nic wiecej... if (pierwszaMacierzZnakow.length != drugaMacierzZnakow.length){ return new char[0][0]; // zwracamy smutna macierz zero na zero :( } int iloscKolumnWMacierzWynikowej = pierwszaMacierzZnakow[0].length + drugaMacierzZnakow[0].length; // O TO! O to trzeba wyliczyc jakos, nie? int iloscWierszyWMacierzyWynikowej = pierwszaMacierzZnakow.length; // To tez chyba. char[][] macierzWynikowa = new char[iloscWierszyWMacierzyWynikowej][iloscKolumnWMacierzWynikowej]; // Wg mnie beda dwie podwojne petle for! // Jedna aby przekopiowac znaki z pierwszej for (int i = 0; i < pierwszaMacierzZnakow.length; i++) { for (int j = 0; j < pierwszaMacierzZnakow[i].length; j++) { macierzWynikowa[i][j] = pierwszaMacierzZnakow[i][j]; } } /* wynikowa v J A V J E S O K E */ for (int i = 0; i < drugaMacierzZnakow.length; i++) { for (int j = 0; j < drugaMacierzZnakow[i].length; j++) { macierzWynikowa[i][pierwszaMacierzZnakow[i].length+j] = drugaMacierzZnakow[i][j]; } } return macierzWynikowa; } /* *************************** METODA MAIN ********************* */ public static void main(String[] arguments){ /* ********************ZADANIE 1******************** */ System.out.println("----ZADANIE 1----"); char [][] macierzDoZadania1Kwadratowa = new char[2][2]; char [][] macierzDoZadania1Dzwina = new char[1][100]; boolean czyKwadratowaJestKwadratowa = czyKwadratowa(macierzDoZadania1Kwadratowa); boolean czyDziwnaJestKwadratowa = czyKwadratowa(macierzDoZadania1Dzwina); if (czyKwadratowaJestKwadratowa == false){ System.err.println("Kwadratowa wg Ciebie nie jest kwadratowa..."); return; } if (czyDziwnaJestKwadratowa == true){ System.err.println("Dziwna wg Ciebie jest kwadratowa..."); return; } System.out.println("Zadanie 1 jest dobrze zrobione!"); /* ********************ZADANIE 2******************** */ // pierwsza i druga macierz maja tyle samo wierszy i kolumn int[][] pierwszaMacierzDoZadania2 = new int[20][40]; int[][] drugaMacierzDoZadania2 = new int[20][40]; // natomiast trzecia macierz ma odwrotna liczbe wierwszy i kolumn jak dwie pierwsze int[][] trzeciaMacierzDoZadania2 = new int[40][20]; boolean czyPierwszaIDrugaMajaTyleSamoWierszyIKolumn = czyMacierzeMajaTyleSamoWierszyIKolumn(pierwszaMacierzDoZadania2, drugaMacierzDoZadania2); boolean czyPierwszaITrzeciaMajaTyleSamoWierszyIKolumn = czyMacierzeMajaTyleSamoWierszyIKolumn(pierwszaMacierzDoZadania2, trzeciaMacierzDoZadania2); if (czyPierwszaIDrugaMajaTyleSamoWierszyIKolumn == false){ System.err.println("Oops, najwyrazniej pierwsza i druga nie maja tyle samo wierszy i kolumn..."); return; } if (czyPierwszaITrzeciaMajaTyleSamoWierszyIKolumn == true){ System.err.println("Oops, najwyrazniej pierwsza i trzecia maja tyle samo wierszy i kolumn..."); return; } System.out.println("Zadanie 2 jest dobrze zrobione!"); /* ********************ZADANIE 3******************** */ int[][] macierzDoZadania3 = { {1, 1, 1}, {2, 2, 2}, {3, 3, 3}}; int sumaElementow = 18; int ileMetodaWyliczyla = zwrocDodaneElementyMacierzy(macierzDoZadania3); if (ileMetodaWyliczyla != sumaElementow){ System.err.println("OJ! Coś w zadaniu 3 źle posumowało :S"); return; } System.out.println("Zadanie 3 jest dobrze zrobione!"); /* ********************ZADANIE 4******************** */ int [][] pierwszaMacierzDoZadania4 = {{1, 2, 3}, {4,5,6}, {7,8,9}}; int [][] drugaMacierzDoZadania4 = {{9,8,7}, {6, 5, 4}, {3, 2, 1}}; int [][] jakaMacierzWinnaByc = {{10, 10, 10}, {10, 10, 10}, {10, 10, 10}}; int [][] coNamWyszloZZadania4 = dodajDoSiebieMacierze(pierwszaMacierzDoZadania4, drugaMacierzDoZadania4); boolean czySaRowneMacierze = CzyRowne(jakaMacierzWinnaByc, coNamWyszloZZadania4); if (czySaRowneMacierze == false){ System.out.println("Te macierze w zadaniu 4 miały być równe..."); return; } System.out.println("Zadanie 4 jest mega extra dobrze zrobione!"); /* ********************ZADANIE 5******************** */ char [][] macierzDoZadania5 = { {'a','b','c'}, {'e', 'f', 'g'}, {'h', 'i', 'j'}}; char znakDoPrzekątnych = 'o'; System.out.println("Już musisz sam sobie porównać czy dobrze wypelnia!"); wypelnijPrzekatneMacierzyZnakami(macierzDoZadania5, znakDoPrzekątnych); System.out.println("Zadanie 5 mam nadzieje, ze dobrze jest zrobione!"); /* ********************ZADANIE 6******************** */ char [][] macierzJA_JE_OK = {{'J', 'A'}, {'J', 'E'}, {'O', 'K'}}; char [][] macierzVA_ST_EJ = {{'V', 'A'}, {'S', 'T'}, {'E', 'J'}}; char[][] jakaMacierzMaByc = { {'J', 'A', 'V', 'A'}, {'J', 'E', 'S', 'T'}, {'O', 'K', 'E', 'J'}}; char [][] otrzymanaZMetody = zlaczMacierzeZnakow(macierzJA_JE_OK, macierzVA_ST_EJ); boolean czy_macierzJakaMaByc_otrzymanaZMetody_saRowne = CzyRowne(jakaMacierzMaByc, otrzymanaZMetody); if (czy_macierzJakaMaByc_otrzymanaZMetody_saRowne == false){ System.err.println("Oj! Coś źle jest w zadaniu 6! chyba!"); return; } System.out.println("Zadanie 6 jest elegancko zrobione.!"); System.out.println("Brawo! :))"); } /* *************************** METODA MAIN ********************* */ private static boolean CzyRowne(char [][] pierwsza, char[][] druga){ if (pierwsza.length != druga.length && pierwsza[0].length != druga[0].length){ return false; } for (int i = 0; i < pierwsza.length; i++) { for (int j = 0; j < pierwsza[i].length; j++) { if (pierwsza[i][j] != druga[i][j]){ return false; } } } return true; } private static boolean CzyRowne(int [][] pierwsza, int[][] druga){ if (!czyMacierzeMajaTyleSamoWierszyIKolumn(pierwsza, druga)){ return false; } for (int i = 0; i < pierwsza.length; i++) { for (int j = 0; j < pierwsza[i].length; j++) { if (pierwsza[i][j] != druga[i][j]){ return false; } } } return true; } /** * Takie cos do drukowania macierzy znakow... */ private static void printujMacierz(char[][] macierzZnakow){ for (int i = 0; i < macierzZnakow.length; i++) { char [] wierszZeZnakami = macierzZnakow[i]; for (int j = 0; j < wierszZeZnakami.length; j++) { System.out.print(" " + wierszZeZnakami[j]); } System.out.println(); } } /** * Takie cos do drukowania macierzy liczb... */ private static void printujMacierz(int [][] macierzLiczb){ for (int i = 0; i < macierzLiczb.length; i++) { int [] wierszZLiczbami = macierzLiczb[i]; for (int j = 0; j < wierszZLiczbami.length; j++) { System.out.print(" " + wierszZLiczbami[j]); } System.out.println(); } } }
KNJPJATK/GrupaPodstawowa
Spotkanie 3/src/Zadania3.java
6,353
// Dla przekątnej z lewego gornego rogu do dolnego prawego - dwie zagniezdzone petle for i sprawdzamy czy akurat
line_comment
pl
/** * ZADANKA PO SPOTKANIU 3! * * Zadanka robimy po kolei! * * Zrobimy zadanie 1, odpalamy kod, jak jest dobrze, to dostaniemy komunikat o tym ze jest dobrze. * Jak nie, to poprawimy i probujemy jeszcze raz. * * W razie pytan, uwag, zastrzezen i zali -> tomasz@wojda.net albo andrew.torski@gmail.com * Albo na grupie fejsbuniowej Grupy Podstawowej zagadujcie Tomasz Wojda albo mnie(Andrew Torski) */ public class Zadania3 { /** * Zadanko 1 - na rozgrzewke! * * Sprwadźmy czy podana macierz jest kwadratowa, tzn. czy ma tyle samo wieszy i kolumn. * * Pozniej to zadanie bedzie potrzebne, wiec je zrob! :)) */ public static boolean czyKwadratowa(char[][] macierz){ boolean czyKwadratowa = false; // jakis wiersz z macierzy moze wyciagnac np tak: // char[] wiersz = macierz[0]; // to jest akurat pierwszy wiersz int liczbaWierszy = macierz.length; int liczbaKolumn = macierz[0].length; // operator logiczny // VV czyKwadratowa = (liczbaWierszy == liczbaKolumn); // wstaw true do czyKwadratowa jezeli jest rzeczywiscie kwadratowa return czyKwadratowa; } /** * Zadanko 2 - dalej sie grzejemy! * * Sprawdzamy czy podane macierze maja tyle samo wierszy i kolumn */ public static boolean czyMacierzeMajaTyleSamoWierszyIKolumn(int[][] pierwszaMacierz, int[][] drugaMacierz){ boolean czyMajaTyleSamoWierszyIKolumn = false; int liczbaWierszyWMacierzyPierwszej = pierwszaMacierz.length, liczbaKolumnWMacierzyPierwszej = pierwszaMacierz[0].length; int liczbaWierszyWMacierzyDrugiej = drugaMacierz.length, liczbaKolumnWMacierzyDrugiej = drugaMacierz[0].length; czyMajaTyleSamoWierszyIKolumn = (liczbaWierszyWMacierzyPierwszej == liczbaWierszyWMacierzyDrugiej) && (liczbaKolumnWMacierzyPierwszej == liczbaKolumnWMacierzyDrugiej); return czyMajaTyleSamoWierszyIKolumn; } /** * Zadanko 3 - juz coś róbmy! * Bierzemy macierz na wejsciu i dodajemy wszystkie jej elementy po kolei jak leci i zwracamy to co otrzymamy. */ public static int zwrocDodaneElementyMacierzy(int[][] macierzLiczb){ int sumaElementow = 0; // jakies for petle pewnie... i cos z ta zmienna sumaElementow musimy robic... for (int i = 0; i < macierzLiczb.length; i++) { // wiersze for (int j = 0; j < macierzLiczb[i].length; j++) { int wartoscZMacierzy = macierzLiczb[i][j]; sumaElementow += macierzLiczb[i][j]; } } return sumaElementow; } /** * Zadanko 4 - działamy!. * * Bierzemy dwie macierze i dodajemy ich rownolezace komorki do siebie i wstawiamy je do macierzy wynikowej * tzn.: bierzemy komorke z wiersza 0 i kolumny 0 w pierwszej macierzy i bierzemy komorke z wiersza 0 i kolumny 0 * drugiej macierzy i dodajemy ich wartosci do siebie. * * np. * 1 2 3 9 8 7 10 10 10 * 4 5 6 + 6 5 4 = 10 10 10 * 7 8 9 3 2 1 10 10 10 * * Uwaga! Fajnie by bylo gdyby te macierze mialy po tyle samo wierszy i kolumn... * */ public static int[][] dodajDoSiebieMacierze(int [][] pierwszaMacierz, int [][] drugaMacierz){ // Tu tylko sprawdzamy czy ich ilosc wierszy i kolumn sie zgadza... // UWAGA uzywamy tu funkcji z zadania 2!!! if (!czyMacierzeMajaTyleSamoWierszyIKolumn(pierwszaMacierz, drugaMacierz)){ System.err.println("EJ! Ale w zadaniu 4 te macierze mialy miec tyle samo wierszy i kolumn :/ >.<"); return null; } int iloscWierszyMacierzyWynikowej = pierwszaMacierz.length; //Co tu bedzie? :o int iloscKolumnMacierzyWynikowej = drugaMacierz[0].length; //A tu?? int [][] macierzWynikowa = new int[iloscWierszyMacierzyWynikowej][iloscKolumnMacierzyWynikowej]; // pewnie jakaś pętla... a moze dwie nawet... pewnie tez cos z macierzWynikowa trzeba robic... nie? for (int i = 0; i < iloscWierszyMacierzyWynikowej; i++) { for (int j = 0; j < iloscKolumnMacierzyWynikowej; j++) { int wartoscZPierwszej = pierwszaMacierz[i][j], wartoscZDrugiej = drugaMacierz[i][j]; macierzWynikowa[i][j] = wartoscZPierwszej + wartoscZDrugiej; } } // jak juz wszystko wyliczylismy to zwracamy nasza macierz wynikowa do swiata zewnetrznego! paaa! return macierzWynikowa; // na zawsze pozostaniesz w naszych sercach :'( } /** * Zadanko 5! - dalej dalej! * * Mamy macierz kwadratową(ma tyle samo wiersz co i kolumn) znaków na przykłąd taką: * * a b c * e f g * h i j * * i teraz chcemy aby jej przekątne wypelnic jakimś znakiem. Na przykład: 'o' * * Ma wyglądać tak: * * o b o * e o g * o i o * * macierzZnakow[i][macierzZnakow.length-1-i] = znakDoWypelnienia; * * j = macierzZnakow.length-1-i * * i 0..1..2 * j 2..1..0 * * 00 01 02 * 10 11 12 * 20 21 22 * * * Mały hint: * * Legenda * xy - wspolrzedne komorki, x - nr wiersza, y - nr kolumny * * Jak masz problemy, to sprobuj sobie rozpisać na kartce albo tu w komentarzach jakie sa kolejne * wspolrzedne kazdej komorki w macierzy i przestudiuj to! Moze zauwazysz cos ciekawego :) */ public static void wypelnijPrzekatneMacierzyZnakami(char[][] macierzZnakow, char znakDoWypelnienia){ // Tylko uwazaj! Uzywamy tu funkcji z zadania 1! boolean czyKwadratowa = czyKwadratowa(macierzZnakow); // NIE-czyKwadratowa if (!czyKwadratowa){ System.err.println("EJ! Ale ta macierz znakow w zadaniu 5 miala byc kwadratowa... Nie bawimy sie tak..."); // jezeli nie jest kwadratowa, to instrukcja return; zaprzestaniemy wykonywac cokolwiek w niej... return; } System.out.println("Macierz przed wypelnieniem"); printujMacierz(macierzZnakow); // Najprosciej: // Dla przekątnej <SUF> // jestesmy na komorkach przekatnej. // DWIE PETLE!!! /*//przekatna z lewego gornego rogu do prawego dolnego for (int i = 0; i < macierzZnakow.length; i++) { for (int j = 0; j < macierzZnakow[i].length; j++) { if (i == j){ macierzZnakow[i][j] = znakDoWypelnienia; } } } for (int i = 0; i < macierzZnakow.length; i++) { for (int j = macierzZnakow[i].length - 1; j >= 0; j--) { if ((i + j) == macierzZnakow.length - 1){ macierzZnakow[i][j] = znakDoWypelnienia; } } }*/ // dwie petle - bez zagniedzen /*for (int i = 0; i < macierzZnakow.length; i++) { macierzZnakow[i][i] = znakDoWypelnienia; } for (int i = 0; i < macierzZnakow.length; i++) { macierzZnakow[i][macierzZnakow.length-1-i] = znakDoWypelnienia; }*/ for (int i = 0; i < macierzZnakow.length; i++) { macierzZnakow[i][i] = znakDoWypelnienia; macierzZnakow[i][macierzZnakow.length-1-i] = znakDoWypelnienia; } // Ambitniej(i lepiej tak naprawde) tylko jedną petla na przekątną! Jest to bardzo proste i o wiele wydajniejsze. // Dla drugiej przekatnej z prawego gornego do lewego dolnego tak samo. // Super ambitniej bedzie uzyc tylko jednej pętli for dla dwoch przekatnych. To juz jest Mt. Everest wydajnosci // :) System.out.println("Macierz po wypelnieniu przekatnych"); printujMacierz(macierzZnakow); } /** * Zadanie 6! Uff! Ale to było dobre! * * Ogólnie sprawa ma się tak: * mamy takie macierze znakow * * macierz pierwsza: * J A V * J E S * O K T * * macierz druga: * A * T * J * * I chcemy złączyć te macierze do jednej wspolnej tak aby wygladała ona o tak: * * J A V A * J E S T * O K E J */ public static char [][] zlaczMacierzeZnakow(char[][] pierwszaMacierzZnakow, char[][] drugaMacierzZnakow){ // jezeli maja inna liczbe wierszy to nic z tego, nie zdzialamy nic wiecej... if (pierwszaMacierzZnakow.length != drugaMacierzZnakow.length){ return new char[0][0]; // zwracamy smutna macierz zero na zero :( } int iloscKolumnWMacierzWynikowej = pierwszaMacierzZnakow[0].length + drugaMacierzZnakow[0].length; // O TO! O to trzeba wyliczyc jakos, nie? int iloscWierszyWMacierzyWynikowej = pierwszaMacierzZnakow.length; // To tez chyba. char[][] macierzWynikowa = new char[iloscWierszyWMacierzyWynikowej][iloscKolumnWMacierzWynikowej]; // Wg mnie beda dwie podwojne petle for! // Jedna aby przekopiowac znaki z pierwszej for (int i = 0; i < pierwszaMacierzZnakow.length; i++) { for (int j = 0; j < pierwszaMacierzZnakow[i].length; j++) { macierzWynikowa[i][j] = pierwszaMacierzZnakow[i][j]; } } /* wynikowa v J A V J E S O K E */ for (int i = 0; i < drugaMacierzZnakow.length; i++) { for (int j = 0; j < drugaMacierzZnakow[i].length; j++) { macierzWynikowa[i][pierwszaMacierzZnakow[i].length+j] = drugaMacierzZnakow[i][j]; } } return macierzWynikowa; } /* *************************** METODA MAIN ********************* */ public static void main(String[] arguments){ /* ********************ZADANIE 1******************** */ System.out.println("----ZADANIE 1----"); char [][] macierzDoZadania1Kwadratowa = new char[2][2]; char [][] macierzDoZadania1Dzwina = new char[1][100]; boolean czyKwadratowaJestKwadratowa = czyKwadratowa(macierzDoZadania1Kwadratowa); boolean czyDziwnaJestKwadratowa = czyKwadratowa(macierzDoZadania1Dzwina); if (czyKwadratowaJestKwadratowa == false){ System.err.println("Kwadratowa wg Ciebie nie jest kwadratowa..."); return; } if (czyDziwnaJestKwadratowa == true){ System.err.println("Dziwna wg Ciebie jest kwadratowa..."); return; } System.out.println("Zadanie 1 jest dobrze zrobione!"); /* ********************ZADANIE 2******************** */ // pierwsza i druga macierz maja tyle samo wierszy i kolumn int[][] pierwszaMacierzDoZadania2 = new int[20][40]; int[][] drugaMacierzDoZadania2 = new int[20][40]; // natomiast trzecia macierz ma odwrotna liczbe wierwszy i kolumn jak dwie pierwsze int[][] trzeciaMacierzDoZadania2 = new int[40][20]; boolean czyPierwszaIDrugaMajaTyleSamoWierszyIKolumn = czyMacierzeMajaTyleSamoWierszyIKolumn(pierwszaMacierzDoZadania2, drugaMacierzDoZadania2); boolean czyPierwszaITrzeciaMajaTyleSamoWierszyIKolumn = czyMacierzeMajaTyleSamoWierszyIKolumn(pierwszaMacierzDoZadania2, trzeciaMacierzDoZadania2); if (czyPierwszaIDrugaMajaTyleSamoWierszyIKolumn == false){ System.err.println("Oops, najwyrazniej pierwsza i druga nie maja tyle samo wierszy i kolumn..."); return; } if (czyPierwszaITrzeciaMajaTyleSamoWierszyIKolumn == true){ System.err.println("Oops, najwyrazniej pierwsza i trzecia maja tyle samo wierszy i kolumn..."); return; } System.out.println("Zadanie 2 jest dobrze zrobione!"); /* ********************ZADANIE 3******************** */ int[][] macierzDoZadania3 = { {1, 1, 1}, {2, 2, 2}, {3, 3, 3}}; int sumaElementow = 18; int ileMetodaWyliczyla = zwrocDodaneElementyMacierzy(macierzDoZadania3); if (ileMetodaWyliczyla != sumaElementow){ System.err.println("OJ! Coś w zadaniu 3 źle posumowało :S"); return; } System.out.println("Zadanie 3 jest dobrze zrobione!"); /* ********************ZADANIE 4******************** */ int [][] pierwszaMacierzDoZadania4 = {{1, 2, 3}, {4,5,6}, {7,8,9}}; int [][] drugaMacierzDoZadania4 = {{9,8,7}, {6, 5, 4}, {3, 2, 1}}; int [][] jakaMacierzWinnaByc = {{10, 10, 10}, {10, 10, 10}, {10, 10, 10}}; int [][] coNamWyszloZZadania4 = dodajDoSiebieMacierze(pierwszaMacierzDoZadania4, drugaMacierzDoZadania4); boolean czySaRowneMacierze = CzyRowne(jakaMacierzWinnaByc, coNamWyszloZZadania4); if (czySaRowneMacierze == false){ System.out.println("Te macierze w zadaniu 4 miały być równe..."); return; } System.out.println("Zadanie 4 jest mega extra dobrze zrobione!"); /* ********************ZADANIE 5******************** */ char [][] macierzDoZadania5 = { {'a','b','c'}, {'e', 'f', 'g'}, {'h', 'i', 'j'}}; char znakDoPrzekątnych = 'o'; System.out.println("Już musisz sam sobie porównać czy dobrze wypelnia!"); wypelnijPrzekatneMacierzyZnakami(macierzDoZadania5, znakDoPrzekątnych); System.out.println("Zadanie 5 mam nadzieje, ze dobrze jest zrobione!"); /* ********************ZADANIE 6******************** */ char [][] macierzJA_JE_OK = {{'J', 'A'}, {'J', 'E'}, {'O', 'K'}}; char [][] macierzVA_ST_EJ = {{'V', 'A'}, {'S', 'T'}, {'E', 'J'}}; char[][] jakaMacierzMaByc = { {'J', 'A', 'V', 'A'}, {'J', 'E', 'S', 'T'}, {'O', 'K', 'E', 'J'}}; char [][] otrzymanaZMetody = zlaczMacierzeZnakow(macierzJA_JE_OK, macierzVA_ST_EJ); boolean czy_macierzJakaMaByc_otrzymanaZMetody_saRowne = CzyRowne(jakaMacierzMaByc, otrzymanaZMetody); if (czy_macierzJakaMaByc_otrzymanaZMetody_saRowne == false){ System.err.println("Oj! Coś źle jest w zadaniu 6! chyba!"); return; } System.out.println("Zadanie 6 jest elegancko zrobione.!"); System.out.println("Brawo! :))"); } /* *************************** METODA MAIN ********************* */ private static boolean CzyRowne(char [][] pierwsza, char[][] druga){ if (pierwsza.length != druga.length && pierwsza[0].length != druga[0].length){ return false; } for (int i = 0; i < pierwsza.length; i++) { for (int j = 0; j < pierwsza[i].length; j++) { if (pierwsza[i][j] != druga[i][j]){ return false; } } } return true; } private static boolean CzyRowne(int [][] pierwsza, int[][] druga){ if (!czyMacierzeMajaTyleSamoWierszyIKolumn(pierwsza, druga)){ return false; } for (int i = 0; i < pierwsza.length; i++) { for (int j = 0; j < pierwsza[i].length; j++) { if (pierwsza[i][j] != druga[i][j]){ return false; } } } return true; } /** * Takie cos do drukowania macierzy znakow... */ private static void printujMacierz(char[][] macierzZnakow){ for (int i = 0; i < macierzZnakow.length; i++) { char [] wierszZeZnakami = macierzZnakow[i]; for (int j = 0; j < wierszZeZnakami.length; j++) { System.out.print(" " + wierszZeZnakami[j]); } System.out.println(); } } /** * Takie cos do drukowania macierzy liczb... */ private static void printujMacierz(int [][] macierzLiczb){ for (int i = 0; i < macierzLiczb.length; i++) { int [] wierszZLiczbami = macierzLiczb[i]; for (int j = 0; j < wierszZLiczbami.length; j++) { System.out.print(" " + wierszZLiczbami[j]); } System.out.println(); } } }
7258_19
/** * Created by Kamil on 2015-11-19. */ public class Spotkanie05 { public static void main(String[] args){ // Rozmowa o pracy domowej Zadania4 // https://gist.github.com/ // // Zmienne instancyjne przechowują stan obiektu. // Metody umożliwiają zmienianie stanu. // Enkapsulacja danych, hermetyzacja: // * zmienne instancyjne powinny być oznaczone jako private // * jeśli potrzebny jest dostęp do tych zmiennych, możemy udostępnić gettery/settery. // przykład gettera: // public double getSaldo(){ // return saldo; // }; // setter: // public double setSaldo(double saldo){ // this.saldo = saldo; // } // W klasie konto nie mamy settera, ponieważ: // zgodnie z zasadą enkapsulacji, wszelkie operacje na zmiennej 'saldo' powinna wykonywać klasa Konto // (to jest jej odpowiedzialność) // Aby zaimplementować wpłaty/wypłaty // nie powinnno się tego robić w jakimś zewnętrznym kodzie, który: pobiera saldo z settera, dodaje/zmniejsza saldo, a następnie ustawia nowe saldo. // Powwinno się tę funkcjonalność umieścić w klasie Konto, np. w dwóch metodach: wplac(double kwota) oraz wyplac(double kwota) // Obiekt niemutowalny - nie zmienia stanu: // - Wartość ustalamy w konstruktorze, i tylko tam. // - żadnej z metod obiektu nie wolno zmieniać jego stanu. W szczególności: obiekt nie może mieć setterów. // Override // Pisząc własną implementację metody equals() musimy przeimplementować także hashCode } }
KNJPJATK/GrupaPodstawowsza
spotkanie_05/src/Spotkanie05.java
578
// Pisząc własną implementację metody equals() musimy przeimplementować także hashCode
line_comment
pl
/** * Created by Kamil on 2015-11-19. */ public class Spotkanie05 { public static void main(String[] args){ // Rozmowa o pracy domowej Zadania4 // https://gist.github.com/ // // Zmienne instancyjne przechowują stan obiektu. // Metody umożliwiają zmienianie stanu. // Enkapsulacja danych, hermetyzacja: // * zmienne instancyjne powinny być oznaczone jako private // * jeśli potrzebny jest dostęp do tych zmiennych, możemy udostępnić gettery/settery. // przykład gettera: // public double getSaldo(){ // return saldo; // }; // setter: // public double setSaldo(double saldo){ // this.saldo = saldo; // } // W klasie konto nie mamy settera, ponieważ: // zgodnie z zasadą enkapsulacji, wszelkie operacje na zmiennej 'saldo' powinna wykonywać klasa Konto // (to jest jej odpowiedzialność) // Aby zaimplementować wpłaty/wypłaty // nie powinnno się tego robić w jakimś zewnętrznym kodzie, który: pobiera saldo z settera, dodaje/zmniejsza saldo, a następnie ustawia nowe saldo. // Powwinno się tę funkcjonalność umieścić w klasie Konto, np. w dwóch metodach: wplac(double kwota) oraz wyplac(double kwota) // Obiekt niemutowalny - nie zmienia stanu: // - Wartość ustalamy w konstruktorze, i tylko tam. // - żadnej z metod obiektu nie wolno zmieniać jego stanu. W szczególności: obiekt nie może mieć setterów. // Override // Pisząc własną <SUF> } }
6273_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 eltharis.wsn; import eltharis.wsn.classes.User; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import eltharis.wsn.classes.UserArray; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.simpleframework.xml.*; import org.simpleframework.xml.core.Persister; /** * * @author eltharis */ public class showAllActivity extends ListActivity { private ArrayAdapter<User> adapter; private User[] users; private String executeGET() throws Exception { HttpClient httpclient = new DefaultHttpClient(); //Korzystamy z Apache, który jest w Android HttpResponse response = httpclient.execute(new HttpGet("https://agile-depths-5530.herokuapp.com/usershow/")); //każemy mu wykonać GETa StatusLine statusline = response.getStatusLine(); //sprawdzamy status Toast toast = Toast.makeText(getApplicationContext(), "HTTP Response: " + Integer.toString(statusline.getStatusCode()), Toast.LENGTH_LONG); toast.show(); //prosty Toast z HttpStatusCode ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); //zapisujemy dane HTTP do ByteArrayOutputStream String responseString = out.toString(); out.close(); //zamykamy OutputStream return responseString; } private void showAll(String httpResponse) { // TextView tv = (TextView)findViewById(R.id.tv); // tv.setText(httpResponse); Serializer ser = new Persister(); try { UserArray ua = ser.read(UserArray.class, httpResponse); users = ua.getUsers(); } catch (Exception ex) { Logger.getLogger(showAllActivity.class.getName()).log(Level.SEVERE, null, ex); } } /** * Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); try { String response = executeGET(); showAll(response); } catch (Exception e) { Toast toast = Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG); //do debuggowania toast.show(); } adapter = new ArrayAdapter<User>(this, android.R.layout.simple_list_item_1, users); setListAdapter(adapter); ListView lv = getListView(); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { //nasłuchiwanie, czy jakiś z użytkowników był naciśnięty public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String username = ((TextView) view).getText().toString(); Toast.makeText(getBaseContext(), username, Toast.LENGTH_SHORT).show(); User selected = null; for (User u : users) { if (u.getUsername().equals(username)) { selected = u; break; } } if (selected != null) { Intent intent = new Intent(getBaseContext(), showIDActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("id", selected.getId()); //dodajemy jako Extra do intentu. Są to tak jakby parametry getBaseContext().startActivity(intent); //zaczynamy intent } } }); } }
KPyda/Django
DjangoTest/src/eltharis/wsn/showAllActivity.java
1,124
//agile-depths-5530.herokuapp.com/usershow/")); //każemy mu wykonać GETa
line_comment
pl
/* * 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 eltharis.wsn; import eltharis.wsn.classes.User; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import eltharis.wsn.classes.UserArray; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.simpleframework.xml.*; import org.simpleframework.xml.core.Persister; /** * * @author eltharis */ public class showAllActivity extends ListActivity { private ArrayAdapter<User> adapter; private User[] users; private String executeGET() throws Exception { HttpClient httpclient = new DefaultHttpClient(); //Korzystamy z Apache, który jest w Android HttpResponse response = httpclient.execute(new HttpGet("https://agile-depths-5530.herokuapp.com/usershow/")); //każemy <SUF> StatusLine statusline = response.getStatusLine(); //sprawdzamy status Toast toast = Toast.makeText(getApplicationContext(), "HTTP Response: " + Integer.toString(statusline.getStatusCode()), Toast.LENGTH_LONG); toast.show(); //prosty Toast z HttpStatusCode ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); //zapisujemy dane HTTP do ByteArrayOutputStream String responseString = out.toString(); out.close(); //zamykamy OutputStream return responseString; } private void showAll(String httpResponse) { // TextView tv = (TextView)findViewById(R.id.tv); // tv.setText(httpResponse); Serializer ser = new Persister(); try { UserArray ua = ser.read(UserArray.class, httpResponse); users = ua.getUsers(); } catch (Exception ex) { Logger.getLogger(showAllActivity.class.getName()).log(Level.SEVERE, null, ex); } } /** * Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); try { String response = executeGET(); showAll(response); } catch (Exception e) { Toast toast = Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG); //do debuggowania toast.show(); } adapter = new ArrayAdapter<User>(this, android.R.layout.simple_list_item_1, users); setListAdapter(adapter); ListView lv = getListView(); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { //nasłuchiwanie, czy jakiś z użytkowników był naciśnięty public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String username = ((TextView) view).getText().toString(); Toast.makeText(getBaseContext(), username, Toast.LENGTH_SHORT).show(); User selected = null; for (User u : users) { if (u.getUsername().equals(username)) { selected = u; break; } } if (selected != null) { Intent intent = new Intent(getBaseContext(), showIDActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("id", selected.getId()); //dodajemy jako Extra do intentu. Są to tak jakby parametry getBaseContext().startActivity(intent); //zaczynamy intent } } }); } }
9402_66
//zakres 3 pierwsze wyklady //12.04 test na wykladzie 10:10 //pytanie o dzialania na shortach i jaki typ danych zwroci wynik czy cos public class NotatkiW3 { } //operatory //moga byc pojedyncze, podwojne lub potrojne //(type) -> operator rzutowania //instance of //casting primitve values //jesli mamy zmienna wezszego typu mozemy ja przekonwertowac na szersza bez problemu short y = (short)20_591 //jesli chcemy zmienna szerszego typu zmienic na wezsza musimy jawnie ja rzutowac [operator (type)] //jesli chcemy dodac do siebie 2 rozne typy java ma nastepujace zasady: //1. wezszy zostanie autorozszerzony do szerszego typu i wynik zwroci jako szerszy //2. jesli jeden z typow jest liczba calkowita a druga to zmiennoprzecinkowa, calkowita zostanie podniesiona do zmiennoprzecinkowej i wynik bedzie zmiennoprzecinkowy //3. byte i short zostaja zawsze automatycznie podnoszone do typu int, nawet jak dodajemy 2 zmienne tego samego typu. aby zmienic typ wyniku na short nalezy uzyc rzutowania //4. po wszystkich promocjach, typ wyniku bedzie taki jak typy do ktorych zostaly podniesione //ternary operator (potrojny operator) //boolExprs ? expr1 : expr2 //java ma for-each //(datatype instance : collection) {} //tablica dwuwymiarowa //int[][] myComplexArray = {{5,5,2},{3,5,1}} //for(int[] mySimpleArray : myComplexArray) { // for(int i : mySimpleArray) { // System.out.print(i) //} //} //dwa sposoby na utworzenie stringa //jezeli tworzymy obiekt tworzac po prostu lancuch znakow, to jezeli ma juz go w puli (zostal stworzony wczesniej taki sam ciag znakow) to utworzy tylko referencje //String name = "Grupa 215IC" //jezeli jawnie piszemy new string to zawsze utworzy nowy obiekt i przypisze referencje //String name = new String("Grupa 215IC)" //znak plusa przy stringach jest operatorem konkatenacji //1 + 2 + "c" //"3c" //obiekty klasy string sa niemutowalne //String s = "1" //s += "2" //w tym przypadku powstaje nowy obiekt //kazda operacja laczenia stringow tworzy nowy obiekt string //musimy przypisac wynik do zmiennej aby go otrzymac .concat("2") == + // s2.concat("3") gdzie s2 = "12" to wciaz "12". s3 = s2.concat("3") to "123" //zestaw metod na Stringach //length(), chartAt(index), indexOf(char), substring(), toLowerCase(), toUpperCase(), equals(String str), equalsIgnoreCase() //startsWith(), endsWith(), replace(), replaceAll(), contains(), trim(), strip(), stripLeading(), stripTrailing(), intern() => for string pools //metody mozna chainowac //String result = "AniMal".trim().toLowerCase().replace('a', 'A'); //klasa StringBuilder //nie bd na testach //mutowalne, działamy cały czas na jednym obiekcie //dobra praktyka jest na koniec tworzenie dzialan na StringBuilder wywolac metode .toString() i wysylanie takiego wyniku //porownywanie wartosci typu String //w zasadzie porowywane sa adresy referencji przy uzyciu operatora '==' //nie uzywa sie go wiec do porownywania lancuchow znakow //String x = new String("Hello World"); //String z = "Hello World"; //x.equals(z); // true //toString(); //przeslanianie metod -> pomiedzy klasami //przeciazanie -> w tej samej klasie //tablice Array. tablice sa stale //int[] numbers = new int[3] <- rozmiar tablicy //int[] numAnimals; //int[][] rectangleArray = new int[3][4]; //rectangleArray[0][2] = 15; //int[][] diffSize = {{1,6}, {3,5,9,8}, {2,4,7}}; //tablice w tablicach sa co do zasady tablice postrzepione. liczba elementow w wymiarach moze byc rozna //tablice ArrayList //kolekcje dynamiczne, moga zmieniac rozmiar //moga zawierac obiekty dowolnych klas //ArrayList<String> list4 = newArrayList<String>(); //ArrayList<String> list5 = newArrayList<>(); //listy dla obiektów klasy string, zainicjowanie bez typu <> zawiera typ obiektowy //ArrayList<Animal> listAnimal = newArrayList<Animal>(); //w kolekcji ArrayList przechowujemy tylko obiekty klas -> mozemy przechowywac liczby bo sa wrappery obiektow dla typow podstawowych typu Double double //metody ArrayList //add(), remove(), set(), isEmpty(), size(), clear(), contains() //import java.util.ArrayList //mechanizm autoboxing //wrapper classes to klasy opakowujace typy podstawowe w obiekty //Integer intWrapped = 1; //Integer typ referencyjny //int i = intWrapped; //intWrapped zostaje rozpakowane i przypisane do typu int, dzieje sie automatycznie //jawne wykonanie tego co robi autoboxing: //Integer intWrapped = Integer.valueOf(1) //zapakowanie we wrapper , wrapper class value //int i = intWrapped.intValue() //rozpakowanie obiektu, converting back to primitive //na zaj w pon //static -> nie trzeba tworzyc obiektu //metody zmiennych klasy //teraz bedziemy powolywac obiekt, kontekst i stan obiektu na podstawie tej instancji
KajtekWisniewski/java-labs
wyklad/NotatkiW3.java
1,698
//jawne wykonanie tego co robi autoboxing:
line_comment
pl
//zakres 3 pierwsze wyklady //12.04 test na wykladzie 10:10 //pytanie o dzialania na shortach i jaki typ danych zwroci wynik czy cos public class NotatkiW3 { } //operatory //moga byc pojedyncze, podwojne lub potrojne //(type) -> operator rzutowania //instance of //casting primitve values //jesli mamy zmienna wezszego typu mozemy ja przekonwertowac na szersza bez problemu short y = (short)20_591 //jesli chcemy zmienna szerszego typu zmienic na wezsza musimy jawnie ja rzutowac [operator (type)] //jesli chcemy dodac do siebie 2 rozne typy java ma nastepujace zasady: //1. wezszy zostanie autorozszerzony do szerszego typu i wynik zwroci jako szerszy //2. jesli jeden z typow jest liczba calkowita a druga to zmiennoprzecinkowa, calkowita zostanie podniesiona do zmiennoprzecinkowej i wynik bedzie zmiennoprzecinkowy //3. byte i short zostaja zawsze automatycznie podnoszone do typu int, nawet jak dodajemy 2 zmienne tego samego typu. aby zmienic typ wyniku na short nalezy uzyc rzutowania //4. po wszystkich promocjach, typ wyniku bedzie taki jak typy do ktorych zostaly podniesione //ternary operator (potrojny operator) //boolExprs ? expr1 : expr2 //java ma for-each //(datatype instance : collection) {} //tablica dwuwymiarowa //int[][] myComplexArray = {{5,5,2},{3,5,1}} //for(int[] mySimpleArray : myComplexArray) { // for(int i : mySimpleArray) { // System.out.print(i) //} //} //dwa sposoby na utworzenie stringa //jezeli tworzymy obiekt tworzac po prostu lancuch znakow, to jezeli ma juz go w puli (zostal stworzony wczesniej taki sam ciag znakow) to utworzy tylko referencje //String name = "Grupa 215IC" //jezeli jawnie piszemy new string to zawsze utworzy nowy obiekt i przypisze referencje //String name = new String("Grupa 215IC)" //znak plusa przy stringach jest operatorem konkatenacji //1 + 2 + "c" //"3c" //obiekty klasy string sa niemutowalne //String s = "1" //s += "2" //w tym przypadku powstaje nowy obiekt //kazda operacja laczenia stringow tworzy nowy obiekt string //musimy przypisac wynik do zmiennej aby go otrzymac .concat("2") == + // s2.concat("3") gdzie s2 = "12" to wciaz "12". s3 = s2.concat("3") to "123" //zestaw metod na Stringach //length(), chartAt(index), indexOf(char), substring(), toLowerCase(), toUpperCase(), equals(String str), equalsIgnoreCase() //startsWith(), endsWith(), replace(), replaceAll(), contains(), trim(), strip(), stripLeading(), stripTrailing(), intern() => for string pools //metody mozna chainowac //String result = "AniMal".trim().toLowerCase().replace('a', 'A'); //klasa StringBuilder //nie bd na testach //mutowalne, działamy cały czas na jednym obiekcie //dobra praktyka jest na koniec tworzenie dzialan na StringBuilder wywolac metode .toString() i wysylanie takiego wyniku //porownywanie wartosci typu String //w zasadzie porowywane sa adresy referencji przy uzyciu operatora '==' //nie uzywa sie go wiec do porownywania lancuchow znakow //String x = new String("Hello World"); //String z = "Hello World"; //x.equals(z); // true //toString(); //przeslanianie metod -> pomiedzy klasami //przeciazanie -> w tej samej klasie //tablice Array. tablice sa stale //int[] numbers = new int[3] <- rozmiar tablicy //int[] numAnimals; //int[][] rectangleArray = new int[3][4]; //rectangleArray[0][2] = 15; //int[][] diffSize = {{1,6}, {3,5,9,8}, {2,4,7}}; //tablice w tablicach sa co do zasady tablice postrzepione. liczba elementow w wymiarach moze byc rozna //tablice ArrayList //kolekcje dynamiczne, moga zmieniac rozmiar //moga zawierac obiekty dowolnych klas //ArrayList<String> list4 = newArrayList<String>(); //ArrayList<String> list5 = newArrayList<>(); //listy dla obiektów klasy string, zainicjowanie bez typu <> zawiera typ obiektowy //ArrayList<Animal> listAnimal = newArrayList<Animal>(); //w kolekcji ArrayList przechowujemy tylko obiekty klas -> mozemy przechowywac liczby bo sa wrappery obiektow dla typow podstawowych typu Double double //metody ArrayList //add(), remove(), set(), isEmpty(), size(), clear(), contains() //import java.util.ArrayList //mechanizm autoboxing //wrapper classes to klasy opakowujace typy podstawowe w obiekty //Integer intWrapped = 1; //Integer typ referencyjny //int i = intWrapped; //intWrapped zostaje rozpakowane i przypisane do typu int, dzieje sie automatycznie //jawne wykonanie <SUF> //Integer intWrapped = Integer.valueOf(1) //zapakowanie we wrapper , wrapper class value //int i = intWrapped.intValue() //rozpakowanie obiektu, converting back to primitive //na zaj w pon //static -> nie trzeba tworzyc obiektu //metody zmiennych klasy //teraz bedziemy powolywac obiekt, kontekst i stan obiektu na podstawie tej instancji
9531_3
package com.janikcrew.szkola; import com.janikcrew.szkola.dao.BudzetDAO; import com.janikcrew.szkola.dao.BudzetDAOImpl; import com.janikcrew.szkola.dao.KlasaDAO; import com.janikcrew.szkola.dao.OsobaDAO; import com.janikcrew.szkola.entity.*; import com.janikcrew.szkola.service.*; import jakarta.persistence.EntityManager; import org.springframework.aop.scope.ScopedProxyUtils; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cglib.core.Local; import org.springframework.context.annotation.Bean; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.List; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Bean public CommandLineRunner commandLineRunner(BudzetService budzetService, OsobaService osobaService, KlasaService klasaService, PrzedmiotService przedmiotService, WiadomoscService wiadomoscService, UwagaService uwagaService, AdminService adminService, GodzinaLekcyjnaService godzinaLekcyjnaService, MiejsceService miejsceService, DyzurService dyzurService) { return runner -> { //utworzOsobe(osobaService); //testTransakcji(budzetService); //testUtworzeniaNauczyciela(budzetService, osobaService); //testUtworzeniaKlasy(osobaService, klasaService); //testUtworzeniaUcznia(osobaService, klasaService); //testDodaniaUczniaDoKlasy(klasaService, osobaService); //testUtworzeniaPrzedmiotu(przedmiotService, klasaService, osobaService); //testUsunieciaPrzedmiotu(przedmiotService); //testDzialaniaKlasy(przedmiotService, osobaService, klasaService); //testUtworzeniaWiadomosci(wiadomoscService, osobaService); //utworzUwage(uwagaService, osobaService); //testUtworzeniaKalendarza(adminService); //testUsunieciaKalendarza(adminService); //testUtworzeniaGodzinyLekcyjnej(godzinaLekcyjnaService, osobaService, przedmiotService, klasaService, miejsceService); //testUsunieciaGodzinyLekcyjnej(godzinaLekcyjnaService); //testDodaniaZastepstwa(godzinaLekcyjnaService, osobaService); //testDodaniaZastepujacejSali(miejsceService, godzinaLekcyjnaService); //testDodaniaZdarzenia(godzinaLekcyjnaService); //testDodaniaMiejsca(miejsceService); //testModyfikacjiNazwySali(miejsceService); testUtworzeniaDyzuru(dyzurService); }; } private void testUtworzeniaDyzuru(DyzurService dyzurService) { } private void testUsunieciaKalendarza(AdminService adminService) { adminService.wyczyscKalendarz(); } private void testDodaniaZastepujacejSali(MiejsceService miejsceService, GodzinaLekcyjnaService godzinaLekcyjnaService) { int idGodzinyLekcyjnej = 15; int idSaliZastepujacej = 5; godzinaLekcyjnaService.dodajZastepujacaSale(idGodzinyLekcyjnej, idSaliZastepujacej); } private void testModyfikacjiNazwySali(MiejsceService miejsceService) { String staraNazwa = "Sala Gimnastyczna nr 21"; String nowaNazwa = "Sala gimnastyczna nr 21"; miejsceService.aktualizujMiejsce(staraNazwa, nowaNazwa); } private void testDodaniaMiejsca(MiejsceService miejsceService) { String miejsce = "Sala nr 1"; miejsceService.dodajMiejsce(miejsce); } private void testUsunieciaGodzinyLekcyjnej(GodzinaLekcyjnaService godzinaLekcyjnaService) { int idPrzedmiotu = 3; godzinaLekcyjnaService.usunGodzineZPlanuByIdPrzedmiotu(idPrzedmiotu); } private void testDodaniaZdarzenia(GodzinaLekcyjnaService godzinaLekcyjnaService) { String zdarzenie = "Klasowe wyjście do kina"; godzinaLekcyjnaService.dodajZdarzenieDoGodzinyLekcyjnej(16, zdarzenie); } private void testDodaniaZastepstwa(GodzinaLekcyjnaService godzinaLekcyjnaService, OsobaService osobaService) { godzinaLekcyjnaService.dodajZastepstwoDoGodzinyLekcyjnej(16, 2); } private void testUtworzeniaGodzinyLekcyjnej(GodzinaLekcyjnaService godzinaLekcyjnaService, OsobaService osobaService, PrzedmiotService przedmiotService, KlasaService klasaService, MiejsceService miejsceService) { Nauczyciel nauczyciel = (Nauczyciel) osobaService.findOsobaById(7); Przedmiot przedmiot = przedmiotService.findPrzedmiotById(3); Klasa klasa = klasaService.findKlasaByName("1a"); Miejsce miejsce = miejsceService.findMiejsceById(1); String dzien = "poniedziałek"; String godzRozpoczecia = "08:00:00"; String dataRozpoczecia = "2023-09-04"; godzinaLekcyjnaService.dodajGodzinaLekcyjnaDoPlanuLekcji(przedmiot, klasa, miejsce, dzien, godzRozpoczecia, dataRozpoczecia); } private void testUtworzeniaKalendarza(AdminService adminService) { adminService.utworzKalendarzNaRokSzkolny(); } private void utworzUwage(UwagaService uwagaService, OsobaService osobaService) { Nauczyciel nauczyciel = (Nauczyciel) osobaService.findOsobaById(7); Uczen uczen = (Uczen) osobaService.findOsobaById(9); Uwaga uwaga = new Uwaga("NEGATYWNA", "Przeklinanie", "Łukasz przeklinał na lekcji niemieckiego"); uwagaService.utworzUwage(uwaga, nauczyciel, uczen); } private void testUtworzeniaWiadomosci(WiadomoscService wiadomoscService, OsobaService osobaService) { Admin admin = (Admin) osobaService.findOsobaById(1); Nauczyciel nauczyciel = (Nauczyciel) osobaService.findOsobaById(2); Wiadomosc wiadomosc = new Wiadomosc("Szanowny Dyrektorze! ", "Dziękuję za przyjęcie do pracy! "); wiadomoscService.utworzWiadomosc(wiadomosc, nauczyciel, admin); } private void testUsunieciaPrzedmiotu(PrzedmiotService przedmiotService) { int id = 2; przedmiotService.deletePrzedmiotById(id); } private void testDzialaniaKlasy(PrzedmiotService przedmiotService, OsobaService osobaService, KlasaService klasaService) { Klasa klasa = klasaService.findKlasaByName("1a"); for(Przedmiot przedmiot : klasa.getListaPrzedmiotow()) { System.out.println(przedmiot.getNazwa()); } } private void testUtworzeniaPrzedmiotu(PrzedmiotService przedmiotService, KlasaService klasaService, OsobaService osobaService) { Przedmiot przedmiot = new Przedmiot("język niemiecki"); String nazwaKlasy = "1a"; int idNauczyciela = 7; Klasa klasa = klasaService.findKlasaByName(nazwaKlasy); Nauczyciel nauczyciel = (Nauczyciel) osobaService.findOsobaById(idNauczyciela); przedmiotService.dodajPrzedmiot(przedmiot, nauczyciel, klasa); } private void testDodaniaUczniaDoKlasy(KlasaService klasaService, OsobaService osobaService) { int id = 3; int id1 = 6; String name = "1a"; Klasa klasa = klasaService.findKlasaByName(name); Uczen uczen = (Uczen) osobaService.findOsobaById(id); Uczen uczen1 = (Uczen) osobaService.findOsobaById(id1); klasaService.dodajUcznia(klasa, uczen, uczen1); } private void utworzOsobe(OsobaService osobaService) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); Uczen uczen = new Uczen("02256745432", "Kacper", "Łukawski", "klukawski45@gmail.com", LocalDate.parse("2002-12-12")); Rodzic rodzic = new Rodzic("694785655678", "Maria", "Łukawska", "gorzowianka32@onet.pl", LocalDate.parse("1969-04-24", formatter)); osobaService.dodajRodzicaUcznia(rodzic, uczen); } private void testUtworzeniaUcznia(OsobaService osobaService, KlasaService klasaService) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); Uczen uczen = new Uczen("02222787564", "Łukasz", "Królicki", "lukupuku123@puk.pl", LocalDate.parse("2002-02-27", formatter)); Rodzic rodzic = new Rodzic("68983746738", "Grażyna", "Królicka", "grazkrol@onet.pl", LocalDate.parse("1968-11-23", formatter)); Klasa klasa = klasaService.findKlasaByName("1a"); osobaService.dodajRodzicaUcznia(rodzic, uczen); klasaService.dodajUcznia(klasa, uczen); } private void testUtworzeniaKlasy(OsobaService osobaService, KlasaService klasaService) { int id = 2; Nauczyciel nauczyciel = (Nauczyciel) osobaService.findOsobaById(id); Klasa klasa = new Klasa("1a"); klasaService.dodajKlase(klasa, nauczyciel); } private void testUtworzeniaNauczyciela(BudzetService budzetService, OsobaService osobaService) { int id = 2; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); //osobaService.dodajUzytkownika(nauczyciel); osobaService.dodajNauczyciela(new Nauczyciel("57829485748", "Donald", "Tusk", "donald57@gmail.com", LocalDate.parse("1957-06-06", formatter))); } public void testTransakcji(BudzetService budzetService) throws Exception { int id = 1; Budzet budzet = budzetService.findBudzetById(id); //Transakcja transakcja = new Transakcja("WYDATEK", 20000.0, LocalDate.now(), LocalTime.now(), "Malowanie pomieszczeń"); //budzetService.dodajTransakcjeDoBudzetu(budzet, transakcja); budzetService.znajdzListeTransakcjiBudzetu(budzet); for(Transakcja transakcja : budzet.getListaTransakcji()) System.out.println(transakcja); } }
Kajzelek/System-zarz-dzaj-cy-plac-wk-o-wiatow-
src/main/java/com/janikcrew/szkola/DemoApplication.java
3,800
//Transakcja transakcja = new Transakcja("WYDATEK", 20000.0, LocalDate.now(), LocalTime.now(), "Malowanie pomieszczeń");
line_comment
pl
package com.janikcrew.szkola; import com.janikcrew.szkola.dao.BudzetDAO; import com.janikcrew.szkola.dao.BudzetDAOImpl; import com.janikcrew.szkola.dao.KlasaDAO; import com.janikcrew.szkola.dao.OsobaDAO; import com.janikcrew.szkola.entity.*; import com.janikcrew.szkola.service.*; import jakarta.persistence.EntityManager; import org.springframework.aop.scope.ScopedProxyUtils; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cglib.core.Local; import org.springframework.context.annotation.Bean; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.List; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Bean public CommandLineRunner commandLineRunner(BudzetService budzetService, OsobaService osobaService, KlasaService klasaService, PrzedmiotService przedmiotService, WiadomoscService wiadomoscService, UwagaService uwagaService, AdminService adminService, GodzinaLekcyjnaService godzinaLekcyjnaService, MiejsceService miejsceService, DyzurService dyzurService) { return runner -> { //utworzOsobe(osobaService); //testTransakcji(budzetService); //testUtworzeniaNauczyciela(budzetService, osobaService); //testUtworzeniaKlasy(osobaService, klasaService); //testUtworzeniaUcznia(osobaService, klasaService); //testDodaniaUczniaDoKlasy(klasaService, osobaService); //testUtworzeniaPrzedmiotu(przedmiotService, klasaService, osobaService); //testUsunieciaPrzedmiotu(przedmiotService); //testDzialaniaKlasy(przedmiotService, osobaService, klasaService); //testUtworzeniaWiadomosci(wiadomoscService, osobaService); //utworzUwage(uwagaService, osobaService); //testUtworzeniaKalendarza(adminService); //testUsunieciaKalendarza(adminService); //testUtworzeniaGodzinyLekcyjnej(godzinaLekcyjnaService, osobaService, przedmiotService, klasaService, miejsceService); //testUsunieciaGodzinyLekcyjnej(godzinaLekcyjnaService); //testDodaniaZastepstwa(godzinaLekcyjnaService, osobaService); //testDodaniaZastepujacejSali(miejsceService, godzinaLekcyjnaService); //testDodaniaZdarzenia(godzinaLekcyjnaService); //testDodaniaMiejsca(miejsceService); //testModyfikacjiNazwySali(miejsceService); testUtworzeniaDyzuru(dyzurService); }; } private void testUtworzeniaDyzuru(DyzurService dyzurService) { } private void testUsunieciaKalendarza(AdminService adminService) { adminService.wyczyscKalendarz(); } private void testDodaniaZastepujacejSali(MiejsceService miejsceService, GodzinaLekcyjnaService godzinaLekcyjnaService) { int idGodzinyLekcyjnej = 15; int idSaliZastepujacej = 5; godzinaLekcyjnaService.dodajZastepujacaSale(idGodzinyLekcyjnej, idSaliZastepujacej); } private void testModyfikacjiNazwySali(MiejsceService miejsceService) { String staraNazwa = "Sala Gimnastyczna nr 21"; String nowaNazwa = "Sala gimnastyczna nr 21"; miejsceService.aktualizujMiejsce(staraNazwa, nowaNazwa); } private void testDodaniaMiejsca(MiejsceService miejsceService) { String miejsce = "Sala nr 1"; miejsceService.dodajMiejsce(miejsce); } private void testUsunieciaGodzinyLekcyjnej(GodzinaLekcyjnaService godzinaLekcyjnaService) { int idPrzedmiotu = 3; godzinaLekcyjnaService.usunGodzineZPlanuByIdPrzedmiotu(idPrzedmiotu); } private void testDodaniaZdarzenia(GodzinaLekcyjnaService godzinaLekcyjnaService) { String zdarzenie = "Klasowe wyjście do kina"; godzinaLekcyjnaService.dodajZdarzenieDoGodzinyLekcyjnej(16, zdarzenie); } private void testDodaniaZastepstwa(GodzinaLekcyjnaService godzinaLekcyjnaService, OsobaService osobaService) { godzinaLekcyjnaService.dodajZastepstwoDoGodzinyLekcyjnej(16, 2); } private void testUtworzeniaGodzinyLekcyjnej(GodzinaLekcyjnaService godzinaLekcyjnaService, OsobaService osobaService, PrzedmiotService przedmiotService, KlasaService klasaService, MiejsceService miejsceService) { Nauczyciel nauczyciel = (Nauczyciel) osobaService.findOsobaById(7); Przedmiot przedmiot = przedmiotService.findPrzedmiotById(3); Klasa klasa = klasaService.findKlasaByName("1a"); Miejsce miejsce = miejsceService.findMiejsceById(1); String dzien = "poniedziałek"; String godzRozpoczecia = "08:00:00"; String dataRozpoczecia = "2023-09-04"; godzinaLekcyjnaService.dodajGodzinaLekcyjnaDoPlanuLekcji(przedmiot, klasa, miejsce, dzien, godzRozpoczecia, dataRozpoczecia); } private void testUtworzeniaKalendarza(AdminService adminService) { adminService.utworzKalendarzNaRokSzkolny(); } private void utworzUwage(UwagaService uwagaService, OsobaService osobaService) { Nauczyciel nauczyciel = (Nauczyciel) osobaService.findOsobaById(7); Uczen uczen = (Uczen) osobaService.findOsobaById(9); Uwaga uwaga = new Uwaga("NEGATYWNA", "Przeklinanie", "Łukasz przeklinał na lekcji niemieckiego"); uwagaService.utworzUwage(uwaga, nauczyciel, uczen); } private void testUtworzeniaWiadomosci(WiadomoscService wiadomoscService, OsobaService osobaService) { Admin admin = (Admin) osobaService.findOsobaById(1); Nauczyciel nauczyciel = (Nauczyciel) osobaService.findOsobaById(2); Wiadomosc wiadomosc = new Wiadomosc("Szanowny Dyrektorze! ", "Dziękuję za przyjęcie do pracy! "); wiadomoscService.utworzWiadomosc(wiadomosc, nauczyciel, admin); } private void testUsunieciaPrzedmiotu(PrzedmiotService przedmiotService) { int id = 2; przedmiotService.deletePrzedmiotById(id); } private void testDzialaniaKlasy(PrzedmiotService przedmiotService, OsobaService osobaService, KlasaService klasaService) { Klasa klasa = klasaService.findKlasaByName("1a"); for(Przedmiot przedmiot : klasa.getListaPrzedmiotow()) { System.out.println(przedmiot.getNazwa()); } } private void testUtworzeniaPrzedmiotu(PrzedmiotService przedmiotService, KlasaService klasaService, OsobaService osobaService) { Przedmiot przedmiot = new Przedmiot("język niemiecki"); String nazwaKlasy = "1a"; int idNauczyciela = 7; Klasa klasa = klasaService.findKlasaByName(nazwaKlasy); Nauczyciel nauczyciel = (Nauczyciel) osobaService.findOsobaById(idNauczyciela); przedmiotService.dodajPrzedmiot(przedmiot, nauczyciel, klasa); } private void testDodaniaUczniaDoKlasy(KlasaService klasaService, OsobaService osobaService) { int id = 3; int id1 = 6; String name = "1a"; Klasa klasa = klasaService.findKlasaByName(name); Uczen uczen = (Uczen) osobaService.findOsobaById(id); Uczen uczen1 = (Uczen) osobaService.findOsobaById(id1); klasaService.dodajUcznia(klasa, uczen, uczen1); } private void utworzOsobe(OsobaService osobaService) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); Uczen uczen = new Uczen("02256745432", "Kacper", "Łukawski", "klukawski45@gmail.com", LocalDate.parse("2002-12-12")); Rodzic rodzic = new Rodzic("694785655678", "Maria", "Łukawska", "gorzowianka32@onet.pl", LocalDate.parse("1969-04-24", formatter)); osobaService.dodajRodzicaUcznia(rodzic, uczen); } private void testUtworzeniaUcznia(OsobaService osobaService, KlasaService klasaService) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); Uczen uczen = new Uczen("02222787564", "Łukasz", "Królicki", "lukupuku123@puk.pl", LocalDate.parse("2002-02-27", formatter)); Rodzic rodzic = new Rodzic("68983746738", "Grażyna", "Królicka", "grazkrol@onet.pl", LocalDate.parse("1968-11-23", formatter)); Klasa klasa = klasaService.findKlasaByName("1a"); osobaService.dodajRodzicaUcznia(rodzic, uczen); klasaService.dodajUcznia(klasa, uczen); } private void testUtworzeniaKlasy(OsobaService osobaService, KlasaService klasaService) { int id = 2; Nauczyciel nauczyciel = (Nauczyciel) osobaService.findOsobaById(id); Klasa klasa = new Klasa("1a"); klasaService.dodajKlase(klasa, nauczyciel); } private void testUtworzeniaNauczyciela(BudzetService budzetService, OsobaService osobaService) { int id = 2; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); //osobaService.dodajUzytkownika(nauczyciel); osobaService.dodajNauczyciela(new Nauczyciel("57829485748", "Donald", "Tusk", "donald57@gmail.com", LocalDate.parse("1957-06-06", formatter))); } public void testTransakcji(BudzetService budzetService) throws Exception { int id = 1; Budzet budzet = budzetService.findBudzetById(id); //Transakcja transakcja <SUF> //budzetService.dodajTransakcjeDoBudzetu(budzet, transakcja); budzetService.znajdzListeTransakcjiBudzetu(budzet); for(Transakcja transakcja : budzet.getListaTransakcji()) System.out.println(transakcja); } }
5235_1
package states; import gameUtils.Fonts; import org.newdawn.slick.Color; import java.util.ArrayList; import org.lwjgl.input.Mouse; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.Input; import org.newdawn.slick.MouseListener; import org.newdawn.slick.SlickException; import org.newdawn.slick.state.BasicGameState; import org.newdawn.slick.state.StateBasedGame; public class QuestsState extends BasicGameState { String mouse; String onScreenLoc; gameUtils.Fonts fonts; ArrayList<String> questy = new ArrayList<>(); int bp = 0; Color c = Color.black; String actualScr; //wsp pocz suwaka int suwX = 790; int suwY = 174; @Override public void init(GameContainer gc, StateBasedGame sbg) throws SlickException { mouse = ""; onScreenLoc = " "; //Wytworzenie własnej czcionki fonts = new gameUtils.Fonts(); questy.add("Zemsta na bandytach"); questy.add("Gdzie uciekl herszt"); questy.add("Obozowisko na polach"); questy.add("Wyprawa po futra."); questy.add("Polowanie na lisy"); questy.add("Zaginiony ładunek"); questy.add("Pradawna krypa"); questy.add("Smocze ostrze"); questy.add("Gdzie są bandyci"); questy.add("Oboz troli"); questy.add("Zaginiona paczka"); questy.add("Bezdomny pies"); questy.add("Rybobranie"); } @Override public void update(GameContainer gc, StateBasedGame sbg, int i) throws SlickException { Input input = gc.getInput(); int xpos = Mouse.getX(); int ypos = Mouse.getY(); int scrolling = Mouse.getDWheel(); mouse = "x= " + xpos + " y=" + ypos; onScreenLoc = "x= " + xpos + " y=" + Math.abs(720-ypos); if (input.isKeyPressed(Input.KEY_ESCAPE) || input.isKeyPressed(Input.KEY_M)) { sbg.enterState(1); } //powrót do menu if (((xpos > 520 && xpos < 720) && (ypos > 145 && ypos < 175)) || /* X okna*/((xpos > 779 && xpos < 812) && (ypos > 606 && ypos < 636))) { if (input.isMouseButtonDown(0)) { sbg.enterState(1); } } //wyjście // if ((xpos > 470 && xpos < 630) && (ypos > 280 && ypos < 312)) { // if (input.isMouseButtonDown(0)) { // System.exit(0); // } // } //Przewijanie do góry - scrool myszy, klawisz, przycisk góra if ((scrolling > 0) || input.isKeyPressed(Input.KEY_UP) || ((xpos > 788 && xpos < 814) && (ypos > 546 && ypos < 569) && (input.isMousePressed(0)))) { if (bp > 0) { bp--; suwY -= 24; } } //Przewijanie do dołu - scrool myszy, klawisz, przycisk dół if ((scrolling < 0) || input.isKeyPressed(Input.KEY_DOWN) || ((xpos > 788 && xpos < 814) && (ypos > 97 && ypos < 124) && (input.isMousePressed(0)))) { if (bp < (questy.size() - 11)) { bp++; suwY += 24; } } } @Override public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException { //Tło sceny - rozmyty printscreen actualScr = screenBlur.ScreenClass.screenNumber(); Image skrinGB = new Image(actualScr); g.drawImage(skrinGB, 0, 0); //Okno questa Image menuW = new Image("graphic/menu/QuestNew.png"); g.drawImage(menuW, 0, 0); //Suwaczek Image skrolus = new Image("graphic/menu/skrolus.png"); g.drawImage(skrolus, suwX, suwY); Fonts.print18().drawString(100, 30, onScreenLoc); Fonts.print18().drawString(100, 10, mouse); Fonts.print18().drawString(100, 30, " bieżący indeks " + String.valueOf(bp)); Fonts.print18().drawString(100, 50, " rozmiar listy " + String.valueOf(questy.size())); // g.drawString("Opcje", 520, 375); // g.drawRoundRect(520, 375, 300, 60, 6); // g.drawString("Twórcy", 520, 445); // g.drawRoundRect(520, 445, 300, 60, 6); // g.drawString("Wyjście", 520, 515); // g.drawRoundRect(520, 515, 300, 60, 6); Fonts.print18().drawString(600, 100, "Questy");// (przewijanie strzalkami)"); int wspqy = 175; // wsp pocz y wyświetlania listy for (int i = bp; i < bp + 11; i++) { Fonts.print18().drawString(519, wspqy += 30, questy.get(i), c); } Fonts.print18().drawString(530, 555, "Powrót do gry", c); g.drawRoundRect(520, 545, 200, 30, 6); Fonts.print18().drawString(510, 595, "C O N C E P T Q U E S T S", c); } public QuestsState(int state) { } public QuestsState() { } public int getID() { return 5; } }
Kalwador/Java-2D-Game
LegendaryAdventure/src/states/QuestsState.java
1,897
//Wytworzenie własnej czcionki
line_comment
pl
package states; import gameUtils.Fonts; import org.newdawn.slick.Color; import java.util.ArrayList; import org.lwjgl.input.Mouse; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.Input; import org.newdawn.slick.MouseListener; import org.newdawn.slick.SlickException; import org.newdawn.slick.state.BasicGameState; import org.newdawn.slick.state.StateBasedGame; public class QuestsState extends BasicGameState { String mouse; String onScreenLoc; gameUtils.Fonts fonts; ArrayList<String> questy = new ArrayList<>(); int bp = 0; Color c = Color.black; String actualScr; //wsp pocz suwaka int suwX = 790; int suwY = 174; @Override public void init(GameContainer gc, StateBasedGame sbg) throws SlickException { mouse = ""; onScreenLoc = " "; //Wytworzenie własnej <SUF> fonts = new gameUtils.Fonts(); questy.add("Zemsta na bandytach"); questy.add("Gdzie uciekl herszt"); questy.add("Obozowisko na polach"); questy.add("Wyprawa po futra."); questy.add("Polowanie na lisy"); questy.add("Zaginiony ładunek"); questy.add("Pradawna krypa"); questy.add("Smocze ostrze"); questy.add("Gdzie są bandyci"); questy.add("Oboz troli"); questy.add("Zaginiona paczka"); questy.add("Bezdomny pies"); questy.add("Rybobranie"); } @Override public void update(GameContainer gc, StateBasedGame sbg, int i) throws SlickException { Input input = gc.getInput(); int xpos = Mouse.getX(); int ypos = Mouse.getY(); int scrolling = Mouse.getDWheel(); mouse = "x= " + xpos + " y=" + ypos; onScreenLoc = "x= " + xpos + " y=" + Math.abs(720-ypos); if (input.isKeyPressed(Input.KEY_ESCAPE) || input.isKeyPressed(Input.KEY_M)) { sbg.enterState(1); } //powrót do menu if (((xpos > 520 && xpos < 720) && (ypos > 145 && ypos < 175)) || /* X okna*/((xpos > 779 && xpos < 812) && (ypos > 606 && ypos < 636))) { if (input.isMouseButtonDown(0)) { sbg.enterState(1); } } //wyjście // if ((xpos > 470 && xpos < 630) && (ypos > 280 && ypos < 312)) { // if (input.isMouseButtonDown(0)) { // System.exit(0); // } // } //Przewijanie do góry - scrool myszy, klawisz, przycisk góra if ((scrolling > 0) || input.isKeyPressed(Input.KEY_UP) || ((xpos > 788 && xpos < 814) && (ypos > 546 && ypos < 569) && (input.isMousePressed(0)))) { if (bp > 0) { bp--; suwY -= 24; } } //Przewijanie do dołu - scrool myszy, klawisz, przycisk dół if ((scrolling < 0) || input.isKeyPressed(Input.KEY_DOWN) || ((xpos > 788 && xpos < 814) && (ypos > 97 && ypos < 124) && (input.isMousePressed(0)))) { if (bp < (questy.size() - 11)) { bp++; suwY += 24; } } } @Override public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException { //Tło sceny - rozmyty printscreen actualScr = screenBlur.ScreenClass.screenNumber(); Image skrinGB = new Image(actualScr); g.drawImage(skrinGB, 0, 0); //Okno questa Image menuW = new Image("graphic/menu/QuestNew.png"); g.drawImage(menuW, 0, 0); //Suwaczek Image skrolus = new Image("graphic/menu/skrolus.png"); g.drawImage(skrolus, suwX, suwY); Fonts.print18().drawString(100, 30, onScreenLoc); Fonts.print18().drawString(100, 10, mouse); Fonts.print18().drawString(100, 30, " bieżący indeks " + String.valueOf(bp)); Fonts.print18().drawString(100, 50, " rozmiar listy " + String.valueOf(questy.size())); // g.drawString("Opcje", 520, 375); // g.drawRoundRect(520, 375, 300, 60, 6); // g.drawString("Twórcy", 520, 445); // g.drawRoundRect(520, 445, 300, 60, 6); // g.drawString("Wyjście", 520, 515); // g.drawRoundRect(520, 515, 300, 60, 6); Fonts.print18().drawString(600, 100, "Questy");// (przewijanie strzalkami)"); int wspqy = 175; // wsp pocz y wyświetlania listy for (int i = bp; i < bp + 11; i++) { Fonts.print18().drawString(519, wspqy += 30, questy.get(i), c); } Fonts.print18().drawString(530, 555, "Powrót do gry", c); g.drawRoundRect(520, 545, 200, 30, 6); Fonts.print18().drawString(510, 595, "C O N C E P T Q U E S T S", c); } public QuestsState(int state) { } public QuestsState() { } public int getID() { return 5; } }
9959_0
/* Kamil Matejuk */ import java.io.Serializable; public class BinarySearchTree<T> implements Serializable { TreeNode root; /** * zerowanie aktualnego drzewa */ public BinarySearchTree(){ root = null; } /** * Wstawienie do drzewa nowego węzła o wartości value * @param value */ public void insertTreeNode(T value) { if (value != null) { TreeNode node = new TreeNode(value); if (root == null) { root = node; System.out.println("Element \"" + value + "\" was added succesfully"); } else { TreeNode nd = root; TreeNode parent; while (true) { parent = nd; if(node.compareTo(nd.value)>0){ nd = nd.rightChild; if (nd == null) { parent.setRightChild(node); System.out.println("Element \"" + value + "\" was added succesfully"); return; } } else { nd = nd.leftChild; if (nd == null) { parent.setLeftChild(node); System.out.println("Element \"" + value + "\" was added succesfully"); return; } } } } } } /** * usunęcie węzła o wartości value * @param value * @return prawda gdy usunięto, fałsz gdy nie */ public boolean deleteTreeNode(T value) { //TODO nie działa, cały czas zwraca false //http://www.algolist.net/Data_structures/Binary_search_tree/Removal if (root == null || value == null) { return false; } else { if (root.value.equals(value)){ TreeNode auxRoot = new TreeNode(0); auxRoot.setLeftChild(root); boolean result = root.remove(value, auxRoot); root = auxRoot.leftChild; return result; } else { return root.remove(value, null); } } } /** * wyszukanie rekurencyjnie węzła o warośi value * @param node wezeł który rozpatrujemy * @param value wartość której szukamy * @return prawda gdy znaleziono, fałsz gdy nie */ public boolean searchTreeNode(TreeNode node, T value){ if(node == null || value == null){ return false; } else if(node.value.equals(value)){ return true; } else if(node.compareTo(value)<0){ return searchTreeNode(node.rightChild, value); } else { return searchTreeNode(node.leftChild, value); } } }
KamilMatejuk/University
Java/Binary_Search_Tree/BinarySearchTree.java
783
/** * zerowanie aktualnego drzewa */
block_comment
pl
/* Kamil Matejuk */ import java.io.Serializable; public class BinarySearchTree<T> implements Serializable { TreeNode root; /** * zerowanie aktualnego drzewa <SUF>*/ public BinarySearchTree(){ root = null; } /** * Wstawienie do drzewa nowego węzła o wartości value * @param value */ public void insertTreeNode(T value) { if (value != null) { TreeNode node = new TreeNode(value); if (root == null) { root = node; System.out.println("Element \"" + value + "\" was added succesfully"); } else { TreeNode nd = root; TreeNode parent; while (true) { parent = nd; if(node.compareTo(nd.value)>0){ nd = nd.rightChild; if (nd == null) { parent.setRightChild(node); System.out.println("Element \"" + value + "\" was added succesfully"); return; } } else { nd = nd.leftChild; if (nd == null) { parent.setLeftChild(node); System.out.println("Element \"" + value + "\" was added succesfully"); return; } } } } } } /** * usunęcie węzła o wartości value * @param value * @return prawda gdy usunięto, fałsz gdy nie */ public boolean deleteTreeNode(T value) { //TODO nie działa, cały czas zwraca false //http://www.algolist.net/Data_structures/Binary_search_tree/Removal if (root == null || value == null) { return false; } else { if (root.value.equals(value)){ TreeNode auxRoot = new TreeNode(0); auxRoot.setLeftChild(root); boolean result = root.remove(value, auxRoot); root = auxRoot.leftChild; return result; } else { return root.remove(value, null); } } } /** * wyszukanie rekurencyjnie węzła o warośi value * @param node wezeł który rozpatrujemy * @param value wartość której szukamy * @return prawda gdy znaleziono, fałsz gdy nie */ public boolean searchTreeNode(TreeNode node, T value){ if(node == null || value == null){ return false; } else if(node.value.equals(value)){ return true; } else if(node.compareTo(value)<0){ return searchTreeNode(node.rightChild, value); } else { return searchTreeNode(node.leftChild, value); } } }
5157_0
public class Student{ //atrybuty: String name; int age; String ID; boolean isValid; int semesterNum; double avgGrade; //metody: public void sayHello(){ System.out.println("Hello!"); } public void displayName(){ System.out.println("I'm "+ this.name); } public void displayStudentData(){ System.out.println("I'm "+ this.name + "\nSemester "+ this.semesterNum + "\nAvg grade "+ this.avgGrade); } public void displayAge(){ System.out.println("I'm "+ this.age + " years old"); } public void changeIDStatus(){ this.isValid = !isValid; } public void displayStudentStatus(){ System.out.println("My name is " + this.name + "my ID " + this.ID + "is " + this.isValid); } //w momencie uruchomienia programu mogę przekazać dane public static void main(String[] args){ Student s1 = new Student(); //konstruktor sam się zrobił s1.name = "Ola"; s1.age = 20; s1.ID = "s123234"; s1.isValid = true; s1.semesterNum = 2; s1.avgGrade = 3.5; s1.sayHello(); s1.displayStudentData(); s1.changeIDStatus(); s1.displayStudentStatus(); } }
Kamila-Kapinos/pp3
02-ClassesAndObjects/classes_and_objects/Student.java
437
//w momencie uruchomienia programu mogę przekazać dane
line_comment
pl
public class Student{ //atrybuty: String name; int age; String ID; boolean isValid; int semesterNum; double avgGrade; //metody: public void sayHello(){ System.out.println("Hello!"); } public void displayName(){ System.out.println("I'm "+ this.name); } public void displayStudentData(){ System.out.println("I'm "+ this.name + "\nSemester "+ this.semesterNum + "\nAvg grade "+ this.avgGrade); } public void displayAge(){ System.out.println("I'm "+ this.age + " years old"); } public void changeIDStatus(){ this.isValid = !isValid; } public void displayStudentStatus(){ System.out.println("My name is " + this.name + "my ID " + this.ID + "is " + this.isValid); } //w momencie <SUF> public static void main(String[] args){ Student s1 = new Student(); //konstruktor sam się zrobił s1.name = "Ola"; s1.age = 20; s1.ID = "s123234"; s1.isValid = true; s1.semesterNum = 2; s1.avgGrade = 3.5; s1.sayHello(); s1.displayStudentData(); s1.changeIDStatus(); s1.displayStudentStatus(); } }
6164_1
public class App { public static void main(String[] args) throws Exception { //pagingManager parameters int RAM_CAPACITY = 50; int VIRTUAL_MEMORY_CAPACITY = 500; // int ALGORITHM = 1; //procesQueue parameters int QUEUE_SIZE = 2000; //proces parameters int PROCES_SIZE = 5; int PROCES_OFFSET = 5; ProcessesQueue queue1 = new ProcessesQueue(QUEUE_SIZE, VIRTUAL_MEMORY_CAPACITY, PROCES_SIZE, PROCES_OFFSET); ProcessesQueue queue2 = new ProcessesQueue(queue1); ProcessesQueue queue3 = new ProcessesQueue(queue1); ProcessesQueue queue4 = new ProcessesQueue(queue1); ProcessesQueue queue5 = new ProcessesQueue(queue1); PagingManager randomManager = new PagingManager(RAM_CAPACITY, VIRTUAL_MEMORY_CAPACITY, 1, queue1.processArray); PagingManager fifoManager = new PagingManager(RAM_CAPACITY, VIRTUAL_MEMORY_CAPACITY, 2, queue2.processArray); PagingManager optManager = new PagingManager(RAM_CAPACITY, VIRTUAL_MEMORY_CAPACITY, 3, queue3.processArray); PagingManager lruManager = new PagingManager(RAM_CAPACITY, VIRTUAL_MEMORY_CAPACITY, 4, queue4.processArray); PagingManager alruManager = new PagingManager(RAM_CAPACITY, VIRTUAL_MEMORY_CAPACITY, 5, queue5.processArray); } } // Main - klasa służąca do wywołania całej symulacji i określenia jej parametrów // Proces - obiekt zawierający w sobie tablicę liczb, będących referencjami do konkretnych obszarów w pamięci // * Lokalność odwolan - będziemy prawdopodobnie brali po kilka sąsiadujących ramek czy coś takiego // RAM - obiekt symulujący pamięć ram, będzie miał w sobie tablicę o sztywno określonej pojemności i indeksach, którym będziemy przypisywać, bądź odpisywać numery indeksów bloków w pamięci // VirtualMemory - również obiekt mający w sobie tablicę, większą niż ta w RAM, w której od początku będziemy mieli sztywno wygenerowane dane indeksowane po kolei // ReferenceManager, czyli obiekt posiadający tablicę par liczb, gdzie po otrzymaniu żądań będzie parował miejsca w Ramie z danymi w VirtualMemory, bądź też rozkazywał RAMowi zwolnić sloty zgodnie z algorytmami // Klasy algorytmów, których parametrami będzie oczywiście nasz menadżer // RAM - potrzebujemy znac kolejnosc zaladowania stron, znac ilosc wywolan indywidualnej strony
Kamotek/pwr-computer-science-courses
Semester2/Operation systems/SO3/SO3/src/App.java
854
// Main - klasa służąca do wywołania całej symulacji i określenia jej parametrów
line_comment
pl
public class App { public static void main(String[] args) throws Exception { //pagingManager parameters int RAM_CAPACITY = 50; int VIRTUAL_MEMORY_CAPACITY = 500; // int ALGORITHM = 1; //procesQueue parameters int QUEUE_SIZE = 2000; //proces parameters int PROCES_SIZE = 5; int PROCES_OFFSET = 5; ProcessesQueue queue1 = new ProcessesQueue(QUEUE_SIZE, VIRTUAL_MEMORY_CAPACITY, PROCES_SIZE, PROCES_OFFSET); ProcessesQueue queue2 = new ProcessesQueue(queue1); ProcessesQueue queue3 = new ProcessesQueue(queue1); ProcessesQueue queue4 = new ProcessesQueue(queue1); ProcessesQueue queue5 = new ProcessesQueue(queue1); PagingManager randomManager = new PagingManager(RAM_CAPACITY, VIRTUAL_MEMORY_CAPACITY, 1, queue1.processArray); PagingManager fifoManager = new PagingManager(RAM_CAPACITY, VIRTUAL_MEMORY_CAPACITY, 2, queue2.processArray); PagingManager optManager = new PagingManager(RAM_CAPACITY, VIRTUAL_MEMORY_CAPACITY, 3, queue3.processArray); PagingManager lruManager = new PagingManager(RAM_CAPACITY, VIRTUAL_MEMORY_CAPACITY, 4, queue4.processArray); PagingManager alruManager = new PagingManager(RAM_CAPACITY, VIRTUAL_MEMORY_CAPACITY, 5, queue5.processArray); } } // Main - <SUF> // Proces - obiekt zawierający w sobie tablicę liczb, będących referencjami do konkretnych obszarów w pamięci // * Lokalność odwolan - będziemy prawdopodobnie brali po kilka sąsiadujących ramek czy coś takiego // RAM - obiekt symulujący pamięć ram, będzie miał w sobie tablicę o sztywno określonej pojemności i indeksach, którym będziemy przypisywać, bądź odpisywać numery indeksów bloków w pamięci // VirtualMemory - również obiekt mający w sobie tablicę, większą niż ta w RAM, w której od początku będziemy mieli sztywno wygenerowane dane indeksowane po kolei // ReferenceManager, czyli obiekt posiadający tablicę par liczb, gdzie po otrzymaniu żądań będzie parował miejsca w Ramie z danymi w VirtualMemory, bądź też rozkazywał RAMowi zwolnić sloty zgodnie z algorytmami // Klasy algorytmów, których parametrami będzie oczywiście nasz menadżer // RAM - potrzebujemy znac kolejnosc zaladowania stron, znac ilosc wywolan indywidualnej strony
4080_4
/*************************************************************************** * (C) Copyright 2003-2018 - Stendhal * *************************************************************************** *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ package games.stendhal.server.maps.krakow.tavern; import java.util.LinkedList; import java.util.List; import java.util.Map; import games.stendhal.server.core.config.ZoneConfigurator; import games.stendhal.server.core.engine.StendhalRPZone; import games.stendhal.server.core.pathfinder.FixedPath; import games.stendhal.server.core.pathfinder.Node; import games.stendhal.server.entity.npc.SpeakerNPC; /** * Build a NPC * * @author KarajuSs */ public class KarczmarkaNPC implements ZoneConfigurator { /** * Configure a zone. * * @param zone The zone to be configured. * @param attributes Configuration attributes. */ @Override public void configureZone(final StendhalRPZone zone, final Map<String, String> attributes) { buildNPC(zone); } private void buildNPC(final StendhalRPZone zone) { final SpeakerNPC npc = new SpeakerNPC("Granny Alina") { @Override protected void createPath() { final List<Node> nodes = new LinkedList<Node>(); nodes.add(new Node(33, 20)); nodes.add(new Node(33, 5)); nodes.add(new Node(35, 5)); nodes.add(new Node(35, 20)); setPath(new FixedPath(nodes, true)); } @Override protected void createDialog() { addGreeting("Witaj w starej karczmie #'U Babci Aliny'! Co potrzebujesz?"); addJob("Jestem karczmarką w swej tawernie."); addHelp("Dobrze, że się pytasz. Aktualnie eksperymentuje, aby zrobić magiczną grzybową zupę. Powiedz mi tylko #'zadanie', a Ci powiem co mógłbyś dla mnie zrobić."); addOffer("Jeżeli wykonasz dla mnie #'zadanie' to będę mogła dla Ciebie robić me specjalne danie!"); // borowik, pieczarka, opieńka, pieprznik jadalny, cebula, marchew, por // powtórka co 7 min. addGoodbye(); } }; npc.setDescription("Oto babcia Alina, jest znana ze swojej wspaniałej kuchni domowej."); npc.setEntityClass("granmanpc"); npc.setPosition(35, 20); zone.add(npc); } }
KarajuSs/PolskaGRA
src/games/stendhal/server/maps/krakow/tavern/KarczmarkaNPC.java
932
// powtórka co 7 min.
line_comment
pl
/*************************************************************************** * (C) Copyright 2003-2018 - Stendhal * *************************************************************************** *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ package games.stendhal.server.maps.krakow.tavern; import java.util.LinkedList; import java.util.List; import java.util.Map; import games.stendhal.server.core.config.ZoneConfigurator; import games.stendhal.server.core.engine.StendhalRPZone; import games.stendhal.server.core.pathfinder.FixedPath; import games.stendhal.server.core.pathfinder.Node; import games.stendhal.server.entity.npc.SpeakerNPC; /** * Build a NPC * * @author KarajuSs */ public class KarczmarkaNPC implements ZoneConfigurator { /** * Configure a zone. * * @param zone The zone to be configured. * @param attributes Configuration attributes. */ @Override public void configureZone(final StendhalRPZone zone, final Map<String, String> attributes) { buildNPC(zone); } private void buildNPC(final StendhalRPZone zone) { final SpeakerNPC npc = new SpeakerNPC("Granny Alina") { @Override protected void createPath() { final List<Node> nodes = new LinkedList<Node>(); nodes.add(new Node(33, 20)); nodes.add(new Node(33, 5)); nodes.add(new Node(35, 5)); nodes.add(new Node(35, 20)); setPath(new FixedPath(nodes, true)); } @Override protected void createDialog() { addGreeting("Witaj w starej karczmie #'U Babci Aliny'! Co potrzebujesz?"); addJob("Jestem karczmarką w swej tawernie."); addHelp("Dobrze, że się pytasz. Aktualnie eksperymentuje, aby zrobić magiczną grzybową zupę. Powiedz mi tylko #'zadanie', a Ci powiem co mógłbyś dla mnie zrobić."); addOffer("Jeżeli wykonasz dla mnie #'zadanie' to będę mogła dla Ciebie robić me specjalne danie!"); // borowik, pieczarka, opieńka, pieprznik jadalny, cebula, marchew, por // powtórka co <SUF> addGoodbye(); } }; npc.setDescription("Oto babcia Alina, jest znana ze swojej wspaniałej kuchni domowej."); npc.setEntityClass("granmanpc"); npc.setPosition(35, 20); zone.add(npc); } }
4469_5
import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class PO_lab2_Swing { private JPanel Panel1; private JButton startButton; private JButton stopButton; private JLabel LabA; private JTextField textFieldA; private JTextField textFieldB; private JLabel WynikLab; private JLabel DataLabel; double stopnie; double wynik; // public static void main(String[] args) { // PO_lab2_Swing okienko = new PO_lab2_Swing(); // okienko.setVisible(true);//wyswietla ramke // } // public PO_lab2_Swing() // { // super("Moja pierwsza aplikacja"); // this.setContentPane(this.Panel1);//wysw. na ekranie // this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//zamkniecie okna // this.setSize(300, 400);//rozmiar okienka // this.pack();//pozwala spakować wszystko i dostosuje wielkość // } //sposob 2 public static void main(String[] args) { PO_lab2_Swing okienko2 = new PO_lab2_Swing(); } public PO_lab2_Swing() { JFrame frame = new JFrame("Moja pierwsza apka"); frame.setContentPane(this.Panel1); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.setSize(500, 500); // frame.pack(); stopButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { stopnie = Double.parseDouble(textFieldA.getText()); wynik = stopnie+32; WynikLab.setText(String.valueOf(stopnie)+" na Fahreneity to: "+ String.valueOf(wynik)); } }); } }
KarolWojnar/ProgramowanieOb
src/PO_lab2_Swing.java
578
// this.pack();//pozwala spakować wszystko i dostosuje wielkość
line_comment
pl
import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class PO_lab2_Swing { private JPanel Panel1; private JButton startButton; private JButton stopButton; private JLabel LabA; private JTextField textFieldA; private JTextField textFieldB; private JLabel WynikLab; private JLabel DataLabel; double stopnie; double wynik; // public static void main(String[] args) { // PO_lab2_Swing okienko = new PO_lab2_Swing(); // okienko.setVisible(true);//wyswietla ramke // } // public PO_lab2_Swing() // { // super("Moja pierwsza aplikacja"); // this.setContentPane(this.Panel1);//wysw. na ekranie // this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//zamkniecie okna // this.setSize(300, 400);//rozmiar okienka // this.pack();//pozwala spakować <SUF> // } //sposob 2 public static void main(String[] args) { PO_lab2_Swing okienko2 = new PO_lab2_Swing(); } public PO_lab2_Swing() { JFrame frame = new JFrame("Moja pierwsza apka"); frame.setContentPane(this.Panel1); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.setSize(500, 500); // frame.pack(); stopButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { stopnie = Double.parseDouble(textFieldA.getText()); wynik = stopnie+32; WynikLab.setText(String.valueOf(stopnie)+" na Fahreneity to: "+ String.valueOf(wynik)); } }); } }
6149_0
import java.io.IOException; import java.util.*; public class World { public static void main( String[] args ) throws InterruptedException, IOException { int width = 20; int height = 20; int moveEnergy = 1; int grassEnregy = 5; int startEnergy = 5; double jungleRatio = 0.4; int firstAnimals = 10; int amountofGrass = 50; Simulation pierwsza = new Simulation(width,height,moveEnergy,grassEnregy,startEnergy,jungleRatio, firstAnimals, amountofGrass); MapVisualizer visualizer = new MapVisualizer(pierwsza.getMap()); int days = 1000; for(int i = 0; i< days; i++) { System.out.println(visualizer.draw(new Vector2d(0, 0), new Vector2d(19, 19))); pierwsza.oneDay(); Thread.sleep(100); } } } // przepraszam ze nie nakłada się jedno na drugie ale nie potrafiłem sobie z tym poradzić
Karolk99/ProjektPO
src/World.java
320
// przepraszam ze nie nakłada się jedno na drugie ale nie potrafiłem sobie z tym poradzić
line_comment
pl
import java.io.IOException; import java.util.*; public class World { public static void main( String[] args ) throws InterruptedException, IOException { int width = 20; int height = 20; int moveEnergy = 1; int grassEnregy = 5; int startEnergy = 5; double jungleRatio = 0.4; int firstAnimals = 10; int amountofGrass = 50; Simulation pierwsza = new Simulation(width,height,moveEnergy,grassEnregy,startEnergy,jungleRatio, firstAnimals, amountofGrass); MapVisualizer visualizer = new MapVisualizer(pierwsza.getMap()); int days = 1000; for(int i = 0; i< days; i++) { System.out.println(visualizer.draw(new Vector2d(0, 0), new Vector2d(19, 19))); pierwsza.oneDay(); Thread.sleep(100); } } } // przepraszam ze <SUF>
3496_1
import javafx.scene.control.Alert; /** * <b>Alert</b> zawierający instrukcje obsługi. */ public class Manual extends Alert { public Manual() { super(AlertType.INFORMATION); this.setGraphic(null); // usuwa ikonkę "i" z nagłówka this.setTitle("Instrukcja"); this.setHeaderText("Instrukcja"); this.setContentText( "Aby zrobić figurę, trzeba wybrać jakąś z menu i przeciągnąć po tym białym. Tak jak w Ms Paint.\n\n" + "Aby oznaczyć figurę jako aktywną, trzeba ją kliknąć lewym przyciskiem myszy.\n\n" + "Aby przesunąć figurę trzeba ją oznaczyć jako aktywną, następnie złapać i przeciągnąć.\n\n" + "Aby zmnienić rozmiar figury trzeba ją oznaczyć jako aktywną, najechać na nią myszką i pokręcić kółkiem.\n\n" + "Aby obrócić figurę trzeba ją oznaczyć jako aktywną, i przytrzymać Q lub E.\n\n" + "Aby zmienić kolor figury trzeba ją oznaczyć jako aktywną i kliknąć prawym i tam już git.\n\n" + "Trójkąt można złapać za rogi by zmienić kształt.\n\n" + "Można jeszcze usunąć figurę klikająć Delejt na klawiaturze."); } }
Kawyn/studia
kurs programowania/lista 5/Manual.java
497
// usuwa ikonkę "i" z nagłówka
line_comment
pl
import javafx.scene.control.Alert; /** * <b>Alert</b> zawierający instrukcje obsługi. */ public class Manual extends Alert { public Manual() { super(AlertType.INFORMATION); this.setGraphic(null); // usuwa ikonkę <SUF> this.setTitle("Instrukcja"); this.setHeaderText("Instrukcja"); this.setContentText( "Aby zrobić figurę, trzeba wybrać jakąś z menu i przeciągnąć po tym białym. Tak jak w Ms Paint.\n\n" + "Aby oznaczyć figurę jako aktywną, trzeba ją kliknąć lewym przyciskiem myszy.\n\n" + "Aby przesunąć figurę trzeba ją oznaczyć jako aktywną, następnie złapać i przeciągnąć.\n\n" + "Aby zmnienić rozmiar figury trzeba ją oznaczyć jako aktywną, najechać na nią myszką i pokręcić kółkiem.\n\n" + "Aby obrócić figurę trzeba ją oznaczyć jako aktywną, i przytrzymać Q lub E.\n\n" + "Aby zmienić kolor figury trzeba ją oznaczyć jako aktywną i kliknąć prawym i tam już git.\n\n" + "Trójkąt można złapać za rogi by zmienić kształt.\n\n" + "Można jeszcze usunąć figurę klikająć Delejt na klawiaturze."); } }
5159_1
package com.kodilla.rps; import static com.kodilla.rps.RpsRunner.player1; import static com.kodilla.rps.RpsRunner.player2; public class GameRules { /* final static private int rules[][] = { { 0,-1, 1}, { 1, 0,-1}, {-1, 1, 0} };*/ final static private int[][] rules = { { 0,-1, 1,-1, 1}, { 1, 0,-1, 1,-1}, {-1, 1, 0,-1, 1}, { 1,-1, 1, 0,-1}, {-1, 1,-1, 1, 0} }; private static int numberOfRounds; public static void whoWins(String player1Move, String player2Move) { int score = rules[Integer.parseInt(player1Move)-1][Integer.parseInt(player2Move)-1]; if(score == 1) { player1.addPoint(); System.out.println("Point for " + player1.getName()); } else if(score == -1) { player2.addPoint(); System.out.println("Point for " + player2.getName()); } else { System.out.println("Draw!"); } System.out.println(); } public static void setNumberOfRounds(int x) { numberOfRounds = x; //dlaczego nie mogę tu użyć this? } public static int getNumberOfRounds() { return numberOfRounds; } }
KayakOnWheels/Grzegorz-Gajewski-Kodilla-Java
kodilla-rps/src/main/java/com/kodilla/rps/GameRules.java
434
//dlaczego nie mogę tu użyć this?
line_comment
pl
package com.kodilla.rps; import static com.kodilla.rps.RpsRunner.player1; import static com.kodilla.rps.RpsRunner.player2; public class GameRules { /* final static private int rules[][] = { { 0,-1, 1}, { 1, 0,-1}, {-1, 1, 0} };*/ final static private int[][] rules = { { 0,-1, 1,-1, 1}, { 1, 0,-1, 1,-1}, {-1, 1, 0,-1, 1}, { 1,-1, 1, 0,-1}, {-1, 1,-1, 1, 0} }; private static int numberOfRounds; public static void whoWins(String player1Move, String player2Move) { int score = rules[Integer.parseInt(player1Move)-1][Integer.parseInt(player2Move)-1]; if(score == 1) { player1.addPoint(); System.out.println("Point for " + player1.getName()); } else if(score == -1) { player2.addPoint(); System.out.println("Point for " + player2.getName()); } else { System.out.println("Draw!"); } System.out.println(); } public static void setNumberOfRounds(int x) { numberOfRounds = x; //dlaczego nie <SUF> } public static int getNumberOfRounds() { return numberOfRounds; } }
10518_0
package petrinet; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import petrinet.models.MutexAndTransitions; import petrinet.models.State; import petrinet.resolvers.PetriNetFireResolver; import petrinet.resolvers.ReachableStatesResolver; import petrinet.resolvers.TransitionMutexResolver; public class PetriNet<T> { private State<T> placesTokens; private TransitionMutexResolver<T> mutexResolver; public PetriNet(Map<T, Integer> initial, boolean fair) { this.placesTokens = new State<>(initial); this.mutexResolver = new TransitionMutexResolver<>(placesTokens, fair); } public Set<Map<T, Integer>> reachable(Collection<Transition<T>> transitions) { ReachableStatesResolver<T> resolver = new ReachableStatesResolver<>(placesTokens, new ArrayList<>(transitions)); return resolver.findAll(); } public Transition<T> fire(Collection<Transition<T>> transitions) throws InterruptedException { List<Transition<T>> transitionsList = new ArrayList<>(transitions); MutexAndTransitions<T> actualMutexAndTransitions = mutexResolver.getMutex(transitionsList); try { actualMutexAndTransitions .getMutex() .acquire(); } catch (InterruptedException e) { mutexResolver.removeFromQueue(actualMutexAndTransitions); throw e; } return fireReleaseAndSave(transitionsList, actualMutexAndTransitions); } private Transition<T> fireReleaseAndSave(List<Transition<T>> transitionsList, MutexAndTransitions<T> actualMutexAndTransitions) { PetriNetFireResolver<T> fireResolver = new PetriNetFireResolver<>(placesTokens); Transition<T> transitionToFire = placesTokens .findFirstTransitionEnabled(transitionsList) .get(); // zawsze sie znajdzie bo dodaje do kolejki placesTokens = fireResolver.fire(transitionToFire); cleanMutex(actualMutexAndTransitions); return transitionToFire; } private void cleanMutex(MutexAndTransitions<T> actualMutexAndTransitions) { mutexResolver.removeFromQueue(actualMutexAndTransitions); mutexResolver.updateStateAndReleaseNext(placesTokens); } }
KimLoanSA/mimuw
sem3/pw/abrams/petri-net/src/petrinet/PetriNet.java
701
// zawsze sie znajdzie bo dodaje do kolejki
line_comment
pl
package petrinet; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import petrinet.models.MutexAndTransitions; import petrinet.models.State; import petrinet.resolvers.PetriNetFireResolver; import petrinet.resolvers.ReachableStatesResolver; import petrinet.resolvers.TransitionMutexResolver; public class PetriNet<T> { private State<T> placesTokens; private TransitionMutexResolver<T> mutexResolver; public PetriNet(Map<T, Integer> initial, boolean fair) { this.placesTokens = new State<>(initial); this.mutexResolver = new TransitionMutexResolver<>(placesTokens, fair); } public Set<Map<T, Integer>> reachable(Collection<Transition<T>> transitions) { ReachableStatesResolver<T> resolver = new ReachableStatesResolver<>(placesTokens, new ArrayList<>(transitions)); return resolver.findAll(); } public Transition<T> fire(Collection<Transition<T>> transitions) throws InterruptedException { List<Transition<T>> transitionsList = new ArrayList<>(transitions); MutexAndTransitions<T> actualMutexAndTransitions = mutexResolver.getMutex(transitionsList); try { actualMutexAndTransitions .getMutex() .acquire(); } catch (InterruptedException e) { mutexResolver.removeFromQueue(actualMutexAndTransitions); throw e; } return fireReleaseAndSave(transitionsList, actualMutexAndTransitions); } private Transition<T> fireReleaseAndSave(List<Transition<T>> transitionsList, MutexAndTransitions<T> actualMutexAndTransitions) { PetriNetFireResolver<T> fireResolver = new PetriNetFireResolver<>(placesTokens); Transition<T> transitionToFire = placesTokens .findFirstTransitionEnabled(transitionsList) .get(); // zawsze sie <SUF> placesTokens = fireResolver.fire(transitionToFire); cleanMutex(actualMutexAndTransitions); return transitionToFire; } private void cleanMutex(MutexAndTransitions<T> actualMutexAndTransitions) { mutexResolver.removeFromQueue(actualMutexAndTransitions); mutexResolver.updateStateAndReleaseNext(placesTokens); } }
5288_0
/** * Typ wyliczeniowy reprezentujący kolory */ public enum Color { BLACK, WHITE, GREEN, YELLOW, RED, ORANGE, PINK, ; @Override public String toString() { return name().substring(0, 1); } /** * Metoda main pozwalająca zobaczyć jak prezentowane są * poszczególne kolory. */ public static void main(String[] args) { for ( Color color : Color.values() ) { System.out.println( color.name() + " -> " + color ); } } }
Kimel-PK/Java_2021-2022
Zadanie 05/src/Color.java
181
/** * Typ wyliczeniowy reprezentujący kolory */
block_comment
pl
/** * Typ wyliczeniowy reprezentujący <SUF>*/ public enum Color { BLACK, WHITE, GREEN, YELLOW, RED, ORANGE, PINK, ; @Override public String toString() { return name().substring(0, 1); } /** * Metoda main pozwalająca zobaczyć jak prezentowane są * poszczególne kolory. */ public static void main(String[] args) { for ( Color color : Color.values() ) { System.out.println( color.name() + " -> " + color ); } } }
9022_0
package First; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; public class Kolekcje { public static void main(String[] args) { System.out.println("ArrayList to lista, która pozwala przechowywać elementy zgodne z zadeklarowanym typem"); List<String> lista = new ArrayList<>(); lista.add("Jabłko"); lista.add("Banan"); lista.add("Gruszka"); System.out.println(lista); // [Jabłko, Banan, Gruszka] System.out.println("HashSet to kolekcja, która przechowuje unikalne elementy w dowolnej kolejności"); Set<Integer> zbior = new HashSet<>(); zbior.add(1); zbior.add(2); zbior.add(1); // Ten element zostanie zignorowany, ponieważ jest duplikatem System.out.println(zbior); // [1, 2] System.out.println("HashMap to kolekcja typu klucz-wartość, która przechowuje pary obiektów"); Map<String, Integer> mapa = new HashMap<>(); mapa.put("Jan", 25); mapa.put("Anna", 30); mapa.put("Marek", 28); System.out.println("Wiek Anny: " + mapa.get("Anna")); // Wiek Anny: 30 System.out.println("LinkedList to lista dwukierunkowa, która pozwala na efektywne dodawanie i usuwanie elementów na początku, końcu i w środku listy."); // Wiek Anny: 30 List<String> linkedLista = new LinkedList<>(); linkedLista.add("Pierwszy"); linkedLista.add("Drugi"); linkedLista.add("Trzeci"); System.out.println(linkedLista); // [Pierwszy, Drugi, Trzeci] linkedLista.remove(1); // Usuwa drugi element System.out.println(linkedLista); // [Pierwszy, Trzeci] System.out.println("TreeSet to kolekcja, która przechowuje unikalne elementy w porządku naturalnym lub według dostarczonego komparatora"); Set<String> treeSet = new TreeSet<>(); treeSet.add("C"); treeSet.add("A"); treeSet.add("B"); System.out.println(treeSet); // [A, B, C] (uporządkowane alfabetycznie) } }
Kinggred/AdvancedJavaClass
src/First/Kolekcje.java
745
// [Jabłko, Banan, Gruszka]
line_comment
pl
package First; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; public class Kolekcje { public static void main(String[] args) { System.out.println("ArrayList to lista, która pozwala przechowywać elementy zgodne z zadeklarowanym typem"); List<String> lista = new ArrayList<>(); lista.add("Jabłko"); lista.add("Banan"); lista.add("Gruszka"); System.out.println(lista); // [Jabłko, Banan, <SUF> System.out.println("HashSet to kolekcja, która przechowuje unikalne elementy w dowolnej kolejności"); Set<Integer> zbior = new HashSet<>(); zbior.add(1); zbior.add(2); zbior.add(1); // Ten element zostanie zignorowany, ponieważ jest duplikatem System.out.println(zbior); // [1, 2] System.out.println("HashMap to kolekcja typu klucz-wartość, która przechowuje pary obiektów"); Map<String, Integer> mapa = new HashMap<>(); mapa.put("Jan", 25); mapa.put("Anna", 30); mapa.put("Marek", 28); System.out.println("Wiek Anny: " + mapa.get("Anna")); // Wiek Anny: 30 System.out.println("LinkedList to lista dwukierunkowa, która pozwala na efektywne dodawanie i usuwanie elementów na początku, końcu i w środku listy."); // Wiek Anny: 30 List<String> linkedLista = new LinkedList<>(); linkedLista.add("Pierwszy"); linkedLista.add("Drugi"); linkedLista.add("Trzeci"); System.out.println(linkedLista); // [Pierwszy, Drugi, Trzeci] linkedLista.remove(1); // Usuwa drugi element System.out.println(linkedLista); // [Pierwszy, Trzeci] System.out.println("TreeSet to kolekcja, która przechowuje unikalne elementy w porządku naturalnym lub według dostarczonego komparatora"); Set<String> treeSet = new TreeSet<>(); treeSet.add("C"); treeSet.add("A"); treeSet.add("B"); System.out.println(treeSet); // [A, B, C] (uporządkowane alfabetycznie) } }
6308_2
package pomodorotimer.view; import java.net.URL; import java.time.LocalDate; import java.util.ResourceBundle; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.chart.BarChart; import javafx.scene.chart.CategoryAxis; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.control.ProgressIndicator; import javafx.scene.control.Slider; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TextArea; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import pomodorotimer.model.*; import pomodorotimer.PomodoroTimer; /** * * @author Bartlomiej Kirejczyk */ public class TabPaneController implements Initializable { TabPaneController tabPaneController; StatisticHolder statistics; @FXML private BarChart<?, ?> barChart; @FXML private TabPane tabPane; @FXML private Tab tabTimer; @FXML private AnchorPane anchorPaneTimer; @FXML private Slider sliderWork; @FXML private Label labelWork; @FXML private Label labelBreak; @FXML private Button buttonStartWork; @FXML private Button buttonStartBreak; @FXML private Slider sliderBreak; @FXML private Tab tabStatistics; @FXML private AnchorPane anchorPaneStatistics; @FXML private Tab tabAbout; @FXML private AnchorPane achorPaneAbout; @FXML private TextArea textAreaAbout; @FXML private ImageView imageViewAbout; @FXML private ProgressIndicator progressIndicatorWork; @FXML private ProgressIndicator progressIndicatorBreak; @FXML private NumberAxis numberAxis; @FXML private CategoryAxis categoryAxis; //obiekty wykresu /** * Sets labels text and progress bars to 0.0 * @param url * @param rb */ @Override public void initialize(URL url, ResourceBundle rb) { labelWork.setText(Integer.toString((int)sliderWork.getValue()) + " minutes"); labelBreak.setText(Integer.toString((int)sliderBreak.getValue()) + " minutes"); progressIndicatorWork.setProgress(0.0); progressIndicatorBreak.setProgress(0.0); //statystyki i wykres statistics = PomodoroTimer.getStatisticHolder(); XYChart.Series xyChart = new XYChart.Series<>(); for(int i = 6; i>=0; i--) { System.out.println(statistics.getWorkDate(i).getDate().toString() + statistics.getWorkDate(i).getWorkMins()); xyChart.getData().add(new XYChart.Data<>(statistics.getWorkDate(i).getDate().toString(), statistics.getWorkDate(i).getWorkMins())); } barChart.getData().addAll(xyChart); } /** * Creates object WorkTimer. Passes time goal from slider. Changes Labels text to cancel and pause. * Pause doesn't stop timer, it stops incrementing time. When "pause" is clicked it changes label text to "pasued" */ @FXML public void onActionStartWork() { WorkTimer workTimer; workTimer = new WorkTimer((int)sliderWork.getValue()); //metoda zmienia przyciski //disabluje i zmienia tekst buttonStartBreak this.buttonStartBreak.setText("Pause"); this.buttonStartBreak.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { workTimer.pause(); } }); this.progressIndicatorBreak.setProgress(0); //i zmienia tekst i przeznaczenie buttonStartWork this.buttonStartWork.setText("Cancel"); this.buttonStartWork.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { workTimer.cancel(); } }); } /** * actualizes text on workLabel when using slider */ @FXML public void actualizeLabelWork() { labelWork.setText(Integer.toString((int)sliderWork.getValue()) + " minutes"); } //resetuje buttonStartWork, nadaje mu pierwotny tekst i pierwotny on ActionEvent /** * resets buttonStart work to previous text and ActionEvent */ @FXML public void resetbuttonStartWork() { //nie rozumiem do końca tego rozwiazania, nie przerabiałem jeszcze wielowątkowości //bład był spowodowany tym, że tylko wątek JavyFX moze edytować tekst przycisków //zmiana tekstu przez wątek timera bez Platform.runLater wywoływała błąd Platform.runLater(new Runnable() { @Override public void run() { buttonStartWork.setDisable(false); buttonStartWork.setText("Start Work"); } }); //changes button ActionEvent to basic one buttonStartWork.setOnAction(new EventHandler<ActionEvent> () { @Override public void handle(ActionEvent event) { onActionStartWork(); } }); } /** * Creates object BreakTimer. Passes time goal from slider. Changes Labels text to cancel and pause. * Pause doesn't stop timer, it stops incrementing time. When "pause" is clicked it changes label text to "pasued". * Stats from this one aren;t saved */ @FXML public void onActionStartBreak() { BreakTimer breakTimer; breakTimer = new BreakTimer((int)sliderBreak.getValue()); this.buttonStartWork.setText("Pause"); this.buttonStartWork.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { breakTimer.pause(); } }); this.progressIndicatorWork.setProgress(0); this.buttonStartBreak.setText("Cancel"); this.buttonStartBreak.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { breakTimer.cancel(); } }); } /** * actualizes text on labale when using slider */ @FXML public void actualizeLabelBreak() { labelBreak.setText(Integer.toString((int)sliderBreak.getValue()) + " minutes"); } //resetuje buttonStartBreak @FXML public void resetButtonStartBreak() { //solves problem that JavaFX had with multithreading Platform.runLater(new Runnable() { @Override public void run() { buttonStartBreak.setText("Start Break"); buttonStartBreak.setDisable(false); } }); //sets previous Action Event on button buttonStartBreak.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { onActionStartBreak(); } }); } //actualizes Progress Indicator work @FXML public void actualizeWorkProgressIndicator(double progress) { progressIndicatorWork.setProgress(progress); } //acualizes Prograss Indicator break @FXML public void actualizeBreakProgressIndicator(double progress) { progressIndicatorBreak.setProgress(progress); } //sets both progress indicators to 0.0 @FXML public void resetProgressIndocators() { this.progressIndicatorBreak.setProgress(0.0); this.progressIndicatorWork.setProgress(0.0); } //resets both buttons @FXML public void resetButtons() { this.resetButtonStartBreak(); this.resetbuttonStartWork(); } //changes text of labels according to status of timer @FXML public void switchPauseBreakButton(boolean isPaused) { if(isPaused) { this.buttonStartBreak.setText("Paused"); }else { this.buttonStartBreak.setText("Pause"); } } //changes text of labels according to status of timer @FXML public void switchPauseWorkButton(boolean isPaused) { if(isPaused) { this.buttonStartWork.setText("Paused"); }else { this.buttonStartWork.setText("Pause"); } } //refreshes chart @FXML public void refreshChart() { Platform.runLater(new Runnable() { @Override public void run(){ XYChart.Series xyChart = new XYChart.Series<>(); for(int i = 6; i>=0; i--) { //System.out.println(statistics.getWorkDate(i).getDate().toString() + statistics.getWorkDate(i).getWorkMins()); xyChart.getData().add(new XYChart.Data<>(statistics.getWorkDate(i).getDate().toString(), statistics.getWorkDate(i).getWorkMins())); } barChart.getData().clear(); barChart.getData().addAll(xyChart); }}); } }
Kiririridev/PomodoroTimer
src/pomodorotimer/view/TabPaneController.java
2,875
//statystyki i wykres
line_comment
pl
package pomodorotimer.view; import java.net.URL; import java.time.LocalDate; import java.util.ResourceBundle; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.chart.BarChart; import javafx.scene.chart.CategoryAxis; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.control.ProgressIndicator; import javafx.scene.control.Slider; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TextArea; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import pomodorotimer.model.*; import pomodorotimer.PomodoroTimer; /** * * @author Bartlomiej Kirejczyk */ public class TabPaneController implements Initializable { TabPaneController tabPaneController; StatisticHolder statistics; @FXML private BarChart<?, ?> barChart; @FXML private TabPane tabPane; @FXML private Tab tabTimer; @FXML private AnchorPane anchorPaneTimer; @FXML private Slider sliderWork; @FXML private Label labelWork; @FXML private Label labelBreak; @FXML private Button buttonStartWork; @FXML private Button buttonStartBreak; @FXML private Slider sliderBreak; @FXML private Tab tabStatistics; @FXML private AnchorPane anchorPaneStatistics; @FXML private Tab tabAbout; @FXML private AnchorPane achorPaneAbout; @FXML private TextArea textAreaAbout; @FXML private ImageView imageViewAbout; @FXML private ProgressIndicator progressIndicatorWork; @FXML private ProgressIndicator progressIndicatorBreak; @FXML private NumberAxis numberAxis; @FXML private CategoryAxis categoryAxis; //obiekty wykresu /** * Sets labels text and progress bars to 0.0 * @param url * @param rb */ @Override public void initialize(URL url, ResourceBundle rb) { labelWork.setText(Integer.toString((int)sliderWork.getValue()) + " minutes"); labelBreak.setText(Integer.toString((int)sliderBreak.getValue()) + " minutes"); progressIndicatorWork.setProgress(0.0); progressIndicatorBreak.setProgress(0.0); //statystyki i <SUF> statistics = PomodoroTimer.getStatisticHolder(); XYChart.Series xyChart = new XYChart.Series<>(); for(int i = 6; i>=0; i--) { System.out.println(statistics.getWorkDate(i).getDate().toString() + statistics.getWorkDate(i).getWorkMins()); xyChart.getData().add(new XYChart.Data<>(statistics.getWorkDate(i).getDate().toString(), statistics.getWorkDate(i).getWorkMins())); } barChart.getData().addAll(xyChart); } /** * Creates object WorkTimer. Passes time goal from slider. Changes Labels text to cancel and pause. * Pause doesn't stop timer, it stops incrementing time. When "pause" is clicked it changes label text to "pasued" */ @FXML public void onActionStartWork() { WorkTimer workTimer; workTimer = new WorkTimer((int)sliderWork.getValue()); //metoda zmienia przyciski //disabluje i zmienia tekst buttonStartBreak this.buttonStartBreak.setText("Pause"); this.buttonStartBreak.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { workTimer.pause(); } }); this.progressIndicatorBreak.setProgress(0); //i zmienia tekst i przeznaczenie buttonStartWork this.buttonStartWork.setText("Cancel"); this.buttonStartWork.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { workTimer.cancel(); } }); } /** * actualizes text on workLabel when using slider */ @FXML public void actualizeLabelWork() { labelWork.setText(Integer.toString((int)sliderWork.getValue()) + " minutes"); } //resetuje buttonStartWork, nadaje mu pierwotny tekst i pierwotny on ActionEvent /** * resets buttonStart work to previous text and ActionEvent */ @FXML public void resetbuttonStartWork() { //nie rozumiem do końca tego rozwiazania, nie przerabiałem jeszcze wielowątkowości //bład był spowodowany tym, że tylko wątek JavyFX moze edytować tekst przycisków //zmiana tekstu przez wątek timera bez Platform.runLater wywoływała błąd Platform.runLater(new Runnable() { @Override public void run() { buttonStartWork.setDisable(false); buttonStartWork.setText("Start Work"); } }); //changes button ActionEvent to basic one buttonStartWork.setOnAction(new EventHandler<ActionEvent> () { @Override public void handle(ActionEvent event) { onActionStartWork(); } }); } /** * Creates object BreakTimer. Passes time goal from slider. Changes Labels text to cancel and pause. * Pause doesn't stop timer, it stops incrementing time. When "pause" is clicked it changes label text to "pasued". * Stats from this one aren;t saved */ @FXML public void onActionStartBreak() { BreakTimer breakTimer; breakTimer = new BreakTimer((int)sliderBreak.getValue()); this.buttonStartWork.setText("Pause"); this.buttonStartWork.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { breakTimer.pause(); } }); this.progressIndicatorWork.setProgress(0); this.buttonStartBreak.setText("Cancel"); this.buttonStartBreak.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { breakTimer.cancel(); } }); } /** * actualizes text on labale when using slider */ @FXML public void actualizeLabelBreak() { labelBreak.setText(Integer.toString((int)sliderBreak.getValue()) + " minutes"); } //resetuje buttonStartBreak @FXML public void resetButtonStartBreak() { //solves problem that JavaFX had with multithreading Platform.runLater(new Runnable() { @Override public void run() { buttonStartBreak.setText("Start Break"); buttonStartBreak.setDisable(false); } }); //sets previous Action Event on button buttonStartBreak.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { onActionStartBreak(); } }); } //actualizes Progress Indicator work @FXML public void actualizeWorkProgressIndicator(double progress) { progressIndicatorWork.setProgress(progress); } //acualizes Prograss Indicator break @FXML public void actualizeBreakProgressIndicator(double progress) { progressIndicatorBreak.setProgress(progress); } //sets both progress indicators to 0.0 @FXML public void resetProgressIndocators() { this.progressIndicatorBreak.setProgress(0.0); this.progressIndicatorWork.setProgress(0.0); } //resets both buttons @FXML public void resetButtons() { this.resetButtonStartBreak(); this.resetbuttonStartWork(); } //changes text of labels according to status of timer @FXML public void switchPauseBreakButton(boolean isPaused) { if(isPaused) { this.buttonStartBreak.setText("Paused"); }else { this.buttonStartBreak.setText("Pause"); } } //changes text of labels according to status of timer @FXML public void switchPauseWorkButton(boolean isPaused) { if(isPaused) { this.buttonStartWork.setText("Paused"); }else { this.buttonStartWork.setText("Pause"); } } //refreshes chart @FXML public void refreshChart() { Platform.runLater(new Runnable() { @Override public void run(){ XYChart.Series xyChart = new XYChart.Series<>(); for(int i = 6; i>=0; i--) { //System.out.println(statistics.getWorkDate(i).getDate().toString() + statistics.getWorkDate(i).getWorkMins()); xyChart.getData().add(new XYChart.Data<>(statistics.getWorkDate(i).getDate().toString(), statistics.getWorkDate(i).getWorkMins())); } barChart.getData().clear(); barChart.getData().addAll(xyChart); }}); } }
5794_3
package PPJ18; //2021-12-03 - PPJ18 public class Main { public static void main(String[] args){ Person Adam = new Person(); Adam.name = "Adam"; Adam.surname = "Kowalski"; Adam.birthyear = 2002; Fruit Mango = new Fruit("Mango"); Mango.show(); Ballon balon1 = new Ballon(); Donkey Osiol = new Donkey(); Osiol.addBaloon(balon1); //isflying oczywiście da nam false, bo jeden balon nie wystarczy System.out.println(Osiol.isFlying()); //pętlujemy tak długo aż isflying da nam true //czyli kiedy masa osla bedzie mniejsza od balonow while(!Osiol.isFlying()){ Ballon balonPetla = new Ballon(); Osiol.addBaloon(balonPetla); } //potem po prostu wypisujemy, bo jak petla sie udala System.out.println("Ja latam! "); //zad5 Point2D punktNr1 = new Point2D(); int[] pointsArray = {3,2}; punktNr1.set(pointsArray); System.out.println(punktNr1.get()); } }
Kleszczz/Java-school-PJATK
src/PPJ18/Main.java
379
//czyli kiedy masa osla bedzie mniejsza od balonow
line_comment
pl
package PPJ18; //2021-12-03 - PPJ18 public class Main { public static void main(String[] args){ Person Adam = new Person(); Adam.name = "Adam"; Adam.surname = "Kowalski"; Adam.birthyear = 2002; Fruit Mango = new Fruit("Mango"); Mango.show(); Ballon balon1 = new Ballon(); Donkey Osiol = new Donkey(); Osiol.addBaloon(balon1); //isflying oczywiście da nam false, bo jeden balon nie wystarczy System.out.println(Osiol.isFlying()); //pętlujemy tak długo aż isflying da nam true //czyli kiedy <SUF> while(!Osiol.isFlying()){ Ballon balonPetla = new Ballon(); Osiol.addBaloon(balonPetla); } //potem po prostu wypisujemy, bo jak petla sie udala System.out.println("Ja latam! "); //zad5 Point2D punktNr1 = new Point2D(); int[] pointsArray = {3,2}; punktNr1.set(pointsArray); System.out.println(punktNr1.get()); } }
6868_2
package org.example.basics.exe25; public class Exercise25 { //TODO do sprawdzenia - przeanalizowac public static void main(String[] args) { int numbers[] = {-65, -60, -70, -38, -43, -6, -24, -97, -23, -27}; double sum = 0; for (int number : numbers) { sum += number; } System.out.println("Average of numbers equals: " + sum / numbers.length); //TODO zapytac dlaczego min a nie max value int maxNumber = Integer.MIN_VALUE; for (int number : numbers) { if (number > maxNumber) { maxNumber = number; } } System.out.println("The greatest number is: " + maxNumber); //TODO zapytac dlacze man a nie min value int minValue = Integer.MAX_VALUE; for (int number : numbers) { if (number < minValue) { minValue = number; } } System.out.println("The lowest number is: " + minValue); } }
Konrad66/small-projects
male-zadania/src/main/java/org/example/basics/exe25/Exercise25.java
312
//TODO zapytac dlacze man a nie min value
line_comment
pl
package org.example.basics.exe25; public class Exercise25 { //TODO do sprawdzenia - przeanalizowac public static void main(String[] args) { int numbers[] = {-65, -60, -70, -38, -43, -6, -24, -97, -23, -27}; double sum = 0; for (int number : numbers) { sum += number; } System.out.println("Average of numbers equals: " + sum / numbers.length); //TODO zapytac dlaczego min a nie max value int maxNumber = Integer.MIN_VALUE; for (int number : numbers) { if (number > maxNumber) { maxNumber = number; } } System.out.println("The greatest number is: " + maxNumber); //TODO zapytac <SUF> int minValue = Integer.MAX_VALUE; for (int number : numbers) { if (number < minValue) { minValue = number; } } System.out.println("The lowest number is: " + minValue); } }
8461_2
import java.util.ArrayList; /*** ASOCJACJA KWALIFIKOWANA ***/ public class Produkt { private String nazwa; private int nrKolejny; private ArrayList<Meal> meal = new ArrayList<>(); // przechowywanie informacji zwrotnej public Produkt(int nrKolejny, String nazwa) { this.setNrKolejny(nrKolejny); this.nazwa = nazwa; } public void addMeal(Meal nowyMeal) { if(!meal.contains(nowyMeal)) { // Sprawdz czy nie mamy juz takiej informacji meal.add(nowyMeal); nowyMeal.addProduktKwalif(this); // Dodaj informacje zwrotna } } public String toString() { System.out.println("----------------------"); String zwrot = "PRODUKT: " + nazwa + "\n"; zwrot += "WCHODZI W SKЈAD POSIЈKU: "; for(Meal p : meal) { zwrot += p.getNazwa()+ "\n"; } return zwrot; } public int getNrKolejny() { return nrKolejny; } public void setNrKolejny(int nrKolejny) { this.nrKolejny = nrKolejny; } }
Kosh4tina/PJATK
MAS/MP2_MAS/src/Produkt.java
419
// Dodaj informacje zwrotna
line_comment
pl
import java.util.ArrayList; /*** ASOCJACJA KWALIFIKOWANA ***/ public class Produkt { private String nazwa; private int nrKolejny; private ArrayList<Meal> meal = new ArrayList<>(); // przechowywanie informacji zwrotnej public Produkt(int nrKolejny, String nazwa) { this.setNrKolejny(nrKolejny); this.nazwa = nazwa; } public void addMeal(Meal nowyMeal) { if(!meal.contains(nowyMeal)) { // Sprawdz czy nie mamy juz takiej informacji meal.add(nowyMeal); nowyMeal.addProduktKwalif(this); // Dodaj informacje <SUF> } } public String toString() { System.out.println("----------------------"); String zwrot = "PRODUKT: " + nazwa + "\n"; zwrot += "WCHODZI W SKЈAD POSIЈKU: "; for(Meal p : meal) { zwrot += p.getNazwa()+ "\n"; } return zwrot; } public int getNrKolejny() { return nrKolejny; } public void setNrKolejny(int nrKolejny) { this.nrKolejny = nrKolejny; } }
8330_2
package pl.koziolekweb.ragecomicsmaker.model; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import pl.koziolekweb.ragecomicsmaker.App; import pl.koziolekweb.ragecomicsmaker.event.ErrorEvent; import pl.koziolekweb.ragecomicsmaker.xml.DirectionAdapter; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.io.File; import java.io.Serializable; import java.util.Collection; import java.util.TreeSet; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; /** * TODO write JAVADOC!!! * User: koziolek */ @XmlRootElement(name = "comic") public class Comic implements Serializable { @XmlAttribute(required = true) private int version; @XmlAttribute(required = true) private String id; @XmlAttribute(required = true) private String title; @XmlAttribute(required = true) @XmlJavaTypeAdapter(DirectionAdapter.class) private Direction direction; @XmlAttribute(required = true) private String orientation; @XmlAttribute(required = true) private String transition; @XmlAttribute(required = true) private String bgcolor; @XmlElement private Images images; @XmlElement(name = "screen") private TreeSet<Screen> screens = new TreeSet<Screen>(); public Comic() { initDefaults(); } /** * Methods to init object with default values. Need in first sprint. * * @return Comic with default values */ public Comic initDefaults() { this.version = 0; this.id = ""; this.title = ""; this.direction = Direction.LTR; this.orientation = ""; this.transition = ""; this.bgcolor = "#FFFFFF"; this.images = new Images().initDefaults(); return this; } public void addScreen(Screen screen) { screens.add(screen); images.setLength(screens.size()); } @XmlTransient public Images getImages() { return images; } public void setImages(Images images) { this.images = images; } @XmlTransient public TreeSet<Screen> getScreens() { return screens; } public void setScreens(TreeSet<Screen> screens) { this.screens = screens; } @XmlTransient public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } @XmlTransient public String getId() { return id; } public void setId(String id) { this.id = id; } @XmlTransient public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @XmlTransient public Direction getDirection() { return direction; } public void setDirection(Direction direction) { this.direction = direction; } @XmlTransient public String getOrientation() { return orientation; } public void setOrientation(String orientation) { this.orientation = orientation; } @XmlTransient public String getTransition() { return transition; } public void setTransition(String transition) { this.transition = transition; } @XmlTransient public String getBgcolor() { return bgcolor; } public void setBgcolor(String bgcolor) { this.bgcolor = bgcolor; } public Screen findScreenByFileName(final String lastSelectedPathComponent) { checkNotNull(lastSelectedPathComponent); Collection<Screen> filtered = Collections2.filter(screens, new Predicate<Screen>() { @Override public boolean apply(Screen input) { File image = input.getImage(); if (image == null) return false; return lastSelectedPathComponent.equals(image.getName()); } }); checkState(filtered.size() == 1); return filtered.iterator().next(); } public Screen findScreenByIndex(String number) { try { final int intNumber = Integer.parseInt(number); Collection<Screen> filtered = Collections2.filter(screens, new Predicate<Screen>() { @Override public boolean apply(Screen input) { return input.getIndex() == intNumber; } }); if (filtered.iterator().hasNext()) return filtered.iterator().next(); return new Screen(); // tak naprawdę do niczego nie podpiety null object } catch (Exception e) { App.EVENT_BUS.post(new ErrorEvent("Nieoczekiwany błąd odczytu - nieprawidłowy numer pliku " + number, e)); return new Screen(); } } }
Koziolek/ragecomicsmaker
src/main/java/pl/koziolekweb/ragecomicsmaker/model/Comic.java
1,490
// tak naprawdę do niczego nie podpiety null object
line_comment
pl
package pl.koziolekweb.ragecomicsmaker.model; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import pl.koziolekweb.ragecomicsmaker.App; import pl.koziolekweb.ragecomicsmaker.event.ErrorEvent; import pl.koziolekweb.ragecomicsmaker.xml.DirectionAdapter; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.io.File; import java.io.Serializable; import java.util.Collection; import java.util.TreeSet; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; /** * TODO write JAVADOC!!! * User: koziolek */ @XmlRootElement(name = "comic") public class Comic implements Serializable { @XmlAttribute(required = true) private int version; @XmlAttribute(required = true) private String id; @XmlAttribute(required = true) private String title; @XmlAttribute(required = true) @XmlJavaTypeAdapter(DirectionAdapter.class) private Direction direction; @XmlAttribute(required = true) private String orientation; @XmlAttribute(required = true) private String transition; @XmlAttribute(required = true) private String bgcolor; @XmlElement private Images images; @XmlElement(name = "screen") private TreeSet<Screen> screens = new TreeSet<Screen>(); public Comic() { initDefaults(); } /** * Methods to init object with default values. Need in first sprint. * * @return Comic with default values */ public Comic initDefaults() { this.version = 0; this.id = ""; this.title = ""; this.direction = Direction.LTR; this.orientation = ""; this.transition = ""; this.bgcolor = "#FFFFFF"; this.images = new Images().initDefaults(); return this; } public void addScreen(Screen screen) { screens.add(screen); images.setLength(screens.size()); } @XmlTransient public Images getImages() { return images; } public void setImages(Images images) { this.images = images; } @XmlTransient public TreeSet<Screen> getScreens() { return screens; } public void setScreens(TreeSet<Screen> screens) { this.screens = screens; } @XmlTransient public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } @XmlTransient public String getId() { return id; } public void setId(String id) { this.id = id; } @XmlTransient public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @XmlTransient public Direction getDirection() { return direction; } public void setDirection(Direction direction) { this.direction = direction; } @XmlTransient public String getOrientation() { return orientation; } public void setOrientation(String orientation) { this.orientation = orientation; } @XmlTransient public String getTransition() { return transition; } public void setTransition(String transition) { this.transition = transition; } @XmlTransient public String getBgcolor() { return bgcolor; } public void setBgcolor(String bgcolor) { this.bgcolor = bgcolor; } public Screen findScreenByFileName(final String lastSelectedPathComponent) { checkNotNull(lastSelectedPathComponent); Collection<Screen> filtered = Collections2.filter(screens, new Predicate<Screen>() { @Override public boolean apply(Screen input) { File image = input.getImage(); if (image == null) return false; return lastSelectedPathComponent.equals(image.getName()); } }); checkState(filtered.size() == 1); return filtered.iterator().next(); } public Screen findScreenByIndex(String number) { try { final int intNumber = Integer.parseInt(number); Collection<Screen> filtered = Collections2.filter(screens, new Predicate<Screen>() { @Override public boolean apply(Screen input) { return input.getIndex() == intNumber; } }); if (filtered.iterator().hasNext()) return filtered.iterator().next(); return new Screen(); // tak naprawdę <SUF> } catch (Exception e) { App.EVENT_BUS.post(new ErrorEvent("Nieoczekiwany błąd odczytu - nieprawidłowy numer pliku " + number, e)); return new Screen(); } } }
9055_26
import java.util.Scanner; // Press Shift twice to open the Search Everywhere dialog and type `show whitespaces`, // then press Enter. You can now see whitespace characters in your code. public class Main { public static void zad1(){ //Napisz prostą aplikację kalkulatora tekstowego, // która przyjmuje dwa liczby od użytkownika jako wejście // i wykonuje podstawowe operacje matematyczne (dodawanie, odejmowanie, mnożenie, dzielenie). // Wyświetl wyniki na ekranie. System.out.print("Podaj pierwszą liczbę: "); Scanner scanner = new Scanner(System.in); double l1 = scanner.nextDouble(); System.out.print("Podaj drugą liczbę: "); double l2 = scanner.nextDouble(); System.out.println("Wynik dodawania: " + (l1+l2)); System.out.println("Wynik odejmowania: " + (l1-l2)); System.out.println("Wynik mnożenia: " + (l1*l2)); System.out.println("Wynik dzielenia: " + (l1/l2)); } public static void zad2(){ //Napisz program, który wczytuje ze standardowego wejścia dwa łańcuchy znaków, // a następnie wypisuje je w kolejnych wierszach na standardowym wyjściu. System.out.print("Podaj pierwszy łańcuch znaków:"); Scanner scanner =new Scanner(System.in); String z1 = scanner.nextLine(); System.out.print("Podaj drugi łańcuch znaków:"); String z2 = scanner.nextLine(); System.out.println(z1); System.out.println(z2); } public static void zad3(){ //Napisz program, który wczytuje ze standardowego wejścia cztery liczby wymierne, // a następnie wypisuje ich sumę na standardowym wyjściu. double suma=0; for(int i=1;i<5;i++) { System.out.println("Podaj liczbę wymierną nr" + i + ":"); Scanner scanner = new Scanner(System.in); double liczba = scanner.nextDouble(); suma+=liczba; } System.out.println("Suma czterech liczb wynosi: "+suma); } public static void zad4(){ //Napisz program, który przyjmuje trzy liczby całkowite jako argumenty // i zwraca największą z nich. Zastosuj instrukcje warunkowe do porównania liczb. System.out.println("Podaj pierwszą liczbę całkowitą: "); Scanner scanner = new Scanner(System.in); int l1 = scanner.nextInt(); System.out.println("Podaj drugą liczbę całkowitą: "); int l2 = scanner.nextInt(); System.out.println("Podaj trzecią liczbę całkowitą: "); int l3 = scanner.nextInt(); if(l1>l2 && l1>l3){ System.out.println("Liczba "+ l1 + " jest największa"); } else if(l3>l1 && l3>l2){ System.out.println("Liczba "+ l3 + " jest największa"); } else{ System.out.println("Liczba "+ l2 + " jest największa"); } } public static void zad5(){ //Napisz program, który na podstawie podanego jako argument numeru dnia tygodnia (od 1 do 7) wypisze nazwę tego dnia tygodnia. // Dla przykładu, jeżeli użytkownik poda liczbę 1, program powinien wypisać “Poniedziałek”. // Jeżeli podana liczba nie jest z zakresu od 1 do 7, // program powinien wyświetlić komunikat “Niepoprawny numer dnia tygodnia”. System.out.println("Podaj numer dnia tygodnia z zakresu 1-7: "); Scanner skaner = new Scanner(System.in); int dzien = skaner.nextInt(); switch(dzien){ case 1: System.out.println("Poniedziałek"); break; case 2: System.out.println("Wtorek"); break; case 3: System.out.println("Środa"); break; case 4: System.out.println("Czwartek"); break; case 5: System.out.println("PIĄTEK"); break; case 6: System.out.println("Sobota"); break; case 7: System.out.println("Niedziela"); break; default: System.out.println("Niepoprawny numer dnia tygodnia"); } } public static void zad6(){ //Napisz program, który będzie sprawdzał, czy podany rok jest rokiem przestępnym. // Rok jest przestępny, jeśli jest podzielny przez 4, ale nie jest podzielny przez 100, // chyba że jest podzielny przez 400 System.out.println("Podaj rok: "); Scanner skaner = new Scanner(System.in); int rok = skaner.nextInt(); if(rok%100==0){ if (rok % 400 == 0) { System.out.println("Podany rok jest przestępny."); } else{ System.out.println("Podany rok nie jest przestępny."); } } else if(rok%4==0){ System.out.println("Podany rok jest przestępny."); } else{ System.out.println("Podany rok nie jest przestępny."); } } public static void zad7(){ //Napisz program, który oblicza sumę cyfr dowolnej wprowadzonej liczby. // Program powinien akceptować liczbę jako input od użytkownika. System.out.print("Podaj liczbę: "); Scanner skaner= new Scanner(System.in); int liczba = skaner.nextInt(); int suma =0; int cyfra=liczba; while (cyfra !=0) { suma+= cyfra%10; cyfra/=10; } System.out.println("Suma cyfr liczby "+liczba+" wynosi: "+suma); } public static void zad8(){ //Napisz program, który tworzy tablicę jednowymiarową 10 liczb całkowitych, // a następnie wyświetla je w konsoli w porządku odwrotnym do wprowadzenia. int[] tablica = new int[10]; Scanner scanner=new Scanner(System.in); // Wprowadzenie liczb do tablicy for (int i=0;i<10;i++) { System.out.print("Podaj liczbę " +(i+1)+ ": "); tablica[i] =scanner.nextInt(); } System.out.println("Liczby w odwrotnej kolejności:"); for (int i=9;i>=0;i--) { System.out.printf(tablica[i]+","); } } public static void zad9(){ //Napisz program, który przyjmuje napis jako wejście // i wypisuje wszystkie znaki znajdujące się na parzystych indeksach napisu, używając metody charAt. System.out.print("Podaj napis: "); Scanner scanner = new Scanner(System.in); String napis =scanner.nextLine(); System.out.println("Znaki na parzystych indeksach:"); for (int i=0;i<napis.length();i+=2) { char znak= napis.charAt(i); System.out.printf(znak+","); } } public static void zad10(){ //Napisz program, który przyjmuje jako wejście pojedynczy znak oraz liczbę całkowitą n. // Używając klasy StringBuilder, zbuduj i wypisz piramidę o wysokości n, // gdzie każdy poziom piramidy składa się z podanego znaku. System.out.print("Podaj znak: "); Scanner scanner = new Scanner(System.in); char znak = scanner.next().charAt(0); System.out.print("Podaj wysokość piramidy (liczba całkowita): "); int n = scanner.nextInt(); if (n<=0) { System.out.println("Wysokość piramidy musi być liczbą dodatnią."); } else { StringBuilder piramida= new StringBuilder(); for (int i=1;i<=n;i++) { for (int j=0;j<n-i;j++) { piramida.append(" "); } for (int k=0;k<2*i-1;k++) { piramida.append(znak); } piramida.append("\n"); } System.out.println(piramida); } } public static void zad11(){ //Stwórz program, który przyjmie od użytkownika liczbę całkowitą i zwróci tę liczbę w odwrotnej kolejności. // Na przykład, dla liczby 12345, wynik powinien wynosić 54321. // Możesz ograniczyć program tylko do liczb dodatnich. System.out.println("Podaj liczbę całkowitą: "); Scanner skaner= new Scanner(System.in); int liczba= skaner.nextInt(); int wynik=0; if(liczba<0){ liczba*=-1; while (liczba !=0) { int cyfra = liczba % 10; wynik=wynik*10+cyfra; liczba/=10; } wynik*=-1; } else { while (liczba !=0) { int cyfra = liczba % 10; wynik=wynik*10+cyfra; liczba/=10; } } System.out.print("Liczba w odwrotnej kolejności:"+wynik); } public static void main(String[] args) { zad1(); zad2(); zad3(); zad4(); zad5(); zad6(); zad7(); zad8(); zad9(); zad10(); zad11(); // } }
KrajewskiMaciej/PO169709
Cw_1/src/Main.java
3,023
//Napisz program, który przyjmuje jako wejście pojedynczy znak oraz liczbę całkowitą n.
line_comment
pl
import java.util.Scanner; // Press Shift twice to open the Search Everywhere dialog and type `show whitespaces`, // then press Enter. You can now see whitespace characters in your code. public class Main { public static void zad1(){ //Napisz prostą aplikację kalkulatora tekstowego, // która przyjmuje dwa liczby od użytkownika jako wejście // i wykonuje podstawowe operacje matematyczne (dodawanie, odejmowanie, mnożenie, dzielenie). // Wyświetl wyniki na ekranie. System.out.print("Podaj pierwszą liczbę: "); Scanner scanner = new Scanner(System.in); double l1 = scanner.nextDouble(); System.out.print("Podaj drugą liczbę: "); double l2 = scanner.nextDouble(); System.out.println("Wynik dodawania: " + (l1+l2)); System.out.println("Wynik odejmowania: " + (l1-l2)); System.out.println("Wynik mnożenia: " + (l1*l2)); System.out.println("Wynik dzielenia: " + (l1/l2)); } public static void zad2(){ //Napisz program, który wczytuje ze standardowego wejścia dwa łańcuchy znaków, // a następnie wypisuje je w kolejnych wierszach na standardowym wyjściu. System.out.print("Podaj pierwszy łańcuch znaków:"); Scanner scanner =new Scanner(System.in); String z1 = scanner.nextLine(); System.out.print("Podaj drugi łańcuch znaków:"); String z2 = scanner.nextLine(); System.out.println(z1); System.out.println(z2); } public static void zad3(){ //Napisz program, który wczytuje ze standardowego wejścia cztery liczby wymierne, // a następnie wypisuje ich sumę na standardowym wyjściu. double suma=0; for(int i=1;i<5;i++) { System.out.println("Podaj liczbę wymierną nr" + i + ":"); Scanner scanner = new Scanner(System.in); double liczba = scanner.nextDouble(); suma+=liczba; } System.out.println("Suma czterech liczb wynosi: "+suma); } public static void zad4(){ //Napisz program, który przyjmuje trzy liczby całkowite jako argumenty // i zwraca największą z nich. Zastosuj instrukcje warunkowe do porównania liczb. System.out.println("Podaj pierwszą liczbę całkowitą: "); Scanner scanner = new Scanner(System.in); int l1 = scanner.nextInt(); System.out.println("Podaj drugą liczbę całkowitą: "); int l2 = scanner.nextInt(); System.out.println("Podaj trzecią liczbę całkowitą: "); int l3 = scanner.nextInt(); if(l1>l2 && l1>l3){ System.out.println("Liczba "+ l1 + " jest największa"); } else if(l3>l1 && l3>l2){ System.out.println("Liczba "+ l3 + " jest największa"); } else{ System.out.println("Liczba "+ l2 + " jest największa"); } } public static void zad5(){ //Napisz program, który na podstawie podanego jako argument numeru dnia tygodnia (od 1 do 7) wypisze nazwę tego dnia tygodnia. // Dla przykładu, jeżeli użytkownik poda liczbę 1, program powinien wypisać “Poniedziałek”. // Jeżeli podana liczba nie jest z zakresu od 1 do 7, // program powinien wyświetlić komunikat “Niepoprawny numer dnia tygodnia”. System.out.println("Podaj numer dnia tygodnia z zakresu 1-7: "); Scanner skaner = new Scanner(System.in); int dzien = skaner.nextInt(); switch(dzien){ case 1: System.out.println("Poniedziałek"); break; case 2: System.out.println("Wtorek"); break; case 3: System.out.println("Środa"); break; case 4: System.out.println("Czwartek"); break; case 5: System.out.println("PIĄTEK"); break; case 6: System.out.println("Sobota"); break; case 7: System.out.println("Niedziela"); break; default: System.out.println("Niepoprawny numer dnia tygodnia"); } } public static void zad6(){ //Napisz program, który będzie sprawdzał, czy podany rok jest rokiem przestępnym. // Rok jest przestępny, jeśli jest podzielny przez 4, ale nie jest podzielny przez 100, // chyba że jest podzielny przez 400 System.out.println("Podaj rok: "); Scanner skaner = new Scanner(System.in); int rok = skaner.nextInt(); if(rok%100==0){ if (rok % 400 == 0) { System.out.println("Podany rok jest przestępny."); } else{ System.out.println("Podany rok nie jest przestępny."); } } else if(rok%4==0){ System.out.println("Podany rok jest przestępny."); } else{ System.out.println("Podany rok nie jest przestępny."); } } public static void zad7(){ //Napisz program, który oblicza sumę cyfr dowolnej wprowadzonej liczby. // Program powinien akceptować liczbę jako input od użytkownika. System.out.print("Podaj liczbę: "); Scanner skaner= new Scanner(System.in); int liczba = skaner.nextInt(); int suma =0; int cyfra=liczba; while (cyfra !=0) { suma+= cyfra%10; cyfra/=10; } System.out.println("Suma cyfr liczby "+liczba+" wynosi: "+suma); } public static void zad8(){ //Napisz program, który tworzy tablicę jednowymiarową 10 liczb całkowitych, // a następnie wyświetla je w konsoli w porządku odwrotnym do wprowadzenia. int[] tablica = new int[10]; Scanner scanner=new Scanner(System.in); // Wprowadzenie liczb do tablicy for (int i=0;i<10;i++) { System.out.print("Podaj liczbę " +(i+1)+ ": "); tablica[i] =scanner.nextInt(); } System.out.println("Liczby w odwrotnej kolejności:"); for (int i=9;i>=0;i--) { System.out.printf(tablica[i]+","); } } public static void zad9(){ //Napisz program, który przyjmuje napis jako wejście // i wypisuje wszystkie znaki znajdujące się na parzystych indeksach napisu, używając metody charAt. System.out.print("Podaj napis: "); Scanner scanner = new Scanner(System.in); String napis =scanner.nextLine(); System.out.println("Znaki na parzystych indeksach:"); for (int i=0;i<napis.length();i+=2) { char znak= napis.charAt(i); System.out.printf(znak+","); } } public static void zad10(){ //Napisz program, <SUF> // Używając klasy StringBuilder, zbuduj i wypisz piramidę o wysokości n, // gdzie każdy poziom piramidy składa się z podanego znaku. System.out.print("Podaj znak: "); Scanner scanner = new Scanner(System.in); char znak = scanner.next().charAt(0); System.out.print("Podaj wysokość piramidy (liczba całkowita): "); int n = scanner.nextInt(); if (n<=0) { System.out.println("Wysokość piramidy musi być liczbą dodatnią."); } else { StringBuilder piramida= new StringBuilder(); for (int i=1;i<=n;i++) { for (int j=0;j<n-i;j++) { piramida.append(" "); } for (int k=0;k<2*i-1;k++) { piramida.append(znak); } piramida.append("\n"); } System.out.println(piramida); } } public static void zad11(){ //Stwórz program, który przyjmie od użytkownika liczbę całkowitą i zwróci tę liczbę w odwrotnej kolejności. // Na przykład, dla liczby 12345, wynik powinien wynosić 54321. // Możesz ograniczyć program tylko do liczb dodatnich. System.out.println("Podaj liczbę całkowitą: "); Scanner skaner= new Scanner(System.in); int liczba= skaner.nextInt(); int wynik=0; if(liczba<0){ liczba*=-1; while (liczba !=0) { int cyfra = liczba % 10; wynik=wynik*10+cyfra; liczba/=10; } wynik*=-1; } else { while (liczba !=0) { int cyfra = liczba % 10; wynik=wynik*10+cyfra; liczba/=10; } } System.out.print("Liczba w odwrotnej kolejności:"+wynik); } public static void main(String[] args) { zad1(); zad2(); zad3(); zad4(); zad5(); zad6(); zad7(); zad8(); zad9(); zad10(); zad11(); // } }
9386_0
package edu.util; import com.lambdaworks.crypto.SCryptUtil; public class PasswordUtils { /* * Metoda koduje haslo, ktore w bazie danych przechowywane jest w formie niejawnej, * jezeli uzytkownik wpisze haslo to nawet administrator czy autor kodu, ktory ma dostep * do bazy danych nie moze hasla podejzec, po przechowywana jest tam jego zakodowana forma. * Sprawdzenie hasla polega na zakodowaniu podanego hasla i porownania ich zakodowanych wersji. */ public static String hashPassword(String originalPassword) { return SCryptUtil.scrypt(originalPassword, 16, 16, 16); } public static boolean isPasswordMatch(String password, String passwordHashed) { return SCryptUtil.check(password, passwordHashed); } }
Kronos1993/pracainz
PracaInz_v01/src/edu/util/PasswordUtils.java
258
/* * Metoda koduje haslo, ktore w bazie danych przechowywane jest w formie niejawnej, * jezeli uzytkownik wpisze haslo to nawet administrator czy autor kodu, ktory ma dostep * do bazy danych nie moze hasla podejzec, po przechowywana jest tam jego zakodowana forma. * Sprawdzenie hasla polega na zakodowaniu podanego hasla i porownania ich zakodowanych wersji. */
block_comment
pl
package edu.util; import com.lambdaworks.crypto.SCryptUtil; public class PasswordUtils { /* * Metoda koduje haslo, <SUF>*/ public static String hashPassword(String originalPassword) { return SCryptUtil.scrypt(originalPassword, 16, 16, 16); } public static boolean isPasswordMatch(String password, String passwordHashed) { return SCryptUtil.check(password, passwordHashed); } }
4534_0
package com.library.model; import com.library.config.LibrarySetupConfig; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; import javax.persistence.*; import java.util.*; /** * Odwzorowuje użytkownika z bazy danych */ @Entity public class User implements Observer { private Long userID; @NotEmpty(message = "*Pole imię nie może być puste") private String firstname; @NotEmpty(message = "*Pole nazwisko nie może być puste") private String surname; @NotEmpty(message = "*Pole login nie może być puste") private String username; @NotEmpty(message = "*Pole hasło nie może być puste") private String password; @Email(message = "*Podaj prawidłowy adres e-mail") @NotEmpty(message = "*Pole e-mail nie może być puste") private String email; private int active; private Set<Role> roles = new HashSet<>(0); private Stack<String> notes = new Stack<>(); public String getNote() { if(!notes.empty()) return notes.pop(); else return null; } public void setNote(String note) { this.notes.push(note); } public void clearNotifications(){ this.notes = new Stack<>(); } @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getUserID() { return userID; } public void setUserID(Long userID) { this.userID = userID; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getActive() { return active; } public void setActive(int active) { this.active = active; } @ManyToMany(cascade = CascadeType.ALL) public Set<Role> getRoles() { return roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } /** * Ustawia notkę użytkownika w odpowiedzi na zmianę statusu BookBorrow * * @param o obiekt Observable * @param arg argument przekazywany przez notify Observable */ @Override public void update(Observable o, Object arg) { String msg; Object[] status = (Object[])arg; Book book = (Book)status[LibrarySetupConfig.OBJECT]; if ((int)status[LibrarySetupConfig.COMPARISON_RESULT] == LibrarySetupConfig.TERM_REACHED) { msg = "Termin przekroczony o " + Math.abs((int) status[LibrarySetupConfig.DAYS_BETWEEN]) + "dni!\n" + "Dotyczy: " + book.getName() + " " + book.getAuthor(); } else { msg ="Zostało " + Math.abs((int) status[LibrarySetupConfig.DAYS_BETWEEN]) + " dni!\n" + "Dotyczy: " + book.getName() + " " + book.getAuthor(); } this.setNote(msg); } }
KryniuPL/Library_managment_system
src/main/java/com/library/model/User.java
1,064
/** * Odwzorowuje użytkownika z bazy danych */
block_comment
pl
package com.library.model; import com.library.config.LibrarySetupConfig; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; import javax.persistence.*; import java.util.*; /** * Odwzorowuje użytkownika z <SUF>*/ @Entity public class User implements Observer { private Long userID; @NotEmpty(message = "*Pole imię nie może być puste") private String firstname; @NotEmpty(message = "*Pole nazwisko nie może być puste") private String surname; @NotEmpty(message = "*Pole login nie może być puste") private String username; @NotEmpty(message = "*Pole hasło nie może być puste") private String password; @Email(message = "*Podaj prawidłowy adres e-mail") @NotEmpty(message = "*Pole e-mail nie może być puste") private String email; private int active; private Set<Role> roles = new HashSet<>(0); private Stack<String> notes = new Stack<>(); public String getNote() { if(!notes.empty()) return notes.pop(); else return null; } public void setNote(String note) { this.notes.push(note); } public void clearNotifications(){ this.notes = new Stack<>(); } @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getUserID() { return userID; } public void setUserID(Long userID) { this.userID = userID; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getActive() { return active; } public void setActive(int active) { this.active = active; } @ManyToMany(cascade = CascadeType.ALL) public Set<Role> getRoles() { return roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } /** * Ustawia notkę użytkownika w odpowiedzi na zmianę statusu BookBorrow * * @param o obiekt Observable * @param arg argument przekazywany przez notify Observable */ @Override public void update(Observable o, Object arg) { String msg; Object[] status = (Object[])arg; Book book = (Book)status[LibrarySetupConfig.OBJECT]; if ((int)status[LibrarySetupConfig.COMPARISON_RESULT] == LibrarySetupConfig.TERM_REACHED) { msg = "Termin przekroczony o " + Math.abs((int) status[LibrarySetupConfig.DAYS_BETWEEN]) + "dni!\n" + "Dotyczy: " + book.getName() + " " + book.getAuthor(); } else { msg ="Zostało " + Math.abs((int) status[LibrarySetupConfig.DAYS_BETWEEN]) + " dni!\n" + "Dotyczy: " + book.getName() + " " + book.getAuthor(); } this.setNote(msg); } }
6307_2
package entities.counters; import entities.Entity; import players.PositionOnMap; import entities.ui.Tile; import entities.HUD.UltimateBar; import ludogame.Handler; import states.SettingState; import java.awt.*; import java.awt.image.BufferedImage; public abstract class Counter extends Entity { public static final int DEFAULT_WIDTH=41, DEFAULT_HEIGHT=78; protected double SCALE; // private final float basex; private final float basey; // protected PositionOnMap pos; protected double directionx,directiony; protected boolean cisinbase, cfinished; protected final Rectangle hitbox; private boolean moving; private boolean reseting; private boolean won; private PositionOnMap bufferedPosition; //cos do umiejetnosci protected boolean killable; //czy może być zbity protected boolean canKill; //czy może zbijąć private boolean beaten; //czy był zbity - do odrodzenia protected boolean vulnerable; //czy ogień go zbija //Ultimate bar protected boolean ultBar; protected UltimateBar ultimateBar=null; protected boolean ultimateAbility=false; // // protected BufferedImage counterColor; //animacja protected int ANIM_TICKS=(int)(0.37* SettingState.FPS); private int tickcount=0; protected int moved=0; protected int tilesMoved=0; public Counter(Handler handler, float x, float y,BufferedImage counterColor) { super(handler,x, y,DEFAULT_WIDTH,DEFAULT_HEIGHT); this.counterColor=counterColor; basex=x; basey=y; hitbox=new Rectangle((int)x, (int)y,DEFAULT_WIDTH,DEFAULT_HEIGHT); beaten=false; cisinbase=true; cfinished=false; SCALE=1; moving =false; won=false; } public void tick(){ if(ultimateBar!=null) ultimateBar.tick(); if(moving) { moveLogic(); } if(reseting){ resetLogic(); } } private void moveLogic(){ if(!won) { if (cisinbase) { if (tickcount == 0) { Tile tempTile = handler.getTile(handler.getPlayer().getStartingPos()); handler.getLoadingScreen().setPlay("move"); directionx = (tempTile.getX() + 4 - x) / ANIM_TICKS; directiony = (tempTile.getY() - 48 - y) / ANIM_TICKS; tickcount++; } else if (tickcount > 0 && tickcount < ANIM_TICKS) { x += directionx; y += directiony; tickcount++; } else if (tickcount == ANIM_TICKS) { Tile tempTile = handler.getTile(handler.getPlayer().getStartingPos()); x = tempTile.getX() + 4; y = tempTile.getY() - 48; hitbox.x = (int) x; hitbox.y = (int) y; cisinbase = false; tickcount = 0; moving = false; tilesMoved=0; pos = new PositionOnMap(handler.getPlayer().getStartingPos()); bufferedPosition = getNextPosition(); handler.setCounterOnTile(pos, this); handler.getTimer().resetTimer(); handler.getDice().setRolled(false); if(handler.getPlayer().getRollsLeft()==0) handler.getPlayer().setRollsLeft(1); handler.getPlayer().setIsinbase(false); handler.getGameState().setRenderOrder(); } } else { if (tickcount == 0) { handler.removeCounterFromTile(pos, this); if (ultimateAbility) counterLogic(); handler.getLoadingScreen().setPlay("move"); renderBig(); directionx = (handler.getTile(bufferedPosition).getX() + 4 - x) / ANIM_TICKS; directiony = (handler.getTile(bufferedPosition).getY() - 48 - y) / ANIM_TICKS; tickcount++; } else if (tickcount > 0 && tickcount < ANIM_TICKS) { x += directionx; y += directiony; tickcount++; } else if (tickcount == ANIM_TICKS) { x = handler.getTile(bufferedPosition).getX() + 4; y = handler.getTile(bufferedPosition).getY() - 48; tickcount = 0; handler.removeCounterFromTile(pos, this); pos = bufferedPosition; handler.getPlayer().addPoint(); moved++; tilesMoved++; bufferedPosition = getNextPosition(); if ((moved != handler.getRoll())&&!won) handler.setCounterOnTile(pos, this); handler.getGameState().setRenderOrder(); if ((moved == handler.getRoll())||won) { moving = false; hitbox.x = (int) x; hitbox.y = (int) y; handler.setCounterOnTile(pos, this); handler.getDice().setRolled(false); handler.getGameState().setRenderOrder(); moved = 0; if (handler.getPlayer().getRollsLeft() == 0) handler.setTurnof(); } } } } else { handler.setTurnof(); handler.getPlayer().setRollsLeft(1); moving=false; handler.getDice().setRolled(false); handler.getTimer().resetTimer(); if(handler.getPlayer().getClass().getName()=="players.Bot") handler.getPlayer().setBotClicked(); } } private void resetLogic(){ if (tickcount == 0) { directionx = (basex - x) / (ANIM_TICKS*2); directiony = (basey - y) / (ANIM_TICKS*2); tickcount++; renderBig(); handler.getGameState().getPlayerByColor(counterColor).addDeath(); cisinbase = true; handler.getGameState().setRenderOrder(); } else if (tickcount > 0 && tickcount < ANIM_TICKS*2) { x += directionx; y += directiony; tickcount++; } else if (tickcount == ANIM_TICKS*2) { x = basex; y = basey; hitbox.x=(int)x; hitbox.y=(int)y; beaten=true; cfinished=false; tickcount = 0; reseting=false; pos = handler.getPlayer().getStartingPos(); //handler.getTimer().resetTimer(); //handler.getDice().setRolled(false); } } protected PositionOnMap getNextPosition(){ if(handler.getDice().getRoll()>0) { if (pos.arr == handler.getPlayer().getEndingPos().arr && pos.tile == handler.getPlayer().getEndingPos().tile&&tilesMoved>49) { if (ultBar) this.ultimateBar.setCanBeLoaded(false); return new PositionOnMap(handler.getTurnOf() + 1, 0); } else if (pos.tile == 51) return new PositionOnMap(0); else if (pos.arr > 0 && pos.tile == 5) { won = true; ultimateAbility = false; System.out.println("WON"); return new PositionOnMap(pos.arr, pos.tile); } else return new PositionOnMap(pos.arr, pos.tile + 1); } //do "cofanie" else if(handler.getDice().getRoll()==0) return new PositionOnMap(pos.arr, pos.tile); else{ if(pos.tile==0) return new PositionOnMap(51); else return new PositionOnMap(pos.arr, pos.tile - 1); } } public boolean isInbase() { return cisinbase; } protected void renderWasKilled(Graphics g){ //g.drawImage(Assets.); } protected abstract void counterLogic(); //true jeśli wraca do bazy, false jeśli nie public abstract boolean ifStepped(); public boolean hasUltBar(){ return this.ultBar; } public boolean isVulnerable(){ return this.vulnerable; } public void setMoving(boolean moving){ this.moving=moving; } public boolean isMoving(){ return this.moving; } public boolean isKillable(){ return this.killable; } public void renderUltBar(Graphics g){ if(ultimateBar!=null) ultimateBar.render(g); } public boolean isClicked(){ return this.hitbox.contains(handler.getMouseClickX(),handler.getMouseClickY()); } public void resetToBase(){ reseting=true; moving=false; cisinbase=true; handler.getGameState().addToReset(this); } public boolean getMoving(){ return this.moving; } public boolean getReseting(){ return this.reseting; } public BufferedImage getCounterColor(){ return this.counterColor; } public int getBaseX(){ return (int)this.basex; } public int getBaseY(){ return (int)this.basey; } public boolean canKill(){ return this.canKill; } public void useUltimateAbility(){ this.ultimateAbility=true; } public void setUltimateAbility(boolean ult){ this.ultimateAbility=ult; } public boolean isBeaten(){ return this.beaten; } public void renderSmall(float shiftX,float shiftY){ if(SCALE==1) { SCALE = 0.65; hitbox.setSize((int)(hitbox.width*SCALE),(int)(hitbox.height*SCALE)); } x=shiftX+4; y=shiftY-48; hitbox.setLocation((int)x,(int)y); } public void renderBig(float x,float y){ SCALE=1; hitbox.setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT); this.x=x; this.y=y; hitbox.setLocation((int)x,(int)y); } public void renderBig(){ SCALE=1; hitbox.setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT); } public UltimateBar getUltimateBar(){ return this.ultimateBar; } public boolean getWon(){ return this.won; } }
KrystianOg/Ludo-Legends
src/entities/counters/Counter.java
3,127
//czy może zbijąć
line_comment
pl
package entities.counters; import entities.Entity; import players.PositionOnMap; import entities.ui.Tile; import entities.HUD.UltimateBar; import ludogame.Handler; import states.SettingState; import java.awt.*; import java.awt.image.BufferedImage; public abstract class Counter extends Entity { public static final int DEFAULT_WIDTH=41, DEFAULT_HEIGHT=78; protected double SCALE; // private final float basex; private final float basey; // protected PositionOnMap pos; protected double directionx,directiony; protected boolean cisinbase, cfinished; protected final Rectangle hitbox; private boolean moving; private boolean reseting; private boolean won; private PositionOnMap bufferedPosition; //cos do umiejetnosci protected boolean killable; //czy może być zbity protected boolean canKill; //czy może <SUF> private boolean beaten; //czy był zbity - do odrodzenia protected boolean vulnerable; //czy ogień go zbija //Ultimate bar protected boolean ultBar; protected UltimateBar ultimateBar=null; protected boolean ultimateAbility=false; // // protected BufferedImage counterColor; //animacja protected int ANIM_TICKS=(int)(0.37* SettingState.FPS); private int tickcount=0; protected int moved=0; protected int tilesMoved=0; public Counter(Handler handler, float x, float y,BufferedImage counterColor) { super(handler,x, y,DEFAULT_WIDTH,DEFAULT_HEIGHT); this.counterColor=counterColor; basex=x; basey=y; hitbox=new Rectangle((int)x, (int)y,DEFAULT_WIDTH,DEFAULT_HEIGHT); beaten=false; cisinbase=true; cfinished=false; SCALE=1; moving =false; won=false; } public void tick(){ if(ultimateBar!=null) ultimateBar.tick(); if(moving) { moveLogic(); } if(reseting){ resetLogic(); } } private void moveLogic(){ if(!won) { if (cisinbase) { if (tickcount == 0) { Tile tempTile = handler.getTile(handler.getPlayer().getStartingPos()); handler.getLoadingScreen().setPlay("move"); directionx = (tempTile.getX() + 4 - x) / ANIM_TICKS; directiony = (tempTile.getY() - 48 - y) / ANIM_TICKS; tickcount++; } else if (tickcount > 0 && tickcount < ANIM_TICKS) { x += directionx; y += directiony; tickcount++; } else if (tickcount == ANIM_TICKS) { Tile tempTile = handler.getTile(handler.getPlayer().getStartingPos()); x = tempTile.getX() + 4; y = tempTile.getY() - 48; hitbox.x = (int) x; hitbox.y = (int) y; cisinbase = false; tickcount = 0; moving = false; tilesMoved=0; pos = new PositionOnMap(handler.getPlayer().getStartingPos()); bufferedPosition = getNextPosition(); handler.setCounterOnTile(pos, this); handler.getTimer().resetTimer(); handler.getDice().setRolled(false); if(handler.getPlayer().getRollsLeft()==0) handler.getPlayer().setRollsLeft(1); handler.getPlayer().setIsinbase(false); handler.getGameState().setRenderOrder(); } } else { if (tickcount == 0) { handler.removeCounterFromTile(pos, this); if (ultimateAbility) counterLogic(); handler.getLoadingScreen().setPlay("move"); renderBig(); directionx = (handler.getTile(bufferedPosition).getX() + 4 - x) / ANIM_TICKS; directiony = (handler.getTile(bufferedPosition).getY() - 48 - y) / ANIM_TICKS; tickcount++; } else if (tickcount > 0 && tickcount < ANIM_TICKS) { x += directionx; y += directiony; tickcount++; } else if (tickcount == ANIM_TICKS) { x = handler.getTile(bufferedPosition).getX() + 4; y = handler.getTile(bufferedPosition).getY() - 48; tickcount = 0; handler.removeCounterFromTile(pos, this); pos = bufferedPosition; handler.getPlayer().addPoint(); moved++; tilesMoved++; bufferedPosition = getNextPosition(); if ((moved != handler.getRoll())&&!won) handler.setCounterOnTile(pos, this); handler.getGameState().setRenderOrder(); if ((moved == handler.getRoll())||won) { moving = false; hitbox.x = (int) x; hitbox.y = (int) y; handler.setCounterOnTile(pos, this); handler.getDice().setRolled(false); handler.getGameState().setRenderOrder(); moved = 0; if (handler.getPlayer().getRollsLeft() == 0) handler.setTurnof(); } } } } else { handler.setTurnof(); handler.getPlayer().setRollsLeft(1); moving=false; handler.getDice().setRolled(false); handler.getTimer().resetTimer(); if(handler.getPlayer().getClass().getName()=="players.Bot") handler.getPlayer().setBotClicked(); } } private void resetLogic(){ if (tickcount == 0) { directionx = (basex - x) / (ANIM_TICKS*2); directiony = (basey - y) / (ANIM_TICKS*2); tickcount++; renderBig(); handler.getGameState().getPlayerByColor(counterColor).addDeath(); cisinbase = true; handler.getGameState().setRenderOrder(); } else if (tickcount > 0 && tickcount < ANIM_TICKS*2) { x += directionx; y += directiony; tickcount++; } else if (tickcount == ANIM_TICKS*2) { x = basex; y = basey; hitbox.x=(int)x; hitbox.y=(int)y; beaten=true; cfinished=false; tickcount = 0; reseting=false; pos = handler.getPlayer().getStartingPos(); //handler.getTimer().resetTimer(); //handler.getDice().setRolled(false); } } protected PositionOnMap getNextPosition(){ if(handler.getDice().getRoll()>0) { if (pos.arr == handler.getPlayer().getEndingPos().arr && pos.tile == handler.getPlayer().getEndingPos().tile&&tilesMoved>49) { if (ultBar) this.ultimateBar.setCanBeLoaded(false); return new PositionOnMap(handler.getTurnOf() + 1, 0); } else if (pos.tile == 51) return new PositionOnMap(0); else if (pos.arr > 0 && pos.tile == 5) { won = true; ultimateAbility = false; System.out.println("WON"); return new PositionOnMap(pos.arr, pos.tile); } else return new PositionOnMap(pos.arr, pos.tile + 1); } //do "cofanie" else if(handler.getDice().getRoll()==0) return new PositionOnMap(pos.arr, pos.tile); else{ if(pos.tile==0) return new PositionOnMap(51); else return new PositionOnMap(pos.arr, pos.tile - 1); } } public boolean isInbase() { return cisinbase; } protected void renderWasKilled(Graphics g){ //g.drawImage(Assets.); } protected abstract void counterLogic(); //true jeśli wraca do bazy, false jeśli nie public abstract boolean ifStepped(); public boolean hasUltBar(){ return this.ultBar; } public boolean isVulnerable(){ return this.vulnerable; } public void setMoving(boolean moving){ this.moving=moving; } public boolean isMoving(){ return this.moving; } public boolean isKillable(){ return this.killable; } public void renderUltBar(Graphics g){ if(ultimateBar!=null) ultimateBar.render(g); } public boolean isClicked(){ return this.hitbox.contains(handler.getMouseClickX(),handler.getMouseClickY()); } public void resetToBase(){ reseting=true; moving=false; cisinbase=true; handler.getGameState().addToReset(this); } public boolean getMoving(){ return this.moving; } public boolean getReseting(){ return this.reseting; } public BufferedImage getCounterColor(){ return this.counterColor; } public int getBaseX(){ return (int)this.basex; } public int getBaseY(){ return (int)this.basey; } public boolean canKill(){ return this.canKill; } public void useUltimateAbility(){ this.ultimateAbility=true; } public void setUltimateAbility(boolean ult){ this.ultimateAbility=ult; } public boolean isBeaten(){ return this.beaten; } public void renderSmall(float shiftX,float shiftY){ if(SCALE==1) { SCALE = 0.65; hitbox.setSize((int)(hitbox.width*SCALE),(int)(hitbox.height*SCALE)); } x=shiftX+4; y=shiftY-48; hitbox.setLocation((int)x,(int)y); } public void renderBig(float x,float y){ SCALE=1; hitbox.setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT); this.x=x; this.y=y; hitbox.setLocation((int)x,(int)y); } public void renderBig(){ SCALE=1; hitbox.setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT); } public UltimateBar getUltimateBar(){ return this.ultimateBar; } public boolean getWon(){ return this.won; } }
6901_0
package com.kodilla.collections.lists.homework; import com.kodilla.collections.arrays.homework.Car; import java.util.ArrayList; import java.util.List; public class CarsListApplication { public static void main(String[] args) { List<Car> cars = new ArrayList<>(); // carList intelij podpowiada - dlaczego? cars.add(new Car("VW", "T4",1997,150)); cars.add(new Car("Citroen", "Picasso",2020,180)); cars.add(new Car("Ford", "Fiesta",2006,130)); cars.add(new Car("Toyota", "Proace",2023,170)); for (Car addedCars : cars) { System.out.println(addedCars); } // usuwam T4 cars.remove(0); System.out.println(cars); // usuwam toyota Car carToRemove = new Car("Toyota", "Proace",2023,170); cars.remove(carToRemove); System.out.println(cars); System.out.println("Długość listy cars to: " + cars.size()); } }
Krzysztof-Switek/kodilla-course
kodilla-collections/src/main/java/com/kodilla/collections/lists/homework/CarsListApplication.java
344
// carList intelij podpowiada - dlaczego?
line_comment
pl
package com.kodilla.collections.lists.homework; import com.kodilla.collections.arrays.homework.Car; import java.util.ArrayList; import java.util.List; public class CarsListApplication { public static void main(String[] args) { List<Car> cars = new ArrayList<>(); // carList intelij <SUF> cars.add(new Car("VW", "T4",1997,150)); cars.add(new Car("Citroen", "Picasso",2020,180)); cars.add(new Car("Ford", "Fiesta",2006,130)); cars.add(new Car("Toyota", "Proace",2023,170)); for (Car addedCars : cars) { System.out.println(addedCars); } // usuwam T4 cars.remove(0); System.out.println(cars); // usuwam toyota Car carToRemove = new Car("Toyota", "Proace",2023,170); cars.remove(carToRemove); System.out.println(cars); System.out.println("Długość listy cars to: " + cars.size()); } }
5138_1
package org.tyszecki.rozkladpkp; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.util.HashMap; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.os.AsyncTask; import android.text.TextUtils; import android.text.format.Time; public class ExternalDelayFetcher { private static HashMap<String, Integer> delays = new HashMap<String, Integer>(); private static Time lastUpdate = null; public static interface ExternalDelayFetcherCallback{ void ready(HashMap<String, Integer> delays, boolean cached); } static boolean isUpToDate() { if(lastUpdate == null) { lastUpdate = new Time(); lastUpdate.setToNow(); } //Nie aktualizujmy za często. long umi = lastUpdate.toMillis(false); Time current = new Time(); current.setToNow(); long nmi = current.toMillis(false); return !(delays.isEmpty() || nmi-umi < 1000*60*3); } static HashMap<String, Integer> getDelays() { return delays; } static void requestUpdate(final ExternalDelayFetcherCallback callback) { class DealyTask extends AsyncTask<Void, Void, Void>{ @Override protected Void doInBackground(Void... arg0) { //Prosty skrypt w pythonie parsuje stronę PR i wysyła mi wyniki. //To lepsze niż parsowanie bezpośrednio w aplikacji: //- W Pythonie można to napisać łatwiej, //- Jeśli PR coś zmienią w formacie danych, wystarczy zmiana skryptu żeby działała ta aplikacja //- Mogę dodawać do skryptu dane o opóźnieniach z innych źródeł String url = "http://opoznienia.appspot.com"; DefaultHttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); request.addHeader("Content-Type", "application/x-www-form-urlencoded"); HttpResponse response = null; InputStream inputStream = null; try { response = client.execute(request); HttpEntity entity = response.getEntity(); inputStream = entity.getContent(); } catch (Exception e) { e.printStackTrace(); } ByteArrayOutputStream content = new ByteArrayOutputStream(); byte[] sBuffer = new byte[512]; // Read response into a buffered stream int readBytes = 0; try { while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } } catch (Exception e) { e.printStackTrace(); } // Return result from buffered stream TextUtils.StringSplitter lineSplitter = new TextUtils.SimpleStringSplitter('\n'); lineSplitter.setString(new String(content.toByteArray())); delays.clear(); for(String s : lineSplitter) { int col = s.indexOf(':'); try{ if(col > -1) delays.put(s.substring(0, col), Integer.parseInt(s.substring(col+1))); }catch(Exception e) { return null; } } return null; } protected void onPostExecute(Void result) { callback.ready(delays, false); } } new DealyTask().execute(null,null,null); } }
KrzysztofT/rozkladpkp-android
src/org/tyszecki/rozkladpkp/ExternalDelayFetcher.java
1,199
//Prosty skrypt w pythonie parsuje stronę PR i wysyła mi wyniki.
line_comment
pl
package org.tyszecki.rozkladpkp; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.util.HashMap; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.os.AsyncTask; import android.text.TextUtils; import android.text.format.Time; public class ExternalDelayFetcher { private static HashMap<String, Integer> delays = new HashMap<String, Integer>(); private static Time lastUpdate = null; public static interface ExternalDelayFetcherCallback{ void ready(HashMap<String, Integer> delays, boolean cached); } static boolean isUpToDate() { if(lastUpdate == null) { lastUpdate = new Time(); lastUpdate.setToNow(); } //Nie aktualizujmy za często. long umi = lastUpdate.toMillis(false); Time current = new Time(); current.setToNow(); long nmi = current.toMillis(false); return !(delays.isEmpty() || nmi-umi < 1000*60*3); } static HashMap<String, Integer> getDelays() { return delays; } static void requestUpdate(final ExternalDelayFetcherCallback callback) { class DealyTask extends AsyncTask<Void, Void, Void>{ @Override protected Void doInBackground(Void... arg0) { //Prosty skrypt <SUF> //To lepsze niż parsowanie bezpośrednio w aplikacji: //- W Pythonie można to napisać łatwiej, //- Jeśli PR coś zmienią w formacie danych, wystarczy zmiana skryptu żeby działała ta aplikacja //- Mogę dodawać do skryptu dane o opóźnieniach z innych źródeł String url = "http://opoznienia.appspot.com"; DefaultHttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); request.addHeader("Content-Type", "application/x-www-form-urlencoded"); HttpResponse response = null; InputStream inputStream = null; try { response = client.execute(request); HttpEntity entity = response.getEntity(); inputStream = entity.getContent(); } catch (Exception e) { e.printStackTrace(); } ByteArrayOutputStream content = new ByteArrayOutputStream(); byte[] sBuffer = new byte[512]; // Read response into a buffered stream int readBytes = 0; try { while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } } catch (Exception e) { e.printStackTrace(); } // Return result from buffered stream TextUtils.StringSplitter lineSplitter = new TextUtils.SimpleStringSplitter('\n'); lineSplitter.setString(new String(content.toByteArray())); delays.clear(); for(String s : lineSplitter) { int col = s.indexOf(':'); try{ if(col > -1) delays.put(s.substring(0, col), Integer.parseInt(s.substring(col+1))); }catch(Exception e) { return null; } } return null; } protected void onPostExecute(Void result) { callback.ready(delays, false); } } new DealyTask().execute(null,null,null); } }
3208_3
package dalsze.podstawy.daty.data.urodzenia; //Poproś program aby zapytal Cię o datę Twojego urodzenia //- jeśli podałeś datę późniejszą niż dziś to niech program rzuci // błędem: InvalidBirthDateException //- program wypisuje ile dni żyjesz już //- program wypisuje ile już miesiecy żyjesz //- program wypisuje już ile lat żyjesz //- program wypisuje w który dzień tygodnia się urodziłeś import java.time.DayOfWeek; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.time.temporal.ChronoUnit; public class Main { public static void main(String[] args) { String data = "14-10-199d5"; DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy"); LocalDate birthDate = null; try { birthDate = LocalDate.parse(data, dtf); czyDataJestWPrzyszlosci(birthDate); System.out.println(ileDniZyje(birthDate)); System.out.println(ileMiesiecyZyje(birthDate)); System.out.println(wJakimDniuSieUrodzil(birthDate)); } catch (DateTimeParseException e) { System.out.println(e.getMessage()); System.out.println("Nie mozna sparsowac daty"); } catch (InvalidBirthDateException e) { System.out.println(e.getMessage()); System.out.println("Nie mozesz podac daty w przyszlosci"); } } public static void czyDataJestWPrzyszlosci(LocalDate date) { if (date.isAfter(LocalDate.now())) { throw new InvalidBirthDateException("data nie moze byc pozniejsza niz dzisiaj"); } } public static long ileDniZyje(LocalDate date) { return ChronoUnit.DAYS.between(LocalDate.now(), date); } public static long ileMiesiecyZyje(LocalDate date) { return ChronoUnit.MONTHS.between(LocalDate.now(), date); } public static long ileLatZyje(LocalDate date) { return ChronoUnit.YEARS.between(LocalDate.now(), date); } public static DayOfWeek wJakimDniuSieUrodzil(LocalDate date) { return date.getDayOfWeek(); } }
KubaRajewski/Kurs
src/dalsze/podstawy/daty/data/urodzenia/Main.java
716
//- program wypisuje ile już miesiecy żyjesz
line_comment
pl
package dalsze.podstawy.daty.data.urodzenia; //Poproś program aby zapytal Cię o datę Twojego urodzenia //- jeśli podałeś datę późniejszą niż dziś to niech program rzuci // błędem: InvalidBirthDateException //- program wypisuje ile dni żyjesz już //- program <SUF> //- program wypisuje już ile lat żyjesz //- program wypisuje w który dzień tygodnia się urodziłeś import java.time.DayOfWeek; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.time.temporal.ChronoUnit; public class Main { public static void main(String[] args) { String data = "14-10-199d5"; DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy"); LocalDate birthDate = null; try { birthDate = LocalDate.parse(data, dtf); czyDataJestWPrzyszlosci(birthDate); System.out.println(ileDniZyje(birthDate)); System.out.println(ileMiesiecyZyje(birthDate)); System.out.println(wJakimDniuSieUrodzil(birthDate)); } catch (DateTimeParseException e) { System.out.println(e.getMessage()); System.out.println("Nie mozna sparsowac daty"); } catch (InvalidBirthDateException e) { System.out.println(e.getMessage()); System.out.println("Nie mozesz podac daty w przyszlosci"); } } public static void czyDataJestWPrzyszlosci(LocalDate date) { if (date.isAfter(LocalDate.now())) { throw new InvalidBirthDateException("data nie moze byc pozniejsza niz dzisiaj"); } } public static long ileDniZyje(LocalDate date) { return ChronoUnit.DAYS.between(LocalDate.now(), date); } public static long ileMiesiecyZyje(LocalDate date) { return ChronoUnit.MONTHS.between(LocalDate.now(), date); } public static long ileLatZyje(LocalDate date) { return ChronoUnit.YEARS.between(LocalDate.now(), date); } public static DayOfWeek wJakimDniuSieUrodzil(LocalDate date) { return date.getDayOfWeek(); } }
9027_2
package pl.edu.amu.wmi.daut.re; import java.util.Stack; import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import pl.edu.amu.wmi.daut.base.AutomatonSpecification; /** * Klasa z pomocniczymi funkcjami operującymi na wyrażeniach regularnych. */ public class RegexpUtilities { protected RegexpUtilities() { throw new UnsupportedOperationException(); } /** * Metoda, która z drzewa operatorów robi automat. */ public static AutomatonSpecification createAutomatonFromOperatorTree(RegexpOperatorTree tree) { //przejdź przez drzewo stanów metodą post-order, przy pomocy dwóch stosów. Stack<RegexpOperatorTree> child = new Stack<RegexpOperatorTree>(); Stack<RegexpOperatorTree> parent = new Stack<RegexpOperatorTree>(); child.push(tree); while (!child.empty()) { RegexpOperatorTree current = child.peek(); parent.push(current); child.pop(); for (RegexpOperatorTree subTree : current.getSubtrees()) child.push(subTree); } //na stosie "parent" mamy teraz wierzchołki w porządku post-order! //w porządku post-order chodzi o to, że zawsze zaczynamy od nieodwiedzonych liści //i idziemy powoli w kierunku korzenia drzewa. //utwórz mapę poddrzew na automaty przez nich utworzone. Map<RegexpOperatorTree, AutomatonSpecification> map = new HashMap<RegexpOperatorTree, AutomatonSpecification>(); while (!parent.empty()) { RegexpOperatorTree current = parent.peek(); //utwórz listę automatów utworzonych przez synów wierzchołka. List<AutomatonSpecification> arguments = new ArrayList<AutomatonSpecification>(); for (RegexpOperatorTree subTree : current.getSubtrees()) { //nie będzie tutaj odwołania do nieistniejących kluczy ze //wzgl. na charakter porządku post-order. jeśli wystąpi tutaj //exception, to znaczy, że źle zaimplementowaliśmy coś wcześniej. AutomatonSpecification subTreeAutomaton = map.get(subTree); arguments.add(subTreeAutomaton); } //utwórz automat, którego argumentami są automaty wszystkich synów. AutomatonSpecification currentAutomaton = current.getRoot().createAutomaton( arguments); //zapamiętaj automat dla danego wierzchołka. ponieważ liście się //wykonają "najpierw", to nadchodzący po tym rodzice tych liści //będą mieli pełną informację o automatach utworzonych przez //swoich synów... map.put(current, currentAutomaton); parent.pop(); //usunęliśmy właśnie wierzchołek-korzeń - zostaliśmy z pustym stosem, //możemy zwrócić automat. if (parent.empty()) return currentAutomaton; } throw new IllegalStateException(); } }
KubaZ/amu_automata_2011
daut-re/src/main/java/pl/edu/amu/wmi/daut/re/RegexpUtilities.java
890
//przejdź przez drzewo stanów metodą post-order, przy pomocy dwóch stosów.
line_comment
pl
package pl.edu.amu.wmi.daut.re; import java.util.Stack; import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import pl.edu.amu.wmi.daut.base.AutomatonSpecification; /** * Klasa z pomocniczymi funkcjami operującymi na wyrażeniach regularnych. */ public class RegexpUtilities { protected RegexpUtilities() { throw new UnsupportedOperationException(); } /** * Metoda, która z drzewa operatorów robi automat. */ public static AutomatonSpecification createAutomatonFromOperatorTree(RegexpOperatorTree tree) { //przejdź przez <SUF> Stack<RegexpOperatorTree> child = new Stack<RegexpOperatorTree>(); Stack<RegexpOperatorTree> parent = new Stack<RegexpOperatorTree>(); child.push(tree); while (!child.empty()) { RegexpOperatorTree current = child.peek(); parent.push(current); child.pop(); for (RegexpOperatorTree subTree : current.getSubtrees()) child.push(subTree); } //na stosie "parent" mamy teraz wierzchołki w porządku post-order! //w porządku post-order chodzi o to, że zawsze zaczynamy od nieodwiedzonych liści //i idziemy powoli w kierunku korzenia drzewa. //utwórz mapę poddrzew na automaty przez nich utworzone. Map<RegexpOperatorTree, AutomatonSpecification> map = new HashMap<RegexpOperatorTree, AutomatonSpecification>(); while (!parent.empty()) { RegexpOperatorTree current = parent.peek(); //utwórz listę automatów utworzonych przez synów wierzchołka. List<AutomatonSpecification> arguments = new ArrayList<AutomatonSpecification>(); for (RegexpOperatorTree subTree : current.getSubtrees()) { //nie będzie tutaj odwołania do nieistniejących kluczy ze //wzgl. na charakter porządku post-order. jeśli wystąpi tutaj //exception, to znaczy, że źle zaimplementowaliśmy coś wcześniej. AutomatonSpecification subTreeAutomaton = map.get(subTree); arguments.add(subTreeAutomaton); } //utwórz automat, którego argumentami są automaty wszystkich synów. AutomatonSpecification currentAutomaton = current.getRoot().createAutomaton( arguments); //zapamiętaj automat dla danego wierzchołka. ponieważ liście się //wykonają "najpierw", to nadchodzący po tym rodzice tych liści //będą mieli pełną informację o automatach utworzonych przez //swoich synów... map.put(current, currentAutomaton); parent.pop(); //usunęliśmy właśnie wierzchołek-korzeń - zostaliśmy z pustym stosem, //możemy zwrócić automat. if (parent.empty()) return currentAutomaton; } throw new IllegalStateException(); } }
5109_0
package LAB_6.examples; import javax.swing.*; public class G0 { public static void createAndShowGUI() { JFrame jf = new JFrame("My First Frame"); jf.pack(); jf.setVisible(true); } public static void main(String[] args) { System.out.println("Before"); javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); System.out.println("After"); } } /* Uwagi: Proszę sprawdzić co zrobić aby: - Aplikacja wyświetlała się na środku ekranu. - Cyfra 0 (oraz inne w polu z wynikiem) były pogrubione, czcionką Arial i z dosunięciem do prawej strony. - Pole z wynikiem nie powinno być edytowalne. - Zaś cała aplikacja ma mieć stały rozmiar i użytkownik nie może go zmieniać. */
Kurczaczek21/Object-oriented-Programming
src/LAB_6/examples/G0.java
297
/* Uwagi: Proszę sprawdzić co zrobić aby: - Aplikacja wyświetlała się na środku ekranu. - Cyfra 0 (oraz inne w polu z wynikiem) były pogrubione, czcionką Arial i z dosunięciem do prawej strony. - Pole z wynikiem nie powinno być edytowalne. - Zaś cała aplikacja ma mieć stały rozmiar i użytkownik nie może go zmieniać. */
block_comment
pl
package LAB_6.examples; import javax.swing.*; public class G0 { public static void createAndShowGUI() { JFrame jf = new JFrame("My First Frame"); jf.pack(); jf.setVisible(true); } public static void main(String[] args) { System.out.println("Before"); javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); System.out.println("After"); } } /* Uwagi: <SUF>*/
9874_2
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.nio.file.Path; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.DoubleStream; public class FoodProduct extends Product{ Map<String, List<Double>> pricesPerProvince = new HashMap<>(); public FoodProduct(String name, Map<String, List<Double>> pricesPerProvince) { super(name); this.pricesPerProvince = pricesPerProvince; } @Override public double getPrice(int year, int month) { return pricesPerProvince.keySet().stream() .map(key -> getPrice(year, month, key)) // weźmiemy nazwy województw i wyciągniemy z nich ceny dla każdego .flatMapToDouble(DoubleStream::of) // zamiana na listę doubli .average() // średnia .orElse(0); // jeśli się nie uda zrobić średniej to zwraca 0 } public static FoodProduct fromCsv(Path path){ try { BufferedReader bufferedReader = new BufferedReader(new FileReader(path.toFile())); String productName = bufferedReader.readLine(); bufferedReader.readLine(); // skip miesięcy String currentLine; Map<String, List<Double>> pricesPerProvince = new HashMap<>(); while ((currentLine = bufferedReader.readLine()) != null){ String[] parts = currentLine.split(";", -1); String province = parts[0]; List<Double> pricePerDate = List.of(parts).subList(1, parts.length - 1).stream() .map(string -> string.replaceAll(",", ".")) // zamiany "," z pliku na "." crtl + spacja robi strzałkę .map(Double::parseDouble) .toList(); //zamiana listy partsów na double pricesPerProvince.put(province, pricePerDate); // wszystkie województwa i wszystkie ich ceny } return new FoodProduct(productName, pricesPerProvince); } catch (IOException e) { throw new RuntimeException(e); } } public double getPrice(int year, int month, String province){ var prices = pricesPerProvince.get(province); int index = (year - 2010) * 12 + month - 1; //zmiana roku i miesiąca w indeks tabeli return prices.get(index); } }
Kwi4t3k/programowanie_java
kolos1_2022/src/FoodProduct.java
690
// jeśli się nie uda zrobić średniej to zwraca 0
line_comment
pl
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.nio.file.Path; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.DoubleStream; public class FoodProduct extends Product{ Map<String, List<Double>> pricesPerProvince = new HashMap<>(); public FoodProduct(String name, Map<String, List<Double>> pricesPerProvince) { super(name); this.pricesPerProvince = pricesPerProvince; } @Override public double getPrice(int year, int month) { return pricesPerProvince.keySet().stream() .map(key -> getPrice(year, month, key)) // weźmiemy nazwy województw i wyciągniemy z nich ceny dla każdego .flatMapToDouble(DoubleStream::of) // zamiana na listę doubli .average() // średnia .orElse(0); // jeśli się <SUF> } public static FoodProduct fromCsv(Path path){ try { BufferedReader bufferedReader = new BufferedReader(new FileReader(path.toFile())); String productName = bufferedReader.readLine(); bufferedReader.readLine(); // skip miesięcy String currentLine; Map<String, List<Double>> pricesPerProvince = new HashMap<>(); while ((currentLine = bufferedReader.readLine()) != null){ String[] parts = currentLine.split(";", -1); String province = parts[0]; List<Double> pricePerDate = List.of(parts).subList(1, parts.length - 1).stream() .map(string -> string.replaceAll(",", ".")) // zamiany "," z pliku na "." crtl + spacja robi strzałkę .map(Double::parseDouble) .toList(); //zamiana listy partsów na double pricesPerProvince.put(province, pricePerDate); // wszystkie województwa i wszystkie ich ceny } return new FoodProduct(productName, pricesPerProvince); } catch (IOException e) { throw new RuntimeException(e); } } public double getPrice(int year, int month, String province){ var prices = pricesPerProvince.get(province); int index = (year - 2010) * 12 + month - 1; //zmiana roku i miesiąca w indeks tabeli return prices.get(index); } }
2795_3
import java.time.LocalDate; public class Manager extends RegularEmployee { // klasa Manager nie musi implementować Serializable, bo dzidziczy go z nadklasy RegularEmployee, która go implementuje private static final long serialVersionUID = 1L; private static double maxBonus = 5000d; // atrybut klasowy - wszyscy managerowie mogą mieć maksymalnie bonus tej wysokości private double managersBaseSalary; // atrybut obiektowy - każdy manager może mieć inną bazę, typ prymityeny - nie sprawdzam czy null private double percentBonus; // opcjonalny i obiektowy, z ograniczeniem (przyjmuje wartości od 0 do 1) public Manager(String name, String surname, LocalDate birthDate, String contactData, double managersBaseSalary) { super(name, surname, birthDate, contactData); this.managersBaseSalary = managersBaseSalary; } public static double getMaxBonus() { return maxBonus; } public static void setMaxBonus(double maxBonus) { Manager.maxBonus = maxBonus; } public double getBonus() { return percentBonus; } public void setBonus(double percentBonus) throws Exception { if(percentBonus < 0.0 || percentBonus > 1.0) { throw new Exception("Percent bonus has to be in range between 0 and 1"); } this.percentBonus = percentBonus; } // przeciążanie metod, inaczej się liczy gdy nie ma bonusa i gdy jest bonus (wtedy jest parametr) public double countSalary() { return managersBaseSalary; } public double countSalary(double percentBonus) { return managersBaseSalary + (percentBonus * maxBonus); } @Override // przesłonięcie metody toString() public String toString() { String description = ""; description += "Name and Surname:\t\t|\t" + getName() + " " + getSurname() + " (MANAGER)"; description += "\nDate of Birth (age):\t|\t" + getBirthDate() + " (" + getAgeInYears() + " years old)"; description += "\nContact Information:\t|\t" + getContactData(); if(getFormalEducation().size() > 0) description += "\nFormal Education: \t\t|\t" + getFormalEducation().toString() + "\n"; else description += "\nFormal Education: \t\t|\tNo formal education to show\n"; return description; } }
LOpuchlik/pjatk
MAS/MAS_MP1_s16478/src/Manager.java
732
// opcjonalny i obiektowy, z ograniczeniem (przyjmuje wartości od 0 do 1)
line_comment
pl
import java.time.LocalDate; public class Manager extends RegularEmployee { // klasa Manager nie musi implementować Serializable, bo dzidziczy go z nadklasy RegularEmployee, która go implementuje private static final long serialVersionUID = 1L; private static double maxBonus = 5000d; // atrybut klasowy - wszyscy managerowie mogą mieć maksymalnie bonus tej wysokości private double managersBaseSalary; // atrybut obiektowy - każdy manager może mieć inną bazę, typ prymityeny - nie sprawdzam czy null private double percentBonus; // opcjonalny i <SUF> public Manager(String name, String surname, LocalDate birthDate, String contactData, double managersBaseSalary) { super(name, surname, birthDate, contactData); this.managersBaseSalary = managersBaseSalary; } public static double getMaxBonus() { return maxBonus; } public static void setMaxBonus(double maxBonus) { Manager.maxBonus = maxBonus; } public double getBonus() { return percentBonus; } public void setBonus(double percentBonus) throws Exception { if(percentBonus < 0.0 || percentBonus > 1.0) { throw new Exception("Percent bonus has to be in range between 0 and 1"); } this.percentBonus = percentBonus; } // przeciążanie metod, inaczej się liczy gdy nie ma bonusa i gdy jest bonus (wtedy jest parametr) public double countSalary() { return managersBaseSalary; } public double countSalary(double percentBonus) { return managersBaseSalary + (percentBonus * maxBonus); } @Override // przesłonięcie metody toString() public String toString() { String description = ""; description += "Name and Surname:\t\t|\t" + getName() + " " + getSurname() + " (MANAGER)"; description += "\nDate of Birth (age):\t|\t" + getBirthDate() + " (" + getAgeInYears() + " years old)"; description += "\nContact Information:\t|\t" + getContactData(); if(getFormalEducation().size() > 0) description += "\nFormal Education: \t\t|\t" + getFormalEducation().toString() + "\n"; else description += "\nFormal Education: \t\t|\tNo formal education to show\n"; return description; } }
8162_2
/** * * @author Reut Anton S24382 * */ package UTP31; import java.util.stream.Collectors; import java.util.*; /*<-- niezbędne importy */ public class Main1 { public static void main(String[] args) { // Lista destynacji: port_wylotu port_przylotu cena_EUR List<String> dest = Arrays.asList( "bleble bleble 2000", "WAW HAV 1200", "xxx yyy 789", "WAW DPS 2000", "WAW HKT 1000" ); double ratePLNvsEUR = 4.30; List<String> result = dest.stream().filter(element->element.startsWith("WAW")).map(element->{ String[] values = element.split(" ",3); int price = Integer.parseInt(values[2]); return "to "+values[1]+" - "+"price in PLN: " + (int)(price*ratePLNvsEUR); }).collect(Collectors.toList() /*<-- lambda wyrażenie * wyliczenie ceny przelotu w PLN * i stworzenie wynikowego napisu */ ); /*<-- tu należy dopisać fragment * przy czym nie wolno używać żadnych własnych klas, jak np. ListCreator * ani też żadnych własnych interfejsów * Podpowiedź: należy użyć strumieni */ for (String r : result) System.out.println(r); } }
LaneyBlack/Practices-UTP
UTP6_RA_S24382/src/UTP31/Main1.java
446
// Lista destynacji: port_wylotu port_przylotu cena_EUR
line_comment
pl
/** * * @author Reut Anton S24382 * */ package UTP31; import java.util.stream.Collectors; import java.util.*; /*<-- niezbędne importy */ public class Main1 { public static void main(String[] args) { // Lista destynacji: <SUF> List<String> dest = Arrays.asList( "bleble bleble 2000", "WAW HAV 1200", "xxx yyy 789", "WAW DPS 2000", "WAW HKT 1000" ); double ratePLNvsEUR = 4.30; List<String> result = dest.stream().filter(element->element.startsWith("WAW")).map(element->{ String[] values = element.split(" ",3); int price = Integer.parseInt(values[2]); return "to "+values[1]+" - "+"price in PLN: " + (int)(price*ratePLNvsEUR); }).collect(Collectors.toList() /*<-- lambda wyrażenie * wyliczenie ceny przelotu w PLN * i stworzenie wynikowego napisu */ ); /*<-- tu należy dopisać fragment * przy czym nie wolno używać żadnych własnych klas, jak np. ListCreator * ani też żadnych własnych interfejsów * Podpowiedź: należy użyć strumieni */ for (String r : result) System.out.println(r); } }
8366_1
package Evolution; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import java.util.*; import static java.lang.Math.toIntExact; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import org.json.simple.parser.ParseException; public class RectangularMap { private final Vector2d startOfTheMap = new Vector2d(0,0); private static final String filePath = "Evolution/parameters.json"; public final int width; public final int height; int moveEnergy = 1; int plantEnergy = 1; int numberOfGrass = 8; double jungleRatio = 0.25; protected final Vector2d endOfTheMap; public final Jungle jungle; public List<Animal> animalsList = new ArrayList<>(); protected Map<Vector2d, Grass> grassMap = new LinkedHashMap<>(); public RectangularMap(int width, int height) { this.width = width; this.height = height; this.endOfTheMap = new Vector2d(width - 1, height - 1); try (FileReader reader = new FileReader(ClassLoader.getSystemResource(filePath).getFile())) { JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(reader); this.moveEnergy = toIntExact((long) jsonObject.get("moveEnergy")); this.plantEnergy = toIntExact((long) jsonObject.get("plantEnergy")); this.numberOfGrass = toIntExact((long) jsonObject.get("initialNumberOfGrass"));; String s = (String) jsonObject.get("jungleRatio"); this.jungleRatio = Double.parseDouble(s); this.jungleRatio = Math.sqrt(this.jungleRatio); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } int jungleWidth = (int) Math.ceil(width *jungleRatio); int jungleHeight = (int) Math.ceil(height *jungleRatio); this.jungle = new Jungle(jungleWidth, jungleHeight); for (int i = 0; i < this.numberOfGrass; i++) { addGrass(); } } public void addGrass(){ //add in Jungle; if (!jungleIsFull()) { boolean toBeContinued = true; int forceToStop = 3000; //usprawnienie dla naprawdę dużej planszy while (toBeContinued) { toBeContinued = false; Vector2d pos = new Vector2d(getRandomNumberInRange(0, width - 1), getRandomNumberInRange(0, height - 1)); Grass insertGrass = new Grass(pos); if (grassMap.containsKey(insertGrass.getPosition())) { toBeContinued = true; forceToStop -= 1; } if (animalObjectAt(insertGrass.getPosition()).size() >= 1) { toBeContinued = true; forceToStop -= 1; } else if (!pos.precedes(jungle.endOfTheJungle) && pos.follows(jungle.startOfTheJungle)) { toBeContinued = true; forceToStop -= 1; } else this.grassMap.put(insertGrass.getPosition(), insertGrass); if (forceToStop <= 0) break; } } //add in step; if (!stepIsFull()) { boolean toBeContinued = true; int forceToStop = 3000; while (toBeContinued) { toBeContinued = false; Vector2d pos = new Vector2d(getRandomNumberInRange(0, width - 1), getRandomNumberInRange(0, height - 1)); Grass insertGrass = new Grass(pos); if (grassMap.containsKey(insertGrass.getPosition())) { toBeContinued = true; forceToStop -= 1; } if (animalObjectAt(insertGrass.getPosition()).size() >= 1) { toBeContinued = true; forceToStop -= 1; } else if (pos.precedes(jungle.endOfTheJungle) && pos.follows(jungle.startOfTheJungle)) { toBeContinued = true; forceToStop -= 1; } else this.grassMap.put(insertGrass.getPosition(), insertGrass); if (forceToStop <= 0) return; } } } public boolean jungleIsFull(){ for (int i = 0; i<jungle.width; i++) for (int j = 0; j<jungle.height; j++){ if ( !isOccupied(new Vector2d(i,j))) return false; } return true; } public boolean stepIsFull(){ for (int i = jungle.width; i<width; i++) for (int j = 0; j<jungle.height; j++){ if ( !isOccupied(new Vector2d(i,j))) return false; } for (int i = 0; i<width; i++) for (int j = jungle.height; j<height; j++){ if ( isOccupied(new Vector2d(i,j))) return false; } return true; } private static int getRandomNumberInRange(int min, int max) { if (min >= max) { throw new IllegalArgumentException("max must be greater than min"); } Random r = new Random(); return r.nextInt((max - min) + 1) + min; } public String toString(){ MapVisualizer mapVisualizer = new MapVisualizer(this); StringBuilder builder = new StringBuilder(); builder.append(mapVisualizer.draw(this.startOfTheMap, this.endOfTheMap)); return builder.toString(); } public boolean isOccupied(Vector2d position) { for (int i=0; i<animalsList.size(); i++){ if (this.animalsList.get(i).getPosition().equals(position)) return true; } if (grassMap.containsKey(position)) return true; return false; } public void place(Animal animal) { this.animalsList.add(animal); } public Object objectAt(Vector2d position) { for (int i=0; i<animalsList.size(); i++) { if (this.animalsList.get(i).getPosition().equals(position)) return animalsList.get(i); } return (grassObjectAt(position)); } public Grass grassObjectAt (Vector2d position){ if (this.grassMap.containsKey(position)) return this.grassMap.get(position); return null; } public List<Animal> animalObjectAt (Vector2d position){ List<Animal> rivals = new ArrayList<>(); for (int i=0; i<animalsList.size(); i++) { if (this.animalsList.get(i).getPosition().equals(position)) rivals.add(animalsList.get(i)); } return rivals; } public List<Animal> strongAnimalObjectAt (Vector2d position){ List<Animal> rivals = new ArrayList<>(); for (int i=0; i<animalsList.size(); i++) { if (this.animalsList.get(i).getPosition().equals(position) && this.animalsList.get(i).getEnergyDay()>=Animal.startEnergy/2) rivals.add(animalsList.get(i)); } return rivals; } public void eatGrassAt (Vector2d position){ this.grassMap.remove(position); List<Animal> rivals = strongAnimalObjectAt(position); if (rivals.size() == 1) {rivals.get(0).energyDay += plantEnergy; return;} double maxEnergyDay = 0; for (int i=0; i<rivals.size(); i++){ if (rivals.get(i).getEnergyDay()>maxEnergyDay) maxEnergyDay = rivals.get(i).getEnergyDay(); } int animalsToShare = 0; for (int i=0; i<rivals.size(); i++){ if (rivals.get(i).getEnergyDay() == maxEnergyDay) animalsToShare += 1; } for (int i=0; i<rivals.size(); i++){ if (rivals.get(i).getEnergyDay() == maxEnergyDay) rivals.get(i).energyDay += (plantEnergy/animalsToShare); } } public void copulateAt(Vector2d position) { List<Animal> rivals = animalObjectAt(position); if (rivals.size() == 2) {makeChild(rivals.get(0),rivals.get(1)); return;} double maxEnergyDay = 0; int maxEnergyHolders = 0; for (int i=0; i<rivals.size(); i++){ if (rivals.get(i).getEnergyDay()>maxEnergyDay){ maxEnergyDay = rivals.get(i).getEnergyDay(); maxEnergyHolders = 1; } if (rivals.get(i).getEnergyDay()==maxEnergyDay) maxEnergyHolders += 1; } Animal parent1 = null; Animal parent2 = null; if (maxEnergyHolders >= 2){ for (int i=0; i<rivals.size(); i++){ if (rivals.get(i).getEnergyDay() == maxEnergyDay) { if (parent1 == null) parent1 = rivals.get(i); else { parent2 = rivals.get(i); makeChild(parent1,parent2); return; } } } } else { for (int i=0; i<rivals.size(); i++){ if (rivals.get(i).getEnergyDay() == maxEnergyDay) parent1 = rivals.get(i); } double secMaxEnergyDay = 0; for (int i=0; i<rivals.size(); i++){ if (rivals.get(i).getEnergyDay() >= secMaxEnergyDay && rivals.get(i).getEnergyDay() < maxEnergyDay) secMaxEnergyDay = rivals.get(i).getEnergyDay(); } for (int i=0; i<rivals.size(); i++){ if (rivals.get(i).getEnergyDay() == secMaxEnergyDay) parent2 = rivals.get(i); } makeChild(parent1, parent2); } } private void makeChild(Animal parent1, Animal parent2) { int cut1 = getRandomNumberInRange(0,32); int cut2 = getRandomNumberInRange(0,32); if(cut1>cut2){ int t = cut2; cut2 = cut1; cut1 = t; } final MoveDirection [] genotype = new MoveDirection[32]; for (int i=0; i<cut1; i++) genotype[i] = parent1.genotype[i]; for (int i=cut1; i<cut2; i++) genotype[i] = parent2.genotype[i]; for (int i=cut2; i<32; i++) genotype[i] = parent1.genotype[i]; parent1.energyDay = (parent1.energyDay * 3)/4; parent2.energyDay = (parent2.energyDay * 3)/4; parent1.noChildren += 1; parent2.noChildren += 1; Animal child = new Animal(this,parent1.getPosition().randomNeighbour(), genotype); child.energyDay = parent1.energyDay/3 + parent2.energyDay/3; child.repairGenotype(); return; } private void removingDead(){ for (int i=0; i<animalsList.size(); i++) if(animalsList.get(i).getEnergyDay() <= 0) animalsList.remove(animalsList.get(i)); } private void running() { for (int i=0; i<animalsList.size(); i++) animalsList.get(i).move(); } private void eating(){ for (int i=0; i<animalsList.size(); i++) animalsList.get(i).tryToEat(); } private void copulating(){ List<Vector2d> places = new ArrayList<>(); for (int i=0; i<animalsList.size(); i++) if(animalsList.get(i).tryToCopulate()) { Vector2d place = animalsList.get(i).getPosition(); boolean newPlace = true; for(int j=0; j<places.size(); j++){ if(places.get(j).equals(place)) newPlace = false; } if (newPlace) places.add(place); } for (int i =0; i<places.size(); i++){ copulateAt(places.get(i)); } } private void sleeping(){ for (int i=0; i<animalsList.size(); i++) animalsList.get(i).energyDay -= moveEnergy; } public void anotherDay(){ removingDead(); running(); eating(); copulating(); sleeping(); addGrass(); } }
Latropos/MyEvolutionProject
MyEvolutionProject/src/Evolution/RectangularMap.java
3,780
//usprawnienie dla naprawdę dużej planszy
line_comment
pl
package Evolution; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import java.util.*; import static java.lang.Math.toIntExact; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import org.json.simple.parser.ParseException; public class RectangularMap { private final Vector2d startOfTheMap = new Vector2d(0,0); private static final String filePath = "Evolution/parameters.json"; public final int width; public final int height; int moveEnergy = 1; int plantEnergy = 1; int numberOfGrass = 8; double jungleRatio = 0.25; protected final Vector2d endOfTheMap; public final Jungle jungle; public List<Animal> animalsList = new ArrayList<>(); protected Map<Vector2d, Grass> grassMap = new LinkedHashMap<>(); public RectangularMap(int width, int height) { this.width = width; this.height = height; this.endOfTheMap = new Vector2d(width - 1, height - 1); try (FileReader reader = new FileReader(ClassLoader.getSystemResource(filePath).getFile())) { JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(reader); this.moveEnergy = toIntExact((long) jsonObject.get("moveEnergy")); this.plantEnergy = toIntExact((long) jsonObject.get("plantEnergy")); this.numberOfGrass = toIntExact((long) jsonObject.get("initialNumberOfGrass"));; String s = (String) jsonObject.get("jungleRatio"); this.jungleRatio = Double.parseDouble(s); this.jungleRatio = Math.sqrt(this.jungleRatio); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } int jungleWidth = (int) Math.ceil(width *jungleRatio); int jungleHeight = (int) Math.ceil(height *jungleRatio); this.jungle = new Jungle(jungleWidth, jungleHeight); for (int i = 0; i < this.numberOfGrass; i++) { addGrass(); } } public void addGrass(){ //add in Jungle; if (!jungleIsFull()) { boolean toBeContinued = true; int forceToStop = 3000; //usprawnienie dla <SUF> while (toBeContinued) { toBeContinued = false; Vector2d pos = new Vector2d(getRandomNumberInRange(0, width - 1), getRandomNumberInRange(0, height - 1)); Grass insertGrass = new Grass(pos); if (grassMap.containsKey(insertGrass.getPosition())) { toBeContinued = true; forceToStop -= 1; } if (animalObjectAt(insertGrass.getPosition()).size() >= 1) { toBeContinued = true; forceToStop -= 1; } else if (!pos.precedes(jungle.endOfTheJungle) && pos.follows(jungle.startOfTheJungle)) { toBeContinued = true; forceToStop -= 1; } else this.grassMap.put(insertGrass.getPosition(), insertGrass); if (forceToStop <= 0) break; } } //add in step; if (!stepIsFull()) { boolean toBeContinued = true; int forceToStop = 3000; while (toBeContinued) { toBeContinued = false; Vector2d pos = new Vector2d(getRandomNumberInRange(0, width - 1), getRandomNumberInRange(0, height - 1)); Grass insertGrass = new Grass(pos); if (grassMap.containsKey(insertGrass.getPosition())) { toBeContinued = true; forceToStop -= 1; } if (animalObjectAt(insertGrass.getPosition()).size() >= 1) { toBeContinued = true; forceToStop -= 1; } else if (pos.precedes(jungle.endOfTheJungle) && pos.follows(jungle.startOfTheJungle)) { toBeContinued = true; forceToStop -= 1; } else this.grassMap.put(insertGrass.getPosition(), insertGrass); if (forceToStop <= 0) return; } } } public boolean jungleIsFull(){ for (int i = 0; i<jungle.width; i++) for (int j = 0; j<jungle.height; j++){ if ( !isOccupied(new Vector2d(i,j))) return false; } return true; } public boolean stepIsFull(){ for (int i = jungle.width; i<width; i++) for (int j = 0; j<jungle.height; j++){ if ( !isOccupied(new Vector2d(i,j))) return false; } for (int i = 0; i<width; i++) for (int j = jungle.height; j<height; j++){ if ( isOccupied(new Vector2d(i,j))) return false; } return true; } private static int getRandomNumberInRange(int min, int max) { if (min >= max) { throw new IllegalArgumentException("max must be greater than min"); } Random r = new Random(); return r.nextInt((max - min) + 1) + min; } public String toString(){ MapVisualizer mapVisualizer = new MapVisualizer(this); StringBuilder builder = new StringBuilder(); builder.append(mapVisualizer.draw(this.startOfTheMap, this.endOfTheMap)); return builder.toString(); } public boolean isOccupied(Vector2d position) { for (int i=0; i<animalsList.size(); i++){ if (this.animalsList.get(i).getPosition().equals(position)) return true; } if (grassMap.containsKey(position)) return true; return false; } public void place(Animal animal) { this.animalsList.add(animal); } public Object objectAt(Vector2d position) { for (int i=0; i<animalsList.size(); i++) { if (this.animalsList.get(i).getPosition().equals(position)) return animalsList.get(i); } return (grassObjectAt(position)); } public Grass grassObjectAt (Vector2d position){ if (this.grassMap.containsKey(position)) return this.grassMap.get(position); return null; } public List<Animal> animalObjectAt (Vector2d position){ List<Animal> rivals = new ArrayList<>(); for (int i=0; i<animalsList.size(); i++) { if (this.animalsList.get(i).getPosition().equals(position)) rivals.add(animalsList.get(i)); } return rivals; } public List<Animal> strongAnimalObjectAt (Vector2d position){ List<Animal> rivals = new ArrayList<>(); for (int i=0; i<animalsList.size(); i++) { if (this.animalsList.get(i).getPosition().equals(position) && this.animalsList.get(i).getEnergyDay()>=Animal.startEnergy/2) rivals.add(animalsList.get(i)); } return rivals; } public void eatGrassAt (Vector2d position){ this.grassMap.remove(position); List<Animal> rivals = strongAnimalObjectAt(position); if (rivals.size() == 1) {rivals.get(0).energyDay += plantEnergy; return;} double maxEnergyDay = 0; for (int i=0; i<rivals.size(); i++){ if (rivals.get(i).getEnergyDay()>maxEnergyDay) maxEnergyDay = rivals.get(i).getEnergyDay(); } int animalsToShare = 0; for (int i=0; i<rivals.size(); i++){ if (rivals.get(i).getEnergyDay() == maxEnergyDay) animalsToShare += 1; } for (int i=0; i<rivals.size(); i++){ if (rivals.get(i).getEnergyDay() == maxEnergyDay) rivals.get(i).energyDay += (plantEnergy/animalsToShare); } } public void copulateAt(Vector2d position) { List<Animal> rivals = animalObjectAt(position); if (rivals.size() == 2) {makeChild(rivals.get(0),rivals.get(1)); return;} double maxEnergyDay = 0; int maxEnergyHolders = 0; for (int i=0; i<rivals.size(); i++){ if (rivals.get(i).getEnergyDay()>maxEnergyDay){ maxEnergyDay = rivals.get(i).getEnergyDay(); maxEnergyHolders = 1; } if (rivals.get(i).getEnergyDay()==maxEnergyDay) maxEnergyHolders += 1; } Animal parent1 = null; Animal parent2 = null; if (maxEnergyHolders >= 2){ for (int i=0; i<rivals.size(); i++){ if (rivals.get(i).getEnergyDay() == maxEnergyDay) { if (parent1 == null) parent1 = rivals.get(i); else { parent2 = rivals.get(i); makeChild(parent1,parent2); return; } } } } else { for (int i=0; i<rivals.size(); i++){ if (rivals.get(i).getEnergyDay() == maxEnergyDay) parent1 = rivals.get(i); } double secMaxEnergyDay = 0; for (int i=0; i<rivals.size(); i++){ if (rivals.get(i).getEnergyDay() >= secMaxEnergyDay && rivals.get(i).getEnergyDay() < maxEnergyDay) secMaxEnergyDay = rivals.get(i).getEnergyDay(); } for (int i=0; i<rivals.size(); i++){ if (rivals.get(i).getEnergyDay() == secMaxEnergyDay) parent2 = rivals.get(i); } makeChild(parent1, parent2); } } private void makeChild(Animal parent1, Animal parent2) { int cut1 = getRandomNumberInRange(0,32); int cut2 = getRandomNumberInRange(0,32); if(cut1>cut2){ int t = cut2; cut2 = cut1; cut1 = t; } final MoveDirection [] genotype = new MoveDirection[32]; for (int i=0; i<cut1; i++) genotype[i] = parent1.genotype[i]; for (int i=cut1; i<cut2; i++) genotype[i] = parent2.genotype[i]; for (int i=cut2; i<32; i++) genotype[i] = parent1.genotype[i]; parent1.energyDay = (parent1.energyDay * 3)/4; parent2.energyDay = (parent2.energyDay * 3)/4; parent1.noChildren += 1; parent2.noChildren += 1; Animal child = new Animal(this,parent1.getPosition().randomNeighbour(), genotype); child.energyDay = parent1.energyDay/3 + parent2.energyDay/3; child.repairGenotype(); return; } private void removingDead(){ for (int i=0; i<animalsList.size(); i++) if(animalsList.get(i).getEnergyDay() <= 0) animalsList.remove(animalsList.get(i)); } private void running() { for (int i=0; i<animalsList.size(); i++) animalsList.get(i).move(); } private void eating(){ for (int i=0; i<animalsList.size(); i++) animalsList.get(i).tryToEat(); } private void copulating(){ List<Vector2d> places = new ArrayList<>(); for (int i=0; i<animalsList.size(); i++) if(animalsList.get(i).tryToCopulate()) { Vector2d place = animalsList.get(i).getPosition(); boolean newPlace = true; for(int j=0; j<places.size(); j++){ if(places.get(j).equals(place)) newPlace = false; } if (newPlace) places.add(place); } for (int i =0; i<places.size(); i++){ copulateAt(places.get(i)); } } private void sleeping(){ for (int i=0; i<animalsList.size(); i++) animalsList.get(i).energyDay -= moveEnergy; } public void anotherDay(){ removingDead(); running(); eating(); copulating(); sleeping(); addGrass(); } }
3402_3
package tillerino.tillerinobot.lang; import java.util.List; import java.util.Random; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import tillerino.tillerinobot.BeatmapMeta; import tillerino.tillerinobot.IRCBot.IRCBotUser; import tillerino.tillerinobot.RecommendationsManager.Recommendation; /** * Polish language implementation by https://osu.ppy.sh/u/pawwit */ public class Polski implements Language { @Override public String unknownBeatmap() { return "Przykro mi, nie znam tej mapy. Możliwe że jest ona nowa albo nierankingowa."; } @Override public String internalException(String marker) { return "Ugh... Wygląda na to że Tillerino (człowiek) uszkodził moje obwody." + "Gdyby wkrótce tego nie zauważył, Możesz go poinformować? Znajdziesz go na @Tillerino lub /u/Tillerino? (odwołanie " + marker + ")"; } @Override public String externalException(String marker) { return "Co jest?! Odpowiedź serwera osu nie ma sensu. Możesz mi powiedzieć co to znaczy \"0011101001010000\"?" + " Tillerino (człowiek) mówi, żeby się tym nie przejmować oraz że powinniśmy spróbować jeszcze raz." + " Jeśli jesteś bardzo zaniepokojony z jakiegoś powodu, możesz mu powiedzieć o tym na @Tillerino lub /u/Tillerino. (odwołanie " + marker + ")"; } @Override public String noInformationForModsShort() { return "brak danych dla wskazanych modów"; } @Override public void welcomeUser(IRCBotUser user, OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { user.message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { user.message("Witaj ponownie, " + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { user.message(apiUser.getUserName() + "..."); user.message("...czy to Ty? Minęło sporo czasu!"); user.message("Dobrze znowu Cie widzieć. Chcesz usłyszeć kilka rekomendacji?"); } else { String[] messages = { "wygląda na to że chcesz jakieś rekomendacje.", "jak dobrze Cie widzieć! :)", "mój ulubiony człowiek. (Nie mów o tym innym ludziom!)", "jakie miłe zaskoczenie! ^.^", "Miałem nadzieję, że się pojawisz. Jesteś fajniejszy niż inni ludzie :3 (nie mówi im że Ci to powiedziałem!)", "jak się masz?", }; Random random = new Random(); String message = messages[random.nextInt(messages.length)]; user.message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "nieznana komenda \"" + command + "\". jeśli potrzebujesz pomocy napisz \"!help\" !"; } @Override public String noInformationForMods() { return "Przykro mi, nie mogę dostarczyć informacji dla tych modów w tym momencie."; } @Override public String malformattedMods(String mods) { return "Coś się nie zgadza. Mody mogą być dowolną kombinacją DT HR HD HT EZ NC FL SO NF. Łącz je nie używając spacji, ani żadnych znaków. Przykład: !with HDHR, !with DTEZ"; } @Override public String noLastSongInfo() { return "Nie pamiętam żebyś pytał się ostatnio o jakąś piosenkę..."; } @Override public String tryWithMods() { return "Spróbuj zagrać tą mapę z modami!"; } @Override public String tryWithMods(List<Mods> mods) { return "Spróbuj zagrać tą mapę z " + Mods.toShortNamesContinuous(mods); } /** * The user's IRC nick name could not be resolved to an osu user id. The * message should suggest to contact @Tillerinobot or /u/Tillerino. * * @param exceptionMarker * a marker to reference the created log entry. six or eight * characters. * @param name * the irc nick which could not be resolved * @return */ public String unresolvableName(String exceptionMarker, String name) { return "Twoja nazwa wydaje mi się jakaś dziwna. Jesteś zbanowany? Jeśli nie napisz na @Tillerino lub /u/Tillerino (odwołanie " + exceptionMarker + ")"; } @Override public String excuseForError() { return "Wybacz, widziałem piękną sekwencję zer i jedynek przez co się trochę rozkojarzyłem. Mógłbyś powtórzyć co chciałeś?"; } @Override public String complaint() { return "Twoje zgłoszenie zostało wypełnione. Tillerino zerknie na nie jak tylko będzie mógł."; } @Override public void hug(final IRCBotUser user, OsuApiUser apiUser) { user.message("Chodź tu!"); user.action("przytula " + apiUser.getUserName()); } @Override public String help() { return "Hej! Jestem robotem który zabił Tillerino, aby przejąc jego konto. Tylko żartowałem, czasem używam tego konta." + " Sprawdź https://twitter.com/Tillerinobot żeby zobaczyć najnowsze aktualizacje!" + " Odwiedź https://github.com/Tillerino/Tillerinobot/wiki żeby poznać komendy!"; } @Override public String faq() { return "Wejdź na https://github.com/Tillerino/Tillerinobot/wiki/FAQ aby zobaczyć FAQ!"; } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Przepraszam, ale w tym momencie " + feature + " jest dostępna tylko dla ludzi którzy przekroczyli pozycję " + minRank + " w rankingu."; } @Override public String mixedNomodAndMods() { return "Jak chcesz połączyć brak modów z modami?"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Skończyły mi się pomysł co mogę Ci jeszcze polecić]." + " Sprawdź inne opcje polecania albo użyj komendy !reset. Jeśli nie wiesz o co mi chodzi wpisz !help."; } @Override public String notRanked() { return "Wygląda na to, że ta mapa nie jest rankingowa."; } @Override public void optionalCommentOnNP(IRCBotUser user, OsuApiUser apiUser, BeatmapMeta meta) { // regular Tillerino doesn't comment on this // return "Ok, zapamiętam tą mapę!"; } @Override public void optionalCommentOnWith(IRCBotUser user, OsuApiUser apiUser, BeatmapMeta meta) { // regular Tillerino doesn't comment on this // return "Ok, zapamiętam te mody"; } @Override public void optionalCommentOnRecommendation(IRCBotUser user, OsuApiUser apiUser, Recommendation meta) { // regular Tillerino doesn't comment on this // I have no idea what Tillerino can say with recommendation } @Override public boolean isChanged() { return false; } @Override public void setChanged(boolean changed) { } @Override public String invalidAccuracy(String acc) { return "Nieprawidłowa celność: \"" + acc + "\""; } @Override public void optionalCommentOnLanguage(IRCBotUser user, OsuApiUser apiUser) { user.message("Pawwit nauczył mnie jak mówić po polsku, jeśli uważasz, że gdzieś się pomylił napisz do niego na osu!"); } @Override public String invalidChoice(String invalid, String choices) { return "Wybacz, nie wiem co \"" + invalid + "\" znaczy. Spróbuj: " + choices + "!"; } @Override public String setFormat() { return "Składnia polecenia \"!set\" jest następująca \"!set opcja wartość\". Wpisz !help jeśli potrzebujesz więcej wskazówek."; } @Override public String apiTimeoutException() { return new Default().apiTimeoutException(); } @Override public String noRecentPlays() { return new Default().noRecentPlays(); } @Override public String isSetId() { return new Default().isSetId(); } @Override public String getPatience() { return new Default().getPatience(); } }
Liby99/Tillerinobot
tillerinobot/src/main/java/tillerino/tillerinobot/lang/Polski.java
2,936
//github.com/Tillerino/Tillerinobot/wiki żeby poznać komendy!";
line_comment
pl
package tillerino.tillerinobot.lang; import java.util.List; import java.util.Random; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import tillerino.tillerinobot.BeatmapMeta; import tillerino.tillerinobot.IRCBot.IRCBotUser; import tillerino.tillerinobot.RecommendationsManager.Recommendation; /** * Polish language implementation by https://osu.ppy.sh/u/pawwit */ public class Polski implements Language { @Override public String unknownBeatmap() { return "Przykro mi, nie znam tej mapy. Możliwe że jest ona nowa albo nierankingowa."; } @Override public String internalException(String marker) { return "Ugh... Wygląda na to że Tillerino (człowiek) uszkodził moje obwody." + "Gdyby wkrótce tego nie zauważył, Możesz go poinformować? Znajdziesz go na @Tillerino lub /u/Tillerino? (odwołanie " + marker + ")"; } @Override public String externalException(String marker) { return "Co jest?! Odpowiedź serwera osu nie ma sensu. Możesz mi powiedzieć co to znaczy \"0011101001010000\"?" + " Tillerino (człowiek) mówi, żeby się tym nie przejmować oraz że powinniśmy spróbować jeszcze raz." + " Jeśli jesteś bardzo zaniepokojony z jakiegoś powodu, możesz mu powiedzieć o tym na @Tillerino lub /u/Tillerino. (odwołanie " + marker + ")"; } @Override public String noInformationForModsShort() { return "brak danych dla wskazanych modów"; } @Override public void welcomeUser(IRCBotUser user, OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { user.message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { user.message("Witaj ponownie, " + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { user.message(apiUser.getUserName() + "..."); user.message("...czy to Ty? Minęło sporo czasu!"); user.message("Dobrze znowu Cie widzieć. Chcesz usłyszeć kilka rekomendacji?"); } else { String[] messages = { "wygląda na to że chcesz jakieś rekomendacje.", "jak dobrze Cie widzieć! :)", "mój ulubiony człowiek. (Nie mów o tym innym ludziom!)", "jakie miłe zaskoczenie! ^.^", "Miałem nadzieję, że się pojawisz. Jesteś fajniejszy niż inni ludzie :3 (nie mówi im że Ci to powiedziałem!)", "jak się masz?", }; Random random = new Random(); String message = messages[random.nextInt(messages.length)]; user.message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "nieznana komenda \"" + command + "\". jeśli potrzebujesz pomocy napisz \"!help\" !"; } @Override public String noInformationForMods() { return "Przykro mi, nie mogę dostarczyć informacji dla tych modów w tym momencie."; } @Override public String malformattedMods(String mods) { return "Coś się nie zgadza. Mody mogą być dowolną kombinacją DT HR HD HT EZ NC FL SO NF. Łącz je nie używając spacji, ani żadnych znaków. Przykład: !with HDHR, !with DTEZ"; } @Override public String noLastSongInfo() { return "Nie pamiętam żebyś pytał się ostatnio o jakąś piosenkę..."; } @Override public String tryWithMods() { return "Spróbuj zagrać tą mapę z modami!"; } @Override public String tryWithMods(List<Mods> mods) { return "Spróbuj zagrać tą mapę z " + Mods.toShortNamesContinuous(mods); } /** * The user's IRC nick name could not be resolved to an osu user id. The * message should suggest to contact @Tillerinobot or /u/Tillerino. * * @param exceptionMarker * a marker to reference the created log entry. six or eight * characters. * @param name * the irc nick which could not be resolved * @return */ public String unresolvableName(String exceptionMarker, String name) { return "Twoja nazwa wydaje mi się jakaś dziwna. Jesteś zbanowany? Jeśli nie napisz na @Tillerino lub /u/Tillerino (odwołanie " + exceptionMarker + ")"; } @Override public String excuseForError() { return "Wybacz, widziałem piękną sekwencję zer i jedynek przez co się trochę rozkojarzyłem. Mógłbyś powtórzyć co chciałeś?"; } @Override public String complaint() { return "Twoje zgłoszenie zostało wypełnione. Tillerino zerknie na nie jak tylko będzie mógł."; } @Override public void hug(final IRCBotUser user, OsuApiUser apiUser) { user.message("Chodź tu!"); user.action("przytula " + apiUser.getUserName()); } @Override public String help() { return "Hej! Jestem robotem który zabił Tillerino, aby przejąc jego konto. Tylko żartowałem, czasem używam tego konta." + " Sprawdź https://twitter.com/Tillerinobot żeby zobaczyć najnowsze aktualizacje!" + " Odwiedź https://github.com/Tillerino/Tillerinobot/wiki żeby <SUF> } @Override public String faq() { return "Wejdź na https://github.com/Tillerino/Tillerinobot/wiki/FAQ aby zobaczyć FAQ!"; } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Przepraszam, ale w tym momencie " + feature + " jest dostępna tylko dla ludzi którzy przekroczyli pozycję " + minRank + " w rankingu."; } @Override public String mixedNomodAndMods() { return "Jak chcesz połączyć brak modów z modami?"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Skończyły mi się pomysł co mogę Ci jeszcze polecić]." + " Sprawdź inne opcje polecania albo użyj komendy !reset. Jeśli nie wiesz o co mi chodzi wpisz !help."; } @Override public String notRanked() { return "Wygląda na to, że ta mapa nie jest rankingowa."; } @Override public void optionalCommentOnNP(IRCBotUser user, OsuApiUser apiUser, BeatmapMeta meta) { // regular Tillerino doesn't comment on this // return "Ok, zapamiętam tą mapę!"; } @Override public void optionalCommentOnWith(IRCBotUser user, OsuApiUser apiUser, BeatmapMeta meta) { // regular Tillerino doesn't comment on this // return "Ok, zapamiętam te mody"; } @Override public void optionalCommentOnRecommendation(IRCBotUser user, OsuApiUser apiUser, Recommendation meta) { // regular Tillerino doesn't comment on this // I have no idea what Tillerino can say with recommendation } @Override public boolean isChanged() { return false; } @Override public void setChanged(boolean changed) { } @Override public String invalidAccuracy(String acc) { return "Nieprawidłowa celność: \"" + acc + "\""; } @Override public void optionalCommentOnLanguage(IRCBotUser user, OsuApiUser apiUser) { user.message("Pawwit nauczył mnie jak mówić po polsku, jeśli uważasz, że gdzieś się pomylił napisz do niego na osu!"); } @Override public String invalidChoice(String invalid, String choices) { return "Wybacz, nie wiem co \"" + invalid + "\" znaczy. Spróbuj: " + choices + "!"; } @Override public String setFormat() { return "Składnia polecenia \"!set\" jest następująca \"!set opcja wartość\". Wpisz !help jeśli potrzebujesz więcej wskazówek."; } @Override public String apiTimeoutException() { return new Default().apiTimeoutException(); } @Override public String noRecentPlays() { return new Default().noRecentPlays(); } @Override public String isSetId() { return new Default().isSetId(); } @Override public String getPatience() { return new Default().getPatience(); } }
10040_17
package Main6; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.layout.GridPane; import javafx.scene.layout.Priority; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URL; import java.util.Optional; import java.util.ResourceBundle; public class Controller implements Initializable { @FXML public Button b1; @Override public void initialize(URL url, ResourceBundle resourceBundle) { } //można deklarować @FXML zamiast public/private @FXML //okienko wyświetlające stacktrace wymuszonego błędu void showDialogWindow(ActionEvent event) { // Alert alert = new Alert(Alert.AlertType.INFORMATION); // Alert alert = new Alert(Alert.AlertType.WARNING); //zmiana typu alertu Alert alert = new Alert(Alert.AlertType.ERROR); //zmiana typu alertu alert.setTitle("Info"); //alert.setHeaderText("Header"); //nagłówek - zmiana nazwy alert.setHeaderText(null); //nagłówek - brak nagłówka (null albo "") alert.setContentText("Test dialog window"); //symulacja błędu, aby wyświtlić stacktrace Exception ex = new FileNotFoundException("Nie odnaleziona pliku"); StringWriter s = new StringWriter(); try (PrintWriter p = new PrintWriter(s)) { ex.printStackTrace(p); } String exText = s.toString(); //konwersja na String Label l = new Label("Excepion"); TextArea txtArea = new TextArea(exText); txtArea.setEditable(false); txtArea.setWrapText(true); txtArea.setMaxWidth(Double.MAX_VALUE); txtArea.setMaxHeight(Double.MAX_VALUE); GridPane.setVgrow(txtArea, Priority.ALWAYS); GridPane.setHgrow(txtArea, Priority.ALWAYS); GridPane exceptionComponent = new GridPane(); exceptionComponent.setMaxWidth(Double.MAX_VALUE); exceptionComponent.add(l, 0, 0); exceptionComponent.add(txtArea, 0, 1); //wyświetlamy zawartosc zwinieta, ale pozwala na rozwiniecie alert.getDialogPane().setExpandableContent(exceptionComponent); alert.showAndWait(); //okienko oczeukuje na naszą reakcję } @FXML //okienko z kilkoma opcjami wyboru void showDialogWindow2(ActionEvent event) { // // Alert alert = new Alert(Alert.AlertType.CONFIRMATION); //zmiana typu alertu // alert.setTitle("Info"); // alert.setHeaderText(""); // alert.setContentText("Do you like me?"); // // ButtonType one = new ButtonType("Yes"); // ButtonType two = new ButtonType("No"); // ButtonType three = new ButtonType("I don't know"); // //do 4 przycisku dodajemy funkcjonalność - ma wyłączać (będzie po prawej odsunięty) // ButtonType buttonCancel = new ButtonType("I won't tell you", ButtonBar.ButtonData.CANCEL_CLOSE); // // alert.getButtonTypes().setAll(one, two, three, buttonCancel); //kolejność przycisków // // // Optional<ButtonType> res = alert.showAndWait(); // //musimy sprawdzić czy res nie jest 'nullem' // if (res.isPresent()) { // if ((res.get() == one)) { // System.out.println("Nice"); // } else if (res.get() == two) { // System.out.println("I'm so sorry"); // } else if (res.get() == three) { // System.out.println("Think about it again");} // else { // System.out.println("I think you need more time"); // } // } } @FXML //okienko do przekazywania wartości void showDialogWindow3(ActionEvent event) { TextInputDialog tid = new TextInputDialog(""); tid.setTitle("Your name"); tid.setHeaderText(""); tid.setContentText("Type your name"); //String, ponieważ interesuje nas odebranie właśnie łańcucha znaków Optional <String> res = tid.showAndWait(); if (res.isPresent()) { System.out.println("Hi " + res.get()); } //drugi sposób na odebranie info res.ifPresent(name -> System.out.println("Hi " + name)); } }
LukasMod/ElementaryJavaFX
src/Main6/Controller.java
1,317
// //do 4 przycisku dodajemy funkcjonalność - ma wyłączać (będzie po prawej odsunięty)
line_comment
pl
package Main6; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.layout.GridPane; import javafx.scene.layout.Priority; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URL; import java.util.Optional; import java.util.ResourceBundle; public class Controller implements Initializable { @FXML public Button b1; @Override public void initialize(URL url, ResourceBundle resourceBundle) { } //można deklarować @FXML zamiast public/private @FXML //okienko wyświetlające stacktrace wymuszonego błędu void showDialogWindow(ActionEvent event) { // Alert alert = new Alert(Alert.AlertType.INFORMATION); // Alert alert = new Alert(Alert.AlertType.WARNING); //zmiana typu alertu Alert alert = new Alert(Alert.AlertType.ERROR); //zmiana typu alertu alert.setTitle("Info"); //alert.setHeaderText("Header"); //nagłówek - zmiana nazwy alert.setHeaderText(null); //nagłówek - brak nagłówka (null albo "") alert.setContentText("Test dialog window"); //symulacja błędu, aby wyświtlić stacktrace Exception ex = new FileNotFoundException("Nie odnaleziona pliku"); StringWriter s = new StringWriter(); try (PrintWriter p = new PrintWriter(s)) { ex.printStackTrace(p); } String exText = s.toString(); //konwersja na String Label l = new Label("Excepion"); TextArea txtArea = new TextArea(exText); txtArea.setEditable(false); txtArea.setWrapText(true); txtArea.setMaxWidth(Double.MAX_VALUE); txtArea.setMaxHeight(Double.MAX_VALUE); GridPane.setVgrow(txtArea, Priority.ALWAYS); GridPane.setHgrow(txtArea, Priority.ALWAYS); GridPane exceptionComponent = new GridPane(); exceptionComponent.setMaxWidth(Double.MAX_VALUE); exceptionComponent.add(l, 0, 0); exceptionComponent.add(txtArea, 0, 1); //wyświetlamy zawartosc zwinieta, ale pozwala na rozwiniecie alert.getDialogPane().setExpandableContent(exceptionComponent); alert.showAndWait(); //okienko oczeukuje na naszą reakcję } @FXML //okienko z kilkoma opcjami wyboru void showDialogWindow2(ActionEvent event) { // // Alert alert = new Alert(Alert.AlertType.CONFIRMATION); //zmiana typu alertu // alert.setTitle("Info"); // alert.setHeaderText(""); // alert.setContentText("Do you like me?"); // // ButtonType one = new ButtonType("Yes"); // ButtonType two = new ButtonType("No"); // ButtonType three = new ButtonType("I don't know"); // //do 4 <SUF> // ButtonType buttonCancel = new ButtonType("I won't tell you", ButtonBar.ButtonData.CANCEL_CLOSE); // // alert.getButtonTypes().setAll(one, two, three, buttonCancel); //kolejność przycisków // // // Optional<ButtonType> res = alert.showAndWait(); // //musimy sprawdzić czy res nie jest 'nullem' // if (res.isPresent()) { // if ((res.get() == one)) { // System.out.println("Nice"); // } else if (res.get() == two) { // System.out.println("I'm so sorry"); // } else if (res.get() == three) { // System.out.println("Think about it again");} // else { // System.out.println("I think you need more time"); // } // } } @FXML //okienko do przekazywania wartości void showDialogWindow3(ActionEvent event) { TextInputDialog tid = new TextInputDialog(""); tid.setTitle("Your name"); tid.setHeaderText(""); tid.setContentText("Type your name"); //String, ponieważ interesuje nas odebranie właśnie łańcucha znaków Optional <String> res = tid.showAndWait(); if (res.isPresent()) { System.out.println("Hi " + res.get()); } //drugi sposób na odebranie info res.ifPresent(name -> System.out.println("Hi " + name)); } }
8288_9
package pl.my.library.datbase.models; import com.j256.ormlite.field.DataType; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import java.util.Date; @DatabaseTable(tableName = "BOOKS") public class Book implements BaseModel { public static final String AUTHOR_ID = "AUTHOR_ID"; public static final String CATEGORY_ID = "CATEGORY_ID"; //bezparametrowy konstruktor Alt+Insert public Book() { } // TWORZYMY POLE OBCE @DatabaseField(generatedId = true) private int id; @DatabaseField(columnName = AUTHOR_ID, foreign = true, foreignAutoCreate = true, foreignAutoRefresh = true, canBeNull = false) private Author author; @DatabaseField(columnName = CATEGORY_ID, foreign = true, foreignAutoCreate = true, foreignAutoRefresh = true, canBeNull = false) private Category category; //utworzy się kolumna z nazwą author_id. Lepiej nazwąć jawną naze, aby uniknąć pomyłek //foreignAutoCreate - pomagają w obsłudze //foreignAutoRefresh - pomagają w obsłudze @DatabaseField(columnName = "TITLE", canBeNull = false) //nigdy nie może być nullem private String title; // @DatabaseField(columnName = "DATE_RELEASE", dataType = DataType.DATE_STRING, format = "yyyy-MM-DD") @DatabaseField(columnName = "RELEASE_DATE") private Date releaseDate; @DatabaseField(columnName = "ISBN") //unique = true, zawsze unikalne elementy private String isbn; @DatabaseField(columnName = "DESCRIPTION", dataType = DataType.LONG_STRING) //dla Stringów powyżej 256 znaków private String description; @DatabaseField(columnName = "RATING", width = 1) //maksymalna ilość znaków (nie działa np. na sqlite, ale na h2 działa) private int rating; @DatabaseField(columnName = "ADDED_DATE") private Date addedDate; // @DatabaseField(columnName = "BORROWED", defaultValue = "false") //domyślna wartość // private boolean borrowed; // // @DatabaseField(columnName = "PRICE") // private double price; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public int getId() { return id; } public void setId(int id) { this.id = id; } public void setDescription(String description) { this.description = description; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public Date getAddedDate() { return addedDate; } public void setAddedDate(Date addedDate) { this.addedDate = addedDate; } public Date getReleaseDate() { return releaseDate; } public void setReleaseDate(Date releaseDate) { this.releaseDate = releaseDate; } public int getRating() { return rating; } public void setRating(int rating) { this.rating = rating; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } // public boolean isBorrowed() { // return borrowed; // } // // public void setBorrowed(boolean borrowed) { // this.borrowed = borrowed; // } // // public double getPrice() { // return price; // } // // public void setPrice(double price) { // this.price = price; // } }
LukasMod/ElementaryJavaFX_LibraryProject
src/main/java/pl/my/library/datbase/models/Book.java
1,165
//maksymalna ilość znaków (nie działa np. na sqlite, ale na h2 działa)
line_comment
pl
package pl.my.library.datbase.models; import com.j256.ormlite.field.DataType; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import java.util.Date; @DatabaseTable(tableName = "BOOKS") public class Book implements BaseModel { public static final String AUTHOR_ID = "AUTHOR_ID"; public static final String CATEGORY_ID = "CATEGORY_ID"; //bezparametrowy konstruktor Alt+Insert public Book() { } // TWORZYMY POLE OBCE @DatabaseField(generatedId = true) private int id; @DatabaseField(columnName = AUTHOR_ID, foreign = true, foreignAutoCreate = true, foreignAutoRefresh = true, canBeNull = false) private Author author; @DatabaseField(columnName = CATEGORY_ID, foreign = true, foreignAutoCreate = true, foreignAutoRefresh = true, canBeNull = false) private Category category; //utworzy się kolumna z nazwą author_id. Lepiej nazwąć jawną naze, aby uniknąć pomyłek //foreignAutoCreate - pomagają w obsłudze //foreignAutoRefresh - pomagają w obsłudze @DatabaseField(columnName = "TITLE", canBeNull = false) //nigdy nie może być nullem private String title; // @DatabaseField(columnName = "DATE_RELEASE", dataType = DataType.DATE_STRING, format = "yyyy-MM-DD") @DatabaseField(columnName = "RELEASE_DATE") private Date releaseDate; @DatabaseField(columnName = "ISBN") //unique = true, zawsze unikalne elementy private String isbn; @DatabaseField(columnName = "DESCRIPTION", dataType = DataType.LONG_STRING) //dla Stringów powyżej 256 znaków private String description; @DatabaseField(columnName = "RATING", width = 1) //maksymalna ilość <SUF> private int rating; @DatabaseField(columnName = "ADDED_DATE") private Date addedDate; // @DatabaseField(columnName = "BORROWED", defaultValue = "false") //domyślna wartość // private boolean borrowed; // // @DatabaseField(columnName = "PRICE") // private double price; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public int getId() { return id; } public void setId(int id) { this.id = id; } public void setDescription(String description) { this.description = description; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public Date getAddedDate() { return addedDate; } public void setAddedDate(Date addedDate) { this.addedDate = addedDate; } public Date getReleaseDate() { return releaseDate; } public void setReleaseDate(Date releaseDate) { this.releaseDate = releaseDate; } public int getRating() { return rating; } public void setRating(int rating) { this.rating = rating; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } // public boolean isBorrowed() { // return borrowed; // } // // public void setBorrowed(boolean borrowed) { // this.borrowed = borrowed; // } // // public double getPrice() { // return price; // } // // public void setPrice(double price) { // this.price = price; // } }
6131_5
class LambdaDemo2 { public static void main(String[] args) { //to wyrażenie lambda sprawdza czy jedna liczba jest czynnikiem drugiej NumericTest isFactor = (n, d) -> (n % d) == 0; if (isFactor.test(10, 2)) System.out.println("Liczba 2 jest czynnikiem liczby 10"); if (!isFactor.test(10, 3)) System.out.println("Liczba 3 nie jest czynniekiem liczby 10"); System.out.println(); //to wyrażenie lambda zwraca true, jeśli pierwszy argument jest mniejszy od drugiego NumericTest lessThan = (n, m) -> (n < m); if (lessThan.test(2, 10)) System.out.println("Liczba 2 jest mniejsza od liczby 10"); if (!lessThan.test(10, 2)) System.out.println("Liczba 10 nie jest mniejsza od liczby 2"); System.out.println(); //to wyraniżenie lambda zwraca true, jeśli wartości bezwzględne argumentów są sobie równe NumericTest absEqual = (n, m) -> (n < 0 ? -n : n) == (m < 0 ? -m : m); // '?' oznacza wyrażnie ? wart. jesli prawda : wart. jesli fałsz if (absEqual.test(-4, 4)) System.out.println("Wartości bezwględne 4 i -4 są równe"); if (!absEqual.test(4, -5)) System.out.println("wartości bezględne 4 i -5 nie są równe"); System.out.println(); //Blokowe wyrażenie lambda znajdujące najmniejszy dodatni czynnik wartości typu int NumericTest2 smallestF = (n) -> { int result = 1; //określa wartość bezwględną n n = n < 0 ? -n : n; for (int i = 2; i <= n / i; i++) if ((n % i) == 0) { result = i; break; } return result; }; //ważny dwukropek System.out.println("Najmniejszym czynnikiem liczby 12 jest " + smallestF.func(12)); System.out.println("Najmniejszym czynnikiem liczby 9 jest " + smallestF.func(9)); } }
LukasMod/JavaElementaryApps
src/LambdaDemo2.java
712
//określa wartość bezwględną n
line_comment
pl
class LambdaDemo2 { public static void main(String[] args) { //to wyrażenie lambda sprawdza czy jedna liczba jest czynnikiem drugiej NumericTest isFactor = (n, d) -> (n % d) == 0; if (isFactor.test(10, 2)) System.out.println("Liczba 2 jest czynnikiem liczby 10"); if (!isFactor.test(10, 3)) System.out.println("Liczba 3 nie jest czynniekiem liczby 10"); System.out.println(); //to wyrażenie lambda zwraca true, jeśli pierwszy argument jest mniejszy od drugiego NumericTest lessThan = (n, m) -> (n < m); if (lessThan.test(2, 10)) System.out.println("Liczba 2 jest mniejsza od liczby 10"); if (!lessThan.test(10, 2)) System.out.println("Liczba 10 nie jest mniejsza od liczby 2"); System.out.println(); //to wyraniżenie lambda zwraca true, jeśli wartości bezwzględne argumentów są sobie równe NumericTest absEqual = (n, m) -> (n < 0 ? -n : n) == (m < 0 ? -m : m); // '?' oznacza wyrażnie ? wart. jesli prawda : wart. jesli fałsz if (absEqual.test(-4, 4)) System.out.println("Wartości bezwględne 4 i -4 są równe"); if (!absEqual.test(4, -5)) System.out.println("wartości bezględne 4 i -5 nie są równe"); System.out.println(); //Blokowe wyrażenie lambda znajdujące najmniejszy dodatni czynnik wartości typu int NumericTest2 smallestF = (n) -> { int result = 1; //określa wartość <SUF> n = n < 0 ? -n : n; for (int i = 2; i <= n / i; i++) if ((n % i) == 0) { result = i; break; } return result; }; //ważny dwukropek System.out.println("Najmniejszym czynnikiem liczby 12 jest " + smallestF.func(12)); System.out.println("Najmniejszym czynnikiem liczby 9 jest " + smallestF.func(9)); } }
2778_0
package main.lists; import main.iteration.ArrayIterator; import main.iteration.Iterator; public class ArrayList implements List { // Domyslny rozmiar początkowy tablicy private static final int DEFAULT_INITIAL_CAPACITY = 16; private final int initialCapacity; private Object[] array; private int size; public ArrayList() { this(DEFAULT_INITIAL_CAPACITY); } public ArrayList(int initialCapacity) { assert initialCapacity > 0 : "Początkowy rozmiar tablicy musi być dodatni"; this.initialCapacity = initialCapacity; clear(); } @Override public Iterator iterator() { return new ArrayIterator(array, 0, size); } @Override public void insert(int index, Object value) throws IndexOutOfBoundsException { assert value != null : "Nie można wstawiać wartości pustych"; if (index < 0 || index > size) { throw new IndexOutOfBoundsException(); } ensureCapacity(size + 1); System.arraycopy(array, index, array, index + 1, size - index); array[index] = value; ++size; } @Override public void add(Object value) { insert(size, value); } @Override public Object delete(int index) throws IndexOutOfBoundsException { checkOutOfBounds(index); Object value = array[index]; int copyFromIndex = index + 1; if (copyFromIndex < size) { System.arraycopy(array, copyFromIndex, array, index, size - copyFromIndex); } array[--size] = null; return value; } @Override public boolean delete(Object value) { int index = indexOf(value); if (index != -1) { delete(index); return true; } return false; } @Override public void clear() { this.array = new Object[initialCapacity]; this.size = 0; } @Override public Object set(int index, Object value) throws IndexOutOfBoundsException { assert value != null : "wartość nie może być pusta"; checkOutOfBounds(index); Object oldValue = array[index]; array[index] = value; return oldValue; } @Override public Object get(int index) throws IndexOutOfBoundsException { checkOutOfBounds(index); return array[index]; } @Override public int indexOf(Object value) { assert value != null : "Wartość nie może być pusta"; for (int i = 0; i < size; i++) { if (value.equals(array[i])) { return i; } } return -1; } @Override public boolean contains(Object value) { return indexOf(value) != -1; } @Override public int size() { return size; } @Override public boolean isEmpty() { return size() == 0; } private void ensureCapacity(int capacity) { assert capacity > 0 : "rozmiar musi być dodatni"; if (array.length < capacity) { Object[] copy = new Object[capacity + capacity / 2]; System.arraycopy(array, 0, copy, 0, size); array = copy; } } private void checkOutOfBounds(int index) { if (isOutOfBounds(index)) { throw new IndexOutOfBoundsException(); } } private boolean isOutOfBounds(int index) { return index < 0 || index >= size; } }
M0ng00se7169/AiSD
src/main/lists/ArrayList.java
1,012
// Domyslny rozmiar początkowy tablicy
line_comment
pl
package main.lists; import main.iteration.ArrayIterator; import main.iteration.Iterator; public class ArrayList implements List { // Domyslny rozmiar <SUF> private static final int DEFAULT_INITIAL_CAPACITY = 16; private final int initialCapacity; private Object[] array; private int size; public ArrayList() { this(DEFAULT_INITIAL_CAPACITY); } public ArrayList(int initialCapacity) { assert initialCapacity > 0 : "Początkowy rozmiar tablicy musi być dodatni"; this.initialCapacity = initialCapacity; clear(); } @Override public Iterator iterator() { return new ArrayIterator(array, 0, size); } @Override public void insert(int index, Object value) throws IndexOutOfBoundsException { assert value != null : "Nie można wstawiać wartości pustych"; if (index < 0 || index > size) { throw new IndexOutOfBoundsException(); } ensureCapacity(size + 1); System.arraycopy(array, index, array, index + 1, size - index); array[index] = value; ++size; } @Override public void add(Object value) { insert(size, value); } @Override public Object delete(int index) throws IndexOutOfBoundsException { checkOutOfBounds(index); Object value = array[index]; int copyFromIndex = index + 1; if (copyFromIndex < size) { System.arraycopy(array, copyFromIndex, array, index, size - copyFromIndex); } array[--size] = null; return value; } @Override public boolean delete(Object value) { int index = indexOf(value); if (index != -1) { delete(index); return true; } return false; } @Override public void clear() { this.array = new Object[initialCapacity]; this.size = 0; } @Override public Object set(int index, Object value) throws IndexOutOfBoundsException { assert value != null : "wartość nie może być pusta"; checkOutOfBounds(index); Object oldValue = array[index]; array[index] = value; return oldValue; } @Override public Object get(int index) throws IndexOutOfBoundsException { checkOutOfBounds(index); return array[index]; } @Override public int indexOf(Object value) { assert value != null : "Wartość nie może być pusta"; for (int i = 0; i < size; i++) { if (value.equals(array[i])) { return i; } } return -1; } @Override public boolean contains(Object value) { return indexOf(value) != -1; } @Override public int size() { return size; } @Override public boolean isEmpty() { return size() == 0; } private void ensureCapacity(int capacity) { assert capacity > 0 : "rozmiar musi być dodatni"; if (array.length < capacity) { Object[] copy = new Object[capacity + capacity / 2]; System.arraycopy(array, 0, copy, 0, size); array = copy; } } private void checkOutOfBounds(int index) { if (isOutOfBounds(index)) { throw new IndexOutOfBoundsException(); } } private boolean isOutOfBounds(int index) { return index < 0 || index >= size; } }
3161_0
/** * Project Praca domowa 01 – plate. * Copyright Michał Szczygieł * Created at Oct 16, 2013. */ import java.util.ArrayList; import java.util.Collections; /** * Class, counting cost for cutting plate. * * @author Michał Szczygieł <michal.szczygiel@wp.pl> * */ public class Plate { /** * Variable stores data with weights for horizontal cuts. */ private ArrayList<Integer> arrayX = null; /** * Variable stores data with weights for vertical cuts. */ private ArrayList<Integer> arrayY = null; /** * Constructor for Plate class. Automatically set arrays with values for vertical and horizontal cuts. * * @param arrayX * @param arrayY */ public Plate(ArrayList<Integer> arrayX, ArrayList<Integer> arrayY) { setArrayX(arrayX); setArrayY(arrayY); } /** * Method counts cost of cuts. * * @return cost of cuts. */ public String cutCost() { // Arrays needs sort, to finding optimal cost. Collections.sort(getArrayX()); Collections.sort(getArrayY()); int accumulator = 0; int horizontalLines = 1; int verticalLines = 1; int sizeX = getArrayX().size(); int sizeY = getArrayY().size(); int numberOfIterations = sizeX + sizeY; for (int i = 0; i < numberOfIterations; i++) { int maxX = 0; int maxY = 0; if (getArrayX().size() > 0) { maxX = Collections.max(getArrayX()); } if (getArrayY().size() > 0) { maxY = Collections.max(getArrayY()); } if (maxX > maxY) { if (getArrayX().size() > 0) { accumulator += maxX * horizontalLines; getArrayX().remove(sizeX - 1); verticalLines++; sizeX--; } } else { if (getArrayY().size() > 0) { accumulator += maxY * verticalLines; getArrayY().remove(sizeY - 1); horizontalLines++; sizeY--; } } } return "Koszt cięcia : " + accumulator; } /** * @return the arrayX */ public ArrayList<Integer> getArrayX() { return arrayX; } /** * @return the arrayY */ public ArrayList<Integer> getArrayY() { return arrayY; } /** * @param arrayX * the arrayX to set */ public void setArrayX(ArrayList<Integer> arrayX) { this.arrayX = arrayX; } /** * @param arrayY * the arrayY to set */ public void setArrayY(ArrayList<Integer> arrayY) { this.arrayY = arrayY; } }
M4GiK/ztp-projects
Plate/Plate.java
854
/** * Project Praca domowa 01 – plate. * Copyright Michał Szczygieł * Created at Oct 16, 2013. */
block_comment
pl
/** * Project Praca domowa <SUF>*/ import java.util.ArrayList; import java.util.Collections; /** * Class, counting cost for cutting plate. * * @author Michał Szczygieł <michal.szczygiel@wp.pl> * */ public class Plate { /** * Variable stores data with weights for horizontal cuts. */ private ArrayList<Integer> arrayX = null; /** * Variable stores data with weights for vertical cuts. */ private ArrayList<Integer> arrayY = null; /** * Constructor for Plate class. Automatically set arrays with values for vertical and horizontal cuts. * * @param arrayX * @param arrayY */ public Plate(ArrayList<Integer> arrayX, ArrayList<Integer> arrayY) { setArrayX(arrayX); setArrayY(arrayY); } /** * Method counts cost of cuts. * * @return cost of cuts. */ public String cutCost() { // Arrays needs sort, to finding optimal cost. Collections.sort(getArrayX()); Collections.sort(getArrayY()); int accumulator = 0; int horizontalLines = 1; int verticalLines = 1; int sizeX = getArrayX().size(); int sizeY = getArrayY().size(); int numberOfIterations = sizeX + sizeY; for (int i = 0; i < numberOfIterations; i++) { int maxX = 0; int maxY = 0; if (getArrayX().size() > 0) { maxX = Collections.max(getArrayX()); } if (getArrayY().size() > 0) { maxY = Collections.max(getArrayY()); } if (maxX > maxY) { if (getArrayX().size() > 0) { accumulator += maxX * horizontalLines; getArrayX().remove(sizeX - 1); verticalLines++; sizeX--; } } else { if (getArrayY().size() > 0) { accumulator += maxY * verticalLines; getArrayY().remove(sizeY - 1); horizontalLines++; sizeY--; } } } return "Koszt cięcia : " + accumulator; } /** * @return the arrayX */ public ArrayList<Integer> getArrayX() { return arrayX; } /** * @return the arrayY */ public ArrayList<Integer> getArrayY() { return arrayY; } /** * @param arrayX * the arrayX to set */ public void setArrayX(ArrayList<Integer> arrayX) { this.arrayX = arrayX; } /** * @param arrayY * the arrayY to set */ public void setArrayY(ArrayList<Integer> arrayY) { this.arrayY = arrayY; } }
5696_13
package mad.widget.activities; import java.util.ArrayList; import mad.widget.R; import mad.widget.connections.GetPlanChanges; import mad.widget.connections.HttpConnect; import mad.widget.models.ListViewAdapterPlanChanges; import mad.widget.models.MessagePlanChanges; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.res.Resources; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; /** * Aktywnosc wyswietlajaca zmiany w planie w formie ListView * * @author Sebastian Swierczek * @version 1.3.1 */ public class PlanChangesActivity extends Activity { /** Obiekt typu GetPlanChanges */ private final GetPlanChanges pars = new GetPlanChanges(); /** * Zmienna do debuggowania. */ private static final String TAG = "PlanChangesActivity"; /** * Obiekt klasy Resources, odwolujacy sie do wartosci z pliku * res/strings.xml */ private Resources res; /** * Obiekt ArrayList zawierajacy obiekty klasy MessagePlanChanges, gdzie * wyswietlane beda zmiany w planie */ private ArrayList<MessagePlanChanges> news = new ArrayList<MessagePlanChanges>(); /** Obiekt ListViewAdapterPlanChanges */ private ListViewAdapterPlanChanges adapter; /** Obiekt ListView */ private ListView lvPlanChanges; /** Obiekt ProgressDialog */ private ProgressDialog pd; /** Zmienna stwierdzajaca wcisniecie przycisku odswiezania */ private boolean enableExecuteRefresh = true; /** Metoda wywolywana przy starcie aktywnosci */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i(TAG, "onCreate"); setContentView(R.layout.main_plan_changes); res = getApplicationContext().getResources(); if (HttpConnect.isOnline(getApplicationContext()) == true) { // firstRun = false; new AsyncTaskGetPlanChanges().execute(getApplicationContext()); } } /** * Metoda wyswietlajaca powiadomienie Toast * * @param text * tekst powiadomienia * @param duration * czas wyswietlania komunikatu * @param con * kontekst aplikacji */ public void showToast(String text, int duration, Context con) { Log.i(TAG, "showToast"); Toast.makeText(con, text, duration).show(); } /** Metoda odswiezajaca ListView ze zmianami w planie */ private void refreshListView() { Log.i(TAG, "refreshListView"); lvPlanChanges = (ListView) findViewById(R.id.listPlanChanges); adapter = new ListViewAdapterPlanChanges(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, news); lvPlanChanges.setAdapter(adapter); adapter.notifyDataSetChanged(); lvPlanChanges.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { TextView body = (TextView) view.findViewById(R.id.body); if (body.getVisibility() == View.GONE) { body.setVisibility(View.VISIBLE); } else body.setVisibility(View.GONE); } }); if (news.size() == 0) { Toast.makeText(this, getString(R.string.no_messages), Toast.LENGTH_LONG).show(); } } /** * Metoda tworzaca menu opcji * * @param menu * * @return true, jezeli utworzono pomyslnie */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.plan_changes_menu, menu); return true; } /** * Metoda sprawdza wybor elementu z menu * * @param item * wybrany element menu * * @return true, jezeli wybrano element */ @Override public boolean onOptionsItemSelected(MenuItem item) { Log.i(TAG, "onOptionsItemSelected"); switch (item.getItemId()) { case R.id.refresh: if (enableExecuteRefresh) { if (HttpConnect.isOnline(getApplicationContext()) == true) { new AsyncTaskGetPlanChanges() .execute(getApplicationContext()); } } return true; case R.id.exit: this.finish(); return true; default: return super.onOptionsItemSelected(item); } } /** Klasa pobierajaca zmiany w planie */ private class AsyncTaskGetPlanChanges extends AsyncTask<Context, Boolean, Void> { /** * ArrayList obiektow MessagePlanChanges, gdzie beda przechowywane dane * o zmianach w planie */ ArrayList<MessagePlanChanges> tempArray = null; /** Obiekt klasy Context */ Context ctx; /** Wykonywanie zadan w tle watku glownego */ @Override protected Void doInBackground(Context... params) { Log.i(TAG, "doInBackground"); ctx = params[0]; if (HttpConnect.isOnline(getApplicationContext()) == true) { tempArray = pars.getServerMessages(); if (tempArray != null) { news = tempArray; } else { publishProgress(false); } } return null; } /** * Metoda umozliwia aktualizowanie watku glownego podczas dzialania * PlanChangesActivity */ @Override protected void onProgressUpdate(Boolean... values) { super.onProgressUpdate(values); Log.i(TAG, "onProgressUpdate"); if (values[0] == false) showToast(res.getString(R.string.plan_changes_Messages), 3000, ctx); } /** Metoda wykonywana przed doInBackground() */ @Override protected void onPreExecute() { Log.i(TAG, "onPreExecute"); pd = ProgressDialog.show(PlanChangesActivity.this, res.getString(R.string.plan_changes_refreshing_title), res.getString(R.string.refreshing_body), true, true); pd.setCancelable(false); enableExecuteRefresh = false; } /** Metoda wykonywana po doInBackground() */ @Override protected void onPostExecute(Void result) { Log.i(TAG, "onPostExecute"); pd.dismiss(); if (tempArray != null) { refreshListView(); publishProgress(true); } enableExecuteRefresh = true; } } @Override protected void onStop() { super.onStop(); finish(); } }
MADWI/Widget_MAD
src/mad/widget/activities/PlanChangesActivity.java
2,207
/** * ArrayList obiektow MessagePlanChanges, gdzie beda przechowywane dane * o zmianach w planie */
block_comment
pl
package mad.widget.activities; import java.util.ArrayList; import mad.widget.R; import mad.widget.connections.GetPlanChanges; import mad.widget.connections.HttpConnect; import mad.widget.models.ListViewAdapterPlanChanges; import mad.widget.models.MessagePlanChanges; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.res.Resources; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; /** * Aktywnosc wyswietlajaca zmiany w planie w formie ListView * * @author Sebastian Swierczek * @version 1.3.1 */ public class PlanChangesActivity extends Activity { /** Obiekt typu GetPlanChanges */ private final GetPlanChanges pars = new GetPlanChanges(); /** * Zmienna do debuggowania. */ private static final String TAG = "PlanChangesActivity"; /** * Obiekt klasy Resources, odwolujacy sie do wartosci z pliku * res/strings.xml */ private Resources res; /** * Obiekt ArrayList zawierajacy obiekty klasy MessagePlanChanges, gdzie * wyswietlane beda zmiany w planie */ private ArrayList<MessagePlanChanges> news = new ArrayList<MessagePlanChanges>(); /** Obiekt ListViewAdapterPlanChanges */ private ListViewAdapterPlanChanges adapter; /** Obiekt ListView */ private ListView lvPlanChanges; /** Obiekt ProgressDialog */ private ProgressDialog pd; /** Zmienna stwierdzajaca wcisniecie przycisku odswiezania */ private boolean enableExecuteRefresh = true; /** Metoda wywolywana przy starcie aktywnosci */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i(TAG, "onCreate"); setContentView(R.layout.main_plan_changes); res = getApplicationContext().getResources(); if (HttpConnect.isOnline(getApplicationContext()) == true) { // firstRun = false; new AsyncTaskGetPlanChanges().execute(getApplicationContext()); } } /** * Metoda wyswietlajaca powiadomienie Toast * * @param text * tekst powiadomienia * @param duration * czas wyswietlania komunikatu * @param con * kontekst aplikacji */ public void showToast(String text, int duration, Context con) { Log.i(TAG, "showToast"); Toast.makeText(con, text, duration).show(); } /** Metoda odswiezajaca ListView ze zmianami w planie */ private void refreshListView() { Log.i(TAG, "refreshListView"); lvPlanChanges = (ListView) findViewById(R.id.listPlanChanges); adapter = new ListViewAdapterPlanChanges(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, news); lvPlanChanges.setAdapter(adapter); adapter.notifyDataSetChanged(); lvPlanChanges.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { TextView body = (TextView) view.findViewById(R.id.body); if (body.getVisibility() == View.GONE) { body.setVisibility(View.VISIBLE); } else body.setVisibility(View.GONE); } }); if (news.size() == 0) { Toast.makeText(this, getString(R.string.no_messages), Toast.LENGTH_LONG).show(); } } /** * Metoda tworzaca menu opcji * * @param menu * * @return true, jezeli utworzono pomyslnie */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.plan_changes_menu, menu); return true; } /** * Metoda sprawdza wybor elementu z menu * * @param item * wybrany element menu * * @return true, jezeli wybrano element */ @Override public boolean onOptionsItemSelected(MenuItem item) { Log.i(TAG, "onOptionsItemSelected"); switch (item.getItemId()) { case R.id.refresh: if (enableExecuteRefresh) { if (HttpConnect.isOnline(getApplicationContext()) == true) { new AsyncTaskGetPlanChanges() .execute(getApplicationContext()); } } return true; case R.id.exit: this.finish(); return true; default: return super.onOptionsItemSelected(item); } } /** Klasa pobierajaca zmiany w planie */ private class AsyncTaskGetPlanChanges extends AsyncTask<Context, Boolean, Void> { /** * ArrayList obiektow MessagePlanChanges, <SUF>*/ ArrayList<MessagePlanChanges> tempArray = null; /** Obiekt klasy Context */ Context ctx; /** Wykonywanie zadan w tle watku glownego */ @Override protected Void doInBackground(Context... params) { Log.i(TAG, "doInBackground"); ctx = params[0]; if (HttpConnect.isOnline(getApplicationContext()) == true) { tempArray = pars.getServerMessages(); if (tempArray != null) { news = tempArray; } else { publishProgress(false); } } return null; } /** * Metoda umozliwia aktualizowanie watku glownego podczas dzialania * PlanChangesActivity */ @Override protected void onProgressUpdate(Boolean... values) { super.onProgressUpdate(values); Log.i(TAG, "onProgressUpdate"); if (values[0] == false) showToast(res.getString(R.string.plan_changes_Messages), 3000, ctx); } /** Metoda wykonywana przed doInBackground() */ @Override protected void onPreExecute() { Log.i(TAG, "onPreExecute"); pd = ProgressDialog.show(PlanChangesActivity.this, res.getString(R.string.plan_changes_refreshing_title), res.getString(R.string.refreshing_body), true, true); pd.setCancelable(false); enableExecuteRefresh = false; } /** Metoda wykonywana po doInBackground() */ @Override protected void onPostExecute(Void result) { Log.i(TAG, "onPostExecute"); pd.dismiss(); if (tempArray != null) { refreshListView(); publishProgress(true); } enableExecuteRefresh = true; } } @Override protected void onStop() { super.onStop(); finish(); } }
6558_2
package agh.ics.oop; import java.util.LinkedHashMap; import java.util.Random; public class GrassField extends AbstractWorldMap{ private final int fieldNumber; private final LinkedHashMap<Vector2d, Grass> grass; public GrassField(int fieldNumber){ this.fieldNumber = fieldNumber; this.grass = new LinkedHashMap<>(); placeGrass(); } private void placeGrass(){ Random random = new Random(); int x ; int y ; for(int i = 0; i < fieldNumber; i++){ do{ // najpierw instrukcja do wykonania x = random.nextInt((int)Math.sqrt(this.fieldNumber * 10)); y = random.nextInt((int)Math.sqrt(this.fieldNumber * 10)); } // instanceof -sprawdzam czy zwracany obiekt z danego pola jest trawą while(isOccupied(new Vector2d(x,y)) && (objectAt(new Vector2d(x,y)) instanceof Grass) ); // pozniej sprawdzany warunek, czyli wykona sie przynamnije raz Grass tuft = new Grass(new Vector2d(x,y)); grass.put(tuft.getPosition(), tuft); // dodaje kępke do trawnika mapElements.add(tuft); boundary.addElements( tuft); } } @Override public boolean canMoveTo(Vector2d position) { // aby można było się tam ruszyć musi być puste pole lub być kępka trawy return !isOccupied(position) || objectAt(position) instanceof Grass ; } @Override public Object objectAt(Vector2d position) { Object object = super.objectAt(position); if (object == null){ return grass.get(position); } else return object; } public Vector2d getLeftCorner(){return boundary.getLeftCorner();} public Vector2d getRightCorner(){return boundary.getRightCorner();} }
MaOlszewska/ObjectOrientedProgramming-2021
src/main/java/agh/ics/oop/GrassField.java
554
// pozniej sprawdzany warunek, czyli wykona sie przynamnije raz
line_comment
pl
package agh.ics.oop; import java.util.LinkedHashMap; import java.util.Random; public class GrassField extends AbstractWorldMap{ private final int fieldNumber; private final LinkedHashMap<Vector2d, Grass> grass; public GrassField(int fieldNumber){ this.fieldNumber = fieldNumber; this.grass = new LinkedHashMap<>(); placeGrass(); } private void placeGrass(){ Random random = new Random(); int x ; int y ; for(int i = 0; i < fieldNumber; i++){ do{ // najpierw instrukcja do wykonania x = random.nextInt((int)Math.sqrt(this.fieldNumber * 10)); y = random.nextInt((int)Math.sqrt(this.fieldNumber * 10)); } // instanceof -sprawdzam czy zwracany obiekt z danego pola jest trawą while(isOccupied(new Vector2d(x,y)) && (objectAt(new Vector2d(x,y)) instanceof Grass) ); // pozniej sprawdzany <SUF> Grass tuft = new Grass(new Vector2d(x,y)); grass.put(tuft.getPosition(), tuft); // dodaje kępke do trawnika mapElements.add(tuft); boundary.addElements( tuft); } } @Override public boolean canMoveTo(Vector2d position) { // aby można było się tam ruszyć musi być puste pole lub być kępka trawy return !isOccupied(position) || objectAt(position) instanceof Grass ; } @Override public Object objectAt(Vector2d position) { Object object = super.objectAt(position); if (object == null){ return grass.get(position); } else return object; } public Vector2d getLeftCorner(){return boundary.getLeftCorner();} public Vector2d getRightCorner(){return boundary.getRightCorner();} }
5777_0
package me.ksiazka.model; /* Opis systemu statusow oferty: Przy pierwszym wyslaniu oferty badz jej odeslaniu po zmianach oferta ma status "pending" poniewaz czeka na akceptacje ze strony drugiego uzytkownika. Gdy uzytkownik, ktoremu wyslana zostala oferta zaakceptuje ja, wtedy oferta dostaje status accepted, ale jest to wciaz akceptacja jednostronna, dopiero kiedy drugi uzytkownik rowniez potwierdzi zgode, oferta staje sie confirmed, tym samym jest zrealizowana i nie zalega juz na liscie aktualnych ofert uzytkownika. */ public enum OfferStatus { CONFIRMED, ACCEPTED, PENDING; }
MacMisDev/Ksiazka
src/main/java/me/ksiazka/model/OfferStatus.java
226
/* Opis systemu statusow oferty: Przy pierwszym wyslaniu oferty badz jej odeslaniu po zmianach oferta ma status "pending" poniewaz czeka na akceptacje ze strony drugiego uzytkownika. Gdy uzytkownik, ktoremu wyslana zostala oferta zaakceptuje ja, wtedy oferta dostaje status accepted, ale jest to wciaz akceptacja jednostronna, dopiero kiedy drugi uzytkownik rowniez potwierdzi zgode, oferta staje sie confirmed, tym samym jest zrealizowana i nie zalega juz na liscie aktualnych ofert uzytkownika. */
block_comment
pl
package me.ksiazka.model; /* Opis systemu statusow <SUF>*/ public enum OfferStatus { CONFIRMED, ACCEPTED, PENDING; }
5793_1
import java.util.ArrayList; import java.util.List; /** * Klasa przechowujaca obiekty produkt */ public class Magazyn { private final List<Produkt> products; public Magazyn(){ products = new ArrayList<>(); } /** * Metoda dodajaca produkt do listy * @param product produkt do dodania * @throws IllegalArgumentException kiedy produkt jest pusty */ public void addProduct(Produkt product){ if (product == null){ throw new IllegalArgumentException("Produkt nie moze byc pusty!"); } products.add(product); } public List<Produkt> getProducts(){ return products; } }
Maciej-Grzesik/ZPO23-L1
LISTA 3/Zad1/src/Magazyn.java
195
/** * Metoda dodajaca produkt do listy * @param product produkt do dodania * @throws IllegalArgumentException kiedy produkt jest pusty */
block_comment
pl
import java.util.ArrayList; import java.util.List; /** * Klasa przechowujaca obiekty produkt */ public class Magazyn { private final List<Produkt> products; public Magazyn(){ products = new ArrayList<>(); } /** * Metoda dodajaca produkt <SUF>*/ public void addProduct(Produkt product){ if (product == null){ throw new IllegalArgumentException("Produkt nie moze byc pusty!"); } products.add(product); } public List<Produkt> getProducts(){ return products; } }