We can use latitude to convert coordinates into meters

I met Yelp Fusion API, which can find objects withing given radius around given location on Earth. Radius should be given in meters.

Simultaneously, Google Maps API uses degrees of latitude and longitude to report map bounds.

How to convert one to another so that provide meters to Yelp API? I realized, that this is pretty easy if we use latitude only:

EarthLatitude

Where alpha is latitude difference in radians.

To convert to degrees we should

2 * Pi / 360. *6371008.8 = 111195 meters per degree of latitude.

I wrote as simple JSFiddle here to illustrate this approach: https://jsfiddle.net/dimskraft/1boks8es/2/

Here is screenshot:

MetersPerDegree screenshot

Swing IOC

I wrote simple project to demonstrate how to create (desktop) UI with IOC. The structure of JForm is defined by special Spring configuration, which contains beans, named by convention. Dedicated service takes configuration, creates child context and set up window according to it. Having child context both isolates it’s beans from overall application beans and also can help to simulate web scopes if each such context will be associated with JFrame.

Also I tried to use RxSwing to bing list to an image.

SwingIOC_Example

https://github.com/dims12/SwingIOC

 

Running Tensorflow train with GPU

Was not realizing, that training of DNN with GPU is so faster, than with CPU.

I have old GTX770 card which is reported to have 3,213 GFLOPS.

My main CPU is Core i7-4770K 3.5 GHz, which is reported to have 177 GFLOPS.

It looks like my GPU should be 18 times faster than CPU.

Actually, I don’t observe this kind of speed. I wrote simple convolutional model for CIFAR-10 database and observed that is works approximately 7 times faster on GPU than on CPU (by eye).

Fastest way to generate random BufferedImage (in Java)

Today I decided to generate random image for an image stub, like this:

fillrandom01

All RGB values are uniformly random here.

How to generate such image in Java?

I wrote a simple program to test:

package com.inthemoon.snippets.swing;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.awt.image.VolatileImage;
import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.Random;

/**
 * Created by Dims on 28.02.2017.
 */
public class FastRandomImageGenerator {

   private final static int width = 1024;
   private final static int height = 768;
   private final static int count = 1000;

   private final static Random rnd = new Random();

   private static int[] array;


   public static void main(String[] args) throws IOException {

      long start, end;
      double elapsed;
      long fps;

      BufferedImage image;
      image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
      array = new int[image.getWidth() * image.getHeight() * image.getRaster().getNumBands()];


      start = System.currentTimeMillis();
      for(int i=0; i<count; ++i) {
         fillRandom00(image);
      }
      end = System.currentTimeMillis();

      elapsed = (double)(end - start) / count;
      fps = Math.round(1000. / elapsed);

      System.out.println(String.format(Locale.US, "Elapsed: %.2f milliseconds per one fillRandom00, expected fps is %d", elapsed, fps));
      //ImageIO.write(image, "PNG", new File("fillRandom01.png"));




      start = System.currentTimeMillis();
      for(int i=0; i<count; ++i) {
         fillRandom01(image);
      }
      end = System.currentTimeMillis();

      elapsed = (double)(end - start) / count;
      fps = Math.round(1000. / elapsed);

      System.out.println(String.format(Locale.US, "Elapsed: %.2f milliseconds per one fillRandom01, expected fps is %d", elapsed, fps));
      ImageIO.write(image, "PNG", new File("fillRandom01.png"));



      start = System.currentTimeMillis();
      for(int i=0; i<count; ++i) {
         fillRandom02(image);
      }
      end = System.currentTimeMillis();

      elapsed = (double)(end - start) / count;
      fps = Math.round(1000. / elapsed);

      System.out.println(String.format(Locale.US, "Elapsed: %.2f milliseconds per one fillRandom02, expected fps is %d", elapsed, fps));
      ImageIO.write(image, "PNG", new File("fillRandom02.png"));




      start = System.currentTimeMillis();
      for(int i=0; i<count; ++i) {
         fillRandom03(image);
      }
      end = System.currentTimeMillis();

      elapsed = (double)(end - start) / count;
      fps = Math.round(1000. / elapsed);

      System.out.println(String.format(Locale.US, "Elapsed: %.2f milliseconds per one fillRandom03, expected fps is %d", elapsed, fps));
      ImageIO.write(image, "PNG", new File("fillRandom03.png"));


   }


   public static void fillRandom00(BufferedImage image) {
      for(int x=0; x<image.getWidth(); ++x) {
         for(int y=0; y<image.getHeight(); ++y) {
            rnd.nextInt(0xFFFFFF);
         }
      }
   }


   public static void fillRandom01(BufferedImage image) {
      for(int x=0; x<image.getWidth(); ++x) {
         for(int y=0; y<image.getHeight(); ++y) {
            image.setRGB(x, y, rnd.nextInt(0xFFFFFF));
         }
      }
   }


   public static void fillRandom02(BufferedImage image) {
      for(int i=0; i<array.length; ++i) {
         array[i] = rnd.nextInt(0xFF);
      }
      image.getRaster().setPixels(0, 0, image.getWidth(), image.getHeight(), array);
   }


   public static void fillRandom03(BufferedImage image) {
      int[] array = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
      for(int i=0; i<array.length; ++i) {
         array[i] = rnd.nextInt(0xFFFFFF);
      }
   }

}

“fillRandom00” method is just generating WxH number of random values.

“fillRandom01” is using straightforward method utilizing BufferedImage#setRGB()

“fillRandom02” is trying to prepare array of ints separately and bitblt them onto BufferedImage.

And the latest method “fillRandom03” is using direct access to BuffereImage data.

Output of the program is following:

