file_id stringlengths 5 10 | content stringlengths 121 33.1k | repo stringlengths 7 77 | path stringlengths 7 174 | token_length int64 42 8.19k | original_comment stringlengths 8 6.63k | comment_type stringclasses 2 values | detected_lang stringclasses 1 value | prompt stringlengths 37 33k |
|---|---|---|---|---|---|---|---|---|
159683_10 | package SnailLifeAnimation;
import java.awt.*;
import java.util.Arrays;
import java.util.Random;
public class Snail extends Thread{
private int y, x, velocity, time;
private Leaf leaf;
public Snail(int velocity, int time, Leaf leaf) {
this.velocity = velocity;
this.time = time;
this.leaf = leaf;
generatePosition();
}
@Override
public void run() {
while (!Thread.interrupted()) {
move();
//System.out.println("test: " + Thread.currentThread().getId() + "x: " + getX() + ", y: " + getY());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public void generatePosition() {
int newX, newY;
Random rn = new Random();
do {
newY = rn.nextInt(leaf.getHeight());
newX = rn.nextInt(leaf.getWidth());
} while (leaf.isOccupiedAt(newY, newX));
this.y = newY;
this.x = newX;
leaf.setOccupiedAt(newY, newX, true);
}
private synchronized void move() {
int[] possibleMoves = getValidMoves();
if (possibleMoves.length > 0) {
int randomMoveIndex = new Random().nextInt(possibleMoves.length);
int selectedMove = possibleMoves[randomMoveIndex];
switch (selectedMove) {
case 0: // Move up
moveUp();
break;
case 1: // Move down
moveDown();
break;
case 2: // Move left
moveLeft();
break;
case 3: // Move right
moveRight();
break;
case 4: // Move diagonally up-left
moveUpLeft();
break;
case 5: // Move diagonally up-right
moveUpRight();
break;
case 6: // Move diagonally down-left
moveDownLeft();
break;
case 7: // Move diagonally down-right
moveDownRight();
break;
}
// Konsumowanie liścia
consumeLeaf();
} else {
try {
Thread.sleep(time); // Uśpienie na określony czas, gdy brak możliwości ruchu
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
private void consumeLeaf() {
int foodAmount = leaf.getFoodAmountAt(y, x);
int newFoodAmount = Math.max(0, foodAmount - velocity);
leaf.setFoodAmountAt(y, x, newFoodAmount);
}
private int[] getValidMoves() {
int[] validMoves = new int[8];
int count = 0;
if (y > 0 && leaf.getFoodAmountAt(y - 1, x) > 0 && !leaf.isOccupiedAt(y - 1, x)) {
validMoves[count++] = 0; // Move up
}
if (y < leaf.getHeight() - 1 && leaf.getFoodAmountAt(y + 1, x) > 0 && !leaf.isOccupiedAt(y + 1, x)) {
validMoves[count++] = 1; // Move down
}
if (x > 0 && leaf.getFoodAmountAt(y, x - 1) > 0 && !leaf.isOccupiedAt(y, x - 1)) {
validMoves[count++] = 2; // Move left
}
if (x < leaf.getWidth() - 1 && leaf.getFoodAmountAt(y, x + 1) > 0 && !leaf.isOccupiedAt(y, x + 1)) {
validMoves[count++] = 3; // Move right
}
if (y > 0 && x > 0 && leaf.getFoodAmountAt(y - 1, x - 1) > 0 && !leaf.isOccupiedAt(y - 1, x - 1)) {
validMoves[count++] = 4; // Move diagonally up-left
}
if (y > 0 && x < leaf.getWidth() - 1 && leaf.getFoodAmountAt(y - 1, x + 1) > 0 && !leaf.isOccupiedAt(y - 1, x + 1)) {
validMoves[count++] = 5; // Move diagonally up-right
}
if (y < leaf.getHeight() - 1 && x > 0 && leaf.getFoodAmountAt(y + 1, x - 1) > 0 && !leaf.isOccupiedAt(y + 1, x - 1)) {
validMoves[count++] = 6; // Move diagonally down-left
}
if (y < leaf.getHeight() - 1 && x < leaf.getWidth() - 1 && leaf.getFoodAmountAt(y + 1, x + 1) > 0 && !leaf.isOccupiedAt(y + 1, x + 1)) {
validMoves[count++] = 7; // Move diagonally down-right
}
// Trim the array to the actual number of valid moves
return Arrays.copyOf(validMoves, count);
}
private void moveUp() {
move(-1, 0);
}
private void moveDown() {
move(1, 0);
}
private void moveLeft() {
move(0, -1);
}
private void moveRight() {
move(0, 1);
}
private void moveUpLeft() {
move(-1, -1);
}
private void moveUpRight() {
move(-1, 1);
}
private void moveDownLeft() {
move(1, -1);
}
private void moveDownRight() {
move(1, 1);
}
private void move(int deltaY, int deltaX) {
leaf.setOccupiedAt(y, x, false);
y += deltaY;
x += deltaX;
leaf.setOccupiedAt(y, x, true);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
} | xzalerr/JezykiProgramowania | src/main/java/SnailLifeAnimation/Snail.java | 1,743 | // Uśpienie na określony czas, gdy brak możliwości ruchu | line_comment | pl | package SnailLifeAnimation;
import java.awt.*;
import java.util.Arrays;
import java.util.Random;
public class Snail extends Thread{
private int y, x, velocity, time;
private Leaf leaf;
public Snail(int velocity, int time, Leaf leaf) {
this.velocity = velocity;
this.time = time;
this.leaf = leaf;
generatePosition();
}
@Override
public void run() {
while (!Thread.interrupted()) {
move();
//System.out.println("test: " + Thread.currentThread().getId() + "x: " + getX() + ", y: " + getY());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public void generatePosition() {
int newX, newY;
Random rn = new Random();
do {
newY = rn.nextInt(leaf.getHeight());
newX = rn.nextInt(leaf.getWidth());
} while (leaf.isOccupiedAt(newY, newX));
this.y = newY;
this.x = newX;
leaf.setOccupiedAt(newY, newX, true);
}
private synchronized void move() {
int[] possibleMoves = getValidMoves();
if (possibleMoves.length > 0) {
int randomMoveIndex = new Random().nextInt(possibleMoves.length);
int selectedMove = possibleMoves[randomMoveIndex];
switch (selectedMove) {
case 0: // Move up
moveUp();
break;
case 1: // Move down
moveDown();
break;
case 2: // Move left
moveLeft();
break;
case 3: // Move right
moveRight();
break;
case 4: // Move diagonally up-left
moveUpLeft();
break;
case 5: // Move diagonally up-right
moveUpRight();
break;
case 6: // Move diagonally down-left
moveDownLeft();
break;
case 7: // Move diagonally down-right
moveDownRight();
break;
}
// Konsumowanie liścia
consumeLeaf();
} else {
try {
Thread.sleep(time); // Uśpie<SUF>
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
private void consumeLeaf() {
int foodAmount = leaf.getFoodAmountAt(y, x);
int newFoodAmount = Math.max(0, foodAmount - velocity);
leaf.setFoodAmountAt(y, x, newFoodAmount);
}
private int[] getValidMoves() {
int[] validMoves = new int[8];
int count = 0;
if (y > 0 && leaf.getFoodAmountAt(y - 1, x) > 0 && !leaf.isOccupiedAt(y - 1, x)) {
validMoves[count++] = 0; // Move up
}
if (y < leaf.getHeight() - 1 && leaf.getFoodAmountAt(y + 1, x) > 0 && !leaf.isOccupiedAt(y + 1, x)) {
validMoves[count++] = 1; // Move down
}
if (x > 0 && leaf.getFoodAmountAt(y, x - 1) > 0 && !leaf.isOccupiedAt(y, x - 1)) {
validMoves[count++] = 2; // Move left
}
if (x < leaf.getWidth() - 1 && leaf.getFoodAmountAt(y, x + 1) > 0 && !leaf.isOccupiedAt(y, x + 1)) {
validMoves[count++] = 3; // Move right
}
if (y > 0 && x > 0 && leaf.getFoodAmountAt(y - 1, x - 1) > 0 && !leaf.isOccupiedAt(y - 1, x - 1)) {
validMoves[count++] = 4; // Move diagonally up-left
}
if (y > 0 && x < leaf.getWidth() - 1 && leaf.getFoodAmountAt(y - 1, x + 1) > 0 && !leaf.isOccupiedAt(y - 1, x + 1)) {
validMoves[count++] = 5; // Move diagonally up-right
}
if (y < leaf.getHeight() - 1 && x > 0 && leaf.getFoodAmountAt(y + 1, x - 1) > 0 && !leaf.isOccupiedAt(y + 1, x - 1)) {
validMoves[count++] = 6; // Move diagonally down-left
}
if (y < leaf.getHeight() - 1 && x < leaf.getWidth() - 1 && leaf.getFoodAmountAt(y + 1, x + 1) > 0 && !leaf.isOccupiedAt(y + 1, x + 1)) {
validMoves[count++] = 7; // Move diagonally down-right
}
// Trim the array to the actual number of valid moves
return Arrays.copyOf(validMoves, count);
}
private void moveUp() {
move(-1, 0);
}
private void moveDown() {
move(1, 0);
}
private void moveLeft() {
move(0, -1);
}
private void moveRight() {
move(0, 1);
}
private void moveUpLeft() {
move(-1, -1);
}
private void moveUpRight() {
move(-1, 1);
}
private void moveDownLeft() {
move(1, -1);
}
private void moveDownRight() {
move(1, 1);
}
private void move(int deltaY, int deltaX) {
leaf.setOccupiedAt(y, x, false);
y += deltaY;
x += deltaX;
leaf.setOccupiedAt(y, x, true);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
} |
41798_13 | /**
Klasa zawierajaca plansze na ktorej odbywa sie symulacja oraz liste zwierzat, plansza ma okreslone wymiary okreslone polami 'width' oraz 'height'
Dwuwymiarowa tablica zawiera polozenie zwierzat oraz sluzy do ich przechowywania w trakcie trwania symulacji
*/
public class Board {
/**
Wysokosc planszy
*/
private static int height;
/**
Szerokosc planszy
*/
private static int width;
/**
Tablica wszystkich zwierzat bioracych udzial w symulacji
*/
private Animal animals[][];
public Board(int width, int height) {
this.width = width;
this.height = height;
this.animals = new Animal[width][height];
}
/**
metoda dodaje zwierze w konkretne miejsce na planszy
*/
public void addAnimal(Animal animal, int x, int y) {
animals[x][y] = animal;
}
/**
metoda usuwa zwierze z miejsca na planszy po przegranej walce
*/
public void removeAnimal(int x, int y) {
animals[x][y] = null;
}
/**
metoda usuwa zwierze z miejsca na planszy po przegranej walce, wykorzystywana gdy chemy usunac konkretne zwierze bez koniecznosci pobierania jego wspolrzednych
*/
public void removeLoserAnimal(Animal loser) {
animals[loser.getX()][loser.getY()] = null;
}
/**
metoda porusza zwierze z punktu a do b, w zaleznosci od metody move() danego gatunku, jesli zwierzeta sie
spotkaja to walcza (chyba ze sa tego samego gatunku), badz roslinozercy odchodza na inne pole niz inny roslinozerca rowniez
metody polowania i ucieczki sa zaimplementowane w tej metodzie przemieszczanie zwierzecia
*/
public void moveAnimal(int fromX, int fromY) {
Animal relocated = getAnimal(fromX, fromY);
relocated.move(fromX, fromY);
int toX = relocated.getX();
int toY = relocated.getY();
if(toX>=Board.getWidth()) {
toX = toX % Board.getWidth();
} else if(toX < 0) {
toX += Board.getWidth();
}
if(toY>=Board.getHeight()) {
toY = toY % Board.getHeight();
} else if(toY < 0) {
toY += Board.getHeight();
}
//jesli pole na ktore przemieszcza sie zwierze jest zajete
if(isOccupied(toX, toY)) {;
System.out.println("SPOTKANIE ZWIERZAT:");
Animal opponent = getAnimal(toX, toY);
//jesli roslinozerca spotka inne zwierze to zawsze pojdzie na pole obok, unikajac ataku
//jesli spotkaja sie 2 zwierzeta tego samego gatunku, nawet miesozercy, to tez ida na pole obok unikajac ataku
if(relocated.getFoodType().equals("herbs") || (relocated.symbol == opponent.symbol)){
System.out.println(relocated.symbol + " spotkal: " + opponent.symbol + ", wiec nie zawalcza.");
int[] moveNearby = findEmptyPosition(relocated);
if(moveNearby != null) {
toX = moveNearby[0];
toY = moveNearby[1];
relocated.setX(moveNearby[0]);
relocated.setY(moveNearby[1]);
animals[toX][toY] = relocated;
removeAnimal(fromX, fromY);
} else {
relocated.setX(fromX);
relocated.setY(fromY);
return;
}
//jesli miesozerca spotka roslinozerce to atakuje go
//jesli miesozerca wygra to przechodzi na miejsce w ktorym pokonal przeciwnika i roslinozerca jest usuwany z planszy
//jesli roslinozerca wygra to miesozerca przechodzi na jego miejsce, a roslinozerca ucieka z uzyciem metody escape()
} else if(relocated.getFoodType().equals("meat") && opponent.getFoodType().equals("herbs")) {
System.out.println(relocated.symbol + " spotkal: " + opponent.symbol + ", wiec zawalcza.");
Animal loser = relocated.fightLoser(opponent);
if(loser == opponent) {
removeLoserAnimal(opponent);
animals[toX][toY] = relocated;
removeAnimal(fromX, fromY);
opponent.setActive(false);
System.out.println(relocated.symbol + " zwyciezyl!");
} else if(loser == relocated) {
System.out.println(relocated.symbol + "(atakujacy) przegral z: " + opponent.symbol);
animals[toX][toY] = relocated;
removeAnimal(fromX, fromY);
int[] esc;
if (opponent.symbol.equals("H")) {
esc = ((Hare) opponent).escape(opponent.getX(), opponent.getY());
} else {
esc = ((RoeDeer) opponent).escape(opponent.getX(), opponent.getY());
}
for (int j = 0; j < 4; j++) {
int escX = esc[j * 2];
int escY = esc[j * 2 + 1];
if ((escX < 0 || escX > Board.getWidth() - 1) || (escY < 0 || escY > Board.getWidth() - 1)) {
continue;
}
else {
if (!isOccupied(escX,escY)){
int newX = opponent.getX();
int newY = opponent.getY();
opponent.setX(escX);
opponent.setY(escY);
animals[escX][escY] = opponent;
//removeAnimal(fromX,fromY);
System.out.println(opponent.symbol + " uciekł!");
break;
}
}
}
}
//jesli miesozerca spotka innego miesozerce to atakuje go
//jesli atakujacy wygra to przechodzi na miejsce w ktorym pokonal przeciwnika i przeciwnik jest usuwany z planszy
//jesli atakujacy przegra to jest usuwany z planszy i zwyciezca pozostaje na swoim miejscu
} else if(relocated.getFoodType().equals("meat") && opponent.getFoodType().equals("meat")) {
System.out.println(relocated.symbol + " spotkal: " + opponent.symbol + ", wiec zawalcza.");
Animal loser = relocated.fightLoser(opponent);
if(loser == opponent) {
removeLoserAnimal(opponent);
opponent.setActive(false);
animals[toX][toY] = relocated;
removeAnimal(fromX, fromY);
System.out.println(relocated.symbol + " zwyciezyl!");
} else if(loser == relocated) {
System.out.println(relocated.symbol + " zaatakował i przegrał z: " + opponent.symbol);
removeAnimal(fromX, fromY);
relocated.setActive(false);
}
}
//jesli zwierze niespotka nikogo
} else {
animals[toX][toY] = relocated;
removeAnimal(fromX, fromY);
boolean attack = false;
//lis implementuje metode hunt i stara sie znalezc przeciwnika do ataku, jesli sie nie uda to konczy sie jego tura
if (relocated.symbol.equals("F")){
int[] arr = ((Fox)relocated).hunt(relocated.getX(), relocated.getY());
for (int i = 0; i < 4; i++) {
int huntX = arr[i*2];
int huntY = arr[i*2+1];
if ((huntX < 0 || huntX > Board.getWidth() - 1) || (huntY < 0 || huntY > Board.getHeight() - 1)) {
continue;
}
else {
if (isOccupied(huntX,huntY) && !attack) {
attack = true;
System.out.println("F zapolowal:");
Animal opponent = getAnimal(huntX, huntY);
System.out.println(relocated.symbol + " zaatakowal: " + opponent.symbol);
if(opponent.getFoodType().equals("herbs")) {
Animal loser = relocated.fightLoser(opponent);
if(loser == opponent) {
removeLoserAnimal(opponent);
animals[huntX][huntY] = relocated;
relocated.setX(huntX);
relocated.setY(huntY);
removeAnimal(toX, toY);
System.out.println("Przegral: " + opponent.symbol);
opponent.setActive(false);
} else if(loser == relocated) {
System.out.println("Ucieczka. Przegral: " + relocated.symbol);
int[] esc;
if (opponent.symbol.equals("H")) {
esc = ((Hare) opponent).escape(opponent.getX(), opponent.getY());
} else {
esc = ((RoeDeer) opponent).escape(opponent.getX(), opponent.getY());
}
for (int j = 0; j < 4; j++) {
int escX = esc[j * 2];
int escY = esc[j * 2 + 1];
if ((escX < 0 || escX > Board.getWidth() - 1) || (escY < 0 || escY > Board.getHeight() - 1)) {
continue;
}
else {
if (!isOccupied(escX,escY)){
int newX = opponent.getX();
int newY = opponent.getY();
opponent.setX(escX);
opponent.setY(escY);
animals[escX][escY] = opponent;
removeAnimal(newX,newY);
break;
}
}
if (j == 3){
System.out.println("Brak opcji ucieczki, zwierze ginie");
removeLoserAnimal(opponent);
animals[huntX][huntY] = relocated;
relocated.setX(huntX);
relocated.setY(huntY);
removeAnimal(toX, toY);
System.out.println("Przegral: " + opponent.symbol + " Bo nie mial gdzie uciec");
opponent.setActive(false);
}
}
}
} else if (opponent.getFoodType().equals("meat") && (relocated.symbol != opponent.symbol)) {
Animal loser = relocated.fightLoser(opponent);
if (loser == opponent) {
removeLoserAnimal(opponent);
animals[huntX][huntY] = relocated;
relocated.setX(huntX);
relocated.setY(huntY);
removeAnimal(toX, toY);
opponent.setActive(false);
System.out.println("Przegral: " + opponent.symbol);
} else if (loser == relocated) {
removeLoserAnimal(relocated);
relocated.setActive(false);
System.out.println("Przegral: " + relocated.symbol);
}
}
}
}
}
}
//wilk implementuje metode hunt i stara sie znalezc przeciwnika do ataku, jesli sie nie uda to konczy sie jego tura
if (relocated.symbol.equals("W")) {
int[] arr = ((Wolf) relocated).hunt(relocated.getX(), relocated.getY());
for (int i = 0; i < 8; i++) {
int huntX = arr[i * 2];
int huntY = arr[i * 2 + 1];
if ((huntX < 0 || huntX > Board.getWidth() - 1) || (huntY < 0 || huntY > Board.getHeight() - 1)) {
continue;
} else {
if (isOccupied(huntX, huntY) && !attack) {
attack = true;
System.out.println("W zapolowal: ");
Animal opponent = getAnimal(huntX, huntY);
System.out.println(relocated.symbol+" zaatakowal: "+opponent.symbol);
if (opponent.getFoodType().equals("herbs")) {
Animal loser = relocated.fightLoser(opponent);
if (loser == opponent) {
removeLoserAnimal(opponent);
animals[huntX][huntY] = relocated;
relocated.setX(huntX);
relocated.setY(huntY);
removeAnimal(toX, toY);
opponent.setActive(false);
System.out.println("Przegral: " + opponent.symbol);
} else if (loser == relocated) {
System.out.println("Ucieczka. Przegral: " + relocated.symbol);
int[] esc;
if (opponent.symbol.equals("H")) {
esc = ((Hare) opponent).escape(opponent.getX(), opponent.getY());
} else {
esc = ((RoeDeer) opponent).escape(opponent.getX(), opponent.getY());
}
for (int j = 0; j < 4; j++) {
int escX = esc[j * 2];
int escY = esc[j * 2 + 1];
if ((escX < 0 || escX > Board.getWidth() - 1) || (escY < 0 || escY > Board.getHeight() - 1)) {
continue;
}
else {
if (!isOccupied(escX,escY)){
int newX = opponent.getX();
int newY = opponent.getY();
opponent.setX(escX);
opponent.setY(escY);
animals[escX][escY] = opponent;
removeAnimal(newX,newY);
break;
}
}
if (j == 3){
System.out.println("Brak opcji ucieczki, zwierze ginie");
removeLoserAnimal(opponent);
animals[huntX][huntY] = relocated;
relocated.setX(huntX);
relocated.setY(huntY);
removeAnimal(toX, toY);
System.out.println("Przegral: " + opponent.symbol + " Bo nie mial gdzie uciec");
opponent.setActive(false);
}
}
}
} else if (opponent.getFoodType().equals("meat") && (relocated.symbol != opponent.symbol)) {
Animal loser = relocated.fightLoser(opponent);
if (loser == opponent) {
removeLoserAnimal(opponent);
animals[huntX][huntY] = relocated;
relocated.setX(huntX);
relocated.setY(huntY);
removeAnimal(toX, toY);
opponent.setActive(false);
System.out.println("Przegral: " + opponent.symbol);
} else if (loser == relocated) {
removeLoserAnimal(relocated);
relocated.setActive(false);
System.out.println("Przegral: " + relocated.symbol);
}
} else {
System.out.println("Zrezygnował z polowania bo zobaczyl ze to ten sam gatunek.");
}
}
}
}
}
}
}
/**
metoda sprawdza czy na danym polu planszy znajduje sie inne zwierze niz to ktore sie tam przemiescilo
*/
public boolean isOccupied(int x, int y) {
return animals[x][y] != null;
}
public Animal getAnimal(int x, int y) {
return animals[x][y];
}
public static int getHeight() {
return height;
}
public static int getWidth() {
return width;
}
/**
metoda sprawdzajaca wszystkie wolne pola w okol pola o zadancyh wspolrzednych, jesli uda sie znalezc to
zwraca jego wspolrzedne, jest wykorzystywana
gdy spotka sie 2 roslinozercow lub 2 zwierzeta tego samego gatunku
*/
public int[] findEmptyPosition(Animal animal) {
int newX, newY;
int[] emptyPosition = new int[2];
emptyPosition[0] = animal.getX();
emptyPosition[1] = animal.getY();
for(int i = -1; i <= 1; i++) {
for(int j = -1; j <=1; j++) {
if( i == 0 && j ==0) {
continue;
}
newX = emptyPosition[0] + i;
newY = emptyPosition[1] + j;
if(newX>=Board.getWidth()) {
newX -= Board.getWidth();
} else if(newX < 0) {
newX += Board.getWidth();
}
if(newY>=Board.getHeight()) {
newY -= Board.getHeight();
} else if(newY < 0) {
newY += Board.getHeight();
}
if(!isOccupied(newX, newY)) {
emptyPosition[0] = newX;
emptyPosition[1] = newY;
animal.setX(newX);
animal.setY(newY);
return emptyPosition;
}
}
}
return null;
}
}
| xzalerr/Projekt_PO | src/main/java/Board.java | 5,232 | //jesli roslinozerca wygra to miesozerca przechodzi na jego miejsce, a roslinozerca ucieka z uzyciem metody escape() | line_comment | pl | /**
Klasa zawierajaca plansze na ktorej odbywa sie symulacja oraz liste zwierzat, plansza ma okreslone wymiary okreslone polami 'width' oraz 'height'
Dwuwymiarowa tablica zawiera polozenie zwierzat oraz sluzy do ich przechowywania w trakcie trwania symulacji
*/
public class Board {
/**
Wysokosc planszy
*/
private static int height;
/**
Szerokosc planszy
*/
private static int width;
/**
Tablica wszystkich zwierzat bioracych udzial w symulacji
*/
private Animal animals[][];
public Board(int width, int height) {
this.width = width;
this.height = height;
this.animals = new Animal[width][height];
}
/**
metoda dodaje zwierze w konkretne miejsce na planszy
*/
public void addAnimal(Animal animal, int x, int y) {
animals[x][y] = animal;
}
/**
metoda usuwa zwierze z miejsca na planszy po przegranej walce
*/
public void removeAnimal(int x, int y) {
animals[x][y] = null;
}
/**
metoda usuwa zwierze z miejsca na planszy po przegranej walce, wykorzystywana gdy chemy usunac konkretne zwierze bez koniecznosci pobierania jego wspolrzednych
*/
public void removeLoserAnimal(Animal loser) {
animals[loser.getX()][loser.getY()] = null;
}
/**
metoda porusza zwierze z punktu a do b, w zaleznosci od metody move() danego gatunku, jesli zwierzeta sie
spotkaja to walcza (chyba ze sa tego samego gatunku), badz roslinozercy odchodza na inne pole niz inny roslinozerca rowniez
metody polowania i ucieczki sa zaimplementowane w tej metodzie przemieszczanie zwierzecia
*/
public void moveAnimal(int fromX, int fromY) {
Animal relocated = getAnimal(fromX, fromY);
relocated.move(fromX, fromY);
int toX = relocated.getX();
int toY = relocated.getY();
if(toX>=Board.getWidth()) {
toX = toX % Board.getWidth();
} else if(toX < 0) {
toX += Board.getWidth();
}
if(toY>=Board.getHeight()) {
toY = toY % Board.getHeight();
} else if(toY < 0) {
toY += Board.getHeight();
}
//jesli pole na ktore przemieszcza sie zwierze jest zajete
if(isOccupied(toX, toY)) {;
System.out.println("SPOTKANIE ZWIERZAT:");
Animal opponent = getAnimal(toX, toY);
//jesli roslinozerca spotka inne zwierze to zawsze pojdzie na pole obok, unikajac ataku
//jesli spotkaja sie 2 zwierzeta tego samego gatunku, nawet miesozercy, to tez ida na pole obok unikajac ataku
if(relocated.getFoodType().equals("herbs") || (relocated.symbol == opponent.symbol)){
System.out.println(relocated.symbol + " spotkal: " + opponent.symbol + ", wiec nie zawalcza.");
int[] moveNearby = findEmptyPosition(relocated);
if(moveNearby != null) {
toX = moveNearby[0];
toY = moveNearby[1];
relocated.setX(moveNearby[0]);
relocated.setY(moveNearby[1]);
animals[toX][toY] = relocated;
removeAnimal(fromX, fromY);
} else {
relocated.setX(fromX);
relocated.setY(fromY);
return;
}
//jesli miesozerca spotka roslinozerce to atakuje go
//jesli miesozerca wygra to przechodzi na miejsce w ktorym pokonal przeciwnika i roslinozerca jest usuwany z planszy
//jesli<SUF>
} else if(relocated.getFoodType().equals("meat") && opponent.getFoodType().equals("herbs")) {
System.out.println(relocated.symbol + " spotkal: " + opponent.symbol + ", wiec zawalcza.");
Animal loser = relocated.fightLoser(opponent);
if(loser == opponent) {
removeLoserAnimal(opponent);
animals[toX][toY] = relocated;
removeAnimal(fromX, fromY);
opponent.setActive(false);
System.out.println(relocated.symbol + " zwyciezyl!");
} else if(loser == relocated) {
System.out.println(relocated.symbol + "(atakujacy) przegral z: " + opponent.symbol);
animals[toX][toY] = relocated;
removeAnimal(fromX, fromY);
int[] esc;
if (opponent.symbol.equals("H")) {
esc = ((Hare) opponent).escape(opponent.getX(), opponent.getY());
} else {
esc = ((RoeDeer) opponent).escape(opponent.getX(), opponent.getY());
}
for (int j = 0; j < 4; j++) {
int escX = esc[j * 2];
int escY = esc[j * 2 + 1];
if ((escX < 0 || escX > Board.getWidth() - 1) || (escY < 0 || escY > Board.getWidth() - 1)) {
continue;
}
else {
if (!isOccupied(escX,escY)){
int newX = opponent.getX();
int newY = opponent.getY();
opponent.setX(escX);
opponent.setY(escY);
animals[escX][escY] = opponent;
//removeAnimal(fromX,fromY);
System.out.println(opponent.symbol + " uciekł!");
break;
}
}
}
}
//jesli miesozerca spotka innego miesozerce to atakuje go
//jesli atakujacy wygra to przechodzi na miejsce w ktorym pokonal przeciwnika i przeciwnik jest usuwany z planszy
//jesli atakujacy przegra to jest usuwany z planszy i zwyciezca pozostaje na swoim miejscu
} else if(relocated.getFoodType().equals("meat") && opponent.getFoodType().equals("meat")) {
System.out.println(relocated.symbol + " spotkal: " + opponent.symbol + ", wiec zawalcza.");
Animal loser = relocated.fightLoser(opponent);
if(loser == opponent) {
removeLoserAnimal(opponent);
opponent.setActive(false);
animals[toX][toY] = relocated;
removeAnimal(fromX, fromY);
System.out.println(relocated.symbol + " zwyciezyl!");
} else if(loser == relocated) {
System.out.println(relocated.symbol + " zaatakował i przegrał z: " + opponent.symbol);
removeAnimal(fromX, fromY);
relocated.setActive(false);
}
}
//jesli zwierze niespotka nikogo
} else {
animals[toX][toY] = relocated;
removeAnimal(fromX, fromY);
boolean attack = false;
//lis implementuje metode hunt i stara sie znalezc przeciwnika do ataku, jesli sie nie uda to konczy sie jego tura
if (relocated.symbol.equals("F")){
int[] arr = ((Fox)relocated).hunt(relocated.getX(), relocated.getY());
for (int i = 0; i < 4; i++) {
int huntX = arr[i*2];
int huntY = arr[i*2+1];
if ((huntX < 0 || huntX > Board.getWidth() - 1) || (huntY < 0 || huntY > Board.getHeight() - 1)) {
continue;
}
else {
if (isOccupied(huntX,huntY) && !attack) {
attack = true;
System.out.println("F zapolowal:");
Animal opponent = getAnimal(huntX, huntY);
System.out.println(relocated.symbol + " zaatakowal: " + opponent.symbol);
if(opponent.getFoodType().equals("herbs")) {
Animal loser = relocated.fightLoser(opponent);
if(loser == opponent) {
removeLoserAnimal(opponent);
animals[huntX][huntY] = relocated;
relocated.setX(huntX);
relocated.setY(huntY);
removeAnimal(toX, toY);
System.out.println("Przegral: " + opponent.symbol);
opponent.setActive(false);
} else if(loser == relocated) {
System.out.println("Ucieczka. Przegral: " + relocated.symbol);
int[] esc;
if (opponent.symbol.equals("H")) {
esc = ((Hare) opponent).escape(opponent.getX(), opponent.getY());
} else {
esc = ((RoeDeer) opponent).escape(opponent.getX(), opponent.getY());
}
for (int j = 0; j < 4; j++) {
int escX = esc[j * 2];
int escY = esc[j * 2 + 1];
if ((escX < 0 || escX > Board.getWidth() - 1) || (escY < 0 || escY > Board.getHeight() - 1)) {
continue;
}
else {
if (!isOccupied(escX,escY)){
int newX = opponent.getX();
int newY = opponent.getY();
opponent.setX(escX);
opponent.setY(escY);
animals[escX][escY] = opponent;
removeAnimal(newX,newY);
break;
}
}
if (j == 3){
System.out.println("Brak opcji ucieczki, zwierze ginie");
removeLoserAnimal(opponent);
animals[huntX][huntY] = relocated;
relocated.setX(huntX);
relocated.setY(huntY);
removeAnimal(toX, toY);
System.out.println("Przegral: " + opponent.symbol + " Bo nie mial gdzie uciec");
opponent.setActive(false);
}
}
}
} else if (opponent.getFoodType().equals("meat") && (relocated.symbol != opponent.symbol)) {
Animal loser = relocated.fightLoser(opponent);
if (loser == opponent) {
removeLoserAnimal(opponent);
animals[huntX][huntY] = relocated;
relocated.setX(huntX);
relocated.setY(huntY);
removeAnimal(toX, toY);
opponent.setActive(false);
System.out.println("Przegral: " + opponent.symbol);
} else if (loser == relocated) {
removeLoserAnimal(relocated);
relocated.setActive(false);
System.out.println("Przegral: " + relocated.symbol);
}
}
}
}
}
}
//wilk implementuje metode hunt i stara sie znalezc przeciwnika do ataku, jesli sie nie uda to konczy sie jego tura
if (relocated.symbol.equals("W")) {
int[] arr = ((Wolf) relocated).hunt(relocated.getX(), relocated.getY());
for (int i = 0; i < 8; i++) {
int huntX = arr[i * 2];
int huntY = arr[i * 2 + 1];
if ((huntX < 0 || huntX > Board.getWidth() - 1) || (huntY < 0 || huntY > Board.getHeight() - 1)) {
continue;
} else {
if (isOccupied(huntX, huntY) && !attack) {
attack = true;
System.out.println("W zapolowal: ");
Animal opponent = getAnimal(huntX, huntY);
System.out.println(relocated.symbol+" zaatakowal: "+opponent.symbol);
if (opponent.getFoodType().equals("herbs")) {
Animal loser = relocated.fightLoser(opponent);
if (loser == opponent) {
removeLoserAnimal(opponent);
animals[huntX][huntY] = relocated;
relocated.setX(huntX);
relocated.setY(huntY);
removeAnimal(toX, toY);
opponent.setActive(false);
System.out.println("Przegral: " + opponent.symbol);
} else if (loser == relocated) {
System.out.println("Ucieczka. Przegral: " + relocated.symbol);
int[] esc;
if (opponent.symbol.equals("H")) {
esc = ((Hare) opponent).escape(opponent.getX(), opponent.getY());
} else {
esc = ((RoeDeer) opponent).escape(opponent.getX(), opponent.getY());
}
for (int j = 0; j < 4; j++) {
int escX = esc[j * 2];
int escY = esc[j * 2 + 1];
if ((escX < 0 || escX > Board.getWidth() - 1) || (escY < 0 || escY > Board.getHeight() - 1)) {
continue;
}
else {
if (!isOccupied(escX,escY)){
int newX = opponent.getX();
int newY = opponent.getY();
opponent.setX(escX);
opponent.setY(escY);
animals[escX][escY] = opponent;
removeAnimal(newX,newY);
break;
}
}
if (j == 3){
System.out.println("Brak opcji ucieczki, zwierze ginie");
removeLoserAnimal(opponent);
animals[huntX][huntY] = relocated;
relocated.setX(huntX);
relocated.setY(huntY);
removeAnimal(toX, toY);
System.out.println("Przegral: " + opponent.symbol + " Bo nie mial gdzie uciec");
opponent.setActive(false);
}
}
}
} else if (opponent.getFoodType().equals("meat") && (relocated.symbol != opponent.symbol)) {
Animal loser = relocated.fightLoser(opponent);
if (loser == opponent) {
removeLoserAnimal(opponent);
animals[huntX][huntY] = relocated;
relocated.setX(huntX);
relocated.setY(huntY);
removeAnimal(toX, toY);
opponent.setActive(false);
System.out.println("Przegral: " + opponent.symbol);
} else if (loser == relocated) {
removeLoserAnimal(relocated);
relocated.setActive(false);
System.out.println("Przegral: " + relocated.symbol);
}
} else {
System.out.println("Zrezygnował z polowania bo zobaczyl ze to ten sam gatunek.");
}
}
}
}
}
}
}
/**
metoda sprawdza czy na danym polu planszy znajduje sie inne zwierze niz to ktore sie tam przemiescilo
*/
public boolean isOccupied(int x, int y) {
return animals[x][y] != null;
}
public Animal getAnimal(int x, int y) {
return animals[x][y];
}
public static int getHeight() {
return height;
}
public static int getWidth() {
return width;
}
/**
metoda sprawdzajaca wszystkie wolne pola w okol pola o zadancyh wspolrzednych, jesli uda sie znalezc to
zwraca jego wspolrzedne, jest wykorzystywana
gdy spotka sie 2 roslinozercow lub 2 zwierzeta tego samego gatunku
*/
public int[] findEmptyPosition(Animal animal) {
int newX, newY;
int[] emptyPosition = new int[2];
emptyPosition[0] = animal.getX();
emptyPosition[1] = animal.getY();
for(int i = -1; i <= 1; i++) {
for(int j = -1; j <=1; j++) {
if( i == 0 && j ==0) {
continue;
}
newX = emptyPosition[0] + i;
newY = emptyPosition[1] + j;
if(newX>=Board.getWidth()) {
newX -= Board.getWidth();
} else if(newX < 0) {
newX += Board.getWidth();
}
if(newY>=Board.getHeight()) {
newY -= Board.getHeight();
} else if(newY < 0) {
newY += Board.getHeight();
}
if(!isOccupied(newX, newY)) {
emptyPosition[0] = newX;
emptyPosition[1] = newY;
animal.setX(newX);
animal.setY(newY);
return emptyPosition;
}
}
}
return null;
}
}
|
132413_2 | package Zombie;
import javax.swing.*;
import java.awt.*;
public interface Sprite {
/**
* Rysuje postać
* @param g
* @param parent
*/
void draw(Graphics g, JPanel parent);
/**
* Przechodzi do następnej klatki
*/
void next();
/**
* Czy już zniknął z ekranu
* @return
*/
default boolean isVisble(){return true;}
/**
* Czy punkt o współrzędnych _x, _y leży w obszarze postaci -
* czyli czy trafiliśmy ją strzelając w punkcie o tych współrzednych
* @param _x
* @param _y
* @return
*/
default boolean isHit(int _x,int _y){return false;}
/** Czy jest bliżej widza niż other, czyli w naszym przypadku czy jest większy,
* czyli ma wiekszą skalę...
*
* @param other
* @return
*/
default boolean isCloser(Sprite other){return false;}
}
| yancostrishevsky/Zombie | Zombie/src/Zombie/Sprite.java | 339 | /**
* Czy już zniknął z ekranu
* @return
*/ | block_comment | pl | package Zombie;
import javax.swing.*;
import java.awt.*;
public interface Sprite {
/**
* Rysuje postać
* @param g
* @param parent
*/
void draw(Graphics g, JPanel parent);
/**
* Przechodzi do następnej klatki
*/
void next();
/**
* Czy ju<SUF>*/
default boolean isVisble(){return true;}
/**
* Czy punkt o współrzędnych _x, _y leży w obszarze postaci -
* czyli czy trafiliśmy ją strzelając w punkcie o tych współrzednych
* @param _x
* @param _y
* @return
*/
default boolean isHit(int _x,int _y){return false;}
/** Czy jest bliżej widza niż other, czyli w naszym przypadku czy jest większy,
* czyli ma wiekszą skalę...
*
* @param other
* @return
*/
default boolean isCloser(Sprite other){return false;}
}
|
103547_13 | /* LanguageTool, a natural language style checker
* Copyright (C) 2012 Marcin Miłkowski (http://www.languagetool.org)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.pl;
import org.languagetool.AnalyzedSentence;
import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.Language;
import org.languagetool.UserConfig;
import org.languagetool.rules.*;
import org.languagetool.rules.spelling.morfologik.MorfologikSpellerRule;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
public final class MorfologikPolishSpellerRule extends MorfologikSpellerRule {
private static final String RESOURCE_FILENAME = "/pl/hunspell/pl_PL.dict";
private static final Pattern POLISH_TOKENIZING_CHARS = Pattern.compile("(?:[Qq]uasi|[Nn]iby)-");
/**
* The set of prefixes that are not allowed to be split in the suggestions.
*/
private static final Set<String> prefixes;
//Polish prefixes that should never be used to
//split parts of words
static {
final Set<String> tempSet = new HashSet<>();
tempSet.add("arcy"); tempSet.add("neo");
tempSet.add("pre"); tempSet.add("anty");
tempSet.add("eks"); tempSet.add("bez");
tempSet.add("beze"); tempSet.add("ekstra");
tempSet.add("hiper"); tempSet.add("infra");
tempSet.add("kontr"); tempSet.add("maksi");
tempSet.add("midi"); tempSet.add("między");
tempSet.add("mini"); tempSet.add("nad");
tempSet.add("nade"); tempSet.add("około");
tempSet.add("ponad"); tempSet.add("post");
tempSet.add("pro"); tempSet.add("przeciw");
tempSet.add("pseudo"); tempSet.add("super");
tempSet.add("śród"); tempSet.add("ultra");
tempSet.add("wice"); tempSet.add("wokół");
tempSet.add("wokoło");
prefixes = Collections.unmodifiableSet(tempSet);
}
/**
* non-word suffixes that should not be suggested (only morphological endings, never after a space)
*/
private static final Set<String> bannedSuffixes;
static {
final Set<String> tempSet = new HashSet<>();
tempSet.add("ami");
tempSet.add("ach");
tempSet.add("e");
tempSet.add("ego");
tempSet.add("em");
tempSet.add("emu");
tempSet.add("ie");
tempSet.add("im");
tempSet.add("m");
tempSet.add("om");
tempSet.add("owie");
tempSet.add("owi");
tempSet.add("ze");
bannedSuffixes = Collections.unmodifiableSet(tempSet);
}
private final UserConfig userConfig;
public MorfologikPolishSpellerRule(ResourceBundle messages,
Language language, UserConfig userConfig, List<Language> altLanguages) throws IOException {
super(messages, language, userConfig, altLanguages);
setCategory(Categories.TYPOS.getCategory(messages));
addExamplePair(Example.wrong("To jest zdanie z <marker>bledem</marker>"),
Example.fixed("To jest zdanie z <marker>błędem</marker>."));
this.userConfig = userConfig;
}
@Override
public String getFileName() {
return RESOURCE_FILENAME;
}
@Override
public String getId() {
return "MORFOLOGIK_RULE_PL_PL";
}
@Override
public Pattern tokenizingPattern() {
return POLISH_TOKENIZING_CHARS;
}
@Override
protected List<RuleMatch> getRuleMatches(final String word, final int startPos, AnalyzedSentence sentence, List<RuleMatch> ruleMatchesSoFar)
throws IOException {
final List<RuleMatch> ruleMatches = new ArrayList<>();
if (isMisspelled(speller1, word) && isNotCompound(word)) {
final RuleMatch ruleMatch = new RuleMatch(this, sentence, startPos, startPos
+ word.length(), messages.getString("spelling"),
messages.getString("desc_spelling_short"));
//If lower case word is not a misspelled word, return it as the only suggestion
boolean createSuggestions = userConfig == null || userConfig.getMaxSpellingSuggestions() == 0 || ruleMatchesSoFar.size() <= userConfig.getMaxSpellingSuggestions();
if (!isMisspelled(speller1, word.toLowerCase(conversionLocale))) {
if (createSuggestions) {
List<String> suggestion = Arrays.asList(word.toLowerCase(conversionLocale));
ruleMatch.setSuggestedReplacements(suggestion);
} else {
// limited to save CPU
ruleMatch.setSuggestedReplacement(messages.getString("too_many_errors"));
}
ruleMatches.add(ruleMatch);
return ruleMatches;
}
if (createSuggestions) {
List<String> suggestions = speller1.getSuggestions(word);
suggestions.addAll(0, getAdditionalTopSuggestions(suggestions, word));
suggestions.addAll(getAdditionalSuggestions(suggestions, word));
if (!suggestions.isEmpty()) {
ruleMatch.setSuggestedReplacements(pruneSuggestions(orderSuggestions(suggestions,word)));
}
} else {
// limited to save CPU
ruleMatch.setSuggestedReplacement(messages.getString("too_many_errors"));
}
ruleMatches.add(ruleMatch);
}
return ruleMatches;
}
/**
* Check whether the word is a compound adjective or contains a non-splitting prefix.
* Used to suppress false positives.
*
* @param word Word to be checked.
* @return True if the word is not a compound.
* @since 2.5
*/
private boolean isNotCompound(String word) throws IOException {
List<String> probablyCorrectWords = new ArrayList<>();
List<String> testedTokens = new ArrayList<>(2);
for (int i = 2; i < word.length(); i++) {
// chop from left to right
final String first = word.substring(0, i);
final String second = word.substring(i, word.length());
if (prefixes.contains(first.toLowerCase(conversionLocale))
&& !isMisspelled(speller1, second)
&& second.length() > first.length()) { // but not for short words such as "premoc"
// ignore this match, it's fine
probablyCorrectWords.add(word); // FIXME: some strange words are being accepted, like prekupa
} else {
testedTokens.clear();
testedTokens.add(first);
testedTokens.add(second);
List<AnalyzedTokenReadings> taggedToks =
language.getTagger().tag(testedTokens);
if (taggedToks.size() == 2
// "białozielony", trzynastobitowy
&& (taggedToks.get(0).hasPosTag("adja")
|| (taggedToks.get(0).hasPosTag("num:comp")
&& !taggedToks.get(0).hasPosTag("adv")))
&& taggedToks.get(1).hasPartialPosTag("adj:")) {
probablyCorrectWords.add(word);
}
}
}
if (!probablyCorrectWords.isEmpty()) {
addIgnoreTokens(probablyCorrectWords);
return false;
}
return true;
}
/**
* Remove suggestions -- not really runon words using a list of non-word suffixes
* @return A list of pruned suggestions.
*/
private List<String> pruneSuggestions(final List<String> suggestions) {
List<String> prunedSuggestions = new ArrayList<>(suggestions.size());
for (final String suggestion : suggestions) {
if (suggestion.indexOf(' ') == -1) {
prunedSuggestions.add(suggestion);
} else {
String[] complexSug = suggestion.split(" ");
if (!bannedSuffixes.contains(complexSug[1])) {
prunedSuggestions.add(suggestion);
}
}
}
return prunedSuggestions;
}
}
| yanshengjia/languagetool | languagetool-language-modules/pl/src/main/java/org/languagetool/rules/pl/MorfologikPolishSpellerRule.java | 2,627 | // "białozielony", trzynastobitowy
| line_comment | pl | /* LanguageTool, a natural language style checker
* Copyright (C) 2012 Marcin Miłkowski (http://www.languagetool.org)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.pl;
import org.languagetool.AnalyzedSentence;
import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.Language;
import org.languagetool.UserConfig;
import org.languagetool.rules.*;
import org.languagetool.rules.spelling.morfologik.MorfologikSpellerRule;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
public final class MorfologikPolishSpellerRule extends MorfologikSpellerRule {
private static final String RESOURCE_FILENAME = "/pl/hunspell/pl_PL.dict";
private static final Pattern POLISH_TOKENIZING_CHARS = Pattern.compile("(?:[Qq]uasi|[Nn]iby)-");
/**
* The set of prefixes that are not allowed to be split in the suggestions.
*/
private static final Set<String> prefixes;
//Polish prefixes that should never be used to
//split parts of words
static {
final Set<String> tempSet = new HashSet<>();
tempSet.add("arcy"); tempSet.add("neo");
tempSet.add("pre"); tempSet.add("anty");
tempSet.add("eks"); tempSet.add("bez");
tempSet.add("beze"); tempSet.add("ekstra");
tempSet.add("hiper"); tempSet.add("infra");
tempSet.add("kontr"); tempSet.add("maksi");
tempSet.add("midi"); tempSet.add("między");
tempSet.add("mini"); tempSet.add("nad");
tempSet.add("nade"); tempSet.add("około");
tempSet.add("ponad"); tempSet.add("post");
tempSet.add("pro"); tempSet.add("przeciw");
tempSet.add("pseudo"); tempSet.add("super");
tempSet.add("śród"); tempSet.add("ultra");
tempSet.add("wice"); tempSet.add("wokół");
tempSet.add("wokoło");
prefixes = Collections.unmodifiableSet(tempSet);
}
/**
* non-word suffixes that should not be suggested (only morphological endings, never after a space)
*/
private static final Set<String> bannedSuffixes;
static {
final Set<String> tempSet = new HashSet<>();
tempSet.add("ami");
tempSet.add("ach");
tempSet.add("e");
tempSet.add("ego");
tempSet.add("em");
tempSet.add("emu");
tempSet.add("ie");
tempSet.add("im");
tempSet.add("m");
tempSet.add("om");
tempSet.add("owie");
tempSet.add("owi");
tempSet.add("ze");
bannedSuffixes = Collections.unmodifiableSet(tempSet);
}
private final UserConfig userConfig;
public MorfologikPolishSpellerRule(ResourceBundle messages,
Language language, UserConfig userConfig, List<Language> altLanguages) throws IOException {
super(messages, language, userConfig, altLanguages);
setCategory(Categories.TYPOS.getCategory(messages));
addExamplePair(Example.wrong("To jest zdanie z <marker>bledem</marker>"),
Example.fixed("To jest zdanie z <marker>błędem</marker>."));
this.userConfig = userConfig;
}
@Override
public String getFileName() {
return RESOURCE_FILENAME;
}
@Override
public String getId() {
return "MORFOLOGIK_RULE_PL_PL";
}
@Override
public Pattern tokenizingPattern() {
return POLISH_TOKENIZING_CHARS;
}
@Override
protected List<RuleMatch> getRuleMatches(final String word, final int startPos, AnalyzedSentence sentence, List<RuleMatch> ruleMatchesSoFar)
throws IOException {
final List<RuleMatch> ruleMatches = new ArrayList<>();
if (isMisspelled(speller1, word) && isNotCompound(word)) {
final RuleMatch ruleMatch = new RuleMatch(this, sentence, startPos, startPos
+ word.length(), messages.getString("spelling"),
messages.getString("desc_spelling_short"));
//If lower case word is not a misspelled word, return it as the only suggestion
boolean createSuggestions = userConfig == null || userConfig.getMaxSpellingSuggestions() == 0 || ruleMatchesSoFar.size() <= userConfig.getMaxSpellingSuggestions();
if (!isMisspelled(speller1, word.toLowerCase(conversionLocale))) {
if (createSuggestions) {
List<String> suggestion = Arrays.asList(word.toLowerCase(conversionLocale));
ruleMatch.setSuggestedReplacements(suggestion);
} else {
// limited to save CPU
ruleMatch.setSuggestedReplacement(messages.getString("too_many_errors"));
}
ruleMatches.add(ruleMatch);
return ruleMatches;
}
if (createSuggestions) {
List<String> suggestions = speller1.getSuggestions(word);
suggestions.addAll(0, getAdditionalTopSuggestions(suggestions, word));
suggestions.addAll(getAdditionalSuggestions(suggestions, word));
if (!suggestions.isEmpty()) {
ruleMatch.setSuggestedReplacements(pruneSuggestions(orderSuggestions(suggestions,word)));
}
} else {
// limited to save CPU
ruleMatch.setSuggestedReplacement(messages.getString("too_many_errors"));
}
ruleMatches.add(ruleMatch);
}
return ruleMatches;
}
/**
* Check whether the word is a compound adjective or contains a non-splitting prefix.
* Used to suppress false positives.
*
* @param word Word to be checked.
* @return True if the word is not a compound.
* @since 2.5
*/
private boolean isNotCompound(String word) throws IOException {
List<String> probablyCorrectWords = new ArrayList<>();
List<String> testedTokens = new ArrayList<>(2);
for (int i = 2; i < word.length(); i++) {
// chop from left to right
final String first = word.substring(0, i);
final String second = word.substring(i, word.length());
if (prefixes.contains(first.toLowerCase(conversionLocale))
&& !isMisspelled(speller1, second)
&& second.length() > first.length()) { // but not for short words such as "premoc"
// ignore this match, it's fine
probablyCorrectWords.add(word); // FIXME: some strange words are being accepted, like prekupa
} else {
testedTokens.clear();
testedTokens.add(first);
testedTokens.add(second);
List<AnalyzedTokenReadings> taggedToks =
language.getTagger().tag(testedTokens);
if (taggedToks.size() == 2
// "biał<SUF>
&& (taggedToks.get(0).hasPosTag("adja")
|| (taggedToks.get(0).hasPosTag("num:comp")
&& !taggedToks.get(0).hasPosTag("adv")))
&& taggedToks.get(1).hasPartialPosTag("adj:")) {
probablyCorrectWords.add(word);
}
}
}
if (!probablyCorrectWords.isEmpty()) {
addIgnoreTokens(probablyCorrectWords);
return false;
}
return true;
}
/**
* Remove suggestions -- not really runon words using a list of non-word suffixes
* @return A list of pruned suggestions.
*/
private List<String> pruneSuggestions(final List<String> suggestions) {
List<String> prunedSuggestions = new ArrayList<>(suggestions.size());
for (final String suggestion : suggestions) {
if (suggestion.indexOf(' ') == -1) {
prunedSuggestions.add(suggestion);
} else {
String[] complexSug = suggestion.split(" ");
if (!bannedSuffixes.contains(complexSug[1])) {
prunedSuggestions.add(suggestion);
}
}
}
return prunedSuggestions;
}
}
|
72478_3 | package fotopolska.uploader;
import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Foto implements Serializable {
Document doc;
String number;
String uploader;
String city;
String image;
String name;
String desc;
String location;
String date;
String source;
String author;
String authorLink;
String coord;
String license;
String extra;
public Foto(String number) throws IOException {
this.doc = Jsoup.connect("http://fotopolska.eu/" + number + ",foto.html").get();
this.number = number;
this.uploader = setUploader();
this.desc = setDesc();
this.location = setLocation();
this.date = setDate();
this.author = setAuthor();
this.authorLink = setAuthorLink();
this.coord = setCoord();
this.license = setLicense();
this.image = setImage();
this.name = setName();
}
/**
* SET
*/
private String setImage() {
Elements e = doc.select("#FotoLoader img");
if(!e.isEmpty())
return "http://fotopolska.eu" + e.get(0).attr("src");
else
return "??";
}
private String setName() {
Elements e = doc.getElementsByTag("title");
String text = "??";
if(!e.isEmpty()) {
if(!e.text().equals("fotopolska.eu - Polska na fotografii"))
text = e.text().replaceAll("<[uib]>", "").replaceAll("</[uib]", "").replace("<br>", "") + " (" + number + ")";
else {
if(city!=null)
text = city + " - fotopolska.eu (" + number + ")";
else {
text = "fotopolska.eu (" + number + ")";
city = "?";
}
}
}
return text + ".jpg";
}
private String setDesc() {
Element e = doc.select("#ed_fn" + number).get(0);
return e.text();
}
private String setLocation() {
Elements e = doc.select("table td.sz7 b");
if(e!=null && e.text().length()>0) {
String text = "|other_fields_1 = {{Building address\n |Street name = \n |House number = \n |House name = \n |Postal code = \n |City = \n" +
" |Powiat = \n |State = \n |Country = PL\n |Listing = \n}}\n";
String[] texts = e.get(0).text().split(" / ");
if(texts.length> 1) {
if(!texts[1].contains("kolejowe")) {
//województwo
Map voiv = new HashMap<>();
voiv.put("dolnośląskie", "DS");
voiv.put("kujawsko-pomorskie","KP");
voiv.put("lubelskie","LU");
voiv.put("lubuskie","LB");
voiv.put("łódzkie","LD");
voiv.put("małopolskie","MA");
voiv.put("mazowieckie","MZ");
voiv.put("opolskie","OP");
voiv.put("podkarpackie","PK");
voiv.put("podlaskie","PD");
voiv.put("pomorskie","PM");
voiv.put("śląskie","SL");
voiv.put("świętokrzyskie","SK");
voiv.put("warmińsko-mazurskie","WN");
voiv.put("wielkopolskie","WP");
voiv.put("zachodniopomorskie","ZP");
text = text.replace("|State = ", "|State = " + voiv.get(texts[1].substring(5)));
//miasto
if(texts[2].contains("Powiat")) {
text = text.replace("|Powiat = ", "|Powiat = " + texts[2]);
text = text.replace("|City = ", "|City = " + texts[3]);
city = texts[3];
}
else {
if(!texts[3].contains("ul.")) text = text.replace("|City = ", "|City = " + texts[2] + " (" + texts[3] + ")");
else text = text.replace("|City = ", "|City = " + texts[2]);
city = texts[2];
}
for(int i=3; i<texts.length; ++i) {
if(texts[i].contains("ul. ") || texts[i].contains("Plac")) {
String street = texts[i];
if(street.contains("ul. ")) street = street.substring(4);
//numer
if(street.contains(" ")) {
String nr = street.substring(street.lastIndexOf(" ")+1);
if(nr.matches("[0-9-]{1,10}")) {
street = street.replace(nr, "");
text = text.replace("|House number = ", "|House number = " + nr);
text = text.replace("|Street name = ", "|Street name = " + street);
} else
text = text.replace("|Street name = ", "|Street name = " + street);
//nie ma numeru
} else {
text = text.replace("|Street name = ", "|Street name = " + street);
}
break;
}
}
return text;
}
}
return "";
} else
return "";
}
private String setDate() {
String text = "?";
//exif
if(!doc.select("div#exif").isEmpty()) {
Element e = doc.select("div#exif").get(0);
text = e.text().replaceAll(".*([0-9]{4}:[0-9]{2}:[0-9]{2}).*", "$1").replace(":", "-");
//text
} else {
String[] month = {"styczeń", "luty", "marzec", "kwiecień", "maj", "czerwiec", "lipiec", "sierpień", "wrzesień", "październik", "listopad", "grudzień"};
Element e = doc.select(".sz7b").get(0);
text = e.text();
for(int i=0; i<month.length; ++i) {
if(text.contains(month[i])) {
String nr = i+1+"";
if(i<10) nr = "0"+nr;
text = text.replace(month[i],nr).replace(" ", "-");
break;
}
}
text = text.replaceAll("^([0-9]{4})-([0-9]{2})-([0-9])$", "$1-$2-0$3");
if(text.contains("Zdjęcie z lat"))
text = text.replace("Zdjęcie z lat ", "");
if(text.contains("Zdjęcie z roku"))
text = text.replace("Zdjęcie z roku ", "");
}
return text;
}
private String setAuthor() {
Element e = doc.select(".zoltemale").get(0);
return e.text().replace("*", "").replace("+", "")/*.substring(0, e.text().length()-1)*/;
}
private String setUploader() {
Elements e = doc.select("#adm");
if(!e.isEmpty())
return e.get(0).text();
else {
e = doc.select("#reg");
if(!e.isEmpty())
return e.get(0).text().replace("*", "");
else
return "???";
}
}
private String setAuthorLink() {
Element e = doc.select(".zoltemale").get(0);
String s = e.attr("href");
if(s.contains("zrodlo=261&") || s.contains("zrodlo=12&") || s.contains("zrodlo=61&"))
return "Wikimedia Commons";
else
return "http://fotopolska.eu" + e.attr("href");
}
private String setCoord() {
Element e = doc.getElementsByTag("script").get(4);
String text = e.html();
text = text.substring(234, 270).replace(", ", "|");
if(text.matches("[0-9\\.\\|]*"))
return "{{Object location dec|" + text + "}}\n";
else
return "";
}
private String setLicense() {
Elements e = doc.select("table.fopis div.sz7 a");
if(!e.isEmpty()) {
String s = e.get(0).text();
if(s.equals("Public Domain")) s = "PD-author";
if(s.contains("CC-BY-SA")) s = s.replaceAll("CC-BY-SA ([0-9\\.]{1,3})", "cc-by-sa-$1");
return "{{" + s + "|[" + authorLink + " " + author + " / fotopolska.eu]}}\n";
} else
return "??";
}
/*
* OTHER
*/
public boolean isUploadable() {
if(authorLink.equals("Wikimedia Commons") || license.equals("??") || image.equals("??") || author.contains("Nemo5576"))
return false;
else
return true;
}
public String getFileName() {
return name;
}
public URL getFileSource() throws MalformedURLException {
return new URL(image);
}
public String getWikiText() {
String text = "=={{int:filedesc}}==\n{{Information\n" +
"|description = {{pl|1=" + desc + "}}\n" + location +
"|date = " + date + "\n" +
"|source = [http://fotopolska.eu/" + number + ",foto.html Fotopolska.eu]" + "\n" +
"|author = [" + authorLink + " " + author + "]\n" +
"|permission = \n" +
"|other_versions = \n" +
"|other_fields = \n" +
"}}\n" +
coord + "{{Watermark}}\n" +
"\n=={{int:license-header}}==\n" + license + "{{Fotopolska review|Yarl|" + Main.tDate.getText() + "}}\n\n[[Category:" + city + "]]";
return text;
}
@Override
public String toString() {
String text = image + "\n" + "File:" + name + "\n" + getWikiText() + "\n\n";
return text;
}
}
| yarl/fotopolska-uploader | src/fotopolska/uploader/Foto.java | 3,139 | //województwo
| line_comment | pl | package fotopolska.uploader;
import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Foto implements Serializable {
Document doc;
String number;
String uploader;
String city;
String image;
String name;
String desc;
String location;
String date;
String source;
String author;
String authorLink;
String coord;
String license;
String extra;
public Foto(String number) throws IOException {
this.doc = Jsoup.connect("http://fotopolska.eu/" + number + ",foto.html").get();
this.number = number;
this.uploader = setUploader();
this.desc = setDesc();
this.location = setLocation();
this.date = setDate();
this.author = setAuthor();
this.authorLink = setAuthorLink();
this.coord = setCoord();
this.license = setLicense();
this.image = setImage();
this.name = setName();
}
/**
* SET
*/
private String setImage() {
Elements e = doc.select("#FotoLoader img");
if(!e.isEmpty())
return "http://fotopolska.eu" + e.get(0).attr("src");
else
return "??";
}
private String setName() {
Elements e = doc.getElementsByTag("title");
String text = "??";
if(!e.isEmpty()) {
if(!e.text().equals("fotopolska.eu - Polska na fotografii"))
text = e.text().replaceAll("<[uib]>", "").replaceAll("</[uib]", "").replace("<br>", "") + " (" + number + ")";
else {
if(city!=null)
text = city + " - fotopolska.eu (" + number + ")";
else {
text = "fotopolska.eu (" + number + ")";
city = "?";
}
}
}
return text + ".jpg";
}
private String setDesc() {
Element e = doc.select("#ed_fn" + number).get(0);
return e.text();
}
private String setLocation() {
Elements e = doc.select("table td.sz7 b");
if(e!=null && e.text().length()>0) {
String text = "|other_fields_1 = {{Building address\n |Street name = \n |House number = \n |House name = \n |Postal code = \n |City = \n" +
" |Powiat = \n |State = \n |Country = PL\n |Listing = \n}}\n";
String[] texts = e.get(0).text().split(" / ");
if(texts.length> 1) {
if(!texts[1].contains("kolejowe")) {
//wojew<SUF>
Map voiv = new HashMap<>();
voiv.put("dolnośląskie", "DS");
voiv.put("kujawsko-pomorskie","KP");
voiv.put("lubelskie","LU");
voiv.put("lubuskie","LB");
voiv.put("łódzkie","LD");
voiv.put("małopolskie","MA");
voiv.put("mazowieckie","MZ");
voiv.put("opolskie","OP");
voiv.put("podkarpackie","PK");
voiv.put("podlaskie","PD");
voiv.put("pomorskie","PM");
voiv.put("śląskie","SL");
voiv.put("świętokrzyskie","SK");
voiv.put("warmińsko-mazurskie","WN");
voiv.put("wielkopolskie","WP");
voiv.put("zachodniopomorskie","ZP");
text = text.replace("|State = ", "|State = " + voiv.get(texts[1].substring(5)));
//miasto
if(texts[2].contains("Powiat")) {
text = text.replace("|Powiat = ", "|Powiat = " + texts[2]);
text = text.replace("|City = ", "|City = " + texts[3]);
city = texts[3];
}
else {
if(!texts[3].contains("ul.")) text = text.replace("|City = ", "|City = " + texts[2] + " (" + texts[3] + ")");
else text = text.replace("|City = ", "|City = " + texts[2]);
city = texts[2];
}
for(int i=3; i<texts.length; ++i) {
if(texts[i].contains("ul. ") || texts[i].contains("Plac")) {
String street = texts[i];
if(street.contains("ul. ")) street = street.substring(4);
//numer
if(street.contains(" ")) {
String nr = street.substring(street.lastIndexOf(" ")+1);
if(nr.matches("[0-9-]{1,10}")) {
street = street.replace(nr, "");
text = text.replace("|House number = ", "|House number = " + nr);
text = text.replace("|Street name = ", "|Street name = " + street);
} else
text = text.replace("|Street name = ", "|Street name = " + street);
//nie ma numeru
} else {
text = text.replace("|Street name = ", "|Street name = " + street);
}
break;
}
}
return text;
}
}
return "";
} else
return "";
}
private String setDate() {
String text = "?";
//exif
if(!doc.select("div#exif").isEmpty()) {
Element e = doc.select("div#exif").get(0);
text = e.text().replaceAll(".*([0-9]{4}:[0-9]{2}:[0-9]{2}).*", "$1").replace(":", "-");
//text
} else {
String[] month = {"styczeń", "luty", "marzec", "kwiecień", "maj", "czerwiec", "lipiec", "sierpień", "wrzesień", "październik", "listopad", "grudzień"};
Element e = doc.select(".sz7b").get(0);
text = e.text();
for(int i=0; i<month.length; ++i) {
if(text.contains(month[i])) {
String nr = i+1+"";
if(i<10) nr = "0"+nr;
text = text.replace(month[i],nr).replace(" ", "-");
break;
}
}
text = text.replaceAll("^([0-9]{4})-([0-9]{2})-([0-9])$", "$1-$2-0$3");
if(text.contains("Zdjęcie z lat"))
text = text.replace("Zdjęcie z lat ", "");
if(text.contains("Zdjęcie z roku"))
text = text.replace("Zdjęcie z roku ", "");
}
return text;
}
private String setAuthor() {
Element e = doc.select(".zoltemale").get(0);
return e.text().replace("*", "").replace("+", "")/*.substring(0, e.text().length()-1)*/;
}
private String setUploader() {
Elements e = doc.select("#adm");
if(!e.isEmpty())
return e.get(0).text();
else {
e = doc.select("#reg");
if(!e.isEmpty())
return e.get(0).text().replace("*", "");
else
return "???";
}
}
private String setAuthorLink() {
Element e = doc.select(".zoltemale").get(0);
String s = e.attr("href");
if(s.contains("zrodlo=261&") || s.contains("zrodlo=12&") || s.contains("zrodlo=61&"))
return "Wikimedia Commons";
else
return "http://fotopolska.eu" + e.attr("href");
}
private String setCoord() {
Element e = doc.getElementsByTag("script").get(4);
String text = e.html();
text = text.substring(234, 270).replace(", ", "|");
if(text.matches("[0-9\\.\\|]*"))
return "{{Object location dec|" + text + "}}\n";
else
return "";
}
private String setLicense() {
Elements e = doc.select("table.fopis div.sz7 a");
if(!e.isEmpty()) {
String s = e.get(0).text();
if(s.equals("Public Domain")) s = "PD-author";
if(s.contains("CC-BY-SA")) s = s.replaceAll("CC-BY-SA ([0-9\\.]{1,3})", "cc-by-sa-$1");
return "{{" + s + "|[" + authorLink + " " + author + " / fotopolska.eu]}}\n";
} else
return "??";
}
/*
* OTHER
*/
public boolean isUploadable() {
if(authorLink.equals("Wikimedia Commons") || license.equals("??") || image.equals("??") || author.contains("Nemo5576"))
return false;
else
return true;
}
public String getFileName() {
return name;
}
public URL getFileSource() throws MalformedURLException {
return new URL(image);
}
public String getWikiText() {
String text = "=={{int:filedesc}}==\n{{Information\n" +
"|description = {{pl|1=" + desc + "}}\n" + location +
"|date = " + date + "\n" +
"|source = [http://fotopolska.eu/" + number + ",foto.html Fotopolska.eu]" + "\n" +
"|author = [" + authorLink + " " + author + "]\n" +
"|permission = \n" +
"|other_versions = \n" +
"|other_fields = \n" +
"}}\n" +
coord + "{{Watermark}}\n" +
"\n=={{int:license-header}}==\n" + license + "{{Fotopolska review|Yarl|" + Main.tDate.getText() + "}}\n\n[[Category:" + city + "]]";
return text;
}
@Override
public String toString() {
String text = image + "\n" + "File:" + name + "\n" + getWikiText() + "\n\n";
return text;
}
}
|
72525_2 | package pl.wikizabytki.classes;
import java.util.ArrayList;
/**
*
* @author Pawel
*/
public class Monument {
public int id;
public String name;
public String number; //aktualny numer rejestru
public String gmina;
public String town;
public String street;
public Material material;
public String year;
//group of monuments (zespół zabytków)
public int partOf = -1;
public ArrayList<Monument> parts = new ArrayList<>();
public String hint; //określnie zespołu, np. 'przy dworcu kolejowym'
public Monument(int id, String name, String number, String gmina, String town) {
this.id = id;
this.name = name;
this.number = number;
this.gmina = gmina;
this.town = town;
}
public Monument(String id, String name, String number, String gmina, String town, String street, int partOf, String hint, String year) {
this.id = Integer.parseInt(id);
this.name = name;
this.number = number;
this.gmina = gmina;
this.town = town;
this.street = street;
this.partOf = partOf;
this.hint = hint;
this.year = year;
}
/**
* Checks if monument in parameter is part of this monument complex
* @param m
* @return
*/
public boolean isPart(Monument m) {
//if "parent" is not complex
if(m.partOf == 1) return false;
//first monument after complex should be in this complex
if(m.parts.isEmpty()) return true;
//match of register number
if(!number.isEmpty() && m.number.equals(number)) return true;
//hint contains text "part of"
if(hint.contains("w zespole")) return true;
//
if(!m.parts.isEmpty()
&& m.parts.get(0).name.contains("kościół")
&& hint.contains("przy "))
return true;
//match of streets
if(!street.isEmpty() && m.street.equals(street)) return true;
return false;
}
public void addPart(Monument m) {
parts.add(m);
}
public void setStreet(String street) {
this.street = street;
}
public void setMaterial(String material) {
switch(material) {
case "mur.": this.material = Material.MUR; break;
case "drewn.": this.material = Material.DRE; break;
case "szach.": this.material = Material.SZACH; break;
case "met.": this.material = Material.MET; break;
case "mur.-drewn.": this.material = Material.MUR_DRE; break;
case "mur.-met.": this.material = Material.MUR_MET; break;
}
};
public String getWikiCode(int n){
String text = "{{zabytki/wpis\n";
text += "| numer = " + number + " | id = " + id + "\n";
text += "| zespół zabytków = ";
if(n>0) text += n + "\n";
else if(partOf == 0) text += "tak\n";
else if(partOf == 1) text += "nie\n";
else text += "??";
text += "| nazwa = " + name;
if(!year.isEmpty()) text += ", " + year;
if(!hint.isEmpty() && n == -1) text += " <small>(" + hint + ")</small>";
if(partOf == 0 && parts.isEmpty()) text += " <font color=red>'''brak zabytków w zespole'''</font>";
text += "\n";
text += "| miejscowość = " + town + "\n";
text += "| adres = " + street + "\n";
text += "| długość = | szerokość = \n";
text += "| zdjęcie = \n";
text += "| commons = \n";
text += "}}\n";
if(partOf == 0){
text += "{{zabytki/zespół zabytków/góra}}\n";
for(Monument m : parts) text += m.getWikiCode(id);
text += "{{zabytki/zespół zabytków/dół}}\n";
}
return text;
}
}
| yarl/wikizabytki-importer | src/pl/wikizabytki/classes/Monument.java | 1,265 | //group of monuments (zespół zabytków)
| line_comment | pl | package pl.wikizabytki.classes;
import java.util.ArrayList;
/**
*
* @author Pawel
*/
public class Monument {
public int id;
public String name;
public String number; //aktualny numer rejestru
public String gmina;
public String town;
public String street;
public Material material;
public String year;
//group<SUF>
public int partOf = -1;
public ArrayList<Monument> parts = new ArrayList<>();
public String hint; //określnie zespołu, np. 'przy dworcu kolejowym'
public Monument(int id, String name, String number, String gmina, String town) {
this.id = id;
this.name = name;
this.number = number;
this.gmina = gmina;
this.town = town;
}
public Monument(String id, String name, String number, String gmina, String town, String street, int partOf, String hint, String year) {
this.id = Integer.parseInt(id);
this.name = name;
this.number = number;
this.gmina = gmina;
this.town = town;
this.street = street;
this.partOf = partOf;
this.hint = hint;
this.year = year;
}
/**
* Checks if monument in parameter is part of this monument complex
* @param m
* @return
*/
public boolean isPart(Monument m) {
//if "parent" is not complex
if(m.partOf == 1) return false;
//first monument after complex should be in this complex
if(m.parts.isEmpty()) return true;
//match of register number
if(!number.isEmpty() && m.number.equals(number)) return true;
//hint contains text "part of"
if(hint.contains("w zespole")) return true;
//
if(!m.parts.isEmpty()
&& m.parts.get(0).name.contains("kościół")
&& hint.contains("przy "))
return true;
//match of streets
if(!street.isEmpty() && m.street.equals(street)) return true;
return false;
}
public void addPart(Monument m) {
parts.add(m);
}
public void setStreet(String street) {
this.street = street;
}
public void setMaterial(String material) {
switch(material) {
case "mur.": this.material = Material.MUR; break;
case "drewn.": this.material = Material.DRE; break;
case "szach.": this.material = Material.SZACH; break;
case "met.": this.material = Material.MET; break;
case "mur.-drewn.": this.material = Material.MUR_DRE; break;
case "mur.-met.": this.material = Material.MUR_MET; break;
}
};
public String getWikiCode(int n){
String text = "{{zabytki/wpis\n";
text += "| numer = " + number + " | id = " + id + "\n";
text += "| zespół zabytków = ";
if(n>0) text += n + "\n";
else if(partOf == 0) text += "tak\n";
else if(partOf == 1) text += "nie\n";
else text += "??";
text += "| nazwa = " + name;
if(!year.isEmpty()) text += ", " + year;
if(!hint.isEmpty() && n == -1) text += " <small>(" + hint + ")</small>";
if(partOf == 0 && parts.isEmpty()) text += " <font color=red>'''brak zabytków w zespole'''</font>";
text += "\n";
text += "| miejscowość = " + town + "\n";
text += "| adres = " + street + "\n";
text += "| długość = | szerokość = \n";
text += "| zdjęcie = \n";
text += "| commons = \n";
text += "}}\n";
if(partOf == 0){
text += "{{zabytki/zespół zabytków/góra}}\n";
for(Monument m : parts) text += m.getWikiCode(id);
text += "{{zabytki/zespół zabytków/dół}}\n";
}
return text;
}
}
|
40063_1 | package koordynator;
import java.util.regex.Pattern;
/**
*
* @author Pawel
*/
public class Wiersz {
String wiersz;
boolean koordynaty, zdjecie, commons;
public Wiersz(String s) {
wiersz = s;
Pattern p,q;
p = Pattern.compile("koordynaty");
q = Pattern.compile("szerokość");
koordynaty = (p.matcher(wiersz).find() || q.matcher(wiersz).find()) ? true : false;
if(koordynaty) {
p = Pattern.compile("koordynaty *= *\n");
q = Pattern.compile("szerokość *= *\n");
koordynaty = (p.matcher(wiersz).find() || q.matcher(wiersz).find()) ? false : true;
} else {
/*
* Wstawianie wierszy koordów, skoro nie ma...
*/
wiersz = wiersz.replaceAll(" *\\| *zdjęcie", "| szerokość = \n| długość =\n| zdjęcie");
}
// p = Pattern.compile("koordynaty *= *\n");
// q = Pattern.compile("szerokość *= *\n");
// koordynaty = (p.matcher(wiersz).find() || q.matcher(wiersz).find()) ? false : true;
// if(koordynaty) {
// p = Pattern.compile("koordynaty");
// koordynaty = (p.matcher(wiersz).find()) ? true : false;
// }
p = Pattern.compile("zdjęcie *= *\n");
zdjecie = (p.matcher(wiersz).find()) ? false : true;
if(zdjecie) {
p = Pattern.compile("zdjęcie");
zdjecie = (p.matcher(wiersz).find()) ? true : false;
}
p = Pattern.compile("commons *= *\n");
commons = (p.matcher(wiersz).find()) ? false : true;
if(commons) {
p = Pattern.compile("commons");
commons = (p.matcher(wiersz).find()) ? true : false;
}
}
/*
*
*/
public boolean jestKoordynaty() {
return koordynaty;
}
public boolean jestZdjecie() {
return zdjecie;
}
public boolean jestCommons() {
return commons;
}
/*
*
*/
public String zwrocWiersz() {
return wiersz;
}
public String zwrocCommons() {
String temp[] = wiersz.split("\n");
for(String i : temp) {
if(i.contains("commons")) {
i = i.replaceAll(" *\\| *commons *= *", "");
return i;
}
}
return "";
}
public String zwrocZdjecie() {
String temp[] = wiersz.split("\n");
for(String i : temp) {
if(i.contains("zdjęcie")) {
i = i.replaceAll(" *\\| *zdjęcie *= *", "");
return i;
}
}
return "";
}
/*
*
*/
public void zapiszKoordynaty(float N, float E) throws Exception {
if(wiersz.contains("koordynaty")) {
wiersz = wiersz.replaceAll(" *\\| *koordynaty *= *", "| szerokość = " + N + "\n| długość = " + E);
} else if(wiersz.contains("szerokość") && wiersz.contains("długość")) {
wiersz = wiersz.replaceAll(" *\\| *szerokość *= *", "| szerokość = " + N);
wiersz = wiersz.replaceAll(" *\\| *długość *= *", "| długość = " + N);
} else
throw new Exception("Brak parametru w szablonie");
}
}
| yarl/wikizabytki-koordynator | src/koordynator/Wiersz.java | 1,160 | /*
* Wstawianie wierszy koordów, skoro nie ma...
*/ | block_comment | pl | package koordynator;
import java.util.regex.Pattern;
/**
*
* @author Pawel
*/
public class Wiersz {
String wiersz;
boolean koordynaty, zdjecie, commons;
public Wiersz(String s) {
wiersz = s;
Pattern p,q;
p = Pattern.compile("koordynaty");
q = Pattern.compile("szerokość");
koordynaty = (p.matcher(wiersz).find() || q.matcher(wiersz).find()) ? true : false;
if(koordynaty) {
p = Pattern.compile("koordynaty *= *\n");
q = Pattern.compile("szerokość *= *\n");
koordynaty = (p.matcher(wiersz).find() || q.matcher(wiersz).find()) ? false : true;
} else {
/*
* Wstawi<SUF>*/
wiersz = wiersz.replaceAll(" *\\| *zdjęcie", "| szerokość = \n| długość =\n| zdjęcie");
}
// p = Pattern.compile("koordynaty *= *\n");
// q = Pattern.compile("szerokość *= *\n");
// koordynaty = (p.matcher(wiersz).find() || q.matcher(wiersz).find()) ? false : true;
// if(koordynaty) {
// p = Pattern.compile("koordynaty");
// koordynaty = (p.matcher(wiersz).find()) ? true : false;
// }
p = Pattern.compile("zdjęcie *= *\n");
zdjecie = (p.matcher(wiersz).find()) ? false : true;
if(zdjecie) {
p = Pattern.compile("zdjęcie");
zdjecie = (p.matcher(wiersz).find()) ? true : false;
}
p = Pattern.compile("commons *= *\n");
commons = (p.matcher(wiersz).find()) ? false : true;
if(commons) {
p = Pattern.compile("commons");
commons = (p.matcher(wiersz).find()) ? true : false;
}
}
/*
*
*/
public boolean jestKoordynaty() {
return koordynaty;
}
public boolean jestZdjecie() {
return zdjecie;
}
public boolean jestCommons() {
return commons;
}
/*
*
*/
public String zwrocWiersz() {
return wiersz;
}
public String zwrocCommons() {
String temp[] = wiersz.split("\n");
for(String i : temp) {
if(i.contains("commons")) {
i = i.replaceAll(" *\\| *commons *= *", "");
return i;
}
}
return "";
}
public String zwrocZdjecie() {
String temp[] = wiersz.split("\n");
for(String i : temp) {
if(i.contains("zdjęcie")) {
i = i.replaceAll(" *\\| *zdjęcie *= *", "");
return i;
}
}
return "";
}
/*
*
*/
public void zapiszKoordynaty(float N, float E) throws Exception {
if(wiersz.contains("koordynaty")) {
wiersz = wiersz.replaceAll(" *\\| *koordynaty *= *", "| szerokość = " + N + "\n| długość = " + E);
} else if(wiersz.contains("szerokość") && wiersz.contains("długość")) {
wiersz = wiersz.replaceAll(" *\\| *szerokość *= *", "| szerokość = " + N);
wiersz = wiersz.replaceAll(" *\\| *długość *= *", "| długość = " + N);
} else
throw new Exception("Brak parametru w szablonie");
}
}
|
17249_25 | /*
* Copyright (c) 2022 Eben Howard, Tommy Ettinger, and contributors
*
* 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 squidpony;
import regexodus.Category;
import squidpony.squidmath.GWTRNG;
import squidpony.squidmath.IStatefulRNG;
import squidpony.squidmath.ProbabilityTable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
/**
* Based on work by Nolithius available at the following two sites
* https://github.com/Nolithius/weighted-letter-namegen
* http://code.google.com/p/weighted-letter-namegen/
*
* @see FakeLanguageGen FakeLanguageGen is meant for generating more than just names, and can imitate language styles.
* @author Eben Howard - http://squidpony.com - howard@squidpony.com
*/
public class WeightedLetterNamegen {
//<editor-fold defaultstate="collapsed" desc="Viking Style static name list">
public static final String[] VIKING_STYLE_NAMES = new String[]{
"Andor",
"Baatar",
"Beowulf",
"Drogo",
"Freya",
"Grog",
"Gruumsh",
"Grunt",
"Hodor",
"Hrothgar",
"Hrun",
"Korg",
"Lothar",
"Odin",
"Theodrin",
"Thor",
"Yngvar",
"Xandor"
};
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Star Wars Style static name list">
public static final String[] STAR_WARS_STYLE_NAMES = new String[]{
"Lutoif Vap",
"Nasoi Seert",
"Jitpai",
"Sose",
"Vainau",
"Jairkau",
"Tirka Kist",
"Boush",
"Wofe",
"Voxin Voges",
"Koux Boiti",
"Loim",
"Gaungu",
"Mut Tep",
"Foimo Saispi",
"Toneeg Vaiba",
"Nix Nast",
"Gup Dangisp",
"Distark Toonausp",
"Tex Brinki",
"Kat Tosha",
"Tauna Foip",
"Frip Cex",
"Fexa Lun",
"Tafa",
"Zeesheerk",
"Cremoim Kixoop",
"Tago",
"Kesha Diplo"
};
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="USA male names static name list">
public static final String[] COMMON_USA_MALE_NAMES = new String[]{
"James",
"John",
"Robert",
"Michael",
"William",
"David",
"Richard",
"Charles",
"Joseph",
"Tomas",
"Christopher",
"Daniel",
"Paul",
"Mark",
"Donald",
"George",
"Kenneth",
"Steven",
"Edward",
"Brian",
"Ronald",
"Anthony",
"Kevin",
"Jason",
"Matthew",
"Gary",
"Timothy",
"Jose",
"Larry",
"Jeffrey",
"Frank",
"Scott",
"Eric",
"Stephen",
"Andrew",
"Raymond",
"Gregory",
"Joshua",
"Jerry",
"Dennis",
"Walter",
"Patrick",
"Peter",
"Harold",
"Douglas",
"Henry",
"Carl",
"Arthur",
"Ryan",
"Roger"
};
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="USA female names static name list">
public static final String[] COMMON_USA_FEMALE_NAMES = new String[]{
"Mary",
"Patricia",
"Linda",
"Barbara",
"Elizabeth",
"Jennifer",
"Maria",
"Susan",
"Margaret",
"Dorothy",
"Lisa",
"Nancy",
"Karen",
"Betty",
"Helen",
"Sandra",
"Donna",
"Carol",
"Ruth",
"Sharon",
"Michelle",
"Laura",
"Sarah",
"Kimberly",
"Deborah",
"Jessica",
"Shirley",
"Cynthia",
"Angela",
"Melissa",
"Brenda",
"Amy",
"Anna",
"Crystal",
"Virginia",
"Kathleen",
"Pamela",
"Martha",
"Becky",
"Amanda",
"Stephanie",
"Carolyn",
"Christine",
"Marie",
"Janet",
"Catherine",
"Frances",
"Ann",
"Joyce",
"Diane",
"Jane",
"Shauna",
"Trisha",
"Eileen",
"Danielle",
"Jacquelyn",
"Lynn",
"Hannah",
"Brittany"
};
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="USA last names static name list">
public static final String[] COMMON_USA_LAST_NAMES = new String[]{
"Smith",
"Johnson",
"Williams",
"Brown",
"Jones",
"Miller",
"Davis",
"Wilson",
"Anderson",
"Taylor",
"Thomas",
"Moore",
"Martin",
"Jackson",
"Thompson",
"White",
"Clark",
"Lewis",
"Robinson",
"Walker",
"Willis",
"Carter",
"King",
"Lee",
"Grant",
"Howard",
"Morris",
"Bartlett",
"Paine",
"Wayne",
"Lorraine"
};
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Lovecraft Mythos style static name list">
public static final String[] LOVECRAFT_MYTHOS_NAMES = new String[]{
"Koth",
"Ghlatelilt",
"Siarlut",
"Nyogongogg",
"Nyialan",
"Nyithiark",
"Lyun",
"Kethoshigr",
"Shobik",
"Tekogr",
"Hru-yn",
"Lya-ehibos",
"Hruna-oma-ult",
"Shabo'en",
"Shrashangal",
"Shukhaniark",
"Thaghum",
"Shrilang",
"Lukhungu'ith",
"Nyun",
"Nyia-ongin",
"Shogia-usun",
"Lyu-yl",
"Liathiagragr",
"Lyathagg",
"Hri'osurkut",
"Shothegh",
"No-orleshigh",
"Zvriangekh",
"Nyesashiv",
"Lyarkio",
"Le'akh",
"Liashi-en",
"Shurkano'um",
"Hrakhanoth",
"Ghlotsuban",
"Cthitughias",
"Ftanugh"
};
//</editor-fold>
private static final char[] vowels = {'a', 'e', 'i', 'o'};//not using y because it looks strange as a vowel in names
private static final int LAST_LETTER_CANDIDATES_MAX = 52;
private IStatefulRNG rng;
private String[] names;
private int consonantLimit;
private ArrayList<Integer> sizes;
private HashMap<Character, HashMap<Character, ProbabilityTable<Character>>> letters;
private ArrayList<Character> firstLetterSamples;
private ArrayList<Character> lastLetterSamples;
private DamerauLevenshteinAlgorithm dla = new DamerauLevenshteinAlgorithm(1, 1, 1, 1);
/**
* Creates the generator by seeding the provided list of names.
*
* @param names an array of Strings that are typical names to be emulated
*/
public WeightedLetterNamegen(String[] names) {
this(names, 2);
}
/**
* Creates the generator by seeding the provided list of names.
*
* @param names an array of Strings that are typical names to be emulated
* @param consonantLimit the maximum allowed consonants in a row
*/
public WeightedLetterNamegen(String[] names, int consonantLimit) {
this(names, consonantLimit, new GWTRNG());
}
/**
* Creates the generator by seeding the provided list of names. The given RNG will be used for
* all random decisions this has to make, so if it has the same state (and RandomnessSource) on
* different runs through the program, it will produce the same names reliably.
*
* @param names an array of Strings that are typical names to be emulated
* @param consonantLimit the maximum allowed consonants in a row
* @param rng the source of randomness to be used
*/
public WeightedLetterNamegen(String[] names, int consonantLimit, IStatefulRNG rng) {
this.names = names;
this.consonantLimit = consonantLimit;
this.rng = rng;
init();
}
/**
* Initialization, statistically measures letter likelihood.
*/
private void init() {
sizes = new ArrayList<>();
letters = new HashMap<>();
firstLetterSamples = new ArrayList<>();
lastLetterSamples = new ArrayList<>();
for (int i = 0; i < names.length - 1; i++) {
String name = names[i];
if (name == null || name.length() < 1) {
continue;
}
// (1) Insert size
sizes.add(name.length());
// (2) Grab first letter
firstLetterSamples.add(name.charAt(0));
// (3) Grab last letter
lastLetterSamples.add(name.charAt(name.length() - 1));
// (4) Process all letters
for (int n = 0; n < name.length() - 1; n++) {
char letter = name.charAt(n);
char nextLetter = name.charAt(n + 1);
// Create letter if it doesn't exist
HashMap<Character, ProbabilityTable<Character>> wl = letters.get(letter);
if (wl == null) {
wl = new HashMap<>();
letters.put(letter, wl);
}
ProbabilityTable<Character> wlg = wl.get(letter);
if (wlg == null) {
wlg = new ProbabilityTable<>(rng.getState());
wl.put(letter, wlg);
}
wlg.add(nextLetter, 1);
// If letter was uppercase (beginning of name), also add a lowercase entry
if (Category.Lu.contains(letter)) {
letter = Character.toLowerCase(letter);
wlg = wl.get(letter);
if (wlg == null) {
wlg = new ProbabilityTable<>(rng.getState());
wl.put(letter, wlg);
}
wlg.add(nextLetter, 1);
}
}
}
}
private StringBuilder generateInner(StringBuilder name) {
for (int runs = 0; runs < LAST_LETTER_CANDIDATES_MAX; runs++) {
name.setLength(0);
// Pick size
int size = rng.getRandomElement(sizes);
// Pick first letter
char latest = rng.getRandomElement(firstLetterSamples);
name.append(latest);
for (int i = 1; i < size - 2; i++) {
name.append(latest = getRandomNextLetter(latest));
}
// Attempt to find a last letter
for (int lastLetterFits = 0; lastLetterFits < LAST_LETTER_CANDIDATES_MAX; lastLetterFits++) {
char lastLetter = rng.getRandomElement(lastLetterSamples);
char intermediateLetterCandidate = getIntermediateLetter(latest, lastLetter);
// Only attach last letter if the candidate is valid (if no candidate, the antepenultimate letter always occurs at the end)
if (Category.L.contains(intermediateLetterCandidate)) {
name.append(intermediateLetterCandidate).append(lastLetter);
break;
}
}
// Check that the word has no triple letter sequences, and that the Levenshtein distance is kosher
if (validateGrouping(name) && checkLevenshtein(name)) {
return name;
}
}
name.setLength(0);
return name.append(rng.getRandomElement(names));
}
/**
* Gets one random String name.
*
* @return a single random String name
*/
public String generate() {
return generateInner(new StringBuilder(32)).toString();
}
/**
* Gets an ArrayList of random String names, sized to match amountToGenerate.
* @param amountToGenerate how many String items to include in the returned ArrayList
* @return an ArrayList of random String names
*/
public ArrayList<String> generateList(int amountToGenerate) {
ArrayList<String> result = new ArrayList<>();
StringBuilder name = new StringBuilder(32);
for (int i = 0; i < amountToGenerate; i++) {
result.add(generateInner(name).toString());
}
return result;
}
/**
* Gets an array of random String names, sized to match amountToGenerate.
*
* @param amountToGenerate how many String items to include in the returned array
* @return an array of random String names
*/
public String[] generate(int amountToGenerate)
{
return generateList(amountToGenerate).toArray(new String[0]);
}
/**
* Searches for the best fit letter between the letter before and the letter
* after (non-random). Used to determine penultimate letters in names.
*
* @param letterBefore The letter before the desired letter.
* @param letterAfter The letter after the desired letter.
* @return The best fit letter between the provided letters.
*/
private char getIntermediateLetter(char letterBefore, char letterAfter) {
if (Category.L.contains(letterBefore) && Category.L.contains(letterAfter)) {
// First grab all letters that come after the 'letterBefore'
HashMap<Character, ProbabilityTable<Character>> wl = letters.get(letterBefore);
if (wl == null) {
return getRandomNextLetter(letterBefore);
}
Set<Character> letterCandidates = wl.get(letterBefore).items();
char bestFitLetter = '\'';
int bestFitScore = 0;
// Step through candidates, and return best scoring letter
for (char letter : letterCandidates) {
wl = letters.get(letter);
if (wl == null) {
continue;
}
ProbabilityTable<Character> weightedLetterGroup = wl.get(letterBefore);
if (weightedLetterGroup != null) {
int letterCounter = weightedLetterGroup.weight(letterAfter);
if (letterCounter > bestFitScore) {
bestFitLetter = letter;
bestFitScore = letterCounter;
}
}
}
return bestFitLetter;
} else {
return '-';
}
}
/**
* Checks that no three letters happen in succession.
*
* @param name The name CharSequence
* @return True if no triple letter sequence is found.
*/
private boolean validateGrouping(CharSequence name) {
for (int i = 2; i < name.length(); i++) {
char c0 = name.charAt(i);
char c1 = name.charAt(i-1);
char c2 = name.charAt(i-2);
if ((c0 == c1 && c0 == c2) || !(isVowel(c0) || isVowel(c1) || isVowel(c2))) {
return false;
}
}
int consonants = 0;
for (int i = 0; i < name.length(); i++) {
if (isVowel(name.charAt(i))) {
consonants = 0;
} else {
if (++consonants > consonantLimit) {
return false;
}
}
}
return true;
}
private boolean isVowel(char c) {
switch(c)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'y':
return true;
default:
return false;
}
}
/**
* Checks that the Damerau-Levenshtein distance of this name is within a
* given bias from a name on the master list.
*
* @param name The name string.
* @return True if a name is found that is within the bias.
*/
private boolean checkLevenshtein(CharSequence name) {
int levenshteinBias = name.length() / 2;
for (String name1 : names) {
int levenshteinDistance = dla.execute(name, name1);
if (levenshteinDistance <= levenshteinBias) {
return true;
}
}
return false;
}
private char getRandomNextLetter(char letter) {
if (letters.containsKey(letter)) {
return letters.get(letter).get(letter).random();
} else {
return vowels[rng.next(2)]; // 2 bits, so ranging from 0 to 3
}
}
}
| yellowstonegames/SquidLib | squidlib-util/src/main/java/squidpony/WeightedLetterNamegen.java | 5,167 | // Pick size | line_comment | pl | /*
* Copyright (c) 2022 Eben Howard, Tommy Ettinger, and contributors
*
* 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 squidpony;
import regexodus.Category;
import squidpony.squidmath.GWTRNG;
import squidpony.squidmath.IStatefulRNG;
import squidpony.squidmath.ProbabilityTable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
/**
* Based on work by Nolithius available at the following two sites
* https://github.com/Nolithius/weighted-letter-namegen
* http://code.google.com/p/weighted-letter-namegen/
*
* @see FakeLanguageGen FakeLanguageGen is meant for generating more than just names, and can imitate language styles.
* @author Eben Howard - http://squidpony.com - howard@squidpony.com
*/
public class WeightedLetterNamegen {
//<editor-fold defaultstate="collapsed" desc="Viking Style static name list">
public static final String[] VIKING_STYLE_NAMES = new String[]{
"Andor",
"Baatar",
"Beowulf",
"Drogo",
"Freya",
"Grog",
"Gruumsh",
"Grunt",
"Hodor",
"Hrothgar",
"Hrun",
"Korg",
"Lothar",
"Odin",
"Theodrin",
"Thor",
"Yngvar",
"Xandor"
};
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Star Wars Style static name list">
public static final String[] STAR_WARS_STYLE_NAMES = new String[]{
"Lutoif Vap",
"Nasoi Seert",
"Jitpai",
"Sose",
"Vainau",
"Jairkau",
"Tirka Kist",
"Boush",
"Wofe",
"Voxin Voges",
"Koux Boiti",
"Loim",
"Gaungu",
"Mut Tep",
"Foimo Saispi",
"Toneeg Vaiba",
"Nix Nast",
"Gup Dangisp",
"Distark Toonausp",
"Tex Brinki",
"Kat Tosha",
"Tauna Foip",
"Frip Cex",
"Fexa Lun",
"Tafa",
"Zeesheerk",
"Cremoim Kixoop",
"Tago",
"Kesha Diplo"
};
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="USA male names static name list">
public static final String[] COMMON_USA_MALE_NAMES = new String[]{
"James",
"John",
"Robert",
"Michael",
"William",
"David",
"Richard",
"Charles",
"Joseph",
"Tomas",
"Christopher",
"Daniel",
"Paul",
"Mark",
"Donald",
"George",
"Kenneth",
"Steven",
"Edward",
"Brian",
"Ronald",
"Anthony",
"Kevin",
"Jason",
"Matthew",
"Gary",
"Timothy",
"Jose",
"Larry",
"Jeffrey",
"Frank",
"Scott",
"Eric",
"Stephen",
"Andrew",
"Raymond",
"Gregory",
"Joshua",
"Jerry",
"Dennis",
"Walter",
"Patrick",
"Peter",
"Harold",
"Douglas",
"Henry",
"Carl",
"Arthur",
"Ryan",
"Roger"
};
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="USA female names static name list">
public static final String[] COMMON_USA_FEMALE_NAMES = new String[]{
"Mary",
"Patricia",
"Linda",
"Barbara",
"Elizabeth",
"Jennifer",
"Maria",
"Susan",
"Margaret",
"Dorothy",
"Lisa",
"Nancy",
"Karen",
"Betty",
"Helen",
"Sandra",
"Donna",
"Carol",
"Ruth",
"Sharon",
"Michelle",
"Laura",
"Sarah",
"Kimberly",
"Deborah",
"Jessica",
"Shirley",
"Cynthia",
"Angela",
"Melissa",
"Brenda",
"Amy",
"Anna",
"Crystal",
"Virginia",
"Kathleen",
"Pamela",
"Martha",
"Becky",
"Amanda",
"Stephanie",
"Carolyn",
"Christine",
"Marie",
"Janet",
"Catherine",
"Frances",
"Ann",
"Joyce",
"Diane",
"Jane",
"Shauna",
"Trisha",
"Eileen",
"Danielle",
"Jacquelyn",
"Lynn",
"Hannah",
"Brittany"
};
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="USA last names static name list">
public static final String[] COMMON_USA_LAST_NAMES = new String[]{
"Smith",
"Johnson",
"Williams",
"Brown",
"Jones",
"Miller",
"Davis",
"Wilson",
"Anderson",
"Taylor",
"Thomas",
"Moore",
"Martin",
"Jackson",
"Thompson",
"White",
"Clark",
"Lewis",
"Robinson",
"Walker",
"Willis",
"Carter",
"King",
"Lee",
"Grant",
"Howard",
"Morris",
"Bartlett",
"Paine",
"Wayne",
"Lorraine"
};
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Lovecraft Mythos style static name list">
public static final String[] LOVECRAFT_MYTHOS_NAMES = new String[]{
"Koth",
"Ghlatelilt",
"Siarlut",
"Nyogongogg",
"Nyialan",
"Nyithiark",
"Lyun",
"Kethoshigr",
"Shobik",
"Tekogr",
"Hru-yn",
"Lya-ehibos",
"Hruna-oma-ult",
"Shabo'en",
"Shrashangal",
"Shukhaniark",
"Thaghum",
"Shrilang",
"Lukhungu'ith",
"Nyun",
"Nyia-ongin",
"Shogia-usun",
"Lyu-yl",
"Liathiagragr",
"Lyathagg",
"Hri'osurkut",
"Shothegh",
"No-orleshigh",
"Zvriangekh",
"Nyesashiv",
"Lyarkio",
"Le'akh",
"Liashi-en",
"Shurkano'um",
"Hrakhanoth",
"Ghlotsuban",
"Cthitughias",
"Ftanugh"
};
//</editor-fold>
private static final char[] vowels = {'a', 'e', 'i', 'o'};//not using y because it looks strange as a vowel in names
private static final int LAST_LETTER_CANDIDATES_MAX = 52;
private IStatefulRNG rng;
private String[] names;
private int consonantLimit;
private ArrayList<Integer> sizes;
private HashMap<Character, HashMap<Character, ProbabilityTable<Character>>> letters;
private ArrayList<Character> firstLetterSamples;
private ArrayList<Character> lastLetterSamples;
private DamerauLevenshteinAlgorithm dla = new DamerauLevenshteinAlgorithm(1, 1, 1, 1);
/**
* Creates the generator by seeding the provided list of names.
*
* @param names an array of Strings that are typical names to be emulated
*/
public WeightedLetterNamegen(String[] names) {
this(names, 2);
}
/**
* Creates the generator by seeding the provided list of names.
*
* @param names an array of Strings that are typical names to be emulated
* @param consonantLimit the maximum allowed consonants in a row
*/
public WeightedLetterNamegen(String[] names, int consonantLimit) {
this(names, consonantLimit, new GWTRNG());
}
/**
* Creates the generator by seeding the provided list of names. The given RNG will be used for
* all random decisions this has to make, so if it has the same state (and RandomnessSource) on
* different runs through the program, it will produce the same names reliably.
*
* @param names an array of Strings that are typical names to be emulated
* @param consonantLimit the maximum allowed consonants in a row
* @param rng the source of randomness to be used
*/
public WeightedLetterNamegen(String[] names, int consonantLimit, IStatefulRNG rng) {
this.names = names;
this.consonantLimit = consonantLimit;
this.rng = rng;
init();
}
/**
* Initialization, statistically measures letter likelihood.
*/
private void init() {
sizes = new ArrayList<>();
letters = new HashMap<>();
firstLetterSamples = new ArrayList<>();
lastLetterSamples = new ArrayList<>();
for (int i = 0; i < names.length - 1; i++) {
String name = names[i];
if (name == null || name.length() < 1) {
continue;
}
// (1) Insert size
sizes.add(name.length());
// (2) Grab first letter
firstLetterSamples.add(name.charAt(0));
// (3) Grab last letter
lastLetterSamples.add(name.charAt(name.length() - 1));
// (4) Process all letters
for (int n = 0; n < name.length() - 1; n++) {
char letter = name.charAt(n);
char nextLetter = name.charAt(n + 1);
// Create letter if it doesn't exist
HashMap<Character, ProbabilityTable<Character>> wl = letters.get(letter);
if (wl == null) {
wl = new HashMap<>();
letters.put(letter, wl);
}
ProbabilityTable<Character> wlg = wl.get(letter);
if (wlg == null) {
wlg = new ProbabilityTable<>(rng.getState());
wl.put(letter, wlg);
}
wlg.add(nextLetter, 1);
// If letter was uppercase (beginning of name), also add a lowercase entry
if (Category.Lu.contains(letter)) {
letter = Character.toLowerCase(letter);
wlg = wl.get(letter);
if (wlg == null) {
wlg = new ProbabilityTable<>(rng.getState());
wl.put(letter, wlg);
}
wlg.add(nextLetter, 1);
}
}
}
}
private StringBuilder generateInner(StringBuilder name) {
for (int runs = 0; runs < LAST_LETTER_CANDIDATES_MAX; runs++) {
name.setLength(0);
// Pick <SUF>
int size = rng.getRandomElement(sizes);
// Pick first letter
char latest = rng.getRandomElement(firstLetterSamples);
name.append(latest);
for (int i = 1; i < size - 2; i++) {
name.append(latest = getRandomNextLetter(latest));
}
// Attempt to find a last letter
for (int lastLetterFits = 0; lastLetterFits < LAST_LETTER_CANDIDATES_MAX; lastLetterFits++) {
char lastLetter = rng.getRandomElement(lastLetterSamples);
char intermediateLetterCandidate = getIntermediateLetter(latest, lastLetter);
// Only attach last letter if the candidate is valid (if no candidate, the antepenultimate letter always occurs at the end)
if (Category.L.contains(intermediateLetterCandidate)) {
name.append(intermediateLetterCandidate).append(lastLetter);
break;
}
}
// Check that the word has no triple letter sequences, and that the Levenshtein distance is kosher
if (validateGrouping(name) && checkLevenshtein(name)) {
return name;
}
}
name.setLength(0);
return name.append(rng.getRandomElement(names));
}
/**
* Gets one random String name.
*
* @return a single random String name
*/
public String generate() {
return generateInner(new StringBuilder(32)).toString();
}
/**
* Gets an ArrayList of random String names, sized to match amountToGenerate.
* @param amountToGenerate how many String items to include in the returned ArrayList
* @return an ArrayList of random String names
*/
public ArrayList<String> generateList(int amountToGenerate) {
ArrayList<String> result = new ArrayList<>();
StringBuilder name = new StringBuilder(32);
for (int i = 0; i < amountToGenerate; i++) {
result.add(generateInner(name).toString());
}
return result;
}
/**
* Gets an array of random String names, sized to match amountToGenerate.
*
* @param amountToGenerate how many String items to include in the returned array
* @return an array of random String names
*/
public String[] generate(int amountToGenerate)
{
return generateList(amountToGenerate).toArray(new String[0]);
}
/**
* Searches for the best fit letter between the letter before and the letter
* after (non-random). Used to determine penultimate letters in names.
*
* @param letterBefore The letter before the desired letter.
* @param letterAfter The letter after the desired letter.
* @return The best fit letter between the provided letters.
*/
private char getIntermediateLetter(char letterBefore, char letterAfter) {
if (Category.L.contains(letterBefore) && Category.L.contains(letterAfter)) {
// First grab all letters that come after the 'letterBefore'
HashMap<Character, ProbabilityTable<Character>> wl = letters.get(letterBefore);
if (wl == null) {
return getRandomNextLetter(letterBefore);
}
Set<Character> letterCandidates = wl.get(letterBefore).items();
char bestFitLetter = '\'';
int bestFitScore = 0;
// Step through candidates, and return best scoring letter
for (char letter : letterCandidates) {
wl = letters.get(letter);
if (wl == null) {
continue;
}
ProbabilityTable<Character> weightedLetterGroup = wl.get(letterBefore);
if (weightedLetterGroup != null) {
int letterCounter = weightedLetterGroup.weight(letterAfter);
if (letterCounter > bestFitScore) {
bestFitLetter = letter;
bestFitScore = letterCounter;
}
}
}
return bestFitLetter;
} else {
return '-';
}
}
/**
* Checks that no three letters happen in succession.
*
* @param name The name CharSequence
* @return True if no triple letter sequence is found.
*/
private boolean validateGrouping(CharSequence name) {
for (int i = 2; i < name.length(); i++) {
char c0 = name.charAt(i);
char c1 = name.charAt(i-1);
char c2 = name.charAt(i-2);
if ((c0 == c1 && c0 == c2) || !(isVowel(c0) || isVowel(c1) || isVowel(c2))) {
return false;
}
}
int consonants = 0;
for (int i = 0; i < name.length(); i++) {
if (isVowel(name.charAt(i))) {
consonants = 0;
} else {
if (++consonants > consonantLimit) {
return false;
}
}
}
return true;
}
private boolean isVowel(char c) {
switch(c)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'y':
return true;
default:
return false;
}
}
/**
* Checks that the Damerau-Levenshtein distance of this name is within a
* given bias from a name on the master list.
*
* @param name The name string.
* @return True if a name is found that is within the bias.
*/
private boolean checkLevenshtein(CharSequence name) {
int levenshteinBias = name.length() / 2;
for (String name1 : names) {
int levenshteinDistance = dla.execute(name, name1);
if (levenshteinDistance <= levenshteinBias) {
return true;
}
}
return false;
}
private char getRandomNextLetter(char letter) {
if (letters.containsKey(letter)) {
return letters.get(letter).get(letter).random();
} else {
return vowels[rng.next(2)]; // 2 bits, so ranging from 0 to 3
}
}
}
|
179038_0 | package org.justynafraczek.plantsshop.warehouse;
import java.util.Timer;
import java.util.TimerTask;
import org.justynafraczek.plantsshop.NewPlantsOrderResponse;
import org.justynafraczek.plantsshop.types.ProcessingEvent;
import org.justynafraczek.plantsshop.types.ProcessingState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.ObjectMapper;
@Service
public class Dispatcher {
@Autowired
KafkaProducer kafkaProducer;
@Autowired
OrdersDatabase ordersDatabase;
private ObjectMapper mapper = new ObjectMapper();
Timer timer = new Timer();
//czekamy 40s, po nich wykonujemy funkcje nizej
public void dispatch(String orderID) {
timer.schedule(new TimerTask() {
@Override
public void run() {
ProcessingState currentStatus = ordersDatabase.getOrder(orderID).getPlantsOrder().getStatus();
// Don't try to send order if it was cancelled or is being refunded
if (currentStatus == ProcessingState.REFUNDING_ORDER
|| currentStatus == ProcessingState.ORDER_CANCELLED) {
return;
}
NewPlantsOrderResponse statusUpdate = new NewPlantsOrderResponse();
statusUpdate.setOrderID(orderID);
// po 40s order jest zmieniany na complete, po stanie order being prepared
statusUpdate.setEvent(ProcessingEvent.COMPLETE);
try {
String res = mapper.writeValueAsString(statusUpdate);
//wysylanie stanu complete do bramy i payments
kafkaProducer.sendMessage(res);
} catch (Exception e) {
e.printStackTrace();
}
}
}, 40000);
}
}
| yennief/PlantsFactory | plants-warehouse-service/src/main/java/org/justynafraczek/plantsshop/warehouse/Dispatcher.java | 504 | //czekamy 40s, po nich wykonujemy funkcje nizej | line_comment | pl | package org.justynafraczek.plantsshop.warehouse;
import java.util.Timer;
import java.util.TimerTask;
import org.justynafraczek.plantsshop.NewPlantsOrderResponse;
import org.justynafraczek.plantsshop.types.ProcessingEvent;
import org.justynafraczek.plantsshop.types.ProcessingState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.ObjectMapper;
@Service
public class Dispatcher {
@Autowired
KafkaProducer kafkaProducer;
@Autowired
OrdersDatabase ordersDatabase;
private ObjectMapper mapper = new ObjectMapper();
Timer timer = new Timer();
//czeka<SUF>
public void dispatch(String orderID) {
timer.schedule(new TimerTask() {
@Override
public void run() {
ProcessingState currentStatus = ordersDatabase.getOrder(orderID).getPlantsOrder().getStatus();
// Don't try to send order if it was cancelled or is being refunded
if (currentStatus == ProcessingState.REFUNDING_ORDER
|| currentStatus == ProcessingState.ORDER_CANCELLED) {
return;
}
NewPlantsOrderResponse statusUpdate = new NewPlantsOrderResponse();
statusUpdate.setOrderID(orderID);
// po 40s order jest zmieniany na complete, po stanie order being prepared
statusUpdate.setEvent(ProcessingEvent.COMPLETE);
try {
String res = mapper.writeValueAsString(statusUpdate);
//wysylanie stanu complete do bramy i payments
kafkaProducer.sendMessage(res);
} catch (Exception e) {
e.printStackTrace();
}
}
}, 40000);
}
}
|
153277_5 | package com.apifan.common.random.source;
import com.apifan.common.random.constant.RandomConstant;
import com.apifan.common.random.entity.IpRange;
import com.apifan.common.random.util.ResourceUtils;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.WordUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* 互联网信息数据源
*
* @author yin
*/
public class InternetSource {
private static final Logger logger = LoggerFactory.getLogger(InternetSource.class);
/**
* 主流安卓厂商名称
*/
private static final String[] ANDROID_MANUFACTURERS = new String[]{"samsung", "sony", "huawei", "honor", "xiaomi", "redmi", "mi", "vivo", "oppo", "oneplus", "lg", "lenovo", "motorola", "nokia", "meizu", "zte", "asus", "smartisan", "nubia", "realme", "iqoo", "coolpad", "gionee"};
/**
* 安卓 User-Agent模板
*/
private static final String ANDROID_TEMPLATE = "Mozilla/5.0 (Linux; U; Android %d.0.0; zh-cn; %s-%s Build/%s) AppleWebKit/537.36 (KHTML, like Gecko)Version/4.0 Chrome/74.0.3729.157 Mobile Safari/537.36";
/**
* iOS User-Agent模板
*/
private static final String IOS_TEMPLATE = "Mozilla/5.0 (iPhone; CPU iPhone OS %s like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/%s";
/**
* 主流iOS版本号
*/
private static final String[] IOS_VERSIONS = new String[]{"10_0", "10_1", "10_2", "10_3", "11_0", "11_1", "11_2", "11_3", "11_4", "12_0", "12_4", "13_0", "13_7", "14_0", "14_7", "15_0", "15_7", "16_0"};
/**
* 主流Windows版本号
*/
private static final String[] WINDOWS_VERSIONS = new String[]{"6.0", "6.1", "6.2", "6.3", "10.0", "11.0"};
/**
* PC User-Agent模板
*/
private static final String PC_TEMPLATE = "Mozilla/5.0 (Windows NT %s; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%d.0.%d.%d Safari/537.36";
/**
* IP范围列表
*/
private List<IpRange> ipRangeList = Lists.newArrayList();
private static final InternetSource instance = new InternetSource();
private InternetSource() {
try {
List<String> areaLines = ResourceUtils.readLines("cn-ip.csv");
if (CollectionUtils.isNotEmpty(areaLines)) {
areaLines.forEach(i -> {
if (StringUtils.isEmpty(i)) {
return;
}
List<String> row = Splitter.on(",").splitToList(i);
IpRange range = new IpRange();
range.setBeginIp(row.get(0));
range.setBeginIpNum(ipv4ToLong(range.getBeginIp()));
range.setEndIp(row.get(1));
range.setEndIpNum(ipv4ToLong(range.getEndIp()));
ipRangeList.add(range);
});
}
} catch (Exception e) {
logger.error("初始化数据异常", e);
}
}
/**
* 获取唯一实例
*
* @return 实例
*/
public static InternetSource getInstance() {
return instance;
}
/**
* 生成随机的邮箱地址
*
* @param maxLength 邮箱用户名最大长度(最小长度为2)
* @return 随机邮箱地址
*/
public String randomEmail(int maxLength) {
return randomEmail(maxLength, null);
}
/**
* 生成随机的邮箱地址(指定后缀)
*
* @param maxLength 邮箱用户名最大长度(最小长度为2)
* @param suffix 后缀
* @return 随机邮箱地址
*/
public String randomEmail(int maxLength, String suffix) {
Preconditions.checkArgument(maxLength >= 2, "邮箱用户名最大长度不能小于2");
if (StringUtils.isBlank(suffix)) {
suffix = randomDomain(RandomUtils.nextInt(2, maxLength + 1));
}
String email = RandomStringUtils.randomAlphanumeric(2, maxLength + 1) +
"@" + suffix;
return email.toLowerCase();
}
/**
* 生成随机的域名
*
* @param maxLength 域名最大长度(最小长度为2)
* @return 随机域名
*/
public String randomDomain(int maxLength) {
Preconditions.checkArgument(maxLength >= 2, "域名最大长度不能小于2");
String domain = RandomStringUtils.randomAlphanumeric(2, maxLength + 1) + "." +
ResourceUtils.getRandomElement(RandomConstant.domainSuffixList);
return domain.toLowerCase();
}
/**
* 生成随机的静态URL
*
* @param suffix 后缀
* @return 随机的静态URL
*/
public String randomStaticUrl(String suffix) {
Preconditions.checkArgument(StringUtils.isNotEmpty(suffix), "后缀为空");
String domain = randomDomain(16);
String prefix = "http://";
int x = RandomUtils.nextInt(0, 101);
if (x % 3 == 0) {
prefix = "https://";
}
return prefix + domain.toLowerCase() + "/" + RandomUtils.nextLong(1L, 10000000000001L) + "/"
+ RandomStringUtils.randomAlphanumeric(8, 33) + "." + suffix;
}
/**
* 随机的公网IPv4地址
*
* @return 公网IPv4地址
*/
public String randomPublicIpv4() {
IpRange range = ResourceUtils.getRandomElement(ipRangeList);
if (range == null) {
return null;
}
long ipv4Num = RandomUtils.nextLong(range.getBeginIpNum(), range.getEndIpNum());
return longToIpv4(ipv4Num);
}
/**
* 随机的私有IPv4地址(内网地址)
*
* @return 私有IPv4地址(内网地址)
*/
public String randomPrivateIpv4() {
int x = RandomUtils.nextInt(1, 101);
if (x % 2 == 0) {
return "10." + RandomUtils.nextInt(0, 256) + "." + RandomUtils.nextInt(0, 256) + "." + RandomUtils.nextInt(0, 256);
} else if (x % 3 == 0) {
return "172." + RandomUtils.nextInt(16, 32) + "." + RandomUtils.nextInt(0, 256) + "." + RandomUtils.nextInt(0, 256);
} else {
return "192.168." + RandomUtils.nextInt(0, 256) + "." + RandomUtils.nextInt(0, 256);
}
}
/**
* 随机的PC User-Agent
*
* @return PC User-Agent
*/
public String randomPCUserAgent() {
return String.format(PC_TEMPLATE,
WINDOWS_VERSIONS[RandomUtils.nextInt(0, WINDOWS_VERSIONS.length)],
RandomUtils.nextInt(60, 100),
RandomUtils.nextInt(2000, 4000),
RandomUtils.nextInt(1, 200));
}
/**
* 随机的Android User-Agent
*
* @return Android User-Agent
*/
public String randomAndroidUserAgent() {
int androidVersion = RandomUtils.nextInt(7, 13);
return String.format(ANDROID_TEMPLATE, androidVersion,
ANDROID_MANUFACTURERS[RandomUtils.nextInt(0, ANDROID_MANUFACTURERS.length)].toUpperCase(),
RandomStringUtils.randomAlphanumeric(6).toUpperCase(),
RandomStringUtils.randomAlphanumeric(6).toUpperCase());
}
/**
* 随机的iOS User-Agent
*
* @return iOS User-Agent
*/
public String randomIOSUserAgent() {
return String.format(IOS_TEMPLATE,
IOS_VERSIONS[RandomUtils.nextInt(0, IOS_VERSIONS.length)],
RandomStringUtils.randomAlphanumeric(6).toUpperCase());
}
/**
* 随机MAC地址
*
* @param splitter 分隔符
* @return 随机MAC地址
*/
public String randomMacAddress(String splitter) {
int count = 6;
List<String> mac = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
int n = RandomUtils.nextInt(0, 255);
mac.add(String.format("%02x", n));
}
return Joiner.on(StringUtils.isNotEmpty(splitter) ? splitter : "-").join(mac).toUpperCase();
}
/**
* 随机端口号
* 注意: 不会生成1024及以下的端口号
*
* @return 随机端口号
*/
public int randomPort() {
return RandomUtils.nextInt(1025, 65535);
}
/**
* 随机App Bundle ID
*
* @return 随机App Bundle ID
*/
public String randomAppBundleId() {
String bundleId = ResourceUtils.getRandomElement(RandomConstant.domainSuffixList)
+ "." + RandomStringUtils.randomAlphabetic(2, 21) + "." + RandomStringUtils.randomAlphabetic(2, 21);
return bundleId.toLowerCase();
}
/**
* 随机App版本号
*
* @return 随机App版本号
*/
public String randomAppVersionCode() {
return RandomUtils.nextInt(1, 11) + "." + RandomUtils.nextInt(0, 100) + "." + RandomUtils.nextInt(0, 1000);
}
/**
* 随机App名称
*
* @return 随机App名称
*/
@SuppressWarnings("deprecation")
public String randomAppName() {
return WordUtils.capitalize(RandomStringUtils.randomAlphabetic(4, 11).toLowerCase());
}
/**
* 随机IPv6地址
*
* @return 随机IPv6地址
*/
public String randomIpV6() {
List<String> numbers = Lists.newArrayList();
for (int i = 0; i < 8; i++) {
numbers.add(Integer.toHexString(RandomUtils.nextInt(0, 65535)));
}
return Joiner.on(":").join(numbers);
}
/**
* IPv4地址转整数
*
* @param ipv4 IPv4地址
* @return 整数
*/
private long ipv4ToLong(String ipv4) {
String[] part = ipv4.split("\\.");
long num = 0;
for (int i = 0; i < part.length; i++) {
int power = 3 - i;
num += ((Integer.parseInt(part[i]) % 256 * Math.pow(256, power)));
}
return num;
}
/**
* 整数转IPv4地址
*
* @param ipv4Num 整数
* @return IPv4地址
*/
private String longToIpv4(long ipv4Num) {
StringBuilder result = new StringBuilder(15);
for (int i = 0; i < 4; i++) {
result.insert(0, (ipv4Num & 0xff));
if (i < 3) {
result.insert(0, '.');
}
ipv4Num = ipv4Num >> 8;
}
return result.toString();
}
}
| yindz/common-random | src/main/java/com/apifan/common/random/source/InternetSource.java | 3,971 | /**
* 主流Windows版本号
*/ | block_comment | pl | package com.apifan.common.random.source;
import com.apifan.common.random.constant.RandomConstant;
import com.apifan.common.random.entity.IpRange;
import com.apifan.common.random.util.ResourceUtils;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.WordUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* 互联网信息数据源
*
* @author yin
*/
public class InternetSource {
private static final Logger logger = LoggerFactory.getLogger(InternetSource.class);
/**
* 主流安卓厂商名称
*/
private static final String[] ANDROID_MANUFACTURERS = new String[]{"samsung", "sony", "huawei", "honor", "xiaomi", "redmi", "mi", "vivo", "oppo", "oneplus", "lg", "lenovo", "motorola", "nokia", "meizu", "zte", "asus", "smartisan", "nubia", "realme", "iqoo", "coolpad", "gionee"};
/**
* 安卓 User-Agent模板
*/
private static final String ANDROID_TEMPLATE = "Mozilla/5.0 (Linux; U; Android %d.0.0; zh-cn; %s-%s Build/%s) AppleWebKit/537.36 (KHTML, like Gecko)Version/4.0 Chrome/74.0.3729.157 Mobile Safari/537.36";
/**
* iOS User-Agent模板
*/
private static final String IOS_TEMPLATE = "Mozilla/5.0 (iPhone; CPU iPhone OS %s like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/%s";
/**
* 主流iOS版本号
*/
private static final String[] IOS_VERSIONS = new String[]{"10_0", "10_1", "10_2", "10_3", "11_0", "11_1", "11_2", "11_3", "11_4", "12_0", "12_4", "13_0", "13_7", "14_0", "14_7", "15_0", "15_7", "16_0"};
/**
* 主流Wind<SUF>*/
private static final String[] WINDOWS_VERSIONS = new String[]{"6.0", "6.1", "6.2", "6.3", "10.0", "11.0"};
/**
* PC User-Agent模板
*/
private static final String PC_TEMPLATE = "Mozilla/5.0 (Windows NT %s; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%d.0.%d.%d Safari/537.36";
/**
* IP范围列表
*/
private List<IpRange> ipRangeList = Lists.newArrayList();
private static final InternetSource instance = new InternetSource();
private InternetSource() {
try {
List<String> areaLines = ResourceUtils.readLines("cn-ip.csv");
if (CollectionUtils.isNotEmpty(areaLines)) {
areaLines.forEach(i -> {
if (StringUtils.isEmpty(i)) {
return;
}
List<String> row = Splitter.on(",").splitToList(i);
IpRange range = new IpRange();
range.setBeginIp(row.get(0));
range.setBeginIpNum(ipv4ToLong(range.getBeginIp()));
range.setEndIp(row.get(1));
range.setEndIpNum(ipv4ToLong(range.getEndIp()));
ipRangeList.add(range);
});
}
} catch (Exception e) {
logger.error("初始化数据异常", e);
}
}
/**
* 获取唯一实例
*
* @return 实例
*/
public static InternetSource getInstance() {
return instance;
}
/**
* 生成随机的邮箱地址
*
* @param maxLength 邮箱用户名最大长度(最小长度为2)
* @return 随机邮箱地址
*/
public String randomEmail(int maxLength) {
return randomEmail(maxLength, null);
}
/**
* 生成随机的邮箱地址(指定后缀)
*
* @param maxLength 邮箱用户名最大长度(最小长度为2)
* @param suffix 后缀
* @return 随机邮箱地址
*/
public String randomEmail(int maxLength, String suffix) {
Preconditions.checkArgument(maxLength >= 2, "邮箱用户名最大长度不能小于2");
if (StringUtils.isBlank(suffix)) {
suffix = randomDomain(RandomUtils.nextInt(2, maxLength + 1));
}
String email = RandomStringUtils.randomAlphanumeric(2, maxLength + 1) +
"@" + suffix;
return email.toLowerCase();
}
/**
* 生成随机的域名
*
* @param maxLength 域名最大长度(最小长度为2)
* @return 随机域名
*/
public String randomDomain(int maxLength) {
Preconditions.checkArgument(maxLength >= 2, "域名最大长度不能小于2");
String domain = RandomStringUtils.randomAlphanumeric(2, maxLength + 1) + "." +
ResourceUtils.getRandomElement(RandomConstant.domainSuffixList);
return domain.toLowerCase();
}
/**
* 生成随机的静态URL
*
* @param suffix 后缀
* @return 随机的静态URL
*/
public String randomStaticUrl(String suffix) {
Preconditions.checkArgument(StringUtils.isNotEmpty(suffix), "后缀为空");
String domain = randomDomain(16);
String prefix = "http://";
int x = RandomUtils.nextInt(0, 101);
if (x % 3 == 0) {
prefix = "https://";
}
return prefix + domain.toLowerCase() + "/" + RandomUtils.nextLong(1L, 10000000000001L) + "/"
+ RandomStringUtils.randomAlphanumeric(8, 33) + "." + suffix;
}
/**
* 随机的公网IPv4地址
*
* @return 公网IPv4地址
*/
public String randomPublicIpv4() {
IpRange range = ResourceUtils.getRandomElement(ipRangeList);
if (range == null) {
return null;
}
long ipv4Num = RandomUtils.nextLong(range.getBeginIpNum(), range.getEndIpNum());
return longToIpv4(ipv4Num);
}
/**
* 随机的私有IPv4地址(内网地址)
*
* @return 私有IPv4地址(内网地址)
*/
public String randomPrivateIpv4() {
int x = RandomUtils.nextInt(1, 101);
if (x % 2 == 0) {
return "10." + RandomUtils.nextInt(0, 256) + "." + RandomUtils.nextInt(0, 256) + "." + RandomUtils.nextInt(0, 256);
} else if (x % 3 == 0) {
return "172." + RandomUtils.nextInt(16, 32) + "." + RandomUtils.nextInt(0, 256) + "." + RandomUtils.nextInt(0, 256);
} else {
return "192.168." + RandomUtils.nextInt(0, 256) + "." + RandomUtils.nextInt(0, 256);
}
}
/**
* 随机的PC User-Agent
*
* @return PC User-Agent
*/
public String randomPCUserAgent() {
return String.format(PC_TEMPLATE,
WINDOWS_VERSIONS[RandomUtils.nextInt(0, WINDOWS_VERSIONS.length)],
RandomUtils.nextInt(60, 100),
RandomUtils.nextInt(2000, 4000),
RandomUtils.nextInt(1, 200));
}
/**
* 随机的Android User-Agent
*
* @return Android User-Agent
*/
public String randomAndroidUserAgent() {
int androidVersion = RandomUtils.nextInt(7, 13);
return String.format(ANDROID_TEMPLATE, androidVersion,
ANDROID_MANUFACTURERS[RandomUtils.nextInt(0, ANDROID_MANUFACTURERS.length)].toUpperCase(),
RandomStringUtils.randomAlphanumeric(6).toUpperCase(),
RandomStringUtils.randomAlphanumeric(6).toUpperCase());
}
/**
* 随机的iOS User-Agent
*
* @return iOS User-Agent
*/
public String randomIOSUserAgent() {
return String.format(IOS_TEMPLATE,
IOS_VERSIONS[RandomUtils.nextInt(0, IOS_VERSIONS.length)],
RandomStringUtils.randomAlphanumeric(6).toUpperCase());
}
/**
* 随机MAC地址
*
* @param splitter 分隔符
* @return 随机MAC地址
*/
public String randomMacAddress(String splitter) {
int count = 6;
List<String> mac = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
int n = RandomUtils.nextInt(0, 255);
mac.add(String.format("%02x", n));
}
return Joiner.on(StringUtils.isNotEmpty(splitter) ? splitter : "-").join(mac).toUpperCase();
}
/**
* 随机端口号
* 注意: 不会生成1024及以下的端口号
*
* @return 随机端口号
*/
public int randomPort() {
return RandomUtils.nextInt(1025, 65535);
}
/**
* 随机App Bundle ID
*
* @return 随机App Bundle ID
*/
public String randomAppBundleId() {
String bundleId = ResourceUtils.getRandomElement(RandomConstant.domainSuffixList)
+ "." + RandomStringUtils.randomAlphabetic(2, 21) + "." + RandomStringUtils.randomAlphabetic(2, 21);
return bundleId.toLowerCase();
}
/**
* 随机App版本号
*
* @return 随机App版本号
*/
public String randomAppVersionCode() {
return RandomUtils.nextInt(1, 11) + "." + RandomUtils.nextInt(0, 100) + "." + RandomUtils.nextInt(0, 1000);
}
/**
* 随机App名称
*
* @return 随机App名称
*/
@SuppressWarnings("deprecation")
public String randomAppName() {
return WordUtils.capitalize(RandomStringUtils.randomAlphabetic(4, 11).toLowerCase());
}
/**
* 随机IPv6地址
*
* @return 随机IPv6地址
*/
public String randomIpV6() {
List<String> numbers = Lists.newArrayList();
for (int i = 0; i < 8; i++) {
numbers.add(Integer.toHexString(RandomUtils.nextInt(0, 65535)));
}
return Joiner.on(":").join(numbers);
}
/**
* IPv4地址转整数
*
* @param ipv4 IPv4地址
* @return 整数
*/
private long ipv4ToLong(String ipv4) {
String[] part = ipv4.split("\\.");
long num = 0;
for (int i = 0; i < part.length; i++) {
int power = 3 - i;
num += ((Integer.parseInt(part[i]) % 256 * Math.pow(256, power)));
}
return num;
}
/**
* 整数转IPv4地址
*
* @param ipv4Num 整数
* @return IPv4地址
*/
private String longToIpv4(long ipv4Num) {
StringBuilder result = new StringBuilder(15);
for (int i = 0; i < 4; i++) {
result.insert(0, (ipv4Num & 0xff));
if (i < 3) {
result.insert(0, '.');
}
ipv4Num = ipv4Num >> 8;
}
return result.toString();
}
}
|
4557_1 | package model;
/**
* Klasa reprezentująca pojedyńcze pole w grze
*
* Zawiera metody pozwalające na odczytnie i zmian stanu pola gry.
* @author ymir
* @since RC1
* @see BoardModel
*/
public class FieldModel {
/**
* Czy pole jest bombą;
*/
private boolean isBomb;
/**
* Zawiera cyferkę mówiącą o okolicznych polach
*/
private byte digit;
/**
* Czy odkryte
*/
private boolean isVisible;
/**
* Czy oflagowane
*/
private boolean isFlagged;
/**
* Getter cyferki na polu.
* @return byte cyferka na polu
*/
public byte getDigit() {
return digit;
}
/**
* Setter cyferki na polu.
* @param byte cyferka
*/
void setDigit(byte digit) {
this.digit = digit;
}
/**
* Czy pole jest bombą?
* @return boolean true jeżeli jest bombą
*/
public boolean isBomb() {
return isBomb;
}
/**
* Ustawia bombę
* @param boolean true jeżeli ma być bombą
*/
void setBomb(boolean isBomb) {
this.isBomb = isBomb;
}
/**
* Czy jest oflagowane?
* @return boolean true jeżeli jest
*/
public boolean isFlagged() {
return isFlagged;
}
/**
* Nadaje/zabiera flagę
* @param boolean czy ma być flaga
*/
public void setFlagged(boolean isFlagged) {
this.isFlagged = isFlagged;
}
/**
* Czy pole jest odkryte (widoczne)?
* @return boolean true jeżeli jest widoczne
*/
public boolean isVisible() {
return isVisible;
}
/**
* Odkrywa pole (isVisible staje się true, odflagowuje sie)
*/
public void show() {
this.isVisible = true;
this.isFlagged = false;
}
/**
* Odkrywa pole nie usuwajac flagi (na koniec gry).
*/
public void showInTheEnd() {
this.isVisible = true;
}
/**
* Domyślny konstruktor
*
* Produkuje pole bez bomby, cyfry ni flagi
*/
public FieldModel() {
this.digit = 0;
this.isBomb = false;
this.isVisible = false;
this.isFlagged = false;
}
}
| ymirpl/nsaper | model/FieldModel.java | 772 | /**
* Czy pole jest bombą;
*/ | block_comment | pl | package model;
/**
* Klasa reprezentująca pojedyńcze pole w grze
*
* Zawiera metody pozwalające na odczytnie i zmian stanu pola gry.
* @author ymir
* @since RC1
* @see BoardModel
*/
public class FieldModel {
/**
* Czy po<SUF>*/
private boolean isBomb;
/**
* Zawiera cyferkę mówiącą o okolicznych polach
*/
private byte digit;
/**
* Czy odkryte
*/
private boolean isVisible;
/**
* Czy oflagowane
*/
private boolean isFlagged;
/**
* Getter cyferki na polu.
* @return byte cyferka na polu
*/
public byte getDigit() {
return digit;
}
/**
* Setter cyferki na polu.
* @param byte cyferka
*/
void setDigit(byte digit) {
this.digit = digit;
}
/**
* Czy pole jest bombą?
* @return boolean true jeżeli jest bombą
*/
public boolean isBomb() {
return isBomb;
}
/**
* Ustawia bombę
* @param boolean true jeżeli ma być bombą
*/
void setBomb(boolean isBomb) {
this.isBomb = isBomb;
}
/**
* Czy jest oflagowane?
* @return boolean true jeżeli jest
*/
public boolean isFlagged() {
return isFlagged;
}
/**
* Nadaje/zabiera flagę
* @param boolean czy ma być flaga
*/
public void setFlagged(boolean isFlagged) {
this.isFlagged = isFlagged;
}
/**
* Czy pole jest odkryte (widoczne)?
* @return boolean true jeżeli jest widoczne
*/
public boolean isVisible() {
return isVisible;
}
/**
* Odkrywa pole (isVisible staje się true, odflagowuje sie)
*/
public void show() {
this.isVisible = true;
this.isFlagged = false;
}
/**
* Odkrywa pole nie usuwajac flagi (na koniec gry).
*/
public void showInTheEnd() {
this.isVisible = true;
}
/**
* Domyślny konstruktor
*
* Produkuje pole bez bomby, cyfry ni flagi
*/
public FieldModel() {
this.digit = 0;
this.isBomb = false;
this.isVisible = false;
this.isFlagged = false;
}
}
|
173548_6 | package playground.michalm.poznan.supply;
import java.util.*;
import org.matsim.api.core.v01.*;
import org.matsim.api.core.v01.network.Node;
import org.matsim.core.config.*;
import org.matsim.core.network.*;
import org.matsim.core.network.algorithms.NetworkCleaner;
import org.matsim.core.scenario.ScenarioUtils;
import org.matsim.pt.transitSchedule.TransitScheduleWriterV1;
import org.matsim.pt.utils.CreatePseudoNetwork;
import org.matsim.vehicles.VehicleWriterV1;
import org.matsim.visum.*;
import playground.mrieser.pt.converter.Visum2TransitSchedule;
public class CreatePoznanPT
{
public static void go(String visumFile, String transitScheduleWithNetworkFile,
String transitNetworkFile, String vehicleFile)
{
Config config = ConfigUtils.createConfig();
config.transit().setUseTransit(true);
config.scenario().setUseVehicles(true);
Scenario scenario = ScenarioUtils.createScenario(config);
final VisumNetwork vNetwork = new VisumNetwork();
new VisumNetworkReader(vNetwork).read(visumFile);
Visum2TransitSchedule converter = new Visum2TransitSchedule(vNetwork,
scenario.getTransitSchedule(), scenario.getTransitVehicles());
// $TSYS:CODE;NAME;TYPE;PCU
// 1S;osobowe;PrT;1.000
// 2D;dostawcze;PrT;1.000
// 3C;ciężarowe;PrT;2.500
// 4R;Rower;PrT;1.000
// 5S_zewn;osobowe_zewn;PrT;1.000
// 6D_zewn;dostawcze_zewn;PrT;1.000
// 7C_zewn;ciężarowe_zewn;PrT;2.000
// 8Cc_zewn;ciężarowe ciężkie_zewn;PrT;3.000
// A;Autobusy ZTM;PuT;1.000
// AT;Tramwaj;PuT;1.000
// KP;Komunikacja podmiejska;PuT;1.000
// TKR;Kolej Regionalna;PuT;1.000
// TKS;Kolej IC;PuT;1.000
// U;Przewozy_PKS;PuT;1.000
// UAM;Autobus marketowy;PuT;1.000
// W;Przejścia piesze;PuTWalk;1.000
// WP;Pieszo;PuTWalk;1.000
// WP-2;Pieszo-2;PuT;1.000
converter.registerTransportMode("S", TransportMode.car);
converter.registerTransportMode("D", TransportMode.car);
converter.registerTransportMode("C", TransportMode.car);
converter.registerTransportMode("R", TransportMode.bike);
converter.registerTransportMode("S_zewn", TransportMode.car);
converter.registerTransportMode("D_zewn", TransportMode.car);
converter.registerTransportMode("C_zewn", TransportMode.car);
converter.registerTransportMode("Cc_zewn", TransportMode.car);
converter.registerTransportMode("A", TransportMode.pt);
converter.registerTransportMode("AT", TransportMode.pt);
converter.registerTransportMode("KP", TransportMode.pt);
converter.registerTransportMode("TKR", TransportMode.pt);
converter.registerTransportMode("TKS", TransportMode.pt);
converter.registerTransportMode("U", TransportMode.pt);
converter.registerTransportMode("UAM", TransportMode.pt);
converter.registerTransportMode("W", TransportMode.walk);
converter.registerTransportMode("WP", TransportMode.transit_walk);
converter.registerTransportMode("WP-2", TransportMode.transit_walk);
converter.convert();
new TransitScheduleWriterV1(scenario.getTransitSchedule())
.write(transitScheduleWithNetworkFile);
new VehicleWriterV1(scenario.getTransitVehicles()).writeFile(vehicleFile);
NetworkImpl network = NetworkImpl.createNetwork();
new CreatePseudoNetwork(scenario.getTransitSchedule(), network, "tr_").createNetwork();
new NetworkCleaner().run(network);
List<Node> nodesToRemove = new ArrayList<>();
for (Node n : network.getNodes().values()) {
if (n.getInLinks().size() == 0 && n.getOutLinks().size() == 0) {
nodesToRemove.add(n);
}
}
for (Node n : nodesToRemove) {
network.removeNode(n.getId());
}
new NetworkCleaner().run(network);
new NetworkWriter(network).write(transitNetworkFile);
//new TransitScheduleWriter(scenario.getTransitSchedule()).writeFile(transitScheduleWithNetworkFile);
}
public static void main(String[] args)
{
//String visumFile = "d:/Google Drive/Poznan/Visum_2014/network/network_ver.4.net";
//String visumFile = "d:/GoogleDrive/Poznan/Visum_2014/network/network_ver.5_(33N).net";
String visumFile = "d:/GoogleDrive/Poznan/Visum_2014/network/A ZTM.net";
String outDir = "d:/PP-rad/poznan/test/";
String transitScheduleWithNetworkFile = outDir + "transitSchedule.xml";
String transitNetworkFile = outDir + "pt_network.xml";
String vehicleFile = outDir + "pt_vehicles.xml";
go(visumFile, transitScheduleWithNetworkFile, transitNetworkFile, vehicleFile);
}
}
| younghai/matsim | playgrounds/michalm/src/main/java/playground/michalm/poznan/supply/CreatePoznanPT.java | 1,635 | // 6D_zewn;dostawcze_zewn;PrT;1.000 | line_comment | pl | package playground.michalm.poznan.supply;
import java.util.*;
import org.matsim.api.core.v01.*;
import org.matsim.api.core.v01.network.Node;
import org.matsim.core.config.*;
import org.matsim.core.network.*;
import org.matsim.core.network.algorithms.NetworkCleaner;
import org.matsim.core.scenario.ScenarioUtils;
import org.matsim.pt.transitSchedule.TransitScheduleWriterV1;
import org.matsim.pt.utils.CreatePseudoNetwork;
import org.matsim.vehicles.VehicleWriterV1;
import org.matsim.visum.*;
import playground.mrieser.pt.converter.Visum2TransitSchedule;
public class CreatePoznanPT
{
public static void go(String visumFile, String transitScheduleWithNetworkFile,
String transitNetworkFile, String vehicleFile)
{
Config config = ConfigUtils.createConfig();
config.transit().setUseTransit(true);
config.scenario().setUseVehicles(true);
Scenario scenario = ScenarioUtils.createScenario(config);
final VisumNetwork vNetwork = new VisumNetwork();
new VisumNetworkReader(vNetwork).read(visumFile);
Visum2TransitSchedule converter = new Visum2TransitSchedule(vNetwork,
scenario.getTransitSchedule(), scenario.getTransitVehicles());
// $TSYS:CODE;NAME;TYPE;PCU
// 1S;osobowe;PrT;1.000
// 2D;dostawcze;PrT;1.000
// 3C;ciężarowe;PrT;2.500
// 4R;Rower;PrT;1.000
// 5S_zewn;osobowe_zewn;PrT;1.000
// 6D_ze<SUF>
// 7C_zewn;ciężarowe_zewn;PrT;2.000
// 8Cc_zewn;ciężarowe ciężkie_zewn;PrT;3.000
// A;Autobusy ZTM;PuT;1.000
// AT;Tramwaj;PuT;1.000
// KP;Komunikacja podmiejska;PuT;1.000
// TKR;Kolej Regionalna;PuT;1.000
// TKS;Kolej IC;PuT;1.000
// U;Przewozy_PKS;PuT;1.000
// UAM;Autobus marketowy;PuT;1.000
// W;Przejścia piesze;PuTWalk;1.000
// WP;Pieszo;PuTWalk;1.000
// WP-2;Pieszo-2;PuT;1.000
converter.registerTransportMode("S", TransportMode.car);
converter.registerTransportMode("D", TransportMode.car);
converter.registerTransportMode("C", TransportMode.car);
converter.registerTransportMode("R", TransportMode.bike);
converter.registerTransportMode("S_zewn", TransportMode.car);
converter.registerTransportMode("D_zewn", TransportMode.car);
converter.registerTransportMode("C_zewn", TransportMode.car);
converter.registerTransportMode("Cc_zewn", TransportMode.car);
converter.registerTransportMode("A", TransportMode.pt);
converter.registerTransportMode("AT", TransportMode.pt);
converter.registerTransportMode("KP", TransportMode.pt);
converter.registerTransportMode("TKR", TransportMode.pt);
converter.registerTransportMode("TKS", TransportMode.pt);
converter.registerTransportMode("U", TransportMode.pt);
converter.registerTransportMode("UAM", TransportMode.pt);
converter.registerTransportMode("W", TransportMode.walk);
converter.registerTransportMode("WP", TransportMode.transit_walk);
converter.registerTransportMode("WP-2", TransportMode.transit_walk);
converter.convert();
new TransitScheduleWriterV1(scenario.getTransitSchedule())
.write(transitScheduleWithNetworkFile);
new VehicleWriterV1(scenario.getTransitVehicles()).writeFile(vehicleFile);
NetworkImpl network = NetworkImpl.createNetwork();
new CreatePseudoNetwork(scenario.getTransitSchedule(), network, "tr_").createNetwork();
new NetworkCleaner().run(network);
List<Node> nodesToRemove = new ArrayList<>();
for (Node n : network.getNodes().values()) {
if (n.getInLinks().size() == 0 && n.getOutLinks().size() == 0) {
nodesToRemove.add(n);
}
}
for (Node n : nodesToRemove) {
network.removeNode(n.getId());
}
new NetworkCleaner().run(network);
new NetworkWriter(network).write(transitNetworkFile);
//new TransitScheduleWriter(scenario.getTransitSchedule()).writeFile(transitScheduleWithNetworkFile);
}
public static void main(String[] args)
{
//String visumFile = "d:/Google Drive/Poznan/Visum_2014/network/network_ver.4.net";
//String visumFile = "d:/GoogleDrive/Poznan/Visum_2014/network/network_ver.5_(33N).net";
String visumFile = "d:/GoogleDrive/Poznan/Visum_2014/network/A ZTM.net";
String outDir = "d:/PP-rad/poznan/test/";
String transitScheduleWithNetworkFile = outDir + "transitSchedule.xml";
String transitNetworkFile = outDir + "pt_network.xml";
String vehicleFile = outDir + "pt_vehicles.xml";
go(visumFile, transitScheduleWithNetworkFile, transitNetworkFile, vehicleFile);
}
}
|
162287_0 | package com.soa.servlet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.stream.Collectors;
@WebServlet("/number")
public class NumbersServlet extends HttpServlet {
//"zadanie przeczytać of jsp"
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter writer = response.getWriter();
String[] numbers = request.getParameterValues("number");
if (numbers == null || numbers.length != 5) {
writer.append("Wrong number of parameters.");
return;
}
Double average = Arrays.stream(numbers)
.mapToDouble(Double::valueOf)
.average()
.orElse(0);
writer.append(average.toString());
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter writer = response.getWriter();
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
try {
String s = request.getParameterMap().values().stream()
.flatMap(Arrays::stream)
.mapToDouble(Double::valueOf)
.boxed()
.sorted(Double::compareTo)
.map(Object::toString)
.collect(Collectors.joining(", "));
writer.append(s);
} catch (NumberFormatException e) {
writer.append("Wrong number formatting");
}
}
}
| yurii-piets/soa-course | lab2/src/main/java/com/soa/servlet/NumbersServlet.java | 455 | //"zadanie przeczytać of jsp" | line_comment | pl | package com.soa.servlet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.stream.Collectors;
@WebServlet("/number")
public class NumbersServlet extends HttpServlet {
//"zada<SUF>
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter writer = response.getWriter();
String[] numbers = request.getParameterValues("number");
if (numbers == null || numbers.length != 5) {
writer.append("Wrong number of parameters.");
return;
}
Double average = Arrays.stream(numbers)
.mapToDouble(Double::valueOf)
.average()
.orElse(0);
writer.append(average.toString());
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter writer = response.getWriter();
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
try {
String s = request.getParameterMap().values().stream()
.flatMap(Arrays::stream)
.mapToDouble(Double::valueOf)
.boxed()
.sorted(Double::compareTo)
.map(Object::toString)
.collect(Collectors.joining(", "));
writer.append(s);
} catch (NumberFormatException e) {
writer.append("Wrong number formatting");
}
}
}
|
163477_2 | package com.example.marcin.nudzimisie.libraries;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.example.marcin.nudzimisie.Constants;
import com.example.marcin.nudzimisie.JSONParser;
import com.example.marcin.nudzimisie.Login;
import com.example.marcin.nudzimisie.R;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
public class MyLibrary {
//hashuje hasło do SHA1
public static String encryptPasswordSHA1(String password)
{
String sha1 = "";
try
{
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(password.getBytes("UTF-8"));
sha1 = byteToHex(crypt.digest());
}
catch(NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
return sha1;
}
//potrzebne do funkcji endryptPassword
private static String byteToHex(final byte[] hash)
{
Formatter formatter = new Formatter();
for (byte b : hash)
{
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
//sprawdza czy zapisane dane uzytkownika sa poprawne, jak nie sa to usuwa sharedpref i przechodzi do loginu, NA WEJSCIU ACTIVITY CONTEXT VIEW (nazwaklasy.this)
public static void checkPass(final Context ctx){
new AsyncTask<Void, Void, Void>(){
protected Void doInBackground(Void... params) {
int success;
SharedPreferences userDataSharedPref = ctx.getSharedPreferences(Constants.USER_DATA_PREF_FILE, Context.MODE_PRIVATE);
JSONParser jsonParser = new JSONParser();
try {
// Building Parameters
List<NameValuePair> paramsL = new ArrayList<NameValuePair>();
paramsL.add(new BasicNameValuePair(Constants.LOGIN_API_KEY, userDataSharedPref.getString(Constants.USERNAME_PREF_KEY, null)));
paramsL.add(new BasicNameValuePair(Constants.PASSWORD_API_KEY, userDataSharedPref.getString(Constants.PASSWORD_SHA1_PREF_KEY, null)));
Log.d("request!", "starting static SSSSSSSSSSSSSSSSSSS");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
Constants.LOGIN_URL, "POST", paramsL);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(Constants.SUCCESS_API_KEY);
if (success == 1) {
Log.d("Dane poprawne", "OKKKKKKKKKKKKKKKKKKKKKKKKKKKK");
}else{
SharedPreferences.Editor editor = userDataSharedPref.edit();
editor.clear();
editor.commit();
Intent i = new Intent(ctx, Login.class);
((Activity) ctx).finish();
ctx.startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
//sprawdza czy telefon ma połączenie z internetem, trzeba przekazać kontekst
public static boolean isOnline(Context context){
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
int duration = Toast.LENGTH_SHORT;
String message = context.getString(R.string.no_internet_to);
Toast toast = Toast.makeText(context, message, duration);
toast.show();
return false;
}
}
| zadadam/NudziMiSie | app/src/main/java/com/example/marcin/nudzimisie/libraries/MyLibrary.java | 1,302 | //sprawdza czy zapisane dane uzytkownika sa poprawne, jak nie sa to usuwa sharedpref i przechodzi do loginu, NA WEJSCIU ACTIVITY CONTEXT VIEW (nazwaklasy.this) | line_comment | pl | package com.example.marcin.nudzimisie.libraries;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.example.marcin.nudzimisie.Constants;
import com.example.marcin.nudzimisie.JSONParser;
import com.example.marcin.nudzimisie.Login;
import com.example.marcin.nudzimisie.R;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
public class MyLibrary {
//hashuje hasło do SHA1
public static String encryptPasswordSHA1(String password)
{
String sha1 = "";
try
{
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(password.getBytes("UTF-8"));
sha1 = byteToHex(crypt.digest());
}
catch(NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
return sha1;
}
//potrzebne do funkcji endryptPassword
private static String byteToHex(final byte[] hash)
{
Formatter formatter = new Formatter();
for (byte b : hash)
{
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
//spraw<SUF>
public static void checkPass(final Context ctx){
new AsyncTask<Void, Void, Void>(){
protected Void doInBackground(Void... params) {
int success;
SharedPreferences userDataSharedPref = ctx.getSharedPreferences(Constants.USER_DATA_PREF_FILE, Context.MODE_PRIVATE);
JSONParser jsonParser = new JSONParser();
try {
// Building Parameters
List<NameValuePair> paramsL = new ArrayList<NameValuePair>();
paramsL.add(new BasicNameValuePair(Constants.LOGIN_API_KEY, userDataSharedPref.getString(Constants.USERNAME_PREF_KEY, null)));
paramsL.add(new BasicNameValuePair(Constants.PASSWORD_API_KEY, userDataSharedPref.getString(Constants.PASSWORD_SHA1_PREF_KEY, null)));
Log.d("request!", "starting static SSSSSSSSSSSSSSSSSSS");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
Constants.LOGIN_URL, "POST", paramsL);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(Constants.SUCCESS_API_KEY);
if (success == 1) {
Log.d("Dane poprawne", "OKKKKKKKKKKKKKKKKKKKKKKKKKKKK");
}else{
SharedPreferences.Editor editor = userDataSharedPref.edit();
editor.clear();
editor.commit();
Intent i = new Intent(ctx, Login.class);
((Activity) ctx).finish();
ctx.startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
//sprawdza czy telefon ma połączenie z internetem, trzeba przekazać kontekst
public static boolean isOnline(Context context){
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
int duration = Toast.LENGTH_SHORT;
String message = context.getString(R.string.no_internet_to);
Toast toast = Toast.makeText(context, message, duration);
toast.show();
return false;
}
}
|
37340_39 | /*
* 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 wwptest;
//import static com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type.Int;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import org.pcj.*;
//import wwptest.WWPtest.Shared;
/**
*
* @author adam
*/
@RegisterStorage(WWPtest.Shared.class)
public class WWPtest implements StartPoint {
static String btsFile = "C:\\Users\\Marianna\\Desktop\\bts2.txt";
static String bpFile = "C:\\Users\\Marianna\\Desktop\\bp_short.txt";
static String terFile = "C:\\Users\\Marianna\\Desktop\\terytoria.txt";
@Storage(WWPtest.class)
enum Shared {
adresy,
terytorium,
dlugosc,
sciezkiZb,
domy
}
ArrayList<dom> adresy;
ArrayList<ArrayList<Punkt>> sciezkiZb;
double dlugosc;
int terytorium;
int domy;
/**
*
* @return
*/
public static ArrayList<Integer> readTeryt() {
ArrayList<Integer> t = new ArrayList<Integer>();
Scanner sc = null;
try {
sc = new Scanner(new File(WWPtest.terFile));
} catch (FileNotFoundException ex) {
System.out.println(ex);
System.out.println("Error");
}
while (sc.hasNextLine()) {
if(!sc.hasNextInt())
break;
int gmina = sc.nextInt();
t.add(gmina);
}
return t;
}
public static ArrayList<BTS> readBTS() {
ArrayList<BTS> listBts = new ArrayList<BTS>();
Scanner sc = null;
try {
sc = new Scanner(new File(WWPtest.btsFile));
} catch (FileNotFoundException ex) {
System.out.println(ex);
System.out.println("Error");
}
while (sc.hasNextLine()) {
if(!sc.hasNextInt())
break;
int gmina = sc.nextInt();
//System.out.println(gmina);
int terc = sc.nextInt();
//System.out.println(terc);
int typTerenu = sc.nextInt();
//System.out.println(typTerenu);
double lon = sc.nextDouble();
double lat = sc.nextDouble();
BTS b = new BTS(gmina, terc, typTerenu, lon, lat);
listBts.add(b);
}
return listBts;
}
public static ArrayList<dom> readDom(int goodTerc) {
ArrayList<dom> listDom = new ArrayList<dom>();
Scanner sc = null;
try {
sc = new Scanner(new File(WWPtest.bpFile));
} catch (FileNotFoundException ex) {
System.out.println(ex);
System.out.println("Error");
}
while (sc.hasNextLine()) {
if(!sc.hasNextInt())
break;
int terc = sc.nextInt();
int gmina = sc.nextInt();
int typGminy = sc.nextInt();
int simc = sc.nextInt();
int ulica = sc.nextInt();
double lat = sc.nextDouble();
double lon = sc.nextDouble();
if(terc == goodTerc) {
//System.out.println(terc);
dom b = new dom(terc, gmina, typGminy, simc, ulica, lon, lat);
listDom.add(b);
}
}
return listDom;
}
public static Map readMapDom() {
Map terytDom = new HashMap();
Scanner sc = null;
try {
sc = new Scanner(new File(WWPtest.bpFile));
} catch (FileNotFoundException ex) {
System.out.println(ex);
System.out.println("Error");
}
while (sc.hasNextLine()) {
if(!sc.hasNextInt())
break;
int terc = sc.nextInt();
int gmina = sc.nextInt();
int typGminy = sc.nextInt();
int simc = sc.nextInt();
int ulica = sc.nextInt();
double lat = sc.nextDouble();
double lon = sc.nextDouble();
//System.out.println(terc);
dom b = new dom(terc, gmina, typGminy, simc, ulica, lon, lat);
if(terytDom.containsKey(terc)) {
((ArrayList<dom>) terytDom.get(terc)).add(b);
} else {
ArrayList<dom> l = new ArrayList<dom>();
l.add(b);
terytDom.put(terc, l);
}
}
return terytDom;
}
public static double calcSwiatlowod(ArrayList<ArrayList<Punkt>> sciezki) {
double l = 0.0;
for(ArrayList<Punkt> s : sciezki) {
for(int i = 1; i < s.size(); ++i) {
l += s.get(i).distance(s.get(i-1));
}
}
return l / 1000.0; // wynik w kilometrach
}
public static double distFrom(double lat1, double lng1, double lat2, double lng2) {
// wziete z
// http://stackoverflow.com/questions/837872/calculate-distance-in-meters-when-you-know-longitude-and-latitude-in-java
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double dist = (double) (earthRadius * c);
return dist;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
String nodes[] = {"localhost","localhost","localhost","localhost","localhost","localhost","localhost","localhost"};
// PCJ.deploy(WWPtest.class, new NodesDescription("nodes.txt"));
PCJ.deploy(WWPtest.class, new NodesDescription(nodes));
}
@Override
public void main() {
// zakaldamy, ze kazdym terytorium istnieje chociaz jeden BTS !!!
int terc = 201011; // terytorium, ktore sprawdzamy
ArrayList<BTS> listBts;
ArrayList<dom> listDom;
ArrayList<Integer> listTeryt;
Map domyMap;
listTeryt = readTeryt();
terc = listTeryt.get(PCJ.myId());
//System.out.println(terc);
listBts = readBTS(); // kazdy dom sprawdza liste btsow tylko raz
if(PCJ.myId() == 0) {
domyMap = readMapDom();
for(int i = 0; i < PCJ.threadCount(); ++i){
int tercN = listTeryt.get(i);
ArrayList<dom> dl = (ArrayList<dom>) domyMap.get(tercN);
PCJ.put(dl, i, Shared.adresy);
PCJ.put(tercN, i, Shared.terytorium);
}
}
PCJ.barrier();
listDom = adresy;
domy = listDom.size();
//System.out.println(listBts.size());
//System.out.println(listDom.size());
ArrayList<ArrayList<Punkt>> sciezki = new ArrayList<ArrayList<Punkt>>();
Map domDist = new HashMap(); // lista odleglosci dom najbliszy BTS
Map domBts = new HashMap(); // lista bts'ow najbliszych do domu
// szukamy jaka jest najkrotsza droga do BTS'a
for(dom d: listDom) {
double distMin = 100000.0;
for(BTS b: listBts) {
double dist;
dist = d.distance(b);
if (dist < distMin) {
distMin = dist;
domDist.put(d, dist);
domBts.put(d, b);
}
}
}
if(listBts.isEmpty()) {
System.out.println(PCJ.myId() + " " + terc + " " + "No BTS!");
return;
}
// kazdy punkt rozwazamy tylko raz
// albo podpinamy do BTS'a albo wysylamy do innego wezla
for(dom d : listDom) {
double distBest = (double) domDist.get(d);
double bestSciezkaDist = 100000.0;
boolean istniejeSciezka = false;
int bestIndex = -1;
for(int i = 0; i < sciezki.size(); ++i) {
double dist = -1.0;
dom dd;
dd = (dom) sciezki.get(i).get(sciezki.get(i).size()-1);
dist = dd.distance(d); // zupelnie jak java script
//System.out.println(dist);
//System.out.println(dd.lon + " " + dd.lat + " " +d.lon + " " + d.lat);
//System.out.println(distFrom(dd.lon, dd.lat, d.lon, d.lat));
// python lepszy
if (dist < bestSciezkaDist) {
bestSciezkaDist= dist;
}
if (dist < distBest) {
istniejeSciezka = true;
distBest = dist;
bestIndex = i;
}
}
//System.out.println(distBest + " " + bestSciezkaDist);
if(istniejeSciezka) {
sciezki.get(bestIndex).add(d);
} else {
ArrayList<Punkt> nowySwiatlowod = new ArrayList<Punkt>();
nowySwiatlowod.add((BTS) domBts.get(d));
nowySwiatlowod.add(d);
sciezki.add(nowySwiatlowod);
}
}
//for(ArrayList<Punkt> s : sciezki) {
// System.out.println(s.size());
//}
dlugosc = calcSwiatlowod(sciezki);
sciezkiZb = sciezki;
System.err.println("\t Skonczylem:" + PCJ.myId());
PCJ.barrier();
//System.out.println("\t" + PCJ.myId() + " " + terc + " " + calcSwiatlowod(sciezki) + " " + listDom.size());
ArrayList<Integer> zT = new ArrayList<Integer>();
ArrayList<Double> zDl = new ArrayList<Double>();
ArrayList<ArrayList<ArrayList<Punkt>>> zSciezki = new ArrayList<ArrayList<ArrayList<Punkt>>>();
ArrayList<Integer> zDomy = new ArrayList<Integer>();
if(PCJ.myId() == 0) {
for(int i = 0; i < PCJ.threadCount(); ++i){
zT.add((Integer) PCJ.get(i, Shared.terytorium));
zDl.add((Double) PCJ.get(i, Shared.dlugosc));
zSciezki.add((ArrayList<ArrayList<Punkt>>) PCJ.get(i, Shared.sciezkiZb));
zDomy.add((Integer) PCJ.get(i, Shared.domy));
//PCJ.barrier();
}
for(int i = 0; i < PCJ.threadCount(); ++i) {
System.err.println("--" +i + " " + zT.get(i) + " " + zDl.get(i) + " " + zDomy.get(i));
}
}
//System.out.println(PCJ.myId() + " " + terc + " " + calcSwiatlowod(sciezki) + " " + listDom.size());
// generowanie Wyniku
if(PCJ.myId() == 0) {
double calaDlugosc = 0.0;
for(int i = 0; i < zDl.size(); ++i) {
calaDlugosc += (Double) zDl.get(i);
}
System.err.println("++++ " + calaDlugosc + " ++++");
}
if(PCJ.myId() == 0) {
int maxReg = 0;
double dlugoscS = 0.0;
for(int i = 0; i < PCJ.threadCount(); ++i) {
dlugoscS += (Double) zDl.get(i);
if(dlugoscS > 1000000.0)
break;
maxReg = i;
}
maxReg = maxReg + 1;
System.out.println(maxReg-1); // ilosc odcinkow
for(int i = 0; i < maxReg; ++i) {
int domy = (int) zDomy.get(i);
int stacje = (int) zSciezki.get(i).size();
int segmenty = (int) zSciezki.get(i).size();
System.out.println(domy + " " + stacje + " " + odcinki);
for(int j = 0; j < zSciezki.get(i).size(); ++j) {
for(int k = 1; k < zSciezki.get(i).get(j).size(); ++k){
dom d = (dom) zSciezki.get(i).get(j).get(k);
System.out.println(d.getLat() + " " +d.getLon());
}
}
// stacje - tu powinnismy usunac duplikaty - za malo czasu sorry
for(int j = 0; j < zSciezki.get(i).size(); ++j) {
dom d = (dom) zSciezki.get(i).get(j).get(0);
System.out.println(d.getLat() + " " +d.getLon());
}
// odcinki
for(int j = 0; j < zSciezki.get(i).size(); ++j) {
for(int k = 0; k < zSciezki.get(i).get(j).size(); ++k){
dom d = (dom) zSciezki.get(i).get(j).get(k);
System.out.print(d.getLat() + " " +d.getLon() + " ");
}
System.out.println();
}
}
}
}
}
| zadadam/WWP | WWPtest.java | 4,226 | // ilosc odcinkow | 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 wwptest;
//import static com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type.Int;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import org.pcj.*;
//import wwptest.WWPtest.Shared;
/**
*
* @author adam
*/
@RegisterStorage(WWPtest.Shared.class)
public class WWPtest implements StartPoint {
static String btsFile = "C:\\Users\\Marianna\\Desktop\\bts2.txt";
static String bpFile = "C:\\Users\\Marianna\\Desktop\\bp_short.txt";
static String terFile = "C:\\Users\\Marianna\\Desktop\\terytoria.txt";
@Storage(WWPtest.class)
enum Shared {
adresy,
terytorium,
dlugosc,
sciezkiZb,
domy
}
ArrayList<dom> adresy;
ArrayList<ArrayList<Punkt>> sciezkiZb;
double dlugosc;
int terytorium;
int domy;
/**
*
* @return
*/
public static ArrayList<Integer> readTeryt() {
ArrayList<Integer> t = new ArrayList<Integer>();
Scanner sc = null;
try {
sc = new Scanner(new File(WWPtest.terFile));
} catch (FileNotFoundException ex) {
System.out.println(ex);
System.out.println("Error");
}
while (sc.hasNextLine()) {
if(!sc.hasNextInt())
break;
int gmina = sc.nextInt();
t.add(gmina);
}
return t;
}
public static ArrayList<BTS> readBTS() {
ArrayList<BTS> listBts = new ArrayList<BTS>();
Scanner sc = null;
try {
sc = new Scanner(new File(WWPtest.btsFile));
} catch (FileNotFoundException ex) {
System.out.println(ex);
System.out.println("Error");
}
while (sc.hasNextLine()) {
if(!sc.hasNextInt())
break;
int gmina = sc.nextInt();
//System.out.println(gmina);
int terc = sc.nextInt();
//System.out.println(terc);
int typTerenu = sc.nextInt();
//System.out.println(typTerenu);
double lon = sc.nextDouble();
double lat = sc.nextDouble();
BTS b = new BTS(gmina, terc, typTerenu, lon, lat);
listBts.add(b);
}
return listBts;
}
public static ArrayList<dom> readDom(int goodTerc) {
ArrayList<dom> listDom = new ArrayList<dom>();
Scanner sc = null;
try {
sc = new Scanner(new File(WWPtest.bpFile));
} catch (FileNotFoundException ex) {
System.out.println(ex);
System.out.println("Error");
}
while (sc.hasNextLine()) {
if(!sc.hasNextInt())
break;
int terc = sc.nextInt();
int gmina = sc.nextInt();
int typGminy = sc.nextInt();
int simc = sc.nextInt();
int ulica = sc.nextInt();
double lat = sc.nextDouble();
double lon = sc.nextDouble();
if(terc == goodTerc) {
//System.out.println(terc);
dom b = new dom(terc, gmina, typGminy, simc, ulica, lon, lat);
listDom.add(b);
}
}
return listDom;
}
public static Map readMapDom() {
Map terytDom = new HashMap();
Scanner sc = null;
try {
sc = new Scanner(new File(WWPtest.bpFile));
} catch (FileNotFoundException ex) {
System.out.println(ex);
System.out.println("Error");
}
while (sc.hasNextLine()) {
if(!sc.hasNextInt())
break;
int terc = sc.nextInt();
int gmina = sc.nextInt();
int typGminy = sc.nextInt();
int simc = sc.nextInt();
int ulica = sc.nextInt();
double lat = sc.nextDouble();
double lon = sc.nextDouble();
//System.out.println(terc);
dom b = new dom(terc, gmina, typGminy, simc, ulica, lon, lat);
if(terytDom.containsKey(terc)) {
((ArrayList<dom>) terytDom.get(terc)).add(b);
} else {
ArrayList<dom> l = new ArrayList<dom>();
l.add(b);
terytDom.put(terc, l);
}
}
return terytDom;
}
public static double calcSwiatlowod(ArrayList<ArrayList<Punkt>> sciezki) {
double l = 0.0;
for(ArrayList<Punkt> s : sciezki) {
for(int i = 1; i < s.size(); ++i) {
l += s.get(i).distance(s.get(i-1));
}
}
return l / 1000.0; // wynik w kilometrach
}
public static double distFrom(double lat1, double lng1, double lat2, double lng2) {
// wziete z
// http://stackoverflow.com/questions/837872/calculate-distance-in-meters-when-you-know-longitude-and-latitude-in-java
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double dist = (double) (earthRadius * c);
return dist;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
String nodes[] = {"localhost","localhost","localhost","localhost","localhost","localhost","localhost","localhost"};
// PCJ.deploy(WWPtest.class, new NodesDescription("nodes.txt"));
PCJ.deploy(WWPtest.class, new NodesDescription(nodes));
}
@Override
public void main() {
// zakaldamy, ze kazdym terytorium istnieje chociaz jeden BTS !!!
int terc = 201011; // terytorium, ktore sprawdzamy
ArrayList<BTS> listBts;
ArrayList<dom> listDom;
ArrayList<Integer> listTeryt;
Map domyMap;
listTeryt = readTeryt();
terc = listTeryt.get(PCJ.myId());
//System.out.println(terc);
listBts = readBTS(); // kazdy dom sprawdza liste btsow tylko raz
if(PCJ.myId() == 0) {
domyMap = readMapDom();
for(int i = 0; i < PCJ.threadCount(); ++i){
int tercN = listTeryt.get(i);
ArrayList<dom> dl = (ArrayList<dom>) domyMap.get(tercN);
PCJ.put(dl, i, Shared.adresy);
PCJ.put(tercN, i, Shared.terytorium);
}
}
PCJ.barrier();
listDom = adresy;
domy = listDom.size();
//System.out.println(listBts.size());
//System.out.println(listDom.size());
ArrayList<ArrayList<Punkt>> sciezki = new ArrayList<ArrayList<Punkt>>();
Map domDist = new HashMap(); // lista odleglosci dom najbliszy BTS
Map domBts = new HashMap(); // lista bts'ow najbliszych do domu
// szukamy jaka jest najkrotsza droga do BTS'a
for(dom d: listDom) {
double distMin = 100000.0;
for(BTS b: listBts) {
double dist;
dist = d.distance(b);
if (dist < distMin) {
distMin = dist;
domDist.put(d, dist);
domBts.put(d, b);
}
}
}
if(listBts.isEmpty()) {
System.out.println(PCJ.myId() + " " + terc + " " + "No BTS!");
return;
}
// kazdy punkt rozwazamy tylko raz
// albo podpinamy do BTS'a albo wysylamy do innego wezla
for(dom d : listDom) {
double distBest = (double) domDist.get(d);
double bestSciezkaDist = 100000.0;
boolean istniejeSciezka = false;
int bestIndex = -1;
for(int i = 0; i < sciezki.size(); ++i) {
double dist = -1.0;
dom dd;
dd = (dom) sciezki.get(i).get(sciezki.get(i).size()-1);
dist = dd.distance(d); // zupelnie jak java script
//System.out.println(dist);
//System.out.println(dd.lon + " " + dd.lat + " " +d.lon + " " + d.lat);
//System.out.println(distFrom(dd.lon, dd.lat, d.lon, d.lat));
// python lepszy
if (dist < bestSciezkaDist) {
bestSciezkaDist= dist;
}
if (dist < distBest) {
istniejeSciezka = true;
distBest = dist;
bestIndex = i;
}
}
//System.out.println(distBest + " " + bestSciezkaDist);
if(istniejeSciezka) {
sciezki.get(bestIndex).add(d);
} else {
ArrayList<Punkt> nowySwiatlowod = new ArrayList<Punkt>();
nowySwiatlowod.add((BTS) domBts.get(d));
nowySwiatlowod.add(d);
sciezki.add(nowySwiatlowod);
}
}
//for(ArrayList<Punkt> s : sciezki) {
// System.out.println(s.size());
//}
dlugosc = calcSwiatlowod(sciezki);
sciezkiZb = sciezki;
System.err.println("\t Skonczylem:" + PCJ.myId());
PCJ.barrier();
//System.out.println("\t" + PCJ.myId() + " " + terc + " " + calcSwiatlowod(sciezki) + " " + listDom.size());
ArrayList<Integer> zT = new ArrayList<Integer>();
ArrayList<Double> zDl = new ArrayList<Double>();
ArrayList<ArrayList<ArrayList<Punkt>>> zSciezki = new ArrayList<ArrayList<ArrayList<Punkt>>>();
ArrayList<Integer> zDomy = new ArrayList<Integer>();
if(PCJ.myId() == 0) {
for(int i = 0; i < PCJ.threadCount(); ++i){
zT.add((Integer) PCJ.get(i, Shared.terytorium));
zDl.add((Double) PCJ.get(i, Shared.dlugosc));
zSciezki.add((ArrayList<ArrayList<Punkt>>) PCJ.get(i, Shared.sciezkiZb));
zDomy.add((Integer) PCJ.get(i, Shared.domy));
//PCJ.barrier();
}
for(int i = 0; i < PCJ.threadCount(); ++i) {
System.err.println("--" +i + " " + zT.get(i) + " " + zDl.get(i) + " " + zDomy.get(i));
}
}
//System.out.println(PCJ.myId() + " " + terc + " " + calcSwiatlowod(sciezki) + " " + listDom.size());
// generowanie Wyniku
if(PCJ.myId() == 0) {
double calaDlugosc = 0.0;
for(int i = 0; i < zDl.size(); ++i) {
calaDlugosc += (Double) zDl.get(i);
}
System.err.println("++++ " + calaDlugosc + " ++++");
}
if(PCJ.myId() == 0) {
int maxReg = 0;
double dlugoscS = 0.0;
for(int i = 0; i < PCJ.threadCount(); ++i) {
dlugoscS += (Double) zDl.get(i);
if(dlugoscS > 1000000.0)
break;
maxReg = i;
}
maxReg = maxReg + 1;
System.out.println(maxReg-1); // ilosc<SUF>
for(int i = 0; i < maxReg; ++i) {
int domy = (int) zDomy.get(i);
int stacje = (int) zSciezki.get(i).size();
int segmenty = (int) zSciezki.get(i).size();
System.out.println(domy + " " + stacje + " " + odcinki);
for(int j = 0; j < zSciezki.get(i).size(); ++j) {
for(int k = 1; k < zSciezki.get(i).get(j).size(); ++k){
dom d = (dom) zSciezki.get(i).get(j).get(k);
System.out.println(d.getLat() + " " +d.getLon());
}
}
// stacje - tu powinnismy usunac duplikaty - za malo czasu sorry
for(int j = 0; j < zSciezki.get(i).size(); ++j) {
dom d = (dom) zSciezki.get(i).get(j).get(0);
System.out.println(d.getLat() + " " +d.getLon());
}
// odcinki
for(int j = 0; j < zSciezki.get(i).size(); ++j) {
for(int k = 0; k < zSciezki.get(i).get(j).size(); ++k){
dom d = (dom) zSciezki.get(i).get(j).get(k);
System.out.print(d.getLat() + " " +d.getLon() + " ");
}
System.out.println();
}
}
}
}
}
|
178137_3 | /*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.i18n.client.impl.cldr;
import com.google.gwt.core.client.JavaScriptObject;
// DO NOT EDIT - GENERATED FROM CLDR DATA
/**
* Localized names for the "dsb" locale.
*/
public class LocalizedNamesImpl_dsb extends LocalizedNamesImpl {
@Override
public String[] loadSortedRegionCodes() {
return new String[] {
"AF",
"AX",
"AL",
"DZ",
"UM",
"AS",
"VI",
"AD",
"AO",
"AI",
"AQ",
"AG",
"AR",
"AM",
"AW",
"AC",
"AU",
"AT",
"AZ",
"BS",
"BH",
"BD",
"BB",
"BE",
"BZ",
"BJ",
"BM",
"BY",
"BT",
"BO",
"BA",
"BW",
"BV",
"BR",
"VG",
"IO",
"BN",
"BG",
"BF",
"BI",
"TD",
"ME",
"CF",
"CZ",
"EA",
"CL",
"CN",
"HR",
"CP",
"CK",
"CI",
"CW",
"CY",
"DK",
"DG",
"DM",
"DO",
"DJ",
"EG",
"EC",
"GQ",
"SV",
"ER",
"EE",
"ET",
"EU",
"EZ",
"FK",
"FO",
"FJ",
"PH",
"FI",
"FR",
"GF",
"PF",
"TF",
"GA",
"GM",
"GE",
"GH",
"GI",
"GN",
"GW",
"CX",
"GD",
"GR",
"GL",
"GP",
"GU",
"GT",
"GG",
"GY",
"HT",
"HM",
"HN",
"HU",
"IN",
"ID",
"IQ",
"IR",
"IE",
"IS",
"IL",
"IT",
"JM",
"JP",
"YE",
"JE",
"JO",
"KY",
"KH",
"CM",
"CA",
"IC",
"CV",
"BQ",
"QA",
"KZ",
"KE",
"KG",
"KI",
"CC",
"CO",
"KM",
"CG",
"CD",
"XK",
"CR",
"CU",
"KW",
"LA",
"LS",
"LV",
"LB",
"LR",
"LY",
"LI",
"LT",
"LU",
"MG",
"MK",
"MY",
"MW",
"MV",
"ML",
"MT",
"IM",
"MA",
"MH",
"MQ",
"MU",
"MR",
"YT",
"MX",
"FM",
"MD",
"MC",
"MN",
"MS",
"MZ",
"MM",
"NA",
"NR",
"NP",
"NE",
"NG",
"NI",
"DE",
"NU",
"NL",
"NF",
"NO",
"NC",
"NZ",
"OM",
"PK",
"PW",
"PS",
"PA",
"PG",
"PY",
"PE",
"PN",
"ZA",
"GS",
"KR",
"SS",
"KP",
"MP",
"EH",
"PL",
"PT",
"PR",
"RE",
"RW",
"RO",
"RU",
"SB",
"ZM",
"WS",
"SM",
"ST",
"SA",
"SN",
"RS",
"SC",
"SL",
"ZW",
"SG",
"SX",
"SO",
"ES",
"LK",
"BL",
"SH",
"KN",
"LC",
"MF",
"PM",
"VC",
"SD",
"SR",
"SJ",
"SZ",
"SE",
"CH",
"SY",
"SK",
"SI",
"TJ",
"TW",
"TZ",
"TH",
"TL",
"TG",
"TK",
"TO",
"TT",
"TA",
"TN",
"TM",
"TR",
"TC",
"TV",
"UG",
"UA",
"UN",
"UY",
"UZ",
"VU",
"VA",
"VE",
"VN",
"WF",
"QO",
"HK",
"MO",
"AE",
"GB",
"US",
};
}
@Override
protected void loadNameMapJava() {
super.loadNameMapJava();
namesMap.put("001", "swět");
namesMap.put("002", "Afrika");
namesMap.put("003", "Pódpołnocna Amerika");
namesMap.put("005", "Pódpołdnjowa Amerika");
namesMap.put("009", "Oceaniska");
namesMap.put("011", "Pódwjacorna Afrika");
namesMap.put("013", "Srjejźna Amerika");
namesMap.put("014", "pódzajtšna Afrika");
namesMap.put("015", "pódpołnocna Afrika");
namesMap.put("017", "srjejźna Afrika");
namesMap.put("018", "pódpołdnjowa Afrika");
namesMap.put("019", "Amerika");
namesMap.put("021", "pódpołnocny ameriski kontinent");
namesMap.put("029", "Karibiska");
namesMap.put("030", "pódzajtšna Azija");
namesMap.put("034", "pódpołdnjowa Azija");
namesMap.put("035", "krotkozajtšna Azija");
namesMap.put("039", "pódpołdnjowa Europa");
namesMap.put("053", "Awstralazija");
namesMap.put("054", "Melaneziska");
namesMap.put("057", "Mikroneziska (kupowy region)");
namesMap.put("061", "Polyneziska");
namesMap.put("142", "Azija");
namesMap.put("143", "centralna Azija");
namesMap.put("145", "pódwjacorna Azija");
namesMap.put("150", "Europa");
namesMap.put("151", "pódzajtšna Europa");
namesMap.put("154", "pódpołnocna Europa");
namesMap.put("155", "pódwjacorna Europa");
namesMap.put("419", "Łatyńska Amerika");
namesMap.put("AC", "Ascension");
namesMap.put("AE", "Zjadnośone arabiske emiraty");
namesMap.put("AG", "Antigua a Barbuda");
namesMap.put("AL", "Albańska");
namesMap.put("AM", "Armeńska");
namesMap.put("AQ", "Antarktis");
namesMap.put("AR", "Argentinska");
namesMap.put("AS", "Ameriska Samoa");
namesMap.put("AT", "Awstriska");
namesMap.put("AU", "Awstralska");
namesMap.put("AX", "Åland");
namesMap.put("AZ", "Azerbajdžan");
namesMap.put("BA", "Bosniska a Hercegowina");
namesMap.put("BD", "Bangladeš");
namesMap.put("BE", "Belgiska");
namesMap.put("BG", "Bulgarska");
namesMap.put("BM", "Bermudy");
namesMap.put("BO", "Boliwiska");
namesMap.put("BQ", "Karibiska Nižozemska");
namesMap.put("BR", "Brazilska");
namesMap.put("BS", "Bahamy");
namesMap.put("BV", "Bouvetowa kupa");
namesMap.put("BY", "Běłoruska");
namesMap.put("CA", "Kanada");
namesMap.put("CC", "Kokosowe kupy");
namesMap.put("CD", "Kongo-Kinshasa");
namesMap.put("CF", "Centralnoafriska republika");
namesMap.put("CG", "Kongo-Brazzaville");
namesMap.put("CH", "Šwicarska");
namesMap.put("CK", "Cookowe kupy");
namesMap.put("CL", "Chilska");
namesMap.put("CM", "Kamerun");
namesMap.put("CO", "Kolumbiska");
namesMap.put("CP", "Clippertonowa kupa");
namesMap.put("CR", "Kosta Rika");
namesMap.put("CU", "Kuba");
namesMap.put("CV", "Kap Verde");
namesMap.put("CX", "Gódowne kupy");
namesMap.put("CY", "Cypriska");
namesMap.put("CZ", "Česka republika");
namesMap.put("DE", "Nimska");
namesMap.put("DJ", "Džibuti");
namesMap.put("DK", "Dańska");
namesMap.put("DM", "Dominika");
namesMap.put("DO", "Dominikańska republika");
namesMap.put("DZ", "Algeriska");
namesMap.put("EA", "Ceuta a Melilla");
namesMap.put("EC", "Ekwador");
namesMap.put("EE", "Estniska");
namesMap.put("EG", "Egyptojska");
namesMap.put("EH", "Pódwjacorna Sahara");
namesMap.put("ER", "Eritreja");
namesMap.put("ES", "Špańska");
namesMap.put("ET", "Etiopiska");
namesMap.put("EU", "Europska unija");
namesMap.put("FI", "Finska");
namesMap.put("FJ", "Fidži");
namesMap.put("FK", "Falklandske kupy");
namesMap.put("FM", "Mikroneziska");
namesMap.put("FO", "Färöje");
namesMap.put("FR", "Francojska");
namesMap.put("GA", "Gabun");
namesMap.put("GB", "Zjadnośone kralejstwo");
namesMap.put("GE", "Georgiska");
namesMap.put("GF", "Francojska Guyana");
namesMap.put("GL", "Grönlandska");
namesMap.put("GM", "Gambija");
namesMap.put("GN", "Gineja");
namesMap.put("GQ", "Ekwatorialna Gineja");
namesMap.put("GR", "Grichiska");
namesMap.put("GS", "Pódpołdnjowa Georgiska a Pódpołdnjowe Sandwichowe kupy");
namesMap.put("GW", "Gineja-Bissau");
namesMap.put("HK", "Wósebna zastojnstwowa cona Hongkong");
namesMap.put("HM", "Heardowa kupa a McDonaldowe kupy");
namesMap.put("HR", "Chorwatska");
namesMap.put("HU", "Hungorska");
namesMap.put("IC", "Kanariske kupy");
namesMap.put("ID", "Indoneziska");
namesMap.put("IE", "Irska");
namesMap.put("IM", "Man");
namesMap.put("IN", "Indiska");
namesMap.put("IO", "Britiski indiskooceaniski teritorium");
namesMap.put("IQ", "Irak");
namesMap.put("IS", "Islandska");
namesMap.put("IT", "Italska");
namesMap.put("JM", "Jamaika");
namesMap.put("JO", "Jordaniska");
namesMap.put("JP", "Japańska");
namesMap.put("KE", "Kenia");
namesMap.put("KG", "Kirgizistan");
namesMap.put("KH", "Kambodža");
namesMap.put("KM", "Komory");
namesMap.put("KN", "St. Kitts a Nevis");
namesMap.put("KP", "Pódpołnocna Koreja");
namesMap.put("KR", "Pódpołdnjowa Koreja");
namesMap.put("KY", "Kajmaniske kupy");
namesMap.put("KZ", "Kazachstan");
namesMap.put("LB", "Libanon");
namesMap.put("LR", "Liberija");
namesMap.put("LT", "Litawska");
namesMap.put("LU", "Luxemburgska");
namesMap.put("LV", "Letiska");
namesMap.put("LY", "Libyska");
namesMap.put("MA", "Marokko");
namesMap.put("MD", "Moldawska");
namesMap.put("ME", "Carna Góra");
namesMap.put("MG", "Madagaskar");
namesMap.put("MH", "Marshallowe kupy");
namesMap.put("MK", "Makedońska");
namesMap.put("MM", "Myanmar");
namesMap.put("MN", "Mongolska");
namesMap.put("MO", "Wósebna zastojnstwowa cona Macao");
namesMap.put("MP", "Pódpołnocne Mariany");
namesMap.put("MR", "Mawretańska");
namesMap.put("MV", "Malediwy");
namesMap.put("MX", "Mexiko");
namesMap.put("MY", "Malajzija");
namesMap.put("MZ", "Mosambik");
namesMap.put("NA", "Namibija");
namesMap.put("NC", "Nowa Kaledoniska");
namesMap.put("NF", "Norfolkowa kupa");
namesMap.put("NG", "Nigerija");
namesMap.put("NI", "Nikaragua");
namesMap.put("NL", "Nižozemska");
namesMap.put("NO", "Norwegska");
namesMap.put("NZ", "Nowoseelandska");
namesMap.put("PF", "Francojska Polyneziska");
namesMap.put("PG", "Papua-Neuguinea");
namesMap.put("PH", "Filipiny");
namesMap.put("PL", "Pólska");
namesMap.put("PM", "St. Pierre a Miquelon");
namesMap.put("PN", "Pitcairnowe kupy");
namesMap.put("PS", "Palestinski awtonomny teritorium");
namesMap.put("PT", "Portugalska");
namesMap.put("QA", "Katar");
namesMap.put("QO", "wenkowna Oceaniska");
namesMap.put("RO", "Rumuńska");
namesMap.put("RS", "Serbiska");
namesMap.put("RU", "Ruska");
namesMap.put("RW", "Ruanda");
namesMap.put("SA", "Saudi-Arabiska");
namesMap.put("SB", "Salomony");
namesMap.put("SC", "Seychelle");
namesMap.put("SE", "Šwedska");
namesMap.put("SG", "Singapur");
namesMap.put("SI", "Słowjeńska");
namesMap.put("SJ", "Svalbard a Jan Mayen");
namesMap.put("SK", "Słowakska");
namesMap.put("SO", "Somalija");
namesMap.put("SR", "Surinamska");
namesMap.put("SS", "Pódpołdnjowy Sudan");
namesMap.put("ST", "São Tomé a Príncipe");
namesMap.put("SY", "Syriska");
namesMap.put("SZ", "Swasiska");
namesMap.put("TC", "Turks a Caicos kupy");
namesMap.put("TD", "Čad");
namesMap.put("TF", "Francojski pódpołdnjowy a antarktiski teritorium");
namesMap.put("TH", "Thailandska");
namesMap.put("TJ", "Tadźikistan");
namesMap.put("TM", "Turkmeniska");
namesMap.put("TN", "Tuneziska");
namesMap.put("TR", "Turkojska");
namesMap.put("TT", "Trinidad a Tobago");
namesMap.put("TZ", "Tansanija");
namesMap.put("UA", "Ukraina");
namesMap.put("UM", "Ameriska Oceaniska");
namesMap.put("US", "Zjadnośone staty Ameriki");
namesMap.put("VA", "Vatikańske město");
namesMap.put("VC", "St. Vincent a Grenadiny");
namesMap.put("VG", "Britiske kněžniske kupy");
namesMap.put("VI", "Ameriske kněžniske kupy");
namesMap.put("WF", "Wallis a Futuna");
namesMap.put("XK", "Kosowo");
namesMap.put("YE", "Jemen");
namesMap.put("ZA", "Pódpołdnjowa Afrika (Republika)");
namesMap.put("ZM", "Sambija");
namesMap.put("ZW", "Simbabwe");
namesMap.put("ZZ", "njeznaty region");
}
@Override
protected JavaScriptObject loadNameMapNative() {
return overrideMap(super.loadNameMapNative(), loadMyNameMap());
}
private native JavaScriptObject loadMyNameMap() /*-{
return {
"001": "swět",
"002": "Afrika",
"003": "Pódpołnocna Amerika",
"005": "Pódpołdnjowa Amerika",
"009": "Oceaniska",
"011": "Pódwjacorna Afrika",
"013": "Srjejźna Amerika",
"014": "pódzajtšna Afrika",
"015": "pódpołnocna Afrika",
"017": "srjejźna Afrika",
"018": "pódpołdnjowa Afrika",
"019": "Amerika",
"021": "pódpołnocny ameriski kontinent",
"029": "Karibiska",
"030": "pódzajtšna Azija",
"034": "pódpołdnjowa Azija",
"035": "krotkozajtšna Azija",
"039": "pódpołdnjowa Europa",
"053": "Awstralazija",
"054": "Melaneziska",
"057": "Mikroneziska (kupowy region)",
"061": "Polyneziska",
"142": "Azija",
"143": "centralna Azija",
"145": "pódwjacorna Azija",
"150": "Europa",
"151": "pódzajtšna Europa",
"154": "pódpołnocna Europa",
"155": "pódwjacorna Europa",
"419": "Łatyńska Amerika",
"AC": "Ascension",
"AE": "Zjadnośone arabiske emiraty",
"AG": "Antigua a Barbuda",
"AL": "Albańska",
"AM": "Armeńska",
"AQ": "Antarktis",
"AR": "Argentinska",
"AS": "Ameriska Samoa",
"AT": "Awstriska",
"AU": "Awstralska",
"AX": "Åland",
"AZ": "Azerbajdžan",
"BA": "Bosniska a Hercegowina",
"BD": "Bangladeš",
"BE": "Belgiska",
"BG": "Bulgarska",
"BM": "Bermudy",
"BO": "Boliwiska",
"BQ": "Karibiska Nižozemska",
"BR": "Brazilska",
"BS": "Bahamy",
"BV": "Bouvetowa kupa",
"BY": "Běłoruska",
"CA": "Kanada",
"CC": "Kokosowe kupy",
"CD": "Kongo-Kinshasa",
"CF": "Centralnoafriska republika",
"CG": "Kongo-Brazzaville",
"CH": "Šwicarska",
"CK": "Cookowe kupy",
"CL": "Chilska",
"CM": "Kamerun",
"CO": "Kolumbiska",
"CP": "Clippertonowa kupa",
"CR": "Kosta Rika",
"CU": "Kuba",
"CV": "Kap Verde",
"CX": "Gódowne kupy",
"CY": "Cypriska",
"CZ": "Česka republika",
"DE": "Nimska",
"DJ": "Džibuti",
"DK": "Dańska",
"DM": "Dominika",
"DO": "Dominikańska republika",
"DZ": "Algeriska",
"EA": "Ceuta a Melilla",
"EC": "Ekwador",
"EE": "Estniska",
"EG": "Egyptojska",
"EH": "Pódwjacorna Sahara",
"ER": "Eritreja",
"ES": "Špańska",
"ET": "Etiopiska",
"EU": "Europska unija",
"FI": "Finska",
"FJ": "Fidži",
"FK": "Falklandske kupy",
"FM": "Mikroneziska",
"FO": "Färöje",
"FR": "Francojska",
"GA": "Gabun",
"GB": "Zjadnośone kralejstwo",
"GE": "Georgiska",
"GF": "Francojska Guyana",
"GL": "Grönlandska",
"GM": "Gambija",
"GN": "Gineja",
"GQ": "Ekwatorialna Gineja",
"GR": "Grichiska",
"GS": "Pódpołdnjowa Georgiska a Pódpołdnjowe Sandwichowe kupy",
"GW": "Gineja-Bissau",
"HK": "Wósebna zastojnstwowa cona Hongkong",
"HM": "Heardowa kupa a McDonaldowe kupy",
"HR": "Chorwatska",
"HU": "Hungorska",
"IC": "Kanariske kupy",
"ID": "Indoneziska",
"IE": "Irska",
"IM": "Man",
"IN": "Indiska",
"IO": "Britiski indiskooceaniski teritorium",
"IQ": "Irak",
"IS": "Islandska",
"IT": "Italska",
"JM": "Jamaika",
"JO": "Jordaniska",
"JP": "Japańska",
"KE": "Kenia",
"KG": "Kirgizistan",
"KH": "Kambodža",
"KM": "Komory",
"KN": "St. Kitts a Nevis",
"KP": "Pódpołnocna Koreja",
"KR": "Pódpołdnjowa Koreja",
"KY": "Kajmaniske kupy",
"KZ": "Kazachstan",
"LB": "Libanon",
"LR": "Liberija",
"LT": "Litawska",
"LU": "Luxemburgska",
"LV": "Letiska",
"LY": "Libyska",
"MA": "Marokko",
"MD": "Moldawska",
"ME": "Carna Góra",
"MG": "Madagaskar",
"MH": "Marshallowe kupy",
"MK": "Makedońska",
"MM": "Myanmar",
"MN": "Mongolska",
"MO": "Wósebna zastojnstwowa cona Macao",
"MP": "Pódpołnocne Mariany",
"MR": "Mawretańska",
"MV": "Malediwy",
"MX": "Mexiko",
"MY": "Malajzija",
"MZ": "Mosambik",
"NA": "Namibija",
"NC": "Nowa Kaledoniska",
"NF": "Norfolkowa kupa",
"NG": "Nigerija",
"NI": "Nikaragua",
"NL": "Nižozemska",
"NO": "Norwegska",
"NZ": "Nowoseelandska",
"PF": "Francojska Polyneziska",
"PG": "Papua-Neuguinea",
"PH": "Filipiny",
"PL": "Pólska",
"PM": "St. Pierre a Miquelon",
"PN": "Pitcairnowe kupy",
"PS": "Palestinski awtonomny teritorium",
"PT": "Portugalska",
"QA": "Katar",
"QO": "wenkowna Oceaniska",
"RO": "Rumuńska",
"RS": "Serbiska",
"RU": "Ruska",
"RW": "Ruanda",
"SA": "Saudi-Arabiska",
"SB": "Salomony",
"SC": "Seychelle",
"SE": "Šwedska",
"SG": "Singapur",
"SI": "Słowjeńska",
"SJ": "Svalbard a Jan Mayen",
"SK": "Słowakska",
"SO": "Somalija",
"SR": "Surinamska",
"SS": "Pódpołdnjowy Sudan",
"ST": "São Tomé a Príncipe",
"SY": "Syriska",
"SZ": "Swasiska",
"TC": "Turks a Caicos kupy",
"TD": "Čad",
"TF": "Francojski pódpołdnjowy a antarktiski teritorium",
"TH": "Thailandska",
"TJ": "Tadźikistan",
"TM": "Turkmeniska",
"TN": "Tuneziska",
"TR": "Turkojska",
"TT": "Trinidad a Tobago",
"TZ": "Tansanija",
"UA": "Ukraina",
"UM": "Ameriska Oceaniska",
"US": "Zjadnośone staty Ameriki",
"VA": "Vatikańske město",
"VC": "St. Vincent a Grenadiny",
"VG": "Britiske kněžniske kupy",
"VI": "Ameriske kněžniske kupy",
"WF": "Wallis a Futuna",
"XK": "Kosowo",
"YE": "Jemen",
"ZA": "Pódpołdnjowa Afrika (Republika)",
"ZM": "Sambija",
"ZW": "Simbabwe",
"ZZ": "njeznaty region"
};
}-*/;
}
| zak905/gwt | user/src/com/google/gwt/i18n/client/impl/cldr/LocalizedNamesImpl_dsb.java | 7,987 | /*-{
return {
"001": "swět",
"002": "Afrika",
"003": "Pódpołnocna Amerika",
"005": "Pódpołdnjowa Amerika",
"009": "Oceaniska",
"011": "Pódwjacorna Afrika",
"013": "Srjejźna Amerika",
"014": "pódzajtšna Afrika",
"015": "pódpołnocna Afrika",
"017": "srjejźna Afrika",
"018": "pódpołdnjowa Afrika",
"019": "Amerika",
"021": "pódpołnocny ameriski kontinent",
"029": "Karibiska",
"030": "pódzajtšna Azija",
"034": "pódpołdnjowa Azija",
"035": "krotkozajtšna Azija",
"039": "pódpołdnjowa Europa",
"053": "Awstralazija",
"054": "Melaneziska",
"057": "Mikroneziska (kupowy region)",
"061": "Polyneziska",
"142": "Azija",
"143": "centralna Azija",
"145": "pódwjacorna Azija",
"150": "Europa",
"151": "pódzajtšna Europa",
"154": "pódpołnocna Europa",
"155": "pódwjacorna Europa",
"419": "Łatyńska Amerika",
"AC": "Ascension",
"AE": "Zjadnośone arabiske emiraty",
"AG": "Antigua a Barbuda",
"AL": "Albańska",
"AM": "Armeńska",
"AQ": "Antarktis",
"AR": "Argentinska",
"AS": "Ameriska Samoa",
"AT": "Awstriska",
"AU": "Awstralska",
"AX": "Åland",
"AZ": "Azerbajdžan",
"BA": "Bosniska a Hercegowina",
"BD": "Bangladeš",
"BE": "Belgiska",
"BG": "Bulgarska",
"BM": "Bermudy",
"BO": "Boliwiska",
"BQ": "Karibiska Nižozemska",
"BR": "Brazilska",
"BS": "Bahamy",
"BV": "Bouvetowa kupa",
"BY": "Běłoruska",
"CA": "Kanada",
"CC": "Kokosowe kupy",
"CD": "Kongo-Kinshasa",
"CF": "Centralnoafriska republika",
"CG": "Kongo-Brazzaville",
"CH": "Šwicarska",
"CK": "Cookowe kupy",
"CL": "Chilska",
"CM": "Kamerun",
"CO": "Kolumbiska",
"CP": "Clippertonowa kupa",
"CR": "Kosta Rika",
"CU": "Kuba",
"CV": "Kap Verde",
"CX": "Gódowne kupy",
"CY": "Cypriska",
"CZ": "Česka republika",
"DE": "Nimska",
"DJ": "Džibuti",
"DK": "Dańska",
"DM": "Dominika",
"DO": "Dominikańska republika",
"DZ": "Algeriska",
"EA": "Ceuta a Melilla",
"EC": "Ekwador",
"EE": "Estniska",
"EG": "Egyptojska",
"EH": "Pódwjacorna Sahara",
"ER": "Eritreja",
"ES": "Špańska",
"ET": "Etiopiska",
"EU": "Europska unija",
"FI": "Finska",
"FJ": "Fidži",
"FK": "Falklandske kupy",
"FM": "Mikroneziska",
"FO": "Färöje",
"FR": "Francojska",
"GA": "Gabun",
"GB": "Zjadnośone kralejstwo",
"GE": "Georgiska",
"GF": "Francojska Guyana",
"GL": "Grönlandska",
"GM": "Gambija",
"GN": "Gineja",
"GQ": "Ekwatorialna Gineja",
"GR": "Grichiska",
"GS": "Pódpołdnjowa Georgiska a Pódpołdnjowe Sandwichowe kupy",
"GW": "Gineja-Bissau",
"HK": "Wósebna zastojnstwowa cona Hongkong",
"HM": "Heardowa kupa a McDonaldowe kupy",
"HR": "Chorwatska",
"HU": "Hungorska",
"IC": "Kanariske kupy",
"ID": "Indoneziska",
"IE": "Irska",
"IM": "Man",
"IN": "Indiska",
"IO": "Britiski indiskooceaniski teritorium",
"IQ": "Irak",
"IS": "Islandska",
"IT": "Italska",
"JM": "Jamaika",
"JO": "Jordaniska",
"JP": "Japańska",
"KE": "Kenia",
"KG": "Kirgizistan",
"KH": "Kambodža",
"KM": "Komory",
"KN": "St. Kitts a Nevis",
"KP": "Pódpołnocna Koreja",
"KR": "Pódpołdnjowa Koreja",
"KY": "Kajmaniske kupy",
"KZ": "Kazachstan",
"LB": "Libanon",
"LR": "Liberija",
"LT": "Litawska",
"LU": "Luxemburgska",
"LV": "Letiska",
"LY": "Libyska",
"MA": "Marokko",
"MD": "Moldawska",
"ME": "Carna Góra",
"MG": "Madagaskar",
"MH": "Marshallowe kupy",
"MK": "Makedońska",
"MM": "Myanmar",
"MN": "Mongolska",
"MO": "Wósebna zastojnstwowa cona Macao",
"MP": "Pódpołnocne Mariany",
"MR": "Mawretańska",
"MV": "Malediwy",
"MX": "Mexiko",
"MY": "Malajzija",
"MZ": "Mosambik",
"NA": "Namibija",
"NC": "Nowa Kaledoniska",
"NF": "Norfolkowa kupa",
"NG": "Nigerija",
"NI": "Nikaragua",
"NL": "Nižozemska",
"NO": "Norwegska",
"NZ": "Nowoseelandska",
"PF": "Francojska Polyneziska",
"PG": "Papua-Neuguinea",
"PH": "Filipiny",
"PL": "Pólska",
"PM": "St. Pierre a Miquelon",
"PN": "Pitcairnowe kupy",
"PS": "Palestinski awtonomny teritorium",
"PT": "Portugalska",
"QA": "Katar",
"QO": "wenkowna Oceaniska",
"RO": "Rumuńska",
"RS": "Serbiska",
"RU": "Ruska",
"RW": "Ruanda",
"SA": "Saudi-Arabiska",
"SB": "Salomony",
"SC": "Seychelle",
"SE": "Šwedska",
"SG": "Singapur",
"SI": "Słowjeńska",
"SJ": "Svalbard a Jan Mayen",
"SK": "Słowakska",
"SO": "Somalija",
"SR": "Surinamska",
"SS": "Pódpołdnjowy Sudan",
"ST": "São Tomé a Príncipe",
"SY": "Syriska",
"SZ": "Swasiska",
"TC": "Turks a Caicos kupy",
"TD": "Čad",
"TF": "Francojski pódpołdnjowy a antarktiski teritorium",
"TH": "Thailandska",
"TJ": "Tadźikistan",
"TM": "Turkmeniska",
"TN": "Tuneziska",
"TR": "Turkojska",
"TT": "Trinidad a Tobago",
"TZ": "Tansanija",
"UA": "Ukraina",
"UM": "Ameriska Oceaniska",
"US": "Zjadnośone staty Ameriki",
"VA": "Vatikańske město",
"VC": "St. Vincent a Grenadiny",
"VG": "Britiske kněžniske kupy",
"VI": "Ameriske kněžniske kupy",
"WF": "Wallis a Futuna",
"XK": "Kosowo",
"YE": "Jemen",
"ZA": "Pódpołdnjowa Afrika (Republika)",
"ZM": "Sambija",
"ZW": "Simbabwe",
"ZZ": "njeznaty region"
};
}-*/ | block_comment | pl | /*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.i18n.client.impl.cldr;
import com.google.gwt.core.client.JavaScriptObject;
// DO NOT EDIT - GENERATED FROM CLDR DATA
/**
* Localized names for the "dsb" locale.
*/
public class LocalizedNamesImpl_dsb extends LocalizedNamesImpl {
@Override
public String[] loadSortedRegionCodes() {
return new String[] {
"AF",
"AX",
"AL",
"DZ",
"UM",
"AS",
"VI",
"AD",
"AO",
"AI",
"AQ",
"AG",
"AR",
"AM",
"AW",
"AC",
"AU",
"AT",
"AZ",
"BS",
"BH",
"BD",
"BB",
"BE",
"BZ",
"BJ",
"BM",
"BY",
"BT",
"BO",
"BA",
"BW",
"BV",
"BR",
"VG",
"IO",
"BN",
"BG",
"BF",
"BI",
"TD",
"ME",
"CF",
"CZ",
"EA",
"CL",
"CN",
"HR",
"CP",
"CK",
"CI",
"CW",
"CY",
"DK",
"DG",
"DM",
"DO",
"DJ",
"EG",
"EC",
"GQ",
"SV",
"ER",
"EE",
"ET",
"EU",
"EZ",
"FK",
"FO",
"FJ",
"PH",
"FI",
"FR",
"GF",
"PF",
"TF",
"GA",
"GM",
"GE",
"GH",
"GI",
"GN",
"GW",
"CX",
"GD",
"GR",
"GL",
"GP",
"GU",
"GT",
"GG",
"GY",
"HT",
"HM",
"HN",
"HU",
"IN",
"ID",
"IQ",
"IR",
"IE",
"IS",
"IL",
"IT",
"JM",
"JP",
"YE",
"JE",
"JO",
"KY",
"KH",
"CM",
"CA",
"IC",
"CV",
"BQ",
"QA",
"KZ",
"KE",
"KG",
"KI",
"CC",
"CO",
"KM",
"CG",
"CD",
"XK",
"CR",
"CU",
"KW",
"LA",
"LS",
"LV",
"LB",
"LR",
"LY",
"LI",
"LT",
"LU",
"MG",
"MK",
"MY",
"MW",
"MV",
"ML",
"MT",
"IM",
"MA",
"MH",
"MQ",
"MU",
"MR",
"YT",
"MX",
"FM",
"MD",
"MC",
"MN",
"MS",
"MZ",
"MM",
"NA",
"NR",
"NP",
"NE",
"NG",
"NI",
"DE",
"NU",
"NL",
"NF",
"NO",
"NC",
"NZ",
"OM",
"PK",
"PW",
"PS",
"PA",
"PG",
"PY",
"PE",
"PN",
"ZA",
"GS",
"KR",
"SS",
"KP",
"MP",
"EH",
"PL",
"PT",
"PR",
"RE",
"RW",
"RO",
"RU",
"SB",
"ZM",
"WS",
"SM",
"ST",
"SA",
"SN",
"RS",
"SC",
"SL",
"ZW",
"SG",
"SX",
"SO",
"ES",
"LK",
"BL",
"SH",
"KN",
"LC",
"MF",
"PM",
"VC",
"SD",
"SR",
"SJ",
"SZ",
"SE",
"CH",
"SY",
"SK",
"SI",
"TJ",
"TW",
"TZ",
"TH",
"TL",
"TG",
"TK",
"TO",
"TT",
"TA",
"TN",
"TM",
"TR",
"TC",
"TV",
"UG",
"UA",
"UN",
"UY",
"UZ",
"VU",
"VA",
"VE",
"VN",
"WF",
"QO",
"HK",
"MO",
"AE",
"GB",
"US",
};
}
@Override
protected void loadNameMapJava() {
super.loadNameMapJava();
namesMap.put("001", "swět");
namesMap.put("002", "Afrika");
namesMap.put("003", "Pódpołnocna Amerika");
namesMap.put("005", "Pódpołdnjowa Amerika");
namesMap.put("009", "Oceaniska");
namesMap.put("011", "Pódwjacorna Afrika");
namesMap.put("013", "Srjejźna Amerika");
namesMap.put("014", "pódzajtšna Afrika");
namesMap.put("015", "pódpołnocna Afrika");
namesMap.put("017", "srjejźna Afrika");
namesMap.put("018", "pódpołdnjowa Afrika");
namesMap.put("019", "Amerika");
namesMap.put("021", "pódpołnocny ameriski kontinent");
namesMap.put("029", "Karibiska");
namesMap.put("030", "pódzajtšna Azija");
namesMap.put("034", "pódpołdnjowa Azija");
namesMap.put("035", "krotkozajtšna Azija");
namesMap.put("039", "pódpołdnjowa Europa");
namesMap.put("053", "Awstralazija");
namesMap.put("054", "Melaneziska");
namesMap.put("057", "Mikroneziska (kupowy region)");
namesMap.put("061", "Polyneziska");
namesMap.put("142", "Azija");
namesMap.put("143", "centralna Azija");
namesMap.put("145", "pódwjacorna Azija");
namesMap.put("150", "Europa");
namesMap.put("151", "pódzajtšna Europa");
namesMap.put("154", "pódpołnocna Europa");
namesMap.put("155", "pódwjacorna Europa");
namesMap.put("419", "Łatyńska Amerika");
namesMap.put("AC", "Ascension");
namesMap.put("AE", "Zjadnośone arabiske emiraty");
namesMap.put("AG", "Antigua a Barbuda");
namesMap.put("AL", "Albańska");
namesMap.put("AM", "Armeńska");
namesMap.put("AQ", "Antarktis");
namesMap.put("AR", "Argentinska");
namesMap.put("AS", "Ameriska Samoa");
namesMap.put("AT", "Awstriska");
namesMap.put("AU", "Awstralska");
namesMap.put("AX", "Åland");
namesMap.put("AZ", "Azerbajdžan");
namesMap.put("BA", "Bosniska a Hercegowina");
namesMap.put("BD", "Bangladeš");
namesMap.put("BE", "Belgiska");
namesMap.put("BG", "Bulgarska");
namesMap.put("BM", "Bermudy");
namesMap.put("BO", "Boliwiska");
namesMap.put("BQ", "Karibiska Nižozemska");
namesMap.put("BR", "Brazilska");
namesMap.put("BS", "Bahamy");
namesMap.put("BV", "Bouvetowa kupa");
namesMap.put("BY", "Běłoruska");
namesMap.put("CA", "Kanada");
namesMap.put("CC", "Kokosowe kupy");
namesMap.put("CD", "Kongo-Kinshasa");
namesMap.put("CF", "Centralnoafriska republika");
namesMap.put("CG", "Kongo-Brazzaville");
namesMap.put("CH", "Šwicarska");
namesMap.put("CK", "Cookowe kupy");
namesMap.put("CL", "Chilska");
namesMap.put("CM", "Kamerun");
namesMap.put("CO", "Kolumbiska");
namesMap.put("CP", "Clippertonowa kupa");
namesMap.put("CR", "Kosta Rika");
namesMap.put("CU", "Kuba");
namesMap.put("CV", "Kap Verde");
namesMap.put("CX", "Gódowne kupy");
namesMap.put("CY", "Cypriska");
namesMap.put("CZ", "Česka republika");
namesMap.put("DE", "Nimska");
namesMap.put("DJ", "Džibuti");
namesMap.put("DK", "Dańska");
namesMap.put("DM", "Dominika");
namesMap.put("DO", "Dominikańska republika");
namesMap.put("DZ", "Algeriska");
namesMap.put("EA", "Ceuta a Melilla");
namesMap.put("EC", "Ekwador");
namesMap.put("EE", "Estniska");
namesMap.put("EG", "Egyptojska");
namesMap.put("EH", "Pódwjacorna Sahara");
namesMap.put("ER", "Eritreja");
namesMap.put("ES", "Špańska");
namesMap.put("ET", "Etiopiska");
namesMap.put("EU", "Europska unija");
namesMap.put("FI", "Finska");
namesMap.put("FJ", "Fidži");
namesMap.put("FK", "Falklandske kupy");
namesMap.put("FM", "Mikroneziska");
namesMap.put("FO", "Färöje");
namesMap.put("FR", "Francojska");
namesMap.put("GA", "Gabun");
namesMap.put("GB", "Zjadnośone kralejstwo");
namesMap.put("GE", "Georgiska");
namesMap.put("GF", "Francojska Guyana");
namesMap.put("GL", "Grönlandska");
namesMap.put("GM", "Gambija");
namesMap.put("GN", "Gineja");
namesMap.put("GQ", "Ekwatorialna Gineja");
namesMap.put("GR", "Grichiska");
namesMap.put("GS", "Pódpołdnjowa Georgiska a Pódpołdnjowe Sandwichowe kupy");
namesMap.put("GW", "Gineja-Bissau");
namesMap.put("HK", "Wósebna zastojnstwowa cona Hongkong");
namesMap.put("HM", "Heardowa kupa a McDonaldowe kupy");
namesMap.put("HR", "Chorwatska");
namesMap.put("HU", "Hungorska");
namesMap.put("IC", "Kanariske kupy");
namesMap.put("ID", "Indoneziska");
namesMap.put("IE", "Irska");
namesMap.put("IM", "Man");
namesMap.put("IN", "Indiska");
namesMap.put("IO", "Britiski indiskooceaniski teritorium");
namesMap.put("IQ", "Irak");
namesMap.put("IS", "Islandska");
namesMap.put("IT", "Italska");
namesMap.put("JM", "Jamaika");
namesMap.put("JO", "Jordaniska");
namesMap.put("JP", "Japańska");
namesMap.put("KE", "Kenia");
namesMap.put("KG", "Kirgizistan");
namesMap.put("KH", "Kambodža");
namesMap.put("KM", "Komory");
namesMap.put("KN", "St. Kitts a Nevis");
namesMap.put("KP", "Pódpołnocna Koreja");
namesMap.put("KR", "Pódpołdnjowa Koreja");
namesMap.put("KY", "Kajmaniske kupy");
namesMap.put("KZ", "Kazachstan");
namesMap.put("LB", "Libanon");
namesMap.put("LR", "Liberija");
namesMap.put("LT", "Litawska");
namesMap.put("LU", "Luxemburgska");
namesMap.put("LV", "Letiska");
namesMap.put("LY", "Libyska");
namesMap.put("MA", "Marokko");
namesMap.put("MD", "Moldawska");
namesMap.put("ME", "Carna Góra");
namesMap.put("MG", "Madagaskar");
namesMap.put("MH", "Marshallowe kupy");
namesMap.put("MK", "Makedońska");
namesMap.put("MM", "Myanmar");
namesMap.put("MN", "Mongolska");
namesMap.put("MO", "Wósebna zastojnstwowa cona Macao");
namesMap.put("MP", "Pódpołnocne Mariany");
namesMap.put("MR", "Mawretańska");
namesMap.put("MV", "Malediwy");
namesMap.put("MX", "Mexiko");
namesMap.put("MY", "Malajzija");
namesMap.put("MZ", "Mosambik");
namesMap.put("NA", "Namibija");
namesMap.put("NC", "Nowa Kaledoniska");
namesMap.put("NF", "Norfolkowa kupa");
namesMap.put("NG", "Nigerija");
namesMap.put("NI", "Nikaragua");
namesMap.put("NL", "Nižozemska");
namesMap.put("NO", "Norwegska");
namesMap.put("NZ", "Nowoseelandska");
namesMap.put("PF", "Francojska Polyneziska");
namesMap.put("PG", "Papua-Neuguinea");
namesMap.put("PH", "Filipiny");
namesMap.put("PL", "Pólska");
namesMap.put("PM", "St. Pierre a Miquelon");
namesMap.put("PN", "Pitcairnowe kupy");
namesMap.put("PS", "Palestinski awtonomny teritorium");
namesMap.put("PT", "Portugalska");
namesMap.put("QA", "Katar");
namesMap.put("QO", "wenkowna Oceaniska");
namesMap.put("RO", "Rumuńska");
namesMap.put("RS", "Serbiska");
namesMap.put("RU", "Ruska");
namesMap.put("RW", "Ruanda");
namesMap.put("SA", "Saudi-Arabiska");
namesMap.put("SB", "Salomony");
namesMap.put("SC", "Seychelle");
namesMap.put("SE", "Šwedska");
namesMap.put("SG", "Singapur");
namesMap.put("SI", "Słowjeńska");
namesMap.put("SJ", "Svalbard a Jan Mayen");
namesMap.put("SK", "Słowakska");
namesMap.put("SO", "Somalija");
namesMap.put("SR", "Surinamska");
namesMap.put("SS", "Pódpołdnjowy Sudan");
namesMap.put("ST", "São Tomé a Príncipe");
namesMap.put("SY", "Syriska");
namesMap.put("SZ", "Swasiska");
namesMap.put("TC", "Turks a Caicos kupy");
namesMap.put("TD", "Čad");
namesMap.put("TF", "Francojski pódpołdnjowy a antarktiski teritorium");
namesMap.put("TH", "Thailandska");
namesMap.put("TJ", "Tadźikistan");
namesMap.put("TM", "Turkmeniska");
namesMap.put("TN", "Tuneziska");
namesMap.put("TR", "Turkojska");
namesMap.put("TT", "Trinidad a Tobago");
namesMap.put("TZ", "Tansanija");
namesMap.put("UA", "Ukraina");
namesMap.put("UM", "Ameriska Oceaniska");
namesMap.put("US", "Zjadnośone staty Ameriki");
namesMap.put("VA", "Vatikańske město");
namesMap.put("VC", "St. Vincent a Grenadiny");
namesMap.put("VG", "Britiske kněžniske kupy");
namesMap.put("VI", "Ameriske kněžniske kupy");
namesMap.put("WF", "Wallis a Futuna");
namesMap.put("XK", "Kosowo");
namesMap.put("YE", "Jemen");
namesMap.put("ZA", "Pódpołdnjowa Afrika (Republika)");
namesMap.put("ZM", "Sambija");
namesMap.put("ZW", "Simbabwe");
namesMap.put("ZZ", "njeznaty region");
}
@Override
protected JavaScriptObject loadNameMapNative() {
return overrideMap(super.loadNameMapNative(), loadMyNameMap());
}
private native JavaScriptObject loadMyNameMap() /*-{
<SUF>*/;
}
|
177736_0 | package com.kodilla.collections.lists;
import com.kodilla.collections.interfaces.Circle;
import com.kodilla.collections.interfaces.Shape;
import com.kodilla.collections.interfaces.Square;
import com.kodilla.collections.interfaces.Triangle;
import java.util.LinkedList;
import java.util.List;
public class GeneralShapesListApplication {
public static void main(String[] args) {
List<Shape> shapes = new LinkedList<>();
Square square = new Square (10.0);//a. tworzymy obiekt klasy Square i zapamiętujemy go w zmiennej o nazwie square. Następnie – linijkę niżej – wstawiamy ten obiekt do kolekcji.
shapes.add(square);
shapes.add(new Circle(7.0));
shapes.add(new Triangle(10.0, 4.0, 10.77));
shapes.remove(1); // 1. remove obiekt z kolekcji podając indeks elementu
shapes.remove(square); // b. Zmiennej square używamy następnie w linii [b], aby wspomniany kwadrat usunąć z kolekcji.
Triangle triangle = new Triangle(10.0, 4.0, 10.77); // tworzymy nowy obiekt klasy Triangle, taki sam jak ten, który został utworzony i wstawiony do listy
shapes.remove(triangle); // wywołujemy metodę remove, przekazując jej jako argument utworzony przed chwilą obiekt.
System.out.println(shapes.size()); // wyświetlamy rozmiar kolekcji
for (Shape shape : shapes) {
System.out.println(shape + ", area: " + shape.getArea() + ", perimeter: " + shape.getPerimeter());
}
}
}
| zalewski2010/krzysztof_zalewski-kodilla_tester | kodilla-collections/src/main/java/com/kodilla/collections/lists/GeneralShapesListApplication.java | 496 | //a. tworzymy obiekt klasy Square i zapamiętujemy go w zmiennej o nazwie square. Następnie – linijkę niżej – wstawiamy ten obiekt do kolekcji. | line_comment | pl | package com.kodilla.collections.lists;
import com.kodilla.collections.interfaces.Circle;
import com.kodilla.collections.interfaces.Shape;
import com.kodilla.collections.interfaces.Square;
import com.kodilla.collections.interfaces.Triangle;
import java.util.LinkedList;
import java.util.List;
public class GeneralShapesListApplication {
public static void main(String[] args) {
List<Shape> shapes = new LinkedList<>();
Square square = new Square (10.0);//a. tw<SUF>
shapes.add(square);
shapes.add(new Circle(7.0));
shapes.add(new Triangle(10.0, 4.0, 10.77));
shapes.remove(1); // 1. remove obiekt z kolekcji podając indeks elementu
shapes.remove(square); // b. Zmiennej square używamy następnie w linii [b], aby wspomniany kwadrat usunąć z kolekcji.
Triangle triangle = new Triangle(10.0, 4.0, 10.77); // tworzymy nowy obiekt klasy Triangle, taki sam jak ten, który został utworzony i wstawiony do listy
shapes.remove(triangle); // wywołujemy metodę remove, przekazując jej jako argument utworzony przed chwilą obiekt.
System.out.println(shapes.size()); // wyświetlamy rozmiar kolekcji
for (Shape shape : shapes) {
System.out.println(shape + ", area: " + shape.getArea() + ", perimeter: " + shape.getPerimeter());
}
}
}
|
4419_0 | package com.example.awarehouse.module.product;
import com.example.awarehouse.module.product.dto.ProductDto;
import com.example.awarehouse.module.product.util.CurrencyProvider;
import lombok.AllArgsConstructor;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.data.domain.PageImpl;
import java.math.BigDecimal;
import java.time.Duration;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@AllArgsConstructor
public abstract class WszystkoPlProductProvider implements ProductProvider {
protected final WebDriver driver;
private final String wszystkoPlUrl = "https://wszystko.pl";
protected UUID associateElementId;
protected List<ProductDto> addedProducts = new ArrayList<>();
public WszystkoPlProductProvider(WebDriver driver, UUID associateElementId) {
this.driver = driver;
this.associateElementId = associateElementId;
}
@Override
public PageImpl<ProductDto> getProductsFromSite(String link) {
try {
Document firstDocument = processFirstPage(link);
int lastPage = getLastPage(firstDocument);
List<String> unloadedPages = processPages(lastPage, link);
processProductsFromUnloadedPage(unloadedPages);
} finally {
driver.quit();
}
return new PageImpl<>(addedProducts);
}
private Document processFirstPage(String link) {
driver.get(link);
Document document = Jsoup.parse(driver.getPageSource());
pageLoaded(60, ".wpl-offer", 4);
processProducts(document);
return document;
}
private int getLastPage(Document document) {
Element listOfPages = document.getElementsByClass("cds-button-icon cds-button-small cds-pager__page-button " +
"cds-ripple cds-pager__number cds-ripple--bounded ng-star-inserted").last();
return Integer.parseInt(listOfPages.text());
}
private List<String> processPages(int lastPage, String link) {
List<String> tryAgainPages = new ArrayList<>();
for (int i = 2; i <= lastPage; i++) {
String linkToPage = link + "?page=" + i;
System.out.println(linkToPage);
driver.navigate().to(linkToPage);
if (pageLoaded(60, ".wpl-offer", 3)) {
Document document1 = Jsoup.parse(driver.getPageSource());
processProducts(document1);
} else {
tryAgainPages.add(linkToPage);
}
}
return tryAgainPages;
}
private List<String> processProductsFromUnloadedPage(List<String> tryAgainPages) {
List<String> unloadedPages = new ArrayList<>();
for (String tryAgainPage : tryAgainPages) {
driver.navigate().to(tryAgainPage);
if (pageLoaded(60, ".wpl-offer", 3)) {
Document document = Jsoup.parse(driver.getPageSource());
processProducts(document);
} else {
unloadedPages.add(tryAgainPage);
}
}
return unloadedPages;
}
private void processProducts(Document document) {
Elements productsContainers = document.select(".wpl-offer");
for (Element productContainer : productsContainers) {
saveProduct(createProduct(productContainer));
}
}
abstract void saveProduct(Product product);
private Product createProduct(Element productContainer) {
Element linkTitle = productContainer.getElementsByClass("cds-text-2 wpl-offer__title wpl-break-word").get(0);
String title = linkTitle.text();
Price price = createPoductPrice(productContainer);
Product product = Product.builder().title(title).price(price).build();
String linkToProduct = linkTitle.attr("href");
setInformationAboutProductFromLink(product, linkToProduct);
System.out.println(product.getTitle() + " " + product.getAmount() + " " + product.getPrice().getAmount() + " " + product.getPrice().getCurrency());
return product;
}
private Price createPoductPrice(Element productContainer) {
Element priceContainer = productContainer.getElementsByClass("cds-text-2 cds-text-2_bold wpl-offer__price").get(0);
String price = priceContainer.text();
BigDecimal decimalPrice = BigDecimal.valueOf(extractDecimalNumberFromString(price));
Currency currency = extractCurrency(price);
return new Price(decimalPrice, currency);
}
private Double extractDecimalNumberFromString(String textWithNumber) {
Pattern pattern = Pattern.compile("\\d+[.,]?\\d*");
Matcher matcher = pattern.matcher(textWithNumber);
if (matcher.find()) {
return extractDecimalNumberFromString(matcher);
} else {
return 0.0;
}
}
private Double extractDecimalNumberFromString(Matcher matcher) {
String decimalPrice = matcher.group();
decimalPrice = removeUnsupportedSignsFromStringNumber(decimalPrice);
return convertToDouble(decimalPrice);
}
private String removeUnsupportedSignsFromStringNumber(String number) {
if (number.contains(",")) number = number.replaceAll(",", ".");
return number;
}
private Double convertToDouble(String number) {
try {
return Double.valueOf(number);
} catch (NumberFormatException ex) {
return 0.0;
}
}
private Currency extractCurrency(String price) {
Pattern currencyPattern = Pattern.compile("\\p{L}+", Pattern.UNICODE_CHARACTER_CLASS);
Matcher matcher = currencyPattern.matcher(price);
if (matcher.find()) {
return extractCurrency(matcher);
}
return null;
}
private Currency extractCurrency(Matcher matcher) {
String currencyString = matcher.group();
return CurrencyProvider.currencyNameMap.get(currencyString);
}
void setInformationAboutProductFromLink(Product product, String linkToProduct) {
driver.navigate().to(wszystkoPlUrl + linkToProduct);
if (pageLoaded(60, ".wpl-offer-presentation-summary__quantity-section", 3)) {
Document document = Jsoup.parse(driver.getPageSource());
product.setAmount(getNumberOfProducts(document));
} else {
product.setAmount(0.0);
}
}
private Double getNumberOfProducts(Document document) {
Elements numberOfProductsElements = document.getElementsByClass("cds-text-2");
Optional<Element> optionalNumberOfProducts = numberOfProductsElements.stream().filter(n -> n.text().contains("sztuk")).findFirst();
return optionalNumberOfProducts.map(element -> extractDecimalNumberFromString(element.text())).orElse(0.0);
}
private boolean pageLoaded(int seconds, String cssSelector, int reptitions) {
while (reptitions > 0) {
try {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(seconds));
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(cssSelector)));
return true;
} catch (Exception ex) {
reptitions--;
}
}
return false;
}
private void removePopup() {
WebElement popup = driver.findElement(By.cssSelector("div.wpl-cookie-popup__container"));
if (popup.isDisplayed()) {
popup.findElement(By.cssSelector("button.cds-button-secondary")).click();
}
}
}
// public Document getDocumentFromSite(String link){
// try {
// System.out.println(link);
// return Jsoup
// .connect(link)
// .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:100.0) Gecko/20100101 Firefox/100.0") //
// .get();
// } catch (HttpStatusException ex) {
// throw new SiteIsNotAvailableException(ex.getMessage());
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
| zannna/awarehouse | src/main/java/com/example/awarehouse/module/product/WszystkoPlProductProvider.java | 2,312 | //wszystko.pl"; | line_comment | pl | package com.example.awarehouse.module.product;
import com.example.awarehouse.module.product.dto.ProductDto;
import com.example.awarehouse.module.product.util.CurrencyProvider;
import lombok.AllArgsConstructor;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.data.domain.PageImpl;
import java.math.BigDecimal;
import java.time.Duration;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@AllArgsConstructor
public abstract class WszystkoPlProductProvider implements ProductProvider {
protected final WebDriver driver;
private final String wszystkoPlUrl = "https://wszys<SUF>
protected UUID associateElementId;
protected List<ProductDto> addedProducts = new ArrayList<>();
public WszystkoPlProductProvider(WebDriver driver, UUID associateElementId) {
this.driver = driver;
this.associateElementId = associateElementId;
}
@Override
public PageImpl<ProductDto> getProductsFromSite(String link) {
try {
Document firstDocument = processFirstPage(link);
int lastPage = getLastPage(firstDocument);
List<String> unloadedPages = processPages(lastPage, link);
processProductsFromUnloadedPage(unloadedPages);
} finally {
driver.quit();
}
return new PageImpl<>(addedProducts);
}
private Document processFirstPage(String link) {
driver.get(link);
Document document = Jsoup.parse(driver.getPageSource());
pageLoaded(60, ".wpl-offer", 4);
processProducts(document);
return document;
}
private int getLastPage(Document document) {
Element listOfPages = document.getElementsByClass("cds-button-icon cds-button-small cds-pager__page-button " +
"cds-ripple cds-pager__number cds-ripple--bounded ng-star-inserted").last();
return Integer.parseInt(listOfPages.text());
}
private List<String> processPages(int lastPage, String link) {
List<String> tryAgainPages = new ArrayList<>();
for (int i = 2; i <= lastPage; i++) {
String linkToPage = link + "?page=" + i;
System.out.println(linkToPage);
driver.navigate().to(linkToPage);
if (pageLoaded(60, ".wpl-offer", 3)) {
Document document1 = Jsoup.parse(driver.getPageSource());
processProducts(document1);
} else {
tryAgainPages.add(linkToPage);
}
}
return tryAgainPages;
}
private List<String> processProductsFromUnloadedPage(List<String> tryAgainPages) {
List<String> unloadedPages = new ArrayList<>();
for (String tryAgainPage : tryAgainPages) {
driver.navigate().to(tryAgainPage);
if (pageLoaded(60, ".wpl-offer", 3)) {
Document document = Jsoup.parse(driver.getPageSource());
processProducts(document);
} else {
unloadedPages.add(tryAgainPage);
}
}
return unloadedPages;
}
private void processProducts(Document document) {
Elements productsContainers = document.select(".wpl-offer");
for (Element productContainer : productsContainers) {
saveProduct(createProduct(productContainer));
}
}
abstract void saveProduct(Product product);
private Product createProduct(Element productContainer) {
Element linkTitle = productContainer.getElementsByClass("cds-text-2 wpl-offer__title wpl-break-word").get(0);
String title = linkTitle.text();
Price price = createPoductPrice(productContainer);
Product product = Product.builder().title(title).price(price).build();
String linkToProduct = linkTitle.attr("href");
setInformationAboutProductFromLink(product, linkToProduct);
System.out.println(product.getTitle() + " " + product.getAmount() + " " + product.getPrice().getAmount() + " " + product.getPrice().getCurrency());
return product;
}
private Price createPoductPrice(Element productContainer) {
Element priceContainer = productContainer.getElementsByClass("cds-text-2 cds-text-2_bold wpl-offer__price").get(0);
String price = priceContainer.text();
BigDecimal decimalPrice = BigDecimal.valueOf(extractDecimalNumberFromString(price));
Currency currency = extractCurrency(price);
return new Price(decimalPrice, currency);
}
private Double extractDecimalNumberFromString(String textWithNumber) {
Pattern pattern = Pattern.compile("\\d+[.,]?\\d*");
Matcher matcher = pattern.matcher(textWithNumber);
if (matcher.find()) {
return extractDecimalNumberFromString(matcher);
} else {
return 0.0;
}
}
private Double extractDecimalNumberFromString(Matcher matcher) {
String decimalPrice = matcher.group();
decimalPrice = removeUnsupportedSignsFromStringNumber(decimalPrice);
return convertToDouble(decimalPrice);
}
private String removeUnsupportedSignsFromStringNumber(String number) {
if (number.contains(",")) number = number.replaceAll(",", ".");
return number;
}
private Double convertToDouble(String number) {
try {
return Double.valueOf(number);
} catch (NumberFormatException ex) {
return 0.0;
}
}
private Currency extractCurrency(String price) {
Pattern currencyPattern = Pattern.compile("\\p{L}+", Pattern.UNICODE_CHARACTER_CLASS);
Matcher matcher = currencyPattern.matcher(price);
if (matcher.find()) {
return extractCurrency(matcher);
}
return null;
}
private Currency extractCurrency(Matcher matcher) {
String currencyString = matcher.group();
return CurrencyProvider.currencyNameMap.get(currencyString);
}
void setInformationAboutProductFromLink(Product product, String linkToProduct) {
driver.navigate().to(wszystkoPlUrl + linkToProduct);
if (pageLoaded(60, ".wpl-offer-presentation-summary__quantity-section", 3)) {
Document document = Jsoup.parse(driver.getPageSource());
product.setAmount(getNumberOfProducts(document));
} else {
product.setAmount(0.0);
}
}
private Double getNumberOfProducts(Document document) {
Elements numberOfProductsElements = document.getElementsByClass("cds-text-2");
Optional<Element> optionalNumberOfProducts = numberOfProductsElements.stream().filter(n -> n.text().contains("sztuk")).findFirst();
return optionalNumberOfProducts.map(element -> extractDecimalNumberFromString(element.text())).orElse(0.0);
}
private boolean pageLoaded(int seconds, String cssSelector, int reptitions) {
while (reptitions > 0) {
try {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(seconds));
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(cssSelector)));
return true;
} catch (Exception ex) {
reptitions--;
}
}
return false;
}
private void removePopup() {
WebElement popup = driver.findElement(By.cssSelector("div.wpl-cookie-popup__container"));
if (popup.isDisplayed()) {
popup.findElement(By.cssSelector("button.cds-button-secondary")).click();
}
}
}
// public Document getDocumentFromSite(String link){
// try {
// System.out.println(link);
// return Jsoup
// .connect(link)
// .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:100.0) Gecko/20100101 Firefox/100.0") //
// .get();
// } catch (HttpStatusException ex) {
// throw new SiteIsNotAvailableException(ex.getMessage());
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
|
96209_22 | package Tetris3D;
import Control.KeyGL;
import Control.Map;
import Control.MouseGL;
import Logic.Array3D;
import Objects3D.Cube;
import Objects3D.Square;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.GLCapabilities;
import com.jogamp.opengl.GLDrawableFactory;
import com.jogamp.opengl.GLEventListener;
import com.jogamp.opengl.GLProfile;
import com.jogamp.opengl.awt.GLCanvas;
import com.jogamp.opengl.glu.GLU;
import com.jogamp.opengl.util.gl2.GLUT;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import jogamp.opengl.GLDrawableFactoryImpl;
public class Frame3D extends JFrame implements GLEventListener {
static GL2 gl;
static GLCanvas canvas;
static GLCapabilities capabilities;
static GLProfile profile;
private GLU glu = new GLU();
private GLUT glut = new GLUT();
private float rotate = 0.0f;
private MouseGL mouseGl = new MouseGL();
private KeyGL keyGL = new KeyGL();
private int distance = 120;
private int i = 0;
private Cube klocek = new Cube();
private Array3D<Boolean> booleanMap = new Array3D<Boolean>();
private ArrayList<Cube> cubes = new ArrayList<Cube>();
private Square container = new Square();
private Runnable r = new CubesMoveThread();
private CubesMoveThread moveThread = new CubesMoveThread(r);
public Frame3D () {
// GLDrawableFactory desktopFactory = (GLDrawableFactoryImpl) GLDrawableFactory.getDesktopFactory();
//
// GLProfile.initProfiles(desktopFactory.getDefaultDevice());
//// GLProfile.initSingleton();
// profile = GLProfile.getMaxProgrammable(true);
////
// capabilities = new GLCapabilities(profile);
canvas = new GLCanvas();
this.add(canvas);
canvas.addGLEventListener(this);
canvas.addMouseMotionListener(mouseGl);
canvas.addMouseWheelListener(mouseGl);
canvas.addMouseListener(mouseGl);
canvas.addKeyListener(keyGL);
this.setBounds(0,0,600,480);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i = 0; i < Map.getCubesNumber(); i++) {
Random r = new Random();
int x = r.nextInt(Map.getWidth())*Map.getCubesSize();
int z = r.nextInt(Map.getWidth())*Map.getCubesSize();
cubes.add(new Cube(x,Map.getHeight(),z));
}
moveThread.setObjectToMove(cubes);
booleanMap.fill(new Boolean(false));
moveThread.setBooleanMap(booleanMap);
}
// @Override
public void display(GLAutoDrawable drawable) {
GL2 gl = (GL2) drawable.getGL();;
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
// obr�t
gl.glRotatef(KeyGL.getRotateLeft(), 0, 1, 0);
KeyGL.setRotateLeft(0);
gl.glRotatef(KeyGL.getRotateRight(), 0, 1, 0);
KeyGL.setRotateRight(0);
gl.glPushMatrix();
//szeroko�� mapy * szeroko�� klocka
gl.glTranslatef(-(Map.getWidth()*Map.getCubesSize())/2, 0, -(Map.getWidth()*Map.getCubesSize())/2);
// gl.glTranslatef(0, 0, 40);
// gl.glTranslatef(mouseGl.getZ(), 0, mouseGl.getZ());
// glu.gluLookAt(0, 0, 10+mouseGl.getZ(), 0, 0, 0, 0, 1, 1);
// glu.gluLookAt(0, 0, distance, 0, 0, 0, 0, 1, 0);
gl.glPushMatrix();
// klocek.moveOnAxisY(t.getX());
// gl.glRotatef(rotate, 0, 1, 0);
// klocek.drawCube(drawable);
for (int i = 0; i < cubes.size(); i++) {
cubes.get(i).drawCube(drawable);
}
gl.glPopMatrix();
gl.glPushMatrix();
container.drawWireSqare(drawable);
gl.glPopMatrix();
gl.glPopMatrix();
gl.glFlush();
canvas.repaint();
}
// @Override
public void init(GLAutoDrawable drawable) {
GL2 gl = (GL2) drawable.getGL();
gl.glEnable(GL2.GL_NORMALIZE);
gl.glShadeModel(GL2.GL_SMOOTH);
gl.glClearColor(0.0f, 0.0f, 0.8f, 0.0f);
gl.glClearDepth(1.0f);
gl.glPolygonMode(GL.GL_FRONT_AND_BACK, GL2.GL_FILL);
gl.glEnable(GL.GL_DEPTH_TEST);
//Alpha
gl.glBlendFunc(gl.GL_SRC_ALPHA,gl.GL_ONE_MINUS_SRC_ALPHA);
gl.glEnable(gl.GL_BLEND);
gl.glEnable(gl.GL_ALPHA_TEST);
//Lights
gl.glEnable(gl.GL_LIGHTING);
gl.glEnable(gl.GL_LIGHT0);//uaktywnienie źródła światła nr. 0
gl.glEnable(gl.GL_COLOR_MATERIAL); //uaktywnienie śledzenia kolorów
gl.glColorMaterial(gl.GL_FRONT, gl.GL_AMBIENT_AND_DIFFUSE); //kolory ustalone za pomocą glColor
gl.glLightfv(gl.GL_LIGHT0, gl.GL_AMBIENT, new float[] { 0.6f, 0.6f, 0.6f, 0.0f },0);//swiatło otaczające
gl.glLightfv(gl.GL_LIGHT0, gl.GL_DIFFUSE, new float[]{ 0.5f, 0.5f, 0.5f, 0.0f },0);//światło rozproszone
gl.glLightfv(gl.GL_LIGHT0, gl.GL_SPECULAR, new float[]{ 0.4f, 0.4f, 0.4f, 0.0f },0); //światło odbite
gl.glLightfv(gl.GL_LIGHT0, gl.GL_POSITION, new float[]{ 10.0f, 15.0f, 0.0f, 0.0f },0);//pozycja światła
gl.glMaterialfv(gl.GL_FRONT_AND_BACK, gl.GL_AMBIENT, new float[] { 0.7f, 0.7f, 0.7f, 0.0f },0);//swiatło otaczające
gl.glMaterialfv(GL.GL_FRONT_AND_BACK, gl.GL_DIFFUSE, new float[] { 0.7f, 0.7f, 0.7f, 0.0f },0);
gl.glMaterialfv(GL.GL_FRONT_AND_BACK, gl.GL_SPECULAR, new float[] { 0.4f, 0.4f, 0.4f, 0.0f },0);//parametry odblaskowości
gl.glMaterialf(GL.GL_FRONT_AND_BACK, gl.GL_SHININESS, 0.3f);
gl.glCullFace( gl.GL_BACK); // ukrywamy tył
//tekstury
gl.glEnable(GL.GL_TEXTURE_2D);
Cube.setGLContext(drawable);
//kamera
gl.glLoadIdentity();
glu.gluPerspective(45, 1.0*this.getWidth()/this.getHeight(), 1, 1000);
//glu.gluLookAt(0, 0, distance, 0, 0, 0, 1, 0, 0);
glu.gluLookAt(132, 80, 124, 0, 10, 0, 0, 1, 0);
canvas.repaint(); // odswie�enie canvasu z ustawionymi juz parametrami
moveThread.start();
}
// @Override
public void dispose(GLAutoDrawable glAutoDrawable) {
}
// @Override
public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3,
int arg4) {
}
}
| zaqpiotr/Tetris3D | src/main/java/Tetris3D/Frame3D.java | 2,695 | //pozycja światła | line_comment | pl | package Tetris3D;
import Control.KeyGL;
import Control.Map;
import Control.MouseGL;
import Logic.Array3D;
import Objects3D.Cube;
import Objects3D.Square;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.GLCapabilities;
import com.jogamp.opengl.GLDrawableFactory;
import com.jogamp.opengl.GLEventListener;
import com.jogamp.opengl.GLProfile;
import com.jogamp.opengl.awt.GLCanvas;
import com.jogamp.opengl.glu.GLU;
import com.jogamp.opengl.util.gl2.GLUT;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import jogamp.opengl.GLDrawableFactoryImpl;
public class Frame3D extends JFrame implements GLEventListener {
static GL2 gl;
static GLCanvas canvas;
static GLCapabilities capabilities;
static GLProfile profile;
private GLU glu = new GLU();
private GLUT glut = new GLUT();
private float rotate = 0.0f;
private MouseGL mouseGl = new MouseGL();
private KeyGL keyGL = new KeyGL();
private int distance = 120;
private int i = 0;
private Cube klocek = new Cube();
private Array3D<Boolean> booleanMap = new Array3D<Boolean>();
private ArrayList<Cube> cubes = new ArrayList<Cube>();
private Square container = new Square();
private Runnable r = new CubesMoveThread();
private CubesMoveThread moveThread = new CubesMoveThread(r);
public Frame3D () {
// GLDrawableFactory desktopFactory = (GLDrawableFactoryImpl) GLDrawableFactory.getDesktopFactory();
//
// GLProfile.initProfiles(desktopFactory.getDefaultDevice());
//// GLProfile.initSingleton();
// profile = GLProfile.getMaxProgrammable(true);
////
// capabilities = new GLCapabilities(profile);
canvas = new GLCanvas();
this.add(canvas);
canvas.addGLEventListener(this);
canvas.addMouseMotionListener(mouseGl);
canvas.addMouseWheelListener(mouseGl);
canvas.addMouseListener(mouseGl);
canvas.addKeyListener(keyGL);
this.setBounds(0,0,600,480);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i = 0; i < Map.getCubesNumber(); i++) {
Random r = new Random();
int x = r.nextInt(Map.getWidth())*Map.getCubesSize();
int z = r.nextInt(Map.getWidth())*Map.getCubesSize();
cubes.add(new Cube(x,Map.getHeight(),z));
}
moveThread.setObjectToMove(cubes);
booleanMap.fill(new Boolean(false));
moveThread.setBooleanMap(booleanMap);
}
// @Override
public void display(GLAutoDrawable drawable) {
GL2 gl = (GL2) drawable.getGL();;
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
// obr�t
gl.glRotatef(KeyGL.getRotateLeft(), 0, 1, 0);
KeyGL.setRotateLeft(0);
gl.glRotatef(KeyGL.getRotateRight(), 0, 1, 0);
KeyGL.setRotateRight(0);
gl.glPushMatrix();
//szeroko�� mapy * szeroko�� klocka
gl.glTranslatef(-(Map.getWidth()*Map.getCubesSize())/2, 0, -(Map.getWidth()*Map.getCubesSize())/2);
// gl.glTranslatef(0, 0, 40);
// gl.glTranslatef(mouseGl.getZ(), 0, mouseGl.getZ());
// glu.gluLookAt(0, 0, 10+mouseGl.getZ(), 0, 0, 0, 0, 1, 1);
// glu.gluLookAt(0, 0, distance, 0, 0, 0, 0, 1, 0);
gl.glPushMatrix();
// klocek.moveOnAxisY(t.getX());
// gl.glRotatef(rotate, 0, 1, 0);
// klocek.drawCube(drawable);
for (int i = 0; i < cubes.size(); i++) {
cubes.get(i).drawCube(drawable);
}
gl.glPopMatrix();
gl.glPushMatrix();
container.drawWireSqare(drawable);
gl.glPopMatrix();
gl.glPopMatrix();
gl.glFlush();
canvas.repaint();
}
// @Override
public void init(GLAutoDrawable drawable) {
GL2 gl = (GL2) drawable.getGL();
gl.glEnable(GL2.GL_NORMALIZE);
gl.glShadeModel(GL2.GL_SMOOTH);
gl.glClearColor(0.0f, 0.0f, 0.8f, 0.0f);
gl.glClearDepth(1.0f);
gl.glPolygonMode(GL.GL_FRONT_AND_BACK, GL2.GL_FILL);
gl.glEnable(GL.GL_DEPTH_TEST);
//Alpha
gl.glBlendFunc(gl.GL_SRC_ALPHA,gl.GL_ONE_MINUS_SRC_ALPHA);
gl.glEnable(gl.GL_BLEND);
gl.glEnable(gl.GL_ALPHA_TEST);
//Lights
gl.glEnable(gl.GL_LIGHTING);
gl.glEnable(gl.GL_LIGHT0);//uaktywnienie źródła światła nr. 0
gl.glEnable(gl.GL_COLOR_MATERIAL); //uaktywnienie śledzenia kolorów
gl.glColorMaterial(gl.GL_FRONT, gl.GL_AMBIENT_AND_DIFFUSE); //kolory ustalone za pomocą glColor
gl.glLightfv(gl.GL_LIGHT0, gl.GL_AMBIENT, new float[] { 0.6f, 0.6f, 0.6f, 0.0f },0);//swiatło otaczające
gl.glLightfv(gl.GL_LIGHT0, gl.GL_DIFFUSE, new float[]{ 0.5f, 0.5f, 0.5f, 0.0f },0);//światło rozproszone
gl.glLightfv(gl.GL_LIGHT0, gl.GL_SPECULAR, new float[]{ 0.4f, 0.4f, 0.4f, 0.0f },0); //światło odbite
gl.glLightfv(gl.GL_LIGHT0, gl.GL_POSITION, new float[]{ 10.0f, 15.0f, 0.0f, 0.0f },0);//pozyc<SUF>
gl.glMaterialfv(gl.GL_FRONT_AND_BACK, gl.GL_AMBIENT, new float[] { 0.7f, 0.7f, 0.7f, 0.0f },0);//swiatło otaczające
gl.glMaterialfv(GL.GL_FRONT_AND_BACK, gl.GL_DIFFUSE, new float[] { 0.7f, 0.7f, 0.7f, 0.0f },0);
gl.glMaterialfv(GL.GL_FRONT_AND_BACK, gl.GL_SPECULAR, new float[] { 0.4f, 0.4f, 0.4f, 0.0f },0);//parametry odblaskowości
gl.glMaterialf(GL.GL_FRONT_AND_BACK, gl.GL_SHININESS, 0.3f);
gl.glCullFace( gl.GL_BACK); // ukrywamy tył
//tekstury
gl.glEnable(GL.GL_TEXTURE_2D);
Cube.setGLContext(drawable);
//kamera
gl.glLoadIdentity();
glu.gluPerspective(45, 1.0*this.getWidth()/this.getHeight(), 1, 1000);
//glu.gluLookAt(0, 0, distance, 0, 0, 0, 1, 0, 0);
glu.gluLookAt(132, 80, 124, 0, 10, 0, 0, 1, 0);
canvas.repaint(); // odswie�enie canvasu z ustawionymi juz parametrami
moveThread.start();
}
// @Override
public void dispose(GLAutoDrawable glAutoDrawable) {
}
// @Override
public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3,
int arg4) {
}
}
|
73016_5 | package zeto.praktyki.Car;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import zeto.praktyki.Car.CarEnums.Drive;
import zeto.praktyki.Car.CarEnums.Gearbox;
import zeto.praktyki.Rent.RentEntity;
import zeto.praktyki.User.UserEntity;
import java.util.HashSet;
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonIdentityReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "car")
// @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
//
// property = "id")
public class CarEntity {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
@Column(nullable = false)
private String brand;
@Column(nullable = false)
private String model;
@Column(nullable = false)
private Integer productionYear;
@Column(nullable = false)
private float fuelConsumption;
@Column(nullable = false)
private float engineCapacity;
@Column(nullable = false)
private Integer horsePower;
@Column(nullable = false)
private Drive drive;
@Column(nullable = false)
private String licensePlate;
@Column(nullable = false)
private int seats;
@Column(nullable = true, length = 1024)
private String description;
@Column(nullable = false)
private double value;
@Column(nullable = false)
private long mileage;
@Column(nullable = false)
private Gearbox gearbox;
@Column(nullable = true, name = "LONG_TEXT", columnDefinition = "TEXT")
String picture;
// @Lob
// @Type(type = "org.hibernate.type.ImageType")
// private byte[] image;
@JsonIdentityReference(alwaysAsId = true)
@JsonIgnore
@OneToMany(mappedBy = "car")
private Set<RentEntity> rents;
@JsonIdentityReference(alwaysAsId = true)
@ManyToOne
@JoinColumn
// @Column(nullable = false) TODO: zmienić na nullable true
private UserEntity addedBy;
protected CarEntity(long id, String brand, String model, Integer productionYear, float fuelConsumption,
float engineCapacity, Integer horsePower, Drive drive, String licensePlate, int seats,
String description, double value, long mileage, Gearbox gearbox, String picture) {
this.id = id;
this.brand = brand;
this.model = model;
this.productionYear = productionYear;
this.fuelConsumption = fuelConsumption;
this.engineCapacity = engineCapacity;
this.horsePower = horsePower;
this.drive = drive;
this.licensePlate = licensePlate;
this.seats = seats;
this.description = description;
this.value = value;
this.mileage = mileage;
this.rents = new HashSet<>();
this.addedBy = null; // TODO jak bedzie token to zmienić
this.gearbox = gearbox;
this.picture = picture;
}
}
| zarnocha/PraktykiZETO | backend/car_rental/src/main/java/zeto/praktyki/Car/CarEntity.java | 896 | // TODO jak bedzie token to zmienić | line_comment | pl | package zeto.praktyki.Car;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import zeto.praktyki.Car.CarEnums.Drive;
import zeto.praktyki.Car.CarEnums.Gearbox;
import zeto.praktyki.Rent.RentEntity;
import zeto.praktyki.User.UserEntity;
import java.util.HashSet;
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonIdentityReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "car")
// @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
//
// property = "id")
public class CarEntity {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
@Column(nullable = false)
private String brand;
@Column(nullable = false)
private String model;
@Column(nullable = false)
private Integer productionYear;
@Column(nullable = false)
private float fuelConsumption;
@Column(nullable = false)
private float engineCapacity;
@Column(nullable = false)
private Integer horsePower;
@Column(nullable = false)
private Drive drive;
@Column(nullable = false)
private String licensePlate;
@Column(nullable = false)
private int seats;
@Column(nullable = true, length = 1024)
private String description;
@Column(nullable = false)
private double value;
@Column(nullable = false)
private long mileage;
@Column(nullable = false)
private Gearbox gearbox;
@Column(nullable = true, name = "LONG_TEXT", columnDefinition = "TEXT")
String picture;
// @Lob
// @Type(type = "org.hibernate.type.ImageType")
// private byte[] image;
@JsonIdentityReference(alwaysAsId = true)
@JsonIgnore
@OneToMany(mappedBy = "car")
private Set<RentEntity> rents;
@JsonIdentityReference(alwaysAsId = true)
@ManyToOne
@JoinColumn
// @Column(nullable = false) TODO: zmienić na nullable true
private UserEntity addedBy;
protected CarEntity(long id, String brand, String model, Integer productionYear, float fuelConsumption,
float engineCapacity, Integer horsePower, Drive drive, String licensePlate, int seats,
String description, double value, long mileage, Gearbox gearbox, String picture) {
this.id = id;
this.brand = brand;
this.model = model;
this.productionYear = productionYear;
this.fuelConsumption = fuelConsumption;
this.engineCapacity = engineCapacity;
this.horsePower = horsePower;
this.drive = drive;
this.licensePlate = licensePlate;
this.seats = seats;
this.description = description;
this.value = value;
this.mileage = mileage;
this.rents = new HashSet<>();
this.addedBy = null; // TODO <SUF>
this.gearbox = gearbox;
this.picture = picture;
}
}
|
89535_10 | import java.util.*;
public class SchedulerSimulator {
private static class Process {
int id; // numer procesu
int burstTime; // czas trwania procesu
int arrivalTime; // czas przyjścia procesu do systemu
int waitingTime; // czas oczekiwania na wykonanie
int remainingTime; // pozostały czas do wykonania
int turnaroundTime; // czas wykonania procesu
boolean started; // czy proces został rozpoczęty
boolean executed; // czy proces został wykonany
public Process(int id, int burstTime, int arrivalTime) {
this.id = id;
this.burstTime = burstTime;
this.arrivalTime = arrivalTime;
this.waitingTime = 0;
this.remainingTime = burstTime;
this.turnaroundTime = 0;
this.executed = false;
this.started = false;
}
public int Execute(int currentTime){
waitingTime = currentTime - arrivalTime;
turnaroundTime = waitingTime + burstTime;
currentTime += burstTime;
remainingTime = 0;
executed = true;
return currentTime;
}
public String ToString(){
return "id: " + id + ", burstTime: " + burstTime + ", arrivalTime: " + arrivalTime + ", waitingTime: " + waitingTime + ", remainingTime: " + remainingTime + ", turnaroundTime: " + turnaroundTime + ", executed: " + executed + ", started: " + started;
}
}
private static List<Process> generateProcesses(int n, int maxBurstTime, int maxArrivalTime) {
List<Process> processes = new ArrayList<>();
Random random = new Random();
for (int i = 1; i <= n; i++) {
int burstTime = random.nextInt(maxBurstTime) + 1;
int arrivalTime = random.nextInt(maxArrivalTime) + 1;
processes.add(new Process(i, burstTime, arrivalTime));
}
return processes;
}
private static List<Process> generateTestProcesses() {
List<Process> processes = new ArrayList<>();
/*processes.add(new Process(1, 5, 0));
processes.add(new Process(2, 3, 1));
processes.add(new Process(3, 6, 3));
processes.add(new Process(4, 1, 5));
processes.add(new Process(5, 4, 6));*/
processes.add(new Process(1, 1, 0));
processes.add(new Process(2, 3, 3));
processes.add(new Process(3, 6, 3));
processes.add(new Process(4, 1, 5));
processes.add(new Process(5, 4, 6));
return processes;
}
private static int scheduleFCFS(List<Process> processes) {
int currentTime = 0;
for (Process process : processes) {
if (process.arrivalTime > currentTime) {
currentTime = process.arrivalTime;
}
currentTime = process.Execute(currentTime);
}
return currentTime;
}
private static int scheduleSJF(List<Process> processes) {
int currentTime = 0;
int i = -1;
List<Process> queue = new ArrayList<>();
while(i < processes.size() || !queue.isEmpty()){
if(!queue.isEmpty()){
Collections.sort(queue, Comparator.comparingInt(p -> p.burstTime));
Process process = queue.get(0);
currentTime = process.Execute(currentTime);
//System.out.println(queue.size());
queue.remove(0);
for (Process _process : processes) {
if(_process.arrivalTime <= currentTime && !_process.executed) {
queue.add(_process);
i++;
}
else{
if(queue.contains(process))queue.remove(process);
}
}
}
else if(i < processes.size()){
i++;
Process process = processes.get(i);
if(!process.executed) {
queue.add(process);
currentTime = process.arrivalTime;
}
}
}
return currentTime;
}
private static int scheduleSJFPreemptive(List<Process> processes) {
int currentTime = processes.get(0).arrivalTime;
int executedIndex = 0;
List<Process> queue = new ArrayList<>();
Process currentProcess = null;
while (executedIndex < processes.size()) {
for (Process process : processes) {
if (process.arrivalTime <= currentTime && !process.executed && (currentProcess == null || process.burstTime < currentProcess.burstTime)) {
if (currentProcess != null) {
queue.add(currentProcess);
}
currentProcess = process;
}
}
if (currentProcess == null) {
currentTime++;
if(currentTime > 10000) break; //tak zeby sie nie robiło w nieskonczonosc w razie bledu
}
else {
currentProcess.remainingTime--;
if (currentProcess.remainingTime == 0) {
currentProcess.waitingTime = currentTime - currentProcess.arrivalTime - currentProcess.burstTime + 1;
currentProcess.turnaroundTime = currentProcess.waitingTime + currentProcess.burstTime;
currentProcess.executed = true;
executedIndex++;
currentProcess = null;
}
currentTime++;
if (!queue.isEmpty() && currentProcess == null) {
Collections.sort(queue, Comparator.comparingInt(p -> p.burstTime));
currentProcess = queue.get(0);
queue.remove(0);
}
}
}
return currentTime;
}
private static int scheduleRR(List<Process> processes, int timeQuant) {
int currentTime = processes.get(0).arrivalTime;
int executedIndex = 0;
Process prevProcess = null;
Queue<Process> roundRobinQueue = new LinkedList<>();
do{
for (Process process : processes) {
if (process.arrivalTime <= currentTime && !process.started) {
roundRobinQueue.add(process);
process.started = true;
}
}
if (prevProcess != null) roundRobinQueue.add(prevProcess);
prevProcess = null;
if (!roundRobinQueue.isEmpty()) {
Process currentProcess = roundRobinQueue.poll();
//System.out.println(currentProcess.id + " " + currentTime);
if (currentProcess.remainingTime <= timeQuant) {
currentProcess.waitingTime = Integer.max(0, currentTime - currentProcess.arrivalTime);
currentProcess.turnaroundTime = currentProcess.waitingTime + currentProcess.burstTime;
currentProcess.executed = true;
executedIndex++;
currentTime += currentProcess.remainingTime;
currentProcess.remainingTime = 0;
} else {
currentProcess.remainingTime -= timeQuant;
prevProcess = currentProcess;
currentTime += timeQuant;
}
}
else currentTime++;
}
while (!roundRobinQueue.isEmpty() || executedIndex < processes.size());
return currentTime;
}
public static void main(String[] args) {
int n = 10; //50
int maxBurstTime = 20;//20
int maxArrivalTime = 20;//20
int timeQuant = 21;
List<Process> processes = generateProcesses(n, maxBurstTime, maxArrivalTime);
//List<Process> processes = generateTestProcesses();
System.out.println("\n==================================\n");
Collections.sort(processes, Comparator.comparingInt(p -> p.arrivalTime));
for (Process process : processes) System.out.println(process.ToString());
System.out.println("\n==================================\n");
List<Process> fcfsProcesses = new ArrayList<>();
for(Process process : processes) fcfsProcesses.add(new Process(process.id, process.burstTime, process.arrivalTime));
//Collections.sort(fcfsProcesses, Comparator.comparingInt(p -> p.arrivalTime));
List<Process> sfjProcesses = new ArrayList<>();
for(Process process : processes) sfjProcesses.add(new Process(process.id, process.burstTime, process.arrivalTime));
//Collections.sort(sfjProcesses, Comparator.comparingInt(p -> p.arrivalTime));
List<Process> sjfPreemptiveProcesses = new ArrayList<>();
for(Process process : processes) sjfPreemptiveProcesses.add(new Process(process.id, process.burstTime, process.arrivalTime));
//Collections.sort(sjfPreemptiveProcesses, Comparator.comparingInt(p -> p.arrivalTime));
List<Process> rrProcesses = new ArrayList<>();
for(Process process : processes) rrProcesses.add(new Process(process.id, process.burstTime, process.arrivalTime));
double fcfsFinalTime = scheduleFCFS(fcfsProcesses);
double fcfsAverageWaitingTime = 0;
for (Process process : fcfsProcesses) {
System.out.println(process.ToString());
fcfsAverageWaitingTime += process.waitingTime;
}
fcfsAverageWaitingTime /= n;
System.out.println("Algorytm FCFS: średni czas oczekiwania = " + fcfsAverageWaitingTime);
System.out.println("Algorytm FCFS: czas wykonania wszystkich procesów = " + fcfsFinalTime);
System.out.println("\n==================================\n");
double sfjFinalTime = scheduleSJF(sfjProcesses);
double sjfAverageWaitingTime = 0;
for (Process process : sfjProcesses) {
System.out.println(process.ToString());
sjfAverageWaitingTime += process.waitingTime;
}
sjfAverageWaitingTime /= n;
System.out.println("Algorytm SJF bez wywłaszczania: średni czas oczekiwania = " + sjfAverageWaitingTime);
System.out.println("Algorytm SJF bez wywłaszczania: czas wykonania wszystkich procesów = " + sfjFinalTime);
System.out.println("\n==================================\n");
double sfjPreemptiveFinalTime = scheduleSJFPreemptive(sjfPreemptiveProcesses);
double sjfPreemptiveAverageWaitingTime = 0;
for (Process process : sjfPreemptiveProcesses) {
System.out.println(process.ToString());
sjfPreemptiveAverageWaitingTime += process.waitingTime;
}
sjfPreemptiveAverageWaitingTime /= n;
System.out.println("Algorytm SJF z wywłaszczaniem: średni czas oczekiwania = " + sjfPreemptiveAverageWaitingTime);
System.out.println("Algorytm SJF z wywłaszczaniem: czas wykonania wszystkich procesów = " + sfjPreemptiveFinalTime);
System.out.println("\n==================================\n");
double rrFinalTime = scheduleRR(rrProcesses, timeQuant);
double rrAverageWaitingTime = 0;
for (Process process : rrProcesses) {
System.out.println(process.ToString());
rrAverageWaitingTime += process.waitingTime;
}
rrAverageWaitingTime /= n;
System.out.println("Algorytm rotacyjny z wyborem kwantu czasu: średni czas oczekiwania = " + rrAverageWaitingTime);
System.out.println("Algorytm rotacyjny z wyborem kwantu czasu: czas wykonania wszystkich procesów " + rrFinalTime);
}
} | zawodev/PWR | sem2/AiDS-java/so-lab/src/SchedulerSimulator.java | 3,161 | //tak zeby sie nie robiło w nieskonczonosc w razie bledu | line_comment | pl | import java.util.*;
public class SchedulerSimulator {
private static class Process {
int id; // numer procesu
int burstTime; // czas trwania procesu
int arrivalTime; // czas przyjścia procesu do systemu
int waitingTime; // czas oczekiwania na wykonanie
int remainingTime; // pozostały czas do wykonania
int turnaroundTime; // czas wykonania procesu
boolean started; // czy proces został rozpoczęty
boolean executed; // czy proces został wykonany
public Process(int id, int burstTime, int arrivalTime) {
this.id = id;
this.burstTime = burstTime;
this.arrivalTime = arrivalTime;
this.waitingTime = 0;
this.remainingTime = burstTime;
this.turnaroundTime = 0;
this.executed = false;
this.started = false;
}
public int Execute(int currentTime){
waitingTime = currentTime - arrivalTime;
turnaroundTime = waitingTime + burstTime;
currentTime += burstTime;
remainingTime = 0;
executed = true;
return currentTime;
}
public String ToString(){
return "id: " + id + ", burstTime: " + burstTime + ", arrivalTime: " + arrivalTime + ", waitingTime: " + waitingTime + ", remainingTime: " + remainingTime + ", turnaroundTime: " + turnaroundTime + ", executed: " + executed + ", started: " + started;
}
}
private static List<Process> generateProcesses(int n, int maxBurstTime, int maxArrivalTime) {
List<Process> processes = new ArrayList<>();
Random random = new Random();
for (int i = 1; i <= n; i++) {
int burstTime = random.nextInt(maxBurstTime) + 1;
int arrivalTime = random.nextInt(maxArrivalTime) + 1;
processes.add(new Process(i, burstTime, arrivalTime));
}
return processes;
}
private static List<Process> generateTestProcesses() {
List<Process> processes = new ArrayList<>();
/*processes.add(new Process(1, 5, 0));
processes.add(new Process(2, 3, 1));
processes.add(new Process(3, 6, 3));
processes.add(new Process(4, 1, 5));
processes.add(new Process(5, 4, 6));*/
processes.add(new Process(1, 1, 0));
processes.add(new Process(2, 3, 3));
processes.add(new Process(3, 6, 3));
processes.add(new Process(4, 1, 5));
processes.add(new Process(5, 4, 6));
return processes;
}
private static int scheduleFCFS(List<Process> processes) {
int currentTime = 0;
for (Process process : processes) {
if (process.arrivalTime > currentTime) {
currentTime = process.arrivalTime;
}
currentTime = process.Execute(currentTime);
}
return currentTime;
}
private static int scheduleSJF(List<Process> processes) {
int currentTime = 0;
int i = -1;
List<Process> queue = new ArrayList<>();
while(i < processes.size() || !queue.isEmpty()){
if(!queue.isEmpty()){
Collections.sort(queue, Comparator.comparingInt(p -> p.burstTime));
Process process = queue.get(0);
currentTime = process.Execute(currentTime);
//System.out.println(queue.size());
queue.remove(0);
for (Process _process : processes) {
if(_process.arrivalTime <= currentTime && !_process.executed) {
queue.add(_process);
i++;
}
else{
if(queue.contains(process))queue.remove(process);
}
}
}
else if(i < processes.size()){
i++;
Process process = processes.get(i);
if(!process.executed) {
queue.add(process);
currentTime = process.arrivalTime;
}
}
}
return currentTime;
}
private static int scheduleSJFPreemptive(List<Process> processes) {
int currentTime = processes.get(0).arrivalTime;
int executedIndex = 0;
List<Process> queue = new ArrayList<>();
Process currentProcess = null;
while (executedIndex < processes.size()) {
for (Process process : processes) {
if (process.arrivalTime <= currentTime && !process.executed && (currentProcess == null || process.burstTime < currentProcess.burstTime)) {
if (currentProcess != null) {
queue.add(currentProcess);
}
currentProcess = process;
}
}
if (currentProcess == null) {
currentTime++;
if(currentTime > 10000) break; //tak z<SUF>
}
else {
currentProcess.remainingTime--;
if (currentProcess.remainingTime == 0) {
currentProcess.waitingTime = currentTime - currentProcess.arrivalTime - currentProcess.burstTime + 1;
currentProcess.turnaroundTime = currentProcess.waitingTime + currentProcess.burstTime;
currentProcess.executed = true;
executedIndex++;
currentProcess = null;
}
currentTime++;
if (!queue.isEmpty() && currentProcess == null) {
Collections.sort(queue, Comparator.comparingInt(p -> p.burstTime));
currentProcess = queue.get(0);
queue.remove(0);
}
}
}
return currentTime;
}
private static int scheduleRR(List<Process> processes, int timeQuant) {
int currentTime = processes.get(0).arrivalTime;
int executedIndex = 0;
Process prevProcess = null;
Queue<Process> roundRobinQueue = new LinkedList<>();
do{
for (Process process : processes) {
if (process.arrivalTime <= currentTime && !process.started) {
roundRobinQueue.add(process);
process.started = true;
}
}
if (prevProcess != null) roundRobinQueue.add(prevProcess);
prevProcess = null;
if (!roundRobinQueue.isEmpty()) {
Process currentProcess = roundRobinQueue.poll();
//System.out.println(currentProcess.id + " " + currentTime);
if (currentProcess.remainingTime <= timeQuant) {
currentProcess.waitingTime = Integer.max(0, currentTime - currentProcess.arrivalTime);
currentProcess.turnaroundTime = currentProcess.waitingTime + currentProcess.burstTime;
currentProcess.executed = true;
executedIndex++;
currentTime += currentProcess.remainingTime;
currentProcess.remainingTime = 0;
} else {
currentProcess.remainingTime -= timeQuant;
prevProcess = currentProcess;
currentTime += timeQuant;
}
}
else currentTime++;
}
while (!roundRobinQueue.isEmpty() || executedIndex < processes.size());
return currentTime;
}
public static void main(String[] args) {
int n = 10; //50
int maxBurstTime = 20;//20
int maxArrivalTime = 20;//20
int timeQuant = 21;
List<Process> processes = generateProcesses(n, maxBurstTime, maxArrivalTime);
//List<Process> processes = generateTestProcesses();
System.out.println("\n==================================\n");
Collections.sort(processes, Comparator.comparingInt(p -> p.arrivalTime));
for (Process process : processes) System.out.println(process.ToString());
System.out.println("\n==================================\n");
List<Process> fcfsProcesses = new ArrayList<>();
for(Process process : processes) fcfsProcesses.add(new Process(process.id, process.burstTime, process.arrivalTime));
//Collections.sort(fcfsProcesses, Comparator.comparingInt(p -> p.arrivalTime));
List<Process> sfjProcesses = new ArrayList<>();
for(Process process : processes) sfjProcesses.add(new Process(process.id, process.burstTime, process.arrivalTime));
//Collections.sort(sfjProcesses, Comparator.comparingInt(p -> p.arrivalTime));
List<Process> sjfPreemptiveProcesses = new ArrayList<>();
for(Process process : processes) sjfPreemptiveProcesses.add(new Process(process.id, process.burstTime, process.arrivalTime));
//Collections.sort(sjfPreemptiveProcesses, Comparator.comparingInt(p -> p.arrivalTime));
List<Process> rrProcesses = new ArrayList<>();
for(Process process : processes) rrProcesses.add(new Process(process.id, process.burstTime, process.arrivalTime));
double fcfsFinalTime = scheduleFCFS(fcfsProcesses);
double fcfsAverageWaitingTime = 0;
for (Process process : fcfsProcesses) {
System.out.println(process.ToString());
fcfsAverageWaitingTime += process.waitingTime;
}
fcfsAverageWaitingTime /= n;
System.out.println("Algorytm FCFS: średni czas oczekiwania = " + fcfsAverageWaitingTime);
System.out.println("Algorytm FCFS: czas wykonania wszystkich procesów = " + fcfsFinalTime);
System.out.println("\n==================================\n");
double sfjFinalTime = scheduleSJF(sfjProcesses);
double sjfAverageWaitingTime = 0;
for (Process process : sfjProcesses) {
System.out.println(process.ToString());
sjfAverageWaitingTime += process.waitingTime;
}
sjfAverageWaitingTime /= n;
System.out.println("Algorytm SJF bez wywłaszczania: średni czas oczekiwania = " + sjfAverageWaitingTime);
System.out.println("Algorytm SJF bez wywłaszczania: czas wykonania wszystkich procesów = " + sfjFinalTime);
System.out.println("\n==================================\n");
double sfjPreemptiveFinalTime = scheduleSJFPreemptive(sjfPreemptiveProcesses);
double sjfPreemptiveAverageWaitingTime = 0;
for (Process process : sjfPreemptiveProcesses) {
System.out.println(process.ToString());
sjfPreemptiveAverageWaitingTime += process.waitingTime;
}
sjfPreemptiveAverageWaitingTime /= n;
System.out.println("Algorytm SJF z wywłaszczaniem: średni czas oczekiwania = " + sjfPreemptiveAverageWaitingTime);
System.out.println("Algorytm SJF z wywłaszczaniem: czas wykonania wszystkich procesów = " + sfjPreemptiveFinalTime);
System.out.println("\n==================================\n");
double rrFinalTime = scheduleRR(rrProcesses, timeQuant);
double rrAverageWaitingTime = 0;
for (Process process : rrProcesses) {
System.out.println(process.ToString());
rrAverageWaitingTime += process.waitingTime;
}
rrAverageWaitingTime /= n;
System.out.println("Algorytm rotacyjny z wyborem kwantu czasu: średni czas oczekiwania = " + rrAverageWaitingTime);
System.out.println("Algorytm rotacyjny z wyborem kwantu czasu: czas wykonania wszystkich procesów " + rrFinalTime);
}
} |
49677_2 | import org.w3c.dom.ls.LSOutput;
import java.util.Arrays;
import java.util.Random;
public class Main {
public static void main(String[] args) throws InterruptedException {
int threads = Runtime.getRuntime().availableProcessors();
System.out.println("COMPUTER HAS " + threads + " THREADS");
// Nasza tablica o rozmiarze 100 z losowymi dannymi
// Ale to bedzie problem dla naprzyklad 15tu elementow
// poniewaz kazda podtablica bedzie miala tylko 1 element O_o
int[] array = new int[new Random().nextInt(10) + 1];
int[][] divided = new int[threads][];
int toGetSize = array.length / threads; // Size of subArray divided by each thread
int initialLength = array.length;
System.out.println("NOT SORTED");
for (int i = 0; i < array.length; i++)
array[i] = new Random().nextInt(100);
System.out.println(Arrays.toString(array));
if (array.length < threads) {
int[] newArray = new int[threads];
System.arraycopy(array, 0, newArray, threads - array.length, array.length);
array = newArray;
toGetSize = 1; // update array size for absolute division for each threads
}
System.out.println("SUBARRAY SIZE: " + toGetSize);
for (int i = 0; i < threads; i++) {
int[] subArr = (i == threads - 1) ? new int[array.length - i * toGetSize] : new int[toGetSize];
System.arraycopy(array, i * toGetSize, subArr, 0, (i == threads - 1) ? array.length - i * toGetSize : toGetSize);
divided[i] = subArr;
}
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <-- array
// |_| |_| |_| |_| |__| |___| |___| |...............| <-- subArrays by threads
int repeats = threads;
int[][] tempArr;
while (repeats > 1) {
tempArr = new int[repeats / 2][];
for (int i = 0; i < repeats; i += 2) {
Worker runner1 = new Worker(divided[i]);
Worker runner2 = new Worker(divided[i + 1]);
runner1.start();
runner2.start();
runner1.join();
runner2.join();
tempArr[i / 2] = finalMerge(runner1.getInternal(), runner2.getInternal());
}
repeats /= 2;
divided = tempArr;
}
int[] res;
if (initialLength < threads) {
res = new int[initialLength];
System.arraycopy(divided[0], threads - initialLength, res, 0, initialLength);
} else {
res = divided[0];
}
System.out.println("SORTED\n" + Arrays.toString(res));
}
public static int[] finalMerge(int[] a, int[] b) {
int[] result = new int[a.length + b.length];
int i = 0;
int j = 0;
int r = 0;
while (i < a.length && j < b.length) {
if (a[i] <= b[j]) {
result[r] = a[i];
i++;
} else {
result[r] = b[j];
j++;
}
r++;
if (i == a.length) {
while (j < b.length) {
result[r] = b[j];
r++;
j++;
}
}
if (j == b.length) {
while (i < a.length) {
result[r] = a[i];
r++;
i++;
}
}
}
return result;
}
static class Worker extends Thread {
private int[] internal;
public int[] getInternal() {
return internal;
}
public void mergeSort(int[] array) {
if (array.length > 1) {
int[] left = leftHalf(array);
int[] right = rightHalf(array);
mergeSort(left);
mergeSort(right);
merge(array, left, right);
}
}
public int[] leftHalf(int[] array) {
int size1 = array.length / 2;
int[] left = new int[size1];
System.arraycopy(array, 0, left, 0, size1);
return left;
}
public int[] rightHalf(int[] array) {
int size1 = array.length / 2;
int size2 = array.length - size1;
int[] right = new int[size2];
System.arraycopy(array, size1, right, 0, size2);
return right;
}
public void merge(int[] result, int[] left, int[] right) {
int i1 = 0;
int i2 = 0;
for (int i = 0; i < result.length; i++) {
if (i2 >= right.length || (i1 < left.length && left[i1] <= right[i2])) {
result[i] = left[i1];
i1++;
} else {
result[i] = right[i2];
i2++;
}
}
}
Worker(int[] arr) {
internal = arr;
}
public void run() {
mergeSort(internal);
}
}
} | zaxoavoki/pwr | sem_3/PP/Laboratoria/lista_11/src/Main.java | 1,569 | // poniewaz kazda podtablica bedzie miala tylko 1 element O_o | line_comment | pl | import org.w3c.dom.ls.LSOutput;
import java.util.Arrays;
import java.util.Random;
public class Main {
public static void main(String[] args) throws InterruptedException {
int threads = Runtime.getRuntime().availableProcessors();
System.out.println("COMPUTER HAS " + threads + " THREADS");
// Nasza tablica o rozmiarze 100 z losowymi dannymi
// Ale to bedzie problem dla naprzyklad 15tu elementow
// ponie<SUF>
int[] array = new int[new Random().nextInt(10) + 1];
int[][] divided = new int[threads][];
int toGetSize = array.length / threads; // Size of subArray divided by each thread
int initialLength = array.length;
System.out.println("NOT SORTED");
for (int i = 0; i < array.length; i++)
array[i] = new Random().nextInt(100);
System.out.println(Arrays.toString(array));
if (array.length < threads) {
int[] newArray = new int[threads];
System.arraycopy(array, 0, newArray, threads - array.length, array.length);
array = newArray;
toGetSize = 1; // update array size for absolute division for each threads
}
System.out.println("SUBARRAY SIZE: " + toGetSize);
for (int i = 0; i < threads; i++) {
int[] subArr = (i == threads - 1) ? new int[array.length - i * toGetSize] : new int[toGetSize];
System.arraycopy(array, i * toGetSize, subArr, 0, (i == threads - 1) ? array.length - i * toGetSize : toGetSize);
divided[i] = subArr;
}
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <-- array
// |_| |_| |_| |_| |__| |___| |___| |...............| <-- subArrays by threads
int repeats = threads;
int[][] tempArr;
while (repeats > 1) {
tempArr = new int[repeats / 2][];
for (int i = 0; i < repeats; i += 2) {
Worker runner1 = new Worker(divided[i]);
Worker runner2 = new Worker(divided[i + 1]);
runner1.start();
runner2.start();
runner1.join();
runner2.join();
tempArr[i / 2] = finalMerge(runner1.getInternal(), runner2.getInternal());
}
repeats /= 2;
divided = tempArr;
}
int[] res;
if (initialLength < threads) {
res = new int[initialLength];
System.arraycopy(divided[0], threads - initialLength, res, 0, initialLength);
} else {
res = divided[0];
}
System.out.println("SORTED\n" + Arrays.toString(res));
}
public static int[] finalMerge(int[] a, int[] b) {
int[] result = new int[a.length + b.length];
int i = 0;
int j = 0;
int r = 0;
while (i < a.length && j < b.length) {
if (a[i] <= b[j]) {
result[r] = a[i];
i++;
} else {
result[r] = b[j];
j++;
}
r++;
if (i == a.length) {
while (j < b.length) {
result[r] = b[j];
r++;
j++;
}
}
if (j == b.length) {
while (i < a.length) {
result[r] = a[i];
r++;
i++;
}
}
}
return result;
}
static class Worker extends Thread {
private int[] internal;
public int[] getInternal() {
return internal;
}
public void mergeSort(int[] array) {
if (array.length > 1) {
int[] left = leftHalf(array);
int[] right = rightHalf(array);
mergeSort(left);
mergeSort(right);
merge(array, left, right);
}
}
public int[] leftHalf(int[] array) {
int size1 = array.length / 2;
int[] left = new int[size1];
System.arraycopy(array, 0, left, 0, size1);
return left;
}
public int[] rightHalf(int[] array) {
int size1 = array.length / 2;
int size2 = array.length - size1;
int[] right = new int[size2];
System.arraycopy(array, size1, right, 0, size2);
return right;
}
public void merge(int[] result, int[] left, int[] right) {
int i1 = 0;
int i2 = 0;
for (int i = 0; i < result.length; i++) {
if (i2 >= right.length || (i1 < left.length && left[i1] <= right[i2])) {
result[i] = left[i1];
i1++;
} else {
result[i] = right[i2];
i2++;
}
}
}
Worker(int[] arr) {
internal = arr;
}
public void run() {
mergeSort(internal);
}
}
} |
178434_1 | package com.github.zaza;
import static java.lang.String.format;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URI;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import com.github.zaza.olx.OlxOffer;
import com.github.zaza.olx.SearchResult;
import com.rometools.rome.feed.synd.SyndContent;
import com.rometools.rome.feed.synd.SyndContentImpl;
import com.rometools.rome.feed.synd.SyndEntry;
import com.rometools.rome.feed.synd.SyndEntryImpl;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.feed.synd.SyndFeedImpl;
import com.rometools.rome.feed.synd.SyndImage;
import com.rometools.rome.feed.synd.SyndImageImpl;
import com.rometools.rome.io.FeedException;
import com.rometools.rome.io.SyndFeedOutput;
public class FeedWriter {
public String write(SearchResult result) throws IOException, FeedException {
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType("rss_2.0");
feed.setTitle(format("OLX.pl \"%s\"", result.getFilterDescription()));
feed.setLink(result.getUrl().toString());
feed.setDescription("Ogłoszenia spełniające Twoje kryteria wyszukiwania");
SyndImage image = new SyndImageImpl();
image.setTitle("OLX.pl");
image.setUrl("https://www.olx.pl/favicon.ico");
image.setLink("https://www.olx.pl");
feed.setImage(image);
List<SyndEntry> entries = result.getItems().stream().map(this::feedEntry).collect(Collectors.toList());
feed.setEntries(entries);
return write(feed);
}
private SyndEntry feedEntry(OlxOffer item) {
SyndEntry entry = new SyndEntryImpl();
entry.setTitle(item.getTitle());
entry.setLink(item.getUri().toString());
entry.setPublishedDate(new Date());
entry.setDescription(createDescription(item));
return entry;
}
private SyndContent createDescription(OlxOffer item) {
SyndContent description = new SyndContentImpl();
description.setType("text/html");
StringBuilder sb = new StringBuilder();
sb.append(format("Cena: %s<br />", item.getPrice()));
sb.append(format("Lokalizacja: %s<br />", item.getCity()));
sb.append(formatPhoto(item.getPhoto()));
description.setValue(sb.toString());
return description;
}
private String formatPhoto(URI photo) {
return photo != null ? asImg(photo) : "";
}
private String asImg(URI photo) {
return format("<img src=\"%s\" width=\"128\" height=\"96\" alt=\"\" ><br />", photo.toString());
}
private String write(SyndFeed feed) throws IOException, FeedException {
Writer writer = new StringWriter();
SyndFeedOutput output = new SyndFeedOutput();
output.output(feed, writer);
writer.close();
return writer.toString();
}
}
| zaza/olx-rss | src/main/java/com/github/zaza/FeedWriter.java | 1,005 | //www.olx.pl");
| line_comment | pl | package com.github.zaza;
import static java.lang.String.format;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URI;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import com.github.zaza.olx.OlxOffer;
import com.github.zaza.olx.SearchResult;
import com.rometools.rome.feed.synd.SyndContent;
import com.rometools.rome.feed.synd.SyndContentImpl;
import com.rometools.rome.feed.synd.SyndEntry;
import com.rometools.rome.feed.synd.SyndEntryImpl;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.feed.synd.SyndFeedImpl;
import com.rometools.rome.feed.synd.SyndImage;
import com.rometools.rome.feed.synd.SyndImageImpl;
import com.rometools.rome.io.FeedException;
import com.rometools.rome.io.SyndFeedOutput;
public class FeedWriter {
public String write(SearchResult result) throws IOException, FeedException {
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType("rss_2.0");
feed.setTitle(format("OLX.pl \"%s\"", result.getFilterDescription()));
feed.setLink(result.getUrl().toString());
feed.setDescription("Ogłoszenia spełniające Twoje kryteria wyszukiwania");
SyndImage image = new SyndImageImpl();
image.setTitle("OLX.pl");
image.setUrl("https://www.olx.pl/favicon.ico");
image.setLink("https://www.o<SUF>
feed.setImage(image);
List<SyndEntry> entries = result.getItems().stream().map(this::feedEntry).collect(Collectors.toList());
feed.setEntries(entries);
return write(feed);
}
private SyndEntry feedEntry(OlxOffer item) {
SyndEntry entry = new SyndEntryImpl();
entry.setTitle(item.getTitle());
entry.setLink(item.getUri().toString());
entry.setPublishedDate(new Date());
entry.setDescription(createDescription(item));
return entry;
}
private SyndContent createDescription(OlxOffer item) {
SyndContent description = new SyndContentImpl();
description.setType("text/html");
StringBuilder sb = new StringBuilder();
sb.append(format("Cena: %s<br />", item.getPrice()));
sb.append(format("Lokalizacja: %s<br />", item.getCity()));
sb.append(formatPhoto(item.getPhoto()));
description.setValue(sb.toString());
return description;
}
private String formatPhoto(URI photo) {
return photo != null ? asImg(photo) : "";
}
private String asImg(URI photo) {
return format("<img src=\"%s\" width=\"128\" height=\"96\" alt=\"\" ><br />", photo.toString());
}
private String write(SyndFeed feed) throws IOException, FeedException {
Writer writer = new StringWriter();
SyndFeedOutput output = new SyndFeedOutput();
output.output(feed, writer);
writer.close();
return writer.toString();
}
}
|
15023_19 | package com.swistak.webapi.model;
/**
* http://www.swistak.pl/out/wsdl/wsdl.html?method=add_auction
*/
public enum AddAuctionStatus {
OK,
/** Niepoprawny hash lub sesja utraciła ważność. */
ERR_AUTHORIZATION,
/** Konto użytkownika posiada ograniczenia na sprzedaż. */
ERR_USER_STATUS,
/** Użytkownik nie zaakceptował aktualnej wersji regulaminu. */
ERR_NOT_ACCEPTED_RULES,
/** Niepoprawny numer id_out. */
ERR_INVALID_ID_OUT,
/** Brak tytułu lub tytuł przekracza 50 znaków. */
ERR_INVALID_TITLE,
/** Brak ceny lub cena większa niż 100000000.00. */
ERR_INVALID_PRICE,
/** Brak określonej ilości sztuk towaru lub ilość sztuk większa niż 9999999. */
ERR_INVALID_ITEM_COUNT,
/** Brak opisu przedmiotu lub opis krótszy niż 20 znaków. */
ERR_INVALID_DESCRIPTION,
/** Słowa pomocnicze dłuższe niż 64 znaki. */
ERR_INVALID_TAGS,
/** Kategoria nie istnieje lub posiada podkategorie. */
ERR_INVALID_CATEGORY,
/** Nazwa lokalizacji posiada powyżej 50 znaków. */
ERR_INVALID_CITY,
/** Użytkowik posiada trwającą aukcję o taki samym id_out. */
ERR_DUPLICATE_ID_OUT,
/**
* Błędnie określone koszty przesyłki. Błędny zakres ilości sztuk lub brak
* kosztu dostawy.
*/
ERR_INVALID_DELIVERY_COST_1,
/**
* Błędnie określone koszty przesyłki. Błędny zakres ilości sztuk lub brak
* kosztu dostawy.
*/
ERR_INVALID_DELIVERY_COST_2,
/**
* Błędnie określone koszty przesyłki. Błędny zakres ilości sztuk lub brak
* kosztu dostawy.
*/
ERR_INVALID_DELIVERY_COST_3,
/**
* Błędnie określone koszty przesyłki. Błędny zakres ilości sztuk lub brak
* kosztu dostawy.
*/
ERR_INVALID_DELIVERY_COST_4,
/**
* Błędnie określone koszty przesyłki. Błędny zakres ilości sztuk lub brak
* kosztu dostawy.
*/
ERR_INVALID_DELIVERY_COST_5,
/**
* Błędnie określone koszty przesyłki. Błędny zakres ilości sztuk lub brak
* kosztu dostawy.
*/
ERR_INVALID_DELIVERY_COST_6,
/**
* Błędnie określone koszty przesyłki. Błędny zakres ilości sztuk lub brak
* kosztu dostawy.
*/
ERR_INVALID_DELIVERY_COST_7,
/**
* Błędnie określone koszty przesyłki. Błędny zakres ilości sztuk lub brak
* kosztu dostawy.
*/
ERR_INVALID_DELIVERY_COST_8,
/**
* Błędnie określone koszty przesyłki. Błędny zakres ilości sztuk lub brak
* kosztu dostawy.
*/
ERR_INVALID_DELIVERY_COST_9,
/**
* Błędnie określone koszty przesyłki. Błędny zakres ilości sztuk lub brak
* kosztu dostawy.
*/
ERR_INVALID_DELIVERY_COST_10,
/**
* Nie określono żadnej formy przesyłki. Należy określić koszty przesyłki
* dla wszystkich sztuk towaru przynjmniej dla jednej formy przesyłki.
*/
ERR_INVALID_DELIVERY_COST,
/** Wewnętrzny błąd WebAPI Swistak.pl. */
ERR_INTERNAL_SERVER_ERROR;
}
| zaza/swistak-webapi | src/com/swistak/webapi/model/AddAuctionStatus.java | 1,336 | /**
* Błędnie określone koszty przesyłki. Błędny zakres ilości sztuk lub brak
* kosztu dostawy.
*/ | block_comment | pl | package com.swistak.webapi.model;
/**
* http://www.swistak.pl/out/wsdl/wsdl.html?method=add_auction
*/
public enum AddAuctionStatus {
OK,
/** Niepoprawny hash lub sesja utraciła ważność. */
ERR_AUTHORIZATION,
/** Konto użytkownika posiada ograniczenia na sprzedaż. */
ERR_USER_STATUS,
/** Użytkownik nie zaakceptował aktualnej wersji regulaminu. */
ERR_NOT_ACCEPTED_RULES,
/** Niepoprawny numer id_out. */
ERR_INVALID_ID_OUT,
/** Brak tytułu lub tytuł przekracza 50 znaków. */
ERR_INVALID_TITLE,
/** Brak ceny lub cena większa niż 100000000.00. */
ERR_INVALID_PRICE,
/** Brak określonej ilości sztuk towaru lub ilość sztuk większa niż 9999999. */
ERR_INVALID_ITEM_COUNT,
/** Brak opisu przedmiotu lub opis krótszy niż 20 znaków. */
ERR_INVALID_DESCRIPTION,
/** Słowa pomocnicze dłuższe niż 64 znaki. */
ERR_INVALID_TAGS,
/** Kategoria nie istnieje lub posiada podkategorie. */
ERR_INVALID_CATEGORY,
/** Nazwa lokalizacji posiada powyżej 50 znaków. */
ERR_INVALID_CITY,
/** Użytkowik posiada trwającą aukcję o taki samym id_out. */
ERR_DUPLICATE_ID_OUT,
/**
* Błędnie określone koszty przesyłki. Błędny zakres ilości sztuk lub brak
* kosztu dostawy.
*/
ERR_INVALID_DELIVERY_COST_1,
/**
* Błędnie określone koszty przesyłki. Błędny zakres ilości sztuk lub brak
* kosztu dostawy.
*/
ERR_INVALID_DELIVERY_COST_2,
/**
* Błędnie określone koszty przesyłki. Błędny zakres ilości sztuk lub brak
* kosztu dostawy.
*/
ERR_INVALID_DELIVERY_COST_3,
/**
* Błędnie określone koszty przesyłki. Błędny zakres ilości sztuk lub brak
* kosztu dostawy.
*/
ERR_INVALID_DELIVERY_COST_4,
/**
* Błędnie określone koszty przesyłki. Błędny zakres ilości sztuk lub brak
* kosztu dostawy.
*/
ERR_INVALID_DELIVERY_COST_5,
/**
* Błędnie określone koszty przesyłki. Błędny zakres ilości sztuk lub brak
* kosztu dostawy.
*/
ERR_INVALID_DELIVERY_COST_6,
/**
* Błędni<SUF>*/
ERR_INVALID_DELIVERY_COST_7,
/**
* Błędnie określone koszty przesyłki. Błędny zakres ilości sztuk lub brak
* kosztu dostawy.
*/
ERR_INVALID_DELIVERY_COST_8,
/**
* Błędnie określone koszty przesyłki. Błędny zakres ilości sztuk lub brak
* kosztu dostawy.
*/
ERR_INVALID_DELIVERY_COST_9,
/**
* Błędnie określone koszty przesyłki. Błędny zakres ilości sztuk lub brak
* kosztu dostawy.
*/
ERR_INVALID_DELIVERY_COST_10,
/**
* Nie określono żadnej formy przesyłki. Należy określić koszty przesyłki
* dla wszystkich sztuk towaru przynjmniej dla jednej formy przesyłki.
*/
ERR_INVALID_DELIVERY_COST,
/** Wewnętrzny błąd WebAPI Swistak.pl. */
ERR_INTERNAL_SERVER_ERROR;
}
|
87613_34 | package webapi.client;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.rmi.RemoteException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.xml.rpc.ServiceException;
import javax.xml.rpc.holders.LongHolder;
import javax.xml.rpc.holders.StringHolder;
import org.apache.axis.encoding.Base64;
import com.allegro.webapi.AllegroWebApiPortType;
import com.allegro.webapi.AllegroWebApiServiceLocator;
import com.allegro.webapi.ItemInfo;
import com.allegro.webapi.MyAccountStruct2;
public class AllegroWebApiClient {
private AllegroWebApiPortType port;
private StringHolder sessionHandlePart;
public AllegroWebApiClient(String username, String password, String key)
throws RemoteException, ServiceException, NoSuchAlgorithmException,
UnsupportedEncodingException {
// Make a service
AllegroWebApiServiceLocator service = new AllegroWebApiServiceLocator();
// Now use the service to get a stub which implements the SDI.
port = service.getAllegroWebApiPort();
// Make the actual call
final String userLogin = username;
final String userPassword = password;
final int countryCode = 1;
final String webapiKey = key;
long localVerKey = readAllegroKey();
StringHolder info = new StringHolder();
LongHolder currentVerKey = new LongHolder();
System.out.print("Receving key version... ");
port.doQuerySysStatus(1, countryCode, webapiKey, info, currentVerKey);
System.out.println("done. Current version key=" + currentVerKey.value);
if (localVerKey != currentVerKey.value) {
System.err.println("Warning: key versions don't match!");
localVerKey = currentVerKey.value;
}
sessionHandlePart = new StringHolder();
LongHolder userId = new LongHolder();
LongHolder serverTime = new LongHolder();
System.out.print("Logging in... ");
port.doLoginEnc(userLogin, encryptAndEncodePassword(userPassword),
countryCode, webapiKey, localVerKey, sessionHandlePart, userId,
serverTime);
System.out.println("done.");
}
private String encryptAndEncodePassword(String password)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(password.getBytes("UTF-8"));
return Base64.encode(md.digest());
}
public List<ItemInfo> collectAuctions(final String accountType) throws RemoteException {
int offset = 0;
long itemsArray[] = {};
int limit = 25;
System.out.println("Accessing '" + accountType + "' auctions... ");
MyAccountStruct2[] doMyAccount2;
List<ItemInfo> infoItems = new ArrayList<ItemInfo>();
do {
doMyAccount2 = port.doMyAccount2(sessionHandlePart.value,
accountType, offset, itemsArray, limit);
for (int i = 0; i < doMyAccount2.length; i++) {
String[] myAccountArray = doMyAccount2[i].getMyAccountArray();
System.out.println("=> item #" + (offset + i + 1) + " id="
+ myAccountArray[0] + ", cena=" + myAccountArray[2]
+ ", end=" + myAccountArray[7] + ", title="
+ myAccountArray[9]);
ItemInfo item = stringArrayToItemInfo(myAccountArray);
infoItems.add(item);
}
offset += limit;
} while(doMyAccount2.length > 0);
System.out.println("done.");
return infoItems;
}
public static ItemInfo stringArrayToItemInfo(String s[]) {
ItemInfo item = new ItemInfo();
// [0] identyfikator aukcji,
item.setItId(Long.parseLong(s[0]));
// [1] cena wywoławcza przedmiotu (lub 0.00 gdy nie została ustawiona),
item.setItStartingPrice(s[1].equals("NULL") ? 0f : Float.parseFloat(s[1]));
// [2] obecna cena przedmiotu,
item.setItPrice(Float.parseFloat(s[2]));
// [3] cena minimalna przedmiotu (lub 0.00 gdy nie została ustawiona),
item.setItReservePrice(s[3].equals("NULL") ? 0f : Float.parseFloat(s[3]));
// [4] cena Kup Teraz! (lub 0.00 gdy nie została ustawiona),
item.setItBuyNowPrice(Float.parseFloat(s[4]));
// [5] liczba przedmiotów dostępnych na aukcji,
// [6] czas rozpoczęcia aukcji (w czasie jej trwania, widzi ją tylko sprzedający),
// [7] czas zakończenia aukcji,
item.setItEndingTime(dateStringToLong(s[7]));
// [8] identyfikator kupującego oferującego najwyższą cenę (lub 0 gdy nikt jeszcze nie złożył oferty),
item.setItHighBidderLogin(s[8]);
// [9] tytuł aukcji,
item.setItName(s[9]);
// [10] liczba złożonych w aukcji ofert,
item.setItBidCount(Integer.parseInt(s[10]));
// [11] identyfikator sprzedającego,
item.setItSellerId(Long.parseLong(s[11]));
// [12] identyfikator kraju,
item.setItCountry(Integer.parseInt(s[12]));
// [13] wartość informująca o wybranych dla aukcji opcjach dodatkowych (więcej),
// [14] maksymalna cena oferowana za przedmiot przez użytkownika,
// [15] maksymalna cena oferowana za przedmiot,
// [16] liczba przedmiotów, które do tej pory nie zostały sprzedane, ale jeszcze mogą zostać sprzedane (dot. aukcji trwających),
// [17] liczba przedmiotów, które zostały do tej pory sprzedane (dot. aukcji trwających),
// [18] pole zdezaktualizowane (zawsze będzie zwracać NULL),
// [19] liczba sprzedanych przedmiotów (dot. aukcji zakończonych),
// [20] liczba niesprzedanych przedmiotów (dot. aukcji zakończonych),
// [21] nazwa kupującego (lub 0 w przypadku braku ofert, pełna wartość pola widoczna jest tylko dla sprzedającego w danej aukcji, dla pozostałych w polu zwracana jest nazwa użytkownika w formie zanonimizowanej: X...Y),
item.setItHighBidderLogin(s[21]);
// [22] liczba punktów kupującego (lub 0 w przypadku braku ofert),
// [23] kraj kupującego (lub 0 w przypadku braku ofert),
// [24] nazwa sprzedającego,
item.setItSellerLogin(s[24]);
// [25] liczba punktów sprzedającego,
item.setItSellerRating(Integer.parseInt(s[25]));
// [26] kraj sprzedającego,
// [27] liczba osób obserwujących aukcję (lub '-' w przypadku braku obserwujących),
// [28] informacja o tym, czy w aukcji włączona jest opcja Kup Teraz! (1 - jest, 0 - nie jest),
item.setItBuyNowActive(s[28].equals("NULL") ? 0 : Integer.parseInt(s[28]));
// [29] liczba zdjęć dołączonych do aukcji,
item.setItHighBidder(Integer.parseInt(s[29]));
// item.setItFotoCount(Integer.parseInt(s[29]));
// [30] treść notatki dodanej przez sprzedającego do aukcji (widoczna tylko dla sprzedającego, dla pozostałych oraz w przypadku braku notatki zwracane jest 0),
// [31] informacja o tym, na ile minut przed końcem aukcji ma zostać wysłane e-mailem przypomnienie o tym fakcie (dot. aukcji obserwowanych),
// [32] tekstowy status aukcji oczekującej na wystawienie (np. 'Oczekuje', 'Wstrzymana przez administratora Allegro', itp.),
// [33] liczba wyświetleń aukcji,
// [34] pole zdezaktualizowane (zawsze będzie zwracać NULL),
// [35] pole zdezaktualizowane (zawsze będzie zwracać NULL).
// item.setItBankAccount1();
// item.setItBankAccount2(itBankAccount2);
// item.setItBidCount(itBidCount);
// item.setItDescription(itDescription);
// item.setItIsEco(itIsEco);
// item.setItLocation(itLocation);
// item.setItOptions(itOptions);
// item.setItPostcode(itPostcode);
// item.setItQuantity(itQuantity);
// item.setItStartingQuantity(itStartingQuantity);
// item.setItStartingTime(dateStringToLong(myAccountArray[6]));
// item.setItState(itState);
// item.setItVatInvoice(itVatInvoice);
return item;
}
public static long dateStringToLong(String s) {
try {
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = (Date) formatter.parse(s);
long l = date.getTime();
return l;
} catch (ParseException e) {
System.out.println("Exception :" + e);
}
return 0;
}
private long readAllegroKey() {
DataInputStream in = null;
try {
FileInputStream fstream = new FileInputStream("allegro.key");
in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
return Long.parseLong(strLine);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in!=null)
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return -1;
}
}
| zaza/webapi-client | src/webapi/client/AllegroWebApiClient.java | 3,373 | // [30] treść notatki dodanej przez sprzedającego do aukcji (widoczna tylko dla sprzedającego, dla pozostałych oraz w przypadku braku notatki zwracane jest 0),
| line_comment | pl | package webapi.client;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.rmi.RemoteException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.xml.rpc.ServiceException;
import javax.xml.rpc.holders.LongHolder;
import javax.xml.rpc.holders.StringHolder;
import org.apache.axis.encoding.Base64;
import com.allegro.webapi.AllegroWebApiPortType;
import com.allegro.webapi.AllegroWebApiServiceLocator;
import com.allegro.webapi.ItemInfo;
import com.allegro.webapi.MyAccountStruct2;
public class AllegroWebApiClient {
private AllegroWebApiPortType port;
private StringHolder sessionHandlePart;
public AllegroWebApiClient(String username, String password, String key)
throws RemoteException, ServiceException, NoSuchAlgorithmException,
UnsupportedEncodingException {
// Make a service
AllegroWebApiServiceLocator service = new AllegroWebApiServiceLocator();
// Now use the service to get a stub which implements the SDI.
port = service.getAllegroWebApiPort();
// Make the actual call
final String userLogin = username;
final String userPassword = password;
final int countryCode = 1;
final String webapiKey = key;
long localVerKey = readAllegroKey();
StringHolder info = new StringHolder();
LongHolder currentVerKey = new LongHolder();
System.out.print("Receving key version... ");
port.doQuerySysStatus(1, countryCode, webapiKey, info, currentVerKey);
System.out.println("done. Current version key=" + currentVerKey.value);
if (localVerKey != currentVerKey.value) {
System.err.println("Warning: key versions don't match!");
localVerKey = currentVerKey.value;
}
sessionHandlePart = new StringHolder();
LongHolder userId = new LongHolder();
LongHolder serverTime = new LongHolder();
System.out.print("Logging in... ");
port.doLoginEnc(userLogin, encryptAndEncodePassword(userPassword),
countryCode, webapiKey, localVerKey, sessionHandlePart, userId,
serverTime);
System.out.println("done.");
}
private String encryptAndEncodePassword(String password)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(password.getBytes("UTF-8"));
return Base64.encode(md.digest());
}
public List<ItemInfo> collectAuctions(final String accountType) throws RemoteException {
int offset = 0;
long itemsArray[] = {};
int limit = 25;
System.out.println("Accessing '" + accountType + "' auctions... ");
MyAccountStruct2[] doMyAccount2;
List<ItemInfo> infoItems = new ArrayList<ItemInfo>();
do {
doMyAccount2 = port.doMyAccount2(sessionHandlePart.value,
accountType, offset, itemsArray, limit);
for (int i = 0; i < doMyAccount2.length; i++) {
String[] myAccountArray = doMyAccount2[i].getMyAccountArray();
System.out.println("=> item #" + (offset + i + 1) + " id="
+ myAccountArray[0] + ", cena=" + myAccountArray[2]
+ ", end=" + myAccountArray[7] + ", title="
+ myAccountArray[9]);
ItemInfo item = stringArrayToItemInfo(myAccountArray);
infoItems.add(item);
}
offset += limit;
} while(doMyAccount2.length > 0);
System.out.println("done.");
return infoItems;
}
public static ItemInfo stringArrayToItemInfo(String s[]) {
ItemInfo item = new ItemInfo();
// [0] identyfikator aukcji,
item.setItId(Long.parseLong(s[0]));
// [1] cena wywoławcza przedmiotu (lub 0.00 gdy nie została ustawiona),
item.setItStartingPrice(s[1].equals("NULL") ? 0f : Float.parseFloat(s[1]));
// [2] obecna cena przedmiotu,
item.setItPrice(Float.parseFloat(s[2]));
// [3] cena minimalna przedmiotu (lub 0.00 gdy nie została ustawiona),
item.setItReservePrice(s[3].equals("NULL") ? 0f : Float.parseFloat(s[3]));
// [4] cena Kup Teraz! (lub 0.00 gdy nie została ustawiona),
item.setItBuyNowPrice(Float.parseFloat(s[4]));
// [5] liczba przedmiotów dostępnych na aukcji,
// [6] czas rozpoczęcia aukcji (w czasie jej trwania, widzi ją tylko sprzedający),
// [7] czas zakończenia aukcji,
item.setItEndingTime(dateStringToLong(s[7]));
// [8] identyfikator kupującego oferującego najwyższą cenę (lub 0 gdy nikt jeszcze nie złożył oferty),
item.setItHighBidderLogin(s[8]);
// [9] tytuł aukcji,
item.setItName(s[9]);
// [10] liczba złożonych w aukcji ofert,
item.setItBidCount(Integer.parseInt(s[10]));
// [11] identyfikator sprzedającego,
item.setItSellerId(Long.parseLong(s[11]));
// [12] identyfikator kraju,
item.setItCountry(Integer.parseInt(s[12]));
// [13] wartość informująca o wybranych dla aukcji opcjach dodatkowych (więcej),
// [14] maksymalna cena oferowana za przedmiot przez użytkownika,
// [15] maksymalna cena oferowana za przedmiot,
// [16] liczba przedmiotów, które do tej pory nie zostały sprzedane, ale jeszcze mogą zostać sprzedane (dot. aukcji trwających),
// [17] liczba przedmiotów, które zostały do tej pory sprzedane (dot. aukcji trwających),
// [18] pole zdezaktualizowane (zawsze będzie zwracać NULL),
// [19] liczba sprzedanych przedmiotów (dot. aukcji zakończonych),
// [20] liczba niesprzedanych przedmiotów (dot. aukcji zakończonych),
// [21] nazwa kupującego (lub 0 w przypadku braku ofert, pełna wartość pola widoczna jest tylko dla sprzedającego w danej aukcji, dla pozostałych w polu zwracana jest nazwa użytkownika w formie zanonimizowanej: X...Y),
item.setItHighBidderLogin(s[21]);
// [22] liczba punktów kupującego (lub 0 w przypadku braku ofert),
// [23] kraj kupującego (lub 0 w przypadku braku ofert),
// [24] nazwa sprzedającego,
item.setItSellerLogin(s[24]);
// [25] liczba punktów sprzedającego,
item.setItSellerRating(Integer.parseInt(s[25]));
// [26] kraj sprzedającego,
// [27] liczba osób obserwujących aukcję (lub '-' w przypadku braku obserwujących),
// [28] informacja o tym, czy w aukcji włączona jest opcja Kup Teraz! (1 - jest, 0 - nie jest),
item.setItBuyNowActive(s[28].equals("NULL") ? 0 : Integer.parseInt(s[28]));
// [29] liczba zdjęć dołączonych do aukcji,
item.setItHighBidder(Integer.parseInt(s[29]));
// item.setItFotoCount(Integer.parseInt(s[29]));
// [30] <SUF>
// [31] informacja o tym, na ile minut przed końcem aukcji ma zostać wysłane e-mailem przypomnienie o tym fakcie (dot. aukcji obserwowanych),
// [32] tekstowy status aukcji oczekującej na wystawienie (np. 'Oczekuje', 'Wstrzymana przez administratora Allegro', itp.),
// [33] liczba wyświetleń aukcji,
// [34] pole zdezaktualizowane (zawsze będzie zwracać NULL),
// [35] pole zdezaktualizowane (zawsze będzie zwracać NULL).
// item.setItBankAccount1();
// item.setItBankAccount2(itBankAccount2);
// item.setItBidCount(itBidCount);
// item.setItDescription(itDescription);
// item.setItIsEco(itIsEco);
// item.setItLocation(itLocation);
// item.setItOptions(itOptions);
// item.setItPostcode(itPostcode);
// item.setItQuantity(itQuantity);
// item.setItStartingQuantity(itStartingQuantity);
// item.setItStartingTime(dateStringToLong(myAccountArray[6]));
// item.setItState(itState);
// item.setItVatInvoice(itVatInvoice);
return item;
}
public static long dateStringToLong(String s) {
try {
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = (Date) formatter.parse(s);
long l = date.getTime();
return l;
} catch (ParseException e) {
System.out.println("Exception :" + e);
}
return 0;
}
private long readAllegroKey() {
DataInputStream in = null;
try {
FileInputStream fstream = new FileInputStream("allegro.key");
in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
return Long.parseLong(strLine);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in!=null)
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return -1;
}
}
|
103078_0 | package Podstawy;
import java.util.Scanner;
public class Sample2_Wypisywanie_I_Wczytywanie {
public static void main(String[] args) {
Scanner skaner = new Scanner(System.in);
/*
System.out.print("Podaj liczbe calkowita: ");
int liiczba = skaner.nextInt();
System.out.println("Podaj liczbe rzeczywista");
double rzeczywista = skaner.nextDouble();
System.out.println("Podana liczba całkowita to: " + liiczba);
System.out.println("Podaj wyraz: ");
String wyraz = skaner.next();
System.out.println("Twoj wyraz to: " + wyraz);
*/
System.out.println("Podaj zdanie ");
String zdanie = skaner.nextLine();
System.out.println("Twoj wyraz to: " + zdanie);
}
}
| zbigolo/Klasa2pp | src/Podstawy/Sample2_Wypisywanie_I_Wczytywanie.java | 263 | /*
System.out.print("Podaj liczbe calkowita: ");
int liiczba = skaner.nextInt();
System.out.println("Podaj liczbe rzeczywista");
double rzeczywista = skaner.nextDouble();
System.out.println("Podana liczba całkowita to: " + liiczba);
System.out.println("Podaj wyraz: ");
String wyraz = skaner.next();
System.out.println("Twoj wyraz to: " + wyraz);
*/ | block_comment | pl | package Podstawy;
import java.util.Scanner;
public class Sample2_Wypisywanie_I_Wczytywanie {
public static void main(String[] args) {
Scanner skaner = new Scanner(System.in);
/*
System<SUF>*/
System.out.println("Podaj zdanie ");
String zdanie = skaner.nextLine();
System.out.println("Twoj wyraz to: " + zdanie);
}
}
|
45493_3 | package Z5Managers;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ManagerFlowLayout implements ActionListener {
private JButton button;
private JLabel pole;
public JPanel createContentPane () {
//1
// JPanel myPanel = new JPanel(new FlowLayout());
//2
// JPanel myPanel = new JPanel();
// myPanel.setLayout(new FlowLayout());
JPanel myPanel = new JPanel();
FlowLayout rozkladLiniowy = new FlowLayout(FlowLayout.LEFT, 20, 40);
myPanel.setLayout(rozkladLiniowy);
for (int i = 1; i < 16 ; i++) {
button = new JButton("Przycisk" + i);
button.addActionListener(this);
myPanel.add(button);
}
pole = new JLabel("Witaj świecie");
pole.setOpaque(true);
pole.setBackground(Color.ORANGE);
pole.setPreferredSize(new Dimension(80,20));
JPanel panelLewy = new JPanel( new FlowLayout());
panelLewy.setBackground(Color.blue);
// panelLewy.setSize(150,200);
panelLewy.setPreferredSize(new Dimension(100,100));
myPanel.add(pole);
myPanel.add(panelLewy);
return myPanel;
}
public ManagerFlowLayout () {
JFrame myWindow = new JFrame("Manager FlowLayout");
myWindow.setContentPane(createContentPane());
myWindow.setSize(300, 400);
myWindow.setLayout(new FlowLayout());
myWindow.setLocationRelativeTo(null);
myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myWindow.setVisible(true);
}
public static void main (String[] args) {
new ManagerFlowLayout();
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(button.getText());
}
}
| zbigolo/Klasa3pp_2324 | src/Z5Managers/ManagerFlowLayout.java | 582 | // panelLewy.setSize(150,200); | line_comment | pl | package Z5Managers;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ManagerFlowLayout implements ActionListener {
private JButton button;
private JLabel pole;
public JPanel createContentPane () {
//1
// JPanel myPanel = new JPanel(new FlowLayout());
//2
// JPanel myPanel = new JPanel();
// myPanel.setLayout(new FlowLayout());
JPanel myPanel = new JPanel();
FlowLayout rozkladLiniowy = new FlowLayout(FlowLayout.LEFT, 20, 40);
myPanel.setLayout(rozkladLiniowy);
for (int i = 1; i < 16 ; i++) {
button = new JButton("Przycisk" + i);
button.addActionListener(this);
myPanel.add(button);
}
pole = new JLabel("Witaj świecie");
pole.setOpaque(true);
pole.setBackground(Color.ORANGE);
pole.setPreferredSize(new Dimension(80,20));
JPanel panelLewy = new JPanel( new FlowLayout());
panelLewy.setBackground(Color.blue);
// panel<SUF>
panelLewy.setPreferredSize(new Dimension(100,100));
myPanel.add(pole);
myPanel.add(panelLewy);
return myPanel;
}
public ManagerFlowLayout () {
JFrame myWindow = new JFrame("Manager FlowLayout");
myWindow.setContentPane(createContentPane());
myWindow.setSize(300, 400);
myWindow.setLayout(new FlowLayout());
myWindow.setLocationRelativeTo(null);
myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myWindow.setVisible(true);
}
public static void main (String[] args) {
new ManagerFlowLayout();
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(button.getText());
}
}
|
113663_3 | package pl.put.poznan.transformer.logic;
/**
* Transformuje pierwszą literę poszczególnych wyrazów na wielką.
*/
public class Capitalize extends TextTransformer {
/**
* Konstruktor dla obiektu dekorującego dany tekst.
*
* @param newText Tekst na którym zostanie wykonana transformacja.
*/
public Capitalize(Text newText) {
super(newText);
}
/**
* Przekazuje odpowiednio zmodyfikowany tekst.
*
* @return Zmodyfikowany tekst.
*/
public String get() {
return transform(tempText.get());
}
/**
* Wykonuje operacje zmiany pierwszej litery poszczególnych wyrazów na wielką.
*
* @param text Tekst poddawany transformacji.
* @return Tekst po wykonaniu transfomacji.
*/
private String transform(String text) {
text = text.toLowerCase();
if (text.length() > 0) {
if (text.trim().length() == 0) {
return text;
}
String[] words = text.trim().split("\\s");
StringBuilder cappedText = new StringBuilder();
for (String word : words) {
char capLetter = Character.toUpperCase(word.charAt(0));
cappedText.append(" ").append(capLetter).append(word.substring(1));
}
return cappedText.toString().trim();
} else {
return text;
}
}
}
| zcienka/text-transformer | src/main/java/pl/put/poznan/transformer/logic/Capitalize.java | 432 | /**
* Wykonuje operacje zmiany pierwszej litery poszczególnych wyrazów na wielką.
*
* @param text Tekst poddawany transformacji.
* @return Tekst po wykonaniu transfomacji.
*/ | block_comment | pl | package pl.put.poznan.transformer.logic;
/**
* Transformuje pierwszą literę poszczególnych wyrazów na wielką.
*/
public class Capitalize extends TextTransformer {
/**
* Konstruktor dla obiektu dekorującego dany tekst.
*
* @param newText Tekst na którym zostanie wykonana transformacja.
*/
public Capitalize(Text newText) {
super(newText);
}
/**
* Przekazuje odpowiednio zmodyfikowany tekst.
*
* @return Zmodyfikowany tekst.
*/
public String get() {
return transform(tempText.get());
}
/**
* Wykonu<SUF>*/
private String transform(String text) {
text = text.toLowerCase();
if (text.length() > 0) {
if (text.trim().length() == 0) {
return text;
}
String[] words = text.trim().split("\\s");
StringBuilder cappedText = new StringBuilder();
for (String word : words) {
char capLetter = Character.toUpperCase(word.charAt(0));
cappedText.append(" ").append(capLetter).append(word.substring(1));
}
return cappedText.toString().trim();
} else {
return text;
}
}
}
|
76511_10 | package com.example.obecnosci_klient_1_0;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
//klient
import java.io.DataInputStream;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends Activity {
//wstepna definicja obiektow gui
TextView responseContentTextView;
EditText requestUidEditText,requestDateEditText;
CheckBox simulateUid,simulateDate;
//ustawienia
SharedPreferences sharedPrefs;
// The client socket
private static Socket clientSocket = null;
// The output stream
private static PrintStream os = null;
// The input stream
private static DataInputStream is = null;
private static BufferedReader inputLine = null;
private static boolean closed = false;
int portNumber;
String host;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
//odnalezienie po ID
requestUidEditText = (EditText)findViewById(R.id.requestUid);
responseContentTextView = (TextView)findViewById(R.id.responseContent);
//inicjalizacja klienta
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
//Toast.makeText(this, "Ustawienia", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, Preferences.class));
break;
case R.id.menu_minimalize:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
break;
default:
break;
}
return true;
}
public void pseudoConsoleWrite(String tekst)
{
responseContentTextView.setText(tekst+"\n"+responseContentTextView.getText());
}
public boolean buttonRequestClick(View view) {
//wstep
//Toast.makeText(this, "Odczytano zbliżenie", Toast.LENGTH_SHORT).show();
host=sharedPrefs.getString("server_ip", "19.168.1.100");
portNumber=Integer.parseInt(sharedPrefs.getString("tcp_port", "2323"));
pseudoConsoleWrite("Nawiazywanie polaczenia z "+host+":"+portNumber+"...");
//inicjalizacja polaczenia
try {
clientSocket = new Socket(host, portNumber);
os = new PrintStream(clientSocket.getOutputStream());
is = new DataInputStream(clientSocket.getInputStream());
pseudoConsoleWrite("Nawiązano poprawne połązenie.");
} catch (UnknownHostException e) {
pseudoConsoleWrite("Nie odnaleziono hosta " + host);
return false;
} catch (IOException e) {
pseudoConsoleWrite("Błąd połączenia I/O z hostem "
+ host);
return false;
}
//wyslanie komunikatu
if (clientSocket != null && os != null && is != null) {
String command="uid "+requestUidEditText.getText()+" sala "+sharedPrefs.getString("id_sali", "-1");
if(requestUidEditText.getText().toString().length() == 0)
{
Toast.makeText(this,"Wpisz poprawną wartość UID", Toast.LENGTH_SHORT).show();
}
else os.println(command);
String responseLine;
try {
responseLine = is.readLine();
Toast.makeText(this,responseLine, Toast.LENGTH_SHORT).show();
is.close();
os.close();
clientSocket.close();
} catch (IOException e) {
Toast.makeText(this,"Błąd! Nie otrzymano odpowiedzi z serwera", Toast.LENGTH_SHORT).show();
pseudoConsoleWrite("! Błąd otrzymywania komunikatu.");
return false;
}
return true;
}
return false;
//Toast.makeText(this, sharedPrefs.getString("server_ip", "19.168.1.100"), Toast.LENGTH_SHORT).show();
//dopisz tekst do symulatora konsoli
//
}
// odblokowanie/zablokowanie inputow
}
| zdanowiczkonrad/AttendanceMonitoring | android/src/com/example/obecnosci_klient_1_0/MainActivity.java | 1,457 | //inicjalizacja polaczenia | line_comment | pl | package com.example.obecnosci_klient_1_0;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
//klient
import java.io.DataInputStream;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends Activity {
//wstepna definicja obiektow gui
TextView responseContentTextView;
EditText requestUidEditText,requestDateEditText;
CheckBox simulateUid,simulateDate;
//ustawienia
SharedPreferences sharedPrefs;
// The client socket
private static Socket clientSocket = null;
// The output stream
private static PrintStream os = null;
// The input stream
private static DataInputStream is = null;
private static BufferedReader inputLine = null;
private static boolean closed = false;
int portNumber;
String host;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
//odnalezienie po ID
requestUidEditText = (EditText)findViewById(R.id.requestUid);
responseContentTextView = (TextView)findViewById(R.id.responseContent);
//inicjalizacja klienta
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
//Toast.makeText(this, "Ustawienia", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, Preferences.class));
break;
case R.id.menu_minimalize:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
break;
default:
break;
}
return true;
}
public void pseudoConsoleWrite(String tekst)
{
responseContentTextView.setText(tekst+"\n"+responseContentTextView.getText());
}
public boolean buttonRequestClick(View view) {
//wstep
//Toast.makeText(this, "Odczytano zbliżenie", Toast.LENGTH_SHORT).show();
host=sharedPrefs.getString("server_ip", "19.168.1.100");
portNumber=Integer.parseInt(sharedPrefs.getString("tcp_port", "2323"));
pseudoConsoleWrite("Nawiazywanie polaczenia z "+host+":"+portNumber+"...");
//inicj<SUF>
try {
clientSocket = new Socket(host, portNumber);
os = new PrintStream(clientSocket.getOutputStream());
is = new DataInputStream(clientSocket.getInputStream());
pseudoConsoleWrite("Nawiązano poprawne połązenie.");
} catch (UnknownHostException e) {
pseudoConsoleWrite("Nie odnaleziono hosta " + host);
return false;
} catch (IOException e) {
pseudoConsoleWrite("Błąd połączenia I/O z hostem "
+ host);
return false;
}
//wyslanie komunikatu
if (clientSocket != null && os != null && is != null) {
String command="uid "+requestUidEditText.getText()+" sala "+sharedPrefs.getString("id_sali", "-1");
if(requestUidEditText.getText().toString().length() == 0)
{
Toast.makeText(this,"Wpisz poprawną wartość UID", Toast.LENGTH_SHORT).show();
}
else os.println(command);
String responseLine;
try {
responseLine = is.readLine();
Toast.makeText(this,responseLine, Toast.LENGTH_SHORT).show();
is.close();
os.close();
clientSocket.close();
} catch (IOException e) {
Toast.makeText(this,"Błąd! Nie otrzymano odpowiedzi z serwera", Toast.LENGTH_SHORT).show();
pseudoConsoleWrite("! Błąd otrzymywania komunikatu.");
return false;
}
return true;
}
return false;
//Toast.makeText(this, sharedPrefs.getString("server_ip", "19.168.1.100"), Toast.LENGTH_SHORT).show();
//dopisz tekst do symulatora konsoli
//
}
// odblokowanie/zablokowanie inputow
}
|
8324_3 | package com.clients;
import com.security.EnabledCiphers;
import com.security.IvGenerator;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
/**
* Class just shows the way of using the
* ClientMPCreator and ClientMPSolver instances.
* @author Karol
*/
public class ClientMPMain {
public static void main(String[] args) {
try {
// Karol chce połączyć się z Dominikiem za pomocą MerklePuzzles, wybiera
// że chce wysłać mu puzzle zakodowane za pomocą DES_CBC
// (możliwe jeszcze DES_EDE_CBC lub AES_CBC, tutaj jednak czas
// rozwiązywania puzzli jest ogromny - trzeba o tym wspomnieć w raporcie i helpie,
// i generalnie przestrzec, że proces trwa w miarę długo.)
ChatClient karol = new ClientMPCreator("Karol");
// inicjalizacja Karola, chce on utworzyć 100000 puzzli zakodowanych DESem.
((ClientMPCreator) karol).init(2, EnabledCiphers.DES_CBC);
// Karol tworzy plik z puzzlami (potem trzeba ten plik przesłać do klienta drugiego)
((ClientMPCreator) karol).createPuzzles("puzzle.puz");
// Dominik musi być teraz MP Solverem - BuilderPattern ustawiamy wszystkie pola po kolei.
ChatClient dominik = new ClientMPSolver("Dominik")
.setFragmentKeylen( ((ClientMPCreator) karol).getFragmentKeyLen() )
.setZerosKeylen( ((ClientMPCreator) karol).getZerosKeyLen() )
.setIv(((ClientMPCreator) karol).getPuzzleIv())
.setPuzzleAlgorithm(((ClientMPCreator) karol).getPuzzleAlgorithm())
.setSecretKeyAlgorithm(((ClientMPCreator) karol).getSecretKeyAlgorithm())
.setPuzzleFilename(((ClientMPCreator) karol).getPuzzlesFilename())
.setReplyFilename("reply.puz"); // plik w którym zapisywać będziemy odpowiedź
// Dominik rozwiązuje puzzle i zapisuje je do pliku.
// Plik trzeba wysłać teraz do Karola.
((ClientMPSolver) dominik).solvePuzzles();
// Karol otrzymuje plik i zgadza się na klucz prywatny
// odpowiadający kluczowi publicznemu zawartemu w pliku.
((ClientMPCreator) karol).agreeOnKey("reply.puz");
// teraz następuje enkrypcja i dekrypcja
// metody używane przez ChatClienta
// Karol chce napisać do Dominika
String message = "Dominik, już naprawdę chce mi się spać.";
IvParameterSpec iv = IvGenerator.generateIV(IvGenerator.AES_BLOCK_SIZE);
// Karol enkryptuje wiadomość
byte[] encryptedMessage = karol.encrypt(message, iv);
ByteArrayOutputStream encryptedStream = karol.writeMessage(encryptedMessage);
ByteArrayOutputStream writeIv = karol.writeIv(iv);
// Dominik odbiera wiadomość oraz iv.
byte[] received = dominik.receiveMessage(encryptedStream);
IvParameterSpec iv2 = dominik.receiveIv(writeIv);
// dekryptuje i odczytuje
String plaintext = dominik.decrypt(received, iv2);
System.out.println(plaintext);
} catch (NoSuchAlgorithmException | FileNotFoundException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException | InvalidAlgorithmParameterException ex) {
Logger.getLogger(ClientMPMain.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ClientMPMain.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| zdoonio/SecureClient | src/com/clients/ClientMPMain.java | 1,304 | // (możliwe jeszcze DES_EDE_CBC lub AES_CBC, tutaj jednak czas | line_comment | pl | package com.clients;
import com.security.EnabledCiphers;
import com.security.IvGenerator;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
/**
* Class just shows the way of using the
* ClientMPCreator and ClientMPSolver instances.
* @author Karol
*/
public class ClientMPMain {
public static void main(String[] args) {
try {
// Karol chce połączyć się z Dominikiem za pomocą MerklePuzzles, wybiera
// że chce wysłać mu puzzle zakodowane za pomocą DES_CBC
// (możl<SUF>
// rozwiązywania puzzli jest ogromny - trzeba o tym wspomnieć w raporcie i helpie,
// i generalnie przestrzec, że proces trwa w miarę długo.)
ChatClient karol = new ClientMPCreator("Karol");
// inicjalizacja Karola, chce on utworzyć 100000 puzzli zakodowanych DESem.
((ClientMPCreator) karol).init(2, EnabledCiphers.DES_CBC);
// Karol tworzy plik z puzzlami (potem trzeba ten plik przesłać do klienta drugiego)
((ClientMPCreator) karol).createPuzzles("puzzle.puz");
// Dominik musi być teraz MP Solverem - BuilderPattern ustawiamy wszystkie pola po kolei.
ChatClient dominik = new ClientMPSolver("Dominik")
.setFragmentKeylen( ((ClientMPCreator) karol).getFragmentKeyLen() )
.setZerosKeylen( ((ClientMPCreator) karol).getZerosKeyLen() )
.setIv(((ClientMPCreator) karol).getPuzzleIv())
.setPuzzleAlgorithm(((ClientMPCreator) karol).getPuzzleAlgorithm())
.setSecretKeyAlgorithm(((ClientMPCreator) karol).getSecretKeyAlgorithm())
.setPuzzleFilename(((ClientMPCreator) karol).getPuzzlesFilename())
.setReplyFilename("reply.puz"); // plik w którym zapisywać będziemy odpowiedź
// Dominik rozwiązuje puzzle i zapisuje je do pliku.
// Plik trzeba wysłać teraz do Karola.
((ClientMPSolver) dominik).solvePuzzles();
// Karol otrzymuje plik i zgadza się na klucz prywatny
// odpowiadający kluczowi publicznemu zawartemu w pliku.
((ClientMPCreator) karol).agreeOnKey("reply.puz");
// teraz następuje enkrypcja i dekrypcja
// metody używane przez ChatClienta
// Karol chce napisać do Dominika
String message = "Dominik, już naprawdę chce mi się spać.";
IvParameterSpec iv = IvGenerator.generateIV(IvGenerator.AES_BLOCK_SIZE);
// Karol enkryptuje wiadomość
byte[] encryptedMessage = karol.encrypt(message, iv);
ByteArrayOutputStream encryptedStream = karol.writeMessage(encryptedMessage);
ByteArrayOutputStream writeIv = karol.writeIv(iv);
// Dominik odbiera wiadomość oraz iv.
byte[] received = dominik.receiveMessage(encryptedStream);
IvParameterSpec iv2 = dominik.receiveIv(writeIv);
// dekryptuje i odczytuje
String plaintext = dominik.decrypt(received, iv2);
System.out.println(plaintext);
} catch (NoSuchAlgorithmException | FileNotFoundException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException | InvalidAlgorithmParameterException ex) {
Logger.getLogger(ClientMPMain.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ClientMPMain.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
85757_1 | #set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.carina.demo.gui.pages.desktop;
import java.util.List;
import java.util.Locale;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.FindBy;
import com.zebrunner.carina.utils.config.Configuration;
import com.zebrunner.carina.webdriver.config.WebDriverConfiguration;
import com.zebrunner.carina.webdriver.decorator.ExtendedWebElement;
import com.zebrunner.carina.webdriver.gui.AbstractPage;
public class WikipediaHomePage extends AbstractPage {
@FindBy(xpath = "//div[@id='js-lang-lists']//a")
private List<ExtendedWebElement> langList;
@FindBy(id = "js-lang-list-button")
private ExtendedWebElement langListBtn;
public WikipediaHomePage(WebDriver driver) {
super(driver);
setPageAbsoluteURL("https://www.wikipedia.org/");
}
public WikipediaLocalePage goToWikipediaLocalePage(WebDriver driver) {
openLangList();
if (!langList.isEmpty()) {
for (ExtendedWebElement languageBtn : langList) {
String localeStr = Configuration.getRequired(WebDriverConfiguration.Parameter.LOCALE);
Locale locale = parseLocale(localeStr);
if (languageBtn.getAttribute("lang").equals(locale.getLanguage())) {
languageBtn.click();
return new WikipediaLocalePage(driver);
}
}
}
throw new RuntimeException("No language ref was found");
}
public void openLangList() {
langListBtn.clickIfPresent();
}
private Locale parseLocale(String localeToParse) {
String[] localeSetttings = localeToParse.trim().split("_");
String lang, country = "";
lang = localeSetttings[0];
if (localeSetttings.length > 1) {
country = localeSetttings[1];
}
return new Locale(lang, country);
}
}
| zebrunner/carina | archetype/src/main/resources/archetype-resources/src/main/java/carina/demo/gui/pages/desktop/WikipediaHomePage.java | 570 | //www.wikipedia.org/"); | line_comment | pl | #set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.carina.demo.gui.pages.desktop;
import java.util.List;
import java.util.Locale;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.FindBy;
import com.zebrunner.carina.utils.config.Configuration;
import com.zebrunner.carina.webdriver.config.WebDriverConfiguration;
import com.zebrunner.carina.webdriver.decorator.ExtendedWebElement;
import com.zebrunner.carina.webdriver.gui.AbstractPage;
public class WikipediaHomePage extends AbstractPage {
@FindBy(xpath = "//div[@id='js-lang-lists']//a")
private List<ExtendedWebElement> langList;
@FindBy(id = "js-lang-list-button")
private ExtendedWebElement langListBtn;
public WikipediaHomePage(WebDriver driver) {
super(driver);
setPageAbsoluteURL("https://www.w<SUF>
}
public WikipediaLocalePage goToWikipediaLocalePage(WebDriver driver) {
openLangList();
if (!langList.isEmpty()) {
for (ExtendedWebElement languageBtn : langList) {
String localeStr = Configuration.getRequired(WebDriverConfiguration.Parameter.LOCALE);
Locale locale = parseLocale(localeStr);
if (languageBtn.getAttribute("lang").equals(locale.getLanguage())) {
languageBtn.click();
return new WikipediaLocalePage(driver);
}
}
}
throw new RuntimeException("No language ref was found");
}
public void openLangList() {
langListBtn.clickIfPresent();
}
private Locale parseLocale(String localeToParse) {
String[] localeSetttings = localeToParse.trim().split("_");
String lang, country = "";
lang = localeSetttings[0];
if (localeSetttings.length > 1) {
country = localeSetttings[1];
}
return new Locale(lang, country);
}
}
|
3628_0 | /*"Pascal interpreter written in Java" jest przeznaczony do
interpretacji kodu napisanego w języku Pascal.
Copyright (C) 2004/2005 Bartyna Waldemar, Faderewski Marek,
Fedorczyk Łukasz, Iwanowski Wojciech.
Niniejszy program jest wolnym oprogramowaniem; możesz go
rozprowadzać dalej i/lub modyfikować na warunkach Powszechnej
Licencji Publicznej GNU, wydanej przez Fundację Wolnego
Oprogramowania - według wersji 2-giej tej Licencji lub którejś
z późniejszych wersji.
Niniejszy program rozpowszechniany jest z nadzieją, iż będzie on
użyteczny - jednak BEZ JAKIEJKOLWIEK GWARANCJI, nawet domyślnej
gwarancji PRZYDATNOŚCI HANDLOWEJ albo PRZYDATNOŚCI DO OKREŚLONYCH
ZASTOSOWAŃ. W celu uzyskania bliższych informacji - Powszechna
Licencja Publiczna GNU.
Z pewnością wraz z niniejszym programem otrzymałeś też egzemplarz
Powszechnej Licencji Publicznej GNU (GNU General Public License);
jeśli nie - napisz do Free Software Foundation, Inc., 675 Mass Ave,
Cambridge, MA 02139, USA.
*/
package net.sourceforge.biff;
import java.io.*;
import java.util.ArrayList;
public class Codes {
// codes for keywords
static final byte PROGRAM = 10;
static final byte BEGIN = 11;
static final byte END = 12;
static final byte END_DOT = 13; // END.
static final byte VAR = 14;
static final byte IF = 15;
static final byte THEN = 16;
static final byte ELSE = 17;
static final byte WHILE = 18;
static final byte DO = 19;
static final byte NOT = 20;
static final byte AND = 21;
static final byte OR = 22;
static final byte READLN = 23;
static final byte WRITELN = 24;
static final byte INTEGER = 25;
static final byte REAL = 26;
static final byte BOOLEAN = 27;
static final byte TRUE = 28;
static final byte FALSE = 29;
// codes for signs
static final byte PLUS = 30; // '+'
static final byte MINUS = 31; // '-'
static final byte MULT = 32; // '*'
static final byte DIV = 33; // '/'
static final byte E = 34; // EQUAL
static final byte NE = 35; // NOTEQUAL
static final byte GT = 36; // GREATER THEN
static final byte GE = 37; // GREATER OR EQUAL
static final byte LT = 38; // LESS THEN
static final byte LE = 39; // LESS OR EQUAL
static final byte COLON = 40; // ':'
static final byte SEMICOLON = 41; // ';'
static final byte COMMA = 42; // ','
static final byte ASOCIATE = 43; // ':='
static final byte LBRACKET = 44; // LEFT BRACKET
static final byte RBRACKET = 45; // RIGHT BRACKET
static final byte QUOTATION = 46; // QUOTATION MARK
// codes for lower categories
static final byte KEYWORD = 60;
static final byte VARIABLE = 61;
static final byte VTYPE = 62; // VARIABLE TYPE
static final byte LOPERATOR = 63; // LOGICAL OPERATOR
static final byte AOPERATOR = 64; // ARITHMETIC OPERATOR
static final byte ROPERATOR = 65; // RELATIONAL OPERATOR
static final byte OOPERATOR = 66; // OTHER OPERATORS
static final byte NUMBER = 67;
// codes for higher categories
static final byte INUMBER = 1; // INTEGER NUMBER
static final byte RNUMBER = 2; // REAL NUMBER
static final byte WORD = 3;
static final byte SIGN = 4;
static final byte STRING = 5;
public ArrayList keywords = new ArrayList();;
private ArrayList signs = new ArrayList();;
public void fillLists() {
keywords.add("PROGRAM");
keywords.add("BEGIN");
keywords.add("END");
keywords.add("END.");
keywords.add("VAR");
keywords.add("IF");
keywords.add("THEN");
keywords.add("ELSE");
keywords.add("WHILE");
keywords.add("DO");
keywords.add("NOT");
keywords.add("AND");
keywords.add("OR");
keywords.add("READLN");
keywords.add("WRITELN");
keywords.add("INTEGER");
keywords.add("REAL");
keywords.add("BOOLEAN");
keywords.add("TRUE");
keywords.add("FALSE");
signs.add("+");
signs.add("-");
signs.add("*");
signs.add("/");
signs.add("=");
signs.add("<>");
signs.add(">");
signs.add(">=");
signs.add("<");
signs.add("<=");
signs.add(":");
signs.add(";");
signs.add(",");
signs.add(":=");
signs.add("(");
signs.add(")");
signs.add("\"");
}// fillLists()
public byte getKeywordCode(String value) {
int index = keywords.indexOf(value);
if (index == -1)
return VARIABLE;
else
return (byte)(10 + index);
}// getKeywordCode(Stirng)
public byte getSignCode(String value) {
return (byte)(30 + signs.indexOf(value));
}// getSignCode(Stirng)
}
| zed-0xff/android-pascal | src/net/sourceforge/biff/Codes.java | 1,856 | /*"Pascal interpreter written in Java" jest przeznaczony do
interpretacji kodu napisanego w języku Pascal.
Copyright (C) 2004/2005 Bartyna Waldemar, Faderewski Marek,
Fedorczyk Łukasz, Iwanowski Wojciech.
Niniejszy program jest wolnym oprogramowaniem; możesz go
rozprowadzać dalej i/lub modyfikować na warunkach Powszechnej
Licencji Publicznej GNU, wydanej przez Fundację Wolnego
Oprogramowania - według wersji 2-giej tej Licencji lub którejś
z późniejszych wersji.
Niniejszy program rozpowszechniany jest z nadzieją, iż będzie on
użyteczny - jednak BEZ JAKIEJKOLWIEK GWARANCJI, nawet domyślnej
gwarancji PRZYDATNOŚCI HANDLOWEJ albo PRZYDATNOŚCI DO OKREŚLONYCH
ZASTOSOWAŃ. W celu uzyskania bliższych informacji - Powszechna
Licencja Publiczna GNU.
Z pewnością wraz z niniejszym programem otrzymałeś też egzemplarz
Powszechnej Licencji Publicznej GNU (GNU General Public License);
jeśli nie - napisz do Free Software Foundation, Inc., 675 Mass Ave,
Cambridge, MA 02139, USA.
*/ | block_comment | pl | /*"Pasca<SUF>*/
package net.sourceforge.biff;
import java.io.*;
import java.util.ArrayList;
public class Codes {
// codes for keywords
static final byte PROGRAM = 10;
static final byte BEGIN = 11;
static final byte END = 12;
static final byte END_DOT = 13; // END.
static final byte VAR = 14;
static final byte IF = 15;
static final byte THEN = 16;
static final byte ELSE = 17;
static final byte WHILE = 18;
static final byte DO = 19;
static final byte NOT = 20;
static final byte AND = 21;
static final byte OR = 22;
static final byte READLN = 23;
static final byte WRITELN = 24;
static final byte INTEGER = 25;
static final byte REAL = 26;
static final byte BOOLEAN = 27;
static final byte TRUE = 28;
static final byte FALSE = 29;
// codes for signs
static final byte PLUS = 30; // '+'
static final byte MINUS = 31; // '-'
static final byte MULT = 32; // '*'
static final byte DIV = 33; // '/'
static final byte E = 34; // EQUAL
static final byte NE = 35; // NOTEQUAL
static final byte GT = 36; // GREATER THEN
static final byte GE = 37; // GREATER OR EQUAL
static final byte LT = 38; // LESS THEN
static final byte LE = 39; // LESS OR EQUAL
static final byte COLON = 40; // ':'
static final byte SEMICOLON = 41; // ';'
static final byte COMMA = 42; // ','
static final byte ASOCIATE = 43; // ':='
static final byte LBRACKET = 44; // LEFT BRACKET
static final byte RBRACKET = 45; // RIGHT BRACKET
static final byte QUOTATION = 46; // QUOTATION MARK
// codes for lower categories
static final byte KEYWORD = 60;
static final byte VARIABLE = 61;
static final byte VTYPE = 62; // VARIABLE TYPE
static final byte LOPERATOR = 63; // LOGICAL OPERATOR
static final byte AOPERATOR = 64; // ARITHMETIC OPERATOR
static final byte ROPERATOR = 65; // RELATIONAL OPERATOR
static final byte OOPERATOR = 66; // OTHER OPERATORS
static final byte NUMBER = 67;
// codes for higher categories
static final byte INUMBER = 1; // INTEGER NUMBER
static final byte RNUMBER = 2; // REAL NUMBER
static final byte WORD = 3;
static final byte SIGN = 4;
static final byte STRING = 5;
public ArrayList keywords = new ArrayList();;
private ArrayList signs = new ArrayList();;
public void fillLists() {
keywords.add("PROGRAM");
keywords.add("BEGIN");
keywords.add("END");
keywords.add("END.");
keywords.add("VAR");
keywords.add("IF");
keywords.add("THEN");
keywords.add("ELSE");
keywords.add("WHILE");
keywords.add("DO");
keywords.add("NOT");
keywords.add("AND");
keywords.add("OR");
keywords.add("READLN");
keywords.add("WRITELN");
keywords.add("INTEGER");
keywords.add("REAL");
keywords.add("BOOLEAN");
keywords.add("TRUE");
keywords.add("FALSE");
signs.add("+");
signs.add("-");
signs.add("*");
signs.add("/");
signs.add("=");
signs.add("<>");
signs.add(">");
signs.add(">=");
signs.add("<");
signs.add("<=");
signs.add(":");
signs.add(";");
signs.add(",");
signs.add(":=");
signs.add("(");
signs.add(")");
signs.add("\"");
}// fillLists()
public byte getKeywordCode(String value) {
int index = keywords.indexOf(value);
if (index == -1)
return VARIABLE;
else
return (byte)(10 + index);
}// getKeywordCode(Stirng)
public byte getSignCode(String value) {
return (byte)(30 + signs.indexOf(value));
}// getSignCode(Stirng)
}
|
91111_1 | package uczelnia;
import osoba.*;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Random;
public class GeneratorDanych {
// private static Uczelnia uczelnia = Uczelnia.getInstance();
public static String generujTekst(String dane) {
String[] listaNazwiskMeskich = {
"Nowak", "Kowalski", "Wiśniewski", "Wójcik", "Kowalczyk",
"Kamiński", "Lewandowski", "Dąbrowski", "Zieliński", "Szymański",
"Woźniak", "Kozłowski", "Jankowski", "Mazur", "Wojciechowski",
"Kwiatkowski", "Krawczyk", "Kaczmarek", "Piotrowski", "Grabowski"
};
String[] listaNazwiskDamskich = {
"Nowak", "Kowalska", "Wiśniewska", "Wójcik", "Kowalczyk",
"Kamińska", "Lewandowska", "Dąbrowska", "Zielińska", "Szymańska",
"Woźniak", "Kozłowska", "Jankowska", "Mazur", "Wojciechowska",
"Kwiatkowska", "Krawczyk", "Kaczmarek", "Piotrowska", "Grabowska"
};
String[] listaNazwisk = new String[listaNazwiskDamskich.length + listaNazwiskMeskich.length];
System.arraycopy(listaNazwiskDamskich, 0, listaNazwisk, 0, listaNazwiskDamskich.length);
System.arraycopy(listaNazwiskMeskich, 0, listaNazwisk, listaNazwiskDamskich.length, listaNazwiskMeskich.length);
String[] listaImionDamskich = {"Anna", "Maria", "Katarzyna", "Agnieszka", "Joanna",
"Małgorzata", "Ewa", "Barbara", "Zofia", "Krystyna", "Janina", "Teresa",
"Elżbieta", "Magdalena", "Ewelina", "Karolina", "Jadwiga", "Irena"};
String[] listaImionMeskich = {"Jan", "Andrzej", "Piotr", "Krzysztof",
"Tomasz", "Józef", "Marcin", "Marek", "Grzegorz",
"Tadeusz", "Adam", "Zbigniew", "Ryszard", "Dariusz",
"Henryk", "Mariusz", "Kazimierz", "Wojciech", "Robert", "Marian",
"Jacek", "Janusz", "Maciej", "Kamil", "Jakub", "Edward", "Kamil", "Damian"};
String[] listaImion = new String[listaImionDamskich.length + listaImionMeskich.length];
System.arraycopy(listaImionDamskich, 0, listaImion, 0, listaImionDamskich.length);
System.arraycopy(listaImionMeskich, 0, listaImion, listaImionDamskich.length, listaImionMeskich.length);
String[] stanowiskaAdministracyjne = {"Dziekan", "Prodziekan", "Kierownik Katedry", "Dyrektor Biura"};
String[] stanowiskaDydaktycznoBadawcze = {"Profesor", "Doktor", "Magister", "Asystent"};
String[] nazwyKursow = {"Analiza matematyczna", "Algebra", "Programowanie", "Bazy danych",
"Systemy operacyjne", "Sieci komputerowe", "Podstawy elektroniki", "Podstawy automatyki",
"Kurs robienia masla", "Lezenie na plazy", "Kurs picia piwa", "Kurs robienia kursow",
"Kurs robienia kursow robienia kursow", "Kurs robienia kursow robienia kursow robienia kursow",
"Wu Ef", "Granie w gry", "Browarnictwo", "Tance fortnite", "Ubijanie mleka"};
Random rand = new Random();
switch (dane) {
case "nazwisko":
return listaNazwisk[rand.nextInt(listaNazwisk.length)];
case "imie":
return listaImion[rand.nextInt(listaImion.length)];
case "imieDamskie":
return listaImionDamskich[rand.nextInt(listaImionDamskich.length)];
case "imieMeskie":
return listaImionMeskich[rand.nextInt(listaImionMeskich.length)];
case "nazwiskoDamskie":
return listaNazwiskDamskich[rand.nextInt(listaNazwiskDamskich.length)];
case "nazwiskoMeskie":
return listaNazwiskMeskich[rand.nextInt(listaNazwiskMeskich.length)];
case "pesel":
return Long.toString(rand.nextLong(10000000000L, 99999999999L));
case "stanowiskoAdministracyjne":
return stanowiskaAdministracyjne[rand.nextInt(stanowiskaAdministracyjne.length)];
case "stanowiskoDydaktycznoBadawcze":
return stanowiskaDydaktycznoBadawcze[rand.nextInt(stanowiskaDydaktycznoBadawcze.length)];
case "nazwaKursu":
return nazwyKursow[rand.nextInt(nazwyKursow.length)];
default:
return "";
}
}
public static Kurs generujKurs() {
return new Kurs(generujTekst("nazwaKursu"), (PracownikBadawczoDydaktyczny) generujPracownik("dydaktycznoBadawczy"), (new Random()).nextInt(1, 5));
}
public static void generujKursy(Uczelnia uczelnia, int liczba) {
Random rand = new Random();
for (int i = 0; i < liczba; i++) {
uczelnia.dodajKurs(generujKurs());
}
}
public static void generujOsoby(Uczelnia uczelnia, int liczba) {
Random rand = new Random();
for (int i = 0; i < liczba; i++) {
Osoba osoba_i;
if (rand.nextBoolean() && rand.nextBoolean() && rand.nextBoolean()) {
osoba_i = generujPracownik("administracyjny");
}
else if (rand.nextBoolean() && rand.nextBoolean()) {
osoba_i = generujPracownik("dydaktycznoBadawczy");
}
else {
osoba_i = generujStudent();
}
uczelnia.dodajOsobe(osoba_i);
}
}
public static Student generujStudent() {
char plec = new Random().nextBoolean() ? 'M' : 'K';
String imie = plec=='M' ? generujTekst("imieMeskie") : generujTekst("imieDamskie");
String nazwisko = plec=='M' ? generujTekst("nazwiskoMeskie") : generujTekst("nazwiskoDamskie");
String pesel = generujTekst("pesel");
int wiek = new Random().nextInt(18, 30);
int nrIndeksu = new Random().nextInt(299900, 300000);
int rokStudiow = new Random().nextInt(5);
Student student = new Student(imie, nazwisko, pesel, wiek, plec, nrIndeksu, rokStudiow);
return student;
}
public static void generujStudentow(Uczelnia uczelnia, int n) {
for (int i = 0; i < n; i++) {
uczelnia.dodajOsobe(generujStudent());
}
}
public static void generujPracownikow(Uczelnia uczelnia, int n) {
for (int i = 0; i < n; i++) {
if (new Random().nextBoolean()) {
uczelnia.dodajOsobe(generujPracownik("administracyjny"));
} else {
uczelnia.dodajOsobe(generujPracownik("dydaktycznoBadawczy"));
}
}
}
/**
* Generuje pracownika uczelni
* @param rodzaj "administracyjny" lub "dydaktyczno-badawczy"
* @return obiekt klasy Pracownik
*/
public static PracownikUczelni generujPracownik(String rodzaj) {
char plec = new Random().nextBoolean() ? 'M' : 'K';
String imie = plec=='M' ? generujTekst("imieMeskie") : generujTekst("imieDamskie");
String nazwisko = plec=='M' ? generujTekst("nazwiskoMeskie") : generujTekst("nazwiskoDamskie");
String pesel = generujTekst("pesel");
int wiek = new Random().nextInt(18, 80);
int stazPracy = new Random().nextInt(30, 100);
int pensja = new Random().nextInt(5000, 10000);
String stanowisko;
PracownikUczelni pracownik;
switch (rodzaj) {
case "administracyjny":
int liczbaNadgodzin = new Random().nextInt(0, 30);
stanowisko = generujTekst("stanowiskoAdministracyjne");
pracownik = new PracownikAdministracyjny(imie, nazwisko, pesel, wiek, plec, stanowisko, stazPracy, pensja, liczbaNadgodzin);
break;
case "dydaktycznoBadawczy":
int liczbaPublikacji = new Random().nextInt(0, 25);
stanowisko = generujTekst("stanowiskoDydaktycznoBadawcze");
pracownik = new PracownikBadawczoDydaktyczny(imie, nazwisko, pesel, wiek, plec, stanowisko, stazPracy, pensja, liczbaPublikacji);
break;
default:
System.out.println("FAtalny blad");
pracownik = null;
}
return pracownik;
}
}
| zeolsem/psio-lista567 | src/uczelnia/GeneratorDanych.java | 2,853 | /**
* Generuje pracownika uczelni
* @param rodzaj "administracyjny" lub "dydaktyczno-badawczy"
* @return obiekt klasy Pracownik
*/ | block_comment | pl | package uczelnia;
import osoba.*;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Random;
public class GeneratorDanych {
// private static Uczelnia uczelnia = Uczelnia.getInstance();
public static String generujTekst(String dane) {
String[] listaNazwiskMeskich = {
"Nowak", "Kowalski", "Wiśniewski", "Wójcik", "Kowalczyk",
"Kamiński", "Lewandowski", "Dąbrowski", "Zieliński", "Szymański",
"Woźniak", "Kozłowski", "Jankowski", "Mazur", "Wojciechowski",
"Kwiatkowski", "Krawczyk", "Kaczmarek", "Piotrowski", "Grabowski"
};
String[] listaNazwiskDamskich = {
"Nowak", "Kowalska", "Wiśniewska", "Wójcik", "Kowalczyk",
"Kamińska", "Lewandowska", "Dąbrowska", "Zielińska", "Szymańska",
"Woźniak", "Kozłowska", "Jankowska", "Mazur", "Wojciechowska",
"Kwiatkowska", "Krawczyk", "Kaczmarek", "Piotrowska", "Grabowska"
};
String[] listaNazwisk = new String[listaNazwiskDamskich.length + listaNazwiskMeskich.length];
System.arraycopy(listaNazwiskDamskich, 0, listaNazwisk, 0, listaNazwiskDamskich.length);
System.arraycopy(listaNazwiskMeskich, 0, listaNazwisk, listaNazwiskDamskich.length, listaNazwiskMeskich.length);
String[] listaImionDamskich = {"Anna", "Maria", "Katarzyna", "Agnieszka", "Joanna",
"Małgorzata", "Ewa", "Barbara", "Zofia", "Krystyna", "Janina", "Teresa",
"Elżbieta", "Magdalena", "Ewelina", "Karolina", "Jadwiga", "Irena"};
String[] listaImionMeskich = {"Jan", "Andrzej", "Piotr", "Krzysztof",
"Tomasz", "Józef", "Marcin", "Marek", "Grzegorz",
"Tadeusz", "Adam", "Zbigniew", "Ryszard", "Dariusz",
"Henryk", "Mariusz", "Kazimierz", "Wojciech", "Robert", "Marian",
"Jacek", "Janusz", "Maciej", "Kamil", "Jakub", "Edward", "Kamil", "Damian"};
String[] listaImion = new String[listaImionDamskich.length + listaImionMeskich.length];
System.arraycopy(listaImionDamskich, 0, listaImion, 0, listaImionDamskich.length);
System.arraycopy(listaImionMeskich, 0, listaImion, listaImionDamskich.length, listaImionMeskich.length);
String[] stanowiskaAdministracyjne = {"Dziekan", "Prodziekan", "Kierownik Katedry", "Dyrektor Biura"};
String[] stanowiskaDydaktycznoBadawcze = {"Profesor", "Doktor", "Magister", "Asystent"};
String[] nazwyKursow = {"Analiza matematyczna", "Algebra", "Programowanie", "Bazy danych",
"Systemy operacyjne", "Sieci komputerowe", "Podstawy elektroniki", "Podstawy automatyki",
"Kurs robienia masla", "Lezenie na plazy", "Kurs picia piwa", "Kurs robienia kursow",
"Kurs robienia kursow robienia kursow", "Kurs robienia kursow robienia kursow robienia kursow",
"Wu Ef", "Granie w gry", "Browarnictwo", "Tance fortnite", "Ubijanie mleka"};
Random rand = new Random();
switch (dane) {
case "nazwisko":
return listaNazwisk[rand.nextInt(listaNazwisk.length)];
case "imie":
return listaImion[rand.nextInt(listaImion.length)];
case "imieDamskie":
return listaImionDamskich[rand.nextInt(listaImionDamskich.length)];
case "imieMeskie":
return listaImionMeskich[rand.nextInt(listaImionMeskich.length)];
case "nazwiskoDamskie":
return listaNazwiskDamskich[rand.nextInt(listaNazwiskDamskich.length)];
case "nazwiskoMeskie":
return listaNazwiskMeskich[rand.nextInt(listaNazwiskMeskich.length)];
case "pesel":
return Long.toString(rand.nextLong(10000000000L, 99999999999L));
case "stanowiskoAdministracyjne":
return stanowiskaAdministracyjne[rand.nextInt(stanowiskaAdministracyjne.length)];
case "stanowiskoDydaktycznoBadawcze":
return stanowiskaDydaktycznoBadawcze[rand.nextInt(stanowiskaDydaktycznoBadawcze.length)];
case "nazwaKursu":
return nazwyKursow[rand.nextInt(nazwyKursow.length)];
default:
return "";
}
}
public static Kurs generujKurs() {
return new Kurs(generujTekst("nazwaKursu"), (PracownikBadawczoDydaktyczny) generujPracownik("dydaktycznoBadawczy"), (new Random()).nextInt(1, 5));
}
public static void generujKursy(Uczelnia uczelnia, int liczba) {
Random rand = new Random();
for (int i = 0; i < liczba; i++) {
uczelnia.dodajKurs(generujKurs());
}
}
public static void generujOsoby(Uczelnia uczelnia, int liczba) {
Random rand = new Random();
for (int i = 0; i < liczba; i++) {
Osoba osoba_i;
if (rand.nextBoolean() && rand.nextBoolean() && rand.nextBoolean()) {
osoba_i = generujPracownik("administracyjny");
}
else if (rand.nextBoolean() && rand.nextBoolean()) {
osoba_i = generujPracownik("dydaktycznoBadawczy");
}
else {
osoba_i = generujStudent();
}
uczelnia.dodajOsobe(osoba_i);
}
}
public static Student generujStudent() {
char plec = new Random().nextBoolean() ? 'M' : 'K';
String imie = plec=='M' ? generujTekst("imieMeskie") : generujTekst("imieDamskie");
String nazwisko = plec=='M' ? generujTekst("nazwiskoMeskie") : generujTekst("nazwiskoDamskie");
String pesel = generujTekst("pesel");
int wiek = new Random().nextInt(18, 30);
int nrIndeksu = new Random().nextInt(299900, 300000);
int rokStudiow = new Random().nextInt(5);
Student student = new Student(imie, nazwisko, pesel, wiek, plec, nrIndeksu, rokStudiow);
return student;
}
public static void generujStudentow(Uczelnia uczelnia, int n) {
for (int i = 0; i < n; i++) {
uczelnia.dodajOsobe(generujStudent());
}
}
public static void generujPracownikow(Uczelnia uczelnia, int n) {
for (int i = 0; i < n; i++) {
if (new Random().nextBoolean()) {
uczelnia.dodajOsobe(generujPracownik("administracyjny"));
} else {
uczelnia.dodajOsobe(generujPracownik("dydaktycznoBadawczy"));
}
}
}
/**
* Generu<SUF>*/
public static PracownikUczelni generujPracownik(String rodzaj) {
char plec = new Random().nextBoolean() ? 'M' : 'K';
String imie = plec=='M' ? generujTekst("imieMeskie") : generujTekst("imieDamskie");
String nazwisko = plec=='M' ? generujTekst("nazwiskoMeskie") : generujTekst("nazwiskoDamskie");
String pesel = generujTekst("pesel");
int wiek = new Random().nextInt(18, 80);
int stazPracy = new Random().nextInt(30, 100);
int pensja = new Random().nextInt(5000, 10000);
String stanowisko;
PracownikUczelni pracownik;
switch (rodzaj) {
case "administracyjny":
int liczbaNadgodzin = new Random().nextInt(0, 30);
stanowisko = generujTekst("stanowiskoAdministracyjne");
pracownik = new PracownikAdministracyjny(imie, nazwisko, pesel, wiek, plec, stanowisko, stazPracy, pensja, liczbaNadgodzin);
break;
case "dydaktycznoBadawczy":
int liczbaPublikacji = new Random().nextInt(0, 25);
stanowisko = generujTekst("stanowiskoDydaktycznoBadawcze");
pracownik = new PracownikBadawczoDydaktyczny(imie, nazwisko, pesel, wiek, plec, stanowisko, stazPracy, pensja, liczbaPublikacji);
break;
default:
System.out.println("FAtalny blad");
pracownik = null;
}
return pracownik;
}
}
|
111440_0 | package judge.remote.provider.spoj;
import judge.remote.RemoteOjInfo;
import judge.remote.crawler.RawProblemInfo;
import judge.remote.crawler.SimpleCrawler;
import judge.tool.Tools;
import org.apache.commons.lang3.Validate;
import org.springframework.stereotype.Component;
@Component
public class SPOJCrawler extends SimpleCrawler {
@Override
public RemoteOjInfo getOjInfo() {
return SPOJInfo.INFO;
}
@Override
protected String getProblemUrl(String problemId) {
return getHost().toURI() + "/problems/" + problemId + "/";
}
@Override
protected void preValidate(String problemId) {
Validate.isTrue(problemId.matches("\\S+"));
}
@Override
protected void populateProblemInfo(RawProblemInfo info, String problemId, String html) {
Validate.isTrue(!html.contains("In a few seconds you will be redirected to"));
info.title = Tools.regFind(html, "<h2 id=\"problem-name\" class=\"text-center\">[\\s\\S]*? - ([\\s\\S]*?)</h2>").trim();
info.timeLimit = (int) (1000 * Double.parseDouble(Tools.regFind(html, "Time limit:</td><td>([\\s\\S]*?)s")));
info.memoryLimit = (int) (1024 * Double.parseDouble(Tools.regFind(html, ">Memory limit:</td><td>([\\s\\S]*?)MB")));
info.description = (Tools.regFind(html, "<div id=\"problem-body\">([\\s\\S]*?)</div><div class=\"text-center\"><a href=\"http://www.spoj.com/submit/"))
.replace("<b>Input:</b> ", "<b>Input:</b>\n").replace("<b>Output:</b>", "\n\n<b>Output:</b>").replace("<b>Output:</b> ", "<b>Output:</b>\n");
info.source = (Tools.regFind(html, "<tr><td>Resource:</td><td>([\\s\\S]*?)</td></tr>"));
}
}
| zhblue/vjudge | vjudge2016/src/judge/remote/provider/spoj/SPOJCrawler.java | 600 | //www.spoj.com/submit/"))
| line_comment | pl | package judge.remote.provider.spoj;
import judge.remote.RemoteOjInfo;
import judge.remote.crawler.RawProblemInfo;
import judge.remote.crawler.SimpleCrawler;
import judge.tool.Tools;
import org.apache.commons.lang3.Validate;
import org.springframework.stereotype.Component;
@Component
public class SPOJCrawler extends SimpleCrawler {
@Override
public RemoteOjInfo getOjInfo() {
return SPOJInfo.INFO;
}
@Override
protected String getProblemUrl(String problemId) {
return getHost().toURI() + "/problems/" + problemId + "/";
}
@Override
protected void preValidate(String problemId) {
Validate.isTrue(problemId.matches("\\S+"));
}
@Override
protected void populateProblemInfo(RawProblemInfo info, String problemId, String html) {
Validate.isTrue(!html.contains("In a few seconds you will be redirected to"));
info.title = Tools.regFind(html, "<h2 id=\"problem-name\" class=\"text-center\">[\\s\\S]*? - ([\\s\\S]*?)</h2>").trim();
info.timeLimit = (int) (1000 * Double.parseDouble(Tools.regFind(html, "Time limit:</td><td>([\\s\\S]*?)s")));
info.memoryLimit = (int) (1024 * Double.parseDouble(Tools.regFind(html, ">Memory limit:</td><td>([\\s\\S]*?)MB")));
info.description = (Tools.regFind(html, "<div id=\"problem-body\">([\\s\\S]*?)</div><div class=\"text-center\"><a href=\"http://www.s<SUF>
.replace("<b>Input:</b> ", "<b>Input:</b>\n").replace("<b>Output:</b>", "\n\n<b>Output:</b>").replace("<b>Output:</b> ", "<b>Output:</b>\n");
info.source = (Tools.regFind(html, "<tr><td>Resource:</td><td>([\\s\\S]*?)</td></tr>"));
}
}
|
36483_11 | /*
* Created on 2008-07-10
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package pl.edu.pjwstk.mteam.core;
import java.util.Hashtable;
import pl.edu.pjwstk.mteam.pubsub.core.PubSubConstants;
import pl.edu.pjwstk.mteam.pubsub.core.Topic;
import pl.edu.pjwstk.mteam.pubsub.topology.maintenance.message.TopologyCacheUpdateRequest;
public interface PubSubInterface {
//utworzenie nowego tematu/ typu zdarzenia
/**
* Creates a new topic with the default Access Control Rules. By default only the
* topic owner is allowed to remove the topic or modify its Access Control
* @param topicID Topic identifier (String value).
* @param subscribe If this value is <code>true</code>, after a successful topic
* creation the node will automatically become its subscriber. After
* completing this operation two callbacks will be invoked -
* {@link NodeCallback#onTopicCreate(Node, Object)} and
* {@link NodeCallback#onTopicSubscribe(Node, Object)}.
*/
void createTopic(Object topicID, boolean subscribe);
/**
* Creates a new topic with custom Access Control Rules.
* @param topicID Topic identifier (String value).
* @param subscribe If this value is <code>true</code>, after a successful topic
* creation node will automatically become its subscriber. After
* completing this operation two callbacks will be invoked -
* {@link NodeCallback#onTopicCreate(Node, Object)} and
* {@link NodeCallback#onTopicSubscribe(Node, Object)}.
* @param acRules New <code>AccessControlRules</code> defined for this topic.
*/
void createTopic(Object topicID, boolean subscribe, Object acRules);
//usunięcie tematu/typu zdarzenia
void removeTopic(Object topicID);
/**
* Modifies the Access Control rules defined for this topic.
*
* @param topicID String value.
* @param acRules <code>AccessControlRules</code> defined for this topic.
*/
void modifyAccessControlRules(Object topicID, Object acRules);
/**
* Modifies the Interest Conditions defined by this node for the specified topic.
*
* @param topicID String value.
* @param ic <code>InterestConditions</code> defined for this topic.
*/
void modifyInterestConditions(Object topicID, Object ic);
//ogłaszanie zdarzenia
void networkPublish(Object topic, byte[] message);
void networkPublish(Object topic, byte[] message, short eventType);
//rejestrowanie się do zdarzenia w sieci (np monitoruję dostępność moich znajomych)
/**
* Subscribes for the new topic with the default settings which are defined as follows:<p>
* <li> All the events are interesting. One can change these settings later on
* using:<p>
* <code>PubSubsManager psmngr = node.getPubSubManager();</code><p>
* <code>InterestConditions ic = psmngr.getTopic("Plants").getInterestConditions()</code><p>
* <code>ic.getRule(PubSubConstants.OPERATION_NOTIFY).addUser(PubSubConstants.EVENT_CUSTOM, new User("paulina"));</code><p>
* <li> Node does not want to receive any events from topic history.
*
* @param topic Topic id (String value).
*/
void networkSubscribe(Object topic);
/**
* Subscribes for the new topic with the customized parameters:
* @param topic Topic id (String value).
* @param ic <code>InterestConditions</code> object containing the lists of the users
* which generate events that are interesting for this node.
* @param eventIndex Value indicating which events from the topic history node wants to
* receive after successfully completing subscribe operation.<p>
* Acceptable values are:<p>
* <li> {@link PubSubConstants#HISTORY_NONE} - if the node does not want to
* receive any events
* <li> {@link PubSubConstants#HISTORY_ALL} - if the node wants to receive all
* the events stored in the topic
* history
* <li> any other value that is >= 0 - indicates the index of the last received
* event for this topic. All the events with
* greater index will be passed to this node
* by its parent after accepting its request.
*/
void networkSubscribe(Object topic, Object ic, int eventIndex);
//wyrejestrowanie się od zdarzenia w sieci
void networkUnsubscribe(Object topic);
void maintenanceCacheUpdate(Object topic, Object nodeInfo,byte eventType);
void onDeliverCacheUpdateRequest(TopologyCacheUpdateRequest req);
void beforeNetworkLeave(Hashtable<String,Topic> topics);
boolean keepAlive(Topic topic);
boolean keepAlive(NodeInfo destination, Object topicID);
}
| zhiji6/p2pm | sources/pubsub/src/main/java/pl/edu/pjwstk/mteam/core/PubSubInterface.java | 1,468 | //wyrejestrowanie się od zdarzenia w sieci
| line_comment | pl | /*
* Created on 2008-07-10
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package pl.edu.pjwstk.mteam.core;
import java.util.Hashtable;
import pl.edu.pjwstk.mteam.pubsub.core.PubSubConstants;
import pl.edu.pjwstk.mteam.pubsub.core.Topic;
import pl.edu.pjwstk.mteam.pubsub.topology.maintenance.message.TopologyCacheUpdateRequest;
public interface PubSubInterface {
//utworzenie nowego tematu/ typu zdarzenia
/**
* Creates a new topic with the default Access Control Rules. By default only the
* topic owner is allowed to remove the topic or modify its Access Control
* @param topicID Topic identifier (String value).
* @param subscribe If this value is <code>true</code>, after a successful topic
* creation the node will automatically become its subscriber. After
* completing this operation two callbacks will be invoked -
* {@link NodeCallback#onTopicCreate(Node, Object)} and
* {@link NodeCallback#onTopicSubscribe(Node, Object)}.
*/
void createTopic(Object topicID, boolean subscribe);
/**
* Creates a new topic with custom Access Control Rules.
* @param topicID Topic identifier (String value).
* @param subscribe If this value is <code>true</code>, after a successful topic
* creation node will automatically become its subscriber. After
* completing this operation two callbacks will be invoked -
* {@link NodeCallback#onTopicCreate(Node, Object)} and
* {@link NodeCallback#onTopicSubscribe(Node, Object)}.
* @param acRules New <code>AccessControlRules</code> defined for this topic.
*/
void createTopic(Object topicID, boolean subscribe, Object acRules);
//usunięcie tematu/typu zdarzenia
void removeTopic(Object topicID);
/**
* Modifies the Access Control rules defined for this topic.
*
* @param topicID String value.
* @param acRules <code>AccessControlRules</code> defined for this topic.
*/
void modifyAccessControlRules(Object topicID, Object acRules);
/**
* Modifies the Interest Conditions defined by this node for the specified topic.
*
* @param topicID String value.
* @param ic <code>InterestConditions</code> defined for this topic.
*/
void modifyInterestConditions(Object topicID, Object ic);
//ogłaszanie zdarzenia
void networkPublish(Object topic, byte[] message);
void networkPublish(Object topic, byte[] message, short eventType);
//rejestrowanie się do zdarzenia w sieci (np monitoruję dostępność moich znajomych)
/**
* Subscribes for the new topic with the default settings which are defined as follows:<p>
* <li> All the events are interesting. One can change these settings later on
* using:<p>
* <code>PubSubsManager psmngr = node.getPubSubManager();</code><p>
* <code>InterestConditions ic = psmngr.getTopic("Plants").getInterestConditions()</code><p>
* <code>ic.getRule(PubSubConstants.OPERATION_NOTIFY).addUser(PubSubConstants.EVENT_CUSTOM, new User("paulina"));</code><p>
* <li> Node does not want to receive any events from topic history.
*
* @param topic Topic id (String value).
*/
void networkSubscribe(Object topic);
/**
* Subscribes for the new topic with the customized parameters:
* @param topic Topic id (String value).
* @param ic <code>InterestConditions</code> object containing the lists of the users
* which generate events that are interesting for this node.
* @param eventIndex Value indicating which events from the topic history node wants to
* receive after successfully completing subscribe operation.<p>
* Acceptable values are:<p>
* <li> {@link PubSubConstants#HISTORY_NONE} - if the node does not want to
* receive any events
* <li> {@link PubSubConstants#HISTORY_ALL} - if the node wants to receive all
* the events stored in the topic
* history
* <li> any other value that is >= 0 - indicates the index of the last received
* event for this topic. All the events with
* greater index will be passed to this node
* by its parent after accepting its request.
*/
void networkSubscribe(Object topic, Object ic, int eventIndex);
//wyrej<SUF>
void networkUnsubscribe(Object topic);
void maintenanceCacheUpdate(Object topic, Object nodeInfo,byte eventType);
void onDeliverCacheUpdateRequest(TopologyCacheUpdateRequest req);
void beforeNetworkLeave(Hashtable<String,Topic> topics);
boolean keepAlive(Topic topic);
boolean keepAlive(NodeInfo destination, Object topicID);
}
|
133201_8 | package chap22_ElementaryGraphAlgo;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
/**
* 161107 Practice 22.4-2 有向无环图,两个结点之间简单路径的数量。
* @author xiuzhu
* !!!! Note: 花了比较多的时间。关键是在扫描邻居的时候,为了不要扫描已经扫描过的,需要加一个map neighborsHasCheckedIndex 来记录。
*/
public class CountOfPaths {
/**
* Get the count of paths between two vertexes.
* @param graph The graph
* @param s Start vertex
* @param t End vertex
* @return count of paths between s and t
*/
public static <E> int countPathsBetweenVertexs(Map<Vertex<E>, List<Vertex<E>>> graph, Vertex<E> s, Vertex<E> t){
int count = 0;
if(!graph.keySet().contains(s) || !graph.keySet().contains(t))
return count;
Stack<Vertex<E>> stack = new Stack<Vertex<E>>();
Set<Vertex<E>> visiting = new HashSet<Vertex<E>>();
Set<Vertex<E>> hasPathToT = new HashSet<Vertex<E>>();
Map<Vertex<E>, Integer> neighborsHasCheckedIndex = new HashMap<Vertex<E>, Integer>(); //Note, need add this to avoid go back and double counted.
//initialize neighborsHasChecked map
for (Vertex<E> ver: graph.keySet()) {
ver.reset();
neighborsHasCheckedIndex.put(ver, 0);
}
s.color = COLOR.GREY;
stack.push(s);
while(s.color != COLOR.BLACK){
Vertex<E> next = null;
int neighborIndex = neighborsHasCheckedIndex.get(stack.peek());
while(neighborIndex < graph.get(stack.peek()).size()){
Vertex<E> neighbor = graph.get(stack.peek()).get(neighborIndex);
if(neighbor.color == COLOR.WHITE){
neighborsHasCheckedIndex.put(stack.peek(), ++ neighborIndex);
next = neighbor;
break;
}
else{
if(neighbor.equals(t) || hasPathToT.contains(neighbor)){
hasPathToT.addAll(visiting);
count ++; //when T is already grey.
}
}
neighborsHasCheckedIndex.put(stack.peek(), ++ neighborIndex);
}
if(next != null && !next.equals(t)){
next.π = stack.peek();
next.color = COLOR.GREY;
stack.push(next);
visiting.add(next);
}else{
if(next == null){
next = stack.pop();
}else{
hasPathToT.addAll(visiting);
count ++; //when T was white.
}
next.color = COLOR.BLACK;
visiting.remove(next);
}
}
return count;
}
//test
public static void main(String[] args) {
//test on image 22.8
Vertex<Character> m = new Vertex<Character>('m'), n = new Vertex<Character>('n'), o = new Vertex<Character>('o'), p = new Vertex<Character>('p'), q = new Vertex<Character>('q'), r = new Vertex<Character>('r'), s = new Vertex<Character>('s'), t = new Vertex<Character>('t'), u = new Vertex<Character>('u'), v = new Vertex<Character>('v'), w = new Vertex<Character>('w'), x = new Vertex<Character>('x'), y = new Vertex<Character>('y'), z = new Vertex<Character>('z');
List<Vertex<Character>> ml = new LinkedList<Vertex<Character>>(); ml.add(q); ml.add(r); ml.add(x);
List<Vertex<Character>> nl = new LinkedList<Vertex<Character>>(); nl.add(o); nl.add(q); nl.add(u);
List<Vertex<Character>> ol = new LinkedList<Vertex<Character>>(); ol.add(r); ol.add(s); ol.add(v);
List<Vertex<Character>> pl = new LinkedList<Vertex<Character>>(); pl.add(o); pl.add(s); pl.add(z);
List<Vertex<Character>> ql = new LinkedList<Vertex<Character>>(); ql.add(t);
List<Vertex<Character>> rl = new LinkedList<Vertex<Character>>(); rl.add(u); rl.add(y);
List<Vertex<Character>> sl = new LinkedList<Vertex<Character>>(); sl.add(r);
List<Vertex<Character>> tl = new LinkedList<Vertex<Character>>();
List<Vertex<Character>> ul = new LinkedList<Vertex<Character>>(); ul.add(t);
List<Vertex<Character>> vl = new LinkedList<Vertex<Character>>(); vl.add(w); vl.add(x);
List<Vertex<Character>> wl = new LinkedList<Vertex<Character>>(); wl.add(z);
List<Vertex<Character>> xl = new LinkedList<Vertex<Character>>();
List<Vertex<Character>> yl = new LinkedList<Vertex<Character>>(); yl.add(v);
List<Vertex<Character>> zl = new LinkedList<Vertex<Character>>();
Map<Vertex<Character>, List<Vertex<Character>>> g = new LinkedHashMap<Vertex<Character>, List<Vertex<Character>>>();
g.put(m, ml); g.put(n, nl); g.put(o, ol); g.put(p, pl); g.put(q, ql); g.put(r, rl); g.put(s, sl); g.put(t, tl); g.put(u, ul); g.put(v, vl); g.put(w, wl); g.put(x, xl); g.put(y, yl); g.put(z, zl);
System.out.println(countPathsBetweenVertexs(g, p, v)); //4 pov, poryv, posryv, psryv
System.out.println(countPathsBetweenVertexs(g, p, z)); //5 povwz, poryvwz, posryvwz, psryvwz, pz
System.out.println(countPathsBetweenVertexs(g, n, t)); //4 nqt, nut, norut, nosrut
System.out.println(countPathsBetweenVertexs(g, p, r)); //3 por, psr, posr
}
}
| zhuxiuwei/CLRS | src/chap22_ElementaryGraphAlgo/CountOfPaths.java | 1,994 | //5 povwz, poryvwz, posryvwz, psryvwz, pz | line_comment | pl | package chap22_ElementaryGraphAlgo;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
/**
* 161107 Practice 22.4-2 有向无环图,两个结点之间简单路径的数量。
* @author xiuzhu
* !!!! Note: 花了比较多的时间。关键是在扫描邻居的时候,为了不要扫描已经扫描过的,需要加一个map neighborsHasCheckedIndex 来记录。
*/
public class CountOfPaths {
/**
* Get the count of paths between two vertexes.
* @param graph The graph
* @param s Start vertex
* @param t End vertex
* @return count of paths between s and t
*/
public static <E> int countPathsBetweenVertexs(Map<Vertex<E>, List<Vertex<E>>> graph, Vertex<E> s, Vertex<E> t){
int count = 0;
if(!graph.keySet().contains(s) || !graph.keySet().contains(t))
return count;
Stack<Vertex<E>> stack = new Stack<Vertex<E>>();
Set<Vertex<E>> visiting = new HashSet<Vertex<E>>();
Set<Vertex<E>> hasPathToT = new HashSet<Vertex<E>>();
Map<Vertex<E>, Integer> neighborsHasCheckedIndex = new HashMap<Vertex<E>, Integer>(); //Note, need add this to avoid go back and double counted.
//initialize neighborsHasChecked map
for (Vertex<E> ver: graph.keySet()) {
ver.reset();
neighborsHasCheckedIndex.put(ver, 0);
}
s.color = COLOR.GREY;
stack.push(s);
while(s.color != COLOR.BLACK){
Vertex<E> next = null;
int neighborIndex = neighborsHasCheckedIndex.get(stack.peek());
while(neighborIndex < graph.get(stack.peek()).size()){
Vertex<E> neighbor = graph.get(stack.peek()).get(neighborIndex);
if(neighbor.color == COLOR.WHITE){
neighborsHasCheckedIndex.put(stack.peek(), ++ neighborIndex);
next = neighbor;
break;
}
else{
if(neighbor.equals(t) || hasPathToT.contains(neighbor)){
hasPathToT.addAll(visiting);
count ++; //when T is already grey.
}
}
neighborsHasCheckedIndex.put(stack.peek(), ++ neighborIndex);
}
if(next != null && !next.equals(t)){
next.π = stack.peek();
next.color = COLOR.GREY;
stack.push(next);
visiting.add(next);
}else{
if(next == null){
next = stack.pop();
}else{
hasPathToT.addAll(visiting);
count ++; //when T was white.
}
next.color = COLOR.BLACK;
visiting.remove(next);
}
}
return count;
}
//test
public static void main(String[] args) {
//test on image 22.8
Vertex<Character> m = new Vertex<Character>('m'), n = new Vertex<Character>('n'), o = new Vertex<Character>('o'), p = new Vertex<Character>('p'), q = new Vertex<Character>('q'), r = new Vertex<Character>('r'), s = new Vertex<Character>('s'), t = new Vertex<Character>('t'), u = new Vertex<Character>('u'), v = new Vertex<Character>('v'), w = new Vertex<Character>('w'), x = new Vertex<Character>('x'), y = new Vertex<Character>('y'), z = new Vertex<Character>('z');
List<Vertex<Character>> ml = new LinkedList<Vertex<Character>>(); ml.add(q); ml.add(r); ml.add(x);
List<Vertex<Character>> nl = new LinkedList<Vertex<Character>>(); nl.add(o); nl.add(q); nl.add(u);
List<Vertex<Character>> ol = new LinkedList<Vertex<Character>>(); ol.add(r); ol.add(s); ol.add(v);
List<Vertex<Character>> pl = new LinkedList<Vertex<Character>>(); pl.add(o); pl.add(s); pl.add(z);
List<Vertex<Character>> ql = new LinkedList<Vertex<Character>>(); ql.add(t);
List<Vertex<Character>> rl = new LinkedList<Vertex<Character>>(); rl.add(u); rl.add(y);
List<Vertex<Character>> sl = new LinkedList<Vertex<Character>>(); sl.add(r);
List<Vertex<Character>> tl = new LinkedList<Vertex<Character>>();
List<Vertex<Character>> ul = new LinkedList<Vertex<Character>>(); ul.add(t);
List<Vertex<Character>> vl = new LinkedList<Vertex<Character>>(); vl.add(w); vl.add(x);
List<Vertex<Character>> wl = new LinkedList<Vertex<Character>>(); wl.add(z);
List<Vertex<Character>> xl = new LinkedList<Vertex<Character>>();
List<Vertex<Character>> yl = new LinkedList<Vertex<Character>>(); yl.add(v);
List<Vertex<Character>> zl = new LinkedList<Vertex<Character>>();
Map<Vertex<Character>, List<Vertex<Character>>> g = new LinkedHashMap<Vertex<Character>, List<Vertex<Character>>>();
g.put(m, ml); g.put(n, nl); g.put(o, ol); g.put(p, pl); g.put(q, ql); g.put(r, rl); g.put(s, sl); g.put(t, tl); g.put(u, ul); g.put(v, vl); g.put(w, wl); g.put(x, xl); g.put(y, yl); g.put(z, zl);
System.out.println(countPathsBetweenVertexs(g, p, v)); //4 pov, poryv, posryv, psryv
System.out.println(countPathsBetweenVertexs(g, p, z)); //5 pov<SUF>
System.out.println(countPathsBetweenVertexs(g, n, t)); //4 nqt, nut, norut, nosrut
System.out.println(countPathsBetweenVertexs(g, p, r)); //3 por, psr, posr
}
}
|
167028_3 | package bada_oceanarium.SpringApplication.DAOs;
import bada_oceanarium.SpringApplication.DTOs.*;
import bada_oceanarium.SpringApplication.RowMappers.ZadaniaRSE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Repository
public class ZadaniaDAO {
public ZadaniaDAO(JdbcTemplate jdbcTemplate) {
super();
this.jdbcTemplate = jdbcTemplate;
}
@Autowired
private JdbcTemplate jdbcTemplate;
public List<ZadaniaPracowniczeDTO> list() {
String sql = "SELECT ZP.*, K.*, P.*, A.* FROM ZADANIA_PRACOWNICZE ZP LEFT OUTER JOIN ZADANIE_PRACOWNICZE_PRACOWNICY ZPP on ZP.ID_ZADANIA = ZPP.ID_ZADANIA LEFT JOIN KARMY K on K.ID_PRODUKTU = ZPP.ID_PRODUKTU LEFT JOIN PRACOWNICY P on ZPP.ID_PRACOWNIKA = P.ID_PRACOWNIKA LEFT JOIN AKWARIA A on ZPP.ID_AKWARIUM = A.ID_AKWARIUM";
ZadaniaRSE<Long, ZadaniaPracowniczeDTO> zadaniaRSE = new ZadaniaRSE<>();
// Use the ZadaniaRSE instance as the ResultSetExtractor
Map<Long, List<ZadaniaPracowniczeDTO>> resultMap = jdbcTemplate.query(sql, zadaniaRSE);
// System.out.println(resultMap);
// Convert the map values to a flat list
List<ZadaniaPracowniczeDTO> resultList = new ArrayList<>();
for (List<ZadaniaPracowniczeDTO> values : resultMap.values()) {
resultList.addAll(values);
}
// for (ZadaniaPracowniczeDTO zp: resultList) {
// System.out.println(zp.getIdZadania());
// System.out.println(zp.getCzestotliwosc());
// for (PracownicyDTO p:zp.getPracownicy()) {
// System.out.println(p.toString());
// }
// System.out.println("===========================");
// }
return resultList;
}
public Long createNew(String czestotliwosc, String czyWykon, java.sql.Date dataRozp, java.sql.Date dataZakon,String rodzaj){
String sqlGetId = "SELECT MAX(ID_ZADANIA) AS NajwyzszeIDAdresu FROM ZADANIA_PRACOWNICZE";
Long zadanieId = jdbcTemplate.queryForObject(sqlGetId, Long.class);
zadanieId++;
String sql = "INSERT INTO Zadania_pracownicze (Id_zadania, Czestotliwosc, Czy_wykonane, Data_rozpoczecia, Data_zakonczenia, Rodzaj_zadania)\n" +
"VALUES (?, ?, ?, ?,?,?)";
jdbcTemplate.update(sql, zadanieId, czestotliwosc, czyWykon,dataRozp,dataZakon,rodzaj);
return zadanieId;
}
public void createNewZPP(Long idZadania,Long idPracownika,Long idProduktu){
//Totalnie spierdolona jest ta tablica xD
System.out.println(idProduktu);
String sql = "INSERT INTO Zadanie_pracownicze_Pracownicy (Id_zadania, Id_pracownika, Id_Produktu, Id_akwarium)\n" +
"VALUES (?, ?, ?, 1)";
jdbcTemplate.update(sql, idZadania, idPracownika, idProduktu);
}
public void delete(String id){
jdbcTemplate.update(
"BEGIN " +
"DELETE FROM ZADANIE_PRACOWNICZE_PRACOWNICY WHERE id_zadania = ?; " +
"DELETE FROM ZADANIA_PRACOWNICZE WHERE ID_ZADANIA = ?; " +
"COMMIT; " +
"END;", id, id);
}
} | ziembar/oceanarium | src/main/java/bada_oceanarium/SpringApplication/DAOs/ZadaniaDAO.java | 1,206 | // for (ZadaniaPracowniczeDTO zp: resultList) { | line_comment | pl | package bada_oceanarium.SpringApplication.DAOs;
import bada_oceanarium.SpringApplication.DTOs.*;
import bada_oceanarium.SpringApplication.RowMappers.ZadaniaRSE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Repository
public class ZadaniaDAO {
public ZadaniaDAO(JdbcTemplate jdbcTemplate) {
super();
this.jdbcTemplate = jdbcTemplate;
}
@Autowired
private JdbcTemplate jdbcTemplate;
public List<ZadaniaPracowniczeDTO> list() {
String sql = "SELECT ZP.*, K.*, P.*, A.* FROM ZADANIA_PRACOWNICZE ZP LEFT OUTER JOIN ZADANIE_PRACOWNICZE_PRACOWNICY ZPP on ZP.ID_ZADANIA = ZPP.ID_ZADANIA LEFT JOIN KARMY K on K.ID_PRODUKTU = ZPP.ID_PRODUKTU LEFT JOIN PRACOWNICY P on ZPP.ID_PRACOWNIKA = P.ID_PRACOWNIKA LEFT JOIN AKWARIA A on ZPP.ID_AKWARIUM = A.ID_AKWARIUM";
ZadaniaRSE<Long, ZadaniaPracowniczeDTO> zadaniaRSE = new ZadaniaRSE<>();
// Use the ZadaniaRSE instance as the ResultSetExtractor
Map<Long, List<ZadaniaPracowniczeDTO>> resultMap = jdbcTemplate.query(sql, zadaniaRSE);
// System.out.println(resultMap);
// Convert the map values to a flat list
List<ZadaniaPracowniczeDTO> resultList = new ArrayList<>();
for (List<ZadaniaPracowniczeDTO> values : resultMap.values()) {
resultList.addAll(values);
}
// for (<SUF>
// System.out.println(zp.getIdZadania());
// System.out.println(zp.getCzestotliwosc());
// for (PracownicyDTO p:zp.getPracownicy()) {
// System.out.println(p.toString());
// }
// System.out.println("===========================");
// }
return resultList;
}
public Long createNew(String czestotliwosc, String czyWykon, java.sql.Date dataRozp, java.sql.Date dataZakon,String rodzaj){
String sqlGetId = "SELECT MAX(ID_ZADANIA) AS NajwyzszeIDAdresu FROM ZADANIA_PRACOWNICZE";
Long zadanieId = jdbcTemplate.queryForObject(sqlGetId, Long.class);
zadanieId++;
String sql = "INSERT INTO Zadania_pracownicze (Id_zadania, Czestotliwosc, Czy_wykonane, Data_rozpoczecia, Data_zakonczenia, Rodzaj_zadania)\n" +
"VALUES (?, ?, ?, ?,?,?)";
jdbcTemplate.update(sql, zadanieId, czestotliwosc, czyWykon,dataRozp,dataZakon,rodzaj);
return zadanieId;
}
public void createNewZPP(Long idZadania,Long idPracownika,Long idProduktu){
//Totalnie spierdolona jest ta tablica xD
System.out.println(idProduktu);
String sql = "INSERT INTO Zadanie_pracownicze_Pracownicy (Id_zadania, Id_pracownika, Id_Produktu, Id_akwarium)\n" +
"VALUES (?, ?, ?, 1)";
jdbcTemplate.update(sql, idZadania, idPracownika, idProduktu);
}
public void delete(String id){
jdbcTemplate.update(
"BEGIN " +
"DELETE FROM ZADANIE_PRACOWNICZE_PRACOWNICY WHERE id_zadania = ?; " +
"DELETE FROM ZADANIA_PRACOWNICZE WHERE ID_ZADANIA = ?; " +
"COMMIT; " +
"END;", id, id);
}
} |
39731_13 | /*
Kyberia Haiku - advanced community web application
Copyright (C) 2010 Robert Hritz
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package models;
// definuje celkovo pohlad na stranku
import java.util.HashMap;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Transient;
import com.mongodb.ObjectId;
// - zavisi od usera a sposobu pristupu
@Entity("ViewTemplate")
public class ViewTemplate extends MongoEntity{
// hlavne templaty - nazvy
public static final String VIEW_USER = "view_user";
// default templaty
public static final String VIEW_NODE_HTML = "app/views/Application/viewNode.html";
public static final String EDIT_NODE_HTML = "app/views/Application/editNode.html";
public static final String SHOW_NODES_HTML = "app/views/Application/showNodes.html";
public static final String SHOW_BOOKMARKS_HTML = "app/views/Application/showBookmarks.html";
public static final String MAIL_HTML = "app/views/Application/mail.html";
public static final String SHOW_LAST_HTML = "app/views/Application/showLast.html";
public static final String SHOW_GROUPS_HTML = "app/views/Application/showGroups.html";
public static final String SHOW_GROUP_HTML = "app/views/Application/showGroup.html";
public static final String EDIT_GROUP_HTML = "app/views/Application/editGroup.html";
public static final String ADD_GROUP_HTML = "app/views/Application/editGroup.html";
public static final String SHOW_ME_HTML = "app/views/Application/showMe.html";
public static final String SHOW_FRIENDS_HTML = "app/views/Application/showFriends.html";
public static final String SHOW_K_HTML = "app/views/Application/showK.html";
public static final String SHOW_USERS_HTML = "app/views/Application/showUsers.html";
public static final String SHOW_USER_HTML = "app/views/Application/viewUser.html";
public static final String SHOW_LIVE_HTML = "app/views/Application/showLive.html";
public static final String SHOW_TAGS_HTML = "app/views/Application/showTags.html";
public static final String ADD_USER_HTML = "app/views/Application/addUser.html";
public static final String ADD_PAGE_HTML = "app/views/Application/addPage.html";
public static final String EDIT_PAGE_HTML = "app/views/Application/editPage.html";
public static final String SHOW_PAGE_HTML = "app/views/Application/showPage.html";
public static final String SHOW_PAGES_HTML = "app/views/Application/showPages.html";
public static final String TOP_LEVEL_TEMPLATE = "topLevelTemplate";
public boolean isDefault; // true - this is the root/default view
// public String superViewId; // view inheritance
public ObjectId superView; // view inheritance
public String defaultFrame; // '/main.html'
public String defaultMenu; // '/menu/html'
public String defaultCss;
// ... and more properties
public HashMap<String,NodeTemplate> templates; // eg 'mail'=> mailTemplateInstance
// default View singleton
private static ViewTemplate defaultView; // new View(....)
public static ViewTemplate getDefaultView()
{
return defaultView;
}
public ViewTemplate(boolean isDefault, ViewTemplate superView)
{
this.isDefault = isDefault;
// this.superView = superView;
}
public void registerTemplate(String templateId, NodeTemplate t)
{
templates.put(templateId, t);
}
// eventualne get a getTemplate budu jedno a to iste
public static String getHtml(String wat)
{
//
return null;
}
public NodeTemplate getTemplate(String templateId)
{
if (templates.containsKey(templateId))
{
return templates.get(templateId);
}
else
{
if (isDefault)
{
// we don't know how to render this
// throw new TemplateInstantiationException();
return null;
}
// return superView.getTemplate(templateId);
return null;
}
}
public static void renderPage(HashMap r, HashMap s, NodeContent n, User u) // RequestParams r, Session s, Node n, User u)
{
ViewTemplate v = null;
if (s.containsKey("view")) {
v = (ViewTemplate) s.get("view");
} else if(r.containsKey("view")) {
v = (ViewTemplate) r.get("view");
} else {
v = ViewTemplate.getDefaultView();
}
// Location bude nastavena v session - tyka sa hlavne veci ako mail a td. ktore nie su Node
NodeTemplate t = null;
if (s.containsKey("Location")) {
t = v.getTemplate((String) s.get("Location"));
} else {
// hierarchia template: 1. request (override), 2. View<->Node
if(r.containsKey("template")) {
t = v.getTemplate((String) r.get("template"));
}
if (t == null) { // else + priapd ze dana tmpl neexistuje
// tu samozrejme predpokladame (ale aj ninde) ze tempalte urcene v Node urcite
// existuju, co nemusi byt pravda
t = v.getTemplate(n.getTemplate().toString());
}
}
// bail here if t is null
// v podstate to co ma tato funkcis spravit je nastavit mena inkludovanych suborov
// a premennych/tagov
// ktore sa potom spracuju v .html subore
// v.render(...);
// t.render(...);
}
public static void render()
{
// put names of files etc into renderArgs
}
// load all views, templates and datadefs and store them either locally
// in a structure or in the cache (but preferably locally)
// - which goes also for the html files (?)
public static void loadViews()
{
// first create the default view
}
/*
ViewTemplate.getTemplate(Templates.MAIL) or so?
render(ViewTemplate.getTmpl(Templates.MAIL), stuff); looks ok
but still we need to feed him session, request and view somehow
*/
public static String getHtmlTemplate(String view, String what)
{
// zatial tmpl podla hashu #what asi len
// + zadefinovat staticke identifikatory tmpl
return null;
}
public static ViewTemplate load(String id)
{
return null;
}
}
| ziman/kyberia-haiku | app/models/ViewTemplate.java | 2,114 | // new View(....) | line_comment | pl | /*
Kyberia Haiku - advanced community web application
Copyright (C) 2010 Robert Hritz
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package models;
// definuje celkovo pohlad na stranku
import java.util.HashMap;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Transient;
import com.mongodb.ObjectId;
// - zavisi od usera a sposobu pristupu
@Entity("ViewTemplate")
public class ViewTemplate extends MongoEntity{
// hlavne templaty - nazvy
public static final String VIEW_USER = "view_user";
// default templaty
public static final String VIEW_NODE_HTML = "app/views/Application/viewNode.html";
public static final String EDIT_NODE_HTML = "app/views/Application/editNode.html";
public static final String SHOW_NODES_HTML = "app/views/Application/showNodes.html";
public static final String SHOW_BOOKMARKS_HTML = "app/views/Application/showBookmarks.html";
public static final String MAIL_HTML = "app/views/Application/mail.html";
public static final String SHOW_LAST_HTML = "app/views/Application/showLast.html";
public static final String SHOW_GROUPS_HTML = "app/views/Application/showGroups.html";
public static final String SHOW_GROUP_HTML = "app/views/Application/showGroup.html";
public static final String EDIT_GROUP_HTML = "app/views/Application/editGroup.html";
public static final String ADD_GROUP_HTML = "app/views/Application/editGroup.html";
public static final String SHOW_ME_HTML = "app/views/Application/showMe.html";
public static final String SHOW_FRIENDS_HTML = "app/views/Application/showFriends.html";
public static final String SHOW_K_HTML = "app/views/Application/showK.html";
public static final String SHOW_USERS_HTML = "app/views/Application/showUsers.html";
public static final String SHOW_USER_HTML = "app/views/Application/viewUser.html";
public static final String SHOW_LIVE_HTML = "app/views/Application/showLive.html";
public static final String SHOW_TAGS_HTML = "app/views/Application/showTags.html";
public static final String ADD_USER_HTML = "app/views/Application/addUser.html";
public static final String ADD_PAGE_HTML = "app/views/Application/addPage.html";
public static final String EDIT_PAGE_HTML = "app/views/Application/editPage.html";
public static final String SHOW_PAGE_HTML = "app/views/Application/showPage.html";
public static final String SHOW_PAGES_HTML = "app/views/Application/showPages.html";
public static final String TOP_LEVEL_TEMPLATE = "topLevelTemplate";
public boolean isDefault; // true - this is the root/default view
// public String superViewId; // view inheritance
public ObjectId superView; // view inheritance
public String defaultFrame; // '/main.html'
public String defaultMenu; // '/menu/html'
public String defaultCss;
// ... and more properties
public HashMap<String,NodeTemplate> templates; // eg 'mail'=> mailTemplateInstance
// default View singleton
private static ViewTemplate defaultView; // new V<SUF>
public static ViewTemplate getDefaultView()
{
return defaultView;
}
public ViewTemplate(boolean isDefault, ViewTemplate superView)
{
this.isDefault = isDefault;
// this.superView = superView;
}
public void registerTemplate(String templateId, NodeTemplate t)
{
templates.put(templateId, t);
}
// eventualne get a getTemplate budu jedno a to iste
public static String getHtml(String wat)
{
//
return null;
}
public NodeTemplate getTemplate(String templateId)
{
if (templates.containsKey(templateId))
{
return templates.get(templateId);
}
else
{
if (isDefault)
{
// we don't know how to render this
// throw new TemplateInstantiationException();
return null;
}
// return superView.getTemplate(templateId);
return null;
}
}
public static void renderPage(HashMap r, HashMap s, NodeContent n, User u) // RequestParams r, Session s, Node n, User u)
{
ViewTemplate v = null;
if (s.containsKey("view")) {
v = (ViewTemplate) s.get("view");
} else if(r.containsKey("view")) {
v = (ViewTemplate) r.get("view");
} else {
v = ViewTemplate.getDefaultView();
}
// Location bude nastavena v session - tyka sa hlavne veci ako mail a td. ktore nie su Node
NodeTemplate t = null;
if (s.containsKey("Location")) {
t = v.getTemplate((String) s.get("Location"));
} else {
// hierarchia template: 1. request (override), 2. View<->Node
if(r.containsKey("template")) {
t = v.getTemplate((String) r.get("template"));
}
if (t == null) { // else + priapd ze dana tmpl neexistuje
// tu samozrejme predpokladame (ale aj ninde) ze tempalte urcene v Node urcite
// existuju, co nemusi byt pravda
t = v.getTemplate(n.getTemplate().toString());
}
}
// bail here if t is null
// v podstate to co ma tato funkcis spravit je nastavit mena inkludovanych suborov
// a premennych/tagov
// ktore sa potom spracuju v .html subore
// v.render(...);
// t.render(...);
}
public static void render()
{
// put names of files etc into renderArgs
}
// load all views, templates and datadefs and store them either locally
// in a structure or in the cache (but preferably locally)
// - which goes also for the html files (?)
public static void loadViews()
{
// first create the default view
}
/*
ViewTemplate.getTemplate(Templates.MAIL) or so?
render(ViewTemplate.getTmpl(Templates.MAIL), stuff); looks ok
but still we need to feed him session, request and view somehow
*/
public static String getHtmlTemplate(String view, String what)
{
// zatial tmpl podla hashu #what asi len
// + zadefinovat staticke identifikatory tmpl
return null;
}
public static ViewTemplate load(String id)
{
return null;
}
}
|
107551_0 | package promitech.colonization.screen.colony;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane;
import com.badlogic.gdx.scenes.scene2d.ui.SplitPane;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.VerticalGroup;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop;
import com.badlogic.gdx.scenes.scene2d.utils.TiledDrawable;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.viewport.FitViewport;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.ColonyTile;
import net.sf.freecol.common.model.ProductionSummary;
import net.sf.freecol.common.model.Specification;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.TileImprovementType;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.model.Unit.UnitState;
import net.sf.freecol.common.model.UnitRole;
import net.sf.freecol.common.model.colonyproduction.ColonyProduction;
import net.sf.freecol.common.model.colonyproduction.DefaultColonySettingProvider;
import net.sf.freecol.common.model.colonyproduction.MaxGoodsProductionLocation;
import net.sf.freecol.common.model.player.Notification;
import net.sf.freecol.common.model.specification.Ability;
import net.sf.freecol.common.model.specification.UnitTypeChange;
import java.util.List;
import promitech.colonization.GameResources;
import promitech.colonization.gdx.Frame;
import promitech.colonization.screen.ApplicationScreen;
import promitech.colonization.screen.ApplicationScreenType;
import promitech.colonization.screen.debug.DebugShortcutsKeys;
import promitech.colonization.screen.map.MapViewApplicationScreen;
import promitech.colonization.screen.map.diplomacy.SettlementImageLabel;
import promitech.colonization.screen.map.hud.GUIGameController;
import promitech.colonization.screen.map.hud.GUIGameModel;
import promitech.colonization.screen.ui.ChangeColonyStateListener;
import promitech.colonization.screen.ui.GoodTransferActorBridge;
import promitech.colonization.screen.ui.UnitActionOrdersDialog;
import promitech.colonization.screen.ui.UnitActionOrdersDialog.ActionTypes;
import promitech.colonization.screen.ui.UnitActionOrdersDialog.UnitActionOrderItem;
import promitech.colonization.screen.ui.UnitActor;
import promitech.colonization.screen.ui.UnitsPanel;
import promitech.colonization.ui.DoubleClickedListener;
import promitech.colonization.ui.QuestionDialog;
import promitech.colonization.ui.QuestionDialog.OptionAction;
import promitech.colonization.ui.resources.Messages;
import promitech.colonization.ui.resources.StringTemplate;
// Szukaj swobody a staniesz sie niewolnikiem wlasnych pragnien.
// Szukaj dyscypliny a znajdziesz wolnosc.
// Herbert Frank - Diuna Kapitularz
public class ColonyApplicationScreen extends ApplicationScreen {
private class ColonyUnitOrders implements UnitActionOrdersDialog.UnitOrderExecutor {
@Override
public boolean executeCommand(UnitActor unitActor, UnitActionOrderItem item, UnitActionOrdersDialog dialog) {
Unit unit = unitActor.unit;
System.out.println("execute action type: " + item.actionType);
if (ActionTypes.LIST_PRODUCTIONS.equals(item.actionType)) {
dialog.clearItem();
productionOrders(unit, dialog);
dialog.pack();
dialog.resetPositionToCenter();
return false;
}
if (ActionTypes.LIST_CHANGE_PRODUCTIONS.equals(item.actionType)) {
dialog.clearItem();
terrainProductionOrders(unit, dialog);
dialog.pack();
dialog.resetPositionToCenter();
return false;
}
if (ActionTypes.LEAVE_TOWN.equals(item.actionType)) {
DragAndDropSourceContainer<UnitActor> source = (DragAndDropSourceContainer<UnitActor>)unitActor.dragAndDropSourceContainer;
source.takePayload(unitActor, -1, -1);
outsideUnitsPanel.putPayload(unitActor, -1, -1);
}
if (ActionTypes.EQUIPPED.equals(item.actionType)) {
DragAndDropSourceContainer<UnitActor> source = (DragAndDropSourceContainer<UnitActor>)unitActor.dragAndDropSourceContainer;
source.takePayload(unitActor, -1, -1);
colony.changeUnitRole(unit, item.newRole);
unitActor.updateTexture();
outsideUnitsPanel.putPayload(unitActor, -1, -1);
}
if (ActionTypes.FORTIFY.equals(item.actionType)) {
unit.fortify();
guiGameController.nextActiveUnitWhenActive(unit);
}
if (ActionTypes.CLEAR_ORDERS.equals(item.actionType)) {
unit.clearOrders();
}
if (ActionTypes.SENTRY.equals(item.actionType)) {
unit.sentry();
guiGameController.nextActiveUnitWhenActive(unit);
}
if (ActionTypes.ACTIVATE.equals(item.actionType)) {
unit.activate();
guiGameController.closeColonyViewAndActiveUnit(colony, unit);
}
if (ActionTypes.ASSIGN_TO_PRODUCTION.equals(item.actionType)) {
DragAndDropSourceContainer<UnitActor> source = (DragAndDropSourceContainer<UnitActor>)unitActor.dragAndDropSourceContainer;
source.takePayload(unitActor, -1, -1);
// from any location to building
if (item.prodLocation.getBuildingType() != null) {
buildingsPanelActor.putWorkerOnBuilding(unitActor, item.prodLocation.getBuildingType());
}
if (item.prodLocation.getColonyTile() != null) {
terrainPanel.putWorkerOnTerrain(unitActor, item.prodLocation.getColonyTile());
}
}
if (ActionTypes.CHANGE_TERRAIN_PRODUCTION.equals(item.actionType)) {
// from terrain location to terrain location but diffrent goods type
terrainPanel.changeWorkerProduction(item.prodLocation.getColonyTile(), item.prodLocation.getTileTypeInitProduction());
}
if (ActionTypes.CLEAR_SPECIALITY.equals(item.actionType)) {
unit.changeUnitType(UnitTypeChange.ChangeType.CLEAR_SKILL);
unitActor.updateTexture();
colony.updateModelOnWorkerAllocationOrGoodsTransfer();
changeColonyStateListener.changeUnitAllocation();
}
return true;
}
private void createOrders(Unit unit, UnitActionOrdersDialog dialog) {
if (unit.isPerson()) {
dialog.addCommandItem(new UnitActionOrderItem("model.unit.workingAs", ActionTypes.LIST_PRODUCTIONS));
}
if (colony.isUnitInColony(unit)) {
if (colony.isUnitOnTerrain(unit)) {
dialog.addCommandItem(new UnitActionOrderItem("model.unit.changeWork", ActionTypes.LIST_CHANGE_PRODUCTIONS));
}
if (colony.canReducePopulation()) {
dialog.addCommandItemSeparator();
addEquippedRoles(unit, dialog);
dialog.addCommandItemSeparator();
dialog.addCommandItem(new UnitActionOrderItem("leaveTown", ActionTypes.LEAVE_TOWN));
}
} else {
dialog.addCommandItemSeparator();
addEquippedRoles(unit, dialog);
dialog.addCommandItemSeparator();
addCommands(unit, dialog);
}
if (unit.isPerson() && unit.unitType.canBeUpgraded(
Specification.instance.freeColonistUnitType,
UnitTypeChange.ChangeType.CLEAR_SKILL
)) {
dialog.addCommandItemSeparator();
dialog.addCommandItem(new UnitActionOrderItem("clearSpeciality", ActionTypes.CLEAR_SPECIALITY));
}
}
private void addCommands(Unit unit, UnitActionOrdersDialog dialog) {
dialog.addCommandItem(new UnitActionOrderItem("activateUnit", ActionTypes.ACTIVATE));
if (unit.canChangeState(UnitState.FORTIFYING)) {
dialog.addCommandItem(new UnitActionOrderItem("fortifyUnit", ActionTypes.FORTIFY));
}
dialog.addCommandItem(new UnitActionOrderItem("clearUnitOrders", ActionTypes.CLEAR_ORDERS));
if (unit.canChangeState(UnitState.SENTRY)) {
dialog.addCommandItem(new UnitActionOrderItem("sentryUnit", ActionTypes.SENTRY));
}
}
private void addEquippedRoles(Unit unit, UnitActionOrdersDialog dialog) {
if (unit.hasAbility(Ability.CAN_BE_EQUIPPED)) {
List<UnitRole> avaliableRoles = unit.avaliableRoles(colony.getColonyUpdatableFeatures());
System.out.println("avaliable roles size " + avaliableRoles.size());
for (UnitRole aRole : avaliableRoles) {
System.out.println("ur " + aRole);
if (unit.getUnitRole().equalsId(aRole)) {
continue;
}
ProductionSummary required = UnitRole.requiredGoodsToChangeRole(unit, aRole);
if (colony.getGoodsContainer().hasGoodsQuantity(required)) {
dialog.addCommandItem(new UnitActionOrderItem(unit, aRole, required, ActionTypes.EQUIPPED));
}
}
}
}
private void terrainProductionOrders(Unit unit, UnitActionOrdersDialog dialog) {
ColonyTile unitColonyTile = unit.getLocationOrNull(ColonyTile.class);
ColonyProduction colonyProduction = new ColonyProduction(new DefaultColonySettingProvider(colony));
List<MaxGoodsProductionLocation> potentialTerrainProductions = colonyProduction.simulation().determinePotentialTerrainProductions(
unitColonyTile,
unit.unitType
);
System.out.println("PotentialTerrainProduction.size = " + potentialTerrainProductions.size());
for (MaxGoodsProductionLocation g : potentialTerrainProductions) {
System.out.println("prod: " + g);
dialog.addCommandItem(new UnitActionOrderItem(g, ActionTypes.CHANGE_TERRAIN_PRODUCTION));
}
}
private void productionOrders(Unit unit, UnitActionOrdersDialog dialog) {
ColonyProduction colonyProduction = new ColonyProduction(new DefaultColonySettingProvider(colony));
java.util.List<MaxGoodsProductionLocation> maxProductionForGoods = colonyProduction.simulation().determinePotentialMaxGoodsProduction(
unit.unitType, false
);
System.out.println("PotentialMaxGoodsProduction.size = " + maxProductionForGoods.size());
for (MaxGoodsProductionLocation g : maxProductionForGoods) {
System.out.println("max: " + g);
dialog.addCommandItem(new UnitActionOrderItem(g, ActionTypes.ASSIGN_TO_PRODUCTION));
}
}
}
private DragAndDrop unitsDragAndDrop;
private DragAndDrop goodsDragAndDrop;
private Stage stage;
private BuildingsPanelActor buildingsPanelActor;
private WarehousePanel warehousePanel;
private TerrainPanel terrainPanel;
private ActualBuildableItemActor actualBuildableItemActor;
private UnitsPanel outsideUnitsPanel;
private UnitsPanel carrierUnitsPanel;
private PopulationPanel populationPanel;
private ProductionPanel productionPanel;
private Colony colony;
private Tile colonyTile;
private GUIGameController guiGameController;
private GUIGameModel guiGameModel;
private TextButton closeButton;
private TextButton customHouseButton;
private boolean colonySpyMode = false;
private final ColonyUnitOrders colonyUnitOrders = new ColonyUnitOrders();
private final ChangeColonyStateListener changeColonyStateListener = new ChangeColonyStateListener() {
@Override
public void changeUnitAllocation() {
colony.updateColonyPopulation();
colony.updateModelOnWorkerAllocationOrGoodsTransfer();
populationPanel.update(colony);
productionPanel.init(colony, colonyTile);
buildingsPanelActor.updateProductionDesc();
terrainPanel.updateProduction();
warehousePanel.updateGoodsQuantity();
actualBuildableItemActor.updateBuildItem(colony);
}
@Override
public void transfereGoods() {
colony.updateModelOnWorkerAllocationOrGoodsTransfer();
productionPanel.init(colony, colonyTile);
buildingsPanelActor.updateProductionDesc();
warehousePanel.updateGoodsQuantity();
actualBuildableItemActor.updateBuildItem(colony);
}
@Override
public void changeBuildingQueue() {
actualBuildableItemActor.updateBuildItem(colony);
}
@Override
public void addNotification(Notification notification) {
}
};
private final DoubleClickedListener unitActorDoubleClickListener = new DoubleClickedListener() {
public void doubleClicked(InputEvent event, float x, float y) {
UnitActor unitActor = (UnitActor)event.getListenerActor();
showUnitOrders(unitActor);
}
};
@Override
public void create() {
guiGameController = di.guiGameController;
guiGameModel = di.guiGameModel;
stage = new Stage(new FitViewport(ApplicationScreen.PREFERED_SCREEN_WIDTH, ApplicationScreen.PREFERED_SCREEN_HEIGHT)) {
@Override
public Actor hit(float stageX, float stageY, boolean touchable) {
Actor hit = super.hit(stageX, stageY, touchable);
if (!colonySpyMode || (closeButton == hit || closeButton.getLabel() == hit)) {
return hit;
}
return null;
}
};
unitsDragAndDrop = new DragAndDrop();
unitsDragAndDrop.setDragActorPosition(0, 0);
unitsDragAndDrop.setTapSquareSize(3);
goodsDragAndDrop = new DragAndDrop();
goodsDragAndDrop.setDragActorPosition(0, 0);
goodsDragAndDrop.setTapSquareSize(3);
GoodTransferActorBridge goodTransferActorBridge = new GoodTransferActorBridge();
buildingsPanelActor = new BuildingsPanelActor(changeColonyStateListener, unitActorDoubleClickListener);
warehousePanel = new WarehousePanel(changeColonyStateListener, goodTransferActorBridge);
terrainPanel = new TerrainPanel(changeColonyStateListener, unitActorDoubleClickListener);
outsideUnitsPanel = new UnitsPanel(Messages.msg("outsideColony"))
.withUnitChips(shape)
.withDragAndDrop(unitsDragAndDrop, changeColonyStateListener)
.withUnitDoubleClick(unitActorDoubleClickListener);
carrierUnitsPanel = new UnitsPanel(Messages.msg("inPort"))
.withUnitChips(shape)
.withUnitDoubleClick(unitActorDoubleClickListener)
.withUnitFocus(shape, goodsDragAndDrop, changeColonyStateListener);
populationPanel = new PopulationPanel();
productionPanel = new ProductionPanel();
actualBuildableItemActor = new ActualBuildableItemActor();
goodTransferActorBridge.set(carrierUnitsPanel);
goodTransferActorBridge.set(warehousePanel);
Frame paperBackground = gameResources.getFrame("Paper");
Table tableLayout = new Table();
tableLayout.setBackground(new TiledDrawable(paperBackground.texture));
VerticalGroup colGroup1 = new VerticalGroup();
colGroup1.addActor(terrainPanel);
colGroup1.addActor(populationPanel);
colGroup1.addActor(actualBuildableItemActor);
SplitPane unitsPanel = new SplitPane(carrierUnitsPanel, outsideUnitsPanel, false, GameResources.instance.getUiSkin());
Table spComponents = new Table();
spComponents.add(colGroup1);
spComponents.add(buildingsPanelActor);
ScrollPane centerComponents = new ScrollPane(spComponents, GameResources.instance.getUiSkin());
centerComponents.setForceScroll(false, false);
centerComponents.setFadeScrollBars(false);
centerComponents.setOverscroll(true, true);
centerComponents.setScrollBarPositions(true, true);
centerComponents.setScrollingDisabled(false, false);
Table buttons = new Table();
buttons.add(createBuildQueueButton()).expandX().fillX().pad(10f);
buttons.add(createCustomHouseButton()).expandX().fillX().pad(10f);
buttons.add(createCloseButton()).expandX().fillX().pad(10f);
tableLayout.setFillParent(true);
tableLayout.add(buttons).fillX().row();
tableLayout.add(productionPanel).fillX();
tableLayout.row();
tableLayout.add(centerComponents).fill().expand();
tableLayout.row();
tableLayout.add(unitsPanel).fillX();
tableLayout.row();
tableLayout.add(warehousePanel);
final DebugShortcutsKeys debugShortcutsKeys = new DebugShortcutsKeys(stage, di, this);
stage.addListener(new InputListener() {
@Override
public boolean keyDown(InputEvent event, int keycode) {
if (debugShortcutsKeys.canHandleKey(keycode)) {
debugShortcutsKeys.handleKey(keycode);
return true;
}
return super.keyDown(event, keycode);
}
});
stage.addActor(tableLayout);
//stage.setDebugAll(true);
}
private TextButton createCustomHouseButton() {
String msg = Messages.msg("model.building.customHouse.name");
customHouseButton = new TextButton(msg, GameResources.instance.getUiSkin());
customHouseButton.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
if (customHouseButton.isDisabled()) {
return;
}
CustomHouseDialog dialog = new CustomHouseDialog(shape, colony);
dialog.addOnCloseListener(new Runnable() {
@Override
public void run() {
warehousePanel.updateGoodsQuantity();
}
});
dialog.show(stage);
}
});
return customHouseButton;
}
private TextButton createBuildQueueButton() {
String msg = Messages.msg("colonyPanel.buildQueue");
TextButton textButton = new TextButton(msg, GameResources.instance.getUiSkin());
textButton.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
BuildingQueueDialog dialog = new BuildingQueueDialog(
shape, guiGameModel.game,
colony, changeColonyStateListener
);
dialog.show(stage);
}
});
return textButton;
}
private TextButton createCloseButton() {
String msg = Messages.msg("close");
closeButton = new TextButton(msg, GameResources.instance.getUiSkin());
closeButton.addListener(new InputListener() {
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
if (colony.isColonyEmpty()) {
confirmAbandonColony();
} else {
guiGameController.closeColonyView(colony);
}
return true;
}
});
return closeButton;
}
private void confirmAbandonColony() {
OptionAction<Colony> abandonColony = new OptionAction<Colony>() {
@Override
public void executeAction(Colony payload) {
colony.tile.removeTileImprovement(TileImprovementType.ROAD_MODEL_IMPROVEMENT_TYPE_ID);
colony.removeFromMap(guiGameModel.game);
colony.removeFromPlayer();
guiGameController.closeColonyView(colony);
}
};
QuestionDialog questionDialog = new QuestionDialog();
questionDialog.withHideWithoutFadeOut();
questionDialog.addDialogActor(new SettlementImageLabel(colony)).align(Align.center).row();
questionDialog.addQuestion(StringTemplate.template("abandonColony.text"));
questionDialog.addAnswer("abandonColony.yes", abandonColony, colony);
questionDialog.addAnswer("abandonColony.no", QuestionDialog.DO_NOTHING_ACTION, colony);
questionDialog.show(stage);
}
public void initColony(Colony colony) {
this.colonySpyMode = false;
this.colony = colony;
this.colonyTile = colony.tile;
unitsDragAndDrop.clear();
goodsDragAndDrop.clear();
MapViewApplicationScreen mapScreen = screenManager.getApplicationScreen(ApplicationScreenType.MAP_VIEW);
productionPanel.init(colony, colonyTile);
buildingsPanelActor.initBuildings(colony, unitsDragAndDrop);
warehousePanel.initGoods(colony, goodsDragAndDrop);
terrainPanel.initTerrains(mapScreen.getMapActor().mapDrawModel(), colonyTile, unitsDragAndDrop);
outsideUnitsPanel.initUnits(colonyTile, Unit.NOT_CARRIER_UNIT_PREDICATE);
carrierUnitsPanel.initUnits(colonyTile, Unit.CARRIER_UNIT_PREDICATE);
populationPanel.update(colony);
actualBuildableItemActor.updateBuildItem(colony);
customHouseButton.setDisabled(!colony.canExportGoods());
}
public void setColonySpyMode() {
this.colonySpyMode = true;
}
private void showUnitOrders(UnitActor unitActor) {
UnitActionOrdersDialog dialog = new UnitActionOrdersDialog(shape, unitActor, colonyUnitOrders);
colonyUnitOrders.createOrders(unitActor.unit, dialog);
dialog.show(stage);
}
@Override
public void onShow() {
resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.input.setInputProcessor(stage);
}
@Override
public void onLeave() {
Gdx.input.setInputProcessor(null);
unitsDragAndDrop.clear();
goodsDragAndDrop.clear();
this.colony = null;
this.colonyTile = null;
super.onLeave();
}
@Override
public void render() {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act();
stage.draw();
}
@Override
public void resize(int width, int height) {
stage.getViewport().update(width, height, true);
}
public Colony getColony() {
return colony;
}
}
| zlyne0/colonization | core/src/promitech/colonization/screen/colony/ColonyApplicationScreen.java | 7,026 | // Szukaj swobody a staniesz sie niewolnikiem wlasnych pragnien. | line_comment | pl | package promitech.colonization.screen.colony;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane;
import com.badlogic.gdx.scenes.scene2d.ui.SplitPane;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.VerticalGroup;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop;
import com.badlogic.gdx.scenes.scene2d.utils.TiledDrawable;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.viewport.FitViewport;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.ColonyTile;
import net.sf.freecol.common.model.ProductionSummary;
import net.sf.freecol.common.model.Specification;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.TileImprovementType;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.model.Unit.UnitState;
import net.sf.freecol.common.model.UnitRole;
import net.sf.freecol.common.model.colonyproduction.ColonyProduction;
import net.sf.freecol.common.model.colonyproduction.DefaultColonySettingProvider;
import net.sf.freecol.common.model.colonyproduction.MaxGoodsProductionLocation;
import net.sf.freecol.common.model.player.Notification;
import net.sf.freecol.common.model.specification.Ability;
import net.sf.freecol.common.model.specification.UnitTypeChange;
import java.util.List;
import promitech.colonization.GameResources;
import promitech.colonization.gdx.Frame;
import promitech.colonization.screen.ApplicationScreen;
import promitech.colonization.screen.ApplicationScreenType;
import promitech.colonization.screen.debug.DebugShortcutsKeys;
import promitech.colonization.screen.map.MapViewApplicationScreen;
import promitech.colonization.screen.map.diplomacy.SettlementImageLabel;
import promitech.colonization.screen.map.hud.GUIGameController;
import promitech.colonization.screen.map.hud.GUIGameModel;
import promitech.colonization.screen.ui.ChangeColonyStateListener;
import promitech.colonization.screen.ui.GoodTransferActorBridge;
import promitech.colonization.screen.ui.UnitActionOrdersDialog;
import promitech.colonization.screen.ui.UnitActionOrdersDialog.ActionTypes;
import promitech.colonization.screen.ui.UnitActionOrdersDialog.UnitActionOrderItem;
import promitech.colonization.screen.ui.UnitActor;
import promitech.colonization.screen.ui.UnitsPanel;
import promitech.colonization.ui.DoubleClickedListener;
import promitech.colonization.ui.QuestionDialog;
import promitech.colonization.ui.QuestionDialog.OptionAction;
import promitech.colonization.ui.resources.Messages;
import promitech.colonization.ui.resources.StringTemplate;
// Szuka<SUF>
// Szukaj dyscypliny a znajdziesz wolnosc.
// Herbert Frank - Diuna Kapitularz
public class ColonyApplicationScreen extends ApplicationScreen {
private class ColonyUnitOrders implements UnitActionOrdersDialog.UnitOrderExecutor {
@Override
public boolean executeCommand(UnitActor unitActor, UnitActionOrderItem item, UnitActionOrdersDialog dialog) {
Unit unit = unitActor.unit;
System.out.println("execute action type: " + item.actionType);
if (ActionTypes.LIST_PRODUCTIONS.equals(item.actionType)) {
dialog.clearItem();
productionOrders(unit, dialog);
dialog.pack();
dialog.resetPositionToCenter();
return false;
}
if (ActionTypes.LIST_CHANGE_PRODUCTIONS.equals(item.actionType)) {
dialog.clearItem();
terrainProductionOrders(unit, dialog);
dialog.pack();
dialog.resetPositionToCenter();
return false;
}
if (ActionTypes.LEAVE_TOWN.equals(item.actionType)) {
DragAndDropSourceContainer<UnitActor> source = (DragAndDropSourceContainer<UnitActor>)unitActor.dragAndDropSourceContainer;
source.takePayload(unitActor, -1, -1);
outsideUnitsPanel.putPayload(unitActor, -1, -1);
}
if (ActionTypes.EQUIPPED.equals(item.actionType)) {
DragAndDropSourceContainer<UnitActor> source = (DragAndDropSourceContainer<UnitActor>)unitActor.dragAndDropSourceContainer;
source.takePayload(unitActor, -1, -1);
colony.changeUnitRole(unit, item.newRole);
unitActor.updateTexture();
outsideUnitsPanel.putPayload(unitActor, -1, -1);
}
if (ActionTypes.FORTIFY.equals(item.actionType)) {
unit.fortify();
guiGameController.nextActiveUnitWhenActive(unit);
}
if (ActionTypes.CLEAR_ORDERS.equals(item.actionType)) {
unit.clearOrders();
}
if (ActionTypes.SENTRY.equals(item.actionType)) {
unit.sentry();
guiGameController.nextActiveUnitWhenActive(unit);
}
if (ActionTypes.ACTIVATE.equals(item.actionType)) {
unit.activate();
guiGameController.closeColonyViewAndActiveUnit(colony, unit);
}
if (ActionTypes.ASSIGN_TO_PRODUCTION.equals(item.actionType)) {
DragAndDropSourceContainer<UnitActor> source = (DragAndDropSourceContainer<UnitActor>)unitActor.dragAndDropSourceContainer;
source.takePayload(unitActor, -1, -1);
// from any location to building
if (item.prodLocation.getBuildingType() != null) {
buildingsPanelActor.putWorkerOnBuilding(unitActor, item.prodLocation.getBuildingType());
}
if (item.prodLocation.getColonyTile() != null) {
terrainPanel.putWorkerOnTerrain(unitActor, item.prodLocation.getColonyTile());
}
}
if (ActionTypes.CHANGE_TERRAIN_PRODUCTION.equals(item.actionType)) {
// from terrain location to terrain location but diffrent goods type
terrainPanel.changeWorkerProduction(item.prodLocation.getColonyTile(), item.prodLocation.getTileTypeInitProduction());
}
if (ActionTypes.CLEAR_SPECIALITY.equals(item.actionType)) {
unit.changeUnitType(UnitTypeChange.ChangeType.CLEAR_SKILL);
unitActor.updateTexture();
colony.updateModelOnWorkerAllocationOrGoodsTransfer();
changeColonyStateListener.changeUnitAllocation();
}
return true;
}
private void createOrders(Unit unit, UnitActionOrdersDialog dialog) {
if (unit.isPerson()) {
dialog.addCommandItem(new UnitActionOrderItem("model.unit.workingAs", ActionTypes.LIST_PRODUCTIONS));
}
if (colony.isUnitInColony(unit)) {
if (colony.isUnitOnTerrain(unit)) {
dialog.addCommandItem(new UnitActionOrderItem("model.unit.changeWork", ActionTypes.LIST_CHANGE_PRODUCTIONS));
}
if (colony.canReducePopulation()) {
dialog.addCommandItemSeparator();
addEquippedRoles(unit, dialog);
dialog.addCommandItemSeparator();
dialog.addCommandItem(new UnitActionOrderItem("leaveTown", ActionTypes.LEAVE_TOWN));
}
} else {
dialog.addCommandItemSeparator();
addEquippedRoles(unit, dialog);
dialog.addCommandItemSeparator();
addCommands(unit, dialog);
}
if (unit.isPerson() && unit.unitType.canBeUpgraded(
Specification.instance.freeColonistUnitType,
UnitTypeChange.ChangeType.CLEAR_SKILL
)) {
dialog.addCommandItemSeparator();
dialog.addCommandItem(new UnitActionOrderItem("clearSpeciality", ActionTypes.CLEAR_SPECIALITY));
}
}
private void addCommands(Unit unit, UnitActionOrdersDialog dialog) {
dialog.addCommandItem(new UnitActionOrderItem("activateUnit", ActionTypes.ACTIVATE));
if (unit.canChangeState(UnitState.FORTIFYING)) {
dialog.addCommandItem(new UnitActionOrderItem("fortifyUnit", ActionTypes.FORTIFY));
}
dialog.addCommandItem(new UnitActionOrderItem("clearUnitOrders", ActionTypes.CLEAR_ORDERS));
if (unit.canChangeState(UnitState.SENTRY)) {
dialog.addCommandItem(new UnitActionOrderItem("sentryUnit", ActionTypes.SENTRY));
}
}
private void addEquippedRoles(Unit unit, UnitActionOrdersDialog dialog) {
if (unit.hasAbility(Ability.CAN_BE_EQUIPPED)) {
List<UnitRole> avaliableRoles = unit.avaliableRoles(colony.getColonyUpdatableFeatures());
System.out.println("avaliable roles size " + avaliableRoles.size());
for (UnitRole aRole : avaliableRoles) {
System.out.println("ur " + aRole);
if (unit.getUnitRole().equalsId(aRole)) {
continue;
}
ProductionSummary required = UnitRole.requiredGoodsToChangeRole(unit, aRole);
if (colony.getGoodsContainer().hasGoodsQuantity(required)) {
dialog.addCommandItem(new UnitActionOrderItem(unit, aRole, required, ActionTypes.EQUIPPED));
}
}
}
}
private void terrainProductionOrders(Unit unit, UnitActionOrdersDialog dialog) {
ColonyTile unitColonyTile = unit.getLocationOrNull(ColonyTile.class);
ColonyProduction colonyProduction = new ColonyProduction(new DefaultColonySettingProvider(colony));
List<MaxGoodsProductionLocation> potentialTerrainProductions = colonyProduction.simulation().determinePotentialTerrainProductions(
unitColonyTile,
unit.unitType
);
System.out.println("PotentialTerrainProduction.size = " + potentialTerrainProductions.size());
for (MaxGoodsProductionLocation g : potentialTerrainProductions) {
System.out.println("prod: " + g);
dialog.addCommandItem(new UnitActionOrderItem(g, ActionTypes.CHANGE_TERRAIN_PRODUCTION));
}
}
private void productionOrders(Unit unit, UnitActionOrdersDialog dialog) {
ColonyProduction colonyProduction = new ColonyProduction(new DefaultColonySettingProvider(colony));
java.util.List<MaxGoodsProductionLocation> maxProductionForGoods = colonyProduction.simulation().determinePotentialMaxGoodsProduction(
unit.unitType, false
);
System.out.println("PotentialMaxGoodsProduction.size = " + maxProductionForGoods.size());
for (MaxGoodsProductionLocation g : maxProductionForGoods) {
System.out.println("max: " + g);
dialog.addCommandItem(new UnitActionOrderItem(g, ActionTypes.ASSIGN_TO_PRODUCTION));
}
}
}
private DragAndDrop unitsDragAndDrop;
private DragAndDrop goodsDragAndDrop;
private Stage stage;
private BuildingsPanelActor buildingsPanelActor;
private WarehousePanel warehousePanel;
private TerrainPanel terrainPanel;
private ActualBuildableItemActor actualBuildableItemActor;
private UnitsPanel outsideUnitsPanel;
private UnitsPanel carrierUnitsPanel;
private PopulationPanel populationPanel;
private ProductionPanel productionPanel;
private Colony colony;
private Tile colonyTile;
private GUIGameController guiGameController;
private GUIGameModel guiGameModel;
private TextButton closeButton;
private TextButton customHouseButton;
private boolean colonySpyMode = false;
private final ColonyUnitOrders colonyUnitOrders = new ColonyUnitOrders();
private final ChangeColonyStateListener changeColonyStateListener = new ChangeColonyStateListener() {
@Override
public void changeUnitAllocation() {
colony.updateColonyPopulation();
colony.updateModelOnWorkerAllocationOrGoodsTransfer();
populationPanel.update(colony);
productionPanel.init(colony, colonyTile);
buildingsPanelActor.updateProductionDesc();
terrainPanel.updateProduction();
warehousePanel.updateGoodsQuantity();
actualBuildableItemActor.updateBuildItem(colony);
}
@Override
public void transfereGoods() {
colony.updateModelOnWorkerAllocationOrGoodsTransfer();
productionPanel.init(colony, colonyTile);
buildingsPanelActor.updateProductionDesc();
warehousePanel.updateGoodsQuantity();
actualBuildableItemActor.updateBuildItem(colony);
}
@Override
public void changeBuildingQueue() {
actualBuildableItemActor.updateBuildItem(colony);
}
@Override
public void addNotification(Notification notification) {
}
};
private final DoubleClickedListener unitActorDoubleClickListener = new DoubleClickedListener() {
public void doubleClicked(InputEvent event, float x, float y) {
UnitActor unitActor = (UnitActor)event.getListenerActor();
showUnitOrders(unitActor);
}
};
@Override
public void create() {
guiGameController = di.guiGameController;
guiGameModel = di.guiGameModel;
stage = new Stage(new FitViewport(ApplicationScreen.PREFERED_SCREEN_WIDTH, ApplicationScreen.PREFERED_SCREEN_HEIGHT)) {
@Override
public Actor hit(float stageX, float stageY, boolean touchable) {
Actor hit = super.hit(stageX, stageY, touchable);
if (!colonySpyMode || (closeButton == hit || closeButton.getLabel() == hit)) {
return hit;
}
return null;
}
};
unitsDragAndDrop = new DragAndDrop();
unitsDragAndDrop.setDragActorPosition(0, 0);
unitsDragAndDrop.setTapSquareSize(3);
goodsDragAndDrop = new DragAndDrop();
goodsDragAndDrop.setDragActorPosition(0, 0);
goodsDragAndDrop.setTapSquareSize(3);
GoodTransferActorBridge goodTransferActorBridge = new GoodTransferActorBridge();
buildingsPanelActor = new BuildingsPanelActor(changeColonyStateListener, unitActorDoubleClickListener);
warehousePanel = new WarehousePanel(changeColonyStateListener, goodTransferActorBridge);
terrainPanel = new TerrainPanel(changeColonyStateListener, unitActorDoubleClickListener);
outsideUnitsPanel = new UnitsPanel(Messages.msg("outsideColony"))
.withUnitChips(shape)
.withDragAndDrop(unitsDragAndDrop, changeColonyStateListener)
.withUnitDoubleClick(unitActorDoubleClickListener);
carrierUnitsPanel = new UnitsPanel(Messages.msg("inPort"))
.withUnitChips(shape)
.withUnitDoubleClick(unitActorDoubleClickListener)
.withUnitFocus(shape, goodsDragAndDrop, changeColonyStateListener);
populationPanel = new PopulationPanel();
productionPanel = new ProductionPanel();
actualBuildableItemActor = new ActualBuildableItemActor();
goodTransferActorBridge.set(carrierUnitsPanel);
goodTransferActorBridge.set(warehousePanel);
Frame paperBackground = gameResources.getFrame("Paper");
Table tableLayout = new Table();
tableLayout.setBackground(new TiledDrawable(paperBackground.texture));
VerticalGroup colGroup1 = new VerticalGroup();
colGroup1.addActor(terrainPanel);
colGroup1.addActor(populationPanel);
colGroup1.addActor(actualBuildableItemActor);
SplitPane unitsPanel = new SplitPane(carrierUnitsPanel, outsideUnitsPanel, false, GameResources.instance.getUiSkin());
Table spComponents = new Table();
spComponents.add(colGroup1);
spComponents.add(buildingsPanelActor);
ScrollPane centerComponents = new ScrollPane(spComponents, GameResources.instance.getUiSkin());
centerComponents.setForceScroll(false, false);
centerComponents.setFadeScrollBars(false);
centerComponents.setOverscroll(true, true);
centerComponents.setScrollBarPositions(true, true);
centerComponents.setScrollingDisabled(false, false);
Table buttons = new Table();
buttons.add(createBuildQueueButton()).expandX().fillX().pad(10f);
buttons.add(createCustomHouseButton()).expandX().fillX().pad(10f);
buttons.add(createCloseButton()).expandX().fillX().pad(10f);
tableLayout.setFillParent(true);
tableLayout.add(buttons).fillX().row();
tableLayout.add(productionPanel).fillX();
tableLayout.row();
tableLayout.add(centerComponents).fill().expand();
tableLayout.row();
tableLayout.add(unitsPanel).fillX();
tableLayout.row();
tableLayout.add(warehousePanel);
final DebugShortcutsKeys debugShortcutsKeys = new DebugShortcutsKeys(stage, di, this);
stage.addListener(new InputListener() {
@Override
public boolean keyDown(InputEvent event, int keycode) {
if (debugShortcutsKeys.canHandleKey(keycode)) {
debugShortcutsKeys.handleKey(keycode);
return true;
}
return super.keyDown(event, keycode);
}
});
stage.addActor(tableLayout);
//stage.setDebugAll(true);
}
private TextButton createCustomHouseButton() {
String msg = Messages.msg("model.building.customHouse.name");
customHouseButton = new TextButton(msg, GameResources.instance.getUiSkin());
customHouseButton.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
if (customHouseButton.isDisabled()) {
return;
}
CustomHouseDialog dialog = new CustomHouseDialog(shape, colony);
dialog.addOnCloseListener(new Runnable() {
@Override
public void run() {
warehousePanel.updateGoodsQuantity();
}
});
dialog.show(stage);
}
});
return customHouseButton;
}
private TextButton createBuildQueueButton() {
String msg = Messages.msg("colonyPanel.buildQueue");
TextButton textButton = new TextButton(msg, GameResources.instance.getUiSkin());
textButton.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
BuildingQueueDialog dialog = new BuildingQueueDialog(
shape, guiGameModel.game,
colony, changeColonyStateListener
);
dialog.show(stage);
}
});
return textButton;
}
private TextButton createCloseButton() {
String msg = Messages.msg("close");
closeButton = new TextButton(msg, GameResources.instance.getUiSkin());
closeButton.addListener(new InputListener() {
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
if (colony.isColonyEmpty()) {
confirmAbandonColony();
} else {
guiGameController.closeColonyView(colony);
}
return true;
}
});
return closeButton;
}
private void confirmAbandonColony() {
OptionAction<Colony> abandonColony = new OptionAction<Colony>() {
@Override
public void executeAction(Colony payload) {
colony.tile.removeTileImprovement(TileImprovementType.ROAD_MODEL_IMPROVEMENT_TYPE_ID);
colony.removeFromMap(guiGameModel.game);
colony.removeFromPlayer();
guiGameController.closeColonyView(colony);
}
};
QuestionDialog questionDialog = new QuestionDialog();
questionDialog.withHideWithoutFadeOut();
questionDialog.addDialogActor(new SettlementImageLabel(colony)).align(Align.center).row();
questionDialog.addQuestion(StringTemplate.template("abandonColony.text"));
questionDialog.addAnswer("abandonColony.yes", abandonColony, colony);
questionDialog.addAnswer("abandonColony.no", QuestionDialog.DO_NOTHING_ACTION, colony);
questionDialog.show(stage);
}
public void initColony(Colony colony) {
this.colonySpyMode = false;
this.colony = colony;
this.colonyTile = colony.tile;
unitsDragAndDrop.clear();
goodsDragAndDrop.clear();
MapViewApplicationScreen mapScreen = screenManager.getApplicationScreen(ApplicationScreenType.MAP_VIEW);
productionPanel.init(colony, colonyTile);
buildingsPanelActor.initBuildings(colony, unitsDragAndDrop);
warehousePanel.initGoods(colony, goodsDragAndDrop);
terrainPanel.initTerrains(mapScreen.getMapActor().mapDrawModel(), colonyTile, unitsDragAndDrop);
outsideUnitsPanel.initUnits(colonyTile, Unit.NOT_CARRIER_UNIT_PREDICATE);
carrierUnitsPanel.initUnits(colonyTile, Unit.CARRIER_UNIT_PREDICATE);
populationPanel.update(colony);
actualBuildableItemActor.updateBuildItem(colony);
customHouseButton.setDisabled(!colony.canExportGoods());
}
public void setColonySpyMode() {
this.colonySpyMode = true;
}
private void showUnitOrders(UnitActor unitActor) {
UnitActionOrdersDialog dialog = new UnitActionOrdersDialog(shape, unitActor, colonyUnitOrders);
colonyUnitOrders.createOrders(unitActor.unit, dialog);
dialog.show(stage);
}
@Override
public void onShow() {
resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.input.setInputProcessor(stage);
}
@Override
public void onLeave() {
Gdx.input.setInputProcessor(null);
unitsDragAndDrop.clear();
goodsDragAndDrop.clear();
this.colony = null;
this.colonyTile = null;
super.onLeave();
}
@Override
public void render() {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act();
stage.draw();
}
@Override
public void resize(int width, int height) {
stage.getViewport().update(width, height, true);
}
public Colony getColony() {
return colony;
}
}
|
29374_0 | package com.example.demo;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
import org.springframework.scheduling.config.ScheduledTask;
public class MyScheduler {
int mySchedulerRunCounter = 0;
@Autowired
ScheduledAnnotationBeanPostProcessor scheduledAnnotationBeanPostProcessor;
@Scheduled(fixedDelayString = "5000", initialDelayString = "5000")
public void run() {
// jak poleci wyjatek to timer czeka i znowu sie odpala
// if (true) {
// throw new IllegalStateException("my exception from scheduler");
// }
System.out.println("MyScheduler run : " + (mySchedulerRunCounter++));
Set<ScheduledTask> scheduledTasks = scheduledAnnotationBeanPostProcessor.getScheduledTasks();
System.out.println("MyScheduler task count: " + scheduledTasks.size());
for (ScheduledTask scheduledTask : scheduledTasks) {
System.out.println("" + scheduledTask.getClass());
System.out.println("" + scheduledTask.getTask().getClass());
}
}
}
| zlyne0/exercises | spring_boot_2_async/src/main/java/com/example/demo/MyScheduler.java | 337 | // jak poleci wyjatek to timer czeka i znowu sie odpala | line_comment | pl | package com.example.demo;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
import org.springframework.scheduling.config.ScheduledTask;
public class MyScheduler {
int mySchedulerRunCounter = 0;
@Autowired
ScheduledAnnotationBeanPostProcessor scheduledAnnotationBeanPostProcessor;
@Scheduled(fixedDelayString = "5000", initialDelayString = "5000")
public void run() {
// jak p<SUF>
// if (true) {
// throw new IllegalStateException("my exception from scheduler");
// }
System.out.println("MyScheduler run : " + (mySchedulerRunCounter++));
Set<ScheduledTask> scheduledTasks = scheduledAnnotationBeanPostProcessor.getScheduledTasks();
System.out.println("MyScheduler task count: " + scheduledTasks.size());
for (ScheduledTask scheduledTask : scheduledTasks) {
System.out.println("" + scheduledTask.getClass());
System.out.println("" + scheduledTask.getTask().getClass());
}
}
}
|
167681_1 | package com.matez.wildnature.common.blocks;
import com.matez.wildnature.init.WN;
import com.matez.wildnature.util.config.CommonConfig;
import net.minecraft.block.BlockState;
import net.minecraft.block.SoundType;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.storage.loot.LootContext;
import java.util.ArrayList;
import java.util.List;
public class RockBase extends BlockBase{
//0 - skały typu kamień(normalne) (0-255)
//1 - skały osadowe (55-255)
//2 - skały metamorficzne (30-55)
//3 - skały magmowe (5-30)
private int type;
private int size = CommonConfig.rockSize.get();
private int count = CommonConfig.rockChance.get();
private ResourceLocation regName;
private static Properties Properties(Properties properties, int type){
properties.sound(SoundType.STONE);
if(type==0) {
properties.hardnessAndResistance(1.5F, 6F);
}else if(type==1){
properties.hardnessAndResistance(1.2F, 3F);
}else if(type==2){
properties.hardnessAndResistance(1.6F, 7F);
}else if(type==3){
properties.hardnessAndResistance(2F, 9F);
}
return properties;
}
public RockBase(Properties properties, Item.Properties builder, ResourceLocation regName, int type) {
super(Properties(properties, type), builder, regName);
this.regName=regName;
this.type=type;
}
public int getType() {
return type;
}
public int getSize() {
return size;
}
public int getCount() {
return count;
}
public int getMinYByType(int seaLevel){
int defaultMinY = Math.round(seaLevel/3);
if(type==0){
return 0;
}else if(type==1){
return defaultMinY+defaultMinY+5;
}else if(type==2){
return defaultMinY+5;
}else if(type==3){
return 5;
}
return 0;
}
public int getMaxYByType(int seaLevel, int worldHeight){
int defaultMaxY = Math.round(seaLevel/3);
if(type==0){
return worldHeight;
}else if(type==1){
return seaLevel;//47-63
}else if(type==2){
return defaultMaxY+defaultMaxY+5;//26-47
}else if(type==3){
return defaultMaxY+5;//5-26
}
return 0;
}
@Override
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
boolean silkTouch = false;
List<ItemStack> list = new ArrayList<>();
String rock = regName.getPath().toString();
list.add(new ItemStack(WN.getBlockByID("wildnature:"+rock+"_cobble"), 1));
return list;
}
}
| zmatez/WNDev1.15.2 | src/main/java/com/matez/wildnature/common/blocks/RockBase.java | 904 | //1 - skały osadowe (55-255) | line_comment | pl | package com.matez.wildnature.common.blocks;
import com.matez.wildnature.init.WN;
import com.matez.wildnature.util.config.CommonConfig;
import net.minecraft.block.BlockState;
import net.minecraft.block.SoundType;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.storage.loot.LootContext;
import java.util.ArrayList;
import java.util.List;
public class RockBase extends BlockBase{
//0 - skały typu kamień(normalne) (0-255)
//1 - s<SUF>
//2 - skały metamorficzne (30-55)
//3 - skały magmowe (5-30)
private int type;
private int size = CommonConfig.rockSize.get();
private int count = CommonConfig.rockChance.get();
private ResourceLocation regName;
private static Properties Properties(Properties properties, int type){
properties.sound(SoundType.STONE);
if(type==0) {
properties.hardnessAndResistance(1.5F, 6F);
}else if(type==1){
properties.hardnessAndResistance(1.2F, 3F);
}else if(type==2){
properties.hardnessAndResistance(1.6F, 7F);
}else if(type==3){
properties.hardnessAndResistance(2F, 9F);
}
return properties;
}
public RockBase(Properties properties, Item.Properties builder, ResourceLocation regName, int type) {
super(Properties(properties, type), builder, regName);
this.regName=regName;
this.type=type;
}
public int getType() {
return type;
}
public int getSize() {
return size;
}
public int getCount() {
return count;
}
public int getMinYByType(int seaLevel){
int defaultMinY = Math.round(seaLevel/3);
if(type==0){
return 0;
}else if(type==1){
return defaultMinY+defaultMinY+5;
}else if(type==2){
return defaultMinY+5;
}else if(type==3){
return 5;
}
return 0;
}
public int getMaxYByType(int seaLevel, int worldHeight){
int defaultMaxY = Math.round(seaLevel/3);
if(type==0){
return worldHeight;
}else if(type==1){
return seaLevel;//47-63
}else if(type==2){
return defaultMaxY+defaultMaxY+5;//26-47
}else if(type==3){
return defaultMaxY+5;//5-26
}
return 0;
}
@Override
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
boolean silkTouch = false;
List<ItemStack> list = new ArrayList<>();
String rock = regName.getPath().toString();
list.add(new ItemStack(WN.getBlockByID("wildnature:"+rock+"_cobble"), 1));
return list;
}
}
|
77503_2 | package com.paul.base.lock;
/**
* 重入锁:同一线程可以进入同步块
* 不可重入锁:同一线程进入获取锁,再次进入同步块。需等待 锁释放
*
* @ClassName: NonReentrantlocks
* @Description: TODO(这里用一句话描述这个类的作用)
* @author admin
* @date 2019年5月13日 下午6:18:58
*/
public class NonReentrantlocks {
boolean isLock = false;
/**
* 模拟锁等待
*/
public synchronized void lock() throws InterruptedException {
while (isLock) {
System.out.println(Thread.currentThread().getName() + "lock 线程等待");
wait();
}
this.isLock = true;
}
public synchronized void unLock() throws InterruptedException {
this.isLock = false;
System.out.println(Thread.currentThread().getName() + "unLock 线程唤醒");
notify();
}
/**
* 验证synchronized 为重入锁
*/
public synchronized void synlock() throws InterruptedException {
System.out.println(Thread.currentThread().getName() + " synlock 线程锁");
}
public synchronized void synunLock() throws InterruptedException {
System.out.println(Thread.currentThread().getName() + " synunLock 线程唤醒");
}
}
| zmpaul/learningprogress | src/main/java/com/paul/base/lock/NonReentrantlocks.java | 450 | /**
* 验证synchronized 为重入锁
*/ | block_comment | pl | package com.paul.base.lock;
/**
* 重入锁:同一线程可以进入同步块
* 不可重入锁:同一线程进入获取锁,再次进入同步块。需等待 锁释放
*
* @ClassName: NonReentrantlocks
* @Description: TODO(这里用一句话描述这个类的作用)
* @author admin
* @date 2019年5月13日 下午6:18:58
*/
public class NonReentrantlocks {
boolean isLock = false;
/**
* 模拟锁等待
*/
public synchronized void lock() throws InterruptedException {
while (isLock) {
System.out.println(Thread.currentThread().getName() + "lock 线程等待");
wait();
}
this.isLock = true;
}
public synchronized void unLock() throws InterruptedException {
this.isLock = false;
System.out.println(Thread.currentThread().getName() + "unLock 线程唤醒");
notify();
}
/**
* 验证sync<SUF>*/
public synchronized void synlock() throws InterruptedException {
System.out.println(Thread.currentThread().getName() + " synlock 线程锁");
}
public synchronized void synunLock() throws InterruptedException {
System.out.println(Thread.currentThread().getName() + " synunLock 线程唤醒");
}
}
|
32742_1 | public class CountingSemaphore implements ISemaphore{
private int _value = 0;
private int _waiting = 0;
private Semaphore next_operation = new Semaphore(true); // wyklucza wykonywanie innych operacji na semaforze w trakcie danej operacji
private Semaphore can_decrement; // wpuszcza, gdy wcześniej semafor ogólny był podniesiony, więc da się go opuścić
public CountingSemaphore(int initial_state){
this._value = initial_state;
if(initial_state > 0){
can_decrement = new Semaphore(true);
}
else{
can_decrement = new Semaphore(false);
}
}
public int getState() {
return _value;
}
@Override
public void P() throws InterruptedException { // decrementation
can_decrement.P();
next_operation.P();
_value--;
if(_value > 0){
can_decrement.V();
}
next_operation.V();
}
@Override
public void V() throws InterruptedException { // incrementation
next_operation.P();
_value++;
if(_value > 0){
can_decrement.V();
}
next_operation.V();
}
}
| zofiagrodecka/Concurrent-computing | Semaphores/src/main/java/CountingSemaphore.java | 359 | // wpuszcza, gdy wcześniej semafor ogólny był podniesiony, więc da się go opuścić | line_comment | pl | public class CountingSemaphore implements ISemaphore{
private int _value = 0;
private int _waiting = 0;
private Semaphore next_operation = new Semaphore(true); // wyklucza wykonywanie innych operacji na semaforze w trakcie danej operacji
private Semaphore can_decrement; // wpusz<SUF>
public CountingSemaphore(int initial_state){
this._value = initial_state;
if(initial_state > 0){
can_decrement = new Semaphore(true);
}
else{
can_decrement = new Semaphore(false);
}
}
public int getState() {
return _value;
}
@Override
public void P() throws InterruptedException { // decrementation
can_decrement.P();
next_operation.P();
_value--;
if(_value > 0){
can_decrement.V();
}
next_operation.V();
}
@Override
public void V() throws InterruptedException { // incrementation
next_operation.P();
_value++;
if(_value > 0){
can_decrement.V();
}
next_operation.V();
}
}
|
179339_4 | package com.github.mubbo.sound;
import javax.sound.midi.MidiUnavailableException;
import java.util.ArrayList;
import java.util.List;
/**
* Sound module main coordinating class. An object of class MusicBox processes coordinates into sound. Playing sound
* requires two different steps:
* - add a note (via {@code addNote} function), that is then converted into sound based on set scale
* - play all added notes: {@code tick}
* Sample usage:
* <pre>
* {@code
* MusicBox mb = new MusicBox(10, 10);
* mb.addNote(0, 1);
* mb.addNote(1, 0);
* mb.tick(); // play two given sounds at once
* Thread.sleep(1000) // wait 1 second
* mb.changeScale("Major");
* for (int i = 0; i < 8; i++) { // play C major scale (one sound every half a second)
* mb.addNode(i, 0);
* Thread.sleep(500);
* }
* }
* </pre>
*/
public class MusicBox {
/**
* Default value of a base pitch in MIDI number. (60 = C4)
*/
private static final int DEFAULT_BASE_PITCH = 55;
/**
* Minimal allowed base pitch value. (21 = A0, which is the lowest piano note)
*/
private static final int MIN_MIDI = 21;
/**
* Maximal allowed base pitch value. (84 = C6, which is two octaves below highest piano note)
*/
private static final int MAX_MIDI = 84;
/**
* Reverb consts // TODO okomentarzować
*/
public static final int REVERB_MAX = 2000;
public static final int REVERB_MIN = 25;
public static final int REVERB_DEFAULT = 200;
/**
* Number of available instruments excluding percussion.
*/
public static final int NUMBER_OF_INSTRUMENTS = 8; // wywalony obój
/**
* Sound producing module.
*/
private final SynthesizerWrapper player;
/**
* Current value of a scale.
*
* @see Scale
*/
private Scale currentScale = Scale.DEFAULT_SCALE;
/**
* Current value of a base pitch in MIDI number.
*/
private int basePitch = DEFAULT_BASE_PITCH;
/**
* Horizontal grid size (used in converting coordinates to pitch.
*/
private int sizeX;
/**
* Vertical grid size (used in converting coordinates to pitch.
*/
private int sizeY;
/**
* Notes added since last {@code tick()} call in MIDI number per instrument.
*/
private List<List<Integer>> currentTickInstruments = new ArrayList<>();
/**
* Percussion sounds added since last {@code tick()} call in range [0; max(sizeX - 3, sizeY - 3)].
*/
private List<Integer> currentTickPercussion = new ArrayList<>();
{
for (int i = 0; i < NUMBER_OF_INSTRUMENTS; i++) {
currentTickInstruments.add(new ArrayList<>());
}
}
/**
* @param x horizontal grid size.
* @param y vertical grid size.
* @throws MidiUnavailableException when it was impossible to init sound module.
*/
public MusicBox(int x, int y) throws MidiUnavailableException {
player = new JavaxSynthesizerWrapper();
this.sizeX = x;
this.sizeY = y;
}
/**
* Changes current scale by a String of display name.
*
* @param scaleDisplayName scale display name.
*/
public void changeScale(String scaleDisplayName) {
Scale newScale = Scale.reverseLookupByString(scaleDisplayName);
if (newScale == null) {
System.err.println("Couldn't find a scale of given name: " + scaleDisplayName);
} else {
currentScale = newScale;
}
}
/**
* Changes current scale by pointing to enumeration value.
*
* @param scale scale enumeration value.
*/
public void changeScale(Scale scale) {
if (scale == null) {
System.err.println("Pointed to a null value scale.");
} else {
currentScale = scale;
}
}
/**
* Changes grid size.
*
* @param x new horizontal size.
* @param y new vertical size.
*/
public void changeSize(int x, int y) {
this.sizeX = x;
this.sizeY = y;
}
/**
* Pitch setter.
*
* @param newPitch new pitch value in MIDI number.
*/
public void setPitch(int newPitch) {
if (newPitch < MIN_MIDI || newPitch > MAX_MIDI) {
System.err.println("new pitch not within expected range of [MIN_MIDI; MAX_MIDI] = [" + MIN_MIDI + "; " + MAX_MIDI + "].");
} else {
this.basePitch = newPitch;
}
}
/**
* Adds node in coordinates to play.
*
* @param x x coordinate.
* @param y y coordinate.
* @param instrument no. of instrument
* @see MusicBox for further explanation.
*/
public void addNote(int x, int y, int instrument) {
// if (instrument == 9) {
// addPercussion(x, y);
// } else {
currentTickInstruments.get(instrument).add(currentScale.scaleDegreeToRelativePitch(soundCoordinateToScaleDegree(x, y)) + basePitch);
// }
}
/**
* Adds node in coordinates to play.
*
* @param x x coordinate.
* @param y y coordinate.
* @see MusicBox for further explanation.
*/
@Deprecated
public void addNote(int x, int y) {
addNote(x, y, 0);
}
/**
* Adds percussion node in coordinates to play. As opposed to addNote, percussion notes are not changed by scale.
* Instead, they are passed to the synthesizer as in a range of [0, size - 3].
*
* @param x x coordinate.
* @param y y coordinate.
*/
public void addPercussion(int x, int y) {
currentTickPercussion.add(soundCoordinateToScaleDegree(x, y));
}
/**
* Plays all added notes.
*
* @see MusicBox for further explanation.
*/
public void tick() {
for (int i = 0; i < NUMBER_OF_INSTRUMENTS; i++) {
player.playNotes(currentTickInstruments.get(i), i);
}
player.playPercussionSounds(currentTickPercussion);
player.tick();
this.clearCurrentNotes();
}
public void setReverb(int ms) {
player.setReverb(ms);
}
public void setPreset(String presetName) {
player.setInstrumentPreset(presetName);
}
/**
* Clears all the currentTickNode subarrays. (Performed at each tick.)
*/
private void clearCurrentNotes() {
for (var currentTickInstrument : currentTickInstruments) {
currentTickInstrument.clear();
}
currentTickPercussion.clear();
}
/**
* Converts coordinates into a scale degree as follows:
* <pre>
* {@code
* +---------+-------+-------+-------+-------+-------+---------+---------+
* | | 0 | 1 | 2 | 3 | ... | sizeX-3 | |
* +---------+-------+-------+-------+-------+-------+---------+---------+
* | sizeY-3 | | | | | | | sizeY-3 |
* +---------+-------+-------+-------+-------+-------+---------+---------+
* | : | | | | | | | : |
* +---------+-------+-------+-------+-------+-------+---------+---------+
* | 3 | | | | | | | 3 |
* +---------+-------+-------+-------+-------+-------+---------+---------+
* | 2 | | | | | | | 2 |
* +---------+-------+-------+-------+-------+-------+---------+---------+
* | 1 | | | | | | | 1 |
* +---------+-------+-------+-------+-------+-------+---------+---------+
* | 0 | | | | | | | 0 |
* +---------+-------+-------+-------+-------+-------+---------+---------+
* | | 0 | 1 | 2 | 3 | ... | sizeX-3 | |
* +---------+-------+-------+-------+-------+-------+---------+---------+
* }
* </pre>
*
* @param x x coordinate
* @param y y coordinate
* @return scale degree as explained above
*/
private int soundCoordinateToScaleDegree(int x, int y) {
if (x == 0 || x == this.sizeX - 1) {
return this.sizeY - y - 2;
} else {
if (y != 0 && y != this.sizeY - 1) {
System.err.println("MusicBox.soundCoordinateToScaleDegree: received coordinates not on border: assuming y = 0.");
}
return x - 1;
}
}
}
| zofja/mubbo | src/main/java/com/github/mubbo/sound/MusicBox.java | 2,613 | /**
* Reverb consts // TODO okomentarzować
*/ | block_comment | pl | package com.github.mubbo.sound;
import javax.sound.midi.MidiUnavailableException;
import java.util.ArrayList;
import java.util.List;
/**
* Sound module main coordinating class. An object of class MusicBox processes coordinates into sound. Playing sound
* requires two different steps:
* - add a note (via {@code addNote} function), that is then converted into sound based on set scale
* - play all added notes: {@code tick}
* Sample usage:
* <pre>
* {@code
* MusicBox mb = new MusicBox(10, 10);
* mb.addNote(0, 1);
* mb.addNote(1, 0);
* mb.tick(); // play two given sounds at once
* Thread.sleep(1000) // wait 1 second
* mb.changeScale("Major");
* for (int i = 0; i < 8; i++) { // play C major scale (one sound every half a second)
* mb.addNode(i, 0);
* Thread.sleep(500);
* }
* }
* </pre>
*/
public class MusicBox {
/**
* Default value of a base pitch in MIDI number. (60 = C4)
*/
private static final int DEFAULT_BASE_PITCH = 55;
/**
* Minimal allowed base pitch value. (21 = A0, which is the lowest piano note)
*/
private static final int MIN_MIDI = 21;
/**
* Maximal allowed base pitch value. (84 = C6, which is two octaves below highest piano note)
*/
private static final int MAX_MIDI = 84;
/**
* Reverb<SUF>*/
public static final int REVERB_MAX = 2000;
public static final int REVERB_MIN = 25;
public static final int REVERB_DEFAULT = 200;
/**
* Number of available instruments excluding percussion.
*/
public static final int NUMBER_OF_INSTRUMENTS = 8; // wywalony obój
/**
* Sound producing module.
*/
private final SynthesizerWrapper player;
/**
* Current value of a scale.
*
* @see Scale
*/
private Scale currentScale = Scale.DEFAULT_SCALE;
/**
* Current value of a base pitch in MIDI number.
*/
private int basePitch = DEFAULT_BASE_PITCH;
/**
* Horizontal grid size (used in converting coordinates to pitch.
*/
private int sizeX;
/**
* Vertical grid size (used in converting coordinates to pitch.
*/
private int sizeY;
/**
* Notes added since last {@code tick()} call in MIDI number per instrument.
*/
private List<List<Integer>> currentTickInstruments = new ArrayList<>();
/**
* Percussion sounds added since last {@code tick()} call in range [0; max(sizeX - 3, sizeY - 3)].
*/
private List<Integer> currentTickPercussion = new ArrayList<>();
{
for (int i = 0; i < NUMBER_OF_INSTRUMENTS; i++) {
currentTickInstruments.add(new ArrayList<>());
}
}
/**
* @param x horizontal grid size.
* @param y vertical grid size.
* @throws MidiUnavailableException when it was impossible to init sound module.
*/
public MusicBox(int x, int y) throws MidiUnavailableException {
player = new JavaxSynthesizerWrapper();
this.sizeX = x;
this.sizeY = y;
}
/**
* Changes current scale by a String of display name.
*
* @param scaleDisplayName scale display name.
*/
public void changeScale(String scaleDisplayName) {
Scale newScale = Scale.reverseLookupByString(scaleDisplayName);
if (newScale == null) {
System.err.println("Couldn't find a scale of given name: " + scaleDisplayName);
} else {
currentScale = newScale;
}
}
/**
* Changes current scale by pointing to enumeration value.
*
* @param scale scale enumeration value.
*/
public void changeScale(Scale scale) {
if (scale == null) {
System.err.println("Pointed to a null value scale.");
} else {
currentScale = scale;
}
}
/**
* Changes grid size.
*
* @param x new horizontal size.
* @param y new vertical size.
*/
public void changeSize(int x, int y) {
this.sizeX = x;
this.sizeY = y;
}
/**
* Pitch setter.
*
* @param newPitch new pitch value in MIDI number.
*/
public void setPitch(int newPitch) {
if (newPitch < MIN_MIDI || newPitch > MAX_MIDI) {
System.err.println("new pitch not within expected range of [MIN_MIDI; MAX_MIDI] = [" + MIN_MIDI + "; " + MAX_MIDI + "].");
} else {
this.basePitch = newPitch;
}
}
/**
* Adds node in coordinates to play.
*
* @param x x coordinate.
* @param y y coordinate.
* @param instrument no. of instrument
* @see MusicBox for further explanation.
*/
public void addNote(int x, int y, int instrument) {
// if (instrument == 9) {
// addPercussion(x, y);
// } else {
currentTickInstruments.get(instrument).add(currentScale.scaleDegreeToRelativePitch(soundCoordinateToScaleDegree(x, y)) + basePitch);
// }
}
/**
* Adds node in coordinates to play.
*
* @param x x coordinate.
* @param y y coordinate.
* @see MusicBox for further explanation.
*/
@Deprecated
public void addNote(int x, int y) {
addNote(x, y, 0);
}
/**
* Adds percussion node in coordinates to play. As opposed to addNote, percussion notes are not changed by scale.
* Instead, they are passed to the synthesizer as in a range of [0, size - 3].
*
* @param x x coordinate.
* @param y y coordinate.
*/
public void addPercussion(int x, int y) {
currentTickPercussion.add(soundCoordinateToScaleDegree(x, y));
}
/**
* Plays all added notes.
*
* @see MusicBox for further explanation.
*/
public void tick() {
for (int i = 0; i < NUMBER_OF_INSTRUMENTS; i++) {
player.playNotes(currentTickInstruments.get(i), i);
}
player.playPercussionSounds(currentTickPercussion);
player.tick();
this.clearCurrentNotes();
}
public void setReverb(int ms) {
player.setReverb(ms);
}
public void setPreset(String presetName) {
player.setInstrumentPreset(presetName);
}
/**
* Clears all the currentTickNode subarrays. (Performed at each tick.)
*/
private void clearCurrentNotes() {
for (var currentTickInstrument : currentTickInstruments) {
currentTickInstrument.clear();
}
currentTickPercussion.clear();
}
/**
* Converts coordinates into a scale degree as follows:
* <pre>
* {@code
* +---------+-------+-------+-------+-------+-------+---------+---------+
* | | 0 | 1 | 2 | 3 | ... | sizeX-3 | |
* +---------+-------+-------+-------+-------+-------+---------+---------+
* | sizeY-3 | | | | | | | sizeY-3 |
* +---------+-------+-------+-------+-------+-------+---------+---------+
* | : | | | | | | | : |
* +---------+-------+-------+-------+-------+-------+---------+---------+
* | 3 | | | | | | | 3 |
* +---------+-------+-------+-------+-------+-------+---------+---------+
* | 2 | | | | | | | 2 |
* +---------+-------+-------+-------+-------+-------+---------+---------+
* | 1 | | | | | | | 1 |
* +---------+-------+-------+-------+-------+-------+---------+---------+
* | 0 | | | | | | | 0 |
* +---------+-------+-------+-------+-------+-------+---------+---------+
* | | 0 | 1 | 2 | 3 | ... | sizeX-3 | |
* +---------+-------+-------+-------+-------+-------+---------+---------+
* }
* </pre>
*
* @param x x coordinate
* @param y y coordinate
* @return scale degree as explained above
*/
private int soundCoordinateToScaleDegree(int x, int y) {
if (x == 0 || x == this.sizeX - 1) {
return this.sizeY - y - 2;
} else {
if (y != 0 && y != this.sizeY - 1) {
System.err.println("MusicBox.soundCoordinateToScaleDegree: received coordinates not on border: assuming y = 0.");
}
return x - 1;
}
}
}
|
21672_22 | /*
JAK TO DODAĆ:
> IntelliJ
> włączyć Klasę Swapper
> Ctrl + T -> Create New Tests
> Testing Library -> JUnit4 (zainstallować jeżeli trzeba)
> Wkleić to do nowego pliku
> Jeżeli coś się podświetla na czerwono, to dodać JUnit4 do Classpath (na przykład jak się już wklei, to najechać na
>>import static org.junit.Assert.*;<< -> kliknąć -> Alt+Enter -> Wybrać Add to Classpath
***ENJOY***
*/
package swapperTests;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import swapper.Swapper;
import java.util.*;
//import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
//import java.util.concurrent.CyclicBarrier;
import static org.junit.Assert.*;
public class SwapperTest {
private Swapper<Integer> swapper;
private List<Integer> emptySet = Collections.emptyList();
@Before
public void setUp() {
swapper = new Swapper<>();
}
@Rule
public final ExpectedException exception = ExpectedException.none();
private List<Integer> getAndSort(Swapper swapper) {
List<Integer> l = new ArrayList<>(swapper.getValueSet());
Collections.sort(l);
return l;
}
@Test
public void emptyArguments() throws InterruptedException {
swapper.swap(Collections.emptySortedSet(), Collections.emptyList());
assertEquals(Collections.emptyList(), getAndSort(swapper));
}
@Test
public void babySteps() throws InterruptedException {
swapper.swap(emptySet, Collections.singletonList(1));
assertEquals(Collections.singletonList(1), getAndSort(swapper));
}
@Test
public void babySteps2() throws InterruptedException {
swapper.swap(emptySet, Collections.singletonList(1));
assertEquals(Collections.singletonList(1), getAndSort(swapper));
swapper.swap(Collections.singletonList(1), emptySet);
assertEquals(emptySet, getAndSort(swapper));
}
@Test
public void add() throws InterruptedException {
swapper.swap(emptySet, Collections.singleton(1));
assertEquals(Collections.singletonList(1), getAndSort(swapper));
swapper.swap(emptySet, Arrays.asList(29, 42, 76));
assertEquals(Arrays.asList(1, 29, 42, 76), getAndSort(swapper));
swapper.swap(emptySet, Collections.singleton(29));
assertEquals(Arrays.asList(1, 29, 42, 76), getAndSort(swapper));
swapper.swap(emptySet, Arrays.asList(76, 28, 42, 1, 28, 29, 42, 76));
assertEquals(Arrays.asList(1, 28, 29, 42, 76), getAndSort(swapper));
swapper.swap(emptySet, Arrays.asList(666, 666, 666, 666, 666, 666, 666, 666, 666));
assertEquals(Arrays.asList(1, 28, 29, 42, 76, 666), getAndSort(swapper));
}
@Test
public void addRemove() throws InterruptedException {
swapper.swap(emptySet, Set.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
assertEquals(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), getAndSort(swapper));
swapper.swap(Arrays.asList(2), emptySet);
assertEquals(Arrays.asList(1, 3, 4, 5, 6, 7, 8, 9, 10), getAndSort(swapper));
swapper.swap(Arrays.asList(1, 3, 5), emptySet);
assertEquals(Arrays.asList(4, 6, 7, 8, 9, 10), getAndSort(swapper));
swapper.swap(Arrays.asList(7, 8, 9, 10), Arrays.asList(7, 8, 9, 10));
assertEquals(Arrays.asList(4, 6, 7, 8, 9, 10), getAndSort(swapper));
}
@Test
public void removeNonExistent() throws InterruptedException {
Thread remThr = new Thread(() -> {
try {
swapper.swap(Collections.singleton(1), emptySet);
exception.expect(InterruptedException.class);
} catch (InterruptedException e) {}
});
remThr.start();
Thread.sleep(1000);
remThr.interrupt();
}
private class Swaping implements Runnable {
private final Collection<Integer> add;
private final Collection<Integer> rem;
private final CountDownLatch latch;
private final int n;
public Swaping(Collection<Integer> rem, Collection<Integer> add, CountDownLatch latch, int n) {
this.add = add;
this.rem = rem;
this.latch = latch;
this.n = n;
}
@Override
public void run() {
try {
for (int i = 0; i < n; i++) {
swapper.swap(rem, add);
}
latch.countDown();
} catch (InterruptedException e) {
fail();
}
}
}
@Test
public void twoThousandTimes() throws InterruptedException {
final int TEST_REPEATS = 100;
final int THREAD_REPEATS = 1000;
CountDownLatch latch;
swapper.swap(emptySet, Collections.singleton(1));
for(int i = 0; i < TEST_REPEATS; i++) {
latch = new CountDownLatch(2);
Thread t1 = new Thread(new Swaping(Collections.singleton(1), Collections.singleton(2), latch, THREAD_REPEATS));
Thread t2 = new Thread(new Swaping(Collections.singleton(2), Collections.singleton(1), latch, THREAD_REPEATS));
t1.start();
t2.start();
latch.await(10, TimeUnit.SECONDS);
Thread.sleep(50);
if (t1.isAlive() || t2.isAlive()) {
fail("Took too long");
}
assertEquals(Collections.singletonList(1), getAndSort(swapper));
}
}
@Test
public void twoThousandThreads() throws InterruptedException {
final int TEST_REPEATS = 1;
final int THREADS = 100; // NEEDS TO BE EVEN
CountDownLatch latch;
swapper.swap(emptySet, Collections.singleton(1));
for (int i = 0; i < TEST_REPEATS; i++) {
latch = new CountDownLatch(THREADS);
for(int j = 0; j < THREADS / 2; j++) {
Thread t1 = new Thread(new Swaping(Collections.singleton(1), Collections.singleton(2), latch, 1));
Thread t2 = new Thread(new Swaping(Collections.singleton(2), Collections.singleton(1), latch, 1));
t1.start();
// t1.interrupt();
t2.start();
}
latch.await();
assertEquals(Collections.singletonList(1), getAndSort(swapper));
}
}
@Test
public void twoThousandThreads2() throws InterruptedException {
final int TEST_REPEATS = 1;
final int THREADS = 100;
CountDownLatch latch;
swapper.swap(emptySet, Collections.singleton(0));
for (int i = 0; i < TEST_REPEATS; i++) {
latch = new CountDownLatch(THREADS);
for(int j = 0; j < THREADS; j++) {
Thread t = new Thread(new Swaping(Collections.singleton(j), Collections.singleton(j + 1), latch, 1));
t.start();
}
latch.await();
assertEquals(Collections.singletonList(THREADS), getAndSort(swapper));
swapper.swap(Collections.singletonList(THREADS), Collections.singletonList(0));
}
}
// private class SwapingCascade implements Runnable{
//
// private final Collection<Integer> add;
// private final Collection<Integer> rem;
// private final CyclicBarrier barrier;
// private final int n;
//
// public SwapingCascade(Collection<Integer> add, Collection<Integer> rem, CyclicBarrier barrier, int n) {
// this.add = add;
// this.rem = rem;
// this.barrier = barrier;
// this.n = n;
// }
//
// @Override
// public void run() {
// try {
// for (int i = 0; i < n; i++) {
// barrier.await();
// swapper.swap(rem, add);
// }
// } catch (InterruptedException | BrokenBarrierException e) {
// fail();
// }
// }
// }
// tu coś nie działa, ale może wymyśli się
// @Test
// public void cascadingThreads() throws InterruptedException {
// final int TEST_REPEATS = 1;
// final int THREADS = 2000; // NEEDS TO BE EVEN
//
// CountDownLatch latch = new CountDownLatch(TEST_REPEATS);
// CyclicBarrier barrier = new CyclicBarrier(THREADS, () -> {
// assertEquals(Collections.emptyList(), getAndSort(swapper));
// latch.countDown();
// });
//
// for (int i = 0; i < THREADS / 2; i++) {
// Thread t1 = new Thread(new SwapingCascade(Collections.singleton(i), emptySet, barrier, TEST_REPEATS));
// Thread t2 = new Thread(new SwapingCascade(emptySet, Collections.singleton(i), barrier, TEST_REPEATS));
// t1.start();
// t2.start();
// }
// latch.await();
// }
// @Test
// public void () throws InterruptedException {
// }
} | zofja/swapper | src/swapperTests/SwapperTest.java | 2,968 | // tu coś nie działa, ale może wymyśli się | line_comment | pl | /*
JAK TO DODAĆ:
> IntelliJ
> włączyć Klasę Swapper
> Ctrl + T -> Create New Tests
> Testing Library -> JUnit4 (zainstallować jeżeli trzeba)
> Wkleić to do nowego pliku
> Jeżeli coś się podświetla na czerwono, to dodać JUnit4 do Classpath (na przykład jak się już wklei, to najechać na
>>import static org.junit.Assert.*;<< -> kliknąć -> Alt+Enter -> Wybrać Add to Classpath
***ENJOY***
*/
package swapperTests;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import swapper.Swapper;
import java.util.*;
//import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
//import java.util.concurrent.CyclicBarrier;
import static org.junit.Assert.*;
public class SwapperTest {
private Swapper<Integer> swapper;
private List<Integer> emptySet = Collections.emptyList();
@Before
public void setUp() {
swapper = new Swapper<>();
}
@Rule
public final ExpectedException exception = ExpectedException.none();
private List<Integer> getAndSort(Swapper swapper) {
List<Integer> l = new ArrayList<>(swapper.getValueSet());
Collections.sort(l);
return l;
}
@Test
public void emptyArguments() throws InterruptedException {
swapper.swap(Collections.emptySortedSet(), Collections.emptyList());
assertEquals(Collections.emptyList(), getAndSort(swapper));
}
@Test
public void babySteps() throws InterruptedException {
swapper.swap(emptySet, Collections.singletonList(1));
assertEquals(Collections.singletonList(1), getAndSort(swapper));
}
@Test
public void babySteps2() throws InterruptedException {
swapper.swap(emptySet, Collections.singletonList(1));
assertEquals(Collections.singletonList(1), getAndSort(swapper));
swapper.swap(Collections.singletonList(1), emptySet);
assertEquals(emptySet, getAndSort(swapper));
}
@Test
public void add() throws InterruptedException {
swapper.swap(emptySet, Collections.singleton(1));
assertEquals(Collections.singletonList(1), getAndSort(swapper));
swapper.swap(emptySet, Arrays.asList(29, 42, 76));
assertEquals(Arrays.asList(1, 29, 42, 76), getAndSort(swapper));
swapper.swap(emptySet, Collections.singleton(29));
assertEquals(Arrays.asList(1, 29, 42, 76), getAndSort(swapper));
swapper.swap(emptySet, Arrays.asList(76, 28, 42, 1, 28, 29, 42, 76));
assertEquals(Arrays.asList(1, 28, 29, 42, 76), getAndSort(swapper));
swapper.swap(emptySet, Arrays.asList(666, 666, 666, 666, 666, 666, 666, 666, 666));
assertEquals(Arrays.asList(1, 28, 29, 42, 76, 666), getAndSort(swapper));
}
@Test
public void addRemove() throws InterruptedException {
swapper.swap(emptySet, Set.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
assertEquals(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), getAndSort(swapper));
swapper.swap(Arrays.asList(2), emptySet);
assertEquals(Arrays.asList(1, 3, 4, 5, 6, 7, 8, 9, 10), getAndSort(swapper));
swapper.swap(Arrays.asList(1, 3, 5), emptySet);
assertEquals(Arrays.asList(4, 6, 7, 8, 9, 10), getAndSort(swapper));
swapper.swap(Arrays.asList(7, 8, 9, 10), Arrays.asList(7, 8, 9, 10));
assertEquals(Arrays.asList(4, 6, 7, 8, 9, 10), getAndSort(swapper));
}
@Test
public void removeNonExistent() throws InterruptedException {
Thread remThr = new Thread(() -> {
try {
swapper.swap(Collections.singleton(1), emptySet);
exception.expect(InterruptedException.class);
} catch (InterruptedException e) {}
});
remThr.start();
Thread.sleep(1000);
remThr.interrupt();
}
private class Swaping implements Runnable {
private final Collection<Integer> add;
private final Collection<Integer> rem;
private final CountDownLatch latch;
private final int n;
public Swaping(Collection<Integer> rem, Collection<Integer> add, CountDownLatch latch, int n) {
this.add = add;
this.rem = rem;
this.latch = latch;
this.n = n;
}
@Override
public void run() {
try {
for (int i = 0; i < n; i++) {
swapper.swap(rem, add);
}
latch.countDown();
} catch (InterruptedException e) {
fail();
}
}
}
@Test
public void twoThousandTimes() throws InterruptedException {
final int TEST_REPEATS = 100;
final int THREAD_REPEATS = 1000;
CountDownLatch latch;
swapper.swap(emptySet, Collections.singleton(1));
for(int i = 0; i < TEST_REPEATS; i++) {
latch = new CountDownLatch(2);
Thread t1 = new Thread(new Swaping(Collections.singleton(1), Collections.singleton(2), latch, THREAD_REPEATS));
Thread t2 = new Thread(new Swaping(Collections.singleton(2), Collections.singleton(1), latch, THREAD_REPEATS));
t1.start();
t2.start();
latch.await(10, TimeUnit.SECONDS);
Thread.sleep(50);
if (t1.isAlive() || t2.isAlive()) {
fail("Took too long");
}
assertEquals(Collections.singletonList(1), getAndSort(swapper));
}
}
@Test
public void twoThousandThreads() throws InterruptedException {
final int TEST_REPEATS = 1;
final int THREADS = 100; // NEEDS TO BE EVEN
CountDownLatch latch;
swapper.swap(emptySet, Collections.singleton(1));
for (int i = 0; i < TEST_REPEATS; i++) {
latch = new CountDownLatch(THREADS);
for(int j = 0; j < THREADS / 2; j++) {
Thread t1 = new Thread(new Swaping(Collections.singleton(1), Collections.singleton(2), latch, 1));
Thread t2 = new Thread(new Swaping(Collections.singleton(2), Collections.singleton(1), latch, 1));
t1.start();
// t1.interrupt();
t2.start();
}
latch.await();
assertEquals(Collections.singletonList(1), getAndSort(swapper));
}
}
@Test
public void twoThousandThreads2() throws InterruptedException {
final int TEST_REPEATS = 1;
final int THREADS = 100;
CountDownLatch latch;
swapper.swap(emptySet, Collections.singleton(0));
for (int i = 0; i < TEST_REPEATS; i++) {
latch = new CountDownLatch(THREADS);
for(int j = 0; j < THREADS; j++) {
Thread t = new Thread(new Swaping(Collections.singleton(j), Collections.singleton(j + 1), latch, 1));
t.start();
}
latch.await();
assertEquals(Collections.singletonList(THREADS), getAndSort(swapper));
swapper.swap(Collections.singletonList(THREADS), Collections.singletonList(0));
}
}
// private class SwapingCascade implements Runnable{
//
// private final Collection<Integer> add;
// private final Collection<Integer> rem;
// private final CyclicBarrier barrier;
// private final int n;
//
// public SwapingCascade(Collection<Integer> add, Collection<Integer> rem, CyclicBarrier barrier, int n) {
// this.add = add;
// this.rem = rem;
// this.barrier = barrier;
// this.n = n;
// }
//
// @Override
// public void run() {
// try {
// for (int i = 0; i < n; i++) {
// barrier.await();
// swapper.swap(rem, add);
// }
// } catch (InterruptedException | BrokenBarrierException e) {
// fail();
// }
// }
// }
// tu co<SUF>
// @Test
// public void cascadingThreads() throws InterruptedException {
// final int TEST_REPEATS = 1;
// final int THREADS = 2000; // NEEDS TO BE EVEN
//
// CountDownLatch latch = new CountDownLatch(TEST_REPEATS);
// CyclicBarrier barrier = new CyclicBarrier(THREADS, () -> {
// assertEquals(Collections.emptyList(), getAndSort(swapper));
// latch.countDown();
// });
//
// for (int i = 0; i < THREADS / 2; i++) {
// Thread t1 = new Thread(new SwapingCascade(Collections.singleton(i), emptySet, barrier, TEST_REPEATS));
// Thread t2 = new Thread(new SwapingCascade(emptySet, Collections.singleton(i), barrier, TEST_REPEATS));
// t1.start();
// t2.start();
// }
// latch.await();
// }
// @Test
// public void () throws InterruptedException {
// }
} |
17467_1 | package tigase.xmpp.impl;
import java.util.Map;
import java.util.Queue;
import java.util.logging.Level;
import java.util.logging.Logger;
import tigase.db.NonAuthUserRepository;
import tigase.db.TigaseDBException;
import tigase.db.UserNotFoundException;
import tigase.server.Packet;
import tigase.xml.Element;
import tigase.xmpp.Authorization;
import tigase.xmpp.BareJID;
import tigase.xmpp.JID;
import tigase.xmpp.NotAuthorizedException;
import tigase.xmpp.PacketErrorTypeException;
import tigase.xmpp.StanzaType;
import tigase.xmpp.XMPPException;
import tigase.xmpp.XMPPProcessorAbstract;
import tigase.xmpp.XMPPResourceConnection;
import tigase.xmpp.XMPPStopListenerIfc;
/**
* Implementation of <a
* href='http://xmpp.org/extensions/xep-0012.html'>XEP-0012</a>: Last Activity.
*
* @author bmalkow
*
*/
public abstract class LastActivity extends XMPPProcessorAbstract implements XMPPStopListenerIfc {
private static final Element[] DISCO_FEATURES = { new Element("feature", new String[] { "var" },
new String[] { "jabber:iq:last" }) };
private static final String[] ELEMENTS = { "query", "presence", "message" };
private final static String ID = "jabber:iq:last";
private final static String LAST_ACTIVITY_KEY = "LAST_ACTIVITY_KEY";
private static final Logger log = Logger.getLogger(LastActivity.class.getName());
private final static String[] XMLNS = new String[] { "jabber:iq:last", "jabber:client", "jabber:client" };
private static final long getTime(NonAuthUserRepository repo, BareJID requestedJid) throws UserNotFoundException {
String data = repo.getPublicData(requestedJid, ID, LAST_ACTIVITY_KEY, null);
if (data == null)
return -1;
try {
return Long.parseLong(data);
} catch (Exception e) {
return -1;
}
}
private static final long getTime(XMPPResourceConnection session) {
final Long last = (Long) session.getSessionData(LAST_ACTIVITY_KEY);
return last == null ? -1 : last.longValue();
}
@Override
public String id() {
return ID;
}
@Override
public void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results,
Map<String, Object> settings) throws XMPPException {
if (packet.getElemName() != "iq" && session != null && session.getBareJID().equals(packet.getStanzaFrom().getBareJID())) {
final long time = System.currentTimeMillis();
if (log.isLoggable(Level.FINEST))
log.finest("Updating last:activity of user " + session.getUserName() + " to " + time);
session.putSessionData(LAST_ACTIVITY_KEY, time);
}
super.process(packet, session, repo, results, settings);
}
/*
* User odpytuje sam siebie
*/
@Override
public void processFromUserToServerPacket(JID connectionId, Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings) throws PacketErrorTypeException {
if (packet.getType() == StanzaType.get) {
long last = getTime(session);
Packet resp = packet.okResult((Element) null, 0);
if (last != -1) {
long result = (System.currentTimeMillis() - last) / 1000;
Element q = new Element("query", new String[] { "xmlns", "seconds" }, new String[] { "jabber:iq:last",
"" + result });
resp.getElement().addChild(q);
results.offer(resp);
} else {
results.offer(Authorization.ITEM_NOT_FOUND.getResponseMessage(packet, "Unknown last activity time", true));
}
} else
results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Message type is incorrect", true));
}
/*
* User docelowy jest offline
*/
@Override
public void processNullSessionPacket(Packet packet, NonAuthUserRepository repo, Queue<Packet> results,
Map<String, Object> settings) throws PacketErrorTypeException {
if (packet.getType() == StanzaType.get) {
try {
BareJID requestedJid = packet.getStanzaTo().getBareJID();
final long last = getTime(repo, requestedJid);
if (log.isLoggable(Level.FINEST))
log.finest("Get last:activity of offline user " + requestedJid + ". value=" + last);
if (last != -1) {
long result = (System.currentTimeMillis() - last) / 1000;
Packet resp = packet.okResult((Element) null, 0);
Element q = new Element("query", new String[] { "xmlns", "seconds" }, new String[] { "jabber:iq:last",
"" + result });
resp.getElement().addChild(q);
results.offer(resp);
} else {
results.offer(Authorization.ITEM_NOT_FOUND.getResponseMessage(packet, "Unknown last activity time", true));
}
} catch (UserNotFoundException e) {
results.offer(Authorization.ITEM_NOT_FOUND.getResponseMessage(packet, "User not found", true));
}
} else if (packet.getType() == StanzaType.set)
results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Message type is incorrect", true));
else
super.processNullSessionPacket(packet, repo, results, settings);
}
@Override
public void processServerSessionPacket(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo,
Queue<Packet> results, Map<String, Object> settings) throws PacketErrorTypeException {
}
/*
* User docelowy jest podłączony
*/
@Override
public void processToUserPacket(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo,
Queue<Packet> results, Map<String, Object> settings) throws PacketErrorTypeException {
if (packet.getType() == StanzaType.get) {
long last = getTime(session);
if (last != -1) {
long result = (System.currentTimeMillis() - last) / 1000;
Packet resp = packet.okResult((Element) null, 0);
Element q = new Element("query", new String[] { "xmlns", "seconds" }, new String[] { "jabber:iq:last",
"" + result });
resp.getElement().addChild(q);
results.offer(resp);
} else {
results.offer(Authorization.ITEM_NOT_FOUND.getResponseMessage(packet, "Unknown last activity time", true));
}
} else if (packet.getType() == StanzaType.set)
results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Message type is incorrect", true));
else
super.processToUserPacket(packet, session, repo, results, settings);
}
@Override
public void stopped(XMPPResourceConnection session, Queue<Packet> results, Map<String, Object> settings) {
if (session != null) {
long last = getTime(session);
try {
if (log.isLoggable(Level.FINEST))
log.finest("Persiting last:activity of user " + session.getUserName() + " in storage (value=" + last + ").");
session.setPublicData(ID, LAST_ACTIVITY_KEY, String.valueOf(last));
} catch (NotAuthorizedException e) {
e.printStackTrace();
} catch (TigaseDBException e) {
e.printStackTrace();
}
}
}
@Override
public Element[] supDiscoFeatures(XMPPResourceConnection session) {
return DISCO_FEATURES;
}
@Override
public String[] supElements() {
return ELEMENTS;
}
@Override
public String[] supNamespaces() {
return XMLNS;
}
}
| zooldk/tigase-server | src/main/java/tigase/xmpp/impl/LastActivity.java | 2,517 | /*
* User odpytuje sam siebie
*/ | block_comment | pl | package tigase.xmpp.impl;
import java.util.Map;
import java.util.Queue;
import java.util.logging.Level;
import java.util.logging.Logger;
import tigase.db.NonAuthUserRepository;
import tigase.db.TigaseDBException;
import tigase.db.UserNotFoundException;
import tigase.server.Packet;
import tigase.xml.Element;
import tigase.xmpp.Authorization;
import tigase.xmpp.BareJID;
import tigase.xmpp.JID;
import tigase.xmpp.NotAuthorizedException;
import tigase.xmpp.PacketErrorTypeException;
import tigase.xmpp.StanzaType;
import tigase.xmpp.XMPPException;
import tigase.xmpp.XMPPProcessorAbstract;
import tigase.xmpp.XMPPResourceConnection;
import tigase.xmpp.XMPPStopListenerIfc;
/**
* Implementation of <a
* href='http://xmpp.org/extensions/xep-0012.html'>XEP-0012</a>: Last Activity.
*
* @author bmalkow
*
*/
public abstract class LastActivity extends XMPPProcessorAbstract implements XMPPStopListenerIfc {
private static final Element[] DISCO_FEATURES = { new Element("feature", new String[] { "var" },
new String[] { "jabber:iq:last" }) };
private static final String[] ELEMENTS = { "query", "presence", "message" };
private final static String ID = "jabber:iq:last";
private final static String LAST_ACTIVITY_KEY = "LAST_ACTIVITY_KEY";
private static final Logger log = Logger.getLogger(LastActivity.class.getName());
private final static String[] XMLNS = new String[] { "jabber:iq:last", "jabber:client", "jabber:client" };
private static final long getTime(NonAuthUserRepository repo, BareJID requestedJid) throws UserNotFoundException {
String data = repo.getPublicData(requestedJid, ID, LAST_ACTIVITY_KEY, null);
if (data == null)
return -1;
try {
return Long.parseLong(data);
} catch (Exception e) {
return -1;
}
}
private static final long getTime(XMPPResourceConnection session) {
final Long last = (Long) session.getSessionData(LAST_ACTIVITY_KEY);
return last == null ? -1 : last.longValue();
}
@Override
public String id() {
return ID;
}
@Override
public void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results,
Map<String, Object> settings) throws XMPPException {
if (packet.getElemName() != "iq" && session != null && session.getBareJID().equals(packet.getStanzaFrom().getBareJID())) {
final long time = System.currentTimeMillis();
if (log.isLoggable(Level.FINEST))
log.finest("Updating last:activity of user " + session.getUserName() + " to " + time);
session.putSessionData(LAST_ACTIVITY_KEY, time);
}
super.process(packet, session, repo, results, settings);
}
/*
* User o<SUF>*/
@Override
public void processFromUserToServerPacket(JID connectionId, Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings) throws PacketErrorTypeException {
if (packet.getType() == StanzaType.get) {
long last = getTime(session);
Packet resp = packet.okResult((Element) null, 0);
if (last != -1) {
long result = (System.currentTimeMillis() - last) / 1000;
Element q = new Element("query", new String[] { "xmlns", "seconds" }, new String[] { "jabber:iq:last",
"" + result });
resp.getElement().addChild(q);
results.offer(resp);
} else {
results.offer(Authorization.ITEM_NOT_FOUND.getResponseMessage(packet, "Unknown last activity time", true));
}
} else
results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Message type is incorrect", true));
}
/*
* User docelowy jest offline
*/
@Override
public void processNullSessionPacket(Packet packet, NonAuthUserRepository repo, Queue<Packet> results,
Map<String, Object> settings) throws PacketErrorTypeException {
if (packet.getType() == StanzaType.get) {
try {
BareJID requestedJid = packet.getStanzaTo().getBareJID();
final long last = getTime(repo, requestedJid);
if (log.isLoggable(Level.FINEST))
log.finest("Get last:activity of offline user " + requestedJid + ". value=" + last);
if (last != -1) {
long result = (System.currentTimeMillis() - last) / 1000;
Packet resp = packet.okResult((Element) null, 0);
Element q = new Element("query", new String[] { "xmlns", "seconds" }, new String[] { "jabber:iq:last",
"" + result });
resp.getElement().addChild(q);
results.offer(resp);
} else {
results.offer(Authorization.ITEM_NOT_FOUND.getResponseMessage(packet, "Unknown last activity time", true));
}
} catch (UserNotFoundException e) {
results.offer(Authorization.ITEM_NOT_FOUND.getResponseMessage(packet, "User not found", true));
}
} else if (packet.getType() == StanzaType.set)
results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Message type is incorrect", true));
else
super.processNullSessionPacket(packet, repo, results, settings);
}
@Override
public void processServerSessionPacket(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo,
Queue<Packet> results, Map<String, Object> settings) throws PacketErrorTypeException {
}
/*
* User docelowy jest podłączony
*/
@Override
public void processToUserPacket(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo,
Queue<Packet> results, Map<String, Object> settings) throws PacketErrorTypeException {
if (packet.getType() == StanzaType.get) {
long last = getTime(session);
if (last != -1) {
long result = (System.currentTimeMillis() - last) / 1000;
Packet resp = packet.okResult((Element) null, 0);
Element q = new Element("query", new String[] { "xmlns", "seconds" }, new String[] { "jabber:iq:last",
"" + result });
resp.getElement().addChild(q);
results.offer(resp);
} else {
results.offer(Authorization.ITEM_NOT_FOUND.getResponseMessage(packet, "Unknown last activity time", true));
}
} else if (packet.getType() == StanzaType.set)
results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Message type is incorrect", true));
else
super.processToUserPacket(packet, session, repo, results, settings);
}
@Override
public void stopped(XMPPResourceConnection session, Queue<Packet> results, Map<String, Object> settings) {
if (session != null) {
long last = getTime(session);
try {
if (log.isLoggable(Level.FINEST))
log.finest("Persiting last:activity of user " + session.getUserName() + " in storage (value=" + last + ").");
session.setPublicData(ID, LAST_ACTIVITY_KEY, String.valueOf(last));
} catch (NotAuthorizedException e) {
e.printStackTrace();
} catch (TigaseDBException e) {
e.printStackTrace();
}
}
}
@Override
public Element[] supDiscoFeatures(XMPPResourceConnection session) {
return DISCO_FEATURES;
}
@Override
public String[] supElements() {
return ELEMENTS;
}
@Override
public String[] supNamespaces() {
return XMLNS;
}
}
|
11192_6 | /*
Witaj świecie!
Rytuał zakończony, bogowie zaspokojeni, ale pytania pozostały.
Pomimo faktu, że wykonujemy bardzo prostą operację wyświetlenia napisu na ekranie,
tak naprawę bardzo wiele się dzieje. I przez dużą część społęczności programistycznej jest to uważan
za dużą wadę Java (tak zwany bloat).
Dla porówniania, dla wygląda ten sam kod w języku Rust:
fn main() {
print!("Hello World!)
}
Czyli trzy linijki czystej magii! W Javie wszystko jest jednak obiektem, więc aby uruchomić program to też najpierw
trzeba zadeklarować jakąś klasę.
Teraz przejdziemy krok po kroku po naszym kodzie.
*/
package net.zorawski.basics;
// Słowo kluczowe package, wskazuje na to do jakiego pakietu należy dana klasa. O pakietach możesz myśleć jak
// o katalogach grupujących klasy. Także ta klas znajduje się w katalogu net\zorawski\basics.
// W przypadku twojego pierwszego programu może się okazać, że nie ma słówka package. Oznacza to, że klasa jest
// w pakiecie domyślnym. Taka sytuacja występuje jedynie w bardzo prostych programach.
// O pakietach opowiemy sobie przy innej okazji. Na razie niech nie przeszkadzają!
/*
Poniżej znajduje się deklaracja klasy publicznej HelloWorld. I od razu wpadamy w tarapaty bo sporo się tu dzieje.
Q: Co to jest klasa publiczna?
A: Jest to klasa, która jest dostępna w całej aplikacji.
- Nazwa klasy i nazwa pliku musi się zgadzać.
- Może być wiele klas w jednym pliku, ale dopuszczalna jest tylko jedna klasa publiczna.
- Plik .java nie musi posiadać klasy publicznej.
Q: Jak się deklaruje klasę?
A: Syngatura deklaracji wygląda w ten sposób:
<kwantyfikator dostępu> class <nazwa klasy> {
O dostępie pogadamy sobie przy innej okazji.
Jeżeli chodzi o nazwy klasy to przyjęło się w Java, że nazwy klas:
- to rzeczowniki,
- pisane są wielką literą
- używany jest camel case
Przykład pisowni CamelCase: HelloWorldController
Przykład pisowni kebab-case: hello-world-controller
Przykład pisowni snake-case: hello_world_controller
Q: Czym jest klasa?
A: O tym szerzej powiemy trochę później. Na teraz powinnaś wiedzieć, że klasa określa typ (np. Person) a instancją klasy
jest obiekt (np. "Artur" lub "Asia").
*/
public class HelloWorld {
/*
Poniżej znajduje się deklaracja specjalnej metody main. Metoda main, oznacza że klasa może być uruchomiona
jak program. Tutaj kilka uwag:
- Sygnatura metody jest zawsze taka sama: public static void main(String[] args)
- Różne klasy mogą mieć różne metody main. Także twój program może działać inaczej, w zależności od tego
która klasa zostanie wywołana.
Teraz spójrzmy na wszystkie słowa w tej linijce:
public - oznacza, że metoda jest publiczna i każdy może ją wywołać
static - deklaruje metodę statyczną. Oznacza to, że metodę można wywołać bez tworzenia obiektu danej klasy.
void - jest to specjalne słowo kluczowe, oznaczające, że metoda nic nie zwraca. Jeżeli zamiast void widniałoby int
to kompilator oczdkiwałby, że metoda zwróci liczbę całkowitą
main - jest to nazwa metody. Metody w Java są pisane małą literą przy wykorzystaniu CamelCase (czyli np. findPerson()
String[] args - jest to tablica Stringów o nazwie "args". W świecie Javy stringi to nuda, więc nie ma się co
na ekscytować :/. W tym przypadku tablica args zawiera parametry przekazane do wywołania naszego programu.
*/
public static void main(String[] args) {
// A tutaj już sam kod odpowiedzlany za wydrukowanie tekstu na ekranie. Pewnie już zauważyłaś,
// że nie jest to takie proste?
// Najpierw wskazujemy klasę System. Następnie za pomocą operatora . (dot) dostajemy się do statycznego obiektu
// out. Out reprezentuje obiekt drukujący na standardowe wyjście. A na samym końcu wywołujemy metodę println.
// I voila! Tylko tyle trzeba, aby ożywić ekran. Jeżeli chciałabyś coś wypisać na standardowy błąd to mogłabyś
// użyć np. System.err.println("Hello Hell!");
System.out.println("Hello World!");
}
}
| zorawek/dev-journey | src/main/java/net/zorawski/basics/HelloWorld.java | 1,484 | /*
Poniżej znajduje się deklaracja klasy publicznej HelloWorld. I od razu wpadamy w tarapaty bo sporo się tu dzieje.
Q: Co to jest klasa publiczna?
A: Jest to klasa, która jest dostępna w całej aplikacji.
- Nazwa klasy i nazwa pliku musi się zgadzać.
- Może być wiele klas w jednym pliku, ale dopuszczalna jest tylko jedna klasa publiczna.
- Plik .java nie musi posiadać klasy publicznej.
Q: Jak się deklaruje klasę?
A: Syngatura deklaracji wygląda w ten sposób:
<kwantyfikator dostępu> class <nazwa klasy> {
O dostępie pogadamy sobie przy innej okazji.
Jeżeli chodzi o nazwy klasy to przyjęło się w Java, że nazwy klas:
- to rzeczowniki,
- pisane są wielką literą
- używany jest camel case
Przykład pisowni CamelCase: HelloWorldController
Przykład pisowni kebab-case: hello-world-controller
Przykład pisowni snake-case: hello_world_controller
Q: Czym jest klasa?
A: O tym szerzej powiemy trochę później. Na teraz powinnaś wiedzieć, że klasa określa typ (np. Person) a instancją klasy
jest obiekt (np. "Artur" lub "Asia").
*/ | block_comment | pl | /*
Witaj świecie!
Rytuał zakończony, bogowie zaspokojeni, ale pytania pozostały.
Pomimo faktu, że wykonujemy bardzo prostą operację wyświetlenia napisu na ekranie,
tak naprawę bardzo wiele się dzieje. I przez dużą część społęczności programistycznej jest to uważan
za dużą wadę Java (tak zwany bloat).
Dla porówniania, dla wygląda ten sam kod w języku Rust:
fn main() {
print!("Hello World!)
}
Czyli trzy linijki czystej magii! W Javie wszystko jest jednak obiektem, więc aby uruchomić program to też najpierw
trzeba zadeklarować jakąś klasę.
Teraz przejdziemy krok po kroku po naszym kodzie.
*/
package net.zorawski.basics;
// Słowo kluczowe package, wskazuje na to do jakiego pakietu należy dana klasa. O pakietach możesz myśleć jak
// o katalogach grupujących klasy. Także ta klas znajduje się w katalogu net\zorawski\basics.
// W przypadku twojego pierwszego programu może się okazać, że nie ma słówka package. Oznacza to, że klasa jest
// w pakiecie domyślnym. Taka sytuacja występuje jedynie w bardzo prostych programach.
// O pakietach opowiemy sobie przy innej okazji. Na razie niech nie przeszkadzają!
/*
Poniże<SUF>*/
public class HelloWorld {
/*
Poniżej znajduje się deklaracja specjalnej metody main. Metoda main, oznacza że klasa może być uruchomiona
jak program. Tutaj kilka uwag:
- Sygnatura metody jest zawsze taka sama: public static void main(String[] args)
- Różne klasy mogą mieć różne metody main. Także twój program może działać inaczej, w zależności od tego
która klasa zostanie wywołana.
Teraz spójrzmy na wszystkie słowa w tej linijce:
public - oznacza, że metoda jest publiczna i każdy może ją wywołać
static - deklaruje metodę statyczną. Oznacza to, że metodę można wywołać bez tworzenia obiektu danej klasy.
void - jest to specjalne słowo kluczowe, oznaczające, że metoda nic nie zwraca. Jeżeli zamiast void widniałoby int
to kompilator oczdkiwałby, że metoda zwróci liczbę całkowitą
main - jest to nazwa metody. Metody w Java są pisane małą literą przy wykorzystaniu CamelCase (czyli np. findPerson()
String[] args - jest to tablica Stringów o nazwie "args". W świecie Javy stringi to nuda, więc nie ma się co
na ekscytować :/. W tym przypadku tablica args zawiera parametry przekazane do wywołania naszego programu.
*/
public static void main(String[] args) {
// A tutaj już sam kod odpowiedzlany za wydrukowanie tekstu na ekranie. Pewnie już zauważyłaś,
// że nie jest to takie proste?
// Najpierw wskazujemy klasę System. Następnie za pomocą operatora . (dot) dostajemy się do statycznego obiektu
// out. Out reprezentuje obiekt drukujący na standardowe wyjście. A na samym końcu wywołujemy metodę println.
// I voila! Tylko tyle trzeba, aby ożywić ekran. Jeżeli chciałabyś coś wypisać na standardowy błąd to mogłabyś
// użyć np. System.err.println("Hello Hell!");
System.out.println("Hello World!");
}
}
|
52806_7 | package Kawalek_Ziemi;
import Obserwator.*;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.Timer;
public abstract class Kawalek_Ziemi implements Podmiot
{
private int x; // pierwsza współrzędna kawałka
private int y; // druga współrzędna kawałka
private Image ikonka = null;
private Image ikonkaPodstawowa = null;
//podmiot
private ArrayList<Obserwator> obserwatorzy;
//w naszym przypadku bedzie tylko jeden obserwator ale oficjalnie jest to zbior obserwatorow
public Kawalek_Ziemi(int x, int y)
{
this.x=x;
this.y=y;
this.obserwatorzy = new ArrayList<>();
this.obserwatorzy.clear();
this.obserwatorzy.add(new InformacjeProduktPole());
Timer timer2 = new Timer(100, (ActionListener) new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
powiadomObserwatorow();
InformacjeProduktPole obserwatorIkonkaPola = (InformacjeProduktPole) obserwatorzy.get(0);
if (obserwatorIkonkaPola.isCzyZagroda()) {
// wybieranie ikonki jesli pole jest zagroda
if (obserwatorIkonkaPola.getZwierze() == null) {
ikonka = ikonkaPodstawowa;
}
else if (obserwatorIkonkaPola.getZwierze() != null) {
ImageIcon icon;
if (obserwatorIkonkaPola.isCzyProdukuje() == false) {
icon = new ImageIcon(obserwatorIkonkaPola.getZwierze().getAdresIkonkiGlodne());
} else if (obserwatorIkonkaPola.isGotoweDoZebrania() == false) {
icon = new ImageIcon(obserwatorIkonkaPola.getZwierze().getAdresIkonkiJedzace());
} else {
icon = new ImageIcon(obserwatorIkonkaPola.getZwierze().getAdresIkonkigotowe());
}
ikonka = icon.getImage().getScaledInstance(74, 70, Image.SCALE_DEFAULT);
}
}
else if (obserwatorIkonkaPola.getNazwa().equals("")) {
// wybieranie ikonki jesli na polu nic nie jest produkowane
ikonka = ikonkaPodstawowa;
}
else if (obserwatorIkonkaPola.isGotoweDoZebrania() == false) {
// wybieranie ikonki jesli produkt jest w trakcie produkcji
ImageIcon icon;
if (obserwatorIkonkaPola.getNazwa().equals("pszenica") || obserwatorIkonkaPola.getNazwa().equals("żyto")) {
icon = new ImageIcon("grafika/zasianeZboze.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("jabłka") || obserwatorIkonkaPola.getNazwa().equals("gruszki")) {
icon = new ImageIcon("grafika/zasadzoneDrzewo.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("winogrona")) {
icon = new ImageIcon("grafika/zasadzonaWinorosl.png");
}
else {
icon = new ImageIcon("grafika/produkujacaPrzetwornia.png");
}
ikonka = icon.getImage().getScaledInstance(74, 70, Image.SCALE_DEFAULT);
}
else {
// wybieranie ikonki jesli produkt jest wyprodukowany
ImageIcon icon;
if (obserwatorIkonkaPola.getNazwa().equals("pszenica")) {
icon = new ImageIcon("grafika/gotowaPszenica.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("żyto")) {
icon = new ImageIcon("grafika/gotoweZyto.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("jabłka")) {
icon = new ImageIcon("grafika/gotowaJablon.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("gruszki")) {
icon = new ImageIcon("grafika/gotowaGrusza.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("winogrona")) {
icon = new ImageIcon("grafika/gotoweWinogrono.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("chleb pszenny")) {
icon = new ImageIcon("grafika/gotowyChlebPszenny.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("chleb żytni")) {
icon = new ImageIcon("grafika/gotowyChlebZytni.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("dżem jabłkowy")) {
icon = new ImageIcon("grafika/gotowyDzemJablkowy.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("dżem gruszkowy")) {
icon = new ImageIcon("grafika/gotowyDzemGruszkowy.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("sok jabłkowy")) {
icon = new ImageIcon("grafika/gotowySokJablkowy.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("sok gruszkowy")) {
icon = new ImageIcon("grafika/gotowySokGruszkowy.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("masło")) {
icon = new ImageIcon("grafika/gotoweMaslo.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("szynka")) {
icon = new ImageIcon("grafika/gotowaSzynka.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("kiełbasa")) {
icon = new ImageIcon("grafika/gotowaKielbasa.png");
}
else {
icon = new ImageIcon("grafika/pustePoleUprawne");
}
ikonka = icon.getImage().getScaledInstance(74, 70, Image.SCALE_DEFAULT);
}
}
});
// Uruchamiamy timer co 0.1 sekundy
timer2.start();
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public Image getIkonka() {
return ikonka;
}
public void setX(int x)
{
this.x=x;
}
public void setIkonka(Image ikonka)
{
this.ikonka=ikonka;
this.ikonkaPodstawowa=ikonka;
}
public void setY(int y)
{
this.y=y;
}
public void getStan()
{
System.out.println("Współrzędne punktu to: ("+getX()+","+getY()+")");
}
public ArrayList<Obserwator> getObserwatorzy() { return obserwatorzy; }
public void dodajObserwatora(Obserwator o)
{
obserwatorzy.add(o);
}
public void usunObserwatora(Obserwator o)
{
int i = obserwatorzy.indexOf(o);
if(i>=0)
obserwatorzy.remove(i);
}
public abstract void powiadomObserwatorow();
//bedzie zaimplementowana w kolejnych klasach (pole uprawne, zagroda, przetwornia)
}
| zosia-r/farma | src/Kawalek_Ziemi/Kawalek_Ziemi.java | 2,421 | // wybieranie ikonki jesli produkt jest wyprodukowany
| line_comment | pl | package Kawalek_Ziemi;
import Obserwator.*;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.Timer;
public abstract class Kawalek_Ziemi implements Podmiot
{
private int x; // pierwsza współrzędna kawałka
private int y; // druga współrzędna kawałka
private Image ikonka = null;
private Image ikonkaPodstawowa = null;
//podmiot
private ArrayList<Obserwator> obserwatorzy;
//w naszym przypadku bedzie tylko jeden obserwator ale oficjalnie jest to zbior obserwatorow
public Kawalek_Ziemi(int x, int y)
{
this.x=x;
this.y=y;
this.obserwatorzy = new ArrayList<>();
this.obserwatorzy.clear();
this.obserwatorzy.add(new InformacjeProduktPole());
Timer timer2 = new Timer(100, (ActionListener) new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
powiadomObserwatorow();
InformacjeProduktPole obserwatorIkonkaPola = (InformacjeProduktPole) obserwatorzy.get(0);
if (obserwatorIkonkaPola.isCzyZagroda()) {
// wybieranie ikonki jesli pole jest zagroda
if (obserwatorIkonkaPola.getZwierze() == null) {
ikonka = ikonkaPodstawowa;
}
else if (obserwatorIkonkaPola.getZwierze() != null) {
ImageIcon icon;
if (obserwatorIkonkaPola.isCzyProdukuje() == false) {
icon = new ImageIcon(obserwatorIkonkaPola.getZwierze().getAdresIkonkiGlodne());
} else if (obserwatorIkonkaPola.isGotoweDoZebrania() == false) {
icon = new ImageIcon(obserwatorIkonkaPola.getZwierze().getAdresIkonkiJedzace());
} else {
icon = new ImageIcon(obserwatorIkonkaPola.getZwierze().getAdresIkonkigotowe());
}
ikonka = icon.getImage().getScaledInstance(74, 70, Image.SCALE_DEFAULT);
}
}
else if (obserwatorIkonkaPola.getNazwa().equals("")) {
// wybieranie ikonki jesli na polu nic nie jest produkowane
ikonka = ikonkaPodstawowa;
}
else if (obserwatorIkonkaPola.isGotoweDoZebrania() == false) {
// wybieranie ikonki jesli produkt jest w trakcie produkcji
ImageIcon icon;
if (obserwatorIkonkaPola.getNazwa().equals("pszenica") || obserwatorIkonkaPola.getNazwa().equals("żyto")) {
icon = new ImageIcon("grafika/zasianeZboze.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("jabłka") || obserwatorIkonkaPola.getNazwa().equals("gruszki")) {
icon = new ImageIcon("grafika/zasadzoneDrzewo.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("winogrona")) {
icon = new ImageIcon("grafika/zasadzonaWinorosl.png");
}
else {
icon = new ImageIcon("grafika/produkujacaPrzetwornia.png");
}
ikonka = icon.getImage().getScaledInstance(74, 70, Image.SCALE_DEFAULT);
}
else {
// wybie<SUF>
ImageIcon icon;
if (obserwatorIkonkaPola.getNazwa().equals("pszenica")) {
icon = new ImageIcon("grafika/gotowaPszenica.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("żyto")) {
icon = new ImageIcon("grafika/gotoweZyto.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("jabłka")) {
icon = new ImageIcon("grafika/gotowaJablon.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("gruszki")) {
icon = new ImageIcon("grafika/gotowaGrusza.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("winogrona")) {
icon = new ImageIcon("grafika/gotoweWinogrono.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("chleb pszenny")) {
icon = new ImageIcon("grafika/gotowyChlebPszenny.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("chleb żytni")) {
icon = new ImageIcon("grafika/gotowyChlebZytni.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("dżem jabłkowy")) {
icon = new ImageIcon("grafika/gotowyDzemJablkowy.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("dżem gruszkowy")) {
icon = new ImageIcon("grafika/gotowyDzemGruszkowy.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("sok jabłkowy")) {
icon = new ImageIcon("grafika/gotowySokJablkowy.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("sok gruszkowy")) {
icon = new ImageIcon("grafika/gotowySokGruszkowy.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("masło")) {
icon = new ImageIcon("grafika/gotoweMaslo.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("szynka")) {
icon = new ImageIcon("grafika/gotowaSzynka.png");
} else if (obserwatorIkonkaPola.getNazwa().equals("kiełbasa")) {
icon = new ImageIcon("grafika/gotowaKielbasa.png");
}
else {
icon = new ImageIcon("grafika/pustePoleUprawne");
}
ikonka = icon.getImage().getScaledInstance(74, 70, Image.SCALE_DEFAULT);
}
}
});
// Uruchamiamy timer co 0.1 sekundy
timer2.start();
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public Image getIkonka() {
return ikonka;
}
public void setX(int x)
{
this.x=x;
}
public void setIkonka(Image ikonka)
{
this.ikonka=ikonka;
this.ikonkaPodstawowa=ikonka;
}
public void setY(int y)
{
this.y=y;
}
public void getStan()
{
System.out.println("Współrzędne punktu to: ("+getX()+","+getY()+")");
}
public ArrayList<Obserwator> getObserwatorzy() { return obserwatorzy; }
public void dodajObserwatora(Obserwator o)
{
obserwatorzy.add(o);
}
public void usunObserwatora(Obserwator o)
{
int i = obserwatorzy.indexOf(o);
if(i>=0)
obserwatorzy.remove(i);
}
public abstract void powiadomObserwatorow();
//bedzie zaimplementowana w kolejnych klasach (pole uprawne, zagroda, przetwornia)
}
|
3384_12 | import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
public class GuiTest extends JComponent{
private MyPanel contentPane;
private int x1,y1;
private Thread thread;
void displayGUI() {
// Generowanie obiektów do GUI
java.util.List<Rower> rowery = Test.genRower();
java.util.List<Stack<Rower>> stackList = Test.genStacks(rowery);
java.util.List<Stojak> stojakList = Test.genStojaki(stackList);
List<StacjaRowerowa> stacjaRowerowaList = Test.genStacjeRowerowe(stojakList);
SystemRowerowy systemRowerowy = new SystemRowerowy(new ArrayList<>(), stacjaRowerowaList);
Miasto miasto = new Miasto(systemRowerowy, "Lublin");
int[] lokalizacja = {22, 22};
Saldo saldo = new Saldo(10);
Uzytkownik user = new Uzytkownik(1, miasto, lokalizacja, saldo);
int x = 12, y = 222, szer = 150, wys = 90;
int vShift = 100; // vertical
Font czcionka = new Font("Courier", Font.BOLD, 50);
JFrame frame = new JFrame("System Rowerowy");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = new MyPanel();
contentPane.setPreferredSize(new Dimension(1024, 750));
// Napis Lublin
JLabel miastoNapis = new JLabel("Lublin");
miastoNapis.setBounds(480,29,300,50);
miastoNapis.setFont(czcionka);
// Przyciski pod Informacjami o użytkowniku
JButton buttonWypozyczRower = new JButton("Wypożycz rower");
JButton buttonOddajRower = new JButton("Oddaj rower");
JButton buttonNajblizszaStacja = new JButton("Najbliższa stacja");
JButton buttonKodObreczy = new JButton("Kod obręczy");
JButton buttonKontakt = new JButton("Kontakt");
// Położenie przycisków
buttonWypozyczRower.setBounds(x, y, szer, wys);
buttonOddajRower.setBounds(x, y+vShift, szer, wys);
buttonNajblizszaStacja.setBounds(x, y+2*vShift, szer, wys);
buttonKodObreczy.setBounds(x, y+3*vShift, szer, wys);
buttonKontakt.setBounds(x, y+4*vShift, szer, wys);
// GridLayouty
GridLayout gridLayoutInformacje = new GridLayout(4, 2); //GridLayout dla małego panelu informacji
GridLayout gridLayoutPrawyGorny = new GridLayout(2,2); //GridLayout dla prawego górnego rogu
gridLayoutInformacje.setVgap(15);
gridLayoutInformacje.setHgap(5);
gridLayoutPrawyGorny.setVgap(15);
gridLayoutPrawyGorny.setHgap(5);
// Panele i obramówki do paneli
JPanel panelMaly = new JPanel(gridLayoutInformacje);
JPanel panelPrawyGorny = new JPanel(gridLayoutPrawyGorny);
panelMaly.setBounds(x,0,szer,wys+110);
panelPrawyGorny.setBounds(x+816,0,szer,wys);
panelMaly.setBorder(BorderFactory.createTitledBorder("Informacje o użytk."));
panelPrawyGorny.setBorder(BorderFactory.createTitledBorder("Info"));
// Pola wyświetlania mały panel informacji
JTextPane rowerWyswietlanie = new JTextPane();
JTextPane nrRoweruWyswietlanie = new JTextPane();
JTextPane czasWyswietlanie = new JTextPane();
JTextPane lokalizacjaWyswietlanie = new JTextPane();
// Pola wyświetlania panel prawy górny róg
JTextPane idWyswietlanie = new JTextPane();
JTextPane saldoWyswietlanie = new JTextPane();
rowerWyswietlanie.setEditable(false);
nrRoweruWyswietlanie.setEditable(false);
czasWyswietlanie.setEditable(false);
lokalizacjaWyswietlanie.setEditable(false);
idWyswietlanie.setEditable(false);
saldoWyswietlanie.setEditable(false);
// Centrowanie napisów w panelach
JPanel panelRowerWyswietlanieCenter = new JPanel(new GridLayout(0,1));
rowerWyswietlanie.setBorder(new EmptyBorder(7,17,5,3));
panelRowerWyswietlanieCenter.add(rowerWyswietlanie);
JPanel panelNrRoweruWyswietlanieCenter = new JPanel(new GridLayout(0,1));
nrRoweruWyswietlanie.setBorder(new EmptyBorder(8,24,5,3));
panelNrRoweruWyswietlanieCenter.add(nrRoweruWyswietlanie);
JPanel panelCzasWyswietlanieCenter = new JPanel(new GridLayout(0,1));
czasWyswietlanie.setBorder(new EmptyBorder(8,24,5,3));
panelCzasWyswietlanieCenter.add(czasWyswietlanie);
JPanel panelLokalizacjaWyswietlanieCenter = new JPanel(new GridLayout(0,1));
lokalizacjaWyswietlanie.setBorder(new EmptyBorder(7,4,5,3));
panelLokalizacjaWyswietlanieCenter.add(lokalizacjaWyswietlanie);
JPanel panelIdWyswietlenieCenter = new JPanel(new GridLayout(0,1));
idWyswietlanie.setBorder(new EmptyBorder(7,30,5,3));
panelIdWyswietlenieCenter.add(idWyswietlanie);
JPanel panelSaldoWyswietlenieCenter = new JPanel(new GridLayout(0,1));
saldoWyswietlanie.setBorder(new EmptyBorder(7,25,5,3));
panelSaldoWyswietlenieCenter.add(saldoWyswietlanie);
// Dodawanie do panela małego z obramówką
panelMaly.add(new JLabel("Rower: "));
panelMaly.add(panelRowerWyswietlanieCenter);
panelMaly.add(new JLabel("Nr roweru: "));
panelMaly.add(panelNrRoweruWyswietlanieCenter);
panelMaly.add(new JLabel("Czas: "));
panelMaly.add(panelCzasWyswietlanieCenter);
panelMaly.add(new JLabel("Pozycja: "));
panelMaly.add(panelLokalizacjaWyswietlanieCenter);
// Dodawanie do panela prawy górny róg z obramówką
panelPrawyGorny.add(new JLabel("ID: "));
panelPrawyGorny.add(panelIdWyswietlenieCenter);
panelPrawyGorny.add(new JLabel("Saldo: "));
panelPrawyGorny.add(panelSaldoWyswietlenieCenter);
// Użytkownik na mapie
JPanel marker = new JPanel(null);
marker.setBackground(new Color(255,128,0));
// Dodawanie do głównego panelu
contentPane.add(buttonWypozyczRower);
contentPane.add(buttonOddajRower);
contentPane.add(buttonNajblizszaStacja);
contentPane.add(buttonKodObreczy);
contentPane.add(buttonKontakt);
contentPane.add(panelMaly);
contentPane.add(panelPrawyGorny);
contentPane.add(miastoNapis);
contentPane.add(marker);
frame.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
PointerInfo a = MouseInfo.getPointerInfo();
Point point = new Point(a.getLocation());
SwingUtilities.convertPointFromScreen(point, e.getComponent());
x1=(int) point.getX();
y1=(int) point.getY();
int [] lokalizacjaUzytkownika = new int[2];
lokalizacjaUzytkownika[0] = x1;
lokalizacjaUzytkownika[1] = y1;
user.setLokalizacja(lokalizacjaUzytkownika);
lokalizacjaWyswietlanie.setText("(" +x1 +","+y1+")");
marker.setBounds(x1-10, y1-34, 20, 20);
// System.out.println(Arrays.toString(user.getLokalizacja()));
// System.out.println("X: "+ x1 + ", Y: "+ y1);
}
});
contentPane.setLayout(null);
// Ustawienie labelów
rowerWyswietlanie.setText(String.valueOf(user.maRower()));
idWyswietlanie.setText(String.valueOf(user.getUserID()));
saldoWyswietlanie.setText(String.valueOf(user.getSaldo().getKwota()));
// Funkcjonalność przycisków
ActionListener wypozyczRowerAkcja = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(!user.maRower()){
Pair stacjaObokUzytkownika = user.getSystemRowerowy().najblizszaStacja(user.getLokalizacja(),user.maRower());
if(stacjaObokUzytkownika.getOdlegloscOdStacji() <= 35){
StringBuilder info = new StringBuilder("Stacja: " + stacjaObokUzytkownika.getNajblizszaStacja().getNazwaStacji() +
"\nDostępne rowery na stacji: \n") ;
for (int i = 0; i < stacjaObokUzytkownika.getNajblizszaStacja().getStojaki().size(); i++) {
info.append("Stojak ").append(i).append(": ");
for (int j = 0; j < stacjaObokUzytkownika.getNajblizszaStacja().getStojaki().get(i).ileRowerow() ; j++) {
info.append(stacjaObokUzytkownika.getNajblizszaStacja().getStojaki().get(i).getRowery().get(j).getNrRoweru()).append(", ");
}
info.append("\n");
}
String wypozyczRowerInfo = "Numer roweru";
String opcja = (String) JOptionPane.showInputDialog(contentPane, info,wypozyczRowerInfo);
try {
user.wypozyczRower(Integer.parseInt(opcja));
thread = new Thread() {
@Override
public void run() {
int czas = 0;
while(!Thread.currentThread().isInterrupted() && user.maRower()) {
czasWyswietlanie.setText(String.valueOf(czas));
czas += 1;
try {
Thread.sleep(1000);
} catch (InterruptedException interruptedException) {
break;
}
}
}
};
thread.start();
rowerWyswietlanie.setText(String.valueOf(user.maRower()));
nrRoweruWyswietlanie.setText(String.valueOf(user.getRower().getNrRoweru()));
JOptionPane.showMessageDialog(contentPane, "Szerokiej drogi","Pomyślne wypożyczenie roweru",JOptionPane.INFORMATION_MESSAGE);
}
catch (NullPointerException e1){
String msg = "Rower o podanym numerze nie znajduje się na stacji na ktrórej jest użytkownik lub rower " +
"nie jest ostatni w danym stojaku";
JOptionPane.showMessageDialog(contentPane, msg,"Błąd wypożyczania",JOptionPane.ERROR_MESSAGE);
}
catch (NumberFormatException e2) {
String msg = "Przerwano wypożyczanie roweru";
JOptionPane.showMessageDialog(contentPane, msg,"Przerwanie wypożyczania",JOptionPane.ERROR_MESSAGE);
}
}
else{
JOptionPane.showMessageDialog(contentPane, "Jesteś za daleko od stacji!","Za daleko od stacji",JOptionPane.INFORMATION_MESSAGE);
}
}
else{
JOptionPane.showMessageDialog(contentPane,"Masz już wypożyczony rower","Wypożyczony rower",JOptionPane.ERROR_MESSAGE );
}
}
};
ActionListener oddajRowerAkcja = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(user.maRower()){
Pair stacjaObokUzytkownika = user.getSystemRowerowy().najblizszaStacja(user.getLokalizacja(),user.maRower());
if(stacjaObokUzytkownika.getOdlegloscOdStacji() <= 35){
String info = "Czy chcesz oddać rower na stację: " + stacjaObokUzytkownika.getNajblizszaStacja().getNazwaStacji();
Object[] options = {"Tak",
"Nie!"};
int potwierdzWybor = JOptionPane.showOptionDialog(contentPane,info,"Potwierdzenie oddania",JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,null,options,options[0]);
if(potwierdzWybor == 0){
try{
user.oddajRower();
thread.interrupt();
user.getSaldo().pomniejsz(Integer.parseInt(czasWyswietlanie.getText()));
saldoWyswietlanie.setText(String.valueOf(user.getSaldo().getKwota()));
rowerWyswietlanie.setText(String.valueOf(user.maRower()));
czasWyswietlanie.setText("");
nrRoweruWyswietlanie.setText("");
if(user.getSaldo().getKwota() <= 0 ) {
JOptionPane.showMessageDialog(contentPane, "Stan twojego konta jest nie większy niż 0", "Uwaga niski stan konta", JOptionPane.WARNING_MESSAGE);
}
} catch (PelnaStacjaException pelnaStacjaException) {
JOptionPane.showMessageDialog(contentPane,pelnaStacjaException.getMessage(),"Pełna stacja",JOptionPane.ERROR_MESSAGE );
}
}
}
else{
JOptionPane.showMessageDialog(contentPane, "Jesteś za daleko od stacji!","Za daleko od stacji",JOptionPane.INFORMATION_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(contentPane,"Nie masz wypożyczonego roweru","Brak wypożyczonego roweru",JOptionPane.ERROR_MESSAGE );
}
}
};
ActionListener najblizszaStacjaAkcja = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String nazwaStacji = user.jakaNajblizszaStacja().getNazwaStacji();
String najblizszaStacjaInfo = "Najblisza stacja to " + nazwaStacji;
JOptionPane.showMessageDialog(contentPane, najblizszaStacjaInfo,"Najbliższa stacja", JOptionPane.INFORMATION_MESSAGE);
}
};
ActionListener kodObreczyAkcja = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(user.maRower()){
String kodObreczy = "Kod obręczy to: " + user.getRower().getKodObreczy();
JOptionPane.showMessageDialog(contentPane, kodObreczy,"Kod obręczy", JOptionPane.INFORMATION_MESSAGE);
}
else{
JOptionPane.showMessageDialog(contentPane, "Nie posiadasz roweru.","Błąd kodu obręczy", JOptionPane.INFORMATION_MESSAGE);
}
}
};
ActionListener kontaktAkcja = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String msg = """
Autorzy projektu: Mateusz Mianowany, Rafał Wolert, Oskar Zając.""";
JOptionPane.showMessageDialog(contentPane, msg,"Kontakt", JOptionPane.INFORMATION_MESSAGE);
}
};
// Dodanie funkcjonalności do przycisków
buttonWypozyczRower.addActionListener(wypozyczRowerAkcja);
buttonOddajRower.addActionListener(oddajRowerAkcja);
buttonNajblizszaStacja.addActionListener(najblizszaStacjaAkcja);
buttonKodObreczy.addActionListener(kodObreczyAkcja);
buttonKontakt.addActionListener(kontaktAkcja);
frame.setResizable(false);
frame.setLayout(null);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private class MyPanel extends JPanel {
private BufferedImage image;
public MyPanel() {
try {
image = ImageIO.read(MyPanel.class.getResource("/resources/images/bg_final.jpg"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 175, 90, this);
// g.fillOval(x1, y1, 20, 20);
}
}
}
| zoskar/SystemRowerowy | system/src/GuiTest.java | 5,320 | // Dodawanie do panela małego z obramówką | line_comment | pl | import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
public class GuiTest extends JComponent{
private MyPanel contentPane;
private int x1,y1;
private Thread thread;
void displayGUI() {
// Generowanie obiektów do GUI
java.util.List<Rower> rowery = Test.genRower();
java.util.List<Stack<Rower>> stackList = Test.genStacks(rowery);
java.util.List<Stojak> stojakList = Test.genStojaki(stackList);
List<StacjaRowerowa> stacjaRowerowaList = Test.genStacjeRowerowe(stojakList);
SystemRowerowy systemRowerowy = new SystemRowerowy(new ArrayList<>(), stacjaRowerowaList);
Miasto miasto = new Miasto(systemRowerowy, "Lublin");
int[] lokalizacja = {22, 22};
Saldo saldo = new Saldo(10);
Uzytkownik user = new Uzytkownik(1, miasto, lokalizacja, saldo);
int x = 12, y = 222, szer = 150, wys = 90;
int vShift = 100; // vertical
Font czcionka = new Font("Courier", Font.BOLD, 50);
JFrame frame = new JFrame("System Rowerowy");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = new MyPanel();
contentPane.setPreferredSize(new Dimension(1024, 750));
// Napis Lublin
JLabel miastoNapis = new JLabel("Lublin");
miastoNapis.setBounds(480,29,300,50);
miastoNapis.setFont(czcionka);
// Przyciski pod Informacjami o użytkowniku
JButton buttonWypozyczRower = new JButton("Wypożycz rower");
JButton buttonOddajRower = new JButton("Oddaj rower");
JButton buttonNajblizszaStacja = new JButton("Najbliższa stacja");
JButton buttonKodObreczy = new JButton("Kod obręczy");
JButton buttonKontakt = new JButton("Kontakt");
// Położenie przycisków
buttonWypozyczRower.setBounds(x, y, szer, wys);
buttonOddajRower.setBounds(x, y+vShift, szer, wys);
buttonNajblizszaStacja.setBounds(x, y+2*vShift, szer, wys);
buttonKodObreczy.setBounds(x, y+3*vShift, szer, wys);
buttonKontakt.setBounds(x, y+4*vShift, szer, wys);
// GridLayouty
GridLayout gridLayoutInformacje = new GridLayout(4, 2); //GridLayout dla małego panelu informacji
GridLayout gridLayoutPrawyGorny = new GridLayout(2,2); //GridLayout dla prawego górnego rogu
gridLayoutInformacje.setVgap(15);
gridLayoutInformacje.setHgap(5);
gridLayoutPrawyGorny.setVgap(15);
gridLayoutPrawyGorny.setHgap(5);
// Panele i obramówki do paneli
JPanel panelMaly = new JPanel(gridLayoutInformacje);
JPanel panelPrawyGorny = new JPanel(gridLayoutPrawyGorny);
panelMaly.setBounds(x,0,szer,wys+110);
panelPrawyGorny.setBounds(x+816,0,szer,wys);
panelMaly.setBorder(BorderFactory.createTitledBorder("Informacje o użytk."));
panelPrawyGorny.setBorder(BorderFactory.createTitledBorder("Info"));
// Pola wyświetlania mały panel informacji
JTextPane rowerWyswietlanie = new JTextPane();
JTextPane nrRoweruWyswietlanie = new JTextPane();
JTextPane czasWyswietlanie = new JTextPane();
JTextPane lokalizacjaWyswietlanie = new JTextPane();
// Pola wyświetlania panel prawy górny róg
JTextPane idWyswietlanie = new JTextPane();
JTextPane saldoWyswietlanie = new JTextPane();
rowerWyswietlanie.setEditable(false);
nrRoweruWyswietlanie.setEditable(false);
czasWyswietlanie.setEditable(false);
lokalizacjaWyswietlanie.setEditable(false);
idWyswietlanie.setEditable(false);
saldoWyswietlanie.setEditable(false);
// Centrowanie napisów w panelach
JPanel panelRowerWyswietlanieCenter = new JPanel(new GridLayout(0,1));
rowerWyswietlanie.setBorder(new EmptyBorder(7,17,5,3));
panelRowerWyswietlanieCenter.add(rowerWyswietlanie);
JPanel panelNrRoweruWyswietlanieCenter = new JPanel(new GridLayout(0,1));
nrRoweruWyswietlanie.setBorder(new EmptyBorder(8,24,5,3));
panelNrRoweruWyswietlanieCenter.add(nrRoweruWyswietlanie);
JPanel panelCzasWyswietlanieCenter = new JPanel(new GridLayout(0,1));
czasWyswietlanie.setBorder(new EmptyBorder(8,24,5,3));
panelCzasWyswietlanieCenter.add(czasWyswietlanie);
JPanel panelLokalizacjaWyswietlanieCenter = new JPanel(new GridLayout(0,1));
lokalizacjaWyswietlanie.setBorder(new EmptyBorder(7,4,5,3));
panelLokalizacjaWyswietlanieCenter.add(lokalizacjaWyswietlanie);
JPanel panelIdWyswietlenieCenter = new JPanel(new GridLayout(0,1));
idWyswietlanie.setBorder(new EmptyBorder(7,30,5,3));
panelIdWyswietlenieCenter.add(idWyswietlanie);
JPanel panelSaldoWyswietlenieCenter = new JPanel(new GridLayout(0,1));
saldoWyswietlanie.setBorder(new EmptyBorder(7,25,5,3));
panelSaldoWyswietlenieCenter.add(saldoWyswietlanie);
// Dodaw<SUF>
panelMaly.add(new JLabel("Rower: "));
panelMaly.add(panelRowerWyswietlanieCenter);
panelMaly.add(new JLabel("Nr roweru: "));
panelMaly.add(panelNrRoweruWyswietlanieCenter);
panelMaly.add(new JLabel("Czas: "));
panelMaly.add(panelCzasWyswietlanieCenter);
panelMaly.add(new JLabel("Pozycja: "));
panelMaly.add(panelLokalizacjaWyswietlanieCenter);
// Dodawanie do panela prawy górny róg z obramówką
panelPrawyGorny.add(new JLabel("ID: "));
panelPrawyGorny.add(panelIdWyswietlenieCenter);
panelPrawyGorny.add(new JLabel("Saldo: "));
panelPrawyGorny.add(panelSaldoWyswietlenieCenter);
// Użytkownik na mapie
JPanel marker = new JPanel(null);
marker.setBackground(new Color(255,128,0));
// Dodawanie do głównego panelu
contentPane.add(buttonWypozyczRower);
contentPane.add(buttonOddajRower);
contentPane.add(buttonNajblizszaStacja);
contentPane.add(buttonKodObreczy);
contentPane.add(buttonKontakt);
contentPane.add(panelMaly);
contentPane.add(panelPrawyGorny);
contentPane.add(miastoNapis);
contentPane.add(marker);
frame.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
PointerInfo a = MouseInfo.getPointerInfo();
Point point = new Point(a.getLocation());
SwingUtilities.convertPointFromScreen(point, e.getComponent());
x1=(int) point.getX();
y1=(int) point.getY();
int [] lokalizacjaUzytkownika = new int[2];
lokalizacjaUzytkownika[0] = x1;
lokalizacjaUzytkownika[1] = y1;
user.setLokalizacja(lokalizacjaUzytkownika);
lokalizacjaWyswietlanie.setText("(" +x1 +","+y1+")");
marker.setBounds(x1-10, y1-34, 20, 20);
// System.out.println(Arrays.toString(user.getLokalizacja()));
// System.out.println("X: "+ x1 + ", Y: "+ y1);
}
});
contentPane.setLayout(null);
// Ustawienie labelów
rowerWyswietlanie.setText(String.valueOf(user.maRower()));
idWyswietlanie.setText(String.valueOf(user.getUserID()));
saldoWyswietlanie.setText(String.valueOf(user.getSaldo().getKwota()));
// Funkcjonalność przycisków
ActionListener wypozyczRowerAkcja = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(!user.maRower()){
Pair stacjaObokUzytkownika = user.getSystemRowerowy().najblizszaStacja(user.getLokalizacja(),user.maRower());
if(stacjaObokUzytkownika.getOdlegloscOdStacji() <= 35){
StringBuilder info = new StringBuilder("Stacja: " + stacjaObokUzytkownika.getNajblizszaStacja().getNazwaStacji() +
"\nDostępne rowery na stacji: \n") ;
for (int i = 0; i < stacjaObokUzytkownika.getNajblizszaStacja().getStojaki().size(); i++) {
info.append("Stojak ").append(i).append(": ");
for (int j = 0; j < stacjaObokUzytkownika.getNajblizszaStacja().getStojaki().get(i).ileRowerow() ; j++) {
info.append(stacjaObokUzytkownika.getNajblizszaStacja().getStojaki().get(i).getRowery().get(j).getNrRoweru()).append(", ");
}
info.append("\n");
}
String wypozyczRowerInfo = "Numer roweru";
String opcja = (String) JOptionPane.showInputDialog(contentPane, info,wypozyczRowerInfo);
try {
user.wypozyczRower(Integer.parseInt(opcja));
thread = new Thread() {
@Override
public void run() {
int czas = 0;
while(!Thread.currentThread().isInterrupted() && user.maRower()) {
czasWyswietlanie.setText(String.valueOf(czas));
czas += 1;
try {
Thread.sleep(1000);
} catch (InterruptedException interruptedException) {
break;
}
}
}
};
thread.start();
rowerWyswietlanie.setText(String.valueOf(user.maRower()));
nrRoweruWyswietlanie.setText(String.valueOf(user.getRower().getNrRoweru()));
JOptionPane.showMessageDialog(contentPane, "Szerokiej drogi","Pomyślne wypożyczenie roweru",JOptionPane.INFORMATION_MESSAGE);
}
catch (NullPointerException e1){
String msg = "Rower o podanym numerze nie znajduje się na stacji na ktrórej jest użytkownik lub rower " +
"nie jest ostatni w danym stojaku";
JOptionPane.showMessageDialog(contentPane, msg,"Błąd wypożyczania",JOptionPane.ERROR_MESSAGE);
}
catch (NumberFormatException e2) {
String msg = "Przerwano wypożyczanie roweru";
JOptionPane.showMessageDialog(contentPane, msg,"Przerwanie wypożyczania",JOptionPane.ERROR_MESSAGE);
}
}
else{
JOptionPane.showMessageDialog(contentPane, "Jesteś za daleko od stacji!","Za daleko od stacji",JOptionPane.INFORMATION_MESSAGE);
}
}
else{
JOptionPane.showMessageDialog(contentPane,"Masz już wypożyczony rower","Wypożyczony rower",JOptionPane.ERROR_MESSAGE );
}
}
};
ActionListener oddajRowerAkcja = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(user.maRower()){
Pair stacjaObokUzytkownika = user.getSystemRowerowy().najblizszaStacja(user.getLokalizacja(),user.maRower());
if(stacjaObokUzytkownika.getOdlegloscOdStacji() <= 35){
String info = "Czy chcesz oddać rower na stację: " + stacjaObokUzytkownika.getNajblizszaStacja().getNazwaStacji();
Object[] options = {"Tak",
"Nie!"};
int potwierdzWybor = JOptionPane.showOptionDialog(contentPane,info,"Potwierdzenie oddania",JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,null,options,options[0]);
if(potwierdzWybor == 0){
try{
user.oddajRower();
thread.interrupt();
user.getSaldo().pomniejsz(Integer.parseInt(czasWyswietlanie.getText()));
saldoWyswietlanie.setText(String.valueOf(user.getSaldo().getKwota()));
rowerWyswietlanie.setText(String.valueOf(user.maRower()));
czasWyswietlanie.setText("");
nrRoweruWyswietlanie.setText("");
if(user.getSaldo().getKwota() <= 0 ) {
JOptionPane.showMessageDialog(contentPane, "Stan twojego konta jest nie większy niż 0", "Uwaga niski stan konta", JOptionPane.WARNING_MESSAGE);
}
} catch (PelnaStacjaException pelnaStacjaException) {
JOptionPane.showMessageDialog(contentPane,pelnaStacjaException.getMessage(),"Pełna stacja",JOptionPane.ERROR_MESSAGE );
}
}
}
else{
JOptionPane.showMessageDialog(contentPane, "Jesteś za daleko od stacji!","Za daleko od stacji",JOptionPane.INFORMATION_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(contentPane,"Nie masz wypożyczonego roweru","Brak wypożyczonego roweru",JOptionPane.ERROR_MESSAGE );
}
}
};
ActionListener najblizszaStacjaAkcja = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String nazwaStacji = user.jakaNajblizszaStacja().getNazwaStacji();
String najblizszaStacjaInfo = "Najblisza stacja to " + nazwaStacji;
JOptionPane.showMessageDialog(contentPane, najblizszaStacjaInfo,"Najbliższa stacja", JOptionPane.INFORMATION_MESSAGE);
}
};
ActionListener kodObreczyAkcja = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(user.maRower()){
String kodObreczy = "Kod obręczy to: " + user.getRower().getKodObreczy();
JOptionPane.showMessageDialog(contentPane, kodObreczy,"Kod obręczy", JOptionPane.INFORMATION_MESSAGE);
}
else{
JOptionPane.showMessageDialog(contentPane, "Nie posiadasz roweru.","Błąd kodu obręczy", JOptionPane.INFORMATION_MESSAGE);
}
}
};
ActionListener kontaktAkcja = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String msg = """
Autorzy projektu: Mateusz Mianowany, Rafał Wolert, Oskar Zając.""";
JOptionPane.showMessageDialog(contentPane, msg,"Kontakt", JOptionPane.INFORMATION_MESSAGE);
}
};
// Dodanie funkcjonalności do przycisków
buttonWypozyczRower.addActionListener(wypozyczRowerAkcja);
buttonOddajRower.addActionListener(oddajRowerAkcja);
buttonNajblizszaStacja.addActionListener(najblizszaStacjaAkcja);
buttonKodObreczy.addActionListener(kodObreczyAkcja);
buttonKontakt.addActionListener(kontaktAkcja);
frame.setResizable(false);
frame.setLayout(null);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private class MyPanel extends JPanel {
private BufferedImage image;
public MyPanel() {
try {
image = ImageIO.read(MyPanel.class.getResource("/resources/images/bg_final.jpg"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 175, 90, this);
// g.fillOval(x1, y1, 20, 20);
}
}
}
|
9509_10 | package introduction;
import javax.swing.*;
//LABELS
public class Second {
JFrame frame;
public Second(){
frame = new JFrame("Label Example"); //tworzymy obiekt klasy JFrame - czyli ramkę
//BUTTONS
JButton button = new JButton("Kliknij!"); //tworzymy nowy obiekt klasy JButton - czyli przycisk
button.setBounds(175,175, 100, 100); //pozycja i rozmiar przycisku - x, y, szerokość, wysokość
frame.add(button); //dodajemy przycisk do ramki
JButton button1 = new JButton(new ImageIcon("/home/zparteka/Pulpit/button.jpg")); //sciezka do pliku
button1.setBounds(350, 175, 318, 287);
frame.add(button1);
//LABEL EXAMPLE
JLabel label1, label2;
label1 = new JLabel("Guziczek pierwszy");
label1.setBounds(175, 140, 200, 30);
frame.add(label1);
label2 = new JLabel("Guziczek drugi");
label2.setBounds(350, 140, 200, 30);
frame.add(label2);
frame.setSize(1000,700); // rozmiar ramki
frame.setLayout(null); // tym zajmiemy się później
frame.setVisible(true); //chyba dość oczywiste
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Second();
}
}
| zparteka/programowanieObiektowe2019 | interfaces_java/src/introduction/Second.java | 483 | //chyba dość oczywiste | line_comment | pl | package introduction;
import javax.swing.*;
//LABELS
public class Second {
JFrame frame;
public Second(){
frame = new JFrame("Label Example"); //tworzymy obiekt klasy JFrame - czyli ramkę
//BUTTONS
JButton button = new JButton("Kliknij!"); //tworzymy nowy obiekt klasy JButton - czyli przycisk
button.setBounds(175,175, 100, 100); //pozycja i rozmiar przycisku - x, y, szerokość, wysokość
frame.add(button); //dodajemy przycisk do ramki
JButton button1 = new JButton(new ImageIcon("/home/zparteka/Pulpit/button.jpg")); //sciezka do pliku
button1.setBounds(350, 175, 318, 287);
frame.add(button1);
//LABEL EXAMPLE
JLabel label1, label2;
label1 = new JLabel("Guziczek pierwszy");
label1.setBounds(175, 140, 200, 30);
frame.add(label1);
label2 = new JLabel("Guziczek drugi");
label2.setBounds(350, 140, 200, 30);
frame.add(label2);
frame.setSize(1000,700); // rozmiar ramki
frame.setLayout(null); // tym zajmiemy się później
frame.setVisible(true); //chyba<SUF>
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Second();
}
}
|
28073_0 | package pwr.zpibackend.services.impl.thesis;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pwr.zpibackend.dto.thesis.ThesisDTO;
import pwr.zpibackend.exceptions.LimitOfThesesReachedException;
import pwr.zpibackend.exceptions.NotFoundException;
import pwr.zpibackend.models.thesis.Reservation;
import pwr.zpibackend.models.thesis.Status;
import pwr.zpibackend.models.thesis.Thesis;
import pwr.zpibackend.models.university.Program;
import pwr.zpibackend.models.user.Employee;
import pwr.zpibackend.models.user.Student;
import pwr.zpibackend.repositories.thesis.CommentRepository;
import pwr.zpibackend.repositories.thesis.ReservationRepository;
import pwr.zpibackend.repositories.thesis.StatusRepository;
import pwr.zpibackend.repositories.thesis.ThesisRepository;
import pwr.zpibackend.repositories.university.ProgramRepository;
import pwr.zpibackend.repositories.university.StudyCycleRepository;
import pwr.zpibackend.repositories.user.EmployeeRepository;
import pwr.zpibackend.repositories.user.StudentRepository;
import pwr.zpibackend.services.mailing.IMailService;
import pwr.zpibackend.services.thesis.IThesisService;
import pwr.zpibackend.utils.MailTemplates;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
@AllArgsConstructor
public class ThesisService implements IThesisService {
private final ThesisRepository thesisRepository;
private final EmployeeRepository employeeRepository;
private final ProgramRepository programRepository;
private final StudyCycleRepository studyCycleRepository;
private final StatusRepository statusRepository;
private final CommentRepository commentRepository;
private final StudentRepository studentRepository;
private final ReservationRepository reservationRepository;
private final IMailService mailService;
private final Sort sort = Sort.by(Sort.Direction.DESC, "studyCycle.name", "id");
public List<Thesis> getAllTheses() {
return thesisRepository.findAllByOrderByStudyCycleNameDescIdDesc();
}
public List<Thesis> getAllPublicTheses() {
return thesisRepository.findAllByStatusNameIn(Arrays.asList("Approved", "Assigned", "Closed"), sort);
}
public Thesis getThesis(Long id) {
return thesisRepository.findById(id)
.orElseThrow(() -> new NotFoundException("Thesis with id " + id + " does not exist"));
}
public Thesis getThesisByStudentId(Long studentId) {
Reservation reservation = reservationRepository.findByStudentId(studentId);
if (reservation == null) {
throw new NotFoundException("Reservation for student with id " + studentId + " not found");
}
return thesisRepository.findByReservations_Id(reservation.getId())
.orElseThrow(() -> new NotFoundException("Thesis for student with id " + studentId + " not found"));
}
@Transactional
public Thesis addThesis(ThesisDTO thesis) {
Employee supervisor = employeeRepository
.findById(thesis.getSupervisorId())
.orElseThrow(
() -> new NotFoundException(
"Employee with id " + thesis.getSupervisorId() + " does not exist"));
Status draftStatus = statusRepository.findByName("Draft").orElseThrow(NotFoundException::new);
Status rejectedStatus = statusRepository.findByName("Rejected").orElseThrow(NotFoundException::new);
Status closedStatus = statusRepository.findByName("Closed").orElseThrow(NotFoundException::new);
if ((!thesis.getStatusId().equals(draftStatus.getId()) &&
!thesis.getStatusId().equals(rejectedStatus.getId()) &&
!thesis.getStatusId().equals(closedStatus.getId())) &&
thesisRepository.findAllBySupervisor_IdAndStatus_NameIn(supervisor.getId(),
Arrays.asList("Pending approval", "Approved", "Assigned"), sort)
.size() >= supervisor.getNumTheses()) {
throw new LimitOfThesesReachedException("Employee with id " + thesis.getSupervisorId() +
" has reached the limit of theses");
}
Thesis newThesis = new Thesis();
newThesis.setNamePL(thesis.getNamePL());
newThesis.setNameEN(thesis.getNameEN());
newThesis.setDescriptionPL(thesis.getDescriptionPL());
newThesis.setDescriptionEN(thesis.getDescriptionEN());
newThesis.setNumPeople(thesis.getNumPeople());
newThesis.setSupervisor(supervisor);
newThesis.setPrograms(new ArrayList<>());
thesis.getProgramIds().forEach(programId -> {
Program program = programRepository.findById(programId).orElseThrow(
() -> new NotFoundException("Program with id " + programId + " does not exist"));
newThesis.getPrograms().add(program);
});
newThesis.setStudyCycle(thesis.getStudyCycleId()
.map(index -> studyCycleRepository.findById(index).orElseThrow(NotFoundException::new)).orElse(null));
newThesis.setStatus(draftStatus);
thesisRepository.saveAndFlush(newThesis);
try {
if (!thesis.getStudentIndexes().isEmpty() && !thesis.getStatusId().equals(draftStatus.getId())) {
for (String index : thesis.getStudentIndexes()) {
Student student = studentRepository.findByIndex(index)
.orElseThrow(
() -> new NotFoundException("Student with index " + index + " does not exist"));
if (reservationRepository.findByStudent_Mail(student.getMail()) != null) {
throw new IllegalArgumentException(
"Student with index " + index + " already has a reservation");
} else {
Reservation reservation = new Reservation();
reservation.setStudent(student);
reservation.setThesis(newThesis);
reservation.setConfirmedByLeader(false);
reservation.setConfirmedBySupervisor(true);
reservation.setConfirmedByStudent(false);
reservation.setReadyForApproval(true);
reservation.setReservationDate(LocalDateTime.now());
reservation.setSentForApprovalDate(LocalDateTime.now());
reservationRepository.saveAndFlush(reservation);
}
}
newThesis.setOccupied(thesis.getNumPeople());
}
} catch (Exception e) {
for (String index : thesis.getStudentIndexes()) {
Student student = studentRepository.findByIndex(index)
.orElseThrow(() -> new NotFoundException("Student with index " + index + "does not exist"));
Reservation reservation = reservationRepository.findByStudent_Mail(student.getMail());
if (reservation != null) {
reservationRepository.delete(reservation);
}
}
thesisRepository.delete(newThesis);
throw e;
}
for (String index : thesis.getStudentIndexes()) {
Student student = studentRepository.findByIndex(index)
.orElseThrow(() -> new NotFoundException("Student with index " + index + "does not exist"));
mailService.sendHtmlMailMessage(student.getMail(), MailTemplates.RESERVATION_SUPERVISOR,
student, supervisor, newThesis);
}
newThesis.setStatus(statusRepository.findById(thesis.getStatusId()).orElseThrow(NotFoundException::new));
thesisRepository.saveAndFlush(newThesis);
return newThesis;
}
@Transactional
public Thesis updateThesis(Long id, ThesisDTO thesis) {
if (thesisRepository.existsById(id)) {
Thesis updated = thesisRepository.findById(id).get();
Status draftStatus = statusRepository.findByName("Draft").orElseThrow(NotFoundException::new);
Status rejectedStatus = statusRepository.findByName("Rejected").orElseThrow(NotFoundException::new);
Status closedStatus = statusRepository.findByName("Closed").orElseThrow(NotFoundException::new);
if ((updated.getStatus().getName().equals("Draft") || updated.getStatus().getName().equals("Rejected") ||
updated.getStatus().getName().equals("Closed")) &&
(!thesis.getStatusId().equals(draftStatus.getId()) &&
!thesis.getStatusId().equals(rejectedStatus.getId()) &&
!thesis.getStatusId().equals(closedStatus.getId()))
&&
thesisRepository.findAllBySupervisor_IdAndStatus_NameIn(updated.getSupervisor().getId(),
Arrays.asList("Pending approval", "Approved", "Assigned"), sort)
.size() >= updated.getSupervisor().getNumTheses()) {
throw new LimitOfThesesReachedException("Employee with id " + updated.getSupervisor().getId() +
" has reached the limit of theses");
}
updated.setNamePL(thesis.getNamePL());
updated.setNameEN(thesis.getNameEN());
updated.setDescriptionPL(thesis.getDescriptionPL());
updated.setDescriptionEN(thesis.getDescriptionEN());
updated.setNumPeople(thesis.getNumPeople());
updated.setSupervisor(employeeRepository.findById(
thesis.getSupervisorId()).orElseThrow(
() -> new NotFoundException(
"Employee with id " + thesis.getSupervisorId() + " does not exist")));
List<Program> programList = new ArrayList<>();
thesis.getProgramIds().forEach(programId -> {
Program program = programRepository.findById(programId).orElseThrow(
() -> new NotFoundException("Program with id " + programId + " does not exist"));
programList.add(program);
});
updated.setPrograms(programList);
updated.setStudyCycle(thesis.getStudyCycleId()
.map(index -> studyCycleRepository.findById(index).orElseThrow(NotFoundException::new))
.orElse(null));
Status status = statusRepository.findById(thesis.getStatusId()).orElseThrow(NotFoundException::new);
if (status.getName().equals("Rejected")) {
for (Reservation reservation : updated.getReservations()) {
mailService.sendHtmlMailMessage(reservation.getStudent().getMail(),
MailTemplates.RESERVATION_CANCELED,
reservation.getStudent(), null, updated);
}
reservationRepository.deleteAll(updated.getReservations());
updated.getReservations().clear();
updated.setOccupied(0);
} else if (status.getName().equals("Approved") && updated.getOccupied() > 0) {
boolean allConfirmed = true;
for (Reservation reservation : updated.getReservations()) {
if (!reservation.isConfirmedByStudent() || !reservation.isConfirmedBySupervisor()) {
allConfirmed = false;
break;
}
}
if (allConfirmed) {
status = statusRepository.findByName("Assigned").orElseThrow(NotFoundException::new);
}
}
updated.setStatus(status);
thesisRepository.saveAndFlush(updated);
return updated;
}
throw new NotFoundException("Thesis with id " + id + " does not exist");
}
// brakowało metody do usuwania tematu
// co z rozłączaniem z employee/studentem itp? dobrze to jest?
@Transactional
public Thesis deleteThesis(Long id) {
Optional<Thesis> thesisOptional = thesisRepository.findById(id);
if (thesisOptional.isPresent()) {
Thesis deletedThesis = thesisOptional.get();
deletedThesis.setStatus(null);
deletedThesis.setPrograms(null);
deletedThesis.getSupervisor().getSupervisedTheses().remove(deletedThesis);
deletedThesis.setSupervisor(null);
deletedThesis.setLeader(null);
deletedThesis.setStudyCycle(null);
thesisRepository.delete(deletedThesis);
return deletedThesis;
}
throw new NotFoundException("Thesis with id " + id + " does not exist");
}
// np na zwrócenie: wszystkich zaakceptowanych, wszystkich archiwalnych itp
public List<Thesis> getAllThesesByStatusName(String name) {
return thesisRepository.findAllByStatusName(name, sort);
}
// np na zwrócenie wszystkich tematów, które nie są draftami
public List<Thesis> getAllThesesExcludingStatusName(String name) {
Optional<Status> excludedStatus = statusRepository.findByName(name);
if (excludedStatus.isEmpty()) {
throw new NotFoundException("Status with name " + name + " does not exist");
}
return thesisRepository.findAllByOrderByStudyCycleNameDescIdDesc().stream()
.filter(thesis -> !name.equals(thesis.getStatus().getName()))
.collect(Collectors.toList());
}
// np na zwrócenie wszystkich draftów danego pracownika
public List<Thesis> getAllThesesForEmployeeByStatusName(Long empId, String statName) {
return thesisRepository.findAllBySupervisorIdAndStatusName(empId, statName, sort);
}
// np na zwrócenie wszystkich tematów danego pracownika
public List<Thesis> getAllThesesForEmployee(Long id) {
return thesisRepository.findAllBySupervisorId(id, sort);
}
public List<Thesis> getAllThesesForEmployeeByStatusNameList(Long empId, List<String> statNames) {
return thesisRepository.findAllBySupervisor_IdAndStatus_NameIn(empId, statNames, sort);
}
@Transactional
public List<Thesis> updateThesesStatusInBulk(String statName, List<Long> thesesIds) {
Status status = statusRepository.findByName(statName).orElseThrow(NotFoundException::new);
List<Thesis> thesesForUpdate = new ArrayList<>();
for (Long id : thesesIds) {
Optional<Thesis> thesisOptional = thesisRepository.findById(id);
if (thesisOptional.isPresent()) {
Thesis thesis = thesisOptional.get();
if (status.getName().equals("Rejected") || (status.getName().equals("Closed") && thesis.getOccupied() > 0)) {
reservationRepository.deleteAll(new ArrayList<>(thesis.getReservations()));
thesis.getReservations().clear();
thesis.setOccupied(0);
} else if (status.getName().equals("Approved") && thesis.getOccupied() > 0) {
boolean allConfirmed = true;
for (Reservation reservation : thesis.getReservations()) {
if (!reservation.isConfirmedByStudent() || !reservation.isConfirmedBySupervisor()) {
allConfirmed = false;
break;
}
}
if (allConfirmed) {
status = statusRepository.findByName("Assigned").orElseThrow(NotFoundException::new);
}
}
thesis.setStatus(status);
thesesForUpdate.add(thesis);
} else {
throw new NotFoundException("Thesis with id " + id + " does not exist");
}
}
return thesisRepository.saveAllAndFlush(thesesForUpdate);
}
@Transactional
public List<Thesis> deleteThesesByStudyCycle(Long cycId) {
List<Thesis> thesesInCycle = thesisRepository.findAllByStudyCycle_Id(cycId);
List<Thesis> closedTheses = thesesInCycle.stream()
.filter(thesis -> "Closed".equals(thesis.getStatus().getName()))
.toList();
closedTheses.forEach(thesis -> {
thesis.getPrograms().size();
thesis.setSupervisor(null);
thesis.setLeader(null);
});
reservationRepository.deleteAll(closedTheses.stream()
.flatMap(thesis -> thesis.getReservations().stream())
.collect(Collectors.toList()));
commentRepository.deleteAll(closedTheses.stream()
.flatMap(thesis -> thesis.getComments().stream())
.collect(Collectors.toList()));
thesisRepository.deleteAll(closedTheses);
return closedTheses;
}
@Transactional
public List<Thesis> deleteThesesInBulk(List<Long> thesesIds) {
List<Thesis> theses = thesisRepository.findAllById(thesesIds);
// programy nie fetchują się leniwie, więc musiałem to zrobić ręcznie
// a nie chciałem robić FetchType.EAGER w temacie jeśli nie ma konieczności
// czyszczę pracowników i studentów, żeby nie usuwali się kaskadowo
theses.forEach(thesis -> {
thesis.getPrograms().size();
thesis.setSupervisor(null);
thesis.setLeader(null);
});
reservationRepository.deleteAll(theses.stream()
.flatMap(thesis -> thesis.getReservations().stream())
.collect(Collectors.toList()));
commentRepository.deleteAll(theses.stream()
.flatMap(thesis -> thesis.getComments().stream())
.collect(Collectors.toList()));
thesisRepository.deleteAll(theses);
return theses;
}
} | zpi-wojdan/zpi-student-project-management | zpi-backend/src/main/java/pwr/zpibackend/services/impl/thesis/ThesisService.java | 4,831 | // brakowało metody do usuwania tematu | line_comment | pl | package pwr.zpibackend.services.impl.thesis;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pwr.zpibackend.dto.thesis.ThesisDTO;
import pwr.zpibackend.exceptions.LimitOfThesesReachedException;
import pwr.zpibackend.exceptions.NotFoundException;
import pwr.zpibackend.models.thesis.Reservation;
import pwr.zpibackend.models.thesis.Status;
import pwr.zpibackend.models.thesis.Thesis;
import pwr.zpibackend.models.university.Program;
import pwr.zpibackend.models.user.Employee;
import pwr.zpibackend.models.user.Student;
import pwr.zpibackend.repositories.thesis.CommentRepository;
import pwr.zpibackend.repositories.thesis.ReservationRepository;
import pwr.zpibackend.repositories.thesis.StatusRepository;
import pwr.zpibackend.repositories.thesis.ThesisRepository;
import pwr.zpibackend.repositories.university.ProgramRepository;
import pwr.zpibackend.repositories.university.StudyCycleRepository;
import pwr.zpibackend.repositories.user.EmployeeRepository;
import pwr.zpibackend.repositories.user.StudentRepository;
import pwr.zpibackend.services.mailing.IMailService;
import pwr.zpibackend.services.thesis.IThesisService;
import pwr.zpibackend.utils.MailTemplates;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
@AllArgsConstructor
public class ThesisService implements IThesisService {
private final ThesisRepository thesisRepository;
private final EmployeeRepository employeeRepository;
private final ProgramRepository programRepository;
private final StudyCycleRepository studyCycleRepository;
private final StatusRepository statusRepository;
private final CommentRepository commentRepository;
private final StudentRepository studentRepository;
private final ReservationRepository reservationRepository;
private final IMailService mailService;
private final Sort sort = Sort.by(Sort.Direction.DESC, "studyCycle.name", "id");
public List<Thesis> getAllTheses() {
return thesisRepository.findAllByOrderByStudyCycleNameDescIdDesc();
}
public List<Thesis> getAllPublicTheses() {
return thesisRepository.findAllByStatusNameIn(Arrays.asList("Approved", "Assigned", "Closed"), sort);
}
public Thesis getThesis(Long id) {
return thesisRepository.findById(id)
.orElseThrow(() -> new NotFoundException("Thesis with id " + id + " does not exist"));
}
public Thesis getThesisByStudentId(Long studentId) {
Reservation reservation = reservationRepository.findByStudentId(studentId);
if (reservation == null) {
throw new NotFoundException("Reservation for student with id " + studentId + " not found");
}
return thesisRepository.findByReservations_Id(reservation.getId())
.orElseThrow(() -> new NotFoundException("Thesis for student with id " + studentId + " not found"));
}
@Transactional
public Thesis addThesis(ThesisDTO thesis) {
Employee supervisor = employeeRepository
.findById(thesis.getSupervisorId())
.orElseThrow(
() -> new NotFoundException(
"Employee with id " + thesis.getSupervisorId() + " does not exist"));
Status draftStatus = statusRepository.findByName("Draft").orElseThrow(NotFoundException::new);
Status rejectedStatus = statusRepository.findByName("Rejected").orElseThrow(NotFoundException::new);
Status closedStatus = statusRepository.findByName("Closed").orElseThrow(NotFoundException::new);
if ((!thesis.getStatusId().equals(draftStatus.getId()) &&
!thesis.getStatusId().equals(rejectedStatus.getId()) &&
!thesis.getStatusId().equals(closedStatus.getId())) &&
thesisRepository.findAllBySupervisor_IdAndStatus_NameIn(supervisor.getId(),
Arrays.asList("Pending approval", "Approved", "Assigned"), sort)
.size() >= supervisor.getNumTheses()) {
throw new LimitOfThesesReachedException("Employee with id " + thesis.getSupervisorId() +
" has reached the limit of theses");
}
Thesis newThesis = new Thesis();
newThesis.setNamePL(thesis.getNamePL());
newThesis.setNameEN(thesis.getNameEN());
newThesis.setDescriptionPL(thesis.getDescriptionPL());
newThesis.setDescriptionEN(thesis.getDescriptionEN());
newThesis.setNumPeople(thesis.getNumPeople());
newThesis.setSupervisor(supervisor);
newThesis.setPrograms(new ArrayList<>());
thesis.getProgramIds().forEach(programId -> {
Program program = programRepository.findById(programId).orElseThrow(
() -> new NotFoundException("Program with id " + programId + " does not exist"));
newThesis.getPrograms().add(program);
});
newThesis.setStudyCycle(thesis.getStudyCycleId()
.map(index -> studyCycleRepository.findById(index).orElseThrow(NotFoundException::new)).orElse(null));
newThesis.setStatus(draftStatus);
thesisRepository.saveAndFlush(newThesis);
try {
if (!thesis.getStudentIndexes().isEmpty() && !thesis.getStatusId().equals(draftStatus.getId())) {
for (String index : thesis.getStudentIndexes()) {
Student student = studentRepository.findByIndex(index)
.orElseThrow(
() -> new NotFoundException("Student with index " + index + " does not exist"));
if (reservationRepository.findByStudent_Mail(student.getMail()) != null) {
throw new IllegalArgumentException(
"Student with index " + index + " already has a reservation");
} else {
Reservation reservation = new Reservation();
reservation.setStudent(student);
reservation.setThesis(newThesis);
reservation.setConfirmedByLeader(false);
reservation.setConfirmedBySupervisor(true);
reservation.setConfirmedByStudent(false);
reservation.setReadyForApproval(true);
reservation.setReservationDate(LocalDateTime.now());
reservation.setSentForApprovalDate(LocalDateTime.now());
reservationRepository.saveAndFlush(reservation);
}
}
newThesis.setOccupied(thesis.getNumPeople());
}
} catch (Exception e) {
for (String index : thesis.getStudentIndexes()) {
Student student = studentRepository.findByIndex(index)
.orElseThrow(() -> new NotFoundException("Student with index " + index + "does not exist"));
Reservation reservation = reservationRepository.findByStudent_Mail(student.getMail());
if (reservation != null) {
reservationRepository.delete(reservation);
}
}
thesisRepository.delete(newThesis);
throw e;
}
for (String index : thesis.getStudentIndexes()) {
Student student = studentRepository.findByIndex(index)
.orElseThrow(() -> new NotFoundException("Student with index " + index + "does not exist"));
mailService.sendHtmlMailMessage(student.getMail(), MailTemplates.RESERVATION_SUPERVISOR,
student, supervisor, newThesis);
}
newThesis.setStatus(statusRepository.findById(thesis.getStatusId()).orElseThrow(NotFoundException::new));
thesisRepository.saveAndFlush(newThesis);
return newThesis;
}
@Transactional
public Thesis updateThesis(Long id, ThesisDTO thesis) {
if (thesisRepository.existsById(id)) {
Thesis updated = thesisRepository.findById(id).get();
Status draftStatus = statusRepository.findByName("Draft").orElseThrow(NotFoundException::new);
Status rejectedStatus = statusRepository.findByName("Rejected").orElseThrow(NotFoundException::new);
Status closedStatus = statusRepository.findByName("Closed").orElseThrow(NotFoundException::new);
if ((updated.getStatus().getName().equals("Draft") || updated.getStatus().getName().equals("Rejected") ||
updated.getStatus().getName().equals("Closed")) &&
(!thesis.getStatusId().equals(draftStatus.getId()) &&
!thesis.getStatusId().equals(rejectedStatus.getId()) &&
!thesis.getStatusId().equals(closedStatus.getId()))
&&
thesisRepository.findAllBySupervisor_IdAndStatus_NameIn(updated.getSupervisor().getId(),
Arrays.asList("Pending approval", "Approved", "Assigned"), sort)
.size() >= updated.getSupervisor().getNumTheses()) {
throw new LimitOfThesesReachedException("Employee with id " + updated.getSupervisor().getId() +
" has reached the limit of theses");
}
updated.setNamePL(thesis.getNamePL());
updated.setNameEN(thesis.getNameEN());
updated.setDescriptionPL(thesis.getDescriptionPL());
updated.setDescriptionEN(thesis.getDescriptionEN());
updated.setNumPeople(thesis.getNumPeople());
updated.setSupervisor(employeeRepository.findById(
thesis.getSupervisorId()).orElseThrow(
() -> new NotFoundException(
"Employee with id " + thesis.getSupervisorId() + " does not exist")));
List<Program> programList = new ArrayList<>();
thesis.getProgramIds().forEach(programId -> {
Program program = programRepository.findById(programId).orElseThrow(
() -> new NotFoundException("Program with id " + programId + " does not exist"));
programList.add(program);
});
updated.setPrograms(programList);
updated.setStudyCycle(thesis.getStudyCycleId()
.map(index -> studyCycleRepository.findById(index).orElseThrow(NotFoundException::new))
.orElse(null));
Status status = statusRepository.findById(thesis.getStatusId()).orElseThrow(NotFoundException::new);
if (status.getName().equals("Rejected")) {
for (Reservation reservation : updated.getReservations()) {
mailService.sendHtmlMailMessage(reservation.getStudent().getMail(),
MailTemplates.RESERVATION_CANCELED,
reservation.getStudent(), null, updated);
}
reservationRepository.deleteAll(updated.getReservations());
updated.getReservations().clear();
updated.setOccupied(0);
} else if (status.getName().equals("Approved") && updated.getOccupied() > 0) {
boolean allConfirmed = true;
for (Reservation reservation : updated.getReservations()) {
if (!reservation.isConfirmedByStudent() || !reservation.isConfirmedBySupervisor()) {
allConfirmed = false;
break;
}
}
if (allConfirmed) {
status = statusRepository.findByName("Assigned").orElseThrow(NotFoundException::new);
}
}
updated.setStatus(status);
thesisRepository.saveAndFlush(updated);
return updated;
}
throw new NotFoundException("Thesis with id " + id + " does not exist");
}
// brako<SUF>
// co z rozłączaniem z employee/studentem itp? dobrze to jest?
@Transactional
public Thesis deleteThesis(Long id) {
Optional<Thesis> thesisOptional = thesisRepository.findById(id);
if (thesisOptional.isPresent()) {
Thesis deletedThesis = thesisOptional.get();
deletedThesis.setStatus(null);
deletedThesis.setPrograms(null);
deletedThesis.getSupervisor().getSupervisedTheses().remove(deletedThesis);
deletedThesis.setSupervisor(null);
deletedThesis.setLeader(null);
deletedThesis.setStudyCycle(null);
thesisRepository.delete(deletedThesis);
return deletedThesis;
}
throw new NotFoundException("Thesis with id " + id + " does not exist");
}
// np na zwrócenie: wszystkich zaakceptowanych, wszystkich archiwalnych itp
public List<Thesis> getAllThesesByStatusName(String name) {
return thesisRepository.findAllByStatusName(name, sort);
}
// np na zwrócenie wszystkich tematów, które nie są draftami
public List<Thesis> getAllThesesExcludingStatusName(String name) {
Optional<Status> excludedStatus = statusRepository.findByName(name);
if (excludedStatus.isEmpty()) {
throw new NotFoundException("Status with name " + name + " does not exist");
}
return thesisRepository.findAllByOrderByStudyCycleNameDescIdDesc().stream()
.filter(thesis -> !name.equals(thesis.getStatus().getName()))
.collect(Collectors.toList());
}
// np na zwrócenie wszystkich draftów danego pracownika
public List<Thesis> getAllThesesForEmployeeByStatusName(Long empId, String statName) {
return thesisRepository.findAllBySupervisorIdAndStatusName(empId, statName, sort);
}
// np na zwrócenie wszystkich tematów danego pracownika
public List<Thesis> getAllThesesForEmployee(Long id) {
return thesisRepository.findAllBySupervisorId(id, sort);
}
public List<Thesis> getAllThesesForEmployeeByStatusNameList(Long empId, List<String> statNames) {
return thesisRepository.findAllBySupervisor_IdAndStatus_NameIn(empId, statNames, sort);
}
@Transactional
public List<Thesis> updateThesesStatusInBulk(String statName, List<Long> thesesIds) {
Status status = statusRepository.findByName(statName).orElseThrow(NotFoundException::new);
List<Thesis> thesesForUpdate = new ArrayList<>();
for (Long id : thesesIds) {
Optional<Thesis> thesisOptional = thesisRepository.findById(id);
if (thesisOptional.isPresent()) {
Thesis thesis = thesisOptional.get();
if (status.getName().equals("Rejected") || (status.getName().equals("Closed") && thesis.getOccupied() > 0)) {
reservationRepository.deleteAll(new ArrayList<>(thesis.getReservations()));
thesis.getReservations().clear();
thesis.setOccupied(0);
} else if (status.getName().equals("Approved") && thesis.getOccupied() > 0) {
boolean allConfirmed = true;
for (Reservation reservation : thesis.getReservations()) {
if (!reservation.isConfirmedByStudent() || !reservation.isConfirmedBySupervisor()) {
allConfirmed = false;
break;
}
}
if (allConfirmed) {
status = statusRepository.findByName("Assigned").orElseThrow(NotFoundException::new);
}
}
thesis.setStatus(status);
thesesForUpdate.add(thesis);
} else {
throw new NotFoundException("Thesis with id " + id + " does not exist");
}
}
return thesisRepository.saveAllAndFlush(thesesForUpdate);
}
@Transactional
public List<Thesis> deleteThesesByStudyCycle(Long cycId) {
List<Thesis> thesesInCycle = thesisRepository.findAllByStudyCycle_Id(cycId);
List<Thesis> closedTheses = thesesInCycle.stream()
.filter(thesis -> "Closed".equals(thesis.getStatus().getName()))
.toList();
closedTheses.forEach(thesis -> {
thesis.getPrograms().size();
thesis.setSupervisor(null);
thesis.setLeader(null);
});
reservationRepository.deleteAll(closedTheses.stream()
.flatMap(thesis -> thesis.getReservations().stream())
.collect(Collectors.toList()));
commentRepository.deleteAll(closedTheses.stream()
.flatMap(thesis -> thesis.getComments().stream())
.collect(Collectors.toList()));
thesisRepository.deleteAll(closedTheses);
return closedTheses;
}
@Transactional
public List<Thesis> deleteThesesInBulk(List<Long> thesesIds) {
List<Thesis> theses = thesisRepository.findAllById(thesesIds);
// programy nie fetchują się leniwie, więc musiałem to zrobić ręcznie
// a nie chciałem robić FetchType.EAGER w temacie jeśli nie ma konieczności
// czyszczę pracowników i studentów, żeby nie usuwali się kaskadowo
theses.forEach(thesis -> {
thesis.getPrograms().size();
thesis.setSupervisor(null);
thesis.setLeader(null);
});
reservationRepository.deleteAll(theses.stream()
.flatMap(thesis -> thesis.getReservations().stream())
.collect(Collectors.toList()));
commentRepository.deleteAll(theses.stream()
.flatMap(thesis -> thesis.getComments().stream())
.collect(Collectors.toList()));
thesisRepository.deleteAll(theses);
return theses;
}
} |
26318_3 | package app;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.event.*;
public class Window extends JFrame implements ActionListener {
private JButton jbtExit, jbtAbout, jbtHelpContext, jbtSave, jbtPrint, jbtSigma, jbtMean, jbtMin, jbtMax;
private JButton addValue, addZeros, addFill, addSave, obliczBtn;
private StatusPanel statusPanel;
private JLabel labelValue, labelRow, labelCol;
private JTextField jtfValue;
private JSpinner jsRow, jsCol;
private SpinnerNumberModel modelRow, modelCol;
protected JTable table;
private JPanel panelOblicz;
protected JTextArea obszarWynikow;
private JScrollPane przewijanieWynikow;
private Font font;
private Icons myIcons = new Icons();
private WindowModel model = new WindowModel();
private Menu myMenu = new Menu(this, myIcons);
public Window() {
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
closeWindow();
}
});
JPanel cp = (JPanel) getContentPane(); //rzutowanie na JPanel
cp.setLayout(new BorderLayout());
try {
myIcons.createIcons();
createMenus();
initGUI();
cp.add(createToolBar(), BorderLayout.NORTH);
cp.add(statusPanel, BorderLayout.SOUTH);
cp.add(createCenterPanel(), BorderLayout.CENTER);
} catch (IconException ie) {
ShowMessageDialog("Błąd: ", "Błąd podczas wczytywania icon");
} catch (Exception e) {
e.printStackTrace();
ShowMessageDialog("Błąd: ", "Błąd podczas tworzenia GUI");
}
}
private void initGUI() {
statusPanel = new StatusPanel();
labelValue = new JLabel("Wprowadź liczbę", JLabel.LEFT);
labelRow = new JLabel("Numer wiersza", JLabel.LEFT);
labelCol = new JLabel("Numer kolumny", JLabel.LEFT);
jtfValue = new JTextField("0");
jtfValue.setHorizontalAlignment(JTextField.RIGHT);
modelRow = new SpinnerNumberModel(1, 1, 5, 1); //(początkowa wartość, minimum, maksimum, krok)
modelCol = new SpinnerNumberModel(1, 1, 5, 1);
jsRow = new JSpinner(modelRow);
jsCol = new JSpinner(modelCol);
table = new JTable(5, 5);
table.setEnabled(false);
table.setRowHeight(table.getRowHeight() + 11);
table.setBackground(new Color(211, 211, 211));
table.getTableHeader().setReorderingAllowed(false);
table.getTableHeader().setResizingAllowed(false);
// Wyśrodkowanie tytułów kolumn znajdujących się na górze tabeli
((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(SwingConstants.CENTER);
// Ustawienie renderera komórek dla danych
DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
rightRenderer.setHorizontalAlignment(SwingConstants.RIGHT);
table.setDefaultRenderer(Object.class, rightRenderer);
new JScrollPane(table);
//definiowanie czcionki przycisków
font = new Font("Helvetica Neue", Font.BOLD, 12);
addValue = new JButton("Dodaj", myIcons.iconAdding);
addValue.addActionListener(this);
addValue.setFont(font);
;
addZeros = new JButton("Wyzeruj", myIcons.iconZero);
addZeros.addActionListener(this);
addZeros.setFont(font);
addFill = new JButton("Wypełnij", myIcons.iconFill);
addFill.addActionListener(this);
addFill.setFont(font);
addSave = new JButton("Zapisz", myIcons.iconSave_Doc);
addSave.addActionListener(this);
addSave.setFont(font);
panelOblicz = new JPanel(new GridLayout(1, 4));
JLabel obliczenia = new JLabel("Obliczenia:");
String[] operacje = {"Wybierz operację", "Dodawanie", "Min", "Max", "Średnia"};
JComboBox<String> comboBox = new JComboBox<>(operacje);
comboBox.setSelectedIndex(0); // Ustawienie domyślnego tekstu
comboBox.setBounds(50, 30, 200, 30);
JLabel pustyLabel = new JLabel();
obliczBtn = new JButton("Oblicz");
obliczBtn.addActionListener(this);
panelOblicz.add(obliczenia);
panelOblicz.add(comboBox);
panelOblicz.add(obliczBtn);
panelOblicz.add(pustyLabel);
obszarWynikow = new JTextArea();
obszarWynikow.setEditable(false);
przewijanieWynikow = new JScrollPane(obszarWynikow);
przewijanieWynikow.setViewportView(obszarWynikow); // Ustawienie widoku na JTextArea
obszarWynikow.setCaretPosition(obszarWynikow.getDocument().getLength()); //automatyczne przewijanie
TitledBorder titledBorder = BorderFactory.createTitledBorder("Uzyskany rezultat");
// Ustawienie wyśrodkowania tytułu
titledBorder.setTitleJustification(TitledBorder.CENTER);
// Ustawienie ramki z tytułem na komponencie
przewijanieWynikow.setBorder(titledBorder);
}
private JPanel createCenterPanel() {
JPanel jp = new JPanel();
FormLayout formLayout = new FormLayout(
//1 2 3 4 5 6 7 8 9 10 11 12 13 14
"5dlu, pref, 2dlu, 50dlu, 10dlu:grow, pref, 3dlu, 40dlu, 20dlu, 10dlu, pref, 3dlu, 40dlu, 5dlu",
"5dlu, pref, 10dlu, pref, 3dlu, pref, 3dlu, pref, 3dlu, pref, 5dlu, 5dlu, pref, 10dlu, pref:grow, 8dlu , 5dlu");
//1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
jp.setLayout(formLayout);
CellConstraints cc = new CellConstraints();
jp.add(labelValue, cc.xy(2, 2, CellConstraints.FILL, CellConstraints.FILL));
jp.add(jtfValue, cc.xy(4, 2, CellConstraints.FILL, CellConstraints.FILL));
jp.add(labelRow, cc.xy(6, 2, CellConstraints.FILL, CellConstraints.FILL));
jp.add(jsRow, cc.xy(8, 2, CellConstraints.FILL, CellConstraints.FILL));
jp.add(labelCol, cc.xy(11, 2, CellConstraints.FILL, CellConstraints.FILL));
jp.add(jsCol, cc.xy(13, 2, CellConstraints.FILL, CellConstraints.FILL));
jp.add(new JScrollPane(table), cc.xywh(2, 4, 8, 7, CellConstraints.FILL, CellConstraints.FILL));
jp.add(addValue, cc.xyw(11, 4, 3, CellConstraints.FILL, CellConstraints.FILL));
jp.add(addZeros, cc.xyw(11, 6, 3, CellConstraints.FILL, CellConstraints.FILL));
jp.add(addFill, cc.xyw(11, 8, 3, CellConstraints.FILL, CellConstraints.FILL));
jp.add(addSave, cc.xyw(11, 10, 3, CellConstraints.FILL, CellConstraints.FILL));
jp.add(panelOblicz, cc.xyw(2, 13, 10, CellConstraints.FILL, CellConstraints.FILL));
jp.add(przewijanieWynikow, cc.xyw(2, 15, 12, CellConstraints.FILL, CellConstraints.FILL));
return jp;
}
private JButton createJButtonToolBar(String tooltip, Icon icon) {
JButton jb = new JButton("", icon);
jb.setToolTipText(tooltip);
jb.addActionListener(this);
return jb;
}
private void createMenus() {
//utworzenie paska manu
JMenuBar menuBar = myMenu.getMenu();
setJMenuBar(menuBar);
}
private JToolBar createToolBar() {
JToolBar jbt = new JToolBar(JToolBar.HORIZONTAL);
jbt.setFloatable(false);
jbtSave = createJButtonToolBar("Zapis pliku", myIcons.iconSave);
jbtPrint = createJButtonToolBar("Drukowanie", myIcons.iconPrint);
jbtExit = createJButtonToolBar("Zamknięcie aplikacji", myIcons.iconExit);
jbtSigma = createJButtonToolBar("Dodawanie", myIcons.iconSigma);
jbtMean = createJButtonToolBar("Średnia", myIcons.iconMean);
jbtMin = createJButtonToolBar("Minimum", myIcons.iconMin);
jbtMax = createJButtonToolBar("Maximum", myIcons.iconMax);
jbtHelpContext = createJButtonToolBar("Kontekst pomocy", myIcons.iconHelp);
jbtAbout = createJButtonToolBar("Informacje o autorze", myIcons.iconAbout);
jbt.add(Box.createHorizontalStrut(5));
jbt.add(jbtSave);
jbt.add(jbtPrint);
jbt.add(jbtExit);
jbt.addSeparator();
jbt.add(jbtSigma);
jbt.add(jbtMean);
jbt.add(jbtMin);
jbt.add(jbtMax);
jbt.addSeparator();
jbt.add(jbtHelpContext);
jbt.add(jbtAbout);
return jbt;
}
public void closeWindow() {
// utworzenie okna dialogowego z zapytanie o zamkniecie projektu
int value = JOptionPane.showOptionDialog(
this,
"Czy chcesz zamknąć aplikację", //komunikat
"Uwaga", // nagłówek okna
JOptionPane.YES_NO_CANCEL_OPTION, //typ opcji
JOptionPane.WARNING_MESSAGE, //typ komunikatu
null, //domyślna ikona
new String[]{"Tak", "Nie"},
"Tak"); // inicjacja aktywnego przycisku
if (value == JOptionPane.YES_OPTION) {
dispose();
System.exit(0);
}
}
@Override
public void actionPerformed(ActionEvent event) {
String result;
result = " ";
if (event.getSource() == myMenu.saveMenuItem || event.getSource() == jbtSave || event.getSource() == addSave) {
ShowMessageDialog("Zapis", "Plik został zapisany pomyślnie!");
}
if (event.getSource() == myMenu.printMenuItem || event.getSource() == jbtPrint) {
ShowMessageDialog("Drukowanie", "Plik został wydrukowany pomyślnie!");
}
if (event.getSource() == myMenu.exitMenuItem || event.getSource() == jbtExit) {
closeWindow();
}
if (event.getSource() == myMenu.helpMenuItem || event.getSource() == jbtHelpContext) {
ShowMessageDialog("Kontekst pomocy", Config.DOCS_INFO);
}
if (event.getSource() == myMenu.aboutMenuItem || event.getSource() == jbtAbout) {
ShowMessageDialog("Informacje o autorze", Config.ABOUT_AUTHOR);
}
if (event.getSource() == myMenu.zoominMenuItem) {
zoomOut();
}
if (event.getSource() == myMenu.zoomoutMenuItem) {
zoomIn();
}
if (event.getSource() == addZeros) {
result = model.resetTable(table);
}
if (event.getSource() == addFill) {
int indeksWiersza = (int) jsRow.getValue();
int indeksKolumny = (int) jsCol.getValue();
int wartosc = Integer.parseInt(jtfValue.getText());
result = model.setValueTable(indeksWiersza, indeksKolumny, wartosc, obszarWynikow, table);
}
if (event.getSource() == jbtSigma || event.getSource() == myMenu.addMenuItem || event.getSource() == addValue) {
result = model.additionalElements(table);
}
if (event.getSource() == jbtMean || event.getSource() == myMenu.meanMenuItem) {
result = model.avgElements(table);
}
if (event.getSource() == jbtMin || event.getSource() == myMenu.minMenuItem) {
result = model.minElements(table);
}
if (event.getSource() == jbtMax || event.getSource() == myMenu.maxMenuItem) {
result = model.maxElements(table);
}
if (event.getSource() == obliczBtn) {
@SuppressWarnings("unchecked")
JComboBox<String> comboBox = (JComboBox<String>) ((JPanel) obliczBtn.getParent()).getComponent(1);
String selectedOperation = (String) comboBox.getSelectedItem();
switch (selectedOperation) {
case "Dodawanie":
result = model.additionalElements(table);
break;
case "Średnia":
result = model.avgElements(table);
break;
case "Min":
result = model.minElements(table);
break;
case "Max":
result = model.maxElements(table);
break;
default:
ShowMessageDialog("Błąd", "Wybierz operację z listy");
break;
}
}
resultAreaAlert(result);
}
protected void resultAreaAlert(String desc){
obszarWynikow.append(desc);
}
protected void ShowMessageDialog(String title1, String title2){
JOptionPane.showMessageDialog(this, title2, title1, JOptionPane.INFORMATION_MESSAGE);
}
protected void zoomIn() {
setSize(900, 650);
setLocationRelativeTo(null);
}
protected void zoomOut() {
setSize(680, 480);
setLocationRelativeTo(null);
}
} | zsoit/java-projekt | src/app/Window.java | 4,214 | // Ustawienie renderera komórek dla danych | line_comment | pl | package app;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.event.*;
public class Window extends JFrame implements ActionListener {
private JButton jbtExit, jbtAbout, jbtHelpContext, jbtSave, jbtPrint, jbtSigma, jbtMean, jbtMin, jbtMax;
private JButton addValue, addZeros, addFill, addSave, obliczBtn;
private StatusPanel statusPanel;
private JLabel labelValue, labelRow, labelCol;
private JTextField jtfValue;
private JSpinner jsRow, jsCol;
private SpinnerNumberModel modelRow, modelCol;
protected JTable table;
private JPanel panelOblicz;
protected JTextArea obszarWynikow;
private JScrollPane przewijanieWynikow;
private Font font;
private Icons myIcons = new Icons();
private WindowModel model = new WindowModel();
private Menu myMenu = new Menu(this, myIcons);
public Window() {
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
closeWindow();
}
});
JPanel cp = (JPanel) getContentPane(); //rzutowanie na JPanel
cp.setLayout(new BorderLayout());
try {
myIcons.createIcons();
createMenus();
initGUI();
cp.add(createToolBar(), BorderLayout.NORTH);
cp.add(statusPanel, BorderLayout.SOUTH);
cp.add(createCenterPanel(), BorderLayout.CENTER);
} catch (IconException ie) {
ShowMessageDialog("Błąd: ", "Błąd podczas wczytywania icon");
} catch (Exception e) {
e.printStackTrace();
ShowMessageDialog("Błąd: ", "Błąd podczas tworzenia GUI");
}
}
private void initGUI() {
statusPanel = new StatusPanel();
labelValue = new JLabel("Wprowadź liczbę", JLabel.LEFT);
labelRow = new JLabel("Numer wiersza", JLabel.LEFT);
labelCol = new JLabel("Numer kolumny", JLabel.LEFT);
jtfValue = new JTextField("0");
jtfValue.setHorizontalAlignment(JTextField.RIGHT);
modelRow = new SpinnerNumberModel(1, 1, 5, 1); //(początkowa wartość, minimum, maksimum, krok)
modelCol = new SpinnerNumberModel(1, 1, 5, 1);
jsRow = new JSpinner(modelRow);
jsCol = new JSpinner(modelCol);
table = new JTable(5, 5);
table.setEnabled(false);
table.setRowHeight(table.getRowHeight() + 11);
table.setBackground(new Color(211, 211, 211));
table.getTableHeader().setReorderingAllowed(false);
table.getTableHeader().setResizingAllowed(false);
// Wyśrodkowanie tytułów kolumn znajdujących się na górze tabeli
((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(SwingConstants.CENTER);
// Ustaw<SUF>
DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
rightRenderer.setHorizontalAlignment(SwingConstants.RIGHT);
table.setDefaultRenderer(Object.class, rightRenderer);
new JScrollPane(table);
//definiowanie czcionki przycisków
font = new Font("Helvetica Neue", Font.BOLD, 12);
addValue = new JButton("Dodaj", myIcons.iconAdding);
addValue.addActionListener(this);
addValue.setFont(font);
;
addZeros = new JButton("Wyzeruj", myIcons.iconZero);
addZeros.addActionListener(this);
addZeros.setFont(font);
addFill = new JButton("Wypełnij", myIcons.iconFill);
addFill.addActionListener(this);
addFill.setFont(font);
addSave = new JButton("Zapisz", myIcons.iconSave_Doc);
addSave.addActionListener(this);
addSave.setFont(font);
panelOblicz = new JPanel(new GridLayout(1, 4));
JLabel obliczenia = new JLabel("Obliczenia:");
String[] operacje = {"Wybierz operację", "Dodawanie", "Min", "Max", "Średnia"};
JComboBox<String> comboBox = new JComboBox<>(operacje);
comboBox.setSelectedIndex(0); // Ustawienie domyślnego tekstu
comboBox.setBounds(50, 30, 200, 30);
JLabel pustyLabel = new JLabel();
obliczBtn = new JButton("Oblicz");
obliczBtn.addActionListener(this);
panelOblicz.add(obliczenia);
panelOblicz.add(comboBox);
panelOblicz.add(obliczBtn);
panelOblicz.add(pustyLabel);
obszarWynikow = new JTextArea();
obszarWynikow.setEditable(false);
przewijanieWynikow = new JScrollPane(obszarWynikow);
przewijanieWynikow.setViewportView(obszarWynikow); // Ustawienie widoku na JTextArea
obszarWynikow.setCaretPosition(obszarWynikow.getDocument().getLength()); //automatyczne przewijanie
TitledBorder titledBorder = BorderFactory.createTitledBorder("Uzyskany rezultat");
// Ustawienie wyśrodkowania tytułu
titledBorder.setTitleJustification(TitledBorder.CENTER);
// Ustawienie ramki z tytułem na komponencie
przewijanieWynikow.setBorder(titledBorder);
}
private JPanel createCenterPanel() {
JPanel jp = new JPanel();
FormLayout formLayout = new FormLayout(
//1 2 3 4 5 6 7 8 9 10 11 12 13 14
"5dlu, pref, 2dlu, 50dlu, 10dlu:grow, pref, 3dlu, 40dlu, 20dlu, 10dlu, pref, 3dlu, 40dlu, 5dlu",
"5dlu, pref, 10dlu, pref, 3dlu, pref, 3dlu, pref, 3dlu, pref, 5dlu, 5dlu, pref, 10dlu, pref:grow, 8dlu , 5dlu");
//1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
jp.setLayout(formLayout);
CellConstraints cc = new CellConstraints();
jp.add(labelValue, cc.xy(2, 2, CellConstraints.FILL, CellConstraints.FILL));
jp.add(jtfValue, cc.xy(4, 2, CellConstraints.FILL, CellConstraints.FILL));
jp.add(labelRow, cc.xy(6, 2, CellConstraints.FILL, CellConstraints.FILL));
jp.add(jsRow, cc.xy(8, 2, CellConstraints.FILL, CellConstraints.FILL));
jp.add(labelCol, cc.xy(11, 2, CellConstraints.FILL, CellConstraints.FILL));
jp.add(jsCol, cc.xy(13, 2, CellConstraints.FILL, CellConstraints.FILL));
jp.add(new JScrollPane(table), cc.xywh(2, 4, 8, 7, CellConstraints.FILL, CellConstraints.FILL));
jp.add(addValue, cc.xyw(11, 4, 3, CellConstraints.FILL, CellConstraints.FILL));
jp.add(addZeros, cc.xyw(11, 6, 3, CellConstraints.FILL, CellConstraints.FILL));
jp.add(addFill, cc.xyw(11, 8, 3, CellConstraints.FILL, CellConstraints.FILL));
jp.add(addSave, cc.xyw(11, 10, 3, CellConstraints.FILL, CellConstraints.FILL));
jp.add(panelOblicz, cc.xyw(2, 13, 10, CellConstraints.FILL, CellConstraints.FILL));
jp.add(przewijanieWynikow, cc.xyw(2, 15, 12, CellConstraints.FILL, CellConstraints.FILL));
return jp;
}
private JButton createJButtonToolBar(String tooltip, Icon icon) {
JButton jb = new JButton("", icon);
jb.setToolTipText(tooltip);
jb.addActionListener(this);
return jb;
}
private void createMenus() {
//utworzenie paska manu
JMenuBar menuBar = myMenu.getMenu();
setJMenuBar(menuBar);
}
private JToolBar createToolBar() {
JToolBar jbt = new JToolBar(JToolBar.HORIZONTAL);
jbt.setFloatable(false);
jbtSave = createJButtonToolBar("Zapis pliku", myIcons.iconSave);
jbtPrint = createJButtonToolBar("Drukowanie", myIcons.iconPrint);
jbtExit = createJButtonToolBar("Zamknięcie aplikacji", myIcons.iconExit);
jbtSigma = createJButtonToolBar("Dodawanie", myIcons.iconSigma);
jbtMean = createJButtonToolBar("Średnia", myIcons.iconMean);
jbtMin = createJButtonToolBar("Minimum", myIcons.iconMin);
jbtMax = createJButtonToolBar("Maximum", myIcons.iconMax);
jbtHelpContext = createJButtonToolBar("Kontekst pomocy", myIcons.iconHelp);
jbtAbout = createJButtonToolBar("Informacje o autorze", myIcons.iconAbout);
jbt.add(Box.createHorizontalStrut(5));
jbt.add(jbtSave);
jbt.add(jbtPrint);
jbt.add(jbtExit);
jbt.addSeparator();
jbt.add(jbtSigma);
jbt.add(jbtMean);
jbt.add(jbtMin);
jbt.add(jbtMax);
jbt.addSeparator();
jbt.add(jbtHelpContext);
jbt.add(jbtAbout);
return jbt;
}
public void closeWindow() {
// utworzenie okna dialogowego z zapytanie o zamkniecie projektu
int value = JOptionPane.showOptionDialog(
this,
"Czy chcesz zamknąć aplikację", //komunikat
"Uwaga", // nagłówek okna
JOptionPane.YES_NO_CANCEL_OPTION, //typ opcji
JOptionPane.WARNING_MESSAGE, //typ komunikatu
null, //domyślna ikona
new String[]{"Tak", "Nie"},
"Tak"); // inicjacja aktywnego przycisku
if (value == JOptionPane.YES_OPTION) {
dispose();
System.exit(0);
}
}
@Override
public void actionPerformed(ActionEvent event) {
String result;
result = " ";
if (event.getSource() == myMenu.saveMenuItem || event.getSource() == jbtSave || event.getSource() == addSave) {
ShowMessageDialog("Zapis", "Plik został zapisany pomyślnie!");
}
if (event.getSource() == myMenu.printMenuItem || event.getSource() == jbtPrint) {
ShowMessageDialog("Drukowanie", "Plik został wydrukowany pomyślnie!");
}
if (event.getSource() == myMenu.exitMenuItem || event.getSource() == jbtExit) {
closeWindow();
}
if (event.getSource() == myMenu.helpMenuItem || event.getSource() == jbtHelpContext) {
ShowMessageDialog("Kontekst pomocy", Config.DOCS_INFO);
}
if (event.getSource() == myMenu.aboutMenuItem || event.getSource() == jbtAbout) {
ShowMessageDialog("Informacje o autorze", Config.ABOUT_AUTHOR);
}
if (event.getSource() == myMenu.zoominMenuItem) {
zoomOut();
}
if (event.getSource() == myMenu.zoomoutMenuItem) {
zoomIn();
}
if (event.getSource() == addZeros) {
result = model.resetTable(table);
}
if (event.getSource() == addFill) {
int indeksWiersza = (int) jsRow.getValue();
int indeksKolumny = (int) jsCol.getValue();
int wartosc = Integer.parseInt(jtfValue.getText());
result = model.setValueTable(indeksWiersza, indeksKolumny, wartosc, obszarWynikow, table);
}
if (event.getSource() == jbtSigma || event.getSource() == myMenu.addMenuItem || event.getSource() == addValue) {
result = model.additionalElements(table);
}
if (event.getSource() == jbtMean || event.getSource() == myMenu.meanMenuItem) {
result = model.avgElements(table);
}
if (event.getSource() == jbtMin || event.getSource() == myMenu.minMenuItem) {
result = model.minElements(table);
}
if (event.getSource() == jbtMax || event.getSource() == myMenu.maxMenuItem) {
result = model.maxElements(table);
}
if (event.getSource() == obliczBtn) {
@SuppressWarnings("unchecked")
JComboBox<String> comboBox = (JComboBox<String>) ((JPanel) obliczBtn.getParent()).getComponent(1);
String selectedOperation = (String) comboBox.getSelectedItem();
switch (selectedOperation) {
case "Dodawanie":
result = model.additionalElements(table);
break;
case "Średnia":
result = model.avgElements(table);
break;
case "Min":
result = model.minElements(table);
break;
case "Max":
result = model.maxElements(table);
break;
default:
ShowMessageDialog("Błąd", "Wybierz operację z listy");
break;
}
}
resultAreaAlert(result);
}
protected void resultAreaAlert(String desc){
obszarWynikow.append(desc);
}
protected void ShowMessageDialog(String title1, String title2){
JOptionPane.showMessageDialog(this, title2, title1, JOptionPane.INFORMATION_MESSAGE);
}
protected void zoomIn() {
setSize(900, 650);
setLocationRelativeTo(null);
}
protected void zoomOut() {
setSize(680, 480);
setLocationRelativeTo(null);
}
} |
31017_8 | package pl.zste.stream.cwiczenia;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.swing.plaf.synth.SynthOptionPaneUI;
public class CwiczeniaStrumienieGr1 {
public static void main(String[] args) {
Rezyser r1 = new Rezyser("James", "Cameron");
Rezyser r2 = new Rezyser("Andrzej", "Wajda");
Rezyser r3 = new Rezyser("Stanisław", "Bareja");
Rezyser r4 = new Rezyser("Patryk", "Vega");
Film titanic = new Film(r1, "Titanic", GatunekFilmu.przygodowy, 160);
Film katyn = new Film(r2, "Katyń", GatunekFilmu.dramat, 90);
Film mis = new Film(r3, "Miś", GatunekFilmu.komedia, 90);
Film mafia = new Film(r4, "Kobiety mafii", GatunekFilmu.sensacyjny, 90);
Film terminator = new Film(r1, "Terminator", GatunekFilmu.sensacyjny, 120);
Recenzja re1 = new Recenzja(1, "Za długi, nudny");
Recenzja re2 = new Recenzja(1, "Nie lubię, taki se");
Recenzja re3 = new Recenzja(6, "Mega mocny, polecam");
Recenzja re4 = new Recenzja(3, "Nie widziałem ale tytuł jest spoko");
Recenzja re5 = new Recenzja(5, "Tylko belfra ten film cieszy");
Recenzja re6 = new Recenzja(6, "Jest mocny");
Recenzja re7 = new Recenzja(5, "Fajne laski");
Recenzja re8 = new Recenzja(6, "Dobre teksty i bluzgi");
Recenzja re9 = new Recenzja(1, "Za szybko miś się kończy");
titanic.getRecenzje().add(re1);
titanic.getRecenzje().add(re2);
katyn.getRecenzje().add(re3);
katyn.getRecenzje().add(re4);
mis.getRecenzje().add(re5);
mis.getRecenzje().add(re9);
mafia.getRecenzje().add(re6);
mafia.getRecenzje().add(re7);
mafia.getRecenzje().add(re8);
List<Film> filmy= new ArrayList<Film>();
filmy.add(titanic);
filmy.add(katyn);
filmy.add(mis);
filmy.add(mafia);
filmy.add(terminator);
//wypisz przy pomocy api strumieni wszystkich reżyserów filmów z kolekcji filmy
filmy.stream().map(f-> f.getRezyser()).forEach(r-> System.out.println(r));
//pogrupuj filmy do mapy według rezysera (reżyser - lista filmów)
Map<Rezyser, List<Film>> mapa = filmy.stream().collect(Collectors.groupingBy(f-> f.getRezyser()));
Map<Rezyser, List<Film>> map2 = filmy.stream().collect(Collectors.groupingBy(Film::getRezyser));// to jest to samo co linia powyżej tylko inne wyrażenie lambda
mapa.forEach((r, lista)->{
System.out.println(r);
lista.forEach(f-> System.out.println(f));
});
//pogrupuj filmy po gatunku filmy (gatunek, lista filmów)
Map<GatunekFilmu, List<Film>> mapa3 = filmy.stream().collect(Collectors.groupingBy(f-> f.getGatunek()));
mapa3.forEach((k,v)-> {
System.out.println(k.name());
v.forEach(f-> System.out.println(f));
});
//z listy filmów utwórz listę rezyserów
List<Rezyser> rezyserzy = filmy.stream().map(f-> f.getRezyser()).collect(Collectors.toList());
System.out.println("xxxxxxxxxxxxx");
rezyserzy.forEach(r-> System.out.println(r));
//z listy filmów utwórz listę rezyserów którzy mają na imię Andrzej
List<Rezyser> rezyserzyAndrzeje = filmy.stream()
.map(f-> f.getRezyser())
.filter(r-> r.getImie().equals("Andrzej"))
.collect(Collectors.toList());
rezyserzyAndrzeje.forEach(r-> System.out.println(r));
//sprawdz czy lista filmów zawiera filmy bez recenzji
boolean czySaFilmyBezRecenzji = filmy.stream().anyMatch(f-> {
return f.getRecenzje()!=null && f.getRecenzje().isEmpty() ;
});
String takNie = czySaFilmyBezRecenzji ? "Tak" : "Nie";
System.out.println("Czy mamy filmy bez recenzji "+ takNie);
//policz ile masz filmów sensacyjnych w liście filmów
long sensacyjne = filmy.stream().filter(f-> f.getGatunek().equals(GatunekFilmu.sensacyjny)).count();
System.out.println("Filmy sensacyjne sztuk :"+ sensacyjne);
//powiedz ile wynosi czas trwania wszytskich filmów
Optional<Integer> reduce = filmy.stream()
.map(f-> f.getCzasTrwaniaWMinutach())
.reduce((cz1, cz2)-> cz1+cz2);
Integer reduce2 = filmy.stream()
.map(f-> f.getCzasTrwaniaWMinutach())
.reduce(0,(cz1, cz2)-> cz1+cz2);
if(reduce.isPresent()) {
System.out.println(reduce.get());
}
System.out.println(reduce2);
}
}
| zstekalisz/technik-programista | KolekcjeMetody/src/pl/zste/stream/cwiczenia/CwiczeniaStrumienieGr1.java | 1,850 | //powiedz ile wynosi czas trwania wszytskich filmów | line_comment | pl | package pl.zste.stream.cwiczenia;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.swing.plaf.synth.SynthOptionPaneUI;
public class CwiczeniaStrumienieGr1 {
public static void main(String[] args) {
Rezyser r1 = new Rezyser("James", "Cameron");
Rezyser r2 = new Rezyser("Andrzej", "Wajda");
Rezyser r3 = new Rezyser("Stanisław", "Bareja");
Rezyser r4 = new Rezyser("Patryk", "Vega");
Film titanic = new Film(r1, "Titanic", GatunekFilmu.przygodowy, 160);
Film katyn = new Film(r2, "Katyń", GatunekFilmu.dramat, 90);
Film mis = new Film(r3, "Miś", GatunekFilmu.komedia, 90);
Film mafia = new Film(r4, "Kobiety mafii", GatunekFilmu.sensacyjny, 90);
Film terminator = new Film(r1, "Terminator", GatunekFilmu.sensacyjny, 120);
Recenzja re1 = new Recenzja(1, "Za długi, nudny");
Recenzja re2 = new Recenzja(1, "Nie lubię, taki se");
Recenzja re3 = new Recenzja(6, "Mega mocny, polecam");
Recenzja re4 = new Recenzja(3, "Nie widziałem ale tytuł jest spoko");
Recenzja re5 = new Recenzja(5, "Tylko belfra ten film cieszy");
Recenzja re6 = new Recenzja(6, "Jest mocny");
Recenzja re7 = new Recenzja(5, "Fajne laski");
Recenzja re8 = new Recenzja(6, "Dobre teksty i bluzgi");
Recenzja re9 = new Recenzja(1, "Za szybko miś się kończy");
titanic.getRecenzje().add(re1);
titanic.getRecenzje().add(re2);
katyn.getRecenzje().add(re3);
katyn.getRecenzje().add(re4);
mis.getRecenzje().add(re5);
mis.getRecenzje().add(re9);
mafia.getRecenzje().add(re6);
mafia.getRecenzje().add(re7);
mafia.getRecenzje().add(re8);
List<Film> filmy= new ArrayList<Film>();
filmy.add(titanic);
filmy.add(katyn);
filmy.add(mis);
filmy.add(mafia);
filmy.add(terminator);
//wypisz przy pomocy api strumieni wszystkich reżyserów filmów z kolekcji filmy
filmy.stream().map(f-> f.getRezyser()).forEach(r-> System.out.println(r));
//pogrupuj filmy do mapy według rezysera (reżyser - lista filmów)
Map<Rezyser, List<Film>> mapa = filmy.stream().collect(Collectors.groupingBy(f-> f.getRezyser()));
Map<Rezyser, List<Film>> map2 = filmy.stream().collect(Collectors.groupingBy(Film::getRezyser));// to jest to samo co linia powyżej tylko inne wyrażenie lambda
mapa.forEach((r, lista)->{
System.out.println(r);
lista.forEach(f-> System.out.println(f));
});
//pogrupuj filmy po gatunku filmy (gatunek, lista filmów)
Map<GatunekFilmu, List<Film>> mapa3 = filmy.stream().collect(Collectors.groupingBy(f-> f.getGatunek()));
mapa3.forEach((k,v)-> {
System.out.println(k.name());
v.forEach(f-> System.out.println(f));
});
//z listy filmów utwórz listę rezyserów
List<Rezyser> rezyserzy = filmy.stream().map(f-> f.getRezyser()).collect(Collectors.toList());
System.out.println("xxxxxxxxxxxxx");
rezyserzy.forEach(r-> System.out.println(r));
//z listy filmów utwórz listę rezyserów którzy mają na imię Andrzej
List<Rezyser> rezyserzyAndrzeje = filmy.stream()
.map(f-> f.getRezyser())
.filter(r-> r.getImie().equals("Andrzej"))
.collect(Collectors.toList());
rezyserzyAndrzeje.forEach(r-> System.out.println(r));
//sprawdz czy lista filmów zawiera filmy bez recenzji
boolean czySaFilmyBezRecenzji = filmy.stream().anyMatch(f-> {
return f.getRecenzje()!=null && f.getRecenzje().isEmpty() ;
});
String takNie = czySaFilmyBezRecenzji ? "Tak" : "Nie";
System.out.println("Czy mamy filmy bez recenzji "+ takNie);
//policz ile masz filmów sensacyjnych w liście filmów
long sensacyjne = filmy.stream().filter(f-> f.getGatunek().equals(GatunekFilmu.sensacyjny)).count();
System.out.println("Filmy sensacyjne sztuk :"+ sensacyjne);
//powie<SUF>
Optional<Integer> reduce = filmy.stream()
.map(f-> f.getCzasTrwaniaWMinutach())
.reduce((cz1, cz2)-> cz1+cz2);
Integer reduce2 = filmy.stream()
.map(f-> f.getCzasTrwaniaWMinutach())
.reduce(0,(cz1, cz2)-> cz1+cz2);
if(reduce.isPresent()) {
System.out.println(reduce.get());
}
System.out.println(reduce2);
}
}
|
41914_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 pl.edu.wat.wel.protocoltest;
/**
*
* @author pdaba
*/
public enum CmdType {
RST, // Zdalny reset mikrokontrolera
LED, // Sterowanie I/O do których podłączone są diody LED
RGB, // Sterowanie I/O do których podłączona dioda LED RGB
LCD, // Sterowanie wyświetlaczem LCD
SEG, // Sterowanie wyświetlaczem 7 segmentowym
JOY, // Odczyt stanu joysticka
ACC, // Odczyt wskazań akcelerometru
MAG, // Odczyt wskazań magnetometru
TEM, // Odczyt czujnika temperatury
ADC, // Odczyt naięcia na potencjometrze
MIC, // Odczyt zarejestrowanego sygału z mikrofonu
SPK, // Zapis syganłu na wyjściu Audio Out
MOT, // Sterowanie I/O dla silnika prądu stałego
MEM // Odczyt/zapis do pamięci QSPI
}
| ztc-wel-wat/pkau-lab2-2020 | JavaApp/src/main/java/pl/edu/wat/wel/javaapp/CmdType.java | 341 | // Sterowanie I/O do których podłączone są diody LED | 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 pl.edu.wat.wel.protocoltest;
/**
*
* @author pdaba
*/
public enum CmdType {
RST, // Zdalny reset mikrokontrolera
LED, // Stero<SUF>
RGB, // Sterowanie I/O do których podłączona dioda LED RGB
LCD, // Sterowanie wyświetlaczem LCD
SEG, // Sterowanie wyświetlaczem 7 segmentowym
JOY, // Odczyt stanu joysticka
ACC, // Odczyt wskazań akcelerometru
MAG, // Odczyt wskazań magnetometru
TEM, // Odczyt czujnika temperatury
ADC, // Odczyt naięcia na potencjometrze
MIC, // Odczyt zarejestrowanego sygału z mikrofonu
SPK, // Zapis syganłu na wyjściu Audio Out
MOT, // Sterowanie I/O dla silnika prądu stałego
MEM // Odczyt/zapis do pamięci QSPI
}
|
22464_0 | package QuadTreeAlgorithm;
public class QuadTree {
private Node root;
private static class Node{
private int x; //x,y wpsolrzedne lewego gornego rogu w obszarze w wezle
private int y;
private int width;
private int height;
private int value;
private boolean isLeaf;
private Node[] children;
public Node(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.isLeaf = false;
this.children = new Node[4]; // kazdy moze miec maksymalnie 4 node dzieci
}
}
public QuadTree(int[][] pixels) {
this.root = buildTree(pixels,0,0, pixels.length, pixels[0].length);
}
private Node buildTree(int[][] pixels, int x, int y, int width,int height){
Node node = new Node(x,y,width,height);
//jeśli mamy rozmiar 1x1 oznacza to ze jest pojedynczy piksel lub srednia z pikseli
if(width == 1 && height == 1){
node.value = pixels[x][y];
node.isLeaf = true;
} else {
boolean isSame = true;
int firstValue = pixels[x][y];
for(int i = x; i < x+width; i++){
for(int j = y; j< + height; j++){
if( pixels[x][y] != firstValue){
isSame = false;
break;
}
}
}
if(isSame){
node.isLeaf = true;
node.value = firstValue;
} else {
int halfWidth = width/2;
int halfHeight = height/2;
node.children[0] = buildTree(pixels, x, y, halfWidth, halfHeight);
node.children[1] = buildTree(pixels, x + halfWidth, y, halfWidth, halfHeight);
node.children[2] = buildTree(pixels, x + halfWidth, y + halfHeight, halfWidth, halfHeight);
node.children[3] = buildTree(pixels,x, y + halfHeight, halfWidth, halfHeight);
}
}
return node;
}
}
| zuzaflis/QuadTreeAlgorithm | src/main/java/QuadTreeAlgorithm/QuadTree.java | 655 | //x,y wpsolrzedne lewego gornego rogu w obszarze w wezle | line_comment | pl | package QuadTreeAlgorithm;
public class QuadTree {
private Node root;
private static class Node{
private int x; //x,y w<SUF>
private int y;
private int width;
private int height;
private int value;
private boolean isLeaf;
private Node[] children;
public Node(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.isLeaf = false;
this.children = new Node[4]; // kazdy moze miec maksymalnie 4 node dzieci
}
}
public QuadTree(int[][] pixels) {
this.root = buildTree(pixels,0,0, pixels.length, pixels[0].length);
}
private Node buildTree(int[][] pixels, int x, int y, int width,int height){
Node node = new Node(x,y,width,height);
//jeśli mamy rozmiar 1x1 oznacza to ze jest pojedynczy piksel lub srednia z pikseli
if(width == 1 && height == 1){
node.value = pixels[x][y];
node.isLeaf = true;
} else {
boolean isSame = true;
int firstValue = pixels[x][y];
for(int i = x; i < x+width; i++){
for(int j = y; j< + height; j++){
if( pixels[x][y] != firstValue){
isSame = false;
break;
}
}
}
if(isSame){
node.isLeaf = true;
node.value = firstValue;
} else {
int halfWidth = width/2;
int halfHeight = height/2;
node.children[0] = buildTree(pixels, x, y, halfWidth, halfHeight);
node.children[1] = buildTree(pixels, x + halfWidth, y, halfWidth, halfHeight);
node.children[2] = buildTree(pixels, x + halfWidth, y + halfHeight, halfWidth, halfHeight);
node.children[3] = buildTree(pixels,x, y + halfHeight, halfWidth, halfHeight);
}
}
return node;
}
}
|
84812_3 | package pl.edu.agh.farfromthesun.map;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.openstreetmap.gui.jmapviewer.Coordinate;
import org.openstreetmap.gui.jmapviewer.JMapViewer;
import org.openstreetmap.gui.jmapviewer.JMapViewerTree;
import org.openstreetmap.gui.jmapviewer.MapMarkerDot;
import org.openstreetmap.gui.jmapviewer.events.JMVCommandEvent;
import org.openstreetmap.gui.jmapviewer.interfaces.JMapViewerEventListener;
import pl.edu.agh.farfromthesun.algorithm.AlgorithmObserver;
import pl.edu.agh.farfromthesun.app.Component;
import pl.edu.agh.farfromthesun.forecast.WeatherLocation;
public class Map implements AlgorithmObserver, JMapViewerEventListener, Component {
private List<Coordinate> coordinates = new ArrayList<>();
private List<WeatherLocation> places = new ArrayList<>();
private JMapViewer treeMap;
private boolean listenerFlag = true;
//final Dimension MAP_DIMENSION = new Dimension(700,600);
@Override
public void initialize(JFrame frame) {
treeMap = new JMapViewer();
//treeMap.setPreferredSize(MAP_DIMENSION);
treeMap.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (listenerFlag) {
Point p = e.getPoint();
System.out.println(treeMap.getPosition(p));
addMarker(p);
}
}});
JButton btnDelete = new JButton("Delete");
JButton btnReset = new JButton("Reset");
JPanel container = new JPanel();
btnDelete.addActionListener(e -> deleteLast());
btnReset.addActionListener(e -> {
listenerFlag = true;
treeMap.removeAllMapMarkers();
coordinates.clear();
treeMap.removeAllMapPolygons();
System.out.println("Removed all coordinates");
});
container.add(btnDelete);
container.add(btnReset);
frame.getContentPane().add(treeMap, BorderLayout.CENTER);
frame.getContentPane().add(container, BorderLayout.NORTH);
}
private void addMarker(Point p) {
Coordinate marker = (Coordinate) treeMap.getPosition(p);
treeMap.addMapMarker(new MapMarkerDot(marker));
coordinates.add(marker);
}
//listener methods
/*
deleteLast to listener do btnDelete, przepiac do btnDelete jest zostanie przeniesiony
*/
public void deleteLast() {
if (!listenerFlag) return;
Coordinate c = coordinates.get(coordinates.size()-1);
treeMap.removeAllMapMarkers();
this.coordinates.remove(c);
for (Coordinate cor : coordinates) {
treeMap.addMapMarker(new MapMarkerDot(cor));
}
}
private void drawRoute() {
Coordinate one,two;
List<Coordinate> route;
if (coordinates.isEmpty()) return;
for (int i = 0; i<coordinates.size()-1; i++ ) {
one = coordinates.get(i);
two = coordinates.get(i+1);
route = new ArrayList<>(Arrays.asList(one, two, two));
treeMap.addMapPolygon(new MyMapMarkerArrow(route));
}
}
/*
Tutaj znajduje sie czesc, ktora powinna byc wykonana natcyhmiast po kliknieciu przyisku START
Wysyla do podsystemu Algorithm ArrayList<Loocation> places - wybranych przez uzytkownika lokacji
Dodatkowo ustawia listenerFlag=false - nie mozna dodawac kolejnych punktow
*/
public List<WeatherLocation> sendPlaces() {
listenerFlag = false;
LocationConverter placeConverter = new LocationConverter();
placeConverter.setCoordinates(coordinates);
places = placeConverter.getPlaces();
return places;
}
/*
Tutaj znajduje sie czesc, ktora wykonuje sie po otrzymaniu przez Algorithm
Konwersja Location na Coordinate, rysowanie trasy
*/
@Override
public void handleResults(List<WeatherLocation> locations) {
LocationConverter placeConverter = new LocationConverter();
placeConverter.setPlaces(locations);
coordinates = placeConverter.getCoordinates();
drawRoute();
}
@Override
public void processCommand(JMVCommandEvent command) {
}
} | zuzannachrzastek/far-from-the-sun | src/main/java/pl/edu/agh/farfromthesun/map/Map.java | 1,397 | /*
deleteLast to listener do btnDelete, przepiac do btnDelete jest zostanie przeniesiony
*/ | block_comment | pl | package pl.edu.agh.farfromthesun.map;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.openstreetmap.gui.jmapviewer.Coordinate;
import org.openstreetmap.gui.jmapviewer.JMapViewer;
import org.openstreetmap.gui.jmapviewer.JMapViewerTree;
import org.openstreetmap.gui.jmapviewer.MapMarkerDot;
import org.openstreetmap.gui.jmapviewer.events.JMVCommandEvent;
import org.openstreetmap.gui.jmapviewer.interfaces.JMapViewerEventListener;
import pl.edu.agh.farfromthesun.algorithm.AlgorithmObserver;
import pl.edu.agh.farfromthesun.app.Component;
import pl.edu.agh.farfromthesun.forecast.WeatherLocation;
public class Map implements AlgorithmObserver, JMapViewerEventListener, Component {
private List<Coordinate> coordinates = new ArrayList<>();
private List<WeatherLocation> places = new ArrayList<>();
private JMapViewer treeMap;
private boolean listenerFlag = true;
//final Dimension MAP_DIMENSION = new Dimension(700,600);
@Override
public void initialize(JFrame frame) {
treeMap = new JMapViewer();
//treeMap.setPreferredSize(MAP_DIMENSION);
treeMap.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (listenerFlag) {
Point p = e.getPoint();
System.out.println(treeMap.getPosition(p));
addMarker(p);
}
}});
JButton btnDelete = new JButton("Delete");
JButton btnReset = new JButton("Reset");
JPanel container = new JPanel();
btnDelete.addActionListener(e -> deleteLast());
btnReset.addActionListener(e -> {
listenerFlag = true;
treeMap.removeAllMapMarkers();
coordinates.clear();
treeMap.removeAllMapPolygons();
System.out.println("Removed all coordinates");
});
container.add(btnDelete);
container.add(btnReset);
frame.getContentPane().add(treeMap, BorderLayout.CENTER);
frame.getContentPane().add(container, BorderLayout.NORTH);
}
private void addMarker(Point p) {
Coordinate marker = (Coordinate) treeMap.getPosition(p);
treeMap.addMapMarker(new MapMarkerDot(marker));
coordinates.add(marker);
}
//listener methods
/*
delete<SUF>*/
public void deleteLast() {
if (!listenerFlag) return;
Coordinate c = coordinates.get(coordinates.size()-1);
treeMap.removeAllMapMarkers();
this.coordinates.remove(c);
for (Coordinate cor : coordinates) {
treeMap.addMapMarker(new MapMarkerDot(cor));
}
}
private void drawRoute() {
Coordinate one,two;
List<Coordinate> route;
if (coordinates.isEmpty()) return;
for (int i = 0; i<coordinates.size()-1; i++ ) {
one = coordinates.get(i);
two = coordinates.get(i+1);
route = new ArrayList<>(Arrays.asList(one, two, two));
treeMap.addMapPolygon(new MyMapMarkerArrow(route));
}
}
/*
Tutaj znajduje sie czesc, ktora powinna byc wykonana natcyhmiast po kliknieciu przyisku START
Wysyla do podsystemu Algorithm ArrayList<Loocation> places - wybranych przez uzytkownika lokacji
Dodatkowo ustawia listenerFlag=false - nie mozna dodawac kolejnych punktow
*/
public List<WeatherLocation> sendPlaces() {
listenerFlag = false;
LocationConverter placeConverter = new LocationConverter();
placeConverter.setCoordinates(coordinates);
places = placeConverter.getPlaces();
return places;
}
/*
Tutaj znajduje sie czesc, ktora wykonuje sie po otrzymaniu przez Algorithm
Konwersja Location na Coordinate, rysowanie trasy
*/
@Override
public void handleResults(List<WeatherLocation> locations) {
LocationConverter placeConverter = new LocationConverter();
placeConverter.setPlaces(locations);
coordinates = placeConverter.getCoordinates();
drawRoute();
}
@Override
public void processCommand(JMVCommandEvent command) {
}
} |
35623_5 | import com.espertech.esper.runtime.client.EPEventService;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class InputStream {
private static final String DATA_ROZPOCZECIA = "2001-09-05";
private static final String DATA_ZAKONCZENIA = "2001-09-20";
private static final int LICZBA_PLIKOW = 12;
private static final int MAX_LICZBA_BLEDOW = 5;
private static InformacjeOPliku[] tablicaInformacjiOPlikach = new InformacjeOPliku[LICZBA_PLIKOW];
private static DateFormat df = null;
public void generuj(EPEventService eventService) throws IOException {
tablicaInformacjiOPlikach[0] = new InformacjeOPliku(
"files/tableAPPLE_NASDAQ.csv", "Apple", "NASDAQ");
tablicaInformacjiOPlikach[1] = new InformacjeOPliku(
"files/tableCOCACOLA_NYSE.csv", "CocaCola", "NYSE");
tablicaInformacjiOPlikach[2] = new InformacjeOPliku(
"files/tableDISNEY_NYSE.csv", "Disney", "NYSE");
tablicaInformacjiOPlikach[3] = new InformacjeOPliku(
"files/tableFORD_NYSE.csv", "Ford", "NYSE");
tablicaInformacjiOPlikach[4] = new InformacjeOPliku(
"files/tableGOOGLE_NASDAQ.csv", "Google", "NASDAQ");
tablicaInformacjiOPlikach[5] = new InformacjeOPliku(
"files/tableHONDA_NYSE.csv", "Honda", "NYSE");
tablicaInformacjiOPlikach[6] = new InformacjeOPliku(
"files/tableIBM_NASDAQ.csv", "IBM", "NASDAQ");
tablicaInformacjiOPlikach[7] = new InformacjeOPliku(
"files/tableINTEL_NASDAQ.csv", "Intel", "NASDAQ");
tablicaInformacjiOPlikach[8] = new InformacjeOPliku(
"files/tableMICROSOFT_NASDAQ.csv", "Microsoft", "NASDAQ");
tablicaInformacjiOPlikach[9] = new InformacjeOPliku(
"files/tableORACLE_NASDAQ.csv", "Oracle", "NASDAQ");
tablicaInformacjiOPlikach[10] = new InformacjeOPliku(
"files/tablePEPSICO_NYSE.csv", "PepsiCo", "NYSE");
tablicaInformacjiOPlikach[11] = new InformacjeOPliku(
"files/tableYAHOO_NASDAQ.csv", "Yahoo", "NASDAQ");
ReverseLineReader[] readers = new ReverseLineReader[LICZBA_PLIKOW];
try {
for (int i = 0; i < LICZBA_PLIKOW; i++) {
readers[i] = new ReverseLineReader(new File(
tablicaInformacjiOPlikach[i].getNazwaPliku()), "UTF-8");
}
} catch (FileNotFoundException e) {
System.err.println("Nie odnaleziono pliku");
System.exit(1);
}
Date dataRozpoczecia = null;
Date dataZakonczenia = null;
try {
df = new SimpleDateFormat("yyyy-MM-dd");
dataRozpoczecia = df.parse(DATA_ROZPOCZECIA);
dataZakonczenia = df.parse(DATA_ZAKONCZENIA);
} catch (ParseException e) {
System.err.println("Nie udalo się wczytac podanych dat rozpoczecia i zakonczenia!");
System.exit(1);
}
String[] linie = new String[LICZBA_PLIKOW];
// Przesuniecie do pierwszych notowan z zakresu dat
String[] splitResult = null;
for (int i = 0; i < LICZBA_PLIKOW; i++) {
while ((linie[i] = readers[i].readLine()) != null) {
splitResult = linie[i].split(",");
Date dataNotowania = null;
try {
dataNotowania = df.parse(splitResult[0]);
if (dataNotowania.compareTo(dataRozpoczecia) >= 0) {
break;
}
} catch (Exception e) {
}
}
}
Date iteratorDaty = dataRozpoczecia;
// Glowna petla
int liczbaBledow = 0;
while ((iteratorDaty.compareTo(dataZakonczenia) <= 0)
&& (liczbaBledow < MAX_LICZBA_BLEDOW)) {
for (int i = 0; i < LICZBA_PLIKOW; i++) {
try {
Date dataNotowania = wyodrebnijDate(linie[i]);
if (dataNotowania == null) {
continue;
}
if ((dataNotowania.compareTo(iteratorDaty) == -1)) {
// Data ostatnio wczytanego notowania wczesniejsza niz
// biezaca data - pobierz kolejne notowanie!
if ((linie[i] = readers[i].readLine()) != null) {
dataNotowania = wyodrebnijDate(linie[i]);
}
} else if ((dataNotowania.compareTo(iteratorDaty) == 1)) {
// Data ostatnio wczytanego notowania poniejsza niz
// biezaca data - czekaj!
continue;
}
if ((dataNotowania != null) && (dataNotowania.equals(iteratorDaty))) {
// Tworzenie obiektu notowania
splitResult = linie[i].split(",");
KursAkcji kurs = new KursAkcji(
tablicaInformacjiOPlikach[i].getNazwaSpolki(),
tablicaInformacjiOPlikach[i].getNazwaMarketu(),
dataNotowania,
Float.valueOf(splitResult[1].trim()),
Float.valueOf(splitResult[2].trim()),
Float.valueOf(splitResult[3].trim()),
Float.valueOf(splitResult[4].trim()),
Float.valueOf(splitResult[5].trim()));
eventService.sendEventBean(kurs, kurs.getClass().getName());
}
} catch (Exception e) {
liczbaBledow++;
System.err.println("Blad parsowania! [" + linie[i] + "]. Po raz: " + liczbaBledow);
if (liczbaBledow >= MAX_LICZBA_BLEDOW) {
System.err.println("Za duzo bledow!");
break;
}
}
}
// Inkrementacja daty
iteratorDaty = inkrementujDate(iteratorDaty);
}
}
// Metody pomocnicze
private static Date inkrementujDate(Date data) {
Calendar c = Calendar.getInstance();
c.setTime(data);
c.add(Calendar.DATE, 1);
return c.getTime();
}
private static Date wyodrebnijDate(String linia) {
String[] splitResult = linia.split(",");
if (!splitResult[0].equals("Date")) {
try {
return df.parse(splitResult[0]);
} catch (ParseException e) {
}
}
return null;
}
// Klasa pomocnicza
private static class InformacjeOPliku {
private String nazwaPliku;
private String nazwaSpolki;
private String nazwaMarketu;
public InformacjeOPliku(String nazwaPliku, String nazwaSpolki, String nazwaMarketu) {
this.nazwaPliku = nazwaPliku;
this.nazwaSpolki = nazwaSpolki;
this.nazwaMarketu = nazwaMarketu;
}
public String getNazwaPliku() {
return nazwaPliku;
}
public String getNazwaSpolki() {
return nazwaSpolki;
}
public String getNazwaMarketu() {
return nazwaMarketu;
}
}
// Klasa pomocnicza
// AUTOR: WhiteFang34
// ZRODO: http://stackoverflow.com/questions/6011345/read-a-file-line-by-line-in-reverse-order
private static class ReverseLineReader {
private static final int BUFFER_SIZE = 8192;
private final FileChannel channel;
private final String encoding;
private long filePos;
private ByteBuffer buf;
private int bufPos;
private byte lastLineBreak = '\n';
private ByteArrayOutputStream baos = new ByteArrayOutputStream();
public ReverseLineReader(File file, String encoding) throws IOException {
RandomAccessFile raf = new RandomAccessFile(file, "r");
channel = raf.getChannel();
filePos = raf.length();
this.encoding = encoding;
}
public String readLine() throws IOException {
while (true) {
if (bufPos < 0) {
if (filePos == 0) {
if (baos == null) {
return null;
}
String line = bufToString();
baos = null;
return line;
}
long start = Math.max(filePos - BUFFER_SIZE, 0);
long end = filePos;
long len = end - start;
buf = channel.map(FileChannel.MapMode.READ_ONLY, start, len);
bufPos = (int) len;
filePos = start;
}
while (bufPos-- > 0) {
byte c = buf.get(bufPos);
if (c == '\r' || c == '\n') {
if (c != lastLineBreak) {
lastLineBreak = c;
continue;
}
lastLineBreak = c;
return bufToString();
}
baos.write(c);
}
}
}
private String bufToString() throws UnsupportedEncodingException {
if (baos.size() == 0) {
return "";
}
byte[] bytes = baos.toByteArray();
for (int i = 0; i < bytes.length / 2; i++) {
byte t = bytes[i];
bytes[i] = bytes[bytes.length - i - 1];
bytes[bytes.length - i - 1] = t;
}
baos.reset();
return new String(bytes, encoding);
}
}
} | zuznnjus/ZTPD | Esper-projekt/src/main/java/InputStream.java | 3,151 | // biezaca data - czekaj!
| line_comment | pl | import com.espertech.esper.runtime.client.EPEventService;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class InputStream {
private static final String DATA_ROZPOCZECIA = "2001-09-05";
private static final String DATA_ZAKONCZENIA = "2001-09-20";
private static final int LICZBA_PLIKOW = 12;
private static final int MAX_LICZBA_BLEDOW = 5;
private static InformacjeOPliku[] tablicaInformacjiOPlikach = new InformacjeOPliku[LICZBA_PLIKOW];
private static DateFormat df = null;
public void generuj(EPEventService eventService) throws IOException {
tablicaInformacjiOPlikach[0] = new InformacjeOPliku(
"files/tableAPPLE_NASDAQ.csv", "Apple", "NASDAQ");
tablicaInformacjiOPlikach[1] = new InformacjeOPliku(
"files/tableCOCACOLA_NYSE.csv", "CocaCola", "NYSE");
tablicaInformacjiOPlikach[2] = new InformacjeOPliku(
"files/tableDISNEY_NYSE.csv", "Disney", "NYSE");
tablicaInformacjiOPlikach[3] = new InformacjeOPliku(
"files/tableFORD_NYSE.csv", "Ford", "NYSE");
tablicaInformacjiOPlikach[4] = new InformacjeOPliku(
"files/tableGOOGLE_NASDAQ.csv", "Google", "NASDAQ");
tablicaInformacjiOPlikach[5] = new InformacjeOPliku(
"files/tableHONDA_NYSE.csv", "Honda", "NYSE");
tablicaInformacjiOPlikach[6] = new InformacjeOPliku(
"files/tableIBM_NASDAQ.csv", "IBM", "NASDAQ");
tablicaInformacjiOPlikach[7] = new InformacjeOPliku(
"files/tableINTEL_NASDAQ.csv", "Intel", "NASDAQ");
tablicaInformacjiOPlikach[8] = new InformacjeOPliku(
"files/tableMICROSOFT_NASDAQ.csv", "Microsoft", "NASDAQ");
tablicaInformacjiOPlikach[9] = new InformacjeOPliku(
"files/tableORACLE_NASDAQ.csv", "Oracle", "NASDAQ");
tablicaInformacjiOPlikach[10] = new InformacjeOPliku(
"files/tablePEPSICO_NYSE.csv", "PepsiCo", "NYSE");
tablicaInformacjiOPlikach[11] = new InformacjeOPliku(
"files/tableYAHOO_NASDAQ.csv", "Yahoo", "NASDAQ");
ReverseLineReader[] readers = new ReverseLineReader[LICZBA_PLIKOW];
try {
for (int i = 0; i < LICZBA_PLIKOW; i++) {
readers[i] = new ReverseLineReader(new File(
tablicaInformacjiOPlikach[i].getNazwaPliku()), "UTF-8");
}
} catch (FileNotFoundException e) {
System.err.println("Nie odnaleziono pliku");
System.exit(1);
}
Date dataRozpoczecia = null;
Date dataZakonczenia = null;
try {
df = new SimpleDateFormat("yyyy-MM-dd");
dataRozpoczecia = df.parse(DATA_ROZPOCZECIA);
dataZakonczenia = df.parse(DATA_ZAKONCZENIA);
} catch (ParseException e) {
System.err.println("Nie udalo się wczytac podanych dat rozpoczecia i zakonczenia!");
System.exit(1);
}
String[] linie = new String[LICZBA_PLIKOW];
// Przesuniecie do pierwszych notowan z zakresu dat
String[] splitResult = null;
for (int i = 0; i < LICZBA_PLIKOW; i++) {
while ((linie[i] = readers[i].readLine()) != null) {
splitResult = linie[i].split(",");
Date dataNotowania = null;
try {
dataNotowania = df.parse(splitResult[0]);
if (dataNotowania.compareTo(dataRozpoczecia) >= 0) {
break;
}
} catch (Exception e) {
}
}
}
Date iteratorDaty = dataRozpoczecia;
// Glowna petla
int liczbaBledow = 0;
while ((iteratorDaty.compareTo(dataZakonczenia) <= 0)
&& (liczbaBledow < MAX_LICZBA_BLEDOW)) {
for (int i = 0; i < LICZBA_PLIKOW; i++) {
try {
Date dataNotowania = wyodrebnijDate(linie[i]);
if (dataNotowania == null) {
continue;
}
if ((dataNotowania.compareTo(iteratorDaty) == -1)) {
// Data ostatnio wczytanego notowania wczesniejsza niz
// biezaca data - pobierz kolejne notowanie!
if ((linie[i] = readers[i].readLine()) != null) {
dataNotowania = wyodrebnijDate(linie[i]);
}
} else if ((dataNotowania.compareTo(iteratorDaty) == 1)) {
// Data ostatnio wczytanego notowania poniejsza niz
// bieza<SUF>
continue;
}
if ((dataNotowania != null) && (dataNotowania.equals(iteratorDaty))) {
// Tworzenie obiektu notowania
splitResult = linie[i].split(",");
KursAkcji kurs = new KursAkcji(
tablicaInformacjiOPlikach[i].getNazwaSpolki(),
tablicaInformacjiOPlikach[i].getNazwaMarketu(),
dataNotowania,
Float.valueOf(splitResult[1].trim()),
Float.valueOf(splitResult[2].trim()),
Float.valueOf(splitResult[3].trim()),
Float.valueOf(splitResult[4].trim()),
Float.valueOf(splitResult[5].trim()));
eventService.sendEventBean(kurs, kurs.getClass().getName());
}
} catch (Exception e) {
liczbaBledow++;
System.err.println("Blad parsowania! [" + linie[i] + "]. Po raz: " + liczbaBledow);
if (liczbaBledow >= MAX_LICZBA_BLEDOW) {
System.err.println("Za duzo bledow!");
break;
}
}
}
// Inkrementacja daty
iteratorDaty = inkrementujDate(iteratorDaty);
}
}
// Metody pomocnicze
private static Date inkrementujDate(Date data) {
Calendar c = Calendar.getInstance();
c.setTime(data);
c.add(Calendar.DATE, 1);
return c.getTime();
}
private static Date wyodrebnijDate(String linia) {
String[] splitResult = linia.split(",");
if (!splitResult[0].equals("Date")) {
try {
return df.parse(splitResult[0]);
} catch (ParseException e) {
}
}
return null;
}
// Klasa pomocnicza
private static class InformacjeOPliku {
private String nazwaPliku;
private String nazwaSpolki;
private String nazwaMarketu;
public InformacjeOPliku(String nazwaPliku, String nazwaSpolki, String nazwaMarketu) {
this.nazwaPliku = nazwaPliku;
this.nazwaSpolki = nazwaSpolki;
this.nazwaMarketu = nazwaMarketu;
}
public String getNazwaPliku() {
return nazwaPliku;
}
public String getNazwaSpolki() {
return nazwaSpolki;
}
public String getNazwaMarketu() {
return nazwaMarketu;
}
}
// Klasa pomocnicza
// AUTOR: WhiteFang34
// ZRODO: http://stackoverflow.com/questions/6011345/read-a-file-line-by-line-in-reverse-order
private static class ReverseLineReader {
private static final int BUFFER_SIZE = 8192;
private final FileChannel channel;
private final String encoding;
private long filePos;
private ByteBuffer buf;
private int bufPos;
private byte lastLineBreak = '\n';
private ByteArrayOutputStream baos = new ByteArrayOutputStream();
public ReverseLineReader(File file, String encoding) throws IOException {
RandomAccessFile raf = new RandomAccessFile(file, "r");
channel = raf.getChannel();
filePos = raf.length();
this.encoding = encoding;
}
public String readLine() throws IOException {
while (true) {
if (bufPos < 0) {
if (filePos == 0) {
if (baos == null) {
return null;
}
String line = bufToString();
baos = null;
return line;
}
long start = Math.max(filePos - BUFFER_SIZE, 0);
long end = filePos;
long len = end - start;
buf = channel.map(FileChannel.MapMode.READ_ONLY, start, len);
bufPos = (int) len;
filePos = start;
}
while (bufPos-- > 0) {
byte c = buf.get(bufPos);
if (c == '\r' || c == '\n') {
if (c != lastLineBreak) {
lastLineBreak = c;
continue;
}
lastLineBreak = c;
return bufToString();
}
baos.write(c);
}
}
}
private String bufToString() throws UnsupportedEncodingException {
if (baos.size() == 0) {
return "";
}
byte[] bytes = baos.toByteArray();
for (int i = 0; i < bytes.length / 2; i++) {
byte t = bytes[i];
bytes[i] = bytes[bytes.length - i - 1];
bytes[bytes.length - i - 1] = t;
}
baos.reset();
return new String(bytes, encoding);
}
}
} |
36849_0 | package com.kodilla.exception.test;
import java.util.HashMap;
import java.util.Map;
public class MainFindFlight {
public static void main(String[] args) {
FindFlight find = new FindFlight();
try {
Map<Flight, Boolean> zx = find.findFlight(new Flight("Chopina", "Kopernika"));
zx.entrySet().stream()
.map(entry -> entry.getKey() + ", " + entry.getValue())
.forEach(System.out::println);
}catch (RouteNotFoundException e){
System.out.println("Nie ma połączenia");
}
/**
* Nie wiem jak zaimplementować tą logikę które będzie rozróżniła czy danie połączenie jest true czy false. Czy mam
* zrobić if-a i na sztywno przypisać połączenia, które są true ? Czy jak inaczej to zrobić ? Nie jestem też pewnien czy
* Flight jako klucz w Map to dobry pomysł. Ogólnie wsadziłem jakąś logikę żeby obsłużyć wyjątki ale jest ona
* niezgodna z treścią zadania. Będę wdzięczny za wskazówkę.
* JK
*/
}
}
| zxkuba/kodilla_course | kodilla-exception/src/main/java/com/kodilla/exception/test/MainFindFlight.java | 352 | /**
* Nie wiem jak zaimplementować tą logikę które będzie rozróżniła czy danie połączenie jest true czy false. Czy mam
* zrobić if-a i na sztywno przypisać połączenia, które są true ? Czy jak inaczej to zrobić ? Nie jestem też pewnien czy
* Flight jako klucz w Map to dobry pomysł. Ogólnie wsadziłem jakąś logikę żeby obsłużyć wyjątki ale jest ona
* niezgodna z treścią zadania. Będę wdzięczny za wskazówkę.
* JK
*/ | block_comment | pl | package com.kodilla.exception.test;
import java.util.HashMap;
import java.util.Map;
public class MainFindFlight {
public static void main(String[] args) {
FindFlight find = new FindFlight();
try {
Map<Flight, Boolean> zx = find.findFlight(new Flight("Chopina", "Kopernika"));
zx.entrySet().stream()
.map(entry -> entry.getKey() + ", " + entry.getValue())
.forEach(System.out::println);
}catch (RouteNotFoundException e){
System.out.println("Nie ma połączenia");
}
/**
* Nie wi<SUF>*/
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.