SPOJ - LASTDIG

Problem: http://www.spoj.com/problems/LASTDIG/
I guess the most interesting part of the problem is to use binary exponentiation to solve the problem.
http://en.wikipedia.org/wiki/Modular_exponentiation#Right-to-left_binary_method



import java.util.Scanner;

/**
 * SPOJ - LASTDIG
 */
class BinaryExponentiation {

public static void main(String[] args){

  Scanner in = new Scanner(System.in);
  int numOfTest = in.nextInt();
  while(numOfTest-- != 0){
    System.out.println(new BinaryExponentiation().modPower(in.nextInt(), in.nextInt(), 10));
  }
}

  private int modPower(int base, int exponent, int modulus) {
    int result = 1;
    while (exponent>0){
      if(exponent % 2 == 1){
        result = (result*base) % modulus;
      }
      exponent = exponent >> 1;
      base = (base * base) % modulus;
    }

    return result;
  }

}

SPOJ - TOANDFRO

Problem: http://www.spoj.com/problems/TOANDFRO/


import java.util.Scanner;

/**
 * SPOJ - TOANDFRO
 */
class TOANDFRO {
  public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    while (true){
      int numOfCols = in.nextInt();
      if(numOfCols==0){
        break;
      }

      char[] encrpytedString = in.next().toCharArray();

      int numOfRows = encrpytedString.length/numOfCols;

      for(int i=0; i < numOfCols; i++){

        for(int k=0; k < numOfRows;k++){
          if(k%2 == 0){
            System.out.print(encrpytedString[k*numOfCols+i]);
          } else {
            System.out.print(encrpytedString[k*numOfCols+ (numOfCols - i -1)]);
          }
        }

      }
      System.out.println();
    }
  }

SPOJ - ACPC10A

Easy problem for fun http://www.spoj.com/problems/ACPC10A/



import java.util.Scanner;

/**
 * 7974. What’s Next
 * Problem code: ACPC10A
 *
 */
class ACPC10A {

  public static void main(String[] args){
    Scanner in = new Scanner(System.in);

    while(true){
      int a = in.nextInt();
      int b = in.nextInt();
      int c = in.nextInt();

      if(a==0 && b==0 && c==0){
        break;
      } else if (b-a == c-b){
         System.out.println("AP " + (c + b - a));
      } else {
        System.out.println("GP " + (c * (b / a)));
      }


    }
  }

}

Factorial (SPOJ - FCTRL)

Problem link http://www.spoj.com/problems/FCTRL/



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

//
// SPOJ Problem Set (classical)
// 11. Factorial
//
// Problem code: FCTRL

class Factorial {

  public static void main(String[] args) throws IOException {
    new Factorial().begin();
  }

  private void begin() throws IOException {

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int lineOfInput = Integer.parseInt(in.readLine().trim());

    while(lineOfInput-- != 0){
      int factorial = Integer.parseInt(in.readLine().trim());

      int totalOfZero = 0;
      while(factorial!=0){
        factorial /= 5;
        totalOfZero += factorial;
      }

      System.out.println(totalOfZero);

    }

  }
}

Prime Generator (SPOJ - PRIME1)


SPOJ Problem Set (classical)
2. Prime Generator
Problem code: PRIME1
Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!
http://www.spoj.com/problems/PRIME1/
The key to solve this problem is to use http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes.


import java.io.*;

/**
 * SPOJ Problem Set (classical)
 * 2. Prime Generator
 * Problem code: PRIME1
 */
class PrimeGen {

  public static void main(String[] args) throws IOException {
    new PrimeGen().begin();
  }

  void begin() throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int numOfTest = Integer.parseInt(in.readLine());

    while((numOfTest--) != 0){
      String[] readRange = in.readLine().split(" ");
      int n = Integer.parseInt(readRange[0]);
      int m = Integer.parseInt(readRange[1]);

      boolean[] primes = new boolean[m-n+1];

      for(int p = 2; p*p <= m; p++){
        int less = n / p;
        less *= p;
        for(int k=less; k<=m; k+=p){
          if(k>=n && p!=k){
            primes[k-n] = true;
          }
        }
      }

      for(int i=0; i<primes.length;i++){
        if((primes[i] != true) && (i+n !=1)){
          System.out.println(n+i);
        }

      }

      if(numOfTest!=0){
        System.out.println();
      }
    }
  }

}

Automatic schema generation with Hibernate’s SchemaExport

On the other hand, we can generate DDL by annotated classes using the SchemaExport class. Below is a sample code in addition to the previous post.



package models;

