Wednesday, 21 August 2019

Swift Automatic reference counting (Weak variable)

Weak reference


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Person{
    var name: String
    var fruit: Fruit?
    
    init(name: String) {
        self.name = name
        print ("Person init")
    }
    
    deinit {
        print ("Person denit")
    }
}

class Fruit{
    var name: String
    init(name: String) {
        self.name = name
        print ("Fruit init")
    }
    
    deinit {
        print ("Fruit denit")
    }
}

var person: Person? = Person(name: "john")
person!.fruit = Fruit(name: "apple")
person = nil //Prints "Person denit", "Fruit denit"

After line 28, the fruit object has one strong reference on it (the property person.fruit), and the person object also has one strong reference on it (the variable person).

At line 29, two things happen.

1. The person object has no reference on it and thus gets deallocated. It prints "Person deinit"
2. Since the person object is gone, the fruit object has no reference on it, and thus gets deallocated. It prints "Fruit deinit"


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Person{
    var name: String
    var fruit: Fruit?
    
    init(name: String) {
        self.name = name
        print ("Person init")
    }
    
    deinit {
        print ("Person denit")
    }
}

class Fruit{
    var name: String
    var person: Person?
    
    init(name: String) {
        self.name = name
        print ("Fruit init")
    }
    
    deinit {
        print ("Fruit denit")
    }
}

var person: Person? = Person(name: "john")
var fruit: Fruit? = Fruit(name: "apple")
person!.fruit = fruit
fruit!.person = person
person = nil
fruit = nil //Nothing is deinitilised. 

After line 32, the fruit object has two strong references on it (the variable fruit, and the property person.fruit). Similarly the person object has two strong references on it (the variable person, and the property fruit.person)

After line 34, both the fruit objects and the person objects have one strong reference on it (the property person.fruit and fruit.person respectively). Hence nothing is deinitilised.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Person{
    var name: String
    weak var fruit: Fruit?
    
    init(name: String) {
        self.name = name
        print ("Person init")
    }
    
    deinit {
        print ("Person deinit")
    }
}

class Fruit{
    var name: String
    var person: Person?
    
    init(name: String) {
        self.name = name
        print ("Fruit init")
    }
    
    deinit {
        print ("Fruit deinit")
    }
}

var person: Person? = Person(name: "john")
var fruit: Fruit? = Fruit(name: "apple")
person!.fruit = fruit
fruit!.person = person
fruit = nil //Prints "Fruit deinit"

After line 32, the fruit object has one strong reference (the variable fruit) and one weak reference (the property person.fruit)

At line 33, the strong reference is broken, and there is only one weak reference left, which can't stop the object being deinitialised.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Person{
    var name: String
    weak var fruit: Fruit?
    
    init(name: String) {
        self.name = name
        print ("Person init")
    }
    
    deinit {
        print ("Person deinit")
    }
}

class Fruit{
    var name: String
    var person: Person?
    
    init(name: String) {
        self.name = name
        print ("Fruit init")
    }
    
    deinit {
        print ("Fruit deinit")
    }
}

var person: Person? = Person(name: "john")
var fruit: Fruit? = Fruit(name: "apple")
person!.fruit = fruit
fruit!.person = person
person = nil
fruit = nil //Prints "Fruit deinit, Person deinit"

After line 32, the fruit object has one strong reference (the variable fruit) and one weak reference (the property person.fruit). The person object two strong references (the variable person and the property fruit.person)

At line 33, one strong reference on the person object is broken, but since there is another strong reference, object person can't be deallocated.

At line 34, the strong reference on the fruit object is broken, the fruit object is deallocated, thus breaking the other strong reference on the person object. Hence the person is deallocated.

Unowned reference


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Person{
    var name: String
    var fruit: Fruit?
    
    init(_ name: String) {
        self.name = name
        print ("Person init")
    }
    
    deinit {
        print ("Person deinit")
    }
}

class Fruit{
    var name: String
    unowned var person: Person
    
    init(_ name: String, person: Person) {
        self.name = name
        self.person = person
        print ("Fruit init")
    }
    
    deinit {
        print ("Fruit deinit")
    }
}