Elapsed: 7.97 milliseconds per one fillRandom00, expected fps is 125
Elapsed: 32.01 milliseconds per one fillRandom01, expected fps is 31
Elapsed: 28.75 milliseconds per one fillRandom02, expected fps is 35
Elapsed: 7.90 milliseconds per one fillRandom03, expected fps is 127

As it can be expected, the latest method appeared as fastest. But surprise is that it appeared even faster, than just generating numbers. Probably, this is effect of nested loop?

From JavaFX properties to reactive observables in Android programming

Previous year I was programming under JavaFX. I found, that they have introduced nice extension over old-fashion Java Bean convention.

In short

Old-fashion Java Bean convention expects, that each property is represented by two methods: so-called “getter” and, optionally, a “setter”. So, if you wish your object have property called message of type String, you define

public String getMessage() {
...
}

public void setMessage( String newValue ) {
...
}

Convention didn’t bother with how and where you will store this propery value. Nor property exist in language. It is some sort of “emergent” or “imaginary” thing. Other propgramming languages like C# have explicit property concept, but Java does not. In Java it’s only convention. Note Camel naming, and “get” and “set” prefixes.

However, this convention is used in many libraries and frameworks. For example, in Spring you can set property just by it’s name from configuration XML file:

<bean id="helloWorld" class="com.tutorialspoint.HelloWorld">
       <property name="message" value="Hello World!"/>
</bean>

Example is from TutorialsPoint.

What if you want property to be observable?

In standard Java you are proposed to add several methods like

addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
}

void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
}

Again, Java does not bother how you will implement housekeeping. Although library provides helper class PropertyChangeSupport. With this class I was usually doing something like this:

public void setMessage( String newValue ) {
   String oldValue = getMessage();
   if( !Objects.equals( newValue, oldValue ) ) {
      ... // housekeeping for property
      pcs.fireProperyChange("message", oldValue, newValue);
   }
}

Property change code is global for a class, i.e. the same set of listeners can be maintained for all observable properties of the class. Additionally tradeoff is that you need to have property names in string form somewhere.

What in JavaFX?

In JavaFX they have expended convention. Additionally to setter and getter programmer is to provide third method:

public StringProperty messageProperty() {
   ...
}

Note, that property name is now goes first in method name, starts with small letter and appended with “Property” postfix. This is property accessor. It returns proprty itself, i.e. now properties “materialized”!

In more detail you can read it in Oracle’s article “Using JavaFX Properties and Binding”.

StringProperty is a member of big family of classes which you can extend and re-implement. Old-fashion getters and setters now may be rewritten as follows:

public String getMessage() {
   return messageProperty().getValue();
}

public void setMessage( String newValue ) {
   messageProperty().setValue( newValue );
}

The sugar is that all JavaFX properties are “bindable” by nature. “Bindable” means not only that you can listen property change as with conventional bean properties, but you can also wire one property to another via complex transformations chain and this wiring will hold all the time application runs.

For example, you can bind property of you messager like this:

helloWorld.messageProperty().bind( 
   Bindings.when( mood.happyProperty() ).
      .then( "Hello World!" )
      .otherwise( "Goodbye Cruel World!" )
);

Here we have bound property “helloWorld.message” with property “mood.happy” via conditional expression. Whenever “mood.happy” will change, “helloWorld.message” will also change appropriatedly. The chain of listeners and updaters is created by JavaFX automatically. This is called “High-Level Binding API” and covered in article, referenced above.

Small runnable binding example is here on Java2S.

ReactiveX

Unfortunately JavaFX propery model has some imperfections and didn’t get wide popularity. Particularly, there are no JavaFX properies on Android. If you wish to bind controls, states and so on, you are to code it different way.

Now, I am writing my first Android application and was thinking about, what library to use instead of JavaFX properties? I found that so-called reactive programming is actively developing and that there are libraries ReactiveX library for many languages, including Java.

Unfortunately, it is not 1:1 corresponding with JavaFX properies and making accents on different things like multithreading.

First problem I met, is that reactive observables are apparently not made to be object members at all. Of course, I am trying to resemble what I was learned in JavaFX, for example, if I want that my object contain observable property, I am creating a method

public Observable<Boolean> connectedObservable() {
    ....
}

As you see, I use postfix “Observable” instead of “Property” here. Don’t know if this has any sense.

Second thing is how to convert Android style notifications to observables. Android uses even older approach, when programmer is provided by abstract class or interface with abstract handler methods, which he need to implement.

For example, ServiceConnection interface. When you implement it, you are to override methods like “onServiceConnected”. What if I want to conver this call into reactive observable?

For now I came to the following solution with the use of BehaviorSubject:

private final BehaviorSubject<Boolean> connectedSubject = BehaviorSubject.create();

public Observable<Boolean> connectedObservable() {
    return connectedSubject.asObservable();
}

....

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
   connectedSubject.onNext(true);
}

Note, that I am making just very first steps in Android and this solution can be absolutely irrelevant with what is really required…

Database Studios Some Criticism

Many of database studios like MySQL Workbench, Devart dbForge Studio for MySQL and  JetBrains DataGrip provides very strange and limited support of SQL files. The only thing you can do with SQL file is run it and see some results, most often limited number of rows.

But it is very strange functionality.

If SQL query returns million of rows, there is no sense to show 1000 of them. If SQL query modifies some table, there is no sence to keep it opened.

From my experience, SQL queries are always parts of some manual or automated procedures, i.e. organized in sequences or trees. So, I would like is SQL studio software provide some sort of “schema” or any other type of organization chart for SQL files.

It can be something like this:

example-of-sql-dependencies

(drawn in EA)

BTW, dbForge has very nice “dependency” feature for server side objects:

dbforge-dependency-feature

Would like something close to development-machine-sided SQL files.