# data[].attributes.body
https://www.w3schools.com/python/python_tuples.asp

https://www.w3schools.com/python/python_lists.asp

# data[].attributes.attachment_link.readable_text
mylist = ["apple", "banana", "cherry"]

List

Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.

Lists are created using square brackets:

List Items

List items are ordered, changeable, and allow duplicate values.

List items are indexed, the first item has index [0], the second item has index[1] etc.

Ordered

When we say that lists are ordered, it means that the items have a defined order, and that order will not change.

If you add new items to a list, the new items will be placed at the end of the list.

Note: There are some list methods that will change the order, but in general: the order of the items will not change.

Changeable

The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.

Allow Duplicates

Since lists are indexed, lists can have items with the same value:

List Length

To determine how many items a list has, use the len() function:

List Items - Data Types

List items can be of any data type:

Example

String, int and boolean data types:

Try it Yourself "

A list can contain different data types:

Example

A list with strings, integers and boolean values:

Try it Yourself "

type()

From Python's perspective, lists are defined as objects with the data type 'list':

The list() Constructor

It is also possible to use the list() constructor when creating a new list.

Example

Using the list() constructor to make a List:

Try it Yourself "

Python Collections (Arrays)

There are four collection data types in the Python programming language:

List is a collection which is ordered and changeable. Allows duplicate members.

Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.

Dictionary is a collection which is ordered** and changeable. No duplicate members.

*Set items are unchangeable, but you can remove and/or add items whenever you like.

**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type for a particular data set could mean retention of meaning, and, it could mean an increase in efficiency or security.

# data[].attributes.attachment_link.description
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

# data[].attributes.body
https://stackoverflow.com/questions/53740820/how-do-i-add-a-tooltip-to-a-rectangular-region-of-a-javafx-canvas

# data[].attributes.body
1. Java od podstaw - poniedziałek 15:30.
2. Java dla średnio-zaawansowanych - wtorek 15:30.
3. C++ od podstaw - piątek 14:45.
4. C++ kontynuacja - czwartek 15:45.
Aby brać udział w zajęciach C++ trzeba się skontaktować z Panem Głuski (email na drzwiach do sali 22).

# data[].attributes.attachment_link.readable_text
package sample;

import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.util.List;

public class Main extends Application {
    static final int SIZE = 800;
    final int STARS = 30;
    final int MAX_STARS_WEIGHT = 1_000;
    final double MAX_STARS_VELOCITY = 1;

    AnchorPane root = new AnchorPane();
    {
        for (int i = 0; i < STARS; i++) {
            root.getChildren().add(new Star());
        }
        ((Star) root.getChildren().get(0)).setFill(Color.RED);
//        ((Star) root.getChildren().get(0)).setCenterX(300);
//        ((Star) root.getChildren().get(0)).setCenterY(100);
        ((Star) root.getChildren().get(0)).m = 1000;
        ((Star) root.getChildren().get(0)).setRadius(10);

        ((Star) root.getChildren().get(1)).setFill(Color.GREEN);
//        ((Star) root.getChildren().get(1)).setCenterX(100);
//        ((Star) root.getChildren().get(1)).setCenterY(300);
        ((Star) root.getChildren().get(1)).m = 500;
        ((Star) root.getChildren().get(1)).setRadius(5);
    }

    class Star extends Circle {
        double m, vx, vy, vxTemp, vyTemp;
        public Star() {
            super(Math.random() * SIZE, Math.random() * SIZE, 10);
            m = Math.random() * MAX_STARS_WEIGHT;
            this.setRadius(m / MAX_STARS_WEIGHT * 20);
            this.setFill(new Color(m/MAX_STARS_WEIGHT, 0,1,1 ));
            vx = Math.random() * MAX_STARS_VELOCITY - MAX_STARS_VELOCITY / 2;
            vy = Math.random() * MAX_STARS_VELOCITY - MAX_STARS_VELOCITY / 2;
        }
    }

    @Override
    public void start(Stage primaryStage) throws Exception{
        Scene scene = new Scene(root, SIZE, SIZE);
        primaryStage.setScene(scene);
        primaryStage.show();

        Timeline timeline = new Timeline(new KeyFrame(Duration.millis(100), event -> {
            //iterate();
            calcGravity(root.getChildren());
            applyChanges(root.getChildren());
        }));
        timeline.setCycleCount(Animation.INDEFINITE);
        timeline.play();
    }

    private void calcGravity(Star star, Star other) {
        double r = Math.pow(star.getCenterX() - other.getCenterX(), 2)
                + Math.pow(star.getCenterY() - other.getCenterY(), 2);
        double theta = Math.asin(Math.abs(star.getCenterY() - other.getCenterY())
                / Math.sqrt(r));
        System.out.println(Math.toDegrees(theta));
        double scale = star.m * other.m / (star.m + other.m) / 100;
        star.vxTemp += other.m * scale * Math.cos(theta) / r;
        star.vyTemp += other.m * scale * Math.sin(theta) / r;
        other.vxTemp -= star.m * scale * Math.cos(theta) / r;
        other.vyTemp -= star.m * scale * Math.sin(theta) / r;
    }

    private void calcGravity2(Star star, Star other) {
        double x = other.getCenterX() - star.getCenterX();
        double y = other.getCenterY() - star.getCenterY();
        double scale = star.m * other.m / (star.m + other.m) / 1000000000;

        star.vxTemp += other.m * scale * x;
        star.vyTemp += other.m * scale * y;
        other.vxTemp -= star.m * scale * x;
        other.vyTemp -= star.m * scale * y;
    }

    private void calcGravity(ObservableList<Node> stars) {
        for (int i = 0; i < stars.size(); i++) {
            for (int j = i + 1; j < stars.size(); j++) {
                calcGravity2((Star) stars.get(i), (Star) stars.get(j));
            }
        }
    }

    private void applyChanges(ObservableList<Node> stars) {
        for (Node n: stars) {
            Star s = (Star) n;
            s.vx += s.vxTemp;
            s.vxTemp = 0;
            s.setCenterX(s.getCenterX() + s.vx);
            s.vy += s.vyTemp;
            s.vyTemp = 0;
            s.setCenterY(s.getCenterY() + s.vy);
            System.out.println(s.vx + " " + s.vy);
        }
    }

    private void iterate() {
        double totalMass = 0;
        double totalX = 0;
        double totalY = 0;
        for (Node node : root.getChildren()) {
            if (node instanceof Star) {
                Star star = (Star) node;
                totalMass += star.m;
                totalX += star.getCenterX() * star.m;
                totalY += star.getCenterY() * star.m;
            }
        }
        double centerX = totalX / totalMass;
        double centerY = totalY / totalMass;

        for (Node node : root.getChildren()) {
            if (node instanceof Star) {
                Star star = (Star) node;
                star.setCenterX(star.getCenterX() + star.vx);
                star.setCenterY(star.getCenterY() + star.vy);
           }
        }
    }
    private double[] getGravitationalForce(Star star, Star other) {
        return null;
    }

    public static void main(String[] args) {
        launch(args);
    }
}

# data[].attributes.attachment_link.readable_text
package sample;

import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Main extends Application {
    static final int SIZE = 800;
    final int STARS = 10_000;
    final int MAX_STARS_WEIGHT = 10;
    final double MAX_STARS_VELOCITY = 6;

    AnchorPane root = new AnchorPane();
    {
        for (int i = 0; i < STARS; i++) {
            root.getChildren().add(new Star());
        }
    }

    class Star extends Circle {
        double m, vx, vy;
        public Star() {
            super(Math.random() * SIZE, Math.random() * SIZE, 1);
            m = Math.random() * MAX_STARS_WEIGHT;
            this.setFill(new Color(m/MAX_STARS_WEIGHT, 0,1,1 ));
            vx = Math.random() * MAX_STARS_VELOCITY - MAX_STARS_VELOCITY / 2;
            vy = Math.random() * MAX_STARS_VELOCITY - MAX_STARS_VELOCITY / 2;
        }
    }

    @Override
    public void start(Stage primaryStage) throws Exception{
        Scene scene = new Scene(root, SIZE, SIZE);
        primaryStage.setScene(scene);
        primaryStage.show();

        Timeline timeline = new Timeline(new KeyFrame(Duration.millis(100), event -> {
            iterate();
        }));
        timeline.setCycleCount(Animation.INDEFINITE);
        timeline.play();
    }

    private void iterate() {
        double totalMass = 0;
        double totalX = 0;
        double totalY = 0;
        for (Node node : root.getChildren()) {
            if (node instanceof Star) {
                Star star = (Star) node;
                totalMass += star.m;
                totalX += star.getCenterX() * star.m;
                totalY += star.getCenterY() * star.m;
            }
        }
        double centerX = totalX / totalMass;
        double centerY = totalY / totalMass;

        for (Node node : root.getChildren()) {
            if (node instanceof Star) {
                Star star = (Star) node;
                star.setCenterX(star.getCenterX() + star.vx);
                star.setCenterY(star.getCenterY() + star.vy);
           }
        }
    }
    private double[] getGravitationalForce(Star star, Star other) {
        return null;
    }

    public static void main(String[] args) {
        launch(args);
    }
}

# data[].attributes.body
<!--database dependencies -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

# data[].attributes.attachment_link.title
Building Modern Web Apps with Spring Boot and Vaadin

# data[].attributes.attachment_link.title
Mobile optimized UI components for your web app | Vaadin

# data[].attributes.attachment_link.description
A modern library of mobile-friendly UI components for the web. Customizable styling and WAI-ARIA support. Works in all frontend frameworks.

# data[].attributes.attachment_link.readable_text
In computer science and mathematics, the Josephus problem (or Josephus permutation) is a theoretical problem related to a certain counting-out game.

People are standing in a circle waiting to be executed. Counting begins at a specified point in the circle and proceeds around the circle in a specified direction. After a specified number of people are skipped, the next person is executed. The procedure is repeated with the remaining people, starting with the next person, going in the same direction and skipping the same number of people, until only one person remains, and is freed.

The problem - given the number of people, starting point, direction, and number to be skipped - is to choose the position in the initial circle to avoid execution.

The problem is named after Flavius Josephus, a Jewish historian living in the 1st century. According to Josephus' account of the siege of Yodfat, he and his 40 soldiers were trapped in a cave by Roman soldiers. They chose suicide over capture, and settled on a serial method of committing suicide by drawing lots. Josephus states that by luck or possibly by the hand of God, he and another man remained until the end and surrendered to the Romans rather than killing themselves. This is the story given in Book 3, Chapter 8, part 7 of Josephus' The Jewish War (writing of himself in the third person):

However, in this extreme distress, he was not destitute of his usual sagacity; but trusting himself to the providence of God, he put his life into hazard [in the manner following]: "And now," said he, "since it is resolved among you that you will die, come on, let us commit our mutual deaths to determination by lot. He whom the lot falls to first, let him be killed by him that hath the second lot, and thus fortune shall make its progress through us all; nor shall any of us perish by his own right hand, for it would be unfair if, when the rest are gone, somebody should repent and save himself." This proposal appeared to them to be very just; and when he had prevailed with them to determine this matter by lots, he drew one of the lots for himself also. He who had the first lot laid his neck bare to him that had the next, as supposing that the general would die among them immediately; for they thought death, if Josephus might but die with them, was sweeter than life; yet was he with another left to the last, whether we must say it happened so by chance, or whether by the providence of God. And as he was very desirous neither to be condemned by the lot, nor, if he had been left to the last, to imbrue his right hand in the blood of his countrymen, he persuaded him to trust his fidelity to him, and to live as well as himself.

The details of the mechanism used in this feat are rather vague. According to James Dowdy and Michael Mays, in 1612 Claude Gaspard Bachet de Méziriac suggested the specific mechanism of arranging the men in a circle and counting by threes to determine the order of elimination. This story has been often repeated and the specific details vary considerably from source to source. For instance, Israel Nathan Herstein and Irving Kaplansky (1974) have Josephus and 39 comrades stand in a circle with every seventh man eliminated. A history of the problem can be found in S. L. Zabell's Letter to the editor of the Fibonacci Quarterly.

Josephus had an accomplice; the problem was then to find the places of the two last remaining survivors (whose conspiracy would ensure their survival). It is alleged that he placed himself and the other man in the 31st and 16th place respectively.

A medieval version of the Josephus problem involves 15 Turks and 15 Christians aboard a ship in a storm which will sink unless half the passengers are thrown overboard. All 30 stand in a circle and every ninth person is to be tossed into the sea. Where should the Christians stand to ensure that only the Turks are tossed? In other versions the roles of Turks and Christians are interchanged.

In Concrete Mathematics: A Foundation for Computer Science, Graham, Knuth and Patashnik describe and study a "standard" variant: Determine where the last survivor stands if there are n people to start and every second person (k = 2 below) is eliminated.

A generalization of this problem is as follows. We suppose that every mth person will be executed from a group of size n, in which the pth person is the survivor. If there is an addition of x people to the circle, then the survivor is in the -th position if this is less than or equal to . If x is the smallest value for which , then the survivor is in position .

In the following, denotes the number of people in the initial circle, and denotes the count for each step, that is, people are skipped and the -th is executed. The people in the circle are numbered from to .

We explicitly solve the problem when every second person will be killed, i.e. . (For the more general case , we outline a solution below.) We express the solution recursively. Let denote the position of the survivor when there are initially people (and ). The first time around the circle, all of the even-numbered people die. The second time around the circle, the new 2nd person dies, then the new 4th person, etc.; it's as though there were no first time around the circle.

If the initial number of people was even, then the person in position during the second time around the circle was originally in position (for every choice of ). Let . The person at who will now survive was originally in position . This gives us the recurrence

If the initial number of people was odd, then we think of person 1 as dying at the end of the first time around the circle. Again, during the second time around the circle, the new 2nd person dies, then the new 4th person, etc. In this case, the person in position was originally in position . This gives us the recurrence

When we tabulate the values of and we see a pattern: OEIS: A006257

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

1

1

3

1

3

5

7

1

3

5

7

9

11

13

15

1

This suggests that is an increasing odd sequence that restarts with whenever the index n is a power of 2. Therefore, if we choose m and l so that and , then . It is clear that values in the table satisfy this equation. Or we can think that after people are dead there are only people and we go to the th person. He must be the survivor. So . Below, we give a proof by induction.

Theorem: If and , then .

Proof: We use strong induction on . The base case is true. We consider separately the cases when is even and when is odd.

If is even, then choose and such that and . Note that . We have , where the second equality follows from the induction hypothesis.

If is odd, then choose and such that and . Note that . We have , where the second equality follows from the induction hypothesis. This completes the proof.

We can solve for to get an explicit expression for :

The most elegant form of the answer involves the binary representation of size : can be obtained by a one-bit left cyclic shift of itself. If we represent in binary as , then the solution is given by . The proof of this follows from the representation of as or from the above expression for .

Implementation: If n denotes the number of people, the safe position is given by the function ,where and .

Now if we represent the number in binary format, the first bit denotes and remaining bits will denote . For example, when n=41, its binary representation is

n = 1 0 1 0 0 1

2m = 1 0 0 0 0 0
l = 0 1 0 0 1
The easiest way to find the safe position is by using bitwise operators. In this approach, shifting the most-significant set bit of n to the least significant bit will return the safe position. Input must be a positive integer.

n = 1 0 1 0 0 1
n = 0 1 0 0 1 1
In 1997, Lorenz Halbeisen and Norbert Hungerbühler discovered a closed-form for the case . They showed that there is a certain constant

that can be computed to arbitrary precision. Given this constant, choose to be the greatest integer such that (this will be either or ). Then, then the final survivor is

if we rounded up else

for all .

