2013年12月22日 星期日

[Webkit] Function flow for javascript JIT execution.

Just a memo for myself to remark function flow of JIT execution.

HTMLTokenizer::scriptHandler                  // start from here to handle script

    HTMLTokenizer::scriptExecution

    ScriptController::executeScript

        Completion::evaluate

            Executable::complie               // Compile script

                 Parser::parse

            bytecodegenerator::generate       // generate byte code



            Interpreter::execute

                Executable::JITCode

                Executable::GenerateJITCode   // Compile and generateJITCode

                    JIT::Compile

                JITCode::execute              // execute JIT code

return to HTMLTokenizer::scriptHandler


Now, we generated some JIT code for basic execution demand and byte code objects for whole script.
Then, we have to compile byte code objects to JIT code for executing each function in script.

CallData::Call     // Get byte code object and compile to JIT code for each call

    Interpreter::executeCall

    JITCodeforCall::executable

        Executable::generateJITCodeforCall

    JIT::Compile

    JITCode::execute

return to CallData::Call

Call stack for reference:
JAVASCRIPTCORE!JSC::Interpreter::execute(JSC::ScopeChainNode * 0x077df768, JSC::JSObject * 0x00c60000, JSC::JSValue * 0x001cc8a0)  line 638
JAVASCRIPTCORE!JSC::evaluate(JSC::JSValue {...})  line 65
WEBKIT!WebCore::JSMainThreadExecState::evaluate(JSC::ExecState * 0x07791870, JSC::ScopeChain & {...}, const JSC::SourceCode & {...}, JSC::JSValue {...})  line 54 + 22 bytes
WEBKIT!WebCore::ScriptController::evaluateInWorld(const WebCore::ScriptSourceCode & {...}, WebCore::DOMWrapperWorld * 0x00000000, WebCore::ShouldAllowXSS 1887600)  line 147
WEBKIT!WebCore::ScriptController::evaluate(const WebCore::ScriptSourceCode & {...}, WebCore::ShouldAllowXSS DoNotAllowXSS)  line 172 + 26 bytes
WEBKIT!WebCore::ScriptController::executeScript(const WebCore::ScriptSourceCode & {...}, WebCore::ShouldAllowXSS AllowXSS)  line 62 + 22 bytes
WEBKIT!WebCore::HTMLTokenizer::scriptExecution(const WebCore::ScriptSourceCode & {...}, WebCore::HTMLTokenizer::State {...})  line 561 + 56 bytes
WEBKIT!WebCore::HTMLTokenizer::scriptHandler(WebCore::HTMLTokenizer::State {...})  line 508 + 230 bytes
WEBKIT!WebCore::HTMLTokenizer::parseNonHTMLText(WebCore::SegmentedString & {...}, WebCore::HTMLTokenizer::State {...})  line 351 + 18 bytes
WEBKIT!WebCore::HTMLTokenizer::advance(WebCore::HTMLTokenizer::State & {...})  line 1626 + 48 bytes
WEBKIT!WebCore::HTMLTokenizer::write(const WebCore::SegmentedString & {...}, bool true)  line 1784
WEBKIT!WebCore::DocumentWriter::addData(const char * 0x00000000, int 1124084960, bool true)  line 191 + 36 bytes
WEBKIT!WebCore::FrameLoader::addData(const char * 0x001cd4cc, int 8192)  line 1414
WEBKIT!WebFrameLoaderClient::receivedData(const char * 0x0752ebe0, int 123760368, const WebCore::String & {...})  line 601
WEBKIT!WebFrameLoaderClient::committedLoad(WebCore::DocumentLoader * 0x00762b80, const char * 0x001cd4cc, int 8192)  line 572
WEBKIT!WebCore::FrameLoader::committedLoad(WebCore::DocumentLoader * 0x00762b80, const char * 0x001cd4cc, int 8192)  line 3016
WEBKIT!WebCore::DocumentLoader::commitLoad(const char * 0x077df768, int 125376624)  line 281
WEBKIT!WebCore::DocumentLoader::receivedData(const char * 0x001cd4cc, int 8192)  line 293
WEBKIT!WebCore::FrameLoader::receivedData(const char * 0x001cd4cc, int 8192)  line 1839
WEBKIT!WebCore::MainResourceLoader::addData(const char * 0x001cd4cc, int 8192, bool false)  line 148
WEBKIT!WebCore::ResourceLoader::didReceiveData(const char * 0x0077e800, int 1125760212, __int64 8101893163188217, bool true)  line 264
WEBKIT!WebCore::MainResourceLoader::didReceiveData(const char * 0xfffffff9, int 1886368, __int64 8101923229845812, bool true)  line 410
WEBKIT!WebCore::ResourceLoader::didReceiveData(WebCore::ResourceHandle * 0x07777b20, const char * 0x001cd4cc, int 8192, int 0)  line 438
WEBKIT!WebCore::ResourceHandle::onRequestComplete(long 1869182051)  line 1550
WEBKIT!WebCore::ResourceJobManager::ResourceHandleWndProc(HWND__ * 0xfe070002, unsigned int 1026, unsigned int 4, long 0)  line 296
WEBKIT!WebCore::CustomEventVictoria::DoAction(NEventHandler * 0x000aa54c)  line 47
NEVENTBASELIB!41113ef6()
NEVENTBASELIB!41114082()
BROWSER!Browser::Run()  line 81
BROWSER!WinMain()  line 23
BROWSER!WinMainCRTStartupHelper()  line 71 + 14 bytes
BROWSER!WinMainCRTStartup()  line 105
COREDLL!MainThreadBaseFunc(HINSTANCE__ * 0x00000000, HINSTANCE__ * 0x00000000)  line 1209 + 54 bytes
fffffdff()
JavaScriptCore.dll!JSC::Interpreter::executeCall(JSC::ExecState * callFrame=0x0c0d1b90, JSC::JSObject * function=0x033ea340, JSC::CallType callType=CallTypeJS, const JSC::CallData & callData={...}, JSC::JSValue thisValue={...}, const JSC::ArgList & args={...}, JSC::JSValue * exception=0x058c4eb8)  Line 738 C++
JavaScriptCore.dll!JSC::call(JSC::ExecState * exec=0x0c0d1b90, JSC::JSValue functionObject={...}, JSC::CallType callType=CallTypeJS, const JSC::CallData & callData={...}, JSC::JSValue thisValue={...}, const JSC::ArgList & args={...})  Line 38 + 0x3b bytes C++
WebKit.dll!WebCore::JSMainThreadExecState::call(JSC::ExecState * exec=0x0c0d1b90, JSC::JSValue functionObject={...}, JSC::CallType callType=CallTypeJS, const JSC::CallData & callData={...}, JSC::JSValue thisValue={...}, const JSC::ArgList & args={...})  Line 48 + 0x20 bytes C++
WebKit.dll!WebCore::JSEventListener::handleEvent(WebCore::ScriptExecutionContext * scriptExecutionContext=0x0b118518, WebCore::Event * event=0x0c565500)  Line 124 + 0x5f bytes C++
WebKit.dll!WebCore::EventTarget::fireEventListeners(WebCore::Event * event=0x0c565500, WebCore::EventTargetData * d=0x0c55007c, WTF::Vector & entry={...})  Line 330 C++
WebKit.dll!WebCore::EventTarget::fireEventListeners(WebCore::Event * event=0x0c565500)  Line 295 C++
WebKit.dll!WebCore::EventTarget::dispatchEvent(WTF::PassRefPtr event={...})  Line 276 + 0x11 bytes C++
WebKit.dll!WebCore::XMLHttpRequestProgressEventThrottle::dispatchEvent(WTF::PassRefPtr event={...}, WebCore::ProgressEventAction progressEventAction=DoNotFlushProgressEvent)  Line 82 C++
WebKit.dll!WebCore::XMLHttpRequest::callReadyStateChangeListener()  Line 287 + 0x53 bytes C++
WebKit.dll!WebCore::XMLHttpRequest::didReceiveData(const char * data=0x0025d914, int len=8192)  Line 987 C++
WebKit.dll!WebCore::DocumentThreadableLoader::didReceiveData(WebCore::SubresourceLoader * loader=0x0c5589a0, const char * data=0x0025d914, int lengthReceived=8192)  Line 226 C++
WebKit.dll!WebCore::SubresourceLoader::didReceiveData(const char * data=0x0025d914, int length=8192, __int64 lengthReceived=0, bool allAtOnce=false)  Line 177 C++
WebKit.dll!WebCore::ResourceLoader::didReceiveData(WebCore::ResourceHandle * __formal=0x0c55f8b8, const char * data=0x0025d914, int length=8192, int lengthReceived=0)  Line 439 C++
WebKit.dll!WebCore::ResourceHandle::onRequestComplete(long lParam=0)  Line 1389 C++
WebKit.dll!WebCore::ResourceJobManager::ResourceHandleWndProc(HWND__ * hWnd=0x00151be8, unsigned int message=1026, unsigned int wParam=5, long lParam=0)  Line 273 C++
WebKit.dll!WebCore::CustomEventVictoria::DoAction(NEventHandler * pEventHandler=0x009b0e20)  Line 47 C++
NEventBaseLib.dll!0f347382()  
[Frames below may be incorrect and/or missing, no symbols loaded for NEventBaseLib.dll] 
NEventBaseLib.dll!0f346ffc()  
Browser.exe!Browser::Run()  Line 80 + 0xe bytes C++
Browser.exe!WinMain(HINSTANCE__ * hInstance=0x00880000, HINSTANCE__ * hPrevInstance=0x00000000, char * lpCmdLine=0x003d3605, int nCmdShow=1)  Line 17 + 0xc bytes C++
Browser.exe!__tmainCRTStartup()  Line 578 + 0x35 bytes C
Browser.exe!WinMainCRTStartup()  Line 403 C
kernel32.dll!757f1154()  
ntdll.dll!773ab299()  
ntdll.dll!773ab26c()  

