Thursday, March 28, 2013

How to check if a value is NaN in C++


I didn't know until now that if (a != a) returns true only when a is NaN.


#include <iostream>
#include <cmath>

using namespace std;

int main() {
    float a = sqrt(-1); // nan
    if (a != a) {
        cout << "It's NaN!" << endl;
        cout << a << endl; // prints 'nan'
    }
    else {
        cout << "It's OK!" << endl;
    }
    return 0;
}

Friday, November 23, 2012

Python threads with queue.

import threading
import Queue

import urllib2
import time
                
urls = ["http://www.google.com", \
    "http://www.naver.com", \
    "http://www.daum.net"]
    
queue = Queue.Queue()
        
class CustomThread(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue

    def run(self):
        while True:
            task_url = self.queue.get()
            start = time.time()
            page = urllib2.urlopen(task_url)
            end = time.time()
            print """%s elapsed %s (from %s)""" \
                % (task_url, end - start, self.getName())
            self.queue.task_done()

def main():
    for i in range(2):
        t = CustomThread(queue)
        t.daemon = True
        t.start()

    for task_url in urls:
        queue.put(task_url)

    queue.join()

    print "Ended"

if __name__ == "__main__":
    main()


This is typical producer-consumer model using queue. We can use this model when we want to keep threads running on though tasks are consumed up(like threadpool). Otherwise, we can call join() for each thread instead of calling queue.join().

Thursday, August 16, 2012

Dustin Hyun at NHN Corporation.

I was interviewed to be posted on corporate blog of nhn(written in Korean).

http://naver_diary.blog.me/150144134830


NHN PEOPLE - 2. 개발자

NHN에서 가장 많은 사람은? 당연히 개발자입니다. NHN 직원 중 절반 이상이 개발자입니다. 게다가 인터넷 서비스에 필요한 소프트웨어는 워낙 다양하기 때문에, 개발자들이 담당하는 역할도 천차만별입니다. 이번 시리즈를 준비하면서 다양한 개발직군의 모습을 보여 드리고 싶었는데요. NHN PEOPLE 두 번째 주인공 현동석 차장은 그 좋은 예가 될 것 같...





Friday, May 25, 2012

Good explanation on linux daemon.

I was programming a daemon invoked from a python script which is also invoked from a server that fork() .py when it gets a command through TCP connection.

TCP:Message => Server:fork() => python:os.system() => daemon(c++)

However, server couldn't return the message from python script even though the binary was demonized successfully(It was a zombie proccess).

I spent a lot of time to find for this. TT. I found that the daemon inherited all file descriptors from the server via .py script.

Now everything works find after closing all fds after being fork()ed.

Useful links:
http://www.enderunix.org/docs/eng/daemon.php

Friday, June 24, 2011

Recording Desktop at Ubuntu

Very simple.

Record with gtk-RecordMyDeskTop. Outfile format will be .ogv

To convert ogv to avi,

> mencoder -idx out.ogv -ovc lavc -oac mp3lame -o out.avi

Done.

Monday, June 13, 2011

C++: Building custom vector class.


Making custom container class with iterator would be a good example for C++ beginner.




Vector.h


#ifndef VECTOR_H
#define VECTOR_H

#include <vector>
#include "VectorIterator.h"

class Vector {
public:
    typedef VectorIterator iterator;

    Vector(int size) { data_.resize(size); }

    int size() const;
    void push_back(const int val);

    VectorIterator begin();
    VectorIterator end();

    int& operator[](const int& idx);
private:
    std::vector<int> data_;
};

inline int &
Vector::operator[](const int& idx) {
    return data_[idx];
}
inline int
Vector::size() const {
    return data_.size();
}

inline void
Vector::push_back(const int val) {
    data_.push_back(val);
    return;
}

#endif /* VECTOR_H */


Vector.cpp


#include "Vector.h"

VectorIterator
Vector::begin() {
    return VectorIterator(&data_);
}

VectorIterator
Vector::end() {
    VectorIterator vec(&data_);
    vec.setIndex(data_.size());
    return vec;
}


VectorIterator.h


#ifndef VECTORITERATOR_H
#define VECTORITERATOR_H

#include <vector>

class VectorIterator {
public:

    VectorIterator();
    VectorIterator(std::vector<int> * data);

    void setIndex(int v);
    int operator*();
    int operator++();
    bool operator==(const VectorIterator& rhs) const;
    bool operator!=(const VectorIterator& rhs) const;
private:
    std::vector<int>* pvec_;
    int index_;
};

inline int
VectorIterator::operator*()
{
    return (*pvec_)[index_];
}

inline int
VectorIterator::operator++()
{
    index_++;
    return (*pvec_)[index_];
}

inline bool
VectorIterator::operator==(const VectorIterator& rhs) const
{
    return (pvec_ == rhs.pvec_ && index_ == rhs.index_);
}

inline bool
VectorIterator::operator!=(const VectorIterator& rhs) const
{
    return !(*this == rhs);
}
#endif /* VECTORITERATOR_H */


VectorIterator.cpp


#include "VectorIterator.h"

void
VectorIterator::setIndex(int v) {
    index_ = v;
    return;
}

VectorIterator::VectorIterator()
    : pvec_(NULL), index_(0) {}

VectorIterator::VectorIterator(std::vector<int> * data)
    : pvec_(data), index_(0) {}



main.cpp


#include <iostream>
#include "Vector.h"

int main()
{
    int size = 10;
    Vector vec(size);

    for (int i = 0; i < vec.size(); i++)
        vec[i] = 2 * i;

    for (Vector::iterator iter = vec.begin();
        iter != vec.end(); ++iter)
        std::cout << *iter << std::endl;

    return 0;
}

Thursday, June 9, 2011

making google preview


With phantomjs, I made a simple search preview like Google's preview.


When user input query, thumbnail for each search result is gathered simultaneously. This works with render function of phantomjs(webkit based script binary). The image it made is saved with hashed url as a filename so that it would not render twice. And it also highlight with red box where the query appears in the page(You can see little tiny red bordered box in the thumbnail above, right?). Though it consumes lots of system resources, it works.