As an example computation, Halbeisen and Hungerbühler give (which is actually the original formulation of Josephus' problem). They compute:

and therefore

(note that we rounded down)

We can verify this looking at each successive pass on the numbers through :

The general case

Dynamic programming is used to solve this problem in the general case by performing the first step and then using the solution of the remaining problem. When the index starts from one, then the person at shifts from the first person is in position , where n is the total number of persons. Let denote the position of the survivor. After the -th person is killed, we're left with a circle of , and we start the next count with the person whose number in the original problem was . The position of the survivor in the remaining circle would be if we start counting at ; shifting this to account for the fact that we're starting at yields the recurrence[12]

which takes the simpler form

if we number the positions from to instead.

This approach has running time , but for small and large there is another approach. The second approach also uses dynamic programming but has running time . It is based on considering killing k-th, 2 k-th, ..., -th people as one step, then changing the numbering.[citation needed ]

This improved approach takes the form

Robinson, W. J. (1960). "The Josephus problem". Math. Gazette. 44 (347): 47-52. doi:10.2307/3608532. JSTOR 3608532.

Woodhouse, David (1973). "The extended Josephus problem". Rev. Mat. Hisp.-Amer. 33 (4): 207-218.

Jakóbczyk, F. (1973). "On the generalized Josephus problem". Glasow Math. J. 14 (2): 168-173. doi:10.1017/S0017089500001919.

Lloyd, Errol L. (1983). "An O(n logm) algorithm for the Josephus Problem". J. Algor. 4 (3): 262-270. doi:10.1016/0196-6774(83)90025-1.

Dowdy, James; Mays, Michael E. (1989). "Josephus Permutations". Journal of Combinatorial Mathematics and Combinatorial Computing. 6: 125-130.

Odlyzko, Andrew M.; Wilf, Herbert S. (1991). "Functional iteration and the Josephus problem". Glasgow Math. J. 33 (2): 235-240. doi:10.1017/S0017089500008272.

Halbeisen, L.; Hungerbühler, N. (1997). "The Josephus Problem". J. Théor. Nombres Bordeaux. 9 (2): 303-318. doi:10.5802/jtnb.204.

Theriault, Nicolas (2001). "Generilazations of the Josephus Problem". Util. Math. (58): 161-173. : 10.1.1.164.2015

Cormen, Thomas H.; Leiserson, Charles E.; Rivest, Ronald L.; Stein, Clifford (2001). "Chapter 14: Augmenting Data Structures". Introduction to Algorithms (Second ed.). MIT Press and McGraw-Hill. p. 318. ISBN 0-262-03293-7.

Shams-Baragh, Armin (2002). "Formulating the Extended Josephus Problem" (PDF).

Ruskey, Frank; Williams, Aaron (2010). "The Feline Josephus Problem". Lect. Not. Comp. Sci. Lecture Notes in Computer Science. 6099: 343-354. Bibcode:2010LNCS.6099..343R. doi:10.1007/978-3-642-13122-6_33. ISBN 978-3-642-13121-9. FUN2010

Ruskey, Frank; Williams, Aaron (2012). "The Feline Josephus Problem". Theory Comput. Systems. 50: 20-34. doi:10.1007/s00224-011-9343-6. S2CID 2273820.

Sullivan, Shaun; Insko, Erik (2018). "A variant on the Feline Josephus Problem". arXiv: [math.CO].

# data[].attributes.attachment_link.description
In computer science and mathematics, the Josephus problem (or Josephus permutation) is a theoretical problem related to a certain counting-out game. People are standing in a circle waiting to be executed. Counting begins at a specified point in the circle and proceeds around the circle in a specified direction.

# data[].attributes.body
https://en.wikipedia.org/wiki/Diffusion-limited_aggregation

Timeline timeline = new Timeline(new KeyFrame(Duration.millis(100), event -> { })); timeline.setCycleCount(Animation.INDEFINITE); timeline.play();

# data[].attributes.attachment_link.readable_text
Written By Paul Bourke
Original: June 1991, Updated: January 2004, Updated: Sept 2014
Sample source code (brute force): dla2D.zip

Many attractive images and life-like structures can be generated using models of physical processes from areas of chemistry and physics. One such example is diffusion limited aggregation or DLA which describes, among other things, the diffusion and aggregation of zinc ions in an electrolytic solution onto electrodes. "Diffusion" because the particles forming the structure wander around randomly before attaching themselves ("Aggregating") to the structure. "Diffusion-limited" because the particles are considered to be in low concentrations so they don't come in contact with each other and the structure grows one particle at a time rather then by chunks of particles. Other examples can be found in coral growth, the path taken by lightning, coalescing of dust or smoke particles, and the growth of some crystals. Perhaps the first serious study of such processes was made by Witten, T.A. and Sander, L. M. and published by them in 1981, titled: "Diffusion limited aggregation, a kinetic critical phenomena" in Physical Review Letters. number 47.

Another more colourful description involves a city square surrounded by taverns. Drunks leave the taverns and stagger randomly around the square until they finally trip over one their insensate companions at which time, lulled by the sounds of peaceful snoring, they lie down and fall asleep. The tendril like structure is an aerial view of the sleeping crowd in the morning.

There are a number of ways of simulating this process by computer, perhaps the most common is to start with a white image except for a single black pixel in the center. New points are introduced at the borders and randomly (approximation of Brownian motion) walk until they are close enough to stick to an existing black pixel. A typical example of this is shown below in figure 1. If a point, during its random walk, approaches an edge of the image there are two strategies. The point either bounces off the edge or the image is toroidally bound (a point moving off the left edge enters on the right, a point moving off the right edge enters on the left, similarly for top and bottom). In general new points can be seeded anywhere in the image area, not just around the border without any significant visual difference.

Another attractor geometry is a line, see figure 2. In this case the bottom row of pixels are initially black and new points enter from the top. The image is normally horizontally circular, that is, points move off the left appear on the right and visa-versa.

Figure 3 shows a box attractor, new points enter in the interior (the center of the image say). The source code supplied here generates the forms by a rather brute force method which is hardly the most efficient. A common efficiency measure is to start the new particles within a certain range of the current structure and abandon them if they move outside some other range.

There are a number of ways of adding colour, figure 4 has a circular seed region (toroidal bounds) and the particles are coloured by the order in which they were introduced.

Another variation is to vary the so called "stickiness". In all the above example if the wandering particle struck part of the existing structure it always stuck (stickiness = 1). This can be modified by introducing a probability of sticking, the general result is to make the form more hairy and solid.

Frosty Windshield in the Morning Woods, Martha's Vineyard. Courtesy:
Stephen Klebs

Using spheres of decreasing radius

The following are examples of growth in three dimensions based upon the same principles as diffusion limited aggregation, normally performed in two dimensions. The basic principle involves a particle that moves around randomly until it gets close to part of the existing structure, at which point it sticks and becomes part of the structure. The process is started with a seeding structure, normally a single point, and continues until the structure reaches a desired size.

Click on the images here for higher resolution versions

Exhibited at Museum of Design, Zurich. einfach komplex - Bildbäume und Baumbilder in der Wissenschaft. Simply Complex -- Picture-Trees and Tree Pictures in Science. 30 April 2005 -- 4 September 2005

The renderings here are created using POV-Ray, each particle is actually represented as a cone and a piecewise Bezier curve is used to smooth continuous chains of particles. As particles are added the thickness of the branch leading to that particle in thickened.

A further extension is to constrain the DLA growth to some "vessel". In the following the constraint takes the form a box (left) or cylinder (right) with one end open.

Grown over a sphere (planetarium), left: looking from inside the planetarium, right: from the outside of the dome.

DLA grown within a 3D scanned model of the human head (plus antlers), described by a STL file. Part of modelling exercise for Philippe Vranjes.

Software

The software presented here is made available for Mac OS-X, for Mac OS-X X-Windows must be installed and running. DLA structures can be grown in 3D, constraint surfaces applied, and resulting structures saved in PovRay format for high quality rendering.

The following downloads are fully functional except saving of the geometry is disabled and size of growth is limited is limited to 4000 branches. The software is provided for a number of versions of Mac OSX, please contact the author if you experience problems. This allows you to check the software, the unrestricted version is available for a modest shareware fee.

Demo versions
dla3dmac_snowleopard.zip
dla3dmac_lion.zip
dla3dmac_mountainlion.zip
dla3dmac_yosemite.zip
dla3dmac_sierra.zip
dla3dmac_highsierra.zip

Buy full version

> dla3dviewer -h
Usage: dla3dviewer [command line options]
Command line options
       -h    this text
       -f    full screen
       -s    active (quad buffer) stereo
      -ss    dual screen stereo
Mouse controls
     left    rotate camera
   middle    roll camera
    right    menus
Function keys: see menus
Keyboard commands
        q    quit
        h    reset camera
      [,]    roll camera
          more camera forward, backward
      +,-    zoom camera in, out
        w    window dump to TGA file

Software Notes

You need to install XQuartz from here: https://www.xquartz.org/

The software expects a three button mouse, note that under Mac OS-X the middle and left button can be activated by using the option and control keys. The left mouse button rotates the camera about the model, the middle button rolls the camera, and the right button brings up a menu system.

Useful keys include the '' keys for moving the camera towards to away from the model. The camera is always pointing towards the origin which is where the initial seed particle is placed.

Using the menus the distribution of the introduced particles can be varied, the default is to introduce new particles on the surface of a sphere. When "extras" are turned on the last few thousand positions of introduced particles are shown. Particles are introduced just past the maximum range of the current model.

Settings dialog

Random seed: Each seed creates a unique structure, alternatively the same structure will result from the same seed (all other conditions being equal).

Bias towards origin: On each time-step the current particle moves in a random direction, the bias moves the particle towards the origin, generally by a very small amount.

Branch length: This sets the scale of the model and is the length of an added branch as well as defining how close a particle needs to get to the existing DLA structure in order to "stick" to it.

Stickiness: This is the probability of a particle sticking to the existing DLA structure once it is close enough. In general this control determines the density and fuzziness of the final structure. More information.

Particle rotation: On each time step this rotates the current particle about the z axis by (usually) a very small angle. Adds a swirling effect to the DLA and can vary the fractal dimension.

Branch thickness: This is used when the DLA structure is drawn with solid branches, instead of lines and points. This is also used in most of the export formats. The minimum value will be the thickness of the end of the branches.

Intersection range is used to avoid self intersections.

Multiple roots can be created, the range is used by the built in root seed distributions distribution.
The constraint surface can be scaled, translated, and rotated.

Physical realisations of various growth stages by David Sutton.

Further examples by David Sutton

Project by Michael Eden, building DLA structure within Architectural elements.

Paul Bourke
Poster: Graphite (ACM Siggraph), Dunedin November/December 2005

Abstract

Diffusion Limited Aggregation (DLA) has usually been studied in 2 dimensions as a model of fractal growth processes such as branching, lightning, snowflakes, mineral deposits, and coral. Here, the basic principles are extended into 3 dimensions and used to create believable models of root systems. A straightforward approach is introduced for constraining the growth of the 3 dimensional DLA by a surface or containing it within a vessel.
PDF version: dla3d.pdf

Miscellaneous images

Credits: William Ewing

DLA in 3 Dimensions, volumetric

The standard 2D DLA can be most simply extended into 3 dimensions by using a 3D pixel grid, more commonly known as a voxel grid. During the random walk, indead of just 8 possible new positions (2D) there are now 26 possible new direction for the particle to move at each step of the random walk.

# data[].attributes.attachment_link.description
Written By Paul Bourke Original: June 1991, Updated: January 2004, Updated: Sept 2014Sample source code (brute force): dla2D.zip Many attractive images and life-like structures can be generated using models of physical processes from areas of chemistry and physics.

# data[].attributes.headline
Randomized depth-first search maze generation algorithm (HL)

# data[].attributes.subject
Randomized depth-first search maze generation algorithm (HL)

# data[].attributes.attachment_link.readable_text
Maze generation algorithms are automated methods for the creation of mazes.

A maze can be generated by starting with a predetermined arrangement of cells (most commonly a rectangular grid but other arrangements are possible) with wall sites between them. This predetermined arrangement can be considered as a connected graph with the edges representing possible wall sites and the nodes representing cells. The purpose of the maze generation algorithm can then be considered to be making a subgraph in which it is challenging to find a route between two particular nodes.

If the subgraph is not connected, then there are regions of the graph that are wasted because they do not contribute to the search space. If the graph contains loops, then there may be multiple paths between the chosen nodes. Because of this, maze generation is often approached as generating a random spanning tree. Loops, which can confound naive maze solvers, may be introduced by adding random edges to the result during the course of the algorithm.

The animation shows the maze generation steps for a graph that is not on a rectangular grid. First, the computer creates a random planar graph G shown in blue, and its dual F shown in yellow. Second, computer traverses F using a chosen algorithm, such as a depth-first search, coloring the path red. During the traversal, whenever a red edge crosses over a blue edge, the blue edge is removed. Finally, when all vertices of F have been visited, F is erased and two edges from G, one for the entrance and one for the exit, are removed.

Randomized depth-first search

This algorithm, also known as the "recursive backtracker" algorithm, is a randomized version of the depth-first search algorithm.

Frequently implemented with a stack, this approach is one of the simplest ways to generate a maze using a computer. Consider the space for a maze being a large grid of cells (like a large chess board), each cell starting with four walls. Starting from a random cell, the computer then selects a random neighbouring cell that has not yet been visited. The computer removes the wall between the two cells and marks the new cell as visited, and adds it to the stack to facilitate backtracking. The computer continues this process, with a cell that has no unvisited neighbours being considered a dead-end. When at a dead-end it backtracks through the path until it reaches a cell with an unvisited neighbour, continuing the path generation by visiting this new, unvisited cell (creating a new junction). This process continues until every cell has been visited, causing the computer to backtrack all the way back to the beginning cell. We can be sure every cell is visited.

As given above this algorithm involves deep recursion which may cause stack overflow issues on some computer architectures. The algorithm can be rearranged into a loop by storing backtracking information in the maze itself. This also provides a quick way to display a solution, by starting at any given point and backtracking to the beginning.

Mazes generated with a depth-first search have a low branching factor and contain many long corridors, because the algorithm explores as far as possible along each branch before backtracking.

The depth-first search algorithm of maze generation is frequently implemented using backtracking. This can be described with a following recursive routine:

1. Given a current cell as a parameter,

2. Mark the current cell as visited

3. While the current cell has any unvisited neighbour cells

1. Choose one of the unvisited neighbours

2. Remove the wall between the current cell and the chosen cell

3. Invoke the routine recursively for a chosen cell

which is invoked once for any initial cell in the area.

A disadvantage of the first approach is a large depth of recursion - in the worst case, the routine may need to recur on every cell of the area being processed, which may exceed the maximum recursion stack depth in many environments. As a solution, the same backtracking method can be implemented with an explicit stack, which is usually allowed to grow much bigger with no harm.

1. Choose the initial cell, mark it as visited and push it to the stack

2. While the stack is not empty

1. Pop a cell from the stack and make it a current cell

2. If the current cell has any neighbours which have not been visited

1. Push the current cell to the stack

2. Choose one of the unvisited neighbours

3. Remove the wall between the current cell and the chosen cell

4. Mark the chosen cell as visited and push it to the stack

Randomized Kruskal's algorithm

This algorithm is a randomized version of Kruskal's algorithm.

1. Create a list of all walls, and create a set for each cell, each containing just that one cell.

2. For each wall, in some random order:
If the cells divided by this wall belong to distinct sets:

1. Remove the current wall.

2. Join the sets of the formerly divided cells.

There are several data structures that can be used to model the sets of cells. An efficient implementation using a disjoint-set data structure can perform each union and find operation on two sets in nearly constant amortized time (specifically, time; for any plausible value of ), so the running time of this algorithm is essentially proportional to the number of walls available to the maze.

It matters little whether the list of walls is initially randomized or if a wall is randomly chosen from a nonrandom list, either way is just as easy to code.

Because the effect of this algorithm is to produce a minimal spanning tree from a graph with equally weighted edges, it tends to produce regular patterns which are fairly easy to solve.

Randomized Prim's algorithm

This algorithm is a randomized version of Prim's algorithm.

1. Start with a grid full of walls.

2. Pick a cell, mark it as part of the maze. Add the walls of the cell to the wall list.

3. While there are walls in the list:

1. Pick a random wall from the list. If only one of the two cells that the wall divides is visited, then:

1. Make the wall a passage and mark the unvisited cell as part of the maze.

2. Add the neighboring walls of the cell to the wall list.

2. Remove the wall from the list.

Note that simply running classical Prim's on a graph with random edge weights would create mazes stylistically identical to Kruskal's, because they are both minimal spanning tree algorithms. Instead, this algorithm introduces stylistic variation because the edges closer to the starting point have a lower effective weight.

Although the classical Prim's algorithm keeps a list of edges, for maze generation we could instead maintain a list of adjacent cells. If the randomly chosen cell has multiple edges that connect it to the existing maze, select one of these edges at random. This will tend to branch slightly more than the edge-based version above.

The algorithm can be simplfied even further by randomly selecting cells that neighbour already-visited cells, rather than keeping track of the weights of all cells or edges.

It will usually be relatively easy to find the way to the starting cell, but hard to find the way anywhere else.

Wilson's algorithm

All the above algorithms have biases of various sorts: depth-first search is biased toward long corridors, while Kruskal's/Prim's algorithms are biased toward many short dead ends. Wilson's algorithm, on the other hand, generates an unbiased sample from the uniform distribution over all mazes, using loop-erased random walks.

We begin the algorithm by initializing the maze with one cell chosen arbitrarily. Then we start at a new cell chosen arbitrarily, and perform a random walk until we reach a cell already in the maze-however, if at any point the random walk reaches its own path, forming a loop, we erase the loop from the path before proceeding. When the path reaches the maze, we add it to the maze. Then we perform another loop-erased random walk from another arbitrary starting cell, repeating until all cells have been filled.

This procedure remains unbiased no matter which method we use to arbitrarily choose starting cells. So we could always choose the first unfilled cell in (say) left-to-right, top-to-bottom order for simplicity.

Aldous-Broder algorithm

The Aldous-Broder algorithm also produces uniform spanning trees.

1. Pick a random cell as the current cell and mark it as visited.

2. While there are unvisited cells:

1. Pick a random neigbour.

2. If the chosen neighbour has not been visited:

1. Remove the wall between the current cell and the chosen neighbour.

2. Mark the chosen neighbour as visited.

3. Make the chosen neighbour the current cell.

Mazes can be created with recursive division, an algorithm which works as follows: Begin with the maze's space with no walls. Call this a chamber. Divide the chamber with a randomly positioned wall (or multiple walls) where each wall contains a randomly positioned passage opening within it. Then recursively repeat the process on the subchambers until all chambers are minimum sized. This method results in mazes with long straight walls crossing their space, making it easier to see which areas to avoid.

For example, in a rectangular maze, build at random points two walls that are perpendicular to each other. These two walls divide the large chamber into four smaller chambers separated by four walls. Choose three of the four walls at random, and open a one cell-wide hole at a random point in each of the three. Continue in this manner recursively, until every chamber has a width of one cell in either of the two directions.

Other algorithms exist that require only enough memory to store one line of a 2D maze or one plane of a 3D maze. Eller's algorithm prevents loops by storing which cells in the current line are connected through cells in the previous lines, and never removes walls between any two cells already connected. The Sidewinder algorithm starts with an open passage along the entire the top row, and subsequent rows consist of shorter horizontal passages with one connection to the passage above. The Sidewinder algorithm is trivial to solve from the bottom up because it has no upward dead ends. Given a starting width, both algorithms create perfect mazes of unlimited height.

Most maze generation algorithms require maintaining relationships between cells within it, to ensure the end result will be solvable. Valid simply connected mazes can however be generated by focusing on each cell independently. A binary tree maze is a standard orthogonal maze where each cell always has a passage leading up or leading left, but never both. To create a binary tree maze, for each cell flip a coin to decide whether to add a passage leading up or left. Always pick the same direction for cells on the boundary, and the end result will be a valid simply connected maze that looks like a binary tree, with the upper left corner its root. As with Sidewinder, the binary tree maze has no dead ends in the directions of bias.

A related form of flipping a coin for each cell is to create an image using a random mix of forward slash and backslash characters. This doesn't generate a valid simply connected maze, but rather a selection of closed loops and unicursal passages. (The manual for the Commodore 64 presents a BASIC program using this algorithm, but using PETSCII diagonal line graphic characters instead for a smoother graphic appearance.)

Certain types of cellular automata can be used to generate mazes. Two well-known such cellular automata, Maze and Mazectric, have rulestrings B3/S12345 and B3/S1234. In the former, this means that cells survive from one generation to the next if they have at least one and at most five neighbours. In the latter, this means that cells survive if they have one to four neighbours. If a cell has exactly three neighbours, it is born. It is similar to Conway's Game of Life in that patterns that do not have a living cell adjacent to 1, 4, or 5 other living cells in any generation will behave identically to it. However, for large patterns, it behaves very differently from Life.

For a random starting pattern, these maze-generating cellular automata will evolve into complex mazes with well-defined walls outlining corridors. Mazecetric, which has the rule B3/S1234 has a tendency to generate longer and straighter corridors compared with Maze, with the rule B3/S12345. Since these cellular automaton rules are deterministic, each maze generated is uniquely determined by its random starting pattern. This is a significant drawback since the mazes tend to be relatively predictable.

Like some of the graph-theory based methods described above, these cellular automata typically generate mazes from a single starting pattern; hence it will usually be relatively easy to find the way to the starting cell, but harder to find the way anywhere else.

# data[].attributes.attachment_link.description
Maze generation algorithms are automated methods for the creation of mazes. A maze can be generated by starting with a predetermined arrangement of cells (most commonly a rectangular grid but other arrangements are possible) with wall sites between them. This predetermined arrangement can be considered as a connected graph with the edges representing possible wall sites and the nodes representing cells.

# data[].attributes.body
1. Zamieniamy ścieżki na bezwzględne i umieszczamy plik z baza danych w folderze na dysku C.
2. Tworzymy artefakt:
File -> Project Structure -> Project Settings -> Artifacts -> Click green plus sign -> Jar -> From modules with dependencies...
https://stackoverflow.com/questions/1082580/how-to-build-jars-from-intellij-properly
3. Budujemy projekt Build -> Build artifacts
4. Przenosimy plik jar do folderu z punktu 1.
5. Piszemy program rozruchowy (z rozszerzeniem .bat):
https://www.youtube.com/watch?v=ifBlevULGtM
W pliku java -jar nazwa_pliku_jar

# data[].attributes.attachment_link.readable_text


import java.util.LinkedList;

public class Main {

    public static void main(String[] args) {
	// write your code here
    }
}

public class Patient {
    private int id;
    private String name;
    private int priority;
    private String doctor;

    public Patient(int i, String n, int p) {
        id = i;
        name = n;
        priority = p;
        doctor = null;
    }

    public void setId(int i) {
        id = i;
    }

    public void setName(String n) {
        name = n;
    }

    public void setPriority(int p) {
        priority = p;
    }

    public void setDoctor(String d) {
        doctor = d;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getPriority() {
        return priority;
    }

    public String getDoctor() {
        return doctor;
    }

    public String toString() {
        return id+" "+name+" "+priority+" "+doctor;
    }
}

public class WaitingRoom {
    private Patient[] patients = new Patients[10];

    // uses default constructor

    public void add(Patient newPatient) {
        // adds the new patient in the next empty array location
        int i = 0;
        while ((patients[i] != null) && (i < 10)) {
            i = i + 1;
        }
        if (i == 10) {
            System.out.println("No more space in the waiting room.");
        } else {
            patients[i] = newPatient;
        }
    }

    public void callNextPatient() {
        // finds the next patient, outputs their details
        // and removes the patient from the array
        int index = 0;
        if (patients[0] == null) {
            System.out.println("The waiting room is empty.");
        }
        else {
            index = findNextPatientIndex();
            remove(index);
        }
    }

    private int findNextPatientIndex() {
        // returns the index of the first patient with the
        // highest priority in the array patients
        int max = 0;
        //... code missing ...
        return max;
    }

    private void remove(int n) {
        // outputs the data of the patient instance at array index n
        // and removes that patient by shifting all remaining patients
        // by one index towards the front of the array

        //... code missing ...
    }
}

public class WaitingRoom2 {
    private LinkedList<Patient> PatientList = new LinkedList<Patient>();

    // methods
    public void add(Patient P) {
        // adds a patient at the end of the list
        PatientList.addLast(P);
    }

    public void remove() {
        // outputs the name of the next patient to see a doctor and
        // removes this patient instance from the list
        int index = findNextPatientIndex();
        System.out.println(PatientList.get(index).getName());
        PatientList.remove(index);
    }

    private int findNextPatientIndex() {
        int i = 0, result = 0;
        Patient current, firstup;
        firstup = new Patient();
        firstup.setPriority(0);
        while (i < PatientList.size()) {
            current = PatientList.get(i);
            if (current.getPriority() > firstup.getPriority()) {
                firstup = current;
                result = i;
            }
            i=i+1;
        }
        return result;
    }
}

# data[].attributes.body
int[] array = {1, 4, 5, 6, 2, 4};
List<Integer> l = Arrays.stream(array)
.distinct()
.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
System.out.println(l);

String[] s = {"a", "b", "c"};
String d = Arrays.stream(s)
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
.toString();
System.out.println(d);

# data[].attributes.attachment_link.readable_text
package bb;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;

public class Main {

    public static void main(String[] args) throws IOException {
        
        //generating streams
        //array
        int[] array = {1, 4, 5, 6, 2, 4};

        System.out.println(Arrays.stream(array)
                .min());

        Arrays.stream(array)
                .forEach(System.out::println);

        
        //list
        List<String> names = new ArrayList <>();
        names.add("Ola");
        names.add("Ala");
        names.add("Adam");

        List<Integer> lengths = names.stream()
                .sorted()   //Adam Ala Ola
                .filter(name -> name.startsWith("A"))  //Adam Ala
                .map(name -> name.length())  //4 3
                .collect(toList());

        System.out.println(lengths);

        
        Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl")
                .stream()
                .distinct()
                .filter(s -> s.contains("a"))
                .sorted(String::compareTo)
                .forEach(System.out::println);

        
        //Stream.of
        System.out.println(
                Stream.of(2, 3, 4, 5, 2, 4, 2, 4, 5)
                    .skip(1)
                    .max(Integer::compareTo)
                    .get());


        //Stream.iterate
        System.out.println(
                Stream.iterate(1, n -> n + 3)
                    .limit(10)
                    .collect(toList()));


        //primitives
        IntStream.range(1, 10)
                .filter(n -> n % 3 ==0)
                .forEach(System.out::println);


        //pseudo-randoms
        new Random().ints(0, 10)
                .limit(100)
                //.map(n -> n / 2)
                .forEach(s -> System.out.print(s + " "));
        
        
        //file reading
        Files.lines(Paths.get("plik.txt"))
                .map(String::toUpperCase)
                .forEach(System.out::println);
        
        
        //przykłady
        //lista imion - poprawiacz imion
        List<String> names2 = new ArrayList <>();
        names2.add(" ola");
        names2.add("ALA ");
        names2.add("AdAm");
        List<String> goodNames = names2.stream()
                .map(String::trim)
                .map(String::toLowerCase)
                .map(getNameStartsWithUpperCase())
                .collect(Collectors.toList());

        goodNames.forEach(System.out::println);
        

        //lambdas
        System.out.println(getSquare().apply(4));
        
        Function<String, Integer> len = s -> s.length(); //String::length
        System.out.println(len.apply("Ala"));

    }

    private static Function<String, String> getNameStartsWithUpperCase() {
        return n -> n.substring(0, 1).toUpperCase() + n.substring(1);
    }

    private static Function<Integer, Double> getSquare() {
        return n -> (double) n * n;
    }
}

# data[].attributes.attachment_link.title
Java Functional Programming | Full Course | 2020

# data[].attributes.attachment_link.readable_text
Please, sign up to use our fast and easy-to-work weather APIs. As a start to use OpenWeather products, we recommend our One Call API 3.0. For more functionality, please consider our products, which are included in professional collections.

Professional collections

For professionals and specialists with middle sized project, we recommend our Professional collections, which included Current & Forecasts collection, Historical weather data collection, Weather Maps collection and other APIs.

For Enterprise level projects we provide Enterprise license, which is included all forecast products and current state, along with alerts, maps, and other products. Learn more

You can read the How to Start guide and enjoy using our powerful weather APIs right now.

Current & Forecast weather data collection

Climatic Forecast 30 days

Forecast weather data for 30 days

JSON format

Included in the Developer, Professional and Enterprise subscription plans

Global Weather Alerts
Push notifications

Get all the warnings from national weather agencies

Weather alerts are pushed to your endpoint as soon as they occur

Data feed provides all active weather alerts from the entire world

Each alert contents date, time, location, and detailed description

Monthly subscription. Please contact us to get access.

Solar Irradiance & Energy Prediction service

Solar Irradiance API

Get the solar data by particular location and calculate energy generation!

GHI, DNI, DHI indices for clear sky and cloudy sky models

Current data and forecast for 15 days ahead solar radiation data

40+ years of historical data (from January 1, 1979)

Daily aggregation for every day with hourly detalization for specified day

Historical solar irradiance and historical solar irradiance forecast bulks downloading

Available worldwide

Solar Panel Energy Prediction

Get the particular solar panel power output, based on the panel's technical characteristics!

Create unlimited number of solar panels for particular location with the desired specifications

Current and forecast for 15 days ahead solar panel power output data

40+ years of historical data (from January 1, 1979)

Daily aggregation for every day with hourly detalization for specified day

Available worldwide

Historical weather data collection

History Bulk

History Bulk provides weather data for any location for more than 40 years back
(from January 01, 1979).

Available through our Marketplace

CSV and JSON formats

Statistical Weather Data API

Statistical data on main weather parameters for any day and month of the year

The statistics is calculated based on our Historical weather data

JSON format

The weather data updated every hour

Included in Medium and Advanced subscription plans

Maps collection

Global Precipitation Maps Historical data

Current and historical weather maps for the previous 2 days

Historical precipitation data with 10-minutes step

Resolution higher than 1 km

Use as layers in Direct Tiles, OpenLayers, Leaflet, and Google Maps

Included in Professional and Enterprise subscription plans

Global Precipitation Maps Historical & Forecast data

Current, forecast and historical precipitation maps

Forecast is available for the next 6 hours for the US territory and for the next 2 hours for other global areas

The historical weather map for the previous 2 days

Data update period is every 10 minutes

Resolution higher than 1 km

Use as layers in Direct Tiles, OpenLayers, Leaflet, and Google Maps

Please contact us to get access

Other weather API's collection

Air Pollution API

Current, forecast and historical air pollution data

Forecast for 4 days ahead with 1-hour step

Air Pollution API includes both Air Quality Index and indices for CO, NO, NO₂, O₃, SO₂, NH₃, PM2.5, PM₁₀

Included in both free and paid subscriptions

Geocoding API

Geocoding API supports both the direct and reverse methods, working at the level of city names, areas and districts, countries and states

You can cap how many locations with the same name or the nearby geographic coordinates will be seen in the API response

Included in both free and paid subscriptions

Weather Stations

API for managing your personal weather stations

Connect your stations and transfer the measurements

Receive the aggregated measurements from the station

Included in both free and paid subscriptions

UV Index Deprecated

The product retired on 1st April 2021, please find UVI data in One Call API 3.0

Current UV index (Clear Sky), forecast and historical data are available for any geo location (lat/lon)

Interpretation of the UV Index and recommended protection are provided

JSON format

Weather Triggers

Simple syntax to create triggers which will be working upon the occurrence of specified weather conditions (temperature, humidity, pressure, etc.) in a certain period of time

The alerts will be generated in our service once the conditions set in the trigger are met

Included in both free and paid subscriptions

# data[].attributes.attachment_link.description
Simple and fast and free weather API from OpenWeatherMap you have access to current weather data, hourly, 5- and 16-day forecasts. Historical weather data for 40 years back for any coordinate. Weather maps, UV Index, air pollution and historical data

# data[].attributes.body
<dependencies>
    <dependency>
        <groupId>com.squareup.retrofit2</groupId>
        <artifactId>retrofit</artifactId>
        <version>2.7.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.6</version>
    </dependency>
    <dependency>
        <groupId>com.squareup.retrofit2</groupId>
        <artifactId>converter-gson</artifactId>
        <version>2.7.1</version>
    </dependency>

</dependencies>

<!--https://stackoverflow.com/questions/27037657/stop-intellij-idea-to-switch-java-language-level-every-time-the-pom-is-reloaded-->
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <source>1.10</source>
                <target>1.10</target>
            </configuration>
        </plugin>
    </plugins>
</build>

# data[].attributes.body
https://app.fake.rest/
https://jsonformatter.curiousconcept.com/

# data[].attributes.attachment_link.description
POSTMAN CHROME IS DEPRECATED DOWNLOAD THE UPDATED POSTMAN NATIVE APPS Postman Chrome is deprecated and is missing essential, new...

# data[].attributes.body
Zadanka do porobienia
dla wszystkich (SL + HL):
Grasshopper - Summation <8>
Century From Year <8>
Find numbers which are divisible by given number <8>
Sum of differences in array <8>
Will you survive the zombie onslaught? <7>
Merging sorted integer arrays (without duplicates) <8>
I love you, a little , a lot, passionately ... not at all <8>
Abbreviate a Two Word Name <8>
Find the first non-consecutive number <8>
Pick peaks <5>

dla HL:
Separate The Wheat From The Chaff <6>
Rotate a square matrix like a vortex <5>
The Clockwise Spiral <5>
Maximum Contiguous Sum <5>
Battle ships: Sunk damaged or not touched? <5>
Josephus Survivor<5>
Snail <4>

Zadania robi się na stronie https://www.codewars.com/

# data[].attributes.body
https://jsonplaceholder.typicode.com/
http://www.jsonschema2pojo.org/
https://square.github.io/retrofit/
https://www.vogella.com/tutorials/Retrofit/article.html

# data[].attributes.body
windows design,
UML diagram,
own classes and methods,
file I/O, SQLite database,
sorting

# data[].attributes.attachment_link.readable_text
package sample;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Arrays;
import java.util.UUID;

public class Main extends Application {

    //inner class; Pixel[][] is a picture
    class Pixel {
        int red;
        int green;
        int blue;

        public Pixel(int red, int green, int blue) {
            this.red = red;
            this.green = green;
            this.blue = blue;
        }

        @Override
        public String toString() {
            return "[" + red + ", " + green + ", " + blue + "] ";
        }
    }

    File selectedFile;

    double[][][] filters = {
            {       {0, 0, 0},
                    {0, 1, 0},
                    {0, 0, 0}
            }
            // TODO: 05.01.2020 new filters https://docs.gimp.org/2.6/C/plug-in-convmatrix.html
    };

    String[] filtersNames = {"identity"};
    // TODO: 05.01.2020 new filters names (parallel arrays!)

    public Pixel[][] getFilteredPicture(Pixel[][] picture, double[][] filter) {
        // https://ujjwalkarn.me/2016/08/11/intuitive-explanation-convnets/
        // TODO: 05.01.2020 method (convolution)
        
        return picture;
    }

    @Override
    public void start(Stage primaryStage) throws Exception{
        primaryStage.setTitle("Filters");

        GridPane root = new GridPane();
        root.setAlignment(Pos.CENTER);
        root.setHgap(100);
        root.setVgap(100);

        FileChooser fileChooser = new FileChooser();
        fileChooser.setInitialDirectory(new File("C:/"));
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("Image files", "*.jpeg", "*.jpg", "*.png", "*.bmp")
        );

        Button buttonFileChooser = new Button("Select image");

        ComboBox<String> comboBox = new ComboBox <>();
        comboBox.setItems(FXCollections.observableList(Arrays.asList(filtersNames)));

        ImageView imageViewOriginal = new ImageView();
        imageViewOriginal.setFitHeight(400);
        imageViewOriginal.setFitWidth(400);

        ImageView imageViewFiltered = new ImageView();
        imageViewFiltered.setFitHeight(400);
        imageViewFiltered.setFitWidth(400);

        buttonFileChooser.setOnAction(e -> {
            selectedFile = fileChooser.showOpenDialog(primaryStage);
            if (selectedFile != null) {
                try {
                    imageViewOriginal.setImage(new Image(new FileInputStream(selectedFile.getAbsolutePath())));
                    comboBox.setPromptText("Chose filter");
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                }
            }
        });

        comboBox.setOnAction(event -> {
            String filterName = comboBox.getValue();
            int filterNumber = 0;
            for (int i = 0; i < filters.length; i++) {
                if (filtersNames[i].equals(filterName)) {
                    filterNumber = i;
                }
            }
            if (selectedFile != null) {
                try {
                    Pixel[][] originalPicture = getPictureFromFile(selectedFile);
                    Pixel[][] filteredPicture = getFilteredPicture(originalPicture, filters[filterNumber]);
                    File filteredFile = getAndSaveFilteredPicture(filteredPicture, selectedFile);
                    imageViewFiltered.setImage(new Image(new FileInputStream(filteredFile.getAbsolutePath())));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        root.addRow(0, buttonFileChooser, comboBox);
        root.addRow(1, imageViewOriginal, imageViewFiltered);

        primaryStage.setScene(new Scene(root, 1000, 800));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    public Pixel[][] getPictureFromFile(File file) throws IOException {
        BufferedImage image = ImageIO.read(file);

        Pixel[][] picture = new Pixel[image.getHeight()][image.getWidth()];

        for (int x = 0; x < image.getHeight(); x++) {
            for (int y = 0; y < image.getWidth(); y++) {
                int clr = image.getRGB(y, x);
                int red = (clr & 0x00ff0000) >> 16;
                int green = (clr & 0x0000ff00) >> 8;
                int blue = clr & 0x000000ff;
                picture[x][y] = new Pixel(red, green, blue);
            }
        }

        System.out.println(Arrays.deepToString(picture));
        return picture;
    }

    public File getAndSaveFilteredPicture(Pixel[][] picture, File originalFile) throws IOException {
        //https://www.dyclassroom.com/image-processing-project/how-to-convert-a-color-image-into-negative
        BufferedImage image = ImageIO.read(originalFile);

        File file = new File(UUID.randomUUID().toString().substring(0, 8) + ".jpeg");

        for(int y = 0; y < image.getWidth() - 2; y++){
            for(int x = 0; x < image.getHeight() - 2; x++){
                int a = 255;
                int red = picture[x][y].red;
                int green = picture[x][y].green;
                int blue = picture[x][y].blue;

                int pixel = (a<<24) | (red<<16) | (green<<8) | blue;
                image.setRGB(y, x, pixel);
            }
        }

        ImageIO.write(image, "jpeg", file);

        return file;
    }
   
}

# data[].attributes.body
methods

# data[].attributes.attachment_link.readable_text
/*Main class*/
public class Main {

    public static Student[] students = new Student[10];

    public static void main(String[] args) {
        Date d1 = new Date(29,02,2018);
        Date d2 = new Date(28,02,2018);
        Date d3 = new Date(32,03,2018);
        Date d4 = new Date(29,02,1899);
        System.out.println(d1.toString());
        System.out.println(d2.toString());
        System.out.println(d3.toString());
        System.out.println(d4.toString());
        Subject s1 = new Subject("    matEMatyka   ", 5);
        Subject s2 = new Subject("Polski", 5);
        Subject s3 = new Subject(" geoGRAFia  ", 0);
        Subject s4 = new Subject("    historia", 9);
        System.out.println(s1.toString());
        System.out.println(s2.toString());
        System.out.println(s3.toString());
        System.out.println(s4.toString());
        //random numbers
        //https://javastart.pl/static/klasy/klasa-random-generator-pseudolosowy/
        Random random = new Random();
        Grade g1 = new Grade(s1, random.nextInt(4) + 2);  //random.nextInt(4) gives 0,1,2 or 3
        Grade g2 = new Grade(s2, random.nextInt(4) + 2);
        Grade g3 = new Grade(s3, random.nextInt(4) + 2);
        Grade g4 = new Grade(s4, random.nextInt(4) + 2);
        System.out.println(g1.toString());
        System.out.println(g2.toString());
        System.out.println(g3.toString());
        System.out.println(g4.toString());
        Student s = new Student(" janeK");
        students[0] = s;
        s.addGrade(g1);
        s.addGrade(g2);
        s.addGrade(g3);
        s.addGrade(g4);
        System.out.println(s.toString());
        s.removeGrade("polski ");
        System.out.println(s.toString());
        System.out.println(s.getTotalECTS());
        System.out.println(s.getAverageMark());
        System.out.println(s.getWeightedAverageMark());
        System.out.println(s.getStandardDeviationOfMarks());
        s.setYearOfBirth(new Date(8, 03, 2000));
        System.out.println(s.isStudentAdult());
        s.setYearOfBirth(new Date(9, 03, 2000));
        System.out.println(s.isStudentAdult());
        s.setYearOfBirth(new Date(10, 03, 2000));
        System.out.println(s.isStudentAdult());
        System.out.println(s.getSubject("GEOGRAFIA"));
        System.out.println(s.getMaxGrade());
        System.out.println(Arrays.toString(s.getFailedGrades()));
    }
}

/*Student class*/
public class Student {
	
    private static int numberOfStudents = 0;
    private static final int MAX_NUMBER_OF_GRADES = 10;
    //unique id's starting from 1
    private int id;
    private String name;
    private Date yearOfBirth;
    private int gradesCount;
    private Grade[] grades;

    /*1*/public Student(String name) {}

    //constructor overloading
    /*2*/public Student(String name, Date yearOfBirth) {
        //constructor chaining
        //invoking previous one-argument constructor
    }

    /*3*/public boolean addGrade(Grade grade){}

    /*4*/public boolean removeLastGrade(){}
	
	/*5*/public Grade removeLastGradeAndReturnIt(){}

	/*6#*/public boolean removeGrade(String name){}
	
	/*7#*/public Grade removeGradeAndReturnIt(String name){}

    /*8*/public Subject getSubject(String name){}
		
	/*9##*/public boolean isStudentAdult(){}//compare to current date

    /*10*/public double getTotalECTS(){}

    /*11*/public double getAverageMark(){}

    /*12*/public double getWeightedAverageMark(){}//pointECTS as a weight

    /*13*/public double getStandardDeviationOfMarks(){}//https://en.wikipedia.org/wiki/Standard_deviation

    /*14*/public Grade getMaxGrade(){}
	
	/*15*/public Grade getMinGrade(){}
	
	/*16#*/public Grade[] getFailedGrades(){}
	
	/*17#*/public Grade[] getGradesWithPointECTS(int pointECTS){}
	
	/*18##*/public Grade[] getGradesSortedByMark(){}
	
	/*19##*/public Grade[] getGradesSortedBySubjectName(){}

	/*20##*/public Grade[] getGradesSortedByPointECTS(){}
	
	/*31#*/public Grade[] getGradesWithMark(int mark){}
	
	/*32##*/public Date getCurrentDateFromSystem(){}
	
	/*33#*/public Grade[] getGradesWithNameStartedWithLetter(String letter){}
	
	/*21*/public String getStudentMarksReport(){}
	//Student name and id
	//Subject1: mark (pointECTS)
	//Subject2: mark (pointECTS)
	//Subject3: mark (pointECTS)...
	
	/*22*/public void setName(String name) {}

    public static int getNumberOfStudents() {
        return numberOfStudents;
    }

    public static int getMaxNumberOfGrades() {
        return MAX_NUMBER_OF_GRADES;
    }

    public int getId() {
        return id;
    }

     public String getName() {
        return name;
    }

    public int getGradesCount() {
        return gradesCount;
    }

    public Grade[] getGrades() {
        return grades;
    }

    public Date getYearOfBirth() {
        return yearOfBirth;
    }

    public void setYearOfBirth(Date yearOfBirth) {
        this.yearOfBirth = yearOfBirth;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name +
                ", yearOfBirth=" + yearOfBirth +
                ", gradesCount=" + gradesCount +
                ", grades=" + Arrays.toString(grades) +
                '}';
    }
}


/*Grade class*/
public class Grade {
	
    private Subject subject;
    private int mark;
    private Date date;
    private boolean retake = false;

    /*23*/public Grade(Subject subject, int mark) {}

    public Subject getSubject() {
        return subject;
    }

    public void setSubject(Subject subject) {
        this.subject = subject;
    }

    public int getMark() {
        return mark;
    }

    public void setMark(int mark) {
        this.mark = mark;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public boolean isRetake() {
        return retake;
    }

    public void setRetake(boolean retake) {
        this.retake = retake;
    }

    @Override
    public String toString() {
        return "Grade{" +
                "subject=" + subject +
                ", mark=" + mark +
                ", date=" + date +
                ", retake=" + retake +
                '}';
    }
}

/*Subject class*/
public class Subject {
    
	private static int numberOfSubjects = 0;
    //unique id's starting from 1
    private int id;
    private String name;
    private int pointECTS;

    /*24*/public Subject(String name, int pointECTS) {}

    public static int getNumberOfSubjects() {
        return numberOfSubjects;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    /*25*/public void setName(String name) {}

    public int getPointECTS() {
        return pointECTS;
    }

    /*26*/public boolean setPointECTS(int pointECTS) {}

    @Override
    public String toString() {
        return "Subject{" +
                "id=" + id +
                ", name='" + name +
                ", pointECTS=" + pointECTS +
                '}';
    }
}

/*Date class*/
public class Date {
	
    private int day;
    private int month;
    private int year;

    /*27*/public Date(int day, int month, int year) {}

    public int getDay() {
        return day;
    }

    public int getMonth() {
        return month;
    }

    public int getYear() {
        return year;
    }

    /*28*/public boolean setDate(int day, int month, int year) {}

    /*29##*/private boolean dateIsValid(int day, int month, int year){}

    @Override
    public String toString() {
        return "Date{" +
                "day=" + day +
                ", month=" + month +
                ", year=" + year +
                '}';
    }
}

/*StringFormat class*/
public class StringFormat {

    /*30##*/public static String getFormatted(String bedString){}
}

# data[].attributes.attachment_link.readable_text
In this tutorial, it shows the use of java.lang.Comparable and java.util.Comparator to sort a Java object based on its property value.

1. Sort an Array

To sort an Array, use the Arrays.sort().

 String[] fruits = new String[] {"Pineapple","Apple", "Orange", "Banana"}; Arrays.sort(fruits); int i=0; for(String temp: fruits){ System.out.println("fruits " + ++i + " : " + temp); }

Output

 fruits 1 : Apple fruits 2 : Banana fruits 3 : Orange fruits 4 : Pineapple

2. Sort an ArrayList

To sort an ArrayList, use the Collections.sort().

 List<String> fruits = new ArrayList<String>(); fruits.add("Pineapple"); fruits.add("Apple"); fruits.add("Orange"); fruits.add("Banana"); Collections.sort(fruits); int i=0; for(String temp: fruits){ System.out.println("fruits " + ++i + " : " + temp); }

Output

 fruits 1 : Apple fruits 2 : Banana fruits 3 : Orange fruits 4 : Pineapple

3. Sort an Object with Comparable

How about a Java Object? Let create a Fruit class:

 public class Fruit{ private String fruitName; private String fruitDesc; private int quantity; public Fruit(String fruitName, String fruitDesc, int quantity) { super(); this.fruitName = fruitName; this.fruitDesc = fruitDesc; this.quantity = quantity; } public String getFruitName() { return fruitName; } public void setFruitName(String fruitName) { this.fruitName = fruitName; } public String getFruitDesc() { return fruitDesc; } public void setFruitDesc(String fruitDesc) { this.fruitDesc = fruitDesc; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } }

To sort it, you may think of Arrays.sort() again, see below example :

 package com.mkyong.common.action; import java.util.Arrays; public class SortFruitObject{ public static void main(String args[]){ Fruit[] fruits = new Fruit[4]; Fruit pineappale = new Fruit("Pineapple", "Pineapple description",70); Fruit apple = new Fruit("Apple", "Apple description",100); Fruit orange = new Fruit("Orange", "Orange description",80); Fruit banana = new Fruit("Banana", "Banana description",90); fruits[0]=pineappale; fruits[1]=apple; fruits[2]=orange; fruits[3]=banana; Arrays.sort(fruits); int i=0; for(Fruit temp: fruits){ System.out.println("fruits " + ++i + " : " + temp.getFruitName() + ", Quantity : " + temp.getQuantity()); } } }

Nice try, but, what you expect the Arrays.sort() will do? You didn't even mention what to sort in the Fruit class. So, it will hits the following error :

 Exception in thread "main" java.lang.ClassCastException: com.mkyong.common.Fruit cannot be cast to java.lang.Comparable at java.util.Arrays.mergeSort(Unknown Source) at java.util.Arrays.sort(Unknown Source)

To sort an Object by its property, you have to make the Object implement the Comparable interface and override the compareTo() method. Lets see the new Fruit class again.

 public class Fruit implements Comparable<Fruit>{ private String fruitName; private String fruitDesc; private int quantity; public Fruit(String fruitName, String fruitDesc, int quantity) { super(); this.fruitName = fruitName; this.fruitDesc = fruitDesc; this.quantity = quantity; } public String getFruitName() { return fruitName; } public void setFruitName(String fruitName) { this.fruitName = fruitName; } public String getFruitDesc() { return fruitDesc; } public void setFruitDesc(String fruitDesc) { this.fruitDesc = fruitDesc; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public int compareTo(Fruit compareFruit) { int compareQuantity = ((Fruit) compareFruit).getQuantity(); //ascending order return this.quantity - compareQuantity; //descending order //return compareQuantity - this.quantity; } }

The new Fruit class implemented the Comparable interface, and overrided the compareTo() method to compare its quantity property in ascending order.

The compareTo() method is hard to explain, in integer sorting, just remember

1. this.quantity - compareQuantity is ascending order.

2. compareQuantity - this.quantity is descending order.

To understand more about compareTo() method, read this Comparable documentation.

Run it again, now the Fruits array is sort by its quantity in ascending order.

 fruits 1 : Pineapple, Quantity : 70 fruits 2 : Orange, Quantity : 80 fruits 3 : Banana, Quantity : 90 fruits 4 : Apple, Quantity : 100

4. Sort an Object with Comparator

How about sorting with Fruit's "fruitName" or "Quantity"? The Comparable interface is only allow to sort a single property. To sort with multiple properties, you need Comparator. See the new updated Fruit class again :

 import java.util.Comparator; public class Fruit implements Comparable<Fruit>{ private String fruitName; private String fruitDesc; private int quantity; public Fruit(String fruitName, String fruitDesc, int quantity) { super(); this.fruitName = fruitName; this.fruitDesc = fruitDesc; this.quantity = quantity; } public String getFruitName() { return fruitName; } public void setFruitName(String fruitName) { this.fruitName = fruitName; } public String getFruitDesc() { return fruitDesc; } public void setFruitDesc(String fruitDesc) { this.fruitDesc = fruitDesc; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public int compareTo(Fruit compareFruit) { int compareQuantity = ((Fruit) compareFruit).getQuantity(); //ascending order return this.quantity - compareQuantity; //descending order //return compareQuantity - this.quantity; } public static Comparator<Fruit> FruitNameComparator = new Comparator<Fruit>() { public int compare(Fruit fruit1, Fruit fruit2) { String fruitName1 = fruit1.getFruitName().toUpperCase(); String fruitName2 = fruit2.getFruitName().toUpperCase(); //ascending order return fruitName1.compareTo(fruitName2); //descending order //return fruitName2.compareTo(fruitName1); } }; }

The Fruit class contains a static FruitNameComparator method to compare the "fruitName". Now the Fruit object is able to sort with either "quantity" or "fruitName" property. Run it again.

1. Sort Fruit array based on its "fruitName" property in ascending order.

 Arrays.sort(fruits, Fruit.FruitNameComparator);

Output

 fruits 1 : Apple, Quantity : 100 fruits 2 : Banana, Quantity : 90 fruits 3 : Orange, Quantity : 80 fruits 4 : Pineapple, Quantity : 70

2. Sort Fruit array based on its "quantity" property in ascending order.

 Arrays.sort(fruits)

Output

 fruits 1 : Pineapple, Quantity : 70 fruits 2 : Orange, Quantity : 80 fruits 3 : Banana, Quantity : 90 fruits 4 : Apple, Quantity : 100

The java.lang.Comparable and java.util.Comparator are powerful but take time to understand and make use of it, may be it's due to the lacking of detail example.

My thoughts...

In future, Arrays class should provides more generic and handy method - Arrays.sort(Object, String, flag).

To sort a object array by its "fruitName" in ascending order.

 Arrays.sort(fruits, fruitName, Arrays.ASCENDING);

To sort a object array by its "quantity" in ascending order.

 Arrays.sort(fruits, quantity, Arrays.DESCENDING);

Reference

# data[].attributes.attachment_link.title
Java object sorting example (Comparable and Comparator)

# data[].attributes.attachment_link.description
In this tutorial, it shows the use of java.lang.Comparable and java.util.Comparator to sort a Java object based on its property value. To sort an Array, use the Arrays.sort().

# data[].attributes.attachment_link.readable_text
Updated on February 3rd, 2019

Java Sorting Example(Comparable and Comparator)

In this article, we will cover Java Sorting Example (Comparable and Comparator). Java Collection API provides a way to sort Array and Lists but it expects input from the developer. This article will try to give an example to use both java.lang.Comparable and java.util.Comparator to sort objects.

1. Sort an ArrayList

Collections API's utility class Collections provide a handy way to sort an ArrayList in a natural ordering provided all elements in the list must implement the Comparable interface.

public class SimpleSorting { public static void main(String[] args) { List<String> locationList = new ArrayList<String>(); locationList.add("California"); locationList.add("Texas"); locationList.add("Seattle"); locationList.add("New Delhi"); Collections.sort(locationList); for (String location : locationList) { System.out.println("Location is: " + location); } } }

Output

Location is: California Location is: New Delhi Location is: Seattle Location is: Texas

Above example worked perfectly with Collections.Sort() as List defined in example was Lits<String> and java.lang.String implements the Comparable interface. With List contains custom objects, Collections.sort() will fail if the custom object does not implement the Comparable interface.

2. Sort Object using Comparable

public class Person implements Comparable<Person> { private String name; private int age; public Person(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int compareTo(Person person) { return this.age > person.age ? 1 : this.age < person.age ? -1 : 0; } }

To sort it, we will use Collections.sort() method

public class ComparableDemo { public static void main(String[] args) { List<Person> persons = new ArrayList<Person>(); persons.add(new Person("Umesh Awasthi", 35)); persons.add(new Person("Robert Hickle", 55)); persons.add(new Person("John Smith", 40)); persons.add(new Person("David", 23)); Collections.sort(persons); for (Person person : persons) { System.out.println("Person is: " + person.getName()); } } }

Output is

Person is: David Person is: Umesh Awasthi Person is: John Smith Person is: Robert Hickle

Pay close attention to Person class declaration public class Person implements Comparable<Person> which shows that Person class is a comparable if you remove Comparable<Person> from your Person class and try Collection.sort(persons) , compile will give the following error

Error:(21, 20) java: no suitable method found for sort(java.util.List<com.umeshawasthi.tutorials.corejava.sorting.Person>) method java.util.Collections.<T>sort(java.util.List<T>) is not applicable (inferred type does not conform to upper bound(s) inferred: com.umeshawasthi.tutorials.corejava.sorting.Person upper bound(s): java.lang.Comparable<? super com.umeshawasthi.tutorials.corejava.sorting.Person>) method java.util.Collections.<T>sort(java.util.List<T>,java.util.Comparator<? super T>) is not applicable (cannot infer type-variable(s) T (actual and formal argument lists differ in length))

As a developer, it's out responsibility to pass the comparable object to Collections.sort() method.
It's up to you how you want to use the compareTo method and what will be your comparison logic, I have used a simple logic to compare the age of the person but you can use any custom logic to in compareTo() method.
3. Sort Object using Comparator

java.lang.Comparable interface provides only one way to compare this object with another one, what are the options in case we need to compare 2 objects to sort them correctly. How about sorting Person with a name or age? What if we want to override the natural ordering? We need to create a Comparator for these requirements.

First and super short template is to provide a custom comparator while calling Collections.sort() method

public class ComparatorDemo { public static void main(String[] args) { List<Person> persons = new ArrayList<Person>(); persons.add(new Person("Umesh Awasthi", 35)); persons.add(new Person("Robert Hickle", 55)); persons.add(new Person("John Smith", 40)); persons.add(new Person("David", 23)); persons.add(new Person("David", 63)); Collections.sort(persons, new Comparator<Person>() { public int compare(Person person, Person person1) { int name = person.getName().compareTo(person1.getName()); if(name == 0){ return name; } return person.getAge() > person1.getAge() ? 1 : person.getAge() < person1.getAge() ? -1 : 0; } }); for (Person person : persons) { System.out.println("Person is: " + person.getName()); } } }

Output

Person is: David Person is: Umesh Awasthi Person is: John Smith Person is: Robert Hickle Person is: David

Check the output, the interesting part is David, which is first and last result of the output.Another efficient way is to define the Comparators in the Contact itself to reuse them instead of recreating every time

public class ComparatorPerson { private String name; private int age; public ComparatorPerson(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public static Comparator<ComparatorPerson> COMPARE_BY_NAME = new Comparator<ComparatorPerson>() { public int compare(ComparatorPerson one, ComparatorPerson other) { return one.name.compareTo(other.name); } }; public static Comparator<ComparatorPerson> COMPARE_BY_AGE = new Comparator<ComparatorPerson>() { public int compare(ComparatorPerson one, ComparatorPerson other) { return one.age > other.age ? 1 : one.age < other.age ? -1 : 0; } }; }

Comparator with multi options

public class MultiComparatorDemo { public static void main(String[] args) { List<ComparatorPerson> persons = new ArrayList<ComparatorPerson>(); persons.add(new ComparatorPerson("Umesh Awasthi", 35)); persons.add(new ComparatorPerson("Robert Hickle", 55)); persons.add(new ComparatorPerson("John Smith", 40)); persons.add(new ComparatorPerson("David", 23)); persons.add(new ComparatorPerson("David", 63)); Collections.sort(persons,ComparatorPerson.COMPARE_BY_AGE ); for (ComparatorPerson person : persons) { System.out.println("Person Name Sorted by Age is: " + person.getName()); } System.out.println("######################################################"); Collections.sort(persons,ComparatorPerson.COMPARE_BY_NAME ); for (ComparatorPerson person : persons) { System.out.println("Person Name Sorted by Name is: " + person.getName()); } } }

Output

Person Name Sorted by Age is: David Person Name Sorted by Age is: Umesh Awasthi Person Name Sorted by Age is: John Smith Person Name Sorted by Age is: Robert Hickle Person Name Sorted by Age is: David ###################################################### Person Name Sorted by Name is: David Person Name Sorted by Name is: David Person Name Sorted by Name is: John Smith Person Name Sorted by Name is: Robert Hickle Person Name Sorted by Name is: Umesh Awasthi

4. Sort Object using Java8

Java 8 added a new way of making Comparators that reduces the amount of code you have to write Comparator.comparing. Java 8 streaming API provides neater approach. It's always good to understand how compareTo() and compare() method work under the hood

public class Java8CompareExample { public static void main(String[] args) { List<Person> persons = new ArrayList<Person>(); persons.add(new Person("Umesh Awasthi", 35)); persons.add(new Person("Robert Hickle", 55)); persons.add(new Person("John Smith", 40)); persons.add(new Person("David", 23)); persons.add(new Person("David", 63)); persons.sort(Comparator.comparing(Person::getName).thenComparingInt(Person::getAge)); for (Person person : persons) { System.out.println("Person Name is: " + person.getName()); } persons.sort(Comparator.comparingInt(Person::getAge).thenComparing(Person::getName)); for (Person person : persons) { System.out.println("Person Name is: " + person.getName()); } } }

In this article, we cover Java Sorting Example (Comparable and Comparator) provided by JDK, we will cover other API which provides the same functionalities with additional features. All the code of this article is available Over on Github. This is a Maven-based project. As a bonus, have a look at Apache Common ComparatorUtils which provide some ready to use a feature for you.

Reference

# data[].attributes.attachment_link.title
Java Sorting Example(Comparable and Comparator) | Java Development Journal

# data[].attributes.attachment_link.description
Updated on February 3rd, 2019 In this article, we will cover Java Sorting Example (Comparable and Comparator). Java Collection API provides a way to sort Array and Lists but it expects input from the developer. This article will try to give an example to use both java.lang.Comparable and java.util.Comparator to sort objects.

# data[].attributes.body
https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life

# data[].attributes.attachment_link.readable_text
﻿package sample;

import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Main extends Application {

    static final int HEIGHT = 60;
    static final int WIDTH = 80;
    static final int TILE_SIZE = 10;

    boolean[][] board = new boolean[HEIGHT][WIDTH];

    Stage stage;

    @Override
    public void start(Stage primaryStage) throws Exception{
        stage = primaryStage;
        stage.setTitle("Game of live");
        
	generateRandomBoard();

        Timeline timeline = new Timeline();
        timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(0.5), event -> {
            printBoard();
            getNextGeneration();
        }));
        timeline.setCycleCount(Animation.INDEFINITE);
        timeline.play();
    }

    private void printBoard(){
        GridPane root = new GridPane();

        for (int r = 0; r < HEIGHT; r++) {
            for (int c = 0; c < WIDTH; c++) {
                Rectangle rectangle;
                if (board[r][c]){
                    rectangle = new Rectangle(TILE_SIZE, TILE_SIZE, Color.LIGHTCORAL);
                }
                else {
                    rectangle = new Rectangle(TILE_SIZE, TILE_SIZE, new Color(1, 0.9608, 0.9569, 1));
                }
                rectangle.setStroke(Color.LIGHTGRAY);
                root.add(rectangle, c, r);
            }
        }

        stage.setScene(new Scene(root, WIDTH * (TILE_SIZE + 1), HEIGHT * (TILE_SIZE + 1)));
        stage.getScene().setOnKeyPressed(event -> {
            if(event.getCode() == SPACE) {
                getNextGeneration(); 
		printBoard();
            }
        });
        stage.show();
    }

    private void generateRandomBoard(){

    }

    private void getNextGeneration(){
        
    }

    public static void main(String[] args) {
        launch(args);
    }
}

# data[].attributes.attachment_link.readable_text
package com.company;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        System.out.println(convertToBinary(12));
        System.out.println(Arrays.toString(convertToBase(17, 2)));
        System.out.println(convertToDecimal(new int[]{15, 1}, 16));
        System.out.println(Arrays.toString(convertFromSystemToSystem(new int[]{1, 1, 2}, 10, 10)));
    }

    public static String convertToBinary(int n) {
        StringBuilder s = new StringBuilder();

        while (n > 0){
            s.append(n % 2);
            n /= 2;
        }

        return s.reverse().toString();
    }

    public static int[] convertToBase(int n, int base) {
        List<Integer> list = new ArrayList<>();

        while (n > 0) {
            list.add(n % base);
            n /= base;
        }

        int[] a = new int[list.size()];

        for (int i = 0; i < a.length; i++) {
            a[i] = list.get(a.length - 1 - i);
        }

        return a;
    }

    public static int convertToDecimal(int[] n, int base) {
        int converted = 0;

        for (int i = n.length - 1, exponent = 0; i >= 0 ; i--, exponent++) {
            converted += n[i] * Math.pow(base, exponent);
        }

        return converted;
    }

    public static int[] convertFromSystemToSystem(int[] n, int baseFrom, int baseTo) {
        int decimal = convertToDecimal(n, baseFrom);
        return convertToBase(decimal, baseTo);
    }
}

# data[].attributes.body
Bezpłatne warsztaty programowania C#

# data[].attributes.attachment_link.readable_text
ONLINE - terminy wkrótce
STACJONARNIE:
Biała Podlaska (Plac Szkolny Dwór 9) - 20.09.2020

Białystok (ul. Legionowa 9/1) - 12-13.09.2020

Bielsko-Biała (ul. Legionów 30) - 20.09.2020

Brzesko (ul. Plac Kazimierza Wielkiego 8) - 19-20.09.2020

Busko-Zdrój (Bohaterów Warszawy 37) - 26-27.09.2020

Bydgoszcz (Plac Wolności 9) - 19.09.2020

Bytom (ul. Podgórna 9) - 26.09.2020

Chełm (ul. Adama Mickiewicza 41) - 19.09.2020

Częstochowa (ul. im. Jana Pawła II 126/130) - 19.09.2020

Dąbrowa Górnicza (ul. Królowej Jadwigi 12) - 19.09.2020

Elbląg (ul. Hetmańska 15 lok. C) - 12-13.09.2020 i 19-20.09.2020

Gdańsk (ul. Grunwaldzka 103) - 19-20.09.2020

Gdynia (ul. Świętojańska 34/3) - 19-20.09.2020

Gliwice (ul. Zwycięstwa 10) - 19-20.09.2020

Gniezno (ul. Bolesława Chrobrego 14)- 19.09.2020

Gorlice (ul. 11 listopada 37)- 19.09.2020

Grodzisk Mazowiecki (ul. Sienkiewicza 52/7) - 12.09.2020

Grójec (ul. Jana Pawła II 26 - "Centrum Konferencyjne i Szkoleniowe EDUSTREFA") - 13.09.2020

Jasło (ul. Szopena 10) - 19.09.2020

Jaworzno (ul. Rynek 17 - Miejska Biblioteka Publiczna) - 19.09.2020

Jędrzejów(Szkoła Podstawowa nr 3, ul. Reymonta 1) - 12-13.09.2020

Kalisz (ul. Kazimierzowska 6/7) - 12-13.09.2020

Katowice (ul. Korfantego 2) - 19-20.09.2020

Kielce (ul. IX Wieków Kielc 6/8) - 19-20.09.2020

Kraków (ul. Lubicz 3) - 19-20.09.2020

Kraków (ul. Kobierzyńska 100) - 19-20.09.2020

Krosno (ul. Grodzka 12) - 19.09.2020

Kościerzyna (ul. Sikorskiego 20) - 12.09.2020

Kozienice (ul. Radomska 14A) - 19.09.2020

Legionowo (ul. Strużańska 2b) - 12.09.2020

Lublin (ul. Niecała 1) - 19-20.09.2020

Łęczna (ul. Jawoszka 11) - 19.09.2020

Łódź (ul. Gdańska 126/128) - 19-20.09.2020

Łomianki (ul. Staszica 2 - SP nr 3) - 12-13.09.2020

Łuków (ul. ks. Brzóski 17) - 19-20.09.2020

Mielec (ul. Stefana Batorego 12) - 12.09.2020

Mysłowice (ul. Mikołowska 29) - 19.09.2020

Mińsk Mazowiecki (ul. Piłsudskiego 33 lok I) - 12-13.09.2020, 19-20.09.2020

Niepołomice (ul. Na Grobli 7) - 12.09.2020 (stacjonarnie), 13.09.2020 (online)

Olkusz (ul. Floriańska 1) - 12.09.2020

Olsztyn (ul. 1 Maja 13) - 12-13.09.2020

Opole (ul. Ozimska 48) - 12-13.09.2020

Otwock (ul. Kazimierza Pułaskiego 7) - 13.09.2020

Ostrołęka (ul. Głowackiego 33) - 12-13.09.2020

Ostrów Wielkopolski (ul. Kaliska 35) - 19.09.2020

Ożarów Mazowiecki (ul. Poznańska 258) - 12-13.09.2020

Piaseczno (ul. Młynarska 2a) - 12-13.09.2020

Płock (ul. Armii Krajowej 10 lok 8) - 13.09.2020 i 20.09.2020

Poznań (ul. Towarowa 35) - 19-20.09.2020

Pruszków (ul. Kościuszki 15) - 12-13.09.2020

Pruszcz Gdański(ul. Chopina 34 - Centrum Kultury i Sportu) - 19-20.09.2020

Puławy (ul. Górna 4b) - 12.09.2020

Radom (u. Rynek 7) - 12-13.09.2020

Ruda Śląska (ul. Główna 1) - 20.09.2020

Rybnik (ul. Tadeusza Kościuszki 54) - 20.09.2020

Rzeszów (Plac Jana. Kilińskiego 2) - 19-20.09.2020

Sanok (ul. Chopina 10) - 19.09.2020

Siedlce (ul. Piłsudskiego 18) - 12-13.09.2020

Skawina (ul. Korabnicka 3c) - 19-20.09.2020

Skierniewice (ul. Adama Asnyka 92) - 19.09.2020

Sochaczew (ul Piłsudskiego 63) -19.09.2020

Sosnowiec (ul. Kilińskiego 43) - 19.09.2020

Stalowa Wola (ul. Jana Pawła II 2a/6a) - 19.09.2020

Starachowice (ul. Witolda Lutosławskiego 6) - 19.09.2020

Starogard Gdański (ul. Jana Sobieskiego 6 - Zespół Szkół Ekonomicznych)- 19.09.2020

Strzelce Opolskie (ul. H. Pobożnego 1) - 12-13.09.2020

Sulejówek (ul. Idzikowskiego 2A) - 12-13.09.2020, 19-20.09.2020

Świdnik (Szkoła Podstawowa nr 5 im. Janusza Kusicińskiego, ul. Jarzębinowa 6) - 24-25.09.2020

Szczecin (al. Piastów 1) - 12-13.09.2020

Tarnobrzeg (ul. H. Sienkiewicza 16) - 20.09.2020

Tarnowskie Góry (ul. Gliwicka 35) - 20.09.2020

Tarnów (ul. Dąbrowskiego 21) - 19.09.2020

Toruń (ul. Jęczmienna 23) - 19.09.2020

Tychy (ul. Korczaka 6) - 19.09.2020

Warszawa (ul. Krucza 46) - 12-13.09.2020

Warszawa (ul. Górczewska 216) - 12-13.09.2020

Warszawa (ul. Wałbrzyska 11) - 12-13.09.2020

Wieliczka (Lokalizacja wkrótce) - 19-20.09.2020

Wołomin (ul. Wileńska PARK 51) - 12.09.2020

Wrocław (ul. Leszczyńskiego 4) - 12-13.09.2020

Wrocław (ul. Legnicka 52) - 12-13.09.2020

Września (ul. Szkolna 3) - 20.09.2020

Wyszków (ul. 11 Listopada 62 - SP 1) - 19.09.2020

Zabrze (ul. Henryka Sienkiewicza 33) - 19.09.2020

Zamość (ul. Legionów 52a) - 20.09.2020

Zielona Góra (al. Niepodległości 16/7) - 19-20.09.2020

Żyrardów (ul. 1 Maja 41b) - 12-13.09.2020

PROGRAM KODUJ Z GIGANTAMI

Warsztaty z programowania w blokach 1- lub 1,5- godzinnych w grupach do 12 osób

Klasy 4-6 szkoły podstawowej: Scratch, App Inventor

7, 8 kl. SP oraz szkoły ponadpodstawowe: C#, Visual Studio

Warsztaty z programowania - szkoła Giganci Programowania. Trenerami prowadzącymi zajęcia będą doświadczeni programiści.

<

POPRZEDNIE EDYCJE

# data[].attributes.attachment_link.title
Giganci Programowania - Nauka programowania dla dzieci i młodzieży.

# data[].attributes.attachment_link.description
ONLINE - terminy wkrótce STACJONARNIE: Biała Podlaska (Plac Szkolny Dwór 9) - 20.09.2020 Białystok (ul. Legionowa 9/1) - 12-13.09.2020 Bielsko-Biała (ul. Legionów 30) - 20.09.2020 Brzesko (ul. Plac Kazimierza Wielkiego 8) - 19-20.09.2020 Busko-Zdrój (Bohaterów Warszawy 37) - 26-27.09.2020 Bydgoszcz (Plac Wolności 9) - 19.09.2020 Bytom (ul. Podgórna 9) - 26.09.2020 Chełm (ul.

# data[].attributes.body
SQL tutorial:
https://www.w3schools.com/sql/sql_select.asp
SQLite Studio:
https://sqlitestudio.pl/index.rvt?act=download
Driver:
https://bitbucket.org/xerial/sqlite-jdbc/downloads/
Connection:
https://www.youtube.com/watch?v=NoPzqahrzp8

# data[].attributes.body
https://www.youtube.com/watch?v=lHDghZE7c-8
https://www.youtube.com/watch?v=yySQWaxZqx4
https://www.youtube.com/watch?v=gENFTNd7T2M
https://www.youtube.com/watch?v=gJYXctDSIl8
https://www.youtube.com/watch?v=9wnetxZ_Www

# data[].attributes.attachment_link.readable_text
package sample;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.shape.Polygon;
import javafx.stage.Stage;

public class Main extends Application {

    public static class Point {
        double x;
        double y;

        public Point(double x, double y) {
            this.x = x;
            this.y = y;
        }

        public static Point middlePoint(Point a, Point b) {
            return new Point((a.x + b.x) / 2, (a.y + b.y) / 2);
        }
    }

    Stage stage;
    Scene scene;
    Group group;

    @Override
    public void start(Stage primaryStage) throws Exception{
        stage = primaryStage;
        stage.setTitle("Sierpiński triangle");

        group = new Group();

        Point a = new Point(100, 700);
        Point b = new Point(700, 700);
        Point c = new Point(400, 100);

        drawLine(a, b);
        drawLine(b, c);
        drawLine(c, a);
        drawSierpinskiTriangle(a, b, c, 8);

        scene = new Scene(group, 800, 800);
        stage.setScene(scene);
        stage.show();
    }

    private void drawLine(Point start, Point end) {
        Line line = new Line(start.x, start.y, end.x, end.y);
        line.setStrokeWidth(4);
        line.setFill(Color.BLACK);

        group.getChildren().add(line);
    }

    private void drawTriangle(Point a, Point b, Point c) {
        Polygon triangle = new Polygon(a.x, a.y, b.x, b.y, c.x, c.y);
        triangle.setFill(Color.BLACK);

        group.getChildren().add(triangle);
    }

    private void drawSierpinskiTriangle(Point a, Point b, Point c, int depth) {
        if (depth > 0) {
            Point ab = Point.middlePoint(a, b);
            Point bc = Point.middlePoint(b, c);
            Point ca = Point.middlePoint(c, a);

            drawTriangle(ab, bc, ca);

            drawSierpinskiTriangle(a, ab, ca, depth - 1);
            drawSierpinskiTriangle(ab, b, bc, depth - 1);
            drawSierpinskiTriangle(bc, c, ca, depth - 1);
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

# data[].attributes.body
update
LocalDate.of(2019, 12, 03)

# data[].attributes.attachment_link.readable_text
To jest jeden z artykułów w ramach darmowego kursu programowania w Javie. Proszę zapoznaj się z pozostałymi częściami, mogą one być pomocne w zrozumieniu materiału z tego artykułu.

Czym jest serializacja

W jednym z poprzednich artykułów przeczytałeś o strumieniach danych, które pozwalały na zapisywanie oraz odczytywanie danych. Poznałeś wówczas między innymi klasy DataInputStream oraz DataOutputStream. Klasy te pomagają zapisywać typy proste i łańcuchy znaków.

Serializacja to wbudowany mechanizm zapisywania obiektów, który pozwala na binarny zapis całego drzewa obiektów. Oznacza to tyle, że jeśli mamy obiekt X, który posiada referencję do obiektu Y to serializując X również Y zostanie automatycznie zapisany w strumieniu wyjściowym.

Tak zapisany obiekt możesz później otworzyć przy kolejnym uruchomieniu programu. Jednak serializacja ma więcej zastosowań.

Dzięki temu mechanizmowi można na przykład przesyłać obiekty przez sieć. Obiekt, który stworzyliśmy na jednym komputerze (wewnątrz pamięci jednej wirtualnej maszyny Java) może być zserializowany, przesłany przez sieć i zdeserializowany na drugim komputerze tworząc nową instancję obiektu (wewnątrz pamięci drugiej wirtualnej maszyny Javy). Na obu tych komputerach wirtualna maszyna Javy musi mieć dostęp do skompilowanej wersji klasy.

Przygotowałem rozwiązania kilku zadań algorytmicznych z rozmów kwalifikacyjnych. Rozkładam je na czynniki pierwsze i pokazuję różne sposoby ich rozwiązania. Dołącz do grupy ponad 2501 Samouków, którzy jako pierwsi dowiadują się o nowych treściach na blogu, a prześlę je na Twój e-mail.

Warunki wymagane do serializacji

Chociaż serializacja dostępna jest automatycznie dla większości obiektów z biblioteki standardowej to jeśli chcesz móc serializować instancje klas, które sam napiszesz musisz spełnić kilka warunków.

Jest to tak zwany interfejs znacznikowy, innymi słowy nie zwiera on żadnej metody. Służy on do pokazania wirtualnej maszynie, że instancje danej klasy implementującej ten interfejs mogą być serializowane. Musisz implementować ten interfejs jeśli chcesz aby twoje klasy były serializowalne. Jeśli będziesz próbował zserializować klasę, która nie implementuje tego interfejsu zostanie rzucony wyjątek typu NotSerializableException.

Konstruktor bezparametrowy

Tutaj reguła niestety nie jest trywialna. Pierwsza klasa w hierarchii dziedziczenia, która nie jest serializowalna musi mieć dostępny konstruktor bezparametrowy. Łatwiej to będzie zrozumieć na przykładzie:

W przykładzie powyżej klasa Fruit musi mieć konstruktor bezparametrowy abyśmy mogli poprawnie serializować instancje klasy Apple. Natomiast ani Apple, ani Tomato takiego konstruktora już nie wymagają ( Tomato dziedziczy po Object, który taki konstruktor posiada).

Dodatkowo istnieje interfejs java.io.Externalizable (opiszę go dokładnie kilka akapitów niżej), który również zapewnia, że obiekty go implementujące są serializowalne. Jednak w tym przypadku obiekt taki musi także zapewnić konstruktor bezparametrowy, który jest wywoływany w trakcie deserializacji.

Określić pola, które nie są serializowalne

Ten krok jest opcjonalny, jednak w bardziej zaawansowanych przypadkach niezbędny. Wyobraź sobie, że napisałeś klasę Human, która jako jeden z atrybutów posiada wiek zapisany w minutach od urodzenia. Zapisanie tego pola mogłoby prowadzić do odczytania niepoprawnego stanu (zapisujemy obiekt dzisiaj, odczytujemy jutro, wiek w minutach jest zupełnie inny).

Tutaj dochodzimy do słowa kluczowego transient. Otóż słowo to może być stosowane przed atrybutami klasy. Oznacza ono, że dany atrybut nie jest serializowalny i zostanie pominięty przez mechanizm serializacji.

Przykład serializacji obiektu

Proszę zwróć uwagę na fragment kodu poniżej, który pokazuje jak mechanizm serializacji działa w praktyce.

W pierwszym bloku try-with-resources otwieramy strumień typu ObjectOutputStream, na którym następnie wywołujemy metodę writeObject zapisując do strumienia dwie liczby.

W kolejnym bloku dzięki instancji ObjectInputStream odczytujemy wcześniej zapisane obiekty. Obiekty odczytywane są w takiej samej kolejności w jakiej zostały zapisane, w naszym przypadku na konsoli zostaną wyświetlone liczby 1 a później 2.

Serializacja drzewa obiektów

Wspomniałem już wcześniej, że mechanizm serializacji automatycznie obsługuje drzewa obiektów. W przykładzie poniżej pokazana jest właśnie taka sytuacja. Instancja klasy Car posiada atrybuty typów Engine oraz Tyre[]. Serializując a następnie deserializując instancję tej klasy wszystkie jej atrybuty zostały także zapisane.

Zwróć proszę uwagę na ostatnią linię. W linijce tej porównywane są dwa adresy instancji klasy Car (pamiętasz różnicę między == a equals?). Oczywiście linijka ta wyświetli false na konsoli co dowodzi, że w procesie deserializacji został stworzony zupełnie nowy obiekt klasy Engine.

Deserializacja atrybutów transient

Zaraz, jak to? Przecież kilka akapitów wyżej napisałem, że atrybuty poprzedzone słowem kluczowym transient nie są serializowane. Tak to prawda, jednak podczas deserializacji atrybuty tego typu należy zainicjalizować pewną wartością. Otóż dla każdego typu mamy taką domyślną wartość:

W przykładzie powyżej po deserializacji pole age będzie miało wartość null ponieważ jest to wartość domyślna dla atrybutów poprzedzonych słowem kluczowym transient, które są obiektami.

Pola statyczne a serializacja

Serializacja dotyczy instancji klasy, nie samej klasy. Zatem jeśli zmodyfikowałeś pole statyczne a następnie zdeserializowałeś taki obiekt wprowadzone zmiany zostaną pominięte. Proszę spójrz na przykład poniżej.

W przykładzie tym modyfikujemy wartość pola statycznego someField a następnie serializujemy instancję klasy do pliku.

W drugim uruchomieniu programu (w którym nie zmodyfikowaliśmy wartości atrybutu statycznego someField) deserializujemy ten sam plik. W tym przypadku otrzymamy wartość 100 a nie 200, które miał obiekt zapisywany do pliku.

To co trzeba zapamiętać to to, że pola statyczne nie są serializowane a są pobierane z aktualnej definicji klasy (nie z klasy z momentu serializacji).

Możemy powiedzieć, że atrybuty static są też domyślnie transient. Jak zatem takie zmiany odzwierciedlić podczas deserializacji? Jest na to sposób :)

Specjalna obsługa serializacji/deserializacji

W specyficznych przypadkach masz możliwość zmodyfikowania domyślnego zachowania mechanizmu serializacji. Możesz to zrobić jeśli zaimplementujesz poniższe metody.

Metoda readObject(java.io.ObjectInputStream stream), którą zaimplementujesz jest automatycznie wywoływana w momencie odczytywania obiektu ze strumienia, czyli w trakcie wywołania metodyObjectInputStream.readObject().

Mechanizm ten wygląda podobnie w przypadku zapisu obiektu. Metoda writeObject(java.io.ObjectOutputStream stream), którą zaimplementujesz jest automatycznie wywoływana w momencie zapisywania obiektu do strumienia, czyli w trakcie wywołania metody ObjectOutputStream.writeObject().

Poniższy przykład powinien Ci pomóc w zrozumieniu tego mechanizmu:

Jak widzisz obie metody są tu zaimplementowane. writeObject jako argument dostaje strumień, do którego powinniśmy zapisać nasz obiekt. Metoda readObject jako jedyny argument przyjmuje strumień, z którego powinniśmy odczytać stan obiektu.

Warto tutaj zwrócić uwagę na to, że klasa ObjectInputStream posiada metodę defaultReadObject, która przeprowadza standardową deserializację, którą możesz rozszerzyć. Podobnie wygląda to w przypadku klasy ObjectOutputStream i metody defaultWriteObject. Metody te mogą być wywołane wyłącznie w trakcie (de)serializacji obiektu. Zajmują się one (de)serializacją atrybutów klasy, które nie są oznaczone jako static lub transient.

Serializacja a dziedziczenie

W poprzednich przykładach użyliśmy klasy Engine, która implementuje interfejs Serializable. Załóżmy, że utworzyliśmy klasę DieselEngine, która dziedziczy po Engine. Automatycznie instancje klasy DieselEngine będą implementowały interfejs Serializable (dziedzicząc go z Engine). Co powinniśmy zrobić jeśli nie chcielibyśmy aby nasz DieselEngine był serializowalny? Należy użyć wspomnianego już wyjątku NotSerializableException jak w przykładzie poniżej:

Pełny wpływ na mechanizm serializacji

Istnieje jeszcze jeden, dużo mniej popularny sposób zapewnienia iż obiekt może być serializowany. Jest nim interfejs Externalizable. W tym przypadku interfejs ten zawiera dwie metody, które musimy zaimplementować. Dodatkowo takie klasy muszą mieć konstruktor bezparametrowy, reszta pozostaje bez zmian. W przypadku tego podejścia cały protokół serializacji, kolejność zapisanych pól, format etc. leży po naszej stronie. Poniżej prosty przykład, w którym używam właśnie takiego podejścia.

W tym przypadku do utworzenia obiektu mechanizm serializacji używa standardowego konstruktora bezparametrowego. Po czym wywołuje na tej instancji metodę readExternal.

Pole serialVersionUID

Dodatkowo musisz wiedzieć o statycznym polu w klasie o nazwie serialVersionUID. Jego pełna definicja wygląda następująco:

Pole to ma specyficzne zastosowanie. Mechanizm serializacji używa go do upewnienia się, że deserializowany obiekt „pasuje" do danych zapisanych w strumieniu. Wie o tym na podstawie wartości tego pola. Jeśli w zdeserializowanym obiekcie wartość tego pola jest taka sama jak aktualnej definicji klasy wówczas można bezpiecznie przeprowadzić deserializację.

Kiedy taka sytuacja może wystąpić? Załóżmy, że dzisiaj napiszesz klasę Human, zdeserializujesz jej instancję i zapiszesz w pliku na dysku. Po jakimś czasie wprowadzisz zmiany w klasie i będziesz chciał odczytać starą wersję z pliku. W niektórych przypadkach taka operacja nie będzie dozwolona. Właśnie wtedy pole serialVersionUID może pomóc w wykryciu takiej sytuacji.

Pole to możesz ustawić samodzielnie, jeśli tego nie zrobisz kompilator wygeneruje tę wartość za Ciebie na podstawie definicji klasy.

Materiały dodatkowe

Na początek zestaw dokumentacji do klas, związanych z tematem, jak zwykle znajdziesz tam ogrom informacji.

Dodatkowo możesz zajrzeć do specyfikacja mechanizmu serializacji albo artykułu na stronie Oracle. Znalazłem też inne opracowanie, które poruszą także zagadnienie serializacji, także do formatu XML. Możesz też rzucić okiem na przykłady użyte w tym artykule.

Zadania

Na koniec jak zwykle zadania dla Ciebie do przećwiczenia materiału z tego artykułu.

Napisz program, który poprosi użytkownika o wprowadzenie kilku imion, imiona te zapisz w liście a następnie zserializuj ją do pliku. Napisz metodę, która odczyta ten plik i wyświetli zawartość listy na konsoli. Wiesz, że właśnie napisałeś prostą bazę danych? ;)

Napisz klasę Human, która będzie miała dwa atrybuty name typu String oraz age typu int. Jak należałoby serializować instancje tej klasy aby zawsze poprawnie deserializować wiek (z dokładnością do roku)? (Wskazówka, możesz użyć metody Calendar.getInstance().get(Calendar.YEAR), która zwraca aktualny rok)

Przygotowałem też dla Ciebie przykładowe rozwiązania powyższych zadań, jednak traktuj je proszę jako ostatnią deskę ratunku :) Więcej nauczysz się próbując samemu rozwiązać powyższe zadania.

Podsumowanie

Po przeczytaniu tego artykułu wiesz już czym są klasy ObjectOutputStream i ObjectInputStream. Znasz zasady serializacji, poznałeś słowo kluczowe transient. Teraz jesteś w stanie zapisać i odczytać każdą instancję klasy, którą stworzysz.

Bardzo się cieszę, że przeczytałeś cały artykuł. Na koniec mam do Ciebie prośbę. Proszę przekaż adres bloga swoim znajomym, w grupie uczy się raźniej ;) Jeśli nie chcesz ominąć nowych artykułów dopisz się do newslettera i polub stronę Samouczka na Facebooku. Miłego dnia i do następnego razu :)

Przygotowałem rozwiązania kilku zadań algorytmicznych z rozmów kwalifikacyjnych. Rozkładam je na czynniki pierwsze i pokazuję różne sposoby ich rozwiązania. Dołącz do grupy ponad 2501 Samouków, którzy jako pierwsi dowiadują się o nowych treściach na blogu, a prześlę je na Twój e-mail.

# data[].attributes.attachment_link.description
W artykule tym dowiesz się czym jest serializacja obiektów w Javie. Przeczytasz o klasach takich jak ObjectInputStream czy ObjectOutputStream i dowiesz się czym różnią się od innych strumieni. Poznasz nowe słowo kluczowe transient. Po przeczytaniu artykułu będziesz w stanie napisać swoją mini bazę danych z użyciem mechanizmu serializacji. Zapraszam do lektury.

# data[].attributes.body
- retrive animals data from the file
- display animals data
- add a new animal (refresh the window)
- display animals stats
- save data in the file

# data[].attributes.body
1. Matrix determinant
https://pl.wikipedia.org/wiki/Rozwini%C4%99cie_Laplace%E2%80%99a
2. Voldemort's martix determinant
https://pl.wikipedia.org/wiki/Macierz_Vandermonde%E2%80%99a

# data[].attributes.attachment_link.readable_text
Java is an object-oriented programming language. It allows you to divide complex problems into smaller sets by creating objects.

These objects share two characteristics:

Let's take few examples:

You will learn about 3 main features of an object-oriented programming: data encapsulation, inheritance and polymorphism in later chapters. This article will focus on class and objects to keep things simple.

Recommended reading: What is an object?

Java Class

Before you create objects in Java, you need to define a class.

A class is a blueprint for the object.

We can think of class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object.

Since, many houses can be made from the same description, we can create many objects from a class.

How to define a class in Java?

Here's how a class is defined in Java:

class ClassName { // variables   // methods }

Here's an example:

class Lamp {   // instance variable private boolean isOn;   // method public void turnOn() { isOn = true; } // method public void turnOff() { isOn = false; } }

Here, we defined a class named Lamp.

The class has one instance variable (variable defined inside class) isOn and two methods turnOn() and turnOff(). These variables and methods defined within a class are called members of the class.

Notice two keywords, private and public in the above program. These are access modifiers which will be discussed in detail in later chapters. For now, just remember:

The private keyword makes instance variables and methods private which can be accessed only from inside the same class.

The public keyword makes instance variables and methods public which can be accessed from outside of the class.

In the above program, isOn variable is private whereas turnOn() and turnOff() methods are public.

If you try to access private members from outside of the class, compiler throws error.

Java Objects

When class is defined, only the specification for the object is defined; no memory or storage is allocated.

To access members defined within the class, you need to create objects. Let's create objects of Lamp class.

class Lamp {
 boolean isOn; void turnOn() { isOn = true; } void turnOff() { isOn = false; } } class ClassObjectsExample { public static void main(String[] args) { Lamp l1 = new Lamp(); // create l1 object of Lamp class Lamp l2 = new Lamp(); // create l2 object of Lamp class } }

This program creates two objects l1 and l2 of class Lamp.

How to access members?

You can access members (call methods and access instance variables) by using . operator. For example,

l1.turnOn();

This statement calls turnOn() method inside Lamp class for l1 object.

We have mentioned word method quite a few times. You will learn about Java methods in detail in the next chapter. Here's what you need to know for now:

When you call the method using the above statement, all statements within the body of turnOn() method are executed. Then, the control of program jumps back to the statement following l1.turnOn();

Similarly, the instance variable can be accessed as:

l2.isOn = false;

It is important to note that, the private members can be accessed only from inside the class. If the code l2.isOn = false; lies within the main() method (outside of the Lamp class), compiler will show error.

Example: Java Class and Objects

class Lamp { boolean isOn; void turnOn() { isOn = true; } void turnOff() { isOn = false; } void displayLightStatus() { System.out.println("Light on? " + isOn); } } class ClassObjectsExample { public static void main(String[] args) { Lamp l1 = new Lamp(), l2 = new Lamp(); l1.turnOn(); l2.turnOff(); l1.displayLightStatus(); l2.displayLightStatus(); } }

When you run the program, the output will be:

Light on? true Light on? false

In the above program,

Lamp class is created.

The class has an instance variable isOn and three methods turnOn(), turnOff() and displayLightStatus().

Two objects l1 and l2 of Lamp class are created in the main() function.

Here, turnOn() method is called using l1 object: l1.turnOn();

This method sets isOn instance variable of l1 object to true.

And, turnOff() method is called using l2 object: l2.turnOff();

This method sets isOff instance variable of l2 object to false.

Finally, l1.displayLightStatus(); statement displays Light on? true because isOn variable holds true for l1 object.

And, l2.displayLightStatus(); statement displays Light on? false because isOn variable holds false for l2 object

Note, variables defined within a class are called instance variable for a reason.

When an object is initialized, it's called an instance. Each instance contains its own copy of these variables. For example, isOn variable for objects l1 and l2 are different.

This article is just a basic introduction on Java Class and Objects. Check these chapters in sequence to learn more:

Java Methods

Java Constructors

Java Access Modifiers

Java this Keyword

Java garbage collection and finalize()

# data[].attributes.attachment_link.description
Java is an object-oriented programming language. It allows you to divide complex problems into smaller sets by creating objects. These objects share two characteristics: Let's take few examples: You will learn about 3 main features of an object-oriented programming: data encapsulation, inheritance and polymorphism in later chapters.

# data[].attributes.attachment_link.readable_text
package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.geometry.Rectangle2D;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;

import java.util.Arrays;

public class Main extends Application {

    Stage stage;

    int[][] landingSite;



    @Override
    public void start(Stage primaryStage) throws Exception{
        stage = primaryStage;
        stage.setTitle("Moon lander");

        getRandomLandingSite(40, 40, 0, 6);
        drawLandingSite();
    }

    private void getRandomLandingSite(int rows, int columns, int min, int max) {
        landingSite = new int[rows][columns];
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < columns; c++) {
                landingSite[r][c] = (int) (Math.random() * (max - min + 1) + min);
            }
        }
        System.out.println(Arrays.deepToString(landingSite));
    }

    private void drawLandingSite() {
        GridPane root = new GridPane();
        root.setAlignment(Pos.CENTER);

        for (int r = 0; r < landingSite.length; r++) {
            for (int c = 0; c < landingSite[0].length; c++) {
                Rectangle rectangle = new Rectangle(20, 20, Color.WHITE);
                rectangle.setStroke(Color.GRAY);

                Text text = new Text("" + landingSite[r][c]);
                text.setFont(Font.font(16));
                text.setFill(Color.GRAY);

                root.add(rectangle, c, r);
                root.add(text, c, r);
            }
        }

        double minDistance = Double.MAX_VALUE;
        int r1, r2, r3, r4;
        int c1, c2, c3, c4;

        int landerX = landingSite.length / 2;
        int landerY = landingSite[0].length / 2;

        for (int r = 0; r < landingSite.length - 1; r++) {
            for (int c = 0; c < landingSite[0].length- 1; c++) {
                if (landingSite[r][c] == landingSite[r + 1][c] && landingSite[r][c] == landingSite[r][c + 1]
                        && landingSite[r][c] == landingSite[r + 1][c + 1]) {

                    double fieldX = (c + c + 1) / 2;
                    double fieldY = (r + r + 1) / 2;

                    double distance = Math.pow(landerX - fieldX, 2) + Math.pow(landerY - fieldY, 2);
                    if (distance < minDistance) {
                        
                    }

                    Rectangle rectangle = new Rectangle(20, 20, Color.RED);
                    rectangle.setStroke(Color.GRAY);

                    Text text = new Text("" + landingSite[r][c]);
                    text.setFont(Font.font(16));
                    text.setFill(Color.BLACK);

                    root.add(rectangle, c, r);
                    root.add(text, c, r);

                    Rectangle rectangle1 = new Rectangle(20, 20, Color.RED);
                    rectangle1.setStroke(Color.GRAY);

                    Text text1 = new Text("" + landingSite[r][c]);
                    text1.setFont(Font.font(16));
                    text1.setFill(Color.BLACK);

                    root.add(rectangle1, c + 1, r);
                    root.add(text1, c + 1, r);

                    Rectangle rectangle2 = new Rectangle(20, 20, Color.RED);
                    rectangle2.setStroke(Color.GRAY);

                    Text text2 = new Text("" + landingSite[r][c]);
                    text2.setFont(Font.font(16));
                    text2.setFill(Color.BLACK);

                    root.add(rectangle2, c, r + 1);
                    root.add(text2, c, r + 1);

                    Rectangle rectangle3 = new Rectangle(20, 20, Color.RED);
                    rectangle3.setStroke(Color.GRAY);

                    Text text3 = new Text("" + landingSite[r][c]);
                    text3.setFont(Font.font(16));
                    text3.setFill(Color.BLACK);

                    root.add(rectangle3, c + 1, r + 1);
                    root.add(text3, c + 1, r + 1);
                }
            }
        }

        // TODO: 2019-11-07 find and draw the closest one
        for (int r = 0; r < landingSite.length - 1; r++) {
            for (int c = 0; c < landingSite[0].length - 1; c++) {
                if (landingSite[r][c] == landingSite[r + 1][c] && landingSite[r][c] == landingSite[r][c + 1]
                        && landingSite[r][c] == landingSite[r + 1][c + 1]) {
                    Rectangle rectangle = new Rectangle(20, 20, Color.GREEN);
                    rectangle.setStroke(Color.GRAY);

                    Text text = new Text("" + landingSite[r][c]);
                    text.setFont(Font.font(16));
                    text.setFill(Color.BLACK);

                    root.add(rectangle, c, r);
                    root.add(text, c, r);

                    Rectangle rectangle1 = new Rectangle(20, 20, Color.GREEN);
                    rectangle1.setStroke(Color.GRAY);

                    Text text1 = new Text("" + landingSite[r][c]);
                    text1.setFont(Font.font(16));
                    text1.setFill(Color.BLACK);

                    root.add(rectangle1, c + 1, r);
                    root.add(text1, c + 1, r);

                    Rectangle rectangle2 = new Rectangle(20, 20, Color.GREEN);
                    rectangle2.setStroke(Color.GRAY);

                    Text text2 = new Text("" + landingSite[r][c]);
                    text2.setFont(Font.font(16));
                    text2.setFill(Color.BLACK);

                    root.add(rectangle2, c, r + 1);
                    root.add(text2, c, r + 1);

                    Rectangle rectangle3 = new Rectangle(20, 20, Color.GREEN);
                    rectangle3.setStroke(Color.GRAY);

                    Text text3 = new Text("" + landingSite[r][c]);
                    text3.setFont(Font.font(16));
                    text3.setFill(Color.BLACK);

                    root.add(rectangle3, c + 1, r + 1);
                    root.add(text3, c + 1, r + 1);
                }
            }
        }

        Scene scene = new Scene(root, 1000, 1000);
        stage.setScene(scene);
        stage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}

# data[].attributes.body
You must install Git:
https://git-scm.com/downloads

List of steps:
I. Leader
- on Github:
1) create new repo and copy link to it
2) add collaborators in Github
- in IntelliJ:
1) VCS -> Enable VCS
2) add files to VCS
3) VCS -> Git -> Remotes
and copy adres of the repo

II. Team member
- on Github:
1) accept invitation link and copy link to repo
- in IntelliJ:
1) File -> Project from Version Control -> Git (past link to repo)

III. Work in IntelliJ
1) update from online repo
2) commit changes to offline repo
3) push changes to online repo

# data[].attributes.body
<!--https://stackoverflow.com/questions/27037657/stop-intellij-idea-to-switch-java-language-level-every-time-the-pom-is-reloaded-->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.10</source>
<target>1.10</target>
</configuration>
</plugin>
</plugins>
</build>

# data[].attributes.body
https://docs.oracle.com/javafx/2/ui_controls/file-chooser.htm

https://o7planning.org/en/11129/javafx-filechooser-and-directorychooser-tutorial

# data[].attributes.attachment_link.title
JavaFX Java GUI Tutorial - 1 - Creating a Basic Window

# data[].attributes.body
https://www.tutorialspoint.com/javafx/javafx_ui_controls.htm

# data[].attributes.attachment_link.readable_text
package com.company;

import java.util.Arrays;

public class Main {

    static final int ROWS = 5;
    static final int COLUMNS = 5;

    public static void main(String[] args) {
	    int[][] numbers = new int[ROWS][COLUMNS];
	    for (int r = 0; r < ROWS; r++) {
            for (int c = 0; c < COLUMNS; c++) {
                numbers[r][c] = (int) (Math.random() * 10);
            }
        }
        System.out.println(Arrays.deepToString(numbers));

        int[][] ages = {
                {5, 1, 4, 6},
                {5, 3, 6, 5},
                {9, 8, 5, 5},
                {9, 6, 5, 6}
        };
        for (int r = 0; r < ages.length; r++) {
            for (int c = 0; c < ages[r].length; c++) {
                System.out.print(ages[r][c] + " ");
            }
            System.out.println();
        }
        System.out.println(getMostCommonDigit(ages));

        int[][] binary = {
                {0, 1, 0, 0},
                {1, 0, 0, 0},
                {0, 0, 1, 0},
                {0, 0, 0, 1}
        };
        System.out.println(isBinary(binary));

        int[][] skew = {
                {-6, 1, -9, 7},
                {-1, 5, 1, 0},
                {9, -1, 3, -2},
                {-7, 0, 2, 1}
        };
        System.out.println(isSkewSymmetric(skew));

        System.out.println(Arrays.deepToString(ages));
        System.out.println(Arrays.deepToString(sumOfNearbyCells(ages)));
    }

    public static boolean isSkewSymmetric(int[][] numbers) {
        int rows = numbers.length;
        for (int r = 0; r < numbers.length; r++) {
            if (rows != numbers[r].length) {
                return false;
            }
        }

        for (int r = 0; r < numbers.length - 1; r++) {
            for (int c = r + 1; c < numbers[r].length; c++) {
                if (numbers[r][c] + numbers[c][r] != 0) {
                    return false;
                }
            }
        }

        return true;
    }

    public static boolean isBinary(int[][] numbers) {
        if (numbers == null) {
            return false;
        }

        for (int r = 0; r < numbers.length; r++) {
            for (int c = 0; c < numbers[r].length; c++) {
                if (numbers[r][c] != 0 && numbers[r][c] != 1) {
                //if ( ! (numbers[r][c] == 0 || numbers[r][c] == 1) ) {
                    return false;
                }
            }
        }

        for (int r = 0; r < numbers.length; r++) {
            int sum = 0;
            for (int c = 0; c < numbers[r].length; c++) {
                sum += numbers[r][c];
            }
            if (sum != 1) {
                return false;
            }
        }

        for (int c = 0; c < numbers[0].length; c++) {
            int sum = 0;
            for (int r = 0; r < numbers.length; r++) {
                sum += numbers[r][c];
            }
            if (sum != 1) {
                return false;
            }
        }

        return true;
    }

    public static int getMostCommonDigit(int[][] numbers) {
        int[] counters = new int[10];
        for (int r = 0; r < numbers.length; r++) {
            for (int c = 0; c < numbers[r].length; c++) {
                counters[ numbers[r][c] ]++;
            }
        }
        System.out.println(Arrays.toString(counters));
        int max = counters[0];
        int index = 0;
        for (int i = 0; i < counters.length; i++) {
            if (counters[i] > max) {
                max = counters[i];
                index = i;
            }
        }
        return index;
    }

    public static int[][] sumOfNearbyCells(int[][] numbers){
        int sum[][] = new int[numbers.length][numbers[0].length];
        for (int i = 0; i < numbers.length; i++) {
            for (int j = 0; j < numbers[0].length; j++) {
                sum[i][j] = getNeighboursNumber(numbers, i, j);
            }
        }
        return sum;
    }

    private static int getNeighboursNumber(int[][] numbers, int row, int column) {
        int sum = 0;
        for (int i = -1; i <= 1 ; i++) {
            for (int j = -1; j <= 1 ; j++) {
                if (i != 0 || j != 0) {
                    sum += getNeighbourFrom(numbers, row + i, column + j);
                }
            }
        }
        return sum;
    }

    private static int getNeighbourFrom(int[][] numbers, int row, int column) {
        if (row < 0 || column < 0 || row >= numbers.length || column >= numbers[0].length) {
            return 0;
        }
        return numbers[row][column];
    }

}

# data[].attributes.body
List of steps:
I. On Github:
1) create new repo and copy link to it

II. In IntelliJ:
1) VCS -> Enable VCS
2) add files to VCS
3) VCS -> Git -> Remotes
and copy adres of the repo

