Dataset Viewer
Auto-converted to Parquet Duplicate
file_id
stringlengths
5
10
content
stringlengths
121
33.1k
repo
stringlengths
7
77
path
stringlengths
7
157
token_length
int64
42
8.19k
original_comment
stringlengths
7
10.6k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
15
33k
101997_3
package panels; import lombok.SneakyThrows; import objects.Predator; import objects.Prey; import objects.RoadManager; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.File; import java.util.Objects; public class SimulationPanel extends JPanel { private RoadManager manager; private boolean preyAddButtonClicked; // zmienna informująca czy przycisk dodania ofary został klikniety private boolean preySet; // zmienna informujaca czy ofaria zostalo dodane BufferedImage backgroundImage; @SneakyThrows public SimulationPanel() { this.manager = new RoadManager(); backgroundImage = ImageIO.read(Objects.requireNonNull(getClass().getClassLoader().getResource("Background.png"))); this.addMouseListener(new MouseAdapter() { // dodanie slchacza na klikniecie @Override public void mouseClicked(MouseEvent e) { if (preyAddButtonClicked == false) { manager.addPredator(e.getX(), e.getY()); } else if (preySet == false) { manager.addPrey(e.getX(), e.getY()); preySet = true; preyAddButtonClicked = false; } else { manager.addPredator(e.getX(), e.getY()); } repaint(); } }); } @SneakyThrows @Override public synchronized void paint(Graphics g) { Graphics2D g2d = (Graphics2D) g; super.paintComponent(g); g.drawImage(backgroundImage, 0, 0, null); g2d.setStroke(new BasicStroke(1)); // ustawienie grubosci lini g2d.setColor(Color.GREEN); g2d.drawLine(450, 0, 450, 1000); // rysowanie mety if (manager.getPredators() != null) { BufferedImage image = ImageIO.read(Objects.requireNonNull(getClass().getClassLoader().getResource("wolf.png"))); // rysowanie predatorów na panelu for (Predator p : manager.getPredators()) { g.drawImage(image, p.getX() - p.getWidth() / 2, p.getY() - p.getHeight() / 2, null); } } if (manager.getPrey() != null && preySet) { // rysowanie ofiary jesli została ustawiona Prey prey = manager.getPrey(); BufferedImage image = ImageIO.read(Objects.requireNonNull(getClass().getClassLoader().getResource("deer.png"))); g.drawImage(image, prey.getX() - prey.getWidth() / 2, prey.getY() - prey.getHeight() / 2, null); } } public void resetProgram() { this.manager.resetProgram(); preySet = false; repaint(); } public void setPreyAddButtonClicked(boolean preyAddButtonClicked) { this.preyAddButtonClicked = preyAddButtonClicked; } public boolean makeMoveRepaint() { if (manager.makeMove(this)) { // sprawdzenie czy ruch mozna wykonac repaint(); // malowanie return true; } else { return false; // zwrocenie informacji ze ruch jest niewykonalny } } }
00Zbiechu/Hunting-Fuzzy-Logic
src/main/java/panels/SimulationPanel.java
1,006
// ustawienie grubosci lini
line_comment
pl
package panels; import lombok.SneakyThrows; import objects.Predator; import objects.Prey; import objects.RoadManager; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.File; import java.util.Objects; public class SimulationPanel extends JPanel { private RoadManager manager; private boolean preyAddButtonClicked; // zmienna informująca czy przycisk dodania ofary został klikniety private boolean preySet; // zmienna informujaca czy ofaria zostalo dodane BufferedImage backgroundImage; @SneakyThrows public SimulationPanel() { this.manager = new RoadManager(); backgroundImage = ImageIO.read(Objects.requireNonNull(getClass().getClassLoader().getResource("Background.png"))); this.addMouseListener(new MouseAdapter() { // dodanie slchacza na klikniecie @Override public void mouseClicked(MouseEvent e) { if (preyAddButtonClicked == false) { manager.addPredator(e.getX(), e.getY()); } else if (preySet == false) { manager.addPrey(e.getX(), e.getY()); preySet = true; preyAddButtonClicked = false; } else { manager.addPredator(e.getX(), e.getY()); } repaint(); } }); } @SneakyThrows @Override public synchronized void paint(Graphics g) { Graphics2D g2d = (Graphics2D) g; super.paintComponent(g); g.drawImage(backgroundImage, 0, 0, null); g2d.setStroke(new BasicStroke(1)); // usta<SUF> g2d.setColor(Color.GREEN); g2d.drawLine(450, 0, 450, 1000); // rysowanie mety if (manager.getPredators() != null) { BufferedImage image = ImageIO.read(Objects.requireNonNull(getClass().getClassLoader().getResource("wolf.png"))); // rysowanie predatorów na panelu for (Predator p : manager.getPredators()) { g.drawImage(image, p.getX() - p.getWidth() / 2, p.getY() - p.getHeight() / 2, null); } } if (manager.getPrey() != null && preySet) { // rysowanie ofiary jesli została ustawiona Prey prey = manager.getPrey(); BufferedImage image = ImageIO.read(Objects.requireNonNull(getClass().getClassLoader().getResource("deer.png"))); g.drawImage(image, prey.getX() - prey.getWidth() / 2, prey.getY() - prey.getHeight() / 2, null); } } public void resetProgram() { this.manager.resetProgram(); preySet = false; repaint(); } public void setPreyAddButtonClicked(boolean preyAddButtonClicked) { this.preyAddButtonClicked = preyAddButtonClicked; } public boolean makeMoveRepaint() { if (manager.makeMove(this)) { // sprawdzenie czy ruch mozna wykonac repaint(); // malowanie return true; } else { return false; // zwrocenie informacji ze ruch jest niewykonalny } } }
142736_0
package obliczenia; abstract class Wyrazenie implements Obliczalny { /** Metoda mnozaca wyrazenia * @param args Ciag wyrazen * @return wynik operacji sumowania argumentow */ public static double sumuj (Wyrazenie...args) throws Exception { double suma=0f; for (Wyrazenie arg : args) { suma = suma + arg.oblicz(); } return suma; } /** Metoda mnozaca wyrazenia * @param args Ciag wyrazen * @return wynik operacji wymnozenia argumentow */ public static double pomnoz (Wyrazenie...args) throws Exception { double suma=0f; for (Wyrazenie arg : args) { suma = suma * arg.oblicz(); } return suma; } /** * Porównanie obiektów * @param o Obiekt do porównania * @return boolowskie true albo false */ @Override public boolean equals(Object o) { if(this==o) return true; if((o==null) || (getClass() != o.getClass())) return false; Wyrazenie wyr = (Wyrazenie) o; try { return oblicz() == wyr.oblicz(); } catch (Exception e) { return false; } } }
0sk4r/Uwr
Java/Lista04/src/obliczenia/Wyrazenie.java
385
/** Metoda mnozaca wyrazenia * @param args Ciag wyrazen * @return wynik operacji sumowania argumentow */
block_comment
pl
package obliczenia; abstract class Wyrazenie implements Obliczalny { /** Metod<SUF>*/ public static double sumuj (Wyrazenie...args) throws Exception { double suma=0f; for (Wyrazenie arg : args) { suma = suma + arg.oblicz(); } return suma; } /** Metoda mnozaca wyrazenia * @param args Ciag wyrazen * @return wynik operacji wymnozenia argumentow */ public static double pomnoz (Wyrazenie...args) throws Exception { double suma=0f; for (Wyrazenie arg : args) { suma = suma * arg.oblicz(); } return suma; } /** * Porównanie obiektów * @param o Obiekt do porównania * @return boolowskie true albo false */ @Override public boolean equals(Object o) { if(this==o) return true; if((o==null) || (getClass() != o.getClass())) return false; Wyrazenie wyr = (Wyrazenie) o; try { return oblicz() == wyr.oblicz(); } catch (Exception e) { return false; } } }
66517_4
package display; import IO.IOManager; import enums.EditableTile; import enums.EditorMode; import enums.Layer; import event.display.*; import event.editor.EnemySelectedEvent; import event.editor.SavePathEvent; import gamemanager.GameManager; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.io.IOException; public class PaletteTabs { private JTabbedPane tabs; private TilePalette tilePalette; private ConnectionsPalette connectionsPalette; private PathEditPalette pathEditPalette; private MessagesPalette messagesPalette; private ToolPalette toolPalette; //trzeba to przemyslec, na razie zrobie tak public PaletteTabs (ToolPalette toolPalette) { tabs = new JTabbedPane(); this.toolPalette = toolPalette; tilePalette = new TilePalette(EditableTile.values()); connectionsPalette = new ConnectionsPalette(); pathEditPalette = new PathEditPalette(); messagesPalette = new MessagesPalette(); try { tabs.addTab("", new ImageIcon(GraphicsHashtable.loadImage("/graphics/tool_tiles.png")), tilePalette, "Tiles"); tabs.addTab("", new ImageIcon(GraphicsHashtable.loadImage("/graphics/tool_connect.png")), connectionsPalette, "Connections"); tabs.addTab("", new ImageIcon(GraphicsHashtable.loadImage("/graphics/tool_path.png")), pathEditPalette, "Pathedit"); tabs.addTab("", new ImageIcon(GraphicsHashtable.loadImage("/graphics/tool_message.png")), messagesPalette, "Messages"); } catch (IOException e) {} tabs.addChangeListener(new ModeListener()); } public void refresh() { connectionsPalette.refresh(); } public JTabbedPane getTabs() { return tabs; } public ToolPalette getToolPalette() { return toolPalette; } public class ModeListener implements ChangeListener { @Override public void stateChanged(ChangeEvent e) { String selectedTabTip = tabs.getToolTipTextAt(tabs.getSelectedIndex()); EditorInputHandler inputHandler = (EditorInputHandler) IOManager.getInstance().getInputHandler(); switch (selectedTabTip) { //FIXME: zrobmy cos z tym pozniej bo to obrzydliwe case "Tiles": { //zrobic cos madrzejszego inputHandler.onEvent(new ConnectableTileSelectedEvent(null)); GameManager.getInstance().onEvent(new SavePathEvent()); resetState(EditorMode.ADD); GameManager.getInstance().onEvent(new PalettePressedEvent(EditableTile.EMPTY)); //pathEditPalette.getArrows().selectOne(pathEditPalette.getArrows().buttons.get(0)); IOManager.getInstance().drawEditor(); break; } case "Connections": { //zrobic cos madrzejszego pozniej inputHandler.onEvent(new ConnectableTileSelectedEvent(null)); GameManager.getInstance().onEvent(new SavePathEvent()); resetState(EditorMode.CONNECT); IOManager.getInstance().drawEditor(); break; } case "Pathedit": { resetState(EditorMode.PATHEDIT); //zrobic cos madrzejszego pozniej inputHandler.onEvent(new ConnectableTileSelectedEvent(null)); pathEditPalette.getTree().clearSelection(); GameManager.getInstance().onEvent(new PalettePressedEvent(enums.Arrow.ARROW_UP)); //tilePalette.selectOne(tilePalette.buttons.get(0)); IOManager.getInstance().drawEditor(); break; } case "Messages": { resetState(EditorMode.MESSAGES); //zrobic cos madrzejszego pozniej inputHandler.onEvent(new ConnectableTileSelectedEvent(null)); messagesPalette.getTree().clearSelection(); GameManager.getInstance().onEvent(new PalettePressedEvent(EditableTile.EMPTY)); //tilePalette.selectOne(tilePalette.buttons.get(0)); IOManager.getInstance().drawEditor(); break; } default: { System.out.println("Ustawiono tryb na default - prawdopodobnie nieporzadane\nPaletteTabs line 63"); inputHandler.onEvent(new ModeChangedEvent(EditorMode.DEFAULT)); break; } } toolPalette.selectOne(toolPalette.buttons.get(0)); } } public void resetState (EditorMode m) { EditorInputHandler inputHandler = (EditorInputHandler) IOManager.getInstance().getInputHandler(); inputHandler.onEvent(new ChangeLayerEvent(Layer.BOTH)); inputHandler.onEvent(new ModeChangedEvent(m)); GameManager.getInstance().onEvent(new EditorChangeEvent()); } }
0stam/psio-game
src/display/PaletteTabs.java
1,559
//zrobic cos madrzejszego pozniej
line_comment
pl
package display; import IO.IOManager; import enums.EditableTile; import enums.EditorMode; import enums.Layer; import event.display.*; import event.editor.EnemySelectedEvent; import event.editor.SavePathEvent; import gamemanager.GameManager; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.io.IOException; public class PaletteTabs { private JTabbedPane tabs; private TilePalette tilePalette; private ConnectionsPalette connectionsPalette; private PathEditPalette pathEditPalette; private MessagesPalette messagesPalette; private ToolPalette toolPalette; //trzeba to przemyslec, na razie zrobie tak public PaletteTabs (ToolPalette toolPalette) { tabs = new JTabbedPane(); this.toolPalette = toolPalette; tilePalette = new TilePalette(EditableTile.values()); connectionsPalette = new ConnectionsPalette(); pathEditPalette = new PathEditPalette(); messagesPalette = new MessagesPalette(); try { tabs.addTab("", new ImageIcon(GraphicsHashtable.loadImage("/graphics/tool_tiles.png")), tilePalette, "Tiles"); tabs.addTab("", new ImageIcon(GraphicsHashtable.loadImage("/graphics/tool_connect.png")), connectionsPalette, "Connections"); tabs.addTab("", new ImageIcon(GraphicsHashtable.loadImage("/graphics/tool_path.png")), pathEditPalette, "Pathedit"); tabs.addTab("", new ImageIcon(GraphicsHashtable.loadImage("/graphics/tool_message.png")), messagesPalette, "Messages"); } catch (IOException e) {} tabs.addChangeListener(new ModeListener()); } public void refresh() { connectionsPalette.refresh(); } public JTabbedPane getTabs() { return tabs; } public ToolPalette getToolPalette() { return toolPalette; } public class ModeListener implements ChangeListener { @Override public void stateChanged(ChangeEvent e) { String selectedTabTip = tabs.getToolTipTextAt(tabs.getSelectedIndex()); EditorInputHandler inputHandler = (EditorInputHandler) IOManager.getInstance().getInputHandler(); switch (selectedTabTip) { //FIXME: zrobmy cos z tym pozniej bo to obrzydliwe case "Tiles": { //zrobic cos madrzejszego inputHandler.onEvent(new ConnectableTileSelectedEvent(null)); GameManager.getInstance().onEvent(new SavePathEvent()); resetState(EditorMode.ADD); GameManager.getInstance().onEvent(new PalettePressedEvent(EditableTile.EMPTY)); //pathEditPalette.getArrows().selectOne(pathEditPalette.getArrows().buttons.get(0)); IOManager.getInstance().drawEditor(); break; } case "Connections": { //zrob<SUF> inputHandler.onEvent(new ConnectableTileSelectedEvent(null)); GameManager.getInstance().onEvent(new SavePathEvent()); resetState(EditorMode.CONNECT); IOManager.getInstance().drawEditor(); break; } case "Pathedit": { resetState(EditorMode.PATHEDIT); //zrobic cos madrzejszego pozniej inputHandler.onEvent(new ConnectableTileSelectedEvent(null)); pathEditPalette.getTree().clearSelection(); GameManager.getInstance().onEvent(new PalettePressedEvent(enums.Arrow.ARROW_UP)); //tilePalette.selectOne(tilePalette.buttons.get(0)); IOManager.getInstance().drawEditor(); break; } case "Messages": { resetState(EditorMode.MESSAGES); //zrobic cos madrzejszego pozniej inputHandler.onEvent(new ConnectableTileSelectedEvent(null)); messagesPalette.getTree().clearSelection(); GameManager.getInstance().onEvent(new PalettePressedEvent(EditableTile.EMPTY)); //tilePalette.selectOne(tilePalette.buttons.get(0)); IOManager.getInstance().drawEditor(); break; } default: { System.out.println("Ustawiono tryb na default - prawdopodobnie nieporzadane\nPaletteTabs line 63"); inputHandler.onEvent(new ModeChangedEvent(EditorMode.DEFAULT)); break; } } toolPalette.selectOne(toolPalette.buttons.get(0)); } } public void resetState (EditorMode m) { EditorInputHandler inputHandler = (EditorInputHandler) IOManager.getInstance().getInputHandler(); inputHandler.onEvent(new ChangeLayerEvent(Layer.BOTH)); inputHandler.onEvent(new ModeChangedEvent(m)); GameManager.getInstance().onEvent(new EditorChangeEvent()); } }
64859_9
package pl.zajavka.mortgage.services; import pl.zajavka.mortgage.model.InputData; import pl.zajavka.mortgage.model.MortgageResidual; import pl.zajavka.mortgage.model.Rate; import pl.zajavka.mortgage.model.RateAmounts; import java.math.BigDecimal; import java.math.RoundingMode; public class ResidualCalculationServiceImpl implements ResidualCalculationService { @Override public MortgageResidual calculate(RateAmounts rateAmounts, InputData inputData) { if (BigDecimal.ZERO.equals(inputData.getAmount())) { return new MortgageResidual(BigDecimal.ZERO, BigDecimal.ZERO); } else { BigDecimal residualAmount = calculateResidualAmount(inputData.getAmount(), rateAmounts); BigDecimal residualDuration = calculateResidualDuration(inputData, residualAmount, inputData.getMonthsDuration(), rateAmounts); return new MortgageResidual(residualAmount, residualDuration); } } @Override public MortgageResidual calculate(RateAmounts rateAmounts, final InputData inputData, Rate previousRate) { BigDecimal previousResidualAmount = previousRate.getMortgageResidual().getResidualAmount(); BigDecimal previousResidualDuration = previousRate.getMortgageResidual().getResidualDuration(); if (BigDecimal.ZERO.equals(previousResidualAmount)) { return new MortgageResidual(BigDecimal.ZERO, BigDecimal.ZERO); } else { BigDecimal residualAmount = calculateResidualAmount(previousResidualAmount, rateAmounts); BigDecimal residualDuration = calculateResidualDuration(inputData, residualAmount, previousResidualDuration, rateAmounts); return new MortgageResidual(residualAmount, residualDuration); } } private BigDecimal calculateResidualDuration( InputData inputData, BigDecimal residualAmount, BigDecimal previousResidualDuration, RateAmounts rateAmounts ) { // jak wystąpi nadpłata to zaczynają się schody, // trzeba przeliczyć kredyt w zależności od tego czy podczas nadpłaty zmniejszamy czas trwania czy wysokość raty if (rateAmounts.getOverpayment().getAmount().compareTo(BigDecimal.ZERO) > 0) { switch (inputData.getRateType()) { case CONSTANT: return calculateConstantResidualDuration(inputData, residualAmount, rateAmounts); case DECREASING: return calculateDecreasingResidualDuration(residualAmount, rateAmounts); default: throw new MortgageException("Case not handled"); } } else { // w każdym normalnym przypadku z miesiąca na miesiąc ilość pozostałych miesięcy jest zmniejszna o 1 return previousResidualDuration.subtract(BigDecimal.ONE); } } private BigDecimal calculateDecreasingResidualDuration(BigDecimal residualAmount, RateAmounts rateAmounts) { return residualAmount.divide(rateAmounts.getCapitalAmount(), 0, RoundingMode.CEILING); } @SuppressWarnings("UnnecessaryLocalVariable") // tutaj mamy zaszytą logikę z tego co wspomniałem w trakcie nagrań, // czyli jak oszacować ilość miesięcy jaka nam pozostała do spłaty przy nadpłacie, ratach stałych i zmniejszeniu czasu trwania. // Wyjaśnienie stosowanych wzorów zostało dostarczone w pliku z rozwiązaniem private BigDecimal calculateConstantResidualDuration(InputData inputData, BigDecimal residualAmount, RateAmounts rateAmounts) { // log_y(x) = log(x) / log (y) BigDecimal q = AmountsCalculationService.calculateQ(inputData.getInterestPercent()); // licznik z naszego logarytmu z licznika wzoru końcowego BigDecimal xNumerator = rateAmounts.getRateAmount(); // mianownik z naszego logarytmu z licznika wzoru końcowego. b/m to równie dobrze q-1 BigDecimal xDenominator = rateAmounts.getRateAmount().subtract(residualAmount.multiply(q.subtract(BigDecimal.ONE))); BigDecimal x = xNumerator.divide(xDenominator, 10, RoundingMode.HALF_UP); BigDecimal y = q; // logarytm z licznika BigDecimal logX = BigDecimal.valueOf(Math.log(x.doubleValue())); // logarytm z mianownika BigDecimal logY = BigDecimal.valueOf(Math.log(y.doubleValue())); return logX.divide(logY, 0, RoundingMode.CEILING); } private BigDecimal calculateResidualAmount(final BigDecimal residualAmount, final RateAmounts rateAmounts) { return residualAmount .subtract(rateAmounts.getCapitalAmount()) .subtract(rateAmounts.getOverpayment().getAmount()) .max(BigDecimal.ZERO); } }
0xRobert1997/Workshops
src/Workshops/no6_lombok/project/src/main/java/pl/zajavka/mortgage/services/ResidualCalculationServiceImpl.java
1,425
// logarytm z licznika
line_comment
pl
package pl.zajavka.mortgage.services; import pl.zajavka.mortgage.model.InputData; import pl.zajavka.mortgage.model.MortgageResidual; import pl.zajavka.mortgage.model.Rate; import pl.zajavka.mortgage.model.RateAmounts; import java.math.BigDecimal; import java.math.RoundingMode; public class ResidualCalculationServiceImpl implements ResidualCalculationService { @Override public MortgageResidual calculate(RateAmounts rateAmounts, InputData inputData) { if (BigDecimal.ZERO.equals(inputData.getAmount())) { return new MortgageResidual(BigDecimal.ZERO, BigDecimal.ZERO); } else { BigDecimal residualAmount = calculateResidualAmount(inputData.getAmount(), rateAmounts); BigDecimal residualDuration = calculateResidualDuration(inputData, residualAmount, inputData.getMonthsDuration(), rateAmounts); return new MortgageResidual(residualAmount, residualDuration); } } @Override public MortgageResidual calculate(RateAmounts rateAmounts, final InputData inputData, Rate previousRate) { BigDecimal previousResidualAmount = previousRate.getMortgageResidual().getResidualAmount(); BigDecimal previousResidualDuration = previousRate.getMortgageResidual().getResidualDuration(); if (BigDecimal.ZERO.equals(previousResidualAmount)) { return new MortgageResidual(BigDecimal.ZERO, BigDecimal.ZERO); } else { BigDecimal residualAmount = calculateResidualAmount(previousResidualAmount, rateAmounts); BigDecimal residualDuration = calculateResidualDuration(inputData, residualAmount, previousResidualDuration, rateAmounts); return new MortgageResidual(residualAmount, residualDuration); } } private BigDecimal calculateResidualDuration( InputData inputData, BigDecimal residualAmount, BigDecimal previousResidualDuration, RateAmounts rateAmounts ) { // jak wystąpi nadpłata to zaczynają się schody, // trzeba przeliczyć kredyt w zależności od tego czy podczas nadpłaty zmniejszamy czas trwania czy wysokość raty if (rateAmounts.getOverpayment().getAmount().compareTo(BigDecimal.ZERO) > 0) { switch (inputData.getRateType()) { case CONSTANT: return calculateConstantResidualDuration(inputData, residualAmount, rateAmounts); case DECREASING: return calculateDecreasingResidualDuration(residualAmount, rateAmounts); default: throw new MortgageException("Case not handled"); } } else { // w każdym normalnym przypadku z miesiąca na miesiąc ilość pozostałych miesięcy jest zmniejszna o 1 return previousResidualDuration.subtract(BigDecimal.ONE); } } private BigDecimal calculateDecreasingResidualDuration(BigDecimal residualAmount, RateAmounts rateAmounts) { return residualAmount.divide(rateAmounts.getCapitalAmount(), 0, RoundingMode.CEILING); } @SuppressWarnings("UnnecessaryLocalVariable") // tutaj mamy zaszytą logikę z tego co wspomniałem w trakcie nagrań, // czyli jak oszacować ilość miesięcy jaka nam pozostała do spłaty przy nadpłacie, ratach stałych i zmniejszeniu czasu trwania. // Wyjaśnienie stosowanych wzorów zostało dostarczone w pliku z rozwiązaniem private BigDecimal calculateConstantResidualDuration(InputData inputData, BigDecimal residualAmount, RateAmounts rateAmounts) { // log_y(x) = log(x) / log (y) BigDecimal q = AmountsCalculationService.calculateQ(inputData.getInterestPercent()); // licznik z naszego logarytmu z licznika wzoru końcowego BigDecimal xNumerator = rateAmounts.getRateAmount(); // mianownik z naszego logarytmu z licznika wzoru końcowego. b/m to równie dobrze q-1 BigDecimal xDenominator = rateAmounts.getRateAmount().subtract(residualAmount.multiply(q.subtract(BigDecimal.ONE))); BigDecimal x = xNumerator.divide(xDenominator, 10, RoundingMode.HALF_UP); BigDecimal y = q; // loga<SUF> BigDecimal logX = BigDecimal.valueOf(Math.log(x.doubleValue())); // logarytm z mianownika BigDecimal logY = BigDecimal.valueOf(Math.log(y.doubleValue())); return logX.divide(logY, 0, RoundingMode.CEILING); } private BigDecimal calculateResidualAmount(final BigDecimal residualAmount, final RateAmounts rateAmounts) { return residualAmount .subtract(rateAmounts.getCapitalAmount()) .subtract(rateAmounts.getOverpayment().getAmount()) .max(BigDecimal.ZERO); } }
67172_0
package com.example.zajecia7doktorki; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Zajecia7DoktorkiApplication { public static void main(String[] args) { /* Stworz aplikacje z pomoca springa gdzie beda mogli Pacjenci rejestrowac sie do Lekarza. Pacjent(id, name, surname, age, pesel, wizyty), Doktor(id, name, surname, specialization, age) Appointment(patientId, DoctorId, date) Pacjent ma miec mozliwosc zapisania sie do specjalisty. Mamy stworzyc pelnego CRUD'a. Doktor ma miec mozliwosc odwolania wizyty. Msmy miec mozliwosc wypisania wszystkich pacjentow danego doktorka I liste wizyt kazdego pacjenta */ SpringApplication.run(Zajecia7DoktorkiApplication.class, args); } }
10brajan/Hospital-manegment
src/main/java/com/example/zajecia7doktorki/Zajecia7DoktorkiApplication.java
291
/* Stworz aplikacje z pomoca springa gdzie beda mogli Pacjenci rejestrowac sie do Lekarza. Pacjent(id, name, surname, age, pesel, wizyty), Doktor(id, name, surname, specialization, age) Appointment(patientId, DoctorId, date) Pacjent ma miec mozliwosc zapisania sie do specjalisty. Mamy stworzyc pelnego CRUD'a. Doktor ma miec mozliwosc odwolania wizyty. Msmy miec mozliwosc wypisania wszystkich pacjentow danego doktorka I liste wizyt kazdego pacjenta */
block_comment
pl
package com.example.zajecia7doktorki; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Zajecia7DoktorkiApplication { public static void main(String[] args) { /* Stwor<SUF>*/ SpringApplication.run(Zajecia7DoktorkiApplication.class, args); } }
46504_6
import java.util.*; public class Main { public static void main(String[] args) { // Tworzenie grafu Graph graph = new Graph(); // Tworzenie wierzchołków Vertex v1 = new Vertex(1); Vertex v2 = new Vertex(2); Vertex v3 = new Vertex(3); Vertex v4 = new Vertex(4); // Dodawanie wierzchołków do grafu graph.addVertex(v1); graph.addVertex(v2); graph.addVertex(v3); graph.addVertex(v4); // Dodawanie krawędzi do grafu graph.addEdge(v1, v2, 2); graph.addEdge(v1, v3, 5); graph.addEdge(v2, v3, 1); graph.addEdge(v2, v4, 6); graph.addEdge(v3, v4, 3); // Wybieranie losowego wierzchołka docelowego Random random = new Random(); Vertex randomEndVertex = graph.vertices.get(random.nextInt(graph.vertices.size())); // Znajdowanie najkrótszej drogi między wierzchołkiem 1 a losowym wierzchołkiem docelowym List<Vertex> shortestPath = graph.shortestPath(v1, randomEndVertex); // Wyświetlanie najkrótszej drogi System.out.println("Najkrótsza droga:"); for (Vertex vertex : shortestPath) { System.out.print(vertex.id + " -> "); } } } class Vertex { int id; List<Edge> edges; public Vertex(int id) { this.id = id; this.edges = new ArrayList<>(); } public void addEdge(Edge edge) { edges.add(edge); } } class Edge { Vertex source; Vertex destination; int weight; public Edge(Vertex source, Vertex destination, int weight) { this.source = source; this.destination = destination; this.weight = weight; } } class Graph { List<Vertex> vertices; public Graph() { this.vertices = new ArrayList<>(); } public void addVertex(Vertex vertex) { vertices.add(vertex); } public void addEdge(Vertex source, Vertex destination, int weight) { Edge edge = new Edge(source, destination, weight); source.addEdge(edge); destination.addEdge(edge); } // Metoda do znajdowania najkrótszej drogi pomiędzy wierzchołkiem początkowym a losowym wierzchołkiem docelowym public List<Vertex> shortestPath(Vertex start, Vertex randomEndVertex) { // Inicjalizacja Map<Vertex, Integer> distances = new HashMap<>(); Map<Vertex, Vertex> previousVertices = new HashMap<>(); PriorityQueue<Vertex> queue = new PriorityQueue<>((v1, v2) -> distances.get(v1) - distances.get(v2)); for (Vertex vertex : vertices) { distances.put(vertex, vertex == start ? 0 : Integer.MAX_VALUE); queue.add(vertex); } // Algorytm Dijkstry while (!queue.isEmpty()) { Vertex current = queue.poll(); if (current == randomEndVertex) break; if (distances.get(current) == Integer.MAX_VALUE) break; for (Edge edge : current.edges) { Vertex neighbor = edge.source == current ? edge.destination : edge.source; int newDistance = distances.get(current) + edge.weight; if (newDistance < distances.get(neighbor)) { distances.put(neighbor, newDistance); previousVertices.put(neighbor, current); queue.remove(neighbor); queue.add(neighbor); } } } // Rekonstrukcja najkrótszej ścieżki List<Vertex> shortestPath = new ArrayList<>(); Vertex current = randomEndVertex; while (current != null) { shortestPath.add(current); current = previousVertices.get(current); } Collections.reverse(shortestPath); return shortestPath; } }
1312oskar/Algorytm-Dijkstry
algorytmDijksry.java
1,205
// Wyświetlanie najkrótszej drogi
line_comment
pl
import java.util.*; public class Main { public static void main(String[] args) { // Tworzenie grafu Graph graph = new Graph(); // Tworzenie wierzchołków Vertex v1 = new Vertex(1); Vertex v2 = new Vertex(2); Vertex v3 = new Vertex(3); Vertex v4 = new Vertex(4); // Dodawanie wierzchołków do grafu graph.addVertex(v1); graph.addVertex(v2); graph.addVertex(v3); graph.addVertex(v4); // Dodawanie krawędzi do grafu graph.addEdge(v1, v2, 2); graph.addEdge(v1, v3, 5); graph.addEdge(v2, v3, 1); graph.addEdge(v2, v4, 6); graph.addEdge(v3, v4, 3); // Wybieranie losowego wierzchołka docelowego Random random = new Random(); Vertex randomEndVertex = graph.vertices.get(random.nextInt(graph.vertices.size())); // Znajdowanie najkrótszej drogi między wierzchołkiem 1 a losowym wierzchołkiem docelowym List<Vertex> shortestPath = graph.shortestPath(v1, randomEndVertex); // Wyśw<SUF> System.out.println("Najkrótsza droga:"); for (Vertex vertex : shortestPath) { System.out.print(vertex.id + " -> "); } } } class Vertex { int id; List<Edge> edges; public Vertex(int id) { this.id = id; this.edges = new ArrayList<>(); } public void addEdge(Edge edge) { edges.add(edge); } } class Edge { Vertex source; Vertex destination; int weight; public Edge(Vertex source, Vertex destination, int weight) { this.source = source; this.destination = destination; this.weight = weight; } } class Graph { List<Vertex> vertices; public Graph() { this.vertices = new ArrayList<>(); } public void addVertex(Vertex vertex) { vertices.add(vertex); } public void addEdge(Vertex source, Vertex destination, int weight) { Edge edge = new Edge(source, destination, weight); source.addEdge(edge); destination.addEdge(edge); } // Metoda do znajdowania najkrótszej drogi pomiędzy wierzchołkiem początkowym a losowym wierzchołkiem docelowym public List<Vertex> shortestPath(Vertex start, Vertex randomEndVertex) { // Inicjalizacja Map<Vertex, Integer> distances = new HashMap<>(); Map<Vertex, Vertex> previousVertices = new HashMap<>(); PriorityQueue<Vertex> queue = new PriorityQueue<>((v1, v2) -> distances.get(v1) - distances.get(v2)); for (Vertex vertex : vertices) { distances.put(vertex, vertex == start ? 0 : Integer.MAX_VALUE); queue.add(vertex); } // Algorytm Dijkstry while (!queue.isEmpty()) { Vertex current = queue.poll(); if (current == randomEndVertex) break; if (distances.get(current) == Integer.MAX_VALUE) break; for (Edge edge : current.edges) { Vertex neighbor = edge.source == current ? edge.destination : edge.source; int newDistance = distances.get(current) + edge.weight; if (newDistance < distances.get(neighbor)) { distances.put(neighbor, newDistance); previousVertices.put(neighbor, current); queue.remove(neighbor); queue.add(neighbor); } } } // Rekonstrukcja najkrótszej ścieżki List<Vertex> shortestPath = new ArrayList<>(); Vertex current = randomEndVertex; while (current != null) { shortestPath.add(current); current = previousVertices.get(current); } Collections.reverse(shortestPath); return shortestPath; } }
107714_6
package esa.Project; import esa.Project.Entities.Pomiar; import esa.Project.Entities.PunktPomiarowy; import esa.Project.Transactions.PomiarTransactions; import org.apache.commons.io.IOUtils; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.sql.Date; import java.sql.Time; import java.time.LocalDateTime; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.Charset; @Component public class EsaJSONData { private static String uriString = "https://public-esa.ose.gov.pl/api/v1/smog"; private static URL url; static { try { url = new URI(uriString).toURL(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } } @Scheduled(fixedRate = 300000) public static void getJson() throws IOException { String json = IOUtils.toString(url, Charset.forName("UTF-8")); json = json.substring(14, json.length()); for (int i = json.length() - 1; i > 0; i--) { if (json.charAt(i) == ']') { json = json.substring(0, i); break; } } readSchoolData(json); } private static void readSchoolData(String json) { String[] schools = json.split("school"); String[][] schoolsData = new String[schools.length][2]; int valid = 0; for (int i = 0; i < schools.length; i++) { try { String[] data = schools[i].split("data"); schoolsData[valid][0] = data[0].replace('{', ' ').replace('}', ' ').substring(3, data[0].length() - 3); //TODO już tutaj wywalić timestamp w pomiarze, znajdując pierwsze wystąpienie } String outTimestamp = trimTimestamp(data[1]); schoolsData[valid][1] = outTimestamp.replace('{', ' ').replace('}', ' ').substring(3); //System.out.println(schoolsData[valid][0]); //System.out.println(schoolsData[valid][1]); valid++; } catch (IndexOutOfBoundsException exc) { /*System.out.println("Brakuje drugiego: "); System.out.println(schools[i]);*/ } } parseToDataBase(schoolsData); } private static String trimTimestamp(String row) { int firstClosedIndex = 0; char closed = '}'; for (int i = 0; i < row.length(); i++) { if (row.charAt(i) == closed) { firstClosedIndex = i; break; } } return row.substring(0, firstClosedIndex); } private static void parseToDataBase(String[][] schoolsData) { Pomiar[] measData = new Pomiar[schoolsData.length]; LocalDateTime now = LocalDateTime.now(); Date date = Date.valueOf(now.toString().split("T")[0]); String timeStr = now.toString().split("T")[1]; String[] timeElem = timeStr.split(":"); Time time = new Time(Integer.parseInt(timeElem[0]), Integer.parseInt(timeElem[1]), 0); for (int i = 0; i < schoolsData.length; i++) { if (schoolsData[i][0] == null || schoolsData[i][1] == null) { break; } PunktPomiarowy school = parseSchool(schoolsData[i][0]); Pomiar meas = parseMeasData(schoolsData[i][1]); if (meas != null) { meas.setPunktPomiarowy(school); meas.setTime(time); meas.setDate(date); //TODO save to database } measData[i] = meas; } PomiarTransactions.addManyPomiar(deleteVoid(measData)); } private static Pomiar[] deleteVoid(Pomiar[] meas){ int correct = 0; for(Pomiar record : meas){ if(record != null){ correct++; } } Pomiar[] correctMeas = new Pomiar[correct]; int counter = 0; for(Pomiar record : meas){ if(record != null){ correctMeas[counter] = record; counter++; } } return correctMeas; } private static PunktPomiarowy parseSchool(String school) { school = school.trim(); JSONObject ob = new JSONObject("{" + school + "}"); String city = ob.get("city").toString().trim(); String street = ob.get("street").toString().trim(); String zipCode = ob.get("post_code").toString().trim(); String schoolName = ob.get("name").toString().trim(); float latitude = Float.parseFloat(ob.get("latitude").toString().trim()); float longitude = Float.parseFloat(ob.get("longitude").toString().trim()); PunktPomiarowy punktPomiarowy = new PunktPomiarowy(city, street, zipCode, schoolName, latitude, longitude); //System.out.println(punktPomiarowy); return punktPomiarowy; } private static Pomiar parseMeasData(String data) { //System.out.println(data); data = data.trim(); try { JSONObject ob = new JSONObject("{" + data + "}"); float temperature = Float.parseFloat(ob.get("temperature_avg").toString().trim()); float humidity = Float.parseFloat(ob.get("humidity_avg").toString().trim()); float pressure = Float.parseFloat(ob.get("pressure_avg").toString().trim()); float pm25 = Float.parseFloat(ob.get("pm25_avg").toString().trim()); float pm10 = Float.parseFloat(ob.get("pm10_avg").toString().trim()); Pomiar pomiar = new Pomiar(temperature, humidity, pressure, pm25, pm10); return pomiar; } catch (org.json.JSONException | NumberFormatException exc) { System.out.println(exc.getMessage()); System.out.println(data); return null; } } }
154436/Aplikacja_gromadzenie_i_prezentowanie_danych_ESA
src/main/java/esa/Project/EsaJSONData.java
1,789
//System.out.println(punktPomiarowy);
line_comment
pl
package esa.Project; import esa.Project.Entities.Pomiar; import esa.Project.Entities.PunktPomiarowy; import esa.Project.Transactions.PomiarTransactions; import org.apache.commons.io.IOUtils; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.sql.Date; import java.sql.Time; import java.time.LocalDateTime; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.Charset; @Component public class EsaJSONData { private static String uriString = "https://public-esa.ose.gov.pl/api/v1/smog"; private static URL url; static { try { url = new URI(uriString).toURL(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } } @Scheduled(fixedRate = 300000) public static void getJson() throws IOException { String json = IOUtils.toString(url, Charset.forName("UTF-8")); json = json.substring(14, json.length()); for (int i = json.length() - 1; i > 0; i--) { if (json.charAt(i) == ']') { json = json.substring(0, i); break; } } readSchoolData(json); } private static void readSchoolData(String json) { String[] schools = json.split("school"); String[][] schoolsData = new String[schools.length][2]; int valid = 0; for (int i = 0; i < schools.length; i++) { try { String[] data = schools[i].split("data"); schoolsData[valid][0] = data[0].replace('{', ' ').replace('}', ' ').substring(3, data[0].length() - 3); //TODO już tutaj wywalić timestamp w pomiarze, znajdując pierwsze wystąpienie } String outTimestamp = trimTimestamp(data[1]); schoolsData[valid][1] = outTimestamp.replace('{', ' ').replace('}', ' ').substring(3); //System.out.println(schoolsData[valid][0]); //System.out.println(schoolsData[valid][1]); valid++; } catch (IndexOutOfBoundsException exc) { /*System.out.println("Brakuje drugiego: "); System.out.println(schools[i]);*/ } } parseToDataBase(schoolsData); } private static String trimTimestamp(String row) { int firstClosedIndex = 0; char closed = '}'; for (int i = 0; i < row.length(); i++) { if (row.charAt(i) == closed) { firstClosedIndex = i; break; } } return row.substring(0, firstClosedIndex); } private static void parseToDataBase(String[][] schoolsData) { Pomiar[] measData = new Pomiar[schoolsData.length]; LocalDateTime now = LocalDateTime.now(); Date date = Date.valueOf(now.toString().split("T")[0]); String timeStr = now.toString().split("T")[1]; String[] timeElem = timeStr.split(":"); Time time = new Time(Integer.parseInt(timeElem[0]), Integer.parseInt(timeElem[1]), 0); for (int i = 0; i < schoolsData.length; i++) { if (schoolsData[i][0] == null || schoolsData[i][1] == null) { break; } PunktPomiarowy school = parseSchool(schoolsData[i][0]); Pomiar meas = parseMeasData(schoolsData[i][1]); if (meas != null) { meas.setPunktPomiarowy(school); meas.setTime(time); meas.setDate(date); //TODO save to database } measData[i] = meas; } PomiarTransactions.addManyPomiar(deleteVoid(measData)); } private static Pomiar[] deleteVoid(Pomiar[] meas){ int correct = 0; for(Pomiar record : meas){ if(record != null){ correct++; } } Pomiar[] correctMeas = new Pomiar[correct]; int counter = 0; for(Pomiar record : meas){ if(record != null){ correctMeas[counter] = record; counter++; } } return correctMeas; } private static PunktPomiarowy parseSchool(String school) { school = school.trim(); JSONObject ob = new JSONObject("{" + school + "}"); String city = ob.get("city").toString().trim(); String street = ob.get("street").toString().trim(); String zipCode = ob.get("post_code").toString().trim(); String schoolName = ob.get("name").toString().trim(); float latitude = Float.parseFloat(ob.get("latitude").toString().trim()); float longitude = Float.parseFloat(ob.get("longitude").toString().trim()); PunktPomiarowy punktPomiarowy = new PunktPomiarowy(city, street, zipCode, schoolName, latitude, longitude); //Syst<SUF> return punktPomiarowy; } private static Pomiar parseMeasData(String data) { //System.out.println(data); data = data.trim(); try { JSONObject ob = new JSONObject("{" + data + "}"); float temperature = Float.parseFloat(ob.get("temperature_avg").toString().trim()); float humidity = Float.parseFloat(ob.get("humidity_avg").toString().trim()); float pressure = Float.parseFloat(ob.get("pressure_avg").toString().trim()); float pm25 = Float.parseFloat(ob.get("pm25_avg").toString().trim()); float pm10 = Float.parseFloat(ob.get("pm10_avg").toString().trim()); Pomiar pomiar = new Pomiar(temperature, humidity, pressure, pm25, pm10); return pomiar; } catch (org.json.JSONException | NumberFormatException exc) { System.out.println(exc.getMessage()); System.out.println(data); return null; } } }
154635_12
/* * WorkSpace.java * * Created on 25. jen 2006, 21:37 * * To change this template, choose Tools | Template Manager * and open the template in the draw. */ package by.dak.cutting.cut.base; import java.util.ArrayList; /** * @author Peca */ public class WorkSpace extends AbstractWorkSpace { //private Dimension plateSize; //rozmery desky k narezani //public QuickList<WorkArea> workAreas; public ArrayList<WorkArea> workAreas; private WorkArea[] workSheets; // public int minElementWidth = 0; // public int minElementHeight = 0; // public int minElementSize = 0; private int mostRightCut = 0; // public ArrayList<Rect> boxes; /** * Creates a new instance of WorkSpace */ protected WorkSpace() { workAreas = new ArrayList<WorkArea>(); } public WorkSpace(WorkArea[] workSheets) { this(); this.workSheets = workSheets; clear(); } public Dimension getPlateSize() { return workSheets[0]; } /* public void setPlateSize(Dimension plateSize){ this.plateSize = plateSize; clear(); } */ public void clear() { workAreas.clear(); mostRightCut = 0; for (int i = 0; i < workSheets.length; i++) { workAreas.add(workSheets[i]); } //workAreas.add(new WorkArea(plateSize.width, plateSize.height)); } public WorkArea[] getWorkAreas() { WorkArea[] was = new WorkArea[workAreas.size()]; for (int i = 0; i < workAreas.size(); i++) { was[i] = workAreas.get(i); } return was; } public WorkArea findTopLeftWorkArea(Dimension elementSize) { long min = Long.MAX_VALUE; WorkArea best = null; for (int i = 0; i < workAreas.size(); i++) { WorkArea wa = workAreas.get(i); long dist = wa.getY() + wa.getX() * getPlateSize().getHeight(); if ((min > dist) && (wa.getWidth() >= elementSize.getWidth()) && (wa.getHeight() >= elementSize.getHeight())) { best = wa; min = dist; } } return best; } public int getRightFreeLength() { return mostRightCut; } public int getRightEmptyArea(WorkArea workSheet) { int r = 0; for (WorkArea wa : workAreas) { if (!wa.intersect(workSheet)) continue; //nepatri to do tohoto sheetu if (wa.getX2() != workSheet.getX2()) continue; //neni to workarea co se dotyka konce if (wa.getY() != workSheet.getY()) continue; if (wa.getY2() != workSheet.getY2()) continue; r = wa.getArea(); break; } return r; } public int getRightEmptyArea() { int r = 0; for (WorkArea ws : workSheets) { r += getRightEmptyArea(ws); } return r; } /** * Plocha workarea nedotykajicich se konce desky * */ public int getLeftEmptyArea(WorkArea workSheet) { int area = 0; for (WorkArea wa : workAreas) { if (!wa.intersect(workSheet)) continue; //nepatri to do tohoto sheetu if (wa.getX2() == workSheet.getX2()) continue; //dotyka se to konce desky area += wa.getArea(); } return area; } public int getLeftEmptyArea() { int area = 0; for (WorkArea ws : workSheets) { area += getLeftEmptyArea(ws); } return area; } public int getTotalArea() { int area = 0; for (WorkArea ws : workSheets) { area += ws.getArea(); } return area; } public void cut(Rect rct) { ArrayList<WorkArea> wanew = new ArrayList<WorkArea>(); //seznam nove vytvorenych pracovnich ploch int i = 0; if (mostRightCut < rct.getX2()) mostRightCut = rct.getX2(); while (i < workAreas.size()) { //projdeme vsechny pracovni plochy WorkArea wa = workAreas.get(i); Rect[] ra = wa.split(rct); //a vsechny je rozdelime (pokud to jde) if (ra != null) { //slo to workAreas.remove(wa); //plochu kterou jsme rezali odstranime for (Rect r : ra) { //vsechny nove casti pridame do seznamu novych if ((r.getWidth() >= minElementSize) && (r.getHeight() >= minElementSize)) wanew.add(new WorkArea(r)); } } else i++; } i = 0; workAreas.addAll(wanew); while (i < workAreas.size()) { //projdeme vsechny pracovni plochy WorkArea wa = workAreas.get(i); if (isWorkAreaOverlapped(wa)) workAreas.remove(wa); //pokud je nova ploska cela prekryta jinou ploskou, tak ji odstranime ze seznamu else i++; } } /*public void cut_O1(Rect rct){ //ArrayList<WorkArea> wanew = new ArrayList<WorkArea>(); //seznam nove vytvorenych pracovnich ploch if(mostRightCut < rct.x2) mostRightCut = rct.x2; int n = workAreas.size(); for(int i=0; i<n; i++){ //projdeme vsechny pracovni plochy WorkArea wa = workAreas.get(i); Rect[] ra = wa.split(rct); //a vsechny je rozdelime (pokud to jde) if(ra != null){ //slo to workAreas.remove(i); //plochu kterou jsme rezali odstranime for(Rect r : ra){ //vsechny nove casti pridame do seznamu novych if((r.width >= minElementSize)&&(r.height >= minElementSize)) wanew.add(new WorkArea(r)); } } else i++; } i = 0; workAreas.addAll(wanew); while(i < workAreas.size()){ //projdeme vsechny pracovni plochy WorkArea wa = workAreas.get(i); if(isWorkAreaOverlapped(wa)) workAreas.remove(i); //pokud je nova ploska cela prekryta jinou ploskou, tak ji odstranime ze seznamu else i++; } }*/ /* public void by.dak.cutting.cut(Rect rct, WorkArea wa, boolean recursive){ Rect[] ra = wa.split(rct); //narezu pracovni plochu if(ra == null)return; //nic se nenarezalo //odstranime wa ze seznamu workAreas.remove(wa); //u vsem sousedum rekneme ze uz s nima tato plocha nesousedi for(WorkArea wan : wa.neighbours){ wan.neighbours.remove(this); } //podivame se jestli nove plosky nejsou obsazeny v nejakem sousedovi int newCount = 0; boolean isInvalid; for(int i=0; i<ra.length; i++){ isInvalid = false; for(WorkArea wan : wa.neighbours){ if(wan.contains(ra[i])){ //nova ploska je uz obsazena v jiny, tak ji oznacime jako null ra[i] = null; isInvalid = true; break; } } if(!isInvalid)newCount++; } //nove vytovrene plosky pridame do seznamu plosek WorkArea[] newWas = new WorkArea[newCount]; int index = 0; for(int i=0; i<ra.length; i++){ if(ra[i] == null)continue; newWas[index] = new WorkArea(ra[i]); workAreas.add(newWas[index]); index++; } //podivame se jak nove plosky sousedi samy s sebou for(int i=0; i<newWas.length; i++){ for(int j=i+1; j<newWas.length; j++){ if(newWas[i].intersect(newWas[j])){ newWas[i].neighbours.add(newWas[j]); newWas[j].neighbours.add(newWas[i]); } } } //nove plosky co sousedi s tema stavajicima oznacime jako sousedi for(int i=0; i<newWas.length; i++){ for(WorkArea wan : wa.neighbours){ if(wan.intersect(newWas[i])){ //nova ploska se dotyka jine plosky newWas[i].neighbours.add(wan); wan.neighbours.add(newWas[i]); } } } // narezeme i plosky co sousedi s wa if(recursive){ WorkArea[] was = new WorkArea[wa.neighbours.size()]; for(int i=0; i<wa.neighbours.size(); i++){ was[i] = wa.neighbours.get(i); } for(int i=0; i<was.length; i++){ by.dak.cutting.cut(rct, was[i], false); //ale uz musime vypnout rekurzi } } }*/ /* private void removeTooSmalWorkAreas(){ while(i < workAreas.size()){ //projdeme vsechny pracovni plochy WorkArea wa = workAreas.get(i); if(isWorkAreaOverlapped(wa)) workAreas.remove(wa); //pokud je nova ploska cela prekryta jinou ploskou, tak ji odstranime ze seznamu else i++; } }*/ /** * zjistuje jestli je pracovni prostor wa cely prekryt jinym pracovnim prostorem */ protected boolean isWorkAreaOverlapped(WorkArea wa) { for (int i = 0; i < workAreas.size(); i++) { WorkArea w = workAreas.get(i); if (w == wa) continue; if (w.contains(wa)) return true; } return false; } public int getFreeArea() { int area = 0; for (WorkArea wa : workAreas) { area += wa.getArea(); } return area; } }
15831944/furman
furman.main/src/main/java/by/dak/cutting/cut/base/WorkSpace.java
3,234
//neni to workarea co se dotyka konce
line_comment
pl
/* * WorkSpace.java * * Created on 25. jen 2006, 21:37 * * To change this template, choose Tools | Template Manager * and open the template in the draw. */ package by.dak.cutting.cut.base; import java.util.ArrayList; /** * @author Peca */ public class WorkSpace extends AbstractWorkSpace { //private Dimension plateSize; //rozmery desky k narezani //public QuickList<WorkArea> workAreas; public ArrayList<WorkArea> workAreas; private WorkArea[] workSheets; // public int minElementWidth = 0; // public int minElementHeight = 0; // public int minElementSize = 0; private int mostRightCut = 0; // public ArrayList<Rect> boxes; /** * Creates a new instance of WorkSpace */ protected WorkSpace() { workAreas = new ArrayList<WorkArea>(); } public WorkSpace(WorkArea[] workSheets) { this(); this.workSheets = workSheets; clear(); } public Dimension getPlateSize() { return workSheets[0]; } /* public void setPlateSize(Dimension plateSize){ this.plateSize = plateSize; clear(); } */ public void clear() { workAreas.clear(); mostRightCut = 0; for (int i = 0; i < workSheets.length; i++) { workAreas.add(workSheets[i]); } //workAreas.add(new WorkArea(plateSize.width, plateSize.height)); } public WorkArea[] getWorkAreas() { WorkArea[] was = new WorkArea[workAreas.size()]; for (int i = 0; i < workAreas.size(); i++) { was[i] = workAreas.get(i); } return was; } public WorkArea findTopLeftWorkArea(Dimension elementSize) { long min = Long.MAX_VALUE; WorkArea best = null; for (int i = 0; i < workAreas.size(); i++) { WorkArea wa = workAreas.get(i); long dist = wa.getY() + wa.getX() * getPlateSize().getHeight(); if ((min > dist) && (wa.getWidth() >= elementSize.getWidth()) && (wa.getHeight() >= elementSize.getHeight())) { best = wa; min = dist; } } return best; } public int getRightFreeLength() { return mostRightCut; } public int getRightEmptyArea(WorkArea workSheet) { int r = 0; for (WorkArea wa : workAreas) { if (!wa.intersect(workSheet)) continue; //nepatri to do tohoto sheetu if (wa.getX2() != workSheet.getX2()) continue; //neni<SUF> if (wa.getY() != workSheet.getY()) continue; if (wa.getY2() != workSheet.getY2()) continue; r = wa.getArea(); break; } return r; } public int getRightEmptyArea() { int r = 0; for (WorkArea ws : workSheets) { r += getRightEmptyArea(ws); } return r; } /** * Plocha workarea nedotykajicich se konce desky * */ public int getLeftEmptyArea(WorkArea workSheet) { int area = 0; for (WorkArea wa : workAreas) { if (!wa.intersect(workSheet)) continue; //nepatri to do tohoto sheetu if (wa.getX2() == workSheet.getX2()) continue; //dotyka se to konce desky area += wa.getArea(); } return area; } public int getLeftEmptyArea() { int area = 0; for (WorkArea ws : workSheets) { area += getLeftEmptyArea(ws); } return area; } public int getTotalArea() { int area = 0; for (WorkArea ws : workSheets) { area += ws.getArea(); } return area; } public void cut(Rect rct) { ArrayList<WorkArea> wanew = new ArrayList<WorkArea>(); //seznam nove vytvorenych pracovnich ploch int i = 0; if (mostRightCut < rct.getX2()) mostRightCut = rct.getX2(); while (i < workAreas.size()) { //projdeme vsechny pracovni plochy WorkArea wa = workAreas.get(i); Rect[] ra = wa.split(rct); //a vsechny je rozdelime (pokud to jde) if (ra != null) { //slo to workAreas.remove(wa); //plochu kterou jsme rezali odstranime for (Rect r : ra) { //vsechny nove casti pridame do seznamu novych if ((r.getWidth() >= minElementSize) && (r.getHeight() >= minElementSize)) wanew.add(new WorkArea(r)); } } else i++; } i = 0; workAreas.addAll(wanew); while (i < workAreas.size()) { //projdeme vsechny pracovni plochy WorkArea wa = workAreas.get(i); if (isWorkAreaOverlapped(wa)) workAreas.remove(wa); //pokud je nova ploska cela prekryta jinou ploskou, tak ji odstranime ze seznamu else i++; } } /*public void cut_O1(Rect rct){ //ArrayList<WorkArea> wanew = new ArrayList<WorkArea>(); //seznam nove vytvorenych pracovnich ploch if(mostRightCut < rct.x2) mostRightCut = rct.x2; int n = workAreas.size(); for(int i=0; i<n; i++){ //projdeme vsechny pracovni plochy WorkArea wa = workAreas.get(i); Rect[] ra = wa.split(rct); //a vsechny je rozdelime (pokud to jde) if(ra != null){ //slo to workAreas.remove(i); //plochu kterou jsme rezali odstranime for(Rect r : ra){ //vsechny nove casti pridame do seznamu novych if((r.width >= minElementSize)&&(r.height >= minElementSize)) wanew.add(new WorkArea(r)); } } else i++; } i = 0; workAreas.addAll(wanew); while(i < workAreas.size()){ //projdeme vsechny pracovni plochy WorkArea wa = workAreas.get(i); if(isWorkAreaOverlapped(wa)) workAreas.remove(i); //pokud je nova ploska cela prekryta jinou ploskou, tak ji odstranime ze seznamu else i++; } }*/ /* public void by.dak.cutting.cut(Rect rct, WorkArea wa, boolean recursive){ Rect[] ra = wa.split(rct); //narezu pracovni plochu if(ra == null)return; //nic se nenarezalo //odstranime wa ze seznamu workAreas.remove(wa); //u vsem sousedum rekneme ze uz s nima tato plocha nesousedi for(WorkArea wan : wa.neighbours){ wan.neighbours.remove(this); } //podivame se jestli nove plosky nejsou obsazeny v nejakem sousedovi int newCount = 0; boolean isInvalid; for(int i=0; i<ra.length; i++){ isInvalid = false; for(WorkArea wan : wa.neighbours){ if(wan.contains(ra[i])){ //nova ploska je uz obsazena v jiny, tak ji oznacime jako null ra[i] = null; isInvalid = true; break; } } if(!isInvalid)newCount++; } //nove vytovrene plosky pridame do seznamu plosek WorkArea[] newWas = new WorkArea[newCount]; int index = 0; for(int i=0; i<ra.length; i++){ if(ra[i] == null)continue; newWas[index] = new WorkArea(ra[i]); workAreas.add(newWas[index]); index++; } //podivame se jak nove plosky sousedi samy s sebou for(int i=0; i<newWas.length; i++){ for(int j=i+1; j<newWas.length; j++){ if(newWas[i].intersect(newWas[j])){ newWas[i].neighbours.add(newWas[j]); newWas[j].neighbours.add(newWas[i]); } } } //nove plosky co sousedi s tema stavajicima oznacime jako sousedi for(int i=0; i<newWas.length; i++){ for(WorkArea wan : wa.neighbours){ if(wan.intersect(newWas[i])){ //nova ploska se dotyka jine plosky newWas[i].neighbours.add(wan); wan.neighbours.add(newWas[i]); } } } // narezeme i plosky co sousedi s wa if(recursive){ WorkArea[] was = new WorkArea[wa.neighbours.size()]; for(int i=0; i<wa.neighbours.size(); i++){ was[i] = wa.neighbours.get(i); } for(int i=0; i<was.length; i++){ by.dak.cutting.cut(rct, was[i], false); //ale uz musime vypnout rekurzi } } }*/ /* private void removeTooSmalWorkAreas(){ while(i < workAreas.size()){ //projdeme vsechny pracovni plochy WorkArea wa = workAreas.get(i); if(isWorkAreaOverlapped(wa)) workAreas.remove(wa); //pokud je nova ploska cela prekryta jinou ploskou, tak ji odstranime ze seznamu else i++; } }*/ /** * zjistuje jestli je pracovni prostor wa cely prekryt jinym pracovnim prostorem */ protected boolean isWorkAreaOverlapped(WorkArea wa) { for (int i = 0; i < workAreas.size(); i++) { WorkArea w = workAreas.get(i); if (w == wa) continue; if (w.contains(wa)) return true; } return false; } public int getFreeArea() { int area = 0; for (WorkArea wa : workAreas) { area += wa.getArea(); } return area; } }
37284_0
package AutomaticService; import java.util.Dictionary; import java.util.Hashtable; import com.skype.ChatMessage; import com.skype.ChatMessageAdapter; import com.skype.Skype; import com.skype.SkypeException; import com.skype.User; public class AutoAnswering { private Dictionary<String, String> Clients = new Hashtable<String, String>(); public AutoAnswering() throws Exception { System.out.println("Start Auto Answering ..."); Skype.setDaemon(false); Skype.addChatMessageListener(new ChatMessageAdapter() { public void chatMessageReceived(ChatMessage received) throws SkypeException { if (received.getType().equals(ChatMessage.Type.SAID)) { User sender =received.getSender(); System.out.println(sender.getId() +" say:"); System.out.println(" "+received.getContent() ); String answer = Answer(sender.getId(), received.getContent()); received.getSender().send(answer); } } }); System.out.println("Auto Answering started!"); } private String Answer(String user, String message){ if(Clients.get(user)==null){ Clients.put(user, "state0"); return "Hello, this is automatic Call Center!\n\n" + "Choose what you want to do:\n" + "press 1 to log in\n" + "press 2 to connect to an agent\n" + "press 3 to hear options again\n"; } else{ if(Clients.get(user)=="state0"){ if(message.equals("1")){ Clients.put(user, "state1");//klient przechodzi do innego taska return "Loging in ..."; } if(message.equals("2")){ Clients.put(user, "state2");//klient przechodzi do innego taska return "Calling ..."; } else{ return "Choose what you want to do:\n" + "press 1 to log in\n" + "press 2 to connect to an agent\n" + "press 3 to hear options again\n"; } } else return "Error - You should be eighter calling or loging in"; } } }
180132/CallCenter
CallCenter/src/AutomaticService/AutoAnswering.java
769
//klient przechodzi do innego taska
line_comment
pl
package AutomaticService; import java.util.Dictionary; import java.util.Hashtable; import com.skype.ChatMessage; import com.skype.ChatMessageAdapter; import com.skype.Skype; import com.skype.SkypeException; import com.skype.User; public class AutoAnswering { private Dictionary<String, String> Clients = new Hashtable<String, String>(); public AutoAnswering() throws Exception { System.out.println("Start Auto Answering ..."); Skype.setDaemon(false); Skype.addChatMessageListener(new ChatMessageAdapter() { public void chatMessageReceived(ChatMessage received) throws SkypeException { if (received.getType().equals(ChatMessage.Type.SAID)) { User sender =received.getSender(); System.out.println(sender.getId() +" say:"); System.out.println(" "+received.getContent() ); String answer = Answer(sender.getId(), received.getContent()); received.getSender().send(answer); } } }); System.out.println("Auto Answering started!"); } private String Answer(String user, String message){ if(Clients.get(user)==null){ Clients.put(user, "state0"); return "Hello, this is automatic Call Center!\n\n" + "Choose what you want to do:\n" + "press 1 to log in\n" + "press 2 to connect to an agent\n" + "press 3 to hear options again\n"; } else{ if(Clients.get(user)=="state0"){ if(message.equals("1")){ Clients.put(user, "state1");//klie<SUF> return "Loging in ..."; } if(message.equals("2")){ Clients.put(user, "state2");//klient przechodzi do innego taska return "Calling ..."; } else{ return "Choose what you want to do:\n" + "press 1 to log in\n" + "press 2 to connect to an agent\n" + "press 3 to hear options again\n"; } } else return "Error - You should be eighter calling or loging in"; } } }
7075_2
/** * @name Simple Java Calculator * @package ph.calculator * @file Main.java * @author SORIA Pierre-Henry * @email pierrehs@hotmail.com * @link http://github.com/pH-7 * @copyright Copyright Pierre-Henry SORIA, All Rights Reserved. * @license Apache (http://www.apache.org/licenses/LICENSE-2.0) * @create 2012-03-30 * * @modifiedby Achintha Gunasekara * @modweb http://www.achinthagunasekara.com * @modemail contact@achinthagunasekara.com */ package simplejavacalculator; public class SimpleJavaCalculator { public static void main(String[] args) { //cokolwiek moze nie //wprowadzam zmiane jeszcze raz //3ci komentarz //4ty komentarz UI uiCal = new UI(); uiCal.init(); } }
180201/ZPI-01
src/simplejavacalculator/SimpleJavaCalculator.java
283
//wprowadzam zmiane jeszcze raz
line_comment
pl
/** * @name Simple Java Calculator * @package ph.calculator * @file Main.java * @author SORIA Pierre-Henry * @email pierrehs@hotmail.com * @link http://github.com/pH-7 * @copyright Copyright Pierre-Henry SORIA, All Rights Reserved. * @license Apache (http://www.apache.org/licenses/LICENSE-2.0) * @create 2012-03-30 * * @modifiedby Achintha Gunasekara * @modweb http://www.achinthagunasekara.com * @modemail contact@achinthagunasekara.com */ package simplejavacalculator; public class SimpleJavaCalculator { public static void main(String[] args) { //cokolwiek moze nie //wpro<SUF> //3ci komentarz //4ty komentarz UI uiCal = new UI(); uiCal.init(); } }
146252_1
package pl.edwi.app; import com.sun.java.swing.plaf.windows.WindowsLookAndFeel; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.Fields; import org.apache.lucene.index.IndexReader; import org.apache.lucene.queries.mlt.MoreLikeThis; import org.apache.lucene.search.*; import org.apache.lucene.search.highlight.*; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.QueryBuilder; import pl.edwi.tool.Try; import pl.edwi.ui.FindResult7; import pl.edwi.ui.FindTableMode7; import javax.swing.*; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @SuppressWarnings("Duplicates") public class App7b { private JPanel jPanel; private JTextField findText; private JComboBox<String> findType; private JComboBox<String> findWhere; private JButton findButton; private JTable resultTable; private JLabel statusText; private FindTableMode7 findTableModel; public App7b(Analyzer analyzer, IndexReader reader) { } public static void main(String[] args) throws IOException { try { UIManager.setLookAndFeel(WindowsLookAndFeel.class.getName()); } catch (ClassNotFoundException | InstantiationException | UnsupportedLookAndFeelException | IllegalAccessException ignored) { } Analyzer analyzer = new StandardAnalyzer(); Directory index = FSDirectory.open(Paths.get(App7a.LUCENE_DIR)); IndexReader reader = DirectoryReader.open(index); App7b app7b = new App7b(analyzer, reader); JFrame frame = new JFrame("Bot internetowy"); frame.setContentPane(app7b.jPanel); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); Component p = app7b.jPanel; while (p != null && !(p instanceof Window)) { p = p.getParent(); } if (p != null) { ((Window) p).addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent winEvt) { Try.ex(reader::close); Try.ex(index::close); Try.ex(analyzer::close); } }); } app7b.findType.addItem("zawiera"); app7b.findType.addItem("dokładne"); app7b.findWhere.addItem("w treści"); app7b.findWhere.addItem("w adresie"); app7b.jPanel.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { app7b.resizeResultTableColumns(); } }); app7b.findText.addActionListener((event) -> app7b.search(analyzer, reader)); app7b.findButton.addActionListener((event) -> app7b.search(analyzer, reader)); app7b.findTableModel = new FindTableMode7(); app7b.resultTable.setModel(app7b.findTableModel); } private void resizeResultTableColumns() { float[] columnWidthPercentage = {2, 38, 30, 30}; int tW = resultTable.getWidth(); TableColumnModel jTableColumnModel = resultTable.getColumnModel(); int cantCols = jTableColumnModel.getColumnCount(); for (int i = 0; i < cantCols; i++) { TableColumn column = jTableColumnModel.getColumn(i); int pWidth = Math.round(columnWidthPercentage[i] * tW); column.setPreferredWidth(pWidth); } } private void search(Analyzer analyzer, IndexReader reader) { long currentTimeMillis = System.currentTimeMillis(); String findTextStr = findText.getText(); int findTypeIndex = findType.getSelectedIndex(); int findWhereIndex = findWhere.getSelectedIndex(); String field = findWhereIndex == 0 ? "text" : "url_1"; try { QueryBuilder queryBuilder = new QueryBuilder(analyzer); Query query = findTypeIndex == 0 ? queryBuilder.createBooleanQuery(field, findTextStr, BooleanClause.Occur.MUST) // zawiera : queryBuilder.createPhraseQuery(field, findTextStr); // dokładnie if (query == null) { query = findTextStr.trim().isEmpty() ? new MatchAllDocsQuery() : new MatchNoDocsQuery(); } IndexSearcher searcher = new IndexSearcher(reader); MoreLikeThis mlt = new MoreLikeThis(reader); mlt.setAnalyzer(analyzer); mlt.setFieldNames(new String[]{"text"}); TopDocs topDocs = searcher.search(query, 5); ScoreDoc[] topHits = topDocs.scoreDocs; statusText.setText( String.format("Znaleziono %d wyników. (%d)", topDocs.totalHits, currentTimeMillis) ); Formatter formatter = new SimpleHTMLFormatter(); Highlighter highlighter = new Highlighter(formatter, new QueryScorer(query)); List<FindResult7> findResults = new ArrayList<>(5); for (ScoreDoc hit : topHits) { FindResult7 fr = new FindResult7(); Document doc = searcher.doc(hit.doc); fr.resultUrl = doc.get("url_0"); String content = doc.get(field); Fields termVectors = reader.getTermVectors(hit.doc); TokenStream tokenStream = TokenSources.getTokenStream(field, termVectors, content, analyzer, -1); TextFragment[] frag = highlighter.getBestTextFragments(tokenStream, content, false, 1); if (frag.length > 0) { fr.matchStr = frag[0].toString().trim(); } Query queryMlt = mlt.like(hit.doc); TopDocs similarDocs = searcher.search(queryMlt, 3); if (similarDocs.totalHits > 1) { ScoreDoc similarHit = Arrays.stream(similarDocs.scoreDocs) .filter(h -> h.doc != hit.doc) .findFirst() .orElse(null); Document similarDoc = searcher.doc(similarHit.doc); fr.similarUrl = similarDoc.get("url_0"); } findResults.add(fr); } findTableModel.setModelData(findResults); resizeResultTableColumns(); } catch (IOException e) { statusText.setText( String.format("Wystąpił błąd %s wyników. (%d)", e.toString(), currentTimeMillis) ); } catch (InvalidTokenOffsetsException e) { e.printStackTrace(); } } }
180254/edwi
src/main/java/pl/edwi/app/App7b.java
2,099
// dokładnie
line_comment
pl
package pl.edwi.app; import com.sun.java.swing.plaf.windows.WindowsLookAndFeel; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.Fields; import org.apache.lucene.index.IndexReader; import org.apache.lucene.queries.mlt.MoreLikeThis; import org.apache.lucene.search.*; import org.apache.lucene.search.highlight.*; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.QueryBuilder; import pl.edwi.tool.Try; import pl.edwi.ui.FindResult7; import pl.edwi.ui.FindTableMode7; import javax.swing.*; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @SuppressWarnings("Duplicates") public class App7b { private JPanel jPanel; private JTextField findText; private JComboBox<String> findType; private JComboBox<String> findWhere; private JButton findButton; private JTable resultTable; private JLabel statusText; private FindTableMode7 findTableModel; public App7b(Analyzer analyzer, IndexReader reader) { } public static void main(String[] args) throws IOException { try { UIManager.setLookAndFeel(WindowsLookAndFeel.class.getName()); } catch (ClassNotFoundException | InstantiationException | UnsupportedLookAndFeelException | IllegalAccessException ignored) { } Analyzer analyzer = new StandardAnalyzer(); Directory index = FSDirectory.open(Paths.get(App7a.LUCENE_DIR)); IndexReader reader = DirectoryReader.open(index); App7b app7b = new App7b(analyzer, reader); JFrame frame = new JFrame("Bot internetowy"); frame.setContentPane(app7b.jPanel); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); Component p = app7b.jPanel; while (p != null && !(p instanceof Window)) { p = p.getParent(); } if (p != null) { ((Window) p).addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent winEvt) { Try.ex(reader::close); Try.ex(index::close); Try.ex(analyzer::close); } }); } app7b.findType.addItem("zawiera"); app7b.findType.addItem("dokładne"); app7b.findWhere.addItem("w treści"); app7b.findWhere.addItem("w adresie"); app7b.jPanel.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { app7b.resizeResultTableColumns(); } }); app7b.findText.addActionListener((event) -> app7b.search(analyzer, reader)); app7b.findButton.addActionListener((event) -> app7b.search(analyzer, reader)); app7b.findTableModel = new FindTableMode7(); app7b.resultTable.setModel(app7b.findTableModel); } private void resizeResultTableColumns() { float[] columnWidthPercentage = {2, 38, 30, 30}; int tW = resultTable.getWidth(); TableColumnModel jTableColumnModel = resultTable.getColumnModel(); int cantCols = jTableColumnModel.getColumnCount(); for (int i = 0; i < cantCols; i++) { TableColumn column = jTableColumnModel.getColumn(i); int pWidth = Math.round(columnWidthPercentage[i] * tW); column.setPreferredWidth(pWidth); } } private void search(Analyzer analyzer, IndexReader reader) { long currentTimeMillis = System.currentTimeMillis(); String findTextStr = findText.getText(); int findTypeIndex = findType.getSelectedIndex(); int findWhereIndex = findWhere.getSelectedIndex(); String field = findWhereIndex == 0 ? "text" : "url_1"; try { QueryBuilder queryBuilder = new QueryBuilder(analyzer); Query query = findTypeIndex == 0 ? queryBuilder.createBooleanQuery(field, findTextStr, BooleanClause.Occur.MUST) // zawiera : queryBuilder.createPhraseQuery(field, findTextStr); // dokł<SUF> if (query == null) { query = findTextStr.trim().isEmpty() ? new MatchAllDocsQuery() : new MatchNoDocsQuery(); } IndexSearcher searcher = new IndexSearcher(reader); MoreLikeThis mlt = new MoreLikeThis(reader); mlt.setAnalyzer(analyzer); mlt.setFieldNames(new String[]{"text"}); TopDocs topDocs = searcher.search(query, 5); ScoreDoc[] topHits = topDocs.scoreDocs; statusText.setText( String.format("Znaleziono %d wyników. (%d)", topDocs.totalHits, currentTimeMillis) ); Formatter formatter = new SimpleHTMLFormatter(); Highlighter highlighter = new Highlighter(formatter, new QueryScorer(query)); List<FindResult7> findResults = new ArrayList<>(5); for (ScoreDoc hit : topHits) { FindResult7 fr = new FindResult7(); Document doc = searcher.doc(hit.doc); fr.resultUrl = doc.get("url_0"); String content = doc.get(field); Fields termVectors = reader.getTermVectors(hit.doc); TokenStream tokenStream = TokenSources.getTokenStream(field, termVectors, content, analyzer, -1); TextFragment[] frag = highlighter.getBestTextFragments(tokenStream, content, false, 1); if (frag.length > 0) { fr.matchStr = frag[0].toString().trim(); } Query queryMlt = mlt.like(hit.doc); TopDocs similarDocs = searcher.search(queryMlt, 3); if (similarDocs.totalHits > 1) { ScoreDoc similarHit = Arrays.stream(similarDocs.scoreDocs) .filter(h -> h.doc != hit.doc) .findFirst() .orElse(null); Document similarDoc = searcher.doc(similarHit.doc); fr.similarUrl = similarDoc.get("url_0"); } findResults.add(fr); } findTableModel.setModelData(findResults); resizeResultTableColumns(); } catch (IOException e) { statusText.setText( String.format("Wystąpił błąd %s wyników. (%d)", e.toString(), currentTimeMillis) ); } catch (InvalidTokenOffsetsException e) { e.printStackTrace(); } } }
160313_4
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package dao; import entities.Osoba; import java.util.List; /** * * @author ZTI */ public interface OsobaDAO { //Zwraca listę wszystkich działów List<Osoba> getAll(); //Zwraca osobę o podanym id Osoba get(int id); //Wstawia do bazy nową osobę void create(Osoba osoba); //Aktualizuje osobę void update(Osoba osoba); //Usuwa osobę void delete(Osoba osoba); //czyści tabelę void clearTable(); }
19Pietruszka20/bazydanych
hibernatejava/AiR_labA_DAO_2018/src/dao/OsobaDAO.java
244
//Wstawia do bazy nową osobę
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 dao; import entities.Osoba; import java.util.List; /** * * @author ZTI */ public interface OsobaDAO { //Zwraca listę wszystkich działów List<Osoba> getAll(); //Zwraca osobę o podanym id Osoba get(int id); //Wsta<SUF> void create(Osoba osoba); //Aktualizuje osobę void update(Osoba osoba); //Usuwa osobę void delete(Osoba osoba); //czyści tabelę void clearTable(); }
172890_2
package org.pwr.tirt.mod; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.pwr.tirt.utils.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class ConnectionProcessor { @Autowired StringUtils stringUtils; private StringBuilder content = new StringBuilder(); private Document doc = null; public String fetchData() { try { //wchodzimy na jsos po ciastka Connection.Response getCookies = Jsoup.connect("https://jsos.pwr.edu.pl/") .method(Connection.Method.GET) .execute(); //z tego co dostajemy pobieramy token i key Connection.Response loginForm = Jsoup.connect("https://jsos.pwr.edu.pl/index.php/site/loginAsStudent") .method(Connection.Method.GET) .cookies(getCookies.cookies()) .execute(); String uriWithToken = loginForm.url().toString(); System.err.println(uriWithToken); Document document = Jsoup.connect("http://oauth.pwr.edu.pl/oauth/authenticate") .data("cookieexists", "false") .data("oauth_symbol", "EIS") .data("oauth_locale", "pl") .data("oauth_token", stringUtils.getTokenFromUrl(uriWithToken)) .data("oauth_consumer_key", stringUtils.getConsumerKeyFromUrl(uriWithToken)) .data("username", "pwr194225") .data("password", "marley1992bob") .followRedirects(true) .cookies(loginForm.cookies()) .post(); // doc = // Jsoup.connect("https://jsos.pwr.edu.pl/index.php/student/zajecia").get(); Elements newsHeadlines = document.select("div"); for (Element el : newsHeadlines) { content.append(el.toString()); } } catch (Exception ex) { ex.printStackTrace(); } return content.toString(); } }
19mateusz92/TIRTproject
src/main/java/org/pwr/tirt/mod/ConnectionProcessor.java
636
//z tego co dostajemy pobieramy token i key
line_comment
pl
package org.pwr.tirt.mod; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.pwr.tirt.utils.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class ConnectionProcessor { @Autowired StringUtils stringUtils; private StringBuilder content = new StringBuilder(); private Document doc = null; public String fetchData() { try { //wchodzimy na jsos po ciastka Connection.Response getCookies = Jsoup.connect("https://jsos.pwr.edu.pl/") .method(Connection.Method.GET) .execute(); //z te<SUF> Connection.Response loginForm = Jsoup.connect("https://jsos.pwr.edu.pl/index.php/site/loginAsStudent") .method(Connection.Method.GET) .cookies(getCookies.cookies()) .execute(); String uriWithToken = loginForm.url().toString(); System.err.println(uriWithToken); Document document = Jsoup.connect("http://oauth.pwr.edu.pl/oauth/authenticate") .data("cookieexists", "false") .data("oauth_symbol", "EIS") .data("oauth_locale", "pl") .data("oauth_token", stringUtils.getTokenFromUrl(uriWithToken)) .data("oauth_consumer_key", stringUtils.getConsumerKeyFromUrl(uriWithToken)) .data("username", "pwr194225") .data("password", "marley1992bob") .followRedirects(true) .cookies(loginForm.cookies()) .post(); // doc = // Jsoup.connect("https://jsos.pwr.edu.pl/index.php/student/zajecia").get(); Elements newsHeadlines = document.select("div"); for (Element el : newsHeadlines) { content.append(el.toString()); } } catch (Exception ex) { ex.printStackTrace(); } return content.toString(); } }
117992_0
package medicalCentre; import lombok.AllArgsConstructor; import lombok.Data; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; @Data @AllArgsConstructor public class MedicalService { /* Stworzyć klasę service.MedicalService, a w niej publiczne metody: 0. Metoda dodająca dane 1. Metoda przyjmująca w argumencie String pesel i zwracająca typ List<Appointment>, która dla pacjenta o danym peselu zwróci jego wszystkie przyszłe wizyty. 2. Metoda przyjmująca w argumencie String identificator i zwracająca typ List<Appointment>, która dla lekarza o danym identyfikatorze zwróci jego wszystkie przyszłe wizyty. 3. Metoda przyjmująca w argumencie SpecialityType type i zwracająca List<Doctor>, która dla podanej w argumencie specjalności zwróci wszystkich lekarzy. 4. Metoda przyjmująca w argumentach Patient patient, Doctor doctor, LocalDateTime dateFrom, LocalDateTime dateTo zapisująca w bazie wizytę dla pacjenta do danego doktora na dany przedział godzinowy. Metoda ma zwrócić obiekt Appointment. 5. Metoda przyjmująca w argumencie String pesel i zwracająca typ Address, która dla pacjenta o danym peselu zwróci jego adres. */ public SessionFactory sessionFactory; //0 public void setDataInDb() { try (Session session = sessionFactory.openSession()) { Transaction transaction = session.beginTransaction(); Patient patient1 = new Patient(null, "Adam", "Smith", "97050535928", LocalDate.of(1997, 05, 05), null, null); Patient patient2 = new Patient(null, "Jordan", "Brake", "88020298321", LocalDate.of(1988, 02, 02), null, null); Patient patient3 = new Patient(null, "John", "Kowalski", "75030210928", LocalDate.of(1975, 03, 02), null, null); Address address1 = new Address(null, "LA", "45th", "10", null); Address address2 = new Address(null, "NYC", "15th", "20", null); Address address3 = new Address(null, "San Francisco", "25th", "30", null); patient1.setAddress(address1); patient2.setAddress(address2); patient3.setAddress(address3); address1.setPatient(patient1); address2.setPatient(patient2); address3.setPatient(patient3); Appointment appointment1 = new Appointment(null, LocalDateTime.now().plusDays(1), LocalDateTime.now().plusDays(2), patient1, null); Appointment appointment2 = new Appointment(null, LocalDateTime.now().plusDays(3), LocalDateTime.now().plusDays(7), patient2, null); Appointment appointment3 = new Appointment(null, LocalDateTime.now().plusDays(23), LocalDateTime.now(), patient3, null); Appointment appointment4 = new Appointment(null, LocalDateTime.now().plusDays(5), LocalDateTime.now().plusMonths(6), patient1, null); Appointment appointment5 = new Appointment(null, LocalDateTime.now().plusHours(8), LocalDateTime.now().plusYears(9), patient2, null); Appointment appointment6 = new Appointment(null, LocalDateTime.now(), LocalDateTime.now().plusHours(1), patient3, null); patient1.setAppointments(Arrays.asList(appointment1, appointment4)); patient2.setAppointments(Arrays.asList(appointment2, appointment5)); patient3.setAppointments(Arrays.asList(appointment3, appointment6)); Doctor doctor1 = new Doctor(null, "Anna", "Crane", "12345", Arrays.asList(appointment1, appointment4), null); Doctor doctor2 = new Doctor(null, "Maria", "Ways", "23456", Arrays.asList(appointment2, appointment5), null); Doctor doctor3 = new Doctor(null, "Ian", "Pickle", "34567", Arrays.asList(appointment3, appointment6), null); appointment1.setDoctor(doctor1); appointment2.setDoctor(doctor2); appointment3.setDoctor(doctor3); appointment4.setDoctor(doctor1); appointment5.setDoctor(doctor2); appointment6.setDoctor(doctor3); Speciality speciality1 = new Speciality(null, SpecialityType.INTERNISTA, Arrays.asList(doctor1, doctor2, doctor3)); Speciality speciality2 = new Speciality(null, SpecialityType.KARDIOLOG, Arrays.asList(doctor1, doctor2, doctor3)); Speciality speciality3 = new Speciality(null, SpecialityType.ORTOPEDA, Arrays.asList(doctor1, doctor2, doctor3)); doctor1.setSpecialities(Arrays.asList(speciality1, speciality2, speciality3)); doctor2.setSpecialities(Arrays.asList(speciality1, speciality2, speciality3)); doctor3.setSpecialities(Arrays.asList(speciality1, speciality2, speciality3)); session.save(patient1); session.save(patient2); session.save(patient3); session.save(address1); session.save(address2); session.save(address3); session.save(appointment1); session.save(appointment2); session.save(appointment3); session.save(appointment4); session.save(appointment5); session.save(appointment6); session.save(doctor1); session.save(doctor2); session.save(doctor3); session.save(speciality1); session.save(speciality2); session.save(speciality3); transaction.commit(); } catch (Exception e) { System.err.println(e.getMessage()); } } //1 public List<Appointment> getAllAppointmentsOfPatient(String pesel) { List<Appointment> appointmentsToReturn = new ArrayList<>(); try (Session session = sessionFactory.openSession()) { Transaction transaction = session.beginTransaction(); Patient patient = session.createQuery( "select p from Patient p join fetch p.appointments where p.pesel = :inputPesel", Patient.class) .setParameter("inputPesel", pesel) .uniqueResult(); transaction.commit(); if (patient != null) { for (Appointment appointment : patient.getAppointments()) { if (appointment.getDateFrom().isAfter(LocalDateTime.now())) { appointmentsToReturn.add(appointment); } } return appointmentsToReturn; } else { System.out.println("No patient with such pesel found."); return Collections.emptyList(); } } catch (Exception e) { System.err.println(e.getMessage()); } return appointmentsToReturn; } //2 public List<Appointment> getAllAppointmentsOfDoctor(String identifier) { List<Appointment> appointmentsToReturn = new ArrayList<>(); try (Session session = sessionFactory.openSession()) { Transaction transaction = session.beginTransaction(); Doctor doctor = (Doctor) session.createQuery("from Doctor d where d.identifier = :inputIdentifier") .setParameter("inputIdentifier", identifier) .getSingleResult(); transaction.commit(); if (doctor != null) { for (Appointment appointment : doctor.getAppointments()) { if (appointment.getDateFrom().isAfter(LocalDateTime.now())) { appointmentsToReturn.add(appointment); } } return appointmentsToReturn; } else { System.out.println("No doctor with such identifier found."); return Collections.emptyList(); } } catch (Exception e) { System.err.println(e.getMessage()); } return appointmentsToReturn; } //3 public List<Doctor> getAllDoctorsBeing(SpecialityType type) { List<Doctor> doctorsToReturn = new ArrayList<>(); try (Session session = sessionFactory.openSession()) { Transaction transaction = session.beginTransaction(); Speciality speciality = session.createQuery("from Speciality s where s.name = :inputSpecialty", Speciality.class) .setParameter("inputSpecialty", type) .getSingleResult(); List<Doctor> doctors = speciality.getDoctors(); transaction.commit(); if (doctors.size() > 0) { for (Doctor doctor : doctors) { doctorsToReturn.add(doctor); } return doctorsToReturn; } else { System.out.println("No doctor with such speciality found."); return Collections.emptyList(); } } catch (Exception e) { System.err.println(e.getMessage()); } return doctorsToReturn; } //4 public Appointment makeAnAppointment(Patient patient, Doctor doctor, LocalDateTime dadeFrom, LocalDateTime dateTo) { Appointment appointmentToReturn = new Appointment(); try (Session session = sessionFactory.openSession()) { Transaction transaction = session.beginTransaction(); Appointment appointmentToSave = new Appointment(null, dadeFrom, dateTo, patient, doctor); session.save(appointmentToSave); appointmentToReturn = appointmentToSave; } catch (Exception e) { System.err.println(e.getMessage()); } return appointmentToReturn; } //5 public Address getPatientsAddress(String pesel) { Address addressToReturn = new Address(); try (Session session = sessionFactory.openSession()) { Transaction transaction = session.beginTransaction(); Patient patient = (Patient) session.createQuery("from Patient p where p.pesel = :inputPesel") .setParameter("inputPesel", pesel) .getSingleResult(); transaction.commit(); if (patient != null) { addressToReturn = patient.getAddress(); } else { System.out.println("No patient with such pesel found."); return new Address(); } } catch (Exception e) { System.err.println(e.getMessage()); } return addressToReturn; } }
19pawel970415/Hibernate
src/main/java/medicalCentre/MedicalService.java
2,960
/* Stworzyć klasę service.MedicalService, a w niej publiczne metody: 0. Metoda dodająca dane 1. Metoda przyjmująca w argumencie String pesel i zwracająca typ List<Appointment>, która dla pacjenta o danym peselu zwróci jego wszystkie przyszłe wizyty. 2. Metoda przyjmująca w argumencie String identificator i zwracająca typ List<Appointment>, która dla lekarza o danym identyfikatorze zwróci jego wszystkie przyszłe wizyty. 3. Metoda przyjmująca w argumencie SpecialityType type i zwracająca List<Doctor>, która dla podanej w argumencie specjalności zwróci wszystkich lekarzy. 4. Metoda przyjmująca w argumentach Patient patient, Doctor doctor, LocalDateTime dateFrom, LocalDateTime dateTo zapisująca w bazie wizytę dla pacjenta do danego doktora na dany przedział godzinowy. Metoda ma zwrócić obiekt Appointment. 5. Metoda przyjmująca w argumencie String pesel i zwracająca typ Address, która dla pacjenta o danym peselu zwróci jego adres. */
block_comment
pl
package medicalCentre; import lombok.AllArgsConstructor; import lombok.Data; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; @Data @AllArgsConstructor public class MedicalService { /* Stwor<SUF>*/ public SessionFactory sessionFactory; //0 public void setDataInDb() { try (Session session = sessionFactory.openSession()) { Transaction transaction = session.beginTransaction(); Patient patient1 = new Patient(null, "Adam", "Smith", "97050535928", LocalDate.of(1997, 05, 05), null, null); Patient patient2 = new Patient(null, "Jordan", "Brake", "88020298321", LocalDate.of(1988, 02, 02), null, null); Patient patient3 = new Patient(null, "John", "Kowalski", "75030210928", LocalDate.of(1975, 03, 02), null, null); Address address1 = new Address(null, "LA", "45th", "10", null); Address address2 = new Address(null, "NYC", "15th", "20", null); Address address3 = new Address(null, "San Francisco", "25th", "30", null); patient1.setAddress(address1); patient2.setAddress(address2); patient3.setAddress(address3); address1.setPatient(patient1); address2.setPatient(patient2); address3.setPatient(patient3); Appointment appointment1 = new Appointment(null, LocalDateTime.now().plusDays(1), LocalDateTime.now().plusDays(2), patient1, null); Appointment appointment2 = new Appointment(null, LocalDateTime.now().plusDays(3), LocalDateTime.now().plusDays(7), patient2, null); Appointment appointment3 = new Appointment(null, LocalDateTime.now().plusDays(23), LocalDateTime.now(), patient3, null); Appointment appointment4 = new Appointment(null, LocalDateTime.now().plusDays(5), LocalDateTime.now().plusMonths(6), patient1, null); Appointment appointment5 = new Appointment(null, LocalDateTime.now().plusHours(8), LocalDateTime.now().plusYears(9), patient2, null); Appointment appointment6 = new Appointment(null, LocalDateTime.now(), LocalDateTime.now().plusHours(1), patient3, null); patient1.setAppointments(Arrays.asList(appointment1, appointment4)); patient2.setAppointments(Arrays.asList(appointment2, appointment5)); patient3.setAppointments(Arrays.asList(appointment3, appointment6)); Doctor doctor1 = new Doctor(null, "Anna", "Crane", "12345", Arrays.asList(appointment1, appointment4), null); Doctor doctor2 = new Doctor(null, "Maria", "Ways", "23456", Arrays.asList(appointment2, appointment5), null); Doctor doctor3 = new Doctor(null, "Ian", "Pickle", "34567", Arrays.asList(appointment3, appointment6), null); appointment1.setDoctor(doctor1); appointment2.setDoctor(doctor2); appointment3.setDoctor(doctor3); appointment4.setDoctor(doctor1); appointment5.setDoctor(doctor2); appointment6.setDoctor(doctor3); Speciality speciality1 = new Speciality(null, SpecialityType.INTERNISTA, Arrays.asList(doctor1, doctor2, doctor3)); Speciality speciality2 = new Speciality(null, SpecialityType.KARDIOLOG, Arrays.asList(doctor1, doctor2, doctor3)); Speciality speciality3 = new Speciality(null, SpecialityType.ORTOPEDA, Arrays.asList(doctor1, doctor2, doctor3)); doctor1.setSpecialities(Arrays.asList(speciality1, speciality2, speciality3)); doctor2.setSpecialities(Arrays.asList(speciality1, speciality2, speciality3)); doctor3.setSpecialities(Arrays.asList(speciality1, speciality2, speciality3)); session.save(patient1); session.save(patient2); session.save(patient3); session.save(address1); session.save(address2); session.save(address3); session.save(appointment1); session.save(appointment2); session.save(appointment3); session.save(appointment4); session.save(appointment5); session.save(appointment6); session.save(doctor1); session.save(doctor2); session.save(doctor3); session.save(speciality1); session.save(speciality2); session.save(speciality3); transaction.commit(); } catch (Exception e) { System.err.println(e.getMessage()); } } //1 public List<Appointment> getAllAppointmentsOfPatient(String pesel) { List<Appointment> appointmentsToReturn = new ArrayList<>(); try (Session session = sessionFactory.openSession()) { Transaction transaction = session.beginTransaction(); Patient patient = session.createQuery( "select p from Patient p join fetch p.appointments where p.pesel = :inputPesel", Patient.class) .setParameter("inputPesel", pesel) .uniqueResult(); transaction.commit(); if (patient != null) { for (Appointment appointment : patient.getAppointments()) { if (appointment.getDateFrom().isAfter(LocalDateTime.now())) { appointmentsToReturn.add(appointment); } } return appointmentsToReturn; } else { System.out.println("No patient with such pesel found."); return Collections.emptyList(); } } catch (Exception e) { System.err.println(e.getMessage()); } return appointmentsToReturn; } //2 public List<Appointment> getAllAppointmentsOfDoctor(String identifier) { List<Appointment> appointmentsToReturn = new ArrayList<>(); try (Session session = sessionFactory.openSession()) { Transaction transaction = session.beginTransaction(); Doctor doctor = (Doctor) session.createQuery("from Doctor d where d.identifier = :inputIdentifier") .setParameter("inputIdentifier", identifier) .getSingleResult(); transaction.commit(); if (doctor != null) { for (Appointment appointment : doctor.getAppointments()) { if (appointment.getDateFrom().isAfter(LocalDateTime.now())) { appointmentsToReturn.add(appointment); } } return appointmentsToReturn; } else { System.out.println("No doctor with such identifier found."); return Collections.emptyList(); } } catch (Exception e) { System.err.println(e.getMessage()); } return appointmentsToReturn; } //3 public List<Doctor> getAllDoctorsBeing(SpecialityType type) { List<Doctor> doctorsToReturn = new ArrayList<>(); try (Session session = sessionFactory.openSession()) { Transaction transaction = session.beginTransaction(); Speciality speciality = session.createQuery("from Speciality s where s.name = :inputSpecialty", Speciality.class) .setParameter("inputSpecialty", type) .getSingleResult(); List<Doctor> doctors = speciality.getDoctors(); transaction.commit(); if (doctors.size() > 0) { for (Doctor doctor : doctors) { doctorsToReturn.add(doctor); } return doctorsToReturn; } else { System.out.println("No doctor with such speciality found."); return Collections.emptyList(); } } catch (Exception e) { System.err.println(e.getMessage()); } return doctorsToReturn; } //4 public Appointment makeAnAppointment(Patient patient, Doctor doctor, LocalDateTime dadeFrom, LocalDateTime dateTo) { Appointment appointmentToReturn = new Appointment(); try (Session session = sessionFactory.openSession()) { Transaction transaction = session.beginTransaction(); Appointment appointmentToSave = new Appointment(null, dadeFrom, dateTo, patient, doctor); session.save(appointmentToSave); appointmentToReturn = appointmentToSave; } catch (Exception e) { System.err.println(e.getMessage()); } return appointmentToReturn; } //5 public Address getPatientsAddress(String pesel) { Address addressToReturn = new Address(); try (Session session = sessionFactory.openSession()) { Transaction transaction = session.beginTransaction(); Patient patient = (Patient) session.createQuery("from Patient p where p.pesel = :inputPesel") .setParameter("inputPesel", pesel) .getSingleResult(); transaction.commit(); if (patient != null) { addressToReturn = patient.getAddress(); } else { System.out.println("No patient with such pesel found."); return new Address(); } } catch (Exception e) { System.err.println(e.getMessage()); } return addressToReturn; } }
139017_7
package renderer; import maths.Matrix3x3; import maths.Vector3; import util.Console; import java.awt.*; /** * Ta klasa implementuje najbardziej podstawowy kształt w grafice 3D - trójkąt. * * @author Bartosz Węgrzyn */ public class Triangle { public final int nVerticies = 3; /** * Wartości wprowadzane do składowych wektora powinny wynosić od -1.0 do 1.0. * <br> * (0, 0) - środek ekranu <br> * (-1, -1) - lewy dolny róg <br> * (1, 1) - prawy górny róg <br> * (-1, 1) - lewy górny róg <br> * (1, -1) - prawy dolny róg <br> * * @author Bartosz Węgrzyn */ public Vector3[] verticies = new Vector3[nVerticies]; Renderer renderer; Camera camera; int[] xVerticies = new int[nVerticies]; int[] yVerticies = new int[nVerticies]; public Vector3[] tempVerticies = new Vector3[nVerticies]; /** * Kolor jest domyślnie biały * * @author Bartosz Węgrzyn */ public Color color = Color.WHITE; double avgDistance = 0; /** * Konstruktor * * @param verticies wierzchołki trójkąta * @param renderer obiekt Renderer * @param camera obiekt Camera * @author Bartosz Węgrzyn */ public Triangle(Vector3[] verticies, Renderer renderer, Camera camera) { for (int i = 0; i < nVerticies; i++) { this.verticies[i] = new Vector3(verticies[i]); this.verticies[i] = new Vector3(verticies[i]); this.tempVerticies[i] = new Vector3(verticies[i]); } this.renderer = renderer; this.camera = camera; updateVerticies(); } /** * Tę funkcję należy wywołać za każdym razem, gdy zmieniamy wartości wektorów * wierzchołków, * np. podczas transformacji. Jest ona wywoływana również za każdym razem, kiedy * zostaje * wywołana funkcja render. * * @author Bartosz Węgrzyn */ double zs[] = new double[3]; public void updateVerticies() { avgDistance = 0; for (int i = 0; i < nVerticies; i++) { tempVerticies[i].x = verticies[i].x; tempVerticies[i].y = verticies[i].y; tempVerticies[i].z = verticies[i].z; } if (renderer.perspective) { camera.position.multiply(-1f); translate(camera.position); camera.position.multiply(-1f); rotateYaw(camera.rotation.x, true, null); rotatePitch(camera.rotation.y, true, null); } for (int i = 0; i < nVerticies; i++) { avgDistance += verticies[i].z; zs[i]=verticies[i].z; double scalingFactor = (double) 1 / verticies[i].z; if (!renderer.perspective) scalingFactor = 1; xVerticies[i] = (int) (renderer.dimensions.x / 2 + (verticies[i].x * scalingFactor * renderer.dimensions.x) / 2); yVerticies[i] = (int) (renderer.dimensions.y / 2 -(verticies[i].y * scalingFactor * renderer.dimensions.x) / 2); // w y jest x zeby obraz nie byl "zgnieciony" tylko rowny we wszystkich osiach, inaczej okno musialoby byc kwadratowe } if (renderer.perspective) { for (int i = 0; i < nVerticies; i++) { verticies[i].x = tempVerticies[i].x; verticies[i].y = tempVerticies[i].y; verticies[i].z = tempVerticies[i].z; } } avgDistance /= nVerticies; } /** * Renderuje ten trójkąt * * @param graphics obiekt Graphics2D * @author Bartosz Węgrzyn */ public void render(Graphics2D graphics) { updateVerticies(); if (renderer.perspective) { for (int i = 0; i < 3; i++) { if (zs[i] < camera.near || zs[i] > camera.far) return; } graphics.setColor(color); graphics.drawPolygon(xVerticies, yVerticies, nVerticies); } else { graphics.setColor(color); graphics.drawPolygon(xVerticies, yVerticies, nVerticies); } } /** * Przesuwa każdy wierzchołek tego trójkąta o podany wektor * * @param translationVector wektor przesunięcia * @author Bartosz Węgrzyn */ public void translate(Vector3 translationVector) { for (int i = 0; i < nVerticies; i++) { verticies[i].add(translationVector); } } /** * Obraca trójkąt wokół osi x * * @param pitchAngle kąt obrotu * @param axis wokół własnej osi x - false * @param rotationAxis axis = true, to można wstawić tu null * @author Bartosz Węgrzyn */ public void rotatePitch(double pitchAngle, boolean axis, Vector3 rotationAxis) { Vector3 translationVector = rotationAxis; if (!axis) { translationVector.multiply(-1); translate(translationVector); } double[][] pitchRotation = new double[][] { { 1, 0, 0 }, { 0, (double) Math.cos(pitchAngle), (double) -Math.sin(pitchAngle) }, { 0, (double) Math.sin(pitchAngle), (double) Math.cos(pitchAngle) } }; Matrix3x3 pitchRotationMatrix = new Matrix3x3(pitchRotation); for (int i = 0; i < nVerticies; i++) { verticies[i] = verticies[i].multiply(pitchRotationMatrix); } if (!axis) { translationVector.multiply(-1); translate(translationVector); } } /** * Obraca trójkąt wokół osi y * * @param yawAngle kąt obrotu * @param axis wokół własnej osi y - false * @param rotationAxis axis = true, to można wstawić tu null * @author Bartosz Węgrzyn */ public void rotateYaw(double yawAngle, boolean axis, Vector3 rotationAxis) { Vector3 translationVector = rotationAxis; if (!axis) { translationVector.multiply(-1); translate(translationVector); } double[][] yawRotation = new double[][] { { (double) Math.cos(yawAngle), 0, (double) Math.sin(yawAngle) }, { 0, 1, 0 }, { (double) -Math.sin(yawAngle), 0, (double) Math.cos(yawAngle) } }; Matrix3x3 yawRotationMatrix = new Matrix3x3(yawRotation); for (int i = 0; i < nVerticies; i++) { verticies[i] = verticies[i].multiply(yawRotationMatrix); } if (!axis) { translationVector.multiply(-1); translate(translationVector); } } /** * Obraca trójkąt wokół osi z * * @param rollAngle kąt obrotu * @param axis wokół własnej osi z - false * @param rotationAxis axis = true, to można wstawić tu null * @author Bartosz Węgrzyn */ public void rotateRoll(double rollAngle, boolean axis, Vector3 rotationAxis) { Vector3 translationVector = rotationAxis; if (!axis) { translationVector.multiply(-1); translate(translationVector); } double[][] rollRotation = new double[][] { { (double) Math.cos(rollAngle), (double) -Math.sin(rollAngle), 0 }, { (double) Math.sin(rollAngle), (double) Math.cos(rollAngle), 0 }, { 0, 0, 1 } }; Matrix3x3 rollRotationMatrix = new Matrix3x3(rollRotation); for (int i = 0; i < nVerticies; i++) { verticies[i] = verticies[i].multiply(rollRotationMatrix); } if (!axis) { translationVector.multiply(-1); translate(translationVector); } } }
2-718281828/gra_wektorowa
src/renderer/Triangle.java
2,588
/** * Przesuwa każdy wierzchołek tego trójkąta o podany wektor * * @param translationVector wektor przesunięcia * @author Bartosz Węgrzyn */
block_comment
pl
package renderer; import maths.Matrix3x3; import maths.Vector3; import util.Console; import java.awt.*; /** * Ta klasa implementuje najbardziej podstawowy kształt w grafice 3D - trójkąt. * * @author Bartosz Węgrzyn */ public class Triangle { public final int nVerticies = 3; /** * Wartości wprowadzane do składowych wektora powinny wynosić od -1.0 do 1.0. * <br> * (0, 0) - środek ekranu <br> * (-1, -1) - lewy dolny róg <br> * (1, 1) - prawy górny róg <br> * (-1, 1) - lewy górny róg <br> * (1, -1) - prawy dolny róg <br> * * @author Bartosz Węgrzyn */ public Vector3[] verticies = new Vector3[nVerticies]; Renderer renderer; Camera camera; int[] xVerticies = new int[nVerticies]; int[] yVerticies = new int[nVerticies]; public Vector3[] tempVerticies = new Vector3[nVerticies]; /** * Kolor jest domyślnie biały * * @author Bartosz Węgrzyn */ public Color color = Color.WHITE; double avgDistance = 0; /** * Konstruktor * * @param verticies wierzchołki trójkąta * @param renderer obiekt Renderer * @param camera obiekt Camera * @author Bartosz Węgrzyn */ public Triangle(Vector3[] verticies, Renderer renderer, Camera camera) { for (int i = 0; i < nVerticies; i++) { this.verticies[i] = new Vector3(verticies[i]); this.verticies[i] = new Vector3(verticies[i]); this.tempVerticies[i] = new Vector3(verticies[i]); } this.renderer = renderer; this.camera = camera; updateVerticies(); } /** * Tę funkcję należy wywołać za każdym razem, gdy zmieniamy wartości wektorów * wierzchołków, * np. podczas transformacji. Jest ona wywoływana również za każdym razem, kiedy * zostaje * wywołana funkcja render. * * @author Bartosz Węgrzyn */ double zs[] = new double[3]; public void updateVerticies() { avgDistance = 0; for (int i = 0; i < nVerticies; i++) { tempVerticies[i].x = verticies[i].x; tempVerticies[i].y = verticies[i].y; tempVerticies[i].z = verticies[i].z; } if (renderer.perspective) { camera.position.multiply(-1f); translate(camera.position); camera.position.multiply(-1f); rotateYaw(camera.rotation.x, true, null); rotatePitch(camera.rotation.y, true, null); } for (int i = 0; i < nVerticies; i++) { avgDistance += verticies[i].z; zs[i]=verticies[i].z; double scalingFactor = (double) 1 / verticies[i].z; if (!renderer.perspective) scalingFactor = 1; xVerticies[i] = (int) (renderer.dimensions.x / 2 + (verticies[i].x * scalingFactor * renderer.dimensions.x) / 2); yVerticies[i] = (int) (renderer.dimensions.y / 2 -(verticies[i].y * scalingFactor * renderer.dimensions.x) / 2); // w y jest x zeby obraz nie byl "zgnieciony" tylko rowny we wszystkich osiach, inaczej okno musialoby byc kwadratowe } if (renderer.perspective) { for (int i = 0; i < nVerticies; i++) { verticies[i].x = tempVerticies[i].x; verticies[i].y = tempVerticies[i].y; verticies[i].z = tempVerticies[i].z; } } avgDistance /= nVerticies; } /** * Renderuje ten trójkąt * * @param graphics obiekt Graphics2D * @author Bartosz Węgrzyn */ public void render(Graphics2D graphics) { updateVerticies(); if (renderer.perspective) { for (int i = 0; i < 3; i++) { if (zs[i] < camera.near || zs[i] > camera.far) return; } graphics.setColor(color); graphics.drawPolygon(xVerticies, yVerticies, nVerticies); } else { graphics.setColor(color); graphics.drawPolygon(xVerticies, yVerticies, nVerticies); } } /** * Przes<SUF>*/ public void translate(Vector3 translationVector) { for (int i = 0; i < nVerticies; i++) { verticies[i].add(translationVector); } } /** * Obraca trójkąt wokół osi x * * @param pitchAngle kąt obrotu * @param axis wokół własnej osi x - false * @param rotationAxis axis = true, to można wstawić tu null * @author Bartosz Węgrzyn */ public void rotatePitch(double pitchAngle, boolean axis, Vector3 rotationAxis) { Vector3 translationVector = rotationAxis; if (!axis) { translationVector.multiply(-1); translate(translationVector); } double[][] pitchRotation = new double[][] { { 1, 0, 0 }, { 0, (double) Math.cos(pitchAngle), (double) -Math.sin(pitchAngle) }, { 0, (double) Math.sin(pitchAngle), (double) Math.cos(pitchAngle) } }; Matrix3x3 pitchRotationMatrix = new Matrix3x3(pitchRotation); for (int i = 0; i < nVerticies; i++) { verticies[i] = verticies[i].multiply(pitchRotationMatrix); } if (!axis) { translationVector.multiply(-1); translate(translationVector); } } /** * Obraca trójkąt wokół osi y * * @param yawAngle kąt obrotu * @param axis wokół własnej osi y - false * @param rotationAxis axis = true, to można wstawić tu null * @author Bartosz Węgrzyn */ public void rotateYaw(double yawAngle, boolean axis, Vector3 rotationAxis) { Vector3 translationVector = rotationAxis; if (!axis) { translationVector.multiply(-1); translate(translationVector); } double[][] yawRotation = new double[][] { { (double) Math.cos(yawAngle), 0, (double) Math.sin(yawAngle) }, { 0, 1, 0 }, { (double) -Math.sin(yawAngle), 0, (double) Math.cos(yawAngle) } }; Matrix3x3 yawRotationMatrix = new Matrix3x3(yawRotation); for (int i = 0; i < nVerticies; i++) { verticies[i] = verticies[i].multiply(yawRotationMatrix); } if (!axis) { translationVector.multiply(-1); translate(translationVector); } } /** * Obraca trójkąt wokół osi z * * @param rollAngle kąt obrotu * @param axis wokół własnej osi z - false * @param rotationAxis axis = true, to można wstawić tu null * @author Bartosz Węgrzyn */ public void rotateRoll(double rollAngle, boolean axis, Vector3 rotationAxis) { Vector3 translationVector = rotationAxis; if (!axis) { translationVector.multiply(-1); translate(translationVector); } double[][] rollRotation = new double[][] { { (double) Math.cos(rollAngle), (double) -Math.sin(rollAngle), 0 }, { (double) Math.sin(rollAngle), (double) Math.cos(rollAngle), 0 }, { 0, 0, 1 } }; Matrix3x3 rollRotationMatrix = new Matrix3x3(rollRotation); for (int i = 0; i < nVerticies; i++) { verticies[i] = verticies[i].multiply(rollRotationMatrix); } if (!axis) { translationVector.multiply(-1); translate(translationVector); } } }
42098_0
package testandexceptions; /** klasa testujaca FileOutputAdapter. * @author Mateusz Ratajczyk */ public class TestFileOutputAdapter { // FileNotFoundException // // Blad ten wystapi gdy podczas tworzenia nowego pliku: // out = new BufferedWriter(new OutputStreamWriter( // new FileOutputStream(config.getLocOutput()))); // // - nie bedzie miejsca na dysku // - nie bedzie polaczenia z dyskiem // Test sprawdzenia czy zdarzenia zapisaly sie // w formacie JSON zakonczony powodzeniem. }
201idzb/project
AL/src/testandexceptions/TestFileOutputAdapter.java
170
/** klasa testujaca FileOutputAdapter. * @author Mateusz Ratajczyk */
block_comment
pl
package testandexceptions; /** klasa<SUF>*/ public class TestFileOutputAdapter { // FileNotFoundException // // Blad ten wystapi gdy podczas tworzenia nowego pliku: // out = new BufferedWriter(new OutputStreamWriter( // new FileOutputStream(config.getLocOutput()))); // // - nie bedzie miejsca na dysku // - nie bedzie polaczenia z dyskiem // Test sprawdzenia czy zdarzenia zapisaly sie // w formacie JSON zakonczony powodzeniem. }
91021_16
/** * Interfejs sterowania i monitoringu sluzy. * */ public interface AirlockInterface { /** * Typ wyliczeniowy Event zawiera zdarzenia, do ktorych moze dojsc w sluzie. * */ enum Event { /** * Wewnetrzne drzwi sluzy zostaly zamkniete */ INTERNAL_AIRTIGHT_DOORS_CLOSED, /** * Wewnetrzne drzwi sluzy zostaly otwarte */ INTERNAL_AIRTIGHT_DOORS_OPENED, /** * Zewnetrzne drzwi sluzy zostaly zamkniete */ EXTERNAL_AIRTIGHT_DOORS_CLOSED, /** * Zewnetrzne drzwi sluzy zostaly otwarte */ EXTERNAL_AIRTIGHT_DOORS_OPENED, /** * Ladunek w sluzie */ CARGO_INSIDE, /** * Sluza jest pusta */ AIRLOCK_EMPTY, /** * Nic dobrego... */ DISASTER } /** * Interfejs umozliwiajacy przekazanie informacji o zdarzeniu w sluzie. */ interface EventsListenerInterface { void newAirlockEvent(Event event); } /** * Zlecenie otwarcia wewnetrznych drzwi sluzy. */ void openInternalAirtightDoors(); /** * Zlecenie zamkniecia wewnetrznych drzwi sluzy. */ void closeInternalAirtightDoors(); /** * Zlecenie otwarcia zewnetrznych drzwi sluzy */ void openExternalAirtightDoors(); /** * Zlecenie zamkniecia zewnetrznych drzwi sluzy */ void closeExternalAirtightDoors(); /** * Ladunek umieszczany jest w sluzie. Aby operacja mogla byc zrealizowana jedne * z drzwi musza byc otwarte i rozmiar sluzy musi byc nie mniejszy niz rozmiar * ladunku. Zlecenie umieszczenia w zamknietej lub zbyt malej sluzie ladunku * powoduje zniszczenie i ladunku i sluzy. * * @param cargo * ladunek umieszczany w sluzie */ void insertCargo(CargoInterface cargo); /** * Ladunek usuwany jest ze sluzy. Jedne z drzwi musza byc otwarte. Kierunek * ruchu zalezy od tego, ktore drzwi sa otwarte. Zlecenie operacji przy * zamknietych drzwiach prowadzi do zniszczenia ladunku i sluzy. */ void ejectCargo(); /** * Metoda zwraca rozmiar sluzy. * @return rozmiar sluzy */ int getSize(); /** * Metoda do ustawienia obiektu, ktory bedzie powiadamiany o zmianach w stanie * sluzy. * * @param eventsListener * obiekt informowany o zmianach w stanie sluzy. */ void setEventsListener(EventsListenerInterface eventsListener); }
204Constie/baseonmars
src/AirlockInterface.java
974
/** * Metoda zwraca rozmiar sluzy. * @return rozmiar sluzy */
block_comment
pl
/** * Interfejs sterowania i monitoringu sluzy. * */ public interface AirlockInterface { /** * Typ wyliczeniowy Event zawiera zdarzenia, do ktorych moze dojsc w sluzie. * */ enum Event { /** * Wewnetrzne drzwi sluzy zostaly zamkniete */ INTERNAL_AIRTIGHT_DOORS_CLOSED, /** * Wewnetrzne drzwi sluzy zostaly otwarte */ INTERNAL_AIRTIGHT_DOORS_OPENED, /** * Zewnetrzne drzwi sluzy zostaly zamkniete */ EXTERNAL_AIRTIGHT_DOORS_CLOSED, /** * Zewnetrzne drzwi sluzy zostaly otwarte */ EXTERNAL_AIRTIGHT_DOORS_OPENED, /** * Ladunek w sluzie */ CARGO_INSIDE, /** * Sluza jest pusta */ AIRLOCK_EMPTY, /** * Nic dobrego... */ DISASTER } /** * Interfejs umozliwiajacy przekazanie informacji o zdarzeniu w sluzie. */ interface EventsListenerInterface { void newAirlockEvent(Event event); } /** * Zlecenie otwarcia wewnetrznych drzwi sluzy. */ void openInternalAirtightDoors(); /** * Zlecenie zamkniecia wewnetrznych drzwi sluzy. */ void closeInternalAirtightDoors(); /** * Zlecenie otwarcia zewnetrznych drzwi sluzy */ void openExternalAirtightDoors(); /** * Zlecenie zamkniecia zewnetrznych drzwi sluzy */ void closeExternalAirtightDoors(); /** * Ladunek umieszczany jest w sluzie. Aby operacja mogla byc zrealizowana jedne * z drzwi musza byc otwarte i rozmiar sluzy musi byc nie mniejszy niz rozmiar * ladunku. Zlecenie umieszczenia w zamknietej lub zbyt malej sluzie ladunku * powoduje zniszczenie i ladunku i sluzy. * * @param cargo * ladunek umieszczany w sluzie */ void insertCargo(CargoInterface cargo); /** * Ladunek usuwany jest ze sluzy. Jedne z drzwi musza byc otwarte. Kierunek * ruchu zalezy od tego, ktore drzwi sa otwarte. Zlecenie operacji przy * zamknietych drzwiach prowadzi do zniszczenia ladunku i sluzy. */ void ejectCargo(); /** * Metod<SUF>*/ int getSize(); /** * Metoda do ustawienia obiektu, ktory bedzie powiadamiany o zmianach w stanie * sluzy. * * @param eventsListener * obiekt informowany o zmianach w stanie sluzy. */ void setEventsListener(EventsListenerInterface eventsListener); }
94628_0
import java.awt.geom.Point2D; public interface ResultConsumerInterface { /** * Metoda pozwala na przekazanie wyniku obliczen. Wynik position to wynik pracy * metody convert, gdy pierwszym z obrazow byl obraz o numerze frameNumber. * Wyniki musza byc dostarczane jednokrotnie i wylacznie z rosnacymi (kolejnymi) * wartosciami dla frameNumber. * * @param frameNumber * numer identyfikacyjny obrazu * @param position * wynik pracy metody convert */ public void accept(int frameNumber, Point2D.Double position); }
204Constie/prirdsys
src/ResultConsumerInterface.java
188
/** * Metoda pozwala na przekazanie wyniku obliczen. Wynik position to wynik pracy * metody convert, gdy pierwszym z obrazow byl obraz o numerze frameNumber. * Wyniki musza byc dostarczane jednokrotnie i wylacznie z rosnacymi (kolejnymi) * wartosciami dla frameNumber. * * @param frameNumber * numer identyfikacyjny obrazu * @param position * wynik pracy metody convert */
block_comment
pl
import java.awt.geom.Point2D; public interface ResultConsumerInterface { /** * Metod<SUF>*/ public void accept(int frameNumber, Point2D.Double position); }
169469_7
package com.spb.StrangersPlayBackend; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.spb.StrangersPlayBackend.dto.AccountDto; import com.spb.StrangersPlayBackend.dto.AdvertisementDto; import com.spb.StrangersPlayBackend.model.Category; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import springfox.documentation.spring.web.json.Json; import springfox.documentation.spring.web.json.JsonSerializer; import java.time.Instant; @SpringBootApplication public class StrangersPlayBackendApplication { public static void main(String[] args) { // AdvertisementDto accountDto = new AdvertisementDto(); // accountDto.setCategory(Category.PILKA_NOZNA); // accountDto.setLevel(1); // accountDto.setPrice(10.0); // accountDto.setCreationTime(Instant.now()); // accountDto.setUsername("janusz"); // accountDto.setEventTime("2019-11-11T15:52:50.065Z"); // accountDto.setTitle("granie w piłkę"); // accountDto.setDescription("granie w piłke za 3 DS PŁ"); // accountDto.setEventLocation("3 ds PŁ"); // ObjectMapper mapper = new ObjectMapper(); // try { // System.out.println(mapper.writeValueAsString(accountDto)); // } catch (JsonProcessingException e) { // e.printStackTrace(); // } SpringApplication.run(StrangersPlayBackendApplication.class, args); } }
209278/StrangersPlayBackend
src/main/java/com/spb/StrangersPlayBackend/StrangersPlayBackendApplication.java
502
// accountDto.setTitle("granie w piłkę");
line_comment
pl
package com.spb.StrangersPlayBackend; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.spb.StrangersPlayBackend.dto.AccountDto; import com.spb.StrangersPlayBackend.dto.AdvertisementDto; import com.spb.StrangersPlayBackend.model.Category; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import springfox.documentation.spring.web.json.Json; import springfox.documentation.spring.web.json.JsonSerializer; import java.time.Instant; @SpringBootApplication public class StrangersPlayBackendApplication { public static void main(String[] args) { // AdvertisementDto accountDto = new AdvertisementDto(); // accountDto.setCategory(Category.PILKA_NOZNA); // accountDto.setLevel(1); // accountDto.setPrice(10.0); // accountDto.setCreationTime(Instant.now()); // accountDto.setUsername("janusz"); // accountDto.setEventTime("2019-11-11T15:52:50.065Z"); // acco<SUF> // accountDto.setDescription("granie w piłke za 3 DS PŁ"); // accountDto.setEventLocation("3 ds PŁ"); // ObjectMapper mapper = new ObjectMapper(); // try { // System.out.println(mapper.writeValueAsString(accountDto)); // } catch (JsonProcessingException e) { // e.printStackTrace(); // } SpringApplication.run(StrangersPlayBackendApplication.class, args); } }
92321_1
import java.awt.*; import java.util.LinkedHashMap; import java.util.Map; import javax.swing.JPanel; public class WykresKolowy extends JPanel { WykresKolowy(){ setPreferredSize(new Dimension(100, 100)); } private Map<Color, Integer> dictionary = new LinkedHashMap<>(); public void dodajKol(Color color, int value) { dictionary.put(color, value); repaint(); } public void usunKol(Color color){ dictionary.remove(color); } @Override public void paintComponent(Graphics g) { // szukam najdłuższego int max = Integer.MIN_VALUE; for (Integer value : dictionary.values()) { max = Math.max(max, value); } // malowanie int width = (getWidth() / dictionary.size()) - 2; int x = 1; for (Color color : dictionary.keySet()) { int value = dictionary.get(color); int height = (int) ((getHeight()-5) * ((double)value / max)); g.setColor(color); g.fillRect(x, getHeight() - height, width, height); g.setColor(Color.black); g.drawRect(x, getHeight() - height, width, height); x += (width + 2); } } }
213N10/jezykiProgramowaniaIte
lab4/src/WykresKolowy.java
373
// malowanie
line_comment
pl
import java.awt.*; import java.util.LinkedHashMap; import java.util.Map; import javax.swing.JPanel; public class WykresKolowy extends JPanel { WykresKolowy(){ setPreferredSize(new Dimension(100, 100)); } private Map<Color, Integer> dictionary = new LinkedHashMap<>(); public void dodajKol(Color color, int value) { dictionary.put(color, value); repaint(); } public void usunKol(Color color){ dictionary.remove(color); } @Override public void paintComponent(Graphics g) { // szukam najdłuższego int max = Integer.MIN_VALUE; for (Integer value : dictionary.values()) { max = Math.max(max, value); } // malo<SUF> int width = (getWidth() / dictionary.size()) - 2; int x = 1; for (Color color : dictionary.keySet()) { int value = dictionary.get(color); int height = (int) ((getHeight()-5) * ((double)value / max)); g.setColor(color); g.fillRect(x, getHeight() - height, width, height); g.setColor(Color.black); g.drawRect(x, getHeight() - height, width, height); x += (width + 2); } } }
51287_3
package pl.zzpj.repository.core.service; import lombok.AllArgsConstructor; import lombok.extern.java.Log; import org.springframework.stereotype.Service; import pl.zzpj.repository.core.domain.exception.rent.*; import pl.zzpj.repository.core.domain.exception.user.UserServiceNotFoundException; import pl.zzpj.repository.core.domain.model.rentModel.Rent; import pl.zzpj.repository.core.domain.model.rentModel.RentStatus; import pl.zzpj.repository.core.domain.model.rentModel.vehicles.Vehicle; import pl.zzpj.repository.core.domain.model.userModel.User; import pl.zzpj.repository.ports.command.rent.RentCommandPort; import pl.zzpj.repository.ports.command.rent.RentCommandService; import pl.zzpj.repository.ports.query.rent.RentQueryPort; import pl.zzpj.repository.ports.query.rent.RentQueryService; import pl.zzpj.repository.ports.query.rent.RentVehiclesQueryPort; import pl.zzpj.repository.ports.query.user.UserQueryRepositoryPort; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.time.Duration; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.UUID; @Service @AllArgsConstructor @Log public class RentServiceImpl implements RentCommandService, RentQueryService { private RentCommandPort commandPort; private RentQueryPort queryPort; private UserQueryRepositoryPort userQueryPort; private RentVehiclesQueryPort vehicleQueryPort; @Override public Rent findRent(UUID rentId) throws RentNotFoundException { return queryPort.getRent(rentId); } @Override public List<Rent> findRentsByUser(UUID userId) { return queryPort.getRentsByUserId(userId); } @Override public List<Rent> findAllRentsByVehicle(UUID vehicleId) { return queryPort.getRentsByVehicleId(vehicleId); } @Override public List<Rent> findFutureRentsByVehicle(UUID vehicleId) { return queryPort.getFutureRentsByVehicleId(vehicleId); } @Override public List<Rent> findRentsByStatus(RentStatus status) { return queryPort.getRentsByStatus(status); } @Override public List<Rent> findRentsToIssue(LocalDateTime endTime) { return queryPort.getRentsByStatusAndDeclaredDatesBetween( RentStatus.CREATED, LocalDateTime.now(), endTime); } @Override public List<Rent> findRentsToReturn(LocalDateTime endTime) { return queryPort.getRentsByStatusAndDeclaredDatesBetween( RentStatus.ISSUED, LocalDateTime.now(), endTime); } @Override public List<Rent> findAllRents() { return queryPort.getAllRents(); } @Override public boolean isVehicleAvailable(UUID vehicleId, LocalDateTime start, LocalDateTime end) { List<Rent> vehicleRents = queryPort.getRentsByVehicleIdAndDatesBetween( vehicleId, start, end); return vehicleRents.isEmpty(); } @Override public BigDecimal calculatePrice(UUID vehicleId, UUID userId, LocalDateTime start, LocalDateTime end) throws UserServiceNotFoundException { User user = userQueryPort.getUserById(userId).orElseThrow( () -> new UserServiceNotFoundException("Given user not found")); Vehicle vehicle = vehicleQueryPort.getById(vehicleId); return calculatePrice(user, vehicle, start, end); } private BigDecimal calculatePrice(User user, Vehicle vehicle, LocalDateTime start, LocalDateTime end) { Duration period = Duration.between(start, end); long baseRentCost = period.toHours() * vehicle.getHourlyRate(); BigDecimal cost = new BigDecimal(baseRentCost); return cost.multiply(BigDecimal.valueOf(100 - (user.getScore() / 10000d))) .divide(BigDecimal.valueOf(100)) .setScale(2, RoundingMode.HALF_UP); } @Override public Rent createRent(UUID userId, UUID vehicleId, LocalDateTime startDate, LocalDateTime endDate) throws RentInvalidDatePeriodException, UserServiceNotFoundException { User user = userQueryPort.getUserById(userId) .orElseThrow(() -> new UserServiceNotFoundException("Given user not found")); Vehicle vehicle = vehicleQueryPort.getById(vehicleId); LocalDateTime now = LocalDateTime.now(); if(startDate.isBefore(now) || endDate.isBefore(startDate)) { throw new RentInvalidDatePeriodException("Invalid date period given"); } Rent rent = Rent.createBuilder() .user(user) .vehicle(vehicle) .price(calculatePrice(user, vehicle, startDate, endDate)) .startDate(startDate) .endDate(endDate) .createBuild(); return commandPort.upsert(rent); } @Override public Rent cancelRent(UUID id) throws RentNotFoundException, RentNotCancellableException { Rent rent = queryPort.getRent(id); if(!this.isCancellable(rent)) { throw new RentNotCancellableException("Rent is not cancellable"); } rent.setStatus(RentStatus.CANCELLED); updateUserScore(rent); return commandPort.upsert(rent); } public boolean isCancellable(Rent rent) { LocalDateTime now = LocalDateTime.now(); if(rent.getCreatedAt().plus(5, ChronoUnit.MINUTES) .isAfter(now)) { return true; } return rent.getDeclaredStartDate().plus(7, ChronoUnit.DAYS) .isAfter(now); } @Override public Rent issueVehicle(UUID id) throws RentNotFoundException, RentCannotIssueVehicleException { Rent rent = queryPort.getRent(id); LocalDateTime now = LocalDateTime.now(); // you can rent 30 mins before declared time if(rent.getDeclaredStartDate() .plus(30, ChronoUnit.MINUTES) .isBefore(now)) { throw new RentCannotIssueVehicleException("Cannot issue right now"); } rent.setStatus(RentStatus.ISSUED); rent.setActualStartDate(now); return commandPort.upsert(rent); } @Override public Rent returnVehicle(UUID id) throws RentNotFoundException, RentVehicleNotIssuedException { Rent rent = queryPort.getRent(id); if(!rent.getStatus().equals(RentStatus.ISSUED)) { throw new RentVehicleNotIssuedException("Vehicle not issued"); } rent.setStatus(RentStatus.RETURNED_GOOD); rent.setActualEndDate(LocalDateTime.now()); updateUserScore(rent); return commandPort.upsert(rent); } @Override public Rent returnDamagedVehicle(UUID id) throws RentNotFoundException, RentVehicleNotIssuedException { Rent rent = queryPort.getRent(id); if(!rent.getStatus().equals(RentStatus.ISSUED)) { throw new RentVehicleNotIssuedException("Vehicle not issued"); } rent.setStatus(RentStatus.RETURNED_DAMAGED); rent.setActualEndDate(LocalDateTime.now()); updateUserScore(rent); return commandPort.upsert(rent); } @Override public Rent returnMissingVehicle(UUID id) throws RentNotFoundException, RentVehicleNotIssuedException { Rent rent = queryPort.getRent(id); if(!rent.getStatus().equals(RentStatus.ISSUED)) { throw new RentVehicleNotIssuedException("Vehicle not issued"); } rent.setStatus(RentStatus.NOT_RETURNED); rent.setActualEndDate(LocalDateTime.now()); updateUserScore(rent); rent.getVehicle().setAvailable(false); return commandPort.upsert(rent); } @Override public void updateRentsNotIssued() { List<Rent> rentsToIssue = queryPort.getRentsByStatus(RentStatus.CREATED); LocalDateTime now = LocalDateTime.now(); rentsToIssue.forEach(rent -> { if(rent.getDeclaredStartDate().isBefore(now)) { rent.setStatus(RentStatus.NOT_ISSUED); updateUserScore(rent); commandPort.upsert(rent); } }); } // modyfikator do ceny z powodu wyniku konta to pomiędzy -30% i +10% // dlatego punkty mogą mieć wartości od 3000 do -1000 // w najlepszym wypadku klient może dostać 1000 punktów za jedno wypożyczenie private void updateUserScore(Rent rent) { double rentPoints = 0; if(rent.getActualStartDate() != null) { Duration deltaStart = Duration.between(rent.getDeclaredStartDate(), rent.getActualStartDate()); if(deltaStart.isNegative()) { // odbiór przed czasem jest możliwy, ale niepożądany rentPoints -= 50d; } else if(deltaStart.toMinutes() < 60){ // im później klient odbierze samochód, tym mniej punktów dostaje rentPoints += 200d * (60 - deltaStart.toMinutes()); } } log.info(Double.toString(rentPoints)); if(rent.getActualEndDate() != null) { log.info(rent.getDeclaredEndDate().toString()); log.info(rent.getActualEndDate().toString()); Duration deltaEnd = Duration.between(rent.getActualEndDate(), rent.getDeclaredEndDate()); if (deltaEnd.isNegative()) { // oddane przed zadeklarowanym czasem (klient płaci za zarezerwowany czas) rentPoints += 300d; } else if (deltaEnd.toMinutes() < 60) { // klient traci 0,1 pkt% zniżki za każdą minutę opóźnienia rentPoints -= 10d * (deltaEnd.toMinutes()); } } switch(rent.getStatus()) { case NOT_ISSUED -> rentPoints -= 100d; case CANCELLED -> rentPoints -= 50d; case RETURNED_GOOD -> rentPoints += 500d; case RETURNED_DAMAGED -> rentPoints -= 200d; case NOT_RETURNED -> rentPoints -= 3000d; // zniweluj każdą zniżkę } // clamp rent.getUser().setScore(Math.max(-1000, Math.min(3000, rentPoints))); } }
229872/ZZPJ
ApplicationCore/ApplicationServices/src/main/java/pl/zzpj/repository/core/service/RentServiceImpl.java
3,116
// w najlepszym wypadku klient może dostać 1000 punktów za jedno wypożyczenie
line_comment
pl
package pl.zzpj.repository.core.service; import lombok.AllArgsConstructor; import lombok.extern.java.Log; import org.springframework.stereotype.Service; import pl.zzpj.repository.core.domain.exception.rent.*; import pl.zzpj.repository.core.domain.exception.user.UserServiceNotFoundException; import pl.zzpj.repository.core.domain.model.rentModel.Rent; import pl.zzpj.repository.core.domain.model.rentModel.RentStatus; import pl.zzpj.repository.core.domain.model.rentModel.vehicles.Vehicle; import pl.zzpj.repository.core.domain.model.userModel.User; import pl.zzpj.repository.ports.command.rent.RentCommandPort; import pl.zzpj.repository.ports.command.rent.RentCommandService; import pl.zzpj.repository.ports.query.rent.RentQueryPort; import pl.zzpj.repository.ports.query.rent.RentQueryService; import pl.zzpj.repository.ports.query.rent.RentVehiclesQueryPort; import pl.zzpj.repository.ports.query.user.UserQueryRepositoryPort; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.time.Duration; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.UUID; @Service @AllArgsConstructor @Log public class RentServiceImpl implements RentCommandService, RentQueryService { private RentCommandPort commandPort; private RentQueryPort queryPort; private UserQueryRepositoryPort userQueryPort; private RentVehiclesQueryPort vehicleQueryPort; @Override public Rent findRent(UUID rentId) throws RentNotFoundException { return queryPort.getRent(rentId); } @Override public List<Rent> findRentsByUser(UUID userId) { return queryPort.getRentsByUserId(userId); } @Override public List<Rent> findAllRentsByVehicle(UUID vehicleId) { return queryPort.getRentsByVehicleId(vehicleId); } @Override public List<Rent> findFutureRentsByVehicle(UUID vehicleId) { return queryPort.getFutureRentsByVehicleId(vehicleId); } @Override public List<Rent> findRentsByStatus(RentStatus status) { return queryPort.getRentsByStatus(status); } @Override public List<Rent> findRentsToIssue(LocalDateTime endTime) { return queryPort.getRentsByStatusAndDeclaredDatesBetween( RentStatus.CREATED, LocalDateTime.now(), endTime); } @Override public List<Rent> findRentsToReturn(LocalDateTime endTime) { return queryPort.getRentsByStatusAndDeclaredDatesBetween( RentStatus.ISSUED, LocalDateTime.now(), endTime); } @Override public List<Rent> findAllRents() { return queryPort.getAllRents(); } @Override public boolean isVehicleAvailable(UUID vehicleId, LocalDateTime start, LocalDateTime end) { List<Rent> vehicleRents = queryPort.getRentsByVehicleIdAndDatesBetween( vehicleId, start, end); return vehicleRents.isEmpty(); } @Override public BigDecimal calculatePrice(UUID vehicleId, UUID userId, LocalDateTime start, LocalDateTime end) throws UserServiceNotFoundException { User user = userQueryPort.getUserById(userId).orElseThrow( () -> new UserServiceNotFoundException("Given user not found")); Vehicle vehicle = vehicleQueryPort.getById(vehicleId); return calculatePrice(user, vehicle, start, end); } private BigDecimal calculatePrice(User user, Vehicle vehicle, LocalDateTime start, LocalDateTime end) { Duration period = Duration.between(start, end); long baseRentCost = period.toHours() * vehicle.getHourlyRate(); BigDecimal cost = new BigDecimal(baseRentCost); return cost.multiply(BigDecimal.valueOf(100 - (user.getScore() / 10000d))) .divide(BigDecimal.valueOf(100)) .setScale(2, RoundingMode.HALF_UP); } @Override public Rent createRent(UUID userId, UUID vehicleId, LocalDateTime startDate, LocalDateTime endDate) throws RentInvalidDatePeriodException, UserServiceNotFoundException { User user = userQueryPort.getUserById(userId) .orElseThrow(() -> new UserServiceNotFoundException("Given user not found")); Vehicle vehicle = vehicleQueryPort.getById(vehicleId); LocalDateTime now = LocalDateTime.now(); if(startDate.isBefore(now) || endDate.isBefore(startDate)) { throw new RentInvalidDatePeriodException("Invalid date period given"); } Rent rent = Rent.createBuilder() .user(user) .vehicle(vehicle) .price(calculatePrice(user, vehicle, startDate, endDate)) .startDate(startDate) .endDate(endDate) .createBuild(); return commandPort.upsert(rent); } @Override public Rent cancelRent(UUID id) throws RentNotFoundException, RentNotCancellableException { Rent rent = queryPort.getRent(id); if(!this.isCancellable(rent)) { throw new RentNotCancellableException("Rent is not cancellable"); } rent.setStatus(RentStatus.CANCELLED); updateUserScore(rent); return commandPort.upsert(rent); } public boolean isCancellable(Rent rent) { LocalDateTime now = LocalDateTime.now(); if(rent.getCreatedAt().plus(5, ChronoUnit.MINUTES) .isAfter(now)) { return true; } return rent.getDeclaredStartDate().plus(7, ChronoUnit.DAYS) .isAfter(now); } @Override public Rent issueVehicle(UUID id) throws RentNotFoundException, RentCannotIssueVehicleException { Rent rent = queryPort.getRent(id); LocalDateTime now = LocalDateTime.now(); // you can rent 30 mins before declared time if(rent.getDeclaredStartDate() .plus(30, ChronoUnit.MINUTES) .isBefore(now)) { throw new RentCannotIssueVehicleException("Cannot issue right now"); } rent.setStatus(RentStatus.ISSUED); rent.setActualStartDate(now); return commandPort.upsert(rent); } @Override public Rent returnVehicle(UUID id) throws RentNotFoundException, RentVehicleNotIssuedException { Rent rent = queryPort.getRent(id); if(!rent.getStatus().equals(RentStatus.ISSUED)) { throw new RentVehicleNotIssuedException("Vehicle not issued"); } rent.setStatus(RentStatus.RETURNED_GOOD); rent.setActualEndDate(LocalDateTime.now()); updateUserScore(rent); return commandPort.upsert(rent); } @Override public Rent returnDamagedVehicle(UUID id) throws RentNotFoundException, RentVehicleNotIssuedException { Rent rent = queryPort.getRent(id); if(!rent.getStatus().equals(RentStatus.ISSUED)) { throw new RentVehicleNotIssuedException("Vehicle not issued"); } rent.setStatus(RentStatus.RETURNED_DAMAGED); rent.setActualEndDate(LocalDateTime.now()); updateUserScore(rent); return commandPort.upsert(rent); } @Override public Rent returnMissingVehicle(UUID id) throws RentNotFoundException, RentVehicleNotIssuedException { Rent rent = queryPort.getRent(id); if(!rent.getStatus().equals(RentStatus.ISSUED)) { throw new RentVehicleNotIssuedException("Vehicle not issued"); } rent.setStatus(RentStatus.NOT_RETURNED); rent.setActualEndDate(LocalDateTime.now()); updateUserScore(rent); rent.getVehicle().setAvailable(false); return commandPort.upsert(rent); } @Override public void updateRentsNotIssued() { List<Rent> rentsToIssue = queryPort.getRentsByStatus(RentStatus.CREATED); LocalDateTime now = LocalDateTime.now(); rentsToIssue.forEach(rent -> { if(rent.getDeclaredStartDate().isBefore(now)) { rent.setStatus(RentStatus.NOT_ISSUED); updateUserScore(rent); commandPort.upsert(rent); } }); } // modyfikator do ceny z powodu wyniku konta to pomiędzy -30% i +10% // dlatego punkty mogą mieć wartości od 3000 do -1000 // w na<SUF> private void updateUserScore(Rent rent) { double rentPoints = 0; if(rent.getActualStartDate() != null) { Duration deltaStart = Duration.between(rent.getDeclaredStartDate(), rent.getActualStartDate()); if(deltaStart.isNegative()) { // odbiór przed czasem jest możliwy, ale niepożądany rentPoints -= 50d; } else if(deltaStart.toMinutes() < 60){ // im później klient odbierze samochód, tym mniej punktów dostaje rentPoints += 200d * (60 - deltaStart.toMinutes()); } } log.info(Double.toString(rentPoints)); if(rent.getActualEndDate() != null) { log.info(rent.getDeclaredEndDate().toString()); log.info(rent.getActualEndDate().toString()); Duration deltaEnd = Duration.between(rent.getActualEndDate(), rent.getDeclaredEndDate()); if (deltaEnd.isNegative()) { // oddane przed zadeklarowanym czasem (klient płaci za zarezerwowany czas) rentPoints += 300d; } else if (deltaEnd.toMinutes() < 60) { // klient traci 0,1 pkt% zniżki za każdą minutę opóźnienia rentPoints -= 10d * (deltaEnd.toMinutes()); } } switch(rent.getStatus()) { case NOT_ISSUED -> rentPoints -= 100d; case CANCELLED -> rentPoints -= 50d; case RETURNED_GOOD -> rentPoints += 500d; case RETURNED_DAMAGED -> rentPoints -= 200d; case NOT_RETURNED -> rentPoints -= 3000d; // zniweluj każdą zniżkę } // clamp rent.getUser().setScore(Math.max(-1000, Math.min(3000, rentPoints))); } }
13157_1
package agh.ics.oop; import java.util.ArrayList; public class Animal { private MapDirection orientation = MapDirection.NORTH; private Vector2d position = new Vector2d(0,0); // Domyślna pozycja jedyna, którą możemy zagwarantować dla każdej mapy private final IWorldMap map; // Konstruktor bez parametrów tylko na potrzeby testów public Animal() { this.position = new Vector2d(2, 2); this.map = new RectangularMap(5, 5); } public Animal(IWorldMap map) { this.map = map; } public Animal(IWorldMap map, Vector2d initialPosition) { this.map = map; this.position = initialPosition; } public MapDirection getOrientation() { return orientation; } public Vector2d getPosition() { return position; } public boolean isAt(Vector2d position) { return this.position.equals(position); } public String toString() { return switch (this.orientation) { case NORTH -> "^"; case EAST -> ">"; case SOUTH -> "v"; case WEST -> "<"; }; } public Animal move(MoveDirection direction) { switch (direction) { case RIGHT -> this.orientation = this.orientation.next(); case LEFT -> this.orientation = this.orientation.previous(); case FORWARD, BACKWARD -> { Vector2d unitVector = this.orientation.toUnitVector(); if (direction == MoveDirection.BACKWARD) unitVector = unitVector.opposite(); Vector2d newPosition = this.position.add(unitVector); if (this.map.canMoveTo(newPosition)) this.position = newPosition; } } return this; } public Animal move(ArrayList<MoveDirection> directions) { for (MoveDirection direction : directions) this.move(direction); return this; } }
23adrian2300/PO_lab-AGH
lab4/src/main/java/agh/ics/oop/Animal.java
552
// Konstruktor bez parametrów tylko na potrzeby testów
line_comment
pl
package agh.ics.oop; import java.util.ArrayList; public class Animal { private MapDirection orientation = MapDirection.NORTH; private Vector2d position = new Vector2d(0,0); // Domyślna pozycja jedyna, którą możemy zagwarantować dla każdej mapy private final IWorldMap map; // Kons<SUF> public Animal() { this.position = new Vector2d(2, 2); this.map = new RectangularMap(5, 5); } public Animal(IWorldMap map) { this.map = map; } public Animal(IWorldMap map, Vector2d initialPosition) { this.map = map; this.position = initialPosition; } public MapDirection getOrientation() { return orientation; } public Vector2d getPosition() { return position; } public boolean isAt(Vector2d position) { return this.position.equals(position); } public String toString() { return switch (this.orientation) { case NORTH -> "^"; case EAST -> ">"; case SOUTH -> "v"; case WEST -> "<"; }; } public Animal move(MoveDirection direction) { switch (direction) { case RIGHT -> this.orientation = this.orientation.next(); case LEFT -> this.orientation = this.orientation.previous(); case FORWARD, BACKWARD -> { Vector2d unitVector = this.orientation.toUnitVector(); if (direction == MoveDirection.BACKWARD) unitVector = unitVector.opposite(); Vector2d newPosition = this.position.add(unitVector); if (this.map.canMoveTo(newPosition)) this.position = newPosition; } } return this; } public Animal move(ArrayList<MoveDirection> directions) { for (MoveDirection direction : directions) this.move(direction); return this; } }
147484_0
package pl.edu.agh.dronka.shop.model.util; import java.util.LinkedHashMap; import java.util.Map; import pl.edu.agh.dronka.shop.model.Item; public class PropertiesHelper { public static Map<String, Object> getPropertiesMap(Item item) { Map<String, Object> propertiesMap = new LinkedHashMap<>(); //zmieniłem nazwy dla lepszego wygladu propertiesMap.put("Nazwy", item.getName()); propertiesMap.put("Cena", item.getPrice()); propertiesMap.put("Kategoria", item.getCategory().getDisplayName()); propertiesMap.put("Ilosc", item.getQuantity()); propertiesMap.put("Czy polskie", item.isPolish()); propertiesMap.put("Czy uzywany", item.isSecondhand()); Map<String, Object> additionalPropertiesMap = item.getExtraFieldsMap(); if (additionalPropertiesMap != null) { propertiesMap.putAll(additionalPropertiesMap); } return propertiesMap; } }
23adrian2300/ProjektowanieObiektowe-AGH
Lab2/dronka-shop/src/pl/edu/agh/dronka/shop/model/util/PropertiesHelper.java
307
//zmieniłem nazwy dla lepszego wygladu
line_comment
pl
package pl.edu.agh.dronka.shop.model.util; import java.util.LinkedHashMap; import java.util.Map; import pl.edu.agh.dronka.shop.model.Item; public class PropertiesHelper { public static Map<String, Object> getPropertiesMap(Item item) { Map<String, Object> propertiesMap = new LinkedHashMap<>(); //zmie<SUF> propertiesMap.put("Nazwy", item.getName()); propertiesMap.put("Cena", item.getPrice()); propertiesMap.put("Kategoria", item.getCategory().getDisplayName()); propertiesMap.put("Ilosc", item.getQuantity()); propertiesMap.put("Czy polskie", item.isPolish()); propertiesMap.put("Czy uzywany", item.isSecondhand()); Map<String, Object> additionalPropertiesMap = item.getExtraFieldsMap(); if (additionalPropertiesMap != null) { propertiesMap.putAll(additionalPropertiesMap); } return propertiesMap; } }
20519_7
package sr.ice.client; import Demo.A; import Demo.CalcPrx; import Demo.EmptySequence; import com.zeroc.Ice.*; import java.io.IOException; import java.lang.Exception; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.CompletableFuture; public class IceClient { public static void main(String[] args) { int status = 0; Communicator communicator = null; try { // 1. Inicjalizacja ICE communicator = Util.initialize(args); // 2. Uzyskanie referencji obiektu na podstawie linii w pliku konfiguracyjnym (wówczas aplikację należy uruchomić z argumentem --Ice.config=config.client) //ObjectPrx base1 = communicator.propertyToProxy("Calc1.Proxy"); //dokończyć // 2. Uzyskanie referencji obiektu - to samo co powyżej, ale mniej ładnie // ObjectPrx base1 = communicator.stringToProxy("calc/calc11:tcp -h 192.168.213.29 -p 10000 -z : udp -h 192.168.213.29 -p 10000 -z"); //opcja -z włącza możliwość kompresji wiadomości ObjectPrx base1 = communicator.stringToProxy("calc/calc11:tcp -h 127.0.0.2 -p 10000 -z : udp -h 127.0.0.2 -p 10000 -z"); // 3. Rzutowanie, zawężanie (do typu Calc) CalcPrx obj1 = CalcPrx.checkedCast(base1); //CalcPrx obj1 = CalcPrx.uncheckedCast(base1); //na czym polega różnica? if (obj1 == null) throw new Error("Invalid proxy"); CompletableFuture<Long> cfl = null; String line = null; java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); long r; A a; double r1; long[] tab = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; long[] emTab = {}; // 4. Wywołanie zdalnych operacji i zmiana trybu proxy dla obiektu obj1 do { try { System.out.print("==> "); line = in.readLine(); switch (line) { case "add": r = obj1.add(7, 8); System.out.println("RESULT = " + r); break; case "add2": r = obj1.add(7000, 8000); System.out.println("RESULT = " + r); break; case "subtract": r = obj1.subtract(7, 8); System.out.println("RESULT = " + r); break; case "avg": try{ r1 = obj1.avg(tab); System.out.println("RESULT = " + r1); } catch (Exception ex) { System.out.println("EXCEPTION: " + ex.getMessage()); } break; case "emptyavg": try{ r1 = obj1.avg(emTab); System.out.println("RESULT = " + r1); } catch (EmptySequence ex) { System.out.println("EXCEPTION: " + ex); } break; case "op": a = new A((short) 11, 22, 33.0f, "ala ma kota"); obj1.op(a, (short) 44); System.out.println("DONE"); break; case "op2": a = new A((short) 11, 22, 33.0f, "ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota "); obj1.op(a, (short) 44); System.out.println("DONE"); break; case "op 10": a = new A((short) 11, 22, 33.0f, "ala ma kota"); for (int i = 0; i < 10; i++) obj1.op(a, (short) 44); System.out.println("DONE"); break; case "add-with-ctx": //wysłanie dodatkowych danych stanowiących kontekst wywołania Map<String, String> map = new HashMap<>(); map.put("key1", "val1"); map.put("key2", "val2"); r = obj1.add(7, 8, map); System.out.println("RESULT = " + r); break; /* PONIŻEJ WYWOŁANIA REALIZOWANE W TRYBIE ASYNCHRONICZNYM */ case "add-asyn1": //future-based obj1.addAsync(7000, 8000).whenComplete((result, ex) -> System.out.println("RESULT (asyn) = " + result)); break; case "add-asyn2-req": //future-based 1. zlecenie wyłania cfl = obj1.addAsync(7000, 8000); break; case "add-asyn2-res": //future-based 2. odebranie wyniku r = cfl.join(); System.out.println("RESULT = " + r); break; case "op-asyn1a 100": //co się dzieje "w sieci"? a = new A((short) 11, 22, 33.0f, "ala ma kota"); for (int i = 0; i < 100; i++) { obj1.opAsync(a, (short) 99); } System.out.println("DONE"); break; case "op-asyn1b 100": a = new A((short) 11, 22, 33.0f, "ala ma kota"); for (int i = 0; i < 100; i++) { obj1.opAsync(a, (short) 99).whenComplete((result, ex) -> System.out.println("CALL (asyn) finished") ); } System.out.println("DONE"); break; /* PONIŻEJ USTAWIANIE TRYBU PRACY PROXY */ case "compress on": obj1 = obj1.ice_compress(true); System.out.println("Compression enabled for obj1"); break; case "compress off": obj1 = obj1.ice_compress(false); System.out.println("Compression disabled for obj1"); break; case "set-proxy twoway": obj1 = obj1.ice_twoway(); System.out.println("obj1 proxy set to 'twoway' mode"); break; case "set-proxy oneway": obj1 = obj1.ice_oneway(); System.out.println("obj1 proxy set to 'oneway' mode"); break; case "set-proxy datagram": obj1 = obj1.ice_datagram(); System.out.println("obj1 proxy set to 'datagram' mode"); break; case "set-proxy batch oneway": obj1 = obj1.ice_batchOneway(); System.out.println("obj1 proxy set to 'batch oneway' mode"); break; case "set-proxy batch datagram": obj1 = obj1.ice_batchDatagram(); System.out.println("obj1 proxy set to 'batch datagram' mode"); break; case "flush": //sensowne tylko dla operacji wywoływanych w trybie batch obj1.ice_flushBatchRequests(); System.out.println("Flush DONE"); break; case "x": case "": break; default: System.out.println("???"); } } catch (IOException | TwowayOnlyException ex) { ex.printStackTrace(System.err); } } while (!Objects.equals(line, "x")); } catch (LocalException e) { e.printStackTrace(); status = 1; } catch (Exception e) { System.err.println(e.getMessage()); status = 1; } if (communicator != null) { //clean try { communicator.destroy(); } catch (Exception e) { System.err.println(e.getMessage()); status = 1; } } System.exit(status); } }
23adrian2300/SR-AGH
Middleware/Ice/src/sr/ice/client/IceClient.java
3,290
//CalcPrx obj1 = CalcPrx.uncheckedCast(base1); //na czym polega różnica?
line_comment
pl
package sr.ice.client; import Demo.A; import Demo.CalcPrx; import Demo.EmptySequence; import com.zeroc.Ice.*; import java.io.IOException; import java.lang.Exception; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.CompletableFuture; public class IceClient { public static void main(String[] args) { int status = 0; Communicator communicator = null; try { // 1. Inicjalizacja ICE communicator = Util.initialize(args); // 2. Uzyskanie referencji obiektu na podstawie linii w pliku konfiguracyjnym (wówczas aplikację należy uruchomić z argumentem --Ice.config=config.client) //ObjectPrx base1 = communicator.propertyToProxy("Calc1.Proxy"); //dokończyć // 2. Uzyskanie referencji obiektu - to samo co powyżej, ale mniej ładnie // ObjectPrx base1 = communicator.stringToProxy("calc/calc11:tcp -h 192.168.213.29 -p 10000 -z : udp -h 192.168.213.29 -p 10000 -z"); //opcja -z włącza możliwość kompresji wiadomości ObjectPrx base1 = communicator.stringToProxy("calc/calc11:tcp -h 127.0.0.2 -p 10000 -z : udp -h 127.0.0.2 -p 10000 -z"); // 3. Rzutowanie, zawężanie (do typu Calc) CalcPrx obj1 = CalcPrx.checkedCast(base1); //Calc<SUF> if (obj1 == null) throw new Error("Invalid proxy"); CompletableFuture<Long> cfl = null; String line = null; java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); long r; A a; double r1; long[] tab = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; long[] emTab = {}; // 4. Wywołanie zdalnych operacji i zmiana trybu proxy dla obiektu obj1 do { try { System.out.print("==> "); line = in.readLine(); switch (line) { case "add": r = obj1.add(7, 8); System.out.println("RESULT = " + r); break; case "add2": r = obj1.add(7000, 8000); System.out.println("RESULT = " + r); break; case "subtract": r = obj1.subtract(7, 8); System.out.println("RESULT = " + r); break; case "avg": try{ r1 = obj1.avg(tab); System.out.println("RESULT = " + r1); } catch (Exception ex) { System.out.println("EXCEPTION: " + ex.getMessage()); } break; case "emptyavg": try{ r1 = obj1.avg(emTab); System.out.println("RESULT = " + r1); } catch (EmptySequence ex) { System.out.println("EXCEPTION: " + ex); } break; case "op": a = new A((short) 11, 22, 33.0f, "ala ma kota"); obj1.op(a, (short) 44); System.out.println("DONE"); break; case "op2": a = new A((short) 11, 22, 33.0f, "ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota ala ma kota "); obj1.op(a, (short) 44); System.out.println("DONE"); break; case "op 10": a = new A((short) 11, 22, 33.0f, "ala ma kota"); for (int i = 0; i < 10; i++) obj1.op(a, (short) 44); System.out.println("DONE"); break; case "add-with-ctx": //wysłanie dodatkowych danych stanowiących kontekst wywołania Map<String, String> map = new HashMap<>(); map.put("key1", "val1"); map.put("key2", "val2"); r = obj1.add(7, 8, map); System.out.println("RESULT = " + r); break; /* PONIŻEJ WYWOŁANIA REALIZOWANE W TRYBIE ASYNCHRONICZNYM */ case "add-asyn1": //future-based obj1.addAsync(7000, 8000).whenComplete((result, ex) -> System.out.println("RESULT (asyn) = " + result)); break; case "add-asyn2-req": //future-based 1. zlecenie wyłania cfl = obj1.addAsync(7000, 8000); break; case "add-asyn2-res": //future-based 2. odebranie wyniku r = cfl.join(); System.out.println("RESULT = " + r); break; case "op-asyn1a 100": //co się dzieje "w sieci"? a = new A((short) 11, 22, 33.0f, "ala ma kota"); for (int i = 0; i < 100; i++) { obj1.opAsync(a, (short) 99); } System.out.println("DONE"); break; case "op-asyn1b 100": a = new A((short) 11, 22, 33.0f, "ala ma kota"); for (int i = 0; i < 100; i++) { obj1.opAsync(a, (short) 99).whenComplete((result, ex) -> System.out.println("CALL (asyn) finished") ); } System.out.println("DONE"); break; /* PONIŻEJ USTAWIANIE TRYBU PRACY PROXY */ case "compress on": obj1 = obj1.ice_compress(true); System.out.println("Compression enabled for obj1"); break; case "compress off": obj1 = obj1.ice_compress(false); System.out.println("Compression disabled for obj1"); break; case "set-proxy twoway": obj1 = obj1.ice_twoway(); System.out.println("obj1 proxy set to 'twoway' mode"); break; case "set-proxy oneway": obj1 = obj1.ice_oneway(); System.out.println("obj1 proxy set to 'oneway' mode"); break; case "set-proxy datagram": obj1 = obj1.ice_datagram(); System.out.println("obj1 proxy set to 'datagram' mode"); break; case "set-proxy batch oneway": obj1 = obj1.ice_batchOneway(); System.out.println("obj1 proxy set to 'batch oneway' mode"); break; case "set-proxy batch datagram": obj1 = obj1.ice_batchDatagram(); System.out.println("obj1 proxy set to 'batch datagram' mode"); break; case "flush": //sensowne tylko dla operacji wywoływanych w trybie batch obj1.ice_flushBatchRequests(); System.out.println("Flush DONE"); break; case "x": case "": break; default: System.out.println("???"); } } catch (IOException | TwowayOnlyException ex) { ex.printStackTrace(System.err); } } while (!Objects.equals(line, "x")); } catch (LocalException e) { e.printStackTrace(); status = 1; } catch (Exception e) { System.err.println(e.getMessage()); status = 1; } if (communicator != null) { //clean try { communicator.destroy(); } catch (Exception e) { System.err.println(e.getMessage()); status = 1; } } System.exit(status); } }
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
5