file_id stringlengths 5 10 | content stringlengths 106 33.1k | repo stringlengths 7 77 | path stringlengths 7 170 | token_length int64 36 8.19k | original_comment stringlengths 5 6.63k | comment_type stringclasses 2
values | detected_lang stringclasses 1
value | prompt stringlengths 14 33.1k |
|---|---|---|---|---|---|---|---|---|
57872_11 | package objects;
import lombok.Data;
import controll.FuzzyLogic;
import lombok.Getter;
import panels.SimulationPanel;
import javax.swing.*;
import java.util.ArrayList;
public class RoadManager {
private ArrayList<Predator> predators;
private Prey prey;
@Getter
private double os_x; // wspolrzedne wyjsciowe do sterowania
@Getter
private double os_y;
private final int moveSensitive = 4; // zmiena odpowiedzialna za czulosc ruchu dla kazdego zbioru jesli dokonamy zmiany musi byc inna , by ruch wydawal sie liniowy nie skokowy
private FuzzyLogic fuzzy;
public RoadManager() {
this.predators = new ArrayList<>();
fuzzy = new FuzzyLogic();
}
public Prey getPrey() {
return prey;
}
public void resetProgram() {
this.predators = new ArrayList<>(); // zerowanie drapieżników
prey = null; // kasowanie ofiary
}
public void addPredator(int x, int y) {
this.predators.add(new Predator(x, y));
}
public ArrayList<Predator> getPredators() {
return predators;
}
public void addPrey(int x, int y) {
this.prey = new Prey(x, y);
}
public boolean makeMove(SimulationPanel panel) {
if (prey == null) {
return false;
}
// sprawdzenie czy ofara doszła do mety
if (prey.getX() >= panel.getWidth() - prey.getWidth() / 2) {
return false;
}
//sprawdzenie czy dodano jakiegos predatora
if (predators.isEmpty()) {
return false;
}
// pobranie pierwszego predatora z listy
Predator closestPredator = predators.get(0);
double r = 0;
// szukanie najbliszego predatora do ominiecia
for (int i = 1; i < predators.size(); i++) {
Predator temp = predators.get(i);
r = closestPredator.getDistanceFromPrey(prey);
if (r > temp.getDistanceFromPrey(prey)) {
// jesli znajdziemy blizszy zamieniamy
closestPredator = temp;
}
}
// pobranie roznicy medzy drapieżnikiem a ofiarą
int rx = closestPredator.getX() - prey.getX();
int ry = closestPredator.getY() - prey.getY();
if (Math.abs(rx) > 100) { // maksymalna wartosc i minimalna zbiorow dla wartosci wejsciowych wynosi -100 i 100
rx = rx > 0 ? 100 : -100;
}
if (Math.abs(ry) > 100) {
ry = ry > 0 ? 100 : -100;
}
fuzzy.fuzzify(rx, ry); // obliczenia zbiorow
os_x = 12.48d;
os_y = fuzzy.getOutY(); //pobranie metody środka ciężkości wartości wyjsciowych
prey.setX(prey.getX() + (int) os_x / moveSensitive); // ustawianie wspolrzednych 4 oznacza czulosc ruchu
prey.setY(prey.getY() - (int) os_y / moveSensitive);
//Poruszanie predatorami na podstawie pozycji ofiary + przypadek schwytania ofiary
for (Predator p : predators) {
// sprawdzenie odleglosci miedzy predatorem, a ofiara jesli < 15 to ofiara schwytana
if (p.getDistanceFromPrey(prey) < 15) {
JOptionPane.showMessageDialog(panel, "Ofiara została schwytana.");
panel.resetProgram();
return false;
}
//poruszanie wilka po osi x
if (p.getX() < prey.getX()) {
p.setX(p.getX() + 1);
} else {
p.setX(p.getX() - 1);
}
//poruszanie wilka po osi y
if (p.getY() < prey.getY()) {
p.setY(p.getY() + 1);
} else {
p.setY(p.getY() - 1);
}
}
return true;
}
}
| 00Zbiechu/Hunting-Fuzzy-Logic | src/main/java/objects/RoadManager.java | 1,326 | // obliczenia zbiorow | line_comment | pl | package objects;
import lombok.Data;
import controll.FuzzyLogic;
import lombok.Getter;
import panels.SimulationPanel;
import javax.swing.*;
import java.util.ArrayList;
public class RoadManager {
private ArrayList<Predator> predators;
private Prey prey;
@Getter
private double os_x; // wspolrzedne wyjsciowe do sterowania
@Getter
private double os_y;
private final int moveSensitive = 4; // zmiena odpowiedzialna za czulosc ruchu dla kazdego zbioru jesli dokonamy zmiany musi byc inna , by ruch wydawal sie liniowy nie skokowy
private FuzzyLogic fuzzy;
public RoadManager() {
this.predators = new ArrayList<>();
fuzzy = new FuzzyLogic();
}
public Prey getPrey() {
return prey;
}
public void resetProgram() {
this.predators = new ArrayList<>(); // zerowanie drapieżników
prey = null; // kasowanie ofiary
}
public void addPredator(int x, int y) {
this.predators.add(new Predator(x, y));
}
public ArrayList<Predator> getPredators() {
return predators;
}
public void addPrey(int x, int y) {
this.prey = new Prey(x, y);
}
public boolean makeMove(SimulationPanel panel) {
if (prey == null) {
return false;
}
// sprawdzenie czy ofara doszła do mety
if (prey.getX() >= panel.getWidth() - prey.getWidth() / 2) {
return false;
}
//sprawdzenie czy dodano jakiegos predatora
if (predators.isEmpty()) {
return false;
}
// pobranie pierwszego predatora z listy
Predator closestPredator = predators.get(0);
double r = 0;
// szukanie najbliszego predatora do ominiecia
for (int i = 1; i < predators.size(); i++) {
Predator temp = predators.get(i);
r = closestPredator.getDistanceFromPrey(prey);
if (r > temp.getDistanceFromPrey(prey)) {
// jesli znajdziemy blizszy zamieniamy
closestPredator = temp;
}
}
// pobranie roznicy medzy drapieżnikiem a ofiarą
int rx = closestPredator.getX() - prey.getX();
int ry = closestPredator.getY() - prey.getY();
if (Math.abs(rx) > 100) { // maksymalna wartosc i minimalna zbiorow dla wartosci wejsciowych wynosi -100 i 100
rx = rx > 0 ? 100 : -100;
}
if (Math.abs(ry) > 100) {
ry = ry > 0 ? 100 : -100;
}
fuzzy.fuzzify(rx, ry); // ob<SUF>
os_x = 12.48d;
os_y = fuzzy.getOutY(); //pobranie metody środka ciężkości wartości wyjsciowych
prey.setX(prey.getX() + (int) os_x / moveSensitive); // ustawianie wspolrzednych 4 oznacza czulosc ruchu
prey.setY(prey.getY() - (int) os_y / moveSensitive);
//Poruszanie predatorami na podstawie pozycji ofiary + przypadek schwytania ofiary
for (Predator p : predators) {
// sprawdzenie odleglosci miedzy predatorem, a ofiara jesli < 15 to ofiara schwytana
if (p.getDistanceFromPrey(prey) < 15) {
JOptionPane.showMessageDialog(panel, "Ofiara została schwytana.");
panel.resetProgram();
return false;
}
//poruszanie wilka po osi x
if (p.getX() < prey.getX()) {
p.setX(p.getX() + 1);
} else {
p.setX(p.getX() - 1);
}
//poruszanie wilka po osi y
if (p.getY() < prey.getY()) {
p.setY(p.getY() + 1);
} else {
p.setY(p.getY() - 1);
}
}
return true;
}
}
|
43670_2 | package struktury;
/**
* Bazowa klasa
* @author Oskar Sobczyk
* @version 1.0
* @since 2018-20-10
*/
public abstract class Zbior {
/** metoda ma szukać pary z określonym kluczem */
public abstract Para szukaj (String k) throws Exception;
/** metoda ma wstawiać do zbioru nową parę */
public abstract void wstaw (Para p) throws Exception;
/** metoda ma odszukać parę i zwrócić wartość związaną z kluczem */
public abstract double czytaj (String k) throws Exception;
/** metoda ma wstawić do zbioru nową albo zaktualizować parę */
public abstract void ustaw (Para p) throws Exception;
/** metoda ma usunąć wszystkie pary ze zbioru */
public abstract void czysc ();
/** metoda ma podać ile par jest przechowywanych w zbiorze */
public abstract int ile ();
}
| 0sk4r/Uwr | Java/Lista03/src/struktury/Zbior.java | 276 | /** metoda ma wstawiać do zbioru nową parę */ | block_comment | pl | package struktury;
/**
* Bazowa klasa
* @author Oskar Sobczyk
* @version 1.0
* @since 2018-20-10
*/
public abstract class Zbior {
/** metoda ma szukać pary z określonym kluczem */
public abstract Para szukaj (String k) throws Exception;
/** met<SUF>*/
public abstract void wstaw (Para p) throws Exception;
/** metoda ma odszukać parę i zwrócić wartość związaną z kluczem */
public abstract double czytaj (String k) throws Exception;
/** metoda ma wstawić do zbioru nową albo zaktualizować parę */
public abstract void ustaw (Para p) throws Exception;
/** metoda ma usunąć wszystkie pary ze zbioru */
public abstract void czysc ();
/** metoda ma podać ile par jest przechowywanych w zbiorze */
public abstract int ile ();
}
|
66517_1 | 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 | //FIXME: zrobmy cos z tym pozniej bo to obrzydliwe | 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)
{
//FI<SUF>
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());
}
}
|
57392_6 | package Workshops.no2_functional_programming.Streams;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class streamOperations {
// podczas debugowania streamu po prawej od ikonek "step over" itd. jest dostępna ikonka Trace Current Stream Chain
// przyjmuje:
// filter - Predicate
// map - Function
// flatMap - Function
// peek - Consumer
// distinct - nic nie przyjmuje, odsiewa duplikaty (objekty muszą mieć equals()
// limit - long
// skip - long
// sorted - Comparator albo nic
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Kazik", new City("Warszawa")),
new Person("Waldek", new City("Wrocław")),
new Person("Damian", new City("Zakopane")),
new Person("Seba", new City("Warszawa")),
new Person("Mati", new City("Gdynia"))
);
Stream<Person> myStream = people.stream();
// filter
Stream<Person> filterResult = myStream
.filter(person -> person.getCity().getCityName().contains("W")
);
// map
// przyjmuje interface Function
// musi zwrócic coś co da stream
// jak w Intelij włączony InlayHints to pokazuje po każdej metodzie .map jaki stream z niej wyjdzie
List<Integer> collect = people.stream()
.map(person -> person + "A")
.map(String::toUpperCase)
.map(s -> s.length())
.collect(Collectors.toList());
int counter1 = 0;
// żeby w streamie móc dodać counter trzeba go zamienić na atomicInteger (bo zmienna musi byc effectivly final
AtomicInteger counter2 = new AtomicInteger(0);
// i wtedy w danej lambdzie można dodać
counter2.incrementAndGet();
Integer collect2 = people.stream()
.map(person -> person + "A")
.map(String::length)
.reduce(0, Integer::sum);
// flatMap
// przyjmuje interface Function
// przy optionalach w mieliśmy Optional'a w Optional'u to flatMap raz go odwijało
List<String> cities1 = Arrays.asList("Warszawa", "Gdańsk", "Łódź", "Wrocław", "Gdańsk");
List<String> cities2 = Arrays.asList("Warszawa", "Gdańsk", "Łódź", "Wrocław", "Gdańsk");
List<String> cities3 = Arrays.asList("Warszawa", "Gdańsk", "Łódź", "Wrocław", "Gdańsk");
List<List<String>> citiesCombined = List.of(cities1, cities2, cities3);
// flatMap spłasza strukture, tzn wychodzi z jednego zagnieżdżenia
List<String> stringStream = citiesCombined.stream()
.flatMap(list -> list.stream())
.collect(Collectors.toList());
// peek
// przyjmuje Consumer'a
Set<City> collect1 = people.stream()
.peek(a -> System.out.println("Step1: " + a))
.map(person -> person.getCity())
.peek(a -> System.out.println("Step2: " + a))
.collect(Collectors.toSet());
// distinct
// nic nie przyjmuje, odsiewa duplikaty
// jeśli jest stream customowych objektów to muszą mieć equals() i hascode()
String collect3 = cities1.stream()
.distinct()
.collect(Collectors.joining(", "));
// limit
// ogranicza ilość elementów które są procesowane w streamie
// jak damy 3 to limituje do 3 elementów a nie do 3 indeksu
// nie ma znaczenia w którym miejscu w streamie postawimy limit
cities1.stream()
.peek(elem -> System.out.println("Step1: " + elem ))
.limit(3)
.collect(Collectors.joining(", "));
// skip
// jak dajemy skip(3) to znaczy że pierwsze 3 elementy które dotrą do metody skip nie przechodzą do kolejnych
// więc step2 będzie wykonany tylko dla elementów 4,5,6...
// zeskipowane elementy nie będą znajdować się w końcowej kolekcji po Collect(...)
String stringCities = cities1.stream()
.peek(elem -> System.out.println("Step1: " + elem ))
.skip(3)
.peek(elem -> System.out.println("Step2: " + elem ))
.collect(Collectors.joining(", "));
// sorted
// może nic nie przyjmowac, lub przyjąć comparator
// najpierw wszystkie elementy dojdą do Step1 później zostaną posortowane i dopiero wtedy każdy elementy przejdzie do Step2 już w kolejności posortowanej
// żeby można było posortować to trzeba mieć wszystkie elementy dlatego przy streamie nieskończonym jeśli damy sorted() przed limit() to nigdy
// nie zbierze wszystkich elementów do posortowania i będzie się kręcił w nieskończoność
cities1.stream()
.peek(elem -> System.out.println("Step1: " + elem ))
.sorted()
.peek(elem -> System.out.println("Step2: " + elem ))
.collect(Collectors.joining(", "));
// sortowanie mapy po values
// Stream<Map.Entry<K,V>> sorted =
// map.entrySet().stream()
// .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()));
}
private static class Person {
private final String name;
private final City city;
public Person(String name, City city) {
this.name = name;
this.city = city;
}
public String getName() {
return name;
}
public City getCity() {
return city;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", city=" + city +
'}';
}
}
private static class City {
private final String cityName;
public City(String cityName) {
this.cityName = cityName;
}
public String getCityName() {
return cityName;
}
@Override
public String toString() {
return "City{" +
"cityName='" + cityName + '\'' +
'}';
}
}
}
| 0xRobert1997/Workshops | src/Workshops/no2_functional_programming/Streams/streamOperations.java | 1,938 | // distinct - nic nie przyjmuje, odsiewa duplikaty (objekty muszą mieć equals() | line_comment | pl | package Workshops.no2_functional_programming.Streams;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class streamOperations {
// podczas debugowania streamu po prawej od ikonek "step over" itd. jest dostępna ikonka Trace Current Stream Chain
// przyjmuje:
// filter - Predicate
// map - Function
// flatMap - Function
// peek - Consumer
// di<SUF>
// limit - long
// skip - long
// sorted - Comparator albo nic
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Kazik", new City("Warszawa")),
new Person("Waldek", new City("Wrocław")),
new Person("Damian", new City("Zakopane")),
new Person("Seba", new City("Warszawa")),
new Person("Mati", new City("Gdynia"))
);
Stream<Person> myStream = people.stream();
// filter
Stream<Person> filterResult = myStream
.filter(person -> person.getCity().getCityName().contains("W")
);
// map
// przyjmuje interface Function
// musi zwrócic coś co da stream
// jak w Intelij włączony InlayHints to pokazuje po każdej metodzie .map jaki stream z niej wyjdzie
List<Integer> collect = people.stream()
.map(person -> person + "A")
.map(String::toUpperCase)
.map(s -> s.length())
.collect(Collectors.toList());
int counter1 = 0;
// żeby w streamie móc dodać counter trzeba go zamienić na atomicInteger (bo zmienna musi byc effectivly final
AtomicInteger counter2 = new AtomicInteger(0);
// i wtedy w danej lambdzie można dodać
counter2.incrementAndGet();
Integer collect2 = people.stream()
.map(person -> person + "A")
.map(String::length)
.reduce(0, Integer::sum);
// flatMap
// przyjmuje interface Function
// przy optionalach w mieliśmy Optional'a w Optional'u to flatMap raz go odwijało
List<String> cities1 = Arrays.asList("Warszawa", "Gdańsk", "Łódź", "Wrocław", "Gdańsk");
List<String> cities2 = Arrays.asList("Warszawa", "Gdańsk", "Łódź", "Wrocław", "Gdańsk");
List<String> cities3 = Arrays.asList("Warszawa", "Gdańsk", "Łódź", "Wrocław", "Gdańsk");
List<List<String>> citiesCombined = List.of(cities1, cities2, cities3);
// flatMap spłasza strukture, tzn wychodzi z jednego zagnieżdżenia
List<String> stringStream = citiesCombined.stream()
.flatMap(list -> list.stream())
.collect(Collectors.toList());
// peek
// przyjmuje Consumer'a
Set<City> collect1 = people.stream()
.peek(a -> System.out.println("Step1: " + a))
.map(person -> person.getCity())
.peek(a -> System.out.println("Step2: " + a))
.collect(Collectors.toSet());
// distinct
// nic nie przyjmuje, odsiewa duplikaty
// jeśli jest stream customowych objektów to muszą mieć equals() i hascode()
String collect3 = cities1.stream()
.distinct()
.collect(Collectors.joining(", "));
// limit
// ogranicza ilość elementów które są procesowane w streamie
// jak damy 3 to limituje do 3 elementów a nie do 3 indeksu
// nie ma znaczenia w którym miejscu w streamie postawimy limit
cities1.stream()
.peek(elem -> System.out.println("Step1: " + elem ))
.limit(3)
.collect(Collectors.joining(", "));
// skip
// jak dajemy skip(3) to znaczy że pierwsze 3 elementy które dotrą do metody skip nie przechodzą do kolejnych
// więc step2 będzie wykonany tylko dla elementów 4,5,6...
// zeskipowane elementy nie będą znajdować się w końcowej kolekcji po Collect(...)
String stringCities = cities1.stream()
.peek(elem -> System.out.println("Step1: " + elem ))
.skip(3)
.peek(elem -> System.out.println("Step2: " + elem ))
.collect(Collectors.joining(", "));
// sorted
// może nic nie przyjmowac, lub przyjąć comparator
// najpierw wszystkie elementy dojdą do Step1 później zostaną posortowane i dopiero wtedy każdy elementy przejdzie do Step2 już w kolejności posortowanej
// żeby można było posortować to trzeba mieć wszystkie elementy dlatego przy streamie nieskończonym jeśli damy sorted() przed limit() to nigdy
// nie zbierze wszystkich elementów do posortowania i będzie się kręcił w nieskończoność
cities1.stream()
.peek(elem -> System.out.println("Step1: " + elem ))
.sorted()
.peek(elem -> System.out.println("Step2: " + elem ))
.collect(Collectors.joining(", "));
// sortowanie mapy po values
// Stream<Map.Entry<K,V>> sorted =
// map.entrySet().stream()
// .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()));
}
private static class Person {
private final String name;
private final City city;
public Person(String name, City city) {
this.name = name;
this.city = city;
}
public String getName() {
return name;
}
public City getCity() {
return city;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", city=" + city +
'}';
}
}
private static class City {
private final String cityName;
public City(String cityName) {
this.cityName = cityName;
}
public String getCityName() {
return cityName;
}
@Override
public String toString() {
return "City{" +
"cityName='" + cityName + '\'' +
'}';
}
}
}
|
146326_5 | /*
* @lc app=leetcode.cn id=1160 lang=java
* @lcpr version=
*
* [1160] 拼写单词
*
* 36/36 cases passed (7 ms)
* Your runtime beats 69.7 % of java submissions
* Your memory usage beats 77.51 % of java submissions (42.9 MB)
*/
// @lcpr-template-start
// @lcpr-template-end
// @lc code=start
class Solution {
public int countCharacters(String[] words, String chars) {
int[] m = new int[26];
for(var c: chars.toCharArray()) m[c - 'a']++;
int ans = 0;
for(var s: words) {
int[] n = new int[26];
for(var c: s.toCharArray()) n[c - 'a']++;
boolean matched = true;
for(int i = 0; i < 26; i++) {
if (n[i] > m[i]) matched = false;
}
if (matched) ans += s.length();
}
return ans;
}
}
// @lc code=end
/*
// @lcpr case=start
// ["cat","bt","hat","tree"]\n"atach"\n
// @lcpr case=end
// @lcpr case=start
// ["hello","world","leetcode"]\n"welldonehoneyr"\n
// ["dyiclysmffuhibgfvapygkorkqllqlvokosagyelotobicwcmebnpznjbirzrzsrtzjxhsfpiwyfhzyonmuabtlwin","ndqeyhhcquplmznwslewjzuyfgklssvkqxmqjpwhrshycmvrb","ulrrbpspyudncdlbkxkrqpivfftrggemkpyjl","boygirdlggnh","xmqohbyqwagkjzpyawsydmdaattthmuvjbzwpyopyafphx","nulvimegcsiwvhwuiyednoxpugfeimnnyeoczuzxgxbqjvegcxeqnjbwnbvowastqhojepisusvsidhqmszbrnynkyop","hiefuovybkpgzygprmndrkyspoiyapdwkxebgsmodhzpx","juldqdzeskpffaoqcyyxiqqowsalqumddcufhouhrskozhlmobiwzxnhdkidr","lnnvsdcrvzfmrvurucrzlfyigcycffpiuoo","oxgaskztzroxuntiwlfyufddl","tfspedteabxatkaypitjfkhkkigdwdkctqbczcugripkgcyfezpuklfqfcsccboarbfbjfrkxp","qnagrpfzlyrouolqquytwnwnsqnmuzphne","eeilfdaookieawrrbvtnqfzcricvhpiv","sisvsjzyrbdsjcwwygdnxcjhzhsxhpceqz","yhouqhjevqxtecomahbwoptzlkyvjexhzcbccusbjjdgcfzlkoqwiwue","hwxxighzvceaplsycajkhynkhzkwkouszwaiuzqcleyflqrxgjsvlegvupzqijbornbfwpefhxekgpuvgiyeudhncv","cpwcjwgbcquirnsazumgjjcltitmeyfaudbnbqhflvecjsupjmgwfbjo","teyygdmmyadppuopvqdodaczob","qaeowuwqsqffvibrtxnjnzvzuuonrkwpysyxvkijemmpdmtnqxwekbpfzs","qqxpxpmemkldghbmbyxpkwgkaykaerhmwwjonrhcsubchs"]\n"usdruypficfbpfbivlrhutcgvyjenlxzeovdyjtgvvfdjzcmikjraspdfp"\n
// @lcpr case=end
*/
| 0xcaffebabe/leetcode | 算法/1001-1500/1160.拼写单词/1160.拼写单词.java | 1,064 | /*
// @lcpr case=start
// ["cat","bt","hat","tree"]\n"atach"\n
// @lcpr case=end
// @lcpr case=start
// ["hello","world","leetcode"]\n"welldonehoneyr"\n
// ["dyiclysmffuhibgfvapygkorkqllqlvokosagyelotobicwcmebnpznjbirzrzsrtzjxhsfpiwyfhzyonmuabtlwin","ndqeyhhcquplmznwslewjzuyfgklssvkqxmqjpwhrshycmvrb","ulrrbpspyudncdlbkxkrqpivfftrggemkpyjl","boygirdlggnh","xmqohbyqwagkjzpyawsydmdaattthmuvjbzwpyopyafphx","nulvimegcsiwvhwuiyednoxpugfeimnnyeoczuzxgxbqjvegcxeqnjbwnbvowastqhojepisusvsidhqmszbrnynkyop","hiefuovybkpgzygprmndrkyspoiyapdwkxebgsmodhzpx","juldqdzeskpffaoqcyyxiqqowsalqumddcufhouhrskozhlmobiwzxnhdkidr","lnnvsdcrvzfmrvurucrzlfyigcycffpiuoo","oxgaskztzroxuntiwlfyufddl","tfspedteabxatkaypitjfkhkkigdwdkctqbczcugripkgcyfezpuklfqfcsccboarbfbjfrkxp","qnagrpfzlyrouolqquytwnwnsqnmuzphne","eeilfdaookieawrrbvtnqfzcricvhpiv","sisvsjzyrbdsjcwwygdnxcjhzhsxhpceqz","yhouqhjevqxtecomahbwoptzlkyvjexhzcbccusbjjdgcfzlkoqwiwue","hwxxighzvceaplsycajkhynkhzkwkouszwaiuzqcleyflqrxgjsvlegvupzqijbornbfwpefhxekgpuvgiyeudhncv","cpwcjwgbcquirnsazumgjjcltitmeyfaudbnbqhflvecjsupjmgwfbjo","teyygdmmyadppuopvqdodaczob","qaeowuwqsqffvibrtxnjnzvzuuonrkwpysyxvkijemmpdmtnqxwekbpfzs","qqxpxpmemkldghbmbyxpkwgkaykaerhmwwjonrhcsubchs"]\n"usdruypficfbpfbivlrhutcgvyjenlxzeovdyjtgvvfdjzcmikjraspdfp"\n
// @lcpr case=end
*/ | block_comment | pl | /*
* @lc app=leetcode.cn id=1160 lang=java
* @lcpr version=
*
* [1160] 拼写单词
*
* 36/36 cases passed (7 ms)
* Your runtime beats 69.7 % of java submissions
* Your memory usage beats 77.51 % of java submissions (42.9 MB)
*/
// @lcpr-template-start
// @lcpr-template-end
// @lc code=start
class Solution {
public int countCharacters(String[] words, String chars) {
int[] m = new int[26];
for(var c: chars.toCharArray()) m[c - 'a']++;
int ans = 0;
for(var s: words) {
int[] n = new int[26];
for(var c: s.toCharArray()) n[c - 'a']++;
boolean matched = true;
for(int i = 0; i < 26; i++) {
if (n[i] > m[i]) matched = false;
}
if (matched) ans += s.length();
}
return ans;
}
}
// @lc code=end
/*
// @lc<SUF>*/
|
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) {
/*
Stw<SUF>*/
SpringApplication.run(Zajecia7DoktorkiApplication.class, args);
}
}
|
46504_0 | 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 | // Tworzenie grafu
| line_comment | pl | import java.util.*;
public class Main {
public static void main(String[] args) {
// Tw<SUF>
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;
}
}
|
107714_1 | 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 | //TODO już tutaj wywalić timestamp w pomiarze, znajdując pierwsze wystąpienie } | 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);
//TO<SUF>
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;
}
}
}
|
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; //ne<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");//kl<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_3 | /**
* @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 | //3ci komentarz | 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
//wprowadzam zmiane jeszcze raz
//3c<SUF>
//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); // do<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_7 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package 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 | //czyści tabelę
| 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);
//Wstawia do bazy nową osobę
void create(Osoba osoba);
//Aktualizuje osobę
void update(Osoba osoba);
//Usuwa osobę
void delete(Osoba osoba);
//cz<SUF>
void clearTable();
}
|
172890_0 | 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 | //wchodzimy na jsos po ciastka | 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 {
//wc<SUF>
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();
}
}
|
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 {
/*
Stw<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_5 | 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 | // w y jest x zeby obraz nie byl "zgnieciony" tylko rowny we wszystkich osiach, inaczej okno musialoby byc kwadratowe | line_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 <SUF>
}
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);
}
}
}
|
16340_2 |
package testandexceptions;
import static org.junit.Assert.assertEquals;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.junit.Test;
/** klasa testujaca FileInputAdapter.
* @author Mateusz Ratajczyk
*/
public class TestFileInputAdapter {
/** Zmienna do przechowywania kolumny timestamp (czas zdarzenia). */
private Timestamp[] timestamp = null;
/** Zmienna do przechowywania kolumny loglevel (typ zdarzenia). */
private String[] loglevel = null;
/** Zmienna do przechowywania kolumny details (opis zdarzenia). */
private String[] details = null;
/** Zmienna do przechowywania kolejnych spacji w linii z loga. */
private String[] parts;
// Testy akceptacyjne - "czarnoskrzynkowe":
// Naprawiono metode createEvents()
//
// Podczas testow znaleziono blad : if (timestamp[i] == null) { break; }
// Powodowalo to, ze nie wszystkie Zdarzenia byly dodawane,
// zamiast 32 zdarzen (z 38 linii loga) dodalo jedynie 18.
// Zamieniono ta linijke na if (timestamp[i] != null) { ... }
// i metoda dodawala 32 zdarzenia z 38 linii loga
// (poprawnie, 6 linii bylo pustych)
/** metoda testujaca
* sprawdza czy poprawnie wycina kolumne Timestamp.
*/
@Test
public final void testTimestamp1() {
timestamp = new Timestamp[1];
parts = getLog1().split(" "); //wyszukiwanie spacji
for (int i = 0; i < 1; ++i) {
/** Format czasu zdarzenia. */
DateFormat df = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS");
Date tmp = null;
try {
tmp = (Date) df.parse((getLog1().substring(1,
0 + parts[0].length() - 1)));
} catch (ParseException e) {
e.printStackTrace();
}
timestamp[i] = new Timestamp(tmp.getTime());
}
assertEquals("Wartosci sa rowne ", timestamp[0], getTimestamp1());
}
/** metoda testujaca
* sprawdza czy poprawnie wycina kolumne Timestamp.
*/
@Test
public final void testTimestamp2() {
timestamp = new Timestamp[1];
parts = getLog2().split(" "); //wyszukiwanie spacji
for (int i = 0; i < 1; ++i) {
/** Format czasu zdarzenia. */
DateFormat df = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS");
Date tmp = null;
try {
tmp = (Date) df.parse((getLog2().substring(1,
0 + parts[0].length() - 1)));
} catch (ParseException e) {
e.printStackTrace();
}
timestamp[i] = new Timestamp(tmp.getTime());
}
assertEquals("Wartosci sa rowne ", timestamp[0], getTimestamp2());
}
/**
* metoda testujaca.
* sprawdza czy poprawnie wycina kolumne loglevel.
*/
@Test
public final void testLogLevel1() {
loglevel = new String[1];
parts = getLog1().split(" "); //wyszukiwanie spacji
for (int i = 0; i < 1; ++i) {
loglevel[i] = getLog1().substring(parts[0].length() + 1,
parts[0].length() + 1 + parts[1].length());
}
assertEquals("Wartosci sa rowne ", loglevel[0], getLogLevel1());
}
/** metoda testujaca
* sprawdza czy poprawnie wycina kolumne loglevel.
*/
@Test
public final void testLogLevel2() {
loglevel = new String[1];
parts = getLog2().split(" "); //wyszukiwanie spacji
for (int i = 0; i < 1; ++i) {
loglevel[i] = getLog2().substring(parts[0].length() + 1,
parts[0].length() + 1 + parts[1].length());
}
assertEquals("Wartosci sa rowne ", loglevel[0], getLogLevel2());
}
/** metoda testujaca
* sprawdza czy poprawnie wycina kolumne details.
*/
@Test
public final void testDetails1() {
details = new String[1];
parts = getLog1().split(" "); //wyszukiwanie spacji
for (int i = 0; i < 1; ++i) {
details[i] = getLog1().substring(parts[0].length()
+ parts[1].length() + 1 + 1 + 1,
getLog1().length());
}
assertEquals("Wartosci sa rowne ", details[0], getDetails1());
}
/** metoda testujaca
* sprawdza czy poprawnie wycina kolumne details.
*/
@Test
public final void testDetails2() {
details = new String[1];
parts = getLog2().split(" "); //wyszukiwanie spacji
for (int i = 0; i < 1; ++i) {
details[i] = getLog2().substring(parts[0].length()
+ parts[1].length() + 1 + 1 + 1,
getLog2().length());
}
assertEquals("Wartosci sa rowne ", details[0], getDetails2());
}
/** metoda zwracajaca 1 linijke z loga.
* @return linijka z loga
*/
public final String getLog1() {
return "(2014-05-22T07:24:45.0813) INFO"
+ " [is.iWeb.sentinel.logic.business."
+ "Configurator.log(Configurator.java:201)]"
+ " (Thread-379544) AO sn=CPE12 Value OK :"
+ "Device.ManagementServer."
+ "ConnectionRequestUsername "
+ " user==user";
}
/** metoda zwracajaca 1 linijke z loga.
* @return linijka z loga
*/
public final String getLog2() {
return "(2014-05-22T07:24:45.0863) INFO "
+ " [org.jboss.stdio.AbstractLoggingWriter."
+ "write(AbstractLoggingWriter.java:71)]"
+ " (default task-54) URI null";
}
/** metoda zwracajaca sparsowany Timestamp.
* @return Timestamp string
*/
public final Timestamp getTimestamp1() {
String tmp = "2014-05-22T07:24:45.0813";
/** Format czasu zdarzenia. */
DateFormat df = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS");
Date tmpdata = null;
try {
tmpdata = (Date) df.parse(tmp);
} catch (ParseException e) {
e.printStackTrace();
}
Timestamp time = new Timestamp(tmpdata.getTime());
return time;
}
/** metoda zwracajaca sparsowany Timestamp.
* @return Timestamp string
*/
public final Timestamp getTimestamp2() {
String tmp = "2014-05-22T07:24:45.0863";
/** Format czasu zdarzenia. */
DateFormat df = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS");
Date tmpdata = null;
try {
tmpdata = (Date) df.parse(tmp);
} catch (ParseException e) {
e.printStackTrace();
}
Timestamp time = new Timestamp(tmpdata.getTime());
return time;
}
/** metoda zwracajaca "INFO".
* @return "INFO" string
*/
public final String getLogLevel1() {
return "INFO";
}
/** metoda zwracajaca "INFO".
* @return "INFO" string
*/
public final String getLogLevel2() {
return "INFO";
}
/** metoda zwracajaca kolumne details.
* @return details string
*/
public final String getDetails1() {
return "[is.iWeb.sentinel.logic.business."
+ "Configurator.log(Configurator.java:201)]"
+ " (Thread-379544) AO sn=CPE12 Value OK :"
+ "Device.ManagementServer."
+ "ConnectionRequestUsername "
+ " user==user";
}
/** metoda zwracajaca kolumne details.
* @return details string
*/
public final String getDetails2() {
return "[org.jboss.stdio.AbstractLoggingWriter."
+ "write(AbstractLoggingWriter.java:71)]"
+ " (default task-54) URI null";
}
} | 201idzb/project | AL/src/testandexceptions/TestFileInputAdapter.java | 2,651 | /** Zmienna do przechowywania kolumny loglevel (typ zdarzenia). */ | block_comment | pl |
package testandexceptions;
import static org.junit.Assert.assertEquals;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.junit.Test;
/** klasa testujaca FileInputAdapter.
* @author Mateusz Ratajczyk
*/
public class TestFileInputAdapter {
/** Zmienna do przechowywania kolumny timestamp (czas zdarzenia). */
private Timestamp[] timestamp = null;
/** Zmi<SUF>*/
private String[] loglevel = null;
/** Zmienna do przechowywania kolumny details (opis zdarzenia). */
private String[] details = null;
/** Zmienna do przechowywania kolejnych spacji w linii z loga. */
private String[] parts;
// Testy akceptacyjne - "czarnoskrzynkowe":
// Naprawiono metode createEvents()
//
// Podczas testow znaleziono blad : if (timestamp[i] == null) { break; }
// Powodowalo to, ze nie wszystkie Zdarzenia byly dodawane,
// zamiast 32 zdarzen (z 38 linii loga) dodalo jedynie 18.
// Zamieniono ta linijke na if (timestamp[i] != null) { ... }
// i metoda dodawala 32 zdarzenia z 38 linii loga
// (poprawnie, 6 linii bylo pustych)
/** metoda testujaca
* sprawdza czy poprawnie wycina kolumne Timestamp.
*/
@Test
public final void testTimestamp1() {
timestamp = new Timestamp[1];
parts = getLog1().split(" "); //wyszukiwanie spacji
for (int i = 0; i < 1; ++i) {
/** Format czasu zdarzenia. */
DateFormat df = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS");
Date tmp = null;
try {
tmp = (Date) df.parse((getLog1().substring(1,
0 + parts[0].length() - 1)));
} catch (ParseException e) {
e.printStackTrace();
}
timestamp[i] = new Timestamp(tmp.getTime());
}
assertEquals("Wartosci sa rowne ", timestamp[0], getTimestamp1());
}
/** metoda testujaca
* sprawdza czy poprawnie wycina kolumne Timestamp.
*/
@Test
public final void testTimestamp2() {
timestamp = new Timestamp[1];
parts = getLog2().split(" "); //wyszukiwanie spacji
for (int i = 0; i < 1; ++i) {
/** Format czasu zdarzenia. */
DateFormat df = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS");
Date tmp = null;
try {
tmp = (Date) df.parse((getLog2().substring(1,
0 + parts[0].length() - 1)));
} catch (ParseException e) {
e.printStackTrace();
}
timestamp[i] = new Timestamp(tmp.getTime());
}
assertEquals("Wartosci sa rowne ", timestamp[0], getTimestamp2());
}
/**
* metoda testujaca.
* sprawdza czy poprawnie wycina kolumne loglevel.
*/
@Test
public final void testLogLevel1() {
loglevel = new String[1];
parts = getLog1().split(" "); //wyszukiwanie spacji
for (int i = 0; i < 1; ++i) {
loglevel[i] = getLog1().substring(parts[0].length() + 1,
parts[0].length() + 1 + parts[1].length());
}
assertEquals("Wartosci sa rowne ", loglevel[0], getLogLevel1());
}
/** metoda testujaca
* sprawdza czy poprawnie wycina kolumne loglevel.
*/
@Test
public final void testLogLevel2() {
loglevel = new String[1];
parts = getLog2().split(" "); //wyszukiwanie spacji
for (int i = 0; i < 1; ++i) {
loglevel[i] = getLog2().substring(parts[0].length() + 1,
parts[0].length() + 1 + parts[1].length());
}
assertEquals("Wartosci sa rowne ", loglevel[0], getLogLevel2());
}
/** metoda testujaca
* sprawdza czy poprawnie wycina kolumne details.
*/
@Test
public final void testDetails1() {
details = new String[1];
parts = getLog1().split(" "); //wyszukiwanie spacji
for (int i = 0; i < 1; ++i) {
details[i] = getLog1().substring(parts[0].length()
+ parts[1].length() + 1 + 1 + 1,
getLog1().length());
}
assertEquals("Wartosci sa rowne ", details[0], getDetails1());
}
/** metoda testujaca
* sprawdza czy poprawnie wycina kolumne details.
*/
@Test
public final void testDetails2() {
details = new String[1];
parts = getLog2().split(" "); //wyszukiwanie spacji
for (int i = 0; i < 1; ++i) {
details[i] = getLog2().substring(parts[0].length()
+ parts[1].length() + 1 + 1 + 1,
getLog2().length());
}
assertEquals("Wartosci sa rowne ", details[0], getDetails2());
}
/** metoda zwracajaca 1 linijke z loga.
* @return linijka z loga
*/
public final String getLog1() {
return "(2014-05-22T07:24:45.0813) INFO"
+ " [is.iWeb.sentinel.logic.business."
+ "Configurator.log(Configurator.java:201)]"
+ " (Thread-379544) AO sn=CPE12 Value OK :"
+ "Device.ManagementServer."
+ "ConnectionRequestUsername "
+ " user==user";
}
/** metoda zwracajaca 1 linijke z loga.
* @return linijka z loga
*/
public final String getLog2() {
return "(2014-05-22T07:24:45.0863) INFO "
+ " [org.jboss.stdio.AbstractLoggingWriter."
+ "write(AbstractLoggingWriter.java:71)]"
+ " (default task-54) URI null";
}
/** metoda zwracajaca sparsowany Timestamp.
* @return Timestamp string
*/
public final Timestamp getTimestamp1() {
String tmp = "2014-05-22T07:24:45.0813";
/** Format czasu zdarzenia. */
DateFormat df = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS");
Date tmpdata = null;
try {
tmpdata = (Date) df.parse(tmp);
} catch (ParseException e) {
e.printStackTrace();
}
Timestamp time = new Timestamp(tmpdata.getTime());
return time;
}
/** metoda zwracajaca sparsowany Timestamp.
* @return Timestamp string
*/
public final Timestamp getTimestamp2() {
String tmp = "2014-05-22T07:24:45.0863";
/** Format czasu zdarzenia. */
DateFormat df = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS");
Date tmpdata = null;
try {
tmpdata = (Date) df.parse(tmp);
} catch (ParseException e) {
e.printStackTrace();
}
Timestamp time = new Timestamp(tmpdata.getTime());
return time;
}
/** metoda zwracajaca "INFO".
* @return "INFO" string
*/
public final String getLogLevel1() {
return "INFO";
}
/** metoda zwracajaca "INFO".
* @return "INFO" string
*/
public final String getLogLevel2() {
return "INFO";
}
/** metoda zwracajaca kolumne details.
* @return details string
*/
public final String getDetails1() {
return "[is.iWeb.sentinel.logic.business."
+ "Configurator.log(Configurator.java:201)]"
+ " (Thread-379544) AO sn=CPE12 Value OK :"
+ "Device.ManagementServer."
+ "ConnectionRequestUsername "
+ " user==user";
}
/** metoda zwracajaca kolumne details.
* @return details string
*/
public final String getDetails2() {
return "[org.jboss.stdio.AbstractLoggingWriter."
+ "write(AbstractLoggingWriter.java:71)]"
+ " (default task-54) URI null";
}
} |
27148_0 | import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class PMO_Airlock implements AirlockInterface, PMO_Testable {
private AtomicBoolean inUse = new AtomicBoolean();
private AtomicReference<DoorState> internalDoor = new AtomicReference<>();
private AtomicReference<DoorState> externalDoor = new AtomicReference<>();
private AtomicReference<CargoInterface> cargoSpace = new AtomicReference<>();
private AtomicReference<CargoSpaceState> cargoSpaceState = new AtomicReference<>();
private BlockingQueue<DelayObject> queue = new DelayQueue<>();
private int size;
private EventsListenerInterface evlis;
private String airlockDescription;
private AtomicInteger correctTransfersCounter;
private Set<CargoInterface> transferedCargoHolder; // identyfikatory przekazanych ladunkow - globalnie
private List<CargoInterface> cargoTransferHistory; // historia pracy sluzy
private PMO_TestThreadsKeeper threadsKeeper; // lista wlasnych watkow
private AtomicBoolean blockCommunication; // blokada komunikacji
private Thread queueRunnerThread; // watek odpowiedzialny za obsluge kolejki
private PMO_Cargo cargo2add; // cargo do dodania "w locie" (w trakcie wyprowadzania poprzedniego cargo)
private AtomicBoolean cargoTransfered = new AtomicBoolean(false); // potwierdzenie dodania dodatkowej paczki
private AtomicBoolean cargoTransfered2Test = new AtomicBoolean(false);
private MoonBaseInterface base;
private AtomicBoolean testOKFlag = new AtomicBoolean(true);
{
internalDoor.set(DoorState.CLOSED);
externalDoor.set(DoorState.CLOSED);
cargoSpaceState.set(CargoSpaceState.EMPTY);
inUse.set(false);
cargoSpace.set(null);
cargoTransferHistory = Collections.synchronizedList(new ArrayList<>());
queueRunnerThread = PMO_ThreadsHelper.startThread(new Runnable() {
@Override
public void run() {
DelayObject dob = null;
while (true) {
try {
PMO_Log.log("Oczekiwanie na obiekt w kolejce");
dob = queue.take();
PMO_Log.log("Z kolejki odebrano obiekt");
} catch (InterruptedException e) {
e.printStackTrace();
}
if (dob != null)
dob.run();
}
}
});
}
@Override
public boolean isOK() {
return testOKFlag.get();
}
private void addThreadToThreadsKeeper() {
if (threadsKeeper != null) {
threadsKeeper.addThread();
}
}
private void removeThreadFromThreadsKeeper() {
if (threadsKeeper != null)
threadsKeeper.removeThread();
}
public void setThreadsKeeper(PMO_TestThreadsKeeper threadsKeeper) {
this.threadsKeeper = threadsKeeper;
threadsKeeper.addThread(queueRunnerThread);
}
public void setCorrectTransfersCounter(AtomicInteger correctTransfersCounter) {
this.correctTransfersCounter = correctTransfersCounter;
}
public void setBlockCommunicationFlag(AtomicBoolean blockCommunication) {
this.blockCommunication = blockCommunication;
}
public void setTransferedCargoHolder(Set<CargoInterface> set) {
transferedCargoHolder = set;
}
public void blockCommunicationIfNecessary() {
if (blockCommunication == null)
return;
if (blockCommunication.get()) {
PMO_ThreadsHelper.wait(blockCommunication);
}
}
public void setMoonBaseInterface(MoonBaseInterface base) {
this.base = base;
}
public void setCargo2Add(PMO_Cargo cargo) {
cargo2add = cargo;
}
public PMO_Airlock(String name, int size) {
this.size = size;
airlockDescription = "Sluza " + name + " size = " + size + " > ";
}
private void log(String txt) {
PMO_Log.log(airlockDescription + txt);
}
private void error(String txt) {
log(txt);
PMO_CommonErrorLog.error(airlockDescription + txt);
testOKFlag.set(false);
}
private void criticalError(String txt) {
error(txt);
PMO_CommonErrorLog.criticalMistake();
}
// stan drzwi
private enum DoorState {
CLOSED {
@Override
DoorState nextCorrectState() {
return OPENED;
}
},
OPENED {
@Override
DoorState nextCorrectState() {
return CLOSED;
}
};
abstract DoorState nextCorrectState();
}
enum CargoSpaceState {
EMPTY, FULL;
}
private class DelayObject implements Delayed, Runnable {
private long startAt;
private Runnable code2run;
AirlockInterface.Event event2send;
public DelayObject(Runnable code2run, AirlockInterface.Event event2send, long delay) {
startAt = System.currentTimeMillis() + delay;
this.code2run = code2run;
this.event2send = event2send;
}
@Override
public void run() {
if (code2run != null)
code2run.run();
unsetAirlockInUse();
PMO_ThreadsHelper.startThread(() -> {
addThreadToThreadsKeeper();
if (evlis == null) {
error("Nie zarejestrowano EventsListener-a");
} else {
blockCommunicationIfNecessary();
log("Wysylamy do Listenera zdarzenie " + event2send );
evlis.newAirlockEvent(event2send);
}
removeThreadFromThreadsKeeper();
});
}
@Override
public int compareTo(Delayed o) {
if (this.startAt < ((DelayObject) o).startAt) {
return -1;
}
if (this.startAt > ((DelayObject) o).startAt) {
return 1;
}
return 0;
}
@Override
public long getDelay(TimeUnit unit) {
long diff = startAt - System.currentTimeMillis();
return unit.convert(diff, TimeUnit.MILLISECONDS);
}
}
/**
* Metoda generuje obiekt i umieszcza go w kolejce
*
* @param code2run
* kod do wykonania po uplywie opoznienia
* @param event2send
* zdarzenie do przekazanie obiektowi nasluchujacemu
* @param delay
* opoznienie obiektu
*/
private void delayObject2queue(Runnable code2run, AirlockInterface.Event event2send, long delay) {
try {
queue.put(new DelayObject(code2run, event2send, delay));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// sluza przestawiana w stan w-uzyciu
private boolean setAirlockInUse() {
boolean changed = inUse.compareAndSet(false, true);
if (!changed) {
log("Proba zmiany stanu na w-uzyciu, ale taki stan juz stwierdzono");
criticalError("Blad: przed zakonczeniem poprzedniego zlecenia wyslano kolejne.");
} else {
log("Zmiana stanu sluzy na w-uzyciu");
}
return changed;
}
// sluza przestawiana w stan w-spoczynku
private boolean unsetAirlockInUse() {
boolean changed = inUse.compareAndSet(true, false);
if (!changed) {
log("Proba zmiany stanu na w-spoczynku, ale taki stan juz stwierdzono");
criticalError("Blad: operacje na jednej sluzie nakladaja sie na siebie.");
} else {
log("Zmiana stanu sluzy na w-spoczynku");
}
return changed;
}
private void airlockUnsealed() {
log("Sssssssssssssssssss... to syczy uciekajace powietrze...");
criticalError("Wykryto jednoczesne otwarcie drzwi sluzy.");
}
private void bothDoorsOpenedTest() {
boolean result = (internalDoor.get() == DoorState.OPENED) && (externalDoor.get() == DoorState.OPENED);
if (result)
airlockUnsealed();
}
private void otherDoorOpenedTest(AtomicReference<DoorState> door) {
boolean result = door.get() == DoorState.OPENED;
if (result)
airlockUnsealed();
}
private String getDoorsName(AtomicReference<DoorState> door) {
return (door == internalDoor) ? "internal" : "external";
}
private void changeDoorState(AtomicReference<DoorState> doors, DoorState from, DoorState to) {
DoorState state = doors.get();
String doorsName = getDoorsName(doors);
if (!doors.compareAndSet(from, to)) {
log("Zmiana stanu drzwi " + doorsName + " z " + from + " na " + to + " zakonczona niepowodzeniem.");
criticalError("Drzwi " + doorsName + " powinny byc w stanie " + from
+ " a nie sa. Odczytany przed momentem stan to " + state);
} else {
log("Zmiana stanu drzwi " + doorsName + " z " + from + " na " + to);
}
}
@Override
public void openInternalAirtightDoors() {
log("Zlecono openInternalAirtightDoors");
openAirtightDoor(internalDoor, externalDoor, AirlockInterface.Event.INTERNAL_AIRTIGHT_DOORS_OPENED);
}
@Override
public void openExternalAirtightDoors() {
log("Zlecono openExternalAirtightDoors");
openAirtightDoor(externalDoor, internalDoor, AirlockInterface.Event.EXTERNAL_AIRTIGHT_DOORS_OPENED);
}
private void openAirtightDoor(AtomicReference<DoorState> door, AtomicReference<DoorState> otherDoor,
AirlockInterface.Event event) {
setAirlockInUse();
otherDoorOpenedTest(otherDoor);
DoorState state = door.get();
String doorName = getDoorsName(door);
if (state == DoorState.OPENED) {
log("WARNING: zlecono otwarcie otwartych juz drzwi " + doorName);
delayObject2queue(null, event, PMO_Consts.DOOR_OPENING_DELAY_SHORT);
} else if (state == DoorState.CLOSED) {
log("Stan drzwi " + doorName + " - CLOSED - OK - uruchamiam naped drzwi");
delayObject2queue(new Runnable() {
public void run() {
addCargo2MoonBaseSystem();
changeDoorState(door, DoorState.CLOSED, DoorState.OPENED);
bothDoorsOpenedTest();
}
}, event, PMO_Consts.DOOR_OPENING_DELAY);
}
}
@Override
public void closeInternalAirtightDoors() {
log("Zlecono closeInternalAirtightDoors");
closeAirtightDoor(internalDoor, externalDoor, AirlockInterface.Event.INTERNAL_AIRTIGHT_DOORS_CLOSED);
}
@Override
public void closeExternalAirtightDoors() {
log("Zlecono closeExternalAirtightDoors");
closeAirtightDoor(externalDoor, internalDoor, AirlockInterface.Event.EXTERNAL_AIRTIGHT_DOORS_CLOSED);
}
private void closeAirtightDoor(AtomicReference<DoorState> door, AtomicReference<DoorState> otherDoor,
AirlockInterface.Event event) {
setAirlockInUse();
bothDoorsOpenedTest();
DoorState state = door.get();
if (state == DoorState.CLOSED) {
log("WARNING: zlecono zamkniecie zamknietych juz drzwi");
delayObject2queue(null, event, PMO_Consts.DOOR_CLOSING_DELAY_SHORT);
} else if (state == DoorState.OPENED) {
log("Stan drzwi - OPENED - OK - uruchamiam naped drzwi");
delayObject2queue(new Runnable() {
public void run() {
otherDoorOpenedTest(otherDoor);
changeDoorState(door, DoorState.OPENED, DoorState.CLOSED);
}
}, event, PMO_Consts.DOOR_CLOSING_DELAY);
}
}
@Override
public void insertCargo(CargoInterface cargo) {
log("Zlecono insertCargo. " + cargo);
setAirlockInUse();
bothDoorsOpenedTest();
if (cargo == null) {
criticalError("Zamiast ladunku do sluzy dotarl null");
}
if (cargo.getDirection() == Direction.INSIDE) {
if (externalDoor.get() != DoorState.OPENED) {
criticalError(cargo + " jest na zewnatrz, ale drzwi zewnetrzne sa zamkniete");
}
if (internalDoor.get() != DoorState.CLOSED) {
criticalError(cargo + " jest na zewnatrz, ale to drzwi wnetrzne sa otwarte");
}
} else {
if (internalDoor.get() != DoorState.OPENED) {
criticalError(cargo + " jest wewnatrz, ale drzwi wnetrzne sa zamkniete");
}
if (externalDoor.get() != DoorState.CLOSED) {
criticalError(cargo + " jest wewnatrz, ale to drzwi zewnetrzne sa otwarte");
}
}
if (cargo.getSize() > size) {
criticalError("Zlecono umieszczenie w sluzie " + cargo + ", ale sluza jest zbyt mala");
}
if (cargoTransfered2Test.get()) {
log("Sluza wczesniej dodala dodatkowy priorytetowy ladunek - sprawdzamy, czy to on teraz dotarl");
if (cargo != cargo2add) {
error("BLAD: system nie respektuje prirytetow. Do sluzy powinna dotrzec inna paczka");
error("Oczekiwano: " + cargo2add + ", a dotarl " + cargo);
} else {
log("OK: Dotarl priorytetowy ladunek");
PMO_SystemOutRedirect.println("OK: Dotarl priorytetowy ladunek");
}
cargoTransfered2Test.set(false); // kolejne sprawdzenie nie ma sensu
}
cargoTransferHistory.add(cargo);
delayObject2queue(() -> {
if (cargoSpaceState.get() != CargoSpaceState.EMPTY) {
criticalError("Zlecono umieszczenie w sluzie " + cargo + ", ale sluza jest juz zajeta");
}
checkIfAlreadyTransfered(cargo);
cargoSpace.set(cargo);
}, AirlockInterface.Event.CARGO_INSIDE, PMO_Consts.CARGO_MOVE_DELAY);
}
private void checkIfAlreadyTransfered(CargoInterface cargo) {
if (transferedCargoHolder == null)
return;
if (transferedCargoHolder.contains(cargo)) {
criticalError(cargo + " juz wczesniej zostal przeslany");
}
}
@Override
public void ejectCargo() {
log("Zlecono ejectCargo.");
setAirlockInUse();
CargoInterface cargo = cargoSpace.get();
if (cargo == null) {
error("WARINIG: Zlecono ejectCargo, ale w sluzie nie ma niczego...");
delayObject2queue(null, AirlockInterface.Event.AIRLOCK_EMPTY, PMO_Consts.CARGO_MOVE_DELAY_SHORT);
} else {
log("Zlecono ejectCargo. W sluzie jest " + cargo);
}
boolean ok = false;
if (cargo.getDirection() == Direction.INSIDE) {
if (internalDoor.get() == DoorState.OPENED) {
ok = true;
}
} else {
if (externalDoor.get() == DoorState.OPENED) {
ok = true;
}
}
if (ok) {
log(cargo + " jest przekazywany w dobrym kierunku");
delayObject2queue(() -> {
addCargoToRegister(cargo);
int counter = correctTransfersCounter.incrementAndGet();
log(cargo + " opuszcza sluze, jest to " + counter + " transfer cargo");
}, AirlockInterface.Event.AIRLOCK_EMPTY, PMO_Consts.CARGO_MOVE_DELAY);
} else {
log("WARNING: " + cargo + " przekazywany jest w zlym kierunku");
delayObject2queue(() -> {
log(cargo + " opuszcza sluze, ale porusza sie w zla strone");
}, AirlockInterface.Event.AIRLOCK_EMPTY, PMO_Consts.CARGO_MOVE_DELAY);
}
}
private void addCargo2MoonBaseSystem() {
if (cargo2add != null) {
if (!cargoTransfered.get()) {
// ladunku jeszcze nie nadano
CyclicBarrier cb = new CyclicBarrier(2);
PMO_ThreadsHelper.startThread(() -> {
base.cargoTransfer(cargo2add, cargo2add.getDirection());
log("Do systemu dodano dodatkowa paczke " + cargo2add);
cargoTransfered.set(true);
// ladunek przekazany - test moze byc wykonany
cargoTransfered2Test.set(true);
PMO_ThreadsHelper.wait(cb);
});
PMO_ThreadsHelper.wait(cb);
}
}
}
private void addCargoToRegister(CargoInterface cargo) {
assert transferedCargoHolder != null : "zbior przechowujacy przekazane ladunki nie zostal ustawiony";
if (transferedCargoHolder == null)
return;
transferedCargoHolder.add(cargo);
}
@Override
public int getSize() {
return size;
}
@Override
public void setEventsListener(EventsListenerInterface eventsListener) {
evlis = eventsListener;
}
}
| 204Constie/baseonmars | src/PMO_Airlock.java | 5,864 | // identyfikatory przekazanych ladunkow - globalnie | line_comment | pl | import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class PMO_Airlock implements AirlockInterface, PMO_Testable {
private AtomicBoolean inUse = new AtomicBoolean();
private AtomicReference<DoorState> internalDoor = new AtomicReference<>();
private AtomicReference<DoorState> externalDoor = new AtomicReference<>();
private AtomicReference<CargoInterface> cargoSpace = new AtomicReference<>();
private AtomicReference<CargoSpaceState> cargoSpaceState = new AtomicReference<>();
private BlockingQueue<DelayObject> queue = new DelayQueue<>();
private int size;
private EventsListenerInterface evlis;
private String airlockDescription;
private AtomicInteger correctTransfersCounter;
private Set<CargoInterface> transferedCargoHolder; // id<SUF>
private List<CargoInterface> cargoTransferHistory; // historia pracy sluzy
private PMO_TestThreadsKeeper threadsKeeper; // lista wlasnych watkow
private AtomicBoolean blockCommunication; // blokada komunikacji
private Thread queueRunnerThread; // watek odpowiedzialny za obsluge kolejki
private PMO_Cargo cargo2add; // cargo do dodania "w locie" (w trakcie wyprowadzania poprzedniego cargo)
private AtomicBoolean cargoTransfered = new AtomicBoolean(false); // potwierdzenie dodania dodatkowej paczki
private AtomicBoolean cargoTransfered2Test = new AtomicBoolean(false);
private MoonBaseInterface base;
private AtomicBoolean testOKFlag = new AtomicBoolean(true);
{
internalDoor.set(DoorState.CLOSED);
externalDoor.set(DoorState.CLOSED);
cargoSpaceState.set(CargoSpaceState.EMPTY);
inUse.set(false);
cargoSpace.set(null);
cargoTransferHistory = Collections.synchronizedList(new ArrayList<>());
queueRunnerThread = PMO_ThreadsHelper.startThread(new Runnable() {
@Override
public void run() {
DelayObject dob = null;
while (true) {
try {
PMO_Log.log("Oczekiwanie na obiekt w kolejce");
dob = queue.take();
PMO_Log.log("Z kolejki odebrano obiekt");
} catch (InterruptedException e) {
e.printStackTrace();
}
if (dob != null)
dob.run();
}
}
});
}
@Override
public boolean isOK() {
return testOKFlag.get();
}
private void addThreadToThreadsKeeper() {
if (threadsKeeper != null) {
threadsKeeper.addThread();
}
}
private void removeThreadFromThreadsKeeper() {
if (threadsKeeper != null)
threadsKeeper.removeThread();
}
public void setThreadsKeeper(PMO_TestThreadsKeeper threadsKeeper) {
this.threadsKeeper = threadsKeeper;
threadsKeeper.addThread(queueRunnerThread);
}
public void setCorrectTransfersCounter(AtomicInteger correctTransfersCounter) {
this.correctTransfersCounter = correctTransfersCounter;
}
public void setBlockCommunicationFlag(AtomicBoolean blockCommunication) {
this.blockCommunication = blockCommunication;
}
public void setTransferedCargoHolder(Set<CargoInterface> set) {
transferedCargoHolder = set;
}
public void blockCommunicationIfNecessary() {
if (blockCommunication == null)
return;
if (blockCommunication.get()) {
PMO_ThreadsHelper.wait(blockCommunication);
}
}
public void setMoonBaseInterface(MoonBaseInterface base) {
this.base = base;
}
public void setCargo2Add(PMO_Cargo cargo) {
cargo2add = cargo;
}
public PMO_Airlock(String name, int size) {
this.size = size;
airlockDescription = "Sluza " + name + " size = " + size + " > ";
}
private void log(String txt) {
PMO_Log.log(airlockDescription + txt);
}
private void error(String txt) {
log(txt);
PMO_CommonErrorLog.error(airlockDescription + txt);
testOKFlag.set(false);
}
private void criticalError(String txt) {
error(txt);
PMO_CommonErrorLog.criticalMistake();
}
// stan drzwi
private enum DoorState {
CLOSED {
@Override
DoorState nextCorrectState() {
return OPENED;
}
},
OPENED {
@Override
DoorState nextCorrectState() {
return CLOSED;
}
};
abstract DoorState nextCorrectState();
}
enum CargoSpaceState {
EMPTY, FULL;
}
private class DelayObject implements Delayed, Runnable {
private long startAt;
private Runnable code2run;
AirlockInterface.Event event2send;
public DelayObject(Runnable code2run, AirlockInterface.Event event2send, long delay) {
startAt = System.currentTimeMillis() + delay;
this.code2run = code2run;
this.event2send = event2send;
}
@Override
public void run() {
if (code2run != null)
code2run.run();
unsetAirlockInUse();
PMO_ThreadsHelper.startThread(() -> {
addThreadToThreadsKeeper();
if (evlis == null) {
error("Nie zarejestrowano EventsListener-a");
} else {
blockCommunicationIfNecessary();
log("Wysylamy do Listenera zdarzenie " + event2send );
evlis.newAirlockEvent(event2send);
}
removeThreadFromThreadsKeeper();
});
}
@Override
public int compareTo(Delayed o) {
if (this.startAt < ((DelayObject) o).startAt) {
return -1;
}
if (this.startAt > ((DelayObject) o).startAt) {
return 1;
}
return 0;
}
@Override
public long getDelay(TimeUnit unit) {
long diff = startAt - System.currentTimeMillis();
return unit.convert(diff, TimeUnit.MILLISECONDS);
}
}
/**
* Metoda generuje obiekt i umieszcza go w kolejce
*
* @param code2run
* kod do wykonania po uplywie opoznienia
* @param event2send
* zdarzenie do przekazanie obiektowi nasluchujacemu
* @param delay
* opoznienie obiektu
*/
private void delayObject2queue(Runnable code2run, AirlockInterface.Event event2send, long delay) {
try {
queue.put(new DelayObject(code2run, event2send, delay));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// sluza przestawiana w stan w-uzyciu
private boolean setAirlockInUse() {
boolean changed = inUse.compareAndSet(false, true);
if (!changed) {
log("Proba zmiany stanu na w-uzyciu, ale taki stan juz stwierdzono");
criticalError("Blad: przed zakonczeniem poprzedniego zlecenia wyslano kolejne.");
} else {
log("Zmiana stanu sluzy na w-uzyciu");
}
return changed;
}
// sluza przestawiana w stan w-spoczynku
private boolean unsetAirlockInUse() {
boolean changed = inUse.compareAndSet(true, false);
if (!changed) {
log("Proba zmiany stanu na w-spoczynku, ale taki stan juz stwierdzono");
criticalError("Blad: operacje na jednej sluzie nakladaja sie na siebie.");
} else {
log("Zmiana stanu sluzy na w-spoczynku");
}
return changed;
}
private void airlockUnsealed() {
log("Sssssssssssssssssss... to syczy uciekajace powietrze...");
criticalError("Wykryto jednoczesne otwarcie drzwi sluzy.");
}
private void bothDoorsOpenedTest() {
boolean result = (internalDoor.get() == DoorState.OPENED) && (externalDoor.get() == DoorState.OPENED);
if (result)
airlockUnsealed();
}
private void otherDoorOpenedTest(AtomicReference<DoorState> door) {
boolean result = door.get() == DoorState.OPENED;
if (result)
airlockUnsealed();
}
private String getDoorsName(AtomicReference<DoorState> door) {
return (door == internalDoor) ? "internal" : "external";
}
private void changeDoorState(AtomicReference<DoorState> doors, DoorState from, DoorState to) {
DoorState state = doors.get();
String doorsName = getDoorsName(doors);
if (!doors.compareAndSet(from, to)) {
log("Zmiana stanu drzwi " + doorsName + " z " + from + " na " + to + " zakonczona niepowodzeniem.");
criticalError("Drzwi " + doorsName + " powinny byc w stanie " + from
+ " a nie sa. Odczytany przed momentem stan to " + state);
} else {
log("Zmiana stanu drzwi " + doorsName + " z " + from + " na " + to);
}
}
@Override
public void openInternalAirtightDoors() {
log("Zlecono openInternalAirtightDoors");
openAirtightDoor(internalDoor, externalDoor, AirlockInterface.Event.INTERNAL_AIRTIGHT_DOORS_OPENED);
}
@Override
public void openExternalAirtightDoors() {
log("Zlecono openExternalAirtightDoors");
openAirtightDoor(externalDoor, internalDoor, AirlockInterface.Event.EXTERNAL_AIRTIGHT_DOORS_OPENED);
}
private void openAirtightDoor(AtomicReference<DoorState> door, AtomicReference<DoorState> otherDoor,
AirlockInterface.Event event) {
setAirlockInUse();
otherDoorOpenedTest(otherDoor);
DoorState state = door.get();
String doorName = getDoorsName(door);
if (state == DoorState.OPENED) {
log("WARNING: zlecono otwarcie otwartych juz drzwi " + doorName);
delayObject2queue(null, event, PMO_Consts.DOOR_OPENING_DELAY_SHORT);
} else if (state == DoorState.CLOSED) {
log("Stan drzwi " + doorName + " - CLOSED - OK - uruchamiam naped drzwi");
delayObject2queue(new Runnable() {
public void run() {
addCargo2MoonBaseSystem();
changeDoorState(door, DoorState.CLOSED, DoorState.OPENED);
bothDoorsOpenedTest();
}
}, event, PMO_Consts.DOOR_OPENING_DELAY);
}
}
@Override
public void closeInternalAirtightDoors() {
log("Zlecono closeInternalAirtightDoors");
closeAirtightDoor(internalDoor, externalDoor, AirlockInterface.Event.INTERNAL_AIRTIGHT_DOORS_CLOSED);
}
@Override
public void closeExternalAirtightDoors() {
log("Zlecono closeExternalAirtightDoors");
closeAirtightDoor(externalDoor, internalDoor, AirlockInterface.Event.EXTERNAL_AIRTIGHT_DOORS_CLOSED);
}
private void closeAirtightDoor(AtomicReference<DoorState> door, AtomicReference<DoorState> otherDoor,
AirlockInterface.Event event) {
setAirlockInUse();
bothDoorsOpenedTest();
DoorState state = door.get();
if (state == DoorState.CLOSED) {
log("WARNING: zlecono zamkniecie zamknietych juz drzwi");
delayObject2queue(null, event, PMO_Consts.DOOR_CLOSING_DELAY_SHORT);
} else if (state == DoorState.OPENED) {
log("Stan drzwi - OPENED - OK - uruchamiam naped drzwi");
delayObject2queue(new Runnable() {
public void run() {
otherDoorOpenedTest(otherDoor);
changeDoorState(door, DoorState.OPENED, DoorState.CLOSED);
}
}, event, PMO_Consts.DOOR_CLOSING_DELAY);
}
}
@Override
public void insertCargo(CargoInterface cargo) {
log("Zlecono insertCargo. " + cargo);
setAirlockInUse();
bothDoorsOpenedTest();
if (cargo == null) {
criticalError("Zamiast ladunku do sluzy dotarl null");
}
if (cargo.getDirection() == Direction.INSIDE) {
if (externalDoor.get() != DoorState.OPENED) {
criticalError(cargo + " jest na zewnatrz, ale drzwi zewnetrzne sa zamkniete");
}
if (internalDoor.get() != DoorState.CLOSED) {
criticalError(cargo + " jest na zewnatrz, ale to drzwi wnetrzne sa otwarte");
}
} else {
if (internalDoor.get() != DoorState.OPENED) {
criticalError(cargo + " jest wewnatrz, ale drzwi wnetrzne sa zamkniete");
}
if (externalDoor.get() != DoorState.CLOSED) {
criticalError(cargo + " jest wewnatrz, ale to drzwi zewnetrzne sa otwarte");
}
}
if (cargo.getSize() > size) {
criticalError("Zlecono umieszczenie w sluzie " + cargo + ", ale sluza jest zbyt mala");
}
if (cargoTransfered2Test.get()) {
log("Sluza wczesniej dodala dodatkowy priorytetowy ladunek - sprawdzamy, czy to on teraz dotarl");
if (cargo != cargo2add) {
error("BLAD: system nie respektuje prirytetow. Do sluzy powinna dotrzec inna paczka");
error("Oczekiwano: " + cargo2add + ", a dotarl " + cargo);
} else {
log("OK: Dotarl priorytetowy ladunek");
PMO_SystemOutRedirect.println("OK: Dotarl priorytetowy ladunek");
}
cargoTransfered2Test.set(false); // kolejne sprawdzenie nie ma sensu
}
cargoTransferHistory.add(cargo);
delayObject2queue(() -> {
if (cargoSpaceState.get() != CargoSpaceState.EMPTY) {
criticalError("Zlecono umieszczenie w sluzie " + cargo + ", ale sluza jest juz zajeta");
}
checkIfAlreadyTransfered(cargo);
cargoSpace.set(cargo);
}, AirlockInterface.Event.CARGO_INSIDE, PMO_Consts.CARGO_MOVE_DELAY);
}
private void checkIfAlreadyTransfered(CargoInterface cargo) {
if (transferedCargoHolder == null)
return;
if (transferedCargoHolder.contains(cargo)) {
criticalError(cargo + " juz wczesniej zostal przeslany");
}
}
@Override
public void ejectCargo() {
log("Zlecono ejectCargo.");
setAirlockInUse();
CargoInterface cargo = cargoSpace.get();
if (cargo == null) {
error("WARINIG: Zlecono ejectCargo, ale w sluzie nie ma niczego...");
delayObject2queue(null, AirlockInterface.Event.AIRLOCK_EMPTY, PMO_Consts.CARGO_MOVE_DELAY_SHORT);
} else {
log("Zlecono ejectCargo. W sluzie jest " + cargo);
}
boolean ok = false;
if (cargo.getDirection() == Direction.INSIDE) {
if (internalDoor.get() == DoorState.OPENED) {
ok = true;
}
} else {
if (externalDoor.get() == DoorState.OPENED) {
ok = true;
}
}
if (ok) {
log(cargo + " jest przekazywany w dobrym kierunku");
delayObject2queue(() -> {
addCargoToRegister(cargo);
int counter = correctTransfersCounter.incrementAndGet();
log(cargo + " opuszcza sluze, jest to " + counter + " transfer cargo");
}, AirlockInterface.Event.AIRLOCK_EMPTY, PMO_Consts.CARGO_MOVE_DELAY);
} else {
log("WARNING: " + cargo + " przekazywany jest w zlym kierunku");
delayObject2queue(() -> {
log(cargo + " opuszcza sluze, ale porusza sie w zla strone");
}, AirlockInterface.Event.AIRLOCK_EMPTY, PMO_Consts.CARGO_MOVE_DELAY);
}
}
private void addCargo2MoonBaseSystem() {
if (cargo2add != null) {
if (!cargoTransfered.get()) {
// ladunku jeszcze nie nadano
CyclicBarrier cb = new CyclicBarrier(2);
PMO_ThreadsHelper.startThread(() -> {
base.cargoTransfer(cargo2add, cargo2add.getDirection());
log("Do systemu dodano dodatkowa paczke " + cargo2add);
cargoTransfered.set(true);
// ladunek przekazany - test moze byc wykonany
cargoTransfered2Test.set(true);
PMO_ThreadsHelper.wait(cb);
});
PMO_ThreadsHelper.wait(cb);
}
}
}
private void addCargoToRegister(CargoInterface cargo) {
assert transferedCargoHolder != null : "zbior przechowujacy przekazane ladunki nie zostal ustawiony";
if (transferedCargoHolder == null)
return;
transferedCargoHolder.add(cargo);
}
@Override
public int getSize() {
return size;
}
@Override
public void setEventsListener(EventsListenerInterface eventsListener) {
evlis = eventsListener;
}
}
|
35809_2 | import java.awt.geom.Point2D.Double;
import java.util.Collections;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public class PMO_ImageConverter implements ImageConverterInterface, PMO_Testable, PMO_LogSource {
private Set<Integer> framesExpected;
private CyclicBarrier blockConversion;
private PMO_Barrier barrier;
private AtomicInteger threadsLimit;
private PMO_AtomicCounter threadsCounter;
private Random rnd = ThreadLocalRandom.current();
private Set<Integer> framesConverted = Collections.synchronizedSet( new TreeSet<>() );
public int getFramesConverted() {
return framesConverted.size();
}
public void setThreadsLimit( AtomicInteger threadsLimit ) {
this.threadsLimit = threadsLimit;
}
public void setThreadsCounters( PMO_AtomicCounter threadsCounter ) {
this.threadsCounter = threadsCounter;
}
public void setBarrier( PMO_Barrier barrier ) {
this.barrier = barrier;
}
public void setBlockConversionBarrier( CyclicBarrier barrier ) {
blockConversion = barrier;
}
@Override
public Double convert(int frameNumber, int[][] firstImage, int[][] secondImage) {
assert threadsLimit != null;
assert threadsCounter != null;
assert barrier != null;
int threads = threadsCounter.incAndStoreMax();
log("Uruchomiono convert dla frameNumber " + frameNumber + " jako " + threads
+ " wspolbiezny watek obliczeniowy");
if (threads > threadsLimit.get()) {
PMO_CommonErrorLog.error("Blad: Doszlo do przekroczenia limitu zasobow");
PMO_CommonErrorLog.error("Blad: Limit " + threadsLimit.get() + " a zmierzono " + threads);
}
if (!framesConverted.add(frameNumber)) {
PMO_CommonErrorLog.error("Blad: ramka " + frameNumber + " ponownie jest konwertowana");
}
long conversionTime = PMO_Consts.CONVERSION_MIN_TIME + rnd.nextLong() % PMO_Consts.CONVERSION_RANDOM_TIME;
Double result = new Double(PMO_ImageGenerator.convert(firstImage), PMO_ImageGenerator.convert(secondImage));
PMO_TimeHelper.sleep(conversionTime);
log( "Zakonczono konwersje frameNumber " + frameNumber );
// blokada w celu niemal rownoczesnego przekazania roznych wynikow - ifContains
if ( barrier.contains(frameNumber) ) {
barrier.await();
}
// blokada komunikacji z powodu zmiany limitu
PMO_ThreadsHelper.wait(blockConversion);
// koniec pracy convert
threadsCounter.dec();
return result;
}
@Override
public boolean isOK() {
assert framesExpected != null;
AtomicBoolean result = new AtomicBoolean(true);
framesExpected.forEach( (f) -> {
if ( ! framesConverted.contains( f ) ) {
error( "Blad: Oczekiwano wywolania convert dla frameNumber " + f );
result.set( false );
}
});
return result.get();
}
}
| 204Constie/prirdsys | src/PMO_ImageConverter.java | 1,013 | // koniec pracy convert | line_comment | pl | import java.awt.geom.Point2D.Double;
import java.util.Collections;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public class PMO_ImageConverter implements ImageConverterInterface, PMO_Testable, PMO_LogSource {
private Set<Integer> framesExpected;
private CyclicBarrier blockConversion;
private PMO_Barrier barrier;
private AtomicInteger threadsLimit;
private PMO_AtomicCounter threadsCounter;
private Random rnd = ThreadLocalRandom.current();
private Set<Integer> framesConverted = Collections.synchronizedSet( new TreeSet<>() );
public int getFramesConverted() {
return framesConverted.size();
}
public void setThreadsLimit( AtomicInteger threadsLimit ) {
this.threadsLimit = threadsLimit;
}
public void setThreadsCounters( PMO_AtomicCounter threadsCounter ) {
this.threadsCounter = threadsCounter;
}
public void setBarrier( PMO_Barrier barrier ) {
this.barrier = barrier;
}
public void setBlockConversionBarrier( CyclicBarrier barrier ) {
blockConversion = barrier;
}
@Override
public Double convert(int frameNumber, int[][] firstImage, int[][] secondImage) {
assert threadsLimit != null;
assert threadsCounter != null;
assert barrier != null;
int threads = threadsCounter.incAndStoreMax();
log("Uruchomiono convert dla frameNumber " + frameNumber + " jako " + threads
+ " wspolbiezny watek obliczeniowy");
if (threads > threadsLimit.get()) {
PMO_CommonErrorLog.error("Blad: Doszlo do przekroczenia limitu zasobow");
PMO_CommonErrorLog.error("Blad: Limit " + threadsLimit.get() + " a zmierzono " + threads);
}
if (!framesConverted.add(frameNumber)) {
PMO_CommonErrorLog.error("Blad: ramka " + frameNumber + " ponownie jest konwertowana");
}
long conversionTime = PMO_Consts.CONVERSION_MIN_TIME + rnd.nextLong() % PMO_Consts.CONVERSION_RANDOM_TIME;
Double result = new Double(PMO_ImageGenerator.convert(firstImage), PMO_ImageGenerator.convert(secondImage));
PMO_TimeHelper.sleep(conversionTime);
log( "Zakonczono konwersje frameNumber " + frameNumber );
// blokada w celu niemal rownoczesnego przekazania roznych wynikow - ifContains
if ( barrier.contains(frameNumber) ) {
barrier.await();
}
// blokada komunikacji z powodu zmiany limitu
PMO_ThreadsHelper.wait(blockConversion);
// ko<SUF>
threadsCounter.dec();
return result;
}
@Override
public boolean isOK() {
assert framesExpected != null;
AtomicBoolean result = new AtomicBoolean(true);
framesExpected.forEach( (f) -> {
if ( ! framesConverted.contains( f ) ) {
error( "Blad: Oczekiwano wywolania convert dla frameNumber " + f );
result.set( false );
}
});
return result.get();
}
}
|
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");
// ac<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);
}
}
|
9879_1 | package zadanie2;
import java.util.ArrayList;
import java.util.Random;
public class Snail extends Thread {
private int eating_speed;
private int sleeping_time;
public int w;
public int h;
public Snail(int h, int w, int eating_speed, int sleeping_time) {
this.eating_speed = eating_speed;
this.sleeping_time = sleeping_time;
this.w = w;
this.h = h;
}
@Override
public void run() {
while (true) {
while (Map.mapa[h][w].getFood() > 0) {
try {
Map.mapa[h][w].consume(this.eating_speed);
Map.mapaGui[h][w].setBackground(Map.mapa[h][w].kolor);
Map.mapaText[h][w].setText(String.valueOf(Map.mapa[h][w].getFood()));
Thread.sleep(1000);
} catch (Exception e) {
System.out.println(e);
}
}
//tutaj wstawić ifa z wyborem czy idzie spac czy sie rusza
int[] pomoc=chooseNextLeaf();
if (pomoc[0]==-1){
try{
Thread.sleep(this.sleeping_time);
}catch(Exception e){
System.out.println("spanie");
}
}else{
move(pomoc);
}
}
}
// w move trzeba zrobić z voida inta i jesli sie powiedzie to zwraca zero jak nie to 1 i wtedy run zdecyduje czy czeka czy sie rusza
private void move(int[] lokacja) {// dodac to co nizej opisane jesli chooseNL zwraca 0,0
try {
Map.mapa[h][w].take_insect();
Map.mapaGui[h][w].setBackground(Map.mapa[h][w].kolor);
this.h = lokacja[0];
this.w=lokacja[1];
Map.mapa[h][w].give_insect();
Map.mapaGui[h][w].setBackground(Map.mapa[h][w].kolor);
System.out.println("ruch");
Thread.sleep(3000);
} catch (Exception e) {
System.out.println(e);
}
}
//choose naprawiony
private int[] chooseNextLeaf() {
int w=0;
int h=0;
int biggestValue = 0;
ArrayList<int[]> opcje = new ArrayList<>();
ArrayList<int[]> najlepsze = new ArrayList<>();
ArrayList<Integer> sasiedztwo = new ArrayList<>();
for (int i = this.h - 1; i <= this.h + 1; i++) {
for (int j = this.w - 1; j <= this.w + 1; j++) {
try {
if (Map.mapa[i][j].getFood()>=biggestValue && Map.mapa[i][j].has_worm==false) {
biggestValue= Map.mapa[i][j].getFood();
w=j;
h=i;
int[] pomoc={Map.mapa[i][j].getFood(),i,j};
opcje.add(pomoc);
}
sasiedztwo.add(Map.mapa[i][j].getFood());
} catch (Exception e) {System.out.println("nextLeaf");}
}
}
if (biggestValue==0) {// nie ma gdzie się ruszyć
int[] pomoc = {-1, -1};
return pomoc;
}
// losowanie ruchu
for(int[] el:opcje){
if (el[0]==biggestValue) najlepsze.add(el);
}
for (int[] el:najlepsze) System.out.println(el[0]);
if (najlepsze.size()>1){ //losuje jak jest pare opcji
Random srand = new Random();
int[] pomoc = najlepsze.get(srand.nextInt(najlepsze.size()));
int[] tymczas={pomoc[1],pomoc[2]};
return tymczas;
}
else{//jak jest tylko 1 opcja
int[] pomoc = {h, w};
return pomoc;
}
//if biggest =0 to znaczy ze trzeba zaczaekac chwile i jeszcze raz odpalic funkcje
//System.out.println(sasiedztwo);//do testów
//System.out.println(biggestValue+" "+h+" "+w);//do testów
}
} | 213N10/jezykiProgramowaniaIte | lab6/src/zadanie2/Snail.java | 1,285 | // w move trzeba zrobić z voida inta i jesli sie powiedzie to zwraca zero jak nie to 1 i wtedy run zdecyduje czy czeka czy sie rusza | line_comment | pl | package zadanie2;
import java.util.ArrayList;
import java.util.Random;
public class Snail extends Thread {
private int eating_speed;
private int sleeping_time;
public int w;
public int h;
public Snail(int h, int w, int eating_speed, int sleeping_time) {
this.eating_speed = eating_speed;
this.sleeping_time = sleeping_time;
this.w = w;
this.h = h;
}
@Override
public void run() {
while (true) {
while (Map.mapa[h][w].getFood() > 0) {
try {
Map.mapa[h][w].consume(this.eating_speed);
Map.mapaGui[h][w].setBackground(Map.mapa[h][w].kolor);
Map.mapaText[h][w].setText(String.valueOf(Map.mapa[h][w].getFood()));
Thread.sleep(1000);
} catch (Exception e) {
System.out.println(e);
}
}
//tutaj wstawić ifa z wyborem czy idzie spac czy sie rusza
int[] pomoc=chooseNextLeaf();
if (pomoc[0]==-1){
try{
Thread.sleep(this.sleeping_time);
}catch(Exception e){
System.out.println("spanie");
}
}else{
move(pomoc);
}
}
}
// w <SUF>
private void move(int[] lokacja) {// dodac to co nizej opisane jesli chooseNL zwraca 0,0
try {
Map.mapa[h][w].take_insect();
Map.mapaGui[h][w].setBackground(Map.mapa[h][w].kolor);
this.h = lokacja[0];
this.w=lokacja[1];
Map.mapa[h][w].give_insect();
Map.mapaGui[h][w].setBackground(Map.mapa[h][w].kolor);
System.out.println("ruch");
Thread.sleep(3000);
} catch (Exception e) {
System.out.println(e);
}
}
//choose naprawiony
private int[] chooseNextLeaf() {
int w=0;
int h=0;
int biggestValue = 0;
ArrayList<int[]> opcje = new ArrayList<>();
ArrayList<int[]> najlepsze = new ArrayList<>();
ArrayList<Integer> sasiedztwo = new ArrayList<>();
for (int i = this.h - 1; i <= this.h + 1; i++) {
for (int j = this.w - 1; j <= this.w + 1; j++) {
try {
if (Map.mapa[i][j].getFood()>=biggestValue && Map.mapa[i][j].has_worm==false) {
biggestValue= Map.mapa[i][j].getFood();
w=j;
h=i;
int[] pomoc={Map.mapa[i][j].getFood(),i,j};
opcje.add(pomoc);
}
sasiedztwo.add(Map.mapa[i][j].getFood());
} catch (Exception e) {System.out.println("nextLeaf");}
}
}
if (biggestValue==0) {// nie ma gdzie się ruszyć
int[] pomoc = {-1, -1};
return pomoc;
}
// losowanie ruchu
for(int[] el:opcje){
if (el[0]==biggestValue) najlepsze.add(el);
}
for (int[] el:najlepsze) System.out.println(el[0]);
if (najlepsze.size()>1){ //losuje jak jest pare opcji
Random srand = new Random();
int[] pomoc = najlepsze.get(srand.nextInt(najlepsze.size()));
int[] tymczas={pomoc[1],pomoc[2]};
return tymczas;
}
else{//jak jest tylko 1 opcja
int[] pomoc = {h, w};
return pomoc;
}
//if biggest =0 to znaczy ze trzeba zaczaekac chwile i jeszcze raz odpalic funkcje
//System.out.println(sasiedztwo);//do testów
//System.out.println(biggestValue+" "+h+" "+w);//do testów
}
} |
51287_7 | 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 | // klient traci 0,1 pkt% zniżki za każdą minutę opóźnienia | 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 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) {
// kl<SUF>
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;
// Ko<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<>();
//zm<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_0 | 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 | // 1. Inicjalizacja ICE | 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.<SUF>
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);
}
} |
44869_0 | package agh.tw.Zadanie6;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.concurrent.Semaphore;
class Arbiter6 { // zezwala na dostep do jadalni tylko N-1 filozofom
Semaphore semaforArbitra;
public Arbiter6(int N) {
this.semaforArbitra = new Semaphore(N - 1);
}
public void zajmijDostep() throws InterruptedException {
this.semaforArbitra.acquire();
}
public void zwolnijDostep() {
this.semaforArbitra.release();
}
}
class Widelec6 {
int id;
Boolean czyUzywany;
public Semaphore semafor;
public Widelec6(int id) {
this.id = id;
this.czyUzywany = false;
this.semafor = new Semaphore(1);
}
void podnies() {
try {
semafor.acquire();
czyUzywany = true;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
void odloz() {
czyUzywany = false;
semafor.release();
}
}
class Filozof6 extends Thread {
int id;
Widelec6 lewy;
Widelec6 prawy;
Arbiter6 arbiter;
public Filozof6(int id, Arbiter6 arbiter) {
this.id = id;
this.arbiter = arbiter;
}
private volatile boolean zastopowany = false;
private long calkowityCzasOczekiwania = 0;
private int liczbaOczekiwan = 0;
public void zatrzymajFilozofa() {
zastopowany = true;
}
public long getCalkowityCzasOczekiwania() {
return calkowityCzasOczekiwania;
}
public int getLiczbaOczekiwan() {
return liczbaOczekiwan;
}
void jedz() throws InterruptedException { // filozofowie moga jesc w jadalni
long poczatek = System.currentTimeMillis();
if (arbiter != null) {
arbiter.zajmijDostep();
}
boolean lewyZajety = false;
boolean prawyZajety = false;
while (!(lewyZajety && prawyZajety)) {
if (!lewy.czyUzywany && !lewyZajety) {
lewy.podnies();
lewyZajety = true;
}
if (!prawy.czyUzywany && lewyZajety) {
prawy.podnies();
prawyZajety = true;
}
if (!(lewyZajety && prawyZajety)) {
// Filozof nie ma dostępu do obu widelców, więc kontynuuje oczekiwanie.
Thread.sleep(10);
}
}
long koniec = System.currentTimeMillis();
System.out.println("Filozof " + id + " je");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lewy.odloz();
prawy.odloz();
if (arbiter != null) {
arbiter.zwolnijDostep();
}
calkowityCzasOczekiwania += (koniec - poczatek);
liczbaOczekiwan++;
}
void jedzNaKorytarzu() throws InterruptedException { // filozofowie jedza swoj posilek na korytarzu
long poczatek = System.currentTimeMillis();
boolean lewyZajety = false;
boolean prawyZajety = false;
while (!(lewyZajety && prawyZajety)) {
if (!prawy.czyUzywany && !prawyZajety) {
prawy.podnies();
prawyZajety = true;
}
if (!lewy.czyUzywany && prawyZajety) {
lewy.podnies();
lewyZajety = true;
}
if (!(lewyZajety && prawyZajety)) {
// Filozof nie ma dostępu do obu widelców, więc kontynuuje oczekiwanie.
Thread.sleep(10);
}
}
long koniec = System.currentTimeMillis();
System.out.println("Filozof " + id + " je na korytarzu");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lewy.odloz();
prawy.odloz();
calkowityCzasOczekiwania += (koniec - poczatek);
liczbaOczekiwan++;
}
void mysl() {
System.out.println("Filozof " + id + " mysli");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public void run() {
while (!zastopowany) {
mysl();
try {
if (arbiter.semaforArbitra.availablePermits() != 0) { // jesli nie ma miejsca w jadalni to jedz na korytarzu
jedz();
} else {
jedzNaKorytarzu();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
public class Zadanie6 {
public static void main(String[] args) {
String sciezka;
String currentDirectory = System.getProperty("user.dir");
if (currentDirectory.endsWith("Project")) {
sciezka = "Symulacja/wyniki6.txt";
} else {
sciezka = "../../../Symulacja/wyniki6.txt";
}
try {
File file = new File(sciezka);
FileOutputStream fos = new FileOutputStream(file, false);
PrintWriter writer = new PrintWriter(fos);
for (int N = 5; N < 21; N += 5) {
if (N>15){
N=100;
}
System.out.println("Symulacja dla " + N + " filozofow");
Widelec6[] widelce = new Widelec6[N];
for (int i = 0; i < N; i++) {
widelce[i] = new Widelec6(i);
}
Arbiter6 arbiter = new Arbiter6(N);
Filozof6[] filozofowie = new Filozof6[N];
for (int i = 0; i < N; i++) {
filozofowie[i] = new Filozof6(i, arbiter);
filozofowie[i].lewy = widelce[i];
filozofowie[i].prawy = widelce[(i + 1) % N];
}
for (int i = 0; i < N; i++) {
filozofowie[i].start();
}
long czasSymulacji = 20000;
try {
Thread.sleep(czasSymulacji);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < N; i++) {
filozofowie[i].zatrzymajFilozofa();
}
for (int i = 0; i < N; i++) {
try {
filozofowie[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
writer.println("Wyniki dla " + N + " filozofow:");
for (int i = 0; i < N; i++) {
Filozof6 filozof = filozofowie[i];
long calkowityCzasOczekiwania = filozof.getCalkowityCzasOczekiwania();
int liczbaOczekiwan = filozof.getLiczbaOczekiwan();
if (liczbaOczekiwan > 0) {
double sredniCzasCzekania = (double) calkowityCzasOczekiwania / liczbaOczekiwan;
writer.println("Filozof " + i + " sredni czas oczekiwania na dostep do widelcow: " + sredniCzasCzekania + " ms");
} else {
writer.println("Filozof " + i + " nie czekal na dostep do widelcow.");
}
}
}
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 23adrian2300/TeoriaWspolbieznosci-AGH | Zadanie domowe I/Project/src/main/java/agh/tw/Zadanie6/Zadanie6.java | 2,485 | // zezwala na dostep do jadalni tylko N-1 filozofom
| line_comment | pl | package agh.tw.Zadanie6;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.concurrent.Semaphore;
class Arbiter6 { // ze<SUF>
Semaphore semaforArbitra;
public Arbiter6(int N) {
this.semaforArbitra = new Semaphore(N - 1);
}
public void zajmijDostep() throws InterruptedException {
this.semaforArbitra.acquire();
}
public void zwolnijDostep() {
this.semaforArbitra.release();
}
}
class Widelec6 {
int id;
Boolean czyUzywany;
public Semaphore semafor;
public Widelec6(int id) {
this.id = id;
this.czyUzywany = false;
this.semafor = new Semaphore(1);
}
void podnies() {
try {
semafor.acquire();
czyUzywany = true;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
void odloz() {
czyUzywany = false;
semafor.release();
}
}
class Filozof6 extends Thread {
int id;
Widelec6 lewy;
Widelec6 prawy;
Arbiter6 arbiter;
public Filozof6(int id, Arbiter6 arbiter) {
this.id = id;
this.arbiter = arbiter;
}
private volatile boolean zastopowany = false;
private long calkowityCzasOczekiwania = 0;
private int liczbaOczekiwan = 0;
public void zatrzymajFilozofa() {
zastopowany = true;
}
public long getCalkowityCzasOczekiwania() {
return calkowityCzasOczekiwania;
}
public int getLiczbaOczekiwan() {
return liczbaOczekiwan;
}
void jedz() throws InterruptedException { // filozofowie moga jesc w jadalni
long poczatek = System.currentTimeMillis();
if (arbiter != null) {
arbiter.zajmijDostep();
}
boolean lewyZajety = false;
boolean prawyZajety = false;
while (!(lewyZajety && prawyZajety)) {
if (!lewy.czyUzywany && !lewyZajety) {
lewy.podnies();
lewyZajety = true;
}
if (!prawy.czyUzywany && lewyZajety) {
prawy.podnies();
prawyZajety = true;
}
if (!(lewyZajety && prawyZajety)) {
// Filozof nie ma dostępu do obu widelców, więc kontynuuje oczekiwanie.
Thread.sleep(10);
}
}
long koniec = System.currentTimeMillis();
System.out.println("Filozof " + id + " je");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lewy.odloz();
prawy.odloz();
if (arbiter != null) {
arbiter.zwolnijDostep();
}
calkowityCzasOczekiwania += (koniec - poczatek);
liczbaOczekiwan++;
}
void jedzNaKorytarzu() throws InterruptedException { // filozofowie jedza swoj posilek na korytarzu
long poczatek = System.currentTimeMillis();
boolean lewyZajety = false;
boolean prawyZajety = false;
while (!(lewyZajety && prawyZajety)) {
if (!prawy.czyUzywany && !prawyZajety) {
prawy.podnies();
prawyZajety = true;
}
if (!lewy.czyUzywany && prawyZajety) {
lewy.podnies();
lewyZajety = true;
}
if (!(lewyZajety && prawyZajety)) {
// Filozof nie ma dostępu do obu widelców, więc kontynuuje oczekiwanie.
Thread.sleep(10);
}
}
long koniec = System.currentTimeMillis();
System.out.println("Filozof " + id + " je na korytarzu");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lewy.odloz();
prawy.odloz();
calkowityCzasOczekiwania += (koniec - poczatek);
liczbaOczekiwan++;
}
void mysl() {
System.out.println("Filozof " + id + " mysli");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public void run() {
while (!zastopowany) {
mysl();
try {
if (arbiter.semaforArbitra.availablePermits() != 0) { // jesli nie ma miejsca w jadalni to jedz na korytarzu
jedz();
} else {
jedzNaKorytarzu();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
public class Zadanie6 {
public static void main(String[] args) {
String sciezka;
String currentDirectory = System.getProperty("user.dir");
if (currentDirectory.endsWith("Project")) {
sciezka = "Symulacja/wyniki6.txt";
} else {
sciezka = "../../../Symulacja/wyniki6.txt";
}
try {
File file = new File(sciezka);
FileOutputStream fos = new FileOutputStream(file, false);
PrintWriter writer = new PrintWriter(fos);
for (int N = 5; N < 21; N += 5) {
if (N>15){
N=100;
}
System.out.println("Symulacja dla " + N + " filozofow");
Widelec6[] widelce = new Widelec6[N];
for (int i = 0; i < N; i++) {
widelce[i] = new Widelec6(i);
}
Arbiter6 arbiter = new Arbiter6(N);
Filozof6[] filozofowie = new Filozof6[N];
for (int i = 0; i < N; i++) {
filozofowie[i] = new Filozof6(i, arbiter);
filozofowie[i].lewy = widelce[i];
filozofowie[i].prawy = widelce[(i + 1) % N];
}
for (int i = 0; i < N; i++) {
filozofowie[i].start();
}
long czasSymulacji = 20000;
try {
Thread.sleep(czasSymulacji);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < N; i++) {
filozofowie[i].zatrzymajFilozofa();
}
for (int i = 0; i < N; i++) {
try {
filozofowie[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
writer.println("Wyniki dla " + N + " filozofow:");
for (int i = 0; i < N; i++) {
Filozof6 filozof = filozofowie[i];
long calkowityCzasOczekiwania = filozof.getCalkowityCzasOczekiwania();
int liczbaOczekiwan = filozof.getLiczbaOczekiwan();
if (liczbaOczekiwan > 0) {
double sredniCzasCzekania = (double) calkowityCzasOczekiwania / liczbaOczekiwan;
writer.println("Filozof " + i + " sredni czas oczekiwania na dostep do widelcow: " + sredniCzasCzekania + " ms");
} else {
writer.println("Filozof " + i + " nie czekal na dostep do widelcow.");
}
}
}
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
151270_11 | /*
* Copyright 2016 radon & agata
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package pz.twojaszkola.szkola;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import static org.springframework.web.bind.annotation.RequestMethod.PUT;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import pz.twojaszkola.OcenaPrzedmiotu.OcenaPrzedmiotuRepository;
import pz.twojaszkola.gallerySchool.GallerySchoolRepository;
import pz.twojaszkola.mediany.MedianyRepository;
import pz.twojaszkola.profil.ProfilEntity;
import pz.twojaszkola.profil.ProfilRepository;
import pz.twojaszkola.proponowaneSzkoly.proponowaneSzkolyEntity;
import pz.twojaszkola.przedmioty.PrzedmiotyEntity;
import pz.twojaszkola.support.ResourceNotFoundException;
import pz.twojaszkola.uczen.UczenEntity;
import pz.twojaszkola.uczen.UczenRepository;
import pz.twojaszkola.ulubione.UlubionaSzkolaEntity2;
import pz.twojaszkola.ulubione.UlubionaSzkolaRepository;
import pz.twojaszkola.user.CurrentUser;
import pz.twojaszkola.user.User;
import pz.twojaszkola.user.UserRepository;
import pz.twojaszkola.zainteresowania.zainteresowaniaController;
import pz.twojaszkola.zainteresowania.zainteresowaniaRepository;
import pz.twojaszkola.przedmioty.PrzedmiotyRepository;
/**
*
* @authors radon, agata
*/
@RestController
@RequestMapping("/api")
public class SzkolaController {
private final SzkolaRepository szkolaRepository;
private final MedianyRepository medianyRepository;
private final ProfilRepository profilRepository;
private final PrzedmiotyRepository przedmiotyRepo;
private final UczenRepository uczenRepository;
private final zainteresowaniaRepository zainteresowaniaRepo;
private final OcenaPrzedmiotuRepository ocenaPrzedmiotuRepo;
private final UlubionaSzkolaRepository ulubionaSzkolaRepo;
private final UserRepository userRepository;
private final GallerySchoolRepository gallerySchoolRepo;
@Autowired
public SzkolaController(final SzkolaRepository szkolaRepository, final MedianyRepository medianyRepository, final ProfilRepository profilRepository, final PrzedmiotyRepository przedmiotyRepo, final UczenRepository uczenRepository, final zainteresowaniaRepository zainteresowaniaRepo, final OcenaPrzedmiotuRepository ocenaPrzedmiotuRepo, final UlubionaSzkolaRepository ulubionaSzkolaRepo, final UserRepository userRepository, final GallerySchoolRepository gallerySchoolRepo) {
this.szkolaRepository = szkolaRepository;
this.medianyRepository = medianyRepository;
this.profilRepository = profilRepository;
this.przedmiotyRepo = przedmiotyRepo;
this.uczenRepository = uczenRepository;
this.zainteresowaniaRepo = zainteresowaniaRepo;
this.ocenaPrzedmiotuRepo = ocenaPrzedmiotuRepo;
this.ulubionaSzkolaRepo = ulubionaSzkolaRepo;
this.userRepository = userRepository;
this.gallerySchoolRepo = gallerySchoolRepo;
}
@RequestMapping(value = "/szkola", method = GET)
public List<SzkolaEntity> getSzkola(final @RequestParam(required = false, defaultValue = "false") boolean all) {
List<SzkolaEntity> rv;
rv = szkolaRepository.findAll(new Sort(Sort.Direction.ASC, "name", "mail", "miasto", "adres", "kodpocztowy", "typSzkoly", "rodzajGwiazdki"));
return rv;
}
@RequestMapping(value = "/szkola/{id}", method = GET)
public SzkolaEntity getSzkolaById(@PathVariable Integer id, final @RequestParam(required = false, defaultValue = "false") boolean all) {
final SzkolaEntity szkola = szkolaRepository.findById(id);
return szkola;
}
@RequestMapping(value = "/szukaneSzkoly/{nazwa}", method = GET)
public List<SzkolaEntity> getSzukaneSzkoly(@PathVariable String nazwa, final @RequestParam(required = false, defaultValue = "false") boolean all) {
List<SzkolaEntity> tmp;
List<SzkolaEntity> rv = new ArrayList<SzkolaEntity>();
tmp = szkolaRepository.findAll(new Sort(Sort.Direction.ASC, "name", "mail", "miasto", "adres", "kodpocztowy", "typSzkoly", "rodzajGwiazdki"));
//Logger.getLogger(SzkolaController.class.getName()).log(Level.SEVERE, "LOG SzUKAJ: " + nazwa.toLowerCase());
for (SzkolaEntity s : tmp) {
Logger.getLogger(SzkolaController.class.getName()).log(Level.SEVERE, s.getName().toLowerCase() + " SzukaJ NR: " + s.getName().indexOf(nazwa));
if ((s.getName().toLowerCase()).indexOf(nazwa.toLowerCase()) >= 0) {
rv.add(s);
}
}
return rv;
}
@RequestMapping(value = "/ProponowaneSzkoly", method = GET)
public List<proponowaneSzkolyEntity> getProponowaneSzkoly(final @RequestParam(required = false, defaultValue = "false") boolean all) {
CurrentUser currentUser = null;
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
currentUser = (CurrentUser) auth.getPrincipal();
Integer idUsera = currentUser.getId();
Logger.getLogger(zainteresowaniaController.class.getName()).log(Level.SEVERE, "LOG: " + idUsera);
Integer idUcznia = uczenRepository.findByUserId(idUsera).getId();
Logger.getLogger(zainteresowaniaController.class.getName()).log(Level.SEVERE, "LOG: " + idUcznia);
List<proponowaneSzkolyEntity> proponowane = new ArrayList<proponowaneSzkolyEntity>();
List<proponowaneSzkolyEntity> rv = new ArrayList<proponowaneSzkolyEntity>();
List<PrzedmiotyEntity> przedmioty = przedmiotyRepo.findAll(new Sort(Sort.Direction.ASC, "name", "kategoria"));
final UczenEntity uczen = uczenRepository.findById(idUcznia);
final String typ = uczen.getCzegoSzukam();
Logger.getLogger(SzkolaController.class.getName()).log(Level.SEVERE, "LOG TYP: " + typ);
List<UlubionaSzkolaEntity2> rv2;
List<SzkolaEntity> tmp;
rv2 = ulubionaSzkolaRepo.findByUczenId(uczen.getId());
tmp = szkolaRepository.findAll();
for (SzkolaEntity s : tmp) {
if (ulubionaSzkolaRepo.findBySzkolaIdAndUczenId(s.getId(), uczen.getId()) != null) {
SzkolaEntity sz = szkolaRepository.findById(s.getId());
s.setRodzajGwiazdki("glyphicon-star");
this.szkolaRepository.save(s);
} else {
SzkolaEntity sz = szkolaRepository.findById(s.getId());
s.setRodzajGwiazdki("glyphicon-star-empty");
this.szkolaRepository.save(s);
}
}
List<ProfilEntity> profile;
if ("Szkoła Średnia dowolnego typu".equals(typ)) {
//profile = profilRepository.findAll(new Sort(Sort.Direction.ASC, "profilNazwa", "szkola"));
profile = profilRepository.findSzkolySrednie("Liceum", "Technikum", "Szkoła Zawodowa");
} else {
profile = profilRepository.findByTypSzkoly(typ);
}
for (ProfilEntity prof : profile) {
Integer punktacja = 0;
for (PrzedmiotyEntity przed : przedmioty) {
Integer stZaint = 0;
Integer ocenaPrzed = 0;
Integer mediana = 0;
if (medianyRepository.findByUczenId2(idUcznia) != null) {
mediana = medianyRepository.findByUczenId2(idUcznia).getMediana();
}
Logger.getLogger(SzkolaController.class.getName()).log(Level.SEVERE, "LOG: " + uczen.getName() + " - mediana " + mediana);
if (zainteresowaniaRepo.getStopienZaintByUczenAndPrzedmiot(idUcznia, przed.getId()) != null) {
stZaint = zainteresowaniaRepo.getStopienZaintByUczenAndPrzedmiot(idUcznia, przed.getId());
}
if (ocenaPrzedmiotuRepo.getOcenaByPrzedmiotAndProfil(przed.getId(), prof.getId()) != null) {
ocenaPrzed = ocenaPrzedmiotuRepo.getOcenaByPrzedmiotAndProfil(przed.getId(), prof.getId());
}
if (stZaint >= mediana) {
punktacja = punktacja + stZaint * ocenaPrzed;
}
//Logger.getLogger(SzkolaController.class.getName()).log(Level.SEVERE, "LOG1: " + przed.getName() + ", " + stZaint);
//Logger.getLogger(SzkolaController.class.getName()).log(Level.SEVERE, "LOG2: " + prof.getProfil_nazwa().getNazwa() + ", " + ocenaPrzed);
}
proponowaneSzkolyEntity p = new proponowaneSzkolyEntity(uczen, prof, punktacja);
proponowane.add(p);
}
Collections.sort(proponowane, new proponowaneSzkolyEntity());
for (proponowaneSzkolyEntity p : proponowane) {
// Logger.getLogger(SzkolaController.class.getName()).log(Level.SEVERE, "LOG3: " + p.getUczenId().getName() + ", " + p.getProfilId().getProfil_nazwa().getNazwa() + ", " + p.getProfilId().getSzkola().getName() +"," + p.getPunktacja());
}
int ilosc = 3;
if (proponowane.size() < 3) {
ilosc = proponowane.size();
}
//Logger.getLogger(SzkolaController.class.getName()).log(Level.SEVERE, "LOG4: " + proponowane.size());
for (int i = 0; i < ilosc; i++) {
if (proponowane.get(i).getPunktacja() != 0) {
rv.add(proponowane.get(i));
}
}
for (proponowaneSzkolyEntity s : rv) {
Logger.getLogger(SzkolaController.class.getName()).log(Level.SEVERE, "LOG5: " + s.getProfilId().getSzkola().getName());
}
return rv;
}
@RequestMapping(value = "/szkola", method = POST)
@PreAuthorize("isAuthenticated()")
public SzkolaEntity createSzkola(final @RequestBody @Valid SzkolaCmd newSzkola, final BindingResult bindingResult) {
// if(bindingResult.hasErrors()) {
// throw new IllegalArgumentException("Invalid arguments.");
// }
User user = userRepository.findById(2);
Logger.getLogger(SzkolaController.class.getName()).log(Level.SEVERE, "LOGG: " + newSzkola.getNumer());
final SzkolaEntity szkola = new SzkolaEntity(newSzkola.getName(), newSzkola.getNumer(), newSzkola.getMiasto(), newSzkola.getAdres(), newSzkola.getKodpocztowy(), newSzkola.getTypSzkoly(), newSzkola.getRodzajSzkoly(), "glyphicon-star-empty", user);
//Logger.getLogger(SzkolaController.class.getName()).log(Level.SEVERE, "LOG GALLERY: " + newSzkola.getGalleryId().getId());
if (gallerySchoolRepo.findOne(2) != null) {
//szkola.setGalleryId(newSzkola.getGalleryId());
szkola.setGalleryId(gallerySchoolRepo.findOne(2));
} else {
szkola.setGalleryId(gallerySchoolRepo.findOne(1));
}
return this.szkolaRepository.save(szkola);
}
@RequestMapping(value = "/szkola/{id}", method = PUT)
@PreAuthorize("isAuthenticated()")
@Transactional
public SzkolaEntity updateSzkola(final @PathVariable Integer id, final @RequestBody @Valid SzkolaCmd updatedSzkola, final BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
throw new IllegalArgumentException("Invalid arguments.");
}
User user = userRepository.findById(2);
final SzkolaEntity szkola = new SzkolaEntity(updatedSzkola.getName(), updatedSzkola.getNumer(), updatedSzkola.getMiasto(), updatedSzkola.getAdres(), updatedSzkola.getKodpocztowy(), updatedSzkola.getTypSzkoly(), updatedSzkola.getRodzajSzkoly(), updatedSzkola.getRodzajGwiazdki(), user);
szkola.setId(id);
if (szkola == null) {
throw new ResourceNotFoundException();
}
return this.szkolaRepository.save(szkola);
}
}
| 267488/zespolowka | TwojaSzkola/twojaszkola/src/main/java/pz/twojaszkola/szkola/SzkolaController.java | 4,137 | //szkola.setGalleryId(newSzkola.getGalleryId()); | line_comment | pl | /*
* Copyright 2016 radon & agata
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package pz.twojaszkola.szkola;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import static org.springframework.web.bind.annotation.RequestMethod.PUT;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import pz.twojaszkola.OcenaPrzedmiotu.OcenaPrzedmiotuRepository;
import pz.twojaszkola.gallerySchool.GallerySchoolRepository;
import pz.twojaszkola.mediany.MedianyRepository;
import pz.twojaszkola.profil.ProfilEntity;
import pz.twojaszkola.profil.ProfilRepository;
import pz.twojaszkola.proponowaneSzkoly.proponowaneSzkolyEntity;
import pz.twojaszkola.przedmioty.PrzedmiotyEntity;
import pz.twojaszkola.support.ResourceNotFoundException;
import pz.twojaszkola.uczen.UczenEntity;
import pz.twojaszkola.uczen.UczenRepository;
import pz.twojaszkola.ulubione.UlubionaSzkolaEntity2;
import pz.twojaszkola.ulubione.UlubionaSzkolaRepository;
import pz.twojaszkola.user.CurrentUser;
import pz.twojaszkola.user.User;
import pz.twojaszkola.user.UserRepository;
import pz.twojaszkola.zainteresowania.zainteresowaniaController;
import pz.twojaszkola.zainteresowania.zainteresowaniaRepository;
import pz.twojaszkola.przedmioty.PrzedmiotyRepository;
/**
*
* @authors radon, agata
*/
@RestController
@RequestMapping("/api")
public class SzkolaController {
private final SzkolaRepository szkolaRepository;
private final MedianyRepository medianyRepository;
private final ProfilRepository profilRepository;
private final PrzedmiotyRepository przedmiotyRepo;
private final UczenRepository uczenRepository;
private final zainteresowaniaRepository zainteresowaniaRepo;
private final OcenaPrzedmiotuRepository ocenaPrzedmiotuRepo;
private final UlubionaSzkolaRepository ulubionaSzkolaRepo;
private final UserRepository userRepository;
private final GallerySchoolRepository gallerySchoolRepo;
@Autowired
public SzkolaController(final SzkolaRepository szkolaRepository, final MedianyRepository medianyRepository, final ProfilRepository profilRepository, final PrzedmiotyRepository przedmiotyRepo, final UczenRepository uczenRepository, final zainteresowaniaRepository zainteresowaniaRepo, final OcenaPrzedmiotuRepository ocenaPrzedmiotuRepo, final UlubionaSzkolaRepository ulubionaSzkolaRepo, final UserRepository userRepository, final GallerySchoolRepository gallerySchoolRepo) {
this.szkolaRepository = szkolaRepository;
this.medianyRepository = medianyRepository;
this.profilRepository = profilRepository;
this.przedmiotyRepo = przedmiotyRepo;
this.uczenRepository = uczenRepository;
this.zainteresowaniaRepo = zainteresowaniaRepo;
this.ocenaPrzedmiotuRepo = ocenaPrzedmiotuRepo;
this.ulubionaSzkolaRepo = ulubionaSzkolaRepo;
this.userRepository = userRepository;
this.gallerySchoolRepo = gallerySchoolRepo;
}
@RequestMapping(value = "/szkola", method = GET)
public List<SzkolaEntity> getSzkola(final @RequestParam(required = false, defaultValue = "false") boolean all) {
List<SzkolaEntity> rv;
rv = szkolaRepository.findAll(new Sort(Sort.Direction.ASC, "name", "mail", "miasto", "adres", "kodpocztowy", "typSzkoly", "rodzajGwiazdki"));
return rv;
}
@RequestMapping(value = "/szkola/{id}", method = GET)
public SzkolaEntity getSzkolaById(@PathVariable Integer id, final @RequestParam(required = false, defaultValue = "false") boolean all) {
final SzkolaEntity szkola = szkolaRepository.findById(id);
return szkola;
}
@RequestMapping(value = "/szukaneSzkoly/{nazwa}", method = GET)
public List<SzkolaEntity> getSzukaneSzkoly(@PathVariable String nazwa, final @RequestParam(required = false, defaultValue = "false") boolean all) {
List<SzkolaEntity> tmp;
List<SzkolaEntity> rv = new ArrayList<SzkolaEntity>();
tmp = szkolaRepository.findAll(new Sort(Sort.Direction.ASC, "name", "mail", "miasto", "adres", "kodpocztowy", "typSzkoly", "rodzajGwiazdki"));
//Logger.getLogger(SzkolaController.class.getName()).log(Level.SEVERE, "LOG SzUKAJ: " + nazwa.toLowerCase());
for (SzkolaEntity s : tmp) {
Logger.getLogger(SzkolaController.class.getName()).log(Level.SEVERE, s.getName().toLowerCase() + " SzukaJ NR: " + s.getName().indexOf(nazwa));
if ((s.getName().toLowerCase()).indexOf(nazwa.toLowerCase()) >= 0) {
rv.add(s);
}
}
return rv;
}
@RequestMapping(value = "/ProponowaneSzkoly", method = GET)
public List<proponowaneSzkolyEntity> getProponowaneSzkoly(final @RequestParam(required = false, defaultValue = "false") boolean all) {
CurrentUser currentUser = null;
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
currentUser = (CurrentUser) auth.getPrincipal();
Integer idUsera = currentUser.getId();
Logger.getLogger(zainteresowaniaController.class.getName()).log(Level.SEVERE, "LOG: " + idUsera);
Integer idUcznia = uczenRepository.findByUserId(idUsera).getId();
Logger.getLogger(zainteresowaniaController.class.getName()).log(Level.SEVERE, "LOG: " + idUcznia);
List<proponowaneSzkolyEntity> proponowane = new ArrayList<proponowaneSzkolyEntity>();
List<proponowaneSzkolyEntity> rv = new ArrayList<proponowaneSzkolyEntity>();
List<PrzedmiotyEntity> przedmioty = przedmiotyRepo.findAll(new Sort(Sort.Direction.ASC, "name", "kategoria"));
final UczenEntity uczen = uczenRepository.findById(idUcznia);
final String typ = uczen.getCzegoSzukam();
Logger.getLogger(SzkolaController.class.getName()).log(Level.SEVERE, "LOG TYP: " + typ);
List<UlubionaSzkolaEntity2> rv2;
List<SzkolaEntity> tmp;
rv2 = ulubionaSzkolaRepo.findByUczenId(uczen.getId());
tmp = szkolaRepository.findAll();
for (SzkolaEntity s : tmp) {
if (ulubionaSzkolaRepo.findBySzkolaIdAndUczenId(s.getId(), uczen.getId()) != null) {
SzkolaEntity sz = szkolaRepository.findById(s.getId());
s.setRodzajGwiazdki("glyphicon-star");
this.szkolaRepository.save(s);
} else {
SzkolaEntity sz = szkolaRepository.findById(s.getId());
s.setRodzajGwiazdki("glyphicon-star-empty");
this.szkolaRepository.save(s);
}
}
List<ProfilEntity> profile;
if ("Szkoła Średnia dowolnego typu".equals(typ)) {
//profile = profilRepository.findAll(new Sort(Sort.Direction.ASC, "profilNazwa", "szkola"));
profile = profilRepository.findSzkolySrednie("Liceum", "Technikum", "Szkoła Zawodowa");
} else {
profile = profilRepository.findByTypSzkoly(typ);
}
for (ProfilEntity prof : profile) {
Integer punktacja = 0;
for (PrzedmiotyEntity przed : przedmioty) {
Integer stZaint = 0;
Integer ocenaPrzed = 0;
Integer mediana = 0;
if (medianyRepository.findByUczenId2(idUcznia) != null) {
mediana = medianyRepository.findByUczenId2(idUcznia).getMediana();
}
Logger.getLogger(SzkolaController.class.getName()).log(Level.SEVERE, "LOG: " + uczen.getName() + " - mediana " + mediana);
if (zainteresowaniaRepo.getStopienZaintByUczenAndPrzedmiot(idUcznia, przed.getId()) != null) {
stZaint = zainteresowaniaRepo.getStopienZaintByUczenAndPrzedmiot(idUcznia, przed.getId());
}
if (ocenaPrzedmiotuRepo.getOcenaByPrzedmiotAndProfil(przed.getId(), prof.getId()) != null) {
ocenaPrzed = ocenaPrzedmiotuRepo.getOcenaByPrzedmiotAndProfil(przed.getId(), prof.getId());
}
if (stZaint >= mediana) {
punktacja = punktacja + stZaint * ocenaPrzed;
}
//Logger.getLogger(SzkolaController.class.getName()).log(Level.SEVERE, "LOG1: " + przed.getName() + ", " + stZaint);
//Logger.getLogger(SzkolaController.class.getName()).log(Level.SEVERE, "LOG2: " + prof.getProfil_nazwa().getNazwa() + ", " + ocenaPrzed);
}
proponowaneSzkolyEntity p = new proponowaneSzkolyEntity(uczen, prof, punktacja);
proponowane.add(p);
}
Collections.sort(proponowane, new proponowaneSzkolyEntity());
for (proponowaneSzkolyEntity p : proponowane) {
// Logger.getLogger(SzkolaController.class.getName()).log(Level.SEVERE, "LOG3: " + p.getUczenId().getName() + ", " + p.getProfilId().getProfil_nazwa().getNazwa() + ", " + p.getProfilId().getSzkola().getName() +"," + p.getPunktacja());
}
int ilosc = 3;
if (proponowane.size() < 3) {
ilosc = proponowane.size();
}
//Logger.getLogger(SzkolaController.class.getName()).log(Level.SEVERE, "LOG4: " + proponowane.size());
for (int i = 0; i < ilosc; i++) {
if (proponowane.get(i).getPunktacja() != 0) {
rv.add(proponowane.get(i));
}
}
for (proponowaneSzkolyEntity s : rv) {
Logger.getLogger(SzkolaController.class.getName()).log(Level.SEVERE, "LOG5: " + s.getProfilId().getSzkola().getName());
}
return rv;
}
@RequestMapping(value = "/szkola", method = POST)
@PreAuthorize("isAuthenticated()")
public SzkolaEntity createSzkola(final @RequestBody @Valid SzkolaCmd newSzkola, final BindingResult bindingResult) {
// if(bindingResult.hasErrors()) {
// throw new IllegalArgumentException("Invalid arguments.");
// }
User user = userRepository.findById(2);
Logger.getLogger(SzkolaController.class.getName()).log(Level.SEVERE, "LOGG: " + newSzkola.getNumer());
final SzkolaEntity szkola = new SzkolaEntity(newSzkola.getName(), newSzkola.getNumer(), newSzkola.getMiasto(), newSzkola.getAdres(), newSzkola.getKodpocztowy(), newSzkola.getTypSzkoly(), newSzkola.getRodzajSzkoly(), "glyphicon-star-empty", user);
//Logger.getLogger(SzkolaController.class.getName()).log(Level.SEVERE, "LOG GALLERY: " + newSzkola.getGalleryId().getId());
if (gallerySchoolRepo.findOne(2) != null) {
//sz<SUF>
szkola.setGalleryId(gallerySchoolRepo.findOne(2));
} else {
szkola.setGalleryId(gallerySchoolRepo.findOne(1));
}
return this.szkolaRepository.save(szkola);
}
@RequestMapping(value = "/szkola/{id}", method = PUT)
@PreAuthorize("isAuthenticated()")
@Transactional
public SzkolaEntity updateSzkola(final @PathVariable Integer id, final @RequestBody @Valid SzkolaCmd updatedSzkola, final BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
throw new IllegalArgumentException("Invalid arguments.");
}
User user = userRepository.findById(2);
final SzkolaEntity szkola = new SzkolaEntity(updatedSzkola.getName(), updatedSzkola.getNumer(), updatedSzkola.getMiasto(), updatedSzkola.getAdres(), updatedSzkola.getKodpocztowy(), updatedSzkola.getTypSzkoly(), updatedSzkola.getRodzajSzkoly(), updatedSzkola.getRodzajGwiazdki(), user);
szkola.setId(id);
if (szkola == null) {
throw new ResourceNotFoundException();
}
return this.szkolaRepository.save(szkola);
}
}
|
105984_1 | package com.example.ts.service;
import com.example.ts.infrastructure.entity.LoanEntity;
import com.example.ts.infrastructure.entity.UserEntity;
import com.example.ts.infrastructure.repository.BookRepository;
import com.example.ts.infrastructure.repository.LoanRepository;
import com.example.ts.infrastructure.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.sql.Date;
import java.util.List;
@Service
public class LoanService {
private final LoanRepository loanRepository;
private final UserRepository userRepository;
private final BookRepository bookRepository;
@Autowired
public LoanService(LoanRepository loanRepository, UserRepository userRepository, BookRepository bookRepository) {
this.loanRepository = loanRepository;
this.userRepository = userRepository;
this.bookRepository = bookRepository;
}
public LoanEntity getOne(Integer id) {
return loanRepository.findById(id).orElseThrow(() -> new RuntimeException("Loan not found."));
}
public LoanEntity addLoan(LoanEntity loan) {
return loanRepository.save(loan);
}
public LoanEntity borrowBook(Integer userId, Integer bookId) {
UserEntity user = userRepository.findById(userId).orElse(null);
if (user == null) {
throw new IllegalArgumentException("User not found");
}
LoanEntity loan = new LoanEntity();
loan.setUser(user);
loan.setLoanDate(new Date(System.currentTimeMillis()));
// Ustawienie książki (bookId przekazywane z żądania)
loan.setBook(bookRepository.findById(bookId));
return loanRepository.save(loan);
}
public void returnBook(Integer loanId) {
// Pobierz wypożyczenie
LoanEntity loan = loanRepository.findById(loanId).orElse(null);
if (loan == null) {
throw new IllegalArgumentException("Loan not found");
}
// Ustaw datę zwrotu na obecną
loan.setReturnDate(new Date(System.currentTimeMillis()));
// Zapisz zmiany
loanRepository.save(loan);
}
public List<LoanEntity> getLoanHistory(Integer userId) {
// Pobierz historię wypożyczeń dla danego użytkownika
return (List<LoanEntity>) loanRepository.findByUserId(userId);
}
public void delete(Integer id) {
loanRepository.deleteById(id);
}
public List<LoanEntity> getAllLoans() {
return loanRepository.findAll();
}
}
| 268312/TS | src/main/java/com/example/ts/service/LoanService.java | 719 | // Pobierz wypożyczenie | line_comment | pl | package com.example.ts.service;
import com.example.ts.infrastructure.entity.LoanEntity;
import com.example.ts.infrastructure.entity.UserEntity;
import com.example.ts.infrastructure.repository.BookRepository;
import com.example.ts.infrastructure.repository.LoanRepository;
import com.example.ts.infrastructure.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.sql.Date;
import java.util.List;
@Service
public class LoanService {
private final LoanRepository loanRepository;
private final UserRepository userRepository;
private final BookRepository bookRepository;
@Autowired
public LoanService(LoanRepository loanRepository, UserRepository userRepository, BookRepository bookRepository) {
this.loanRepository = loanRepository;
this.userRepository = userRepository;
this.bookRepository = bookRepository;
}
public LoanEntity getOne(Integer id) {
return loanRepository.findById(id).orElseThrow(() -> new RuntimeException("Loan not found."));
}
public LoanEntity addLoan(LoanEntity loan) {
return loanRepository.save(loan);
}
public LoanEntity borrowBook(Integer userId, Integer bookId) {
UserEntity user = userRepository.findById(userId).orElse(null);
if (user == null) {
throw new IllegalArgumentException("User not found");
}
LoanEntity loan = new LoanEntity();
loan.setUser(user);
loan.setLoanDate(new Date(System.currentTimeMillis()));
// Ustawienie książki (bookId przekazywane z żądania)
loan.setBook(bookRepository.findById(bookId));
return loanRepository.save(loan);
}
public void returnBook(Integer loanId) {
// Po<SUF>
LoanEntity loan = loanRepository.findById(loanId).orElse(null);
if (loan == null) {
throw new IllegalArgumentException("Loan not found");
}
// Ustaw datę zwrotu na obecną
loan.setReturnDate(new Date(System.currentTimeMillis()));
// Zapisz zmiany
loanRepository.save(loan);
}
public List<LoanEntity> getLoanHistory(Integer userId) {
// Pobierz historię wypożyczeń dla danego użytkownika
return (List<LoanEntity>) loanRepository.findByUserId(userId);
}
public void delete(Integer id) {
loanRepository.deleteById(id);
}
public List<LoanEntity> getAllLoans() {
return loanRepository.findAll();
}
}
|
14432_9 | package serwer.model;
/**
* Klasa do zarządzania budowniczymi planszy
*/
public class ZarzadcaBudowniczych {
private PlanszaBudowniczy planszaBudowniczy;
/**
* Przypisuje budowniczego planszy do zarządcy
* @param planszaBudowniczy budowniczy planszy do przypisania
*/
public void ustawPlanszaBudowniczy(final PlanszaBudowniczy planszaBudowniczy) {
this.planszaBudowniczy = planszaBudowniczy;
}
/**
* Tworzy planszę, ustawia początkowe ułożenie
*/
public void skonstruujPlansze() {
planszaBudowniczy.poczatkoweUstawienie();
}
/**
* Wywołuje metodę budowniczego konkretnego do zbijania pionka
* @see PlanszaBudowniczy#zbijPionek(char, int, int, int, int)
* @param kolorPionka kolor pionka, który wykonuje bicie
* @param xPocz początkowa współrzędna x
* @param yPocz początkowa współrzędna y
* @param xKonc końcowa współrzędna x
* @param yKonc końcowa współrzędna y
* @return true jeżeli bicie się powiodło, false w przeciwnym przypadku
*/
public boolean zbijPionek(final char kolorPionka, final int xPocz, final int yPocz, final int xKonc, final int yKonc) {
return planszaBudowniczy.zbijPionek(kolorPionka, xPocz, yPocz, xKonc, yKonc);
}
/**
* Wywołuje metodę budowniczego konkretnego do normalnego ruchu pionkiem
* @see PlanszaBudowniczy#normalnyRuch(char, int, int, int, int)
* @param kolorPionka kolor ruszanego pionka
* @param xPocz początkowa współrzędna x
* @param yPocz początkowa współrzędna y
* @param xKonc końcowa współrzędna x
* @param yKonc końcowa współrzędna y
* @return true jeżeli ruch się powiódł, false w przeciwnym przypadku
*/
public boolean normalnyRuch(final char kolorPionka, final int xPocz, final int yPocz, final int xKonc, final int yKonc) {
return planszaBudowniczy.normalnyRuch(kolorPionka, xPocz, yPocz, xKonc, yKonc);
}
/**
* Wywołuje metodę budowniczego konkretnego do sprawdzania czy można dalej bić
* @see PlanszaBudowniczy#moznaDalejBic(char, int, int)
* @param kolorPionka kolor pionka, dla którego jest sprawdzana dostępność bicia
* @param x współrzędna x pionka
* @param y współrzędna y pionka
* @return true jeśli dla danego pionka jest dostępne bicie, false w przeciwnym przypadku
*/
public boolean moznaDalejBic(final char kolorPionka, final int x, final int y) {
return planszaBudowniczy.moznaDalejBic(kolorPionka, x, y);
}
/**
* Wywołuje metodę budowniczego konkretnego do sprawdzania czy nastąpił remis
* @see PlanszaBudowniczy#czyRemis()
* @return true w przypadku remisu, false gdy remisu nie ma
*/
public boolean czyRemis() {
return planszaBudowniczy.czyRemis();
}
/**
* Wywołuje metodę budowniczego konkretnego do sprawdzania czy nastąpiła wygrana gracza danego koloru
* @see PlanszaBudowniczy#czyWygrana(char)
* @param kolor kolor gracza, dla którego sprawdzany jest warunek zwycięstwa
* @return true jeśli gracz o danym kolorze zwycieżył, false w przeciwnym przypadku
*/
public boolean czyWygrana(final char kolor) {
return planszaBudowniczy.czyWygrana(kolor);
}
/**
* Pobiera planszę budowniczego konkretnego
* @return plansza budowniczego konkretnego
*/
public Plansza pobierzPlansza() {
return planszaBudowniczy.pobierzPlansza();
}
/**
* Wywołuje metodę budowniczego konkretnego do sprawdzania czy istnieje bicie
* @see PlanszaBudowniczy#istniejeBicie(char)
* @param kolor kolor gracza
* @return true jesli jest dostępne bicie, false w przeciwnym przypadku
*/
public boolean istniejeBicie(final char kolor) {
return planszaBudowniczy.istniejeBicie(kolor);
}
/**
* Wywołuje metodę budowniczego konkretnego do ustawiania, że żaden pionek aktualnie nie jest w trkacie ruchu
* @see PlanszaBudowniczy#zresetujObecneWspolrzedne()
*/
public void zresetujObecneWspolrzedne() {
planszaBudowniczy.zresetujObecneWspolrzedne();
}
}
| 268503/Warcaby | src/main/java/serwer/model/ZarzadcaBudowniczych.java | 1,552 | /**
* Wywołuje metodę budowniczego konkretnego do sprawdzania czy istnieje bicie
* @see PlanszaBudowniczy#istniejeBicie(char)
* @param kolor kolor gracza
* @return true jesli jest dostępne bicie, false w przeciwnym przypadku
*/ | block_comment | pl | package serwer.model;
/**
* Klasa do zarządzania budowniczymi planszy
*/
public class ZarzadcaBudowniczych {
private PlanszaBudowniczy planszaBudowniczy;
/**
* Przypisuje budowniczego planszy do zarządcy
* @param planszaBudowniczy budowniczy planszy do przypisania
*/
public void ustawPlanszaBudowniczy(final PlanszaBudowniczy planszaBudowniczy) {
this.planszaBudowniczy = planszaBudowniczy;
}
/**
* Tworzy planszę, ustawia początkowe ułożenie
*/
public void skonstruujPlansze() {
planszaBudowniczy.poczatkoweUstawienie();
}
/**
* Wywołuje metodę budowniczego konkretnego do zbijania pionka
* @see PlanszaBudowniczy#zbijPionek(char, int, int, int, int)
* @param kolorPionka kolor pionka, który wykonuje bicie
* @param xPocz początkowa współrzędna x
* @param yPocz początkowa współrzędna y
* @param xKonc końcowa współrzędna x
* @param yKonc końcowa współrzędna y
* @return true jeżeli bicie się powiodło, false w przeciwnym przypadku
*/
public boolean zbijPionek(final char kolorPionka, final int xPocz, final int yPocz, final int xKonc, final int yKonc) {
return planszaBudowniczy.zbijPionek(kolorPionka, xPocz, yPocz, xKonc, yKonc);
}
/**
* Wywołuje metodę budowniczego konkretnego do normalnego ruchu pionkiem
* @see PlanszaBudowniczy#normalnyRuch(char, int, int, int, int)
* @param kolorPionka kolor ruszanego pionka
* @param xPocz początkowa współrzędna x
* @param yPocz początkowa współrzędna y
* @param xKonc końcowa współrzędna x
* @param yKonc końcowa współrzędna y
* @return true jeżeli ruch się powiódł, false w przeciwnym przypadku
*/
public boolean normalnyRuch(final char kolorPionka, final int xPocz, final int yPocz, final int xKonc, final int yKonc) {
return planszaBudowniczy.normalnyRuch(kolorPionka, xPocz, yPocz, xKonc, yKonc);
}
/**
* Wywołuje metodę budowniczego konkretnego do sprawdzania czy można dalej bić
* @see PlanszaBudowniczy#moznaDalejBic(char, int, int)
* @param kolorPionka kolor pionka, dla którego jest sprawdzana dostępność bicia
* @param x współrzędna x pionka
* @param y współrzędna y pionka
* @return true jeśli dla danego pionka jest dostępne bicie, false w przeciwnym przypadku
*/
public boolean moznaDalejBic(final char kolorPionka, final int x, final int y) {
return planszaBudowniczy.moznaDalejBic(kolorPionka, x, y);
}
/**
* Wywołuje metodę budowniczego konkretnego do sprawdzania czy nastąpił remis
* @see PlanszaBudowniczy#czyRemis()
* @return true w przypadku remisu, false gdy remisu nie ma
*/
public boolean czyRemis() {
return planszaBudowniczy.czyRemis();
}
/**
* Wywołuje metodę budowniczego konkretnego do sprawdzania czy nastąpiła wygrana gracza danego koloru
* @see PlanszaBudowniczy#czyWygrana(char)
* @param kolor kolor gracza, dla którego sprawdzany jest warunek zwycięstwa
* @return true jeśli gracz o danym kolorze zwycieżył, false w przeciwnym przypadku
*/
public boolean czyWygrana(final char kolor) {
return planszaBudowniczy.czyWygrana(kolor);
}
/**
* Pobiera planszę budowniczego konkretnego
* @return plansza budowniczego konkretnego
*/
public Plansza pobierzPlansza() {
return planszaBudowniczy.pobierzPlansza();
}
/**
* Wyw<SUF>*/
public boolean istniejeBicie(final char kolor) {
return planszaBudowniczy.istniejeBicie(kolor);
}
/**
* Wywołuje metodę budowniczego konkretnego do ustawiania, że żaden pionek aktualnie nie jest w trkacie ruchu
* @see PlanszaBudowniczy#zresetujObecneWspolrzedne()
*/
public void zresetujObecneWspolrzedne() {
planszaBudowniczy.zresetujObecneWspolrzedne();
}
}
|
156534_1 | package figury;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.util.Random;
public abstract class Figura implements Runnable, ActionListener/*, Shape*/ {
// wspolny bufor
protected Graphics2D buffer;
protected Area area;
// do wykreslania
protected Shape shape;
// przeksztalcenie obiektu
protected AffineTransform aft;
// przesuniecie
private int dx, dy;
// rozciaganie
private double sf;
// kat obrotu
private double an;
private int delay;
private int width;
private int height;
private Color clr;
protected static final Random rand = new Random();
public Figura(Graphics2D buf, int del, int w, int h) {
delay = del;
buffer = buf;
width = w;
height = h;
dx = 1 + rand.nextInt(5);
dy = 1 + rand.nextInt(5);
sf = 1 + 0.05 * rand.nextDouble();
an = 0.1 * rand.nextDouble();
clr = new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255), rand.nextInt(255));
// reszta musi być zawarta w realizacji klasy Figure
// (tworzenie figury i przygotowanie transformacji)
}
@Override
public void run() {
// przesuniecie na srodek
aft.translate(100, 100);
area.transform(aft);
shape = area;
while (true) {
// przygotowanie nastepnego kadru
shape = nextFrame();
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
}
}
}
protected Shape nextFrame() {
// zapamietanie na zmiennej tymczasowej
// aby nie przeszkadzalo w wykreslaniu
area = new Area(area);
aft = new AffineTransform();
Rectangle bounds = area.getBounds();
int cx = bounds.x + bounds.width / 2;
int cy = bounds.y + bounds.height / 2;
// odbicie
if (cx < 0 || cx > width)
dx = -dx;
if (cy < 0 || cy > height)
dy = -dy;
// zwiekszenie lub zmniejszenie
if (bounds.height > height / 3 || bounds.height < 10)
sf = 1 / sf;
// konstrukcja przeksztalcenia
aft.translate(cx, cy);
aft.scale(sf, sf);
aft.rotate(an);
aft.translate(-cx, -cy);
aft.translate(dx, dy);
// przeksztalcenie obiektu
area.transform(aft);
return area;
}
@Override
public void actionPerformed(ActionEvent evt) {
// wypelnienie obiektu
buffer.setColor(clr.brighter());
buffer.fill(shape);
// wykreslenie ramki
buffer.setColor(clr.darker());
buffer.draw(shape);
}
}
| 272869/Jezyki_Programowania | gui_swing_anim-main/gui_swing_anim-main/src/figury/Figura.java | 984 | // wspolny bufor | line_comment | pl | package figury;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.util.Random;
public abstract class Figura implements Runnable, ActionListener/*, Shape*/ {
// ws<SUF>
protected Graphics2D buffer;
protected Area area;
// do wykreslania
protected Shape shape;
// przeksztalcenie obiektu
protected AffineTransform aft;
// przesuniecie
private int dx, dy;
// rozciaganie
private double sf;
// kat obrotu
private double an;
private int delay;
private int width;
private int height;
private Color clr;
protected static final Random rand = new Random();
public Figura(Graphics2D buf, int del, int w, int h) {
delay = del;
buffer = buf;
width = w;
height = h;
dx = 1 + rand.nextInt(5);
dy = 1 + rand.nextInt(5);
sf = 1 + 0.05 * rand.nextDouble();
an = 0.1 * rand.nextDouble();
clr = new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255), rand.nextInt(255));
// reszta musi być zawarta w realizacji klasy Figure
// (tworzenie figury i przygotowanie transformacji)
}
@Override
public void run() {
// przesuniecie na srodek
aft.translate(100, 100);
area.transform(aft);
shape = area;
while (true) {
// przygotowanie nastepnego kadru
shape = nextFrame();
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
}
}
}
protected Shape nextFrame() {
// zapamietanie na zmiennej tymczasowej
// aby nie przeszkadzalo w wykreslaniu
area = new Area(area);
aft = new AffineTransform();
Rectangle bounds = area.getBounds();
int cx = bounds.x + bounds.width / 2;
int cy = bounds.y + bounds.height / 2;
// odbicie
if (cx < 0 || cx > width)
dx = -dx;
if (cy < 0 || cy > height)
dy = -dy;
// zwiekszenie lub zmniejszenie
if (bounds.height > height / 3 || bounds.height < 10)
sf = 1 / sf;
// konstrukcja przeksztalcenia
aft.translate(cx, cy);
aft.scale(sf, sf);
aft.rotate(an);
aft.translate(-cx, -cy);
aft.translate(dx, dy);
// przeksztalcenie obiektu
area.transform(aft);
return area;
}
@Override
public void actionPerformed(ActionEvent evt) {
// wypelnienie obiektu
buffer.setColor(clr.brighter());
buffer.fill(shape);
// wykreslenie ramki
buffer.setColor(clr.darker());
buffer.draw(shape);
}
}
|
73949_0 | package daangnmungcat.service;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class GpsToAddressService {
double latitude;
double longitude;
String regionAddress;
public GpsToAddressService(double latitude, double longitude) throws Exception {
this.latitude = latitude;
this.longitude = longitude;
this.regionAddress = getRegionAddress(getJSONData(getApiAddress()));
}
private String getApiAddress() {
//https://maps.googleapis.com/maps/api/geocode/json?latlng=37.566535,126.977969&language=ko&key=AIzaSyCI3czUjEtTIOLyljHyhEUo6ZVhAiel4Is
//String apiURL = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "&language=ko";
String apiURL = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "&language=ko&key=AIzaSyBydfS3SpBFCvXonhHL9Z-FYm7wzDMTeoQ";
return apiURL;
}
public String getJSONData(String apiURL) throws Exception {
String jsonString = new String();
String buf;
URL url = new URL(apiURL);
URLConnection conn = url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
while ((buf = br.readLine()) != null) {
jsonString += buf;
}
return jsonString;
}
private String getRegionAddress(String jsonString) {
JSONObject jObj = (JSONObject) JSONValue.parse(jsonString);
JSONArray jArray = (JSONArray) jObj.get("results");
jObj = (JSONObject) jArray.get(0);
return (String) jObj.get("formatted_address");
}
public String getAddress() {
return regionAddress;
}
@Override
public String toString() {
return String.format("GpsToAddressService [latitude=%s, longitude=%s, regionAddress=%s]", latitude, longitude,
regionAddress);
}
}
| 2jigoo/daangnmungcat | src/main/java/daangnmungcat/service/GpsToAddressService.java | 690 | //https://maps.googleapis.com/maps/api/geocode/json?latlng=37.566535,126.977969&language=ko&key=AIzaSyCI3czUjEtTIOLyljHyhEUo6ZVhAiel4Is
| line_comment | pl | package daangnmungcat.service;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class GpsToAddressService {
double latitude;
double longitude;
String regionAddress;
public GpsToAddressService(double latitude, double longitude) throws Exception {
this.latitude = latitude;
this.longitude = longitude;
this.regionAddress = getRegionAddress(getJSONData(getApiAddress()));
}
private String getApiAddress() {
//ht<SUF>
//String apiURL = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "&language=ko";
String apiURL = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "&language=ko&key=AIzaSyBydfS3SpBFCvXonhHL9Z-FYm7wzDMTeoQ";
return apiURL;
}
public String getJSONData(String apiURL) throws Exception {
String jsonString = new String();
String buf;
URL url = new URL(apiURL);
URLConnection conn = url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
while ((buf = br.readLine()) != null) {
jsonString += buf;
}
return jsonString;
}
private String getRegionAddress(String jsonString) {
JSONObject jObj = (JSONObject) JSONValue.parse(jsonString);
JSONArray jArray = (JSONArray) jObj.get("results");
jObj = (JSONObject) jArray.get(0);
return (String) jObj.get("formatted_address");
}
public String getAddress() {
return regionAddress;
}
@Override
public String toString() {
return String.format("GpsToAddressService [latitude=%s, longitude=%s, regionAddress=%s]", latitude, longitude,
regionAddress);
}
}
|
53468_7 | package pg.eti.arapp.catan;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageDecoder;
import android.util.Log;
import com.googlecode.tesseract.android.TessBaseAPI;
import org.opencv.android.Utils;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.imgcodecs.Imgcodecs;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import pg.eti.arapp.detectortl.BufferBitmap;
public class CatanCardsDetector {
private TessBaseAPI tessBaseAPI;
public native ArrayList<BufferBitmap> getCardsNative(BufferBitmap bitmap);
public void initTesseract(Context context, String language)
{
this.tessBaseAPI = new TessBaseAPI();
this.setupOCR(context, language);
File dataPath = new File(context.getFilesDir()+"/tesseract");
if(dataPath.exists()) {
if (!this.tessBaseAPI.init(dataPath.getAbsolutePath(), language)) {
// Error initializing Tesseract (wrong data path or language)
//this.tessBaseAPI.recycle();
this.freeTesseract();
Log.d("Tess", "Nooo ;-;");
} else
Log.d("Tess", "Yes :D");
}
}
public void freeTesseract()
{
if(this.tessBaseAPI != null)
this.tessBaseAPI.recycle();
}
private void setupOCR(Context context, String language){
File folder = new File(context.getFilesDir() + "/tesseract/tessdata");
if (!folder.exists()) {
folder.mkdirs();
}
Log.d("Cards", "Folder "+ (folder.exists() ? "exists" : "doesn't exist"));
File saving = new File(folder, language+".traineddata");
try {
saving.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("Cards", "File "+ (saving.exists() ? "exists" : "doesn't exist"));
InputStream stream = null;
try {
stream = context.getAssets().open(language+".traineddata", AssetManager.ACCESS_STREAMING);
} catch (IOException e) {
e.printStackTrace();
}
if (stream != null){
copyInputStreamToFile(stream, saving);
}
}
private void copyInputStreamToFile( InputStream in, File file ) {
Log.d("Cards", "Stream exists");
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// recognition part
public Mat cutOutCardBottom(Mat card, float bottomAreaCoeff)
{
Rect bottomBoundingRect = new Rect(new Point(0, card.size().height * (1.0 - bottomAreaCoeff)), new Point(card.size().width - 1, card.size().height - 1));
Mat cardBottom = card.submat(bottomBoundingRect);//card(bottomBoundingRect);
return cardBottom;
}
public Mat cutOutCardHeading(Mat card, float headingAreaCoeff)
{
Rect headingBoundingRect = new Rect(new Point(0, 0), new Point(card.size().width - 1, card.size().height * headingAreaCoeff - 1));
Mat cardBottom = card.submat(headingBoundingRect);// card(headingBoundingRect);
return cardBottom;
}
private String prepareString(String text)
{
String s = text.replaceAll("[^a-zA-Z]", ""); //trimNonAlphabethical
s = s.toUpperCase();
return s;
}
private int assignCardTypeBasedOnText(String cardText)
{
/*String[] cardsCaptions = {"Koszty budowy", "Rycerz", "Katedra", "Ratusz", "Biblioteka", "Rynek", "Uniwersytet", "Postęp",
"Najwyższa Władza Rycerska 2 Punkty Zwycięstwa", "Najdłuższa Droga Handlowa 2 Punkty Zwycięstwa" };*/
String[] twoPointCardsContents = { "Najwyższa", "Władza", "Rycerska", "Najdłuższa", "Droga Handlowa", "trzy karty rycerz", "pięć połączonych dróg", "Punkty Zwycięstwa" }; // "2 Punkty Zwyci�stwa"
String[] onePointCardsContents = { /*"1",*/ "Punkt", "Zwycięstwa", "Katedra", "Ratusz", "Biblioteka", "Rynek", "Uniwersytet" };
cardText = prepareString(cardText);
String[] costsTableContents = { "Koszty budowy", "Rozwój", "pkt"};
for (String templateText : costsTableContents)
{
//std::cout << "templateText: " << prepareString(templateText) << std::endl;
if (cardText.contains(prepareString(templateText)))
return 0;//scoringCardType::OTHER;
}
for (String templateText : twoPointCardsContents)
{
//std::cout << "templateText: " << prepareString(templateText) << std::endl;
if (cardText.contains(prepareString(templateText)))
return 2;//scoringCardType::TWO_POINTS;
}
for (String templateText : onePointCardsContents)
{
//std::cout << "templateText: " << prepareString(templateText) << std::endl;
if (cardText.contains(prepareString(templateText)))
return 1;//scoringCardType::ONE_POINT;
}
return 0;//scoringCardType::OTHER;
}
public int recognizeCard(Mat card, boolean isPlasticVer)
{
Mat cardCopy = new Mat(); //Mat.zeros(card.size(), card.type())
card.copyTo(cardCopy);
String outText = null;
int cardType = 0;
Mat cardPart;
for (int a = 0; a < 2; a++)
{
if(!isPlasticVer)
cardPart = cutOutCardHeading(cardCopy, 0.2f);
else
cardPart = cutOutCardBottom(cardCopy, 0.4f);
Bitmap bmp = this.convertMatToBitmap(cardPart);
this.tessBaseAPI.setImage(bmp);
outText = this.tessBaseAPI.getUTF8Text();
Log.d("Cards", "Card text"+outText);
//outText = recognizeTextOnImage(cardPart, this.tessBaseAPI);
cardType = assignCardTypeBasedOnText(outText);
//std::cout << "OCR output:\n" << prepareString(std::string(outText)) << std::endl;
//std::cout << "Recognition:\n" << cardTypeToString(cardType) << std::endl;
//cv::imshow("Card part", cardPart);
//cv::waitKey();
if (cardType != 0)
return cardType;
Core.rotate(cardCopy, cardCopy, Core.ROTATE_180);
}
return cardType;
}
public Bitmap convertMatToBitmap(Mat mat)
{
Bitmap bmp = Bitmap.createBitmap(mat.width(), mat.height(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(mat, bmp);
return bmp;
}
public Mat convertBitmapToMat(Bitmap bmp)
{
Bitmap bmp32 = bmp.copy(Bitmap.Config.ARGB_8888, true);
Mat mat = new Mat();
Utils.bitmapToMat(bmp32, mat);
return mat;
}
}
| 311Volt/board-game-ar | app/src/main/java/pg/eti/arapp/catan/CatanCardsDetector.java | 2,248 | // "2 Punkty Zwyci�stwa" | line_comment | pl | package pg.eti.arapp.catan;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageDecoder;
import android.util.Log;
import com.googlecode.tesseract.android.TessBaseAPI;
import org.opencv.android.Utils;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.imgcodecs.Imgcodecs;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import pg.eti.arapp.detectortl.BufferBitmap;
public class CatanCardsDetector {
private TessBaseAPI tessBaseAPI;
public native ArrayList<BufferBitmap> getCardsNative(BufferBitmap bitmap);
public void initTesseract(Context context, String language)
{
this.tessBaseAPI = new TessBaseAPI();
this.setupOCR(context, language);
File dataPath = new File(context.getFilesDir()+"/tesseract");
if(dataPath.exists()) {
if (!this.tessBaseAPI.init(dataPath.getAbsolutePath(), language)) {
// Error initializing Tesseract (wrong data path or language)
//this.tessBaseAPI.recycle();
this.freeTesseract();
Log.d("Tess", "Nooo ;-;");
} else
Log.d("Tess", "Yes :D");
}
}
public void freeTesseract()
{
if(this.tessBaseAPI != null)
this.tessBaseAPI.recycle();
}
private void setupOCR(Context context, String language){
File folder = new File(context.getFilesDir() + "/tesseract/tessdata");
if (!folder.exists()) {
folder.mkdirs();
}
Log.d("Cards", "Folder "+ (folder.exists() ? "exists" : "doesn't exist"));
File saving = new File(folder, language+".traineddata");
try {
saving.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("Cards", "File "+ (saving.exists() ? "exists" : "doesn't exist"));
InputStream stream = null;
try {
stream = context.getAssets().open(language+".traineddata", AssetManager.ACCESS_STREAMING);
} catch (IOException e) {
e.printStackTrace();
}
if (stream != null){
copyInputStreamToFile(stream, saving);
}
}
private void copyInputStreamToFile( InputStream in, File file ) {
Log.d("Cards", "Stream exists");
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// recognition part
public Mat cutOutCardBottom(Mat card, float bottomAreaCoeff)
{
Rect bottomBoundingRect = new Rect(new Point(0, card.size().height * (1.0 - bottomAreaCoeff)), new Point(card.size().width - 1, card.size().height - 1));
Mat cardBottom = card.submat(bottomBoundingRect);//card(bottomBoundingRect);
return cardBottom;
}
public Mat cutOutCardHeading(Mat card, float headingAreaCoeff)
{
Rect headingBoundingRect = new Rect(new Point(0, 0), new Point(card.size().width - 1, card.size().height * headingAreaCoeff - 1));
Mat cardBottom = card.submat(headingBoundingRect);// card(headingBoundingRect);
return cardBottom;
}
private String prepareString(String text)
{
String s = text.replaceAll("[^a-zA-Z]", ""); //trimNonAlphabethical
s = s.toUpperCase();
return s;
}
private int assignCardTypeBasedOnText(String cardText)
{
/*String[] cardsCaptions = {"Koszty budowy", "Rycerz", "Katedra", "Ratusz", "Biblioteka", "Rynek", "Uniwersytet", "Postęp",
"Najwyższa Władza Rycerska 2 Punkty Zwycięstwa", "Najdłuższa Droga Handlowa 2 Punkty Zwycięstwa" };*/
String[] twoPointCardsContents = { "Najwyższa", "Władza", "Rycerska", "Najdłuższa", "Droga Handlowa", "trzy karty rycerz", "pięć połączonych dróg", "Punkty Zwycięstwa" }; // "2<SUF>
String[] onePointCardsContents = { /*"1",*/ "Punkt", "Zwycięstwa", "Katedra", "Ratusz", "Biblioteka", "Rynek", "Uniwersytet" };
cardText = prepareString(cardText);
String[] costsTableContents = { "Koszty budowy", "Rozwój", "pkt"};
for (String templateText : costsTableContents)
{
//std::cout << "templateText: " << prepareString(templateText) << std::endl;
if (cardText.contains(prepareString(templateText)))
return 0;//scoringCardType::OTHER;
}
for (String templateText : twoPointCardsContents)
{
//std::cout << "templateText: " << prepareString(templateText) << std::endl;
if (cardText.contains(prepareString(templateText)))
return 2;//scoringCardType::TWO_POINTS;
}
for (String templateText : onePointCardsContents)
{
//std::cout << "templateText: " << prepareString(templateText) << std::endl;
if (cardText.contains(prepareString(templateText)))
return 1;//scoringCardType::ONE_POINT;
}
return 0;//scoringCardType::OTHER;
}
public int recognizeCard(Mat card, boolean isPlasticVer)
{
Mat cardCopy = new Mat(); //Mat.zeros(card.size(), card.type())
card.copyTo(cardCopy);
String outText = null;
int cardType = 0;
Mat cardPart;
for (int a = 0; a < 2; a++)
{
if(!isPlasticVer)
cardPart = cutOutCardHeading(cardCopy, 0.2f);
else
cardPart = cutOutCardBottom(cardCopy, 0.4f);
Bitmap bmp = this.convertMatToBitmap(cardPart);
this.tessBaseAPI.setImage(bmp);
outText = this.tessBaseAPI.getUTF8Text();
Log.d("Cards", "Card text"+outText);
//outText = recognizeTextOnImage(cardPart, this.tessBaseAPI);
cardType = assignCardTypeBasedOnText(outText);
//std::cout << "OCR output:\n" << prepareString(std::string(outText)) << std::endl;
//std::cout << "Recognition:\n" << cardTypeToString(cardType) << std::endl;
//cv::imshow("Card part", cardPart);
//cv::waitKey();
if (cardType != 0)
return cardType;
Core.rotate(cardCopy, cardCopy, Core.ROTATE_180);
}
return cardType;
}
public Bitmap convertMatToBitmap(Mat mat)
{
Bitmap bmp = Bitmap.createBitmap(mat.width(), mat.height(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(mat, bmp);
return bmp;
}
public Mat convertBitmapToMat(Bitmap bmp)
{
Bitmap bmp32 = bmp.copy(Bitmap.Config.ARGB_8888, true);
Mat mat = new Mat();
Utils.bitmapToMat(bmp32, mat);
return mat;
}
}
|
36412_0 | import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PersonWithParentsNames {
public final Person person;
public final String[] parentNames;
public PersonWithParentsNames(Person person, String[] parents) {
this.person = person;
this.parentNames = parents;
}
public static PersonWithParentsNames fromCsvLine(String line) throws NegativeLifespanException {
Person person = Person.fromCsvLine(line);
String[] fields = line.split(",", -1); //-1 powoduje, ze puste pola na końcu linii nie będą ignorowane, będzie utworzona pusta składowa tablicy
String[] parents = new String[2];
for (int i = 0; i < 2; ++i) {
if (!fields[i + 3].isEmpty())
parents[i] = fields[i + 3];
}
return new PersonWithParentsNames(person, parents);
}
public static void linkRelatives(List<PersonWithParentsNames> people) throws UndefinedParentException {
Map<String, PersonWithParentsNames> peopleMap = new HashMap<>();
for(PersonWithParentsNames personWithNames : people)
peopleMap.put(personWithNames.person.getName(), personWithNames);
for(PersonWithParentsNames personWithNames : people) {
Person person = personWithNames.person;
for (int i = 0; i < 2; ++i) {
String parentName = personWithNames.parentNames[i];
if(parentName != null)
if(peopleMap.containsKey(parentName))
person.addParent(peopleMap.get(parentName).person);
else
throw new UndefinedParentException(person, parentName);
}
}
}
}
| 3entropyy/kolokwium1 | lab4/src/PersonWithParentsNames.java | 469 | //-1 powoduje, ze puste pola na końcu linii nie będą ignorowane, będzie utworzona pusta składowa tablicy | line_comment | pl | import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PersonWithParentsNames {
public final Person person;
public final String[] parentNames;
public PersonWithParentsNames(Person person, String[] parents) {
this.person = person;
this.parentNames = parents;
}
public static PersonWithParentsNames fromCsvLine(String line) throws NegativeLifespanException {
Person person = Person.fromCsvLine(line);
String[] fields = line.split(",", -1); //-1<SUF>
String[] parents = new String[2];
for (int i = 0; i < 2; ++i) {
if (!fields[i + 3].isEmpty())
parents[i] = fields[i + 3];
}
return new PersonWithParentsNames(person, parents);
}
public static void linkRelatives(List<PersonWithParentsNames> people) throws UndefinedParentException {
Map<String, PersonWithParentsNames> peopleMap = new HashMap<>();
for(PersonWithParentsNames personWithNames : people)
peopleMap.put(personWithNames.person.getName(), personWithNames);
for(PersonWithParentsNames personWithNames : people) {
Person person = personWithNames.person;
for (int i = 0; i < 2; ++i) {
String parentName = personWithNames.parentNames[i];
if(parentName != null)
if(peopleMap.containsKey(parentName))
person.addParent(peopleMap.get(parentName).person);
else
throw new UndefinedParentException(person, parentName);
}
}
}
}
|
58848_2 | package pl.edu.pwr.server;
import pl.edu.pwr.server.authentication.AuthImpl;
import pl.edu.pwr.server.secured.SecuredServiceImpl;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class RunServer {
public static void main(String[] args) {
try {
Registry registry = LocateRegistry.createRegistry(1099);
// TODO to co mi przyszło do głowy dla serwera:
// - od klienta powinien przychodzic hash hasła a nie string hasła
// - mozna dodac powiadomienie na serwerze za kazdym razem jak uzytkownik sie polaczy i zaloguje(wtedy który - wyswietlac id)
// Ogólne:
// - dodać taski do gradla zeby odpalało serwer i klienta z tej zakładki na prawo
// - największy problem gradla to póki co znalezienie repozytorium java.rmi w maven central
// Create auth remote object
AuthImpl auth = new AuthImpl();
SecuredServiceImpl service = new SecuredServiceImpl(auth);
// Register remote objects
registry.rebind("AuthService", auth);
registry.rebind("SecuredService", service);
System.out.println("--- Server started ---");
} catch (RemoteException e) {
System.err.println("Server exception: " + e);
e.printStackTrace();
}
}
}
| 404kacper/Depot-RMI | src/main/java/pl/edu/pwr/server/RunServer.java | 412 | // - mozna dodac powiadomienie na serwerze za kazdym razem jak uzytkownik sie polaczy i zaloguje(wtedy który - wyswietlac id) | line_comment | pl | package pl.edu.pwr.server;
import pl.edu.pwr.server.authentication.AuthImpl;
import pl.edu.pwr.server.secured.SecuredServiceImpl;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class RunServer {
public static void main(String[] args) {
try {
Registry registry = LocateRegistry.createRegistry(1099);
// TODO to co mi przyszło do głowy dla serwera:
// - od klienta powinien przychodzic hash hasła a nie string hasła
// - <SUF>
// Ogólne:
// - dodać taski do gradla zeby odpalało serwer i klienta z tej zakładki na prawo
// - największy problem gradla to póki co znalezienie repozytorium java.rmi w maven central
// Create auth remote object
AuthImpl auth = new AuthImpl();
SecuredServiceImpl service = new SecuredServiceImpl(auth);
// Register remote objects
registry.rebind("AuthService", auth);
registry.rebind("SecuredService", service);
System.out.println("--- Server started ---");
} catch (RemoteException e) {
System.err.println("Server exception: " + e);
e.printStackTrace();
}
}
}
|
96026_11 | import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.sql.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
public class AdminDashboard extends JFrame{
private JPanel JPanel1;
private JTable table1;
private JButton closeButton;
private JButton usunButton;
private JPanel close;
private JLabel jDane;
private JLabel jDane2;
private JLabel jDane3;
private JButton ksiazkiButton;
private JButton wylogujButton;
private JLabel jOsoba;
private JTable ksiazkiTable;
private User loggedInUser;
public static void main(String[] args) throws SQLException {
AdminDashboard admindashboard = new AdminDashboard();
admindashboard.setVisible(true);
}
public AdminDashboard() throws SQLException {
setTitle("Panel administracyjny");
this.setContentPane(JPanel1);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
int width = 800, height = 600;
setMinimumSize(new Dimension(width, height));
setLocationRelativeTo(null);
ksiazkiTable = new JTable();
try {
setIconImage(ImageIO.read(new File("src/icon.png")));
} catch (IOException | IllegalArgumentException e) {
System.out.println("Wystąpił błąd przy wczytywaniu icon.png.");
}
Connection connection = Database.getConnection();
String sql = "SELECT * FROM users";
try{
PreparedStatement pst = connection.prepareStatement(sql);
ResultSet rst = pst.executeQuery();
rst.next();
jDane.setText("Zalogowany jako: ");
jDane2.setText("Administrator");
}catch (Exception e){
System.out.println("Error: " + e.getMessage());
}
closeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
usunButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Pobierz zaznaczone ID użytkownika
int selectedRow = table1.getSelectedRow();
if (selectedRow != -1) {
int userId = (int) table1.getValueAt(selectedRow, 0);
try {
// Usuń użytkownika z bazy danych
deleteUser(userId);
// Komunikat o prawidłowym usunięciu użytkownika
JOptionPane.showMessageDialog(null, "Użytkownik został pomyślnie usunięty.", "Sukces", JOptionPane.INFORMATION_MESSAGE);
// Odśwież tabelę po usunięciu użytkownika
refreshTable();
} catch (SQLException ex) {
ex.printStackTrace();
// Komunikat o błędzie podczas usuwania użytkownika
JOptionPane.showMessageDialog(null, "Błąd podczas usuwania użytkownika.", "Błąd", JOptionPane.ERROR_MESSAGE);
}
} else {
// Komunikat gdy nie zaznaczono użytkownika do usunięcia
JOptionPane.showMessageDialog(null, "Nie wybrano użytkownika.", "Błąd", JOptionPane.WARNING_MESSAGE);
}
}
});
ksiazkiButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
AdminBiblioteka adminBiblioteka = null;
try {
adminBiblioteka = new AdminBiblioteka();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
adminBiblioteka.setVisible(true);
}
});
try {
PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
DefaultTableModel model = new DefaultTableModel(new String[]{
"ID",
"Imię i nazwisko",
"Mail",
"Wypożyczone książki",
"Zalegające książki",
"Opłaty"
}, 0);
while (rs.next()) {
int userId = rs.getInt("id");
String userName = rs.getString("name") + " " + rs.getString("surname");
String userMail = rs.getString("mail");
String userBooks = rs.getString("books");
// Dodaj warunek sprawdzający, czy userBooks jest null
String[] borrowedBooks = (userBooks != null) ? userBooks.split(", ") : new String[]{};
String overdueBooks = getOverdueBooks(userBooks);
String overdueFees = "";
// Dodaj warunek sprawdzający, czy borrowedBooks nie jest null
if (borrowedBooks != null) {
overdueFees = String.valueOf(calculateOverdueFees(overdueBooks));
}
model.addRow(new String[]{
String.valueOf(userId),
userName,
userMail,
String.valueOf(borrowedBooks.length), // Zmiana: Ilość wypożyczonych książek
overdueBooks,
overdueFees
});
}
table1.setModel(model);
} catch (Exception ex) {
System.out.println("Error: " + ex.getMessage());
}
wylogujButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
menu Menu = new menu();
Menu.setVisible(true);
}
});
}
private double calculateOverdueFees(String books) {
double overdueFees = 0.0;
if (books != null && !books.isEmpty()) {
String[] bookList = books.split(", ");
for (String book : bookList) {
String[] bookInfo = book.split(":");
if (bookInfo.length == 2) {
String returnDate = bookInfo[1];
// Sprawdź, czy książka jest zaległa
if (returnDate != null && !returnDate.isEmpty()) {
try {
LocalDate currentDate = LocalDate.now();
LocalDate dueDate = LocalDate.parse(returnDate.trim());
if (currentDate.isAfter(dueDate)) {
long daysOverdue = ChronoUnit.DAYS.between(dueDate, currentDate);
overdueFees += daysOverdue * 3.0; // Przyjęta stawka za opóźnienie (1 dzień = 3 zł)
}
} catch (DateTimeParseException e) {
// Dodaj obsługę błędnych dat (jeśli występują)
System.err.println("Błąd podczas parsowania daty: " + e.getMessage());
}
}
}
}
}
return overdueFees;
}
private void deleteUser(int userId) throws SQLException {
Connection connection = Database.getConnection();
String deleteSql = "DELETE FROM users WHERE id = ?";
try (PreparedStatement pst = connection.prepareStatement(deleteSql)) {
pst.setInt(1, userId);
pst.executeUpdate();
}
}
private void refreshTable() {
}
private String getOverdueBooks(String books) {
StringBuilder overdueBooks = new StringBuilder();
if (books != null && !books.isEmpty()) {
String[] bookList = books.split(", ");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
for (String book : bookList) {
String[] bookInfo = book.split(":");
if (bookInfo.length == 2) {
String bookName = bookInfo[0];
String returnDate = bookInfo[1];
// Sprawdź, czy książka jest zaległa
if (returnDate != null && !returnDate.isEmpty()) {
try {
LocalDate currentDate = LocalDate.now();
LocalDate dueDate = LocalDate.parse(returnDate.trim(), formatter);
if (currentDate.isAfter(dueDate)) {
if (overdueBooks.length() > 0) {
overdueBooks.append(", ");
}
overdueBooks.append(bookName).append(":").append(returnDate);
}
} catch (DateTimeParseException e) {
// Dodaj obsługę błędnych dat (jeśli występują)
System.err.println("Błąd podczas parsowania daty: " + e.getMessage());
}
}
}
}
}
return overdueBooks.toString();
}
}
| 404ptk/wirtualna_biblioteka | src/AdminDashboard.java | 2,564 | // Dodaj obsługę błędnych dat (jeśli występują)
| line_comment | pl | import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.sql.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
public class AdminDashboard extends JFrame{
private JPanel JPanel1;
private JTable table1;
private JButton closeButton;
private JButton usunButton;
private JPanel close;
private JLabel jDane;
private JLabel jDane2;
private JLabel jDane3;
private JButton ksiazkiButton;
private JButton wylogujButton;
private JLabel jOsoba;
private JTable ksiazkiTable;
private User loggedInUser;
public static void main(String[] args) throws SQLException {
AdminDashboard admindashboard = new AdminDashboard();
admindashboard.setVisible(true);
}
public AdminDashboard() throws SQLException {
setTitle("Panel administracyjny");
this.setContentPane(JPanel1);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
int width = 800, height = 600;
setMinimumSize(new Dimension(width, height));
setLocationRelativeTo(null);
ksiazkiTable = new JTable();
try {
setIconImage(ImageIO.read(new File("src/icon.png")));
} catch (IOException | IllegalArgumentException e) {
System.out.println("Wystąpił błąd przy wczytywaniu icon.png.");
}
Connection connection = Database.getConnection();
String sql = "SELECT * FROM users";
try{
PreparedStatement pst = connection.prepareStatement(sql);
ResultSet rst = pst.executeQuery();
rst.next();
jDane.setText("Zalogowany jako: ");
jDane2.setText("Administrator");
}catch (Exception e){
System.out.println("Error: " + e.getMessage());
}
closeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
usunButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Pobierz zaznaczone ID użytkownika
int selectedRow = table1.getSelectedRow();
if (selectedRow != -1) {
int userId = (int) table1.getValueAt(selectedRow, 0);
try {
// Usuń użytkownika z bazy danych
deleteUser(userId);
// Komunikat o prawidłowym usunięciu użytkownika
JOptionPane.showMessageDialog(null, "Użytkownik został pomyślnie usunięty.", "Sukces", JOptionPane.INFORMATION_MESSAGE);
// Odśwież tabelę po usunięciu użytkownika
refreshTable();
} catch (SQLException ex) {
ex.printStackTrace();
// Komunikat o błędzie podczas usuwania użytkownika
JOptionPane.showMessageDialog(null, "Błąd podczas usuwania użytkownika.", "Błąd", JOptionPane.ERROR_MESSAGE);
}
} else {
// Komunikat gdy nie zaznaczono użytkownika do usunięcia
JOptionPane.showMessageDialog(null, "Nie wybrano użytkownika.", "Błąd", JOptionPane.WARNING_MESSAGE);
}
}
});
ksiazkiButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
AdminBiblioteka adminBiblioteka = null;
try {
adminBiblioteka = new AdminBiblioteka();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
adminBiblioteka.setVisible(true);
}
});
try {
PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
DefaultTableModel model = new DefaultTableModel(new String[]{
"ID",
"Imię i nazwisko",
"Mail",
"Wypożyczone książki",
"Zalegające książki",
"Opłaty"
}, 0);
while (rs.next()) {
int userId = rs.getInt("id");
String userName = rs.getString("name") + " " + rs.getString("surname");
String userMail = rs.getString("mail");
String userBooks = rs.getString("books");
// Dodaj warunek sprawdzający, czy userBooks jest null
String[] borrowedBooks = (userBooks != null) ? userBooks.split(", ") : new String[]{};
String overdueBooks = getOverdueBooks(userBooks);
String overdueFees = "";
// Dodaj warunek sprawdzający, czy borrowedBooks nie jest null
if (borrowedBooks != null) {
overdueFees = String.valueOf(calculateOverdueFees(overdueBooks));
}
model.addRow(new String[]{
String.valueOf(userId),
userName,
userMail,
String.valueOf(borrowedBooks.length), // Zmiana: Ilość wypożyczonych książek
overdueBooks,
overdueFees
});
}
table1.setModel(model);
} catch (Exception ex) {
System.out.println("Error: " + ex.getMessage());
}
wylogujButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
menu Menu = new menu();
Menu.setVisible(true);
}
});
}
private double calculateOverdueFees(String books) {
double overdueFees = 0.0;
if (books != null && !books.isEmpty()) {
String[] bookList = books.split(", ");
for (String book : bookList) {
String[] bookInfo = book.split(":");
if (bookInfo.length == 2) {
String returnDate = bookInfo[1];
// Sprawdź, czy książka jest zaległa
if (returnDate != null && !returnDate.isEmpty()) {
try {
LocalDate currentDate = LocalDate.now();
LocalDate dueDate = LocalDate.parse(returnDate.trim());
if (currentDate.isAfter(dueDate)) {
long daysOverdue = ChronoUnit.DAYS.between(dueDate, currentDate);
overdueFees += daysOverdue * 3.0; // Przyjęta stawka za opóźnienie (1 dzień = 3 zł)
}
} catch (DateTimeParseException e) {
// Do<SUF>
System.err.println("Błąd podczas parsowania daty: " + e.getMessage());
}
}
}
}
}
return overdueFees;
}
private void deleteUser(int userId) throws SQLException {
Connection connection = Database.getConnection();
String deleteSql = "DELETE FROM users WHERE id = ?";
try (PreparedStatement pst = connection.prepareStatement(deleteSql)) {
pst.setInt(1, userId);
pst.executeUpdate();
}
}
private void refreshTable() {
}
private String getOverdueBooks(String books) {
StringBuilder overdueBooks = new StringBuilder();
if (books != null && !books.isEmpty()) {
String[] bookList = books.split(", ");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
for (String book : bookList) {
String[] bookInfo = book.split(":");
if (bookInfo.length == 2) {
String bookName = bookInfo[0];
String returnDate = bookInfo[1];
// Sprawdź, czy książka jest zaległa
if (returnDate != null && !returnDate.isEmpty()) {
try {
LocalDate currentDate = LocalDate.now();
LocalDate dueDate = LocalDate.parse(returnDate.trim(), formatter);
if (currentDate.isAfter(dueDate)) {
if (overdueBooks.length() > 0) {
overdueBooks.append(", ");
}
overdueBooks.append(bookName).append(":").append(returnDate);
}
} catch (DateTimeParseException e) {
// Dodaj obsługę błędnych dat (jeśli występują)
System.err.println("Błąd podczas parsowania daty: " + e.getMessage());
}
}
}
}
}
return overdueBooks.toString();
}
}
|
143261_1 | package pl.koziel.liebert.magahurtomonitor.Model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by wojciech.liebert on 01.01.2018.
*/
/**
* Dostarczenie zleceń zakupu towarów przez jednego dostawcę.
*/
public class Dostawa {
@SerializedName("DostawcaNrDostawcy")
@Expose
private int dostawcaNrDostawcy;
@SerializedName("PotrzebneTowary")
@Expose
private List<PotrzebnyTowar> potrzebneTowary;
public int getDostawcaNrDostawcy() {
return dostawcaNrDostawcy;
}
public void setDostawcaNrDostawcy(int dostawcaNrDostawcy) {
this.dostawcaNrDostawcy = dostawcaNrDostawcy;
}
public List<PotrzebnyTowar> getPotrzebneTowary() {
return potrzebneTowary;
}
public void setPotrzebneTowary(List<PotrzebnyTowar> potrzebneTowary) {
this.potrzebneTowary = potrzebneTowary;
}
} | 5l1v3r1/Magazyn_PO | app/src/main/java/pl/koziel/liebert/magahurtomonitor/Model/Dostawa.java | 398 | /**
* Dostarczenie zleceń zakupu towarów przez jednego dostawcę.
*/ | block_comment | pl | package pl.koziel.liebert.magahurtomonitor.Model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by wojciech.liebert on 01.01.2018.
*/
/**
* Dos<SUF>*/
public class Dostawa {
@SerializedName("DostawcaNrDostawcy")
@Expose
private int dostawcaNrDostawcy;
@SerializedName("PotrzebneTowary")
@Expose
private List<PotrzebnyTowar> potrzebneTowary;
public int getDostawcaNrDostawcy() {
return dostawcaNrDostawcy;
}
public void setDostawcaNrDostawcy(int dostawcaNrDostawcy) {
this.dostawcaNrDostawcy = dostawcaNrDostawcy;
}
public List<PotrzebnyTowar> getPotrzebneTowary() {
return potrzebneTowary;
}
public void setPotrzebneTowary(List<PotrzebnyTowar> potrzebneTowary) {
this.potrzebneTowary = potrzebneTowary;
}
} |
82061_15 | // jDownloader - Downloadmanager
// Copyright (C) 2014 JD-Team support@jdownloader.org
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.hoster;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import org.appwork.utils.formatter.SizeFormatter;
import org.appwork.utils.formatter.TimeFormatter;
import org.jdownloader.gui.translate._GUI;
import org.jdownloader.plugins.controller.host.LazyHostPlugin.FEATURE;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Browser;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.http.URLConnectionAdapter;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginConfigPanelNG;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
@HostPlugin(revision = "$Revision$", interfaceVersion = 3, names = { "xt7.pl" }, urls = { "" })
public class Xt7Pl extends PluginForHost {
private String MAINPAGE = "https://xt7.pl/";
private static HashMap<Account, HashMap<String, Long>> hostUnavailableMap = new HashMap<Account, HashMap<String, Long>>();
private static Object LOCK = new Object();
public Xt7Pl(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium(MAINPAGE + "login");
}
@Override
public FEATURE[] getFeatures() {
return new FEATURE[] { FEATURE.MULTIHOST };
}
private void login(Account account, boolean force) throws PluginException, IOException {
synchronized (LOCK) {
try {
br.postPage(MAINPAGE + "login", "login=" + Encoding.urlEncode(account.getUser()) + "&password=" + Encoding.urlEncode(account.getPass()));
if (br.getCookie(MAINPAGE, "autologin") == null) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("PREMIUM_ERROR"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
// Save cookies
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
account.setProperty("cookies", cookies);
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
List<String> getSupportedHosts() {
List<String> supportedHosts = new ArrayList<String>();
String hosts;
try {
hosts = br.getPage(MAINPAGE + "jdhostingi.txt");
} catch (IOException e) {
return null;
}
if (hosts != null) {
String hoster[] = new Regex(hosts, "([A-Zaa-z0-9]+\\.[A-Zaa-z0-9]+)").getColumn(0);
for (String host : hoster) {
if (hosts == null || host.length() == 0) {
continue;
}
supportedHosts.add(host.trim());
}
return supportedHosts;
} else {
return null;
}
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
String validUntil = null;
final AccountInfo ai = new AccountInfo();
br.setConnectTimeout(60 * 1000);
br.setReadTimeout(60 * 1000);
login(account, true);
if (!br.getURL().contains("mojekonto")) {
br.getPage("/mojekonto");
}
if (br.containsHTML("Brak ważnego dostępu Premium")) {
ai.setExpired(true);
// ai.setStatus("Account expired");
ai.setStatus(getPhrase("EXPIRED"));
ai.setProperty("premium", "FALSE");
return ai;
} else if (br.containsHTML(">Brak ważnego dostępu Premium<")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("UNSUPPORTED_PREMIUM"), PluginException.VALUE_ID_PREMIUM_DISABLE);
} else {
validUntil = br.getRegex("<div class=\"textPremium\">Dostęp Premium ważny do <b>(.*?)</b><br />").getMatch(0);
if (validUntil == null) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("PLUGIN_BROKEN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
validUntil = validUntil.replace(" / ", " ");
ai.setProperty("premium", "TRUE");
}
long expireTime = TimeFormatter.getMilliSeconds(validUntil, "dd.MM.yyyy HH:mm", Locale.ENGLISH);
ai.setValidUntil(expireTime);
account.setValid(true);
String otherHostersLimitLeft = // br.getRegex(" Pozostały limit na serwisy dodatkowe: <b>([^<>\"\\']+)</b></div>").getMatch(0);
br.getRegex("Pozostały Limit Premium do wykorzystania: <b>([^<>\"\\']+)</b></div>").getMatch(0);
if (otherHostersLimitLeft == null) {
otherHostersLimitLeft = br.getRegex("Pozostały limit na serwisy dodatkowe: <b>([^<>\"\\']+)</b></div>").getMatch(0);
}
ai.setProperty("TRAFFIC_LEFT", otherHostersLimitLeft == null ? getPhrase("UNKNOWN") : SizeFormatter.getSize(otherHostersLimitLeft));
String unlimited = br.getRegex("<br />(.*): <b>Bez limitu</b> \\|").getMatch(0);
if (unlimited != null) {
ai.setProperty("UNLIMITED", unlimited);
}
ai.setStatus("Premium" + " (" + getPhrase("TRAFFIC_LEFT") + ": " + (otherHostersLimitLeft == null ? getPhrase("UNKNOWN") : otherHostersLimitLeft) + (unlimited == null ? "" : ", " + unlimited + ": " + getPhrase("UNLIMITED")) + ")");
if (otherHostersLimitLeft != null) {
ai.setTrafficLeft(SizeFormatter.getSize(otherHostersLimitLeft));
}
List<String> supportedHostsList = getSupportedHosts();
ai.setMultiHostSupport(this, supportedHostsList);
return ai;
}
@Override
public String getAGBLink() {
return MAINPAGE + "regulamin";
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 0;
}
@Override
public void handleFree(DownloadLink downloadLink) throws Exception, PluginException {
throw new PluginException(LinkStatus.ERROR_PREMIUM, PluginException.VALUE_ID_PREMIUM_ONLY);
}
private void showMessage(DownloadLink link, String message) {
link.getLinkStatus().setStatusText(message);
}
/** no override to keep plugin compatible to old stable */
public void handleMultiHost(final DownloadLink link, final Account account) throws Exception {
synchronized (hostUnavailableMap) {
HashMap<String, Long> unavailableMap = hostUnavailableMap.get(account);
if (unavailableMap != null) {
Long lastUnavailable = unavailableMap.get(link.getHost());
if (lastUnavailable != null && System.currentTimeMillis() < lastUnavailable) {
final long wait = lastUnavailable - System.currentTimeMillis();
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, getPhrase("HOSTER_UNAVAILABLE") + " " + this.getHost(), wait);
} else if (lastUnavailable != null) {
unavailableMap.remove(link.getHost());
if (unavailableMap.size() == 0) {
hostUnavailableMap.remove(account);
}
}
}
}
final String downloadUrl = link.getPluginPatternMatcher();
boolean resume = true;
showMessage(link, "Phase 1/3: Login");
login(account, false);
br.setConnectTimeout(90 * 1000);
br.setReadTimeout(90 * 1000);
dl = null;
// each time new download link is generated
// (so even after user interrupted download) - transfer
// is reduced, so:
// first check if the property generatedLink was previously generated
// if so, then try to use it, generated link store in link properties
// for future usage (broken download etc)
String generatedLink = checkDirectLink(link, "generatedLinkXt7");
if (generatedLink == null) {
/* generate new downloadlink */
String url = Encoding.urlEncode(downloadUrl);
String postData = "step=1" + "&content=" + url;
showMessage(link, "Phase 2/3: Generating Link");
br.postPage(MAINPAGE + "mojekonto/sciagaj", postData);
if (br.containsHTML("Wymagane dodatkowe [0-9.]+ MB limitu")) {
logger.severe("Xt7.pl(Error): " + br.getRegex("(Wymagane dodatkowe [0-9.]+ MB limitu)"));
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, getPhrase("DOWNLOAD_LIMIT"), 1 * 60 * 1000l);
}
postData = "step=2" + "&0=on";
br.postPage(MAINPAGE + "mojekonto/sciagaj", postData);
// New Regex, but not tested if it works for all files (not video)
// String generatedLink =
// br.getRegex("<div class=\"download\">(<a target=\"_blank\" href=\"mojekonto/ogladaj/[0-9A-Za-z]*?\">Oglądaj online</a> /
// )*?<a href=\"([^\"<>]+)\" target=\"_blank\">Pobierz</a>").getMatch(1);
// Old Regex
generatedLink = br.getRegex("<div class=\"download\"><a href=\"([^\"<>]+)\" target=\"_blank\">Pobierz</a>").getMatch(0);
if (generatedLink == null) {
// New Regex (works with video files)
generatedLink = br.getRegex("<div class=\"download\">(<a target=\"_blank\" href=\"mojekonto/ogladaj/[0-9A-Za-z]*?\">Oglądaj[ online]*?</a> / )<a href=\"([^\"<>]+)\" target=\"_blank\">Pobierz</a>").getMatch(1);
}
if (generatedLink == null) {
logger.severe("Xt7.pl(Error): " + generatedLink);
//
// after x retries we disable this host and retry with normal plugin
// but because traffic limit is decreased even if there's a problem
// with download (seems like bug) - we limit retries to 2
//
if (link.getLinkStatus().getRetryCount() >= 2) {
try {
// disable hoster for 30min
tempUnavailableHoster(account, link, 30 * 60 * 1000l);
} catch (Exception e) {
}
/* reset retrycounter */
link.getLinkStatus().setRetryCount(0);
final String inactiveLink = br.getRegex("textarea id=\"listInactive\" class=\"small\" readonly>(.*?)[ \t\n\r]+</textarea>").getMatch(0);
if (downloadUrl.compareTo(inactiveLink) != 0) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, getPhrase("LINK_INACTIVE"), 30 * 1000l);
}
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE);
}
String msg = "(" + link.getLinkStatus().getRetryCount() + 1 + "/" + 2 + ")";
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, getPhrase("RETRY") + msg, 20 * 1000l);
}
link.setProperty("generatedLinkXt7", generatedLink);
}
// wait, workaround
sleep(1 * 1000l, link);
int chunks = 0;
// generated fileshark/lunaticfiles link allows only 1 chunk
// because download doesn't support more chunks and
// and resume (header response has no: "Content-Range" info)
final String url = link.getPluginPatternMatcher();
final String oneChunkHostersPattern = ".*(lunaticfiles\\.com|fileshark\\.pl).*";
if (url.matches(oneChunkHostersPattern) || downloadUrl.matches(oneChunkHostersPattern)) {
chunks = 1;
resume = false;
}
dl = jd.plugins.BrowserAdapter.openDownload(br, link, generatedLink, resume, chunks);
if (dl.getConnection().getContentType().equalsIgnoreCase("text/html")) // unknown
// error
{
br.followConnection();
if (br.containsHTML("<div id=\"message\">Ważność linka wygasła.</div>")) {
// previously generated link expired,
// clear the property and restart the download
// and generate new link
sleep(10 * 1000l, link, getPhrase("LINK_EXPIRED"));
logger.info("Xt7.pl: previously generated link expired - removing it and restarting download process.");
link.setProperty("generatedLinkXt7", null);
throw new PluginException(LinkStatus.ERROR_RETRY);
}
if (br.getBaseURL().contains("notransfer")) {
/* No traffic left */
account.getAccountInfo().setTrafficLeft(0);
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("NO_TRAFFIC"), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE);
}
if (br.getBaseURL().contains("serviceunavailable")) {
tempUnavailableHoster(account, link, 60 * 60 * 1000l);
}
if (br.getBaseURL().contains("connecterror")) {
tempUnavailableHoster(account, link, 60 * 60 * 1000l);
}
if (br.getBaseURL().contains("invaliduserpass")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("PREMIUM_ERROR"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ((br.getBaseURL().contains("notfound")) || (br.containsHTML("404 Not Found"))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
if (br.containsHTML("Wymagane dodatkowe [0-9.]+ MB limitu")) {
logger.severe("Xt7.pl(Error): " + br.getRegex("(Wymagane dodatkowe [0-9.]+ MB limitu)"));
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, getPhrase("DOWNLOAD_LIMIT"), 1 * 60 * 1000l);
}
}
if (dl.getConnection().getResponseCode() == 404) {
/* file offline */
dl.getConnection().disconnect();
tempUnavailableHoster(account, link, 20 * 60 * 1000l);
}
showMessage(link, "Phase 3/3: Begin download");
dl.startDownload();
}
private String checkDirectLink(final DownloadLink downloadLink, final String property) {
String dllink = downloadLink.getStringProperty(property);
if (dllink != null) {
URLConnectionAdapter con = null;
try {
final Browser br2 = br.cloneBrowser();
con = br2.openGetConnection(dllink);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
// try redirected link
boolean resetGeneratedLink = true;
String redirectConnection = br2.getRedirectLocation();
if (redirectConnection != null) {
if (redirectConnection.contains("xt7.pl")) {
con = br2.openGetConnection(redirectConnection);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
resetGeneratedLink = true;
} else {
resetGeneratedLink = false;
}
} else { // turbobit link is already redirected link
resetGeneratedLink = false;
}
}
if (resetGeneratedLink) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
}
} catch (final Exception e) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
} finally {
try {
con.disconnect();
} catch (final Throwable e) {
}
}
}
return dllink;
}
@Override
public AvailableStatus requestFileInformation(DownloadLink link) throws Exception {
return AvailableStatus.UNCHECKABLE;
}
private void tempUnavailableHoster(Account account, DownloadLink downloadLink, long timeout) throws PluginException {
if (downloadLink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT, getPhrase("UNKNOWN_ERROR"));
}
synchronized (hostUnavailableMap) {
HashMap<String, Long> unavailableMap = hostUnavailableMap.get(account);
if (unavailableMap == null) {
unavailableMap = new HashMap<String, Long>();
hostUnavailableMap.put(account, unavailableMap);
}
/* wait to retry this host */
unavailableMap.put(downloadLink.getHost(), (System.currentTimeMillis() + timeout));
}
throw new PluginException(LinkStatus.ERROR_RETRY);
}
@Override
public boolean canHandle(DownloadLink downloadLink, Account account) throws Exception {
return true;
}
@Override
public void reset() {
}
@Override
public void resetDownloadlink(DownloadLink link) {
link.setProperty("generatedLinkXt7", null);
}
@Override
public void extendAccountSettingsPanel(Account acc, PluginConfigPanelNG panel) {
AccountInfo ai = acc.getAccountInfo();
if (ai == null) {
return;
}
if (!"FALSE".equals(ai.getProperty("premium"))) {
long otherHostersLimit = Long.parseLong(ai.getProperty("TRAFFIC_LEFT").toString(), 10);
String unlimited = (String) (ai.getProperty("UNLIMITED"));
panel.addStringPair(_GUI.T.lit_traffic_left(), SizeFormatter.formatBytes(otherHostersLimit) + (unlimited == null ? "" : "\n" + unlimited + ": " + getPhrase("UNLIMITED")));
}
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("PREMIUM_ERROR", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("UNSUPPORTED_PREMIUM", "\r\nUnsupported account type!\r\nIf you think this message is incorrect or it makes sense to add support for this account type\r\ncontact us via our support forum.");
put("PLUGIN_BROKEN", "\r\nPlugin broken, please contact the JDownloader Support!");
put("TRAFFIC_LEFT", "Traffic left");
put("HOSTER_UNAVAILABLE", "Host is temporarily unavailable via");
put("DOWNLOAD_LIMIT", "Download limit exceeded!");
put("RETRY", "Retry in few secs");
put("LINK_INACTIVE", "Xt7 reports the link is as inactive!");
put("LINK_EXPIRED", "Previously generated Link expired!");
put("NO_TRAFFIC", "No traffic left");
put("UNKNOWN_ERROR", "Unable to handle this errorcode!");
put("ACCOUNT_TYPE", "Account type");
put("UNKNOWN", "Unknown");
put("UNLIMITED", "Unlimited");
put("FREE", "free");
put("EXPIRED", "Account expired/free");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("PREMIUM_ERROR", "\r\nNieprawidłowy użytkownik/hasło!\r\nUpewnij się, że wprowadziłeś poprawnie użytkownika i hasło. Podpowiedzi:\r\n1. Jeśli w twoim haśle znajdują się znaki specjalne - usuń je/popraw i wprowadź ponownie hasło!\r\n2. Wprowadzając nazwę użytkownika i hasło - nie używaj operacji Kopiuj i Wklej.");
put("UNSUPPORTED_PREMIUM", "\r\nNieobsługiwany typ konta!\r\nJesli uważasz, że informacja ta jest niepoprawna i chcesz aby dodac obsługę tego typu konta\r\nskontaktuj się z nami poprzez forum wsparcia.");
put("PLUGIN_BROKEN", "\r\nProblem z wtyczką, skontaktuj się z zespołem wsparcia JDownloader!");
put("TRAFFIC_LEFT", "Pozostały transfer");
put("HOSTER_UNAVAILABLE", "Serwis jest niedostępny przez");
put("DOWNLOAD_LIMIT", "Przekroczono dostępny limit transferu!");
put("RETRY", "Ponawianie za kilka sekund");
put("LINK_INACTIVE", "Xt7 raportuje link jako nieaktywny!");
put("LINK_EXPIRED", "Poprzednio wygenerowany link wygasł!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("UNKNOWN_ERROR", "Nieobsługiwany kod błędu!");
put("ACCOUNT_TYPE", "Typ konta");
put("UNKNOWN", "Nieznany");
put("UNLIMITED", "Bez limitu");
put("FREE", "darmowe");
put("EXPIRED", "Konto wygasło/darmowe");
}
};
/**
* Returns a Polish/English translation of a phrase. We don't use the JDownloader translation framework since we need only Polish and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
String language = System.getProperty("user.language");
if ("pl".equals(language) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} | 5l1v3r1/jdownloader | src/jd/plugins/hoster/Xt7Pl.java | 6,873 | // br.getRegex(" Pozostały limit na serwisy dodatkowe: <b>([^<>\"\\']+)</b></div>").getMatch(0);
| line_comment | pl | // jDownloader - Downloadmanager
// Copyright (C) 2014 JD-Team support@jdownloader.org
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.hoster;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import org.appwork.utils.formatter.SizeFormatter;
import org.appwork.utils.formatter.TimeFormatter;
import org.jdownloader.gui.translate._GUI;
import org.jdownloader.plugins.controller.host.LazyHostPlugin.FEATURE;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Browser;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.http.URLConnectionAdapter;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginConfigPanelNG;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
@HostPlugin(revision = "$Revision$", interfaceVersion = 3, names = { "xt7.pl" }, urls = { "" })
public class Xt7Pl extends PluginForHost {
private String MAINPAGE = "https://xt7.pl/";
private static HashMap<Account, HashMap<String, Long>> hostUnavailableMap = new HashMap<Account, HashMap<String, Long>>();
private static Object LOCK = new Object();
public Xt7Pl(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium(MAINPAGE + "login");
}
@Override
public FEATURE[] getFeatures() {
return new FEATURE[] { FEATURE.MULTIHOST };
}
private void login(Account account, boolean force) throws PluginException, IOException {
synchronized (LOCK) {
try {
br.postPage(MAINPAGE + "login", "login=" + Encoding.urlEncode(account.getUser()) + "&password=" + Encoding.urlEncode(account.getPass()));
if (br.getCookie(MAINPAGE, "autologin") == null) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("PREMIUM_ERROR"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
// Save cookies
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
account.setProperty("cookies", cookies);
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
List<String> getSupportedHosts() {
List<String> supportedHosts = new ArrayList<String>();
String hosts;
try {
hosts = br.getPage(MAINPAGE + "jdhostingi.txt");
} catch (IOException e) {
return null;
}
if (hosts != null) {
String hoster[] = new Regex(hosts, "([A-Zaa-z0-9]+\\.[A-Zaa-z0-9]+)").getColumn(0);
for (String host : hoster) {
if (hosts == null || host.length() == 0) {
continue;
}
supportedHosts.add(host.trim());
}
return supportedHosts;
} else {
return null;
}
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
String validUntil = null;
final AccountInfo ai = new AccountInfo();
br.setConnectTimeout(60 * 1000);
br.setReadTimeout(60 * 1000);
login(account, true);
if (!br.getURL().contains("mojekonto")) {
br.getPage("/mojekonto");
}
if (br.containsHTML("Brak ważnego dostępu Premium")) {
ai.setExpired(true);
// ai.setStatus("Account expired");
ai.setStatus(getPhrase("EXPIRED"));
ai.setProperty("premium", "FALSE");
return ai;
} else if (br.containsHTML(">Brak ważnego dostępu Premium<")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("UNSUPPORTED_PREMIUM"), PluginException.VALUE_ID_PREMIUM_DISABLE);
} else {
validUntil = br.getRegex("<div class=\"textPremium\">Dostęp Premium ważny do <b>(.*?)</b><br />").getMatch(0);
if (validUntil == null) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("PLUGIN_BROKEN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
validUntil = validUntil.replace(" / ", " ");
ai.setProperty("premium", "TRUE");
}
long expireTime = TimeFormatter.getMilliSeconds(validUntil, "dd.MM.yyyy HH:mm", Locale.ENGLISH);
ai.setValidUntil(expireTime);
account.setValid(true);
String otherHostersLimitLeft = // br<SUF>
br.getRegex("Pozostały Limit Premium do wykorzystania: <b>([^<>\"\\']+)</b></div>").getMatch(0);
if (otherHostersLimitLeft == null) {
otherHostersLimitLeft = br.getRegex("Pozostały limit na serwisy dodatkowe: <b>([^<>\"\\']+)</b></div>").getMatch(0);
}
ai.setProperty("TRAFFIC_LEFT", otherHostersLimitLeft == null ? getPhrase("UNKNOWN") : SizeFormatter.getSize(otherHostersLimitLeft));
String unlimited = br.getRegex("<br />(.*): <b>Bez limitu</b> \\|").getMatch(0);
if (unlimited != null) {
ai.setProperty("UNLIMITED", unlimited);
}
ai.setStatus("Premium" + " (" + getPhrase("TRAFFIC_LEFT") + ": " + (otherHostersLimitLeft == null ? getPhrase("UNKNOWN") : otherHostersLimitLeft) + (unlimited == null ? "" : ", " + unlimited + ": " + getPhrase("UNLIMITED")) + ")");
if (otherHostersLimitLeft != null) {
ai.setTrafficLeft(SizeFormatter.getSize(otherHostersLimitLeft));
}
List<String> supportedHostsList = getSupportedHosts();
ai.setMultiHostSupport(this, supportedHostsList);
return ai;
}
@Override
public String getAGBLink() {
return MAINPAGE + "regulamin";
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 0;
}
@Override
public void handleFree(DownloadLink downloadLink) throws Exception, PluginException {
throw new PluginException(LinkStatus.ERROR_PREMIUM, PluginException.VALUE_ID_PREMIUM_ONLY);
}
private void showMessage(DownloadLink link, String message) {
link.getLinkStatus().setStatusText(message);
}
/** no override to keep plugin compatible to old stable */
public void handleMultiHost(final DownloadLink link, final Account account) throws Exception {
synchronized (hostUnavailableMap) {
HashMap<String, Long> unavailableMap = hostUnavailableMap.get(account);
if (unavailableMap != null) {
Long lastUnavailable = unavailableMap.get(link.getHost());
if (lastUnavailable != null && System.currentTimeMillis() < lastUnavailable) {
final long wait = lastUnavailable - System.currentTimeMillis();
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, getPhrase("HOSTER_UNAVAILABLE") + " " + this.getHost(), wait);
} else if (lastUnavailable != null) {
unavailableMap.remove(link.getHost());
if (unavailableMap.size() == 0) {
hostUnavailableMap.remove(account);
}
}
}
}
final String downloadUrl = link.getPluginPatternMatcher();
boolean resume = true;
showMessage(link, "Phase 1/3: Login");
login(account, false);
br.setConnectTimeout(90 * 1000);
br.setReadTimeout(90 * 1000);
dl = null;
// each time new download link is generated
// (so even after user interrupted download) - transfer
// is reduced, so:
// first check if the property generatedLink was previously generated
// if so, then try to use it, generated link store in link properties
// for future usage (broken download etc)
String generatedLink = checkDirectLink(link, "generatedLinkXt7");
if (generatedLink == null) {
/* generate new downloadlink */
String url = Encoding.urlEncode(downloadUrl);
String postData = "step=1" + "&content=" + url;
showMessage(link, "Phase 2/3: Generating Link");
br.postPage(MAINPAGE + "mojekonto/sciagaj", postData);
if (br.containsHTML("Wymagane dodatkowe [0-9.]+ MB limitu")) {
logger.severe("Xt7.pl(Error): " + br.getRegex("(Wymagane dodatkowe [0-9.]+ MB limitu)"));
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, getPhrase("DOWNLOAD_LIMIT"), 1 * 60 * 1000l);
}
postData = "step=2" + "&0=on";
br.postPage(MAINPAGE + "mojekonto/sciagaj", postData);
// New Regex, but not tested if it works for all files (not video)
// String generatedLink =
// br.getRegex("<div class=\"download\">(<a target=\"_blank\" href=\"mojekonto/ogladaj/[0-9A-Za-z]*?\">Oglądaj online</a> /
// )*?<a href=\"([^\"<>]+)\" target=\"_blank\">Pobierz</a>").getMatch(1);
// Old Regex
generatedLink = br.getRegex("<div class=\"download\"><a href=\"([^\"<>]+)\" target=\"_blank\">Pobierz</a>").getMatch(0);
if (generatedLink == null) {
// New Regex (works with video files)
generatedLink = br.getRegex("<div class=\"download\">(<a target=\"_blank\" href=\"mojekonto/ogladaj/[0-9A-Za-z]*?\">Oglądaj[ online]*?</a> / )<a href=\"([^\"<>]+)\" target=\"_blank\">Pobierz</a>").getMatch(1);
}
if (generatedLink == null) {
logger.severe("Xt7.pl(Error): " + generatedLink);
//
// after x retries we disable this host and retry with normal plugin
// but because traffic limit is decreased even if there's a problem
// with download (seems like bug) - we limit retries to 2
//
if (link.getLinkStatus().getRetryCount() >= 2) {
try {
// disable hoster for 30min
tempUnavailableHoster(account, link, 30 * 60 * 1000l);
} catch (Exception e) {
}
/* reset retrycounter */
link.getLinkStatus().setRetryCount(0);
final String inactiveLink = br.getRegex("textarea id=\"listInactive\" class=\"small\" readonly>(.*?)[ \t\n\r]+</textarea>").getMatch(0);
if (downloadUrl.compareTo(inactiveLink) != 0) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, getPhrase("LINK_INACTIVE"), 30 * 1000l);
}
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE);
}
String msg = "(" + link.getLinkStatus().getRetryCount() + 1 + "/" + 2 + ")";
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, getPhrase("RETRY") + msg, 20 * 1000l);
}
link.setProperty("generatedLinkXt7", generatedLink);
}
// wait, workaround
sleep(1 * 1000l, link);
int chunks = 0;
// generated fileshark/lunaticfiles link allows only 1 chunk
// because download doesn't support more chunks and
// and resume (header response has no: "Content-Range" info)
final String url = link.getPluginPatternMatcher();
final String oneChunkHostersPattern = ".*(lunaticfiles\\.com|fileshark\\.pl).*";
if (url.matches(oneChunkHostersPattern) || downloadUrl.matches(oneChunkHostersPattern)) {
chunks = 1;
resume = false;
}
dl = jd.plugins.BrowserAdapter.openDownload(br, link, generatedLink, resume, chunks);
if (dl.getConnection().getContentType().equalsIgnoreCase("text/html")) // unknown
// error
{
br.followConnection();
if (br.containsHTML("<div id=\"message\">Ważność linka wygasła.</div>")) {
// previously generated link expired,
// clear the property and restart the download
// and generate new link
sleep(10 * 1000l, link, getPhrase("LINK_EXPIRED"));
logger.info("Xt7.pl: previously generated link expired - removing it and restarting download process.");
link.setProperty("generatedLinkXt7", null);
throw new PluginException(LinkStatus.ERROR_RETRY);
}
if (br.getBaseURL().contains("notransfer")) {
/* No traffic left */
account.getAccountInfo().setTrafficLeft(0);
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("NO_TRAFFIC"), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE);
}
if (br.getBaseURL().contains("serviceunavailable")) {
tempUnavailableHoster(account, link, 60 * 60 * 1000l);
}
if (br.getBaseURL().contains("connecterror")) {
tempUnavailableHoster(account, link, 60 * 60 * 1000l);
}
if (br.getBaseURL().contains("invaliduserpass")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("PREMIUM_ERROR"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ((br.getBaseURL().contains("notfound")) || (br.containsHTML("404 Not Found"))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
if (br.containsHTML("Wymagane dodatkowe [0-9.]+ MB limitu")) {
logger.severe("Xt7.pl(Error): " + br.getRegex("(Wymagane dodatkowe [0-9.]+ MB limitu)"));
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, getPhrase("DOWNLOAD_LIMIT"), 1 * 60 * 1000l);
}
}
if (dl.getConnection().getResponseCode() == 404) {
/* file offline */
dl.getConnection().disconnect();
tempUnavailableHoster(account, link, 20 * 60 * 1000l);
}
showMessage(link, "Phase 3/3: Begin download");
dl.startDownload();
}
private String checkDirectLink(final DownloadLink downloadLink, final String property) {
String dllink = downloadLink.getStringProperty(property);
if (dllink != null) {
URLConnectionAdapter con = null;
try {
final Browser br2 = br.cloneBrowser();
con = br2.openGetConnection(dllink);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
// try redirected link
boolean resetGeneratedLink = true;
String redirectConnection = br2.getRedirectLocation();
if (redirectConnection != null) {
if (redirectConnection.contains("xt7.pl")) {
con = br2.openGetConnection(redirectConnection);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
resetGeneratedLink = true;
} else {
resetGeneratedLink = false;
}
} else { // turbobit link is already redirected link
resetGeneratedLink = false;
}
}
if (resetGeneratedLink) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
}
} catch (final Exception e) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
} finally {
try {
con.disconnect();
} catch (final Throwable e) {
}
}
}
return dllink;
}
@Override
public AvailableStatus requestFileInformation(DownloadLink link) throws Exception {
return AvailableStatus.UNCHECKABLE;
}
private void tempUnavailableHoster(Account account, DownloadLink downloadLink, long timeout) throws PluginException {
if (downloadLink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT, getPhrase("UNKNOWN_ERROR"));
}
synchronized (hostUnavailableMap) {
HashMap<String, Long> unavailableMap = hostUnavailableMap.get(account);
if (unavailableMap == null) {
unavailableMap = new HashMap<String, Long>();
hostUnavailableMap.put(account, unavailableMap);
}
/* wait to retry this host */
unavailableMap.put(downloadLink.getHost(), (System.currentTimeMillis() + timeout));
}
throw new PluginException(LinkStatus.ERROR_RETRY);
}
@Override
public boolean canHandle(DownloadLink downloadLink, Account account) throws Exception {
return true;
}
@Override
public void reset() {
}
@Override
public void resetDownloadlink(DownloadLink link) {
link.setProperty("generatedLinkXt7", null);
}
@Override
public void extendAccountSettingsPanel(Account acc, PluginConfigPanelNG panel) {
AccountInfo ai = acc.getAccountInfo();
if (ai == null) {
return;
}
if (!"FALSE".equals(ai.getProperty("premium"))) {
long otherHostersLimit = Long.parseLong(ai.getProperty("TRAFFIC_LEFT").toString(), 10);
String unlimited = (String) (ai.getProperty("UNLIMITED"));
panel.addStringPair(_GUI.T.lit_traffic_left(), SizeFormatter.formatBytes(otherHostersLimit) + (unlimited == null ? "" : "\n" + unlimited + ": " + getPhrase("UNLIMITED")));
}
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("PREMIUM_ERROR", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("UNSUPPORTED_PREMIUM", "\r\nUnsupported account type!\r\nIf you think this message is incorrect or it makes sense to add support for this account type\r\ncontact us via our support forum.");
put("PLUGIN_BROKEN", "\r\nPlugin broken, please contact the JDownloader Support!");
put("TRAFFIC_LEFT", "Traffic left");
put("HOSTER_UNAVAILABLE", "Host is temporarily unavailable via");
put("DOWNLOAD_LIMIT", "Download limit exceeded!");
put("RETRY", "Retry in few secs");
put("LINK_INACTIVE", "Xt7 reports the link is as inactive!");
put("LINK_EXPIRED", "Previously generated Link expired!");
put("NO_TRAFFIC", "No traffic left");
put("UNKNOWN_ERROR", "Unable to handle this errorcode!");
put("ACCOUNT_TYPE", "Account type");
put("UNKNOWN", "Unknown");
put("UNLIMITED", "Unlimited");
put("FREE", "free");
put("EXPIRED", "Account expired/free");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("PREMIUM_ERROR", "\r\nNieprawidłowy użytkownik/hasło!\r\nUpewnij się, że wprowadziłeś poprawnie użytkownika i hasło. Podpowiedzi:\r\n1. Jeśli w twoim haśle znajdują się znaki specjalne - usuń je/popraw i wprowadź ponownie hasło!\r\n2. Wprowadzając nazwę użytkownika i hasło - nie używaj operacji Kopiuj i Wklej.");
put("UNSUPPORTED_PREMIUM", "\r\nNieobsługiwany typ konta!\r\nJesli uważasz, że informacja ta jest niepoprawna i chcesz aby dodac obsługę tego typu konta\r\nskontaktuj się z nami poprzez forum wsparcia.");
put("PLUGIN_BROKEN", "\r\nProblem z wtyczką, skontaktuj się z zespołem wsparcia JDownloader!");
put("TRAFFIC_LEFT", "Pozostały transfer");
put("HOSTER_UNAVAILABLE", "Serwis jest niedostępny przez");
put("DOWNLOAD_LIMIT", "Przekroczono dostępny limit transferu!");
put("RETRY", "Ponawianie za kilka sekund");
put("LINK_INACTIVE", "Xt7 raportuje link jako nieaktywny!");
put("LINK_EXPIRED", "Poprzednio wygenerowany link wygasł!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("UNKNOWN_ERROR", "Nieobsługiwany kod błędu!");
put("ACCOUNT_TYPE", "Typ konta");
put("UNKNOWN", "Nieznany");
put("UNLIMITED", "Bez limitu");
put("FREE", "darmowe");
put("EXPIRED", "Konto wygasło/darmowe");
}
};
/**
* Returns a Polish/English translation of a phrase. We don't use the JDownloader translation framework since we need only Polish and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
String language = System.getProperty("user.language");
if ("pl".equals(language) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} |
28013_2 | package wtf.norma.nekito.module.impl;
import net.minecraft.client.entity.AbstractClientPlayer;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.entity.RenderManager;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
import wtf.norma.nekito.event.Event;
import wtf.norma.nekito.event.impl.*;
import wtf.norma.nekito.module.Module;
import wtf.norma.nekito.settings.impl.ModeSetting;
import wtf.norma.nekito.util.math.MathUtility;
import wtf.norma.nekito.util.render.models.TessellatorModel;
import wtf.norma.nekito.event.impl.EventCustomModel;
public class CustomModel extends Module {
public ModeSetting mode = new ModeSetting("Mode", "Hitla", "Hitla", "Jake","Baba");
public CustomModel() {
super("CustomModel", Category.VISUALS, Keyboard.KEY_NONE);
addSettings(mode);
}
private TessellatorModel hitlerHead;
private TessellatorModel hitlerBody;
private TessellatorModel jake;
private TessellatorModel baba;
@Override
public void onEnable() {
super.onEnable();
this.hitlerHead = new TessellatorModel("/assets/minecraft/nekito/head.obj");
this.hitlerBody = new TessellatorModel("/assets/minecraft/nekito/body.obj");
this.jake = new TessellatorModel("/assets/minecraft/nekito/Jake.obj");
this.baba = new TessellatorModel("/assets/minecraft/nekito/Aether.obj"); // ta z genshina kojarze ja bo gralem
// cwele z mihoyo kiedy kurwa wkoncu ten jeabny nintendo switch support bo na tym jebanym nvidia now sie grac nie dai
}
@Override
public void onDisable() {
super.onDisable();
this.hitlerHead = null;
this.jake = null;
this.hitlerBody = null;
this.baba = null;
}
// nie wiem
// https://www.youtube.com/watch?v=xjD8MiCe9BU
public void onEvent(Event event) {
if (event instanceof EventCustomModel) {
GlStateManager.pushMatrix();
AbstractClientPlayer entity = mc.thePlayer; // tu mozna zmienic np na friends jak dodam ale mi sie nie chce Xddddddddd
RenderManager manager = mc.getRenderManager();
double x = MathUtility.interpolate(entity.posX, entity.lastTickPosX, mc.getRenderPartialTicks()) - manager.renderPosX;
double y = MathUtility.interpolate(entity.posY, entity.lastTickPosY, mc.getRenderPartialTicks()) - manager.renderPosY;
double z = MathUtility.interpolate(entity.posZ, entity.lastTickPosZ, mc.getRenderPartialTicks()) - manager.renderPosZ;
float yaw = mc.thePlayer.prevRotationYaw + (mc.thePlayer.rotationYaw - mc.thePlayer.prevRotationYaw) * mc.getRenderPartialTicks();
boolean sneak = mc.thePlayer.isSneaking();
GL11.glTranslated(x, y, z);
if (!(mc.currentScreen instanceof GuiContainer))
GL11.glRotatef(-yaw, 0.0F, mc.thePlayer.height, 0.0F);
switch (mode.getMode()) {
case"Hitla":
GlStateManager.scale(0.03, sneak ? 0.027 : 0.029, 0.03);
GlStateManager.disableLighting();
GlStateManager.color(1, 1, 1, 1.0F);
this.hitlerHead.render();
this.hitlerBody.render();
break;
case "Jake":
GlStateManager.scale(0.3, sneak ? 0.27 : 0.29, 0.3);
GlStateManager.disableLighting();
GlStateManager.color(1, 1, 1, 1.0F);
this.jake.render();
break;
case"Baba":
GlStateManager.scale(0.3, sneak ? 0.12 : 0.15, 0.3);
GlStateManager.disableLighting();
GlStateManager.color(1, 1, 1, 1.0F);
this.baba.render();
break;
}
GlStateManager.enableLighting();
GlStateManager.resetColor();
GlStateManager.popMatrix();
}
}
}
| 5l1v3r1/nekito | src/main/java/wtf/norma/nekito/module/impl/CustomModel.java | 1,338 | // nie wiem | line_comment | pl | package wtf.norma.nekito.module.impl;
import net.minecraft.client.entity.AbstractClientPlayer;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.entity.RenderManager;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
import wtf.norma.nekito.event.Event;
import wtf.norma.nekito.event.impl.*;
import wtf.norma.nekito.module.Module;
import wtf.norma.nekito.settings.impl.ModeSetting;
import wtf.norma.nekito.util.math.MathUtility;
import wtf.norma.nekito.util.render.models.TessellatorModel;
import wtf.norma.nekito.event.impl.EventCustomModel;
public class CustomModel extends Module {
public ModeSetting mode = new ModeSetting("Mode", "Hitla", "Hitla", "Jake","Baba");
public CustomModel() {
super("CustomModel", Category.VISUALS, Keyboard.KEY_NONE);
addSettings(mode);
}
private TessellatorModel hitlerHead;
private TessellatorModel hitlerBody;
private TessellatorModel jake;
private TessellatorModel baba;
@Override
public void onEnable() {
super.onEnable();
this.hitlerHead = new TessellatorModel("/assets/minecraft/nekito/head.obj");
this.hitlerBody = new TessellatorModel("/assets/minecraft/nekito/body.obj");
this.jake = new TessellatorModel("/assets/minecraft/nekito/Jake.obj");
this.baba = new TessellatorModel("/assets/minecraft/nekito/Aether.obj"); // ta z genshina kojarze ja bo gralem
// cwele z mihoyo kiedy kurwa wkoncu ten jeabny nintendo switch support bo na tym jebanym nvidia now sie grac nie dai
}
@Override
public void onDisable() {
super.onDisable();
this.hitlerHead = null;
this.jake = null;
this.hitlerBody = null;
this.baba = null;
}
// ni<SUF>
// https://www.youtube.com/watch?v=xjD8MiCe9BU
public void onEvent(Event event) {
if (event instanceof EventCustomModel) {
GlStateManager.pushMatrix();
AbstractClientPlayer entity = mc.thePlayer; // tu mozna zmienic np na friends jak dodam ale mi sie nie chce Xddddddddd
RenderManager manager = mc.getRenderManager();
double x = MathUtility.interpolate(entity.posX, entity.lastTickPosX, mc.getRenderPartialTicks()) - manager.renderPosX;
double y = MathUtility.interpolate(entity.posY, entity.lastTickPosY, mc.getRenderPartialTicks()) - manager.renderPosY;
double z = MathUtility.interpolate(entity.posZ, entity.lastTickPosZ, mc.getRenderPartialTicks()) - manager.renderPosZ;
float yaw = mc.thePlayer.prevRotationYaw + (mc.thePlayer.rotationYaw - mc.thePlayer.prevRotationYaw) * mc.getRenderPartialTicks();
boolean sneak = mc.thePlayer.isSneaking();
GL11.glTranslated(x, y, z);
if (!(mc.currentScreen instanceof GuiContainer))
GL11.glRotatef(-yaw, 0.0F, mc.thePlayer.height, 0.0F);
switch (mode.getMode()) {
case"Hitla":
GlStateManager.scale(0.03, sneak ? 0.027 : 0.029, 0.03);
GlStateManager.disableLighting();
GlStateManager.color(1, 1, 1, 1.0F);
this.hitlerHead.render();
this.hitlerBody.render();
break;
case "Jake":
GlStateManager.scale(0.3, sneak ? 0.27 : 0.29, 0.3);
GlStateManager.disableLighting();
GlStateManager.color(1, 1, 1, 1.0F);
this.jake.render();
break;
case"Baba":
GlStateManager.scale(0.3, sneak ? 0.12 : 0.15, 0.3);
GlStateManager.disableLighting();
GlStateManager.color(1, 1, 1, 1.0F);
this.baba.render();
break;
}
GlStateManager.enableLighting();
GlStateManager.resetColor();
GlStateManager.popMatrix();
}
}
}
|
135988_1 | package com.example.lsoapp;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.room.RoomDatabase;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.room.Room;
import androidx.sqlite.db.SupportSQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
PlanNaTydzien_DB planNaTydzien_db;
public EditText imie;
public EditText dzien;
public EditText godzina;
List<DodanieSluzby> list = new ArrayList<>();
Button button;
Button button2;
Button button3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
planNaTydzien_db = PlanNaTydzien_DB.zwrocInstancjeBazy(getApplicationContext());
imie = findViewById(R.id.imie);
dzien = findViewById(R.id.dzien);
godzina = findViewById(R.id.godzina);
button = findViewById(R.id.button);
button2 = findViewById(R.id.button2);
button3 = findViewById(R.id.button3);
//przycisk dodający osobę do bazy danych
button.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Integer.parseInt(godzina.getText().toString()) == 7 || Integer.parseInt(godzina.getText().toString()) == 18) {
DodanieSluzby dodanieSluzby = new DodanieSluzby(imie.getText().toString(), dzien.getText().toString(), Integer.parseInt(godzina.getText().toString()));
planNaTydzien_db.getPlanDao().dodajOsobe(dodanieSluzby);
imie.setText("");
dzien.setText("");
godzina.setText("");
}
else{
godzina.setText("");
}
}
}
);
//przycisk przenoszący użytkownika do aktywności z planem służb
button2.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, PlanTydzienList.class);
startActivity(intent);
}
}
);
//przycisk używający funkcji do pobrania danych z pliku db.json poprzez Retrofit
button3.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
pobierzBazeDanych();
}
}
);
}
//funkcja popierająca dane członków z pliku db.json za pomocą Retrofit
public void pobierzBazeDanych() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://my-json-server.typicode.com/617ka/LSOApp/")
.addConverterFactory(GsonConverterFactory.create()).build();
JsonPlaceholderApi jsonPlaceholderApi = retrofit.create(JsonPlaceholderApi.class);
Call<List<DodanieSluzby>> call = jsonPlaceholderApi.getCzlonkow();
call.enqueue(
new Callback<List<DodanieSluzby>>() {
@Override
public void onResponse(Call<List<DodanieSluzby>> call, Response<List<DodanieSluzby>> response) {
if (!response.isSuccessful()) {
Toast.makeText(MainActivity.this, response.code(), Toast.LENGTH_SHORT).show();
} else {
for (DodanieSluzby item : response.body()) {
list.add(item);
}
for (DodanieSluzby item1 : list) {
planNaTydzien_db.getPlanDao().dodajOsobe(item1);
}
}
}
@Override
public void onFailure(Call<List<DodanieSluzby>> call, Throwable t) {
}
}
);
}
}
| 617ka/LSOApp | app/src/main/java/com/example/lsoapp/MainActivity.java | 1,306 | //przycisk przenoszący użytkownika do aktywności z planem służb | line_comment | pl | package com.example.lsoapp;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.room.RoomDatabase;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.room.Room;
import androidx.sqlite.db.SupportSQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
PlanNaTydzien_DB planNaTydzien_db;
public EditText imie;
public EditText dzien;
public EditText godzina;
List<DodanieSluzby> list = new ArrayList<>();
Button button;
Button button2;
Button button3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
planNaTydzien_db = PlanNaTydzien_DB.zwrocInstancjeBazy(getApplicationContext());
imie = findViewById(R.id.imie);
dzien = findViewById(R.id.dzien);
godzina = findViewById(R.id.godzina);
button = findViewById(R.id.button);
button2 = findViewById(R.id.button2);
button3 = findViewById(R.id.button3);
//przycisk dodający osobę do bazy danych
button.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Integer.parseInt(godzina.getText().toString()) == 7 || Integer.parseInt(godzina.getText().toString()) == 18) {
DodanieSluzby dodanieSluzby = new DodanieSluzby(imie.getText().toString(), dzien.getText().toString(), Integer.parseInt(godzina.getText().toString()));
planNaTydzien_db.getPlanDao().dodajOsobe(dodanieSluzby);
imie.setText("");
dzien.setText("");
godzina.setText("");
}
else{
godzina.setText("");
}
}
}
);
//pr<SUF>
button2.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, PlanTydzienList.class);
startActivity(intent);
}
}
);
//przycisk używający funkcji do pobrania danych z pliku db.json poprzez Retrofit
button3.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
pobierzBazeDanych();
}
}
);
}
//funkcja popierająca dane członków z pliku db.json za pomocą Retrofit
public void pobierzBazeDanych() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://my-json-server.typicode.com/617ka/LSOApp/")
.addConverterFactory(GsonConverterFactory.create()).build();
JsonPlaceholderApi jsonPlaceholderApi = retrofit.create(JsonPlaceholderApi.class);
Call<List<DodanieSluzby>> call = jsonPlaceholderApi.getCzlonkow();
call.enqueue(
new Callback<List<DodanieSluzby>>() {
@Override
public void onResponse(Call<List<DodanieSluzby>> call, Response<List<DodanieSluzby>> response) {
if (!response.isSuccessful()) {
Toast.makeText(MainActivity.this, response.code(), Toast.LENGTH_SHORT).show();
} else {
for (DodanieSluzby item : response.body()) {
list.add(item);
}
for (DodanieSluzby item1 : list) {
planNaTydzien_db.getPlanDao().dodajOsobe(item1);
}
}
}
@Override
public void onFailure(Call<List<DodanieSluzby>> call, Throwable t) {
}
}
);
}
}
|
16472_0 | package pl.programowaniezespolowe.planner.dtos;
import lombok.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.Date;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class CalendarEventDto {
private int id;
private String title;
private Instant start;
private Instant end;
// powinien zawierac primary i secondary color - na razie niech zostanie to ustawiane na froncie
// private String[] color;
//opcjonalne - nie obslugujemy tego na razie na backu - na razie na froncie bedzie dodawane recznie
//okresla akcje dostepne dla eventu np edycje lub dodawanie notatki
//w przyszlosci mozna zmienic na enum
// a11yLabel: 'Edit' lub a11yLabel: 'Note'
// private String[] actions;
//opcjonalne - nie obslugujemy tego na razie
// private Integer draggable;
//opcjonalne - nie obslugujemy tego na razie
// private Integer beforeStart;
//opcjonalne - nie obslugujemy tego na razie
// private Integer afterEnd;
}
//back musi obsluzyc odebranie i wyslanie obiektu calendarevent w Event
//calendar event ma byc zwracany/wysylany z:
// title, start, end (end jest opcjonalne)
| 7GitHub7/planner_backend | src/main/java/pl/programowaniezespolowe/planner/dtos/CalendarEventDto.java | 402 | // powinien zawierac primary i secondary color - na razie niech zostanie to ustawiane na froncie | line_comment | pl | package pl.programowaniezespolowe.planner.dtos;
import lombok.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.Date;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class CalendarEventDto {
private int id;
private String title;
private Instant start;
private Instant end;
// po<SUF>
// private String[] color;
//opcjonalne - nie obslugujemy tego na razie na backu - na razie na froncie bedzie dodawane recznie
//okresla akcje dostepne dla eventu np edycje lub dodawanie notatki
//w przyszlosci mozna zmienic na enum
// a11yLabel: 'Edit' lub a11yLabel: 'Note'
// private String[] actions;
//opcjonalne - nie obslugujemy tego na razie
// private Integer draggable;
//opcjonalne - nie obslugujemy tego na razie
// private Integer beforeStart;
//opcjonalne - nie obslugujemy tego na razie
// private Integer afterEnd;
}
//back musi obsluzyc odebranie i wyslanie obiektu calendarevent w Event
//calendar event ma byc zwracany/wysylany z:
// title, start, end (end jest opcjonalne)
|
60281_0 | package com.example.mpklubartow.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "stops_";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableQueryFirst = "CREATE TABLE IF NOT EXISTS stops_f ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "busStop TEXT, "
+ "time1 DATETIME, "
+ "time2 DATETIME, "
+ "time3 DATETIME, "
+ "time4 DATETIME, "
+ "time5 DATETIME, "
+ "time6 DATETIME, "
+ "time7 DATETIME, "
+ "time8 DATETIME)";
db.execSQL(createTableQueryFirst);
String insertDataQueryFirst = "INSERT INTO stops_f (busStop, time1, time2, time3, time4, time5, time6, time7, time8) "
+ "VALUES "
+ "('ul. Hutnicza', '05:00', '06:55', '08:50', '10:20', '14:00', '16:05', '18:00', '19:25'), "
+ "('ul. Kolejowa / DW PKP', '05:01', '06:56', '08:51', '10:21', '14:01', '16:06', '18:01', '19:26'), "
+ "('ul. Powstańców Warszawy', '05:02', '06:57', '08:52', '10:22', '14:02', '16:07', '18:02', '19:27'), "
+ "('ul. Cicha / Spółdzielnia Mieszkaniowa', '05:04', '06:59', '08:54', '10:24', '14:04', '16:09', '18:04', '19:29'), "
+ "('ul. 1 Maja / Topaz', '05:06', '07:01', '08:56', '10:26', '14:06', '16:11', '18:06', '19:31'), "
+ "('ul. Piaskowa / ul. 1 Maja', '05:07', '07:02', '08:57', '10:27', '14:07', '16:12', '18:07', '19:32'), "
+ "('ul. Łąkowa / ul. Piaskowa', '05:08', '07:03', '08:58', '10:28', '14:08', '16:13', '18:08', '19:33'), "
+ "('ul. Łąkowa / Szpital', '05:09', '07:04', '08:59', '10:29', '14:09', '16:14', '18:09', '19:34'), "
+ "('ul. Cicha / Policja', '05:10', '07:05', '09:00', '10:30', '14:10', '16:15', '18:10', '19:35'), "
+ "('ul. Lubelska / przy skrzyżowaniu z ul. Mickiewicza', '05:11', '07:06', '09:01', '10:31', '14:11', '16:16', '18:11', '19:36'), "
+ "('ul. Partyzancka / PEC', '05:13', '07:08', '09:03', '10:33', '14:13', '16:18', '18:13', '19:38'), "
+ "('ul. Farna / Targ', '05:14', '07:09', '09:04', '10:34', '14:14', '16:19', '18:14', '19:39'), "
+ "('ul. Szaniawskiego', '05:16', '07:11', '09:06', '10:36', '14:16', '16:21', '18:16', '19:40'), "
+ "('Aleje Tysiąclecia', '05:18', '07:13', '09:08', '10:38', '14:18', '16:23', '18:18', '19:42'), "
+ "('ul. Nowodworska', '05:19', '07:14', '09:09', '10:39', '14:19', '16:24', '18:19', '19:43'), "
+ "('ul. Lipowa III', '05:22', '07:17', '09:12', '10:42', '14:22', '16:27', '18:22', '19:45'), "
+ "('ul. Lipowa II', '05:23', '07:18', '09:13', '10:43', '14:23', '16:28', '18:23', '19:46'), "
+ "('ul. Lipowa I', '05:24', '07:19', '09:14', '10:44', '14:24', '16:29', '18:24', '19:47'), "
+ "('ul. Chopina / I LO', '05:25', '07:20', '09:15', '10:45', '14:25', '16:30', '18:25', '19:48'), "
+ "('ul. K. Jadwigi / Al. Zwycięstwa', '05:28', '07:23', '09:18', '10:48', '14:28', '16:33', '18:28', '19:50'), "
+ "('ul. Mieszka I / ul. Leśna', '05:30', '07:25', '09:20', '10:50', '14:30', '16:35', '18:30', '19:52'), "
+ "('Kopernika II', '05:32', '07:27', '09:22', '10:52', '14:32', '16:37', '18:32', '19:54'), "
+ "('ul. Polesie / ul. Kawalerzystów', '05:33', '07:28', '09:23', '10:53', '14:33', '16:38', '18:33', '19:56'), "
+ "('ul. Polesie / ul. Lotników', '05:34', '07:29', '09:24', '10:54', '14:34', '16:39', '18:34', '19:57'), "
+ "('ul. Kosmonautów / SP 4', '05:35', '07:30', '09:25', '10:55', '14:35', '16:40', '18:35', '19:58'), "
+ "('Lisów V / Kościół', '05:36', '07:31', '09:26', '10:56', '14:36', '16:41', '18:36', '19:59')";
db.execSQL(insertDataQueryFirst);
String createTableQuerySecond = "CREATE TABLE IF NOT EXISTS stops_s ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "busStop TEXT, "
+ "time1 TEXT, "
+ "time2 TEXT, "
+ "time3 TEXT, "
+ "time4 TEXT, "
+ "time5 TEXT, "
+ "time6 TEXT, "
+ "time7 TEXT, "
+ "time8 TEXT)";
db.execSQL(createTableQuerySecond);
String insertDataQuerySecond = "INSERT INTO stops_s (busStop, time1, time2, time3, time4, time5, time6, time7, time8) "
+ "VALUES "
+ "('Lisów V / Kościół', '05:40', '07:35', '09:30', '11:05', '13:15', '14:40', '16:45', '18:45'), "
+ "('ul. Kosmonautów / SP 4', '05:41', '07:36', '09:31', '11:06', '13:16', '14:41', '16:46', '18:46'), "
+ "('ul. Polesie / ul. Lotników', '05:42', '07:37', '09:32', '11:07', '13:17', '14:42', '16:47', '18:47'), "
+ "('ul. Polesie / ul. Kawalerzystów', '05:43', '07:38', '09:33', '11:08', '13:18', '14:43', '16:48', '18:48'), "
+ "('ul. Kopernika II', '05:44', '07:39', '09:34', '11:09', '13:19', '14:44', '16:49', '18:49'), "
+ "('ul. Mieszka I / ul. Leśna', '05:46', '07:41', '09:36', '11:11', '13:21', '14:46', '16:51', '18:51'), "
+ "('ul. K. Jadwigi / Al.Zwycięstwa', '05:47', '07:42', '09:37', '11:12', '13:22', '14:47', '16:52', '15:52'), "
+ "('ul. Lipowa I', '05:49', '07:44', '09:39', '11:14', '13:24', '14:49', '16:54', '18:54'), "
+ "('ul. Chopina / I LO', '05:52', '07:47', '09:42', '11:17', '13:27', '14:52', '16:57', '18:57'), "
+ "('ul. Lipowa II', '05:54', '07:49', '09:44', '11:19', '13:29', '14:54', '16:59', '18:58'), "
+ "('ul. Lipowa III', '05:56', '07:51', '09:46', '11:21', '13:31', '14:56', '17:01', '18:59'), "
+ "('ul. Nowodworska', '05:58', '07:53', '09:48', '11:23', '13:33', '14:58', '17:03', '19:01'), "
+ "('Aleje Tysiąclecia', '05:59', '07:54', '09:49', '11:24', '13:34', '14:59', '17:04', '19:03'), "
+ "('ul. Szaniawskiego', '06:02', '07:57', '09:52', '11:27', '13:37', '15:02', '17:07', '19:05'), "
+ "('ul. Farna / Targ', '06:03', '07:58', '09:53', '11:28', '13:38', '15:03', '17:08', '19:06'), "
+ "('ul. Partyzancka / PEC', '06:04', '07:59', '09:54', '11:29', '13:39', '15:04', '17:09', '19:08'), "
+ "('ul. Lubelska / przy skrzyżowaniu z ul. Mickiewicza', '06:06', '08:01', '09:56', '11:31', '13:41', '15:06', '17:11', '19:10'), "
+ "('ul. Cicha / Spółdzielnia Mieszkaniowa', '06:07', '08:02', '09:57', '11:32', '13:42', '15:07', '17:12', '19:11'), "
+ "('ul. Łąkowa / Szpital', '06:08', '08:03', '09:58', '11:33', '13:43', '15:08', '17:13', '19:12'), "
+ "('ul. Łąkowa / ul. Piaskowa', '06:09', '08:04', '09:59', '11:34', '13:44', '15:09', '17:14', '19:13'), "
+ "('ul. Piaskowa / ul. 1 Maja', '06:10', '08:05', '10:00', '11:35', '13:45', '15:10', '17:15', '19:15'), "
+ "('ul. 1 Maja / Topaz', '06:12', '08:07', '10:02', '11:37', '13:47', '15:12', '17:17', '19:16'), "
+ "('ul. Cicha / Policja', '06:13', '08:08', '10:03', '11:38', '13:48', '15:13', '17:18', '19:17'), "
+ "('ul. Powstańców Warszawy', '06:17', '08:12', '10:07', '11:42', '13:52', '15:17', '17:22', '19:19'), "
+ "('ul. Kolejowa / DW PKP', '06:18', '08:13', '10:08', '11:43', '13:53', '15:18', '17:23', '19:21'), "
+ "('ul. Hutnicza', '06:20', '08:15', '10:10', '11:45', '13:55', '15:20', '17:25', '19:23')";
db.execSQL(insertDataQuerySecond);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// tutaj wykonujesz migracje bazy danych
}
}
| 7onyy/project | app/src/main/java/com/example/mpklubartow/db/DatabaseHelper.java | 4,456 | // tutaj wykonujesz migracje bazy danych
| line_comment | pl | package com.example.mpklubartow.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "stops_";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableQueryFirst = "CREATE TABLE IF NOT EXISTS stops_f ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "busStop TEXT, "
+ "time1 DATETIME, "
+ "time2 DATETIME, "
+ "time3 DATETIME, "
+ "time4 DATETIME, "
+ "time5 DATETIME, "
+ "time6 DATETIME, "
+ "time7 DATETIME, "
+ "time8 DATETIME)";
db.execSQL(createTableQueryFirst);
String insertDataQueryFirst = "INSERT INTO stops_f (busStop, time1, time2, time3, time4, time5, time6, time7, time8) "
+ "VALUES "
+ "('ul. Hutnicza', '05:00', '06:55', '08:50', '10:20', '14:00', '16:05', '18:00', '19:25'), "
+ "('ul. Kolejowa / DW PKP', '05:01', '06:56', '08:51', '10:21', '14:01', '16:06', '18:01', '19:26'), "
+ "('ul. Powstańców Warszawy', '05:02', '06:57', '08:52', '10:22', '14:02', '16:07', '18:02', '19:27'), "
+ "('ul. Cicha / Spółdzielnia Mieszkaniowa', '05:04', '06:59', '08:54', '10:24', '14:04', '16:09', '18:04', '19:29'), "
+ "('ul. 1 Maja / Topaz', '05:06', '07:01', '08:56', '10:26', '14:06', '16:11', '18:06', '19:31'), "
+ "('ul. Piaskowa / ul. 1 Maja', '05:07', '07:02', '08:57', '10:27', '14:07', '16:12', '18:07', '19:32'), "
+ "('ul. Łąkowa / ul. Piaskowa', '05:08', '07:03', '08:58', '10:28', '14:08', '16:13', '18:08', '19:33'), "
+ "('ul. Łąkowa / Szpital', '05:09', '07:04', '08:59', '10:29', '14:09', '16:14', '18:09', '19:34'), "
+ "('ul. Cicha / Policja', '05:10', '07:05', '09:00', '10:30', '14:10', '16:15', '18:10', '19:35'), "
+ "('ul. Lubelska / przy skrzyżowaniu z ul. Mickiewicza', '05:11', '07:06', '09:01', '10:31', '14:11', '16:16', '18:11', '19:36'), "
+ "('ul. Partyzancka / PEC', '05:13', '07:08', '09:03', '10:33', '14:13', '16:18', '18:13', '19:38'), "
+ "('ul. Farna / Targ', '05:14', '07:09', '09:04', '10:34', '14:14', '16:19', '18:14', '19:39'), "
+ "('ul. Szaniawskiego', '05:16', '07:11', '09:06', '10:36', '14:16', '16:21', '18:16', '19:40'), "
+ "('Aleje Tysiąclecia', '05:18', '07:13', '09:08', '10:38', '14:18', '16:23', '18:18', '19:42'), "
+ "('ul. Nowodworska', '05:19', '07:14', '09:09', '10:39', '14:19', '16:24', '18:19', '19:43'), "
+ "('ul. Lipowa III', '05:22', '07:17', '09:12', '10:42', '14:22', '16:27', '18:22', '19:45'), "
+ "('ul. Lipowa II', '05:23', '07:18', '09:13', '10:43', '14:23', '16:28', '18:23', '19:46'), "
+ "('ul. Lipowa I', '05:24', '07:19', '09:14', '10:44', '14:24', '16:29', '18:24', '19:47'), "
+ "('ul. Chopina / I LO', '05:25', '07:20', '09:15', '10:45', '14:25', '16:30', '18:25', '19:48'), "
+ "('ul. K. Jadwigi / Al. Zwycięstwa', '05:28', '07:23', '09:18', '10:48', '14:28', '16:33', '18:28', '19:50'), "
+ "('ul. Mieszka I / ul. Leśna', '05:30', '07:25', '09:20', '10:50', '14:30', '16:35', '18:30', '19:52'), "
+ "('Kopernika II', '05:32', '07:27', '09:22', '10:52', '14:32', '16:37', '18:32', '19:54'), "
+ "('ul. Polesie / ul. Kawalerzystów', '05:33', '07:28', '09:23', '10:53', '14:33', '16:38', '18:33', '19:56'), "
+ "('ul. Polesie / ul. Lotników', '05:34', '07:29', '09:24', '10:54', '14:34', '16:39', '18:34', '19:57'), "
+ "('ul. Kosmonautów / SP 4', '05:35', '07:30', '09:25', '10:55', '14:35', '16:40', '18:35', '19:58'), "
+ "('Lisów V / Kościół', '05:36', '07:31', '09:26', '10:56', '14:36', '16:41', '18:36', '19:59')";
db.execSQL(insertDataQueryFirst);
String createTableQuerySecond = "CREATE TABLE IF NOT EXISTS stops_s ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "busStop TEXT, "
+ "time1 TEXT, "
+ "time2 TEXT, "
+ "time3 TEXT, "
+ "time4 TEXT, "
+ "time5 TEXT, "
+ "time6 TEXT, "
+ "time7 TEXT, "
+ "time8 TEXT)";
db.execSQL(createTableQuerySecond);
String insertDataQuerySecond = "INSERT INTO stops_s (busStop, time1, time2, time3, time4, time5, time6, time7, time8) "
+ "VALUES "
+ "('Lisów V / Kościół', '05:40', '07:35', '09:30', '11:05', '13:15', '14:40', '16:45', '18:45'), "
+ "('ul. Kosmonautów / SP 4', '05:41', '07:36', '09:31', '11:06', '13:16', '14:41', '16:46', '18:46'), "
+ "('ul. Polesie / ul. Lotników', '05:42', '07:37', '09:32', '11:07', '13:17', '14:42', '16:47', '18:47'), "
+ "('ul. Polesie / ul. Kawalerzystów', '05:43', '07:38', '09:33', '11:08', '13:18', '14:43', '16:48', '18:48'), "
+ "('ul. Kopernika II', '05:44', '07:39', '09:34', '11:09', '13:19', '14:44', '16:49', '18:49'), "
+ "('ul. Mieszka I / ul. Leśna', '05:46', '07:41', '09:36', '11:11', '13:21', '14:46', '16:51', '18:51'), "
+ "('ul. K. Jadwigi / Al.Zwycięstwa', '05:47', '07:42', '09:37', '11:12', '13:22', '14:47', '16:52', '15:52'), "
+ "('ul. Lipowa I', '05:49', '07:44', '09:39', '11:14', '13:24', '14:49', '16:54', '18:54'), "
+ "('ul. Chopina / I LO', '05:52', '07:47', '09:42', '11:17', '13:27', '14:52', '16:57', '18:57'), "
+ "('ul. Lipowa II', '05:54', '07:49', '09:44', '11:19', '13:29', '14:54', '16:59', '18:58'), "
+ "('ul. Lipowa III', '05:56', '07:51', '09:46', '11:21', '13:31', '14:56', '17:01', '18:59'), "
+ "('ul. Nowodworska', '05:58', '07:53', '09:48', '11:23', '13:33', '14:58', '17:03', '19:01'), "
+ "('Aleje Tysiąclecia', '05:59', '07:54', '09:49', '11:24', '13:34', '14:59', '17:04', '19:03'), "
+ "('ul. Szaniawskiego', '06:02', '07:57', '09:52', '11:27', '13:37', '15:02', '17:07', '19:05'), "
+ "('ul. Farna / Targ', '06:03', '07:58', '09:53', '11:28', '13:38', '15:03', '17:08', '19:06'), "
+ "('ul. Partyzancka / PEC', '06:04', '07:59', '09:54', '11:29', '13:39', '15:04', '17:09', '19:08'), "
+ "('ul. Lubelska / przy skrzyżowaniu z ul. Mickiewicza', '06:06', '08:01', '09:56', '11:31', '13:41', '15:06', '17:11', '19:10'), "
+ "('ul. Cicha / Spółdzielnia Mieszkaniowa', '06:07', '08:02', '09:57', '11:32', '13:42', '15:07', '17:12', '19:11'), "
+ "('ul. Łąkowa / Szpital', '06:08', '08:03', '09:58', '11:33', '13:43', '15:08', '17:13', '19:12'), "
+ "('ul. Łąkowa / ul. Piaskowa', '06:09', '08:04', '09:59', '11:34', '13:44', '15:09', '17:14', '19:13'), "
+ "('ul. Piaskowa / ul. 1 Maja', '06:10', '08:05', '10:00', '11:35', '13:45', '15:10', '17:15', '19:15'), "
+ "('ul. 1 Maja / Topaz', '06:12', '08:07', '10:02', '11:37', '13:47', '15:12', '17:17', '19:16'), "
+ "('ul. Cicha / Policja', '06:13', '08:08', '10:03', '11:38', '13:48', '15:13', '17:18', '19:17'), "
+ "('ul. Powstańców Warszawy', '06:17', '08:12', '10:07', '11:42', '13:52', '15:17', '17:22', '19:19'), "
+ "('ul. Kolejowa / DW PKP', '06:18', '08:13', '10:08', '11:43', '13:53', '15:18', '17:23', '19:21'), "
+ "('ul. Hutnicza', '06:20', '08:15', '10:10', '11:45', '13:55', '15:20', '17:25', '19:23')";
db.execSQL(insertDataQuerySecond);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// tu<SUF>
}
}
|
98245_0 | package edu.kis.vh.nursery;
public class HanoiRhymer extends DefaultCountingOutRhymer {
private int totalRejected = 0;
int reportRejected() {
return totalRejected;
}
@Override
public void countIn(int in) {
if (!callCheck() && in > peekaboo())
totalRejected++;
else
super.countIn(in);
}
}
// kominacja alt + <-/-> powoduje przełączanie pomiędzy aktywnymi kartami/plikami | 88GitHub88/powp_rhymers_bridge | src/main/java/edu/kis/vh/nursery/HanoiRhymer.java | 159 | // kominacja alt + <-/-> powoduje przełączanie pomiędzy aktywnymi kartami/plikami | line_comment | pl | package edu.kis.vh.nursery;
public class HanoiRhymer extends DefaultCountingOutRhymer {
private int totalRejected = 0;
int reportRejected() {
return totalRejected;
}
@Override
public void countIn(int in) {
if (!callCheck() && in > peekaboo())
totalRejected++;
else
super.countIn(in);
}
}
// ko<SUF> |
174922_1 | package org.project;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Main class
*/
public class Main {
public static String Role1; //Do zrobienia: 1. Wpakowanie programu do Jar (opcjonalnie) 2. Użyć JAVA stream API w programie
public static String Role2;
public static void main(String[] args) { //arg[0] -> file path, arg[1] -> role able to work on two projects (QA), arg[2] -> role able to work on two projects (PM)
String filename = args[0]; //taking the file path
Role1 = args[1];
Role2 = args[2];
ArrayList<String> data = TXTFileWorker.ReadFile(filename); //reading the file
HashMap<String, ArrayList<String>> projectList = TXTFileWorker.MakeAList(data.subList(data.indexOf("PROJECTS") + 1 , data.indexOf("STAFF") - 1)); //creating lists
ArrayList<Programmer> devList = TXTFileWorker.MakeADevList(data.subList(data.indexOf("STAFF") + 1 , data.size()));
OutputDisplay.Display(projectList); //displaying data
OutputDisplay.DevDisplay(devList);
SigningUp.FindAProject(projectList, devList); //matching programmers to their projects
OutputDisplay.Display(projectList); //displaying data
TXTFileWorker.Write2File(projectList); //creating output file
}
} | 8RiVeR8/WorkerFinder | Laboratorium_2/src/main/java/org/project/Main.java | 425 | //Do zrobienia: 1. Wpakowanie programu do Jar (opcjonalnie) 2. Użyć JAVA stream API w programie
| line_comment | pl | package org.project;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Main class
*/
public class Main {
public static String Role1; //Do<SUF>
public static String Role2;
public static void main(String[] args) { //arg[0] -> file path, arg[1] -> role able to work on two projects (QA), arg[2] -> role able to work on two projects (PM)
String filename = args[0]; //taking the file path
Role1 = args[1];
Role2 = args[2];
ArrayList<String> data = TXTFileWorker.ReadFile(filename); //reading the file
HashMap<String, ArrayList<String>> projectList = TXTFileWorker.MakeAList(data.subList(data.indexOf("PROJECTS") + 1 , data.indexOf("STAFF") - 1)); //creating lists
ArrayList<Programmer> devList = TXTFileWorker.MakeADevList(data.subList(data.indexOf("STAFF") + 1 , data.size()));
OutputDisplay.Display(projectList); //displaying data
OutputDisplay.DevDisplay(devList);
SigningUp.FindAProject(projectList, devList); //matching programmers to their projects
OutputDisplay.Display(projectList); //displaying data
TXTFileWorker.Write2File(projectList); //creating output file
}
} |
101437_6 | package com.a8thmile.rvce.a8thmile.ui.fragments;
import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.a8thmile.rvce.a8thmile.R;
import com.a8thmile.rvce.a8thmile.ui.Activities.HomeActivity;
public class SponserFragment extends Fragment implements OnClickListener{
ImageView indigo,specsmaker,honda,coke,eureka,jkcement,kotak,jeolous,aia,chefs;
String[] links=new String[]{
"http://www.specsmakers.in"
,"https://www.honda2wheelersindia.com/",
"http://www.mtvindia.com/cokestudio/"
,"https://www.allindiaadmission.co.in/",
"http://www.eurekaforbes.com/"
,"http://www.jkcement.com/"
,"http://www.kotak.com/"
,"http://www.indigonation.com/",
"http://www.jealous21.com/",
"http://chefsbasket.com/"
};
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState)
{
View view= inflater.inflate(R.layout.fragment_sponser, container,false);
super.onCreate(savedInstanceState);
indigo=(ImageView)view.findViewById(R.id.indigo) ;
indigo.setOnClickListener(this);
specsmaker=(ImageView)view.findViewById(R.id.specs) ;
honda=(ImageView)view.findViewById(R.id.honda) ;
coke=(ImageView)view.findViewById(R.id.coke) ;
eureka=(ImageView)view.findViewById(R.id.eureka) ;
jkcement=(ImageView)view.findViewById(R.id.jk) ;
kotak=(ImageView)view.findViewById(R.id.kotak) ;
jeolous=(ImageView)view.findViewById(R.id.jeolous) ;
aia=(ImageView)view.findViewById(R.id.aia) ;
chefs=(ImageView)view.findViewById(R.id.chefs);
chefs.setOnClickListener(this);
specsmaker.setOnClickListener(this);
honda.setOnClickListener(this);
coke.setOnClickListener(this);
eureka.setOnClickListener(this);
jkcement.setOnClickListener(this);
kotak.setOnClickListener(this);
jeolous.setOnClickListener(this);
aia.setOnClickListener(this);
indigo.setBackgroundColor(Color.WHITE);
((HomeActivity)getActivity()).changeActionbar(30);
return view;
}
public void goToWebsite(String site){
Intent websiteIntent=new Intent(Intent.ACTION_VIEW);
websiteIntent.setData(Uri.parse(site));
startActivity(websiteIntent);
}
public void onClick(View v) {
switch (v.getId())
{
case R.id.specs:
goToWebsite(links[0]);
break;
case R.id.honda:
goToWebsite(links[1]);
break;
case R.id.coke:
goToWebsite(links[2]);
break;
case R.id.aia:
goToWebsite(links[3]);
break;
case R.id.eureka:
goToWebsite(links[4]);
break;
case R.id.jk:
goToWebsite(links[5]);
break;
case R.id.kotak:
goToWebsite(links[6]);
break;
case R.id.indigo:
goToWebsite(links[7]);
break;
case R.id.jeolous:
goToWebsite(links[8]);
break;
case R.id.chefs:
goToWebsite(links[9]);
break;
}
}
} | 8th-mile/android-publicity | app/src/main/java/com/a8thmile/rvce/a8thmile/ui/fragments/SponserFragment.java | 1,110 | //www.kotak.com/" | line_comment | pl | package com.a8thmile.rvce.a8thmile.ui.fragments;
import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.a8thmile.rvce.a8thmile.R;
import com.a8thmile.rvce.a8thmile.ui.Activities.HomeActivity;
public class SponserFragment extends Fragment implements OnClickListener{
ImageView indigo,specsmaker,honda,coke,eureka,jkcement,kotak,jeolous,aia,chefs;
String[] links=new String[]{
"http://www.specsmakers.in"
,"https://www.honda2wheelersindia.com/",
"http://www.mtvindia.com/cokestudio/"
,"https://www.allindiaadmission.co.in/",
"http://www.eurekaforbes.com/"
,"http://www.jkcement.com/"
,"http://ww<SUF>
,"http://www.indigonation.com/",
"http://www.jealous21.com/",
"http://chefsbasket.com/"
};
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState)
{
View view= inflater.inflate(R.layout.fragment_sponser, container,false);
super.onCreate(savedInstanceState);
indigo=(ImageView)view.findViewById(R.id.indigo) ;
indigo.setOnClickListener(this);
specsmaker=(ImageView)view.findViewById(R.id.specs) ;
honda=(ImageView)view.findViewById(R.id.honda) ;
coke=(ImageView)view.findViewById(R.id.coke) ;
eureka=(ImageView)view.findViewById(R.id.eureka) ;
jkcement=(ImageView)view.findViewById(R.id.jk) ;
kotak=(ImageView)view.findViewById(R.id.kotak) ;
jeolous=(ImageView)view.findViewById(R.id.jeolous) ;
aia=(ImageView)view.findViewById(R.id.aia) ;
chefs=(ImageView)view.findViewById(R.id.chefs);
chefs.setOnClickListener(this);
specsmaker.setOnClickListener(this);
honda.setOnClickListener(this);
coke.setOnClickListener(this);
eureka.setOnClickListener(this);
jkcement.setOnClickListener(this);
kotak.setOnClickListener(this);
jeolous.setOnClickListener(this);
aia.setOnClickListener(this);
indigo.setBackgroundColor(Color.WHITE);
((HomeActivity)getActivity()).changeActionbar(30);
return view;
}
public void goToWebsite(String site){
Intent websiteIntent=new Intent(Intent.ACTION_VIEW);
websiteIntent.setData(Uri.parse(site));
startActivity(websiteIntent);
}
public void onClick(View v) {
switch (v.getId())
{
case R.id.specs:
goToWebsite(links[0]);
break;
case R.id.honda:
goToWebsite(links[1]);
break;
case R.id.coke:
goToWebsite(links[2]);
break;
case R.id.aia:
goToWebsite(links[3]);
break;
case R.id.eureka:
goToWebsite(links[4]);
break;
case R.id.jk:
goToWebsite(links[5]);
break;
case R.id.kotak:
goToWebsite(links[6]);
break;
case R.id.indigo:
goToWebsite(links[7]);
break;
case R.id.jeolous:
goToWebsite(links[8]);
break;
case R.id.chefs:
goToWebsite(links[9]);
break;
}
}
} |
84411_3 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template
*/
package pwo;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class LucasGenerator {
public static void main(String[] args) {
int n = 100; // Liczba wyrazów do wygenerowania
long[] lucasSequence = new long[n];
// Pierwsze dwa wyrazy ciągu Lucas
lucasSequence[0] = 2;
lucasSequence[1] = 1;
// Generowanie pozostałych wyrazów
for (int i = 2; i < n; i++) {
lucasSequence[i] = lucasSequence[i - 1] + lucasSequence[i - 2];
}
// Zapisywanie wyrazów ciągu do pliku tekstowego
try {
PrintWriter writer = new PrintWriter(new FileWriter("lucas_sequence.txt"));
for (int i = 0; i < n; i++) {
writer.println("L(" + i + ") = " + lucasSequence[i]);
}
writer.close();
System.out.println("Ciąg Lucas zapisany do pliku 'lucas_sequence.txt'");
} catch (IOException e) {
System.err.println("Błąd podczas zapisu do pliku.");
e.printStackTrace();
}
}
}
| 97073/pwo-lab05 | src/main/java/pwo/LucasGenerator.java | 416 | // Generowanie pozostałych wyrazów | line_comment | pl | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template
*/
package pwo;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class LucasGenerator {
public static void main(String[] args) {
int n = 100; // Liczba wyrazów do wygenerowania
long[] lucasSequence = new long[n];
// Pierwsze dwa wyrazy ciągu Lucas
lucasSequence[0] = 2;
lucasSequence[1] = 1;
// Ge<SUF>
for (int i = 2; i < n; i++) {
lucasSequence[i] = lucasSequence[i - 1] + lucasSequence[i - 2];
}
// Zapisywanie wyrazów ciągu do pliku tekstowego
try {
PrintWriter writer = new PrintWriter(new FileWriter("lucas_sequence.txt"));
for (int i = 0; i < n; i++) {
writer.println("L(" + i + ") = " + lucasSequence[i]);
}
writer.close();
System.out.println("Ciąg Lucas zapisany do pliku 'lucas_sequence.txt'");
} catch (IOException e) {
System.err.println("Błąd podczas zapisu do pliku.");
e.printStackTrace();
}
}
}
|
21124_1 | package musicproject.domain;
// 5 roznych typow
// transakcyjnosc - (na jego githubie masz xd)
// CRD - + ewentualnie update
// searche
// wiele do arraylist
public class Music {
private String autor;
private String title;
private long id;
public Music( String autor , String title )
{
this.autor = autor;
this.title = title;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getAutor()
{
return this.autor;
}
public String getTitle()
{
return this.title;
}
public void setAutor(String autor)
{
this.autor = autor;
}
public void setTitle(String title)
{
this.title = title;
}
}
| AChorostian/TechUt | zad02/src/main/java/musicproject/domain/Music.java | 264 | // transakcyjnosc - (na jego githubie masz xd) | line_comment | pl | package musicproject.domain;
// 5 roznych typow
// tr<SUF>
// CRD - + ewentualnie update
// searche
// wiele do arraylist
public class Music {
private String autor;
private String title;
private long id;
public Music( String autor , String title )
{
this.autor = autor;
this.title = title;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getAutor()
{
return this.autor;
}
public String getTitle()
{
return this.title;
}
public void setAutor(String autor)
{
this.autor = autor;
}
public void setTitle(String title)
{
this.title = title;
}
}
|
147398_7 | package pl.afyaan.antipearlbug.event;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.util.Vector;
public class PearlTeleportEvent implements Listener{
private final Set<Material> xList;
private final Set<Material> gateList;
private final Set<Material> slabList;
private final Set<Material> stairList;
private final Set<Material> fenceList;
private final Set<Material> doorList;
private final Set<Material> otherIgnoreBlockList;
public PearlTeleportEvent(){
this.xList = new HashSet<Material>(Arrays.asList(new Material[] { Material.COBBLE_WALL, Material.IRON_FENCE, Material.THIN_GLASS, Material.STAINED_GLASS_PANE}));
this.gateList = new HashSet<Material>(Arrays.asList(new Material[] { Material.FENCE_GATE, Material.SPRUCE_FENCE_GATE, Material.BIRCH_FENCE_GATE, Material.JUNGLE_FENCE_GATE, Material.DARK_OAK_FENCE_GATE, Material.ACACIA_FENCE_GATE}));
this.slabList = new HashSet<Material>(Arrays.asList(new Material[] { Material.STEP, Material.WOOD_STEP, Material.STONE_SLAB2}));
this.stairList = new HashSet<Material>(Arrays.asList(new Material[] { Material.WOOD_STAIRS, Material.COBBLESTONE_STAIRS, Material.BRICK_STAIRS, Material.SMOOTH_STAIRS, Material.NETHER_BRICK_STAIRS, Material.SANDSTONE_STAIRS, Material.SPRUCE_WOOD_STAIRS, Material.BIRCH_WOOD_STAIRS, Material.JUNGLE_WOOD_STAIRS, Material.QUARTZ_STAIRS, Material.ACACIA_STAIRS, Material.DARK_OAK_STAIRS, Material.RED_SANDSTONE_STAIRS}));
this.fenceList = new HashSet<Material>(Arrays.asList(new Material[] { Material.FENCE, Material.NETHER_FENCE, Material.DARK_OAK_FENCE, Material.SPRUCE_FENCE, Material.BIRCH_FENCE, Material.JUNGLE_FENCE, Material.DARK_OAK_FENCE, Material.ACACIA_FENCE}));
this.doorList = new HashSet<Material>(Arrays.asList(new Material[] { Material.WOODEN_DOOR, Material.IRON_DOOR_BLOCK, Material.SPRUCE_DOOR, Material.BIRCH_DOOR, Material.JUNGLE_DOOR, Material.ACACIA_DOOR, Material.DARK_OAK_DOOR}));
this.otherIgnoreBlockList = new HashSet<Material>(Arrays.asList(
new Material[] { Material.LADDER, Material.SAPLING, Material.POWERED_RAIL, Material.DETECTOR_RAIL, Material.RAILS,
Material.ACTIVATOR_RAIL, Material.THIN_GLASS, Material.STAINED_GLASS_PANE, Material.PISTON_EXTENSION,
Material.PISTON_BASE, Material.PISTON_STICKY_BASE, Material.LONG_GRASS, Material.DEAD_BUSH, Material.RED_ROSE,
Material.YELLOW_FLOWER, Material.RED_MUSHROOM, Material.BROWN_MUSHROOM, Material.CHEST, Material.TRAPPED_CHEST,
Material.TORCH, Material.REDSTONE_TORCH_ON, Material.REDSTONE_TORCH_OFF, Material.TRIPWIRE_HOOK, //Material.TRIPWIRE,
Material.STONE_PLATE, Material.WOOD_PLATE, Material.GOLD_PLATE, Material.IRON_PLATE, Material.SNOW, Material.STONE_BUTTON,
Material.WOOD_BUTTON, Material.STONE_BUTTON, Material.ANVIL, Material.CACTUS, Material.IRON_FENCE, Material.TRAP_DOOR,
Material.IRON_TRAPDOOR, Material.ENDER_PORTAL, Material.VINE, Material.ENDER_CHEST, Material.COBBLE_WALL, Material.HOPPER,
Material.DAYLIGHT_DETECTOR, Material.DAYLIGHT_DETECTOR_INVERTED, Material.REDSTONE_WIRE, Material.ENCHANTMENT_TABLE,
Material.CARPET, Material.DOUBLE_PLANT, Material.STATIONARY_LAVA, Material.STATIONARY_WATER, Material.DIODE_BLOCK_OFF,
Material.DIODE_BLOCK_ON, Material.REDSTONE_COMPARATOR, Material.REDSTONE_COMPARATOR_OFF, Material.REDSTONE_COMPARATOR_ON,
Material.CAKE_BLOCK, Material.STANDING_BANNER, Material.SIGN, Material.WALL_SIGN, Material.ARMOR_STAND}));
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL)
public void onPlayerInteract(PlayerInteractEvent event) {
if(event.getAction() == Action.RIGHT_CLICK_BLOCK && event.hasItem() && event.getItem().getType() == Material.ENDER_PEARL) {
Location playerLoc = event.getPlayer().getLocation();
Block block = playerLoc.getWorld().getBlockAt(new Location(playerLoc.getWorld(), playerLoc.getX(), playerLoc.getY() + 1, playerLoc.getZ()));
//Gracz nie moze uzyc perly jesli jest w bloku
if(block.getType() != Material.AIR && !this.fenceList.contains(block.getType()) && !this.doorList.contains(block.getType()) && !this.otherIgnoreBlockList.contains(block.getType()) &&
!this.gateList.contains(block.getType())) {
event.setCancelled(true);
}
}
}
public static Vector getUnitVectorFacing(final Player ply) {
double x = -Math.sin(Math.toRadians(ply.getLocation().getYaw())) *
Math.cos(Math.toRadians(ply.getLocation().getPitch()));
double z = Math.cos(Math.toRadians(ply.getLocation().getYaw())) *
Math.cos(Math.toRadians(ply.getLocation().getPitch()));
double y = 0;
return new Vector(x, y, z);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL)
public void onPearlTeleport(PlayerTeleportEvent event) {
if(event.getCause() == PlayerTeleportEvent.TeleportCause.ENDER_PEARL) {
Player pl = event.getPlayer();
Location pearlLoc = event.getTo();
Block bottomBlock = event.getTo().getWorld().getBlockAt(
new Location(event.getTo().getWorld(), pearlLoc.getBlockX(), pearlLoc.getBlockY() - 1, pearlLoc.getZ()));
Block centerBlock = event.getTo().getWorld().getBlockAt(
new Location(event.getTo().getWorld(), pearlLoc.getBlockX(), pearlLoc.getBlockY(), pearlLoc.getZ()));
Block top2Block = event.getTo().getWorld().getBlockAt(
new Location(event.getTo().getWorld(), pearlLoc.getBlockX(), pearlLoc.getBlockY() + 2, pearlLoc.getZ()));
//Zmienia pozycje perly na srodek bloku i blok nizej jesli jeden blok pod lokalizacja perly jest powietrze
if(bottomBlock.getType() == Material.AIR) {
pearlLoc.setX(pearlLoc.getBlockX() + 0.5);
pearlLoc.setY(pearlLoc.getBlockY() - 1);
pearlLoc.setZ(pearlLoc.getBlockZ() + 0.5);
}
//Zmienia pozycje perly na srodek bloku jesli w lokalizacji perly jest powietrze lub drzwi
if(centerBlock.getType() == Material.AIR || this.doorList.contains(centerBlock.getType())) {
pearlLoc.setX(pearlLoc.getBlockX() + 0.5);
pearlLoc.setZ(pearlLoc.getBlockZ() + 0.5);
}
//Zmienia pozycje perly 1.5 bloku nizej jesli w lokalizacji perly jest nitka
if(top2Block.getType() == Material.TRIPWIRE) {
pearlLoc.setY(pearlLoc.getBlockY() - 1.5);
}
//Zmienia pozycje perly kilka kratek do tylu jesli w lokalizacji perly jest blok typu plot, szyba, lub furtka
if(this.xList.contains(pearlLoc.getBlock().getType()) || this.xList.contains(bottomBlock.getType())
|| this.gateList.contains(pearlLoc.getBlock().getType()) || this.gateList.contains(bottomBlock.getType())
|| this.fenceList.contains(pearlLoc.getBlock().getType()) || this.fenceList.contains(bottomBlock.getType()))
{
Vector vec = getUnitVectorFacing(pl);
if(event.getFrom().distance(pearlLoc) < 3)
vec.multiply(-2);
else {
vec.multiply(-1);
}
pl.setVelocity(vec);
if(this.gateList.contains(pearlLoc.getBlock().getType()) || this.gateList.contains(bottomBlock.getType())) {
pearlLoc.setX((vec.getX() * 2) + pearlLoc.getX());
pearlLoc.setZ((vec.getZ() * 2) + pearlLoc.getZ());
}
}
//Zmienia pozycje perly na srodek bloku i 0.5 bloku wyzej jesli w lokalizacji perly jest polblok
if(this.slabList.contains(pearlLoc.getBlock().getType())) {
pearlLoc.setX(pearlLoc.getBlockX() + 0.5);
pearlLoc.setY(pearlLoc.getBlockY() + 0.5);
pearlLoc.setZ(pearlLoc.getBlockZ() + 0.5);
}
//Zmienia pozycje perly 0.5 bloku wyzej jesli w lokalizacji perly sa schody
if(this.stairList.contains(pearlLoc.getBlock().getType())) {
pearlLoc.setY(pearlLoc.getBlockY() + 1.0);
}
if(!this.otherIgnoreBlockList.contains(pearlLoc.getBlock().getType()) || !this.otherIgnoreBlockList.contains(bottomBlock.getType())) {
pearlLoc.setX(pearlLoc.getX());
pearlLoc.setY(pearlLoc.getY());
pearlLoc.setZ(pearlLoc.getZ());
}
event.setTo(pearlLoc);
}
}
} | AFYaan/AntiPearlBug | src/pl/afyaan/antipearlbug/event/PearlTeleportEvent.java | 3,490 | //Zmienia pozycje perly 0.5 bloku wyzej jesli w lokalizacji perly sa schody | line_comment | pl | package pl.afyaan.antipearlbug.event;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.util.Vector;
public class PearlTeleportEvent implements Listener{
private final Set<Material> xList;
private final Set<Material> gateList;
private final Set<Material> slabList;
private final Set<Material> stairList;
private final Set<Material> fenceList;
private final Set<Material> doorList;
private final Set<Material> otherIgnoreBlockList;
public PearlTeleportEvent(){
this.xList = new HashSet<Material>(Arrays.asList(new Material[] { Material.COBBLE_WALL, Material.IRON_FENCE, Material.THIN_GLASS, Material.STAINED_GLASS_PANE}));
this.gateList = new HashSet<Material>(Arrays.asList(new Material[] { Material.FENCE_GATE, Material.SPRUCE_FENCE_GATE, Material.BIRCH_FENCE_GATE, Material.JUNGLE_FENCE_GATE, Material.DARK_OAK_FENCE_GATE, Material.ACACIA_FENCE_GATE}));
this.slabList = new HashSet<Material>(Arrays.asList(new Material[] { Material.STEP, Material.WOOD_STEP, Material.STONE_SLAB2}));
this.stairList = new HashSet<Material>(Arrays.asList(new Material[] { Material.WOOD_STAIRS, Material.COBBLESTONE_STAIRS, Material.BRICK_STAIRS, Material.SMOOTH_STAIRS, Material.NETHER_BRICK_STAIRS, Material.SANDSTONE_STAIRS, Material.SPRUCE_WOOD_STAIRS, Material.BIRCH_WOOD_STAIRS, Material.JUNGLE_WOOD_STAIRS, Material.QUARTZ_STAIRS, Material.ACACIA_STAIRS, Material.DARK_OAK_STAIRS, Material.RED_SANDSTONE_STAIRS}));
this.fenceList = new HashSet<Material>(Arrays.asList(new Material[] { Material.FENCE, Material.NETHER_FENCE, Material.DARK_OAK_FENCE, Material.SPRUCE_FENCE, Material.BIRCH_FENCE, Material.JUNGLE_FENCE, Material.DARK_OAK_FENCE, Material.ACACIA_FENCE}));
this.doorList = new HashSet<Material>(Arrays.asList(new Material[] { Material.WOODEN_DOOR, Material.IRON_DOOR_BLOCK, Material.SPRUCE_DOOR, Material.BIRCH_DOOR, Material.JUNGLE_DOOR, Material.ACACIA_DOOR, Material.DARK_OAK_DOOR}));
this.otherIgnoreBlockList = new HashSet<Material>(Arrays.asList(
new Material[] { Material.LADDER, Material.SAPLING, Material.POWERED_RAIL, Material.DETECTOR_RAIL, Material.RAILS,
Material.ACTIVATOR_RAIL, Material.THIN_GLASS, Material.STAINED_GLASS_PANE, Material.PISTON_EXTENSION,
Material.PISTON_BASE, Material.PISTON_STICKY_BASE, Material.LONG_GRASS, Material.DEAD_BUSH, Material.RED_ROSE,
Material.YELLOW_FLOWER, Material.RED_MUSHROOM, Material.BROWN_MUSHROOM, Material.CHEST, Material.TRAPPED_CHEST,
Material.TORCH, Material.REDSTONE_TORCH_ON, Material.REDSTONE_TORCH_OFF, Material.TRIPWIRE_HOOK, //Material.TRIPWIRE,
Material.STONE_PLATE, Material.WOOD_PLATE, Material.GOLD_PLATE, Material.IRON_PLATE, Material.SNOW, Material.STONE_BUTTON,
Material.WOOD_BUTTON, Material.STONE_BUTTON, Material.ANVIL, Material.CACTUS, Material.IRON_FENCE, Material.TRAP_DOOR,
Material.IRON_TRAPDOOR, Material.ENDER_PORTAL, Material.VINE, Material.ENDER_CHEST, Material.COBBLE_WALL, Material.HOPPER,
Material.DAYLIGHT_DETECTOR, Material.DAYLIGHT_DETECTOR_INVERTED, Material.REDSTONE_WIRE, Material.ENCHANTMENT_TABLE,
Material.CARPET, Material.DOUBLE_PLANT, Material.STATIONARY_LAVA, Material.STATIONARY_WATER, Material.DIODE_BLOCK_OFF,
Material.DIODE_BLOCK_ON, Material.REDSTONE_COMPARATOR, Material.REDSTONE_COMPARATOR_OFF, Material.REDSTONE_COMPARATOR_ON,
Material.CAKE_BLOCK, Material.STANDING_BANNER, Material.SIGN, Material.WALL_SIGN, Material.ARMOR_STAND}));
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL)
public void onPlayerInteract(PlayerInteractEvent event) {
if(event.getAction() == Action.RIGHT_CLICK_BLOCK && event.hasItem() && event.getItem().getType() == Material.ENDER_PEARL) {
Location playerLoc = event.getPlayer().getLocation();
Block block = playerLoc.getWorld().getBlockAt(new Location(playerLoc.getWorld(), playerLoc.getX(), playerLoc.getY() + 1, playerLoc.getZ()));
//Gracz nie moze uzyc perly jesli jest w bloku
if(block.getType() != Material.AIR && !this.fenceList.contains(block.getType()) && !this.doorList.contains(block.getType()) && !this.otherIgnoreBlockList.contains(block.getType()) &&
!this.gateList.contains(block.getType())) {
event.setCancelled(true);
}
}
}
public static Vector getUnitVectorFacing(final Player ply) {
double x = -Math.sin(Math.toRadians(ply.getLocation().getYaw())) *
Math.cos(Math.toRadians(ply.getLocation().getPitch()));
double z = Math.cos(Math.toRadians(ply.getLocation().getYaw())) *
Math.cos(Math.toRadians(ply.getLocation().getPitch()));
double y = 0;
return new Vector(x, y, z);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL)
public void onPearlTeleport(PlayerTeleportEvent event) {
if(event.getCause() == PlayerTeleportEvent.TeleportCause.ENDER_PEARL) {
Player pl = event.getPlayer();
Location pearlLoc = event.getTo();
Block bottomBlock = event.getTo().getWorld().getBlockAt(
new Location(event.getTo().getWorld(), pearlLoc.getBlockX(), pearlLoc.getBlockY() - 1, pearlLoc.getZ()));
Block centerBlock = event.getTo().getWorld().getBlockAt(
new Location(event.getTo().getWorld(), pearlLoc.getBlockX(), pearlLoc.getBlockY(), pearlLoc.getZ()));
Block top2Block = event.getTo().getWorld().getBlockAt(
new Location(event.getTo().getWorld(), pearlLoc.getBlockX(), pearlLoc.getBlockY() + 2, pearlLoc.getZ()));
//Zmienia pozycje perly na srodek bloku i blok nizej jesli jeden blok pod lokalizacja perly jest powietrze
if(bottomBlock.getType() == Material.AIR) {
pearlLoc.setX(pearlLoc.getBlockX() + 0.5);
pearlLoc.setY(pearlLoc.getBlockY() - 1);
pearlLoc.setZ(pearlLoc.getBlockZ() + 0.5);
}
//Zmienia pozycje perly na srodek bloku jesli w lokalizacji perly jest powietrze lub drzwi
if(centerBlock.getType() == Material.AIR || this.doorList.contains(centerBlock.getType())) {
pearlLoc.setX(pearlLoc.getBlockX() + 0.5);
pearlLoc.setZ(pearlLoc.getBlockZ() + 0.5);
}
//Zmienia pozycje perly 1.5 bloku nizej jesli w lokalizacji perly jest nitka
if(top2Block.getType() == Material.TRIPWIRE) {
pearlLoc.setY(pearlLoc.getBlockY() - 1.5);
}
//Zmienia pozycje perly kilka kratek do tylu jesli w lokalizacji perly jest blok typu plot, szyba, lub furtka
if(this.xList.contains(pearlLoc.getBlock().getType()) || this.xList.contains(bottomBlock.getType())
|| this.gateList.contains(pearlLoc.getBlock().getType()) || this.gateList.contains(bottomBlock.getType())
|| this.fenceList.contains(pearlLoc.getBlock().getType()) || this.fenceList.contains(bottomBlock.getType()))
{
Vector vec = getUnitVectorFacing(pl);
if(event.getFrom().distance(pearlLoc) < 3)
vec.multiply(-2);
else {
vec.multiply(-1);
}
pl.setVelocity(vec);
if(this.gateList.contains(pearlLoc.getBlock().getType()) || this.gateList.contains(bottomBlock.getType())) {
pearlLoc.setX((vec.getX() * 2) + pearlLoc.getX());
pearlLoc.setZ((vec.getZ() * 2) + pearlLoc.getZ());
}
}
//Zmienia pozycje perly na srodek bloku i 0.5 bloku wyzej jesli w lokalizacji perly jest polblok
if(this.slabList.contains(pearlLoc.getBlock().getType())) {
pearlLoc.setX(pearlLoc.getBlockX() + 0.5);
pearlLoc.setY(pearlLoc.getBlockY() + 0.5);
pearlLoc.setZ(pearlLoc.getBlockZ() + 0.5);
}
//Zm<SUF>
if(this.stairList.contains(pearlLoc.getBlock().getType())) {
pearlLoc.setY(pearlLoc.getBlockY() + 1.0);
}
if(!this.otherIgnoreBlockList.contains(pearlLoc.getBlock().getType()) || !this.otherIgnoreBlockList.contains(bottomBlock.getType())) {
pearlLoc.setX(pearlLoc.getX());
pearlLoc.setY(pearlLoc.getY());
pearlLoc.setZ(pearlLoc.getZ());
}
event.setTo(pearlLoc);
}
}
} |
28052_16 | package com.example.automotive;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager2.widget.ViewPager2;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;
import com.example.automotive.Adapters.ViewPager2FragmentStateAdapter;
import com.example.automotive.ViewModels.MyViewModel;
//import com.example.automotive.ViewModels.SharedViewModel;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.polidea.rxandroidble2.RxBleClient;
import com.polidea.rxandroidble2.RxBleDevice;
import androidx.lifecycle.ViewModelProvider;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity {
private static final String MAC_ADDRESS = "EA:A5:34:E6:28:2E";
ViewPager2 viewPager2;
ViewPager2FragmentStateAdapter fragmentStateAdapter;
TabLayout tabLayout;
// RxBleDevice device = rxBleClient.getBleDevice(macAddress);
// SampleApplication sampleApplication = new SampleApplication(getApplicationContext());
// --------------------------------------------------- przechowywanie info przy ROTACJI ---------------------------------------------------
// https://stackoverflow.com/questions/151777/how-to-save-an-activity-state-using-save-instance-state?page=1&tab=votes#tab-top
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
// outState.putString("stringContainer", stringContainer);
}
// @Override
// protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
// super.onRestoreInstanceState(savedInstanceState);
// stringContainer = savedInstanceState.getString("stringContainer");
// setStringContainer(stringContainer);
// textView_input = replaceTheContentOfTextView(textView_input, stringContainer);
// }
// https://stackoverflow.com/questions/151777/how-to-save-an-activity-state-using-save-instance-state?page=1&tab=votes#tab-top
// --------------------------------------------------- przechowywanie info przy ROTACJI ---------------------------------------------------
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyViewModel model = new ViewModelProvider(this).get(MyViewModel.class);
// Turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
int REQUEST_ENABLE_BT = 1;
this.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
// create instance in ViewModel
// rxBleClient = RxBleClient.create(getApplicationContext());
// model.setRxBleClient(rxBleClient);
// rxBleClient = SampleApplication.getRxBleClient(this);
ButterKnife.bind(this);
if (savedInstanceState == null) {
// nic nie zostało zapisane -> patrz onSaveInstanceState()
Bundle extras = getIntent().getExtras();
if (extras == null) {
// nic nie zostało przekazane pomiędzy aktywnościami
// finish(); // ciekawe jak to działa xd KURWA, nie uzywac tego w zadnym jebanym wypadku
} else {
// pierwsze wywołanie danej aktywności z innej aktywności
// przejście pomiędzy activity, tj. activity 1 zapisało coś do extras i teraz można coś zgarnać :)
// np. extras.getLong(SOMETHING);
}
} else {
// czyli ponowne wywołanie aplikacji
// coś jest w środku np. -> savedInstanceState.getLong(SOMETHING);
}
// FRAGMENT ADAPTER
fragmentStateAdapter = new ViewPager2FragmentStateAdapter(getSupportFragmentManager(), getLifecycle());
viewPager2 = findViewById(R.id.pager);
viewPager2.setUserInputEnabled(false);
viewPager2.setAdapter(fragmentStateAdapter);
// TOP BAR
final String tabTitles[] = {"Debugging", "Bluetooth", "Video"};
final @DrawableRes int tabDrawable[] = {R.drawable.ic_bug_report_24px, R.drawable.ic_bluetooth_24px, R.drawable.ic_videocam_24px};
tabLayout = findViewById(R.id.tab_layout);
new TabLayoutMediator(tabLayout, viewPager2,
(tab, position) -> tab.setText(tabTitles[position]).setIcon(tabDrawable[position])
).attach();
// Use this check to determine whether SampleApplication is supported on the device. Then
// you can selectively disable SampleApplication-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
} else {
// good to know ;)
Toast.makeText(this, R.string.ble_is_supported, Toast.LENGTH_SHORT).show();
}
// rxBleClient.getBleDevice(MAC_ADDRESS).getBluetoothDevice().createBond();
// rxBleClient.getBleDevice(MAC_ADDRESS).establishConnection(false);
//// https://developer.android.com/guide/topics/connectivity/use-ble
// // Initializes Bluetooth adapter.
// final BluetoothManager bluetoothManager = getSystemService(BluetoothManager.class);
// BluetoothAdapter bluetoothAdapter = null;
// if (bluetoothManager != null) {
// bluetoothAdapter = bluetoothManager.getAdapter();
// }
//
//
// int REQUEST_ENABLE_BT = 0;
// // Ensures Bluetooth is available on the device and it is enabled. If not,
// // displays a dialog requesting user permission to enable Bluetooth.
// if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled()) {
// Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
// startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
// }
// rxBleClient = SampleApplication.getRxBleClient(this);
// MyApplicationContext
// rxBleClient = RxBleClient.create(this.getApplicationContext());
}
// lifecycle
@Override
protected void onStart() {
super.onStart();
checkPermission();
}
// lifecycle
@Override
protected void onResume() {
super.onResume();
}
// lifecycle
@Override
protected void onPause() {
super.onPause();
}
// lifecycle
@Override
protected void onStop() {
super.onStop();
}
// lifecycle
@Override
protected void onRestart() {
super.onRestart();
}
// lifecycle
@Override
protected void onDestroy() {
super.onDestroy();
}
public void checkPermission() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
} else {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,}, 1);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
} else {
checkPermission();
}
}
} | AKrupaa/Android-Automotive-Student-Project | app/src/main/java/com/example/automotive/MainActivity.java | 2,343 | // --------------------------------------------------- przechowywanie info przy ROTACJI --------------------------------------------------- | line_comment | pl | package com.example.automotive;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager2.widget.ViewPager2;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;
import com.example.automotive.Adapters.ViewPager2FragmentStateAdapter;
import com.example.automotive.ViewModels.MyViewModel;
//import com.example.automotive.ViewModels.SharedViewModel;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.polidea.rxandroidble2.RxBleClient;
import com.polidea.rxandroidble2.RxBleDevice;
import androidx.lifecycle.ViewModelProvider;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity {
private static final String MAC_ADDRESS = "EA:A5:34:E6:28:2E";
ViewPager2 viewPager2;
ViewPager2FragmentStateAdapter fragmentStateAdapter;
TabLayout tabLayout;
// RxBleDevice device = rxBleClient.getBleDevice(macAddress);
// SampleApplication sampleApplication = new SampleApplication(getApplicationContext());
// --------------------------------------------------- przechowywanie info przy ROTACJI ---------------------------------------------------
// https://stackoverflow.com/questions/151777/how-to-save-an-activity-state-using-save-instance-state?page=1&tab=votes#tab-top
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
// outState.putString("stringContainer", stringContainer);
}
// @Override
// protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
// super.onRestoreInstanceState(savedInstanceState);
// stringContainer = savedInstanceState.getString("stringContainer");
// setStringContainer(stringContainer);
// textView_input = replaceTheContentOfTextView(textView_input, stringContainer);
// }
// https://stackoverflow.com/questions/151777/how-to-save-an-activity-state-using-save-instance-state?page=1&tab=votes#tab-top
// --<SUF>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyViewModel model = new ViewModelProvider(this).get(MyViewModel.class);
// Turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
int REQUEST_ENABLE_BT = 1;
this.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
// create instance in ViewModel
// rxBleClient = RxBleClient.create(getApplicationContext());
// model.setRxBleClient(rxBleClient);
// rxBleClient = SampleApplication.getRxBleClient(this);
ButterKnife.bind(this);
if (savedInstanceState == null) {
// nic nie zostało zapisane -> patrz onSaveInstanceState()
Bundle extras = getIntent().getExtras();
if (extras == null) {
// nic nie zostało przekazane pomiędzy aktywnościami
// finish(); // ciekawe jak to działa xd KURWA, nie uzywac tego w zadnym jebanym wypadku
} else {
// pierwsze wywołanie danej aktywności z innej aktywności
// przejście pomiędzy activity, tj. activity 1 zapisało coś do extras i teraz można coś zgarnać :)
// np. extras.getLong(SOMETHING);
}
} else {
// czyli ponowne wywołanie aplikacji
// coś jest w środku np. -> savedInstanceState.getLong(SOMETHING);
}
// FRAGMENT ADAPTER
fragmentStateAdapter = new ViewPager2FragmentStateAdapter(getSupportFragmentManager(), getLifecycle());
viewPager2 = findViewById(R.id.pager);
viewPager2.setUserInputEnabled(false);
viewPager2.setAdapter(fragmentStateAdapter);
// TOP BAR
final String tabTitles[] = {"Debugging", "Bluetooth", "Video"};
final @DrawableRes int tabDrawable[] = {R.drawable.ic_bug_report_24px, R.drawable.ic_bluetooth_24px, R.drawable.ic_videocam_24px};
tabLayout = findViewById(R.id.tab_layout);
new TabLayoutMediator(tabLayout, viewPager2,
(tab, position) -> tab.setText(tabTitles[position]).setIcon(tabDrawable[position])
).attach();
// Use this check to determine whether SampleApplication is supported on the device. Then
// you can selectively disable SampleApplication-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
} else {
// good to know ;)
Toast.makeText(this, R.string.ble_is_supported, Toast.LENGTH_SHORT).show();
}
// rxBleClient.getBleDevice(MAC_ADDRESS).getBluetoothDevice().createBond();
// rxBleClient.getBleDevice(MAC_ADDRESS).establishConnection(false);
//// https://developer.android.com/guide/topics/connectivity/use-ble
// // Initializes Bluetooth adapter.
// final BluetoothManager bluetoothManager = getSystemService(BluetoothManager.class);
// BluetoothAdapter bluetoothAdapter = null;
// if (bluetoothManager != null) {
// bluetoothAdapter = bluetoothManager.getAdapter();
// }
//
//
// int REQUEST_ENABLE_BT = 0;
// // Ensures Bluetooth is available on the device and it is enabled. If not,
// // displays a dialog requesting user permission to enable Bluetooth.
// if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled()) {
// Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
// startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
// }
// rxBleClient = SampleApplication.getRxBleClient(this);
// MyApplicationContext
// rxBleClient = RxBleClient.create(this.getApplicationContext());
}
// lifecycle
@Override
protected void onStart() {
super.onStart();
checkPermission();
}
// lifecycle
@Override
protected void onResume() {
super.onResume();
}
// lifecycle
@Override
protected void onPause() {
super.onPause();
}
// lifecycle
@Override
protected void onStop() {
super.onStop();
}
// lifecycle
@Override
protected void onRestart() {
super.onRestart();
}
// lifecycle
@Override
protected void onDestroy() {
super.onDestroy();
}
public void checkPermission() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
} else {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,}, 1);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
} else {
checkPermission();
}
}
} |
12587_1 | package com.example.demo.model;
import javax.persistence.*;
@Entity
//@Table(name = "tickets")
public class Ticket {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
// jeden ticket do jednego eventu, po prostu pole wskazujace na wydarzenie
// mapuje na zmienna w evencie o nazwie oneTicket, z ktora ma byc powiazana
@ManyToOne(
fetch = FetchType.EAGER
)
// @JoinColumn(name = "event_id")
private Event event;
// @ManyToOne(fetch = FetchType.EAGER)
// private Account account;
private boolean taken;
private float price;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Event getEvent() {
return event;
}
public void setEvent(Event event) {
this.event = event;
}
public boolean isTaken() {
return taken;
}
public void setTaken(boolean taken) {
this.taken = taken;
}
// public Account getAccount() {
// return account;
// }
//
// public void setAccount(Account account) {
// this.account = account;
// }
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
| AKrupaa/Angular-Student-Works | projekt/demo/src/main/java/com/example/demo/model/Ticket.java | 412 | // jeden ticket do jednego eventu, po prostu pole wskazujace na wydarzenie | line_comment | pl | package com.example.demo.model;
import javax.persistence.*;
@Entity
//@Table(name = "tickets")
public class Ticket {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
// je<SUF>
// mapuje na zmienna w evencie o nazwie oneTicket, z ktora ma byc powiazana
@ManyToOne(
fetch = FetchType.EAGER
)
// @JoinColumn(name = "event_id")
private Event event;
// @ManyToOne(fetch = FetchType.EAGER)
// private Account account;
private boolean taken;
private float price;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Event getEvent() {
return event;
}
public void setEvent(Event event) {
this.event = event;
}
public boolean isTaken() {
return taken;
}
public void setTaken(boolean taken) {
this.taken = taken;
}
// public Account getAccount() {
// return account;
// }
//
// public void setAccount(Account account) {
// this.account = account;
// }
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
|
28046_8 | package com.example.astro;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public static final String MY_PREFERENCES = "MY_PREFERENCES";
public static final String LAST_CITY_KEY = "LAST_CITY_KEY";
public static final String INPUTED_TIME = "INPUTED_TIME";
private EditText city;
private Button confirm;
private Button force;
private WeatherForecast weatherForecast;
private SharedViewModel sharedViewModel;
private ProgressBar progressBar;
private SharedPreferences sharedPreferences;
Spinner spinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedViewModel = new ViewModelProvider(this).get(SharedViewModel.class);
weatherForecast = new WeatherForecast(getApplicationContext(), sharedViewModel);
initialization();
hideProgressBar();
Context context = getApplicationContext();
// You can create a new shared preference file or access an existing one by calling method
sharedPreferences = context.getSharedPreferences(MY_PREFERENCES, context.MODE_PRIVATE);
// int defaultValue = getResources().getInteger(R.integer.saved_high_score_default_key);
city.setText(sharedPreferences.getString(LAST_CITY_KEY, ""));
spinner = findViewById(R.id.spinnerTime);
addItemsToTimeSpinner();
setConfirm();
setForce();
}
@Override
protected void onStart() {
super.onStart();
}
private void initialization() {
city = (EditText) findViewById(R.id.city);
confirm = (Button) findViewById(R.id.buttonConfirm);
force = (Button) findViewById(R.id.buttonForce);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
}
private void showProgressBar() {
progressBar.setVisibility(View.VISIBLE);
}
private void hideProgressBar() {
progressBar.setVisibility(View.INVISIBLE);
}
private void setConfirm() {
confirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showProgressBar();
// pobieraj, nie patyczkuj się
final String sCity = city.getText().toString();
final String finalSCity = sCity;
weatherForecast.saveInternetWeatherContentInViewModel(sCity, new WeatherForecast.onSavedResponse() {
@Override
public void onSaved() {
// przejdz do nowej intencji
hideProgressBar();
// Navigate from MainActivity to OverviewActivity
Intent intent = new Intent(MainActivity.this, OverviewActivity.class);
intent.putExtra(DatabaseHelper.CITY_ID, sharedViewModel.getCommon().getAsLong(DatabaseHelper.CITY_ID));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(LAST_CITY_KEY, sCity);
editor.apply(); // writes the updates to disk asynchronously
String readTime = String.valueOf(spinner.getSelectedItem()).substring(0, 2);
intent.putExtra(INPUTED_TIME, readTime);
startActivity(intent);
}
@Override
public void onFailed() {
// sprobuj baze danych
// nie -> blad
// tak -> przejdz
DBManager dbManager = new DBManager(getApplicationContext());
dbManager.open();
long cityID = UtilAstro.isCityExistInDB(finalSCity, dbManager);
if (cityID < 0) {
Toast.makeText(getApplicationContext(), "Offline: brak danych", Toast.LENGTH_SHORT).show();
hideProgressBar();
} else {
// umiesc dane w ViewModel
// pobierz dane z bazy i dopiero zaaktualizuj
UtilAstro.fetchFromDatabaseAndUpdateViewModel(cityID, dbManager, sharedViewModel);
// przejdz do instancji
hideProgressBar();
// Navigate from MainActivity to OverviewActivity
Intent intent = new Intent(MainActivity.this, OverviewActivity.class);
intent.putExtra(DatabaseHelper.CITY_ID, sharedViewModel.getCommon().getAsLong(DatabaseHelper.CITY_ID));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(LAST_CITY_KEY, sCity);
editor.apply(); // writes the updates to disk asynchronously
String readTime = String.valueOf(spinner.getSelectedItem()).substring(0, 2);
intent.putExtra(INPUTED_TIME, readTime);
startActivity(intent);
}
}
});
}
});
}
private void setForce() {
force.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showProgressBar();
final String sCity = city.getText().toString();
//working
weatherForecast.saveInternetWeatherContentInViewModel(sCity, new WeatherForecast.onSavedResponse() {
//zablokuj ekran
@Override
public void onSaved() {
// odblokuj ekran
hideProgressBar();
// Navigate from MainActivity to OverviewActivity
Intent intent = new Intent(MainActivity.this, OverviewActivity.class);
intent.putExtra(DatabaseHelper.CITY_ID, sharedViewModel.getCommon().getAsLong(DatabaseHelper.CITY_ID));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(LAST_CITY_KEY, sCity);
editor.apply(); // writes the updates to disk asynchronously
String readTime = String.valueOf(spinner.getSelectedItem()).substring(0, 2);
intent.putExtra(INPUTED_TIME, readTime);
startActivity(intent);
}
@Override
public void onFailed() {
// odblokuj ekran
// zglos blad jakis tam dodatkowy. kurwa nie wiem, wymysl cos
Toast.makeText(getApplicationContext(), "Sprawdz dane/Polaczenie z Internetem", Toast.LENGTH_SHORT).show();
hideProgressBar();
}
});
}
});
}
private void addItemsToTimeSpinner() {
List<String> timeDelayList = new ArrayList<String>();
timeDelayList.add("1 minuta");
timeDelayList.add("2 minuty");
timeDelayList.add("5 minut");
timeDelayList.add("10 minut");
timeDelayList.add("30 minut");
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, timeDelayList);
// Specify the layout to use when the list of choices appears
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(dataAdapter);
}
}
| AKrupaa/Astro | app/src/main/java/com/example/astro/MainActivity.java | 2,033 | // tak -> przejdz | line_comment | pl | package com.example.astro;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public static final String MY_PREFERENCES = "MY_PREFERENCES";
public static final String LAST_CITY_KEY = "LAST_CITY_KEY";
public static final String INPUTED_TIME = "INPUTED_TIME";
private EditText city;
private Button confirm;
private Button force;
private WeatherForecast weatherForecast;
private SharedViewModel sharedViewModel;
private ProgressBar progressBar;
private SharedPreferences sharedPreferences;
Spinner spinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedViewModel = new ViewModelProvider(this).get(SharedViewModel.class);
weatherForecast = new WeatherForecast(getApplicationContext(), sharedViewModel);
initialization();
hideProgressBar();
Context context = getApplicationContext();
// You can create a new shared preference file or access an existing one by calling method
sharedPreferences = context.getSharedPreferences(MY_PREFERENCES, context.MODE_PRIVATE);
// int defaultValue = getResources().getInteger(R.integer.saved_high_score_default_key);
city.setText(sharedPreferences.getString(LAST_CITY_KEY, ""));
spinner = findViewById(R.id.spinnerTime);
addItemsToTimeSpinner();
setConfirm();
setForce();
}
@Override
protected void onStart() {
super.onStart();
}
private void initialization() {
city = (EditText) findViewById(R.id.city);
confirm = (Button) findViewById(R.id.buttonConfirm);
force = (Button) findViewById(R.id.buttonForce);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
}
private void showProgressBar() {
progressBar.setVisibility(View.VISIBLE);
}
private void hideProgressBar() {
progressBar.setVisibility(View.INVISIBLE);
}
private void setConfirm() {
confirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showProgressBar();
// pobieraj, nie patyczkuj się
final String sCity = city.getText().toString();
final String finalSCity = sCity;
weatherForecast.saveInternetWeatherContentInViewModel(sCity, new WeatherForecast.onSavedResponse() {
@Override
public void onSaved() {
// przejdz do nowej intencji
hideProgressBar();
// Navigate from MainActivity to OverviewActivity
Intent intent = new Intent(MainActivity.this, OverviewActivity.class);
intent.putExtra(DatabaseHelper.CITY_ID, sharedViewModel.getCommon().getAsLong(DatabaseHelper.CITY_ID));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(LAST_CITY_KEY, sCity);
editor.apply(); // writes the updates to disk asynchronously
String readTime = String.valueOf(spinner.getSelectedItem()).substring(0, 2);
intent.putExtra(INPUTED_TIME, readTime);
startActivity(intent);
}
@Override
public void onFailed() {
// sprobuj baze danych
// nie -> blad
// ta<SUF>
DBManager dbManager = new DBManager(getApplicationContext());
dbManager.open();
long cityID = UtilAstro.isCityExistInDB(finalSCity, dbManager);
if (cityID < 0) {
Toast.makeText(getApplicationContext(), "Offline: brak danych", Toast.LENGTH_SHORT).show();
hideProgressBar();
} else {
// umiesc dane w ViewModel
// pobierz dane z bazy i dopiero zaaktualizuj
UtilAstro.fetchFromDatabaseAndUpdateViewModel(cityID, dbManager, sharedViewModel);
// przejdz do instancji
hideProgressBar();
// Navigate from MainActivity to OverviewActivity
Intent intent = new Intent(MainActivity.this, OverviewActivity.class);
intent.putExtra(DatabaseHelper.CITY_ID, sharedViewModel.getCommon().getAsLong(DatabaseHelper.CITY_ID));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(LAST_CITY_KEY, sCity);
editor.apply(); // writes the updates to disk asynchronously
String readTime = String.valueOf(spinner.getSelectedItem()).substring(0, 2);
intent.putExtra(INPUTED_TIME, readTime);
startActivity(intent);
}
}
});
}
});
}
private void setForce() {
force.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showProgressBar();
final String sCity = city.getText().toString();
//working
weatherForecast.saveInternetWeatherContentInViewModel(sCity, new WeatherForecast.onSavedResponse() {
//zablokuj ekran
@Override
public void onSaved() {
// odblokuj ekran
hideProgressBar();
// Navigate from MainActivity to OverviewActivity
Intent intent = new Intent(MainActivity.this, OverviewActivity.class);
intent.putExtra(DatabaseHelper.CITY_ID, sharedViewModel.getCommon().getAsLong(DatabaseHelper.CITY_ID));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(LAST_CITY_KEY, sCity);
editor.apply(); // writes the updates to disk asynchronously
String readTime = String.valueOf(spinner.getSelectedItem()).substring(0, 2);
intent.putExtra(INPUTED_TIME, readTime);
startActivity(intent);
}
@Override
public void onFailed() {
// odblokuj ekran
// zglos blad jakis tam dodatkowy. kurwa nie wiem, wymysl cos
Toast.makeText(getApplicationContext(), "Sprawdz dane/Polaczenie z Internetem", Toast.LENGTH_SHORT).show();
hideProgressBar();
}
});
}
});
}
private void addItemsToTimeSpinner() {
List<String> timeDelayList = new ArrayList<String>();
timeDelayList.add("1 minuta");
timeDelayList.add("2 minuty");
timeDelayList.add("5 minut");
timeDelayList.add("10 minut");
timeDelayList.add("30 minut");
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, timeDelayList);
// Specify the layout to use when the list of choices appears
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(dataAdapter);
}
}
|
55133_4 | package com.example.astroweathercz2;
import android.database.Cursor;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
//1. pobierz z bazy danych
//2. sprawdz date z bazy danych z aktualnym czasem
//3. jezeli rozni sie o godzine
//4. zgarnij z neta
//5. podmiec baze danych
public class AstroWeatherCompare {
public AstroWeatherCompare() {
}
boolean doINeedToFetchFromInternet(String name, Cursor cur) {
Cursor cursor = cur;
cursor.moveToFirst();
for (; !cursor.isAfterLast(); cursor.moveToNext()) {
// jezeli masz to miasto ...
// jezeli miasto w bazie danych == miasto ktore szuka uzytkownik
String value = cursor.getString(cursor.getColumnIndex(DatabaseHelper.NAME));
if (value.equals(name)) {
// to zgarnij date wpisu dla tego wlasnie miasta
String fetchedDate = cursor.getString(cursor.getColumnIndex(DatabaseHelper.DATE_OF_INSERT));
// porownaj aktualny czas z tym w bazie danych
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dateFromDB = null;
try {
dateFromDB = sdf.parse(fetchedDate);
} catch (ParseException e) {
e.printStackTrace();
}
String time = sdf.format(Calendar.getInstance().getTime());
Date now = null;
try {
now = sdf.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
long timeFromDB = dateFromDB.getTime();
long timeNow = now.getTime();
long timeDifferenceMilliseconds = Math.abs(timeFromDB - timeNow);
// jezeli dane nie są stare tj. minelo mniej niz 30 minut od ostatniego sprawdzenia to...
// GET FROM DATABASE
if (timeDifferenceMilliseconds < (1000 * 60 * 30))
return false;
}
}
// FETCH FROM INTERNET
return true;
}
public long IDOfCityName(String name, Cursor cursor) throws Exception {
cursor.moveToFirst();
for (; !cursor.isAfterLast(); cursor.moveToNext()) {
if (cursor.getString(cursor.getColumnIndex(DatabaseHelper.NAME)).equals(name)) {
// ID
long ID = cursor.getLong(cursor.getColumnIndex(DatabaseHelper._ID));
// Toast.makeText(null, "ID of City Name " + ID, Toast.LENGTH_LONG).show();
return ID;
}
}
throw new Exception("There is not any city " + name + " in database");
}
}
| AKrupaa/AstroWeather-and-OpenWeather-API | app/src/main/java/com/example/astroweathercz2/AstroWeatherCompare.java | 779 | //5. podmiec baze danych | line_comment | pl | package com.example.astroweathercz2;
import android.database.Cursor;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
//1. pobierz z bazy danych
//2. sprawdz date z bazy danych z aktualnym czasem
//3. jezeli rozni sie o godzine
//4. zgarnij z neta
//5.<SUF>
public class AstroWeatherCompare {
public AstroWeatherCompare() {
}
boolean doINeedToFetchFromInternet(String name, Cursor cur) {
Cursor cursor = cur;
cursor.moveToFirst();
for (; !cursor.isAfterLast(); cursor.moveToNext()) {
// jezeli masz to miasto ...
// jezeli miasto w bazie danych == miasto ktore szuka uzytkownik
String value = cursor.getString(cursor.getColumnIndex(DatabaseHelper.NAME));
if (value.equals(name)) {
// to zgarnij date wpisu dla tego wlasnie miasta
String fetchedDate = cursor.getString(cursor.getColumnIndex(DatabaseHelper.DATE_OF_INSERT));
// porownaj aktualny czas z tym w bazie danych
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dateFromDB = null;
try {
dateFromDB = sdf.parse(fetchedDate);
} catch (ParseException e) {
e.printStackTrace();
}
String time = sdf.format(Calendar.getInstance().getTime());
Date now = null;
try {
now = sdf.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
long timeFromDB = dateFromDB.getTime();
long timeNow = now.getTime();
long timeDifferenceMilliseconds = Math.abs(timeFromDB - timeNow);
// jezeli dane nie są stare tj. minelo mniej niz 30 minut od ostatniego sprawdzenia to...
// GET FROM DATABASE
if (timeDifferenceMilliseconds < (1000 * 60 * 30))
return false;
}
}
// FETCH FROM INTERNET
return true;
}
public long IDOfCityName(String name, Cursor cursor) throws Exception {
cursor.moveToFirst();
for (; !cursor.isAfterLast(); cursor.moveToNext()) {
if (cursor.getString(cursor.getColumnIndex(DatabaseHelper.NAME)).equals(name)) {
// ID
long ID = cursor.getLong(cursor.getColumnIndex(DatabaseHelper._ID));
// Toast.makeText(null, "ID of City Name " + ID, Toast.LENGTH_LONG).show();
return ID;
}
}
throw new Exception("There is not any city " + name + " in database");
}
}
|
102125_23 | package com.example.astroweathercz1_v11;
import com.astrocalculator.AstroCalculator;
import com.astrocalculator.AstroDateTime;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class Astronomy implements Serializable {
private AstroCalculator astroCalculator;
private AstroDateTime astroDateTime;
public void setAstroCalculator(Double latitude, Double longitude) {
int year = Calendar.getInstance().get(Calendar.YEAR);
int month = Calendar.getInstance().get(Calendar.MONTH) +1;
int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
int hour = Calendar.getInstance().get(Calendar.HOUR);
int minute = Calendar.getInstance().get(Calendar.MINUTE);
int second = Calendar.getInstance().get(Calendar.SECOND);
// timezoneOffset - Time zone offset (in hours)
int timezoneOffset = Calendar.getInstance().get(Calendar.ZONE_OFFSET);
// daylightSaving - Flag indicating if daylight saving is applicable or not
// ... jpdl
boolean daylightSaving = Calendar.getInstance().getTimeZone().inDaylightTime(new Date());
astroDateTime = new AstroDateTime(year, month, day, hour, minute, second, timezoneOffset, daylightSaving);
// AstroCalculator.Location(double latitude, double longitude);
AstroCalculator.Location astroLocation = new AstroCalculator.Location(latitude, longitude);
astroCalculator = new AstroCalculator(astroDateTime, astroLocation);
}
public ArrayList<String> getSunInfo() {
// Map<String, String> mapSunInfo = new TreeMap<>();
ArrayList<String> arrayList = new ArrayList<>();
AstroCalculator.SunInfo sunAstroInfo = astroCalculator.getSunInfo();
// Function returns azimuth of sunrise for specific date and location
String azimuthRise = String.valueOf(sunAstroInfo.getAzimuthRise());
// Function returns azimuth of sunset for specific date and location
String azimuthSet = String.valueOf(sunAstroInfo.getAzimuthSet());
// Function returns time of sunrise for specific date and location
String sunRise = sunAstroInfo.getSunrise().toString();
// Function returns time of sunset for specific date and location
String sunSet = sunAstroInfo.getSunset().toString();
// Function returns time of civil morning twilight for specific date and location
String twilightMorning = sunAstroInfo.getTwilightMorning().toString();
// Function returns time of civil evening twilight for specific date and location
String twilightEvening = sunAstroInfo.getTwilightEvening().toString();
arrayList.add("Wschód słońca: " + sunRise);
arrayList.add("Azymut: "+ azimuthRise);
arrayList.add("Zachód słońca: " + sunSet);
arrayList.add("Azymut: " + azimuthSet);
arrayList.add("Civil morning twilight: " + twilightMorning);
arrayList.add("Civil evening twilight: " + twilightEvening);
return arrayList;
}
public ArrayList<String> getMoonInfo() {
/*Wchód i zachód (czas).
• Najbliższy nów i pełnia (data).
• Faza księżyca (w procentach).
• Dzień miesiąca synodycznego.*/
ArrayList<String> arrayList = new ArrayList<>();
AstroCalculator.MoonInfo moonAstroInfo = astroCalculator.getMoonInfo();
// Function returns moon age
// String moonAge = String.valueOf(moonAstroInfo.getAge());
// Function returns time of moonrise for specific date and location
String moonRise = moonAstroInfo.getMoonrise().toString();
// Function returns time of moonset for specific date and location
String moonSet = moonAstroInfo.getMoonset().toString();
// Function returns date and time of next new moon phase
// we need only date
int yearNextMoon = moonAstroInfo.getNextNewMoon().getYear();
int monthNextMoon = moonAstroInfo.getNextNewMoon().getMonth();
int dayNextMoon = moonAstroInfo.getNextNewMoon().getDay();
String nextNewMoon = String.format("%s-%s-%s", yearNextMoon, monthNextMoon, dayNextMoon);
// Function returns date and time of next full moon phase
// we need only date
int yearFullMoon = moonAstroInfo.getNextFullMoon().getYear();
int monthFullMoon = moonAstroInfo.getNextFullMoon().getMonth();
int dayFullMoon = moonAstroInfo.getNextFullMoon().getDay();
String fullMoon = String.format("%s-%s-%s", yearFullMoon, monthFullMoon, dayFullMoon);
// Function returns moon illumination
// %.4 -> returns 2 char fractional part filling with 0
// multiply by 100%
String moonIllumination = String.format(Locale.getDefault(), "%.2f", moonAstroInfo.getIllumination() * 100);
// Dzień miesiąca synodycznego.???????
// Miesiąc synodyczny[1], lunacja[2] – średni czas pomiędzy kolejnymi nowiami[a] Księżyca
// int yearNewNextMoon = moonAstroInfo.getNextNewMoon().getYear();
// int monthNewNextMoon = moonAstroInfo.getNextNewMoon().getMonth();
// int dayNewNextMoon = moonAstroInfo.getNextNewMoon().getDay();
int nowYear = astroDateTime.getYear();
int nowMonth = astroDateTime.getMonth();
int nowDay = astroDateTime.getDay();
String nextNewestNewMoon = String.format("%s-%s-%s", nowYear, nowMonth, nowDay);
long timeDifferenceMilliseconds = 0;
try {
Date oldDate = new SimpleDateFormat("yyyy-mm-dd").parse(nextNewMoon);
Date newDate = new SimpleDateFormat("yyyy-mm-dd").parse(nextNewestNewMoon);
long oldTime = oldDate.getTime();
long newTime = newDate.getTime();
timeDifferenceMilliseconds = Math.abs(newTime - oldTime);
} catch (ParseException e) {
e.printStackTrace();
}
// long synodicMonthDay = synodicMonthDayCalculator(nextNewMoon/*, yearNextMoon, monthNextMoon, dayNextMoon*/);
long synodicMonthDay = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24);
arrayList.add("Wschód księżyca: " + moonRise);
arrayList.add("Zachód księżyca: " + moonSet);
arrayList.add("Najbliższy nów: " + nextNewMoon);
arrayList.add("Najbliższa pełnia: " + fullMoon);
arrayList.add("Faza księżyca: " + moonIllumination);
arrayList.add("Dzień miesiąca synodycznego: " + synodicMonthDay);
return arrayList;
}
private long synodicMonthDayCalculator(String nextNewMoon) {
AstroCalculator.MoonInfo moonAstroInfo;
moonAstroInfo = astroCalculator.getMoonInfo();
int yearNewNextMoon = moonAstroInfo.getNextNewMoon().getYear();
int monthNewNextMoon = moonAstroInfo.getNextNewMoon().getMonth();
int dayNewNextMoon = moonAstroInfo.getNextNewMoon().getDay();
String nextNewestNewMoon = String.format("%s-%s-%s", yearNewNextMoon, monthNewNextMoon, dayNewNextMoon);
long timeDifferenceMilliseconds = 0;
try {
Date oldDate = new SimpleDateFormat("yyyy-mm-dd").parse(nextNewMoon);
Date newDate = new SimpleDateFormat("yyyy-mm-dd").parse(nextNewestNewMoon);
long oldTime = oldDate.getTime();
long newTime = newDate.getTime();
timeDifferenceMilliseconds = Math.abs(newTime - oldTime);
} catch (ParseException e) {
e.printStackTrace();
}
// https://stackoverflow.com/questions/4673527/converting-milliseconds-to-a-date-jquery-javascript
// https://stackoverflow.com/questions/5351483/calculate-date-time-difference-in-java
// int synodicMonthDay = new Date(diff).getDay();
long diffDays = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24);
// long synodicMonthDay = diffDays;
return diffDays;
}
}
| AKrupaa/AstroWeather_v1 | app/src/main/java/com/example/astroweathercz1_v11/Astronomy.java | 2,401 | // Dzień miesiąca synodycznego.??????? | line_comment | pl | package com.example.astroweathercz1_v11;
import com.astrocalculator.AstroCalculator;
import com.astrocalculator.AstroDateTime;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class Astronomy implements Serializable {
private AstroCalculator astroCalculator;
private AstroDateTime astroDateTime;
public void setAstroCalculator(Double latitude, Double longitude) {
int year = Calendar.getInstance().get(Calendar.YEAR);
int month = Calendar.getInstance().get(Calendar.MONTH) +1;
int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
int hour = Calendar.getInstance().get(Calendar.HOUR);
int minute = Calendar.getInstance().get(Calendar.MINUTE);
int second = Calendar.getInstance().get(Calendar.SECOND);
// timezoneOffset - Time zone offset (in hours)
int timezoneOffset = Calendar.getInstance().get(Calendar.ZONE_OFFSET);
// daylightSaving - Flag indicating if daylight saving is applicable or not
// ... jpdl
boolean daylightSaving = Calendar.getInstance().getTimeZone().inDaylightTime(new Date());
astroDateTime = new AstroDateTime(year, month, day, hour, minute, second, timezoneOffset, daylightSaving);
// AstroCalculator.Location(double latitude, double longitude);
AstroCalculator.Location astroLocation = new AstroCalculator.Location(latitude, longitude);
astroCalculator = new AstroCalculator(astroDateTime, astroLocation);
}
public ArrayList<String> getSunInfo() {
// Map<String, String> mapSunInfo = new TreeMap<>();
ArrayList<String> arrayList = new ArrayList<>();
AstroCalculator.SunInfo sunAstroInfo = astroCalculator.getSunInfo();
// Function returns azimuth of sunrise for specific date and location
String azimuthRise = String.valueOf(sunAstroInfo.getAzimuthRise());
// Function returns azimuth of sunset for specific date and location
String azimuthSet = String.valueOf(sunAstroInfo.getAzimuthSet());
// Function returns time of sunrise for specific date and location
String sunRise = sunAstroInfo.getSunrise().toString();
// Function returns time of sunset for specific date and location
String sunSet = sunAstroInfo.getSunset().toString();
// Function returns time of civil morning twilight for specific date and location
String twilightMorning = sunAstroInfo.getTwilightMorning().toString();
// Function returns time of civil evening twilight for specific date and location
String twilightEvening = sunAstroInfo.getTwilightEvening().toString();
arrayList.add("Wschód słońca: " + sunRise);
arrayList.add("Azymut: "+ azimuthRise);
arrayList.add("Zachód słońca: " + sunSet);
arrayList.add("Azymut: " + azimuthSet);
arrayList.add("Civil morning twilight: " + twilightMorning);
arrayList.add("Civil evening twilight: " + twilightEvening);
return arrayList;
}
public ArrayList<String> getMoonInfo() {
/*Wchód i zachód (czas).
• Najbliższy nów i pełnia (data).
• Faza księżyca (w procentach).
• Dzień miesiąca synodycznego.*/
ArrayList<String> arrayList = new ArrayList<>();
AstroCalculator.MoonInfo moonAstroInfo = astroCalculator.getMoonInfo();
// Function returns moon age
// String moonAge = String.valueOf(moonAstroInfo.getAge());
// Function returns time of moonrise for specific date and location
String moonRise = moonAstroInfo.getMoonrise().toString();
// Function returns time of moonset for specific date and location
String moonSet = moonAstroInfo.getMoonset().toString();
// Function returns date and time of next new moon phase
// we need only date
int yearNextMoon = moonAstroInfo.getNextNewMoon().getYear();
int monthNextMoon = moonAstroInfo.getNextNewMoon().getMonth();
int dayNextMoon = moonAstroInfo.getNextNewMoon().getDay();
String nextNewMoon = String.format("%s-%s-%s", yearNextMoon, monthNextMoon, dayNextMoon);
// Function returns date and time of next full moon phase
// we need only date
int yearFullMoon = moonAstroInfo.getNextFullMoon().getYear();
int monthFullMoon = moonAstroInfo.getNextFullMoon().getMonth();
int dayFullMoon = moonAstroInfo.getNextFullMoon().getDay();
String fullMoon = String.format("%s-%s-%s", yearFullMoon, monthFullMoon, dayFullMoon);
// Function returns moon illumination
// %.4 -> returns 2 char fractional part filling with 0
// multiply by 100%
String moonIllumination = String.format(Locale.getDefault(), "%.2f", moonAstroInfo.getIllumination() * 100);
// Dz<SUF>
// Miesiąc synodyczny[1], lunacja[2] – średni czas pomiędzy kolejnymi nowiami[a] Księżyca
// int yearNewNextMoon = moonAstroInfo.getNextNewMoon().getYear();
// int monthNewNextMoon = moonAstroInfo.getNextNewMoon().getMonth();
// int dayNewNextMoon = moonAstroInfo.getNextNewMoon().getDay();
int nowYear = astroDateTime.getYear();
int nowMonth = astroDateTime.getMonth();
int nowDay = astroDateTime.getDay();
String nextNewestNewMoon = String.format("%s-%s-%s", nowYear, nowMonth, nowDay);
long timeDifferenceMilliseconds = 0;
try {
Date oldDate = new SimpleDateFormat("yyyy-mm-dd").parse(nextNewMoon);
Date newDate = new SimpleDateFormat("yyyy-mm-dd").parse(nextNewestNewMoon);
long oldTime = oldDate.getTime();
long newTime = newDate.getTime();
timeDifferenceMilliseconds = Math.abs(newTime - oldTime);
} catch (ParseException e) {
e.printStackTrace();
}
// long synodicMonthDay = synodicMonthDayCalculator(nextNewMoon/*, yearNextMoon, monthNextMoon, dayNextMoon*/);
long synodicMonthDay = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24);
arrayList.add("Wschód księżyca: " + moonRise);
arrayList.add("Zachód księżyca: " + moonSet);
arrayList.add("Najbliższy nów: " + nextNewMoon);
arrayList.add("Najbliższa pełnia: " + fullMoon);
arrayList.add("Faza księżyca: " + moonIllumination);
arrayList.add("Dzień miesiąca synodycznego: " + synodicMonthDay);
return arrayList;
}
private long synodicMonthDayCalculator(String nextNewMoon) {
AstroCalculator.MoonInfo moonAstroInfo;
moonAstroInfo = astroCalculator.getMoonInfo();
int yearNewNextMoon = moonAstroInfo.getNextNewMoon().getYear();
int monthNewNextMoon = moonAstroInfo.getNextNewMoon().getMonth();
int dayNewNextMoon = moonAstroInfo.getNextNewMoon().getDay();
String nextNewestNewMoon = String.format("%s-%s-%s", yearNewNextMoon, monthNewNextMoon, dayNewNextMoon);
long timeDifferenceMilliseconds = 0;
try {
Date oldDate = new SimpleDateFormat("yyyy-mm-dd").parse(nextNewMoon);
Date newDate = new SimpleDateFormat("yyyy-mm-dd").parse(nextNewestNewMoon);
long oldTime = oldDate.getTime();
long newTime = newDate.getTime();
timeDifferenceMilliseconds = Math.abs(newTime - oldTime);
} catch (ParseException e) {
e.printStackTrace();
}
// https://stackoverflow.com/questions/4673527/converting-milliseconds-to-a-date-jquery-javascript
// https://stackoverflow.com/questions/5351483/calculate-date-time-difference-in-java
// int synodicMonthDay = new Date(diff).getDay();
long diffDays = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24);
// long synodicMonthDay = diffDays;
return diffDays;
}
}
|
49714_0 | package com.example.astroweathercz1;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class Fragment1 extends Fragment {
private IFragment1Listener listener;
private EditText editText;
private Button buttonOK;
public interface IFragment1Listener {
void onInput1Sent (CharSequence input);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment1_fragment, container, false);
editText = v.findViewById(R.id.editTextFragment1);
buttonOK = v.findViewById(R.id.buttonFragment1);
buttonOK.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CharSequence input = editText.getText();
listener.onInput1Sent(input);
}
});
return v;
}
public void updateEditText(CharSequence newText) {
editText.setText(newText);
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
// jeżeli nasza aktywność implementuje IFragmentAListener
if (context instanceof IFragment1Listener) {
listener = (IFragment1Listener) context;
} else {
throw new RuntimeException(context.toString() + " musisz zaimplementowac IFragment1Listener");
}
}
@Override
public void onDetach() {
super.onDetach();
listener = null;
}
}
| AKrupaa/Fragments-With-Interface-Android-Studio | app/src/main/java/com/example/astroweathercz1/Fragment1.java | 493 | // jeżeli nasza aktywność implementuje IFragmentAListener | line_comment | pl | package com.example.astroweathercz1;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class Fragment1 extends Fragment {
private IFragment1Listener listener;
private EditText editText;
private Button buttonOK;
public interface IFragment1Listener {
void onInput1Sent (CharSequence input);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment1_fragment, container, false);
editText = v.findViewById(R.id.editTextFragment1);
buttonOK = v.findViewById(R.id.buttonFragment1);
buttonOK.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CharSequence input = editText.getText();
listener.onInput1Sent(input);
}
});
return v;
}
public void updateEditText(CharSequence newText) {
editText.setText(newText);
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
// je<SUF>
if (context instanceof IFragment1Listener) {
listener = (IFragment1Listener) context;
} else {
throw new RuntimeException(context.toString() + " musisz zaimplementowac IFragment1Listener");
}
}
@Override
public void onDetach() {
super.onDetach();
listener = null;
}
}
|
7185_12 | package com.example.my_application;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
// potrzebne do pisania logow w Logcat
private static final String TAG = "onCreatedMethodSHOW";
// wypisywanie daty w elemncie TextView (android)
TextView textView_output;
// utowrzenie przycisku aby wystartowal Kalkulator
Button launchCalculatorAdvanced;
Button launchCalculatorSimple;
Button launchInfo;
Button exitProgram;
// lifecycle
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
launchCalculatorAdvanced = findViewById(R.id.turnOnTheCalculatorAdvanced);
launchCalculatorSimple = findViewById(R.id.turnOnTheCalculatorSimple);
launchInfo = findViewById(R.id.turnOnTheInfo);
exitProgram = findViewById(R.id.exit);
launchInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String title = "Informacje o twórcy";
final String message = "Wykonał i opracował:\n\n\nArkadiusz Krupiński, Poland\n\n\n" +
"Aby rozpocząć wybierz swoją wersję kalkulatora";
popUp(title, message);
}
});
launchCalculatorSimple.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Navigate from MainActivity to Main3Activity
Intent intent = new Intent(MainActivity.this, Kalkulator.class);
intent.putExtra("isThisSimpleCalculator", "1");
startActivity(intent);
}
});
launchCalculatorAdvanced.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Navigate from MainActivity to Main3Activity
Intent intent = new Intent(MainActivity.this, Kalkulator.class);
intent.putExtra("isThisSimpleCalculator", "0");
startActivity(intent);
}
});
exitProgram.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
System.exit(0);
}
});
}
// lifecycle
@Override
protected void onStart() {
super.onStart();
}
// lifecycle
@Override
protected void onResume() {
super.onResume();
}
// lifecycle
@Override
protected void onPause() {
super.onPause();
}
// lifecycle
@Override
protected void onStop() {
super.onStop();
}
// lifecycle
@Override
protected void onRestart() {
super.onRestart();
}
// lifecycle
@Override
protected void onDestroy() {
super.onDestroy();
}
// szkoda ze ne wiem jak wyslac funkcje, wiec to bedzie tylko na potrzeby info o mnie
private void popUp(String title, String message) {
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this)
//set icon
.setIcon(android.R.drawable.ic_dialog_alert)
//set title
.setTitle(title)
//set message
.setMessage(message)
//set positive button
.setPositiveButton("Zrozumiałem!", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//set what would happen when positive button is clicked
//nothing happened
// finish();
}
})
//set negative button
.setNegativeButton("Sprwadź mój GitHub", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//set what should happen when negative button is clicked
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/AKrupaa"));
startActivity(browserIntent);
}
})
.show();
}
}
| AKrupaa/Simple-Calculator-Android-Studio | app/src/main/java/com/example/my_application/MainActivity.java | 1,225 | // szkoda ze ne wiem jak wyslac funkcje, wiec to bedzie tylko na potrzeby info o mnie | line_comment | pl | package com.example.my_application;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
// potrzebne do pisania logow w Logcat
private static final String TAG = "onCreatedMethodSHOW";
// wypisywanie daty w elemncie TextView (android)
TextView textView_output;
// utowrzenie przycisku aby wystartowal Kalkulator
Button launchCalculatorAdvanced;
Button launchCalculatorSimple;
Button launchInfo;
Button exitProgram;
// lifecycle
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
launchCalculatorAdvanced = findViewById(R.id.turnOnTheCalculatorAdvanced);
launchCalculatorSimple = findViewById(R.id.turnOnTheCalculatorSimple);
launchInfo = findViewById(R.id.turnOnTheInfo);
exitProgram = findViewById(R.id.exit);
launchInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String title = "Informacje o twórcy";
final String message = "Wykonał i opracował:\n\n\nArkadiusz Krupiński, Poland\n\n\n" +
"Aby rozpocząć wybierz swoją wersję kalkulatora";
popUp(title, message);
}
});
launchCalculatorSimple.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Navigate from MainActivity to Main3Activity
Intent intent = new Intent(MainActivity.this, Kalkulator.class);
intent.putExtra("isThisSimpleCalculator", "1");
startActivity(intent);
}
});
launchCalculatorAdvanced.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Navigate from MainActivity to Main3Activity
Intent intent = new Intent(MainActivity.this, Kalkulator.class);
intent.putExtra("isThisSimpleCalculator", "0");
startActivity(intent);
}
});
exitProgram.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
System.exit(0);
}
});
}
// lifecycle
@Override
protected void onStart() {
super.onStart();
}
// lifecycle
@Override
protected void onResume() {
super.onResume();
}
// lifecycle
@Override
protected void onPause() {
super.onPause();
}
// lifecycle
@Override
protected void onStop() {
super.onStop();
}
// lifecycle
@Override
protected void onRestart() {
super.onRestart();
}
// lifecycle
@Override
protected void onDestroy() {
super.onDestroy();
}
// sz<SUF>
private void popUp(String title, String message) {
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this)
//set icon
.setIcon(android.R.drawable.ic_dialog_alert)
//set title
.setTitle(title)
//set message
.setMessage(message)
//set positive button
.setPositiveButton("Zrozumiałem!", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//set what would happen when positive button is clicked
//nothing happened
// finish();
}
})
//set negative button
.setNegativeButton("Sprwadź mój GitHub", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//set what should happen when negative button is clicked
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/AKrupaa"));
startActivity(browserIntent);
}
})
.show();
}
}
|
5618_31 | package app;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map.Entry;
public class Tabela {
// ~~ nazwaKolumny, zawartoscTejKolumny ~~ tabela
private Map<String, List<String>> tabela;
public Tabela() {
tabela = new TreeMap<>();
}
// SPRAWNE - nie dotykać
public void dodajKolumne(String nazwaKolumny) {
// sprawdz czy taka juz nie istnieje
boolean czyIstnieje = sprawdzCzyJuzIstniejeKolumna(nazwaKolumny);
if (czyIstnieje) {
System.out.println("Kolumna o podanej nazwie: " + nazwaKolumny + " już istnieje!");
}
// nie istnieje
// dodaj nową kolumnę i pustą zawartość
List<String> zawartoscKolumny = new ArrayList<>();
this.tabela.put(nazwaKolumny, zawartoscKolumny);
}
// SPRAWNE - nie dotykać
public void dodajWartoscDoKolumny(String nazwaKolumny, String wartosc) throws Exception {
boolean znalezionoKolumne = znajdzKolumne(nazwaKolumny);
boolean zawartoscKolumnyJestPusta = czyZawartoscKolumnyJestPusta(nazwaKolumny);
List<String> zawartoscKolumny = new ArrayList<>();
if (znalezionoKolumne) {
if (zawartoscKolumnyJestPusta) {
zawartoscKolumny.add(wartosc);
this.tabela.put(nazwaKolumny, zawartoscKolumny);
} else {
zawartoscKolumny = tabela.get(nazwaKolumny);
zawartoscKolumny.add(wartosc);
this.tabela.put(nazwaKolumny, zawartoscKolumny);
}
} else {
throw new Exception("Nie znaleziono kolumny: " + nazwaKolumny);
}
}
public void dodajWartosciDoKolumn(String[] zbiorWartosci) {
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
int i = 0;
for (Entry<String, List<String>> entry : tabela.entrySet()) {
// dla kazdej kolumny, wez i wstaw, jezeli nie masz co wstawic, wstaw ""
List<String> lista = entry.getValue();
if (i == zbiorWartosci.length)
lista.add("");
while (i < zbiorWartosci.length) {
lista.add(zbiorWartosci[i]);
i++;
break;
}
tabela.put(entry.getKey(), lista);
}
}
// SPRAWNE - nie dotykać
public Map<String, List<String>> usunKolumne(String nazwaKolumny) {
if (znajdzKolumne(nazwaKolumny)) {
// znaleziono
tabela.remove(nazwaKolumny);
return this.tabela;
}
// nie znaleziono -> wyjatek
System.out.println("Nie znaleziono kolumny" + nazwaKolumny);
return this.tabela;
}
// SPRAWNE - nie dotykać
public Map<String, List<String>> usunWartoscZKolumny(String nazwaKolumny, int index) {
boolean znalezionoKolumneOrazCzyNieJestPusta;
try {
znalezionoKolumneOrazCzyNieJestPusta = czyZnalezionoKolumneOrazCzyNieJestPusta(nazwaKolumny);
} catch (Exception e) {
System.out.println(e.getMessage());
znalezionoKolumneOrazCzyNieJestPusta = false;
}
if (znalezionoKolumneOrazCzyNieJestPusta) {
List<String> zawartoscKolumny = tabela.get(nazwaKolumny);
try {
zawartoscKolumny.remove(index);
tabela.put(nazwaKolumny, zawartoscKolumny);
} catch (IndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
return this.tabela;
}
public void usunWartosciZKolumn() {
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
for (Entry<String, List<String>> entry : tabela.entrySet()) {
List<String> nowaZawartoscKolumny = entry.getValue();
nowaZawartoscKolumny.clear();
tabela.put(entry.getKey(), nowaZawartoscKolumny);
}
}
public void usunWiersz(String kolumna, String wartosc) throws Exception {
boolean istnieje = sprawdzCzyJuzIstniejeKolumna(kolumna);
if (istnieje == false)
throw new Exception("Nie istnieje taka kolumna " + kolumna);
boolean zawiera = false;
int indexOfValue = 0;
List<String> zawartoscKolumny = tabela.get(kolumna);
for (String string : zawartoscKolumny) {
if (string.equals(wartosc)) {
zawiera = true;
break;
}
indexOfValue++;
}
if (zawiera == true) {
for (Entry<String, List<String>> entry : tabela.entrySet()) {
List<String> nowaZawartoscKolumny = entry.getValue();
nowaZawartoscKolumny.remove(indexOfValue);
tabela.put(entry.getKey(), nowaZawartoscKolumny);
}
}
}
// SPRAWNE - nie dotykać
public void wypiszWszystkieKolumny() {
System.out.println("Wszystkie dostępne kolumny");
Set<String> tabelaKeys = this.tabela.keySet();
System.out.println(tabelaKeys);
}
public void wypiszWszystkieKolumnyWrazZZawaroscia() {
Set<Entry<String, List<String>>> entires = tabela.entrySet();
for (Entry<String, List<String>> ent : entires) {
System.out.println(ent.getKey() + " ==> " + ent.getValue());
}
}
// SPRAWNE - nie dotykać
public void wypiszZawartoscKolumny(String nazwaKolumny) {
try {
czyZnalezionoKolumneOrazCzyNieJestPusta(nazwaKolumny);
// znaleziono i nie jest pusta
List<String> zawartoscKolumny;
zawartoscKolumny = tabela.get(nazwaKolumny);
// zawartoscKolumny;
if (zawartoscKolumny.size() != 0) {
System.out.println("Zawartosc kolumny " + nazwaKolumny + " to:");
for (int i = 0; i < zawartoscKolumny.size(); i++)
System.out.println("Indeks " + i + ": " + zawartoscKolumny.get(i));
} else
System.out.println("Zawartosc kolumny " + nazwaKolumny + " jest pusta!");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void wypiszKolumnyZTablicyGdzieKolumnaSpelniaWarunek(String[] zbiorKolumn, String[] warunekKolumnaWartosc) {
// wcale nie robię niezrozumiałych zagnieżdżeń
boolean wypiszWszystkieKolumny = false;
for (String kolumna : zbiorKolumn) {
if (kolumna.equals("*")) {
wypiszWszystkieKolumny = true;
break;
}
}
if (wypiszWszystkieKolumny == true) {
// wypisz wszystkie kolumny, ale tylko rzad gdzie wystapil ten ... warunek
String warunekKolumna = warunekKolumnaWartosc[0];
String warunekWartosc = warunekKolumnaWartosc[1];
// poszczegolne kolumny do wypisania
// for (String kolumna : zbiorKolumn) {
// kolumny
if (tabela.containsKey(warunekKolumna)) {
// posiada taka kolumne gdzie nalezy sprawdzic warunek
// pobierz zawartosc kolumny
List<String> zawartoscKolumny = tabela.get(warunekKolumna);
int index = 0;
// dopoki nie wyszedles ze ZBIORU WARTOSCI DANEJ KOLUMNY
while (index < zawartoscKolumny.size())
// jezeli kolumna Y posiada wartosc X ( Imie ?= Arkadiusz )
// na miejscu index
if (zawartoscKolumny.get(index).equals(warunekWartosc)) {
// wypisz teraz wszystkie rzedy, wlacznie z nazwami ... kolumn
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
for (Entry<String, List<String>> ent : tabela.entrySet()) {
// System.out.println(ent.getKey() + " ==> " + ent.getValue());
// wypisz wszystkie kolumny, ale tylko rzad gdzie wystapil ten ... warunek
System.out.println("Kolumna: " + ent.getKey() + " ==> " + ent.getValue().get(index));
}
index++;
}
}
// }
} else {
// wypisz TYLKO poszczegolne KOLUMNY oraz RZEDY
// lalalalalalaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
String warunekKolumna = warunekKolumnaWartosc[0];
String warunekWartosc = warunekKolumnaWartosc[1];
// poszczegolne kolumny do wypisania
for (String kolumna : zbiorKolumn) {
if (tabela.containsKey(warunekKolumna)) {
// posiada taka kolumne gdzie nalezy sprawdzic warunek
// pobierz zawartosc kolumny
List<String> zawartoscKolumny = tabela.get(warunekKolumna);
int index = 0;
// dopoki nie wyszedles ze ZBIORU WARTOSCI DANEJ KOLUMNY
while (index < zawartoscKolumny.size())
// jezeli kolumna Y posiada wartosc X ( Imie ?= Arkadiusz )
// na miejscu index
if (zawartoscKolumny.get(index).equals(warunekWartosc)) {
// wypisz teraz wszystkie rzedy, wlacznie z nazwami ... kolumn
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
for (Entry<String, List<String>> ent : tabela.entrySet()) {
// System.out.println(ent.getKey() + " ==> " + ent.getValue());
// wypisz WYBRANE kolumny, ale tylko rzad gdzie wystapil ten ... warunek
// lalala.
if (ent.getKey().equals(kolumna))
System.out.println("Kolumna: " + ent.getKey() + " ==> " + ent.getValue().get(index));
}
index++;
}
// index++;
}
}
}
}
// SPRAWNE - nie dotykać
public boolean znajdzKolumne(String nazwaKolumny) {
Set<String> tabelaKeys = this.tabela.keySet();
for (String tabelaKey : tabelaKeys) {
if (tabelaKey.compareTo(nazwaKolumny) == 0) {
return true;
}
}
return false;
}
// SPRAWNE - nie dotykać
private boolean sprawdzCzyJuzIstniejeKolumna(String nazwaKolumny) {
Set<String> tabelaKeys = this.tabela.keySet();
int counter = 0;
for (String tabelaKey : tabelaKeys) {
if (tabelaKey.compareTo(nazwaKolumny) == 0) {
counter = counter + 1;
}
}
if (counter > 0)
return true; // wystapil duplikat
else
return false; // nie ma duplikatu
}
// SPRAWNE - nie dotykać
private boolean czyZawartoscKolumnyJestPusta(String nazwaKolumny) {
if (tabela.get(nazwaKolumny) == null)
return true;
else
return false;
}
// SPRAWNE - nie dotykać
public boolean czyZnalezionoKolumneOrazCzyNieJestPusta(String nazwaKolumny) throws Exception {
// znaleziono ale jest pusta
if (znajdzKolumne(nazwaKolumny) && czyZawartoscKolumnyJestPusta(nazwaKolumny))
throw new Exception("Zawartosc kolumny " + nazwaKolumny + " jest akutalnie pusta");
// nie znaleziono
if (!znajdzKolumne(nazwaKolumny))
throw new Exception("Nie znaleziono kolumny " + nazwaKolumny);
// znaleziono
return true;
}
} | AKrupaa/Simple-database-in-Java | src/app/Tabela.java | 3,959 | // wypisz TYLKO poszczegolne KOLUMNY oraz RZEDY | line_comment | pl | package app;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map.Entry;
public class Tabela {
// ~~ nazwaKolumny, zawartoscTejKolumny ~~ tabela
private Map<String, List<String>> tabela;
public Tabela() {
tabela = new TreeMap<>();
}
// SPRAWNE - nie dotykać
public void dodajKolumne(String nazwaKolumny) {
// sprawdz czy taka juz nie istnieje
boolean czyIstnieje = sprawdzCzyJuzIstniejeKolumna(nazwaKolumny);
if (czyIstnieje) {
System.out.println("Kolumna o podanej nazwie: " + nazwaKolumny + " już istnieje!");
}
// nie istnieje
// dodaj nową kolumnę i pustą zawartość
List<String> zawartoscKolumny = new ArrayList<>();
this.tabela.put(nazwaKolumny, zawartoscKolumny);
}
// SPRAWNE - nie dotykać
public void dodajWartoscDoKolumny(String nazwaKolumny, String wartosc) throws Exception {
boolean znalezionoKolumne = znajdzKolumne(nazwaKolumny);
boolean zawartoscKolumnyJestPusta = czyZawartoscKolumnyJestPusta(nazwaKolumny);
List<String> zawartoscKolumny = new ArrayList<>();
if (znalezionoKolumne) {
if (zawartoscKolumnyJestPusta) {
zawartoscKolumny.add(wartosc);
this.tabela.put(nazwaKolumny, zawartoscKolumny);
} else {
zawartoscKolumny = tabela.get(nazwaKolumny);
zawartoscKolumny.add(wartosc);
this.tabela.put(nazwaKolumny, zawartoscKolumny);
}
} else {
throw new Exception("Nie znaleziono kolumny: " + nazwaKolumny);
}
}
public void dodajWartosciDoKolumn(String[] zbiorWartosci) {
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
int i = 0;
for (Entry<String, List<String>> entry : tabela.entrySet()) {
// dla kazdej kolumny, wez i wstaw, jezeli nie masz co wstawic, wstaw ""
List<String> lista = entry.getValue();
if (i == zbiorWartosci.length)
lista.add("");
while (i < zbiorWartosci.length) {
lista.add(zbiorWartosci[i]);
i++;
break;
}
tabela.put(entry.getKey(), lista);
}
}
// SPRAWNE - nie dotykać
public Map<String, List<String>> usunKolumne(String nazwaKolumny) {
if (znajdzKolumne(nazwaKolumny)) {
// znaleziono
tabela.remove(nazwaKolumny);
return this.tabela;
}
// nie znaleziono -> wyjatek
System.out.println("Nie znaleziono kolumny" + nazwaKolumny);
return this.tabela;
}
// SPRAWNE - nie dotykać
public Map<String, List<String>> usunWartoscZKolumny(String nazwaKolumny, int index) {
boolean znalezionoKolumneOrazCzyNieJestPusta;
try {
znalezionoKolumneOrazCzyNieJestPusta = czyZnalezionoKolumneOrazCzyNieJestPusta(nazwaKolumny);
} catch (Exception e) {
System.out.println(e.getMessage());
znalezionoKolumneOrazCzyNieJestPusta = false;
}
if (znalezionoKolumneOrazCzyNieJestPusta) {
List<String> zawartoscKolumny = tabela.get(nazwaKolumny);
try {
zawartoscKolumny.remove(index);
tabela.put(nazwaKolumny, zawartoscKolumny);
} catch (IndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
return this.tabela;
}
public void usunWartosciZKolumn() {
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
for (Entry<String, List<String>> entry : tabela.entrySet()) {
List<String> nowaZawartoscKolumny = entry.getValue();
nowaZawartoscKolumny.clear();
tabela.put(entry.getKey(), nowaZawartoscKolumny);
}
}
public void usunWiersz(String kolumna, String wartosc) throws Exception {
boolean istnieje = sprawdzCzyJuzIstniejeKolumna(kolumna);
if (istnieje == false)
throw new Exception("Nie istnieje taka kolumna " + kolumna);
boolean zawiera = false;
int indexOfValue = 0;
List<String> zawartoscKolumny = tabela.get(kolumna);
for (String string : zawartoscKolumny) {
if (string.equals(wartosc)) {
zawiera = true;
break;
}
indexOfValue++;
}
if (zawiera == true) {
for (Entry<String, List<String>> entry : tabela.entrySet()) {
List<String> nowaZawartoscKolumny = entry.getValue();
nowaZawartoscKolumny.remove(indexOfValue);
tabela.put(entry.getKey(), nowaZawartoscKolumny);
}
}
}
// SPRAWNE - nie dotykać
public void wypiszWszystkieKolumny() {
System.out.println("Wszystkie dostępne kolumny");
Set<String> tabelaKeys = this.tabela.keySet();
System.out.println(tabelaKeys);
}
public void wypiszWszystkieKolumnyWrazZZawaroscia() {
Set<Entry<String, List<String>>> entires = tabela.entrySet();
for (Entry<String, List<String>> ent : entires) {
System.out.println(ent.getKey() + " ==> " + ent.getValue());
}
}
// SPRAWNE - nie dotykać
public void wypiszZawartoscKolumny(String nazwaKolumny) {
try {
czyZnalezionoKolumneOrazCzyNieJestPusta(nazwaKolumny);
// znaleziono i nie jest pusta
List<String> zawartoscKolumny;
zawartoscKolumny = tabela.get(nazwaKolumny);
// zawartoscKolumny;
if (zawartoscKolumny.size() != 0) {
System.out.println("Zawartosc kolumny " + nazwaKolumny + " to:");
for (int i = 0; i < zawartoscKolumny.size(); i++)
System.out.println("Indeks " + i + ": " + zawartoscKolumny.get(i));
} else
System.out.println("Zawartosc kolumny " + nazwaKolumny + " jest pusta!");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void wypiszKolumnyZTablicyGdzieKolumnaSpelniaWarunek(String[] zbiorKolumn, String[] warunekKolumnaWartosc) {
// wcale nie robię niezrozumiałych zagnieżdżeń
boolean wypiszWszystkieKolumny = false;
for (String kolumna : zbiorKolumn) {
if (kolumna.equals("*")) {
wypiszWszystkieKolumny = true;
break;
}
}
if (wypiszWszystkieKolumny == true) {
// wypisz wszystkie kolumny, ale tylko rzad gdzie wystapil ten ... warunek
String warunekKolumna = warunekKolumnaWartosc[0];
String warunekWartosc = warunekKolumnaWartosc[1];
// poszczegolne kolumny do wypisania
// for (String kolumna : zbiorKolumn) {
// kolumny
if (tabela.containsKey(warunekKolumna)) {
// posiada taka kolumne gdzie nalezy sprawdzic warunek
// pobierz zawartosc kolumny
List<String> zawartoscKolumny = tabela.get(warunekKolumna);
int index = 0;
// dopoki nie wyszedles ze ZBIORU WARTOSCI DANEJ KOLUMNY
while (index < zawartoscKolumny.size())
// jezeli kolumna Y posiada wartosc X ( Imie ?= Arkadiusz )
// na miejscu index
if (zawartoscKolumny.get(index).equals(warunekWartosc)) {
// wypisz teraz wszystkie rzedy, wlacznie z nazwami ... kolumn
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
for (Entry<String, List<String>> ent : tabela.entrySet()) {
// System.out.println(ent.getKey() + " ==> " + ent.getValue());
// wypisz wszystkie kolumny, ale tylko rzad gdzie wystapil ten ... warunek
System.out.println("Kolumna: " + ent.getKey() + " ==> " + ent.getValue().get(index));
}
index++;
}
}
// }
} else {
// wy<SUF>
// lalalalalalaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
String warunekKolumna = warunekKolumnaWartosc[0];
String warunekWartosc = warunekKolumnaWartosc[1];
// poszczegolne kolumny do wypisania
for (String kolumna : zbiorKolumn) {
if (tabela.containsKey(warunekKolumna)) {
// posiada taka kolumne gdzie nalezy sprawdzic warunek
// pobierz zawartosc kolumny
List<String> zawartoscKolumny = tabela.get(warunekKolumna);
int index = 0;
// dopoki nie wyszedles ze ZBIORU WARTOSCI DANEJ KOLUMNY
while (index < zawartoscKolumny.size())
// jezeli kolumna Y posiada wartosc X ( Imie ?= Arkadiusz )
// na miejscu index
if (zawartoscKolumny.get(index).equals(warunekWartosc)) {
// wypisz teraz wszystkie rzedy, wlacznie z nazwami ... kolumn
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
for (Entry<String, List<String>> ent : tabela.entrySet()) {
// System.out.println(ent.getKey() + " ==> " + ent.getValue());
// wypisz WYBRANE kolumny, ale tylko rzad gdzie wystapil ten ... warunek
// lalala.
if (ent.getKey().equals(kolumna))
System.out.println("Kolumna: " + ent.getKey() + " ==> " + ent.getValue().get(index));
}
index++;
}
// index++;
}
}
}
}
// SPRAWNE - nie dotykać
public boolean znajdzKolumne(String nazwaKolumny) {
Set<String> tabelaKeys = this.tabela.keySet();
for (String tabelaKey : tabelaKeys) {
if (tabelaKey.compareTo(nazwaKolumny) == 0) {
return true;
}
}
return false;
}
// SPRAWNE - nie dotykać
private boolean sprawdzCzyJuzIstniejeKolumna(String nazwaKolumny) {
Set<String> tabelaKeys = this.tabela.keySet();
int counter = 0;
for (String tabelaKey : tabelaKeys) {
if (tabelaKey.compareTo(nazwaKolumny) == 0) {
counter = counter + 1;
}
}
if (counter > 0)
return true; // wystapil duplikat
else
return false; // nie ma duplikatu
}
// SPRAWNE - nie dotykać
private boolean czyZawartoscKolumnyJestPusta(String nazwaKolumny) {
if (tabela.get(nazwaKolumny) == null)
return true;
else
return false;
}
// SPRAWNE - nie dotykać
public boolean czyZnalezionoKolumneOrazCzyNieJestPusta(String nazwaKolumny) throws Exception {
// znaleziono ale jest pusta
if (znajdzKolumne(nazwaKolumny) && czyZawartoscKolumnyJestPusta(nazwaKolumny))
throw new Exception("Zawartosc kolumny " + nazwaKolumny + " jest akutalnie pusta");
// nie znaleziono
if (!znajdzKolumne(nazwaKolumny))
throw new Exception("Nie znaleziono kolumny " + nazwaKolumny);
// znaleziono
return true;
}
} |
176633_4 | package pl.arkadiusz.validator;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import pl.arkadiusz.domain.UserAddress;
import java.util.regex.Pattern;
public class AddressValidator implements Validator {
public boolean supports(Class<?> aClass) {
return UserAddress.class.isAssignableFrom(aClass);
}
public void validate(Object o, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "address", "error.field.required");
ValidationUtils.rejectIfEmpty(errors, "zipCode", "error.field.required");
ValidationUtils.rejectIfEmpty(errors, "city", "error.field.required");
ValidationUtils.rejectIfEmpty(errors, "country", "error.field.required");
ValidationUtils.rejectIfEmpty(errors, "state", "error.field.required");
// if (errors.getErrorCount() == 0) {
//// .+ – dowolny symbol użyty co najmniej raz,
//// @ – małpka,
//// .+ – ponownie dowolny symbol użyty co najmniej raz,
//// \. – kropka rozumiana dosłownie (nie jako specjalny znak wyrażenia regularnego),
//// pl – następujące po sobie litery p i l.
//// \d{5} Match 5 digits
//// ^ Start of the string.
//// Pattern zipCodePattern = Pattern.compile("\d{2}-\d{3}");
// }
}
}
| AKrupaa/Spring-Student-Works | zadania/src/main/java/pl/arkadiusz/validator/AddressValidator.java | 446 | //// \. – kropka rozumiana dosłownie (nie jako specjalny znak wyrażenia regularnego), | line_comment | pl | package pl.arkadiusz.validator;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import pl.arkadiusz.domain.UserAddress;
import java.util.regex.Pattern;
public class AddressValidator implements Validator {
public boolean supports(Class<?> aClass) {
return UserAddress.class.isAssignableFrom(aClass);
}
public void validate(Object o, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "address", "error.field.required");
ValidationUtils.rejectIfEmpty(errors, "zipCode", "error.field.required");
ValidationUtils.rejectIfEmpty(errors, "city", "error.field.required");
ValidationUtils.rejectIfEmpty(errors, "country", "error.field.required");
ValidationUtils.rejectIfEmpty(errors, "state", "error.field.required");
// if (errors.getErrorCount() == 0) {
//// .+ – dowolny symbol użyty co najmniej raz,
//// @ – małpka,
//// .+ – ponownie dowolny symbol użyty co najmniej raz,
//// \.<SUF>
//// pl – następujące po sobie litery p i l.
//// \d{5} Match 5 digits
//// ^ Start of the string.
//// Pattern zipCodePattern = Pattern.compile("\d{2}-\d{3}");
// }
}
}
|
19873_4 | package pl.majkut.press;
import Books.Book;
//import Books.Poster;
//import Magazines.Advertisement;
import Magazines.Magazine;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.InputMismatchException;
import java.lang.Throwable; // wyjatki
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Press {
static Scanner scanner = new Scanner(System.in); // umożliwia wpisywanie danych
public static void zmiennoprzecinkowe() {
/* odczyt z pliku, który zawiera liczby zmiennoprzecinkowe */
System.out.print("Odczyt z pliku zawierający liczby przecinkowe: ");
try {
FileInputStream fileInputStream = new FileInputStream("D:\\__Rozproszona Sztuczna Inteligencja\\LABORATORIA\\lab_5\\ZmiennoPrzecinkowe.txt");
// Odczytywanie jednego bajtu z pliku
int b = fileInputStream.read();
while(b != -1) { // dopóki jest bajt
// Rzutowanie na typ znakowy
System.out.print((char) b);
b = fileInputStream.read();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println("\n");
}
public static double addOrder(int count, double price, float priceBulk) throws InputMismatchException{
System.out.println("Co chcesz zamówić?" + "\n Książkę" + "\n Magazyn");
switch (scanner.nextInt()) {
case 1:
System.out.println("Wybrano książke.");
System.out.println("Autor: " + scanner.nextInt());
System.out.println("Tytuł: " + scanner.nextInt());
System.out.println("Wydawnictwo: " + scanner.nextInt());
case 2:
System.out.println("Wybrano magazyn.");
System.out.println("Nazwa magazynu: " + scanner.nextInt());
System.out.println("Wydawnictwo: " + scanner.nextInt());
}
System.out.println("Podaj format kopii: \n 1. A4 \n 2. A3 \n 3. B4 \n 4. B3");
switch (scanner.nextInt()) {
case 1:
System.out.println("Wybrano format A4.");
break;
case 2:
System.out.println("Wybrano format A3.");
break;
case 3:
System.out.println("Wybrano format B4.");
break;
case 4:
System.out.println("Wybrano format B3.");
break;
default:
throw new InputMismatchException("Niedozwolony znak. Podaj cyfrę od 1 do 4.");
//break;
}
System.out.println("Podaj ilość kopii:"); // wprowadzenie danych z klawiatury
count = scanner.nextInt();
if (count >= 0) {
throw new IllegalArgumentException("Podana wartość musi być większa od 0.");
}
else if (count >= 1000) {
System.out.println("Zniżka 30%. Do zapłaty: " + 0.3 * (count * priceBulk));
return 0.3 * (count * priceBulk);
} else {
System.out.println("Cena detaliczna. Do zapłaty:" + count * price);
return count * price;
}
}
public static void statusOrder ( boolean order){
if (order == false) {
System.out.println("Zamówienie w trakcie realizacji.");
} else {
System.out.println("Zamówienie gotowe do odbioru.");
}
}
public static void main(String[] args) throws FileNotFoundException{
File plik = new File("Press.txt"); //
float priceBulk = 50; // cena hurtowa
double price = 80; // cena detaliczna
int count = 0; // ilosc kopii
char[] finish = new char[]{'P', 'r', 'o', 'c', 'e', 's', ' ', 'z', 'a', 'k', 'o', 'n', 'c', 'z', 'o', 'n', 'y', '.'};
int[][] index = new int[100][1000]; // indeks kopii [100] - która drukarka; [1000] - które zamówienie z danej drukarki
boolean order = false;
boolean exit = false;
while (exit != true) {
try {
System.out.println("\t\n Wyświetlenie liczb zmiennoprzecinkowych: ");
zmiennoprzecinkowe();
System.out.println(" \n WITAMY W DRUKARNII!");
System.out.println("Wybierz co chcesz zrobić.");
System.out.println("1. Dodaj zamówienie.");
System.out.println("2. Sprawdź status zamówienia.");
System.out.println("3. Najnowsze pozycje w drukrnii.");
System.out.println("4. Wyjście.");
switch (scanner.nextInt()) {
case 1:
addOrder(count, price, priceBulk);
System.out.println("Dodałeś zamówienie.");
order = true;
break;
case 2:
statusOrder(order);
break;
case 3:
/* ZAPIS DO PLIKU */
PrintWriter write = new PrintWriter("Book.txt");
Book book = new Book("Stephen King", "Smentarz dla zwierząt", "Prószyński i Sp.", 1000);
book.print();
// write.println("Autor: Stephen King" + "\t Tytuł: Smentarz dla zwierząt" + "\t Wydawnictwo: Prószyński i Sp." + "\t Ilość: " + 1000);
write.println("Autor: Stephen King");
write.println("Tytuł: Smentarz dla zwierząt");
write.println("Wydawnictwo: Prószyński i Sp.");
write.println("Ilość: " + 1000);
write.close();
/* ZAPIS DO PLIKU */
Magazine magazine = new Magazine("Świat Wiedzy", "Bauer", 100);
magazine.print();
PrintWriter write2 = new PrintWriter("Magazine.txt");
// write2.println("Nazwa magazynu: Świat Wiedzy" + "\t Wydawnictwo: Bauer" + "\t Ilość: " + 100);
write2.println("Nazwa magazynu: Świat Wiedzy");
write2.println("Wydawnictwo: Bauer");
write2.println("Ilość: " + 100);
write2.close();
/* SERIALIZACJA */
Books.Poster poster = new Books.Poster("Stephen King", "Smentarz dla zwierząt", "Prószyński i Sp.", 1000, "A3");
poster.getPosterFormat(); // sprawdzanie rozszerzenia klasy Poster przez metody klasy Book
poster.print();
// zapis do pliku
PrintWriter serialWrite = new PrintWriter("Poster(serial).txt");
serialWrite.println(poster.getAuthor() + " " + poster.getTitle() + " " + poster.getPublishingHouse() + " " + poster.getCount() + " " + poster.getPosterFormat());
serialWrite.close();
System.out.println("Sprawdzenie roszczerzenia klas dla klasy 'Poster': \n użycie dziedziczonej metody 'getTitle' z klasy 'Book': \n" + poster.getTitle() + "\n");
// odczyt z pliku zapisany w wyniku serializacji
File file = new File("Poster(serial).txt");
Scanner po = new Scanner(file);
String serialRead = po.nextLine();
System.out.println(serialRead + "\n");
/* SERIALIZACJA */
// System.out.println("Reklama nowego wydania gazety Świat Wiedzy");
Magazines.Advertisement advertisement = new Magazines.Advertisement("Reklama nowego wydania gazety Świat Wiedzy", "Bauer", 100, "Reklama nowego wydania Swiata Wiedzy! Kup już dziś!", "A5");
advertisement.getClass();
advertisement.print();
// zapis do pliku
PrintWriter serialWrite2 = new PrintWriter("Advertisment(serial).txt");
serialWrite2.println(advertisement.getNameOfMagazine() + " " + advertisement.getPublishingHouseMagazine() + " " + advertisement.getCountMagazine() + " " + advertisement.getTypeOfAdvertisment() + " " + advertisement.getFormat());
serialWrite2.close();
System.out.println("Sprawdzenie roszczerzenia klas dla klasy 'Advertisment': \n użycie dziedziczonej metody 'getTypeOfAdverisment' z klasy 'Magazine': \n" + advertisement.getTypeOfAdvertisment() + "\n");
// odczyt z pliku zapisany w wyniku serializacji
File file2 = new File("Adverisment(serial).txt");
Scanner ad = new Scanner(file2);
String serialRead2 = ad.nextLine();
System.out.println(serialRead2 + "\n");
break;
case 4:
exit = true;
System.out.println(finish);
System.out.println("Do widzenia!");
break;
default:
throw new IllegalArgumentException("Podaj wartość: 1, 2, 3 lub 4.");
}
} catch (InputMismatchException expection) {
System.out.println("Niedozwolony znak. Podaj cyfrę od 1 do 4.");
} finally {
break;
}
}
}
// public void save() throws FileNotFoundException{
// PrintWriter zapis = new PrintWriter("Press.txt");
// zapis.println("pressss");
// zapis.close();
// }
} | AMajkut/Rozproszona-Sztuczna-Inteligencja | Laboratorium 5/pl/majkut/press/Press.java | 2,996 | /* odczyt z pliku, który zawiera liczby zmiennoprzecinkowe */ | block_comment | pl | package pl.majkut.press;
import Books.Book;
//import Books.Poster;
//import Magazines.Advertisement;
import Magazines.Magazine;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.InputMismatchException;
import java.lang.Throwable; // wyjatki
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Press {
static Scanner scanner = new Scanner(System.in); // umożliwia wpisywanie danych
public static void zmiennoprzecinkowe() {
/* odc<SUF>*/
System.out.print("Odczyt z pliku zawierający liczby przecinkowe: ");
try {
FileInputStream fileInputStream = new FileInputStream("D:\\__Rozproszona Sztuczna Inteligencja\\LABORATORIA\\lab_5\\ZmiennoPrzecinkowe.txt");
// Odczytywanie jednego bajtu z pliku
int b = fileInputStream.read();
while(b != -1) { // dopóki jest bajt
// Rzutowanie na typ znakowy
System.out.print((char) b);
b = fileInputStream.read();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println("\n");
}
public static double addOrder(int count, double price, float priceBulk) throws InputMismatchException{
System.out.println("Co chcesz zamówić?" + "\n Książkę" + "\n Magazyn");
switch (scanner.nextInt()) {
case 1:
System.out.println("Wybrano książke.");
System.out.println("Autor: " + scanner.nextInt());
System.out.println("Tytuł: " + scanner.nextInt());
System.out.println("Wydawnictwo: " + scanner.nextInt());
case 2:
System.out.println("Wybrano magazyn.");
System.out.println("Nazwa magazynu: " + scanner.nextInt());
System.out.println("Wydawnictwo: " + scanner.nextInt());
}
System.out.println("Podaj format kopii: \n 1. A4 \n 2. A3 \n 3. B4 \n 4. B3");
switch (scanner.nextInt()) {
case 1:
System.out.println("Wybrano format A4.");
break;
case 2:
System.out.println("Wybrano format A3.");
break;
case 3:
System.out.println("Wybrano format B4.");
break;
case 4:
System.out.println("Wybrano format B3.");
break;
default:
throw new InputMismatchException("Niedozwolony znak. Podaj cyfrę od 1 do 4.");
//break;
}
System.out.println("Podaj ilość kopii:"); // wprowadzenie danych z klawiatury
count = scanner.nextInt();
if (count >= 0) {
throw new IllegalArgumentException("Podana wartość musi być większa od 0.");
}
else if (count >= 1000) {
System.out.println("Zniżka 30%. Do zapłaty: " + 0.3 * (count * priceBulk));
return 0.3 * (count * priceBulk);
} else {
System.out.println("Cena detaliczna. Do zapłaty:" + count * price);
return count * price;
}
}
public static void statusOrder ( boolean order){
if (order == false) {
System.out.println("Zamówienie w trakcie realizacji.");
} else {
System.out.println("Zamówienie gotowe do odbioru.");
}
}
public static void main(String[] args) throws FileNotFoundException{
File plik = new File("Press.txt"); //
float priceBulk = 50; // cena hurtowa
double price = 80; // cena detaliczna
int count = 0; // ilosc kopii
char[] finish = new char[]{'P', 'r', 'o', 'c', 'e', 's', ' ', 'z', 'a', 'k', 'o', 'n', 'c', 'z', 'o', 'n', 'y', '.'};
int[][] index = new int[100][1000]; // indeks kopii [100] - która drukarka; [1000] - które zamówienie z danej drukarki
boolean order = false;
boolean exit = false;
while (exit != true) {
try {
System.out.println("\t\n Wyświetlenie liczb zmiennoprzecinkowych: ");
zmiennoprzecinkowe();
System.out.println(" \n WITAMY W DRUKARNII!");
System.out.println("Wybierz co chcesz zrobić.");
System.out.println("1. Dodaj zamówienie.");
System.out.println("2. Sprawdź status zamówienia.");
System.out.println("3. Najnowsze pozycje w drukrnii.");
System.out.println("4. Wyjście.");
switch (scanner.nextInt()) {
case 1:
addOrder(count, price, priceBulk);
System.out.println("Dodałeś zamówienie.");
order = true;
break;
case 2:
statusOrder(order);
break;
case 3:
/* ZAPIS DO PLIKU */
PrintWriter write = new PrintWriter("Book.txt");
Book book = new Book("Stephen King", "Smentarz dla zwierząt", "Prószyński i Sp.", 1000);
book.print();
// write.println("Autor: Stephen King" + "\t Tytuł: Smentarz dla zwierząt" + "\t Wydawnictwo: Prószyński i Sp." + "\t Ilość: " + 1000);
write.println("Autor: Stephen King");
write.println("Tytuł: Smentarz dla zwierząt");
write.println("Wydawnictwo: Prószyński i Sp.");
write.println("Ilość: " + 1000);
write.close();
/* ZAPIS DO PLIKU */
Magazine magazine = new Magazine("Świat Wiedzy", "Bauer", 100);
magazine.print();
PrintWriter write2 = new PrintWriter("Magazine.txt");
// write2.println("Nazwa magazynu: Świat Wiedzy" + "\t Wydawnictwo: Bauer" + "\t Ilość: " + 100);
write2.println("Nazwa magazynu: Świat Wiedzy");
write2.println("Wydawnictwo: Bauer");
write2.println("Ilość: " + 100);
write2.close();
/* SERIALIZACJA */
Books.Poster poster = new Books.Poster("Stephen King", "Smentarz dla zwierząt", "Prószyński i Sp.", 1000, "A3");
poster.getPosterFormat(); // sprawdzanie rozszerzenia klasy Poster przez metody klasy Book
poster.print();
// zapis do pliku
PrintWriter serialWrite = new PrintWriter("Poster(serial).txt");
serialWrite.println(poster.getAuthor() + " " + poster.getTitle() + " " + poster.getPublishingHouse() + " " + poster.getCount() + " " + poster.getPosterFormat());
serialWrite.close();
System.out.println("Sprawdzenie roszczerzenia klas dla klasy 'Poster': \n użycie dziedziczonej metody 'getTitle' z klasy 'Book': \n" + poster.getTitle() + "\n");
// odczyt z pliku zapisany w wyniku serializacji
File file = new File("Poster(serial).txt");
Scanner po = new Scanner(file);
String serialRead = po.nextLine();
System.out.println(serialRead + "\n");
/* SERIALIZACJA */
// System.out.println("Reklama nowego wydania gazety Świat Wiedzy");
Magazines.Advertisement advertisement = new Magazines.Advertisement("Reklama nowego wydania gazety Świat Wiedzy", "Bauer", 100, "Reklama nowego wydania Swiata Wiedzy! Kup już dziś!", "A5");
advertisement.getClass();
advertisement.print();
// zapis do pliku
PrintWriter serialWrite2 = new PrintWriter("Advertisment(serial).txt");
serialWrite2.println(advertisement.getNameOfMagazine() + " " + advertisement.getPublishingHouseMagazine() + " " + advertisement.getCountMagazine() + " " + advertisement.getTypeOfAdvertisment() + " " + advertisement.getFormat());
serialWrite2.close();
System.out.println("Sprawdzenie roszczerzenia klas dla klasy 'Advertisment': \n użycie dziedziczonej metody 'getTypeOfAdverisment' z klasy 'Magazine': \n" + advertisement.getTypeOfAdvertisment() + "\n");
// odczyt z pliku zapisany w wyniku serializacji
File file2 = new File("Adverisment(serial).txt");
Scanner ad = new Scanner(file2);
String serialRead2 = ad.nextLine();
System.out.println(serialRead2 + "\n");
break;
case 4:
exit = true;
System.out.println(finish);
System.out.println("Do widzenia!");
break;
default:
throw new IllegalArgumentException("Podaj wartość: 1, 2, 3 lub 4.");
}
} catch (InputMismatchException expection) {
System.out.println("Niedozwolony znak. Podaj cyfrę od 1 do 4.");
} finally {
break;
}
}
}
// public void save() throws FileNotFoundException{
// PrintWriter zapis = new PrintWriter("Press.txt");
// zapis.println("pressss");
// zapis.close();
// }
} |
50749_1 | package uni.projects.reader;
import org.jetbrains.annotations.NotNull;
import java.io.BufferedReader;
import java.io.IOException;
public class Reader {
private BufferedReader reader;
private char current;
private Position pos;
private StringBuilder context;
private int maxContextLength;
public Reader(@NotNull BufferedReader br, int mcl) throws IOException {
this.reader = br;
this.current = (char) br.read();
this.pos = new Position();
this.maxContextLength = mcl;
this.context = new StringBuilder();
}
public Position getPosition() {
return this.pos;
}
public char getCurrent() {
return this.current;
}
public String getContext() {
return this.context.toString();
}
public StringBuilder getContextBuilder() {
return this.context;
}
public void setCurrent(char ch) {
this.current = ch;
}
public void consume() throws IOException {
if (getCurrent() != '\n' && getCurrent() != 21 && getCurrent() != '\r') {
if (this.context.length() == this.maxContextLength)
this.context.deleteCharAt(0);
this.context.append(getCurrent());
}
setCurrent((char) reader.read());
pos.incrementColumn();
if (getCurrent() == '\r') {
reader.mark(1);
char ch = (char) reader.read();
if (ch == '\n')
setCurrent(ch);
else
reader.reset();
this.context.delete(0, context.length());
pos.incrementLine();
pos.setColumn(0);
} else if (getCurrent() == '\n' || getCurrent() == 21) // NEL 0x15
{
this.context.delete(0, context.length());
pos.incrementLine();
pos.setColumn(0); //w następnym wywołaniu tej funkcji dopiero ustawimy się na pierwszym znaku w linii
}
}
}
| AMazur2/TKOM | src/main/java/uni/projects/reader/Reader.java | 576 | //w następnym wywołaniu tej funkcji dopiero ustawimy się na pierwszym znaku w linii
| line_comment | pl | package uni.projects.reader;
import org.jetbrains.annotations.NotNull;
import java.io.BufferedReader;
import java.io.IOException;
public class Reader {
private BufferedReader reader;
private char current;
private Position pos;
private StringBuilder context;
private int maxContextLength;
public Reader(@NotNull BufferedReader br, int mcl) throws IOException {
this.reader = br;
this.current = (char) br.read();
this.pos = new Position();
this.maxContextLength = mcl;
this.context = new StringBuilder();
}
public Position getPosition() {
return this.pos;
}
public char getCurrent() {
return this.current;
}
public String getContext() {
return this.context.toString();
}
public StringBuilder getContextBuilder() {
return this.context;
}
public void setCurrent(char ch) {
this.current = ch;
}
public void consume() throws IOException {
if (getCurrent() != '\n' && getCurrent() != 21 && getCurrent() != '\r') {
if (this.context.length() == this.maxContextLength)
this.context.deleteCharAt(0);
this.context.append(getCurrent());
}
setCurrent((char) reader.read());
pos.incrementColumn();
if (getCurrent() == '\r') {
reader.mark(1);
char ch = (char) reader.read();
if (ch == '\n')
setCurrent(ch);
else
reader.reset();
this.context.delete(0, context.length());
pos.incrementLine();
pos.setColumn(0);
} else if (getCurrent() == '\n' || getCurrent() == 21) // NEL 0x15
{
this.context.delete(0, context.length());
pos.incrementLine();
pos.setColumn(0); //w <SUF>
}
}
}
|
131549_0 | package apsi.team3.backend.services;
import apsi.team3.backend.DTOs.DTOMapper;
import apsi.team3.backend.DTOs.EventDTO;
import apsi.team3.backend.DTOs.PaginatedList;
import apsi.team3.backend.exceptions.ApsiValidationException;
import apsi.team3.backend.interfaces.IEventService;
import apsi.team3.backend.model.EventImage;
import apsi.team3.backend.model.User;
import apsi.team3.backend.repository.EventImageRepository;
import apsi.team3.backend.repository.EventRepository;
import apsi.team3.backend.repository.LocationRepository;
import apsi.team3.backend.repository.TicketTypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class EventService implements IEventService {
private final int PAGE_SIZE = 10;
private final LocationRepository locationRepository;
private final EventRepository eventRepository;
private final TicketTypeRepository ticketTypeRepository;
private final EventImageRepository eventImageRepository;
@Autowired
public EventService(
EventRepository eventRepository,
LocationRepository locationRepository,
TicketTypeRepository ticketTypeRepository,
EventImageRepository eventImageRepository
) {
this.eventRepository = eventRepository;
this.locationRepository = locationRepository;
this.ticketTypeRepository = ticketTypeRepository;
this.eventImageRepository = eventImageRepository;
}
private void validateEvent(EventDTO eventDTO, User loggedUser) throws ApsiValidationException {
if (eventDTO == null || eventDTO.getName() == null || eventDTO.getName().isBlank())
throw new ApsiValidationException("Należy podać nazwę wydarzenia", "name");
if (eventDTO.getName().length() > 255)
throw new ApsiValidationException("Zbyt długa nazwa wydarzenia", "name");
if (eventDTO.getDescription().length() > 2000)
throw new ApsiValidationException("Zbyt długi opis wydarzenia", "description");
if (eventDTO.getStartDate().isAfter(eventDTO.getEndDate()))
throw new ApsiValidationException("Data końcowa nie może być wcześniejsza niż data początkowa", "endDate");
if (eventDTO.getEndDate().isBefore(LocalDate.now()))
throw new ApsiValidationException("Data końcowa nie może być przeszła", "endDate");
if (eventDTO.getStartTime() != null && eventDTO.getEndTime() != null)
if (eventDTO.getStartDate().atTime(eventDTO.getStartTime()).isAfter(eventDTO.getEndDate().atTime(eventDTO.getEndTime())))
throw new ApsiValidationException("Data początkowa nie może być wcześniejsza niż data końcowa", "startDate");
if (eventDTO.getLocation() != null && eventDTO.getLocation().getId() != null) {
var location = locationRepository.findById(eventDTO.getLocation().getId());
if (location.isEmpty())
throw new ApsiValidationException("Wybrana lokacja nie istnieje", "location");
if (eventDTO.getTicketTypes().size() > 0 &&
location.get().getCapacity() != 0 &&
location.get().getCapacity() < eventDTO.getTicketTypes().stream().mapToInt(e -> e.getQuantityAvailable()).sum()
)
throw new ApsiValidationException("Ilość biletów większa niż dopuszczalna w danej lokalizacji", "tickets");
if (location.get().getCreator().getId() != loggedUser.getId())
throw new ApsiValidationException("Lokalizacja niedostępna", "location");
}
if (eventDTO.getTicketTypes().size() < 1)
throw new ApsiValidationException("Należy stworzyć przynajmniej jeden typ biletów", "tickets");
if (eventDTO.getTicketTypes().size() > 16)
throw new ApsiValidationException("Można stworzyć maksymalnie 16 typów biletów", "tickets");
if (!eventDTO.getTicketTypes().stream().allMatch(x -> x.getName() != null && !x.getName().isEmpty() && x.getName().length() < 100))
throw new ApsiValidationException("Dla każdego typu biletów należy podać maksymalnie 100-znakową nazwę", "tickets");
}
@Override
public Optional<EventDTO> getEventById(Long id) {
return eventRepository.findById(id).map(DTOMapper::toDTO);
}
@Override
public PaginatedList<EventDTO> getEvents(LocalDate from, LocalDate to, int pageIndex) throws ApsiValidationException {
if (from == null)
throw new ApsiValidationException("Należy podać datę początkową", "from");
if (to == null)
throw new ApsiValidationException("Należy podać datę końcową", "to");
if (from.isAfter(to))
throw new ApsiValidationException("Data końcowa nie może być mniejsza niż początkowa", "to");
if (pageIndex < 0)
throw new ApsiValidationException("Indeks strony nie może być ujemny", "pageIndex");
var page = eventRepository.getEventsWithDatesBetween(PageRequest.of(pageIndex, PAGE_SIZE), from, to);
var items = page
.stream()
.map(DTOMapper::toDTO)
.collect(Collectors.toList());
return new PaginatedList<EventDTO>(items, pageIndex, page.getTotalElements(), page.getTotalPages());
}
@Override
public EventDTO create(EventDTO eventDTO, MultipartFile image) throws ApsiValidationException {
if (eventDTO.getId() != null)
throw new ApsiValidationException("Podano niedozwolony identyfikator wydarzenia", "id");
var loggedUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
validateEvent(eventDTO, loggedUser);
var entity = DTOMapper.toEntity(eventDTO);
entity.setOrganizer(loggedUser);
if (entity.getLocation() != null){
var loc = locationRepository.findById(entity.getLocation().getId()).get();
entity.setLocation(loc);
}
byte[] bytes = null;
if (image != null) {
try{
bytes = image.getBytes();
}
catch (IOException e) {
e.printStackTrace();
throw new ApsiValidationException("Uszkodzony plik obrazu", "image");
}
}
var saved = eventRepository.save(entity);
if (!eventDTO.getTicketTypes().isEmpty()){
var entities = eventDTO.getTicketTypes().stream().map(e -> DTOMapper.toEntity(e, saved)).toList();
var savedTickets = ticketTypeRepository.saveAll(entities);
saved.setTicketTypes(savedTickets);
}
if (bytes != null){
var eventImage = EventImage.builder()
.image(bytes)
.event(saved)
.build();
eventImageRepository.save(eventImage);
saved.setImages(new ArrayList<>() {{ add(eventImage); }});
}
return DTOMapper.toDTO(saved);
}
@Override
public EventDTO replace(EventDTO eventDTO) throws ApsiValidationException {
var loggedUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
validateEvent(eventDTO, loggedUser);
var entity = DTOMapper.toEntity(eventDTO);
var saved = eventRepository.save(entity);
return DTOMapper.toDTO(saved);
}
@Override
public void delete(Long id) {
eventRepository.deleteById(id);
}
@Override
public boolean notExists(Long id) {
return !eventRepository.existsById(id);
}
@Override
public byte[] getImageByEventId(Long id) {
var images = eventImageRepository.findByEventId(id);
if (images.size() == 0)
return new byte[0];
// na razie spodziewamy się 1 obrazka per event
return images.get(0).getImage();
}
}
| APSI3/APSI | backend/src/main/java/apsi/team3/backend/services/EventService.java | 2,346 | // na razie spodziewamy się 1 obrazka per event | line_comment | pl | package apsi.team3.backend.services;
import apsi.team3.backend.DTOs.DTOMapper;
import apsi.team3.backend.DTOs.EventDTO;
import apsi.team3.backend.DTOs.PaginatedList;
import apsi.team3.backend.exceptions.ApsiValidationException;
import apsi.team3.backend.interfaces.IEventService;
import apsi.team3.backend.model.EventImage;
import apsi.team3.backend.model.User;
import apsi.team3.backend.repository.EventImageRepository;
import apsi.team3.backend.repository.EventRepository;
import apsi.team3.backend.repository.LocationRepository;
import apsi.team3.backend.repository.TicketTypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class EventService implements IEventService {
private final int PAGE_SIZE = 10;
private final LocationRepository locationRepository;
private final EventRepository eventRepository;
private final TicketTypeRepository ticketTypeRepository;
private final EventImageRepository eventImageRepository;
@Autowired
public EventService(
EventRepository eventRepository,
LocationRepository locationRepository,
TicketTypeRepository ticketTypeRepository,
EventImageRepository eventImageRepository
) {
this.eventRepository = eventRepository;
this.locationRepository = locationRepository;
this.ticketTypeRepository = ticketTypeRepository;
this.eventImageRepository = eventImageRepository;
}
private void validateEvent(EventDTO eventDTO, User loggedUser) throws ApsiValidationException {
if (eventDTO == null || eventDTO.getName() == null || eventDTO.getName().isBlank())
throw new ApsiValidationException("Należy podać nazwę wydarzenia", "name");
if (eventDTO.getName().length() > 255)
throw new ApsiValidationException("Zbyt długa nazwa wydarzenia", "name");
if (eventDTO.getDescription().length() > 2000)
throw new ApsiValidationException("Zbyt długi opis wydarzenia", "description");
if (eventDTO.getStartDate().isAfter(eventDTO.getEndDate()))
throw new ApsiValidationException("Data końcowa nie może być wcześniejsza niż data początkowa", "endDate");
if (eventDTO.getEndDate().isBefore(LocalDate.now()))
throw new ApsiValidationException("Data końcowa nie może być przeszła", "endDate");
if (eventDTO.getStartTime() != null && eventDTO.getEndTime() != null)
if (eventDTO.getStartDate().atTime(eventDTO.getStartTime()).isAfter(eventDTO.getEndDate().atTime(eventDTO.getEndTime())))
throw new ApsiValidationException("Data początkowa nie może być wcześniejsza niż data końcowa", "startDate");
if (eventDTO.getLocation() != null && eventDTO.getLocation().getId() != null) {
var location = locationRepository.findById(eventDTO.getLocation().getId());
if (location.isEmpty())
throw new ApsiValidationException("Wybrana lokacja nie istnieje", "location");
if (eventDTO.getTicketTypes().size() > 0 &&
location.get().getCapacity() != 0 &&
location.get().getCapacity() < eventDTO.getTicketTypes().stream().mapToInt(e -> e.getQuantityAvailable()).sum()
)
throw new ApsiValidationException("Ilość biletów większa niż dopuszczalna w danej lokalizacji", "tickets");
if (location.get().getCreator().getId() != loggedUser.getId())
throw new ApsiValidationException("Lokalizacja niedostępna", "location");
}
if (eventDTO.getTicketTypes().size() < 1)
throw new ApsiValidationException("Należy stworzyć przynajmniej jeden typ biletów", "tickets");
if (eventDTO.getTicketTypes().size() > 16)
throw new ApsiValidationException("Można stworzyć maksymalnie 16 typów biletów", "tickets");
if (!eventDTO.getTicketTypes().stream().allMatch(x -> x.getName() != null && !x.getName().isEmpty() && x.getName().length() < 100))
throw new ApsiValidationException("Dla każdego typu biletów należy podać maksymalnie 100-znakową nazwę", "tickets");
}
@Override
public Optional<EventDTO> getEventById(Long id) {
return eventRepository.findById(id).map(DTOMapper::toDTO);
}
@Override
public PaginatedList<EventDTO> getEvents(LocalDate from, LocalDate to, int pageIndex) throws ApsiValidationException {
if (from == null)
throw new ApsiValidationException("Należy podać datę początkową", "from");
if (to == null)
throw new ApsiValidationException("Należy podać datę końcową", "to");
if (from.isAfter(to))
throw new ApsiValidationException("Data końcowa nie może być mniejsza niż początkowa", "to");
if (pageIndex < 0)
throw new ApsiValidationException("Indeks strony nie może być ujemny", "pageIndex");
var page = eventRepository.getEventsWithDatesBetween(PageRequest.of(pageIndex, PAGE_SIZE), from, to);
var items = page
.stream()
.map(DTOMapper::toDTO)
.collect(Collectors.toList());
return new PaginatedList<EventDTO>(items, pageIndex, page.getTotalElements(), page.getTotalPages());
}
@Override
public EventDTO create(EventDTO eventDTO, MultipartFile image) throws ApsiValidationException {
if (eventDTO.getId() != null)
throw new ApsiValidationException("Podano niedozwolony identyfikator wydarzenia", "id");
var loggedUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
validateEvent(eventDTO, loggedUser);
var entity = DTOMapper.toEntity(eventDTO);
entity.setOrganizer(loggedUser);
if (entity.getLocation() != null){
var loc = locationRepository.findById(entity.getLocation().getId()).get();
entity.setLocation(loc);
}
byte[] bytes = null;
if (image != null) {
try{
bytes = image.getBytes();
}
catch (IOException e) {
e.printStackTrace();
throw new ApsiValidationException("Uszkodzony plik obrazu", "image");
}
}
var saved = eventRepository.save(entity);
if (!eventDTO.getTicketTypes().isEmpty()){
var entities = eventDTO.getTicketTypes().stream().map(e -> DTOMapper.toEntity(e, saved)).toList();
var savedTickets = ticketTypeRepository.saveAll(entities);
saved.setTicketTypes(savedTickets);
}
if (bytes != null){
var eventImage = EventImage.builder()
.image(bytes)
.event(saved)
.build();
eventImageRepository.save(eventImage);
saved.setImages(new ArrayList<>() {{ add(eventImage); }});
}
return DTOMapper.toDTO(saved);
}
@Override
public EventDTO replace(EventDTO eventDTO) throws ApsiValidationException {
var loggedUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
validateEvent(eventDTO, loggedUser);
var entity = DTOMapper.toEntity(eventDTO);
var saved = eventRepository.save(entity);
return DTOMapper.toDTO(saved);
}
@Override
public void delete(Long id) {
eventRepository.deleteById(id);
}
@Override
public boolean notExists(Long id) {
return !eventRepository.existsById(id);
}
@Override
public byte[] getImageByEventId(Long id) {
var images = eventImageRepository.findByEventId(id);
if (images.size() == 0)
return new byte[0];
// na<SUF>
return images.get(0).getImage();
}
}
|
65201_0 | package refactoring.extractmethod;
public class CodeRefactored {
private class User {
private String firstName;
private String lastName;
private double saldo;
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public double getSaldo() {
return saldo;
}
}
public void printUser(User user) {
// coś z tym userem robimy
// kilka instrukcji
printUserDetails(user);
}
private void printUserDetails(User user) {
printUserName(user);
printUserSaldo(user);
}
private void printUserName(User user) {
System.out.println("Imię i nazwisko:");
System.out.println(user.getFirstName() + " " + user.getLastName());
}
private void printUserSaldo(User user) {
System.out.println("Saldo");
System.out.println(user.getSaldo());
}
}
| ARPJavaPL1/DesignPatterns | src/main/java/refactoring/extractmethod/CodeRefactored.java | 277 | // coś z tym userem robimy | line_comment | pl | package refactoring.extractmethod;
public class CodeRefactored {
private class User {
private String firstName;
private String lastName;
private double saldo;
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public double getSaldo() {
return saldo;
}
}
public void printUser(User user) {
// co<SUF>
// kilka instrukcji
printUserDetails(user);
}
private void printUserDetails(User user) {
printUserName(user);
printUserSaldo(user);
}
private void printUserName(User user) {
System.out.println("Imię i nazwisko:");
System.out.println(user.getFirstName() + " " + user.getLastName());
}
private void printUserSaldo(User user) {
System.out.println("Saldo");
System.out.println(user.getSaldo());
}
}
|
38601_21 | package com.example.anamariapaula.myastroweather;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.app.FragmentTransaction;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.astrocalculator.AstroCalculator;
import com.astrocalculator.AstroDateTime;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutionException;
import data.FetchWeatherData;
import model.KnownLocations;
import model.Location;
import model.Weather;
import utility.DefaultValue;
//AppCompatActivity
public class AstroWeather extends AppCompatActivity implements ViewPager.OnPageChangeListener{
private int minutesFrequency;
private int hoursFrequency;
private int lastRefreshedMinutes = 0;
private int lastRefreshedHours = 0;
boolean isAvailableInternetConnection;
Timer rTimer;
Timer cTimer;
double longitude = 0;
double latitude = 0;
ViewPager pager;
AstroDateTime current_time = new AstroDateTime();
AstroCalculator calculator;
Calendar calendar;
Calendar newRefresh;
Bundle bundle;
MyAdapter adapter;
FragmentSun firstFragment;
FragmentMoon secondFragment;
FragmentBasicInformations thirdFragment;
FragmentAdditionalInformation fourthFragment;
FragmentWeatherForecast fifthFragment;
DBHandler dbHandler;
SharedPreferences prefs;
private final String PREFS_NAME = "mySharedPreferences";
WeatherInformation weatherInformation;
long currTime = System.currentTimeMillis();
long updateTimeFromFile = 0;
float refresh = 15f;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
isAvailableInternetConnection = Utils.isOnline(this);
dbHandler = new DBHandler(this);
setContentView(R.layout.activity_astro_weather);
try {
File file = getBaseContext().getFileStreamPath("updateTime");
if(!file.exists()){//jeśli nie ma, to stworz
Log.d("XXXXXXXXXXXXXX", "NIE Znalazl pliku");
FileOutputStream outputStream;
outputStream = this.openFileOutput("updateTime", Context.MODE_PRIVATE);
outputStream.write(String.valueOf(currTime).getBytes());
outputStream.close();
}
Log.d("XXXXXXXXXXXXXX", "Znalazl plik");
FileInputStream fileInputStream = this.openFileInput("updateTime");
StringBuilder stringBuilder = new StringBuilder();
int ch;
while ((ch = fileInputStream.read()) != -1) {
stringBuilder.append((char) ch);
}
updateTimeFromFile = Long.parseLong(stringBuilder.toString());
}
catch (Exception e){
Log.d("XXXXXXXXXXXXXX", "Jestesmy w catchu");
}
long time = (currTime - updateTimeFromFile)/60000;
Log.d("XXXXXXXXXXXXXX", "TIME:" + String.valueOf(time));
//sprawdzenie dostępu do internetu
if(isConnected() && (time > 15 || time == 0)) { //źle sie dzieje
//internetConnection = true;
Toast toast = Toast.makeText(getApplicationContext(),"Aktualizowanie danych", Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER,0,0);
toast.show();
new SaveDataAsyncTask(this).execute();
}
else if(isConnected()){
Toast toast = Toast.makeText(getApplicationContext(),"Dane aktualne", Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER,0,0);
toast.show();
}
/*else {
//internetConnection = false;
Toast toast = Toast.makeText(getApplicationContext(),"Brak połączenia z internetem. Dane mogą być nieaktualne.", Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER,0,0);
toast.show();
}*/
bundle = getIntent().getExtras();
longitude = Double.parseDouble(bundle.getString("longitude"));
latitude = Double.parseDouble(bundle.getString("latitude"));
minutesFrequency = Integer.parseInt(bundle.getString("updateTimeMinutes"));
hoursFrequency = Integer.parseInt(bundle.getString("updateTimeHours"));
TextView text_long = (TextView) findViewById(R.id.longitude_view);
TextView text_lat = (TextView) findViewById(R.id.latitude_view);
text_long.setText(Double.toString(longitude));
text_lat.setText(Double.toString(latitude));
viewInitialize();
initializeAllClocks();
}
private void initializeAllClocks() {
calendar = Calendar.getInstance();
startClock();
refreshTimer();
current_time = getCurrentTime();
getSunInfo();
lastRefreshedMinutes = calendar.MINUTE;
lastRefreshedHours = calendar.HOUR;
newRefresh = Calendar.getInstance();
newRefresh.add(Calendar.HOUR, hoursFrequency);
newRefresh.add(Calendar.MINUTE, minutesFrequency);
}
private void viewInitialize() {
if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {
viewPagerInitialize();
}
else {
if (findViewById(R.id.fragment_container_sun) != null) {
firstFragment = new FragmentSun();
firstFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container_sun, firstFragment).commit();
}
if (findViewById(R.id.fragment_container_moon) != null) {
secondFragment = new FragmentMoon();
secondFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container_moon, secondFragment).commit();
}
if (findViewById(R.id.fragment_container_basic) != null) {
thirdFragment = new FragmentBasicInformations();
thirdFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container_basic, thirdFragment).commit();
}
if (findViewById(R.id.fragment_container_additional) != null) {
fourthFragment = new FragmentAdditionalInformation();
fourthFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container_additional, fourthFragment).commit();
}
if (findViewById(R.id.fragment_container_forecast) != null) {
fifthFragment = new FragmentWeatherForecast();
fifthFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container_forecast, fifthFragment).commit();
}
}
}
private void viewPagerInitialize() {
pager = (ViewPager) findViewById(R.id.view_pager);
adapter = new MyAdapter(getSupportFragmentManager());
pager.addOnPageChangeListener(this);
adapter.setIsNeedToUpdate(true);
}
@Override
protected void onResume() {
super.onResume();
long time = (currTime - updateTimeFromFile)/60000;
Log.d("XXXXXXXXXXXXXX", "TIME:" + String.valueOf(time));
//sprawdzenie dostępu do internetu
if(isAvailableInternetConnection) {
new SaveDataAsyncTask(this).execute();
}
SharedPreferences sharedpreferences = getSharedPreferences("ShPe", Context.MODE_PRIVATE);
refresh = sharedpreferences.getFloat("czas", 15.0f);
getCurrentTime();
initializeDataForForecast();
viewPagerInitialize();
initializeAllClocks();
}
public AstroDateTime getCurrentTime() {
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1; //index starts from 0
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
return new AstroDateTime(year, month, day, hour, minute, second, 0, false);
}
private void startClock() {
cTimer = new Timer();
cTimer.scheduleAtFixedRate(
new java.util.TimerTask() {
@Override
public void run() {
// final String time = tempCalendar.getTime().getSeconds();
runOnUiThread(new Runnable() {
@Override
public void run() {
Calendar tempCalendar = Calendar.getInstance();
String time = String.format("%02d:%02d:%02d", tempCalendar.getTime().getHours(), tempCalendar.getTime().getMinutes(), tempCalendar.getTime().getSeconds());
TextView textViewTime = (TextView) findViewById(R.id.textClock);
textViewTime.setText(time);
}
});
}
},0 , 1000 //1 sekunda = 1000ms
);
}
private void refreshTimer() {
rTimer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
calendar = Calendar.getInstance();
if (isAvailableInternetConnection) {
Toast.makeText(getBaseContext(), "Refreshed", Toast.LENGTH_SHORT).show();
}
if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {
pager.setAdapter(adapter);
} else {
firstFragment.newInstance("Fragment Sun", true);
refreshSunFragment();
refreshMoonFragment();
}
}
});
}
};
int milis = (hoursFrequency * 60 + minutesFrequency) * 60 * 1000;
rTimer.scheduleAtFixedRate(task, 0, milis);
}
private void refreshSunFragment() {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container_sun, firstFragment.newInstance("", true));
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
private void refreshMoonFragment() {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container_moon, secondFragment.newInstance("Moon Fragment", true));
// Commit the transaction
transaction.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
super.onCreateOptionsMenu(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
cTimer.cancel();
rTimer.cancel();
if(item.getItemId() == R.id.action_location) {
Intent intent = new Intent(AstroWeather.this, MainActivity.class);
intent.putExtra("longitude", Double.toString(longitude));
intent.putExtra("latitude", Double.toString(latitude));
intent.putExtra("updateTimeMinutes", Integer.toString(minutesFrequency));
intent.putExtra("updateTimeHours", Integer.toString(hoursFrequency));
startActivity(intent);
} else if(item.getItemId() == R.id.action_frequency) {
Intent intent = new Intent(AstroWeather.this, Settings.class);
intent.putExtra("longitude", Double.toString(longitude));
intent.putExtra("latitude", Double.toString(latitude));
intent.putExtra("updateTimeMinutes", Integer.toString(minutesFrequency));
intent.putExtra("updateTimeHours", Integer.toString(hoursFrequency));
startActivity(intent);
} else if(item.getItemId() == R.id.action_exit) {
finishAffinity();
} else if (item.getItemId() == R.id.action_locations) {
Intent intent = new Intent(AstroWeather.this, FavouritesLocationsActivity.class);
startActivity(intent);
} else if (item.getItemId() == R.id.action_refresh_weather) {
if (Utils.isOnline(this)) {
onlineInitialize();
Toast.makeText(this, "Weather refreshed.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "No internet connection.", Toast.LENGTH_SHORT).show();
}
}
return super.onOptionsItemSelected(item);
}
@Override
public void onPageSelected(int position) {
switch (position){
case 0:
pager.setCurrentItem(0);
break;
case 1:
pager.setCurrentItem(1);
break;
case 2:
pager.setCurrentItem(2);
break;
case 3:
pager.setCurrentItem(3);
break;
case 4:
pager.setCurrentItem(4);
break;
default:
pager.setCurrentItem(0);
break;
}
}
@Override
public void onPageScrolled(int position, float v, int i) {
}
@Override
public void onPageScrollStateChanged(int position) {
}
public void getSunInfo() {
calculator = new AstroCalculator(current_time, new AstroCalculator.Location(latitude, longitude));
calculator.getSunInfo();
calculator.getSunInfo().getSunrise();
calculator.getSunInfo().getSunrise().toString();
}
public void setMinutesFrequency(int in){
if (in >= 0 && in < 60) {
minutesFrequency = in;
}
}
public boolean isConnected() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); //jakiś problem z tą linijką kodu (klasa Connectivity Manager jest cała w errorach)
if(activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
return true;
}
else return false;
}
private void initializeDataForForecast() {
prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
//TODO przy braku połączenia robi się bzdura
if (Utils.isOnline(this)) { //Online
onlineInitialize();
} else { //Offline
offlineInitialize();
}
//TODO Tutaj skończyłem, kontynuować odtąd
}
private void onlineInitialize() {
JSONObject jsonObject = Utils.getJsonFromWOEID(prefs.getInt("woeid", 0), prefs.getBoolean("metrics", true));
Utils.writeJSONObjectToFile(this, jsonObject, prefs.getInt("woeid", 0));
JSONObject jsonObject1 = Utils.getJsonFromFile(this, prefs.getInt("woeid", 0));
weatherInformation = Utils.getAllInformations(jsonObject1);
}
private void offlineInitialize() {
if (isDataFileExists()) { //Czy istnieje plik z danymi
/*if (Utils.isNeedToBeRefreshed(this, Integer.toString(prefs.getInt("woeid", 0)))) {
Utils.readAllData(); //TODO bez sprawdzania czy dane wymag. aktualizacji
}*/
Utils.readAllData(); //TODO DOKOŃCZYĆ !!!!!!!!!!!!!!MOTHERFUCKA!!!!!!!!!!!
} else {
Toast.makeText( this.getApplicationContext(), "No available internete connection. No data to be displayed.", Toast.LENGTH_LONG).show();
}
JSONObject jsonObject1 = Utils.getJsonFromFile(this, prefs.getInt("woeid", 0));
weatherInformation = Utils.getAllInformations(jsonObject1);
}
// private WeatherInformation loadAllInfo() {
//
// }
private boolean isDataFileExists() {
return Utils.isDataFileExists(Integer.toString(prefs.getInt("woeid", 0)));
}
private void initializeWeatherData()
{
if (isOnline(this))
{
initializeOnlineWeather();
}
else
{
noInternetConnectionInfo();
initializeOfflineWeather();
}
initializeOfflineWeather();
}
public static boolean isOnline(Context context)
{
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnectedOrConnecting();
}
private void initializeOnlineWeather()
{
FetchWeatherData fetchWeatherData = new FetchWeatherData();
DefaultValue defaultValue = new DefaultValue();
fetchWeatherData.execute(defaultValue.system + "", defaultValue.selectedLocation.getCity().toString(), defaultValue.selectedLocation.getCountry().toString());
try
{
DefaultValue.weather = fetchWeatherData.get();
saveWeather(DefaultValue.weather);
saveLocations(DefaultValue.locations);
}
catch (ExecutionException | InterruptedException e)
{
e.printStackTrace();
}
Toast.makeText(this, R.string.updateData, Toast.LENGTH_SHORT).show();
saveWeather(DefaultValue.weather);
saveLocations(DefaultValue.locations);
}
private void saveWeather(Weather weather)
{
FileOutputStream fileOutputStream = null;
try {
File file = new File(getCacheDir() + File.separator + R.string.weatherFile);
if (file.exists())
{
file.delete();
}
file.createNewFile();
fileOutputStream = new FileOutputStream(file);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(weather);
objectOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
private void saveLocations(KnownLocations knownLocations)
{
FileOutputStream fileOutputStream = null;
try
{
File file = new File(getCacheDir() + File.separator + getResources().getString(R.string.weatherFile)); //źle
if (file.exists())
{
file.delete();
}
file.createNewFile();
fileOutputStream = new FileOutputStream(file);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(knownLocations);
objectOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
private void noInternetConnectionInfo()
{
new AlertDialog.Builder(this)
.setTitle("Tryb Offline")
.setMessage("Brak połączenia z Internetem!")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), R.string.noWeatherInfo, Toast.LENGTH_LONG).show();
}
})
.show();
}
private void initializeOfflineWeather()
{
DefaultValue.locations = loadLocations();
DefaultValue.weather = loadWeather();
}
private KnownLocations loadLocations()
{
FileInputStream fileInputStream = null;
KnownLocations knownLocations = new KnownLocations();
try
{
File file = new File(getCacheDir() + File.separator + R.string.locationsFile);
if (file.exists())
{
fileInputStream = new FileInputStream(file);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
knownLocations = (KnownLocations) objectInputStream.readObject();
objectInputStream.close();
}
}
catch (ClassNotFoundException | IOException e)
{
e.printStackTrace();
}
if (knownLocations.getLocationList().size() <= 0)
{
knownLocations = new KnownLocations();
knownLocations.addLocation(new Location("lodz", "pl"));
}
return knownLocations;
}
private Weather loadWeather()
{
FileInputStream fileInputStream = null;
Weather weather = null;
try
{
File file = new File(getCacheDir() + File.separator + R.string.weatherFile);
if (file.exists())
{
fileInputStream = new FileInputStream(file);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
weather = (Weather) objectInputStream.readObject();
objectInputStream.close();
}
}
catch (ClassNotFoundException | IOException e)
{
e.printStackTrace();
}
return weather;
}
}
| AVladyslav/MyAstroWeather | app/src/main/java/com/example/anamariapaula/myastroweather/AstroWeather.java | 6,046 | //TODO Tutaj skończyłem, kontynuować odtąd | line_comment | pl | package com.example.anamariapaula.myastroweather;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.app.FragmentTransaction;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.astrocalculator.AstroCalculator;
import com.astrocalculator.AstroDateTime;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutionException;
import data.FetchWeatherData;
import model.KnownLocations;
import model.Location;
import model.Weather;
import utility.DefaultValue;
//AppCompatActivity
public class AstroWeather extends AppCompatActivity implements ViewPager.OnPageChangeListener{
private int minutesFrequency;
private int hoursFrequency;
private int lastRefreshedMinutes = 0;
private int lastRefreshedHours = 0;
boolean isAvailableInternetConnection;
Timer rTimer;
Timer cTimer;
double longitude = 0;
double latitude = 0;
ViewPager pager;
AstroDateTime current_time = new AstroDateTime();
AstroCalculator calculator;
Calendar calendar;
Calendar newRefresh;
Bundle bundle;
MyAdapter adapter;
FragmentSun firstFragment;
FragmentMoon secondFragment;
FragmentBasicInformations thirdFragment;
FragmentAdditionalInformation fourthFragment;
FragmentWeatherForecast fifthFragment;
DBHandler dbHandler;
SharedPreferences prefs;
private final String PREFS_NAME = "mySharedPreferences";
WeatherInformation weatherInformation;
long currTime = System.currentTimeMillis();
long updateTimeFromFile = 0;
float refresh = 15f;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
isAvailableInternetConnection = Utils.isOnline(this);
dbHandler = new DBHandler(this);
setContentView(R.layout.activity_astro_weather);
try {
File file = getBaseContext().getFileStreamPath("updateTime");
if(!file.exists()){//jeśli nie ma, to stworz
Log.d("XXXXXXXXXXXXXX", "NIE Znalazl pliku");
FileOutputStream outputStream;
outputStream = this.openFileOutput("updateTime", Context.MODE_PRIVATE);
outputStream.write(String.valueOf(currTime).getBytes());
outputStream.close();
}
Log.d("XXXXXXXXXXXXXX", "Znalazl plik");
FileInputStream fileInputStream = this.openFileInput("updateTime");
StringBuilder stringBuilder = new StringBuilder();
int ch;
while ((ch = fileInputStream.read()) != -1) {
stringBuilder.append((char) ch);
}
updateTimeFromFile = Long.parseLong(stringBuilder.toString());
}
catch (Exception e){
Log.d("XXXXXXXXXXXXXX", "Jestesmy w catchu");
}
long time = (currTime - updateTimeFromFile)/60000;
Log.d("XXXXXXXXXXXXXX", "TIME:" + String.valueOf(time));
//sprawdzenie dostępu do internetu
if(isConnected() && (time > 15 || time == 0)) { //źle sie dzieje
//internetConnection = true;
Toast toast = Toast.makeText(getApplicationContext(),"Aktualizowanie danych", Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER,0,0);
toast.show();
new SaveDataAsyncTask(this).execute();
}
else if(isConnected()){
Toast toast = Toast.makeText(getApplicationContext(),"Dane aktualne", Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER,0,0);
toast.show();
}
/*else {
//internetConnection = false;
Toast toast = Toast.makeText(getApplicationContext(),"Brak połączenia z internetem. Dane mogą być nieaktualne.", Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER,0,0);
toast.show();
}*/
bundle = getIntent().getExtras();
longitude = Double.parseDouble(bundle.getString("longitude"));
latitude = Double.parseDouble(bundle.getString("latitude"));
minutesFrequency = Integer.parseInt(bundle.getString("updateTimeMinutes"));
hoursFrequency = Integer.parseInt(bundle.getString("updateTimeHours"));
TextView text_long = (TextView) findViewById(R.id.longitude_view);
TextView text_lat = (TextView) findViewById(R.id.latitude_view);
text_long.setText(Double.toString(longitude));
text_lat.setText(Double.toString(latitude));
viewInitialize();
initializeAllClocks();
}
private void initializeAllClocks() {
calendar = Calendar.getInstance();
startClock();
refreshTimer();
current_time = getCurrentTime();
getSunInfo();
lastRefreshedMinutes = calendar.MINUTE;
lastRefreshedHours = calendar.HOUR;
newRefresh = Calendar.getInstance();
newRefresh.add(Calendar.HOUR, hoursFrequency);
newRefresh.add(Calendar.MINUTE, minutesFrequency);
}
private void viewInitialize() {
if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {
viewPagerInitialize();
}
else {
if (findViewById(R.id.fragment_container_sun) != null) {
firstFragment = new FragmentSun();
firstFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container_sun, firstFragment).commit();
}
if (findViewById(R.id.fragment_container_moon) != null) {
secondFragment = new FragmentMoon();
secondFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container_moon, secondFragment).commit();
}
if (findViewById(R.id.fragment_container_basic) != null) {
thirdFragment = new FragmentBasicInformations();
thirdFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container_basic, thirdFragment).commit();
}
if (findViewById(R.id.fragment_container_additional) != null) {
fourthFragment = new FragmentAdditionalInformation();
fourthFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container_additional, fourthFragment).commit();
}
if (findViewById(R.id.fragment_container_forecast) != null) {
fifthFragment = new FragmentWeatherForecast();
fifthFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container_forecast, fifthFragment).commit();
}
}
}
private void viewPagerInitialize() {
pager = (ViewPager) findViewById(R.id.view_pager);
adapter = new MyAdapter(getSupportFragmentManager());
pager.addOnPageChangeListener(this);
adapter.setIsNeedToUpdate(true);
}
@Override
protected void onResume() {
super.onResume();
long time = (currTime - updateTimeFromFile)/60000;
Log.d("XXXXXXXXXXXXXX", "TIME:" + String.valueOf(time));
//sprawdzenie dostępu do internetu
if(isAvailableInternetConnection) {
new SaveDataAsyncTask(this).execute();
}
SharedPreferences sharedpreferences = getSharedPreferences("ShPe", Context.MODE_PRIVATE);
refresh = sharedpreferences.getFloat("czas", 15.0f);
getCurrentTime();
initializeDataForForecast();
viewPagerInitialize();
initializeAllClocks();
}
public AstroDateTime getCurrentTime() {
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1; //index starts from 0
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
return new AstroDateTime(year, month, day, hour, minute, second, 0, false);
}
private void startClock() {
cTimer = new Timer();
cTimer.scheduleAtFixedRate(
new java.util.TimerTask() {
@Override
public void run() {
// final String time = tempCalendar.getTime().getSeconds();
runOnUiThread(new Runnable() {
@Override
public void run() {
Calendar tempCalendar = Calendar.getInstance();
String time = String.format("%02d:%02d:%02d", tempCalendar.getTime().getHours(), tempCalendar.getTime().getMinutes(), tempCalendar.getTime().getSeconds());
TextView textViewTime = (TextView) findViewById(R.id.textClock);
textViewTime.setText(time);
}
});
}
},0 , 1000 //1 sekunda = 1000ms
);
}
private void refreshTimer() {
rTimer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
calendar = Calendar.getInstance();
if (isAvailableInternetConnection) {
Toast.makeText(getBaseContext(), "Refreshed", Toast.LENGTH_SHORT).show();
}
if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {
pager.setAdapter(adapter);
} else {
firstFragment.newInstance("Fragment Sun", true);
refreshSunFragment();
refreshMoonFragment();
}
}
});
}
};
int milis = (hoursFrequency * 60 + minutesFrequency) * 60 * 1000;
rTimer.scheduleAtFixedRate(task, 0, milis);
}
private void refreshSunFragment() {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container_sun, firstFragment.newInstance("", true));
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
private void refreshMoonFragment() {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container_moon, secondFragment.newInstance("Moon Fragment", true));
// Commit the transaction
transaction.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
super.onCreateOptionsMenu(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
cTimer.cancel();
rTimer.cancel();
if(item.getItemId() == R.id.action_location) {
Intent intent = new Intent(AstroWeather.this, MainActivity.class);
intent.putExtra("longitude", Double.toString(longitude));
intent.putExtra("latitude", Double.toString(latitude));
intent.putExtra("updateTimeMinutes", Integer.toString(minutesFrequency));
intent.putExtra("updateTimeHours", Integer.toString(hoursFrequency));
startActivity(intent);
} else if(item.getItemId() == R.id.action_frequency) {
Intent intent = new Intent(AstroWeather.this, Settings.class);
intent.putExtra("longitude", Double.toString(longitude));
intent.putExtra("latitude", Double.toString(latitude));
intent.putExtra("updateTimeMinutes", Integer.toString(minutesFrequency));
intent.putExtra("updateTimeHours", Integer.toString(hoursFrequency));
startActivity(intent);
} else if(item.getItemId() == R.id.action_exit) {
finishAffinity();
} else if (item.getItemId() == R.id.action_locations) {
Intent intent = new Intent(AstroWeather.this, FavouritesLocationsActivity.class);
startActivity(intent);
} else if (item.getItemId() == R.id.action_refresh_weather) {
if (Utils.isOnline(this)) {
onlineInitialize();
Toast.makeText(this, "Weather refreshed.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "No internet connection.", Toast.LENGTH_SHORT).show();
}
}
return super.onOptionsItemSelected(item);
}
@Override
public void onPageSelected(int position) {
switch (position){
case 0:
pager.setCurrentItem(0);
break;
case 1:
pager.setCurrentItem(1);
break;
case 2:
pager.setCurrentItem(2);
break;
case 3:
pager.setCurrentItem(3);
break;
case 4:
pager.setCurrentItem(4);
break;
default:
pager.setCurrentItem(0);
break;
}
}
@Override
public void onPageScrolled(int position, float v, int i) {
}
@Override
public void onPageScrollStateChanged(int position) {
}
public void getSunInfo() {
calculator = new AstroCalculator(current_time, new AstroCalculator.Location(latitude, longitude));
calculator.getSunInfo();
calculator.getSunInfo().getSunrise();
calculator.getSunInfo().getSunrise().toString();
}
public void setMinutesFrequency(int in){
if (in >= 0 && in < 60) {
minutesFrequency = in;
}
}
public boolean isConnected() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); //jakiś problem z tą linijką kodu (klasa Connectivity Manager jest cała w errorach)
if(activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
return true;
}
else return false;
}
private void initializeDataForForecast() {
prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
//TODO przy braku połączenia robi się bzdura
if (Utils.isOnline(this)) { //Online
onlineInitialize();
} else { //Offline
offlineInitialize();
}
//TO<SUF>
}
private void onlineInitialize() {
JSONObject jsonObject = Utils.getJsonFromWOEID(prefs.getInt("woeid", 0), prefs.getBoolean("metrics", true));
Utils.writeJSONObjectToFile(this, jsonObject, prefs.getInt("woeid", 0));
JSONObject jsonObject1 = Utils.getJsonFromFile(this, prefs.getInt("woeid", 0));
weatherInformation = Utils.getAllInformations(jsonObject1);
}
private void offlineInitialize() {
if (isDataFileExists()) { //Czy istnieje plik z danymi
/*if (Utils.isNeedToBeRefreshed(this, Integer.toString(prefs.getInt("woeid", 0)))) {
Utils.readAllData(); //TODO bez sprawdzania czy dane wymag. aktualizacji
}*/
Utils.readAllData(); //TODO DOKOŃCZYĆ !!!!!!!!!!!!!!MOTHERFUCKA!!!!!!!!!!!
} else {
Toast.makeText( this.getApplicationContext(), "No available internete connection. No data to be displayed.", Toast.LENGTH_LONG).show();
}
JSONObject jsonObject1 = Utils.getJsonFromFile(this, prefs.getInt("woeid", 0));
weatherInformation = Utils.getAllInformations(jsonObject1);
}
// private WeatherInformation loadAllInfo() {
//
// }
private boolean isDataFileExists() {
return Utils.isDataFileExists(Integer.toString(prefs.getInt("woeid", 0)));
}
private void initializeWeatherData()
{
if (isOnline(this))
{
initializeOnlineWeather();
}
else
{
noInternetConnectionInfo();
initializeOfflineWeather();
}
initializeOfflineWeather();
}
public static boolean isOnline(Context context)
{
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnectedOrConnecting();
}
private void initializeOnlineWeather()
{
FetchWeatherData fetchWeatherData = new FetchWeatherData();
DefaultValue defaultValue = new DefaultValue();
fetchWeatherData.execute(defaultValue.system + "", defaultValue.selectedLocation.getCity().toString(), defaultValue.selectedLocation.getCountry().toString());
try
{
DefaultValue.weather = fetchWeatherData.get();
saveWeather(DefaultValue.weather);
saveLocations(DefaultValue.locations);
}
catch (ExecutionException | InterruptedException e)
{
e.printStackTrace();
}
Toast.makeText(this, R.string.updateData, Toast.LENGTH_SHORT).show();
saveWeather(DefaultValue.weather);
saveLocations(DefaultValue.locations);
}
private void saveWeather(Weather weather)
{
FileOutputStream fileOutputStream = null;
try {
File file = new File(getCacheDir() + File.separator + R.string.weatherFile);
if (file.exists())
{
file.delete();
}
file.createNewFile();
fileOutputStream = new FileOutputStream(file);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(weather);
objectOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
private void saveLocations(KnownLocations knownLocations)
{
FileOutputStream fileOutputStream = null;
try
{
File file = new File(getCacheDir() + File.separator + getResources().getString(R.string.weatherFile)); //źle
if (file.exists())
{
file.delete();
}
file.createNewFile();
fileOutputStream = new FileOutputStream(file);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(knownLocations);
objectOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
private void noInternetConnectionInfo()
{
new AlertDialog.Builder(this)
.setTitle("Tryb Offline")
.setMessage("Brak połączenia z Internetem!")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), R.string.noWeatherInfo, Toast.LENGTH_LONG).show();
}
})
.show();
}
private void initializeOfflineWeather()
{
DefaultValue.locations = loadLocations();
DefaultValue.weather = loadWeather();
}
private KnownLocations loadLocations()
{
FileInputStream fileInputStream = null;
KnownLocations knownLocations = new KnownLocations();
try
{
File file = new File(getCacheDir() + File.separator + R.string.locationsFile);
if (file.exists())
{
fileInputStream = new FileInputStream(file);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
knownLocations = (KnownLocations) objectInputStream.readObject();
objectInputStream.close();
}
}
catch (ClassNotFoundException | IOException e)
{
e.printStackTrace();
}
if (knownLocations.getLocationList().size() <= 0)
{
knownLocations = new KnownLocations();
knownLocations.addLocation(new Location("lodz", "pl"));
}
return knownLocations;
}
private Weather loadWeather()
{
FileInputStream fileInputStream = null;
Weather weather = null;
try
{
File file = new File(getCacheDir() + File.separator + R.string.weatherFile);
if (file.exists())
{
fileInputStream = new FileInputStream(file);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
weather = (Weather) objectInputStream.readObject();
objectInputStream.close();
}
}
catch (ClassNotFoundException | IOException e)
{
e.printStackTrace();
}
return weather;
}
}
|
22531_17 | package s;
public class DSP {
/**
* QDSS Windowed Sinc ReSampling subroutine in Basic
*
* @param x
* new sample point location (relative to old indexes) (e.g. every
* other integer for 0.5x decimation)
* @param indat
* = original data array
* @param alim
* = size of data array
* @param fmax
* = low pass filter cutoff frequency
* @param fsr
* = sample rate
* @param wnwdth
* = width of windowed Sinc used as the low pass filter rem resamp()
* returns a filtered new sample point
*/
public float resamp(float x, float[] indat, int alim, float fmax,
float fsr, int wnwdth) {
int i, j;
float r_w, r_g, r_a;
int r_snc, r_y; // some local variables
r_g = 2 * fmax / fsr; // Calc gain correction factor
r_y = 0;
for (i = -wnwdth / 2; i < wnwdth / 2; i++) { // For 1 window width
j = (int) (x + i); // Calc input sample index
// calculate von Hann Window. Scale and calculate Sinc
r_w =
(float) (0.5 - 0.5 * Math.cos(2 * Math.PI
* (0.5 + (j - x) / wnwdth)));
r_a = (float) (2 * Math.PI * (j - x) * fmax / fsr);
r_snc = 1;
if (Math.abs(r_a) > 0)
r_snc = (int) (Math.sin(r_a) / r_a);
if ((j >= 0) && (j < alim)) {
r_y = (int) (r_y + r_g * r_w * r_snc * indat[j]);
}
}
return r_y; // return new filtered sample
}
/*
* Ron Nicholson's QDSS ReSampler cookbook recipe QDSS = Quick, Dirty,
* Simple and Short Version 0.1b - 2007-Aug-01 Copyright 2007 Ronald H.
* Nicholson Jr. No warranties implied. Error checking, optimization, and
* quality assessment of the "results" is left as an exercise for the
* student. (consider this code Open Source under a BSD style license) IMHO.
* YMMV. http://www.nicholson.com/rhn/dsp.html
*/
/**
* R. Nicholson's QDDS FIR filter generator cookbook recipe QDDS = Quick,
* Dirty, Dumb and Short version 0.6b - 2006-Dec-14, 2007-Sep-30 No
* warranties implied. Error checking, optimization, and quality assessment
* of the "results" is left as an exercise for the student. (consider this
* code Open Source under a BSD style license) Some example filter
* parameters:
*
* @param fsr
* = 44100 : rem set fsr = sample rate
* @param fc
* = 0 : rem set fc = 0 for lowpass fc = center frequency for
* bandpass filter fc = fsr/2 for a highpass
* @param bw
* = 3000 : rem bw = bandwidth, range 0 .. fsr/2 and bw >= fsr/n bw =
* 3 db corner frequency for a lowpass bw = half the 3 db passband
* for a bandpass filter
* @param nt
* = 128 : rem nt = number of taps + 1 (nt must be even) nt should be
* > fsr / bw transition band will be around 3.5 * fsr / nt depending
* on the window applied and ripple spec.
* @param g
* = 1 : rem g = filter gain for bandpass g = 0.5 , half the gain for
* a lowpass filter
* @return array of FIR taps
*/
public static double[] wsfiltgen(int nt, double fc, double fsr, double bw, double g) {
double[] fir = new double[nt];//
// fir(0) = 0
// fir(1) is the first tap
// fir(nt/2) is the middle tap
// fir(nt-1) is the last tap
double a, ys, yg, yf, yw;
for (int i = 1; i < nt; i++) {
a = (i - nt / 2) * 2.0 * Math.PI * bw / fsr; // scale Sinc width
ys = 1;
if (Math.abs(a) > 0)
ys = Math.sin(a) / a; // calculate Sinc function
yg = g * (4.0 * bw / fsr); // correct window gain
yw = 0.54 - 0.46 * Math.cos(i * 2.0 * Math.PI / nt); // Hamming
// window
yf = Math.cos((i - nt / 2) * 2.0 * Math.PI * fc / fsr); // spectral
// shift to
// fc
fir[i] = yf * yw * yg * ys; // rem assign fir coeff.
}
return fir;
}
public static void main(String[] argv){
double[] fir=wsfiltgen(128,11025/2.0,22050,22050*3.0/4,0.5);
System.out.println(fir);
}
public static byte[] crudeResample(byte[] input,int factor){
if (input==null || input.length<1) return null;
final int LEN=input.length;
byte[] res=new byte[LEN*factor];
int k=0;
float start,end;
res[0]=input[0];
for (int i=0;i<LEN;i++){
if (i==0)
start=127;
else
start=0xFF&input[i];
if (i<LEN-1)
end=0xFF&input[i+1];
else
end=127;
double slope=(end-start)/factor;
res[k]=input[i];
//res[k+factor]=input[i+1];
for (int j=1;j<factor;j++){
double ratio=j/(double)factor;
double value=start+slope*ratio;
byte bval=(byte)Math.round(value);
res[k+j]=bval;
}
k+=factor;
}
return res;
}
public static void filter(byte[] input,int samplerate, int cutoff){
double[] tmp=new double[input.length];
// Normalize
for (int i=0;i<input.length;i++){
tmp[i]=(0xFF&input[i])/255.0;
}
filter(tmp,samplerate,cutoff,tmp.length);
// De-normalize
for (int i=0;i<input.length;i++){
input[i]=(byte) (0xFF&(int)(tmp[i]*255.0));
}
}
/** Taken from here
* http://baumdevblog.blogspot.gr/2010/11/butterworth-lowpass-filter-coefficients.html
*/
private static void getLPCoefficientsButterworth2Pole(final int samplerate, final double cutoff, final double[] ax, final double[] by)
{
double PI = 3.1415926535897932385;
double sqrt2 = 1.4142135623730950488;
double QcRaw = (2 * PI * cutoff) / samplerate; // Find cutoff frequency in [0..PI]
double QcWarp = Math.tan(QcRaw); // Warp cutoff frequency
double gain = 1 / (1+sqrt2/QcWarp + 2/(QcWarp*QcWarp));
by[2] = (1 - sqrt2/QcWarp + 2/(QcWarp*QcWarp)) * gain;
by[1] = (2 - 2 * 2/(QcWarp*QcWarp)) * gain;
by[0] = 1;
ax[0] = 1 * gain;
ax[1] = 2 * gain;
ax[2] = 1 * gain;
}
public static void filter(double[] samples, int smp, double cutoff,int count)
{
// Essentially a 3-tap filter?
double[] ax=new double[3];
double[] by=new double[3];
double[] xv=new double[3];
double[] yv=new double[3];
getLPCoefficientsButterworth2Pole(smp, cutoff, ax, by);
for (int i=0;i<count;i++)
{
xv[2] = xv[1];
xv[1] = xv[0];
xv[0] = samples[i];
yv[2] = yv[1];
yv[1] = yv[0];
yv[0] = (ax[0] * xv[0] + ax[1] * xv[1] + ax[2] * xv[2]
- by[1] * yv[0]
- by[2] * yv[1]);
samples[i] = yv[0];
}
}
}
| AXDOOMER/mochadoom | src/s/DSP.java | 2,693 | // window | line_comment | pl | package s;
public class DSP {
/**
* QDSS Windowed Sinc ReSampling subroutine in Basic
*
* @param x
* new sample point location (relative to old indexes) (e.g. every
* other integer for 0.5x decimation)
* @param indat
* = original data array
* @param alim
* = size of data array
* @param fmax
* = low pass filter cutoff frequency
* @param fsr
* = sample rate
* @param wnwdth
* = width of windowed Sinc used as the low pass filter rem resamp()
* returns a filtered new sample point
*/
public float resamp(float x, float[] indat, int alim, float fmax,
float fsr, int wnwdth) {
int i, j;
float r_w, r_g, r_a;
int r_snc, r_y; // some local variables
r_g = 2 * fmax / fsr; // Calc gain correction factor
r_y = 0;
for (i = -wnwdth / 2; i < wnwdth / 2; i++) { // For 1 window width
j = (int) (x + i); // Calc input sample index
// calculate von Hann Window. Scale and calculate Sinc
r_w =
(float) (0.5 - 0.5 * Math.cos(2 * Math.PI
* (0.5 + (j - x) / wnwdth)));
r_a = (float) (2 * Math.PI * (j - x) * fmax / fsr);
r_snc = 1;
if (Math.abs(r_a) > 0)
r_snc = (int) (Math.sin(r_a) / r_a);
if ((j >= 0) && (j < alim)) {
r_y = (int) (r_y + r_g * r_w * r_snc * indat[j]);
}
}
return r_y; // return new filtered sample
}
/*
* Ron Nicholson's QDSS ReSampler cookbook recipe QDSS = Quick, Dirty,
* Simple and Short Version 0.1b - 2007-Aug-01 Copyright 2007 Ronald H.
* Nicholson Jr. No warranties implied. Error checking, optimization, and
* quality assessment of the "results" is left as an exercise for the
* student. (consider this code Open Source under a BSD style license) IMHO.
* YMMV. http://www.nicholson.com/rhn/dsp.html
*/
/**
* R. Nicholson's QDDS FIR filter generator cookbook recipe QDDS = Quick,
* Dirty, Dumb and Short version 0.6b - 2006-Dec-14, 2007-Sep-30 No
* warranties implied. Error checking, optimization, and quality assessment
* of the "results" is left as an exercise for the student. (consider this
* code Open Source under a BSD style license) Some example filter
* parameters:
*
* @param fsr
* = 44100 : rem set fsr = sample rate
* @param fc
* = 0 : rem set fc = 0 for lowpass fc = center frequency for
* bandpass filter fc = fsr/2 for a highpass
* @param bw
* = 3000 : rem bw = bandwidth, range 0 .. fsr/2 and bw >= fsr/n bw =
* 3 db corner frequency for a lowpass bw = half the 3 db passband
* for a bandpass filter
* @param nt
* = 128 : rem nt = number of taps + 1 (nt must be even) nt should be
* > fsr / bw transition band will be around 3.5 * fsr / nt depending
* on the window applied and ripple spec.
* @param g
* = 1 : rem g = filter gain for bandpass g = 0.5 , half the gain for
* a lowpass filter
* @return array of FIR taps
*/
public static double[] wsfiltgen(int nt, double fc, double fsr, double bw, double g) {
double[] fir = new double[nt];//
// fir(0) = 0
// fir(1) is the first tap
// fir(nt/2) is the middle tap
// fir(nt-1) is the last tap
double a, ys, yg, yf, yw;
for (int i = 1; i < nt; i++) {
a = (i - nt / 2) * 2.0 * Math.PI * bw / fsr; // scale Sinc width
ys = 1;
if (Math.abs(a) > 0)
ys = Math.sin(a) / a; // calculate Sinc function
yg = g * (4.0 * bw / fsr); // correct window gain
yw = 0.54 - 0.46 * Math.cos(i * 2.0 * Math.PI / nt); // Hamming
// wi<SUF>
yf = Math.cos((i - nt / 2) * 2.0 * Math.PI * fc / fsr); // spectral
// shift to
// fc
fir[i] = yf * yw * yg * ys; // rem assign fir coeff.
}
return fir;
}
public static void main(String[] argv){
double[] fir=wsfiltgen(128,11025/2.0,22050,22050*3.0/4,0.5);
System.out.println(fir);
}
public static byte[] crudeResample(byte[] input,int factor){
if (input==null || input.length<1) return null;
final int LEN=input.length;
byte[] res=new byte[LEN*factor];
int k=0;
float start,end;
res[0]=input[0];
for (int i=0;i<LEN;i++){
if (i==0)
start=127;
else
start=0xFF&input[i];
if (i<LEN-1)
end=0xFF&input[i+1];
else
end=127;
double slope=(end-start)/factor;
res[k]=input[i];
//res[k+factor]=input[i+1];
for (int j=1;j<factor;j++){
double ratio=j/(double)factor;
double value=start+slope*ratio;
byte bval=(byte)Math.round(value);
res[k+j]=bval;
}
k+=factor;
}
return res;
}
public static void filter(byte[] input,int samplerate, int cutoff){
double[] tmp=new double[input.length];
// Normalize
for (int i=0;i<input.length;i++){
tmp[i]=(0xFF&input[i])/255.0;
}
filter(tmp,samplerate,cutoff,tmp.length);
// De-normalize
for (int i=0;i<input.length;i++){
input[i]=(byte) (0xFF&(int)(tmp[i]*255.0));
}
}
/** Taken from here
* http://baumdevblog.blogspot.gr/2010/11/butterworth-lowpass-filter-coefficients.html
*/
private static void getLPCoefficientsButterworth2Pole(final int samplerate, final double cutoff, final double[] ax, final double[] by)
{
double PI = 3.1415926535897932385;
double sqrt2 = 1.4142135623730950488;
double QcRaw = (2 * PI * cutoff) / samplerate; // Find cutoff frequency in [0..PI]
double QcWarp = Math.tan(QcRaw); // Warp cutoff frequency
double gain = 1 / (1+sqrt2/QcWarp + 2/(QcWarp*QcWarp));
by[2] = (1 - sqrt2/QcWarp + 2/(QcWarp*QcWarp)) * gain;
by[1] = (2 - 2 * 2/(QcWarp*QcWarp)) * gain;
by[0] = 1;
ax[0] = 1 * gain;
ax[1] = 2 * gain;
ax[2] = 1 * gain;
}
public static void filter(double[] samples, int smp, double cutoff,int count)
{
// Essentially a 3-tap filter?
double[] ax=new double[3];
double[] by=new double[3];
double[] xv=new double[3];
double[] yv=new double[3];
getLPCoefficientsButterworth2Pole(smp, cutoff, ax, by);
for (int i=0;i<count;i++)
{
xv[2] = xv[1];
xv[1] = xv[0];
xv[0] = samples[i];
yv[2] = yv[1];
yv[1] = yv[0];
yv[0] = (ax[0] * xv[0] + ax[1] * xv[1] + ax[2] * xv[2]
- by[1] * yv[0]
- by[2] * yv[1]);
samples[i] = yv[0];
}
}
}
|
134875_12 | package com.ayutaki.chinjufumod.items.armor.model;
import net.minecraft.client.model.geom.PartPose;
import net.minecraft.client.model.geom.builders.CubeDeformation;
import net.minecraft.client.model.geom.builders.CubeListBuilder;
import net.minecraft.client.model.geom.builders.MeshDefinition;
import net.minecraft.client.model.geom.builders.PartDefinition;
public class SubmarineModel {
public static MeshDefinition createInner() {
MeshDefinition meshD = new MeshDefinition();
PartDefinition root = meshD.getRoot();
float scale = 0.15F;
/** Base **/
root.addOrReplaceChild("head", CubeListBuilder.create(), PartPose.ZERO);
root.addOrReplaceChild("hat", CubeListBuilder.create(), PartPose.ZERO);
PartDefinition bipedBody = root.addOrReplaceChild("body", CubeListBuilder.create()
.texOffs(16, 16)
.addBox(-4.0F, 0.0F, -2.0F, 8, 12, 4, new CubeDeformation(scale)),
PartPose.offset(0.0F, 0.0F, 0.0F));
root.addOrReplaceChild("left_arm", CubeListBuilder.create(), PartPose.ZERO);
root.addOrReplaceChild("right_arm", CubeListBuilder.create(), PartPose.ZERO);
PartDefinition bipedRightLeg = root.addOrReplaceChild("right_leg", CubeListBuilder.create(), PartPose.ZERO);
PartDefinition bipedLeftLeg = root.addOrReplaceChild("left_leg", CubeListBuilder.create(), PartPose.ZERO);
/** Add **/
bipedBody.addOrReplaceChild("eri", CubeListBuilder.create()
.texOffs(32, 32)
.addBox(-4.0F, 0.0F, -2.0F, 8, 12, 4, new CubeDeformation(scale + 0.3F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //ERI
bipedBody.addOrReplaceChild("uwagi", CubeListBuilder.create()
.texOffs(32, 48)
.addBox(-4.0F, 0.0F, -2.0F, 8, 12, 4, new CubeDeformation(scale + 0.2F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //UWAGI
bipedBody.addOrReplaceChild("tie", CubeListBuilder.create()
.texOffs(32, 64)
.addBox(-4.0F, 0.0F, -2.0F, 8, 12, 4, new CubeDeformation(scale + 0.1F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //TIE
bipedRightLeg.addOrReplaceChild("right_wa", CubeListBuilder.create()
.texOffs(0, 48)
.addBox(-2.0F, 0.0F, -2.0F, 4, 12, 4, new CubeDeformation(scale + 0.1F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //RIGHT_WA
bipedLeftLeg.addOrReplaceChild("left_wa", CubeListBuilder.create()
.texOffs(0, 48)
.addBox(-2.0F, 0.0F, -2.0F, 4, 12, 4, new CubeDeformation(scale + 0.1F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //LEFT_WA
return meshD;
}
public static MeshDefinition createOuter() {
MeshDefinition meshD = new MeshDefinition();
PartDefinition root = meshD.getRoot();
float scale = 0.55F;
/** Base **/
PartDefinition bipedHead = root.addOrReplaceChild("head", CubeListBuilder.create()
.texOffs(0, 0)
.addBox(-4.0F, -8.0F, -4.0F, 8, 8, 8, new CubeDeformation(scale)),
PartPose.offset(0.0F, 0.0F, 0.0F));
root.addOrReplaceChild("hat", CubeListBuilder.create(), PartPose.ZERO);
PartDefinition bipedBody = root.addOrReplaceChild("body", CubeListBuilder.create()
.texOffs(16, 16)
.addBox(-4.0F, 0.0F, -2.0F, 8, 12, 4, new CubeDeformation(scale)),
PartPose.offset(0.0F, 0.0F, 0.0F));
PartDefinition bipedRightArm = root.addOrReplaceChild("right_arm", CubeListBuilder.create()
.texOffs(40, 16)
.addBox(-3.0F, -2.0F, -2.0F, 4, 12, 4, new CubeDeformation(scale)),
PartPose.offset(0.0F, 0.0F, 0.0F));
PartDefinition bipedLeftArm = root.addOrReplaceChild("left_arm", CubeListBuilder.create()
.texOffs(40, 16)
.mirror(true)
.addBox(-1.0F, -2.0F, -2.0F, 4, 12, 4, new CubeDeformation(scale)),
PartPose.offset(0.0F, 0.0F, 0.0F));
PartDefinition bipedRightLeg = root.addOrReplaceChild("right_leg", CubeListBuilder.create()
.texOffs(0, 16)
.addBox(-2.0F, 0.0F, -2.0F, 4, 12, 4, new CubeDeformation(scale)),
PartPose.offset(0.0F, 0.0F, 0.0F));
PartDefinition bipedLeftLeg = root.addOrReplaceChild("left_leg", CubeListBuilder.create()
.texOffs(0, 16)
.mirror(true)
.addBox(-2.0F, 0.0F, -2.0F, 4, 12, 4, new CubeDeformation(scale)),
PartPose.offset(0.0F, 0.0F, 0.0F));
/** Add **/
float ag = (float)Math.PI / 180;
float hi = -7.55F;
bipedHead.addOrReplaceChild("boushi_f", CubeListBuilder.create()
.texOffs(20, 100)
.addBox(-0.09F, -10.58F, -2.91F, 3, 3, 3, new CubeDeformation(-0.09F)),
PartPose.offsetAndRotation(0.0F, 0.0F, 0.0F, 0.0F, 45 * ag, 0.0F)); //BOUSHI_F
bipedHead.addOrReplaceChild("boushi_b", CubeListBuilder.create()
.texOffs(0, 100)
.addBox(-2.0F, -10.5F, -2.0F, 4, 3, 6, new CubeDeformation(0.0F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //BOUSHI_B
bipedHead.addOrReplaceChild("boushi_w", CubeListBuilder.create()
.texOffs(32, 100)
.addBox(-4.0F, hi, -9.0F, 8, 1, 8, new CubeDeformation(0.75F)),
PartPose.offsetAndRotation(0.0F, 0.0F, 0.0F, -30 * ag, 0.0F, 0.0F)); //BOUSHI_W
bipedHead.addOrReplaceChild("boushi_w2", CubeListBuilder.create()
.texOffs(32, 110)
.addBox(-4.0F, hi - 2.48F, -9.0F, 8, 1, 8, new CubeDeformation(0.75F)),
PartPose.offsetAndRotation(0.0F, 0.0F, 0.0F, -30 * ag, 0.0F, 0.0F)); //BOUSHI_W2
bipedBody.addOrReplaceChild("ransel", CubeListBuilder.create()
.texOffs(0, 32)
.addBox(-4.0F, 0.1F, -1.9F, 8, 12, 4, new CubeDeformation(1.0F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //RANSEL
bipedBody.addOrReplaceChild("eri", CubeListBuilder.create()
.texOffs(32, 32)
.addBox(-4.0F, 0.0F, -2.0F, 8, 12, 4, new CubeDeformation(scale + 0.2F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //ERI
bipedBody.addOrReplaceChild("tie", CubeListBuilder.create()
.texOffs(32, 48)
.addBox(-4.0F, 0.0F, -2.0F, 8, 12, 4, new CubeDeformation(scale + 0.1F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //TIE
bipedRightArm.addOrReplaceChild("right_sode", CubeListBuilder.create()
.texOffs(32, 80)
.addBox(-3.0F, -2.0F, -2.0F, 4, 12, 4, new CubeDeformation(scale - 0.2F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //RIGHT_SODE
bipedLeftArm.addOrReplaceChild("left_sode", CubeListBuilder.create()
.texOffs(48, 80)
.addBox(-1.0F, -2.0F, -2.0F, 4, 12, 4, new CubeDeformation(scale - 0.2F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //LEFT_SODE
bipedRightLeg.addOrReplaceChild("right_sox", CubeListBuilder.create()
.texOffs(0, 80)
.addBox(-2.0F, 0.0F, -2.0F, 4, 12, 4, new CubeDeformation(0.3F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //RIGHT_SOX
bipedLeftLeg.addOrReplaceChild("left_sox", CubeListBuilder.create()
.texOffs(0, 80)
.mirror(true)
.addBox(-2.0F, 0.0F, -2.0F, 4, 12, 4, new CubeDeformation(0.3F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //LEFT_SOX
return meshD;
}
}
| AYUTAKI-Shou/ChinjufuMod7.0.1 | src/main/java/com/ayutaki/chinjufumod/items/armor/model/SubmarineModel.java | 3,464 | //BOUSHI_W2 | line_comment | pl | package com.ayutaki.chinjufumod.items.armor.model;
import net.minecraft.client.model.geom.PartPose;
import net.minecraft.client.model.geom.builders.CubeDeformation;
import net.minecraft.client.model.geom.builders.CubeListBuilder;
import net.minecraft.client.model.geom.builders.MeshDefinition;
import net.minecraft.client.model.geom.builders.PartDefinition;
public class SubmarineModel {
public static MeshDefinition createInner() {
MeshDefinition meshD = new MeshDefinition();
PartDefinition root = meshD.getRoot();
float scale = 0.15F;
/** Base **/
root.addOrReplaceChild("head", CubeListBuilder.create(), PartPose.ZERO);
root.addOrReplaceChild("hat", CubeListBuilder.create(), PartPose.ZERO);
PartDefinition bipedBody = root.addOrReplaceChild("body", CubeListBuilder.create()
.texOffs(16, 16)
.addBox(-4.0F, 0.0F, -2.0F, 8, 12, 4, new CubeDeformation(scale)),
PartPose.offset(0.0F, 0.0F, 0.0F));
root.addOrReplaceChild("left_arm", CubeListBuilder.create(), PartPose.ZERO);
root.addOrReplaceChild("right_arm", CubeListBuilder.create(), PartPose.ZERO);
PartDefinition bipedRightLeg = root.addOrReplaceChild("right_leg", CubeListBuilder.create(), PartPose.ZERO);
PartDefinition bipedLeftLeg = root.addOrReplaceChild("left_leg", CubeListBuilder.create(), PartPose.ZERO);
/** Add **/
bipedBody.addOrReplaceChild("eri", CubeListBuilder.create()
.texOffs(32, 32)
.addBox(-4.0F, 0.0F, -2.0F, 8, 12, 4, new CubeDeformation(scale + 0.3F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //ERI
bipedBody.addOrReplaceChild("uwagi", CubeListBuilder.create()
.texOffs(32, 48)
.addBox(-4.0F, 0.0F, -2.0F, 8, 12, 4, new CubeDeformation(scale + 0.2F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //UWAGI
bipedBody.addOrReplaceChild("tie", CubeListBuilder.create()
.texOffs(32, 64)
.addBox(-4.0F, 0.0F, -2.0F, 8, 12, 4, new CubeDeformation(scale + 0.1F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //TIE
bipedRightLeg.addOrReplaceChild("right_wa", CubeListBuilder.create()
.texOffs(0, 48)
.addBox(-2.0F, 0.0F, -2.0F, 4, 12, 4, new CubeDeformation(scale + 0.1F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //RIGHT_WA
bipedLeftLeg.addOrReplaceChild("left_wa", CubeListBuilder.create()
.texOffs(0, 48)
.addBox(-2.0F, 0.0F, -2.0F, 4, 12, 4, new CubeDeformation(scale + 0.1F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //LEFT_WA
return meshD;
}
public static MeshDefinition createOuter() {
MeshDefinition meshD = new MeshDefinition();
PartDefinition root = meshD.getRoot();
float scale = 0.55F;
/** Base **/
PartDefinition bipedHead = root.addOrReplaceChild("head", CubeListBuilder.create()
.texOffs(0, 0)
.addBox(-4.0F, -8.0F, -4.0F, 8, 8, 8, new CubeDeformation(scale)),
PartPose.offset(0.0F, 0.0F, 0.0F));
root.addOrReplaceChild("hat", CubeListBuilder.create(), PartPose.ZERO);
PartDefinition bipedBody = root.addOrReplaceChild("body", CubeListBuilder.create()
.texOffs(16, 16)
.addBox(-4.0F, 0.0F, -2.0F, 8, 12, 4, new CubeDeformation(scale)),
PartPose.offset(0.0F, 0.0F, 0.0F));
PartDefinition bipedRightArm = root.addOrReplaceChild("right_arm", CubeListBuilder.create()
.texOffs(40, 16)
.addBox(-3.0F, -2.0F, -2.0F, 4, 12, 4, new CubeDeformation(scale)),
PartPose.offset(0.0F, 0.0F, 0.0F));
PartDefinition bipedLeftArm = root.addOrReplaceChild("left_arm", CubeListBuilder.create()
.texOffs(40, 16)
.mirror(true)
.addBox(-1.0F, -2.0F, -2.0F, 4, 12, 4, new CubeDeformation(scale)),
PartPose.offset(0.0F, 0.0F, 0.0F));
PartDefinition bipedRightLeg = root.addOrReplaceChild("right_leg", CubeListBuilder.create()
.texOffs(0, 16)
.addBox(-2.0F, 0.0F, -2.0F, 4, 12, 4, new CubeDeformation(scale)),
PartPose.offset(0.0F, 0.0F, 0.0F));
PartDefinition bipedLeftLeg = root.addOrReplaceChild("left_leg", CubeListBuilder.create()
.texOffs(0, 16)
.mirror(true)
.addBox(-2.0F, 0.0F, -2.0F, 4, 12, 4, new CubeDeformation(scale)),
PartPose.offset(0.0F, 0.0F, 0.0F));
/** Add **/
float ag = (float)Math.PI / 180;
float hi = -7.55F;
bipedHead.addOrReplaceChild("boushi_f", CubeListBuilder.create()
.texOffs(20, 100)
.addBox(-0.09F, -10.58F, -2.91F, 3, 3, 3, new CubeDeformation(-0.09F)),
PartPose.offsetAndRotation(0.0F, 0.0F, 0.0F, 0.0F, 45 * ag, 0.0F)); //BOUSHI_F
bipedHead.addOrReplaceChild("boushi_b", CubeListBuilder.create()
.texOffs(0, 100)
.addBox(-2.0F, -10.5F, -2.0F, 4, 3, 6, new CubeDeformation(0.0F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //BOUSHI_B
bipedHead.addOrReplaceChild("boushi_w", CubeListBuilder.create()
.texOffs(32, 100)
.addBox(-4.0F, hi, -9.0F, 8, 1, 8, new CubeDeformation(0.75F)),
PartPose.offsetAndRotation(0.0F, 0.0F, 0.0F, -30 * ag, 0.0F, 0.0F)); //BOUSHI_W
bipedHead.addOrReplaceChild("boushi_w2", CubeListBuilder.create()
.texOffs(32, 110)
.addBox(-4.0F, hi - 2.48F, -9.0F, 8, 1, 8, new CubeDeformation(0.75F)),
PartPose.offsetAndRotation(0.0F, 0.0F, 0.0F, -30 * ag, 0.0F, 0.0F)); //BO<SUF>
bipedBody.addOrReplaceChild("ransel", CubeListBuilder.create()
.texOffs(0, 32)
.addBox(-4.0F, 0.1F, -1.9F, 8, 12, 4, new CubeDeformation(1.0F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //RANSEL
bipedBody.addOrReplaceChild("eri", CubeListBuilder.create()
.texOffs(32, 32)
.addBox(-4.0F, 0.0F, -2.0F, 8, 12, 4, new CubeDeformation(scale + 0.2F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //ERI
bipedBody.addOrReplaceChild("tie", CubeListBuilder.create()
.texOffs(32, 48)
.addBox(-4.0F, 0.0F, -2.0F, 8, 12, 4, new CubeDeformation(scale + 0.1F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //TIE
bipedRightArm.addOrReplaceChild("right_sode", CubeListBuilder.create()
.texOffs(32, 80)
.addBox(-3.0F, -2.0F, -2.0F, 4, 12, 4, new CubeDeformation(scale - 0.2F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //RIGHT_SODE
bipedLeftArm.addOrReplaceChild("left_sode", CubeListBuilder.create()
.texOffs(48, 80)
.addBox(-1.0F, -2.0F, -2.0F, 4, 12, 4, new CubeDeformation(scale - 0.2F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //LEFT_SODE
bipedRightLeg.addOrReplaceChild("right_sox", CubeListBuilder.create()
.texOffs(0, 80)
.addBox(-2.0F, 0.0F, -2.0F, 4, 12, 4, new CubeDeformation(0.3F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //RIGHT_SOX
bipedLeftLeg.addOrReplaceChild("left_sox", CubeListBuilder.create()
.texOffs(0, 80)
.mirror(true)
.addBox(-2.0F, 0.0F, -2.0F, 4, 12, 4, new CubeDeformation(0.3F)),
PartPose.offset(0.0F, 0.0F, 0.0F)); //LEFT_SOX
return meshD;
}
}
|
54663_1 | package Go.IO.WindowViewInput;
import Go.IO.WindowViewInput.Controllers.MenuController;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import java.util.concurrent.TimeUnit;
import static Go.IO.WindowViewInput.Go.flag;
import static Go.IO.WindowViewInput.Move.setMove;
import static Go.IO.WindowViewInput.WindowView.*;
public class Tile extends Rectangle {
public static Go paneThatImOn;
public static void setMenu(MenuController menu) {
Tile.menu = menu;
}
public static MenuController menu;
public Tile(int x, int y, Go pane) {
paneThatImOn = pane;
setWidth(Go.TILE_SIZE);
setHeight(Go.TILE_SIZE);
relocate(x * Go.TILE_SIZE, y * Go.TILE_SIZE);
setFill(Color.valueOf("#ffad33"));
setOnMouseClicked(e -> thingsToDoWhenClicked(x, y)); // Must check what if doubleclicked
setOnMouseEntered(e -> thingsToDoWhenEntered(x,y));
}
public static synchronized void thingsToDoWhenClicked(int x, int y) {
if ( x!= -1 ) {
array[lasty][lastx] = 0;
lastx = finalSize;
lasty = finalSize;
array[y][x] = 0;
}
setMove(x, y);
while (!judgeDidHisJob) {
try
{
TimeUnit.MILLISECONDS.sleep(100);
} catch(InterruptedException e)
{}
}
judgeDidHisJob = false;
paneThatImOn.setGoPane();
menu.refresh();
flag = !flag;
}
static void thingsToDoWhenEntered(int x, int y) {
if( ( x != lastx || y != lasty ) && array[y][x] == 0) {
array[lasty][lastx] = 0;
array[y][x] = 3;
lasty = y;
lastx = x;
paneThatImOn.setGoPane();
// Go.scene.setRoot(createContent()); // TODO trzeba odświeżyć
}
else if( ( x != lastx || y != lasty ) && array[y][x] != 0) {
array[lasty][lastx] = 0;
lasty = finalSize;
lastx = finalSize;
paneThatImOn.setGoPane();
}
menu.refresh();
}
}
| Aasfga/szalonyObject | src/Go/IO/WindowViewInput/Tile.java | 717 | // Go.scene.setRoot(createContent()); // TODO trzeba odświeżyć
| line_comment | pl | package Go.IO.WindowViewInput;
import Go.IO.WindowViewInput.Controllers.MenuController;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import java.util.concurrent.TimeUnit;
import static Go.IO.WindowViewInput.Go.flag;
import static Go.IO.WindowViewInput.Move.setMove;
import static Go.IO.WindowViewInput.WindowView.*;
public class Tile extends Rectangle {
public static Go paneThatImOn;
public static void setMenu(MenuController menu) {
Tile.menu = menu;
}
public static MenuController menu;
public Tile(int x, int y, Go pane) {
paneThatImOn = pane;
setWidth(Go.TILE_SIZE);
setHeight(Go.TILE_SIZE);
relocate(x * Go.TILE_SIZE, y * Go.TILE_SIZE);
setFill(Color.valueOf("#ffad33"));
setOnMouseClicked(e -> thingsToDoWhenClicked(x, y)); // Must check what if doubleclicked
setOnMouseEntered(e -> thingsToDoWhenEntered(x,y));
}
public static synchronized void thingsToDoWhenClicked(int x, int y) {
if ( x!= -1 ) {
array[lasty][lastx] = 0;
lastx = finalSize;
lasty = finalSize;
array[y][x] = 0;
}
setMove(x, y);
while (!judgeDidHisJob) {
try
{
TimeUnit.MILLISECONDS.sleep(100);
} catch(InterruptedException e)
{}
}
judgeDidHisJob = false;
paneThatImOn.setGoPane();
menu.refresh();
flag = !flag;
}
static void thingsToDoWhenEntered(int x, int y) {
if( ( x != lastx || y != lasty ) && array[y][x] == 0) {
array[lasty][lastx] = 0;
array[y][x] = 3;
lasty = y;
lastx = x;
paneThatImOn.setGoPane();
// Go<SUF>
}
else if( ( x != lastx || y != lasty ) && array[y][x] != 0) {
array[lasty][lastx] = 0;
lasty = finalSize;
lastx = finalSize;
paneThatImOn.setGoPane();
}
menu.refresh();
}
}
|
152371_14 | package eu.europeana.corelib.edm.utils;
import eu.europeana.corelib.definitions.edm.model.metainfo.ImageOrientation;
import eu.europeana.corelib.definitions.solr.DocType;
import eu.europeana.corelib.edm.model.metainfo.ImageMetaInfoImpl;
import eu.europeana.corelib.edm.model.metainfo.VideoMetaInfoImpl;
import eu.europeana.corelib.edm.model.metainfo.WebResourceMetaInfoImpl;
import eu.europeana.corelib.solr.bean.impl.FullBeanImpl;
import eu.europeana.corelib.solr.entity.AgentImpl;
import eu.europeana.corelib.solr.entity.AggregationImpl;
import eu.europeana.corelib.solr.entity.ConceptImpl;
import eu.europeana.corelib.solr.entity.EuropeanaAggregationImpl;
import eu.europeana.corelib.solr.entity.PlaceImpl;
import eu.europeana.corelib.solr.entity.ProvidedCHOImpl;
import eu.europeana.corelib.solr.entity.ProxyImpl;
import eu.europeana.corelib.solr.entity.TimespanImpl;
import eu.europeana.corelib.solr.entity.WebResourceImpl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* Given our current FullBean implementation it's not easy to deserialize a FullBean from json string, so for now we
* create a test fullbean by hand.
*
* @author Patrick Ehlert
* <p>
* Created on 10-09-2018
*/
public final class MockFullBean {
private MockFullBean() {
// empty constructor to prevent initialization
}
public static FullBeanImpl mock() {
FullBeanImpl bean = new FullBeanImpl();
bean.setAbout(MockBeanConstants.ABOUT);
bean.setTitle(new String[]{MockBeanConstants.DC_TITLE});
bean.setLanguage(new String[]{MockBeanConstants.LANGUAUGE_NL});
bean.setTimestampCreated(new Date(MockBeanConstants.TIMESTAMP_CREATED));
bean.setTimestampUpdated(new Date(MockBeanConstants.TIMESTAMP_UPDATED));
bean.setEuropeanaCollectionName(new String[]{MockBeanConstants.EUROPEANA_COLLECTION});
setProvidedCHO(bean);
setAgents(bean);
setAggregations(bean);
setEuropeanaAggregation(bean);
setProxies(bean);
setPlaces(bean);
setConcepts(bean);
setTimespans(bean);
return bean;
}
private static void setProxies(FullBeanImpl bean) {
List<ProxyImpl> proxies = new ArrayList<>();
ProxyImpl proxy = new ProxyImpl();
proxies.add(proxy);
proxy.setEdmType(DocType.IMAGE.getEnumNameValue());
proxy.setProxyIn(new String[]{MockBeanConstants.AGGREGATION_ABOUT});
proxy.setProxyFor(MockBeanConstants.ABOUT);
proxy.setDcCreator(new HashMap<>());
proxy.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_1);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_2);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_3);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_4);
proxy.setDcDate(new HashMap<>());
proxy.getDcDate().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcDate().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_DATE);
proxy.setDcFormat(new HashMap<>());
proxy.getDcFormat().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcFormat().get(MockBeanConstants.DEF).add("papier: hoogte: 675 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("papier: breedte: 522 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("plaat: hoogte: 565 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("plaat: breedte: 435 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("beeld: hoogte: 376 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("beeld: breedte: 275 mm");
proxy.setDcIdentifier(new HashMap<>());
proxy.getDcIdentifier().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcIdentifier().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_IDENTIFIER);
proxy.setDcTitle(new HashMap<>());
proxy.getDcTitle().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcTitle().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TITLE);
proxy.setDcType(new HashMap<>());
proxy.getDcType().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcType().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TYPE_1);
proxy.getDcType().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TYPE_2);
proxy.setDctermsAlternative(new HashMap<>());
proxy.getDctermsAlternative().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsAlternative().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_ALTERNATIVE);
proxy.setAbout(MockBeanConstants.PROXY_ABOUT_1);
proxy = new ProxyImpl();
proxies.add(proxy);
proxy.setEdmType(DocType.IMAGE.getEnumNameValue());
proxy.setProxyIn(new String[]{MockBeanConstants.EUROPEANA_AGG_ABOUT});
proxy.setProxyFor(MockBeanConstants.ABOUT);
proxy.setDcCreator(new HashMap<>());
proxy.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_5);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_6);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_7);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_8);
proxy.setDctermsTemporal(new HashMap<>());
proxy.getDctermsTemporal().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_1);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_2);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_3);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_4);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_4); //duplicate
proxy.setDctermsCreated(new HashMap<>());
proxy.getDctermsCreated().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsCreated().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_CREATED);
proxy.setDcCoverage(new HashMap<>());
proxy.getDcCoverage().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCoverage().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_COVERAGE_TEMPORAL);
proxy.getDcCoverage().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_COVERAGE_ABOUT); //allow invalid is false for dcCoverage and this should not get added in temporal coverage, But then it will get added in about
//to test https mapping
proxy.setDcDescription(new HashMap<>());
proxy.getDcDescription().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcDescription().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_DESCRIPTION);
proxy.setAbout(MockBeanConstants.PROXY_ABOUT_2);
bean.setProxies(proxies);
}
private static void setEuropeanaAggregation(FullBeanImpl bean) {
EuropeanaAggregationImpl europeanaAggregation = new EuropeanaAggregationImpl();
europeanaAggregation.setAbout(MockBeanConstants.EUROPEANA_AGG_ABOUT);
europeanaAggregation.setAggregatedCHO(MockBeanConstants.ABOUT);
europeanaAggregation.setDcCreator(new HashMap<>());
europeanaAggregation.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_9);
europeanaAggregation.setEdmCountry(new HashMap<>());
europeanaAggregation.getEdmCountry().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmCountry().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_COUNTRY);
europeanaAggregation.setEdmLanguage(new HashMap<>());
europeanaAggregation.getEdmLanguage().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmLanguage().get(MockBeanConstants.DEF).add(MockBeanConstants.LANGUAUGE_NL);
europeanaAggregation.setEdmRights(new HashMap<>());
europeanaAggregation.getEdmRights().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmLanguage().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_RIGHTS);
europeanaAggregation.setEdmPreview(MockBeanConstants.EDM_PREVIEW);
bean.setEuropeanaAggregation(europeanaAggregation);
}
private static void setAggregations(FullBeanImpl bean) {
List<AggregationImpl> aggregations = new ArrayList<>();
AggregationImpl aggregation = new AggregationImpl();
aggregation.setEdmDataProvider(new HashMap<>());
aggregation.getEdmDataProvider().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmDataProvider().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_PROVIDER_1);
//should be present in associated media as Image object
aggregation.setEdmIsShownBy(MockBeanConstants.EDM_IS_SHOWN_BY);
//should be present in associatedMedia as Video object
String[] hasViews = {MockBeanConstants.EDM_IS_SHOWN_AT};
aggregation.setHasView(hasViews);
aggregation.setEdmIsShownAt(MockBeanConstants.EDM_IS_SHOWN_AT);
aggregation.setEdmObject(MockBeanConstants.EDM_IS_SHOWN_BY);
aggregation.setEdmProvider(new HashMap<>());
aggregation.getEdmProvider().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmProvider().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_PROVIDER_2);
aggregation.setEdmRights(new HashMap<>());
aggregation.getEdmRights().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmRights().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_RIGHTS);
aggregation.setAggregatedCHO(MockBeanConstants.ABOUT);
aggregation.setAbout(MockBeanConstants.AGGREGATION_ABOUT);
List<WebResourceImpl> webResources = new ArrayList<>();
WebResourceImpl webResource = new WebResourceImpl();
webResources.add(webResource);
webResource.setDctermsCreated(new HashMap<>());
webResource.getDctermsCreated().put(MockBeanConstants.DEF, new ArrayList<>());
webResource.getDctermsCreated().get(MockBeanConstants.DEF).add("1936-05-11");
//should be present in videoObject
webResource.setAbout(MockBeanConstants.EDM_IS_SHOWN_AT);
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setVideoMetaInfo(new VideoMetaInfoImpl());
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_VIDEO);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setBitRate(400);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setDuration(2000L);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setHeight(500);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setWidth(650);
webResource = new WebResourceImpl();
webResources.add(webResource);
//this weresource will not be added in the schema.org as there is no associatedMedia present for value "testing"
webResource.setAbout("testing");
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setVideoMetaInfo(new VideoMetaInfoImpl());
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_VIDEO);
webResource = new WebResourceImpl();
webResources.add(webResource);
//should be present in ImageObject
webResource.setAbout(MockBeanConstants.EDM_IS_SHOWN_BY);
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setImageMetaInfo(new ImageMetaInfoImpl());
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setWidth(598);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setHeight(768);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_IMAGE);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setFileFormat("JPEG");
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setColorSpace("sRGB");
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setFileSize(61347L);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setColorPalette(new String[]{"#DCDCDC", "#2F4F4F", "#FAEBD7", "#FAF0E6", "#F5F5DC", "#696969"});
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setOrientation(ImageOrientation.PORTRAIT);
aggregation.setWebResources(webResources);
aggregations.add(aggregation);
bean.setAggregations(aggregations);
}
private static void setAgents(FullBeanImpl bean) {
List<AgentImpl> agents = new ArrayList<>();
AgentImpl agent = new AgentImpl();
agents.add(agent);
// first agent Person
agent.setEnd(new HashMap<>());
agent.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getEnd().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_DATE);
agent.setOwlSameAs(new String[]{"http://purl.org/collections/nl/am/p-10456",
"http://rdf.freebase.com/ns/m.011bn9nx",
"http://sv.dbpedia.org/resource/Leonardo_da_Vincis_uppfinningar",
"http://pl.dbpedia.org/resource/Wynalazki_i_konstrukcje_Leonarda_da_Vinci"});
agent.setRdaGr2DateOfBirth(new HashMap<>());
agent.getRdaGr2DateOfBirth().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_DATE);
agent.setRdaGr2DateOfDeath(new HashMap<>());
agent.getRdaGr2DateOfDeath().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_DATE);
agent.setRdaGr2PlaceOfBirth(new HashMap<>());
agent.getRdaGr2PlaceOfBirth().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_PLACE_1);
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_PLACE_2);
agent.getRdaGr2PlaceOfBirth().put(MockBeanConstants.EN, new ArrayList<>());
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.EN).add(MockBeanConstants.BIRTH_PLACE_3);
agent.setRdaGr2PlaceOfDeath(new HashMap<>());
agent.getRdaGr2PlaceOfDeath().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2PlaceOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_PLACE_1);
agent.getRdaGr2PlaceOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_PLACE_2);
agent.setRdaGr2BiographicalInformation(new HashMap<>());
agent.getRdaGr2BiographicalInformation().put(MockBeanConstants.EN, new ArrayList<>());
agent.getRdaGr2BiographicalInformation().get(MockBeanConstants.EN).add("Leonardo da Vinci (1452–1519) was an Italian polymath, regarded as the epitome of the \"Renaissance Man\", displaying skills in numerous diverse areas of study. Whilst most famous for his paintings such as the Mona Lisa and the Last Supper, Leonardo is also renowned in the fields of civil engineering, chemistry, geology, geometry, hydrodynamics, mathematics, mechanical engineering, optics, physics, pyrotechnics, and zoology.While the full extent of his scientific studies has only become recognized in the last 150 years, he was, during his lifetime, employed for his engineering and skill of invention. Many of his designs, such as the movable dikes to protect Venice from invasion, proved too costly or impractical. Some of his smaller inventions entered the world of manufacturing unheralded. As an engineer, Leonardo conceived ideas vastly ahead of his own time, conceptually inventing a helicopter, a tank, the use of concentrated solar power, a calculator, a rudimentary theory of plate tectonics and the double hull. In practice, he greatly advanced the state of knowledge in the fields of anatomy, astronomy, civil engineering, optics, and the study of water (hydrodynamics).Leonardo's most famous drawing, the Vitruvian Man, is a study of the proportions of the human body, linking art and science in a single work that has come to represent Renaissance Humanism.");
agent.getRdaGr2BiographicalInformation().put("pl", new ArrayList<>());
agent.getRdaGr2BiographicalInformation().get("pl").add("Leonardo da Vinci na prawie sześciu tysiącach stron notatek wykonał znacznie więcej projektów technicznych niż prac artystycznych, co wskazuje na to, że inżynieria była niezmiernie ważną dziedziną jego zainteresowań.Giorgio Vasari w Żywotach najsławniejszych malarzy, rzeźbiarzy i architektów pisał o Leonardzie:");
agent.setPrefLabel(new HashMap<>());
agent.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.EN).add("Science and inventions of Leonardo da Vinci");
agent.getPrefLabel().put(MockBeanConstants.PL, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.PL).add("Wynalazki i konstrukcje Leonarda da Vinci");
agent.setAltLabel(new HashMap<>());
agent.getAltLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getAltLabel().get(MockBeanConstants.EN).add("Leonardo da Vinci");
agent.setAbout(MockBeanConstants.DC_CREATOR_6);
//adding second agent Orgainsation
agent = new AgentImpl();
agents.add(agent);
agent.setPrefLabel(new HashMap<>());
agent.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.EN).add("European museums");
agent.getPrefLabel().put(MockBeanConstants.FR, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.FR).add("Musées européens");
agent.setRdaGr2DateOfTermination(new HashMap<>());
agent.getRdaGr2DateOfTermination().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfTermination().get(MockBeanConstants.DEF).add(MockBeanConstants.DISOLUTION_DATE);
agent.setAbout(MockBeanConstants.DC_CREATOR_8);
bean.setAgents(agents);
}
private static void setProvidedCHO(FullBeanImpl bean) {
List<ProvidedCHOImpl> providedCHOs = new ArrayList<>();
ProvidedCHOImpl providedCHO = new ProvidedCHOImpl();
providedCHO.setAbout(MockBeanConstants.ABOUT);
providedCHOs.add(providedCHO);
bean.setProvidedCHOs(providedCHOs);
}
public static void setTimespans(FullBeanImpl bean) {
List<TimespanImpl> timespans = new ArrayList<>();
TimespanImpl timespan = new TimespanImpl();
timespans.add(timespan);
timespan.setBegin(new HashMap<>());
timespan.getBegin().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getBegin().get(MockBeanConstants.DEF).add("Tue Jan 01 00:19:32 CET 1901");
timespan.setEnd(new HashMap<>());
timespan.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getEnd().get(MockBeanConstants.DEF).add("Sun Dec 31 01:00:00 CET 2000");
timespan.setAbout(MockBeanConstants.DC_TERMS_TEMPORAL_1);
timespan = new TimespanImpl();
timespans.add(timespan);
timespan.setBegin(new HashMap<>());
timespan.getBegin().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getBegin().get(MockBeanConstants.DEF).add("1901-01-01");
timespan.setEnd(new HashMap<>());
timespan.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getEnd().get(MockBeanConstants.DEF).add("1902-01-01");
timespan.setAbout(MockBeanConstants.DC_TERMS_TEMPORAL_2);
bean.setTimespans(timespans);
}
private static void setConcepts(FullBeanImpl bean) {
List<ConceptImpl> concepts = new ArrayList<>();
ConceptImpl concept = new ConceptImpl();
concepts.add(concept);
concept.setRelated(new String[]{"http://dbpedia.org/resource/Category:Agriculture"});
concept.setExactMatch(new String[]{"http://bg.dbpedia.org/resource/Селско_стопанство",
"http://ia.dbpedia.org/resource/Agricultura",
"http://sl.dbpedia.org/resource/Kmetijstvo",
"http://pnb.dbpedia.org/resource/وائی_بیجی",
"http://el.dbpedia.org/resource/Γεωργία_(δραστηριότητα)"});
concept.setPrefLabel(new HashMap<>());
concept.getPrefLabel().put("no", new ArrayList<>());
concept.getPrefLabel().get("no").add(MockBeanConstants.CONCEPT_PREF_LABEL_1);
concept.getPrefLabel().put("de", new ArrayList<>());
concept.getPrefLabel().get("de").add(MockBeanConstants.CONCEPT_PREF_LABEL_2);
concept.setNote(new HashMap<>());
concept.getNote().put("no", new ArrayList<>());
concept.getNote().get("no").add(MockBeanConstants.CONCEPT_NOTE_1);
concept.getNote().put("de", new ArrayList<>());
concept.getNote().get("de").add(MockBeanConstants.CONCEPT_NOTE_2);
concept.setAbout(MockBeanConstants.DC_CREATOR_4);
bean.setConcepts(concepts);
}
private static void setPlaces(FullBeanImpl bean) {
List<PlaceImpl> places = new ArrayList<>();
PlaceImpl place = new PlaceImpl();
places.add(place);
place.setIsPartOf(new HashMap<>());
place.getIsPartOf().put(MockBeanConstants.DEF, new ArrayList<>());
place.getIsPartOf().get(MockBeanConstants.DEF).add(MockBeanConstants.PLACE_IS_PART);
place.setLatitude(46.0F);
place.setAltitude(70.0F);
place.setLongitude(2.0F);
place.setDcTermsHasPart(new HashMap<>());
place.getDcTermsHasPart().put(MockBeanConstants.DEF, new ArrayList<>());
place.getDcTermsHasPart().get(MockBeanConstants.DEF).add(MockBeanConstants.PLACE_HAS_PART);
place.setOwlSameAs(new String[]{MockBeanConstants.PLACE_SAME_OWL_AS});
place.setPrefLabel(new HashMap<>());
place.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
place.getPrefLabel().get(MockBeanConstants.EN).add(MockBeanConstants.PLACE_PREF_LABEL);
place.setAltLabel(new HashMap<>());
place.getAltLabel().put(MockBeanConstants.IT, new ArrayList<>());
place.getAltLabel().get(MockBeanConstants.IT).add(MockBeanConstants.PLACE_PREF_LABEL);
place.setNote(new HashMap<>());
place.getNote().put(MockBeanConstants.EN, new ArrayList<>());
place.getNote().get(MockBeanConstants.EN).add(MockBeanConstants.PLACE_NOTE);
place.setAbout(MockBeanConstants.DC_CREATOR_7);
bean.setPlaces(places);
}
} | Abbe98/corelib | corelib-schemaorg/src/test/java/eu/europeana/corelib/edm/utils/MockFullBean.java | 7,415 | //pl.dbpedia.org/resource/Wynalazki_i_konstrukcje_Leonarda_da_Vinci"}); | line_comment | pl | package eu.europeana.corelib.edm.utils;
import eu.europeana.corelib.definitions.edm.model.metainfo.ImageOrientation;
import eu.europeana.corelib.definitions.solr.DocType;
import eu.europeana.corelib.edm.model.metainfo.ImageMetaInfoImpl;
import eu.europeana.corelib.edm.model.metainfo.VideoMetaInfoImpl;
import eu.europeana.corelib.edm.model.metainfo.WebResourceMetaInfoImpl;
import eu.europeana.corelib.solr.bean.impl.FullBeanImpl;
import eu.europeana.corelib.solr.entity.AgentImpl;
import eu.europeana.corelib.solr.entity.AggregationImpl;
import eu.europeana.corelib.solr.entity.ConceptImpl;
import eu.europeana.corelib.solr.entity.EuropeanaAggregationImpl;
import eu.europeana.corelib.solr.entity.PlaceImpl;
import eu.europeana.corelib.solr.entity.ProvidedCHOImpl;
import eu.europeana.corelib.solr.entity.ProxyImpl;
import eu.europeana.corelib.solr.entity.TimespanImpl;
import eu.europeana.corelib.solr.entity.WebResourceImpl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* Given our current FullBean implementation it's not easy to deserialize a FullBean from json string, so for now we
* create a test fullbean by hand.
*
* @author Patrick Ehlert
* <p>
* Created on 10-09-2018
*/
public final class MockFullBean {
private MockFullBean() {
// empty constructor to prevent initialization
}
public static FullBeanImpl mock() {
FullBeanImpl bean = new FullBeanImpl();
bean.setAbout(MockBeanConstants.ABOUT);
bean.setTitle(new String[]{MockBeanConstants.DC_TITLE});
bean.setLanguage(new String[]{MockBeanConstants.LANGUAUGE_NL});
bean.setTimestampCreated(new Date(MockBeanConstants.TIMESTAMP_CREATED));
bean.setTimestampUpdated(new Date(MockBeanConstants.TIMESTAMP_UPDATED));
bean.setEuropeanaCollectionName(new String[]{MockBeanConstants.EUROPEANA_COLLECTION});
setProvidedCHO(bean);
setAgents(bean);
setAggregations(bean);
setEuropeanaAggregation(bean);
setProxies(bean);
setPlaces(bean);
setConcepts(bean);
setTimespans(bean);
return bean;
}
private static void setProxies(FullBeanImpl bean) {
List<ProxyImpl> proxies = new ArrayList<>();
ProxyImpl proxy = new ProxyImpl();
proxies.add(proxy);
proxy.setEdmType(DocType.IMAGE.getEnumNameValue());
proxy.setProxyIn(new String[]{MockBeanConstants.AGGREGATION_ABOUT});
proxy.setProxyFor(MockBeanConstants.ABOUT);
proxy.setDcCreator(new HashMap<>());
proxy.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_1);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_2);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_3);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_4);
proxy.setDcDate(new HashMap<>());
proxy.getDcDate().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcDate().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_DATE);
proxy.setDcFormat(new HashMap<>());
proxy.getDcFormat().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcFormat().get(MockBeanConstants.DEF).add("papier: hoogte: 675 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("papier: breedte: 522 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("plaat: hoogte: 565 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("plaat: breedte: 435 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("beeld: hoogte: 376 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("beeld: breedte: 275 mm");
proxy.setDcIdentifier(new HashMap<>());
proxy.getDcIdentifier().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcIdentifier().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_IDENTIFIER);
proxy.setDcTitle(new HashMap<>());
proxy.getDcTitle().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcTitle().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TITLE);
proxy.setDcType(new HashMap<>());
proxy.getDcType().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcType().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TYPE_1);
proxy.getDcType().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TYPE_2);
proxy.setDctermsAlternative(new HashMap<>());
proxy.getDctermsAlternative().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsAlternative().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_ALTERNATIVE);
proxy.setAbout(MockBeanConstants.PROXY_ABOUT_1);
proxy = new ProxyImpl();
proxies.add(proxy);
proxy.setEdmType(DocType.IMAGE.getEnumNameValue());
proxy.setProxyIn(new String[]{MockBeanConstants.EUROPEANA_AGG_ABOUT});
proxy.setProxyFor(MockBeanConstants.ABOUT);
proxy.setDcCreator(new HashMap<>());
proxy.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_5);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_6);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_7);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_8);
proxy.setDctermsTemporal(new HashMap<>());
proxy.getDctermsTemporal().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_1);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_2);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_3);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_4);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_4); //duplicate
proxy.setDctermsCreated(new HashMap<>());
proxy.getDctermsCreated().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsCreated().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_CREATED);
proxy.setDcCoverage(new HashMap<>());
proxy.getDcCoverage().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCoverage().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_COVERAGE_TEMPORAL);
proxy.getDcCoverage().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_COVERAGE_ABOUT); //allow invalid is false for dcCoverage and this should not get added in temporal coverage, But then it will get added in about
//to test https mapping
proxy.setDcDescription(new HashMap<>());
proxy.getDcDescription().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcDescription().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_DESCRIPTION);
proxy.setAbout(MockBeanConstants.PROXY_ABOUT_2);
bean.setProxies(proxies);
}
private static void setEuropeanaAggregation(FullBeanImpl bean) {
EuropeanaAggregationImpl europeanaAggregation = new EuropeanaAggregationImpl();
europeanaAggregation.setAbout(MockBeanConstants.EUROPEANA_AGG_ABOUT);
europeanaAggregation.setAggregatedCHO(MockBeanConstants.ABOUT);
europeanaAggregation.setDcCreator(new HashMap<>());
europeanaAggregation.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_9);
europeanaAggregation.setEdmCountry(new HashMap<>());
europeanaAggregation.getEdmCountry().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmCountry().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_COUNTRY);
europeanaAggregation.setEdmLanguage(new HashMap<>());
europeanaAggregation.getEdmLanguage().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmLanguage().get(MockBeanConstants.DEF).add(MockBeanConstants.LANGUAUGE_NL);
europeanaAggregation.setEdmRights(new HashMap<>());
europeanaAggregation.getEdmRights().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmLanguage().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_RIGHTS);
europeanaAggregation.setEdmPreview(MockBeanConstants.EDM_PREVIEW);
bean.setEuropeanaAggregation(europeanaAggregation);
}
private static void setAggregations(FullBeanImpl bean) {
List<AggregationImpl> aggregations = new ArrayList<>();
AggregationImpl aggregation = new AggregationImpl();
aggregation.setEdmDataProvider(new HashMap<>());
aggregation.getEdmDataProvider().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmDataProvider().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_PROVIDER_1);
//should be present in associated media as Image object
aggregation.setEdmIsShownBy(MockBeanConstants.EDM_IS_SHOWN_BY);
//should be present in associatedMedia as Video object
String[] hasViews = {MockBeanConstants.EDM_IS_SHOWN_AT};
aggregation.setHasView(hasViews);
aggregation.setEdmIsShownAt(MockBeanConstants.EDM_IS_SHOWN_AT);
aggregation.setEdmObject(MockBeanConstants.EDM_IS_SHOWN_BY);
aggregation.setEdmProvider(new HashMap<>());
aggregation.getEdmProvider().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmProvider().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_PROVIDER_2);
aggregation.setEdmRights(new HashMap<>());
aggregation.getEdmRights().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmRights().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_RIGHTS);
aggregation.setAggregatedCHO(MockBeanConstants.ABOUT);
aggregation.setAbout(MockBeanConstants.AGGREGATION_ABOUT);
List<WebResourceImpl> webResources = new ArrayList<>();
WebResourceImpl webResource = new WebResourceImpl();
webResources.add(webResource);
webResource.setDctermsCreated(new HashMap<>());
webResource.getDctermsCreated().put(MockBeanConstants.DEF, new ArrayList<>());
webResource.getDctermsCreated().get(MockBeanConstants.DEF).add("1936-05-11");
//should be present in videoObject
webResource.setAbout(MockBeanConstants.EDM_IS_SHOWN_AT);
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setVideoMetaInfo(new VideoMetaInfoImpl());
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_VIDEO);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setBitRate(400);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setDuration(2000L);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setHeight(500);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setWidth(650);
webResource = new WebResourceImpl();
webResources.add(webResource);
//this weresource will not be added in the schema.org as there is no associatedMedia present for value "testing"
webResource.setAbout("testing");
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setVideoMetaInfo(new VideoMetaInfoImpl());
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_VIDEO);
webResource = new WebResourceImpl();
webResources.add(webResource);
//should be present in ImageObject
webResource.setAbout(MockBeanConstants.EDM_IS_SHOWN_BY);
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setImageMetaInfo(new ImageMetaInfoImpl());
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setWidth(598);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setHeight(768);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_IMAGE);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setFileFormat("JPEG");
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setColorSpace("sRGB");
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setFileSize(61347L);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setColorPalette(new String[]{"#DCDCDC", "#2F4F4F", "#FAEBD7", "#FAF0E6", "#F5F5DC", "#696969"});
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setOrientation(ImageOrientation.PORTRAIT);
aggregation.setWebResources(webResources);
aggregations.add(aggregation);
bean.setAggregations(aggregations);
}
private static void setAgents(FullBeanImpl bean) {
List<AgentImpl> agents = new ArrayList<>();
AgentImpl agent = new AgentImpl();
agents.add(agent);
// first agent Person
agent.setEnd(new HashMap<>());
agent.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getEnd().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_DATE);
agent.setOwlSameAs(new String[]{"http://purl.org/collections/nl/am/p-10456",
"http://rdf.freebase.com/ns/m.011bn9nx",
"http://sv.dbpedia.org/resource/Leonardo_da_Vincis_uppfinningar",
"http://pl<SUF>
agent.setRdaGr2DateOfBirth(new HashMap<>());
agent.getRdaGr2DateOfBirth().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_DATE);
agent.setRdaGr2DateOfDeath(new HashMap<>());
agent.getRdaGr2DateOfDeath().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_DATE);
agent.setRdaGr2PlaceOfBirth(new HashMap<>());
agent.getRdaGr2PlaceOfBirth().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_PLACE_1);
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_PLACE_2);
agent.getRdaGr2PlaceOfBirth().put(MockBeanConstants.EN, new ArrayList<>());
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.EN).add(MockBeanConstants.BIRTH_PLACE_3);
agent.setRdaGr2PlaceOfDeath(new HashMap<>());
agent.getRdaGr2PlaceOfDeath().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2PlaceOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_PLACE_1);
agent.getRdaGr2PlaceOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_PLACE_2);
agent.setRdaGr2BiographicalInformation(new HashMap<>());
agent.getRdaGr2BiographicalInformation().put(MockBeanConstants.EN, new ArrayList<>());
agent.getRdaGr2BiographicalInformation().get(MockBeanConstants.EN).add("Leonardo da Vinci (1452–1519) was an Italian polymath, regarded as the epitome of the \"Renaissance Man\", displaying skills in numerous diverse areas of study. Whilst most famous for his paintings such as the Mona Lisa and the Last Supper, Leonardo is also renowned in the fields of civil engineering, chemistry, geology, geometry, hydrodynamics, mathematics, mechanical engineering, optics, physics, pyrotechnics, and zoology.While the full extent of his scientific studies has only become recognized in the last 150 years, he was, during his lifetime, employed for his engineering and skill of invention. Many of his designs, such as the movable dikes to protect Venice from invasion, proved too costly or impractical. Some of his smaller inventions entered the world of manufacturing unheralded. As an engineer, Leonardo conceived ideas vastly ahead of his own time, conceptually inventing a helicopter, a tank, the use of concentrated solar power, a calculator, a rudimentary theory of plate tectonics and the double hull. In practice, he greatly advanced the state of knowledge in the fields of anatomy, astronomy, civil engineering, optics, and the study of water (hydrodynamics).Leonardo's most famous drawing, the Vitruvian Man, is a study of the proportions of the human body, linking art and science in a single work that has come to represent Renaissance Humanism.");
agent.getRdaGr2BiographicalInformation().put("pl", new ArrayList<>());
agent.getRdaGr2BiographicalInformation().get("pl").add("Leonardo da Vinci na prawie sześciu tysiącach stron notatek wykonał znacznie więcej projektów technicznych niż prac artystycznych, co wskazuje na to, że inżynieria była niezmiernie ważną dziedziną jego zainteresowań.Giorgio Vasari w Żywotach najsławniejszych malarzy, rzeźbiarzy i architektów pisał o Leonardzie:");
agent.setPrefLabel(new HashMap<>());
agent.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.EN).add("Science and inventions of Leonardo da Vinci");
agent.getPrefLabel().put(MockBeanConstants.PL, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.PL).add("Wynalazki i konstrukcje Leonarda da Vinci");
agent.setAltLabel(new HashMap<>());
agent.getAltLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getAltLabel().get(MockBeanConstants.EN).add("Leonardo da Vinci");
agent.setAbout(MockBeanConstants.DC_CREATOR_6);
//adding second agent Orgainsation
agent = new AgentImpl();
agents.add(agent);
agent.setPrefLabel(new HashMap<>());
agent.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.EN).add("European museums");
agent.getPrefLabel().put(MockBeanConstants.FR, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.FR).add("Musées européens");
agent.setRdaGr2DateOfTermination(new HashMap<>());
agent.getRdaGr2DateOfTermination().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfTermination().get(MockBeanConstants.DEF).add(MockBeanConstants.DISOLUTION_DATE);
agent.setAbout(MockBeanConstants.DC_CREATOR_8);
bean.setAgents(agents);
}
private static void setProvidedCHO(FullBeanImpl bean) {
List<ProvidedCHOImpl> providedCHOs = new ArrayList<>();
ProvidedCHOImpl providedCHO = new ProvidedCHOImpl();
providedCHO.setAbout(MockBeanConstants.ABOUT);
providedCHOs.add(providedCHO);
bean.setProvidedCHOs(providedCHOs);
}
public static void setTimespans(FullBeanImpl bean) {
List<TimespanImpl> timespans = new ArrayList<>();
TimespanImpl timespan = new TimespanImpl();
timespans.add(timespan);
timespan.setBegin(new HashMap<>());
timespan.getBegin().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getBegin().get(MockBeanConstants.DEF).add("Tue Jan 01 00:19:32 CET 1901");
timespan.setEnd(new HashMap<>());
timespan.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getEnd().get(MockBeanConstants.DEF).add("Sun Dec 31 01:00:00 CET 2000");
timespan.setAbout(MockBeanConstants.DC_TERMS_TEMPORAL_1);
timespan = new TimespanImpl();
timespans.add(timespan);
timespan.setBegin(new HashMap<>());
timespan.getBegin().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getBegin().get(MockBeanConstants.DEF).add("1901-01-01");
timespan.setEnd(new HashMap<>());
timespan.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getEnd().get(MockBeanConstants.DEF).add("1902-01-01");
timespan.setAbout(MockBeanConstants.DC_TERMS_TEMPORAL_2);
bean.setTimespans(timespans);
}
private static void setConcepts(FullBeanImpl bean) {
List<ConceptImpl> concepts = new ArrayList<>();
ConceptImpl concept = new ConceptImpl();
concepts.add(concept);
concept.setRelated(new String[]{"http://dbpedia.org/resource/Category:Agriculture"});
concept.setExactMatch(new String[]{"http://bg.dbpedia.org/resource/Селско_стопанство",
"http://ia.dbpedia.org/resource/Agricultura",
"http://sl.dbpedia.org/resource/Kmetijstvo",
"http://pnb.dbpedia.org/resource/وائی_بیجی",
"http://el.dbpedia.org/resource/Γεωργία_(δραστηριότητα)"});
concept.setPrefLabel(new HashMap<>());
concept.getPrefLabel().put("no", new ArrayList<>());
concept.getPrefLabel().get("no").add(MockBeanConstants.CONCEPT_PREF_LABEL_1);
concept.getPrefLabel().put("de", new ArrayList<>());
concept.getPrefLabel().get("de").add(MockBeanConstants.CONCEPT_PREF_LABEL_2);
concept.setNote(new HashMap<>());
concept.getNote().put("no", new ArrayList<>());
concept.getNote().get("no").add(MockBeanConstants.CONCEPT_NOTE_1);
concept.getNote().put("de", new ArrayList<>());
concept.getNote().get("de").add(MockBeanConstants.CONCEPT_NOTE_2);
concept.setAbout(MockBeanConstants.DC_CREATOR_4);
bean.setConcepts(concepts);
}
private static void setPlaces(FullBeanImpl bean) {
List<PlaceImpl> places = new ArrayList<>();
PlaceImpl place = new PlaceImpl();
places.add(place);
place.setIsPartOf(new HashMap<>());
place.getIsPartOf().put(MockBeanConstants.DEF, new ArrayList<>());
place.getIsPartOf().get(MockBeanConstants.DEF).add(MockBeanConstants.PLACE_IS_PART);
place.setLatitude(46.0F);
place.setAltitude(70.0F);
place.setLongitude(2.0F);
place.setDcTermsHasPart(new HashMap<>());
place.getDcTermsHasPart().put(MockBeanConstants.DEF, new ArrayList<>());
place.getDcTermsHasPart().get(MockBeanConstants.DEF).add(MockBeanConstants.PLACE_HAS_PART);
place.setOwlSameAs(new String[]{MockBeanConstants.PLACE_SAME_OWL_AS});
place.setPrefLabel(new HashMap<>());
place.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
place.getPrefLabel().get(MockBeanConstants.EN).add(MockBeanConstants.PLACE_PREF_LABEL);
place.setAltLabel(new HashMap<>());
place.getAltLabel().put(MockBeanConstants.IT, new ArrayList<>());
place.getAltLabel().get(MockBeanConstants.IT).add(MockBeanConstants.PLACE_PREF_LABEL);
place.setNote(new HashMap<>());
place.getNote().put(MockBeanConstants.EN, new ArrayList<>());
place.getNote().get(MockBeanConstants.EN).add(MockBeanConstants.PLACE_NOTE);
place.setAbout(MockBeanConstants.DC_CREATOR_7);
bean.setPlaces(places);
}
} |
155615_0 | package com.example.sm_project.Activity;
import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.room.Room;
import com.example.sm_project.Activity.Settings.SettingsActivity;
import com.example.sm_project.Adapter.BestRestAdapter;
import com.example.sm_project.Adapter.CategoryAdapter;
import com.example.sm_project.Converter.DataConverter;
import com.example.sm_project.Dao.CategoryDao;
import com.example.sm_project.Dao.OrderDao;
import com.example.sm_project.Dao.RestaurantDao;
import com.example.sm_project.Dao.RestaurantDishCrossRefDao;
import com.example.sm_project.Helper.CategoryTable;
import com.example.sm_project.Helper.MyDataBase;
import com.example.sm_project.Helper.OrderTable;
import com.example.sm_project.Helper.RestaurantDishCrossRef;
import com.example.sm_project.Helper.RestaurantTable;
import com.example.sm_project.R;
import com.example.sm_project.databinding.ActivityMainBinding;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.model.RectangularBounds;
import com.google.android.libraries.places.widget.AutocompleteSupportFragment;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import androidx.annotation.NonNull;
import com.google.android.gms.common.api.Status;
import com.google.android.libraries.places.widget.listener.PlaceSelectionListener;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
MyDataBase myDB;
RestaurantDao RestaurantDao;
private int selectedRestaurantId = -1;
private String API_KEY = "AIzaSyCEPM7C8Hx3XDlOFYSW2pjcCmtGCvjor4w";
private ActivityMainBinding binding;
private Spinner combinedInfoTextView;
private static final int SEARCH_RADIUS_METERS = 5000;
private double currentLatitude = 0.0;
private double currentLongitude = 0.0;
private CategoryDao categoryDao;
private RestaurantDao restaurantDao;
private BestRestAdapter restaurantAdapter;
private ImageView settingsBtn;
private RestaurantDishCrossRefDao restaurantDishCrossRefDao;
private OrderDao orderDao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
settingsBtn = findViewById(R.id.settingsBtn);
myDB = Room.databaseBuilder(this, MyDataBase.class, "Database_db")
.allowMainThreadQueries().fallbackToDestructiveMigration().build();
categoryDao = myDB.getCategoryDao();
restaurantDao = myDB.getRestaurantDao();
restaurantDishCrossRefDao = myDB.getRDCrossDao();
goToSettings();
restaurantDishCrossRefDao.getAllRDCross().observe(this, categories -> {
if (categories == null || categories.isEmpty()) {
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(1,1));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(1,2));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(1,3));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(1,4));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(1,5));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(1,6));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(1,7));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(2,8));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(2,9));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(2,10));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(2,11));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(2,12));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(3,13));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(3,14));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(3,15));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(3,16));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(4,17));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(4,18));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(4,19));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(4,20));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(4,21));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(5,22));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(5,23));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(5,24));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(5,25));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(5,26));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(5,27));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(9,28));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(9,29));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(9,30));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(9,31));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(9,32));
} else {
}
});
RecyclerView recyclerViewRest = findViewById(R.id.bestRestView);
recyclerViewRest.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
List<RestaurantTable> restaurantTables = restaurantDao.getAllRestaurantsSync();
BestRestAdapter RestAdapter = new BestRestAdapter(restaurantTables);
recyclerViewRest.setAdapter(RestAdapter);
restaurantAdapter = new BestRestAdapter(restaurantTables);
recyclerViewRest.setAdapter(restaurantAdapter);
restaurantAdapter.setOnRestaurantClickListener(new BestRestAdapter.OnRestaurantClickListener() {
@Override
public void onRestaurantClick(RestaurantTable restaurant) {
Intent intent = new Intent(MainActivity.this, ListFoodActivity.class);
intent.putExtra("restaurantId", restaurant.getId());
intent.putExtra("nazwaRestauracji", restaurant.getName());
startActivity(intent);
}
});
restaurantAdapter.setOnDataLoadedListener(new BestRestAdapter.OnDataLoadedListener() {
@Override
public void onDataLoaded() {
ProgressBar progressBarBestRest = findViewById(R.id.progressBarBestRest);
progressBarBestRest.setVisibility(View.GONE);
}
});
RecyclerView recyclerViewCat = findViewById(R.id.categoryView); // RecyclerView
recyclerViewCat.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
List<CategoryTable> categoryTables = categoryDao.getAllCategoriesSync();
CategoryAdapter adapterrr = new CategoryAdapter(categoryTables);
recyclerViewCat.setAdapter(adapterrr);
adapterrr.setOnDataLoadedListener(new CategoryAdapter.OnDataLoadedListener() {
@Override
public void onDataLoaded() {
ProgressBar progressBarCategory = findViewById(R.id.progressBarCategory);
progressBarCategory.setVisibility(View.GONE);
}
});
adapterrr.setOnCategoryClickListener(new CategoryAdapter.OnCategoryClickListener() {
@Override
public void onCategoryClick(CategoryTable category) {
String categoryName = category.getName();
Intent intent = new Intent(MainActivity.this, CategoryActivity.class);
intent.putExtra("categoryName", categoryName);
startActivity(intent);
}
});
combinedInfoTextView = findViewById(R.id.locationSp);
Intent intent = getIntent();
String userAddress = intent.getStringExtra("userAddress");
String userCity = intent.getStringExtra("userCity");
String userCountry = intent.getStringExtra("userCountry");
double latitude = intent.getDoubleExtra("latitude", 0.0);
double longitude = intent.getDoubleExtra("longitude", 0.0);
String combinedInfo = userAddress + "\n" + userCity + "\n" + userCountry;
ArrayList<String> list = new ArrayList<>();
list.add(combinedInfo);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, list);
combinedInfoTextView.setAdapter(adapter);
SharedPreferences preferences = getSharedPreferences("MyPreferences", MODE_PRIVATE);
String savedUsername = preferences.getString("username", null);
if (intent.hasExtra("userLogin")) {
String userLogin = intent.getStringExtra("userLogin");
saveUsername(userLogin);
TextView loginTextView = findViewById(R.id.usernameTxt);
loginTextView.setText(userLogin);
} else if (savedUsername != null) {
TextView loginTextView = findViewById(R.id.usernameTxt);
loginTextView.setText(savedUsername);
}
binding.geoIcon.setOnClickListener(v -> {
Intent intentGeo = new Intent(MainActivity.this, GeolocationActivity.class);
startActivity(intentGeo);
});
binding.logoutBtn.setOnClickListener(v -> {
showCustomDialog(getString(R.string.logout_confirm));
});
AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
if (!Places.isInitialized()) {
Places.initialize(getApplicationContext(), API_KEY);
}
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG));
autocompleteFragment.setTypesFilter(Arrays.asList("restaurant"));
LatLng bialystokLatLng = new LatLng(latitude, longitude);
autocompleteFragment.setLocationRestriction(RectangularBounds.newInstance(
new LatLng(bialystokLatLng.latitude - 0.1, bialystokLatLng.longitude - 0.1),
new LatLng(bialystokLatLng.latitude + 0.1, bialystokLatLng.longitude + 0.1)));
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
private int getRestaurantIdByName(List<RestaurantTable> restaurantTables, String restaurantName) {
for (RestaurantTable restaurantTable : restaurantTables) {
if (restaurantTable.getName().equalsIgnoreCase(restaurantName)) {
return restaurantTable.getId();
}
}
return -1;
}
@Override
public void onPlaceSelected(@NonNull Place place) {
Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
// Sprawdzamy, czy wybrane miejsce jest na liście restauracji
String selectedRestaurantName = place.getName();
boolean isRestaurantOnList = isRestaurantOnList(restaurantTables, selectedRestaurantName);
if (isRestaurantOnList) {
selectedRestaurantId = getRestaurantIdByName(restaurantTables, selectedRestaurantName);
Intent intent = new Intent(MainActivity.this, ListFoodActivity.class);
intent.putExtra("restaurantId", selectedRestaurantId);
intent.putExtra("nazwaRestauracji", selectedRestaurantName);
startActivity(intent);
} else {
// Komunikat informujący, że restauracja nie jest na liście
Toast.makeText(MainActivity.this, R.string.invalid_restaurant, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError(@NonNull Status status) {
Log.i(TAG, "An error occurred: " + status);
}
});
binding.bottomNavigationView.setOnItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int itemId = item.getItemId();
if(itemId == R.id.home){
Intent ordersIntent = new Intent(MainActivity.this, MainActivity.class);
startActivity(ordersIntent);
} else if(itemId == R.id.orders){
Intent ordersIntent = new Intent(MainActivity.this, OrdersActivity.class);
startActivity(ordersIntent);
}else if(itemId == R.id.search){
Intent ordersIntent = new Intent(MainActivity.this, ListFoodActivity.class);
startActivity(ordersIntent);
}
return false;
}
});
}
// Metoda sprawdzająca, czy restauracja jest na liście
private boolean isRestaurantOnList (List < RestaurantTable > restaurantTables, String
restaurantName){
for (RestaurantTable restaurantTable : restaurantTables) {
if (restaurantTable.getName().equalsIgnoreCase(restaurantName)) {
return true;
}
}
return false;
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.botttom_nav_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.orders) {
Log.d("MainActivity", "Clicked on Profile");
startActivity(new Intent(this, StartActivity.class));
return true;
} else if (itemId == R.id.search) {
startActivity(new Intent(this, CartActivity.class));
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
private void showCustomDialog(String message) {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_dialog);
TextView dialogMessage = dialog.findViewById(R.id.dialogMessage);
dialogMessage.setText(message);
Button dialogButton = dialog.findViewById(R.id.dialogButton);
Button cancelButton = dialog.findViewById(R.id.cancel_button);
dialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
if (v.getId() == R.id.dialogButton) {
clearUsername();
Intent intent3 = new Intent(MainActivity.this, StartActivity.class);
startActivity(intent3);
}
}
});
dialog.show();
}
private void saveUsername(String username) {
SharedPreferences preferences = getSharedPreferences("MyPreferences", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("username", username);
editor.apply();
}
private void clearUsername() {
SharedPreferences preferences = getSharedPreferences("MyPreferences", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.remove("username");
editor.apply();
}
private void goToSettings() {
settingsBtn.setOnClickListener(v -> {
SharedPreferences preferences = getSharedPreferences("MyPreferences", MODE_PRIVATE);
String loggedInUsername = preferences.getString("username", null);
if (loggedInUsername != null && loggedInUsername.equals("admin")) {
Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(intent);
} else {
Toast.makeText(MainActivity.this, "Brak uprawnień do ustawień.", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onPointerCaptureChanged(boolean hasCapture) {
super.onPointerCaptureChanged(hasCapture);
}
} | AbsenceOfHxpe/SM_Projekt | app/src/main/java/com/example/sm_project/Activity/MainActivity.java | 4,720 | // RecyclerView | line_comment | pl | package com.example.sm_project.Activity;
import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.room.Room;
import com.example.sm_project.Activity.Settings.SettingsActivity;
import com.example.sm_project.Adapter.BestRestAdapter;
import com.example.sm_project.Adapter.CategoryAdapter;
import com.example.sm_project.Converter.DataConverter;
import com.example.sm_project.Dao.CategoryDao;
import com.example.sm_project.Dao.OrderDao;
import com.example.sm_project.Dao.RestaurantDao;
import com.example.sm_project.Dao.RestaurantDishCrossRefDao;
import com.example.sm_project.Helper.CategoryTable;
import com.example.sm_project.Helper.MyDataBase;
import com.example.sm_project.Helper.OrderTable;
import com.example.sm_project.Helper.RestaurantDishCrossRef;
import com.example.sm_project.Helper.RestaurantTable;
import com.example.sm_project.R;
import com.example.sm_project.databinding.ActivityMainBinding;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.model.RectangularBounds;
import com.google.android.libraries.places.widget.AutocompleteSupportFragment;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import androidx.annotation.NonNull;
import com.google.android.gms.common.api.Status;
import com.google.android.libraries.places.widget.listener.PlaceSelectionListener;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
MyDataBase myDB;
RestaurantDao RestaurantDao;
private int selectedRestaurantId = -1;
private String API_KEY = "AIzaSyCEPM7C8Hx3XDlOFYSW2pjcCmtGCvjor4w";
private ActivityMainBinding binding;
private Spinner combinedInfoTextView;
private static final int SEARCH_RADIUS_METERS = 5000;
private double currentLatitude = 0.0;
private double currentLongitude = 0.0;
private CategoryDao categoryDao;
private RestaurantDao restaurantDao;
private BestRestAdapter restaurantAdapter;
private ImageView settingsBtn;
private RestaurantDishCrossRefDao restaurantDishCrossRefDao;
private OrderDao orderDao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
settingsBtn = findViewById(R.id.settingsBtn);
myDB = Room.databaseBuilder(this, MyDataBase.class, "Database_db")
.allowMainThreadQueries().fallbackToDestructiveMigration().build();
categoryDao = myDB.getCategoryDao();
restaurantDao = myDB.getRestaurantDao();
restaurantDishCrossRefDao = myDB.getRDCrossDao();
goToSettings();
restaurantDishCrossRefDao.getAllRDCross().observe(this, categories -> {
if (categories == null || categories.isEmpty()) {
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(1,1));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(1,2));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(1,3));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(1,4));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(1,5));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(1,6));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(1,7));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(2,8));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(2,9));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(2,10));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(2,11));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(2,12));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(3,13));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(3,14));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(3,15));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(3,16));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(4,17));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(4,18));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(4,19));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(4,20));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(4,21));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(5,22));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(5,23));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(5,24));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(5,25));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(5,26));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(5,27));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(9,28));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(9,29));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(9,30));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(9,31));
restaurantDishCrossRefDao.insert(new RestaurantDishCrossRef(9,32));
} else {
}
});
RecyclerView recyclerViewRest = findViewById(R.id.bestRestView);
recyclerViewRest.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
List<RestaurantTable> restaurantTables = restaurantDao.getAllRestaurantsSync();
BestRestAdapter RestAdapter = new BestRestAdapter(restaurantTables);
recyclerViewRest.setAdapter(RestAdapter);
restaurantAdapter = new BestRestAdapter(restaurantTables);
recyclerViewRest.setAdapter(restaurantAdapter);
restaurantAdapter.setOnRestaurantClickListener(new BestRestAdapter.OnRestaurantClickListener() {
@Override
public void onRestaurantClick(RestaurantTable restaurant) {
Intent intent = new Intent(MainActivity.this, ListFoodActivity.class);
intent.putExtra("restaurantId", restaurant.getId());
intent.putExtra("nazwaRestauracji", restaurant.getName());
startActivity(intent);
}
});
restaurantAdapter.setOnDataLoadedListener(new BestRestAdapter.OnDataLoadedListener() {
@Override
public void onDataLoaded() {
ProgressBar progressBarBestRest = findViewById(R.id.progressBarBestRest);
progressBarBestRest.setVisibility(View.GONE);
}
});
RecyclerView recyclerViewCat = findViewById(R.id.categoryView); // Re<SUF>
recyclerViewCat.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
List<CategoryTable> categoryTables = categoryDao.getAllCategoriesSync();
CategoryAdapter adapterrr = new CategoryAdapter(categoryTables);
recyclerViewCat.setAdapter(adapterrr);
adapterrr.setOnDataLoadedListener(new CategoryAdapter.OnDataLoadedListener() {
@Override
public void onDataLoaded() {
ProgressBar progressBarCategory = findViewById(R.id.progressBarCategory);
progressBarCategory.setVisibility(View.GONE);
}
});
adapterrr.setOnCategoryClickListener(new CategoryAdapter.OnCategoryClickListener() {
@Override
public void onCategoryClick(CategoryTable category) {
String categoryName = category.getName();
Intent intent = new Intent(MainActivity.this, CategoryActivity.class);
intent.putExtra("categoryName", categoryName);
startActivity(intent);
}
});
combinedInfoTextView = findViewById(R.id.locationSp);
Intent intent = getIntent();
String userAddress = intent.getStringExtra("userAddress");
String userCity = intent.getStringExtra("userCity");
String userCountry = intent.getStringExtra("userCountry");
double latitude = intent.getDoubleExtra("latitude", 0.0);
double longitude = intent.getDoubleExtra("longitude", 0.0);
String combinedInfo = userAddress + "\n" + userCity + "\n" + userCountry;
ArrayList<String> list = new ArrayList<>();
list.add(combinedInfo);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, list);
combinedInfoTextView.setAdapter(adapter);
SharedPreferences preferences = getSharedPreferences("MyPreferences", MODE_PRIVATE);
String savedUsername = preferences.getString("username", null);
if (intent.hasExtra("userLogin")) {
String userLogin = intent.getStringExtra("userLogin");
saveUsername(userLogin);
TextView loginTextView = findViewById(R.id.usernameTxt);
loginTextView.setText(userLogin);
} else if (savedUsername != null) {
TextView loginTextView = findViewById(R.id.usernameTxt);
loginTextView.setText(savedUsername);
}
binding.geoIcon.setOnClickListener(v -> {
Intent intentGeo = new Intent(MainActivity.this, GeolocationActivity.class);
startActivity(intentGeo);
});
binding.logoutBtn.setOnClickListener(v -> {
showCustomDialog(getString(R.string.logout_confirm));
});
AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
if (!Places.isInitialized()) {
Places.initialize(getApplicationContext(), API_KEY);
}
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG));
autocompleteFragment.setTypesFilter(Arrays.asList("restaurant"));
LatLng bialystokLatLng = new LatLng(latitude, longitude);
autocompleteFragment.setLocationRestriction(RectangularBounds.newInstance(
new LatLng(bialystokLatLng.latitude - 0.1, bialystokLatLng.longitude - 0.1),
new LatLng(bialystokLatLng.latitude + 0.1, bialystokLatLng.longitude + 0.1)));
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
private int getRestaurantIdByName(List<RestaurantTable> restaurantTables, String restaurantName) {
for (RestaurantTable restaurantTable : restaurantTables) {
if (restaurantTable.getName().equalsIgnoreCase(restaurantName)) {
return restaurantTable.getId();
}
}
return -1;
}
@Override
public void onPlaceSelected(@NonNull Place place) {
Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
// Sprawdzamy, czy wybrane miejsce jest na liście restauracji
String selectedRestaurantName = place.getName();
boolean isRestaurantOnList = isRestaurantOnList(restaurantTables, selectedRestaurantName);
if (isRestaurantOnList) {
selectedRestaurantId = getRestaurantIdByName(restaurantTables, selectedRestaurantName);
Intent intent = new Intent(MainActivity.this, ListFoodActivity.class);
intent.putExtra("restaurantId", selectedRestaurantId);
intent.putExtra("nazwaRestauracji", selectedRestaurantName);
startActivity(intent);
} else {
// Komunikat informujący, że restauracja nie jest na liście
Toast.makeText(MainActivity.this, R.string.invalid_restaurant, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError(@NonNull Status status) {
Log.i(TAG, "An error occurred: " + status);
}
});
binding.bottomNavigationView.setOnItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int itemId = item.getItemId();
if(itemId == R.id.home){
Intent ordersIntent = new Intent(MainActivity.this, MainActivity.class);
startActivity(ordersIntent);
} else if(itemId == R.id.orders){
Intent ordersIntent = new Intent(MainActivity.this, OrdersActivity.class);
startActivity(ordersIntent);
}else if(itemId == R.id.search){
Intent ordersIntent = new Intent(MainActivity.this, ListFoodActivity.class);
startActivity(ordersIntent);
}
return false;
}
});
}
// Metoda sprawdzająca, czy restauracja jest na liście
private boolean isRestaurantOnList (List < RestaurantTable > restaurantTables, String
restaurantName){
for (RestaurantTable restaurantTable : restaurantTables) {
if (restaurantTable.getName().equalsIgnoreCase(restaurantName)) {
return true;
}
}
return false;
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.botttom_nav_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.orders) {
Log.d("MainActivity", "Clicked on Profile");
startActivity(new Intent(this, StartActivity.class));
return true;
} else if (itemId == R.id.search) {
startActivity(new Intent(this, CartActivity.class));
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
private void showCustomDialog(String message) {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_dialog);
TextView dialogMessage = dialog.findViewById(R.id.dialogMessage);
dialogMessage.setText(message);
Button dialogButton = dialog.findViewById(R.id.dialogButton);
Button cancelButton = dialog.findViewById(R.id.cancel_button);
dialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
if (v.getId() == R.id.dialogButton) {
clearUsername();
Intent intent3 = new Intent(MainActivity.this, StartActivity.class);
startActivity(intent3);
}
}
});
dialog.show();
}
private void saveUsername(String username) {
SharedPreferences preferences = getSharedPreferences("MyPreferences", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("username", username);
editor.apply();
}
private void clearUsername() {
SharedPreferences preferences = getSharedPreferences("MyPreferences", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.remove("username");
editor.apply();
}
private void goToSettings() {
settingsBtn.setOnClickListener(v -> {
SharedPreferences preferences = getSharedPreferences("MyPreferences", MODE_PRIVATE);
String loggedInUsername = preferences.getString("username", null);
if (loggedInUsername != null && loggedInUsername.equals("admin")) {
Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(intent);
} else {
Toast.makeText(MainActivity.this, "Brak uprawnień do ustawień.", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onPointerCaptureChanged(boolean hasCapture) {
super.onPointerCaptureChanged(hasCapture);
}
} |
111754_0 | package com.group3.twat.auth;
import com.group3.twat.auth.service.JwtService;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtService jwtService;
private UserDetailsService userDetailsService;
@Autowired
public JwtAuthenticationFilter(JwtService jwtService, UserDetailsService userDetailsService) {
this.jwtService = jwtService;
this.userDetailsService = userDetailsService;
}
@Override
protected void doFilterInternal(
@NotNull HttpServletRequest request,
@NotNull HttpServletResponse response,
@NotNull FilterChain filterChain)
throws ServletException, IOException {
final String authHeader = request.getHeader("Authorization");
final String jwt;
final String username;
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
filterChain.doFilter(request, response);
return;
}
//7 dla tego że jak liczymy Bearer i " " to wychodzi 7
jwt = authHeader.substring(7);
try {
username = jwtService.extractUsername(jwt);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
System.out.println("JWTFilter 51: " + userDetails.getPassword());
if (jwtService.isTokenValid(jwt, userDetails)) {
System.out.println("Token is valid 53");
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
userDetails.getUsername(),
userDetails.getPassword(),
userDetails.getAuthorities()
);
authToken.setDetails(
new WebAuthenticationDetailsSource().buildDetails(request)
);
SecurityContextHolder.getContext().setAuthentication(authToken);
System.out.println(SecurityContextHolder.getContext().getAuthentication().isAuthenticated());
System.out.println(SecurityContextHolder.getContext().getAuthentication());
filterChain.doFilter(request, response);
return;
} else {
System.out.println("Token not valid");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write("Unauthorized");
}
}
} catch(JwtException e){
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write("Unauthorized");
}
}
}
| AceOfSnakes60/Twatter_Server | src/main/java/com/group3/twat/auth/JwtAuthenticationFilter.java | 878 | //7 dla tego że jak liczymy Bearer i " " to wychodzi 7 | line_comment | pl | package com.group3.twat.auth;
import com.group3.twat.auth.service.JwtService;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtService jwtService;
private UserDetailsService userDetailsService;
@Autowired
public JwtAuthenticationFilter(JwtService jwtService, UserDetailsService userDetailsService) {
this.jwtService = jwtService;
this.userDetailsService = userDetailsService;
}
@Override
protected void doFilterInternal(
@NotNull HttpServletRequest request,
@NotNull HttpServletResponse response,
@NotNull FilterChain filterChain)
throws ServletException, IOException {
final String authHeader = request.getHeader("Authorization");
final String jwt;
final String username;
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
filterChain.doFilter(request, response);
return;
}
//7 <SUF>
jwt = authHeader.substring(7);
try {
username = jwtService.extractUsername(jwt);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
System.out.println("JWTFilter 51: " + userDetails.getPassword());
if (jwtService.isTokenValid(jwt, userDetails)) {
System.out.println("Token is valid 53");
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
userDetails.getUsername(),
userDetails.getPassword(),
userDetails.getAuthorities()
);
authToken.setDetails(
new WebAuthenticationDetailsSource().buildDetails(request)
);
SecurityContextHolder.getContext().setAuthentication(authToken);
System.out.println(SecurityContextHolder.getContext().getAuthentication().isAuthenticated());
System.out.println(SecurityContextHolder.getContext().getAuthentication());
filterChain.doFilter(request, response);
return;
} else {
System.out.println("Token not valid");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write("Unauthorized");
}
}
} catch(JwtException e){
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write("Unauthorized");
}
}
}
|
15600_0 | package com.redartedgames.ball.map;
import com.redartedgames.ball.editor.EditorPicker;
import com.redartedgames.ball.objects.GameObject;
import com.redartedgames.ball.screen.MyScreen;
public class MapScreen extends MyScreen{
public MapScreen(int width, int height) {
super(0, 0, width, height);
world = new MapWorld();
screenRenderer = new MapRenderer(world, camera);
}
//nwm, czy to wgl bedzie uzywane... chyba lepiej add jakis zrobic
public void loadObjectsToEditorOptions(EditorPicker ep) {
for (GameObject obj : world.getGameObjects()) {
//ep.add(new ObjectPick("object", obj, null));
}
}
public void addGameObject(GameObject object) {
world.getGameObjects().add(object);
}
public void removeGameObject(GameObject object) {
world.getGameObjects().remove(object);
}
} | AconLight/Erron | core/src/com/redartedgames/ball/map/MapScreen.java | 287 | //nwm, czy to wgl bedzie uzywane... chyba lepiej add jakis zrobic | line_comment | pl | package com.redartedgames.ball.map;
import com.redartedgames.ball.editor.EditorPicker;
import com.redartedgames.ball.objects.GameObject;
import com.redartedgames.ball.screen.MyScreen;
public class MapScreen extends MyScreen{
public MapScreen(int width, int height) {
super(0, 0, width, height);
world = new MapWorld();
screenRenderer = new MapRenderer(world, camera);
}
//nw<SUF>
public void loadObjectsToEditorOptions(EditorPicker ep) {
for (GameObject obj : world.getGameObjects()) {
//ep.add(new ObjectPick("object", obj, null));
}
}
public void addGameObject(GameObject object) {
world.getGameObjects().add(object);
}
public void removeGameObject(GameObject object) {
world.getGameObjects().remove(object);
}
} |
97494_9 | package com.example.canv;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
/*
Do obsługi siatki uzywana jest tablica 3 wymiarowa
tablica przechowuje 3 informacje o kazdym punkcie
pierwsze dwa indexy sluza do wyboru punktu w tablicy 2
3 index sluzy do przechowywania nastepujacych informacji:
TaB[x][y][0] => stan rzeczywisty punktu 1 zycie 0 smierc na podstawie tej wartosci rysowane jest plotno
TaB[x][y][1] => ilosc sasiednich zyjacych pol
TaB[x][y][1] => Tablica pomocnicza zapisujaca stan nowej tablicy zyjacych i martwych komorek tak aby wykonywanie obliczen nie wplywalo na nastepne punkty,
po wykonaniu algorytmu wartosci z tej tablicy sa przepisywane do tablicy TaB[x][y][0] i aktualizowane jest plotno
*/
public class MyCanv extends View {
Paint paint;
public static int[][][] TaB= new int[13][18][3];
public MyCanv(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int xs = canvas.getWidth() / 2;
int ys = canvas.getHeight() / 2;
// rysowanie siatki czerwoych lini /////////////////////////////////////////////////////////////////
for(int a=0; a< 2*xs; a=a+100){
paint.setColor(Color.RED);
canvas.drawLine(a, 2*ys, a, -ys, paint);
}
for(int b=0; b< 2*ys; b=b+100){
paint.setColor(Color.RED);
canvas.drawLine(2*xs, b, -xs, b, paint);
}
// rysowanie komorek z tablicy na plotnie //////////////////////////////////////////////////////////
for (int x1 = 0; x1<=11;x1++){
for(int y1 = 0; y1<=16;y1++){
RectF pp = new RectF(
x1*100+1,
y1*100+1,
x1*100+99,
y1*100+99);
if( TaB[x1+1][y1][0]==1){
paint.setColor(Color.BLACK);
canvas.drawRect(pp, paint);
}
if( TaB[x1+1][y1][0]==0){
paint.setColor(Color.WHITE);
canvas.drawRect(pp, paint);
}
}
}
//Gray Bar top
paint.setColor(Color.GRAY);
canvas.drawRect(1f,1f,canvas.getWidth(),100, paint);
}
public boolean onTouchEvent(MotionEvent event) {
//wyluskanie akcji pojedynczego klikniecia za pomoca rejestrowania akcji wcisniecia ekranu
if(event.getAction()==MotionEvent.ACTION_DOWN){
//przepisanie wartosci wspolrzednej na tablice
int a = (int) (( (event.getX()-event.getX()%100)/100)+1);
int b = (int) (( (event.getY()-event.getY()%100)/100));
if (TaB[a][b][0]==0)
{
TaB[a][b][0]=1;
}
else if(TaB[a][b][0]==1)
{
TaB[a][b][0]=0;
}
invalidate();
}
return true;
}
//czyszczenie tablicy
public void clear(){
for (int x2 = 0; x2<=11;x2++){
for(int y2 = 0; y2<=16;y2++) {
TaB[x2][y2][0]=0;
}
}
}
//algorytm life
public void oneStep(){
for (int x2 = 0; x2<=11;x2++){
for(int y2 = 0; y2<=16;y2++) {
//liczenie sasiadow dla kazdegj komorki
int neighbour = 0;
if(x2-1>=0 && y2-1>=0)
if(TaB[x2-1][y2-1][0]==1)
neighbour++;
if(x2-1>=0 && y2-1>=0)
if(TaB[x2-1][y2][0]==1)
neighbour++;
if(x2-1>=0 && y2-1>=0)
if(TaB[x2-1][y2+1][0]==1)
neighbour++;
if(x2-1>=0 && y2-1>=0)
if(TaB[x2][y2-1][0]==1)
neighbour++;
if(x2-1>=0 && y2-1>=0)
if(TaB[x2][y2+1][0]==1)
neighbour++;
if(x2-1>=0 && y2-1>=0)
if(TaB[x2+1][y2-1][0]==1)
neighbour++;
if(x2-1>=0 && y2-1>=0)
if(TaB[x2+1][y2][0]==1)
neighbour++;
if(x2-1>=0 && y2-1>=0)
if(TaB[x2+1][y2+1][0]==1)
neighbour++;
TaB[x2][y2][1]=neighbour;
}
}
// realizacja zasad ewolucji
for (int x3 = 0; x3<=11;x3++) {
for (int y3 = 0; y3 <= 16; y3++) {
// tworzenie nowych komorek z martwych
if(TaB[x3][y3][0]==0){
if (TaB[x3][y3][1] == 3){
TaB[x3][y3][2] = 1;
}
else
TaB[x3][y3][2] = TaB[x3][y3][0];
}
//operacje na zyjacych komorkach
if(TaB[x3][y3][0]==1){
if (TaB[x3][y3][1] < 2){
TaB[x3][y3][2] = 0;
}
else if (TaB[x3][y3][1] == 2 || TaB[x3][y3][1] == 3){
TaB[x3][y3][2] = 1;
}
else if (TaB[x3][y3][1] > 3){
TaB[x3][y3][2] = 0;
}
else
TaB[x3][y3][2] = TaB[x3][y3][0];
}
}
}
//przepisanie pomocniczej tablicy do wlasciwej
for (int x3 = 0; x3<=11;x3++) {
for (int y3 = 0; y3 <= 16; y3++) {
TaB[x3][y3][0] = TaB[x3][y3][2];
}
}
}
}
| Adam0Wasik/AndroidGameOfLife | app/src/main/java/com/example/canv/MyCanv.java | 2,173 | // realizacja zasad ewolucji | line_comment | pl | package com.example.canv;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
/*
Do obsługi siatki uzywana jest tablica 3 wymiarowa
tablica przechowuje 3 informacje o kazdym punkcie
pierwsze dwa indexy sluza do wyboru punktu w tablicy 2
3 index sluzy do przechowywania nastepujacych informacji:
TaB[x][y][0] => stan rzeczywisty punktu 1 zycie 0 smierc na podstawie tej wartosci rysowane jest plotno
TaB[x][y][1] => ilosc sasiednich zyjacych pol
TaB[x][y][1] => Tablica pomocnicza zapisujaca stan nowej tablicy zyjacych i martwych komorek tak aby wykonywanie obliczen nie wplywalo na nastepne punkty,
po wykonaniu algorytmu wartosci z tej tablicy sa przepisywane do tablicy TaB[x][y][0] i aktualizowane jest plotno
*/
public class MyCanv extends View {
Paint paint;
public static int[][][] TaB= new int[13][18][3];
public MyCanv(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int xs = canvas.getWidth() / 2;
int ys = canvas.getHeight() / 2;
// rysowanie siatki czerwoych lini /////////////////////////////////////////////////////////////////
for(int a=0; a< 2*xs; a=a+100){
paint.setColor(Color.RED);
canvas.drawLine(a, 2*ys, a, -ys, paint);
}
for(int b=0; b< 2*ys; b=b+100){
paint.setColor(Color.RED);
canvas.drawLine(2*xs, b, -xs, b, paint);
}
// rysowanie komorek z tablicy na plotnie //////////////////////////////////////////////////////////
for (int x1 = 0; x1<=11;x1++){
for(int y1 = 0; y1<=16;y1++){
RectF pp = new RectF(
x1*100+1,
y1*100+1,
x1*100+99,
y1*100+99);
if( TaB[x1+1][y1][0]==1){
paint.setColor(Color.BLACK);
canvas.drawRect(pp, paint);
}
if( TaB[x1+1][y1][0]==0){
paint.setColor(Color.WHITE);
canvas.drawRect(pp, paint);
}
}
}
//Gray Bar top
paint.setColor(Color.GRAY);
canvas.drawRect(1f,1f,canvas.getWidth(),100, paint);
}
public boolean onTouchEvent(MotionEvent event) {
//wyluskanie akcji pojedynczego klikniecia za pomoca rejestrowania akcji wcisniecia ekranu
if(event.getAction()==MotionEvent.ACTION_DOWN){
//przepisanie wartosci wspolrzednej na tablice
int a = (int) (( (event.getX()-event.getX()%100)/100)+1);
int b = (int) (( (event.getY()-event.getY()%100)/100));
if (TaB[a][b][0]==0)
{
TaB[a][b][0]=1;
}
else if(TaB[a][b][0]==1)
{
TaB[a][b][0]=0;
}
invalidate();
}
return true;
}
//czyszczenie tablicy
public void clear(){
for (int x2 = 0; x2<=11;x2++){
for(int y2 = 0; y2<=16;y2++) {
TaB[x2][y2][0]=0;
}
}
}
//algorytm life
public void oneStep(){
for (int x2 = 0; x2<=11;x2++){
for(int y2 = 0; y2<=16;y2++) {
//liczenie sasiadow dla kazdegj komorki
int neighbour = 0;
if(x2-1>=0 && y2-1>=0)
if(TaB[x2-1][y2-1][0]==1)
neighbour++;
if(x2-1>=0 && y2-1>=0)
if(TaB[x2-1][y2][0]==1)
neighbour++;
if(x2-1>=0 && y2-1>=0)
if(TaB[x2-1][y2+1][0]==1)
neighbour++;
if(x2-1>=0 && y2-1>=0)
if(TaB[x2][y2-1][0]==1)
neighbour++;
if(x2-1>=0 && y2-1>=0)
if(TaB[x2][y2+1][0]==1)
neighbour++;
if(x2-1>=0 && y2-1>=0)
if(TaB[x2+1][y2-1][0]==1)
neighbour++;
if(x2-1>=0 && y2-1>=0)
if(TaB[x2+1][y2][0]==1)
neighbour++;
if(x2-1>=0 && y2-1>=0)
if(TaB[x2+1][y2+1][0]==1)
neighbour++;
TaB[x2][y2][1]=neighbour;
}
}
// re<SUF>
for (int x3 = 0; x3<=11;x3++) {
for (int y3 = 0; y3 <= 16; y3++) {
// tworzenie nowych komorek z martwych
if(TaB[x3][y3][0]==0){
if (TaB[x3][y3][1] == 3){
TaB[x3][y3][2] = 1;
}
else
TaB[x3][y3][2] = TaB[x3][y3][0];
}
//operacje na zyjacych komorkach
if(TaB[x3][y3][0]==1){
if (TaB[x3][y3][1] < 2){
TaB[x3][y3][2] = 0;
}
else if (TaB[x3][y3][1] == 2 || TaB[x3][y3][1] == 3){
TaB[x3][y3][2] = 1;
}
else if (TaB[x3][y3][1] > 3){
TaB[x3][y3][2] = 0;
}
else
TaB[x3][y3][2] = TaB[x3][y3][0];
}
}
}
//przepisanie pomocniczej tablicy do wlasciwej
for (int x3 = 0; x3<=11;x3++) {
for (int y3 = 0; y3 <= 16; y3++) {
TaB[x3][y3][0] = TaB[x3][y3][2];
}
}
}
}
|
148225_0 | package com.example.colonybattle.colors;
public enum ConsoleColor {
RED("\033[0;31m"),
GREEN("\033[0;32m"),
BLUE("\033[0;34m"),
YELLOW("\033[0;33m"),
PURPLE("\033[0;35m"), // fioletowy
CYAN("\033[0;36m"), // turkusowy
WHITE("\033[0;37m"), // biały
BLACK("\033[0;30m"), // czarny
BRIGHT_RED("\033[0;91m"), // jasnoczerwony
BRIGHT_GREEN("\033[0;92m"), // jasnozielony
BRIGHT_BLUE("\033[0;94m"), // jasnoniebieski
BRIGHT_YELLOW("\033[0;93m"), // jasnożółty
BRIGHT_PURPLE("\033[0;95m"), // jasnofioletowy
BRIGHT_CYAN("\033[0;96m"), // jasnoturkusowy
BRIGHT_WHITE("\033[0;97m"), // jasnobiały
RESET("\033[0m"); // używane do resetowania koloru do domyślnego
private final String code;
ConsoleColor(String code) {
this.code = code;
}
@Override
public String toString() {
return code;
}
}
| Adam0s007/ColonyBattle | src/main/java/com/example/colonybattle/colors/ConsoleColor.java | 433 | // fioletowy | line_comment | pl | package com.example.colonybattle.colors;
public enum ConsoleColor {
RED("\033[0;31m"),
GREEN("\033[0;32m"),
BLUE("\033[0;34m"),
YELLOW("\033[0;33m"),
PURPLE("\033[0;35m"), // fi<SUF>
CYAN("\033[0;36m"), // turkusowy
WHITE("\033[0;37m"), // biały
BLACK("\033[0;30m"), // czarny
BRIGHT_RED("\033[0;91m"), // jasnoczerwony
BRIGHT_GREEN("\033[0;92m"), // jasnozielony
BRIGHT_BLUE("\033[0;94m"), // jasnoniebieski
BRIGHT_YELLOW("\033[0;93m"), // jasnożółty
BRIGHT_PURPLE("\033[0;95m"), // jasnofioletowy
BRIGHT_CYAN("\033[0;96m"), // jasnoturkusowy
BRIGHT_WHITE("\033[0;97m"), // jasnobiały
RESET("\033[0m"); // używane do resetowania koloru do domyślnego
private final String code;
ConsoleColor(String code) {
this.code = code;
}
@Override
public String toString() {
return code;
}
}
|
22283_3 | package evol.gen;
import evol.gen.gui.App;
import javafx.application.Platform;
import java.util.*;
public class SimulationEngine implements IEngine,Runnable {
private final GrassField myMap;
//private App observer;
public int moveDelay = 300;
private final boolean isAppOpening;
public boolean someMadness = false;
public boolean showJustDay = false;
private App observer;
public SimulationEngine(GrassField map, int initAnimals,App app) {
this.myMap = map; //nasza kochana mapa
this.observer = app;
this.isAppOpening =true;
for(int i = 0; i < initAnimals;i++){
Vector2d newVec =((GrassField) this.myMap).getRandom(((GrassField)this.myMap).topRight);
Animal animal = new Animal(this.myMap, newVec);
this.myMap.place(animal);
}
System.out.println(myMap.toString());
}
@Override
public void run() {
// Symulacja każdego dnia składa się z poniższej sekwencji kroków:
// usunięcie martwych zwierząt z mapy,
// skręt i przemieszczenie każdego zwierzęcia,
// konsumpcja roślin na których pola weszły zwierzęta,
// rozmnażanie się najedzonych zwierząt znajdujących się na tym samym polu,
// wzrastanie nowych roślin na wybranych polach mapy.
//mamy listę zwierzątek; teraz musimy uzyskać informację o ich aktywowanym genie:
//w petli:
// tworzymy teraz listę aktywnych genów (animal.activatedGen)
//podaną listę aktywnych genów dodajemy do parsera, przeksztalci nam je w MoveDirection)
// zwierzątka się zaczynają poruszać (tutaj zajdzie duzo roznych akcji)
//warunek pętli: (poniewaz wiemy, ze kazdy zwierzak ma taką samą długość genomu, to wybierzmy jeden ze zwierzakow i dla niego robmy warunek)
if(!showJustDay){
this.observer.updateMap(0);
}
int counter = 0;
boolean start = true;
while(counter != -1 && this.myMap.animalQuantity() > 0){//jesli zwierzakow nie ma to nie ma sensu uruchamiac petli, dzialamy do ostatniego dnia! (tzn. do dlugosci genomu)
if(!start) {
System.out.println("przed usuwaniem zwlok: ");
System.out.println(this.myMap);
if(!showJustDay){
this.observer.updateMap(0);
this.sleepNow(moveDelay);
}
this.myMap.removingCorpse();
if(!showJustDay){
this.sleepNow(moveDelay);
}
}
start = false;
if(!showJustDay){
this.observer.updateMap(1);
this.sleepNow(moveDelay);
}
//System.out.println("po usunieciu zwlok: ");
//System.out.println(this.myMap);
//przemieszczanie sie!!! ---------------------------------------------
ArrayList<Vector2d> originalVectorki= new ArrayList<>();
Set<Vector2d> keys = this.myMap.animals.keySet();
originalVectorki.addAll(keys);
originalVectorki.stream().forEach(vector->{
PriorityQueue<Animal> queue = ((GrassField)this.myMap).animals.get(vector);
while(!queue.isEmpty()) this.myMap.temporaryAnimalsArray.add(queue.poll());
((GrassField)this.myMap).animals.remove(vector);
while(this.myMap.temporaryAnimalsArray.size() > 0){
Animal animal = this.myMap.temporaryAnimalsArray.remove(this.myMap.temporaryAnimalsArray.size()-1);
if(!animal.moved){
int active = animal.activatedGen;
animal.nextActivatedGen(someMadness);
animal.move(new OptionsParser().parseOneOption(animal.gen.charAt(active)));//ta metoda z automatu dodaje do animals!
animal.moved = true;
//System.out.println(this.myMap);
}else{
this.myMap.addAnimal(animal.position,animal);
}
}
//this.observer.updateMap(1);
//this.sleepNow(500);
});
if(!showJustDay){
this.observer.updateMap(1);
this.sleepNow(moveDelay);
}
this.myMap.clearMovedValues();
// koniec funkcjonalnosci zwiazanej z przemieszczaniem sie!!------------------------
//System.out.println("po przemieszczeniu sie");
if(!showJustDay){
this.observer.updateMap(2);
this.sleepNow(moveDelay);
}
this.myMap.eatingTime();
if(!showJustDay){
this.observer.updateMap(2);
this.sleepNow(moveDelay);
this.observer.updateMap(3);
this.sleepNow(moveDelay);
}
int oldNumberOfAnimals = this.myMap.animalQuantity(); //jesli są nowe zwierzaki na mapie, to muszą przejść cały swoj genom!
this.myMap.reproducingTime();
counter = this.clearCounter(oldNumberOfAnimals,counter); // jesli pojawi sie nowe zwierze na mapie to musi wykonac caly swoj genom, wiec resetujemy counter;
// inne zwierzaki będą powtarzać swoje sekwencje.
if(!showJustDay){
this.observer.updateMap(3);
this.sleepNow(moveDelay);
this.observer.updateMap(5);
this.sleepNow(moveDelay);
}
this.myMap.createProperNumberOfGrass(-1);
if(!showJustDay){
this.observer.updateMap(5);
}
this.sleepNow(moveDelay);
this.observer.updateMap(4);
this.sleepNow(moveDelay);
this.myMap.aging();
if(!showJustDay){
this.sleepNow(moveDelay);
}
//System.out.println("-------INFO-----");
//this.myMap.printInfo();
//System.out.println(this.myMap);
//System.out.println("-------INFO END-----");
//System.out.println("Po wykonanych pracach, przed starzeniem sie:");
//System.out.println(this.myMap);
this.observer.updateMap(4);
counter++;
}
System.out.println("Ostateczny stan:");
//System.out.println(this.myMap);
//this.sleepNow(2000);
Platform.exit();
System.exit(0);
}
public void sleepNow(int time){
try{
Thread.sleep(time);
}catch (InterruptedException e) {
throw new RuntimeException(e + "Przerwano symulację");
}
}
public int clearCounter(int oldNumberOfAnimals,int counter){
if(this.myMap.animals.size() > oldNumberOfAnimals){
counter = 0;
}
return counter;
}
}
| Adam0s007/evolution-generator | src/main/java/evol/gen/SimulationEngine.java | 2,049 | // usunięcie martwych zwierząt z mapy, | line_comment | pl | package evol.gen;
import evol.gen.gui.App;
import javafx.application.Platform;
import java.util.*;
public class SimulationEngine implements IEngine,Runnable {
private final GrassField myMap;
//private App observer;
public int moveDelay = 300;
private final boolean isAppOpening;
public boolean someMadness = false;
public boolean showJustDay = false;
private App observer;
public SimulationEngine(GrassField map, int initAnimals,App app) {
this.myMap = map; //nasza kochana mapa
this.observer = app;
this.isAppOpening =true;
for(int i = 0; i < initAnimals;i++){
Vector2d newVec =((GrassField) this.myMap).getRandom(((GrassField)this.myMap).topRight);
Animal animal = new Animal(this.myMap, newVec);
this.myMap.place(animal);
}
System.out.println(myMap.toString());
}
@Override
public void run() {
// Symulacja każdego dnia składa się z poniższej sekwencji kroków:
// us<SUF>
// skręt i przemieszczenie każdego zwierzęcia,
// konsumpcja roślin na których pola weszły zwierzęta,
// rozmnażanie się najedzonych zwierząt znajdujących się na tym samym polu,
// wzrastanie nowych roślin na wybranych polach mapy.
//mamy listę zwierzątek; teraz musimy uzyskać informację o ich aktywowanym genie:
//w petli:
// tworzymy teraz listę aktywnych genów (animal.activatedGen)
//podaną listę aktywnych genów dodajemy do parsera, przeksztalci nam je w MoveDirection)
// zwierzątka się zaczynają poruszać (tutaj zajdzie duzo roznych akcji)
//warunek pętli: (poniewaz wiemy, ze kazdy zwierzak ma taką samą długość genomu, to wybierzmy jeden ze zwierzakow i dla niego robmy warunek)
if(!showJustDay){
this.observer.updateMap(0);
}
int counter = 0;
boolean start = true;
while(counter != -1 && this.myMap.animalQuantity() > 0){//jesli zwierzakow nie ma to nie ma sensu uruchamiac petli, dzialamy do ostatniego dnia! (tzn. do dlugosci genomu)
if(!start) {
System.out.println("przed usuwaniem zwlok: ");
System.out.println(this.myMap);
if(!showJustDay){
this.observer.updateMap(0);
this.sleepNow(moveDelay);
}
this.myMap.removingCorpse();
if(!showJustDay){
this.sleepNow(moveDelay);
}
}
start = false;
if(!showJustDay){
this.observer.updateMap(1);
this.sleepNow(moveDelay);
}
//System.out.println("po usunieciu zwlok: ");
//System.out.println(this.myMap);
//przemieszczanie sie!!! ---------------------------------------------
ArrayList<Vector2d> originalVectorki= new ArrayList<>();
Set<Vector2d> keys = this.myMap.animals.keySet();
originalVectorki.addAll(keys);
originalVectorki.stream().forEach(vector->{
PriorityQueue<Animal> queue = ((GrassField)this.myMap).animals.get(vector);
while(!queue.isEmpty()) this.myMap.temporaryAnimalsArray.add(queue.poll());
((GrassField)this.myMap).animals.remove(vector);
while(this.myMap.temporaryAnimalsArray.size() > 0){
Animal animal = this.myMap.temporaryAnimalsArray.remove(this.myMap.temporaryAnimalsArray.size()-1);
if(!animal.moved){
int active = animal.activatedGen;
animal.nextActivatedGen(someMadness);
animal.move(new OptionsParser().parseOneOption(animal.gen.charAt(active)));//ta metoda z automatu dodaje do animals!
animal.moved = true;
//System.out.println(this.myMap);
}else{
this.myMap.addAnimal(animal.position,animal);
}
}
//this.observer.updateMap(1);
//this.sleepNow(500);
});
if(!showJustDay){
this.observer.updateMap(1);
this.sleepNow(moveDelay);
}
this.myMap.clearMovedValues();
// koniec funkcjonalnosci zwiazanej z przemieszczaniem sie!!------------------------
//System.out.println("po przemieszczeniu sie");
if(!showJustDay){
this.observer.updateMap(2);
this.sleepNow(moveDelay);
}
this.myMap.eatingTime();
if(!showJustDay){
this.observer.updateMap(2);
this.sleepNow(moveDelay);
this.observer.updateMap(3);
this.sleepNow(moveDelay);
}
int oldNumberOfAnimals = this.myMap.animalQuantity(); //jesli są nowe zwierzaki na mapie, to muszą przejść cały swoj genom!
this.myMap.reproducingTime();
counter = this.clearCounter(oldNumberOfAnimals,counter); // jesli pojawi sie nowe zwierze na mapie to musi wykonac caly swoj genom, wiec resetujemy counter;
// inne zwierzaki będą powtarzać swoje sekwencje.
if(!showJustDay){
this.observer.updateMap(3);
this.sleepNow(moveDelay);
this.observer.updateMap(5);
this.sleepNow(moveDelay);
}
this.myMap.createProperNumberOfGrass(-1);
if(!showJustDay){
this.observer.updateMap(5);
}
this.sleepNow(moveDelay);
this.observer.updateMap(4);
this.sleepNow(moveDelay);
this.myMap.aging();
if(!showJustDay){
this.sleepNow(moveDelay);
}
//System.out.println("-------INFO-----");
//this.myMap.printInfo();
//System.out.println(this.myMap);
//System.out.println("-------INFO END-----");
//System.out.println("Po wykonanych pracach, przed starzeniem sie:");
//System.out.println(this.myMap);
this.observer.updateMap(4);
counter++;
}
System.out.println("Ostateczny stan:");
//System.out.println(this.myMap);
//this.sleepNow(2000);
Platform.exit();
System.exit(0);
}
public void sleepNow(int time){
try{
Thread.sleep(time);
}catch (InterruptedException e) {
throw new RuntimeException(e + "Przerwano symulację");
}
}
public int clearCounter(int oldNumberOfAnimals,int counter){
if(this.myMap.animals.size() > oldNumberOfAnimals){
counter = 0;
}
return counter;
}
}
|
127240_7 | package agh.ics.oop;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class AnimalTest {
@Test
void isAt() {
// IWorldMap map0 = new RectangularMap(4, 4);
// Vector2d position0 = new Vector2d(2, 2);
Animal tomek = new Animal();
assertTrue(tomek.isAt(new Vector2d(2,2)));
tomek.move(MoveDirection.BACKWARD);
assertTrue(tomek.isAt(new Vector2d(2,1)));
tomek.move(MoveDirection.BACKWARD);
assertTrue(tomek.isAt(new Vector2d(2,0)));
tomek.move(MoveDirection.BACKWARD); // SPRAWDZENIE CZY WYJEDZIE POZA MAPE!
assertFalse(tomek.isAt(new Vector2d(2,-1)));
tomek.move(MoveDirection.FORWARD);
tomek.move(MoveDirection.FORWARD);
tomek.move(MoveDirection.FORWARD);
tomek.move(MoveDirection.FORWARD); // 4 pozycje do przodu od (2,0)
assertTrue(tomek.isAt(new Vector2d(2,4)));
tomek.move(MoveDirection.FORWARD);
assertFalse(tomek.isAt(new Vector2d(2,5)));
tomek.move(MoveDirection.LEFT);
}
@Test
void getDirection(){
//getDirection()
Animal tomek = new Animal();
assertEquals(MapDirection.NORTH, tomek.getDirection());
tomek.move(MoveDirection.LEFT);
assertEquals(MapDirection.WEST, tomek.getDirection());
tomek.move(MoveDirection.LEFT);
assertEquals(MapDirection.SOUTH, tomek.getDirection());
tomek.move(MoveDirection.RIGHT);
assertEquals(MapDirection.WEST, tomek.getDirection());
tomek.move(MoveDirection.LEFT);
assertEquals(MapDirection.SOUTH, tomek.getDirection());
tomek.move(MoveDirection.LEFT);
assertEquals(MapDirection.EAST, tomek.getDirection());
}
@Test
void move() {
Animal grzesiek = new Animal();
assertEquals("(2,2) N", grzesiek.extendedToString());//pozycja defaultowa!
grzesiek.move(MoveDirection.BACKWARD);
assertEquals("(2,1) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.BACKWARD);
assertEquals("(2,0) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.BACKWARD); // SPRAWDZENIE CZY WYJEDZIE POZA MAPE!
assertEquals("(2,0) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(2,1) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(2,2) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.BACKWARD);
assertEquals("(2,1) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.RIGHT); //ZMIENIONA ORIENTACJA NA PRAWO! (kierunek wschodni)
assertEquals("(2,1) E",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD); //PRZEMIESZCZANIE SIE PRZY NOWEJ ORIENTACJI
assertEquals("(3,1) E",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(4,1) E",grzesiek.extendedToString());
grzesiek.move(MoveDirection.BACKWARD);
assertEquals("(3,1) E",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(4,1) E",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD); // SPRAWDZENIE CZY WYJEDZIE POZA MAPE!
assertEquals("(4,1) E",grzesiek.extendedToString());
grzesiek.move(MoveDirection.LEFT); //ZMIENIONA ORIENTACJA NA LEWO! (ponownie jedzie w kierunku polnocnym)
assertEquals("(4,1) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(4,2) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(4,3) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.BACKWARD);
assertEquals("(4,2) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(4,3) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(4,4) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD); // SPRAWDZENIE PRZY WYJEDZIE POZA MAPE!
assertEquals("(4,4) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD); // PONOWNE SPRAWDZENIE PRZY WYJEDZIE POZA MAPE!
assertEquals("(4,4) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.LEFT); // ZMIENIONA ORIENTACJA! Teraz w kierunku zachodnim
assertEquals("(4,4) W",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(3,4) W",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(2,4) W",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(1,4) W",grzesiek.extendedToString());
grzesiek.move(MoveDirection.BACKWARD);
assertEquals("(2,4) W",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(1,4) W",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(0,4) W",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD); // SPRAWDZENIE PRZY WYJEDZIE POZA MAPE!
assertEquals("(0,4) W",grzesiek.extendedToString());
grzesiek.move(MoveDirection.LEFT); // PONOWNIE ZMIENIONA ORIENTACJA! Teraz w kierunku poludniowym
assertEquals("(0,4) S",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(0,3) S",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(0,2) S",grzesiek.extendedToString());
grzesiek.move(MoveDirection.BACKWARD);
assertEquals("(0,3) S",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(0,2) S",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(0,1) S",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(0,0) S",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD); // SPRAWDZENIE PRZY WYJEDZIE POZA MAPE!
assertEquals("(0,0) S",grzesiek.extendedToString());
}
} | Adam0s007/programowanie-obiektowe | oolab/src/test/java/agh/ics/oop/AnimalTest.java | 2,211 | //ZMIENIONA ORIENTACJA NA PRAWO! (kierunek wschodni) | line_comment | pl | package agh.ics.oop;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class AnimalTest {
@Test
void isAt() {
// IWorldMap map0 = new RectangularMap(4, 4);
// Vector2d position0 = new Vector2d(2, 2);
Animal tomek = new Animal();
assertTrue(tomek.isAt(new Vector2d(2,2)));
tomek.move(MoveDirection.BACKWARD);
assertTrue(tomek.isAt(new Vector2d(2,1)));
tomek.move(MoveDirection.BACKWARD);
assertTrue(tomek.isAt(new Vector2d(2,0)));
tomek.move(MoveDirection.BACKWARD); // SPRAWDZENIE CZY WYJEDZIE POZA MAPE!
assertFalse(tomek.isAt(new Vector2d(2,-1)));
tomek.move(MoveDirection.FORWARD);
tomek.move(MoveDirection.FORWARD);
tomek.move(MoveDirection.FORWARD);
tomek.move(MoveDirection.FORWARD); // 4 pozycje do przodu od (2,0)
assertTrue(tomek.isAt(new Vector2d(2,4)));
tomek.move(MoveDirection.FORWARD);
assertFalse(tomek.isAt(new Vector2d(2,5)));
tomek.move(MoveDirection.LEFT);
}
@Test
void getDirection(){
//getDirection()
Animal tomek = new Animal();
assertEquals(MapDirection.NORTH, tomek.getDirection());
tomek.move(MoveDirection.LEFT);
assertEquals(MapDirection.WEST, tomek.getDirection());
tomek.move(MoveDirection.LEFT);
assertEquals(MapDirection.SOUTH, tomek.getDirection());
tomek.move(MoveDirection.RIGHT);
assertEquals(MapDirection.WEST, tomek.getDirection());
tomek.move(MoveDirection.LEFT);
assertEquals(MapDirection.SOUTH, tomek.getDirection());
tomek.move(MoveDirection.LEFT);
assertEquals(MapDirection.EAST, tomek.getDirection());
}
@Test
void move() {
Animal grzesiek = new Animal();
assertEquals("(2,2) N", grzesiek.extendedToString());//pozycja defaultowa!
grzesiek.move(MoveDirection.BACKWARD);
assertEquals("(2,1) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.BACKWARD);
assertEquals("(2,0) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.BACKWARD); // SPRAWDZENIE CZY WYJEDZIE POZA MAPE!
assertEquals("(2,0) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(2,1) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(2,2) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.BACKWARD);
assertEquals("(2,1) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.RIGHT); //ZM<SUF>
assertEquals("(2,1) E",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD); //PRZEMIESZCZANIE SIE PRZY NOWEJ ORIENTACJI
assertEquals("(3,1) E",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(4,1) E",grzesiek.extendedToString());
grzesiek.move(MoveDirection.BACKWARD);
assertEquals("(3,1) E",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(4,1) E",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD); // SPRAWDZENIE CZY WYJEDZIE POZA MAPE!
assertEquals("(4,1) E",grzesiek.extendedToString());
grzesiek.move(MoveDirection.LEFT); //ZMIENIONA ORIENTACJA NA LEWO! (ponownie jedzie w kierunku polnocnym)
assertEquals("(4,1) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(4,2) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(4,3) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.BACKWARD);
assertEquals("(4,2) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(4,3) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(4,4) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD); // SPRAWDZENIE PRZY WYJEDZIE POZA MAPE!
assertEquals("(4,4) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD); // PONOWNE SPRAWDZENIE PRZY WYJEDZIE POZA MAPE!
assertEquals("(4,4) N",grzesiek.extendedToString());
grzesiek.move(MoveDirection.LEFT); // ZMIENIONA ORIENTACJA! Teraz w kierunku zachodnim
assertEquals("(4,4) W",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(3,4) W",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(2,4) W",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(1,4) W",grzesiek.extendedToString());
grzesiek.move(MoveDirection.BACKWARD);
assertEquals("(2,4) W",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(1,4) W",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(0,4) W",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD); // SPRAWDZENIE PRZY WYJEDZIE POZA MAPE!
assertEquals("(0,4) W",grzesiek.extendedToString());
grzesiek.move(MoveDirection.LEFT); // PONOWNIE ZMIENIONA ORIENTACJA! Teraz w kierunku poludniowym
assertEquals("(0,4) S",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(0,3) S",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(0,2) S",grzesiek.extendedToString());
grzesiek.move(MoveDirection.BACKWARD);
assertEquals("(0,3) S",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(0,2) S",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(0,1) S",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD);
assertEquals("(0,0) S",grzesiek.extendedToString());
grzesiek.move(MoveDirection.FORWARD); // SPRAWDZENIE PRZY WYJEDZIE POZA MAPE!
assertEquals("(0,0) S",grzesiek.extendedToString());
}
} |
6263_3 | package agh.ics.oop;
import java.util.Comparator;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
public class MapBoundary implements IPositionChangeObserver {
private final SortedSet<Vector2d> xAxis;
private final SortedSet<Vector2d> yAxis;
public MapBoundary() {
this.xAxis = new TreeSet<>(Comparator.comparing(Vector2d::getX));
this.yAxis = new TreeSet<>(Comparator.comparing(Vector2d::getY));
}
public void addElementToAxes(IMapObject object) {
xAxis.add(object.getPosition());
yAxis.add(object.getPosition());
}
public SortedSet<Vector2d> getXAxis() {
return xAxis;
}
public SortedSet<Vector2d> getYAxis() {
return yAxis;
}
public void repairAxes(Map<Vector2d, IMapObject> objectPositions) {
for (Vector2d vector2d : objectPositions.keySet()) {
xAxis.add(vector2d);
yAxis.add(vector2d);
}
}
public void removePosition(Vector2d oldPosition) {
xAxis.remove(oldPosition);
yAxis.remove(oldPosition);
}
// dodaje tylko 1 x i jesli sie przesunie animala no to się robi problem, bo nie ma trawnika co tam był
@Override
public void positionChanged(Vector2d oldPosition, Vector2d newPosition) {
removePosition(oldPosition);
xAxis.add(newPosition);
yAxis.add(newPosition);
}
// te dodatkowe funkcje rozwiązują powyższy problem trawnika który nie jest uwzględniany jeśli mnie go animal, ale na
// niego nie wejdzie (np animal idzie po x od 5 do 1 i na wysokosci y=3, a trawa jest na y=5. Jeśli animal przejdzie
// z (3,3) na (2,3) to trawy nie będzie w liscie
}
| Adam3004/programowanie-obiektowe | lab1/oolab/src/main/java/agh/ics/oop/MapBoundary.java | 573 | // z (3,3) na (2,3) to trawy nie będzie w liscie | line_comment | pl | package agh.ics.oop;
import java.util.Comparator;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
public class MapBoundary implements IPositionChangeObserver {
private final SortedSet<Vector2d> xAxis;
private final SortedSet<Vector2d> yAxis;
public MapBoundary() {
this.xAxis = new TreeSet<>(Comparator.comparing(Vector2d::getX));
this.yAxis = new TreeSet<>(Comparator.comparing(Vector2d::getY));
}
public void addElementToAxes(IMapObject object) {
xAxis.add(object.getPosition());
yAxis.add(object.getPosition());
}
public SortedSet<Vector2d> getXAxis() {
return xAxis;
}
public SortedSet<Vector2d> getYAxis() {
return yAxis;
}
public void repairAxes(Map<Vector2d, IMapObject> objectPositions) {
for (Vector2d vector2d : objectPositions.keySet()) {
xAxis.add(vector2d);
yAxis.add(vector2d);
}
}
public void removePosition(Vector2d oldPosition) {
xAxis.remove(oldPosition);
yAxis.remove(oldPosition);
}
// dodaje tylko 1 x i jesli sie przesunie animala no to się robi problem, bo nie ma trawnika co tam był
@Override
public void positionChanged(Vector2d oldPosition, Vector2d newPosition) {
removePosition(oldPosition);
xAxis.add(newPosition);
yAxis.add(newPosition);
}
// te dodatkowe funkcje rozwiązują powyższy problem trawnika który nie jest uwzględniany jeśli mnie go animal, ale na
// niego nie wejdzie (np animal idzie po x od 5 do 1 i na wysokosci y=3, a trawa jest na y=5. Jeśli animal przejdzie
// z <SUF>
}
|
93137_4 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pl.waw.frej;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;
import javax.swing.JPanel;
/**
*
* @author adam
*/
public class SiatkaPanel extends JPanel {
private int gridWidth;
private int gridSize;
private ArrayList<Point> line = new ArrayList<>();
private ArrayList<Point> points = new ArrayList<>();
private KrzywaDyskretna interpolująca;
public SiatkaPanel() {
this.gridWidth = 20;
this.gridSize = 20;
this.interpolująca = new KrzywaDyskretna(gridWidth, gridSize);
}
public int getGridSize() {
return gridSize;
}
public void setGridSize(int gridSize) {
this.gridSize = gridSize;
}
public ArrayList<Point> getPoints() {
return points;
}
public void setPoints(ArrayList<Point> points) {
clearPoints();
this.points = points;
}
public void setInterpolująca(KrzywaDyskretna krzywa) {
interpolująca = krzywa;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); //To change body of generated methods, choose Tools | Templates.
drawGrid(g);
drawLine(g);
drawPoints(g);
drawRedLines(g);
drawInterpolująca(g);
}
public void addPointToLine(Point point) {
line.add(point);
}
public void setGridWidth(int gridWidth) {
this.gridWidth = gridWidth;
}
private void clearLine() {
boolean pointCrosedXLine;
boolean pointCrosedYLine;
int prevLineNumberX = 0;
int lineNumberX;
int prevLineNumberY = 0;
int lineNumberY;
for (Point p : line) {
lineNumberX = p.x;
pointCrosedXLine = Math.abs(lineNumberX - prevLineNumberX) >= gridWidth;
lineNumberY = p.y;
pointCrosedYLine = Math.abs(lineNumberY - prevLineNumberY) >= gridWidth;
boolean pointCrossedLine = pointCrosedYLine || pointCrosedXLine;
boolean pointOnTheGrid = p.x <= gridSize * gridWidth && p.y <= gridSize * gridWidth;
if (pointCrossedLine && pointOnTheGrid) {
Point punkt = snapToGrid(p);
prevLineNumberY = punkt.y;
prevLineNumberX = punkt.x;
points.add(punkt);
}
}
line.clear();
}
private void drawGrid(Graphics g) {
for (int i = 0; i <= gridSize * gridWidth; i += gridWidth) {
g.drawLine(i, 0, i, gridSize * gridWidth);
}
for (int i = 0; i <= gridSize * gridWidth; i += gridWidth) {
g.drawLine(0, i, gridSize * gridWidth, i);
}
}
private void drawLine(Graphics g) {
for (int i = 0; i < line.size() - 2; i++) {
Point p1 = line.get(i);
Point p2 = line.get(i + 1);
g.drawLine(p1.x, p1.y, p2.x, p2.y);
}
}
private void drawPoints(Graphics g) {
g.setColor(Color.red);
for (Point p : points) {
g.fillOval(p.x - 5, p.y - 5, 10, 10);
}
}
private void drawRedLines(Graphics g) {
g.setColor(Color.red);
for (int i = 0; i < points.size() - 1; i++) {
g.drawLine(points.get(i).x, points.get(i).y, points.get(i + 1).x, points.get(i + 1).y);
}
}
public void drawInterpolująca(Graphics g) {
g.setColor(Color.blue);
for (Point p : interpolująca.getPoints()) {
g.fillOval(p.x - 5, p.y - 5, 10, 10);
}
//g.setColor(Color.decode("0x3BBBD3"));
for (int i = 0; i < interpolująca.getPoints().size() - 1; i++) {
Point obecny = interpolująca.getPoints().get(i);
Point następny = interpolująca.getPoints().get(i + 1);
double a = (double) (następny.y - obecny.y) / (double) (następny.x - obecny.x);
double b = obecny.y - a * obecny.x;
boolean pointCrosedXLine;
boolean pointCrosedYLine;
boolean warunek = true;
int prevLineNumberX = 0;
int lineNumberX;
int prevLineNumberY = 0;
int lineNumberY;
//for (int j = obecny.x; j <= następny.x; j++)
int j = obecny.x;
int k = obecny.y;
while (warunek) {
int y = (int) Math.round(a * j + b);
if (obecny.x == następny.x) y=k;
lineNumberX = j;
pointCrosedXLine = Math.abs(lineNumberX - prevLineNumberX) >= gridWidth;
lineNumberY = y;
pointCrosedYLine = Math.abs(lineNumberY - prevLineNumberY) >= gridWidth;
if (pointCrosedYLine || pointCrosedXLine) {
Point punkt = snapToGrid(new Point(j, y));
prevLineNumberY = punkt.y;
prevLineNumberX = punkt.x;
g.fillOval(punkt.x - 3, punkt.y - 3, 6, 6);
}
if (obecny.x < następny.x) {
warunek = j <= następny.x;
j++;
}
if (obecny.x > następny.x) {
warunek = j >= następny.x;
j--;
}
if (obecny.x == następny.x) {
if (obecny.y < następny.y) {
warunek = k <= następny.y;
k++;
} else {
warunek = k >= następny.y;
k--;
}
}
}
}
}
private Point snapToGrid(Point p) {
double halfPoint = gridWidth / 2.0;
int xDetail = p.x % gridWidth;
int pointX;
if (xDetail <= halfPoint) {
pointX = p.x - xDetail;
} else {
pointX = p.x + (gridWidth - xDetail);
}
int yDetail = p.y % gridWidth;
int pointY;
if (yDetail <= halfPoint) {
pointY = p.y - yDetail;
} else {
pointY = p.y + (gridWidth - yDetail);
}
return new Point(pointX, pointY);
}
void clearPoints() {
points.clear();
interpolująca = new KrzywaDyskretna(gridWidth, gridSize);
}
KrzywaDyskretna getKrzywa() {
clearLine();
return new KrzywaDyskretna(points, gridWidth, gridSize);
}
}
| AdamFrej/EgzaminAPO | EgzaminZAPO/src/pl/waw/frej/SiatkaPanel.java | 2,115 | //for (int j = obecny.x; j <= następny.x; j++) | line_comment | pl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pl.waw.frej;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;
import javax.swing.JPanel;
/**
*
* @author adam
*/
public class SiatkaPanel extends JPanel {
private int gridWidth;
private int gridSize;
private ArrayList<Point> line = new ArrayList<>();
private ArrayList<Point> points = new ArrayList<>();
private KrzywaDyskretna interpolująca;
public SiatkaPanel() {
this.gridWidth = 20;
this.gridSize = 20;
this.interpolująca = new KrzywaDyskretna(gridWidth, gridSize);
}
public int getGridSize() {
return gridSize;
}
public void setGridSize(int gridSize) {
this.gridSize = gridSize;
}
public ArrayList<Point> getPoints() {
return points;
}
public void setPoints(ArrayList<Point> points) {
clearPoints();
this.points = points;
}
public void setInterpolująca(KrzywaDyskretna krzywa) {
interpolująca = krzywa;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); //To change body of generated methods, choose Tools | Templates.
drawGrid(g);
drawLine(g);
drawPoints(g);
drawRedLines(g);
drawInterpolująca(g);
}
public void addPointToLine(Point point) {
line.add(point);
}
public void setGridWidth(int gridWidth) {
this.gridWidth = gridWidth;
}
private void clearLine() {
boolean pointCrosedXLine;
boolean pointCrosedYLine;
int prevLineNumberX = 0;
int lineNumberX;
int prevLineNumberY = 0;
int lineNumberY;
for (Point p : line) {
lineNumberX = p.x;
pointCrosedXLine = Math.abs(lineNumberX - prevLineNumberX) >= gridWidth;
lineNumberY = p.y;
pointCrosedYLine = Math.abs(lineNumberY - prevLineNumberY) >= gridWidth;
boolean pointCrossedLine = pointCrosedYLine || pointCrosedXLine;
boolean pointOnTheGrid = p.x <= gridSize * gridWidth && p.y <= gridSize * gridWidth;
if (pointCrossedLine && pointOnTheGrid) {
Point punkt = snapToGrid(p);
prevLineNumberY = punkt.y;
prevLineNumberX = punkt.x;
points.add(punkt);
}
}
line.clear();
}
private void drawGrid(Graphics g) {
for (int i = 0; i <= gridSize * gridWidth; i += gridWidth) {
g.drawLine(i, 0, i, gridSize * gridWidth);
}
for (int i = 0; i <= gridSize * gridWidth; i += gridWidth) {
g.drawLine(0, i, gridSize * gridWidth, i);
}
}
private void drawLine(Graphics g) {
for (int i = 0; i < line.size() - 2; i++) {
Point p1 = line.get(i);
Point p2 = line.get(i + 1);
g.drawLine(p1.x, p1.y, p2.x, p2.y);
}
}
private void drawPoints(Graphics g) {
g.setColor(Color.red);
for (Point p : points) {
g.fillOval(p.x - 5, p.y - 5, 10, 10);
}
}
private void drawRedLines(Graphics g) {
g.setColor(Color.red);
for (int i = 0; i < points.size() - 1; i++) {
g.drawLine(points.get(i).x, points.get(i).y, points.get(i + 1).x, points.get(i + 1).y);
}
}
public void drawInterpolująca(Graphics g) {
g.setColor(Color.blue);
for (Point p : interpolująca.getPoints()) {
g.fillOval(p.x - 5, p.y - 5, 10, 10);
}
//g.setColor(Color.decode("0x3BBBD3"));
for (int i = 0; i < interpolująca.getPoints().size() - 1; i++) {
Point obecny = interpolująca.getPoints().get(i);
Point następny = interpolująca.getPoints().get(i + 1);
double a = (double) (następny.y - obecny.y) / (double) (następny.x - obecny.x);
double b = obecny.y - a * obecny.x;
boolean pointCrosedXLine;
boolean pointCrosedYLine;
boolean warunek = true;
int prevLineNumberX = 0;
int lineNumberX;
int prevLineNumberY = 0;
int lineNumberY;
//fo<SUF>
int j = obecny.x;
int k = obecny.y;
while (warunek) {
int y = (int) Math.round(a * j + b);
if (obecny.x == następny.x) y=k;
lineNumberX = j;
pointCrosedXLine = Math.abs(lineNumberX - prevLineNumberX) >= gridWidth;
lineNumberY = y;
pointCrosedYLine = Math.abs(lineNumberY - prevLineNumberY) >= gridWidth;
if (pointCrosedYLine || pointCrosedXLine) {
Point punkt = snapToGrid(new Point(j, y));
prevLineNumberY = punkt.y;
prevLineNumberX = punkt.x;
g.fillOval(punkt.x - 3, punkt.y - 3, 6, 6);
}
if (obecny.x < następny.x) {
warunek = j <= następny.x;
j++;
}
if (obecny.x > następny.x) {
warunek = j >= następny.x;
j--;
}
if (obecny.x == następny.x) {
if (obecny.y < następny.y) {
warunek = k <= następny.y;
k++;
} else {
warunek = k >= następny.y;
k--;
}
}
}
}
}
private Point snapToGrid(Point p) {
double halfPoint = gridWidth / 2.0;
int xDetail = p.x % gridWidth;
int pointX;
if (xDetail <= halfPoint) {
pointX = p.x - xDetail;
} else {
pointX = p.x + (gridWidth - xDetail);
}
int yDetail = p.y % gridWidth;
int pointY;
if (yDetail <= halfPoint) {
pointY = p.y - yDetail;
} else {
pointY = p.y + (gridWidth - yDetail);
}
return new Point(pointX, pointY);
}
void clearPoints() {
points.clear();
interpolująca = new KrzywaDyskretna(gridWidth, gridSize);
}
KrzywaDyskretna getKrzywa() {
clearLine();
return new KrzywaDyskretna(points, gridWidth, gridSize);
}
}
|
73457_0 | package sample;
import java.sql.*;
import java.time.LocalDate;
public class Baza {
public Connection connect() throws SQLException { //tworzy połączenie
Connection connection = DriverManager.getConnection("jdbc:hsqldb:mem:mymemdb", "SA", "");
return connection;
}
public void wedkarzeTabela(Connection connection) throws SQLException { //tworzy tabele w bazie
Statement s = connection.createStatement();
s.execute("CREATE TABLE FANATYCY_WEDKARSTWA (ID INTEGER IDENTITY PRIMARY KEY,IMIE varchar(255), " +
"NAZWISKO varchar(255), " +
"CZY_NALEZY bit," +
"DATA_UZYSKANIA date)");
s.execute("CREATE TABLE ZLOWIONE_RYBY (ID INTEGER IDENTITY PRIMARY KEY, GATUNEK varchar(255), " +
"ROZMIAR float, " +
"CZY_ZWERYFIKOWANA bit," +
"DATA_ZLOWIENIA date,"+
"WEDKARZ INT)");
}
public Person addPerson(String imie, String nazwisko, LocalDate data, Boolean czyNalezy, Connection connection){ //dodaje fanatyków do bazy i zwraca obiek Person
Person person;
int ID = 0;
try {
PreparedStatement statement = connection.prepareStatement("INSERT INTO FANATYCY_WEDKARSTWA (IMIE,NAZWISKO,CZY_NALEZY,DATA_UZYSKANIA) VALUES (?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
statement.setString(1,imie);
statement.setString(2,nazwisko);
statement.setBoolean(3, czyNalezy);
statement.setDate(4, Date.valueOf(data));
statement.execute();
ResultSet rs = statement.getGeneratedKeys();
if (rs.next()) {
ID = Math.toIntExact(rs.getLong(1));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
person = new Person(imie,nazwisko,data,czyNalezy,ID);
return person;
}
}
| AdamKasinski/Programowanie-aplikacji-Java | zad2/Baza.java | 628 | //tworzy połączenie
| line_comment | pl | package sample;
import java.sql.*;
import java.time.LocalDate;
public class Baza {
public Connection connect() throws SQLException { //tw<SUF>
Connection connection = DriverManager.getConnection("jdbc:hsqldb:mem:mymemdb", "SA", "");
return connection;
}
public void wedkarzeTabela(Connection connection) throws SQLException { //tworzy tabele w bazie
Statement s = connection.createStatement();
s.execute("CREATE TABLE FANATYCY_WEDKARSTWA (ID INTEGER IDENTITY PRIMARY KEY,IMIE varchar(255), " +
"NAZWISKO varchar(255), " +
"CZY_NALEZY bit," +
"DATA_UZYSKANIA date)");
s.execute("CREATE TABLE ZLOWIONE_RYBY (ID INTEGER IDENTITY PRIMARY KEY, GATUNEK varchar(255), " +
"ROZMIAR float, " +
"CZY_ZWERYFIKOWANA bit," +
"DATA_ZLOWIENIA date,"+
"WEDKARZ INT)");
}
public Person addPerson(String imie, String nazwisko, LocalDate data, Boolean czyNalezy, Connection connection){ //dodaje fanatyków do bazy i zwraca obiek Person
Person person;
int ID = 0;
try {
PreparedStatement statement = connection.prepareStatement("INSERT INTO FANATYCY_WEDKARSTWA (IMIE,NAZWISKO,CZY_NALEZY,DATA_UZYSKANIA) VALUES (?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
statement.setString(1,imie);
statement.setString(2,nazwisko);
statement.setBoolean(3, czyNalezy);
statement.setDate(4, Date.valueOf(data));
statement.execute();
ResultSet rs = statement.getGeneratedKeys();
if (rs.next()) {
ID = Math.toIntExact(rs.getLong(1));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
person = new Person(imie,nazwisko,data,czyNalezy,ID);
return person;
}
}
|
18879_0 | package com.example.watercheckapp.alarms;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
import com.example.watercheckapp.DrawerBaseActivity;
import com.example.watercheckapp.JSONMethods;
import com.example.watercheckapp.R;
import com.example.watercheckapp.databinding.ActivityAlarmBinding;
import com.example.watercheckapp.databinding.ActivityHomeBinding;
import com.example.watercheckapp.home.HomeActivity;
import com.example.watercheckapp.home.MyHomeService;
import java.util.ArrayList;
public class AlarmActivity extends DrawerBaseActivity {
ActivityAlarmBinding alarmBinding;
ArrayList<String> localoccurredAlarmsList = new ArrayList<>();
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
alarmBinding = ActivityAlarmBinding.inflate(getLayoutInflater());
setContentView(alarmBinding.getRoot());
allocateActivityTitle("Alarms");
MyHomeService.checkRedundance();
//TODO: wyswietlanie info o alarmie + zapisywanie na stałe (pewnie do plik)
// occuredAlarmsList.add("UWAGA UWAGA ");
// occuredAlarmsList.add("UWAGA UWAGA 2222 ");
// occuredAlarmsList.add("UWAGA UWAGA 2222 ");
// occuredAlarmsList.add("UWAGA UWAGA 2222 ");
// occuredAlarmsList.add("UWAGA UWAGA 2222 ");
// occuredAlarmsList.add("UWAGA UWAGA 2222 ");
// occuredAlarmsList.add("UWAGA UWAGA 2222 ");
// occuredAlarmsList.add("UWAGA UWAGA 2222 ");
// occuredAlarmsList.add("UWAGA UWAGA 2222 ");
// occuredAlarmsList.add("UWAGA UWAGA 2222 ");
// occuredAlarmsList.add("UWAGA UWAGA 2222 ");
localoccurredAlarmsList = JSONMethods.occurredAlarmsList;
listView = (ListView) findViewById(R.id.alarmsListView);
AlarmListAdapter alarmListAdapter = new AlarmListAdapter(getApplicationContext(),localoccurredAlarmsList);
listView.setAdapter(alarmListAdapter);
}
@Override
protected void onStop() {
super.onStop();
//localoccurredAlarmsList.clear();
}
} | AdamPomorski/WaterCheckApp | application/app/src/main/java/com/example/watercheckapp/alarms/AlarmActivity.java | 769 | //TODO: wyswietlanie info o alarmie + zapisywanie na stałe (pewnie do plik) | line_comment | pl | package com.example.watercheckapp.alarms;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
import com.example.watercheckapp.DrawerBaseActivity;
import com.example.watercheckapp.JSONMethods;
import com.example.watercheckapp.R;
import com.example.watercheckapp.databinding.ActivityAlarmBinding;
import com.example.watercheckapp.databinding.ActivityHomeBinding;
import com.example.watercheckapp.home.HomeActivity;
import com.example.watercheckapp.home.MyHomeService;
import java.util.ArrayList;
public class AlarmActivity extends DrawerBaseActivity {
ActivityAlarmBinding alarmBinding;
ArrayList<String> localoccurredAlarmsList = new ArrayList<>();
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
alarmBinding = ActivityAlarmBinding.inflate(getLayoutInflater());
setContentView(alarmBinding.getRoot());
allocateActivityTitle("Alarms");
MyHomeService.checkRedundance();
//TO<SUF>
// occuredAlarmsList.add("UWAGA UWAGA ");
// occuredAlarmsList.add("UWAGA UWAGA 2222 ");
// occuredAlarmsList.add("UWAGA UWAGA 2222 ");
// occuredAlarmsList.add("UWAGA UWAGA 2222 ");
// occuredAlarmsList.add("UWAGA UWAGA 2222 ");
// occuredAlarmsList.add("UWAGA UWAGA 2222 ");
// occuredAlarmsList.add("UWAGA UWAGA 2222 ");
// occuredAlarmsList.add("UWAGA UWAGA 2222 ");
// occuredAlarmsList.add("UWAGA UWAGA 2222 ");
// occuredAlarmsList.add("UWAGA UWAGA 2222 ");
// occuredAlarmsList.add("UWAGA UWAGA 2222 ");
localoccurredAlarmsList = JSONMethods.occurredAlarmsList;
listView = (ListView) findViewById(R.id.alarmsListView);
AlarmListAdapter alarmListAdapter = new AlarmListAdapter(getApplicationContext(),localoccurredAlarmsList);
listView.setAdapter(alarmListAdapter);
}
@Override
protected void onStop() {
super.onStop();
//localoccurredAlarmsList.clear();
}
} |
42206_21 | package ap1.src;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Ap1 {
public static void main(String[] args) {
int[] nums = new int[] {1, 3, 4};
Boolean result = scoresIncreasing(nums);
System.out.println("Result: " + result);
}
/**
* Given an array of scores, return true if each score is equal or greater than the one before.
* The array will be length 2 or more.
*
* scoresIncreasing([1, 3, 4]) → true
* scoresIncreasing([1, 3, 2]) → false
* scoresIncreasing([1, 1, 4]) → true
*
* @param scores
* @return
*/
public static boolean scoresIncreasing(int[] scores) {
boolean increase = false;
int i = 0;
do{
increase = scores[i + 1] >= scores[i];
i++;
} while(i < scores.length - 1 && increase);
if(increase){
return scores[i] >= scores[i -1];
}
return increase;
}
/**
* Given an array of scores, return true if there are scores of 100 next to each other in the array.
* The array length will be at least 2.
*
* scores100([1, 100, 100]) → true
* scores100([1, 100, 99, 100]) → false
* scores100([100, 1, 100, 100]) → true
*
* @param scores
* @return
*/
public boolean scores100(int[] scores) {
boolean foundScores100 = false;
int i = 0;
do{
if(scores[i] == 100 && scores[i + 1] == 100){
foundScores100 = true;
}
i++;
} while(!foundScores100 && i < scores.length - 1);
return foundScores100;
}
/**
* Given an array of scores sorted in increasing order, return true if the array contains 3 adjacent scores
* that differ from each other by at most 2, such as with {3, 4, 5} or {3, 5, 5}.
*
* scoresClump([3, 4, 5]) → true
* scoresClump([3, 4, 6]) → false
* scoresClump([1, 3, 5, 5]) → true
*
* @param scores
* @return
*/
public boolean scoresClump(int[] scores) {
if(scores.length < 3){
return false;
}
boolean isClump = false;
int i = 0;
do{
if(scores[i + 2] - scores[i] <= 2){
isClump = true;
}
i++;
} while(i < scores.length - 2 && !isClump);
return isClump;
}
/**
* Given an array of scores, compute the int average of the first half and the second half,
* and return whichever is larger. We'll say that the second half begins at index length/2.
* The array length will be at least 2. To practice decomposition, write a separate helper method
* int average(int[] scores, int start, int end) { which computes the average of the elements
* between indexes start..end. Call your helper method twice to implement scoresAverage().
* Write your helper method after your scoresAverage() method in the JavaBat text area.
* Normally you would compute averages with doubles, but here we use ints so the expected results are exact.
*
* scoresAverage([2, 2, 4, 4]) → 4
* scoresAverage([4, 4, 4, 2, 2, 2]) → 4
* scoresAverage([3, 4, 5, 1, 2, 3]) → 4
*
* @param scores
* @return
*/
public int scoresAverage(int[] scores) {
return Math.max(average(scores, 0, (scores.length / 2) - 1), average(scores, (scores.length / 2), scores.length - 1));
}
private int average(int[] scores, int startIndex, int endIndex){
int sum = 0;
int counter = 0;
for(int i = startIndex; i <= endIndex; i++){
sum += scores[i];
counter++;
}
return sum / counter;
}
/**
* Given an array of strings, return the count of the number of strings with the given length.
*
* wordsCount(["a", "bb", "b", "ccc"], 1) → 2
* wordsCount(["a", "bb", "b", "ccc"], 3) → 1
* wordsCount(["a", "bb", "b", "ccc"], 4) → 0
*
* @param words
* @param len
* @return
*/
public int wordsCount(String[] words, int len) {
if(words.length == 0){
return 0;
}
int[] lengthWector = new int[words.length];
for(int i = 0; i < words.length; i++){
lengthWector[i] = words[i].length();
}
int counter = 0;
for(int i = 0; i < words.length; i++){
if(lengthWector[i] == len){
counter++;
}
}
return counter;
}
/**
* Given an array of strings, return a new array containing the first N strings. N will be in the range 1..length.
*
* wordsFront(["a", "b", "c", "d"], 1) → ["a"]
* wordsFront(["a", "b", "c", "d"], 2) → ["a", "b"]
* wordsFront(["a", "b", "c", "d"], 3) → ["a", "b", "c"]
*
* @param words
* @param n
* @return
*/
public String[] wordsFront(String[] words, int n) {
if(words.length == 1 && n == 1){
return words;
}
String[] newWords = new String[n];
for(int i = 0; i < n; i++){
newWords[i] = words[i];
}
return newWords;
}
/**
* Given an array of strings, return a new List (e.g. an ArrayList) where all the strings of the given length
* are omitted. See wordsWithout() below which is more difficult because it uses arrays.
*
* wordsWithoutList(["a", "bb", "b", "ccc"], 1) → ["bb", "ccc"]
* wordsWithoutList(["a", "bb", "b", "ccc"], 3) → ["a", "bb", "b"]
* wordsWithoutList(["a", "bb", "b", "ccc"], 4) → ["a", "bb", "b", "ccc"]
*
* @param words
* @param len
* @return
*/
public List wordsWithoutList(String[] words, int len) {
List<String> returnList = new ArrayList<>();
if(words.length == 0){
return returnList;
}
for(int i = 0; i < words.length; i++){
if(words[i].length() != len){
returnList.add(words[i]);
}
}
return returnList;
}
/**
* Given a positive int n, return true if it contains a 1 digit. Note: use % to get the rightmost digit,
* and / to discard the rightmost digit.
*
* hasOne(10) → true
* hasOne(22) → false
* hasOne(220) → false
*
* @param n
* @return
*/
public boolean hasOne(int n) {
if(n == 1){
return true;
}
boolean has1 = false;
int nn = n;
int remainder = 0;
do{
remainder = nn%10;
nn = nn / 10;
if(remainder == 1 || nn == 1){
has1 = true;
}
} while(!has1 && nn > 10);
return has1;
}
/**
* We'll say that a positive int divides itself if every digit in the number divides into the number evenly.
* So for example 128 divides itself since 1, 2, and 8 all divide into 128 evenly.
* We'll say that 0 does not divide into anything evenly, so no number with a 0 digit divides itself.
* Note: use % to get the rightmost digit, and / to discard the rightmost digit.
*
* dividesSelf(128) → true
* dividesSelf(12) → true
* dividesSelf(120) → false
*
* @param n
* @return
*/
public boolean dividesSelf(int n) {
if(n == 0 || n % 10 == 0){
return false;
}
if(n < 10){
return true;
}
boolean digitPass = true;
int nn = n;
int remainder = 0;
do{
remainder = nn % 10;
nn = nn / 10;
digitPass = checkDigit(n, remainder);
} while(nn > 10 && digitPass);
return digitPass && (n % nn == 0);
}
private boolean checkDigit(int n, int remainder){
if(remainder == 0){
return false;
}
return n % remainder == 0;
}
/**
* Given an array of positive ints, return a new array of length "count" containing the first even numbers
* from the original array. The original array will contain at least "count" even numbers.
*
* copyEvens([3, 2, 4, 5, 8], 2) → [2, 4]
* copyEvens([3, 2, 4, 5, 8], 3) → [2, 4, 8]
* copyEvens([6, 1, 2, 4, 5, 8], 3) → [6, 2, 4]
*
* @param nums
* @param count
* @return
*/
public int[] copyEvens(int[] nums, int count) {
int[] newNums = new int[nums.length];
if(count == 0){
return newNums;
}
Arrays.fill(newNums, -1);
int j = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] % 2 == 0){
newNums[j] = nums[i];
j++;
}
}
int[] copied = new int[count];
copied = Arrays.copyOfRange(newNums, 0, count);
return copied;
}
/**
* We'll say that a positive int n is "endy" if it is in the range 0..10 or 90..100 (inclusive).
* Given an array of positive ints, return a new array of length "count" containing the first endy numbers
* from the original array. Decompose out a separate isEndy(int n) method to test if a number is endy.
* The original array will contain at least "count" endy numbers.
*
* copyEndy([9, 11, 90, 22, 6], 2) → [9, 90]
* copyEndy([9, 11, 90, 22, 6], 3) → [9, 90, 6]
* copyEndy([12, 1, 1, 13, 0, 20], 2) → [1, 1]
*
* @param nums
* @param count
* @return
*/
public int[] copyEndy(int[] nums, int count) {
int[] endies = new int[nums.length];
if(nums.length == 0){
return endies;
}
Arrays.fill(endies, -1);
int j = 0;
for(int i = 0; i < nums.length; i++){
if(isEndy(nums[i])){
endies[j] = nums[i];
j++;
}
}
j = 0;
int[] arrayOfEndyNumbers = new int[count];
arrayOfEndyNumbers = Arrays.copyOfRange(endies, 0, count);
return arrayOfEndyNumbers;
}
private boolean isEndy(int number){
if((number >= 0 && number <= 10) || (number >= 90 && number <= 100)){
return true;
}
else {
return false;
}
}
/**
* Given 2 arrays that are the same length containing strings, compare the 1st string in one array to the 1st string
* in the other array, the 2nd to the 2nd and so on. Count the number of times that the 2 strings are non-empty
* and start with the same char. The strings may be any length, including 0.
*
* matchUp(["aa", "bb", "cc"], ["aaa", "xx", "bb"]) → 1
* matchUp(["aa", "bb", "cc"], ["aaa", "b", "bb"]) → 2
* matchUp(["aa", "bb", "cc"], ["", "", "ccc"]) → 1
*
* @param a
* @param b
* @return
*/
public int matchUp(String[] a, String[] b) {
if(a.length == 0){
return 0;
}
int counter = 0;
for(int i = 0; i < a.length; i++){
if(a[i].length() != 0 && b[i].length() != 0){
if(a[i].charAt(0) == b[i].charAt(0)){
counter++;
}
}
}
return counter;
}
/**
* The "key" array is an array containing the correct answers to an exam, like {"a", "a", "b", "b"}.
* the "answers" array contains a student's answers, with "?" representing a question left blank.
* The two arrays are not empty and are the same length. Return the score for this array of answers,
* giving +4 for each correct answer, -1 for each incorrect answer, and +0 for each blank answer.
*
* scoreUp(["a", "a", "b", "b"], ["a", "c", "b", "c"]) → 6
* scoreUp(["a", "a", "b", "b"], ["a", "a", "b", "c"]) → 11
* scoreUp(["a", "a", "b", "b"], ["a", "a", "b", "b"]) → 16
*
* @param key
* @param answers
* @return
*/
public int scoreUp(String[] key, String[] answers) {
int score = 0;
for(int i = 0; i < key.length; i++){
if(answers[i].equals(key[i])){
score += 4;
}
else if(!"?".equals(answers[i])){
score -= 1;
}
}
return score;
}
/**
* Given an array of strings, return a new array without the strings that are equal to the target string.
* One approach is to count the occurrences of the target string, make a new array of the correct length,
* and then copy over the correct strings.
*
* wordsWithout(["a", "b", "c", "a"], "a") → ["b", "c"]
* wordsWithout(["a", "b", "c", "a"], "b") → ["a", "c", "a"]
* wordsWithout(["a", "b", "c", "a"], "c") → ["a", "b", "a"]
*
* @param words
* @param target
* @return
*/
public String[] wordsWithout(String[] words, String target) {
if(words.length == 0){
return new String[0];
}
boolean[] checker = new boolean[words.length];
Arrays.fill(checker, true);
int targetCounter = 0;
for(int i = 0; i < words.length; i++){
if(words[i].equals(target)){
checker[i] = false;
targetCounter++;
}
}
String[] newWords = new String[words.length - targetCounter];
int j = 0;
for(int i = 0; i < words.length; i++){
if(checker[i]){
newWords[j] = words[i];
j++;
}
}
return newWords;
}
/**
* Given two arrays, A and B, of non-negative int scores. A "special" score is one which is a multiple of 10,
* such as 40 or 90. Return the sum of largest special score in A and the largest special score in B.
* To practice decomposition, write a separate helper method which finds the largest special score in an array.
* Write your helper method after your scoresSpecial() method in the JavaBat text area.
*
* scoresSpecial([12, 10, 4], [2, 20, 30]) → 40
* scoresSpecial([20, 10, 4], [2, 20, 10]) → 40
* scoresSpecial([12, 11, 4], [2, 20, 31]) → 20
* @param a
* @param b
* @return
*/
public int scoresSpecial(int[] a, int[] b) {
return findSpecial(a) + findSpecial(b);
}
private int findSpecial(int[] scores){
if(scores.length == 0){
return 0;
}
int maxScore = 0;
for(int i = 0; i < scores.length; i++){
if(scores[i]%10 == 0){
if(scores[i] > maxScore){
maxScore = scores[i];
}
}
}
return maxScore;
}
/**
* We have an array of heights, representing the altitude along a walking trail. Given start/end indexes
* into the array, return the sum of the changes for a walk beginning at the start index and ending at the end index.
* For example, with the heights {5, 3, 6, 7, 2} and start=2, end=4 yields a sum of 1 + 5 = 6.
* The start end end index will both be valid indexes into the array with start <= end.
*
* sumHeights([5, 3, 6, 7, 2], 2, 4) → 6
* sumHeights([5, 3, 6, 7, 2], 0, 1) → 2
* sumHeights([5, 3, 6, 7, 2], 0, 4) → 11
*
* @param heights
* @param start
* @param end
* @return
*/
public int sumHeights(int[] heights, int start, int end) {
int[] counterTrack = new int[end - start];
counterTrack = Arrays.copyOfRange(heights, start, end + 1);
int counter = 0;
for(int i = 0; i < counterTrack.length - 1; i++){
counter += Math.abs(counterTrack[i + 1] - counterTrack[i]);
}
return counter;
}
/**
* (A variation on the sumHeights problem.) We have an array of heights, representing the altitude along a walking trail.
* Given start/end indexes into the array, return the sum of the changes for a walk beginning at the start index
* and ending at the end index, however increases in height count double.
* For example, with the heights {5, 3, 6, 7, 2} and start=2, end=4 yields a sum of 1*2 + 5 = 7.
* The start end end index will both be valid indexes into the array with start <= end.
*
* sumHeights2([5, 3, 6, 7, 2], 2, 4) → 7
* sumHeights2([5, 3, 6, 7, 2], 0, 1) → 2
* sumHeights2([5, 3, 6, 7, 2], 0, 4) → 15
*
* @param heights
* @param start
* @param end
* @return
*/
public int sumHeights2(int[] heights, int start, int end) {
int[] counterTrack = new int[end - start];
counterTrack = Arrays.copyOfRange(heights, start, end + 1);
int counter = 0;
for(int i = 0; i < counterTrack.length - 1; i++){
if(counterTrack[i + 1] - counterTrack[i] >= 0){
counter += 2 * (counterTrack[i + 1] - counterTrack[i]);
}
else {
counter += Math.abs(counterTrack[i + 1] - counterTrack[i]);
}
}
return counter;
}
/**
* (A variation on the sumHeights problem.) We have an array of heights, representing the altitude along a walking trail.
* Given start/end indexes into the array, return the number of "big" steps for a walk starting at the start index
* and ending at the end index. We'll say that step is big if it is 5 or more up or down.
* The start end end index will both be valid indexes into the array with start <= end.
*
* bigHeights([5, 3, 6, 7, 2], 2, 4) → 1
* bigHeights([5, 3, 6, 7, 2], 0, 1) → 0
* bigHeights([5, 3, 6, 7, 2], 0, 4) → 1
*
* @param heights
* @param start
* @param end
* @return
*/
public int bigHeights(int[] heights, int start, int end) {
int[] counterTrack = new int[end - start];
counterTrack = Arrays.copyOfRange(heights, start, end + 1);
int counter = 0;
for(int i = 0; i < counterTrack.length - 1; i++){
if(Math.abs(counterTrack[i + 1] - counterTrack[i]) >= 5){
counter++;
}
}
return counter;
}
/**
* We have data for two users, A and B, each with a String name and an int id. The goal is to order the users
* such as for sorting. Return -1 if A comes before B, 1 if A comes after B, and 0 if they are the same.
* Order first by the string names, and then by the id numbers if the names are the same.
* Note: with Strings str1.compareTo(str2) returns an int value which is negative/0/positive to indicate
* how str1 is ordered to str2 (the value is not limited to -1/0/1).
* (On the AP, there would be two User objects, but here the code simply takes the two strings and two ints directly.
* The code logic is the same.)
*
* userCompare("bb", 1, "zz", 2) → -1
* userCompare("bb", 1, "aa", 2) → 1
* userCompare("bb", 1, "bb", 1) → 0
*
* @param aName
* @param aId
* @param bName
* @param bId
* @return
*/
public int userCompare(String aName, int aId, String bName, int bId) {
int orderByName = compareByName(aName, bName);
int orderById = compareById(aId, bId);
return computeResult(orderByName, orderById);
}
private int compareByName(String nameA, String nameB){
if(nameA.compareTo(nameB) < 0){
return -1;
}
else if(nameA.compareTo(nameB) == 0){
return 0;
}
else{
return 1;
}
}
private int compareById(int idA, int idB){
if(idA < idB){
return -1;
}
else if(idA == idB){
return 0;
}
else {
return 1;
}
}
private int computeResult(int orderByName, int orderById){
if(orderByName == 0){
return orderById;
}
else {
return orderByName;
}
}
/**
* Start with two arrays of strings, A and B, each with its elements in alphabetical order and without duplicates.
* Return a new array containing the first N elements from the two arrays. The result array should be
* in alphabetical order and without duplicates. A and B will both have a length which is N or more.
* The best "linear" solution makes a single pass over A and B, taking advantage of the fact
* that they are in alphabetical order, copying elements directly to the new array.
*
* mergeTwo(["a", "c", "z"], ["b", "f", "z"], 3) → ["a", "b", "c"]
* mergeTwo(["a", "c", "z"], ["c", "f", "z"], 3) → ["a", "c", "f"]
* mergeTwo(["f", "g", "z"], ["c", "f", "g"], 3) → ["c", "f", "g"]
*
* @param a
* @param b
* @param n
* @return
*/
public String[] mergeTwo(String[] a, String[] b, int n) {
String[] result = new String[n];
int aIndex = 0;
int bIndex = 0;
for(int i = 0; i < n; i++){
if(a[aIndex].compareTo(b[bIndex]) <= 0){
result[i] = a[aIndex];
if(aIndex < a.length - 1){
aIndex++;
}
}
else{
result[i] = b[bIndex];
if(bIndex < b.length - 1){
bIndex++;
}
}
if(result[i].equals(a[aIndex])){
if(aIndex < a.length - 1){
aIndex++;
}
}
if(result[i].equals(b[bIndex])){
if(bIndex < b.length - 1){
bIndex++;
}
}
}
return result;
}
/**
* Start with two arrays of strings, a and b, each in alphabetical order, possibly with duplicates.
* Return the count of the number of strings which appear in both arrays. The best "linear" solution
* makes a single pass over both arrays, taking advantage of the fact that they are in alphabetical order.
*
* commonTwo(["a", "c", "x"], ["b", "c", "d", "x"]) → 2
* commonTwo(["a", "c", "x"], ["a", "b", "c", "x", "z"]) → 3
* commonTwo(["a", "b", "c"], ["a", "b", "c"]) → 3
*
* @param a
* @param b
* @return
*/
public int commonTwo(String[] a, String[] b) {
if(a.length == 0 || b.length == 0){
return 0;
}
int aIndex = 0;
int bIndex = 0;
int counter = 0;
while(aIndex != -1 && bIndex != -1){ //Wystarczy, że jedno będize -1, wtedy drugiej listy nie ma sensu sprawdzać.
if(a[aIndex].equals(b[bIndex])){
counter++;
aIndex = indexOfNextLetter(a, aIndex);
bIndex = indexOfNextLetter(b, bIndex);
}
else if(a[aIndex].compareTo(b[bIndex]) < 0){
aIndex = indexOfNextLetter(a, aIndex);
}
else {
bIndex = indexOfNextLetter(b, bIndex);
}
};
return counter;
}
private int indexOfNextLetter(String[] lista, int oldIndex){
if(oldIndex == lista.length - 1){
return -1;
}
String currentLetter = lista[oldIndex];
int newIndex = oldIndex;
if(oldIndex < lista.length - 1){
do{
newIndex++;
} while(lista[newIndex].equals(currentLetter) && newIndex != lista.length - 1);
}
return newIndex;
}
}
| AdamSajewicz/java-coding-bat | ap1/src/Ap1.java | 7,823 | //Wystarczy, że jedno będize -1, wtedy drugiej listy nie ma sensu sprawdzać. | line_comment | pl | package ap1.src;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Ap1 {
public static void main(String[] args) {
int[] nums = new int[] {1, 3, 4};
Boolean result = scoresIncreasing(nums);
System.out.println("Result: " + result);
}
/**
* Given an array of scores, return true if each score is equal or greater than the one before.
* The array will be length 2 or more.
*
* scoresIncreasing([1, 3, 4]) → true
* scoresIncreasing([1, 3, 2]) → false
* scoresIncreasing([1, 1, 4]) → true
*
* @param scores
* @return
*/
public static boolean scoresIncreasing(int[] scores) {
boolean increase = false;
int i = 0;
do{
increase = scores[i + 1] >= scores[i];
i++;
} while(i < scores.length - 1 && increase);
if(increase){
return scores[i] >= scores[i -1];
}
return increase;
}
/**
* Given an array of scores, return true if there are scores of 100 next to each other in the array.
* The array length will be at least 2.
*
* scores100([1, 100, 100]) → true
* scores100([1, 100, 99, 100]) → false
* scores100([100, 1, 100, 100]) → true
*
* @param scores
* @return
*/
public boolean scores100(int[] scores) {
boolean foundScores100 = false;
int i = 0;
do{
if(scores[i] == 100 && scores[i + 1] == 100){
foundScores100 = true;
}
i++;
} while(!foundScores100 && i < scores.length - 1);
return foundScores100;
}
/**
* Given an array of scores sorted in increasing order, return true if the array contains 3 adjacent scores
* that differ from each other by at most 2, such as with {3, 4, 5} or {3, 5, 5}.
*
* scoresClump([3, 4, 5]) → true
* scoresClump([3, 4, 6]) → false
* scoresClump([1, 3, 5, 5]) → true
*
* @param scores
* @return
*/
public boolean scoresClump(int[] scores) {
if(scores.length < 3){
return false;
}
boolean isClump = false;
int i = 0;
do{
if(scores[i + 2] - scores[i] <= 2){
isClump = true;
}
i++;
} while(i < scores.length - 2 && !isClump);
return isClump;
}
/**
* Given an array of scores, compute the int average of the first half and the second half,
* and return whichever is larger. We'll say that the second half begins at index length/2.
* The array length will be at least 2. To practice decomposition, write a separate helper method
* int average(int[] scores, int start, int end) { which computes the average of the elements
* between indexes start..end. Call your helper method twice to implement scoresAverage().
* Write your helper method after your scoresAverage() method in the JavaBat text area.
* Normally you would compute averages with doubles, but here we use ints so the expected results are exact.
*
* scoresAverage([2, 2, 4, 4]) → 4
* scoresAverage([4, 4, 4, 2, 2, 2]) → 4
* scoresAverage([3, 4, 5, 1, 2, 3]) → 4
*
* @param scores
* @return
*/
public int scoresAverage(int[] scores) {
return Math.max(average(scores, 0, (scores.length / 2) - 1), average(scores, (scores.length / 2), scores.length - 1));
}
private int average(int[] scores, int startIndex, int endIndex){
int sum = 0;
int counter = 0;
for(int i = startIndex; i <= endIndex; i++){
sum += scores[i];
counter++;
}
return sum / counter;
}
/**
* Given an array of strings, return the count of the number of strings with the given length.
*
* wordsCount(["a", "bb", "b", "ccc"], 1) → 2
* wordsCount(["a", "bb", "b", "ccc"], 3) → 1
* wordsCount(["a", "bb", "b", "ccc"], 4) → 0
*
* @param words
* @param len
* @return
*/
public int wordsCount(String[] words, int len) {
if(words.length == 0){
return 0;
}
int[] lengthWector = new int[words.length];
for(int i = 0; i < words.length; i++){
lengthWector[i] = words[i].length();
}
int counter = 0;
for(int i = 0; i < words.length; i++){
if(lengthWector[i] == len){
counter++;
}
}
return counter;
}
/**
* Given an array of strings, return a new array containing the first N strings. N will be in the range 1..length.
*
* wordsFront(["a", "b", "c", "d"], 1) → ["a"]
* wordsFront(["a", "b", "c", "d"], 2) → ["a", "b"]
* wordsFront(["a", "b", "c", "d"], 3) → ["a", "b", "c"]
*
* @param words
* @param n
* @return
*/
public String[] wordsFront(String[] words, int n) {
if(words.length == 1 && n == 1){
return words;
}
String[] newWords = new String[n];
for(int i = 0; i < n; i++){
newWords[i] = words[i];
}
return newWords;
}
/**
* Given an array of strings, return a new List (e.g. an ArrayList) where all the strings of the given length
* are omitted. See wordsWithout() below which is more difficult because it uses arrays.
*
* wordsWithoutList(["a", "bb", "b", "ccc"], 1) → ["bb", "ccc"]
* wordsWithoutList(["a", "bb", "b", "ccc"], 3) → ["a", "bb", "b"]
* wordsWithoutList(["a", "bb", "b", "ccc"], 4) → ["a", "bb", "b", "ccc"]
*
* @param words
* @param len
* @return
*/
public List wordsWithoutList(String[] words, int len) {
List<String> returnList = new ArrayList<>();
if(words.length == 0){
return returnList;
}
for(int i = 0; i < words.length; i++){
if(words[i].length() != len){
returnList.add(words[i]);
}
}
return returnList;
}
/**
* Given a positive int n, return true if it contains a 1 digit. Note: use % to get the rightmost digit,
* and / to discard the rightmost digit.
*
* hasOne(10) → true
* hasOne(22) → false
* hasOne(220) → false
*
* @param n
* @return
*/
public boolean hasOne(int n) {
if(n == 1){
return true;
}
boolean has1 = false;
int nn = n;
int remainder = 0;
do{
remainder = nn%10;
nn = nn / 10;
if(remainder == 1 || nn == 1){
has1 = true;
}
} while(!has1 && nn > 10);
return has1;
}
/**
* We'll say that a positive int divides itself if every digit in the number divides into the number evenly.
* So for example 128 divides itself since 1, 2, and 8 all divide into 128 evenly.
* We'll say that 0 does not divide into anything evenly, so no number with a 0 digit divides itself.
* Note: use % to get the rightmost digit, and / to discard the rightmost digit.
*
* dividesSelf(128) → true
* dividesSelf(12) → true
* dividesSelf(120) → false
*
* @param n
* @return
*/
public boolean dividesSelf(int n) {
if(n == 0 || n % 10 == 0){
return false;
}
if(n < 10){
return true;
}
boolean digitPass = true;
int nn = n;
int remainder = 0;
do{
remainder = nn % 10;
nn = nn / 10;
digitPass = checkDigit(n, remainder);
} while(nn > 10 && digitPass);
return digitPass && (n % nn == 0);
}
private boolean checkDigit(int n, int remainder){
if(remainder == 0){
return false;
}
return n % remainder == 0;
}
/**
* Given an array of positive ints, return a new array of length "count" containing the first even numbers
* from the original array. The original array will contain at least "count" even numbers.
*
* copyEvens([3, 2, 4, 5, 8], 2) → [2, 4]
* copyEvens([3, 2, 4, 5, 8], 3) → [2, 4, 8]
* copyEvens([6, 1, 2, 4, 5, 8], 3) → [6, 2, 4]
*
* @param nums
* @param count
* @return
*/
public int[] copyEvens(int[] nums, int count) {
int[] newNums = new int[nums.length];
if(count == 0){
return newNums;
}
Arrays.fill(newNums, -1);
int j = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] % 2 == 0){
newNums[j] = nums[i];
j++;
}
}
int[] copied = new int[count];
copied = Arrays.copyOfRange(newNums, 0, count);
return copied;
}
/**
* We'll say that a positive int n is "endy" if it is in the range 0..10 or 90..100 (inclusive).
* Given an array of positive ints, return a new array of length "count" containing the first endy numbers
* from the original array. Decompose out a separate isEndy(int n) method to test if a number is endy.
* The original array will contain at least "count" endy numbers.
*
* copyEndy([9, 11, 90, 22, 6], 2) → [9, 90]
* copyEndy([9, 11, 90, 22, 6], 3) → [9, 90, 6]
* copyEndy([12, 1, 1, 13, 0, 20], 2) → [1, 1]
*
* @param nums
* @param count
* @return
*/
public int[] copyEndy(int[] nums, int count) {
int[] endies = new int[nums.length];
if(nums.length == 0){
return endies;
}
Arrays.fill(endies, -1);
int j = 0;
for(int i = 0; i < nums.length; i++){
if(isEndy(nums[i])){
endies[j] = nums[i];
j++;
}
}
j = 0;
int[] arrayOfEndyNumbers = new int[count];
arrayOfEndyNumbers = Arrays.copyOfRange(endies, 0, count);
return arrayOfEndyNumbers;
}
private boolean isEndy(int number){
if((number >= 0 && number <= 10) || (number >= 90 && number <= 100)){
return true;
}
else {
return false;
}
}
/**
* Given 2 arrays that are the same length containing strings, compare the 1st string in one array to the 1st string
* in the other array, the 2nd to the 2nd and so on. Count the number of times that the 2 strings are non-empty
* and start with the same char. The strings may be any length, including 0.
*
* matchUp(["aa", "bb", "cc"], ["aaa", "xx", "bb"]) → 1
* matchUp(["aa", "bb", "cc"], ["aaa", "b", "bb"]) → 2
* matchUp(["aa", "bb", "cc"], ["", "", "ccc"]) → 1
*
* @param a
* @param b
* @return
*/
public int matchUp(String[] a, String[] b) {
if(a.length == 0){
return 0;
}
int counter = 0;
for(int i = 0; i < a.length; i++){
if(a[i].length() != 0 && b[i].length() != 0){
if(a[i].charAt(0) == b[i].charAt(0)){
counter++;
}
}
}
return counter;
}
/**
* The "key" array is an array containing the correct answers to an exam, like {"a", "a", "b", "b"}.
* the "answers" array contains a student's answers, with "?" representing a question left blank.
* The two arrays are not empty and are the same length. Return the score for this array of answers,
* giving +4 for each correct answer, -1 for each incorrect answer, and +0 for each blank answer.
*
* scoreUp(["a", "a", "b", "b"], ["a", "c", "b", "c"]) → 6
* scoreUp(["a", "a", "b", "b"], ["a", "a", "b", "c"]) → 11
* scoreUp(["a", "a", "b", "b"], ["a", "a", "b", "b"]) → 16
*
* @param key
* @param answers
* @return
*/
public int scoreUp(String[] key, String[] answers) {
int score = 0;
for(int i = 0; i < key.length; i++){
if(answers[i].equals(key[i])){
score += 4;
}
else if(!"?".equals(answers[i])){
score -= 1;
}
}
return score;
}
/**
* Given an array of strings, return a new array without the strings that are equal to the target string.
* One approach is to count the occurrences of the target string, make a new array of the correct length,
* and then copy over the correct strings.
*
* wordsWithout(["a", "b", "c", "a"], "a") → ["b", "c"]
* wordsWithout(["a", "b", "c", "a"], "b") → ["a", "c", "a"]
* wordsWithout(["a", "b", "c", "a"], "c") → ["a", "b", "a"]
*
* @param words
* @param target
* @return
*/
public String[] wordsWithout(String[] words, String target) {
if(words.length == 0){
return new String[0];
}
boolean[] checker = new boolean[words.length];
Arrays.fill(checker, true);
int targetCounter = 0;
for(int i = 0; i < words.length; i++){
if(words[i].equals(target)){
checker[i] = false;
targetCounter++;
}
}
String[] newWords = new String[words.length - targetCounter];
int j = 0;
for(int i = 0; i < words.length; i++){
if(checker[i]){
newWords[j] = words[i];
j++;
}
}
return newWords;
}
/**
* Given two arrays, A and B, of non-negative int scores. A "special" score is one which is a multiple of 10,
* such as 40 or 90. Return the sum of largest special score in A and the largest special score in B.
* To practice decomposition, write a separate helper method which finds the largest special score in an array.
* Write your helper method after your scoresSpecial() method in the JavaBat text area.
*
* scoresSpecial([12, 10, 4], [2, 20, 30]) → 40
* scoresSpecial([20, 10, 4], [2, 20, 10]) → 40
* scoresSpecial([12, 11, 4], [2, 20, 31]) → 20
* @param a
* @param b
* @return
*/
public int scoresSpecial(int[] a, int[] b) {
return findSpecial(a) + findSpecial(b);
}
private int findSpecial(int[] scores){
if(scores.length == 0){
return 0;
}
int maxScore = 0;
for(int i = 0; i < scores.length; i++){
if(scores[i]%10 == 0){
if(scores[i] > maxScore){
maxScore = scores[i];
}
}
}
return maxScore;
}
/**
* We have an array of heights, representing the altitude along a walking trail. Given start/end indexes
* into the array, return the sum of the changes for a walk beginning at the start index and ending at the end index.
* For example, with the heights {5, 3, 6, 7, 2} and start=2, end=4 yields a sum of 1 + 5 = 6.
* The start end end index will both be valid indexes into the array with start <= end.
*
* sumHeights([5, 3, 6, 7, 2], 2, 4) → 6
* sumHeights([5, 3, 6, 7, 2], 0, 1) → 2
* sumHeights([5, 3, 6, 7, 2], 0, 4) → 11
*
* @param heights
* @param start
* @param end
* @return
*/
public int sumHeights(int[] heights, int start, int end) {
int[] counterTrack = new int[end - start];
counterTrack = Arrays.copyOfRange(heights, start, end + 1);
int counter = 0;
for(int i = 0; i < counterTrack.length - 1; i++){
counter += Math.abs(counterTrack[i + 1] - counterTrack[i]);
}
return counter;
}
/**
* (A variation on the sumHeights problem.) We have an array of heights, representing the altitude along a walking trail.
* Given start/end indexes into the array, return the sum of the changes for a walk beginning at the start index
* and ending at the end index, however increases in height count double.
* For example, with the heights {5, 3, 6, 7, 2} and start=2, end=4 yields a sum of 1*2 + 5 = 7.
* The start end end index will both be valid indexes into the array with start <= end.
*
* sumHeights2([5, 3, 6, 7, 2], 2, 4) → 7
* sumHeights2([5, 3, 6, 7, 2], 0, 1) → 2
* sumHeights2([5, 3, 6, 7, 2], 0, 4) → 15
*
* @param heights
* @param start
* @param end
* @return
*/
public int sumHeights2(int[] heights, int start, int end) {
int[] counterTrack = new int[end - start];
counterTrack = Arrays.copyOfRange(heights, start, end + 1);
int counter = 0;
for(int i = 0; i < counterTrack.length - 1; i++){
if(counterTrack[i + 1] - counterTrack[i] >= 0){
counter += 2 * (counterTrack[i + 1] - counterTrack[i]);
}
else {
counter += Math.abs(counterTrack[i + 1] - counterTrack[i]);
}
}
return counter;
}
/**
* (A variation on the sumHeights problem.) We have an array of heights, representing the altitude along a walking trail.
* Given start/end indexes into the array, return the number of "big" steps for a walk starting at the start index
* and ending at the end index. We'll say that step is big if it is 5 or more up or down.
* The start end end index will both be valid indexes into the array with start <= end.
*
* bigHeights([5, 3, 6, 7, 2], 2, 4) → 1
* bigHeights([5, 3, 6, 7, 2], 0, 1) → 0
* bigHeights([5, 3, 6, 7, 2], 0, 4) → 1
*
* @param heights
* @param start
* @param end
* @return
*/
public int bigHeights(int[] heights, int start, int end) {
int[] counterTrack = new int[end - start];
counterTrack = Arrays.copyOfRange(heights, start, end + 1);
int counter = 0;
for(int i = 0; i < counterTrack.length - 1; i++){
if(Math.abs(counterTrack[i + 1] - counterTrack[i]) >= 5){
counter++;
}
}
return counter;
}
/**
* We have data for two users, A and B, each with a String name and an int id. The goal is to order the users
* such as for sorting. Return -1 if A comes before B, 1 if A comes after B, and 0 if they are the same.
* Order first by the string names, and then by the id numbers if the names are the same.
* Note: with Strings str1.compareTo(str2) returns an int value which is negative/0/positive to indicate
* how str1 is ordered to str2 (the value is not limited to -1/0/1).
* (On the AP, there would be two User objects, but here the code simply takes the two strings and two ints directly.
* The code logic is the same.)
*
* userCompare("bb", 1, "zz", 2) → -1
* userCompare("bb", 1, "aa", 2) → 1
* userCompare("bb", 1, "bb", 1) → 0
*
* @param aName
* @param aId
* @param bName
* @param bId
* @return
*/
public int userCompare(String aName, int aId, String bName, int bId) {
int orderByName = compareByName(aName, bName);
int orderById = compareById(aId, bId);
return computeResult(orderByName, orderById);
}
private int compareByName(String nameA, String nameB){
if(nameA.compareTo(nameB) < 0){
return -1;
}
else if(nameA.compareTo(nameB) == 0){
return 0;
}
else{
return 1;
}
}
private int compareById(int idA, int idB){
if(idA < idB){
return -1;
}
else if(idA == idB){
return 0;
}
else {
return 1;
}
}
private int computeResult(int orderByName, int orderById){
if(orderByName == 0){
return orderById;
}
else {
return orderByName;
}
}
/**
* Start with two arrays of strings, A and B, each with its elements in alphabetical order and without duplicates.
* Return a new array containing the first N elements from the two arrays. The result array should be
* in alphabetical order and without duplicates. A and B will both have a length which is N or more.
* The best "linear" solution makes a single pass over A and B, taking advantage of the fact
* that they are in alphabetical order, copying elements directly to the new array.
*
* mergeTwo(["a", "c", "z"], ["b", "f", "z"], 3) → ["a", "b", "c"]
* mergeTwo(["a", "c", "z"], ["c", "f", "z"], 3) → ["a", "c", "f"]
* mergeTwo(["f", "g", "z"], ["c", "f", "g"], 3) → ["c", "f", "g"]
*
* @param a
* @param b
* @param n
* @return
*/
public String[] mergeTwo(String[] a, String[] b, int n) {
String[] result = new String[n];
int aIndex = 0;
int bIndex = 0;
for(int i = 0; i < n; i++){
if(a[aIndex].compareTo(b[bIndex]) <= 0){
result[i] = a[aIndex];
if(aIndex < a.length - 1){
aIndex++;
}
}
else{
result[i] = b[bIndex];
if(bIndex < b.length - 1){
bIndex++;
}
}
if(result[i].equals(a[aIndex])){
if(aIndex < a.length - 1){
aIndex++;
}
}
if(result[i].equals(b[bIndex])){
if(bIndex < b.length - 1){
bIndex++;
}
}
}
return result;
}
/**
* Start with two arrays of strings, a and b, each in alphabetical order, possibly with duplicates.
* Return the count of the number of strings which appear in both arrays. The best "linear" solution
* makes a single pass over both arrays, taking advantage of the fact that they are in alphabetical order.
*
* commonTwo(["a", "c", "x"], ["b", "c", "d", "x"]) → 2
* commonTwo(["a", "c", "x"], ["a", "b", "c", "x", "z"]) → 3
* commonTwo(["a", "b", "c"], ["a", "b", "c"]) → 3
*
* @param a
* @param b
* @return
*/
public int commonTwo(String[] a, String[] b) {
if(a.length == 0 || b.length == 0){
return 0;
}
int aIndex = 0;
int bIndex = 0;
int counter = 0;
while(aIndex != -1 && bIndex != -1){ //Wy<SUF>
if(a[aIndex].equals(b[bIndex])){
counter++;
aIndex = indexOfNextLetter(a, aIndex);
bIndex = indexOfNextLetter(b, bIndex);
}
else if(a[aIndex].compareTo(b[bIndex]) < 0){
aIndex = indexOfNextLetter(a, aIndex);
}
else {
bIndex = indexOfNextLetter(b, bIndex);
}
};
return counter;
}
private int indexOfNextLetter(String[] lista, int oldIndex){
if(oldIndex == lista.length - 1){
return -1;
}
String currentLetter = lista[oldIndex];
int newIndex = oldIndex;
if(oldIndex < lista.length - 1){
do{
newIndex++;
} while(lista[newIndex].equals(currentLetter) && newIndex != lista.length - 1);
}
return newIndex;
}
}
|
60501_9 | public class BoundingBox {
double xmin = Double.NaN;
double ymin = Double.NaN;
double xmax = Double.NaN;
double ymax = Double.NaN;
public String toString(){
return String.format("%f %f %f %f", xmin, xmax, ymin, ymax);
}
/**
* Powi�ksza BB tak, aby zawiera� punkt (x,y)
* Je�eli by� wcze�niej pusty - w�wczas ma zawiera� wy��cznie ten punkt
* @param x - wsp�rz�dna x
* @param y - wsp�rz�dna y
*/
void addPoint(double x, double y){
if(isEmpty()){
xmin = x;
xmax = x;
ymin = ymax = y;
}
else{
xmax = Math.max(x, xmax);
xmin = Math.min(x, xmin);
ymax = Math.max(y, ymax);
ymin = Math.min(y, ymin);
}
}
/**
* Sprawdza, czy BB zawiera punkt (x,y)
* @param x
* @param y
* @return
*/
boolean contains(double x, double y){
return x>=xmin && x<=xmax && y>=ymin && y<=ymax;
}
/**
* Sprawdza czy dany BB zawiera bb
* @param bb
* @return
*/
boolean contains(BoundingBox bb){
return this.contains(bb.xmax, bb.ymax) && this.contains(bb.xmin, bb.ymin) &&
this.contains(bb.xmax, bb.ymin) && this.contains(bb.xmin, bb.ymax);
}
/**
* Sprawdza, czy dany BB przecina si� z bb
* @param bb
* @return
*/
boolean intersects(BoundingBox bb){
return this.contains(bb.xmax, bb.ymax) || this.contains(bb.xmin, bb.ymin) ||
this.contains(bb.xmax, bb.ymin) || this.contains(bb.xmin, bb.ymax) || bb.contains(this.xmax, this.ymax) ||
bb.contains(this.xmin, this.ymin) || bb.contains(this.xmax, this.ymin) || bb.contains(this.xmin, this.ymax);
}
/**
* Powi�ksza rozmiary tak, aby zawiera� bb oraz poprzedni� wersj� this
* Je�eli by� pusty - po wykonaniu operacji ma by� r�wny bb
* @param bb
* @return
*/
BoundingBox add(BoundingBox bb){
if(isEmpty()){
xmin = bb.xmin;
xmax = bb.xmax;
ymin = bb.ymin;
ymax = bb.ymax;
}
else{
xmax = Math.max(bb.xmax, xmax);
xmin = Math.min(bb.xmin, xmin);
ymax = Math.max(bb.ymax, ymax);
ymin = Math.min(bb.ymin, ymin);
}
return this;
}
/**
* Sprawdza czy BB jest pusty
* @return
*/
boolean isEmpty(){
return Double.isNaN(xmin);
}
/**
* Sprawdza czy
* 1) typem o jest BoundingBox
* 2) this jest r�wny bb
* @return
*/
public boolean equals(Object o){
return o instanceof BoundingBox && ((BoundingBox) o).xmax == xmax && ((BoundingBox) o).xmin == xmin &&
((BoundingBox) o).ymax == ymax && ((BoundingBox) o).ymin == ymin;
}
/**
* Oblicza i zwraca wsp�rz�dn� x �rodka
* @return if !isEmpty() wsp�rz�dna x �rodka else wyrzuca wyj�tek
* (sam dobierz typ)
*/
double getCenterX(){
if(isEmpty()){
throw new RuntimeException("Can't evaluate Xcenter of an empty square");}
return (xmax + xmin) / 2;
}
/**
* Oblicza i zwraca wsp�rz�dn� y �rodka
* @return if !isEmpty() wsp�rz�dna y �rodka else wyrzuca wyj�tek
* (sam dobierz typ)
*/
double getCenterY(){
if(isEmpty()){
throw new RuntimeException("Can't evaluate Ycenter of an empty square");}
return (ymax + ymin) / 2;
}
/**
* Oblicza odleg�o�� pomi�dzy �rodkami this bounding box oraz bbx
* @param bbx prostok�t, do kt�rego liczona jest odleg�o��
* @return if !isEmpty odleg�o��, else wyrzuca wyj�tek lub zwraca maksymaln� mo�liw� warto�� double
* Ze wzgl�du na to, �e s� to wsp�rz�dne geograficzne, zamiast odleg�o�ci u�yj wzoru haversine
* (ang. haversine formula)
*
* Gotowy kod mo�na znale�� w Internecie...
*/
double distanceTo(BoundingBox bbx){
double x1 = this.getCenterX();
double y1 = this.getCenterY();
double x2 = bbx.getCenterX();
double y2 = bbx.getCenterY();
y1 = Math.toRadians(y1);
x1 = Math.toRadians(x1);
y2 = Math.toRadians(y2);
x2 = Math.toRadians(x2);
if(this.isEmpty()){
return Double.MAX_VALUE;
}
else{
return 2 * 6371* Math.asin(Math.sqrt(Math.pow(Math.sin((y2-y1)/2), 2) +
Math.cos(y1) * Math.cos(y2) * Math.pow(Math.sin((x2-x1)/2), 2)));
}
}
} | AdamStajek/CSV-Reader | src/BoundingBox.java | 1,708 | /**
* Oblicza odleg�o�� pomi�dzy �rodkami this bounding box oraz bbx
* @param bbx prostok�t, do kt�rego liczona jest odleg�o��
* @return if !isEmpty odleg�o��, else wyrzuca wyj�tek lub zwraca maksymaln� mo�liw� warto�� double
* Ze wzgl�du na to, �e s� to wsp�rz�dne geograficzne, zamiast odleg�o�ci u�yj wzoru haversine
* (ang. haversine formula)
*
* Gotowy kod mo�na znale�� w Internecie...
*/ | block_comment | pl | public class BoundingBox {
double xmin = Double.NaN;
double ymin = Double.NaN;
double xmax = Double.NaN;
double ymax = Double.NaN;
public String toString(){
return String.format("%f %f %f %f", xmin, xmax, ymin, ymax);
}
/**
* Powi�ksza BB tak, aby zawiera� punkt (x,y)
* Je�eli by� wcze�niej pusty - w�wczas ma zawiera� wy��cznie ten punkt
* @param x - wsp�rz�dna x
* @param y - wsp�rz�dna y
*/
void addPoint(double x, double y){
if(isEmpty()){
xmin = x;
xmax = x;
ymin = ymax = y;
}
else{
xmax = Math.max(x, xmax);
xmin = Math.min(x, xmin);
ymax = Math.max(y, ymax);
ymin = Math.min(y, ymin);
}
}
/**
* Sprawdza, czy BB zawiera punkt (x,y)
* @param x
* @param y
* @return
*/
boolean contains(double x, double y){
return x>=xmin && x<=xmax && y>=ymin && y<=ymax;
}
/**
* Sprawdza czy dany BB zawiera bb
* @param bb
* @return
*/
boolean contains(BoundingBox bb){
return this.contains(bb.xmax, bb.ymax) && this.contains(bb.xmin, bb.ymin) &&
this.contains(bb.xmax, bb.ymin) && this.contains(bb.xmin, bb.ymax);
}
/**
* Sprawdza, czy dany BB przecina si� z bb
* @param bb
* @return
*/
boolean intersects(BoundingBox bb){
return this.contains(bb.xmax, bb.ymax) || this.contains(bb.xmin, bb.ymin) ||
this.contains(bb.xmax, bb.ymin) || this.contains(bb.xmin, bb.ymax) || bb.contains(this.xmax, this.ymax) ||
bb.contains(this.xmin, this.ymin) || bb.contains(this.xmax, this.ymin) || bb.contains(this.xmin, this.ymax);
}
/**
* Powi�ksza rozmiary tak, aby zawiera� bb oraz poprzedni� wersj� this
* Je�eli by� pusty - po wykonaniu operacji ma by� r�wny bb
* @param bb
* @return
*/
BoundingBox add(BoundingBox bb){
if(isEmpty()){
xmin = bb.xmin;
xmax = bb.xmax;
ymin = bb.ymin;
ymax = bb.ymax;
}
else{
xmax = Math.max(bb.xmax, xmax);
xmin = Math.min(bb.xmin, xmin);
ymax = Math.max(bb.ymax, ymax);
ymin = Math.min(bb.ymin, ymin);
}
return this;
}
/**
* Sprawdza czy BB jest pusty
* @return
*/
boolean isEmpty(){
return Double.isNaN(xmin);
}
/**
* Sprawdza czy
* 1) typem o jest BoundingBox
* 2) this jest r�wny bb
* @return
*/
public boolean equals(Object o){
return o instanceof BoundingBox && ((BoundingBox) o).xmax == xmax && ((BoundingBox) o).xmin == xmin &&
((BoundingBox) o).ymax == ymax && ((BoundingBox) o).ymin == ymin;
}
/**
* Oblicza i zwraca wsp�rz�dn� x �rodka
* @return if !isEmpty() wsp�rz�dna x �rodka else wyrzuca wyj�tek
* (sam dobierz typ)
*/
double getCenterX(){
if(isEmpty()){
throw new RuntimeException("Can't evaluate Xcenter of an empty square");}
return (xmax + xmin) / 2;
}
/**
* Oblicza i zwraca wsp�rz�dn� y �rodka
* @return if !isEmpty() wsp�rz�dna y �rodka else wyrzuca wyj�tek
* (sam dobierz typ)
*/
double getCenterY(){
if(isEmpty()){
throw new RuntimeException("Can't evaluate Ycenter of an empty square");}
return (ymax + ymin) / 2;
}
/**
* Obl<SUF>*/
double distanceTo(BoundingBox bbx){
double x1 = this.getCenterX();
double y1 = this.getCenterY();
double x2 = bbx.getCenterX();
double y2 = bbx.getCenterY();
y1 = Math.toRadians(y1);
x1 = Math.toRadians(x1);
y2 = Math.toRadians(y2);
x2 = Math.toRadians(x2);
if(this.isEmpty()){
return Double.MAX_VALUE;
}
else{
return 2 * 6371* Math.asin(Math.sqrt(Math.pow(Math.sin((y2-y1)/2), 2) +
Math.cos(y1) * Math.cos(y2) * Math.pow(Math.sin((x2-x1)/2), 2)));
}
}
} |
3934_3 | package classes.AE;
import java.util.ArrayList;
import java.util.Random;
import classes.Miasta;
public class Chromosom {
//Chromosom jego tworzenie i parametry
public double przystosowanieChromosomu;
int[] geny;
public static ArrayList<Chromosom> populacja = new ArrayList<Chromosom>();
public Chromosom(){//konstruktor chromosomu wykorzystujący ilosc genów jako argument
this.geny = GenerowanieGenow(Miasta.MIASTA.length);// jest 30 miast więc ilośc genów to zawsze będzie 30
this.WyznaczPrzystosowanieChromosomu(); //chromosom zaraz po poznaniu swojego zestawu genów jest w stanie wyznaczyć swoje przystosowanie więc to robi
populacja.add(this);
}
public Chromosom(int[] geny){//konstruktor chromosomu wykorzystujący gotowy zestaw genów jako argument
this.geny = geny;
this.WyznaczPrzystosowanieChromosomu();//chromosom zaraz po poznaniu swojego zestawu genów jest w stanie wyznaczyć swoje przystosowanie więc to robi
populacja.add(this);
}
int[] GenerowanieGenow(int iloscgenow){//generowanie tablicy z genami, każdy gen występuje w tablicy tylko raz
int[] geny =new int[iloscgenow];
Random rng = new Random();
int miasto;
ArrayList <Integer> wykorzystaneMiasta = new ArrayList<Integer>();
//dodanie tablicy uzytych indeksów w celu wykluczenia powtórzeń
for(int i=0;i<iloscgenow;i++){
do {
miasto = rng.nextInt(iloscgenow);
}
while (wykorzystaneMiasta.contains(miasto));
wykorzystaneMiasta.add(miasto);
geny[i]=miasto;
}
return geny;
}
void WyznaczPrzystosowanieChromosomu(){//przeniosłem z AE
double wartoscFunkcjiPrzystosowania = 0.0;
for (int i = 1; i < geny.length; i++) {
wartoscFunkcjiPrzystosowania=Miasta.ODLEGLOSCI[geny[i-1]][geny[i]]+wartoscFunkcjiPrzystosowania;
}
wartoscFunkcjiPrzystosowania=wartoscFunkcjiPrzystosowania+Miasta.ODLEGLOSCI[geny[0]][geny[geny.length-1]];
przystosowanieChromosomu=wartoscFunkcjiPrzystosowania;
}
public double[] wyznaczPrzystosowaniaPopulacji(){
double[] przystosowaniaPopulacji = new double[populacja.size()];
for (int i = 0; i < przystosowaniaPopulacji.length; i++) {
przystosowaniaPopulacji[i] = przystosowanieChromosomu;
}
return przystosowaniaPopulacji;
}
public void DrukujGeny(){// do debugowania XD
for (int i = 0; i < geny.length; i++) {
System.out.print(geny[i]+"|");
}
System.out.println();
}
}
| Adamo2499/ProjektMiNSI | src/classes/AE/Chromosom.java | 938 | //chromosom zaraz po poznaniu swojego zestawu genów jest w stanie wyznaczyć swoje przystosowanie więc to robi | line_comment | pl | package classes.AE;
import java.util.ArrayList;
import java.util.Random;
import classes.Miasta;
public class Chromosom {
//Chromosom jego tworzenie i parametry
public double przystosowanieChromosomu;
int[] geny;
public static ArrayList<Chromosom> populacja = new ArrayList<Chromosom>();
public Chromosom(){//konstruktor chromosomu wykorzystujący ilosc genów jako argument
this.geny = GenerowanieGenow(Miasta.MIASTA.length);// jest 30 miast więc ilośc genów to zawsze będzie 30
this.WyznaczPrzystosowanieChromosomu(); //ch<SUF>
populacja.add(this);
}
public Chromosom(int[] geny){//konstruktor chromosomu wykorzystujący gotowy zestaw genów jako argument
this.geny = geny;
this.WyznaczPrzystosowanieChromosomu();//chromosom zaraz po poznaniu swojego zestawu genów jest w stanie wyznaczyć swoje przystosowanie więc to robi
populacja.add(this);
}
int[] GenerowanieGenow(int iloscgenow){//generowanie tablicy z genami, każdy gen występuje w tablicy tylko raz
int[] geny =new int[iloscgenow];
Random rng = new Random();
int miasto;
ArrayList <Integer> wykorzystaneMiasta = new ArrayList<Integer>();
//dodanie tablicy uzytych indeksów w celu wykluczenia powtórzeń
for(int i=0;i<iloscgenow;i++){
do {
miasto = rng.nextInt(iloscgenow);
}
while (wykorzystaneMiasta.contains(miasto));
wykorzystaneMiasta.add(miasto);
geny[i]=miasto;
}
return geny;
}
void WyznaczPrzystosowanieChromosomu(){//przeniosłem z AE
double wartoscFunkcjiPrzystosowania = 0.0;
for (int i = 1; i < geny.length; i++) {
wartoscFunkcjiPrzystosowania=Miasta.ODLEGLOSCI[geny[i-1]][geny[i]]+wartoscFunkcjiPrzystosowania;
}
wartoscFunkcjiPrzystosowania=wartoscFunkcjiPrzystosowania+Miasta.ODLEGLOSCI[geny[0]][geny[geny.length-1]];
przystosowanieChromosomu=wartoscFunkcjiPrzystosowania;
}
public double[] wyznaczPrzystosowaniaPopulacji(){
double[] przystosowaniaPopulacji = new double[populacja.size()];
for (int i = 0; i < przystosowaniaPopulacji.length; i++) {
przystosowaniaPopulacji[i] = przystosowanieChromosomu;
}
return przystosowaniaPopulacji;
}
public void DrukujGeny(){// do debugowania XD
for (int i = 0; i < geny.length; i++) {
System.out.print(geny[i]+"|");
}
System.out.println();
}
}
|
3803_18 | package com.eternalsrv.ui;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import com.eternalsrv.App;
import com.eternalsrv.R;
import com.eternalsrv.models.PersonalityTrait;
import com.eternalsrv.utils.MyPreferences;
import com.eternalsrv.utils.asynctasks.BaseAsyncTask;
import com.eternalsrv.utils.asynctasks.model.TestRequest;
import com.eternalsrv.utils.constant.ServerMethodsConsts;
import com.kofigyan.stateprogressbar.StateProgressBar;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class TestFragment extends Fragment {
private ScrollView scrollView;
private SeekBar SliderQ1;
private SeekBar SliderQ2;
private SeekBar SliderQ3;
private SeekBar SliderQ4;
private SeekBar SliderQ5;
private SeekBar SliderQ6;
private SeekBar[] sliders;
private StateProgressBar pageProgressBar;
private TextView[] textViews;
private PersonalityTrait[] personalityTraits;
String[] allQuestions;
private ArrayList<Integer> shuffledQuestionIndexes;
private int numberOfScreens;
private int actualScreen;
private int numberOfQuestionsPerPage;
private float range;
private MyPreferences myPreferences;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test, container, false);
myPreferences = App.getPreferences();
range = 120;
actualScreen = 0;
numberOfScreens = 4;
numberOfQuestionsPerPage = 6;
allQuestions = new String[numberOfScreens * numberOfQuestionsPerPage];
shuffledQuestionIndexes = new ArrayList<>();
for (int i = 0; i < allQuestions.length; i++)
shuffledQuestionIndexes.add(i + 1);
Collections.shuffle(shuffledQuestionIndexes);
scrollView = (ScrollView) view.findViewById(R.id.test_container_scrollView);
SliderQ1 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ1);
SliderQ2 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ2);
SliderQ3 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ3);
SliderQ4 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ4);
SliderQ5 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ5);
SliderQ6 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ6);
sliders = new SeekBar[]{SliderQ1, SliderQ2, SliderQ3, SliderQ4, SliderQ5, SliderQ6};
for (SeekBar s : sliders) {
s.setOnSeekBarChangeListener(seekBarChangeListener);
s.setProgress(51);
s.setProgress(50);
}
TextView textQ1 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ1);
TextView textQ2 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ2);
TextView textQ3 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ3);
TextView textQ4 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ4);
TextView textQ5 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ5);
TextView textQ6 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ6);
textViews = new TextView[]{textQ1, textQ2, textQ3, textQ4, textQ5, textQ6};
Button nextQuestions = (Button) view.findViewById(com.eternalsrv.R.id.nextQuestions);
nextQuestions.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawQuestions();
}
});
pageProgressBar = (StateProgressBar) view.findViewById(R.id.pageProgressBar);
String[] questionsJ = new String[4];
// Tworzę listę zadań do wykonania i trzymam się jej
questionsJ[0] = "I create to-do list and stick to it";
// Skupiam się na jednej rzeczy do wykonania na raz
questionsJ[1] = "I focus on one thing at a time";
// Moja praca jest metodyczna i zorganizowana
questionsJ[2] = "My work is methodical and organized";
// Nie lubię niespodziewanych wydarzeń
questionsJ[3] = "I don't like unexpected events";
int[] numbers = new int[]{1, 2, 3, 4};
System.arraycopy(questionsJ, 0, allQuestions, 0, questionsJ.length);
PersonalityTrait JTrait = new PersonalityTrait("J", questionsJ, numbers);
String[] questionsP = new String[2];
// Jestem najbardziej efektywny, kiedy wykonuję swoje zadania na ostatnią chwilę
questionsP[0] = "I am most effective when I complete my tasks at the last minute";
// Często podejmuję decyzje impulsywnie
questionsP[1] = "I often make decisions impulsively";
numbers = new int[]{5, 6};
System.arraycopy(questionsP, 0, allQuestions, 4, questionsP.length);
PersonalityTrait PTrait = new PersonalityTrait("P", questionsP, numbers);
String[] questionsN = new String[3];
// Żyję bardziej w swojej głowie, niż w świecie rzeczywistym
questionsN[0] = "I live more in my head than in the real world";
// Fantazjowanie często sprawia mi większą przyjemność niż realne doznania
questionsN[1] = "Fantasizing often give more joy than real sensations";
// Wolę wymyślać nowe sposoby na rozwiązanie problemu, niż korzystać ze sprawdzonych
questionsN[2] = "I prefer to invent new ways to solve problems, than using a proven ones";
numbers = new int[]{7, 8, 9};
System.arraycopy(questionsN, 0, allQuestions, 6, questionsN.length);
PersonalityTrait NTrait = new PersonalityTrait("N", questionsN, numbers);
NTrait.setScore(40);
String[] questionsS = new String[3];
// Stąpam twardo po ziemi
questionsS[0] = "I keep my feet firmly on the ground";
// Wolę skupić się na rzeczywistości, niż oddawać fantazjom
questionsS[1] = "I prefer to focus on reality than indulge in fantasies";
// Aktywność fizyczna sprawia mi większą przyjemność niż umysłowa
questionsS[2] = "Psychical activity is more enjoyable than mental one";
numbers = new int[]{10, 11, 12};
System.arraycopy(questionsS, 0, allQuestions, 9, questionsS.length);
PersonalityTrait STrait = new PersonalityTrait("S", questionsS, numbers);
STrait.setScore(60);
String[] questionsE = {
// Mówienie o moich problemach nie jest dla mnie trudne
"It is not difficult for me to talk about my problems",
// Lubię być w centrum uwagi
"I like being the center of attention",
// Łatwo nawiązuję nowe znajomości
"I easily make new friendships",
// Często rozpoczynam rozmowę
"I start conversations often"};
numbers = new int[]{13, 14, 15, 16};
System.arraycopy(questionsE, 0, allQuestions, 12, questionsE.length);
PersonalityTrait ETrait = new PersonalityTrait("E", questionsE, numbers);
String[] questionsI = new String[2];
// Chętnie chodzę na samotne spacery z dala od zgiełku i hałasu
questionsI[0] = "I like to go for lonely walks away from the hustle and bustle";
// Wolę przysłuchiwać się dyskusji niż w niej uczestniczyć
questionsI[1] = "I prefer to listen to the discussion than to participate in it";
numbers = new int[]{17, 18};
System.arraycopy(questionsI, 0, allQuestions, 16, questionsI.length);
PersonalityTrait ITrait = new PersonalityTrait("I", questionsI, numbers);
String[] questionsF = new String[3];
// Unikam kłótni, nawet jeśli wiem, że mam rację
questionsF[0] = "I avoid arguing, even if I know I'm right";
// Subiektywne odczucia mają duży wpływ na moje decyzje
questionsF[1] = "Subjective feelings have a big influence on my decisions";
// Wyrażanie swoich uczuć nie sprawia mi problemu
questionsF[2] = "I have no problem expressing my feelings";
numbers = new int[]{19, 20, 21};
System.arraycopy(questionsF, 0, allQuestions, 18, questionsF.length);
PersonalityTrait FTrait = new PersonalityTrait("F", questionsF, numbers);
String[] questionsT = new String[3];
// Wolę być postrzegany jako ktoś niemiły, niż nielogiczny
questionsT[0] = "I'd rather be seen as rude than illogical";
// Uważam, że logiczne rozwiązania są zawsze najlepsze
questionsT[1] = "I believe logical solutions are always the best";
// Jestem bezpośredni, nawet jeśli mogę tym kogoś zranić"
questionsT[2] = "I am straightforward, even if it can hurt somebody";
numbers = new int[]{22, 23, 24};
System.arraycopy(questionsT, 0, allQuestions, 21, questionsT.length);
PersonalityTrait TTrait = new PersonalityTrait("T", questionsT, numbers);
personalityTraits = new PersonalityTrait[]{ETrait, ITrait, NTrait, STrait, TTrait, JTrait, FTrait, PTrait};
drawQuestions();
return view;
}
private SeekBar.OnSeekBarChangeListener seekBarChangeListener
= new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
double barProgress = seekBar.getProgress();
float max = (float) seekBar.getMax();
float h = 15 + (float) ((max / range) * barProgress);
float s = 100;
float v = 90;
String hexColor = hsvToRgb(h, s, v);
//String hexColor = String.format("#%06X", (0xFFFFFF & color));
seekBar.getProgressDrawable().setColorFilter(Color.parseColor(hexColor), PorterDuff.Mode.SRC_IN);
seekBar.getThumb().setColorFilter(Color.parseColor(hexColor), PorterDuff.Mode.SRC_IN);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
public void saveAnswers() {
for (int i = 0; i < numberOfQuestionsPerPage; i++) {
for (PersonalityTrait temp : personalityTraits) {
if (temp.containsNumber(shuffledQuestionIndexes.get(numberOfQuestionsPerPage * (actualScreen - 1) + i))) {
temp.saveScore(shuffledQuestionIndexes.get(numberOfQuestionsPerPage * (actualScreen - 1) + i), Math.round(sliders[i].getProgress()));
break;
}
}
}
}
public void drawQuestions() {
if (actualScreen < numberOfScreens) {
if (actualScreen > 0)
saveAnswers();
actualScreen++;
switch (actualScreen) {
case 2:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.TWO);
break;
case 3:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.THREE);
break;
case 4:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.FOUR);
break;
default:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.ONE);
}
SliderQ1.setProgress(50);
SliderQ2.setProgress(50);
SliderQ3.setProgress(50);
SliderQ4.setProgress(50);
SliderQ5.setProgress(50);
SliderQ6.setProgress(50);
for (int i = 0; i < numberOfQuestionsPerPage; i++) {
textViews[i].setText(allQuestions[shuffledQuestionIndexes.get(numberOfQuestionsPerPage * (actualScreen - 1) + i) - 1]);
}
scrollView.scrollTo(0, 0);
} else {
saveAnswers();
HashMap<String, String> answers = new HashMap<>();
for (PersonalityTrait tr : personalityTraits) {
for (int i = 0; i < tr.getNumbersOfQuestions().length; i++) {
answers.put("q" + tr.getNumbersOfQuestions()[i], String.valueOf(tr.getAnswerPoints()[i]));
}
}
TestRequest testRequest = new TestRequest(myPreferences.getUserId(), 24, answers);
BaseAsyncTask<TestRequest> sendResults = new BaseAsyncTask<>(ServerMethodsConsts.TEST, testRequest);
sendResults.setHttpMethod("POST");
sendResults.execute();
showResults();
}
}
private void showResults() {
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.main_content, new TestResultsFragment());
ft.commit();
}
public static String hsvToRgb(float H, float S, float V) {
float R, G, B;
H /= 360f;
S /= 100f;
V /= 100f;
if (S == 0) {
R = V * 255;
G = V * 255;
B = V * 255;
} else {
float var_h = H * 6;
if (var_h == 6)
var_h = 0; // H must be < 1
int var_i = (int) Math.floor((double) var_h); // Or ... var_i =
// floor( var_h )
float var_1 = V * (1 - S);
float var_2 = V * (1 - S * (var_h - var_i));
float var_3 = V * (1 - S * (1 - (var_h - var_i)));
float var_r;
float var_g;
float var_b;
if (var_i == 0) {
var_r = V;
var_g = var_3;
var_b = var_1;
} else if (var_i == 1) {
var_r = var_2;
var_g = V;
var_b = var_1;
} else if (var_i == 2) {
var_r = var_1;
var_g = V;
var_b = var_3;
} else if (var_i == 3) {
var_r = var_1;
var_g = var_2;
var_b = V;
} else if (var_i == 4) {
var_r = var_3;
var_g = var_1;
var_b = V;
} else {
var_r = V;
var_g = var_1;
var_b = var_2;
}
R = var_r * 255;
G = var_g * 255;
B = var_b * 255;
}
String rs = Integer.toHexString((int) (R));
String gs = Integer.toHexString((int) (G));
String bs = Integer.toHexString((int) (B));
if (rs.length() == 1)
rs = "0" + rs;
if (gs.length() == 1)
gs = "0" + gs;
if (bs.length() == 1)
bs = "0" + bs;
return "#" + rs + gs + bs;
}
}
| Adamoll/Eternal | app/src/main/java/com/eternalsrv/ui/TestFragment.java | 4,731 | // Unikam kłótni, nawet jeśli wiem, że mam rację | line_comment | pl | package com.eternalsrv.ui;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import com.eternalsrv.App;
import com.eternalsrv.R;
import com.eternalsrv.models.PersonalityTrait;
import com.eternalsrv.utils.MyPreferences;
import com.eternalsrv.utils.asynctasks.BaseAsyncTask;
import com.eternalsrv.utils.asynctasks.model.TestRequest;
import com.eternalsrv.utils.constant.ServerMethodsConsts;
import com.kofigyan.stateprogressbar.StateProgressBar;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class TestFragment extends Fragment {
private ScrollView scrollView;
private SeekBar SliderQ1;
private SeekBar SliderQ2;
private SeekBar SliderQ3;
private SeekBar SliderQ4;
private SeekBar SliderQ5;
private SeekBar SliderQ6;
private SeekBar[] sliders;
private StateProgressBar pageProgressBar;
private TextView[] textViews;
private PersonalityTrait[] personalityTraits;
String[] allQuestions;
private ArrayList<Integer> shuffledQuestionIndexes;
private int numberOfScreens;
private int actualScreen;
private int numberOfQuestionsPerPage;
private float range;
private MyPreferences myPreferences;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test, container, false);
myPreferences = App.getPreferences();
range = 120;
actualScreen = 0;
numberOfScreens = 4;
numberOfQuestionsPerPage = 6;
allQuestions = new String[numberOfScreens * numberOfQuestionsPerPage];
shuffledQuestionIndexes = new ArrayList<>();
for (int i = 0; i < allQuestions.length; i++)
shuffledQuestionIndexes.add(i + 1);
Collections.shuffle(shuffledQuestionIndexes);
scrollView = (ScrollView) view.findViewById(R.id.test_container_scrollView);
SliderQ1 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ1);
SliderQ2 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ2);
SliderQ3 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ3);
SliderQ4 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ4);
SliderQ5 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ5);
SliderQ6 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ6);
sliders = new SeekBar[]{SliderQ1, SliderQ2, SliderQ3, SliderQ4, SliderQ5, SliderQ6};
for (SeekBar s : sliders) {
s.setOnSeekBarChangeListener(seekBarChangeListener);
s.setProgress(51);
s.setProgress(50);
}
TextView textQ1 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ1);
TextView textQ2 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ2);
TextView textQ3 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ3);
TextView textQ4 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ4);
TextView textQ5 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ5);
TextView textQ6 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ6);
textViews = new TextView[]{textQ1, textQ2, textQ3, textQ4, textQ5, textQ6};
Button nextQuestions = (Button) view.findViewById(com.eternalsrv.R.id.nextQuestions);
nextQuestions.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawQuestions();
}
});
pageProgressBar = (StateProgressBar) view.findViewById(R.id.pageProgressBar);
String[] questionsJ = new String[4];
// Tworzę listę zadań do wykonania i trzymam się jej
questionsJ[0] = "I create to-do list and stick to it";
// Skupiam się na jednej rzeczy do wykonania na raz
questionsJ[1] = "I focus on one thing at a time";
// Moja praca jest metodyczna i zorganizowana
questionsJ[2] = "My work is methodical and organized";
// Nie lubię niespodziewanych wydarzeń
questionsJ[3] = "I don't like unexpected events";
int[] numbers = new int[]{1, 2, 3, 4};
System.arraycopy(questionsJ, 0, allQuestions, 0, questionsJ.length);
PersonalityTrait JTrait = new PersonalityTrait("J", questionsJ, numbers);
String[] questionsP = new String[2];
// Jestem najbardziej efektywny, kiedy wykonuję swoje zadania na ostatnią chwilę
questionsP[0] = "I am most effective when I complete my tasks at the last minute";
// Często podejmuję decyzje impulsywnie
questionsP[1] = "I often make decisions impulsively";
numbers = new int[]{5, 6};
System.arraycopy(questionsP, 0, allQuestions, 4, questionsP.length);
PersonalityTrait PTrait = new PersonalityTrait("P", questionsP, numbers);
String[] questionsN = new String[3];
// Żyję bardziej w swojej głowie, niż w świecie rzeczywistym
questionsN[0] = "I live more in my head than in the real world";
// Fantazjowanie często sprawia mi większą przyjemność niż realne doznania
questionsN[1] = "Fantasizing often give more joy than real sensations";
// Wolę wymyślać nowe sposoby na rozwiązanie problemu, niż korzystać ze sprawdzonych
questionsN[2] = "I prefer to invent new ways to solve problems, than using a proven ones";
numbers = new int[]{7, 8, 9};
System.arraycopy(questionsN, 0, allQuestions, 6, questionsN.length);
PersonalityTrait NTrait = new PersonalityTrait("N", questionsN, numbers);
NTrait.setScore(40);
String[] questionsS = new String[3];
// Stąpam twardo po ziemi
questionsS[0] = "I keep my feet firmly on the ground";
// Wolę skupić się na rzeczywistości, niż oddawać fantazjom
questionsS[1] = "I prefer to focus on reality than indulge in fantasies";
// Aktywność fizyczna sprawia mi większą przyjemność niż umysłowa
questionsS[2] = "Psychical activity is more enjoyable than mental one";
numbers = new int[]{10, 11, 12};
System.arraycopy(questionsS, 0, allQuestions, 9, questionsS.length);
PersonalityTrait STrait = new PersonalityTrait("S", questionsS, numbers);
STrait.setScore(60);
String[] questionsE = {
// Mówienie o moich problemach nie jest dla mnie trudne
"It is not difficult for me to talk about my problems",
// Lubię być w centrum uwagi
"I like being the center of attention",
// Łatwo nawiązuję nowe znajomości
"I easily make new friendships",
// Często rozpoczynam rozmowę
"I start conversations often"};
numbers = new int[]{13, 14, 15, 16};
System.arraycopy(questionsE, 0, allQuestions, 12, questionsE.length);
PersonalityTrait ETrait = new PersonalityTrait("E", questionsE, numbers);
String[] questionsI = new String[2];
// Chętnie chodzę na samotne spacery z dala od zgiełku i hałasu
questionsI[0] = "I like to go for lonely walks away from the hustle and bustle";
// Wolę przysłuchiwać się dyskusji niż w niej uczestniczyć
questionsI[1] = "I prefer to listen to the discussion than to participate in it";
numbers = new int[]{17, 18};
System.arraycopy(questionsI, 0, allQuestions, 16, questionsI.length);
PersonalityTrait ITrait = new PersonalityTrait("I", questionsI, numbers);
String[] questionsF = new String[3];
// Un<SUF>
questionsF[0] = "I avoid arguing, even if I know I'm right";
// Subiektywne odczucia mają duży wpływ na moje decyzje
questionsF[1] = "Subjective feelings have a big influence on my decisions";
// Wyrażanie swoich uczuć nie sprawia mi problemu
questionsF[2] = "I have no problem expressing my feelings";
numbers = new int[]{19, 20, 21};
System.arraycopy(questionsF, 0, allQuestions, 18, questionsF.length);
PersonalityTrait FTrait = new PersonalityTrait("F", questionsF, numbers);
String[] questionsT = new String[3];
// Wolę być postrzegany jako ktoś niemiły, niż nielogiczny
questionsT[0] = "I'd rather be seen as rude than illogical";
// Uważam, że logiczne rozwiązania są zawsze najlepsze
questionsT[1] = "I believe logical solutions are always the best";
// Jestem bezpośredni, nawet jeśli mogę tym kogoś zranić"
questionsT[2] = "I am straightforward, even if it can hurt somebody";
numbers = new int[]{22, 23, 24};
System.arraycopy(questionsT, 0, allQuestions, 21, questionsT.length);
PersonalityTrait TTrait = new PersonalityTrait("T", questionsT, numbers);
personalityTraits = new PersonalityTrait[]{ETrait, ITrait, NTrait, STrait, TTrait, JTrait, FTrait, PTrait};
drawQuestions();
return view;
}
private SeekBar.OnSeekBarChangeListener seekBarChangeListener
= new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
double barProgress = seekBar.getProgress();
float max = (float) seekBar.getMax();
float h = 15 + (float) ((max / range) * barProgress);
float s = 100;
float v = 90;
String hexColor = hsvToRgb(h, s, v);
//String hexColor = String.format("#%06X", (0xFFFFFF & color));
seekBar.getProgressDrawable().setColorFilter(Color.parseColor(hexColor), PorterDuff.Mode.SRC_IN);
seekBar.getThumb().setColorFilter(Color.parseColor(hexColor), PorterDuff.Mode.SRC_IN);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
public void saveAnswers() {
for (int i = 0; i < numberOfQuestionsPerPage; i++) {
for (PersonalityTrait temp : personalityTraits) {
if (temp.containsNumber(shuffledQuestionIndexes.get(numberOfQuestionsPerPage * (actualScreen - 1) + i))) {
temp.saveScore(shuffledQuestionIndexes.get(numberOfQuestionsPerPage * (actualScreen - 1) + i), Math.round(sliders[i].getProgress()));
break;
}
}
}
}
public void drawQuestions() {
if (actualScreen < numberOfScreens) {
if (actualScreen > 0)
saveAnswers();
actualScreen++;
switch (actualScreen) {
case 2:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.TWO);
break;
case 3:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.THREE);
break;
case 4:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.FOUR);
break;
default:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.ONE);
}
SliderQ1.setProgress(50);
SliderQ2.setProgress(50);
SliderQ3.setProgress(50);
SliderQ4.setProgress(50);
SliderQ5.setProgress(50);
SliderQ6.setProgress(50);
for (int i = 0; i < numberOfQuestionsPerPage; i++) {
textViews[i].setText(allQuestions[shuffledQuestionIndexes.get(numberOfQuestionsPerPage * (actualScreen - 1) + i) - 1]);
}
scrollView.scrollTo(0, 0);
} else {
saveAnswers();
HashMap<String, String> answers = new HashMap<>();
for (PersonalityTrait tr : personalityTraits) {
for (int i = 0; i < tr.getNumbersOfQuestions().length; i++) {
answers.put("q" + tr.getNumbersOfQuestions()[i], String.valueOf(tr.getAnswerPoints()[i]));
}
}
TestRequest testRequest = new TestRequest(myPreferences.getUserId(), 24, answers);
BaseAsyncTask<TestRequest> sendResults = new BaseAsyncTask<>(ServerMethodsConsts.TEST, testRequest);
sendResults.setHttpMethod("POST");
sendResults.execute();
showResults();
}
}
private void showResults() {
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.main_content, new TestResultsFragment());
ft.commit();
}
public static String hsvToRgb(float H, float S, float V) {
float R, G, B;
H /= 360f;
S /= 100f;
V /= 100f;
if (S == 0) {
R = V * 255;
G = V * 255;
B = V * 255;
} else {
float var_h = H * 6;
if (var_h == 6)
var_h = 0; // H must be < 1
int var_i = (int) Math.floor((double) var_h); // Or ... var_i =
// floor( var_h )
float var_1 = V * (1 - S);
float var_2 = V * (1 - S * (var_h - var_i));
float var_3 = V * (1 - S * (1 - (var_h - var_i)));
float var_r;
float var_g;
float var_b;
if (var_i == 0) {
var_r = V;
var_g = var_3;
var_b = var_1;
} else if (var_i == 1) {
var_r = var_2;
var_g = V;
var_b = var_1;
} else if (var_i == 2) {
var_r = var_1;
var_g = V;
var_b = var_3;
} else if (var_i == 3) {
var_r = var_1;
var_g = var_2;
var_b = V;
} else if (var_i == 4) {
var_r = var_3;
var_g = var_1;
var_b = V;
} else {
var_r = V;
var_g = var_1;
var_b = var_2;
}
R = var_r * 255;
G = var_g * 255;
B = var_b * 255;
}
String rs = Integer.toHexString((int) (R));
String gs = Integer.toHexString((int) (G));
String bs = Integer.toHexString((int) (B));
if (rs.length() == 1)
rs = "0" + rs;
if (gs.length() == 1)
gs = "0" + gs;
if (bs.length() == 1)
bs = "0" + bs;
return "#" + rs + gs + bs;
}
}
|
94573_17 | package all.algorithms;
import java.util.ArrayList;
import javax.swing.JTextArea;
import all.model.Bet;
import all.model.Driver;
import all.model.Participant;
public class CountPointsAlgorithm {
ArrayList<Bet> betsArray = new ArrayList<>();
public void countRace(JTextArea bets, ArrayList<Driver> driversArrayList, Participant chosen, String fastestDriver){
boolean joker=false;
String getBets = bets.getText(); //take bets from jtextarea
String[] parts = getBets.split("\n"); //divide on position+driver
int jokers=0;
double points=0;
for (String string : parts) {
String s=string;
if(s.contains("NO: ")) {
System.out.println(chosen.getName()+": ");
if(s.contains(fastestDriver)){
System.out.println(s+" "+1);
points+=1;
}
else System.out.println(s+" "+0);
continue;
}
if(s.equals("(J)")) {
joker=true;
break;
}
String[] parts2=s.split(" "); //divide position and driver
parts2[0]=parts2[0].replace(".","");
Bet bet = new Bet(Integer.parseInt(parts2[0]), parts2[1]);
betsArray.add(bet); //add bet to arraylist
}
for (Bet bet: betsArray) {
double eachpoints=0; //for every bet separately
for (Driver driver : driversArrayList) {
if(bet.getSurname().equals(driver.getName())) {
if(bet.getPosition()==driver.getPosition()) {
switch(bet.getPosition()){
case 1: points+=3; eachpoints+=3; break;
case 2: points+=2; eachpoints+=2; break;
case 3: points+=1; eachpoints+=1; break;
}
points+=2;
eachpoints+=2;
}
else if(bet.getPosition()==driver.getPosition()-1 || bet.getPosition()==driver.getPosition()+1){
points+=1;
eachpoints+=1;
}
}
}
System.out.println(bet.getPosition()+" "+bet.getSurname()+" "+eachpoints);
}
points*=2; //because it's race
if(joker) {
points*=2;
chosen.setNumberOfUsedJokers(1);
}
chosen.setPoints(points);
System.out.println("Sum of points: "+points);
System.out.println();
}
public void countQuali(JTextArea bets, ArrayList<Driver> driversArrayList, Participant chosen){
boolean joker=false;
String getBets = bets.getText(); //take bets from jtextarea
String[] parts = getBets.split("\n"); //divide on position+driver
int jokers=0;
double points=0;
for (String string : parts) {
String s=string;
if(s.equals("(J)")) {
joker=true;
break;
}
String[] parts2=s.split(" "); //divide on position+driver
parts2[0]=parts2[0].replace(".","");
Bet bet = new Bet(Integer.parseInt(parts2[0]), parts2[1]);
betsArray.add(bet); //add bet to arraylist
}
for (Bet bet: betsArray) {
double eachpoints=0;
for (Driver driver : driversArrayList) {
if(bet.getSurname().equals(driver.getName())) {
if(bet.getPosition()==driver.getPosition()) {
switch(bet.getPosition()){
case 1: points+=3; eachpoints+=3; break;
case 2: points+=2; eachpoints+=2; break;
case 3: points+=1; eachpoints+=1; break;
}
points+=2;
eachpoints+=2;
}
else if(bet.getPosition()==driver.getPosition()-1 || bet.getPosition()==driver.getPosition()+1){
points+=1;
eachpoints+=1;
}
else points+=0;
}
}
System.out.println(bet.getPosition()+" "+bet.getSurname()+" "+eachpoints);
}
if(joker) {
points*=2;
}
chosen.setPoints(points);
System.out.println(points);
}
public void countSprint(JTextArea bets, ArrayList<Driver> driversArrayList, Participant chosen){
boolean joker=false;
String getBets = bets.getText(); //take bets from jtextarea
String[] parts = getBets.split("\n"); //divide on position+driver
int jokers=0;
double points=0;
for (String string : parts) {
String s=string;
if(s.equals("(J)")) {
joker=true;
break;
}
String[] parts2=s.split(" "); //divide on position+driver
parts2[0]=parts2[0].replace(".","");
Bet bet = new Bet(Integer.parseInt(parts2[0]), parts2[1]);
betsArray.add(bet); //add bet to arraylist
}
for (Bet bet: betsArray) {
double eachpoints=0; //for every bet separately
for (Driver driver : driversArrayList) {
if(bet.getSurname().equals(driver.getName())) {
if(bet.getPosition()==driver.getPosition()) {
switch(bet.getPosition()){
case 1: points+=3; eachpoints+=3; break;
case 2: points+=2; eachpoints+=2; break;
case 3: points+=1; eachpoints+=1; break;
}
points+=2;
eachpoints+=2;
}
else if(bet.getPosition()==driver.getPosition()-1 || bet.getPosition()==driver.getPosition()+1){
points+=1;
eachpoints+=1;
}
}
}
System.out.println(bet.getPosition()+" "+bet.getSurname()+" "+eachpoints);
}
if(joker) {
points*=2;
chosen.setNumberOfUsedJokers(1);
}
chosen.setPoints(points);
System.out.println("Sum of points: "+points);
System.out.println();
}
public void countSprintShootout(JTextArea bets, ArrayList<Driver> driversArrayList, Participant chosen){
boolean joker=false;
String getBets = bets.getText(); //take bets from jtextarea
String[] parts = getBets.split("\n"); //divide on position+driver
int jokers=0;
double points=0;
for (String string : parts) {
String s=string;
if(s.equals("(J)")) { //tu jeszcze zeby jakos dodawal, bo jakbym dal w kwali i race jokera to by dodal 2
joker=true;
break;
}
String[] parts2=s.split(" "); //divide on position+driver
parts2[0]=parts2[0].replace(".","");
Bet bet = new Bet(Integer.parseInt(parts2[0]), parts2[1]);
betsArray.add(bet); //dodanie betu do arraylisty
}
for (Bet bet: betsArray) {
double eachpoints=0; //for every bet separately
for (Driver driver : driversArrayList) {
if(bet.getSurname().equals(driver.getName())) {
if(bet.getPosition()==driver.getPosition()) {
switch(bet.getPosition()){
case 1: points+=3; eachpoints+=3; break;
case 2: points+=2; eachpoints+=2; break;
case 3: points+=1; eachpoints+=1; break;
}
points+=2;
eachpoints+=2;
}
else if(bet.getPosition()==driver.getPosition()-1 || bet.getPosition()==driver.getPosition()+1){
points+=1;
eachpoints+=1;
}
else points+=0;
}
}
System.out.println(bet.getPosition()+" "+bet.getSurname()+" "+eachpoints);
}
points*=0.5; //because it's sprint shootout
if(joker) {
points*=2;
}
chosen.setPoints(points);
System.out.println(points);
}
}
| AdamusPL/F1-Adder | SumaTor/src/main/java/all/algorithms/CountPointsAlgorithm.java | 2,333 | //tu jeszcze zeby jakos dodawal, bo jakbym dal w kwali i race jokera to by dodal 2 | line_comment | pl | package all.algorithms;
import java.util.ArrayList;
import javax.swing.JTextArea;
import all.model.Bet;
import all.model.Driver;
import all.model.Participant;
public class CountPointsAlgorithm {
ArrayList<Bet> betsArray = new ArrayList<>();
public void countRace(JTextArea bets, ArrayList<Driver> driversArrayList, Participant chosen, String fastestDriver){
boolean joker=false;
String getBets = bets.getText(); //take bets from jtextarea
String[] parts = getBets.split("\n"); //divide on position+driver
int jokers=0;
double points=0;
for (String string : parts) {
String s=string;
if(s.contains("NO: ")) {
System.out.println(chosen.getName()+": ");
if(s.contains(fastestDriver)){
System.out.println(s+" "+1);
points+=1;
}
else System.out.println(s+" "+0);
continue;
}
if(s.equals("(J)")) {
joker=true;
break;
}
String[] parts2=s.split(" "); //divide position and driver
parts2[0]=parts2[0].replace(".","");
Bet bet = new Bet(Integer.parseInt(parts2[0]), parts2[1]);
betsArray.add(bet); //add bet to arraylist
}
for (Bet bet: betsArray) {
double eachpoints=0; //for every bet separately
for (Driver driver : driversArrayList) {
if(bet.getSurname().equals(driver.getName())) {
if(bet.getPosition()==driver.getPosition()) {
switch(bet.getPosition()){
case 1: points+=3; eachpoints+=3; break;
case 2: points+=2; eachpoints+=2; break;
case 3: points+=1; eachpoints+=1; break;
}
points+=2;
eachpoints+=2;
}
else if(bet.getPosition()==driver.getPosition()-1 || bet.getPosition()==driver.getPosition()+1){
points+=1;
eachpoints+=1;
}
}
}
System.out.println(bet.getPosition()+" "+bet.getSurname()+" "+eachpoints);
}
points*=2; //because it's race
if(joker) {
points*=2;
chosen.setNumberOfUsedJokers(1);
}
chosen.setPoints(points);
System.out.println("Sum of points: "+points);
System.out.println();
}
public void countQuali(JTextArea bets, ArrayList<Driver> driversArrayList, Participant chosen){
boolean joker=false;
String getBets = bets.getText(); //take bets from jtextarea
String[] parts = getBets.split("\n"); //divide on position+driver
int jokers=0;
double points=0;
for (String string : parts) {
String s=string;
if(s.equals("(J)")) {
joker=true;
break;
}
String[] parts2=s.split(" "); //divide on position+driver
parts2[0]=parts2[0].replace(".","");
Bet bet = new Bet(Integer.parseInt(parts2[0]), parts2[1]);
betsArray.add(bet); //add bet to arraylist
}
for (Bet bet: betsArray) {
double eachpoints=0;
for (Driver driver : driversArrayList) {
if(bet.getSurname().equals(driver.getName())) {
if(bet.getPosition()==driver.getPosition()) {
switch(bet.getPosition()){
case 1: points+=3; eachpoints+=3; break;
case 2: points+=2; eachpoints+=2; break;
case 3: points+=1; eachpoints+=1; break;
}
points+=2;
eachpoints+=2;
}
else if(bet.getPosition()==driver.getPosition()-1 || bet.getPosition()==driver.getPosition()+1){
points+=1;
eachpoints+=1;
}
else points+=0;
}
}
System.out.println(bet.getPosition()+" "+bet.getSurname()+" "+eachpoints);
}
if(joker) {
points*=2;
}
chosen.setPoints(points);
System.out.println(points);
}
public void countSprint(JTextArea bets, ArrayList<Driver> driversArrayList, Participant chosen){
boolean joker=false;
String getBets = bets.getText(); //take bets from jtextarea
String[] parts = getBets.split("\n"); //divide on position+driver
int jokers=0;
double points=0;
for (String string : parts) {
String s=string;
if(s.equals("(J)")) {
joker=true;
break;
}
String[] parts2=s.split(" "); //divide on position+driver
parts2[0]=parts2[0].replace(".","");
Bet bet = new Bet(Integer.parseInt(parts2[0]), parts2[1]);
betsArray.add(bet); //add bet to arraylist
}
for (Bet bet: betsArray) {
double eachpoints=0; //for every bet separately
for (Driver driver : driversArrayList) {
if(bet.getSurname().equals(driver.getName())) {
if(bet.getPosition()==driver.getPosition()) {
switch(bet.getPosition()){
case 1: points+=3; eachpoints+=3; break;
case 2: points+=2; eachpoints+=2; break;
case 3: points+=1; eachpoints+=1; break;
}
points+=2;
eachpoints+=2;
}
else if(bet.getPosition()==driver.getPosition()-1 || bet.getPosition()==driver.getPosition()+1){
points+=1;
eachpoints+=1;
}
}
}
System.out.println(bet.getPosition()+" "+bet.getSurname()+" "+eachpoints);
}
if(joker) {
points*=2;
chosen.setNumberOfUsedJokers(1);
}
chosen.setPoints(points);
System.out.println("Sum of points: "+points);
System.out.println();
}
public void countSprintShootout(JTextArea bets, ArrayList<Driver> driversArrayList, Participant chosen){
boolean joker=false;
String getBets = bets.getText(); //take bets from jtextarea
String[] parts = getBets.split("\n"); //divide on position+driver
int jokers=0;
double points=0;
for (String string : parts) {
String s=string;
if(s.equals("(J)")) { //tu<SUF>
joker=true;
break;
}
String[] parts2=s.split(" "); //divide on position+driver
parts2[0]=parts2[0].replace(".","");
Bet bet = new Bet(Integer.parseInt(parts2[0]), parts2[1]);
betsArray.add(bet); //dodanie betu do arraylisty
}
for (Bet bet: betsArray) {
double eachpoints=0; //for every bet separately
for (Driver driver : driversArrayList) {
if(bet.getSurname().equals(driver.getName())) {
if(bet.getPosition()==driver.getPosition()) {
switch(bet.getPosition()){
case 1: points+=3; eachpoints+=3; break;
case 2: points+=2; eachpoints+=2; break;
case 3: points+=1; eachpoints+=1; break;
}
points+=2;
eachpoints+=2;
}
else if(bet.getPosition()==driver.getPosition()-1 || bet.getPosition()==driver.getPosition()+1){
points+=1;
eachpoints+=1;
}
else points+=0;
}
}
System.out.println(bet.getPosition()+" "+bet.getSurname()+" "+eachpoints);
}
points*=0.5; //because it's sprint shootout
if(joker) {
points*=2;
}
chosen.setPoints(points);
System.out.println(points);
}
}
|
36836_3 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package wmi.sd;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
/**
*
* @author bikol
*/
public class Dodawanie {
public static String dodawanie(String a, String b) throws IllegalArgumentException {
List<String> Cyfry = Arrays.asList("Jeden", "Dwa", "Trzy", "Cztery", "Pięć", "Sześć", "Siedem", "Osiem", "Dziewięć", "Zero");
char[] charactersA = a.toCharArray();
char[] charactersB = b.toCharArray();
if(!isInteger(a)) {
if(Cyfry.contains(a) && Cyfry.contains(b)) {
int aa = cyfryToInt(a);
int bb = cyfryToInt(b);
String cc = String.valueOf(aa+bb);
return cc;
} else if(charactersA[1]==';' && charactersA[3]==';' && charactersB[1]==';' && charactersB[3]==';' && charactersA.length==5 && charactersB.length==5) {
int a1 = Character.getNumericValue(charactersA[0]);
System.out.println(a1);
int a2 = Character.getNumericValue(charactersA[2]);
System.out.println(a2);
int a3 = Character.getNumericValue(charactersA[4]);
System.out.println(a3);
int b1 = Character.getNumericValue(charactersB[0]);
System.out.println(b1);
int b2 = Character.getNumericValue(charactersB[2]);
System.out.println(b2);
int b3 = Character.getNumericValue(charactersB[4]);
System.out.println(b3);
int c1 = a1+b1;
System.out.println(c1);
int c2 = a2+b2;
int c3 = a3+b3;
String dd = c1+";"+c2+";"+c3;
return dd;
}
PizzaFactory pizzaFactory = new PizzaFactory();
if (pizzaFactory.CanMakePizza(a,b)){
return pizzaFactory.Make(a,b);
}
if(!isInteger(a)) {
return dodawanieFloatDoInt(a, b);
} else if(isValidNumber(a) && isValidNumber(b)) {
int aa = Integer.valueOf(a);
int bb = Integer.valueOf(b);
if(aa<=100 && bb<=100){
return Integer.toString(aa+bb);
}
if(!isInteger(b)){
return "Niedozwolona operacja";
}
if(aa>=1000 && aa<=1200){
int wynik = aa + bb;
return "HEX: " + Integer.toHexString(wynik);
}
else if (aa>1200 && aa<=1300) {
int wynik = aa + aa;
return "SPECJALNY WYNIK HEX DLA CIEBIE: " + Integer.toHexString(wynik);
}
return "etam co mnie to";
}
else{
throw new IllegalArgumentException("Co najmniej jeden z argumentow nie jest liczba");
}
try {
int aa = Integer.parseInt(a);
int bb = Integer.parseInt(b);
if (aa <= 100 && bb <= 100) {
return Integer.toString(aa + bb);
}
}
catch (java.lang.NumberFormatException e) {
}
return a+b;
}
static class PizzaFactory{
/*Jedyna na świecie fabryka produkująca pizzę ze stringów!*/
//masz nowy pomysł na składniki? Dodaj je
List<String> allowedIngridients = Arrays.asList("ser", "kiełbasa", "sos czosnkowy", "szynka", "kukurydza", "kurczak");
List<String> forbiddenIngridients = Arrays.asList("ananas", "keczup", "musztarda");
PizzaFactory(){
}
boolean CanMakePizza(String a, String b){
return (allowedIngridients.contains(a.toLowerCase())||forbiddenIngridients.contains(a.toLowerCase())) &&( allowedIngridients.contains(b.toLowerCase())||forbiddenIngridients.contains(b.toLowerCase()));
}
String Make(String ingridient1, String ingridient2){
if (forbiddenIngridients.contains(ingridient1.toLowerCase()) || forbiddenIngridients.contains(ingridient2.toLowerCase())){
return "Nie.";
}
else{
return ingridient1.toLowerCase()+" i "+ingridient2.toLowerCase()+" :)";
}
}
}
private static boolean isInteger(String s){
try {
Integer.parseInt(s);
} catch(NumberFormatException e){
return false;
}
return true;
}
private static String dodawanieFloatDoInt(String a, String b){
float aa = Float.valueOf(a);
int bb = Integer.valueOf(b);
System.out.println(aa+bb);
return Float.toString(aa+bb);
}
private static boolean isValidNumber(String a) {
return a.matches("[0-9]+");
}
private static int cyfryToInt(String a) {
if (a.equals("Zero")) {
return 0;
} else if(a.equals("Jeden")) {
return 1;
} else if(a.equals("Dwa")) {
return 2;
} else if(a.equals("Trzy")) {
return 3;
} else if(a.equals("Cztery")) {
return 4;
} else if(a.equals("Pięć")) {
return 5;
} else if(a.equals("Sześć")) {
return 6;
} else if(a.equals("Siedem")) {
return 7;
} else if(a.equals("Osiem")) {
return 8;
} else if(a.equals("Dziewięć")) {
return 9;
} else {
return -1;
}
}
}
| Adelionek/DINO1920-testing | SuperDodawanie/src/main/java/wmi/sd/Dodawanie.java | 1,873 | //masz nowy pomysł na składniki? Dodaj je | 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 wmi.sd;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
/**
*
* @author bikol
*/
public class Dodawanie {
public static String dodawanie(String a, String b) throws IllegalArgumentException {
List<String> Cyfry = Arrays.asList("Jeden", "Dwa", "Trzy", "Cztery", "Pięć", "Sześć", "Siedem", "Osiem", "Dziewięć", "Zero");
char[] charactersA = a.toCharArray();
char[] charactersB = b.toCharArray();
if(!isInteger(a)) {
if(Cyfry.contains(a) && Cyfry.contains(b)) {
int aa = cyfryToInt(a);
int bb = cyfryToInt(b);
String cc = String.valueOf(aa+bb);
return cc;
} else if(charactersA[1]==';' && charactersA[3]==';' && charactersB[1]==';' && charactersB[3]==';' && charactersA.length==5 && charactersB.length==5) {
int a1 = Character.getNumericValue(charactersA[0]);
System.out.println(a1);
int a2 = Character.getNumericValue(charactersA[2]);
System.out.println(a2);
int a3 = Character.getNumericValue(charactersA[4]);
System.out.println(a3);
int b1 = Character.getNumericValue(charactersB[0]);
System.out.println(b1);
int b2 = Character.getNumericValue(charactersB[2]);
System.out.println(b2);
int b3 = Character.getNumericValue(charactersB[4]);
System.out.println(b3);
int c1 = a1+b1;
System.out.println(c1);
int c2 = a2+b2;
int c3 = a3+b3;
String dd = c1+";"+c2+";"+c3;
return dd;
}
PizzaFactory pizzaFactory = new PizzaFactory();
if (pizzaFactory.CanMakePizza(a,b)){
return pizzaFactory.Make(a,b);
}
if(!isInteger(a)) {
return dodawanieFloatDoInt(a, b);
} else if(isValidNumber(a) && isValidNumber(b)) {
int aa = Integer.valueOf(a);
int bb = Integer.valueOf(b);
if(aa<=100 && bb<=100){
return Integer.toString(aa+bb);
}
if(!isInteger(b)){
return "Niedozwolona operacja";
}
if(aa>=1000 && aa<=1200){
int wynik = aa + bb;
return "HEX: " + Integer.toHexString(wynik);
}
else if (aa>1200 && aa<=1300) {
int wynik = aa + aa;
return "SPECJALNY WYNIK HEX DLA CIEBIE: " + Integer.toHexString(wynik);
}
return "etam co mnie to";
}
else{
throw new IllegalArgumentException("Co najmniej jeden z argumentow nie jest liczba");
}
try {
int aa = Integer.parseInt(a);
int bb = Integer.parseInt(b);
if (aa <= 100 && bb <= 100) {
return Integer.toString(aa + bb);
}
}
catch (java.lang.NumberFormatException e) {
}
return a+b;
}
static class PizzaFactory{
/*Jedyna na świecie fabryka produkująca pizzę ze stringów!*/
//ma<SUF>
List<String> allowedIngridients = Arrays.asList("ser", "kiełbasa", "sos czosnkowy", "szynka", "kukurydza", "kurczak");
List<String> forbiddenIngridients = Arrays.asList("ananas", "keczup", "musztarda");
PizzaFactory(){
}
boolean CanMakePizza(String a, String b){
return (allowedIngridients.contains(a.toLowerCase())||forbiddenIngridients.contains(a.toLowerCase())) &&( allowedIngridients.contains(b.toLowerCase())||forbiddenIngridients.contains(b.toLowerCase()));
}
String Make(String ingridient1, String ingridient2){
if (forbiddenIngridients.contains(ingridient1.toLowerCase()) || forbiddenIngridients.contains(ingridient2.toLowerCase())){
return "Nie.";
}
else{
return ingridient1.toLowerCase()+" i "+ingridient2.toLowerCase()+" :)";
}
}
}
private static boolean isInteger(String s){
try {
Integer.parseInt(s);
} catch(NumberFormatException e){
return false;
}
return true;
}
private static String dodawanieFloatDoInt(String a, String b){
float aa = Float.valueOf(a);
int bb = Integer.valueOf(b);
System.out.println(aa+bb);
return Float.toString(aa+bb);
}
private static boolean isValidNumber(String a) {
return a.matches("[0-9]+");
}
private static int cyfryToInt(String a) {
if (a.equals("Zero")) {
return 0;
} else if(a.equals("Jeden")) {
return 1;
} else if(a.equals("Dwa")) {
return 2;
} else if(a.equals("Trzy")) {
return 3;
} else if(a.equals("Cztery")) {
return 4;
} else if(a.equals("Pięć")) {
return 5;
} else if(a.equals("Sześć")) {
return 6;
} else if(a.equals("Siedem")) {
return 7;
} else if(a.equals("Osiem")) {
return 8;
} else if(a.equals("Dziewięć")) {
return 9;
} else {
return -1;
}
}
}
|
90277_0 | package com.gusia.backend.person;
import org.springframework.hateoas.RepresentationModel;
import java.util.UUID;
public class PersonModel extends RepresentationModel<PersonModel> {
//TODO - wywalić to, po prostu nie wiem jak front rozegrać
private final UUID pid;
private final String name;
public PersonModel(Person person) {
this.pid = person.getPid();
this.name = person.getName();
}
public UUID getPid() {
return pid;
}
public String getName() {
return name;
}
}
| Adenka/PrezentPerfekt | backend/src/main/java/com/gusia/backend/person/PersonModel.java | 167 | //TODO - wywalić to, po prostu nie wiem jak front rozegrać | line_comment | pl | package com.gusia.backend.person;
import org.springframework.hateoas.RepresentationModel;
import java.util.UUID;
public class PersonModel extends RepresentationModel<PersonModel> {
//TO<SUF>
private final UUID pid;
private final String name;
public PersonModel(Person person) {
this.pid = person.getPid();
this.name = person.getName();
}
public UUID getPid() {
return pid;
}
public String getName() {
return name;
}
}
|
118988_2 | package pt;
import java.util.Random;
/**
* Trida reprezentujici kolecka a jejich typy
* @author TR
*
*/
public class Wheelbarrow {
/**
* nazev kolecka
*/
public String name;
/**
* minimalni rychlost kolecka
*/
private final double vmin;
/**
* maximalni rychlost kolecka
*/
private final double vmax;
/**
* minilani vzzdalenost potrebna pro opravu
*/
private final double dmin;
/**
* maximalni vzdalenost potrebna pro opravu
*/
private final double dmax;
/**
* doba opravy kolecka
*/
private final double td;
/**
* maximalni pocet pytlu na kolecku
*/
private final int kd;
/**
* procentualni zastoupeni kolecka
*/
private final double pd;
/**
* vysledna rychlost generovaneho kolecka
*/
private final double velocity;
/**
* vyslednou urazenou drahu do udrzby generovaneho kolecka
*/
private final double distance;
/**
* pocet kolecek
*/
private static int count = 0;
/**
*id kolecka
*/
private final int id;
/**
* random generator
*/
private final Random rd = new Random();
/**
* aktualni dojezd
*/
private double dcurrent;
/**
* opravuje se
*/
private boolean repairing;
/**
* cas do konce opravy
*/
private double tr;
/**
* Konstrktor pro vytvoreni typu kolecka
* @param name jmeno kolecka
* @param vmin min rychlost
* @param vmax max rychlost
* @param dmin min vzdalenost do udrzby
* @param dmax max vzdalenost do udrzby
* @param td doba opravy
* @param kd pocet pytlu
* @param pd pravdepodobnost kolecka
*/
public Wheelbarrow(String name, double vmin, double vmax, double dmin, double dmax, double td, int kd, double pd) {
this.name = name;
this.vmin = vmin;
this.vmax = vmax;
this.dmin = dmin;
this.dmax = dmax;
this.td = td;
this.kd = kd;
this.pd = pd;
this.id = 0;
this.velocity = 0;
this.distance = 0;
this.repairing = false;
this.dcurrent = 0;
this.tr = Double.MAX_VALUE;
}
/**
* Konstruktor pro vygenerovani kolecka na zaklade jeho druhu
* @param type druh kolecka
*/
public Wheelbarrow(Wheelbarrow type) {
this.name = type.name;
this.velocity = generateVelocity(type.vmax, type.vmin);
this.distance = generateDistance(type.dmax, type.dmin);
this.vmin = type.vmin;
this.vmax = type.vmax;
this.dmin = type.dmin;
this.dmax = type.dmax;
this.td = type.td;
this.kd = type.kd;
this.pd = -1;
count();
this.id = count;
this.repairing = false;
this.dcurrent = distance;
this.tr = -1;
}
/**
* Metoda zvysujici pocitac kolecek
*/
private void count() {
count++;
}
/**
* Metoda vypisujici jmeno kolecka
*
* @return vraci jmeno kolecka
*/
public String getName(){
return name;
}
/**
* Metoda generujici rychlost kolecka
* @param vx max rychlost
* @param vn min rychlost
* @return vraci vyslednou rychlost
*/
private double generateVelocity(double vx, double vn){
double v = vn + (vx - vn) * rd.nextDouble();
return v;
}
/**
* Metoda generujici vzdalenost do udrzby kolecka
* @param dmax maximalni vzdalenost
* @param dmin minimalni vzdalenost
* @return vraci vzdalenost do udrzby
*/
private double generateDistance(double dmax, double dmin) {
double mi = (dmin + dmax) / 2;
double sigma = (dmax - dmin) / 4;
double dfinal = rd.nextGaussian() * sigma + mi;
return dfinal;
}
/**
* Getter pro cas potrebny na opravu kolecka
* @return
*/
public double getRepairTime() {
return td;
}
/**
* Getter pro objem (pocet pytlu) kolecka
* @return vraci pocet pytlu kolecka
*/
public int getVolume() {
return kd;
}
/**
* Getter pro rychlost kolecka
* @return vraci rychlost kolecka
*/
public double getVelocity() {
return velocity;
}
/**
* Getter pro vzdalenost potrebnou do udrzby
* @return vraci vzdalenost do udrzby
*/
public double getDistance() {
return distance;
}
/**
* Getter pro ziskani pravdepodobnosti druhu kolecka
* @return vraci pravdepodobnost druhu kolecka
*/
public double getProbability() {
return pd;
}
/**
* Getter pro ziskani id kolecka
* @return vraci id kolecka
*/
public int getID() {
return id;
}
/**
* Vypis id pro kontrolu
*/
public void printID() {
System.out.println("ID: " + id);
}
/**
* Getter na maximalni vzdalenost
* @return vraci max vzdalenost
*/
public double getDMax(){
return dmax;
}
/**
* Getter aktualni vzdalenosti
* @return aktualni vzdalenost
*/
public double getDcurrent() {
return dcurrent;
}
/**
* Setter pro nastaveni aktualni vzdalenosti
* @param dcurrent hodnota vzdalenosti
* @param m znacka - pokud true tak menim hodnotu, pokud false tak odecitam od aktualni hodnoty
*/
public void setDcurrent(double dcurrent, boolean m) {
if(m) {
this.dcurrent = dcurrent;
}
else {
this.dcurrent -= dcurrent;
}
}
/**
* Setter pro spusteni/ukonceni opravy kolecka
* Zaporny cas slouzi pro nastaveni opravy do stavu False
* @param repairing
* @param time
*/
public void setRepairing(boolean repairing, double time) {
this.repairing = repairing;
if(time < 0) {
this.tr = time;
}
else {
this.tr = time+this.td;
}
}
/**
* Getter opravy kolecka
* @return true pokud se kolecko opravuje jinak false
*/
public boolean getRepairing() {
return this.repairing;
}
/**
* Getter na cas konce opravy
* @return cas konce opravy
*/
public double getTr() {
return tr;
}
/**
* Setter na cas konce opravy
* @param tr novy cas konce
*/
public void setTr(double tr) {
this.tr = tr;
}
}
| Admiam/PT-Uhlik | Uhlik/src/pt/Wheelbarrow.java | 2,309 | /**
* minimalni rychlost kolecka
*/ | block_comment | pl | package pt;
import java.util.Random;
/**
* Trida reprezentujici kolecka a jejich typy
* @author TR
*
*/
public class Wheelbarrow {
/**
* nazev kolecka
*/
public String name;
/**
* min<SUF>*/
private final double vmin;
/**
* maximalni rychlost kolecka
*/
private final double vmax;
/**
* minilani vzzdalenost potrebna pro opravu
*/
private final double dmin;
/**
* maximalni vzdalenost potrebna pro opravu
*/
private final double dmax;
/**
* doba opravy kolecka
*/
private final double td;
/**
* maximalni pocet pytlu na kolecku
*/
private final int kd;
/**
* procentualni zastoupeni kolecka
*/
private final double pd;
/**
* vysledna rychlost generovaneho kolecka
*/
private final double velocity;
/**
* vyslednou urazenou drahu do udrzby generovaneho kolecka
*/
private final double distance;
/**
* pocet kolecek
*/
private static int count = 0;
/**
*id kolecka
*/
private final int id;
/**
* random generator
*/
private final Random rd = new Random();
/**
* aktualni dojezd
*/
private double dcurrent;
/**
* opravuje se
*/
private boolean repairing;
/**
* cas do konce opravy
*/
private double tr;
/**
* Konstrktor pro vytvoreni typu kolecka
* @param name jmeno kolecka
* @param vmin min rychlost
* @param vmax max rychlost
* @param dmin min vzdalenost do udrzby
* @param dmax max vzdalenost do udrzby
* @param td doba opravy
* @param kd pocet pytlu
* @param pd pravdepodobnost kolecka
*/
public Wheelbarrow(String name, double vmin, double vmax, double dmin, double dmax, double td, int kd, double pd) {
this.name = name;
this.vmin = vmin;
this.vmax = vmax;
this.dmin = dmin;
this.dmax = dmax;
this.td = td;
this.kd = kd;
this.pd = pd;
this.id = 0;
this.velocity = 0;
this.distance = 0;
this.repairing = false;
this.dcurrent = 0;
this.tr = Double.MAX_VALUE;
}
/**
* Konstruktor pro vygenerovani kolecka na zaklade jeho druhu
* @param type druh kolecka
*/
public Wheelbarrow(Wheelbarrow type) {
this.name = type.name;
this.velocity = generateVelocity(type.vmax, type.vmin);
this.distance = generateDistance(type.dmax, type.dmin);
this.vmin = type.vmin;
this.vmax = type.vmax;
this.dmin = type.dmin;
this.dmax = type.dmax;
this.td = type.td;
this.kd = type.kd;
this.pd = -1;
count();
this.id = count;
this.repairing = false;
this.dcurrent = distance;
this.tr = -1;
}
/**
* Metoda zvysujici pocitac kolecek
*/
private void count() {
count++;
}
/**
* Metoda vypisujici jmeno kolecka
*
* @return vraci jmeno kolecka
*/
public String getName(){
return name;
}
/**
* Metoda generujici rychlost kolecka
* @param vx max rychlost
* @param vn min rychlost
* @return vraci vyslednou rychlost
*/
private double generateVelocity(double vx, double vn){
double v = vn + (vx - vn) * rd.nextDouble();
return v;
}
/**
* Metoda generujici vzdalenost do udrzby kolecka
* @param dmax maximalni vzdalenost
* @param dmin minimalni vzdalenost
* @return vraci vzdalenost do udrzby
*/
private double generateDistance(double dmax, double dmin) {
double mi = (dmin + dmax) / 2;
double sigma = (dmax - dmin) / 4;
double dfinal = rd.nextGaussian() * sigma + mi;
return dfinal;
}
/**
* Getter pro cas potrebny na opravu kolecka
* @return
*/
public double getRepairTime() {
return td;
}
/**
* Getter pro objem (pocet pytlu) kolecka
* @return vraci pocet pytlu kolecka
*/
public int getVolume() {
return kd;
}
/**
* Getter pro rychlost kolecka
* @return vraci rychlost kolecka
*/
public double getVelocity() {
return velocity;
}
/**
* Getter pro vzdalenost potrebnou do udrzby
* @return vraci vzdalenost do udrzby
*/
public double getDistance() {
return distance;
}
/**
* Getter pro ziskani pravdepodobnosti druhu kolecka
* @return vraci pravdepodobnost druhu kolecka
*/
public double getProbability() {
return pd;
}
/**
* Getter pro ziskani id kolecka
* @return vraci id kolecka
*/
public int getID() {
return id;
}
/**
* Vypis id pro kontrolu
*/
public void printID() {
System.out.println("ID: " + id);
}
/**
* Getter na maximalni vzdalenost
* @return vraci max vzdalenost
*/
public double getDMax(){
return dmax;
}
/**
* Getter aktualni vzdalenosti
* @return aktualni vzdalenost
*/
public double getDcurrent() {
return dcurrent;
}
/**
* Setter pro nastaveni aktualni vzdalenosti
* @param dcurrent hodnota vzdalenosti
* @param m znacka - pokud true tak menim hodnotu, pokud false tak odecitam od aktualni hodnoty
*/
public void setDcurrent(double dcurrent, boolean m) {
if(m) {
this.dcurrent = dcurrent;
}
else {
this.dcurrent -= dcurrent;
}
}
/**
* Setter pro spusteni/ukonceni opravy kolecka
* Zaporny cas slouzi pro nastaveni opravy do stavu False
* @param repairing
* @param time
*/
public void setRepairing(boolean repairing, double time) {
this.repairing = repairing;
if(time < 0) {
this.tr = time;
}
else {
this.tr = time+this.td;
}
}
/**
* Getter opravy kolecka
* @return true pokud se kolecko opravuje jinak false
*/
public boolean getRepairing() {
return this.repairing;
}
/**
* Getter na cas konce opravy
* @return cas konce opravy
*/
public double getTr() {
return tr;
}
/**
* Setter na cas konce opravy
* @param tr novy cas konce
*/
public void setTr(double tr) {
this.tr = tr;
}
}
|
49826_0 | package com.adrjan.gymtracker.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class MeasureForm {
// TODO Dodać odpowiednie komunikaty w odpowiedniej chwili.
// Obecnie wali komunikatem 'nie może mieć wartości null'.
@NotNull @Positive
private Double leftBiceps;
@NotNull @Positive
private Double rightBiceps;
@NotNull @Positive
private Double chest;
@NotNull @Positive
private Double waist;
@NotNull @Positive
private Double leftThigh;
@NotNull @Positive
private Double rightThigh;
@NotNull @Positive
private Double weight;
}
| AdrJan/gym-tracker | src/main/java/com/adrjan/gymtracker/model/MeasureForm.java | 253 | // TODO Dodać odpowiednie komunikaty w odpowiedniej chwili. | line_comment | pl | package com.adrjan.gymtracker.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class MeasureForm {
// TO<SUF>
// Obecnie wali komunikatem 'nie może mieć wartości null'.
@NotNull @Positive
private Double leftBiceps;
@NotNull @Positive
private Double rightBiceps;
@NotNull @Positive
private Double chest;
@NotNull @Positive
private Double waist;
@NotNull @Positive
private Double leftThigh;
@NotNull @Positive
private Double rightThigh;
@NotNull @Positive
private Double weight;
}
|
142277_3 | package pl.edu.pg.eti.ksg.po.lab2.symulatorwycieczki;
/**
*
* @author TB
*/
public interface Uczestnik {
/**
* @return Bazowa prędkość z którą porusza się uczestnik. Wyrażona w GOT/h.
*/
double getBazowaPredkosc();
/**
* @return Umiejętnośc znajdywania drogi w terenie wyrażona w skali 1-5
*/
int getUmiejetnosciNawigacyjne();
/**
* @return Poziom zmęczenia w skali 0-1, gdzie 0 to uczestnik wypoczęty a 1 zmęczony tak, że nie może dalej wędrować.
*/
double getPoziomZmeczenia();
void reagujNaAtrakcje(Atrakcja a);
void opiszWycieczke(Wycieczka wycieczka);
void reagujNaWedrowke(Wedrowka w, double czas);
}
| Adrian-Sciepura/Studies | Object-oriented programming/laboratory-4/pl/edu/pg/eti/ksg/po/lab2/symulatorwycieczki/Uczestnik.java | 297 | /**
* @return Poziom zmęczenia w skali 0-1, gdzie 0 to uczestnik wypoczęty a 1 zmęczony tak, że nie może dalej wędrować.
*/ | block_comment | pl | package pl.edu.pg.eti.ksg.po.lab2.symulatorwycieczki;
/**
*
* @author TB
*/
public interface Uczestnik {
/**
* @return Bazowa prędkość z którą porusza się uczestnik. Wyrażona w GOT/h.
*/
double getBazowaPredkosc();
/**
* @return Umiejętnośc znajdywania drogi w terenie wyrażona w skali 1-5
*/
int getUmiejetnosciNawigacyjne();
/**
* @re<SUF>*/
double getPoziomZmeczenia();
void reagujNaAtrakcje(Atrakcja a);
void opiszWycieczke(Wycieczka wycieczka);
void reagujNaWedrowke(Wedrowka w, double czas);
}
|
2842_4 | package pl.edu.uwm.po.lab_01;
import java.lang.Math;
public class Start {
public static void main(String[] args) {
//System.out.println(z01());
//System.out.println(z02());
//System.out.println(z03());
//z04();
//z05();
//z06();
//z09();
//z10();
//z11();
z12();
}
static int z01 () {
return 31 + 29 + 31;
}
static int z02 () {
int sum=0;
for (int i=1;i<=10;i++){
sum+=i;
}
return sum;
}
static int z03 () {
int il=1;
for (int i=1;i<=10;i++){
il*=i;
}
return il;
}
static void z04 () {
float s=1000;
for (int i=1;i<=2;i++){
s*=1.06;
System.out.println(Math.round(s * 100.0) / 100.0);
}
}
static void z05 () {
System.out.println("+----+");
System.out.println("|JAVA|");
System.out.println("+----+");
}
static void z06 () {
System.out.println(" /////");
System.out.println(" +\"\"\"\"\"+");
System.out.println("(| o o |)");
System.out.println(" | ^ |");
System.out.println(" | `-' |");
System.out.println(" +-----+");
}
static void z09 () {
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@@@@@@@@@@// //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@@# @@@@@@@@@@@@@@@@, *@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@@@@@@@@ /@@@@@@@@@@@@@@@@@@@@@&#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("@@@@@@@ @@@@@@@ HELLO JUNIOR @@@@@@@@@@@@@ &@@@@@@@@@@@@@@@ /(((( @@% &@@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("@@@@@ @@@@@@@@@@@@@ CODER! @@@@@@@@@@@@@@@@@ @@@@@@@@@@@@.*(((((/ ((((((( @@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ &@@@@@@@@@#*(((((/(((((* @@@@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ &@@@@@@@@@#*(((((/(((((* @@@@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("@@@ #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@& @@@@@@@@. ((((((((((((((((((* @@@@@@@@@@@@@@@@@@@@@");
System.out.println("@@@ @@@@@@@@@@@@ You're just watching @@@@@@@@@@ &@@@@ ,((((((((((((*..*((((((((* @@@@@@@@@@@@@@@@@@");
System.out.println("@@@ #@@@@@@@@@@@ on a blue bird from @@@@@@@@@@@ @@@ ..@@@@% (((( @@@@@@@@@ ((((((( &@@@@@@@@@@@@@@@");
System.out.println("@@@% @@@@@@@@@@@ game 'Angry bird'! @@@@@@@@@@@ /@@ ,@@@@@@@@@ /%@/@@@@@@@@@.(((((((( %@@@@@@@@@@@@@");
System.out.println("@@@@* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@ @ @@@@@@ ,@ @@@@@@@@.(((((((((# @@@@@@@@@@@@");
System.out.println("@@@@@@, @@@@@@@@@@ Beautiful one? @@@@@@@@@@ *@@ # .(@% ,######/ #@@@@@%* / (((((((((( @@@@@@@@@@@");
System.out.println("@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ / ,@@@ ( *################ //////**(((((((((/.@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@ /@@@@@@@@@@@@@@@@@@@@/ @@@, @@@/ (#####################*.// (((((((((((( @@@@@@@@@@");
System.out.println("@@@@@@@@@@@@@@@@@@ @@@@@@@@@ @# ########/, *((((((((((((( @@ @@");
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@% (@@@@@@@( @#@//(((((((/*#. ..,,. ### ((((((((((((( */ &@");
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#. @@@ ((((((*(# ,,,,,,. #####.((((((((((((( &@@@@@");
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@//@@@ ((((*(# ,,,,,, /######.((((((((((((( @@@@ @@@");
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ((#,## ,,,, ,########,((((((((((((( @@@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#.,##, #######%* .((((((((((((( %@@@@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*#######, ,(((((((((((((((((/ @@@@@@@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ . (((((((((((((((((((( @@@@@@@@@@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&* ... *@@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
}
static void z10 () {
System.out.println("No.1. Sweeney Todd: The Demon Barber from Fleet Street");
System.out.println("No.2. Imaginaerum");
System.out.println("No.3. Skyfall");
}
static void z11 () {
System.out.print("Wywód Jestem’u\n" +
"Miron Białoszewski\n"+
"\n" +
"jestem sobie\n" +
"jestem głupi\n" +
"co mam robić\n" +
"jak nie wiedzieć\n" +
"a co ja wiem\n" +
"co ja wiem\n" +
"co ja jestem\n" +
"wiem, że jestem\n" +
"taki jak jestem\n" +
"może nieglupi\n" +
"ale to może tylko dlatego że wiem\n" +
"że każdy dla siebie jest najważniejszy\n" +
"bo jak się na siebie nie godzi\n" +
"to i tak taki jest się jaki jest");
}
static void z12() {
System.out.println("* * * * * * =====================================");
System.out.println(" * * * * *");
System.out.println("* * * * * * =====================================");
System.out.println(" * * * * *");
System.out.println("* * * * * * =====================================");
System.out.println("");
System.out.println("=================================================");
System.out.println("");
System.out.println("=================================================");
System.out.println("");
System.out.println("=================================================");
}
}
| AdrianAlbrecht/PO_20-21 | Lab_01/src/pl/edu/uwm/po/lab_01/Start.java | 2,506 | //z05(); | line_comment | pl | package pl.edu.uwm.po.lab_01;
import java.lang.Math;
public class Start {
public static void main(String[] args) {
//System.out.println(z01());
//System.out.println(z02());
//System.out.println(z03());
//z04();
//z0<SUF>
//z06();
//z09();
//z10();
//z11();
z12();
}
static int z01 () {
return 31 + 29 + 31;
}
static int z02 () {
int sum=0;
for (int i=1;i<=10;i++){
sum+=i;
}
return sum;
}
static int z03 () {
int il=1;
for (int i=1;i<=10;i++){
il*=i;
}
return il;
}
static void z04 () {
float s=1000;
for (int i=1;i<=2;i++){
s*=1.06;
System.out.println(Math.round(s * 100.0) / 100.0);
}
}
static void z05 () {
System.out.println("+----+");
System.out.println("|JAVA|");
System.out.println("+----+");
}
static void z06 () {
System.out.println(" /////");
System.out.println(" +\"\"\"\"\"+");
System.out.println("(| o o |)");
System.out.println(" | ^ |");
System.out.println(" | `-' |");
System.out.println(" +-----+");
}
static void z09 () {
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@@@@@@@@@@// //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@@# @@@@@@@@@@@@@@@@, *@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@@@@@@@@ /@@@@@@@@@@@@@@@@@@@@@&#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("@@@@@@@ @@@@@@@ HELLO JUNIOR @@@@@@@@@@@@@ &@@@@@@@@@@@@@@@ /(((( @@% &@@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("@@@@@ @@@@@@@@@@@@@ CODER! @@@@@@@@@@@@@@@@@ @@@@@@@@@@@@.*(((((/ ((((((( @@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ &@@@@@@@@@#*(((((/(((((* @@@@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ &@@@@@@@@@#*(((((/(((((* @@@@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("@@@ #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@& @@@@@@@@. ((((((((((((((((((* @@@@@@@@@@@@@@@@@@@@@");
System.out.println("@@@ @@@@@@@@@@@@ You're just watching @@@@@@@@@@ &@@@@ ,((((((((((((*..*((((((((* @@@@@@@@@@@@@@@@@@");
System.out.println("@@@ #@@@@@@@@@@@ on a blue bird from @@@@@@@@@@@ @@@ ..@@@@% (((( @@@@@@@@@ ((((((( &@@@@@@@@@@@@@@@");
System.out.println("@@@% @@@@@@@@@@@ game 'Angry bird'! @@@@@@@@@@@ /@@ ,@@@@@@@@@ /%@/@@@@@@@@@.(((((((( %@@@@@@@@@@@@@");
System.out.println("@@@@* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@ @ @@@@@@ ,@ @@@@@@@@.(((((((((# @@@@@@@@@@@@");
System.out.println("@@@@@@, @@@@@@@@@@ Beautiful one? @@@@@@@@@@ *@@ # .(@% ,######/ #@@@@@%* / (((((((((( @@@@@@@@@@@");
System.out.println("@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ / ,@@@ ( *################ //////**(((((((((/.@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@ /@@@@@@@@@@@@@@@@@@@@/ @@@, @@@/ (#####################*.// (((((((((((( @@@@@@@@@@");
System.out.println("@@@@@@@@@@@@@@@@@@ @@@@@@@@@ @# ########/, *((((((((((((( @@ @@");
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@% (@@@@@@@( @#@//(((((((/*#. ..,,. ### ((((((((((((( */ &@");
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#. @@@ ((((((*(# ,,,,,,. #####.((((((((((((( &@@@@@");
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@//@@@ ((((*(# ,,,,,, /######.((((((((((((( @@@@ @@@");
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ((#,## ,,,, ,########,((((((((((((( @@@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#.,##, #######%* .((((((((((((( %@@@@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*#######, ,(((((((((((((((((/ @@@@@@@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ . (((((((((((((((((((( @@@@@@@@@@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&* ... *@@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
}
static void z10 () {
System.out.println("No.1. Sweeney Todd: The Demon Barber from Fleet Street");
System.out.println("No.2. Imaginaerum");
System.out.println("No.3. Skyfall");
}
static void z11 () {
System.out.print("Wywód Jestem’u\n" +
"Miron Białoszewski\n"+
"\n" +
"jestem sobie\n" +
"jestem głupi\n" +
"co mam robić\n" +
"jak nie wiedzieć\n" +
"a co ja wiem\n" +
"co ja wiem\n" +
"co ja jestem\n" +
"wiem, że jestem\n" +
"taki jak jestem\n" +
"może nieglupi\n" +
"ale to może tylko dlatego że wiem\n" +
"że każdy dla siebie jest najważniejszy\n" +
"bo jak się na siebie nie godzi\n" +
"to i tak taki jest się jaki jest");
}
static void z12() {
System.out.println("* * * * * * =====================================");
System.out.println(" * * * * *");
System.out.println("* * * * * * =====================================");
System.out.println(" * * * * *");
System.out.println("* * * * * * =====================================");
System.out.println("");
System.out.println("=================================================");
System.out.println("");
System.out.println("=================================================");
System.out.println("");
System.out.println("=================================================");
}
}
|
35913_1 | package pl.sdacademy.java.hibernate.workshop12;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import pl.sdacademy.java.hibernate.common.sakila.Country;
import pl.sdacademy.java.hibernate.utils.ApplicationPropertiesProvider;
import java.util.Properties;
import java.util.Scanner;
/*
Przygotuj metodę zmieniającą kraj według podanego identyfikatora i nazwy, niech zwraca true jeśli istniał i false jeśli nie (find(...) zwróci null).
Zmień stan zarządzanego obiektu w trakcie transakcji używając zwykłego settera.
Przetestuj następujące scenariusze:
* Kraj nie istnieje (ma zwrócić false).
* Dowolny inny kraj (ma go zmienić i zwrócić true).
*/
public class Workshop12 {
public static void main(String[] args) {
final var scanner = new Scanner(System.in);
System.out.println("Podaj id kraju:");
final long countryId = Long.parseLong(scanner.nextLine());
System.out.println("Podaj nazwę kraju:");
final String newName = scanner.nextLine();
final var result = renameCountry(ApplicationPropertiesProvider.getSakilaProperties(), countryId, newName);
System.out.println("Wynik: " + result);
}
public static boolean renameCountry(Properties properties, long countryId, String newName) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("SakilaPU", properties);
EntityManager entityManager = entityManagerFactory.createEntityManager();
try {
final Country country = entityManager.find(Country.class, countryId);
// Nie powinniśmy wychodzić z metody w trakcie otwartej transakcji!
if (country == null) {
return false;
}
entityManager.getTransaction().begin();
country.setName(newName);
entityManager.getTransaction().commit();
}
catch(Exception e) {
entityManager.getTransaction().rollback();
throw new RuntimeException(e);
}
finally {
entityManagerFactory.close();
}
return true;
}
}
| AdrianSzydlowski/sda-zdjava124 | hibernate/src/main/java/pl/sdacademy/java/hibernate/workshop12/Workshop12.java | 621 | // Nie powinniśmy wychodzić z metody w trakcie otwartej transakcji! | line_comment | pl | package pl.sdacademy.java.hibernate.workshop12;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import pl.sdacademy.java.hibernate.common.sakila.Country;
import pl.sdacademy.java.hibernate.utils.ApplicationPropertiesProvider;
import java.util.Properties;
import java.util.Scanner;
/*
Przygotuj metodę zmieniającą kraj według podanego identyfikatora i nazwy, niech zwraca true jeśli istniał i false jeśli nie (find(...) zwróci null).
Zmień stan zarządzanego obiektu w trakcie transakcji używając zwykłego settera.
Przetestuj następujące scenariusze:
* Kraj nie istnieje (ma zwrócić false).
* Dowolny inny kraj (ma go zmienić i zwrócić true).
*/
public class Workshop12 {
public static void main(String[] args) {
final var scanner = new Scanner(System.in);
System.out.println("Podaj id kraju:");
final long countryId = Long.parseLong(scanner.nextLine());
System.out.println("Podaj nazwę kraju:");
final String newName = scanner.nextLine();
final var result = renameCountry(ApplicationPropertiesProvider.getSakilaProperties(), countryId, newName);
System.out.println("Wynik: " + result);
}
public static boolean renameCountry(Properties properties, long countryId, String newName) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("SakilaPU", properties);
EntityManager entityManager = entityManagerFactory.createEntityManager();
try {
final Country country = entityManager.find(Country.class, countryId);
// Ni<SUF>
if (country == null) {
return false;
}
entityManager.getTransaction().begin();
country.setName(newName);
entityManager.getTransaction().commit();
}
catch(Exception e) {
entityManager.getTransaction().rollback();
throw new RuntimeException(e);
}
finally {
entityManagerFactory.close();
}
return true;
}
}
|
133480_3 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import Handler.ExceptionHandler;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author angelina
*/
public class Uslugi {
private int id;
private String nazwa;
private double cena;
public Uslugi(int id, String n, double c)
{
this.cena=c;
this.nazwa=n;
this.id=id;
}
public String getNazwa()
{
return this.nazwa;
}
public void setNazwa(String n)
{
this.nazwa = n;
}
public double getCena()
{
return this.cena;
}
public void setCena(double c)
{
this.cena = c;
}
public int getId()
{
return this.id;
}
public void setId(int id)
{
this.id = id;
}
public void DodajUsluge()
{
PreparedStatement stmt;
try
{
stmt = conn.prepareStatement("INSERT INTO uslugi(nazwa, cena) VALUES(?, ?)");
stmt.setString(1, nazwa);
stmt.setDouble(2, cena);
}catch(SQLException e){
ExceptionHandler.handle(e, ExceptionHandler.MESSAGE);
}
}
public Uslugi getUsluga(int indeks)
{
Statement stmt;
ResultSet rs;
Uslugi result = null;
try {
stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery("SELECT id_uslugi, nazwa, cena FROM uslugi WHERE id_uslugi=" + id + " LIMIT 1");
if(rs.next()) { //jezeli wynik pusty, to metoda zwraca null
result = new Uslugi(rs.getInt(1), rs.getString(2), rs.getDouble(3) );
}
} catch (SQLException e) {
ExceptionHandler.handle(e, ExceptionHandler.MESSAGE);
}
return result;
}
public List<Uslugi> getAll()
{
Statement stmt;
ResultSet rs;
List result = new ArrayList<Uslugi>();
try {
stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery("SELECT id_uslugi, nazwa, cena FROM uslugi");
while(rs.next()) {
result.add( new Uslugi(rs.getInt(1), rs.getString(2), rs.getDouble(3) )) ;
}
} catch (SQLException e) {
ExceptionHandler.handle(e, ExceptionHandler.MESSAGE);
}
return result;
}
static Connection conn = null;
public void changePriceId(double percent, int id)
{
PreparedStatement stmt;
try {
stmt = conn.prepareStatement("UPDATE uslugi SET cena=cena*? WHERE id_uslugi=?");
stmt.setDouble(1, percent);
stmt.setInt(2, id);
} catch (SQLException e) {
ExceptionHandler.handle(e, ExceptionHandler.MESSAGE);
}
}
//Cena dla klientów z powyżej pięcioma wizytami jest o 10% niższa
public double getCena(int id_klienta, int id_wizyty)
{
Statement stmt;
ResultSet rs;
int iloscWizyt = 0;
double cena = 0.0;
try {
stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery("SELECT count(id_klienta) FROM wizyty WHERE id_klienta=" + id_klienta);
if(rs.next()) { //jezeli wynik pusty, to metoda zwraca null
iloscWizyt =rs.getInt(1);
}
} catch (SQLException e) {
ExceptionHandler.handle(e, ExceptionHandler.MESSAGE);
}
try {
stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery("SELECT u.cena FROM wizyty w, usugi u WHERE u.id_usugi=w.id_uslugi AND w.id_klienta="+id_klienta+"AND w.id_wizyty="+id_wizyty);
if(rs.next()) { //jezeli wynik pusty, to metoda zwraca null
cena =rs.getDouble(1);
}
} catch (SQLException e) {
ExceptionHandler.handle(e, ExceptionHandler.MESSAGE);
}
if(iloscWizyt > 5)
{
cena = 0.9*cena;
}
return cena;
}
}
| AdrianWii/BeautyStudioManagment | src/Model/Uslugi.java | 1,490 | //Cena dla klientów z powyżej pięcioma wizytami jest o 10% niższa | 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 Model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import Handler.ExceptionHandler;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author angelina
*/
public class Uslugi {
private int id;
private String nazwa;
private double cena;
public Uslugi(int id, String n, double c)
{
this.cena=c;
this.nazwa=n;
this.id=id;
}
public String getNazwa()
{
return this.nazwa;
}
public void setNazwa(String n)
{
this.nazwa = n;
}
public double getCena()
{
return this.cena;
}
public void setCena(double c)
{
this.cena = c;
}
public int getId()
{
return this.id;
}
public void setId(int id)
{
this.id = id;
}
public void DodajUsluge()
{
PreparedStatement stmt;
try
{
stmt = conn.prepareStatement("INSERT INTO uslugi(nazwa, cena) VALUES(?, ?)");
stmt.setString(1, nazwa);
stmt.setDouble(2, cena);
}catch(SQLException e){
ExceptionHandler.handle(e, ExceptionHandler.MESSAGE);
}
}
public Uslugi getUsluga(int indeks)
{
Statement stmt;
ResultSet rs;
Uslugi result = null;
try {
stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery("SELECT id_uslugi, nazwa, cena FROM uslugi WHERE id_uslugi=" + id + " LIMIT 1");
if(rs.next()) { //jezeli wynik pusty, to metoda zwraca null
result = new Uslugi(rs.getInt(1), rs.getString(2), rs.getDouble(3) );
}
} catch (SQLException e) {
ExceptionHandler.handle(e, ExceptionHandler.MESSAGE);
}
return result;
}
public List<Uslugi> getAll()
{
Statement stmt;
ResultSet rs;
List result = new ArrayList<Uslugi>();
try {
stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery("SELECT id_uslugi, nazwa, cena FROM uslugi");
while(rs.next()) {
result.add( new Uslugi(rs.getInt(1), rs.getString(2), rs.getDouble(3) )) ;
}
} catch (SQLException e) {
ExceptionHandler.handle(e, ExceptionHandler.MESSAGE);
}
return result;
}
static Connection conn = null;
public void changePriceId(double percent, int id)
{
PreparedStatement stmt;
try {
stmt = conn.prepareStatement("UPDATE uslugi SET cena=cena*? WHERE id_uslugi=?");
stmt.setDouble(1, percent);
stmt.setInt(2, id);
} catch (SQLException e) {
ExceptionHandler.handle(e, ExceptionHandler.MESSAGE);
}
}
//Ce<SUF>
public double getCena(int id_klienta, int id_wizyty)
{
Statement stmt;
ResultSet rs;
int iloscWizyt = 0;
double cena = 0.0;
try {
stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery("SELECT count(id_klienta) FROM wizyty WHERE id_klienta=" + id_klienta);
if(rs.next()) { //jezeli wynik pusty, to metoda zwraca null
iloscWizyt =rs.getInt(1);
}
} catch (SQLException e) {
ExceptionHandler.handle(e, ExceptionHandler.MESSAGE);
}
try {
stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery("SELECT u.cena FROM wizyty w, usugi u WHERE u.id_usugi=w.id_uslugi AND w.id_klienta="+id_klienta+"AND w.id_wizyty="+id_wizyty);
if(rs.next()) { //jezeli wynik pusty, to metoda zwraca null
cena =rs.getDouble(1);
}
} catch (SQLException e) {
ExceptionHandler.handle(e, ExceptionHandler.MESSAGE);
}
if(iloscWizyt > 5)
{
cena = 0.9*cena;
}
return cena;
}
}
|
16139_8 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package institutestrategy;
import java.util.Random;
/**
*
* @author mlyczkowska2
*/
public class instituteStrategy {
private static final int RANDOM_RANGE = 99;
/**
* n - długosc wektora, rozmiar macierzy
*/
private static final int n = 10;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
/**
* C - tablica wypłat dla wektora y, macierz NxN, wypełniona losowymi
* liczbami naturalnymi
*/
int[][] C = new int[n][n];
/**
* x - składa się z ułamków sumujących się do 1
*/
double[] x = new double[n];
/**
* R - tablica wypłat dla wektora x, macierz NxN, wypełniona losowymi
* liczbami naturalnymi
*/
int[][] R = new int[n][n];
/**
* y - wektor o rozmiarze n, składa się z jednej "1", pozostałe "0"
*/
double[] y = new double[n];
double[][] coefficients = new double[n][n];
double[] linearCoefficients = new double[n];
Random generator = new Random();
/**
* inicjalizacja wektora x
*/
x = initializeVector(n);
boolean haveCorrectSum = validateVectorSum(x);
if (haveCorrectSum == false) {
System.out.println(
"Vector x has not been properly initialized.\n"
+ "The sum of the elements are different from one");
x = initializeVector(n);
}
System.out.println("\nWEKTOR x");
displayVector(x, "x");
/**
* inicjalizacja danych macierzy C
*/
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
C[i][j] = generator.nextInt(RANDOM_RANGE);
}
}
/**
* inicjalizacja danych macierzy R
*/
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
R[i][j] = generator.nextInt(RANDOM_RANGE);
}
}
System.out.println("\nMACIERZ C");
displayMatrix(C, n, "C");
System.out.println("\nMACIERZ R");
displayMatrix(R, n, "R");
/**
* mnożymy macierz C i wektor x
*/
double[] suma = new double[n];
double wynik = 0;
double tmp = 0;
int q = 0;
for (int j = 0; j < n; j++) {
for (int i = 0; i < n; i++) {
tmp += C[i][j] * x[i];
}
suma[j] = tmp;
if (wynik < tmp) {
wynik = tmp;
q = j + 1;
}
tmp = 0;
}
/**
* wynikiem mnożenia macierzy C i wektora x jest wektor, który musimy
* pomnożyć przez wektor y, tak, aby wynikiem była jak największa
* liczba. W wektorze y 1 może wystąpić tylko raz - więc ustawimy jej
* indeks w tablicy y taki, jak największy element w tablicy z mnożenia
* C i x
*/
System.out.println("\nWYNIK MNOŻENIA MACIERZY C I WEKTORA x:");
displayVector(suma, "s");
/**
* inicjalizacja wektora y
*/
for (int i = 0; i < n; i++) {
if (i == (q - 1)) {
y[i] = 1;
} else {
y[i] = 0;
}
}
System.out.println("\nWEKTOR y");
displayVector(y, "y");
System.out.println("\nSuma dla q[" + q + "] = 1: " + wynik + "\n\n");
/**
* the leader finds the strategy x that maximizes his utility, under the
* assumption that the follower used optimal response a(x): maxq Ei∈X
* Ej∈Q Ri,j*q(x)*xi
*/
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
/**
* szukamy nowe wartości wektora x, tak, aby wielomian miał jak
* największą wartość. Trzeba pamiętać, że elementy wektora x
* muszą sumować się do 1.
*/
coefficients[i][j] = R[i][j] * suma[i];
}
}
System.out.println("\nWSPÓŁCZYNNIKI UKŁADU RÓWNAŃ:");
displayMatrix(coefficients, n, "");
/**
* macierz coefficients to nasz układ równań, dodajmy każdy wiersz
* stronami, tak, aby uzyskać jedno równanie liniowe
*/
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
linearCoefficients[i] += coefficients[j][i];
}
}
System.out.println("\nWSPÓŁCZYNNIKI UKŁADU LINIOWEGO");
displayVector(linearCoefficients, "q");
/**
* musimy teraz wyznaczyć to równanie tak, aby wielomian uzyskał
* maksimum, mamy:
* x[1]*linearCoefficients[1]+...+x[n]*linearCoefficients[n]
*
* dodatkowo musi być spełnione: x[1]+...x[n]=1;
*/
//TODO - rozwiązać układ
//max of x[1]*linearCoefficients[1]+...+x[n]*linearCoefficients[n]
//x[1]+...x[n]=1;
//utwórzmy nowy wektor x, ktorego suma elemento = 1
if (haveCorrectSum == false) {
System.out.println(
"Vector x has not been properly initialized.\n"
+ "The sum of the elements are different from one");
x = initializeVector(n);
}
System.out.println("\nNOWY WEKTOR x");
displayVector(x, "x");
//teraz przypiszmy jego wartośći odpowiednio do najwyższym
//współczynnika najwiekszy x z utworzonego wczesniej wektora
x = sort(x);
System.out.println("\nPOSORTOWANY WEKTOR x");
displayVector(x, "x");
//x = assignMax(x, linearCoefficients);
//policzyc sume i wynik bedzie maksymalna wartoscia.
}
public static double[] initializeVector(int n) {
Random r = new Random();
double result[] = new double[n];
int numbers[] = new int[n];
int sum = 0;
for (int i = 0; i < n - 1; i++) {
numbers[i] = r.nextInt((100 - sum) / 2) + 1;
sum += numbers[i];
}
numbers[n - 1] = 100 - sum;
/**
* normalizacja tablicy, tak, aby elementy sumowały się do 1
*/
for (int i = 0; i < n; i++) {
result[i] = numbers[i] / 100.0;
}
return result;
}
public static void displayVector(double[] vector, String name) {
StringBuilder vectorElements = new StringBuilder();
for (int i = 0; i < vector.length; i++) {
vectorElements.append(name + "[" + (i + 1) + "]=" + vector[i] + " ");
}
System.out.println(vectorElements);
}
public static boolean validateVectorSum(double[] x) {
boolean flag = false;
double sum = 0.;
for (int i = 0; i < x.length; i++) {
sum += x[i];
}
if (sum == 1.0) {
flag = true;
} else {
flag = false;
}
return flag;
}
public static void displayMatrix(int[][] matrix, int n, String name) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(name + "[" + (i + 1) + "][" + (j + 1) + "]=" + matrix[i][j] + " ");
}
System.out.println("");
}
}
public static void displayMatrix(double[][] matrix, int n, String name) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int ii = i + 1;
int jj = j + 1;
System.out.print(name + "[" + (i + 1) + "][" + (j + 1) + "]=" + matrix[i][j] + " ");
}
System.out.println("");
}
}
public static double[] sort(double x[]) {
double temp;
for (int i = 0; i < x.length - 1; i++) {
for (int j = i + 1; j < x.length; j++) {
if (x[j] < x[i]) {
temp = x[j];
x[j] = x[i];
x[i] = temp;
}
}
}
return x;
}
// public static double[] assignMax(double x[], double coefficients[]) {
//
// double[] tempCoefficients = coefficients;
// double[] temp2Coefficients = coefficients;
//
// double[] tempX = new double[n];
// tempCoefficients = sort(coefficients);
//
// for (int i = 0; i < n; i++) {
// for (int j = 0; j < n; j++) {
// if (tempCoefficients[i] == temp2Coefficients[j]) {
// tempX[j] = x[i];
// }
// }
// }
//
// return tempX;
// }
}
| AdrianWii/InstituteStrategy | src/institutestrategy/instituteStrategy.java | 3,126 | /**
* inicjalizacja wektora x
*/ | block_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 institutestrategy;
import java.util.Random;
/**
*
* @author mlyczkowska2
*/
public class instituteStrategy {
private static final int RANDOM_RANGE = 99;
/**
* n - długosc wektora, rozmiar macierzy
*/
private static final int n = 10;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
/**
* C - tablica wypłat dla wektora y, macierz NxN, wypełniona losowymi
* liczbami naturalnymi
*/
int[][] C = new int[n][n];
/**
* x - składa się z ułamków sumujących się do 1
*/
double[] x = new double[n];
/**
* R - tablica wypłat dla wektora x, macierz NxN, wypełniona losowymi
* liczbami naturalnymi
*/
int[][] R = new int[n][n];
/**
* y - wektor o rozmiarze n, składa się z jednej "1", pozostałe "0"
*/
double[] y = new double[n];
double[][] coefficients = new double[n][n];
double[] linearCoefficients = new double[n];
Random generator = new Random();
/**
* ini<SUF>*/
x = initializeVector(n);
boolean haveCorrectSum = validateVectorSum(x);
if (haveCorrectSum == false) {
System.out.println(
"Vector x has not been properly initialized.\n"
+ "The sum of the elements are different from one");
x = initializeVector(n);
}
System.out.println("\nWEKTOR x");
displayVector(x, "x");
/**
* inicjalizacja danych macierzy C
*/
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
C[i][j] = generator.nextInt(RANDOM_RANGE);
}
}
/**
* inicjalizacja danych macierzy R
*/
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
R[i][j] = generator.nextInt(RANDOM_RANGE);
}
}
System.out.println("\nMACIERZ C");
displayMatrix(C, n, "C");
System.out.println("\nMACIERZ R");
displayMatrix(R, n, "R");
/**
* mnożymy macierz C i wektor x
*/
double[] suma = new double[n];
double wynik = 0;
double tmp = 0;
int q = 0;
for (int j = 0; j < n; j++) {
for (int i = 0; i < n; i++) {
tmp += C[i][j] * x[i];
}
suma[j] = tmp;
if (wynik < tmp) {
wynik = tmp;
q = j + 1;
}
tmp = 0;
}
/**
* wynikiem mnożenia macierzy C i wektora x jest wektor, który musimy
* pomnożyć przez wektor y, tak, aby wynikiem była jak największa
* liczba. W wektorze y 1 może wystąpić tylko raz - więc ustawimy jej
* indeks w tablicy y taki, jak największy element w tablicy z mnożenia
* C i x
*/
System.out.println("\nWYNIK MNOŻENIA MACIERZY C I WEKTORA x:");
displayVector(suma, "s");
/**
* inicjalizacja wektora y
*/
for (int i = 0; i < n; i++) {
if (i == (q - 1)) {
y[i] = 1;
} else {
y[i] = 0;
}
}
System.out.println("\nWEKTOR y");
displayVector(y, "y");
System.out.println("\nSuma dla q[" + q + "] = 1: " + wynik + "\n\n");
/**
* the leader finds the strategy x that maximizes his utility, under the
* assumption that the follower used optimal response a(x): maxq Ei∈X
* Ej∈Q Ri,j*q(x)*xi
*/
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
/**
* szukamy nowe wartości wektora x, tak, aby wielomian miał jak
* największą wartość. Trzeba pamiętać, że elementy wektora x
* muszą sumować się do 1.
*/
coefficients[i][j] = R[i][j] * suma[i];
}
}
System.out.println("\nWSPÓŁCZYNNIKI UKŁADU RÓWNAŃ:");
displayMatrix(coefficients, n, "");
/**
* macierz coefficients to nasz układ równań, dodajmy każdy wiersz
* stronami, tak, aby uzyskać jedno równanie liniowe
*/
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
linearCoefficients[i] += coefficients[j][i];
}
}
System.out.println("\nWSPÓŁCZYNNIKI UKŁADU LINIOWEGO");
displayVector(linearCoefficients, "q");
/**
* musimy teraz wyznaczyć to równanie tak, aby wielomian uzyskał
* maksimum, mamy:
* x[1]*linearCoefficients[1]+...+x[n]*linearCoefficients[n]
*
* dodatkowo musi być spełnione: x[1]+...x[n]=1;
*/
//TODO - rozwiązać układ
//max of x[1]*linearCoefficients[1]+...+x[n]*linearCoefficients[n]
//x[1]+...x[n]=1;
//utwórzmy nowy wektor x, ktorego suma elemento = 1
if (haveCorrectSum == false) {
System.out.println(
"Vector x has not been properly initialized.\n"
+ "The sum of the elements are different from one");
x = initializeVector(n);
}
System.out.println("\nNOWY WEKTOR x");
displayVector(x, "x");
//teraz przypiszmy jego wartośći odpowiednio do najwyższym
//współczynnika najwiekszy x z utworzonego wczesniej wektora
x = sort(x);
System.out.println("\nPOSORTOWANY WEKTOR x");
displayVector(x, "x");
//x = assignMax(x, linearCoefficients);
//policzyc sume i wynik bedzie maksymalna wartoscia.
}
public static double[] initializeVector(int n) {
Random r = new Random();
double result[] = new double[n];
int numbers[] = new int[n];
int sum = 0;
for (int i = 0; i < n - 1; i++) {
numbers[i] = r.nextInt((100 - sum) / 2) + 1;
sum += numbers[i];
}
numbers[n - 1] = 100 - sum;
/**
* normalizacja tablicy, tak, aby elementy sumowały się do 1
*/
for (int i = 0; i < n; i++) {
result[i] = numbers[i] / 100.0;
}
return result;
}
public static void displayVector(double[] vector, String name) {
StringBuilder vectorElements = new StringBuilder();
for (int i = 0; i < vector.length; i++) {
vectorElements.append(name + "[" + (i + 1) + "]=" + vector[i] + " ");
}
System.out.println(vectorElements);
}
public static boolean validateVectorSum(double[] x) {
boolean flag = false;
double sum = 0.;
for (int i = 0; i < x.length; i++) {
sum += x[i];
}
if (sum == 1.0) {
flag = true;
} else {
flag = false;
}
return flag;
}
public static void displayMatrix(int[][] matrix, int n, String name) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(name + "[" + (i + 1) + "][" + (j + 1) + "]=" + matrix[i][j] + " ");
}
System.out.println("");
}
}
public static void displayMatrix(double[][] matrix, int n, String name) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int ii = i + 1;
int jj = j + 1;
System.out.print(name + "[" + (i + 1) + "][" + (j + 1) + "]=" + matrix[i][j] + " ");
}
System.out.println("");
}
}
public static double[] sort(double x[]) {
double temp;
for (int i = 0; i < x.length - 1; i++) {
for (int j = i + 1; j < x.length; j++) {
if (x[j] < x[i]) {
temp = x[j];
x[j] = x[i];
x[i] = temp;
}
}
}
return x;
}
// public static double[] assignMax(double x[], double coefficients[]) {
//
// double[] tempCoefficients = coefficients;
// double[] temp2Coefficients = coefficients;
//
// double[] tempX = new double[n];
// tempCoefficients = sort(coefficients);
//
// for (int i = 0; i < n; i++) {
// for (int j = 0; j < n; j++) {
// if (tempCoefficients[i] == temp2Coefficients[j]) {
// tempX[j] = x[i];
// }
// }
// }
//
// return tempX;
// }
}
|
167363_11 | package com.kodilla.patterns.singleton;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class LoggerTestSuite {
@Test
void testGetLastLoad(){
//Given
Logger logger = Logger.getInstance();
String logMessage = "This is a massage for test ";
//When
logger.log(logMessage);
String lastlog = logger.getLastLog();
//Given
Assertions.assertEquals(logMessage , lastlog);
}
@Test
void testGetLastLogAfterMultipleLogs() {
// Given
Logger logger = Logger.getInstance();
String logMessage1 = "First log ";
String logMessage2 = "Second log ";
// When
logger.log(logMessage1);
logger.log(logMessage2);
String lastLog = logger.getLastLog();
// Then
Assertions.assertEquals(logMessage2, lastLog);
}
}
// Utwórz w katalogu src/test/java w pakiecie com.kodilla.patterns.singleton nowy zestaw testów
// o nazwie LoggerTestSuite,a w nim testy sprawdzające działanie metody getLastLog() klasy Logger.
// Aby to przetestować, zapisz coś wcześniej do logów przy pomocy metody log(String log).
// Zmodyfikuj kod klasy Logger tak, aby była zgodna ze wzorcem "Singleton".
// Zmodyfikuj napisane przed chwilą testy tak, aby uwzględniały zmiany w klasie Logger.
// Utworzony kod prześlij do repozytorium GitHub. | Adrtre/module_6.1 | kodilla-patterns/src/test/java/com/kodilla/patterns/singleton/LoggerTestSuite.java | 445 | // Utworzony kod prześlij do repozytorium GitHub. | line_comment | pl | package com.kodilla.patterns.singleton;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class LoggerTestSuite {
@Test
void testGetLastLoad(){
//Given
Logger logger = Logger.getInstance();
String logMessage = "This is a massage for test ";
//When
logger.log(logMessage);
String lastlog = logger.getLastLog();
//Given
Assertions.assertEquals(logMessage , lastlog);
}
@Test
void testGetLastLogAfterMultipleLogs() {
// Given
Logger logger = Logger.getInstance();
String logMessage1 = "First log ";
String logMessage2 = "Second log ";
// When
logger.log(logMessage1);
logger.log(logMessage2);
String lastLog = logger.getLastLog();
// Then
Assertions.assertEquals(logMessage2, lastLog);
}
}
// Utwórz w katalogu src/test/java w pakiecie com.kodilla.patterns.singleton nowy zestaw testów
// o nazwie LoggerTestSuite,a w nim testy sprawdzające działanie metody getLastLog() klasy Logger.
// Aby to przetestować, zapisz coś wcześniej do logów przy pomocy metody log(String log).
// Zmodyfikuj kod klasy Logger tak, aby była zgodna ze wzorcem "Singleton".
// Zmodyfikuj napisane przed chwilą testy tak, aby uwzględniały zmiany w klasie Logger.
// Ut<SUF> |
65345_1 | /*
*
* Projekt pisany przez:
* AdversTM, luxDev, ProgrammingWizard (_an0)
* Aktualnie piszemy wszystko od podstaw, a an0 sie oper*ala
* Zobaczymy co z tego wyjdzie, liczymy na cos ciekawego.
* Wszystko co tu jest, moze ulec zmianie w kazdej chwili, lux zdaje sobie sprawe z optymalnosci kodu (RIP).
*
*
*/
package pl.luxdev.lol;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Squid;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import net.minecraft.server.v1_8_R1.EntityInsentient;
import pl.luxdev.lol.entities.PathFinderGoalWalkTo;
import pl.luxdev.lol.listeners.EntityExplodeList;
import pl.luxdev.lol.listeners.PlayerAttackTurretList;
import pl.luxdev.lol.listeners.PlayerInteractList;
import pl.luxdev.lol.listeners.PlayerInvClickList;
import pl.luxdev.lol.listeners.PlayerJoinList;
import pl.luxdev.lol.managers.ConfigManager;
import pl.luxdev.lol.managers.DataManager;
import pl.luxdev.lol.tasks.MainGameLoop;
import pl.luxdev.lol.utils.Utils;
public class Main extends JavaPlugin implements Listener {
private static Main inst;
public void onEnable(){
inst = this;
Utils.getLogger();
ConfigManager.load();
DataManager.load();
this.getServer().getPluginManager().registerEvents(new PlayerInteractList(), this);
this.getServer().getPluginManager().registerEvents(new PlayerJoinList(), this);
this.getServer().getPluginManager().registerEvents(new EntityExplodeList(), this);
this.getServer().getPluginManager().registerEvents(new PlayerInvClickList(), this);
this.getServer().getPluginManager().registerEvents(new PlayerAttackTurretList(), this);
MainGameLoop.start();
}
public void onDisable(){
inst = null;
}
/*
* TODO
* Napewno to usunac, i zaczac pisac minionki!
* Nie wiem kto to pisal, ale napewno musi isc do izby wytrzeźwień.
*/
private static void SpawnMiniontest(World world, Location spawn, Location walkTo){
Squid squid = world.spawn(spawn, Squid.class);
Bukkit.broadcastMessage("Zrespiono moba, idzie sb tam gdzies xD");
}
public static Main getInst(){
return inst;
}
}
| AdversTM/LeagueOfLegends | src/pl/luxdev/lol/Main.java | 822 | /*
* TODO
* Napewno to usunac, i zaczac pisac minionki!
* Nie wiem kto to pisal, ale napewno musi isc do izby wytrzeźwień.
*/ | block_comment | pl | /*
*
* Projekt pisany przez:
* AdversTM, luxDev, ProgrammingWizard (_an0)
* Aktualnie piszemy wszystko od podstaw, a an0 sie oper*ala
* Zobaczymy co z tego wyjdzie, liczymy na cos ciekawego.
* Wszystko co tu jest, moze ulec zmianie w kazdej chwili, lux zdaje sobie sprawe z optymalnosci kodu (RIP).
*
*
*/
package pl.luxdev.lol;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Squid;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import net.minecraft.server.v1_8_R1.EntityInsentient;
import pl.luxdev.lol.entities.PathFinderGoalWalkTo;
import pl.luxdev.lol.listeners.EntityExplodeList;
import pl.luxdev.lol.listeners.PlayerAttackTurretList;
import pl.luxdev.lol.listeners.PlayerInteractList;
import pl.luxdev.lol.listeners.PlayerInvClickList;
import pl.luxdev.lol.listeners.PlayerJoinList;
import pl.luxdev.lol.managers.ConfigManager;
import pl.luxdev.lol.managers.DataManager;
import pl.luxdev.lol.tasks.MainGameLoop;
import pl.luxdev.lol.utils.Utils;
public class Main extends JavaPlugin implements Listener {
private static Main inst;
public void onEnable(){
inst = this;
Utils.getLogger();
ConfigManager.load();
DataManager.load();
this.getServer().getPluginManager().registerEvents(new PlayerInteractList(), this);
this.getServer().getPluginManager().registerEvents(new PlayerJoinList(), this);
this.getServer().getPluginManager().registerEvents(new EntityExplodeList(), this);
this.getServer().getPluginManager().registerEvents(new PlayerInvClickList(), this);
this.getServer().getPluginManager().registerEvents(new PlayerAttackTurretList(), this);
MainGameLoop.start();
}
public void onDisable(){
inst = null;
}
/*
* TOD<SUF>*/
private static void SpawnMiniontest(World world, Location spawn, Location walkTo){
Squid squid = world.spawn(spawn, Squid.class);
Bukkit.broadcastMessage("Zrespiono moba, idzie sb tam gdzies xD");
}
public static Main getInst(){
return inst;
}
}
|
61357_0 | import java.util.ArrayList;
import java.util.List;
public class Greedy {
private Problem problem;
public Greedy(Problem problem) {
this.problem = problem;
}
public void getBest() {
List<Node> nodes = new ArrayList<>();
for(Node node: problem.nodes){
nodes.add(node.clone());
}
List<Node> visitedNodes = new ArrayList<>();
// zaczynamy od pierszego miasta
visitedNodes.add(nodes.get(0));
int bestIndex;
double bestDistance;
for (int i = 1; i < nodes.size(); i++) {
Node previous = visitedNodes.get(i - 1);
bestDistance = Double.MAX_VALUE;
bestIndex = i;
for (int j = 1; j < nodes.size(); j++) {
double distance = calculateDistance(nodes.get(j), previous);
if (distance < bestDistance) {
bestDistance = distance;
bestIndex = j;
}
}
visitedNodes.add(nodes.get(bestIndex));
nodes.remove(bestIndex);
}
int[] route = new int[visitedNodes.size()];
for (int i = 0; i < route.length; i++) {
route[i] = visitedNodes.get(i).getIndex();
}
Individual individual = new Individual(route, problem);
double fitness = individual.calculateFitnessFunctionValue();
System.out.println("Greedy algorithm: "+ fitness);
}
private double calculateDistance(Node fst, Node snd) {
int xFirst = fst.getxCoord();
int yFirst = fst.getyCoord();
int xSecond = snd.getxCoord();
int ySecond = snd.getyCoord();
return Math.sqrt(Math.pow(Math.abs(xFirst - xSecond), 2) + Math.pow(Math.abs(yFirst - ySecond), 2));
}
public static void main(String[] args) {
Problem problem = new Problem("resources/medium_4.ttp");
Greedy greedy = new Greedy(problem);
greedy.getBest();
}
}
| AgataSkibinska/Genetic-Algorithm | src/Greedy.java | 572 | // zaczynamy od pierszego miasta | line_comment | pl | import java.util.ArrayList;
import java.util.List;
public class Greedy {
private Problem problem;
public Greedy(Problem problem) {
this.problem = problem;
}
public void getBest() {
List<Node> nodes = new ArrayList<>();
for(Node node: problem.nodes){
nodes.add(node.clone());
}
List<Node> visitedNodes = new ArrayList<>();
// za<SUF>
visitedNodes.add(nodes.get(0));
int bestIndex;
double bestDistance;
for (int i = 1; i < nodes.size(); i++) {
Node previous = visitedNodes.get(i - 1);
bestDistance = Double.MAX_VALUE;
bestIndex = i;
for (int j = 1; j < nodes.size(); j++) {
double distance = calculateDistance(nodes.get(j), previous);
if (distance < bestDistance) {
bestDistance = distance;
bestIndex = j;
}
}
visitedNodes.add(nodes.get(bestIndex));
nodes.remove(bestIndex);
}
int[] route = new int[visitedNodes.size()];
for (int i = 0; i < route.length; i++) {
route[i] = visitedNodes.get(i).getIndex();
}
Individual individual = new Individual(route, problem);
double fitness = individual.calculateFitnessFunctionValue();
System.out.println("Greedy algorithm: "+ fitness);
}
private double calculateDistance(Node fst, Node snd) {
int xFirst = fst.getxCoord();
int yFirst = fst.getyCoord();
int xSecond = snd.getxCoord();
int ySecond = snd.getyCoord();
return Math.sqrt(Math.pow(Math.abs(xFirst - xSecond), 2) + Math.pow(Math.abs(yFirst - ySecond), 2));
}
public static void main(String[] args) {
Problem problem = new Problem("resources/medium_4.ttp");
Greedy greedy = new Greedy(problem);
greedy.getBest();
}
}
|
8210_4 | package zad2;
public class FloristsTest {
// definicja metody sumowania wartosci kwiatów o podanym kolorze
static int valueOf(Box box, String color) {
PriceList pl = PriceList.getInstance();
double price = 0;
for (int i = 0; i < box.getList().size(); i++) {
Flower f = box.getList().get(i);
if (f.getColour().equals(color)) price += (f.getQuantity() * pl.getPrice(f));
}
return (int) price;
}
public static void main(String[] args) {
// Kwiaciarnia samoobsługowa
// ustalenie cennika
PriceList pl = PriceList.getInstance();
pl.put("róża", 10.0);
pl.put("bez", 12.0);
pl.put("piwonia", 8.0);
// Przychodzi klient janek. Ma 200 zł
Customer janek = new Customer("Janek", 200);
// Bierze różne kwiaty: 5 róż, 5 piwonii, 3 frezje, 3 bzy
janek.get(new Rose(5));
janek.get(new Peony(5));
janek.get(new Freesia(3));
janek.get(new Lilac(3));
// Pewnie je umieścił na wózku sklepowyem
// Zobaczmy co tam ma
ShoppingCart wozekJanka = janek.getShoppingCart();
System.out.println("Przed płaceniem\n" + wozekJanka);
// Teraz za to zapłaci...
janek.pay();
// Czy przypadkiem przy płaceniu nie okazało się,
// że w koszu są kwiaty na które nie ustalono jeszcze ceny?
// W takim arzie zostałyby usunięte z wózka i Janek nie płaciłby za nie
// Również może mu zabraknąc pieniędzy, wtedy też kwaity są odkładane.
System.out.println("Po zapłaceniu\n" + janek.getShoppingCart());
// Ile Jankowi zostało pieniędzy?
System.out.println("Jankowi zostało : " + janek.getCash() + " zł");
// Teraz jakos zapakuje kwiaty (może do pudełka)
Box pudelkoJanka = new Box(janek);
janek.pack(pudelkoJanka);
// Co jest teraz w wózku Janka...
// (nie powinno już nic być)
System.out.println("Po zapakowaniu do pudełka\n" + janek.getShoppingCart());
// a co w pudełku
System.out.println(pudelkoJanka);
// Zobaczmy jaka jest wartość czerwonych kwiatów w pudełku Janka
System.out.println("Czerwone kwiaty w pudełku Janka kosztowały: "
+ valueOf(pudelkoJanka, "czerwony"));
// Teraz przychodzi Stefan
// ma tylko 60 zł
Customer stefan = new Customer("Stefan", 60);
// Ale nabrał kwiatów nieco za dużo jak na tę sumę
stefan.get(new Lilac(3));
stefan.get(new Rose(5));
// co ma w wózku
System.out.println(stefan.getShoppingCart());
// płaci i pakuje do pudełka
stefan.pay();
Box pudelkoStefana = new Box(stefan);
stefan.pack(pudelkoStefana);
// co ostatecznie udało mu się kupić
System.out.println(pudelkoStefana);
// ... i ile zostało mu pieniędzy
System.out.println("Stefanowi zostało : " + stefan.getCash() + " zł");
}
} | AgelkazzWrenchsprocket/PJATK_JAVA_GUI | lab2/src/zad2/FloristsTest.java | 1,103 | // Bierze różne kwiaty: 5 róż, 5 piwonii, 3 frezje, 3 bzy | line_comment | pl | package zad2;
public class FloristsTest {
// definicja metody sumowania wartosci kwiatów o podanym kolorze
static int valueOf(Box box, String color) {
PriceList pl = PriceList.getInstance();
double price = 0;
for (int i = 0; i < box.getList().size(); i++) {
Flower f = box.getList().get(i);
if (f.getColour().equals(color)) price += (f.getQuantity() * pl.getPrice(f));
}
return (int) price;
}
public static void main(String[] args) {
// Kwiaciarnia samoobsługowa
// ustalenie cennika
PriceList pl = PriceList.getInstance();
pl.put("róża", 10.0);
pl.put("bez", 12.0);
pl.put("piwonia", 8.0);
// Przychodzi klient janek. Ma 200 zł
Customer janek = new Customer("Janek", 200);
// Bi<SUF>
janek.get(new Rose(5));
janek.get(new Peony(5));
janek.get(new Freesia(3));
janek.get(new Lilac(3));
// Pewnie je umieścił na wózku sklepowyem
// Zobaczmy co tam ma
ShoppingCart wozekJanka = janek.getShoppingCart();
System.out.println("Przed płaceniem\n" + wozekJanka);
// Teraz za to zapłaci...
janek.pay();
// Czy przypadkiem przy płaceniu nie okazało się,
// że w koszu są kwiaty na które nie ustalono jeszcze ceny?
// W takim arzie zostałyby usunięte z wózka i Janek nie płaciłby za nie
// Również może mu zabraknąc pieniędzy, wtedy też kwaity są odkładane.
System.out.println("Po zapłaceniu\n" + janek.getShoppingCart());
// Ile Jankowi zostało pieniędzy?
System.out.println("Jankowi zostało : " + janek.getCash() + " zł");
// Teraz jakos zapakuje kwiaty (może do pudełka)
Box pudelkoJanka = new Box(janek);
janek.pack(pudelkoJanka);
// Co jest teraz w wózku Janka...
// (nie powinno już nic być)
System.out.println("Po zapakowaniu do pudełka\n" + janek.getShoppingCart());
// a co w pudełku
System.out.println(pudelkoJanka);
// Zobaczmy jaka jest wartość czerwonych kwiatów w pudełku Janka
System.out.println("Czerwone kwiaty w pudełku Janka kosztowały: "
+ valueOf(pudelkoJanka, "czerwony"));
// Teraz przychodzi Stefan
// ma tylko 60 zł
Customer stefan = new Customer("Stefan", 60);
// Ale nabrał kwiatów nieco za dużo jak na tę sumę
stefan.get(new Lilac(3));
stefan.get(new Rose(5));
// co ma w wózku
System.out.println(stefan.getShoppingCart());
// płaci i pakuje do pudełka
stefan.pay();
Box pudelkoStefana = new Box(stefan);
stefan.pack(pudelkoStefana);
// co ostatecznie udało mu się kupić
System.out.println(pudelkoStefana);
// ... i ile zostało mu pieniędzy
System.out.println("Stefanowi zostało : " + stefan.getCash() + " zł");
}
} |
75889_2 | package window;
import java.io.Serializable;
public enum TaskRelationType implements Serializable {
SS, //Start to Start. Aby zacząć, musi się poprzednie zacząć
SF, //Start to Finish. Aby zakończyć, musi poprzednie się zacząć.
FS, //Finish to Start. Aby zacząć, musi poprzednie się zakończyć
FF; //Finish to Finish, Aby zakończyć, musi poprzednie się zakończyć.
}
| AgiiCat/Gantt | src/window/TaskRelationType.java | 144 | //Finish to Start. Aby zacząć, musi poprzednie się zakończyć | line_comment | pl | package window;
import java.io.Serializable;
public enum TaskRelationType implements Serializable {
SS, //Start to Start. Aby zacząć, musi się poprzednie zacząć
SF, //Start to Finish. Aby zakończyć, musi poprzednie się zacząć.
FS, //Fi<SUF>
FF; //Finish to Finish, Aby zakończyć, musi poprzednie się zakończyć.
}
|
21342_20 | import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import pages.ChosenResult;
import pages.GoogleSearch;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class TestGoogle {
WebDriver driver;
@Before
public void testSetup() {
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
driver = new ChromeDriver();
driver.navigate().to("http://www.google.com");
}
@After
public void tearDown() {
driver.close();
}
@Test
public void testGooglePage() {
GoogleSearch googleSearch = new GoogleSearch(driver);
googleSearch.searchResults();
}
@Test
public void chooseElementToBeClickedByIndex() {
//given
GoogleSearch googleSearch = new GoogleSearch(driver);
ChosenResult chosenResult = new ChosenResult(driver);
WebDriverWait wait = new WebDriverWait(driver,10);
googleSearch.searchResults();
wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//*[@class='g']")));
chosenResult.storeResultsToClick();
//when
//chcę wywołać 5. wynik wyszukiwania - to się zmienia dość szybko, strony poniżej strony głównej Kodilli
// potrafią "wymieniać się" miejscami przy kolejnych próbach uruchomienia testu przez pozycjonowanie SEO
WebElement expectedClickable = driver.findElement(By.xpath("//*[@class='g'][5]/div/div[1]/a/h3/span"));
System.out.println("Expected: " + expectedClickable.getText());
List<String> allowedResults = new ArrayList<>();
allowedResults.add("Czy warto iść na kurs programowania Kodilla? - Girl Into The ...");
allowedResults.add("Kodilla - opinie, informacje, kursy | Bootcampy.pl");
allowedResults.add("Dlaczego wybrałam Bootcamp Kodilla | BedeProgramistka.pl");
allowedResults.add("Kodilla - Home | Facebook");
allowedResults.add("Kodilla - znaleziska i wpisy o #kodilla w Wykop.pl");
wait.until(ExpectedConditions.visibilityOf(expectedClickable));
chosenResult.getChosenWebsiteElement(4);
String chosenElementHeadline = chosenResult.getChosenWebsiteElement(4).findElement(By.tagName("span")).getText();
System.out.println(chosenElementHeadline);
//then
//tutaj nie wiem, czemu przestało przechodzić
assertTrue(allowedResults.contains(chosenElementHeadline));
}
@Test
public void elementChosenToBeClickedIsNotUnexpectedOne() {
//given
GoogleSearch googleSearch = new GoogleSearch(driver);
ChosenResult chosenResult = new ChosenResult(driver);
WebDriverWait wait = new WebDriverWait(driver,10);
googleSearch.searchResults();
wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//*[@class='g']")));
chosenResult.storeResultsToClick();
//when
//wybieram na wynik false stronę główną Kodilli (wynik 1.)
WebElement expectedToBeFalse = driver.findElement(By.xpath("//*[@id=\"rso\"]/div[1]/div/div/div/div[1]/a/h3/span"));
String expectedToBeFalseTitle = expectedToBeFalse.getText();
System.out.println("Expected to assert false: " + expectedToBeFalseTitle);
chosenResult.getChosenWebsiteElement(4);
String chosenElementHeadline = chosenResult.getChosenWebsiteElement(4).findElement(By.tagName("span")).getText();
System.out.println("Chosen by method: " + chosenElementHeadline);
//then
assertNotEquals(String.valueOf(expectedToBeFalseTitle),String.valueOf(chosenElementHeadline));
}
@Test
public void clickedElementIsOneChosenToBeClicked() {
//given
GoogleSearch googleSearch = new GoogleSearch(driver);
ChosenResult chosenResult = new ChosenResult(driver);
WebDriverWait wait = new WebDriverWait(driver,10);
googleSearch.searchResults();
wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//*[@class='g']")));
chosenResult.storeResultsToClick();
//when
//tu zaczęło wychodzić na Index Out Of Bounds, bo jest już tylko 5 wyników na 1. stronie wyszukiwania, a nie 6 tak jak podczas pierwszego
// rozwiązywania zadania
chosenResult.getChosenWebsiteElement(2);
String expectedTitle = chosenResult.getChosenWebsiteElement(2).findElement(By.tagName("span")).getText();
chosenResult.clickChosenElement();
//czekam na załadowanie nowej strony
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//html/body")));
String openedWebsiteTitle = driver.getTitle();
System.out.println(openedWebsiteTitle);
//then
assertEquals(expectedTitle, openedWebsiteTitle);
}
@Test
public void clickedElementIsNotOneNotChosenToBeClicked() {
//given
GoogleSearch googleSearch = new GoogleSearch(driver);
ChosenResult chosenResult = new ChosenResult(driver);
WebDriverWait wait = new WebDriverWait(driver,10);
googleSearch.searchResults();
wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//*[@class='g']")));
chosenResult.storeResultsToClick();
//when
//wybieram na wynik false stronę główną Kodilli (wynik 1.)
WebElement expectedToBeFalse = driver.findElement(By.xpath("//*[@id=\"rso\"]/div[1]/div/div/div/div[1]/a/h3/span"));
String expectedToBeFalseTitle = expectedToBeFalse.getText();
System.out.println("Expected to assert false: " + expectedToBeFalseTitle);
chosenResult.getChosenWebsiteElement(2);
chosenResult.clickChosenElement();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//html/body")));
String openedWebsiteTitle = driver.getTitle();
System.out.println(openedWebsiteTitle);
//then
assertNotEquals(expectedToBeFalseTitle, openedWebsiteTitle);
}
}
| AgnesKkj/agnieszka_korowaj-kodilla_tester | kodilla-google-selenium/src/test/java/TestGoogle.java | 1,856 | //czekam na załadowanie nowej strony | line_comment | pl | import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import pages.ChosenResult;
import pages.GoogleSearch;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class TestGoogle {
WebDriver driver;
@Before
public void testSetup() {
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
driver = new ChromeDriver();
driver.navigate().to("http://www.google.com");
}
@After
public void tearDown() {
driver.close();
}
@Test
public void testGooglePage() {
GoogleSearch googleSearch = new GoogleSearch(driver);
googleSearch.searchResults();
}
@Test
public void chooseElementToBeClickedByIndex() {
//given
GoogleSearch googleSearch = new GoogleSearch(driver);
ChosenResult chosenResult = new ChosenResult(driver);
WebDriverWait wait = new WebDriverWait(driver,10);
googleSearch.searchResults();
wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//*[@class='g']")));
chosenResult.storeResultsToClick();
//when
//chcę wywołać 5. wynik wyszukiwania - to się zmienia dość szybko, strony poniżej strony głównej Kodilli
// potrafią "wymieniać się" miejscami przy kolejnych próbach uruchomienia testu przez pozycjonowanie SEO
WebElement expectedClickable = driver.findElement(By.xpath("//*[@class='g'][5]/div/div[1]/a/h3/span"));
System.out.println("Expected: " + expectedClickable.getText());
List<String> allowedResults = new ArrayList<>();
allowedResults.add("Czy warto iść na kurs programowania Kodilla? - Girl Into The ...");
allowedResults.add("Kodilla - opinie, informacje, kursy | Bootcampy.pl");
allowedResults.add("Dlaczego wybrałam Bootcamp Kodilla | BedeProgramistka.pl");
allowedResults.add("Kodilla - Home | Facebook");
allowedResults.add("Kodilla - znaleziska i wpisy o #kodilla w Wykop.pl");
wait.until(ExpectedConditions.visibilityOf(expectedClickable));
chosenResult.getChosenWebsiteElement(4);
String chosenElementHeadline = chosenResult.getChosenWebsiteElement(4).findElement(By.tagName("span")).getText();
System.out.println(chosenElementHeadline);
//then
//tutaj nie wiem, czemu przestało przechodzić
assertTrue(allowedResults.contains(chosenElementHeadline));
}
@Test
public void elementChosenToBeClickedIsNotUnexpectedOne() {
//given
GoogleSearch googleSearch = new GoogleSearch(driver);
ChosenResult chosenResult = new ChosenResult(driver);
WebDriverWait wait = new WebDriverWait(driver,10);
googleSearch.searchResults();
wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//*[@class='g']")));
chosenResult.storeResultsToClick();
//when
//wybieram na wynik false stronę główną Kodilli (wynik 1.)
WebElement expectedToBeFalse = driver.findElement(By.xpath("//*[@id=\"rso\"]/div[1]/div/div/div/div[1]/a/h3/span"));
String expectedToBeFalseTitle = expectedToBeFalse.getText();
System.out.println("Expected to assert false: " + expectedToBeFalseTitle);
chosenResult.getChosenWebsiteElement(4);
String chosenElementHeadline = chosenResult.getChosenWebsiteElement(4).findElement(By.tagName("span")).getText();
System.out.println("Chosen by method: " + chosenElementHeadline);
//then
assertNotEquals(String.valueOf(expectedToBeFalseTitle),String.valueOf(chosenElementHeadline));
}
@Test
public void clickedElementIsOneChosenToBeClicked() {
//given
GoogleSearch googleSearch = new GoogleSearch(driver);
ChosenResult chosenResult = new ChosenResult(driver);
WebDriverWait wait = new WebDriverWait(driver,10);
googleSearch.searchResults();
wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//*[@class='g']")));
chosenResult.storeResultsToClick();
//when
//tu zaczęło wychodzić na Index Out Of Bounds, bo jest już tylko 5 wyników na 1. stronie wyszukiwania, a nie 6 tak jak podczas pierwszego
// rozwiązywania zadania
chosenResult.getChosenWebsiteElement(2);
String expectedTitle = chosenResult.getChosenWebsiteElement(2).findElement(By.tagName("span")).getText();
chosenResult.clickChosenElement();
//cz<SUF>
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//html/body")));
String openedWebsiteTitle = driver.getTitle();
System.out.println(openedWebsiteTitle);
//then
assertEquals(expectedTitle, openedWebsiteTitle);
}
@Test
public void clickedElementIsNotOneNotChosenToBeClicked() {
//given
GoogleSearch googleSearch = new GoogleSearch(driver);
ChosenResult chosenResult = new ChosenResult(driver);
WebDriverWait wait = new WebDriverWait(driver,10);
googleSearch.searchResults();
wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//*[@class='g']")));
chosenResult.storeResultsToClick();
//when
//wybieram na wynik false stronę główną Kodilli (wynik 1.)
WebElement expectedToBeFalse = driver.findElement(By.xpath("//*[@id=\"rso\"]/div[1]/div/div/div/div[1]/a/h3/span"));
String expectedToBeFalseTitle = expectedToBeFalse.getText();
System.out.println("Expected to assert false: " + expectedToBeFalseTitle);
chosenResult.getChosenWebsiteElement(2);
chosenResult.clickChosenElement();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//html/body")));
String openedWebsiteTitle = driver.getTitle();
System.out.println(openedWebsiteTitle);
//then
assertNotEquals(expectedToBeFalseTitle, openedWebsiteTitle);
}
}
|
52599_0 | package com.kodilla.collections.sets;
import java.util.HashSet;
import java.util.Set;
public class OrderApplication {
public static void main(String[] args) {
Set<Order> orders = new HashSet<>(); /*tworzy kolekcję orders typu HashSet<Order>*/
orders.add(new Order("1/2019", "Iron", 1.0)); /* wstawia do kolekcji cztery zamówienia.*/
orders.add(new Order("2/2019", "Cutlery", 6.0));
orders.add(new Order("3/2019", "Chair", 2.0));
orders.add(new Order("1/2019", "Iron", 1.0));
//Pętla for-each natomiast pozwala nam na przeglądanie różnych zbiorów danych (tablice, listy, kolekcje)
//for (Typ zmienna : kolekcja) {
// // kod
//}
//Iteruj po kolekcji kolekcja i kolejne jej elementy wstawiaj do zmiennej o nazwie zmienna, która jest typu Typ.
// Dla każdego elementu kolekcji ciało pętli wykonywane jest jeden raz.
System.out.println(orders.size());
for (Order order : orders) /*dla każdego elementu kolekcji orders wykonaj kod zawarty w ciele pętli*/
System.out.println(order);
}
}
| AgnieszkaChmielewska/Agnieszka_Chmielewska-kodilla_tester | kodilla-colections/src/main/java/com/kodilla/collections/sets/OrderApplication.java | 395 | /*tworzy kolekcję orders typu HashSet<Order>*/ | block_comment | pl | package com.kodilla.collections.sets;
import java.util.HashSet;
import java.util.Set;
public class OrderApplication {
public static void main(String[] args) {
Set<Order> orders = new HashSet<>(); /*two<SUF>*/
orders.add(new Order("1/2019", "Iron", 1.0)); /* wstawia do kolekcji cztery zamówienia.*/
orders.add(new Order("2/2019", "Cutlery", 6.0));
orders.add(new Order("3/2019", "Chair", 2.0));
orders.add(new Order("1/2019", "Iron", 1.0));
//Pętla for-each natomiast pozwala nam na przeglądanie różnych zbiorów danych (tablice, listy, kolekcje)
//for (Typ zmienna : kolekcja) {
// // kod
//}
//Iteruj po kolekcji kolekcja i kolejne jej elementy wstawiaj do zmiennej o nazwie zmienna, która jest typu Typ.
// Dla każdego elementu kolekcji ciało pętli wykonywane jest jeden raz.
System.out.println(orders.size());
for (Order order : orders) /*dla każdego elementu kolekcji orders wykonaj kod zawarty w ciele pętli*/
System.out.println(order);
}
}
|
29936_15 | package PO_projekt_2;
import java.awt.*;
import java.util.Random;
public abstract class Organizm
{
private Color kolor;
private Swiat swiat;
private final Koordynaty koordynaty;
private TypOrganizmu typOrganizmu;
private int sila;
private int inicjatywa;
private int tura_urodzenia;
private boolean czy_zyje;
protected final boolean[] kierunek;
private boolean czy_sie_rozmnazal;
public abstract void akcja();
public abstract void kolizja(Organizm other);
public abstract String typ_organizmu_to_string();
public abstract boolean czy_zwierze();
public Organizm(Swiat swiat, TypOrganizmu typOrganizmu, int sila, int inicjatywa, Organizm.Koordynaty koordynaty, int tura_urodzenia) //konstruktor organizmu, nadpisywany w innych klasach za pomoca słowa kluczowego "super();"
{
this.swiat = swiat;
this.typOrganizmu = typOrganizmu;
this.sila = sila;
this.inicjatywa = inicjatywa;
this.koordynaty = koordynaty;
this.tura_urodzenia = tura_urodzenia;
czy_zyje = true;
kierunek = new boolean[]{true, true, true, true};
set_czy_sie_rozmnazal(false);
}
public Swiat get_swiat() { return swiat; }
public void setSwiat(Swiat swiat) { this.swiat = swiat; }
public Koordynaty get_koordynaty() { return koordynaty; }
public TypOrganizmu get_typ_organizmu() { return typOrganizmu; }
public void setTypOrganizmu(TypOrganizmu typOrganizmu) { this.typOrganizmu = typOrganizmu; }
// gettery i settery do prywatnych pól: siła, inicjatywa, tura urodzenia, czy_zyje, czy_sie_rozmnazal, kolor
public int get_sila() { return sila; }
public void set_sila(int sila) { this.sila = sila; }
public int get_inicjatywa() { return inicjatywa; }
public void setInicjatywa(int inicjatywa) { this.inicjatywa = inicjatywa; }
public int get_tura_urodzenia() { return tura_urodzenia; }
public void set_tura_urodzenia(int tura_urodzenia) { this.tura_urodzenia = tura_urodzenia; }
public boolean get_czy_zyje() { return czy_zyje; }
public void set_czy_zyje(boolean czy_zyje) { this.czy_zyje = czy_zyje; }
public boolean get_czy_sie_rozmnazal() { return czy_sie_rozmnazal; }
public void set_czy_sie_rozmnazal(boolean czy_sie_rozmnazal){ this.czy_sie_rozmnazal = czy_sie_rozmnazal; }
public Color get_kolor() { return kolor;}
public void set_kolor(Color kolor) {this.kolor = kolor;}
public enum Kierunek // enum wszystkich kierunków, w tym braku kierunku, gdyy wszystkie są zajęte
{
PRAWO(0),
LEWO(1),
GORA(2),
DOL(3),
BRAK_KIERUNKU(4);
private final int kierunek;
Kierunek(int kierunek) { this.kierunek = kierunek; }
public int getValue() { return kierunek; }
}
public enum TypOrganizmu // enum wszystkich typów organizmów, które występuja na świecie
{
CZLOWIEK,
WILK,
OWCA,
LIS,
ZOLW,
ANTYLOPA,
CYBER_OWCA,
TRAWA,
MLECZ,
GUARANA,
WILCZE_JAGODY,
BARSZCZ_SOSNOWSKIEGO
}
static TypOrganizmu daj_dowolny_organizm() // losuje dowolny tep organizmu, użyte przy dodawaniu organizmów do planszy gry
{
Random rand = new Random();
int tmp = rand.nextInt(11);
switch(tmp)
{
case 0: return TypOrganizmu.WILK;
case 1: return TypOrganizmu.OWCA;
case 2: return TypOrganizmu.CYBER_OWCA;
case 3: return TypOrganizmu.LIS;
case 4: return TypOrganizmu.ZOLW;
case 5: return TypOrganizmu.ANTYLOPA;
case 6: return TypOrganizmu.TRAWA;
case 7: return TypOrganizmu.MLECZ;
case 8: return TypOrganizmu.GUARANA;
case 9: return TypOrganizmu.WILCZE_JAGODY;
case 10: return TypOrganizmu.BARSZCZ_SOSNOWSKIEGO;
}
return TypOrganizmu.WILK;
}
public String OrganizmToSring() // informacje wyświetlane o każdym organizmie: pozycja, siła, inicjatywa
{
return (typ_organizmu_to_string() + " x[" + koordynaty.getX() + "] y[" + koordynaty.getY() + "] (sila: " + sila + ") (inicjatywa: " + inicjatywa + ")");
}
public boolean supermoc(Organizm wykonujacy_akcje, Organizm atakowany) // supermoc nadpisywana w poszczególnych organizmach, wywoływana podczas kolizi
{
return false;
}
public static class Koordynaty // publiczna klasa, używana do nadania i określenia pozycji organizmów
{
private int pozycja_x;
private int pozycja_y;
public int getX() { return pozycja_x; }
public int getY() { return pozycja_y; }
public void setX(int x) { this.pozycja_x = x; }
public void setY(int y) { this.pozycja_y = y; }
public Koordynaty() { pozycja_x = 0; pozycja_y = 0; }
public Koordynaty(int x, int y) { this.pozycja_x = x; this.pozycja_y = y; }
@Override
public boolean equals(Object obiekt_do_porownania)
{
if (!(obiekt_do_porownania instanceof PO_projekt_2.Organizm.Koordynaty)) return false;
if (obiekt_do_porownania == this) return true;
Koordynaty obj_do_porownania = (Koordynaty)obiekt_do_porownania;
return pozycja_x == obj_do_porownania.pozycja_x && pozycja_y == obj_do_porownania.pozycja_y;
}
}
public void wykonaj_ruch(Koordynaty zaplanowane_przyszle_miejsce) // wykonuje ruch na zaplanowane przyszłe miejsce
{
int wspolrzedna_x = zaplanowane_przyszle_miejsce.getX();
int wspolrzedna_y = zaplanowane_przyszle_miejsce.getY();
swiat.getPlansza()[koordynaty.getY()][koordynaty.getX()] = null;
swiat.getPlansza()[wspolrzedna_y][wspolrzedna_x] = this;
koordynaty.setX(wspolrzedna_x);
koordynaty.setY(wspolrzedna_y);
}
public Koordynaty daj_losowe_pole(Koordynaty koordynaty) // losuje pole dowolne, może być zajęte
{ // użyte do planowania losowego ruchu zwierząt
odblokuj_wszystkie_kierunki();
int wspolrzedna_x = koordynaty.getX();
int wspolrzedna_y = koordynaty.getY();
int ile_wolnych = 0; //kierunki, które są możliwe, by wykonać ruch
if (wspolrzedna_x == 19) zablokuj_kierunek(Kierunek.PRAWO); else ile_wolnych++;
if (wspolrzedna_x == 0) zablokuj_kierunek(Kierunek.LEWO); else ile_wolnych++;
if (wspolrzedna_y == 0) zablokuj_kierunek(Kierunek.GORA); else ile_wolnych++;
if (wspolrzedna_y == 19) zablokuj_kierunek(Kierunek.DOL); else ile_wolnych++;
if (ile_wolnych == 0) return koordynaty; // nie udało się przestawić organizmu, zostaje na swoim miejscu
while (true)
{
Random rand = new Random();
int wylosowany = rand.nextInt(4);
if (wylosowany == 0 && !kierunek_zablokowany(Kierunek.PRAWO)) return new Koordynaty(wspolrzedna_x + 1, wspolrzedna_y);
else if (wylosowany == 1 && !kierunek_zablokowany(Kierunek.LEWO)) return new Koordynaty(wspolrzedna_x - 1, wspolrzedna_y);
else if (wylosowany == 2 && !kierunek_zablokowany(Kierunek.GORA)) return new Koordynaty(wspolrzedna_x, wspolrzedna_y - 1);
else if (wylosowany == 3 && !kierunek_zablokowany(Kierunek.DOL)) return new Koordynaty(wspolrzedna_x, wspolrzedna_y + 1);
}
}
public Koordynaty daj_niezajete_pole(Koordynaty koordynaty) // losuje pole niezajęte
{ // użyte do rozmnażania się zwierząt i roślin, potrzebuja znaleźć losowe niezajęte pole, by wykonać ruch
odblokuj_wszystkie_kierunki();
int wspolrzedna_x = koordynaty.getX();
int wspolrzedna_y = koordynaty.getY();
int ile_wolnych = 0; //kierunki, które są możliwe, by wykonać ruch
if (wspolrzedna_x == 19) zablokuj_kierunek(Kierunek.PRAWO);
else
{
if (!swiat.czy_miejsce_zajete(new Koordynaty(wspolrzedna_x + 1, wspolrzedna_y))) ile_wolnych++;
else zablokuj_kierunek(Kierunek.PRAWO);
}
if (wspolrzedna_x == 0) zablokuj_kierunek(Kierunek.LEWO);
else
{
if (!swiat.czy_miejsce_zajete(new Koordynaty(wspolrzedna_x - 1, wspolrzedna_y))) ile_wolnych++;
else zablokuj_kierunek(Kierunek.LEWO);
}
if (wspolrzedna_y == 0) zablokuj_kierunek(Kierunek.GORA);
else
{
if (!swiat.czy_miejsce_zajete(new Koordynaty(wspolrzedna_x, wspolrzedna_y - 1))) ile_wolnych++;
else zablokuj_kierunek(Kierunek.GORA);
}
if (wspolrzedna_y == 19) zablokuj_kierunek(Kierunek.DOL);
else
{
if (!swiat.czy_miejsce_zajete(new Koordynaty(wspolrzedna_x, wspolrzedna_y + 1))) ile_wolnych++;
else zablokuj_kierunek(Kierunek.DOL);
}
if (ile_wolnych == 0) return new Koordynaty(wspolrzedna_x, wspolrzedna_y);
while (true)
{
Random rand = new Random();
int wylosowany = rand.nextInt(4);
if (wylosowany == 0 && !kierunek_zablokowany(Kierunek.PRAWO)) return new Koordynaty(wspolrzedna_x + 1, wspolrzedna_y);
else if (wylosowany == 1 && !kierunek_zablokowany(Kierunek.LEWO)) return new Koordynaty(wspolrzedna_x - 1, wspolrzedna_y);
else if (wylosowany == 2 && !kierunek_zablokowany(Kierunek.GORA)) return new Koordynaty(wspolrzedna_x, wspolrzedna_y - 1);
else if (wylosowany == 3 && !kierunek_zablokowany(Kierunek.DOL)) return new Koordynaty(wspolrzedna_x, wspolrzedna_y + 1);
}
}
protected boolean kierunek_zablokowany(Kierunek kierunek) { return !(this.kierunek[kierunek.getValue()]); }
protected void zablokuj_kierunek(Kierunek kierunek) { this.kierunek[kierunek.getValue()] = false; }
protected void odblokuj_kierunek(Kierunek kierunek) { this.kierunek[kierunek.getValue()] = true; }
protected void odblokuj_wszystkie_kierunki()
{
odblokuj_kierunek(Kierunek.PRAWO);
odblokuj_kierunek(Kierunek.LEWO);
odblokuj_kierunek(Kierunek.GORA);
odblokuj_kierunek(Kierunek.DOL);
}
} | AgnieszkaDelmaczynska/OOP-virtual-world-java | src/PO_projekt_2/Organizm.java | 4,197 | //kierunki, które są możliwe, by wykonać ruch
| line_comment | pl | package PO_projekt_2;
import java.awt.*;
import java.util.Random;
public abstract class Organizm
{
private Color kolor;
private Swiat swiat;
private final Koordynaty koordynaty;
private TypOrganizmu typOrganizmu;
private int sila;
private int inicjatywa;
private int tura_urodzenia;
private boolean czy_zyje;
protected final boolean[] kierunek;
private boolean czy_sie_rozmnazal;
public abstract void akcja();
public abstract void kolizja(Organizm other);
public abstract String typ_organizmu_to_string();
public abstract boolean czy_zwierze();
public Organizm(Swiat swiat, TypOrganizmu typOrganizmu, int sila, int inicjatywa, Organizm.Koordynaty koordynaty, int tura_urodzenia) //konstruktor organizmu, nadpisywany w innych klasach za pomoca słowa kluczowego "super();"
{
this.swiat = swiat;
this.typOrganizmu = typOrganizmu;
this.sila = sila;
this.inicjatywa = inicjatywa;
this.koordynaty = koordynaty;
this.tura_urodzenia = tura_urodzenia;
czy_zyje = true;
kierunek = new boolean[]{true, true, true, true};
set_czy_sie_rozmnazal(false);
}
public Swiat get_swiat() { return swiat; }
public void setSwiat(Swiat swiat) { this.swiat = swiat; }
public Koordynaty get_koordynaty() { return koordynaty; }
public TypOrganizmu get_typ_organizmu() { return typOrganizmu; }
public void setTypOrganizmu(TypOrganizmu typOrganizmu) { this.typOrganizmu = typOrganizmu; }
// gettery i settery do prywatnych pól: siła, inicjatywa, tura urodzenia, czy_zyje, czy_sie_rozmnazal, kolor
public int get_sila() { return sila; }
public void set_sila(int sila) { this.sila = sila; }
public int get_inicjatywa() { return inicjatywa; }
public void setInicjatywa(int inicjatywa) { this.inicjatywa = inicjatywa; }
public int get_tura_urodzenia() { return tura_urodzenia; }
public void set_tura_urodzenia(int tura_urodzenia) { this.tura_urodzenia = tura_urodzenia; }
public boolean get_czy_zyje() { return czy_zyje; }
public void set_czy_zyje(boolean czy_zyje) { this.czy_zyje = czy_zyje; }
public boolean get_czy_sie_rozmnazal() { return czy_sie_rozmnazal; }
public void set_czy_sie_rozmnazal(boolean czy_sie_rozmnazal){ this.czy_sie_rozmnazal = czy_sie_rozmnazal; }
public Color get_kolor() { return kolor;}
public void set_kolor(Color kolor) {this.kolor = kolor;}
public enum Kierunek // enum wszystkich kierunków, w tym braku kierunku, gdyy wszystkie są zajęte
{
PRAWO(0),
LEWO(1),
GORA(2),
DOL(3),
BRAK_KIERUNKU(4);
private final int kierunek;
Kierunek(int kierunek) { this.kierunek = kierunek; }
public int getValue() { return kierunek; }
}
public enum TypOrganizmu // enum wszystkich typów organizmów, które występuja na świecie
{
CZLOWIEK,
WILK,
OWCA,
LIS,
ZOLW,
ANTYLOPA,
CYBER_OWCA,
TRAWA,
MLECZ,
GUARANA,
WILCZE_JAGODY,
BARSZCZ_SOSNOWSKIEGO
}
static TypOrganizmu daj_dowolny_organizm() // losuje dowolny tep organizmu, użyte przy dodawaniu organizmów do planszy gry
{
Random rand = new Random();
int tmp = rand.nextInt(11);
switch(tmp)
{
case 0: return TypOrganizmu.WILK;
case 1: return TypOrganizmu.OWCA;
case 2: return TypOrganizmu.CYBER_OWCA;
case 3: return TypOrganizmu.LIS;
case 4: return TypOrganizmu.ZOLW;
case 5: return TypOrganizmu.ANTYLOPA;
case 6: return TypOrganizmu.TRAWA;
case 7: return TypOrganizmu.MLECZ;
case 8: return TypOrganizmu.GUARANA;
case 9: return TypOrganizmu.WILCZE_JAGODY;
case 10: return TypOrganizmu.BARSZCZ_SOSNOWSKIEGO;
}
return TypOrganizmu.WILK;
}
public String OrganizmToSring() // informacje wyświetlane o każdym organizmie: pozycja, siła, inicjatywa
{
return (typ_organizmu_to_string() + " x[" + koordynaty.getX() + "] y[" + koordynaty.getY() + "] (sila: " + sila + ") (inicjatywa: " + inicjatywa + ")");
}
public boolean supermoc(Organizm wykonujacy_akcje, Organizm atakowany) // supermoc nadpisywana w poszczególnych organizmach, wywoływana podczas kolizi
{
return false;
}
public static class Koordynaty // publiczna klasa, używana do nadania i określenia pozycji organizmów
{
private int pozycja_x;
private int pozycja_y;
public int getX() { return pozycja_x; }
public int getY() { return pozycja_y; }
public void setX(int x) { this.pozycja_x = x; }
public void setY(int y) { this.pozycja_y = y; }
public Koordynaty() { pozycja_x = 0; pozycja_y = 0; }
public Koordynaty(int x, int y) { this.pozycja_x = x; this.pozycja_y = y; }
@Override
public boolean equals(Object obiekt_do_porownania)
{
if (!(obiekt_do_porownania instanceof PO_projekt_2.Organizm.Koordynaty)) return false;
if (obiekt_do_porownania == this) return true;
Koordynaty obj_do_porownania = (Koordynaty)obiekt_do_porownania;
return pozycja_x == obj_do_porownania.pozycja_x && pozycja_y == obj_do_porownania.pozycja_y;
}
}
public void wykonaj_ruch(Koordynaty zaplanowane_przyszle_miejsce) // wykonuje ruch na zaplanowane przyszłe miejsce
{
int wspolrzedna_x = zaplanowane_przyszle_miejsce.getX();
int wspolrzedna_y = zaplanowane_przyszle_miejsce.getY();
swiat.getPlansza()[koordynaty.getY()][koordynaty.getX()] = null;
swiat.getPlansza()[wspolrzedna_y][wspolrzedna_x] = this;
koordynaty.setX(wspolrzedna_x);
koordynaty.setY(wspolrzedna_y);
}
public Koordynaty daj_losowe_pole(Koordynaty koordynaty) // losuje pole dowolne, może być zajęte
{ // użyte do planowania losowego ruchu zwierząt
odblokuj_wszystkie_kierunki();
int wspolrzedna_x = koordynaty.getX();
int wspolrzedna_y = koordynaty.getY();
int ile_wolnych = 0; //kierunki, które są możliwe, by wykonać ruch
if (wspolrzedna_x == 19) zablokuj_kierunek(Kierunek.PRAWO); else ile_wolnych++;
if (wspolrzedna_x == 0) zablokuj_kierunek(Kierunek.LEWO); else ile_wolnych++;
if (wspolrzedna_y == 0) zablokuj_kierunek(Kierunek.GORA); else ile_wolnych++;
if (wspolrzedna_y == 19) zablokuj_kierunek(Kierunek.DOL); else ile_wolnych++;
if (ile_wolnych == 0) return koordynaty; // nie udało się przestawić organizmu, zostaje na swoim miejscu
while (true)
{
Random rand = new Random();
int wylosowany = rand.nextInt(4);
if (wylosowany == 0 && !kierunek_zablokowany(Kierunek.PRAWO)) return new Koordynaty(wspolrzedna_x + 1, wspolrzedna_y);
else if (wylosowany == 1 && !kierunek_zablokowany(Kierunek.LEWO)) return new Koordynaty(wspolrzedna_x - 1, wspolrzedna_y);
else if (wylosowany == 2 && !kierunek_zablokowany(Kierunek.GORA)) return new Koordynaty(wspolrzedna_x, wspolrzedna_y - 1);
else if (wylosowany == 3 && !kierunek_zablokowany(Kierunek.DOL)) return new Koordynaty(wspolrzedna_x, wspolrzedna_y + 1);
}
}
public Koordynaty daj_niezajete_pole(Koordynaty koordynaty) // losuje pole niezajęte
{ // użyte do rozmnażania się zwierząt i roślin, potrzebuja znaleźć losowe niezajęte pole, by wykonać ruch
odblokuj_wszystkie_kierunki();
int wspolrzedna_x = koordynaty.getX();
int wspolrzedna_y = koordynaty.getY();
int ile_wolnych = 0; //ki<SUF>
if (wspolrzedna_x == 19) zablokuj_kierunek(Kierunek.PRAWO);
else
{
if (!swiat.czy_miejsce_zajete(new Koordynaty(wspolrzedna_x + 1, wspolrzedna_y))) ile_wolnych++;
else zablokuj_kierunek(Kierunek.PRAWO);
}
if (wspolrzedna_x == 0) zablokuj_kierunek(Kierunek.LEWO);
else
{
if (!swiat.czy_miejsce_zajete(new Koordynaty(wspolrzedna_x - 1, wspolrzedna_y))) ile_wolnych++;
else zablokuj_kierunek(Kierunek.LEWO);
}
if (wspolrzedna_y == 0) zablokuj_kierunek(Kierunek.GORA);
else
{
if (!swiat.czy_miejsce_zajete(new Koordynaty(wspolrzedna_x, wspolrzedna_y - 1))) ile_wolnych++;
else zablokuj_kierunek(Kierunek.GORA);
}
if (wspolrzedna_y == 19) zablokuj_kierunek(Kierunek.DOL);
else
{
if (!swiat.czy_miejsce_zajete(new Koordynaty(wspolrzedna_x, wspolrzedna_y + 1))) ile_wolnych++;
else zablokuj_kierunek(Kierunek.DOL);
}
if (ile_wolnych == 0) return new Koordynaty(wspolrzedna_x, wspolrzedna_y);
while (true)
{
Random rand = new Random();
int wylosowany = rand.nextInt(4);
if (wylosowany == 0 && !kierunek_zablokowany(Kierunek.PRAWO)) return new Koordynaty(wspolrzedna_x + 1, wspolrzedna_y);
else if (wylosowany == 1 && !kierunek_zablokowany(Kierunek.LEWO)) return new Koordynaty(wspolrzedna_x - 1, wspolrzedna_y);
else if (wylosowany == 2 && !kierunek_zablokowany(Kierunek.GORA)) return new Koordynaty(wspolrzedna_x, wspolrzedna_y - 1);
else if (wylosowany == 3 && !kierunek_zablokowany(Kierunek.DOL)) return new Koordynaty(wspolrzedna_x, wspolrzedna_y + 1);
}
}
protected boolean kierunek_zablokowany(Kierunek kierunek) { return !(this.kierunek[kierunek.getValue()]); }
protected void zablokuj_kierunek(Kierunek kierunek) { this.kierunek[kierunek.getValue()] = false; }
protected void odblokuj_kierunek(Kierunek kierunek) { this.kierunek[kierunek.getValue()] = true; }
protected void odblokuj_wszystkie_kierunki()
{
odblokuj_kierunek(Kierunek.PRAWO);
odblokuj_kierunek(Kierunek.LEWO);
odblokuj_kierunek(Kierunek.GORA);
odblokuj_kierunek(Kierunek.DOL);
}
} |
58433_28 | package pl.edu.agh.szymczyk.checkers.logic;
import pl.edu.agh.szymczyk.checkers.configuration.*;
import pl.edu.agh.szymczyk.checkers.enums.Color;
import pl.edu.agh.szymczyk.checkers.figures.Figure;
import pl.edu.agh.szymczyk.checkers.figures.Pawn;
import pl.edu.agh.szymczyk.checkers.figures.Queen;
import pl.edu.agh.szymczyk.checkers.history.History;
import pl.edu.agh.szymczyk.checkers.history.HistoryList;
import pl.edu.agh.szymczyk.checkers.history.HistoryState;
import java.util.LinkedList;
/**
* Created by Darek on 2016-12-19.
*/
public class Game {
private Figure[][] board;
private Player current;
private Settings settings;
private History history;
private HistoryList history_list;
LinkedList<int[]>[][] possibilities;
private int[] lf = {-1, -1}; // Ostatni ruch w kolejce -1, -1 domyślnie
private Boolean lfwb = false; // Czy ostatni ruch w kolejce był biciem
public Game(Settings settings, HistoryList history_list) {
this.settings = settings;
this.history_list = history_list;
this.current = settings.getWhitePlayer();
this.board = new Figure[this.settings.getBoardSize()][this.settings.getBoardSize()];
for (int y = 0; y < this.settings.getBoardSize(); y++) {
for (int x = y%2; x < this.settings.getBoardSize(); x += 2) {
if (y < 3) {
this.board[x][y] = new Pawn(Color.WHITE);
}
else if (y < this.settings.getBoardSize() && y > this.settings.getBoardSize() - 4) {
this.board[x][y] = new Pawn(Color.BLACK);
}
}
}
// this.board[0][0] = new Queen(Color.WHITE);
// this.board[3][3] = new Pawn(Color.BLACK);
// this.board[2][6] = new Pawn(Color.BLACK);
this.history = new History(this.settings, new HistoryState(this.board, this.getCurrentPlayer()));
this.generatePossibilities();
}
public Figure[][] getBoard() {
return this.board;
}
public Settings getSettings() { return this.settings; }
public History getHistory() {
return this.history;
}
public Player getCurrentPlayer() {
return this.current;
}
public boolean isFinished() {
return !this.hasMoreMoves();
}
public Player getWinner() throws FinishedGameException {
if (!this.isFinished()) {
throw new FinishedGameException();
}
if (this.current.getColor() == Color.WHITE) {
return this.settings.getBlackPlayer();
}
else {
return this.settings.getWhitePlayer();
}
}
public void move(int x1, int y1, int x2, int y2) throws WrongMoveException, FinishedGameException {
if (this.isFinished()) {
throw new FinishedGameException();
}
// Sprawdza czy ruch jest możliwy
if (!this.isPossible(x1, y1, x2, y2)) {
throw new WrongMoveException();
}
// Porusza pionkiem
this.board[x2][y2] = this.board[x1][y1];
this.board[x1][y1] = null;
// Ustawia ostatni pionek w kolejce
this.lf = new int[]{x2, y2};
this.lfwb = this.isBeat(x1, y1, x2, y2);
// Usuwa wszystkie pionki po drodze
this.deleteOnTheWay(x1, y1, x2, y2);
// Jeśli to konieczne zamienia pionka na damkę
if (this.changeIfItIsNecessary(x2, y2)) {
this.nextPlayer();
}
else {
this.generatePossibilities();
// Jeśli nie ma więcej ruchów zmienia kolejkę
if (!this.hasMoreMoves()) {
this.nextPlayer();
}
}
// Aktualizuje historię
try {
this.history.add(new HistoryState(this.board, this.getCurrentPlayer()));
} catch (GameEndedException e) {
e.printStackTrace();
}
// Jeśli gra się skończyła
if (isFinished()) {
this.history.end();
try {
this.history_list.add(history);
} catch (GameDoesntEndException e) {
e.printStackTrace();
}
}
}
public LinkedList<int[]>[][] getPossibilities() {
return this.possibilities;
}
public Boolean hasPossibitiesWith(int x, int y) {
return (!this.getPossibilities()[x][y].isEmpty());
}
public LinkedList<int[]> getPossibilitiesWith(int x, int y) {
return this.getPossibilities()[x][y];
}
public void printBoard() {
for (int y = (this.settings.getBoardSize() - 1); y >= 0; y--) {
for (int x = 0; x < this.settings.getBoardSize(); x++) {
if (board[x][y] != null) {
System.out.print(this.board[x][y].getShortName());
}
else {
System.out.print("[]");
}
}
System.out.print("\n");
}
}
public void printPossibilities() {
for (int y = 0; y < this.settings.getBoardSize(); y++) {
for (int x = y%2; x < this.settings.getBoardSize(); x += 2) {
for (int[] p : this.possibilities[x][y]) {
System.out.println("(" + x + ", " + y + ")" + " -> " + "(" + p[0] + ", " + p[1] + ")");
}
}
}
}
public void printPossibilitiesWith(int x, int y) {
for (int[] p : this.possibilities[x][y]) {
System.out.println("(" + x + ", " + y + ")" + " -> " + "(" + p[0] + ", " + p[1] + ")");
}
}
private void nextPlayer() {
this.lf = new int[]{-1, -1};
this.lfwb = false;
if (this.current.getColor() == Color.WHITE) {
this.current = this.settings.getBlackPlayer();
}
else {
this.current = this.settings.getWhitePlayer();
}
this.generatePossibilities();
}
private Boolean isPossible(int x1, int y1, int x2, int y2) {
for (int[] p : this.possibilities[x1][y1]) {
if (x2 == p[0] && y2 == p[1]) {
return true;
}
}
return false;
}
private Boolean hasMoreMoves() {
for (int y = 0; y < this.settings.getBoardSize(); y++) {
for (int x = y%2; x < this.settings.getBoardSize(); x += 2) {
if (!this.possibilities[x][y].isEmpty()) {
return true;
}
}
}
return false;
}
private void generatePossibilities() {
Boolean beat = false;
this.possibilities = this.generatePossibilitiesStructure();
if (this.lf[0] == -1 || (this.lf[0] != -1 && this.lfwb == true)) {
// Wyszukuje możliwości bicia
for (int y = 0; y < this.settings.getBoardSize(); y++) {
for (int x = y % 2; x < this.settings.getBoardSize(); x += 2) {
Figure f = this.board[x][y];
// Jeśli pole jest puste lub jeśli pionek nie należy do gracza aktualnie wykonującego ruch nie sprawdza ich
if (f == null || f.getColor() != this.current.getColor()) {
continue;
}
// Jeśli to nie pierwszy ruch w kolejce i to nie ta figura to idzie dalej
if (this.lf[0] != -1 && (x != this.lf[0] || y != this.lf[1])) {
continue;
}
// Pobiera zasięg figury
int range = f.getRange();
// Sprawdza możliwości bicia
int[][] directions = f.getBeatDirections();
// Ustawia kierunek poruszania się figur
int d = 1;
if (f.getColor() == Color.BLACK) {
d = -1;
}
for (int i = 0; i < directions.length; i++) {
int dx = directions[i][0];
int dy = directions[i][1]*1;
for (int j = 1; j <= range; j++) {
int vx = dx * j;
int vy = dy * j;
// Jeśli ruch wyrzuca poza planszę
if (!this.inBoard(x + vx, y + vy)) {
break;
}
if (this.board[x + vx][y + vy] != null) {
// Jeśli pole jest koloru aktualnie wykonującego ruch gracza
if (this.board[x + vx][y + vy].getColor() == this.current.getColor()) {
break;
}
// Jeśli można za nim stanąć tzn że można go zbić
if (inBoard(x + vx + dx, y + vy + dy) && this.board[x + vx + dx][y + vy + dy] == null) {
beat = true;
this.possibilities[x][y].add(new int[]{x + vx + dx, y + vy + dy});
}
break;
}
}
}
}
}
if (!beat && this.lf[0] == -1) {
// Wyszukuje możliwości zwykłych ruchów pod warunkiem że nie ma bić
for (int y = 0; y < this.settings.getBoardSize(); y++) {
for (int x = y % 2; x < this.settings.getBoardSize(); x += 2) {
Figure f = this.board[x][y];
// Jeśli pole jest puste lub jeśli pionek nie należy do gracza aktualnie wykonującego ruch nie sprawdza ich
if (f == null || f.getColor() != this.current.getColor()) {
continue;
}
// Pobiera zasięg figury
int range = f.getRange();
// Sprawdza możliwości ruchu
int[][] directions = f.getMoveDirections();
// Ustawia kierunek poruszania się figur
int d = 1;
if (f.getColor() == Color.BLACK) {
d = -1;
}
for (int i = 0; i < directions.length; i++) {
int dx = directions[i][0];
int dy = directions[i][1]*d;
for (int j = 1; j <= range; j++) {
int vx = dx * j;
int vy = dy * j;
// Jeśli ruch wyrzuca poza planszę
if (!this.inBoard(x + vx, y + vy)) {
break;
}
// Jeśli pole nie jest puste to kończy
if (this.board[x + vx][y + vy] != null) {
break;
}
this.possibilities[x][y].add(new int[]{x + vx, y + vy});
}
}
}
}
}
}
}
private boolean inBoard(int x, int y) {
return ((x >= 0) && (x < this.settings.getBoardSize()) && (y >= 0) && (y < this.settings.getBoardSize()));
}
private LinkedList<int[]>[][] generatePossibilitiesStructure() {
LinkedList<int[]>[][] result = new LinkedList[this.settings.getBoardSize()][this.settings.getBoardSize()];
for (int y = 0; y < this.settings.getBoardSize(); y++) {
for (int x = y%2; x < this.settings.getBoardSize(); x += 2) {
result[x][y] = new LinkedList<>();
}
}
return result;
}
private void deleteOnTheWay(int x1, int y1, int x2, int y2) {
int dx = Integer.signum(x2 - x1);
int dy = Integer.signum(y2 - y1);
int cx = x1 + dx;
int cy = y1 + dy;
while (cx != x2) {
this.board[cx][cy] = null;
cx += dx;
cy += dy;
}
}
private Boolean changeIfItIsNecessary(int x, int y) {
Figure f = this.board[x][y];
// Jeśli to damki to nic nie robi
if (f instanceof Queen) {
return false;
}
if (f.getColor() == Color.BLACK && y == 0) {
this.board[x][y] = new Queen(Color.BLACK);
return true;
}
else if (f.getColor() == Color.WHITE && y == this.settings.getBoardSize()-1) {
this.board[x][y] = new Queen(Color.WHITE);
return true;
}
return false;
}
private Boolean isBeat(int x1, int y1, int x2, int y2) {
int dx = Integer.signum(x2 - x1);
int dy = Integer.signum(y2 - y1);
int cx = x1 + dx;
int cy = y1 + dy;
while (cx != x2) {
if (this.board[cx][cy] != null) {
return true;
}
cx += dx;
cy += dy;
}
return false;
}
} | Ahmore/Checkers | src/pl/edu/agh/szymczyk/checkers/logic/Game.java | 4,058 | // Jeśli ruch wyrzuca poza planszę | line_comment | pl | package pl.edu.agh.szymczyk.checkers.logic;
import pl.edu.agh.szymczyk.checkers.configuration.*;
import pl.edu.agh.szymczyk.checkers.enums.Color;
import pl.edu.agh.szymczyk.checkers.figures.Figure;
import pl.edu.agh.szymczyk.checkers.figures.Pawn;
import pl.edu.agh.szymczyk.checkers.figures.Queen;
import pl.edu.agh.szymczyk.checkers.history.History;
import pl.edu.agh.szymczyk.checkers.history.HistoryList;
import pl.edu.agh.szymczyk.checkers.history.HistoryState;
import java.util.LinkedList;
/**
* Created by Darek on 2016-12-19.
*/
public class Game {
private Figure[][] board;
private Player current;
private Settings settings;
private History history;
private HistoryList history_list;
LinkedList<int[]>[][] possibilities;
private int[] lf = {-1, -1}; // Ostatni ruch w kolejce -1, -1 domyślnie
private Boolean lfwb = false; // Czy ostatni ruch w kolejce był biciem
public Game(Settings settings, HistoryList history_list) {
this.settings = settings;
this.history_list = history_list;
this.current = settings.getWhitePlayer();
this.board = new Figure[this.settings.getBoardSize()][this.settings.getBoardSize()];
for (int y = 0; y < this.settings.getBoardSize(); y++) {
for (int x = y%2; x < this.settings.getBoardSize(); x += 2) {
if (y < 3) {
this.board[x][y] = new Pawn(Color.WHITE);
}
else if (y < this.settings.getBoardSize() && y > this.settings.getBoardSize() - 4) {
this.board[x][y] = new Pawn(Color.BLACK);
}
}
}
// this.board[0][0] = new Queen(Color.WHITE);
// this.board[3][3] = new Pawn(Color.BLACK);
// this.board[2][6] = new Pawn(Color.BLACK);
this.history = new History(this.settings, new HistoryState(this.board, this.getCurrentPlayer()));
this.generatePossibilities();
}
public Figure[][] getBoard() {
return this.board;
}
public Settings getSettings() { return this.settings; }
public History getHistory() {
return this.history;
}
public Player getCurrentPlayer() {
return this.current;
}
public boolean isFinished() {
return !this.hasMoreMoves();
}
public Player getWinner() throws FinishedGameException {
if (!this.isFinished()) {
throw new FinishedGameException();
}
if (this.current.getColor() == Color.WHITE) {
return this.settings.getBlackPlayer();
}
else {
return this.settings.getWhitePlayer();
}
}
public void move(int x1, int y1, int x2, int y2) throws WrongMoveException, FinishedGameException {
if (this.isFinished()) {
throw new FinishedGameException();
}
// Sprawdza czy ruch jest możliwy
if (!this.isPossible(x1, y1, x2, y2)) {
throw new WrongMoveException();
}
// Porusza pionkiem
this.board[x2][y2] = this.board[x1][y1];
this.board[x1][y1] = null;
// Ustawia ostatni pionek w kolejce
this.lf = new int[]{x2, y2};
this.lfwb = this.isBeat(x1, y1, x2, y2);
// Usuwa wszystkie pionki po drodze
this.deleteOnTheWay(x1, y1, x2, y2);
// Jeśli to konieczne zamienia pionka na damkę
if (this.changeIfItIsNecessary(x2, y2)) {
this.nextPlayer();
}
else {
this.generatePossibilities();
// Jeśli nie ma więcej ruchów zmienia kolejkę
if (!this.hasMoreMoves()) {
this.nextPlayer();
}
}
// Aktualizuje historię
try {
this.history.add(new HistoryState(this.board, this.getCurrentPlayer()));
} catch (GameEndedException e) {
e.printStackTrace();
}
// Jeśli gra się skończyła
if (isFinished()) {
this.history.end();
try {
this.history_list.add(history);
} catch (GameDoesntEndException e) {
e.printStackTrace();
}
}
}
public LinkedList<int[]>[][] getPossibilities() {
return this.possibilities;
}
public Boolean hasPossibitiesWith(int x, int y) {
return (!this.getPossibilities()[x][y].isEmpty());
}
public LinkedList<int[]> getPossibilitiesWith(int x, int y) {
return this.getPossibilities()[x][y];
}
public void printBoard() {
for (int y = (this.settings.getBoardSize() - 1); y >= 0; y--) {
for (int x = 0; x < this.settings.getBoardSize(); x++) {
if (board[x][y] != null) {
System.out.print(this.board[x][y].getShortName());
}
else {
System.out.print("[]");
}
}
System.out.print("\n");
}
}
public void printPossibilities() {
for (int y = 0; y < this.settings.getBoardSize(); y++) {
for (int x = y%2; x < this.settings.getBoardSize(); x += 2) {
for (int[] p : this.possibilities[x][y]) {
System.out.println("(" + x + ", " + y + ")" + " -> " + "(" + p[0] + ", " + p[1] + ")");
}
}
}
}
public void printPossibilitiesWith(int x, int y) {
for (int[] p : this.possibilities[x][y]) {
System.out.println("(" + x + ", " + y + ")" + " -> " + "(" + p[0] + ", " + p[1] + ")");
}
}
private void nextPlayer() {
this.lf = new int[]{-1, -1};
this.lfwb = false;
if (this.current.getColor() == Color.WHITE) {
this.current = this.settings.getBlackPlayer();
}
else {
this.current = this.settings.getWhitePlayer();
}
this.generatePossibilities();
}
private Boolean isPossible(int x1, int y1, int x2, int y2) {
for (int[] p : this.possibilities[x1][y1]) {
if (x2 == p[0] && y2 == p[1]) {
return true;
}
}
return false;
}
private Boolean hasMoreMoves() {
for (int y = 0; y < this.settings.getBoardSize(); y++) {
for (int x = y%2; x < this.settings.getBoardSize(); x += 2) {
if (!this.possibilities[x][y].isEmpty()) {
return true;
}
}
}
return false;
}
private void generatePossibilities() {
Boolean beat = false;
this.possibilities = this.generatePossibilitiesStructure();
if (this.lf[0] == -1 || (this.lf[0] != -1 && this.lfwb == true)) {
// Wyszukuje możliwości bicia
for (int y = 0; y < this.settings.getBoardSize(); y++) {
for (int x = y % 2; x < this.settings.getBoardSize(); x += 2) {
Figure f = this.board[x][y];
// Jeśli pole jest puste lub jeśli pionek nie należy do gracza aktualnie wykonującego ruch nie sprawdza ich
if (f == null || f.getColor() != this.current.getColor()) {
continue;
}
// Jeśli to nie pierwszy ruch w kolejce i to nie ta figura to idzie dalej
if (this.lf[0] != -1 && (x != this.lf[0] || y != this.lf[1])) {
continue;
}
// Pobiera zasięg figury
int range = f.getRange();
// Sprawdza możliwości bicia
int[][] directions = f.getBeatDirections();
// Ustawia kierunek poruszania się figur
int d = 1;
if (f.getColor() == Color.BLACK) {
d = -1;
}
for (int i = 0; i < directions.length; i++) {
int dx = directions[i][0];
int dy = directions[i][1]*1;
for (int j = 1; j <= range; j++) {
int vx = dx * j;
int vy = dy * j;
// Jeśli ruch wyrzuca poza planszę
if (!this.inBoard(x + vx, y + vy)) {
break;
}
if (this.board[x + vx][y + vy] != null) {
// Jeśli pole jest koloru aktualnie wykonującego ruch gracza
if (this.board[x + vx][y + vy].getColor() == this.current.getColor()) {
break;
}
// Jeśli można za nim stanąć tzn że można go zbić
if (inBoard(x + vx + dx, y + vy + dy) && this.board[x + vx + dx][y + vy + dy] == null) {
beat = true;
this.possibilities[x][y].add(new int[]{x + vx + dx, y + vy + dy});
}
break;
}
}
}
}
}
if (!beat && this.lf[0] == -1) {
// Wyszukuje możliwości zwykłych ruchów pod warunkiem że nie ma bić
for (int y = 0; y < this.settings.getBoardSize(); y++) {
for (int x = y % 2; x < this.settings.getBoardSize(); x += 2) {
Figure f = this.board[x][y];
// Jeśli pole jest puste lub jeśli pionek nie należy do gracza aktualnie wykonującego ruch nie sprawdza ich
if (f == null || f.getColor() != this.current.getColor()) {
continue;
}
// Pobiera zasięg figury
int range = f.getRange();
// Sprawdza możliwości ruchu
int[][] directions = f.getMoveDirections();
// Ustawia kierunek poruszania się figur
int d = 1;
if (f.getColor() == Color.BLACK) {
d = -1;
}
for (int i = 0; i < directions.length; i++) {
int dx = directions[i][0];
int dy = directions[i][1]*d;
for (int j = 1; j <= range; j++) {
int vx = dx * j;
int vy = dy * j;
// Je<SUF>
if (!this.inBoard(x + vx, y + vy)) {
break;
}
// Jeśli pole nie jest puste to kończy
if (this.board[x + vx][y + vy] != null) {
break;
}
this.possibilities[x][y].add(new int[]{x + vx, y + vy});
}
}
}
}
}
}
}
private boolean inBoard(int x, int y) {
return ((x >= 0) && (x < this.settings.getBoardSize()) && (y >= 0) && (y < this.settings.getBoardSize()));
}
private LinkedList<int[]>[][] generatePossibilitiesStructure() {
LinkedList<int[]>[][] result = new LinkedList[this.settings.getBoardSize()][this.settings.getBoardSize()];
for (int y = 0; y < this.settings.getBoardSize(); y++) {
for (int x = y%2; x < this.settings.getBoardSize(); x += 2) {
result[x][y] = new LinkedList<>();
}
}
return result;
}
private void deleteOnTheWay(int x1, int y1, int x2, int y2) {
int dx = Integer.signum(x2 - x1);
int dy = Integer.signum(y2 - y1);
int cx = x1 + dx;
int cy = y1 + dy;
while (cx != x2) {
this.board[cx][cy] = null;
cx += dx;
cy += dy;
}
}
private Boolean changeIfItIsNecessary(int x, int y) {
Figure f = this.board[x][y];
// Jeśli to damki to nic nie robi
if (f instanceof Queen) {
return false;
}
if (f.getColor() == Color.BLACK && y == 0) {
this.board[x][y] = new Queen(Color.BLACK);
return true;
}
else if (f.getColor() == Color.WHITE && y == this.settings.getBoardSize()-1) {
this.board[x][y] = new Queen(Color.WHITE);
return true;
}
return false;
}
private Boolean isBeat(int x1, int y1, int x2, int y2) {
int dx = Integer.signum(x2 - x1);
int dy = Integer.signum(y2 - y1);
int cx = x1 + dx;
int cy = y1 + dy;
while (cx != x2) {
if (this.board[cx][cy] != null) {
return true;
}
cx += dx;
cy += dy;
}
return false;
}
} |
35638_52 | package com.example.artbaryl.firehelper;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.PlaceLikelihood;
import com.google.android.gms.location.places.PlaceLikelihoodBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* An activity that displays a map showing the place at the device's current location.
*/
public class MapsActivityCurrentPlace extends AppCompatActivity
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = MapsActivityCurrentPlace.class.getSimpleName();
private GoogleMap mMap;
private CameraPosition mCameraPosition;
// The entry point to Google Play services, used by the Places API and Fused Location Provider.
private GoogleApiClient mGoogleApiClient;
// A default location (Sydney, Australia) and default zoom to use when location permission is
// not granted.
private final LatLng mDefaultLocation = new LatLng(-33.8523341, 151.2106085);
private static final int DEFAULT_ZOOM = 15;
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private boolean mLocationPermissionGranted;
// The geographical location where the device is currently located. That is, the last-known
// location retrieved by the Fused Location Provider.
private Location mLastKnownLocation;
// Keys for storing activity state.
private static final String KEY_CAMERA_POSITION = "camera_position";
private static final String KEY_LOCATION = "location";
// Used for selecting the current place.
private final int mMaxEntries = 5;
private String[] mLikelyPlaceNames = new String[mMaxEntries];
private String[] mLikelyPlaceAddresses = new String[mMaxEntries];
private String[] mLikelyPlaceAttributions = new String[mMaxEntries];
private LatLng[] mLikelyPlaceLatLngs = new LatLng[mMaxEntries];
//My changes
String aws = "http://ec2-54-93-96-33.eu-central-1.compute.amazonaws.com:5000/51.763635/8.065624/51.754994/8.045626";
private final OkHttpClient client = new OkHttpClient();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retrieve location and camera position from saved instance state.
if (savedInstanceState != null) {
mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
}
// Retrieve the content view that renders the map.
setContentView(R.layout.activity_maps);
// Build the Play services client for use by the Fused Location Provider and the Places API.
// Use the addApi() method to request the Google Places API and the Fused Location Provider.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this ,
this )
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
mGoogleApiClient.connect();
}
/**
* Saves the state of the map when the activity is paused.
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
if (mMap != null) {
outState.putParcelable(KEY_CAMERA_POSITION, mMap.getCameraPosition());
outState.putParcelable(KEY_LOCATION, mLastKnownLocation);
super.onSaveInstanceState(outState);
}
}
/**
* Builds the map when the Google Play services client is successfully connected.
*/
@Override
public void onConnected(Bundle connectionHint) {
// Build the map.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Handles failure to connect to the Google Play services client.
*/
@Override
public void onConnectionFailed(@NonNull ConnectionResult result) {
// Refer to the reference doc for ConnectionResult to see what error codes might
// be returned in onConnectionFailed.
Log.d(TAG, "Play services connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
/**
* Handles suspension of the connection to the Google Play services client.
*/
@Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "Play services connection suspended");
}
/**
* Sets up the options menu.
* @param menu The options menu.
* @return Boolean.
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.current_place_menu, menu);
return true;
}
/**
* Handles a click on the menu option to get a place.
* @param item The menu item to handle.
* @return Boolean.
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.option_get_place) {
showCurrentPlace();
}
return true;
}
/**
* Manipulates the map when it's available.
* This callback is triggered when the map is ready to be used.
*/
@Override
public void onMapReady(GoogleMap map) {
mMap = map;
// Use a custom info window adapter to handle multiple lines of text in the
// info window contents.
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
@Override
// Return null here, so that getInfoContents() is called next.
public View getInfoWindow(Marker arg0) {
return null;
}
@Override
public View getInfoContents(Marker marker) {
// Inflate the layouts for the info window, title and snippet.
View infoWindow = getLayoutInflater().inflate(R.layout.custom_info_contents,
(FrameLayout)findViewById(R.id.map), false);
TextView title = ((TextView) infoWindow.findViewById(R.id.title));
title.setText(marker.getTitle());
TextView snippet = ((TextView) infoWindow.findViewById(R.id.snippet));
snippet.setText(marker.getSnippet());
return infoWindow;
}
});
// Turn on the My Location layer and the related control on the map.
updateLocationUI();
// Get the current location of the device and set the position of the map.
getDeviceLocation();
}
/**
* Gets the current location of the device, and positions the map's camera.
*/
private void getDeviceLocation() {
/*
* Request location permission, so that we can get the location of the
* device. The result of the permission request is handled by a callback,
* onRequestPermissionsResult.
*/
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
/*
* Get the best and most recent location of the device, which may be null in rare
* cases when a location is not available.
*/
if (mLocationPermissionGranted) {
mLastKnownLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
}
// Set the map's camera position to the current location of the device.
if (mCameraPosition != null) {
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(mCameraPosition));
} else if (mLastKnownLocation != null) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(mLastKnownLocation.getLatitude(),
mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
} else {
Log.d(TAG, "Current location is null. Using defaults.");
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
/**
* Handles the result of the request for location permissions.
*/
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[],
@NonNull int[] grantResults) {
mLocationPermissionGranted = false;
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
}
}
updateLocationUI();
}
/**
* Prompts the user to select the current place from a list of likely places, and shows the
* current place on the map - provided the user has granted location permission.
*/
private void showCurrentPlace() {
if (mMap == null) {
return;
}
new WebServiceHandler()
.execute(aws);
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
/*
if (mLocationPermissionGranted) {
Log.d("lol", "Im in - agree");
// Get the likely places - that is, the businesses and other points of interest that
// are the best match for the device's current location.
@SuppressWarnings("MissingPermission")
PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
.getCurrentPlace(mGoogleApiClient, null);
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
@Override
public void onResult(@NonNull PlaceLikelihoodBuffer likelyPlaces) {
int i = 0;
mLikelyPlaceNames = new String[mMaxEntries];
mLikelyPlaceAddresses = new String[mMaxEntries];
mLikelyPlaceAttributions = new String[mMaxEntries];
mLikelyPlaceLatLngs = new LatLng[mMaxEntries];
for (PlaceLikelihood placeLikelihood : likelyPlaces) {
// Build a list of likely places to show the user. Max 5.
mLikelyPlaceNames[i] = (String) placeLikelihood.getPlace().getName();
mLikelyPlaceAddresses[i] = (String) placeLikelihood.getPlace().getAddress();
mLikelyPlaceAttributions[i] = (String) placeLikelihood.getPlace()
.getAttributions();
mLikelyPlaceLatLngs[i] = placeLikelihood.getPlace().getLatLng();
i++;
if (i > (mMaxEntries - 1)) {
break;
}
}
// Release the place likelihood buffer, to avoid memory leaks.
likelyPlaces.release();
// Show a dialog offering the user the list of likely places, and add a
// marker at the selected place.
openPlacesDialog();
}
});
} else {
Log.d("lol", "Im in - without agree");
// Add a default marker, because the user hasn't selected a place.
mMap.addMarker(new MarkerOptions()
.title(getString(R.string.default_info_title))
.position(mDefaultLocation)
.snippet(getString(R.string.default_info_snippet)));
}*/
}
/**
* Displays a form allowing the user to select a place from a list of likely places.
*/
private void openPlacesDialog() {
// Ask the user to choose the place where they are now.
DialogInterface.OnClickListener listener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// The "which" argument contains the position of the selected item.
LatLng markerLatLng = mLikelyPlaceLatLngs[which];
String markerSnippet = mLikelyPlaceAddresses[which];
if (mLikelyPlaceAttributions[which] != null) {
markerSnippet = markerSnippet + "\n" + mLikelyPlaceAttributions[which];
}
// Add a marker for the selected place, with an info window
// showing information about that place.
mMap.addMarker(new MarkerOptions()
.title(mLikelyPlaceNames[which])
.position(markerLatLng)
.snippet(markerSnippet));
//Log.d("LatLng", String.valueOf(markerLatLng));
// Position the map's camera at the location of the marker.
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(markerLatLng,
DEFAULT_ZOOM));
}
};
// Display the dialog.
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle(R.string.pick_place)
.setItems(mLikelyPlaceNames, listener)
.show();
}
/**
* Updates the map's UI settings based on whether the user has granted location permission.
*/
private void updateLocationUI() {
if (mMap == null) {
return;
}
/*
* Request location permission, so that we can get the location of the
* device. The result of the permission request is handled by a callback,
* onRequestPermissionsResult.
*/
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
if (mLocationPermissionGranted) {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
mMap.setMyLocationEnabled(false);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mLastKnownLocation = null;
}
}
private class WebServiceHandler extends AsyncTask<String, Void, String> {
// okienko dialogowe, które każe użytkownikowi czekać
private ProgressDialog dialog = new ProgressDialog(MapsActivityCurrentPlace.this);
// metoda wykonywana jest zaraz przed główną operacją (doInBackground())
// mamy w niej dostęp do elementów UI
@Override
protected void onPreExecute() {
// wyświetlamy okienko dialogowe każące czekać
dialog.setMessage("Czekaj...");
dialog.show();
}
// główna operacja, która wykona się w osobnym wątku
// nie ma w niej dostępu do elementów UI
@Override
protected String doInBackground(String... urls) {
try {
// zakładamy, że jest tylko jeden URL
URL url = new URL(urls[0]);
URLConnection connection = url.openConnection();
// pobranie danych do InputStream
InputStream in = new BufferedInputStream(
connection.getInputStream());
// konwersja InputStream na String
// wynik będzie przekazany do metody onPostExecute()
return streamToString(in);
} catch (Exception e) {
// obsłuż wyjątek
Log.d(MainActivity.class.getSimpleName(), e.toString());
return null;
}
}
// metoda wykonuje się po zakończeniu metody głównej,
// której wynik będzie przekazany;
// w tej metodzie mamy dostęp do UI
@Override
protected void onPostExecute(String result) {
// chowamy okno dialogowe
dialog.dismiss();
try {
// reprezentacja obiektu JSON w Javie
JSONObject json = new JSONObject(result);
JSONArray path= (JSONArray) json.get("path");
List<LatLng> road = new ArrayList<LatLng>();
for (int i = 0; i<path.length(); i++) {
road.add(new LatLng(Double.parseDouble(path.getJSONArray(i).get(0).toString()),Double.parseDouble(path.getJSONArray(i).get(1).toString() )));
}
Log.d("aws", path.getJSONArray(0).get(0).toString());
mMap.addPolyline(new PolylineOptions().addAll(road));
JSONArray fire = (JSONArray)json.get("fires");
for (int i = 0; i < fire.length(); i++) {
JSONObject fires = (JSONObject) fire.get(i);
JSONArray coords = (JSONArray)fires.get("coords");
LatLng fireplace = new LatLng(coords.getDouble(0), coords.getDouble(1));
LatLng yourPosition = new LatLng(Double.parseDouble(path.getJSONArray(i).get(0).toString()),Double.parseDouble(path.getJSONArray(i).get(1).toString() ));
Circle circle = mMap.addCircle(new CircleOptions()
.center(fireplace)
.radius(fires.getDouble("radius"))
.strokeColor(Color.RED)
.fillColor(Color.argb(100, 255, 40, 40)));
mMap.addMarker(new MarkerOptions().position(fireplace).title("Danger place"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(yourPosition, 18));
}
} catch (Exception e) {
// obsłuż wyjątek
Log.d("aws", e.toString());
}
}
}
// konwersja z InputStream do String
public static String streamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
reader.close();
} catch (IOException e) {
// obsłuż wyjątek
Log.d(MainActivity.class.getSimpleName(), e.toString());
}
return stringBuilder.toString();
}
}
| Aifryz/FireHelper | android_app/app/src/main/java/com/example/artbaryl/firehelper/MapsActivityCurrentPlace.java | 5,684 | // główna operacja, która wykona się w osobnym wątku | line_comment | pl | package com.example.artbaryl.firehelper;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.PlaceLikelihood;
import com.google.android.gms.location.places.PlaceLikelihoodBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* An activity that displays a map showing the place at the device's current location.
*/
public class MapsActivityCurrentPlace extends AppCompatActivity
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = MapsActivityCurrentPlace.class.getSimpleName();
private GoogleMap mMap;
private CameraPosition mCameraPosition;
// The entry point to Google Play services, used by the Places API and Fused Location Provider.
private GoogleApiClient mGoogleApiClient;
// A default location (Sydney, Australia) and default zoom to use when location permission is
// not granted.
private final LatLng mDefaultLocation = new LatLng(-33.8523341, 151.2106085);
private static final int DEFAULT_ZOOM = 15;
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private boolean mLocationPermissionGranted;
// The geographical location where the device is currently located. That is, the last-known
// location retrieved by the Fused Location Provider.
private Location mLastKnownLocation;
// Keys for storing activity state.
private static final String KEY_CAMERA_POSITION = "camera_position";
private static final String KEY_LOCATION = "location";
// Used for selecting the current place.
private final int mMaxEntries = 5;
private String[] mLikelyPlaceNames = new String[mMaxEntries];
private String[] mLikelyPlaceAddresses = new String[mMaxEntries];
private String[] mLikelyPlaceAttributions = new String[mMaxEntries];
private LatLng[] mLikelyPlaceLatLngs = new LatLng[mMaxEntries];
//My changes
String aws = "http://ec2-54-93-96-33.eu-central-1.compute.amazonaws.com:5000/51.763635/8.065624/51.754994/8.045626";
private final OkHttpClient client = new OkHttpClient();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retrieve location and camera position from saved instance state.
if (savedInstanceState != null) {
mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
}
// Retrieve the content view that renders the map.
setContentView(R.layout.activity_maps);
// Build the Play services client for use by the Fused Location Provider and the Places API.
// Use the addApi() method to request the Google Places API and the Fused Location Provider.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this ,
this )
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
mGoogleApiClient.connect();
}
/**
* Saves the state of the map when the activity is paused.
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
if (mMap != null) {
outState.putParcelable(KEY_CAMERA_POSITION, mMap.getCameraPosition());
outState.putParcelable(KEY_LOCATION, mLastKnownLocation);
super.onSaveInstanceState(outState);
}
}
/**
* Builds the map when the Google Play services client is successfully connected.
*/
@Override
public void onConnected(Bundle connectionHint) {
// Build the map.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Handles failure to connect to the Google Play services client.
*/
@Override
public void onConnectionFailed(@NonNull ConnectionResult result) {
// Refer to the reference doc for ConnectionResult to see what error codes might
// be returned in onConnectionFailed.
Log.d(TAG, "Play services connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
/**
* Handles suspension of the connection to the Google Play services client.
*/
@Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "Play services connection suspended");
}
/**
* Sets up the options menu.
* @param menu The options menu.
* @return Boolean.
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.current_place_menu, menu);
return true;
}
/**
* Handles a click on the menu option to get a place.
* @param item The menu item to handle.
* @return Boolean.
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.option_get_place) {
showCurrentPlace();
}
return true;
}
/**
* Manipulates the map when it's available.
* This callback is triggered when the map is ready to be used.
*/
@Override
public void onMapReady(GoogleMap map) {
mMap = map;
// Use a custom info window adapter to handle multiple lines of text in the
// info window contents.
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
@Override
// Return null here, so that getInfoContents() is called next.
public View getInfoWindow(Marker arg0) {
return null;
}
@Override
public View getInfoContents(Marker marker) {
// Inflate the layouts for the info window, title and snippet.
View infoWindow = getLayoutInflater().inflate(R.layout.custom_info_contents,
(FrameLayout)findViewById(R.id.map), false);
TextView title = ((TextView) infoWindow.findViewById(R.id.title));
title.setText(marker.getTitle());
TextView snippet = ((TextView) infoWindow.findViewById(R.id.snippet));
snippet.setText(marker.getSnippet());
return infoWindow;
}
});
// Turn on the My Location layer and the related control on the map.
updateLocationUI();
// Get the current location of the device and set the position of the map.
getDeviceLocation();
}
/**
* Gets the current location of the device, and positions the map's camera.
*/
private void getDeviceLocation() {
/*
* Request location permission, so that we can get the location of the
* device. The result of the permission request is handled by a callback,
* onRequestPermissionsResult.
*/
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
/*
* Get the best and most recent location of the device, which may be null in rare
* cases when a location is not available.
*/
if (mLocationPermissionGranted) {
mLastKnownLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
}
// Set the map's camera position to the current location of the device.
if (mCameraPosition != null) {
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(mCameraPosition));
} else if (mLastKnownLocation != null) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(mLastKnownLocation.getLatitude(),
mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
} else {
Log.d(TAG, "Current location is null. Using defaults.");
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
/**
* Handles the result of the request for location permissions.
*/
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[],
@NonNull int[] grantResults) {
mLocationPermissionGranted = false;
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
}
}
updateLocationUI();
}
/**
* Prompts the user to select the current place from a list of likely places, and shows the
* current place on the map - provided the user has granted location permission.
*/
private void showCurrentPlace() {
if (mMap == null) {
return;
}
new WebServiceHandler()
.execute(aws);
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
/*
if (mLocationPermissionGranted) {
Log.d("lol", "Im in - agree");
// Get the likely places - that is, the businesses and other points of interest that
// are the best match for the device's current location.
@SuppressWarnings("MissingPermission")
PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
.getCurrentPlace(mGoogleApiClient, null);
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
@Override
public void onResult(@NonNull PlaceLikelihoodBuffer likelyPlaces) {
int i = 0;
mLikelyPlaceNames = new String[mMaxEntries];
mLikelyPlaceAddresses = new String[mMaxEntries];
mLikelyPlaceAttributions = new String[mMaxEntries];
mLikelyPlaceLatLngs = new LatLng[mMaxEntries];
for (PlaceLikelihood placeLikelihood : likelyPlaces) {
// Build a list of likely places to show the user. Max 5.
mLikelyPlaceNames[i] = (String) placeLikelihood.getPlace().getName();
mLikelyPlaceAddresses[i] = (String) placeLikelihood.getPlace().getAddress();
mLikelyPlaceAttributions[i] = (String) placeLikelihood.getPlace()
.getAttributions();
mLikelyPlaceLatLngs[i] = placeLikelihood.getPlace().getLatLng();
i++;
if (i > (mMaxEntries - 1)) {
break;
}
}
// Release the place likelihood buffer, to avoid memory leaks.
likelyPlaces.release();
// Show a dialog offering the user the list of likely places, and add a
// marker at the selected place.
openPlacesDialog();
}
});
} else {
Log.d("lol", "Im in - without agree");
// Add a default marker, because the user hasn't selected a place.
mMap.addMarker(new MarkerOptions()
.title(getString(R.string.default_info_title))
.position(mDefaultLocation)
.snippet(getString(R.string.default_info_snippet)));
}*/
}
/**
* Displays a form allowing the user to select a place from a list of likely places.
*/
private void openPlacesDialog() {
// Ask the user to choose the place where they are now.
DialogInterface.OnClickListener listener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// The "which" argument contains the position of the selected item.
LatLng markerLatLng = mLikelyPlaceLatLngs[which];
String markerSnippet = mLikelyPlaceAddresses[which];
if (mLikelyPlaceAttributions[which] != null) {
markerSnippet = markerSnippet + "\n" + mLikelyPlaceAttributions[which];
}
// Add a marker for the selected place, with an info window
// showing information about that place.
mMap.addMarker(new MarkerOptions()
.title(mLikelyPlaceNames[which])
.position(markerLatLng)
.snippet(markerSnippet));
//Log.d("LatLng", String.valueOf(markerLatLng));
// Position the map's camera at the location of the marker.
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(markerLatLng,
DEFAULT_ZOOM));
}
};
// Display the dialog.
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle(R.string.pick_place)
.setItems(mLikelyPlaceNames, listener)
.show();
}
/**
* Updates the map's UI settings based on whether the user has granted location permission.
*/
private void updateLocationUI() {
if (mMap == null) {
return;
}
/*
* Request location permission, so that we can get the location of the
* device. The result of the permission request is handled by a callback,
* onRequestPermissionsResult.
*/
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
if (mLocationPermissionGranted) {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
mMap.setMyLocationEnabled(false);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mLastKnownLocation = null;
}
}
private class WebServiceHandler extends AsyncTask<String, Void, String> {
// okienko dialogowe, które każe użytkownikowi czekać
private ProgressDialog dialog = new ProgressDialog(MapsActivityCurrentPlace.this);
// metoda wykonywana jest zaraz przed główną operacją (doInBackground())
// mamy w niej dostęp do elementów UI
@Override
protected void onPreExecute() {
// wyświetlamy okienko dialogowe każące czekać
dialog.setMessage("Czekaj...");
dialog.show();
}
// gł<SUF>
// nie ma w niej dostępu do elementów UI
@Override
protected String doInBackground(String... urls) {
try {
// zakładamy, że jest tylko jeden URL
URL url = new URL(urls[0]);
URLConnection connection = url.openConnection();
// pobranie danych do InputStream
InputStream in = new BufferedInputStream(
connection.getInputStream());
// konwersja InputStream na String
// wynik będzie przekazany do metody onPostExecute()
return streamToString(in);
} catch (Exception e) {
// obsłuż wyjątek
Log.d(MainActivity.class.getSimpleName(), e.toString());
return null;
}
}
// metoda wykonuje się po zakończeniu metody głównej,
// której wynik będzie przekazany;
// w tej metodzie mamy dostęp do UI
@Override
protected void onPostExecute(String result) {
// chowamy okno dialogowe
dialog.dismiss();
try {
// reprezentacja obiektu JSON w Javie
JSONObject json = new JSONObject(result);
JSONArray path= (JSONArray) json.get("path");
List<LatLng> road = new ArrayList<LatLng>();
for (int i = 0; i<path.length(); i++) {
road.add(new LatLng(Double.parseDouble(path.getJSONArray(i).get(0).toString()),Double.parseDouble(path.getJSONArray(i).get(1).toString() )));
}
Log.d("aws", path.getJSONArray(0).get(0).toString());
mMap.addPolyline(new PolylineOptions().addAll(road));
JSONArray fire = (JSONArray)json.get("fires");
for (int i = 0; i < fire.length(); i++) {
JSONObject fires = (JSONObject) fire.get(i);
JSONArray coords = (JSONArray)fires.get("coords");
LatLng fireplace = new LatLng(coords.getDouble(0), coords.getDouble(1));
LatLng yourPosition = new LatLng(Double.parseDouble(path.getJSONArray(i).get(0).toString()),Double.parseDouble(path.getJSONArray(i).get(1).toString() ));
Circle circle = mMap.addCircle(new CircleOptions()
.center(fireplace)
.radius(fires.getDouble("radius"))
.strokeColor(Color.RED)
.fillColor(Color.argb(100, 255, 40, 40)));
mMap.addMarker(new MarkerOptions().position(fireplace).title("Danger place"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(yourPosition, 18));
}
} catch (Exception e) {
// obsłuż wyjątek
Log.d("aws", e.toString());
}
}
}
// konwersja z InputStream do String
public static String streamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
reader.close();
} catch (IOException e) {
// obsłuż wyjątek
Log.d(MainActivity.class.getSimpleName(), e.toString());
}
return stringBuilder.toString();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.