III. Work in IntelliJ
1) commit changes to offline repo
2) push changes to online repo

# data[].attributes.attachment_link.description
Git is easy to learn and has a tiny footprint with lightning fast performance. It outclasses SCM tools like Subversion, CVS, Perforce, and ClearCase with features like cheap local branching, convenient staging areas, and multiple workflows.

# data[].attributes.body
https://www.programiz.com/java-programming/multidimensional-array

# data[].attributes.body
int[] numbers = {1, 4, 15, 17, 23, 36};
String[] names = {"Adam", "John", "Alex", "Zoe", "Mark", "Luce"};
int givenNumber = 22_746_332;

Create the following methods:
1. Calculate average number.
2. Return index of first appearance or -1 for numbers array (linear search / *binary search).
3. Calculate how many times the array contains name starting with given letter (char / String).
4. Calculate how many elements in the array are between given boundaries (intigers).
5. Calculate digits sum for given number.

# data[].attributes.body
czwartek godz. 8.00 - 10.00

# data[].attributes.attachment_link.title
Zadania z Olimpiady Lingwistyki Matematycznej | Fundacja Matematyków Wrocławskich

# data[].attributes.attachment_link.description
Strona główna/ Dla uczniów/ Lingwistyka matematyczna/ Olimpiada Lingwistyczna/ Zadania z Olimpiady Lingwistyki Matematycznej