import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class App {

    enum Dialect {
        MYSQL("org.hibernate.dialect.MySQLInnoDBDialect");

        private String className;

        private Dialect(String className) {
            this.className = className;
        }

        public String getClassName() {
            return className;
        }
    }

    private void executeSchemaExport(Dialect dialect, Class<?>... classes) {
        Configuration configuration = new Configuration();
        configuration.setProperty(Environment.DIALECT, dialect.getClassName());
        for (Class<?> entityClass : classes) {
            configuration.addAnnotatedClass(entityClass);
        }
        SchemaExport schemaExport = new SchemaExport(configuration);
        schemaExport.setDelimiter(";");
        schemaExport.setOutputFile(String.format("%s_%s.%s ", new Object[] {"ddl", dialect.name().toLowerCase(), "sql" }));
        boolean consolePrint = true;
        boolean exportInDatabase = false;
        schemaExport.create(consolePrint, exportInDatabase);
    }


  public static void main(String[] args) {
      new App().executeSchemaExport(Dialect.MYSQL, AvatarEntity.class, StockEntity.class);
  }



}

How to use JPA and Hibernate Support in IntelliJ IDEA


Objective:

  • Add sample tables and records to MySql database with for preparation
  • Generate persistency mapping in IntelliJ IDEA (You will need Enterprise edition) 
  • Query records from database
  • Storing and retreiving an image


Let’s start by creating the sample database


create database springtest;