2013年12月12日 星期四

[Webkit] Callstack for RenderObject::setStyle

Webkit development offen happen to layout issue, I just remark where to set object style here.

WEBKIT!WebCore::RenderObject::setStyle(WTF::PassRefPtr<WebCore::RenderStyle> * 0x0010d430 {m_ptr=0x004eb898 {m_affectedByAttributeSelectors=false m_unique=false m_affectedByEmpty=false ...} })  line 1523
WEBKIT!WebCore::Document::recalcStyle(WebCore::Node::StyleChange 0x00512c80)  line 1377
WEBKIT!WebCore::Document::attach()  line 1527
WEBKIT!WebCore::Frame::setDocument(WTF::PassRefPtr<WebCore::Document> * ...)  line 273
WEBKIT!WebCore::DocumentWriter::begin(const WebCore::KURL & {m_string={m_impl={m_ptr=0x00000000 {s_copyCharsInlineCutOff=??? m_data=??? m_buffer=??? ...} } } m_isValid=true m_protocolInHTTPFamily=false ...}, bool true, WebCore::SecurityOrigin * ...)  line 115
WEBKIT!WebCore::FrameLoader::receivedFirstData()  line 784
WEBKIT!WebCore::FrameLoader::willSetEncoding()  line 1406
WEBKIT!WebCore::DocumentWriter::setEncoding(const WebCore::String & {m_impl={m_ptr=0x00000000 {s_copyCharsInlineCutOff=??? m_data=??? m_buffer=??? ...} } }, bool false)  line 243
WEBKIT!WebFrameLoaderClient::receivedData()  line 595
WEBKIT!WebFrameLoaderClient::committedLoad()  line 567
WEBKIT!WebCore::FrameLoader::committedLoad(WebCore::DocumentLoader * 0x00523600 {m_dataSource=0x06cb4400 {m_refCount=0x00000001 m_loader={m_ptr=0x00523600 {m_dataSource=0x06cb4400 m_detachedDataSource=0x00000000 } } m_representation={m_ptr=0x00000000 } } m_detachedDataSource=0x00000000 {m_refCount=??? m_loader={m_ptr=??? } m_representation={m_ptr=??? } } }, const char * ...)  line
WEBKIT!WebCore::DocumentLoader::commitLoad(const char * 0x00000000 <Bad Ptr>, int 0x004ef200)  line 281
WEBKIT!WebCore::DocumentLoader::receivedData(const char * ...)  line 293
WEBKIT!WebCore::FrameLoader::receivedData(const char * ...)  line 1839
WEBKIT!WebCore::MainResourceLoader::addData(const char * ...)  line 148
WEBKIT!WebCore::ResourceLoader::didReceiveData(const char * 0x00000000 <Bad Ptr>, int 0x005897e0, __int64 0x4180000000000000, bool true)  line 264
WEBKIT!WebCore::MainResourceLoader::didReceiveData(const char * 0x00000000 <Bad Ptr>, int 0x41800000, __int64 0x00512c980058d7d0, bool true)  line 410
WEBKIT!WebCore::ResourceLoader::didReceiveData(WebCore::ResourceHandle * 0x004e15c0 {m_dumpedFileHandle=0x00000000 d={m_ptr=0x00581800 {m_client=0x004f4000 {m_initialRequest={...} m_substituteData={...} m_dataLoadTimer={...} ...} m_request={m_type=RequestMain } m_lastHTTPMethod={m_impl={...} } ...} } }, const char * ...)  line 438
WEBKIT!WebCore::ResourceHandle::loadFile()  line 1938
WEBKIT!WebCore::ResourceHandle::fileLoadTimer(WebCore::Timer<WebCore::ResourceHandle> * 0x0010d003 {m_object=0xec2d7000 {m_dumpedFileHandle=??? d={m_ptr=??? } } m_function=0xec2d7e00 })  line 2086
WEBKIT!WebCore::Timer<WebCore::Document>::fired()  line 113 + 26 bytes
WEBKIT!WebCore::ThreadTimers::sharedTimerFiredInternal()  line 115
WEBKIT!WebCore::ThreadTimers::sharedTimerFired()  line 91
WEBKIT!WebCore::Victoria_Shared_Timer::OnTimer()  line 87
NSTANDARDLIB!40de3538()
NEVENTBASELIB!41033f98()
NEVENTBASELIB!41034078()
BROWSER!Browser::Run()  line 81
BROWSER!WinMain()  line 23
BROWSER!WinMainCRTStartupHelper()  line 71 + 14 bytes
BROWSER!WinMainCRTStartup()  line 105
COREDLL!MainThreadBaseFunc(HINSTANCE__ * 0x00000000 {unused=??? }, HINSTANCE__ * 0x00000000 {unused=??? })  line 1209 + 54 bytes
fffffdff()