# data[].attributes.body
1. Wtorek, godz. 15:30 - 17:00
Programowanie dla średnio-zaawansowanych w Javie:
- projektowanie prostych gier (2048, tetris, snake)

2. Czwartek, godz. 15:30 - 17:00
Sztuczna inteligencja (dla średnio-zaawansowanych):
- algorytmy genetyczne i sieci neuronowe od podstaw
- aplikacje mobilne na Androida

3. Środa, godz. 15:30 - 17:00 (zapisy u p. Głuskiego)
Nauka programowania od podstaw w C++

# data[].attributes.attachment_link.readable_text
In cryptography, a substitution cipher is a method of encrypting by which units of plaintext are replaced with ciphertext, according to a fixed system; the "units" may be single letters (the most common), pairs of letters, triplets of letters, mixtures of the above, and so forth. The receiver deciphers the text by performing the inverse substitution.

Substitution ciphers can be compared with transposition ciphers. In a transposition cipher, the units of the plaintext are rearranged in a different and usually quite complex order, but the units themselves are left unchanged. By contrast, in a substitution cipher, the units of the plaintext are retained in the same sequence in the ciphertext, but the units themselves are altered.

There are a number of different types of substitution cipher. If the cipher operates on single letters, it is termed a simple substitution cipher; a cipher that operates on larger groups of letters is termed polygraphic. A monoalphabetic cipher uses fixed substitution over the entire message, whereas a polyalphabetic cipher uses a number of substitutions at different positions in the message, where a unit from the plaintext is mapped to one of several possibilities in the ciphertext and vice versa.

