DB with anorm

scala 2016. 3. 2. 16:58

scala에서 DB를 연동할 때, JDBC를 직접 사용할 수도 있지만

Play Framework와 함께 할때는 Anorm을 사용하는 방법이 편리하다.


REF-SITE :play



사용모습을 보면 아래와 같다.



(예제: 출처 https://janhelwich.wordpress.com/tag/anorm/ )

object Post{
  val parser = {
      get[String]("title") ~
      get[Date]("posted") ~
      get[String]("content")~
      get[Pk[Int]]("authorId") map {
      case title ~ posted ~ content ~ author => Post(title,  posted, content, User.findBy(author))
    }
  }
 
  def findAll() = {
    DB.withConnection {
      implicit connection =>
        SQL("select * from posts").as(parser *)
    }
  }
 
  def create(post: Post): Unit = {
    DB.withConnection {
      implicit connection =>
        SQL("insert into posts(title, posted, content, authorId) values ({title}, {posted}, {content}, {authorId})").on(
          'title -> post.title,
          'posted -> post.posted,
          'content -> post.content,
          'authorId -> post.author.id
        ).executeUpdate()
    }
  }


Posted by yongary
,

Anonymous class

java core 2016. 2. 26. 21:50

java의 abstract class 나 interface가  instance 화가 될 수 있냐? 고 질문한다면

답은  1. 일반적으론 안된다.  

          2. 그렇지만 anonymous class 방식으로는 된다. REF(Runnable 참조)

       이렇게 둘 다 답하면 best 이다.

 

참고로 
 abstract class : 추상 method가 하나이상 존재--> 상속시 추상 method구현을 강제함.
 Interface : 추상 method만으로 이루어진 class   but jdk1.8에서는  구현된 method도 허용함.  

     REF-SITE:

Posted by yongary
,

[char array->String]

char cArr[] ;  

String s = String.valueOf(cArr);

 

 

 

 

1. Array에 특정한 Object가 있는지 Check:


Arrays.asList(yourArray).contains(yourValue)

Warning: this doesn't work for arrays of primitives (see the comments).


2. LinkedList 에서 삭제 및 data Set.

Size()가 변하는 loop안이라면 Iterator를 사용하여 삭제하는 게 안전.

아니면 뒤에서부터 앞으로 Loop돌면서 삭제. (테스트 필요)

 

Iterator<String> iter = list.iterator();
while (iter.hasNext()) {  
     String s = iter.next(); //꼭 next먼저 호출.
     if (s.equals("a"))  iter.remove();  //원래 remove는 가장최근 return()한 걸 삭제하는 이상한 함수임.
}


ListIterator의 경우에는 iter.set() 함수도 매우 쓸만하다. //이 역시, 가장 장최근 return()한 걸 치환.


3. LinkedList  에 특정위치에 data 넣고 싶을때?

    LikedList<String> list = new LinkedList<String>();

    list.add("a");list.add("c");


    <a,c사이에 b를 넣고 싶으면>

    list.add(1,"b");   // index를 이미 안다면,  방법을 쓰거나..

    list.add ( getIndex("a")+1, "b"); //모른다면.. 이방법. 근데이게 getIndex가 속도가 의심이 됨..  

     최상의 방법은? 뭘까요?  
     자가 List라면  node.next.next = node.next;  node.next = new Node(); 하면 되는데.. 
     

     이런방법 없을까요?


     

      

     

      

    

    


Posted by yongary
,

Java memory 사용량.

java core 2016. 2. 23. 23:50
public static void main(String[] args) {

    long used1 = memoryUsed();
    int[][] array = new int[200][2];

    long used2 = memoryUsed();
    int[][] array2 = new int[2][200];

    long used3 = memoryUsed();
    if (used1 == used2) {
        System.err.println("You need to turn off the TLAB with -XX:-UseTLAB");
    } else {
        System.out.printf("Space used by int[200][2] is " + (used2 - used1) + " bytes%n");
        System.out.printf("Space used by int[2][200] is " + (used3 - used2) + " bytes%n");
    }
}

public static long memoryUsed() {
    Runtime rt = Runtime.getRuntime();
    return rt.totalMemory() - rt.freeMemory();
}
출처: stackoverflow peter lawrey 


Posted by yongary
,

/*

usage: 

MyJson mj = new MyJson(aLineString);   // {"key1:value1","key2:value2"} 

        String offTime = mj.get("key1") ;

*/



class MyJson{

private HashMap<String, String> hm = new HashMap<String,String>();

public MyJson(String json){

String normal = json.replaceAll("[{\"}]", ""); //remove {,", }

System.out.println("(normal)"+normal);

String[] kvset = normal.split(",\\s*");  // comma + (*:space exist or not)

for( String s : kvset){

String kv[] = s.split(":");

if( kv.length==2)

hm.put(kv[0], kv[1]);

else{

System.err.println("Json Parse err(may have only key) "+s);

}

}

}

public String get(String key){

return hm.get(key);

}

}

Posted by yongary
,

=============My BucketSort. Example===================

 

import java.util.HashMap;
import java.util.LinkedList;
import java.util.ListIterator;



public class BucketSort {

private HashMap<Integer, LinkedList> hMap;
/*
input: unSorted Array, #bucket(number of Bucket)
process: bucket sorting Using #bucket
return: sorted Array.
*/
public Integer[] bucketSort(Integer data[], int numBucket){
Integer[] ret = new Integer[data.length];
hMap = new HashMap<Integer, LinkedList>();



for (int i: data) {
Integer key = numBucket * (i / numBucket); //분모가 maxInt 가 맞을듯.(16.6)

==> 그냥 i%numBucket가 맞을 듯한데.. 좀더 보자.(2017.10)

LinkedList<Integer> prevList;



//make new List and add to HashMap.. when there's no data
if ( (prevList = hMap.get(key)) == null ) {
LinkedList<Integer> list = new LinkedList<Integer>();
list.add(i);
hMap.put(key,list);
}else{ //prevList traverse and add i to apporate position
ListIterator<Integer> it = prevList.listIterator();

boolean added = false; //added flag prevents Concurrent Modify Error.
while (it.hasNext()) { //at least 1 element. SO always on this loop.
if (it.next() > i ) { //Add to Proper position
prevList.add(it.previousIndex(),i);
added = true;
break;
}
}
if (!added)
prevList.add(i); //Add to End

}//else
} //for



//to array.
int k=0;
for (int j=0; j< numBucket; j++){
Integer key = numBucket*j;
LinkedList<Integer> list = hMap.get(key);

if (list!=null) {
ListIterator<Integer> it = list.listIterator();

while (it.hasNext())
ret[k++] = it.next();
}
}

return ret;
}

/////////MAIN /////////////////
public static Integer datas[]={77, 11, 22, 55, 44, 33, 99, 88, 21, 23, 37, 41, 81, 91, 74, 19, 30, 40 };

public static void main(String args[]){

BucketSort b = new BucketSort();
Integer[] data = b.bucketSort(datas, 10);

for ( int i : data)
System.out.print(i+",");
}
}


Posted by yongary
,

Quick Sort using java Generic.

==>   <T extends Comparable> working. <T implements Comparable> not working.

 (Java Generic을 이용해서 Quick Sort를 구현하여보았는데..

            ==>  <T extends Comparable> 이건 동작하는데 <T implements Comparable>은 동작하지 않음)

public class QSortGen<T extends Comparable> {  


void swap(T data[], int i, int j){
T tmp = data[i];
data[i]=data[j];
data[j]=tmp;
}

public void qSort( T[] data, int st, int end){
if (st == end || end < 0) return;

T pivot=data[end]; //Pivot is End (temporary)

int j=end-1;
int i=0;
while (i<j) {
while ( i<j && data[i].compareTo(pivot) < 0 ) i++;
while ( j>i && data[j].compareTo(pivot) > 0) j--;
if (i < j)
swap(data, i, j);
};

System.out.println( "new Pivot:" +i + ","+j);

//IF pivot Largest ?
if ( j == end-1 && data[j].compareTo(pivot) < 0 ) // (j == end-1) =>sometimes wrong. when only 3 data.
qSort(data, 0, end-1);

//General pivot
else {
swap(data, i ,end); //i is real Pivot
qSort(data, 0, i-1); //left divide and conquer:recursive
qSort(data, j+1, end); //right divide and comquer:recursive
}
}

/////////MAIN /////////////////
public static String datas[]={"adf", "kk", "bb", "aa", "dd", "cc", "ff" };

public static void main(String args[]){
QSortGen<String> q = new QSortGen<String>();
q.qSort(datas, 0, datas.length-1);

for( String a : datas)
System.out.println(a);
}
}


Posted by yongary
,

Scala OO Example

scala 2016. 2. 1. 10:52

Scala를 이용해서 OO를 TEST.

(OO Test using Scala)

object Seminar{


class Dog(a:Int, n:String){
var age:Int = a
var name:String = n

def feed()={
println(this.name+ ":eating dog food")
}
}


class Cat(a:Int, n:String) extends Dog(a:Int, n:String){
override def feed()={
println(this.name+ ":eating Cat food")
}
}


//////// MAIN ////////////////////////////////////////////////
def main(args:Array[String]) = {
var allDog:Array[Dog] = Array( new Dog(1,"dogA"),
new Dog(2,"dogB"),
new Dog(3,"dogC"),
new Dog(4,"dogD"),
new Cat(5,"catA"))


for( dog<- allDog)
dog.feed()

}
} //end
Posted by yongary
,

Quick Sort (java)

algorithm & type 2016. 1. 31. 00:34

[int Array기반 간단한 QuickSort]

- http://www.algolist.net/Algorithms/Sorting/Quicksort 참고.

=>c++ 코드 참조하면.. 한번소트 후에, 끝나면 i가 j보다 크군요..

(j=2, i=3) 이때, j포함 왼쪽. i포함 오른쪽 돌려야 함.

public void quickSort(int arr[], int left, int right) { int i = left, j = right; int tmp; int pivotValue = arr[(left + right) / 2]; /* partition */ while (i <= j) { while (arr[i] < pivotValue) i++; while (arr[j] > pivotValue) j--; if (i <= j) { tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; i++; j--; } }; /* recursion */ if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } public static void main(String args[]){ SortSearch s = new SortSearch(); int A[] = new int[] {9,8,7,6,5,4,3,2,1}; s.quickSort(A, 0, A.length-1); for (int a : A){ System.out.println(a); }

}




-----------아래 건은 연습용------------------

[Simple Quick Sort Example.. with String Array]

- using End element as a temporary Pivot.


 

public class QuickSort {


void swap(String data[], int i, int j){
String tmp = data[i];
data[i]=data[j];
data[j]=tmp;
}

public void qSort( String[] data, int st, int end){
if (st == end || end < 0) return;

String pivot=data[end];
//Pivot is End (temporary)

int j=end-1;
int i=0;
while (i<j) {
while ( i<j && data[i].compareTo(pivot) < 0 ) i++;
while ( j>i && data[j].compareTo(pivot) > 0) j--;
if (i < j)
swap(data, i, j);
};

System.
out.println( "new Pivot:" +i + ","+j);

//IF pivot Largest ?
if ( j == end-1 && data[j].compareTo(pivot) < 0 ) // (j == end-1) =>sometimes wrong. when only 3 data.
qSort(data, 0, end-1);

//General pivot
else {
swap(data, i ,end);
//i is real Pivot
qSort(data, 0, i-1); //left divide and conquer:recursive
qSort(data, j+1, end); //right divide and comquer:recursive
}
}

/////////main
public static String datas[]={"adf", "kk", "bb", "aa", "dd", "cc", "ff" };
public static void main(String args[]){
QuickSort q =
new QuickSort();
q.qSort(
datas, 0, datas.length-1);

for( String a : datas)
System.
out.println(a);
}
}


Posted by yongary
,

일반적으로 정렬 중에 가장 빠른 알고리듬은 quick sort로서 O(N*logN)의 평균속도를 가지고 있다.

 

하지만, 분포가 어느정도 균등한 자료의 경우

버킷 소트를 하게 되면 O(n)으로 정렬을 할 수 있다.

 

Hash의 개념을 사용하게 되며..  그림은 REF-SITE  참조.

 

 

단점: 버킷을 미리 만들어 둬야 하므로 메모리 소비가 좀 있고

그 외 최악의 속도는 O(n)*버킷내 정렬시간 이 되므로 O(n**2)까지도 갈 수 있다.

(어차피 quick sort도 O(n**2)까지 갈 수 있으므로.  자료가 적당하다면 일반적으로 quick sort보다 속도는 좋은 것 같다 ).

Posted by yongary
,