2013年12月2日 星期一

[Webkit] Callstack for handle string event to append text to HtmlInputElement.

Memo for handle string event.

It would be useful if you like to know the function flow to append text to HtmlInputElement.

WEBKIT!WebCore::TypingCommand::insertTextRunWithoutNewlines(const WTF::String & {...}, bool false)  line 369
WEBKIT!WebCore::TypingCommandLineOperation::operator()(unsigned int 0, unsigned int 1, bool true)  line 63 + 68 bytes
WEBKIT!WebCore::forEachLineInString<WebCore::TypingCommandLineOperation>(const WTF::String & {...}, const WebCore::TypingCommandLineOperation & {...})  line 62
WEBKIT!WebCore::TypingCommand::insertText(const WTF::String & {...}, bool false)  line 360
WEBKIT!WebCore::TypingCommand::insertText(WebCore::Document * 0x0c71f800, const WTF::String & {...}, const WebCore::VisibleSelection & {...}, unsigned int 0, WebCore::TypingCommand::TextCompositionType TextCompositionNone)  line 194
WEBKIT!WebCore::Editor::insertTextWithoutSendingTextEvent(const WTF::String & {...}, bool false, WebCore::TextEvent * 0x0062b420)  line 944
WEBKIT!WebCore::Editor::handleTextEvent(WebCore::TextEvent * 0x0062b420)  line 181 + 20 bytes
WEBKIT!WebCore::EventHandler::defaultTextInputEventHandler(WebCore::TextEvent * 0x0062b420)  line 3501 + 20 bytes
WEBKIT!WebCore::Node::defaultEventHandler(WebCore::Event * 0x0062b420)  line 2760
WEBKIT!WebCore::HTMLTextFormControlElement::defaultEventHandler(WebCore::Event * 0x0062b420)  line 106
WEBKIT!WebCore::HTMLInputElement::defaultEventHandler(WebCore::Event * 0x0062b420)  line 1249
WEBKIT!WebCore::EventDispatcher::dispatchEventPostProcess(WTF::PassRefPtr<WebCore::Event> * 0x0015e4bc, void * 0x00000000)  line 350
WEBKIT!WebCore::EventDispatcher::dispatchEvent(WTF::PassRefPtr<WebCore::Event> * 0x0015e784)  line 267
WEBKIT!WebCore::EventDispatchMediator::dispatchEvent(WebCore::EventDispatcher * 0x0015e7b4)  line 52 + 108 bytes
WEBKIT!WebCore::EventDispatcher::dispatchEvent(WebCore::Node * 0x0063e140, WTF::PassRefPtr<WebCore::EventDispatchMediator> * 0x0015e828)  line 129 + 52 bytes
WEBKIT!WebCore::Node::dispatchEvent(WTF::PassRefPtr<WebCore::Event> * 0x0015e874)  line 2577 + 96 bytes
WEBKIT!WebCore::EventTarget::dispatchEvent(WTF::PassRefPtr<WebCore::Event> * 0x0015e934, int & 6831584)  line 143 + 84 bytes
WEBKIT!WebCore::EventHandler::handleTextInputEvent(const WTF::String & {...}, WebCore::Event * 0x0c70a0b0, WebCore::TextEventInputType TextEventInputKeyboard)  line 3467
WEBKIT!WebCore::Editor::insertText(const WTF::String & {...}, WebCore::Event * 0x0c70a0b0)  line 885 + 36 bytes
WEBKIT!WebView::handleEditingKeyboardEvent(WebCore::KeyboardEvent * 0x0c70a0b0)  line 3246 + 116 bytes
WEBKIT!WebEditorClient::handleKeyboardEvent(WebCore::KeyboardEvent * 0x0c70a0b0)  line 636 + 20 bytes
WEBKIT!WebCore::Editor::handleKeyboardEvent(WebCore::KeyboardEvent * 0x0c70a0b0)  line 151
WEBKIT!WebCore::EventHandler::defaultKeyboardEventHandler(WebCore::KeyboardEvent * 0x0c70a0b0)  line 3200
WEBKIT!WebCore::Node::defaultEventHandler(WebCore::Event * 0x0c70a0b0)  line 2745
WEBKIT!WebCore::HTMLTextFormControlElement::defaultEventHandler(WebCore::Event * 0x0c70a0b0)  line 106
WEBKIT!WebCore::HTMLInputElement::defaultEventHandler(WebCore::Event * 0x0c70a0b0)  line 1189
WEBKIT!WebCore::EventDispatcher::dispatchEventPostProcess(WTF::PassRefPtr<WebCore::Event> * 0x0015f36c, void * 0x00000000)  line 350
WEBKIT!WebCore::EventDispatcher::dispatchEvent(WTF::PassRefPtr<WebCore::Event> * 0x0015f634)  line 267
WEBKIT!WebCore::EventDispatchMediator::dispatchEvent(WebCore::EventDispatcher * 0x0015f690)  line 52 + 108 bytes
WEBKIT!WebCore::KeyboardEventDispatchMediator::dispatchEvent(WebCore::EventDispatcher * 0x0015f690)  line 222 + 12 bytes
WEBKIT!WebCore::EventDispatcher::dispatchEvent(WebCore::Node * 0x0063e140, WTF::PassRefPtr<WebCore::EventDispatchMediator> * 0x0015f704)  line 129 + 52 bytes
WEBKIT!WebCore::Node::dispatchKeyEvent(const WebCore::PlatformKeyboardEvent & {...})  line 2618 + 188 bytes
WEBKIT!WebCore::EventHandler::keyEvent(const WebCore::PlatformKeyboardEvent & {...})  line 3049 + 12 bytes
WEBKIT!WebView::keyPress(unsigned int 71, long 0, bool false)  line 3525 + 20 bytes
WEBKIT!WebView::handleStrEvent(wchar_t * 0x005005d8)  line 3402 + 44 bytes
BROWSER!CoreService::OnPressTenKey2()  line 904
BROWSER!EBSS_fBrowser__onPressTenKey2()  line 106
UICOMMONLIB!40f683f0()
NEVENTBASELIB!40d63f10()
NEVENTBASELIB!40d64530()
BROWSER!Browser::Run()  line 81
BROWSER!WinMain()  line 17 + 8 bytes
BROWSER!WinMainCRTStartupHelper(HINSTANCE__ * 0xfffffffd, HINSTANCE__ * 0x00000005, unsigned short * 0xf101f798, int 1)  line 71 + 20 bytes
COREDLL!MainThreadBaseFunc(void * 0x00000000, const wchar_t * 0x00000000, const wchar_t * 0x00000000, HINSTANCE__ * 0x00000000, HINSTANCE__ * 0x00000000, HINSTANCE__ * 0x00000000)  line 1209 + 88 bytes
f101fffc()