Substitution of single letters separately- simple substitution-can be demonstrated by writing out the alphabet in some order to represent the substitution. This is termed a substitution alphabet. The cipher alphabet may be shifted or reversed (creating the Caesar and Atbash ciphers, respectively) or scrambled in a more complex fashion, in which case it is called a mixed alphabet or deranged alphabet. Traditionally, mixed alphabets may be created by first writing out a keyword, removing repeated letters in it, then writing all the remaining letters in the alphabet in the usual order.

Using this system, the keyword " zebras" gives us the following alphabets:

A message of

flee at once. we are discovered!

enciphers to

SIAA ZQ LKBA. VA ZOA RFPBLUAOAR!

Traditionally, the ciphertext is written out in blocks of fixed length, omitting punctuation and spaces; this is done to help avoid transmission errors and to disguise word boundaries from the plaintext. These blocks are called "groups", and sometimes a "group count" (i.e., the number of groups) is given as an additional check. Five-letter groups are traditional, dating from when messages used to be transmitted by telegraph:

SIAAZ QLKBA VAZOA RFPBL UAOAR

If the length of the message happens not to be divisible by five, it may be padded at the end with " nulls". These can be any characters that decrypt to obvious nonsense, so the receiver can easily spot them and discard them.

The ciphertext alphabet is sometimes different from the plaintext alphabet; for example, in the pigpen cipher, the ciphertext consists of a set of symbols derived from a grid. For example:

Such features make little difference to the security of a scheme, however - at the very least, any set of strange symbols can be transcribed back into an A-Z alphabet and dealt with as normal.

In lists and catalogues for salespeople, a very simple encryption is sometimes used to replace numeric digits by letters.

Example: MAT would be used to represent 120.

Security for simple substitution ciphers

Although the traditional keyword method for creating a mixed substitution alphabet is simple, a serious disadvantage is that the last letters of the alphabet (which are mostly low frequency) tend to stay at the end. A stronger way of constructing a mixed alphabet is to perform a columnar transposition on the ordinary alphabet using the keyword, but this is not often done.

Although the number of possible keys is very large (26! ≈ 2 88.4, or about 88 bits), this cipher is not very strong, and is easily broken. Provided the message is of reasonable length (see below), the cryptanalyst can deduce the probable meaning of the most common symbols by analyzing the frequency distribution of the ciphertext. This allows formation of partial words, which can be tentatively filled in, progressively expanding the (partial) solution (see frequency analysis for a demonstration of this). In some cases, underlying words can also be determined from the pattern of their letters; for example, attract, osseous, and words with those two as the root are the only common English words with the pattern ABBCADB. Many people solve such ciphers for recreation, as with cryptogram puzzles in the newspaper.

According to the unicity distance of English, 27.6 letters of ciphertext are required to crack a mixed alphabet simple substitution. In practice, typically about 50 letters are needed, although some messages can be broken with fewer if unusual patterns are found. In other cases, the plaintext can be contrived to have a nearly flat frequency distribution, and much longer plaintexts will then be required by the cryptanalyst.

