Skip to content

Commit b4a5880

Browse files
committed
Merge remote-tracking branch 'upstream/master'
2 parents 917d7ea + ffd17c1 commit b4a5880

38 files changed

Lines changed: 863 additions & 342 deletions

File tree

‎apache-thrift/src/main/java/com/baeldung/thrift/Application.java‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
package com.baeldung.thrift;
22

3+
import org.apache.thrift.transport.TTransportException;
4+
35
public class Application {
46

5-
public static void main(String[] args) {
7+
public static void main(String[] args) throws TTransportException {
68
CrossPlatformServiceServer server = new CrossPlatformServiceServer();
79
server.start();
810
}

‎apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceServer.java‎

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,25 +6,22 @@
66
import org.apache.thrift.server.TSimpleServer;
77
import org.apache.thrift.transport.TServerSocket;
88
import org.apache.thrift.transport.TServerTransport;
9+
import org.apache.thrift.transport.TTransportException;
910

1011
public class CrossPlatformServiceServer {
1112

1213
private TServer server;
1314

14-
public void start() {
15-
try {
16-
TServerTransport serverTransport = new TServerSocket(9090);
17-
server = new TSimpleServer(new TServer.Args(serverTransport)
18-
.processor(new CrossPlatformService.Processor<>(new CrossPlatformServiceImpl())));
15+
public void start() throws TTransportException {
16+
TServerTransport serverTransport = new TServerSocket(9090);
17+
server = new TSimpleServer(new TServer.Args(serverTransport)
18+
.processor(new CrossPlatformService.Processor<>(new CrossPlatformServiceImpl())));
1919

20-
System.out.print("Starting the server... ");
20+
System.out.print("Starting the server... ");
2121

22-
server.serve();
22+
server.serve();
2323

24-
System.out.println("done.");
25-
} catch (Exception e) {
26-
e.printStackTrace();
27-
}
24+
System.out.println("done.");
2825
}
2926

3027
public void stop() {

‎apache-thrift/src/test/java/com/baeldung/thrift/CrossPlatformServiceTest.java‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package com.baeldung.thrift;
22

3+
import org.apache.thrift.transport.TTransportException;
34
import org.junit.After;
45
import org.junit.Assert;
56
import org.junit.Before;
@@ -11,7 +12,13 @@ public class CrossPlatformServiceTest {
1112

1213
@Before
1314
public void setUp() {
14-
new Thread(() -> server.start()).start();
15+
new Thread(() -> {
16+
try {
17+
server.start();
18+
} catch (TTransportException e) {
19+
e.printStackTrace();
20+
}
21+
}).start();
1522
try {
1623
// wait for the server start up
1724
Thread.sleep(1000);

‎core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java‎

Lines changed: 25 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,28 +3,34 @@
33
import java.util.Scanner;
44

55
import com.baeldung.algorithms.annealing.SimulatedAnnealing;
6+
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
67
import com.baeldung.algorithms.slope_one.SlopeOne;
78

89
public class RunAlgorithm {
910

10-
public static void main(String[] args) {
11-
Scanner in = new Scanner(System.in);
12-
System.out.println("Run algorithm:");
13-
System.out.println("1 - Simulated Annealing");
14-
System.out.println("2 - Slope One");
15-
int decision = in.nextInt();
16-
switch (decision) {
17-
case 1:
18-
System.out.println("Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
19-
break;
20-
case 2:
21-
SlopeOne.slopeOne(3);
22-
break;
23-
default:
24-
System.out.println("Unknown option");
25-
break;
26-
}
27-
in.close();
28-
}
11+
public static void main(String[] args) {
12+
Scanner in = new Scanner(System.in);
13+
System.out.println("Run algorithm:");
14+
System.out.println("1 - Simulated Annealing");
15+
System.out.println("2 - Slope One");
16+
System.out.println("3 - Simple Genetic Algorithm");
17+
int decision = in.nextInt();
18+
switch (decision) {
19+
case 1:
20+
System.out.println(
21+
"Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
22+
break;
23+
case 2:
24+
SlopeOne.slopeOne(3);
25+
break;
26+
case 3:
27+
SimpleGeneticAlgorithm.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
28+
break;
29+
default:
30+
System.out.println("Unknown option");
31+
break;
32+
}
33+
in.close();
34+
}
2935

3036
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.baeldung.algorithms.ga.binary;
2+
3+
import lombok.Data;
4+
5+
@Data
6+
public class Individual {
7+
8+
protected int defaultGeneLength = 64;
9+
private byte[] genes = new byte[defaultGeneLength];
10+
private int fitness = 0;
11+
12+
public Individual() {
13+
for (int i = 0; i < genes.length; i++) {
14+
byte gene = (byte) Math.round(Math.random());
15+
genes[i] = gene;
16+
}
17+
}
18+
19+
protected byte getSingleGene(int index) {
20+
return genes[index];
21+
}
22+
23+
protected void setSingleGene(int index, byte value) {
24+
genes[index] = value;
25+
fitness = 0;
26+
}
27+
28+
public int getFitness() {
29+
if (fitness == 0) {
30+
fitness = SimpleGeneticAlgorithm.getFitness(this);
31+
}
32+
return fitness;
33+
}
34+
35+
@Override
36+
public String toString() {
37+
String geneString = "";
38+
for (int i = 0; i < genes.length; i++) {
39+
geneString += getSingleGene(i);
40+
}
41+
return geneString;
42+
}
43+
44+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.baeldung.algorithms.ga.binary;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
import lombok.Data;
7+
8+
@Data
9+
public class Population {
10+
11+
private List<Individual> individuals;
12+
13+
public Population(int size, boolean createNew) {
14+
individuals = new ArrayList<>();
15+
if (createNew) {
16+
createNewPopulation(size);
17+
}
18+
}
19+
20+
protected Individual getIndividual(int index) {
21+
return individuals.get(index);
22+
}
23+
24+
protected Individual getFittest() {
25+
Individual fittest = individuals.get(0);
26+
for (int i = 0; i < individuals.size(); i++) {
27+
if (fittest.getFitness() <= getIndividual(i).getFitness()) {
28+
fittest = getIndividual(i);
29+
}
30+
}
31+
return fittest;
32+
}
33+
34+
private void createNewPopulation(int size) {
35+
for (int i = 0; i < size; i++) {
36+
Individual newIndividual = new Individual();
37+
individuals.add(i, newIndividual);
38+
}
39+
}
40+
}
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
package com.baeldung.algorithms.ga.binary;
2+
3+
import lombok.Data;
4+
5+
@Data
6+
public class SimpleGeneticAlgorithm {
7+
8+
private static final double uniformRate = 0.5;
9+
private static final double mutationRate = 0.025;
10+
private static final int tournamentSize = 5;
11+
private static final boolean elitism = true;
12+
private static byte[] solution = new byte[64];
13+
14+
public static boolean runAlgorithm(int populationSize, String solution) {
15+
if (solution.length() != SimpleGeneticAlgorithm.solution.length) {
16+
throw new RuntimeException(
17+
"The solution needs to have " + SimpleGeneticAlgorithm.solution.length + " bytes");
18+
}
19+
SimpleGeneticAlgorithm.setSolution(solution);
20+
Population myPop = new Population(populationSize, true);
21+
22+
int generationCount = 1;
23+
while (myPop.getFittest().getFitness() < SimpleGeneticAlgorithm.getMaxFitness()) {
24+
System.out.println(
25+
"Generation: " + generationCount + " Correct genes found: " + myPop.getFittest().getFitness());
26+
myPop = SimpleGeneticAlgorithm.evolvePopulation(myPop);
27+
generationCount++;
28+
}
29+
System.out.println("Solution found!");
30+
System.out.println("Generation: " + generationCount);
31+
System.out.println("Genes: ");
32+
System.out.println(myPop.getFittest());
33+
return true;
34+
}
35+
36+
public static Population evolvePopulation(Population pop) {
37+
int elitismOffset;
38+
Population newPopulation = new Population(pop.getIndividuals().size(), false);
39+
40+
if (elitism) {
41+
newPopulation.getIndividuals().add(0, pop.getFittest());
42+
elitismOffset = 1;
43+
} else {
44+
elitismOffset = 0;
45+
}
46+
47+
for (int i = elitismOffset; i < pop.getIndividuals().size(); i++) {
48+
Individual indiv1 = tournamentSelection(pop);
49+
Individual indiv2 = tournamentSelection(pop);
50+
Individual newIndiv = crossover(indiv1, indiv2);
51+
newPopulation.getIndividuals().add(i, newIndiv);
52+
}
53+
54+
for (int i = elitismOffset; i < newPopulation.getIndividuals().size(); i++) {
55+
mutate(newPopulation.getIndividual(i));
56+
}
57+
58+
return newPopulation;
59+
}
60+
61+
private static Individual crossover(Individual indiv1, Individual indiv2) {
62+
Individual newSol = new Individual();
63+
for (int i = 0; i < newSol.getDefaultGeneLength(); i++) {
64+
if (Math.random() <= uniformRate) {
65+
newSol.setSingleGene(i, indiv1.getSingleGene(i));
66+
} else {
67+
newSol.setSingleGene(i, indiv2.getSingleGene(i));
68+
}
69+
}
70+
return newSol;
71+
}
72+
73+
private static void mutate(Individual indiv) {
74+
for (int i = 0; i < indiv.getDefaultGeneLength(); i++) {
75+
if (Math.random() <= mutationRate) {
76+
byte gene = (byte) Math.round(Math.random());
77+
indiv.setSingleGene(i, gene);
78+
}
79+
}
80+
}
81+
82+
private static Individual tournamentSelection(Population pop) {
83+
Population tournament = new Population(tournamentSize, false);
84+
for (int i = 0; i < tournamentSize; i++) {
85+
int randomId = (int) (Math.random() * pop.getIndividuals().size());
86+
tournament.getIndividuals().add(i, pop.getIndividual(randomId));
87+
}
88+
Individual fittest = tournament.getFittest();
89+
return fittest;
90+
}
91+
92+
protected static int getFitness(Individual individual) {
93+
int fitness = 0;
94+
for (int i = 0; i < individual.getDefaultGeneLength() && i < solution.length; i++) {
95+
if (individual.getSingleGene(i) == solution[i]) {
96+
fitness++;
97+
}
98+
}
99+
return fitness;
100+
}
101+
102+
protected static int getMaxFitness() {
103+
int maxFitness = solution.length;
104+
return maxFitness;
105+
}
106+
107+
protected static void setSolution(String newSolution) {
108+
solution = new byte[newSolution.length()];
109+
for (int i = 0; i < newSolution.length(); i++) {
110+
String character = newSolution.substring(i, i + 1);
111+
if (character.contains("0") || character.contains("1")) {
112+
solution[i] = Byte.parseByte(character);
113+
} else {
114+
solution[i] = 0;
115+
}
116+
}
117+
}
118+
119+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.baeldung.algorithms;
2+
3+
import org.junit.Assert;
4+
import org.junit.Test;
5+
6+
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
7+
8+
public class BinaryGeneticAlgorithmTest {
9+
10+
@Test
11+
public void testGA() {
12+
Assert.assertTrue(SimpleGeneticAlgorithm.runAlgorithm(50,
13+
"1011000100000100010000100000100111001000000100000100000000001111"));
14+
}
15+
16+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.baeldung.concurrent.priorityblockingqueue;
2+
3+
import org.junit.Test;
4+
5+
import java.util.ArrayList;
6+
import java.util.concurrent.PriorityBlockingQueue;
7+
import java.util.concurrent.TimeUnit;
8+
9+
import static org.assertj.core.api.Assertions.assertThat;
10+
import static org.assertj.core.util.Lists.newArrayList;
11+
12+
public class PriorityBlockingQueueUnitTest {
13+
14+
@Test
15+
public void givenUnorderedValues_whenPolling_thenShouldOrderQueue() throws InterruptedException {
16+
PriorityBlockingQueue<Integer> queue = new PriorityBlockingQueue<>();
17+
ArrayList<Integer> polledElements = new ArrayList<>();
18+
19+
queue.add(1);
20+
queue.add(5);
21+
queue.add(2);
22+
queue.add(3);
23+
queue.add(4);
24+
25+
queue.drainTo(polledElements);
26+
27+
assertThat(polledElements).containsExactly(1, 2, 3, 4, 5);
28+
}
29+
30+
@Test
31+
public void whenPollingEmptyQueue_thenShouldBlockThread() throws InterruptedException {
32+
PriorityBlockingQueue<Integer> queue = new PriorityBlockingQueue<>();
33+
34+
final Thread thread = new Thread(() -> {
35+
System.out.println("Polling...");
36+
while (true) {
37+
try {
38+
Integer poll = queue.take();
39+
System.out.println("Polled: " + poll);
40+
} catch (InterruptedException e) {}
41+
}
42+
});
43+
thread.start();
44+
45+
Thread.sleep(TimeUnit.SECONDS.toMillis(5));
46+
System.out.println("Adding to queue");
47+
48+
queue.addAll(newArrayList(1, 5, 6, 1, 2, 6, 7));
49+
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
50+
}
51+
}

0 commit comments

Comments
 (0)