2013年11月26日 星期二

Step by step to compile a C++ program on Ubuntu.

Reference:
http://www.wikihow.com/Compile-a-C/C%2B%2B-Program-on-Ubuntu-Linux

1. Install compiling tool
sudo apt-get install build-essential

2.Create a directory to hold your programs
mkdir -p CCPP/HelloWorld

3. Go into the directory you created.
cd CCPP/HelloWorld

4. Create CPP file
gedit main.cpp

5. Fill code in main.cpp and save it.
#include<iostream>
using namespace std;
int main()
{
    cout << "\nHello World !\n" << endl;
    return(0);
}

6. Compile it.
g++ -Wall -W -Werror main.cpp -o HelloWorldCPP
7. Execute it.
./HelloWorldCPP



2013年10月28日 星期一

2013年10月22日 星期二

Install LAMP on Ubuntu

Copy from http://www.howtoforge.com/ubuntu_lamp_for_newbies for note.

Install Apache

1. Open up the Terminal (Applications > Accessories > Terminal).
2. Type the following command in Terminal
sudo apt-get install apache2
3. The Terminal will then ask you for you're password, type it and then press enter.

Testing Apache

1. Open up any web browser and then enter the following into the web address:
http://localhost/












Install PHP

Step 1. Again open up the Terminal (Applications > Accessories > Terminal).
Step 2. Copy/Paste the following line into Terminal and press enter:
sudo apt-get install php5 libapache2-mod-php5
Step 3. In order for PHP to work and be compatible with Apache we must restart it. Type the following code in Terminal to do this:
sudo /etc/init.d/apache2 restart