One once-common variant of the substitution cipher is the nomenclator. Named after the public official who announced the titles of visiting dignitaries, this cipher uses a small code sheet containing letter, syllable and word substitution tables, sometimes homophonic, that typically converted symbols into numbers. Originally the code portion was restricted to the names of important people, hence the name of the cipher; in later years it covered many common words and place names as well. The symbols for whole words ( in modern parlance) and letters ( cipher in modern parlance) were not distinguished in the ciphertext. The Rossignols' Great Cipher used by Louis XIV of France was one.

Nomenclators were the standard fare of diplomatic correspondence, espionage, and advanced political conspiracy from the early fifteenth century to the late eighteenth century; most conspirators were and have remained less cryptographically sophisticated. Although government intelligence cryptanalysts were systematically breaking nomenclators by the mid-sixteenth century, and superior systems had been available since 1467, the usual response to cryptanalysis was simply to make the tables larger. By the late eighteenth century, when the system was beginning to die out, some nomenclators had 50,000 symbols.[citation needed ]

Nevertheless, not all nomenclators were broken; today, cryptanalysis of archived ciphertexts remains a fruitful area of historical research.

An early attempt to increase the difficulty of frequency analysis attacks on substitution ciphers was to disguise plaintext letter frequencies by homophony. In these ciphers, plaintext letters map to more than one ciphertext symbol. Usually, the highest-frequency plaintext symbols are given more equivalents than lower frequency letters. In this way, the frequency distribution is flattened, making analysis more difficult.

Since more than 26 characters will be required in the ciphertext alphabet, various solutions are employed to invent larger alphabets. Perhaps the simplest is to use a numeric substitution 'alphabet'. Another method consists of simple variations on the existing alphabet; uppercase, lowercase, upside down, etc. More artistically, though not necessarily more securely, some homophonic ciphers employed wholly invented alphabets of fanciful symbols.

The Beale ciphers are another example of a homophonic cipher. This is a story of buried treasure that was described in 1819-21 by use of a ciphered text that was keyed to the Declaration of Independence. Here each ciphertext character was represented by a number. The number was determined by taking the plaintext character and finding a word in the Declaration of Independence that started with that character and using the numerical position of that word in the Declaration of Independence as the encrypted form of that letter. Since many words in the Declaration of Independence start with the same letter, the encryption of that character could be any of the numbers associated with the words in the Declaration of Independence that start with that letter. Deciphering the encrypted text character X (which is a number) is as simple as looking up the Xth word of the Declaration of Independence and using the first letter of that word as the decrypted character.

Another homophonic cipher was described by Stahl and was one of the first[citation needed ] attempts to provide for computer security of data systems in computers through encryption. Stahl constructed the cipher in such a way that the number of homophones for a given character was in proportion to the frequency of the character, thus making frequency analysis much more difficult.

The book cipher and straddling checkerboard are types of homophonic cipher.

Francesco I Gonzaga, Duke of Mantua, used the earliest known example of a homophonic substitution cipher in 1401 for correspondence with one Simone de Crema.

The work of Al-Qalqashandi (1355-1418), based on the earlier work of Ibn al-Durayhim (1312-1359), contained the first published discussion of the substitution and transposition of ciphers, as well as the first description of a polyalphabetic cipher, in which each plaintext letter is assigned more than one substitute. Polyalphabetic substitution ciphers were later described in 1467 by Leone Battista Alberti in the form of disks. Johannes Trithemius, in his book Steganographia ( Ancient Greek for "hidden writing") introduced the now more standard form of a tableau (see below; ca. 1500 but not published until much later). A more sophisticated version using mixed alphabets was described in 1563 by Giovanni Battista della Porta in his book, De Furtivis Literarum Notis ( Latin for "On concealed characters in writing").

In a polyalphabetic cipher, multiple cipher alphabets are used. To facilitate encryption, all the alphabets are usually written out in a large table, traditionally called a tableau. The tableau is usually 26×26, so that 26 full ciphertext alphabets are available. The method of filling the tableau, and of choosing which alphabet to use next, defines the particular polyalphabetic cipher. All such ciphers are easier to break than once believed, as substitution alphabets are repeated for sufficiently large plaintexts.

One of the most popular was that of Blaise de Vigenère. First published in 1585, it was considered unbreakable until 1863, and indeed was commonly called le chiffre indéchiffrable ( French for "indecipherable cipher").

In the Vigenère cipher, the first row of the tableau is filled out with a copy of the plaintext alphabet, and successive rows are simply shifted one place to the left. (Such a simple tableau is called a tabula recta, and mathematically corresponds to adding the plaintext and key letters, modulo 26.) A keyword is then used to choose which ciphertext alphabet to use. Each letter of the keyword is used in turn, and then they are repeated again from the beginning. So if the keyword is 'CAT', the first letter of plaintext is enciphered under alphabet 'C', the second under 'A', the third under 'T', the fourth under 'C' again, and so on. In practice, Vigenère keys were often phrases several words long.

In 1863, Friedrich Kasiski published a method (probably discovered secretly and independently before the Crimean War by Charles Babbage) which enabled the calculation of the length of the keyword in a Vigenère ciphered message. Once this was done, ciphertext letters that had been enciphered under the same alphabet could be picked out and attacked separately as a number of semi-independent simple substitutions - complicated by the fact that within one alphabet letters were separated and did not form complete words, but simplified by the fact that usually a tabula recta had been employed.

As such, even today a Vigenère type cipher should theoretically be difficult to break if mixed alphabets are used in the tableau, if the keyword is random, and if the total length of ciphertext is less than 27.67 times the length of the keyword. These requirements are rarely understood in practice, and so Vigenère enciphered message security is usually less than might have been.

Other notable polyalphabetics include:

The Gronsfeld cipher. This is identical to the Vigenère except that only 10 alphabets are used, and so the "keyword" is numerical.

The Beaufort cipher. This is practically the same as the Vigenère, except the tabula recta is replaced by a backwards one, mathematically equivalent to ciphertext = key - plaintext. This operation is self-inverse, whereby the same table is used for both encryption and decryption.

The autokey cipher, which mixes plaintext with a key to avoid periodicity.

The running key cipher, where the key is made very long by using a passage from a book or similar text.

Modern stream ciphers can also be seen, from a sufficiently abstract perspective, to be a form of polyalphabetic cipher in which all the effort has gone into making the keystream as long and unpredictable as possible.

In a polygraphic substitution cipher, plaintext letters are substituted in larger groups, instead of substituting letters individually. The first advantage is that the frequency distribution is much flatter than that of individual letters (though not actually flat in real languages; for example, 'TH' is much more common than 'XQ' in English). Second, the larger number of symbols requires correspondingly more ciphertext to productively analyze letter frequencies.

To substitute pairs of letters would take a substitution alphabet 676 symbols long ( ). In the same De Furtivis Literarum Notis mentioned above, della Porta actually proposed such a system, with a 20 x 20 tableau (for the 20 letters of the Italian/Latin alphabet he was using) filled with 400 unique glyphs. However the system was impractical and probably never actually used.

The earliest practical digraphic cipher (pairwise substitution), was the so-called Playfair cipher, invented by Sir Charles Wheatstone in 1854. In this cipher, a 5 x 5 grid is filled with the letters of a mixed alphabet (two letters, usually I and J, are combined). A digraphic substitution is then simulated by taking pairs of letters as two corners of a rectangle, and using the other two corners as the ciphertext (see the Playfair cipher main article for a diagram). Special rules handle double letters and pairs falling in the same row or column. Playfair was in military use from the Boer War through World War II.

Several other practical polygraphics were introduced in 1901 by Felix Delastelle, including the bifid and four-square ciphers (both digraphic) and the trifid cipher (probably the first practical trigraphic).

The Hill cipher, invented in 1929 by Lester S. Hill, is a polygraphic substitution which can combine much larger groups of letters simultaneously using linear algebra. Each letter is treated as a digit in base 26: A = 0, B =1, and so on. (In a variation, 3 extra symbols are added to make the basis prime.) A block of n letters is then considered as a vector of n dimensions, and multiplied by a n x n matrix, modulo 26. The components of the matrix are the key, and should be random provided that the matrix is invertible in (to ensure decryption is possible). A mechanical version of the Hill cipher of dimension 6 was patented in 1929.[8]

The Hill cipher is vulnerable to a known-plaintext attack because it is completely linear, so it must be combined with some non-linear step to defeat this attack. The combination of wider and wider weak, linear diffusive steps like a Hill cipher, with non-linear substitution steps, ultimately leads to a substitution-permutation network (e.g. a Feistel cipher), so it is possible - from this extreme perspective - to consider modern block ciphers as a type of polygraphic substitution.

Between circa World War I and the widespread availability of computers (for some governments this was approximately the 1950s or 1960s; for other organizations it was a decade or more later; for individuals it was no earlier than 1975), mechanical implementations of polyalphabetic substitution ciphers were widely used. Several inventors had similar ideas about the same time, and rotor cipher machines were patented four times in 1919. The most important of the resulting machines was the Enigma, especially in the versions used by the German military from approximately 1930. The Allies also developed and used rotor machines (e.g., SIGABA and Typex).

All of these were similar in that the substituted letter was chosen electrically from amongst the huge number of possible combinations resulting from the rotation of several letter disks. Since one or more of the disks rotated mechanically with each plaintext letter enciphered, the number of alphabets used was astronomical. Early versions of these machine were, nevertheless, breakable. William F. Friedman of the US Army's SIS early found vulnerabilities in Hebern's rotor machine, and GC&CS's Dillwyn Knox solved versions of the Enigma machine (those without the "plugboard") well before WWII began. Traffic protected by essentially all of the German military Enigmas was broken by Allied cryptanalysts, most notably those at Bletchley Park, beginning with the German Army variant used in the early 1930s. This version was broken by inspired mathematical insight by Marian Rejewski in Poland.

No messages protected by the SIGABA and Typex machines were ever, so far as is publicly known, broken.

One type of substitution cipher, the one-time pad, is quite special. It was invented near the end of World War I by Gilbert Vernam and Joseph Mauborgne in the US. It was mathematically proven unbreakable by Claude Shannon, probably during World War II; his work was first published in the late 1940s. In its most common implementation, the one-time pad can be called a substitution cipher only from an unusual perspective; typically, the plaintext letter is combined (not substituted) in some manner (e.g., XOR) with the key material character at that position.

The one-time pad is, in most cases, impractical as it requires that the key material be as long as the plaintext, actually random, used once and only once, and kept entirely secret from all except the sender and intended receiver. When these conditions are violated, even marginally, the one-time pad is no longer unbreakable. Soviet one-time pad messages sent from the US for a brief time during World War II used non-random key material. US cryptanalysts, beginning in the late 40s, were able to, entirely or partially, break a few thousand messages out of several hundred thousand. (See Venona project)

In a mechanical implementation, rather like the Rockex equipment, the one-time pad was used for messages sent on the Moscow- Washington hot line established after the Cuban missile crisis.

Substitution ciphers as discussed above, especially the older pencil-and-paper hand ciphers, are no longer in serious use. However, the cryptographic concept of substitution carries on even today. From a sufficiently abstract perspective, modern bit-oriented block ciphers (e.g., DES, or AES) can be viewed as substitution ciphers on an enormously large binary alphabet. In addition, block ciphers often include smaller substitution tables called S-boxes. See also substitution-permutation network.

Sherlock Holmes breaks a substitution cipher in "The Adventure of the Dancing Men". There, the cipher remained undeciphered for years if not decades; not due to its difficulty, but because no one suspected it to be a code, instead considering it childish scribblings.

The Al Bhed language in Final Fantasy X is actually a substitution cipher, although it is pronounced phonetically (i.e. "you" in English is translated to "oui" in Al Bhed, but is pronounced the same way that "oui" is pronounced in French).

The Minbari's alphabet from the series is a substitution cipher from English.

The language in Starfox Adventures: Dinosaur Planet spoken by native Saurians and Krystal is also a substitution cipher of the English alphabet.

The television program contained a substitution cipher in which all 26 letters were replaced by symbols and called "Alien Language". This was deciphered rather quickly by the die hard viewers by showing a "Slurm" ad with the word "Drink" in both plain English and the Alien language thus giving the key. Later, the producers created a second alien language that used a combination of replacement and mathematical Ciphers. Once the English letter of the alien language is deciphered, then the numerical value of that letter (0 for "A" through 25 for "Z" respectively) is then added (modulo 26) to the value of the previous letter showing the actual intended letter. These messages can be seen throughout every episode of the series and the subsequent movies.

At the end of every season 1 episode of the cartoon series Gravity Falls, during the credit roll, there is one of three simple substitution ciphers: A -3 Caesar cipher (hinted by "3 letters back" at the end of the opening sequence), an Atbash cipher, or a letter-to-number simple substitution cipher. The season 1 finale encodes a message with all three. In the second season, Vigenère ciphers are used in place of the various monoalphabetic ciphers, each using a key hidden within its episode.

In the Artemis Fowl series by Eoin Colfer there are three substitution ciphers; Gnommish, Centaurean and Eternean, which run along the bottom of the pages or are somewhere else within the books.

In Bitterblue, the third novel by Kristin Cashore, substitution ciphers serve as an important form of coded communication.

In the 2013 video game BioShock Infinite, there are substitution ciphers hidden throughout the game in which the player must find code books to help decipher them and gain access to a surplus of supplies.

In the anime adaptation of The Devil Is a Part-Timer!, the language of Ente Isla, called Entean, uses a substitution cipher with the ciphertext alphabet AZYXEWVTISRLPNOMQKJHUGFDCB, leaving only A, E, I, O, U, L, N, and Q in their original positions.

1. David Crawford / Mike Esterl, ^ At Siemens, witnesses cite pattern of bribery, The Wall Street Journal, January 31, 2007: "Back at Munich headquarters, he [Michael Kutschenreuter, a former Siemens-Manager] told prosecutors, he learned of an encryption code he alleged was widely used at Siemens to itemize bribe payments. He said it was derived from the phrase "Make Profit," with the phrase's 10 letters corresponding to the numbers 1-2-3-4-5-6-7-8-9-0. Thus, with the letter A standing for 2 and P standing for 5, a reference to "file this in the APP file" meant a bribe was authorized at 2.55 percent of sales. - A spokesman for Siemens said it has no knowledge of a "Make Profit" encryption system."

2. Stahl, Fred A., ^ On Computational Security, University of Illinois, 1974

3. Stahl, Fred A. "^ A homophonic cipher for computational cryptography", afips, pp. 565, 1973 Proceedings of the National Computer Conference, 1973

4. David Salomon. ^ Coding for Data and Computer Communications. Springer, 2005.