var person: Person? = Person("john")
person!.fruit = Fruit("apple", person: person!)
person = nil //Prints "Person deinit, Fruit deinit"

After line 31, the person object has one strong reference (var person), and one unowned reference (property fruit.person).

At line 32, the strong reference on the person object is broken, and the person object is deallocated.

Note unowned cannot be used on optional type. (i.e. replacing unowned by weak in the above code causes compilation error)

Thursday, 8 August 2019

HttpClient's post request doesn't reach the outside world

The issue is HttpClient's post request cannot reach the outside world due to the Internet access restriction. Even after having configured the proxy on jvm, it still doesn't work.

The error message reads

14:31:06.604 java[31504]: 2019-08-06 14:31:06.604  INFO 31504 --- [tp2088371948-52] o.apache.http.impl.execchain.RetryExec   : Retrying request to {s}->https://www.google.com:443
14:33:13.837 java[31504]: 2019-08-06 14:33:13.837 ERROR 31504 --- [tp2088371948-52] a.g.n.t.service.utils.HttpClientUtil     : Post request failed: https://www.google.com/recaptcha/api/siteverify
14:33:13.837 java[31504]: 
14:33:13.837 java[31504]: java.net.SocketException: Network is unreachable (connect failed)
14:33:13.837 java[31504]:       at java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:1.8.0_222]
14:33:13.837 java[31504]:       at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) ~[na:1.8.0_222]
14:33:13.837 java[31504]:       at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[na:1.8.0_222]
14:33:13.837 java[31504]:       at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[na:1.8.0_222]
14:33:13.837 java[31504]:       at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:1.8.0_222]
14:33:13.837 java[31504]:       at java.net.Socket.connect(Socket.java:589) ~[na:1.8.0_222]
14:33:13.837 java[31504]:       at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:339) ~[httpclient-4.5.6.jar!/:4.5.6]

The solution is using HttpClients.createSystem() instead of HttpCients.createDefault() to create the HttpClient instance.

 createSystem

public static CloseableHttpClient createSystem()

    Creates CloseableHttpClient instance with default configuration based on system properties. 

Thursday, 1 August 2019

Font awesome CSS

To display this little icon





we can use the font awesome css.

It looks extremely simple to use. Here is an example from w3school.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<i class="fa fa-home"></i>

The problem arises when I copy the css file locally. What I get looks...





It is because the css file alone is not enough to render the image. I also need to save the image files locally.

Where to find the image files? If we hit

https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css


@font-face {
  font-family: 'FontAwesome';
  src: url('../fonts/fontawesome-webfont.eot?v=4.7.0');
  src: url('../fonts/fontawesome-webfont.eot?#iefix&v=4.7.0') format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff2?v=4.7.0') format('woff2'), url('../fonts/fontawesome-webfont.woff?v=4.7.0') format('woff'), url('../fonts/fontawesome-webfont.ttf?v=4.7.0') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.7.0#fontawesomeregular') format('svg');
  font-weight: normal;
  font-style: normal;
}

We need to download
  • fontawesome-webfont.eot
  • fontawesome-webfont.woff2
  • fontawesome-webfont.woff
  • fontawesome-webfont.ttf
  • fontawesome-webfont.svg  
Replace the css/font-awesome.css with fonts/<image-file-names>, e.g

https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/fonts/fontawesome-webfont.eot

Then put these image files in the fonts folder at the same level with css folder


How to delete a cookie

Naively, the code looks like this

for (Cookie cookie : request.getCookies()) {
    if (StringUtils.equalsIgnoreCase(cookie.getName(), "cookie-name")) {
        cookie.setValue("");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }
}

Unfortunately, it doesn't work because a cookie is identified by its name, domain, and path. But we don't change the domain or path, do we? Actually the browser will send only name=value in the HTTP Cookie header.

Other attributes (secure, domain, path, expiration) are only available for cookies that we set into the response yourself. They are used to create the Set-Cookie response headers.

Therefore cookie.getDomain() and cookie.getPath() always return null.

The solution is explicitly set domain and path


for (Cookie cookie : request.getCookies()) {
    if (StringUtils.equalsIgnoreCase(cookie.getName(), "cookie-name")) {
     cookie.setDomain("localhost");
     cookie.setPath("/");
        cookie.setValue("");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }
}