Test PHP

Step 1. In the terminal copy/paste the following line:
sudo gedit /var/www/testphp.php
This will open up a file called phptest.php.
Step 2. Copy/Paste this line into the phptest file:
<?php phpinfo(); ?>
Step 3. Save and close the file.
Step 4. Now open you're web browser and type the following into the web address:
http://localhost/testphp.php
The page should look like this:
















Install MySQL

To finish this guide up we will install MySQL. (Note - Out of Apache and PHP, MySQL is the most difficult to set up. I will provide some great resources for anyone having trouble at the end of this guide.)
Step 1. Once again open up the amazing Terminal and then copy/paste this line:
sudo apt-get install mysql-server

It would tip you to set password for 'root' and continue the installing.














Step 2 (optional). In order for other computers on your network to view the server you have created, you must first edit the "Bind Address". Begin by opening up Terminal to edit the my.cnf file.
gksudo gedit /etc/mysql/my.cnf
Change the line
bind-address = 127.0.0.1
And change the 127.0.0.1 to your IP address.

Step 3 (optional). Login mysql and set password for root
mysql -u root -p
Following that copy/paste this line:
mysql> set password for root@localhost = password('yourpassword');
(Make sure to change yourpassword to a password of your choice.)

Step 4. We are now going to install a program called phpMyAdmin which is an easy tool to edit your databases. Copy/paste the following line into Terminal:
sudo apt-get install libapache2-mod-auth-mysql php5-mysql phpmyadmin
It would ask you to choice http server type and input mysql password to set config.

Now just restart Apache and you are all set!
sudo /etc/init.d/apache2 restart

2013年10月16日 星期三

Get web content by telnet

We can get http content by telnet.

1. telnet to host server.
    telnet www.yahoo.com 80
2. send request
    GET / HTTP/1.1
    Host: www.yahoo.com









2013年6月28日 星期五

Convert from char* to wchar_t*

To Convert char* to wchar_t*

Assume we have a char* string named c

    const size_t cSize = strlen(c)+1;
    wchar_t* wc = new wchar_t[cSize];
    mbstowcs (wc, c, cSize);


Now you have wchar_t* string wc.