5. Fred A. Stahl. "^ A homophonic cipher for computational cryptography" Proceedings of the national computer conference and exposition (AFIPS '73), pp. 123-126, New York, USA, 1973.

6. ^ Toemeh, Ragheb (2014). "Certain investigations in Cryptanalysis of classical ciphers Using genetic algorithm". Shodhganga.

# data[].attributes.attachment_link.description
In cryptography, a substitution cipher is a method of encrypting by which units of plaintext are replaced with ciphertext, according to a fixed system; the "units" may be single letters (the most common), pairs of letters, triplets of letters, mixtures of the above, and so forth.

# data[].attributes.attachment_link.description
Coin values can be modeled by a set of n distinct positive integer values (whole numbers), arranged in increasing order as through .

# data[].attributes.attachment_link.readable_text
package bb;

public class Main {

    public static void main(String[] args) {
        //algae(8);
        System.out.println(algaeR("A", 5));
    }

    public static String algaeR(String prev, int depth) {
        if (depth == 0 && prev.equals("A")) {
            return "AB";
        }
        else if (depth == 0 && prev.equals("B")) {
            return "A";
        }
        else if (prev.equals("A")){
            return algaeR("A", depth - 1) + algaeR("B", depth - 1);
        }
        else {
            return algaeR("A", depth - 1);
        }
    }

    public static void algae(int iterations) {
        String axiom = "A";
        System.out.println(axiom);
        for (int step = 1; step <= iterations; step++) {
            String temp = "";
            for (int ch = 0; ch < axiom.length(); ch++) {
                if (axiom.charAt(ch) == 'A') {
                    temp += "AB";
                }
                else {
                    temp += "A";
                }
            }
            axiom = temp;
            //System.out.println(step + "(" + axiom.length() + "):"
                    //+ axiom);
            System.out.printf("%d (%d): %s\n",
                    step, axiom.length(), axiom);
        }
    }

}

# data[].attributes.attachment_link.readable_text
package bb;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        String[] names = {"wojtek" , "asia"};
        int[] ages = {12, 15};
        //writeInFile(names, ages);
        readFromFile();
    }

    public static void writeInFile(String[] names, int[] ages) {
        File file = new File("data.csv");
        try {
            PrintWriter printWriter = new PrintWriter(file);
            for (int i = 0; i < names.length; i++) {
                printWriter.println(names[i] + ";" + ages[i]);
            }
            printWriter.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void readFromFile() {
        File file = new File("data.csv");
        try {
            Scanner scanner = new Scanner(file);
            while (scanner.hasNext()) {
                String[] record = scanner.nextLine().split(";");
                System.out.println(record[0]);
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

}

# data[].attributes.body
L-systems

# data[].attributes.attachment_link.description
An L-system or Lindenmayer system is a parallel rewriting system and a type of formal grammar. An L-system consists of an alphabet of symbols that can be used to make strings, a collection of production rules that expand each symbol into some larger string of symbols, an initial " axiom" string from which to begin construction, and a mechanism for translating the generated strings into geometric structures.

# data[].attributes.headline
Classic Puzzle - Easy (October challenge and homework)

# data[].attributes.subject
Classic Puzzle - Easy (October challenge and homework)

# data[].attributes.body
The Descent,
Temperatures,
Power of Thor,
Chuch Norris,
Mars Lander,
ASCII Art,
MIME Type,
Defibrillators,
Horse-racing Duals

# data[].attributes.attachment_link.readable_text
Practice & learn the fun way

Practice pure code

Learn new concepts by solving fun challenges in 25+ languages addressing all the hot programming topics.

Learn from the best

In a matter of hours, discover new languages, algorithms or tricks in courses crafted by top developers.

Become the expert

Our approach has been designed to lead advanced developers to the next level.
Level up your skills
We're smarter together

Belong

We're developers just like you.

Join the community and feel at home.

Get insights

Meet like-minded enthusiasts, ask for help and have your code reviewed. We're here for each other.

Be inspired

Compare solutions and learn tips from the best programmers.
Join the community
Challenge your friends

Play

Have fun with friends, schoolmates or co-workers on multiplayer programming games and show them who's the boss!

Compete

Join our international online programming contests for fun, prizes or glory.

Rise & Shine

Hit the Leaderboard and get recognition from your peers.
Rediscover fun
Get hired at awesome companies

Build up

Strengthen your developer profile as you code and play.

Control

Choose which companies can see your profile and set your conditions.

Stand out

Prove your worth as a developer and get noticed by top companies for a career change and jobs you deserve.
Get the job you deserve

# data[].attributes.attachment_link.title
Coding Games and Programming Challenges to Code Better

# data[].attributes.attachment_link.description
Learn new concepts by solving fun challenges in 25+ languages addressing all the hot programming topics. In a matter of hours, discover new languages, algorithms or tricks in courses crafted by top developers. Our approach has been designed to lead advanced developers to the next level.

# data[].attributes.body
1. Create pseudo-random array.
2. Create method that calculate average value of the elements from index 0 do k.
3. Create method that calculate how many elements in the array are between given boundaries.
4. Calculate digit sum.
5. Calculate how many times given digit is present in the number.
6. Calculate how many times all digits are present int the array of numbers.
7*. Calucate how many times certain days of the week  (MONDAY etc.) are present in the array of LocalDates: today, yesterday, tomorrow and few pseudo-random.

# data[].attributes.attachment_link.readable_text
A simple text scanner which can parse primitive types and strings using regular expressions.

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

For example, this code allows a user to read a number from System.in:

     Scanner sc = new Scanner(System.in);
     int i = sc.nextInt();

As another example, this code allows long types to be assigned from entries in a file myNumbers:

      Scanner sc = new Scanner(new File("myNumbers"));
      while (sc.hasNextLong()) {
          long aLong = sc.nextLong();
      }

The scanner can also use delimiters other than whitespace. This example reads several items in from a string:

     String input = "1 fish 2 fish red fish blue fish";
     Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
     System.out.println(s.nextInt());
     System.out.println(s.nextInt());
     System.out.println(s.next());
     System.out.println(s.next());
     s.close();

prints the following output:

The same output can be generated with this code, which uses a regular expression to parse all four tokens at once:

     String input = "1 fish 2 fish red fish blue fish";
     Scanner s = new Scanner(input);
     s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
     MatchResult result = s.match();
     for (int i=1; i<=result.groupCount(); i++)
         System.out.println(result.group(i));
     s.close();

The default whitespace delimiter used by a scanner is as recognized by .isWhitespace. The method will reset the value of the scanner's delimiter to the default whitespace delimiter regardless of whether it was previously changed.

A scanning operation may block waiting for input.

The and methods and their primitive-type companion methods (such as and hasNextInt()) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext and next methods may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block.

The findInLine(java.lang.String), findWithinHorizon(java.lang.String, int), and skip(java.util.regex.Pattern) methods operate independently of the delimiter pattern. These methods will attempt to match the specified pattern with no regard to delimiters in the input and thus can be used in special circumstances where delimiters are not relevant. These methods may block waiting for more input.

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

Depending upon the type of delimiting pattern, empty tokens may be returned. For example, the pattern "\\s+" will return no empty tokens since it matches multiple instances of the delimiter. The delimiting pattern"\\s" could return empty tokens since it only passes one space at a time.

A scanner can read text from any object which implements the interface. If an invocation of the underlying readable's Readable.read(java.nio.CharBuffer) method throws an IOException then the scanner assumes that the end of the input has been reached. The most recent IOException thrown by the underlying readable can be retrieved via theioException() method.

When a Scanner is closed, it will close its input source if the source implements the interface.

A Scanner is not safe for multithreaded use without external synchronization.

Unless otherwise mentioned, passing a null parameter into any method of a Scanner will cause a NullPointerException to be thrown.

A scanner will default to interpreting numbers as decimal unless a different radix has been set by using the useRadix(int) method. The method will reset the value of the scanner's radix to 10 regardless of whether it was previously changed.

Whitespace is not significant in the above regular expressions.

# data[].attributes.attachment_link.description
A simple text scanner which can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

# data[].attributes.attachment_link.readable_text
package bb;

/*
The original game scenario was formulated in 1994 by Kaushik Basu and goes as follows:

An airline loses two suitcases belonging to two different travelers. Both suitcases happen to be identical and contain identical antiques.
An airline manager tasked to settle the claims of both travelers explains that the airline is liable for a maximum of $100 per suitcase
—he is unable to find out directly the price of the antiques.

To determine an honest appraised value of the antiques, the manager separates both travelers so they can't confer,
and asks them to write down the amount of their value at no less than $20 and no larger than $100.
He also tells them that if both write down the same number, he will treat that number as the true dollar value of both suitcases
and reimburse both travelers that amount. However, if one writes down a smaller number than the other,
this smaller number will be taken as the true dollar value, and both travelers will receive that amount along with a bonus/malus:
$10 extra will be paid to the traveler who wrote down the lower value and a $10 deduction will be taken from the person who wrote down the higher amount.
The challenge is: what strategy should both travelers follow to decide the value they should write down?

https://en.wikipedia.org/wiki/Traveler%27s_dilemma
*/

import java.util.Arrays;

public class Main {

    private static final int MIN_PRICE = 20;
    private static final int MAX_PRICE = 100;
    private static final int BONUS = 10;
    private static final int ROUNDS = 30;

    public static void main(String[] args) {
        int[] firstPlayerChoices = new int[ROUNDS];
        int[] secondPlayerChoices = new int[ROUNDS];
        int firstPlayerTotalScore = 0;
        int secondPlayerTotalScore = 0;

        for (int currentRound = 0; currentRound < ROUNDS; currentRound++) {
            int[] firstPlayerChoicesTemp = Arrays.copyOf(firstPlayerChoices, firstPlayerChoices.length);
            int[] secondPlayerChoicesTemp = Arrays.copyOf(secondPlayerChoices, secondPlayerChoices.length);
            int firstPlayerChoice = getFirstPlayerChoice(currentRound, firstPlayerTotalScore, secondPlayerTotalScore, firstPlayerChoicesTemp, secondPlayerChoicesTemp);
            int secondPlayerChoice = getSecondPlayerChoice(currentRound, secondPlayerTotalScore, firstPlayerTotalScore, secondPlayerChoicesTemp, firstPlayerChoicesTemp);
            firstPlayerChoices[currentRound] = firstPlayerChoice;
            secondPlayerChoices[currentRound] = secondPlayerChoice;

            int firstPlayerScore = -1;
            int secondPlayerScore = -1;

            if (firstPlayerChoice < MIN_PRICE || firstPlayerChoice > MAX_PRICE){
                firstPlayerScore = 0;
                if (secondPlayerChoice >= MIN_PRICE && secondPlayerChoice <= MAX_PRICE){
                    secondPlayerScore = secondPlayerChoice + BONUS;
                }
            }
            if (secondPlayerChoice < MIN_PRICE || secondPlayerChoice > MAX_PRICE){
                secondPlayerScore = 0;
                if (firstPlayerChoice >= MIN_PRICE && firstPlayerChoice <= MAX_PRICE){
                    firstPlayerScore = firstPlayerChoice + BONUS;
                }
            }
            if (firstPlayerScore == -1 && secondPlayerScore == -1){
                if (firstPlayerChoice == secondPlayerChoice){
                    firstPlayerScore = secondPlayerScore = firstPlayerChoice;
                }
                else if (firstPlayerChoice < secondPlayerChoice){
                    firstPlayerScore = firstPlayerChoice + BONUS;
                    secondPlayerScore = firstPlayerChoice - BONUS;
                }
                else {
                    firstPlayerScore = secondPlayerChoice - BONUS;
                    secondPlayerScore = secondPlayerChoice + BONUS;
                }
            }

            firstPlayerTotalScore += firstPlayerScore;
            secondPlayerTotalScore += secondPlayerScore;

            System.out.printf("First player choice: %d and score: + %d (= %d), second player choice %d and score: + %d (= %d).\n",
                    firstPlayerChoice, firstPlayerScore, firstPlayerTotalScore, secondPlayerChoice, secondPlayerScore, secondPlayerTotalScore);
        }
        System.out.printf("\nFirst player score: %d, second player score: %d.\n\n", firstPlayerTotalScore, secondPlayerTotalScore);
        System.out.println(Arrays.toString(secondPlayerChoices));
        System.out.println(Arrays.toString(firstPlayerChoices));
    }

	//yours bot
    private static int getFirstPlayerChoice(int currentRound, int yourScore, int enemyScore, final int[] yourChoices, final int[] enemyChoices){
        return (int) (Math.random() * 120);
    }

	//enemies bot
    private static int getSecondPlayerChoice(int currentRound, int yourScore, int enemyScore, final int[] yourChoices, final int[] enemyChoices){
        return 60;
    }

	
/*    private static int getSecondPlayerChoice(int currentRound, int yourScore, int enemyScore, final int[] yourChoices, final int[] enemyChoices){
        return (int) (Math.random() * 120);
    }*/


/*    private static int getSecondPlayerChoice(int currentRound, int yourScore, int enemyScore, final int[] yourChoices, final int[] enemyChoices){
        return 60;
    }*/


/*    private static int getSecondPlayerChoice(int currentRound, int yourScore, int enemyScore, final int[] yourChoices, final int[] enemyChoices){
      int choice;
        if (currentRound == 0){
            choice = MAX_PRICE;
        }
        else {
            choice = enemyChoices[currentRound - 1];
        }
        return choice;
    }*/
}

# data[].attributes.body
Strings:
{"Adam", "Ola", "Ela", "Ewa", "adam", ""}
1. Check if the array contains given string.
2. Calculate how many times given name is present in the array.
3. Calculate how many times the array contains name starting with given letter.
4. Construct an array with names starting with given letter.
5. Find the longest word in the array.
6. Find the shortest word(!) in the array.
7. Correct names in the array.
8. Check how many times given letter is present in the array.

User input:
"  aDam " - > "Adam"
"nowak, andrzej " -> "Andrzej Nowak"
" 600.600-600 " -> "600 600 600"
9. Transform user inputs to more appropriate form.

Important methods:
charAt, concat, compareTo, contains, endsWith, equals, indexOf, isEmpty, length, replace, split, startsWith, substring, toLowerCase, toUpperCase, trim.

# data[].attributes.attachment_link.description
The implementation of the string concatenation operator is left to the discretion of a Java compiler, as long as the compiler ultimately conforms to The Java™ Language Specification. For example, the javac compiler may implement the operator with StringBuffer, StringBuilder, or java.lang.invoke.StringConcatFactory depending on the JDK version.

# data[].attributes.body
- memoization
- reversing an array
- palindrom checking
- binary search

# data[].attributes.body
1. For a given array of numbers find:
a. the sum of the elements
b. the average value (arithmetic mean)
c. the geometric mean
d. the standard deviation
e. the max value
f. the min value
g*. the mode (the value that appears most often)
2. For a given array of numbers and a number:
a. check if this numer is present in the array or not (T/F)
b. calculate how many times
c. return index of first appearance
d. return indexes of all appearances
https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html
Important methods: equals, fill, sort, toString.

# data[].attributes.body
Book [Core CS] p. 102 - 122
Construct a truth table for the following Boolean expressions:
(A AND B) NOR C
A XOR (B OR C)
NOT (A OR B) AND (A NOR B)
(NOT A OR A) XOR (B AND NOT B)
((P NOR Q) NAND S) AND (P XOR S)

You can check your answers here: https://www.wolframalpha.com/

More info here:
http://ib.compscihub.net/wp-content/uploads/2018/06/2.1.12.pdf

# data[].attributes.body
Book [CSaIA] p. 53 - 89
1. Add numbers from 1 to 100 inclusive.
2. Add even numbers from 1 to 100 inclusive.
3. Add numbers from 1 to 100 that are divided by 7.
4. Take a number n from the user. Print n-first elements of the Fibonacci sequence.
5. Collect two numbers a and b from the user. Compute a^b.
6*. Create the Pascal triangle (normal and colorised).

# data[].attributes.attachment_link.readable_text
Loop is used in programming to repeat a specific block of code until certain condition is met (test expression is false).

Loops are what makes computers interesting machines. Imagine you need to print a sentence 50 times on your screen. Well, you can do it by using print statement 50 times (without using loops). How about you need to print a sentence one million times? You need to use loops.

It's just a simple example. You will learn to use while and do..while loop to write some interesting programs in this article.

Java while Loop

The syntax of while loop is:

while (testExpression) {
    // codes inside body of while loop
}

How while loop works?

The test expression inside parenthesis is a boolean expression.

If the test expression is evaluated to true,

statements inside the while loop are executed.

then, the test expression is evaluated again.

This process goes on until the test expression is evaluated to false.

If the test expression is evaluated to false,

while loop is terminated.

Flowchart of while Loop

Example 1: while Loop

// Program to print line 10 times class Loop { public static void main(String[] args) { int i = 1; while (i <= 10) { System.out.println("Line " + i); ++i; } } }

When you run the program, the output will be:

Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10

Notice, ++i; statement inside the while loop. After 10 iterations, variable i will be 11. Then, the test expression i <= 10 is evaluated to false and while loop terminates.

Example 2: Java while Loop

// Program to find the sum of natural numbers from 1 to 100. class AssignmentOperator { public static void main(String[] args) { int sum = 0, i = 100; while (i != 0) { sum += i; // sum = sum + i; --i; } System.out.println("Sum = " + sum); } }

When you run the program, the output will be:

Here, the variable sum is initialized to 0 and i is initialized to 100. In each iteration of while loop, variable sum is assigned sum + i, and the value of i is decreased by 1 until i is equal to 0. For better visualization,

1st iteration: sum = 0+100 = 100, i = 99
2nd iteration: sum = 100+99 = 199, i = 98
3rd iteration: sum = 199+98 = 297, i = 97
... .. ...
... .. ...
99th iteration: sum = 5047+2 = 5049, i = 1
100th iteration: sum = 5049+1 = 5050, i = 0

To learn more about test expression and how it is evaluated, visit relational and logical operators.

Java do...while Loop

The do...while loop is similar to while loop with one key difference. The body of do...while loop is executed for once before the test expression is checked.

The syntax of do..while loop is:

do {
   // codes inside body of do while loop
} while (testExpression);

How do...while loop works?

The body of do...while loop is executed once (before checking the test expression). Only then, the test expression is checked.

If the test expression is evaluated to true, codes inside the body of the loop are executed, and the test expression is evaluated again. This process goes on until the test expression is evaluated to false.

When the test expression is false, the do..while loop terminates.

Flowchart of do...while Loop

Example 3: do...while Loop

The program below calculates the sum of numbers entered by the user until user enters 0.

To take input from the user, Scanner object is used. Visit Java Basic Input to learn more on how to take input from the user.

import java.util.Scanner; class Sum { public static void main(String[] args) { Double number, sum = 0.0; Scanner input = new Scanner(System.in); do { System.out.print("Enter a number: "); number = input.nextDouble(); sum += number; } while (number != 0.0); System.out.println("Sum = " + sum); } }

When you run the program, the output will be:

Enter a number: 2.5 Enter a number: 23.3 Enter a number: -4.2 Enter a number: 3.4 Enter a number: 0 Sum = 25.0

Infinite while Loop

If the test expression never evaluates to false, the body of while and do..while loop is executed infinite number of times (at least in theory). For example,

while (true) { // body of while loop }

Let's take another example,

 int i = 100; while (i == 100) { System.out.print("Hey!"); }

The infinite do...while loop works in similar way like while loop.

# data[].attributes.attachment_link.description
Loop is used in programming to repeat a specific block of code until certain condition is met (test expression is false). Loops are what makes computers interesting machines. Imagine you need to print a sentence 50 times on your screen. Well, you can do it by using print statement 50 times (without using loops).

# data[].attributes.body
ankieta

# data[].attributes.attachment_link.description
POLSKA EDYCJA 2020 REJESTRACJA O konkursie Pix Programming Challenge to międzynarodowy konkurs programistyczny dla dzieci i młodzieży. Jest on w pełni przeprowadza za pośrednictwem aplikacji PixBlocks. Zarówno udział w konkursie jak i aplikacja są całkowicie bezpłatne! Uczestnicy konkursu muszą rozwiązać zadania z zakresu programowania. Zadania dostosowane są do różnych grup wiekowych.

# data[].attributes.body
1. The calculator.
2. Adding hours in the clock.
3. Print number of days from a given month and year. Note a leap year.
https://www.programiz.com/java-programming/methods

# data[].attributes.attachment_link.readable_text
package bb;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int month = scanner.nextInt();
        int year = scanner.nextInt();
        System.out.println(getDays(month, year));
    }

    public static int getDays(int month, int year) {
        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
            return 31;
        }
        else if (month == 2) {
            //mind the leap year
            if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
                return 29;
            }
            else {
                return 28;
            }
        }
        else {
            return 30;
        }
    }


}

# data[].attributes.headline
Exercises (conditionals and math functions)

# data[].attributes.subject
Exercises (conditionals and math functions)

# data[].attributes.body
1. Print a sign of a given number (whether it is positive, negative or zero).
2. Give a test grade (A, B, C, D or F) for a student with marks from 0 to 100. State your own boundaries.
2. Find max value from 3 given numbers.
3. Find min value from 4 given numbers.
4. Solve the quadratic equation from the coefficients.
5. Test whether 3 given numbers can be the sides of a triangle (do they respect the triangular inequality?). Check whether this is a right triangle or not. Compute its area, perimeter and angles.
6*. Print number of days from a given month and year. Note a leap year.  Compute the date of the next day.

# data[].attributes.body
Variables:
https://www.baeldung.com/java-primitives
Conditional statements:
https://www.programiz.com/java-programming/if-else-statement
Java Math class:
https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html

# data[].attributes.body
1. JDK 8 (Java Development Kit)
https://oraclemirror.np.gy/jdk8/
or
https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
2. IntelliJ IDEA Community (IDE)
https://www.jetbrains.com/idea/download/#section=windows

# data[].attributes.body
https://ideone.com/

https://www.tutorialspoint.com/compile_java_online.php

# data[].attributes.body
0. Introduction to Programming in Java : An Interdisciplinary Approach

https://helion.pl/ksiazki/programowanie-w-jezyku-java-podejscie-interdyscyplinarne-wydanie-ii-robert-sedgewick-kevin-wayne,prjaid.htm#format/d
1. Java. Fundamentals

https://helion.pl/ksiazki/java-podstawy-wydanie-x-cay-s-horstmann,javp10.htm
2. Java. Head first

https://helion.pl/ksiazki/java-rusz-glowa-wydanie-ii-kathy-sierra-bert-bates,javrg2.htm
3. Documentation
https://docs.oracle.com/javase/tutorial/
4. Tutorials
https://javastart.pl/static/darmowy-kurs-java/ https://www.javatpoint.com/java-tutorial
5. YouTube tutorial
https://www.youtube.com/watch?v=3u1fu6f8Hto