CREATE TABLE  `springtest`.`stock` (
  `STOCK_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `STOCK_CODE` VARCHAR(10) NOT NULL,
  `STOCK_NAME` VARCHAR(20) NOT NULL,
  PRIMARY KEY (`STOCK_ID`) USING BTREE,
  UNIQUE KEY `UNI_STOCK_NAME` (`STOCK_NAME`),
  UNIQUE KEY `UNI_STOCK_ID` (`STOCK_CODE`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

insert into stock (STOCK_ID,STOCK_CODE,STOCK_NAME) VALUES (1,'MQG','Mac Bank');

CREATE TABLE  `springtest`.`avatar` (
  `AVATAR_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `IMAGE` BLOB NOT NULL,
  PRIMARY KEY (`AVATAR_ID`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

Following this video to generate persistency mapping in IntelliJ, note that you will end up with different classes because it depends on the data source we used.

http://www.youtube.com/watch?v=bGl4u44WRiI

At the end you will have two Entity Classes generated:

AvatarEntity


package models;

import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Arrays;

@javax.persistence.Table(name = "avatar", schema = "", catalog = "springtest")
@Entity
public class AvatarEntity {
    private int avatarId;

    @javax.persistence.Column(name = "AVATAR_ID")
    @Id
    public int getAvatarId() {
        return avatarId;
    }

    public void setAvatarId(int avatarId) {
        this.avatarId = avatarId;
    }

    private byte[] image;

    @javax.persistence.Column(name = "IMAGE")
    @Basic
    public byte[] getImage() {
        return image;
    }

    public void setImage(byte[] image) {
        this.image = image;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        AvatarEntity that = (AvatarEntity) o;

        if (avatarId != that.avatarId) return false;
        if (!Arrays.equals(image, that.image)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = avatarId;
        result = 31 * result + (image != null ? Arrays.hashCode(image) : 0);
        return result;
    }
}

StockEntity



package models;

import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.Id;

@javax.persistence.Table(name = "stock", schema = "", catalog = "springtest")
@Entity
public class StockEntity {
    private int stockId;

    @javax.persistence.Column(name = "STOCK_ID")
    @Id
    public int getStockId() {
        return stockId;
    }

    public void setStockId(int stockId) {
        this.stockId = stockId;
    }

    private String stockCode;

    @javax.persistence.Column(name = "STOCK_CODE")
    @Basic
    public String getStockCode() {
        return stockCode;
    }

    public void setStockCode(String stockCode) {
        this.stockCode = stockCode;
    }

    private String stockName;

    @javax.persistence.Column(name = "STOCK_NAME")
    @Basic
    public String getStockName() {
        return stockName;
    }

    public void setStockName(String stockName) {
        this.stockName = stockName;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        StockEntity that = (StockEntity) o;

        if (stockId != that.stockId) return false;
        if (stockCode != null ? !stockCode.equals(that.stockCode) : that.stockCode != null) return false;
        if (stockName != null ? !stockName.equals(that.stockName) : that.stockName != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = stockId;
        result = 31 * result + (stockCode != null ? stockCode.hashCode() : 0);
        result = 31 * result + (stockName != null ? stockName.hashCode() : 0);
        return result;
    }
}

We can now query the record from the stock table using the entityManager. We can also save a image to the database and export it out.


package models;

import org.hibernate.ejb.HibernatePersistence;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.spi.PersistenceProvider;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;


public class HibernateApp {

  public static final String SELECT_QUERY =
          "from StockEntity where stockId =:stockId";

  public static void main(String[] args) {

    HibernateApp hibernateApp = new HibernateApp();
    EntityManager entityManager = hibernateApp.getEntityManager();

    int stockId = 1;

    List stocks = entityManager.createQuery(SELECT_QUERY, StockEntity.class).setParameter("stockId", stockId).getResultList();

    System.out.println(stocks.get(0).getStockCode());

    //begin transaction
    entityManager.getTransaction().begin();

    //save image into database
    File file = new File("ostrich.jpg");
    hibernateApp.saveImage(entityManager, file);

      //Get image from database

    hibernateApp.exportImage(entityManager);

    //end transaction
    entityManager.getTransaction().commit();
  }

  private void exportImage(EntityManager entityManager) {
    List result = entityManager.createQuery( "from AvatarEntity", AvatarEntity.class ).getResultList();
    for ( AvatarEntity event : result ) {
        byte[] bAvatar = event.getImage();
        try{
            FileOutputStream fos = new FileOutputStream("ostrichCopy.jpg");
            fos.write(bAvatar);
            fos.close();
        }catch(Exception e){
            e.printStackTrace();
        }


    }
  }

  private void saveImage(EntityManager entityManager, File file) {
    byte[] bFile = new byte[(int) file.length()];

    try {
        FileInputStream fileInputStream = new FileInputStream(file);
        //convert file into array of bytes
        fileInputStream.read(bFile);
        fileInputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    AvatarEntity avatar = new AvatarEntity();
    avatar.setImage(bFile);

    entityManager.persist(avatar);
  }

  private EntityManager getEntityManager() {
        PersistenceProvider persistenceProvider = new HibernatePersistence();
        EntityManagerFactory entityManagerFactory = persistenceProvider.createEntityManagerFactory("NewPersistenceUnit", new HashMap());
        return entityManagerFactory.createEntityManager();
    }
}

Notes on book: “JavaScript: The Good Parts Unearthing the Excellence in JavaScript”

Javascript is not going away, it had been here since 1994, and after 18 years, it is still here, all the popular frameworks and libraries such as JQuery, AngularJS are all built on top of Javascript. I strongly encourage anyone to learn JavaScript properly instead of scrapping and learning bit and pieces from little scripts on the internet. A good start is to read Douglas Crockford’s JavaScript: The Good Parts Unearthing the Excellence in JavaScript. Douglas as you may aware of, is known for JSON.

I am half way through the book. To be frank, I absolutely loved the book and I hope to finish it soon as it contains 170-ish page only. I was always trying to find a book that is thin but still manages to cover the crucial fundamentals that I need to remember, and this book does it perfectly by not including the bad parts of Javascript that we should not learn anyway (quite difficult to unlearn stuff).

Some comments on the examples in the book:

Page 84 | Chapter 8: Methods

Function

function.apply(thisArg, argArray)

The apply method invokes a function, passing in the object that will be bound to this and an optional array of arguments. The apply method is used in the apply invocation pattern (Chapter 4):

 
Function.method('bind', function (that) { 
    // Return a function that will call this function as 
    // though it is a method of that object. 
    var method = this, 
    slice = Array.prototype.slice, 
    args = slice.apply(arguments, [1]); 
    return function () { 
         return method.apply(that, 
             args.concat(slice.apply(arguments, [0]))
        ); 
    }; 
}); 
    
var x = function () { 
    return this.value; 
}.bind(
    {value: 666}
); 

alert(x()); // 666 

I was confused with the example as first, because of the unnecessary code, which could be simplify to:

 
Function.method('bind1', function (that) { 
    // Return a function that will call this function as 
    // though it is a method of that object. 
    var method = this; 
    return function () { 
        return method.apply(that, arguments); 
    };} 
); 

Second thought, it might be because the author wanted it to be generic enough for code reuse, but it does not seems so, as you may notice,

 slice.apply(arguments, ...); 

is executed twice and then concatenated together, with hard-coded argArrays [0] and [1].

Let me know if you know what did he intended to do.


Where did I get my blog social network icons from? Here: IconFinder
                                       

Where did I get my blog social network icons from? Here: IconFinder



CSS goodies:
I was trying to find out ways to customise this blog’s theme, and instead of starting from scratch, I found out that there is actually a pretty awesome framework - Twitter Bootstrap that did the groundwork for us.
However, one thing that I feel quite annoyed about is that the icons from Twitter Bootstrap could not be resized nicely without fiddling CSS quite a bit with the image. See post which suggeted that Font-Awesome is a better alternative, it uses fonts instead of images, much easier and conveninent to deal with enlarging.
Links:
http://twitter.github.com/bootstrap/index.htmlhttp://fortawesome.github.com/Font-Awesome
                                       

CSS goodies:

I was trying to find out ways to customise this blog’s theme, and instead of starting from scratch, I found out that there is actually a pretty awesome framework - Twitter Bootstrap that did the groundwork for us.

However, one thing that I feel quite annoyed about is that the icons from Twitter Bootstrap could not be resized nicely without fiddling CSS quite a bit with the image. See post which suggeted that Font-Awesome is a better alternative, it uses fonts instead of images, much easier and conveninent to deal with enlarging.

Links:

http://twitter.github.com/bootstrap/index.html
http://fortawesome.github.com/Font-Awesome


blog comments powered by Disqus