You can also refer to http://twnin.blogspot.tw/2012/03/convert-between-char.html for more type to convert.

2013年5月27日 星期一

[C#] Download files from website.

We have two ways to download files from website by using .net framework.

1. WebClient.
using System.Net;

private void button1_Click(object sender, EventArgs e)
{
    WebClient wc = new WebClient();
    wc.DownloadFile("http://www.taifex.com.tw/DailyDownload/Daily_2013_05_24.zip", "d:\\Daily_2013_05_24.zip");
}


2. HttpRequest + Stream
using System.IO;
using System.Net;

private void button1_Click(object sender, EventArgs e)
{
    string url = "http://www.taifex.com.tw/DailyDownload/Daily_2013_05_24.zip";
    HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
    HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();

    System.IO.Stream dataStream = httpResponse.GetResponseStream();
    byte[] buffer = new byte[8192];

    FileStream fs = new FileStream("d:\\Daily_2013_05_24.zip", FileMode.Create, FileAccess.Write);
    int size = 0;
    do
    {
        size = dataStream.Read(buffer, 0, buffer.Length);
        if (size > 0)
            fs.Write(buffer, 0, size);
    } while (size > 0);
    fs.Close();

    httpResponse.Close();

    Console.WriteLine("Done at " + DateTime.Now.ToString("HH:mm:ss.fff"));
}



Reference:
http://blog.darkthread.net/post-2008-10-14-download-file-with-c.aspx

2013年5月11日 星期六

N Coin Problem

Question:
Given a list of 'N' coins, their values being in an array A[], return the minimum number of coins required to sum to 'S' (you can use as many coins you want). If it's not possible to sum to 'S', return -1

For Example, input N coins array { 1, 3, 5 } and S as 11, the answer should be 3



My Answer:  (I am not sure if it is correct.)
int minCoins(int* a, int count, int target)
{
    int N = count;
    int S = target;

    int *mina=NULL;
    mina = new int[S+1];
 
    mina[0]=0;
     
    for(int i=1;i<=S;i++)
    {
        mina[i]=-1;
 
        for(int j=0;j<N;j++)
        {
            if(a[j]<=i && mina[i-a[j]] != -1)  
            {
                if(mina[i]==-1 || mina[i-a[j]]+1 < mina[i])
                {
                   mina[i] = mina[i-a[j]]+1;
                }
            }
        }
    }
 
    return mina[S];
}

2013年5月10日 星期五

Circle sorted array searching.

Question:
Given a circle sorted array, please write a function to search a number and output its position.

Example:
Find number 6 in array { 1,2,3,4,5,6,7 }, output is 5
Find number 6 in array { 5,6,7,1,2,3,4 }, output is 1

My Answer:  (I am no sure if it is correct.)

#include "stdafx.h"
#include 

using namespace std;

int binarySearch(int n, int* a, int l, int r);

int _tmain(int argc, _TCHAR* argv[])
{
 int a[7] = { 4, 5, 6, 7, 1, 2, 3 };
 
 cout << binarySearch(6, a, 0, 6) << endl;
 cout << binarySearch(2, a, 0, 6) << endl;
 cout << binarySearch(5, a, 0, 6) << endl;

 cin.get();
 return 0;
}

int binarySearch(int n, int* a, int l, int r)
{
 int i = (l + r) / 2;
 if (n == a[i])
  return i;

 if (a[l] < a[r])
 {
  if (n > a[i])
  {
   l += 1;
  }
  else
  {
   r = i - 1;
  }
 }
 else
 {
  if (n > a[i] || n < a[l])
  {
   l += 1;
  }
  else
  {
   r = i - 1;
  }
 }

 return binarySearch(n, a, l, r);
}

2013年5月9日 星期四

Number Complement.

Question: 
A complement of a number is defined as inversion (if the bit value = 0, change it to 1 and vice-versa) of all bits of the number starting from the leftmost bit that is set to 1. 

For example, if N = 5, N is 101 in binary. The complement of N is 010, which is 2 in decimal. Similarly if N = 50, then complement of N is 13 
Complete the function getIntegerComplement(). This function takes N as it's parameter. The function should return the complement of N.  (The N >=0)


My Answer:  (I am not sure if it is correct.)
int getComplement(int n)
{
    if (n == 0)
        return 1;

    int b = 0;
    int a = n;
    while (a > 0)
    {
        a >>= 1;
        b++;
    };

    int mask = pow(2.0, b) - 1;
    int result = n ^ mask;
    return result;
}

2013年5月8日 星期三

Get Nth power of number.

Question:
Given two integer a and b (b >= 0), please write a function to return the result of "a to the power of b".

My Anwser: (I am no sure if it is correct.)
The easiest way is recursively multiply integer a.
int power(int a, int b)
{
    if (b <= 0)
        return 1;

    return a * power(a, b-1);
}


Question:
Improve time complexity to log(n)

My Anwser: (I am no sure if it is correct.)
Consider a to the power of 15 is power(a, 8) * power(a, 4) * power(a, 2) * power(a, 1) * power(a, 0)
#include "stdafx.h"
#include 

using namespace std;

int getPower(int a, int b);
int power(int a, int b);

int _tmain(int argc, _TCHAR* argv[])
{
    int a = 2, b = 15;
 
    cout << power(a, b) << endl;

    cin.get();
    return 0;
}

int getPower(int a, int logb)
{
    if (logb <= 0)
        return 1;

    return a * getPower(a*a, logb-1);
}

int power(int a, int b)
{
    if (b == 0)
        return 1;

    int logb = 0;
    while(b>0)
    {
        logb++;
        b >>= 1;
    }

    return getPower(a, logb);
}


2013年3月16日 星期六

Fibonacci Factor Problem


Story
Given a number K, find the smallest Fibonacci number that shares a common factor( other than 1 ) with it. A number is said to be a common factor of two numbers if it exactly divides both of them. 
Output two separate numbers, F and D, where F is the smallest fibonacci number and D is the smallest number other than 1 which divides K and F.
Input Format  
First line of the input contains an integer T, the number of testcases.
Then follows T lines, each containing an integer K.
Output Format
Output T lines, each containing the required answer for each corresponding testcase.

Sample Input 
3
3
5
161
Sample Output
3 3
5 5
21 7

Explanation 
There are three testcases. The first test case is 3, the smallest required fibonacci number  3. The second testcase is 5 and the third is 161. For 161 the smallest fibonacci numer sharing a common divisor with it is 21 and the smallest number other than 1 dividing 161 and 7 is 7.

Constraints :
1 <= T <= 5
2 <= K <= 1000,000
The required fibonacci number is guranteed to be less than 10^18.


My Answer: (I am no sure if it is correct.)
#include "stdafx.h"
#include <iostream>

using namespace std;

int fb(int i);

int _tmain(int argc, _TCHAR* argv[])
{
 int count = 0;
 cin >> count;
 int *input = new int[count];
 for (int i = 0; i<count; i++)
 {
  cin >> input[i];
 }

 for (int i = 0; i<count; i++)
 {
  int k = 1;
  int fbNumber = 1;
  while (fbNumber <= input[i]) 
  {
   for (int x=2; x<=fbNumber; x++)
   {
    if (fbNumber % x == 0 && input[i] % x == 0 )
    {
     cout << input[i] << " " << fbNumber << endl;
    }
   }

   k++;
   fbNumber = fb(k);
  };
 }

 return 0;
}

int fb(int i)
{
 if (i<=1)
  return 1;

 if (i==2)
  return fb(1);

 return fb(i-1) + fb(i-2);
}


Reference:
https://amazon.interviewstreet.com/challenges/dashboard/#problem/4fd653336df28

2013年3月15日 星期五

Candies giving problem

Story

Alice is a teacher of kindergarten. She wants to give some candies to the children in her class. All the children sit in a line and each of them has a rating score according to his or her usual performance. Alice wants to give at least 1 candy for each children. Because children are somehow jealousy. Alice must give her candies according to their ratings subjects to for any adjacent 2 children if one's rating is higher than the other he/she must get more candies than the other. Alice wants to save money so she wants to give as few as candies in total.

Input

The first line of the input is an integer N, the number of children in Alice's class. Each of the followingN lines contains an integer indicates the rating of each child.

Output

On the only line of the output print an integer describing the minimum number of candies Alice must give.

Sample Input

3
1
2
2

Sample Output

4




My Answer (I am no sure if it is correct.)
#include "stdafx.h"
#include <iostream;

using namespace std;

class child {
public:
    child() : m_candy(1) {}
    child(int rating) : m_rating(rating), m_candy(1) {}

    int Rating() { return m_rating; }
    void setRating(int rate) { m_rating = rate; }
    int Candy() { return m_candy; }
    void setCandy(int candies) { m_candy = candies; }

private:
    int m_rating;
    int m_candy;
};

void showCandies(int[], int);

int _tmain(int argc, _TCHAR* argv[])
{
    const int count = 10;
    int childs_rating[] = {9,2,3,3,3,2,1,1,3,4};

    showCandies(childs_rating, count);

    cin.get();
 return 0;
}

void showCandies(int* rating, int count)
{
    child* childs = new child[count];
    for(int i=0;i<count;i++)
    {
        childs[i].setRating(rating[i]);
    }

    bool run = false;
    do
    {
        run = false;

        for(int i=0;i<count-1;i++)
        {
            if( childs[i].Rating() ; childs[i+1].Rating() && childs[i].Candy() <= childs[i+1].Candy())
            {
                run = true;
                childs[i].setCandy(childs[i+1].Candy() + 1);
            }

            if( childs[i+1].Rating() ; childs[i].Rating() && childs[i+1].Candy() <= childs[i].Candy())
            {
                run = true;
                childs[i+1].setCandy(childs[i].Candy() + 1);
            }
        }

        for(int i=0;i<count;i++)
        {
            cout << childs[i].Candy() << '\t';
        }
        cout << endl;
    } while(run);

    delete[] childs;
}



Reference:
http://stackoverflow.com/questions/11292913/candies-interviewstreet

How to sum the Integers from 1 to N.

Question:
How to sum the Integers from 1 to N.

Answer:
#include "stdafx.h"
#include 

using namespace std;

int allPlus(int n);

int _tmain(int argc, _TCHAR* argv[])
{
    const int n = 100;
    int sum = allPlus(n);

    cout << sum << endl;

    std::cin.get();
 return 0;
}

int allPlus(int n)
{
    if (n == 0)
        return 0;

    return n + allPlus(n-1);
}


Advanced Answer:
Change function allPlus below for O(1) time complexity
int allPlus(int n)
{
    return (1 + n) * n / 2;
}


* All answer just my answer, I am no sure if it is correct.

2013年3月14日 星期四

Find duplicated numbers in an array.

Question:
Given an array with N+M items, each item is number between 1 to N, please give a O(M+N) solution to print all duplicated numbers.

Answer:
#include "stdafx.h"
#include 

using namespace std;

void printDuplicate(int arr[], int nm, int n);

int _tmain(int argc, _TCHAR* argv[])
{
    const int n = 10, m = 5;
    const int nm = n+m;
    int arr[nm] = {1,2,3,4,5,6,7,8,9,10,1,2,3,4,2};

    printDuplicate(arr, nm, n);

    std::cin.get();
    return 0;
}

void printDuplicate(int arr[], int nm, int n)
{
    int* pArray = new int[n];
    for (int i=0; i<n; i++)
    {
        pArray[i] = 0;
    }

    for (int i=0; i<nm; i++)
    {
        int value = arr[i];
        pArray[value]++;

        if (pArray[value] == 2)
            cout << value << endl;
    }
}


Advanced Question:
Give an answer without using extra space.

Answer:
Change function printDumplicate as below.
void printDuplicate(int arr[], int nm, int n)
{
    int pArray = 0;

    for (int i=0; i 0)
            cout << value << endl;

        pArray |= (1 << (value-1));
    }
}