Wednesday, 10 July 2019

Switch git user on command line

Check who is the current user

$ git config --list  

Change user


$ git config --global user.name "Bob"
$ git config --global user.email "bob@example.com"

Delete old password

Open keychain



 Search 'git', delete 'github.com'



Reference: https://superuser.com/questions/1064197/how-to-switch-git-user-at-terminal

Monday, 8 July 2019

Mapstruct quickstart

Maven pom.xml
    <properties>
        <org.mapstruct.version>1.3.0.Final</org.mapstruct.version>
    </properties>

    <dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct</artifactId>
        <version>${org.mapstruct.version}</version>
    </dependency>

 <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version> <!-- or newer version -->
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
            <annotationProcessorPaths>
                <path>
                    <groupId>org.mapstruct</groupId>
                    <artifactId>mapstruct-processor</artifactId>
                    <version>${org.mapstruct.version}</version>
                </path>
                <!-- other annotation processors -->
            </annotationProcessorPaths>
        </configuration>
    </plugin>

Java
public class Car {
 
    private String make;
    private int numberOfSeats;
    private CarType type;
    
    public Car(String make, int numberOfSeats, CarType type) {
        super();
        this.make = make;
        this.numberOfSeats = numberOfSeats;
        this.type = type;
    }
    public String getMake() {
        return make;
    }
    public void setMake(String make) {
        this.make = make;
    }
    public int getNumberOfSeats() {
        return numberOfSeats;
    }
    public void setNumberOfSeats(int numberOfSeats) {
        this.numberOfSeats = numberOfSeats;
    }
    public CarType getType() {
        return type;
    }
    public void setType(CarType type) {
        this.type = type;
    }
}

public class CarDto {
 
    private String make;
    private int seatCount;
    private String type;
    public String getMake() {
        return make;
    }
    public void setMake(String make) {
        this.make = make;
    }
    public int getSeatCount() {
        return seatCount;
    }
    public void setSeatCount(int seatCount) {
        this.seatCount = seatCount;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
}

@Mapper
public interface CarMapper {
    CarMapper INSTANCE = Mappers.getMapper( CarMapper.class );
    
    @Mapping(source = "numberOfSeats", target = "seatCount")
    CarDto carToCarDto(Car car);
}

public enum CarType {
    SEDAN, HATCHBACK;
}

Test case
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

class CarMapperTest {

    @BeforeEach
    void setUp() throws Exception {
    }

    @Test
    void test() {
        //given
        Car car = new Car( "Morris", 5, CarType.SEDAN );
     
        //when
        CarDto carDto = CarMapper.INSTANCE.carToCarDto( car );
     
        assertNotNull(carDto);
        assertThat(carDto.getMake(), is("Morris") );
        assertThat(carDto.getSeatCount(), is(5));
        assertThat(carDto.getType(), is("SEDAN"));
    }

}

Sunday, 23 June 2019

Project Euler 154 - Exploring Pascal's pyramid

A triangular pyramid is constructed using spherical balls so that each ball rests on exactly three balls of the next lower level.
Then, we calculate the number of paths leading from the apex to each position:
A path starts at the apex and progresses downwards to any of the three spheres directly below the current position.
Consequently, the number of paths to reach a certain position is the sum of the numbers immediately above it (depending on the position, there are up to three numbers above it).
The result is Pascal's pyramid and the numbers at each level n are the coefficients of the trinomial expansion (x + y + z)n.
How many coefficients in the expansion of (x + y + z)200000 are multiples of 1012?

Solution

I have spent a week to solve this problem.

First step is observe the pattern



Now we can see the for any given level l, any row m (starting 0), any column n (starting 0), the value is Clm * Cmn

Due to the symmetry, there is no need to go through the entire a triangle. Only going through the red ones is sufficient.


To illustrate the idea, considering peeling an onion, we take off the outermost layer of the triangle, what is left is:


Then again take off the outermost layer, what is left is:


The complexity of the algorithm is O(n^2), which runs 19 minutes on my iMac. I struggle to make it run any faster.