Thinking:
If you use bits of an integer variable to keep all status, remember that there are 32 bits only.


* All answer just my answer, not the best one.

How to swap two variables without using a temporary variable.

Question:
How to swap two variables without using a temporary variable.


Anser:
There are 3 methods to tackle this issue.

1. XOR
a = a ^ b;
b = a ^ b;
a = a ^ b;

2. Addition and Minus
a = a + b;
b = a - b;
a = a - b;


3. Multiplying and Division
a = a * b;
b = a / b;
a = a / b;


Thinking:
It is possible overflow if you use method 2 and 3.

Why method 1 work? Because N ^ N = 0 and N ^ 0 = N, so you can think
a' = a ^ b;
b' = a' ^ b 
   = a ^ b ^ b 
   = a ^ 0 
   = a;
a'' = a' ^ b' 
    = a ^ b ^ a 
    = 0 ^ b 
    = b;



Reference:
http://emn178.pixnet.net/blog/post/92113175
http://emn178.pixnet.net/blog/post/92389195-%E9%9D%A2%E8%A9%A6%E5%B8%B8%E8%A6%8B%E7%A8%8B%E5%BC%8F%E8%80%83%E9%A1%8C-%E7%A8%8B%E5%BC%8F%E5%AF%A6%E5%81%9A


2013年3月10日 星期日

internal and external iterator

What different between internal and external iterator?


external iterator:
It is a separate class that can step through its container/collection.
So you can control the logic to get the item what you want.


ex.
std::vector<int> v;
for(vint::iterator it=v.begin(), it!=v.end(); ++i)
    std::cout << *it << "\n";




internal iterator:
It is implemented with member functions to step through.
You only can get the items in turn, but it is more easy to use than external iterator.


ex.
MACRO_FOREACH(v)
{
    std::cout << v << "\n";
}


2013年1月16日 星期三

Output Debug String

As we know, we can use API OutputDebugString to show string on output window, like,

OutputDebugString(" This is debug message. ");
OutputDebugStringW(L" This is debug message. ");

You also can attach some variable to the output string.

wchar_t* world = L"world";
wchar_t* szBuffer = new wchar_t[512];
wsprintf(szBuffer, _T(" Hello %s \n"),  world);
OutputDebugString(szBuffer);
delete[] szBuffer;

or

wchar_t* message = L"world !";

wchar_t* str = L" Hello ";
wchar_t* buffer = new wchar_t[sizeof(str)+sizeof(message)+1];
wcscpy(buffer, str);
wcscat(buffer, message);
OutputDebugStringW(buffer);


or

float value = 100;
wchar_t* szBuffer = new wchar_t[512];
wsprintf(szBuffer, L" My math grade is %d \n",   (int)value);
OutputDebugString(szBuffer);
delete[] szBuffer;

or

float value = 100;
char* szBuffer = new char[512];
sprintf(szBuffer, L" My math grade is %f \n",  value);
OutputDebugStringA(szBuffer);
delete[] szBuffer;




2013年1月15日 星期二

[Platform Builder] Output Logging Message to File

As we all know, there are lots of useful message shown in output window.
The window doesn't has huge buffer to keep all of messages.













We can try to output it to file and check it later.
Click Target->Debug Message Options->Check Send to file and specify file path