Tag Archives: class

I got my Java class, I got my Matlab HFT system with potential listener and callback, let’s merge them

I got my Java class, I got my Matlab HFT system with potential listener and callback, let’s merge them

So close…I can taste it now. I just want to demo it once complete!!

Find out what I plan to do with this by joining my FREE newsletter 

 

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

how to export Java class into JAR then convert EXE using IKVM for Dot Net C# Apps

how to export Java class into JAR then convert EXE using IKVM for Dot Net C# Apps

Learn more what I do with this here.

www.sourceforge.net/projects/ikvm/files/ikvm/

www.ikvm.net/index.html

 

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

Any suggestions for an intro to STATA class for quant development?

Any suggestions for an intro to STATA class for quant development?

 

Having no experience with STATA, I would start with the vendor website and see where that takes me. The product’s main page at http://data.princeton.edu/stata/ has everything that someone like me needs to get started, and so with this material I would be comfortable downloading the demo and experimenting with it.

I’ll be taking my BI practicum this Spring (topic: Data Visualization), and so thanks for tipping me off to (yet another) viz app that I can add to my toolbox!

 

I’ve used the stata book to get started, it’s not complete/thorough, but it will be perfect to get you going, and from there it should be pretty easy for you to dig deeper.

https://www.google.com/search?tbm=shop&hl=en&q=Statistics+With+Stata&oq=Statistics+With+Stata&aq=f&aqi=g2&aql=&gs_sm=3&gs_upl=22664l22664l0l23879l1l1l0l0l0l0l59l59l1l1l0

 

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

Small C++ class to transform any static control into a hyperlink control for Windows Download C++ hyperlink control for W

Small C++ class to transform any static control into a hyperlink control for Windows

Contents

The demo program

The demo program is just a simple MFC AppWizard generated application where the About dialog class has been changed to demonstrate how to use myCHyperLink class.

First, in the Dialog editor, add some static controls. Make sure to select the TABSTOP style and to give the control a unique ID. Then I derive a new class from CHyperLink to override OnSelect() and OnDeselect(). I am sending the URL text to the status bar by calling the Frame window SetMessageText()

class CDemoLink : public CHyperLink
{
protected:
    virtual void OnSelect(void)
    { ((CFrameWnd *)AfxGetMainWnd())->
               SetMessageText(m_strURL); }
    virtual void OnDeselect(void)
    { ((CFrameWnd *)AfxGetMainWnd())->
               SetMessageText(AFX_IDS_IDLEMESSAGE); }
};

Then add member variables of type CDemoLink to the dialog class and do the following in the WM_INITDIALOG handler:

void CAboutDlg::setURL(CHyperLink &ctr, int id)
{
   TCHAR buffer[URLMAXLENGTH];
   int nLen = ::LoadString(AfxGetResourceHandle(),
                           id, buffer, URLMAXLENGTH);
   if( !nLen )
   {
     lstrcpy( buffer, __TEXT(""));
   }
    ctr.ConvertStaticToHyperlink(GetSafeHwnd(),id,buffer);
}

BOOL CAboutDlg::OnInitDialog()
{
   CAboutDlg::OnInitDialog();

   // TODO: Add extra initialization here
   setURL(m_DemoLink,IDC_HOMEPAGE);
   setURL(m_DemoMail,IDC_EMAIL);

   return TRUE;  // return TRUE unless you
                 // set the focus to a control
                 // EXCEPTION: OCX Property
                 // Pages should return FALSE
}

The demo program also demonstrates how to use CHyperLink with the tooltip control. To do so, I had to derive a new class from MFC CToolTipCtrl class. I am going to first show you the code using the new derived class and then explain the purpose of the new class:

BOOL CAboutDlgWithToolTipURL::OnInitDialog()
{
   CAboutDlg::OnInitDialog();

   // TODO: Add extra initialization here
   m_ctlTT.Create(this);
   setURL(m_DemoLink,IDC_HOMEPAGE);
   setURL(m_DemoMail,IDC_EMAIL);

   /*
    * It is OK to add a Window tool
    * to the tool tip control with
    * the CHyperLink dynamically
    * allocated URL string because
    * the windows are destroyed with
    * WM_DESTROY before the CHyperLink
    * destructor call where the URL string is freed.
    */
   m_ctlTT.AddWindowTool(GetDlgItem(IDC_HOMEPAGE)->GetSafeHwnd(),
                       (LPTSTR)m_DemoLink.getURL());
   m_ctlTT.AddWindowTool(GetDlgItem(IDC_EMAIL)->GetSafeHwnd(),
                       (LPTSTR)m_DemoMail.getURL());

   return TRUE;  // return TRUE unless you set the focus to a control
                 // EXCEPTION: OCX Property Pages should return FALSE
}

Note that m_ctlTT type is CSubclassToolTipCtrl and that AddWindowTool() is a new function. The reason why MFC CToolTipCtrl was not used directly is that the ToolTip control needs to receive the tool’s messages in order to work. The low level ToolTip API provides different ways to achieve this but the MFC class only exposes one way of doing it. It is to relay the tool messages through CToolTipCtrl::RelayEvent(). It is relatively easy to use but it was inconvenient for CHyperLink as one of the design goals is to not force users to use MFC. The low level API could have been used with the messageTTM_RELAYEVENT but still it would incur unnecessary overhead to all the hyperlinks not using tooltips. I found the solution in the book Programming Windows With MFC. It uses the ToolTip control feature that allows it to subclass the tools windows.

/*
 * class CSubclassToolTipCtrl
 */
class CSubclassToolTipCtrl : public CToolTipCtrl
{
// Operations
public:
/******************************************************************************
 *
 * Name      : AddWindowTool
 *
 * Purpose   : Add a window tool by using the Tooltip subclass feature
 *
 * Parameters:
 *     hWin    (HWND)    Tool window
 *     pszText (LPTSTR)  Tip text (can also be a string resource ID).
 *
 * Return value : Returns TRUE if successful, or FALSE otherwise.
 *
 ****************************************************************************/
   BOOL AddWindowTool( HWND hWin, LPTSTR pszText );

/******************************************************************************
 *
 * Name      : AddRectTool
 *
 * Purpose   : Add a rect tool by using the Tooltip subclass feature
 *
 * Parameters:
 *     hWin    (HWND)    Tool window parent
 *     pszText (LPTSTR)  Tip text (can also be a string resource ID).
 *     lpRect  (LPCRECT) Tool rect
 *     nIDTool (UINT)    User defined Tool ID
 *
 * Return value : Returns TRUE if successful, or FALSE otherwise.
 *
 ****************************************************************************/
   BOOL AddRectTool( HWND hWin, LPTSTR pszText, LPCRECT lpRect, UINT nIDTool );

// Implementation
   void FillInToolInfo(TOOLINFO& ti, HWND hWnd, UINT nIDTool) const;
};
/*
 * Function CSubclassToolTipCtrl::AddWindowTool
 */
BOOL CSubclassToolTipCtrl::AddWindowTool( HWND hWin, LPTSTR pszText )
{
    TOOLINFO ti;
    FillInToolInfo(ti,hWin,0);
    ti.uFlags  |= TTF_SUBCLASS;
    ti.hinst    = AfxGetInstanceHandle();
    ti.lpszText = pszText;

    return (BOOL)SendMessage(TTM_ADDTOOL,0,(LPARAM)&ti);
}

/*
 * Function CSubclassToolTipCtrl::AddRectTool
 */
BOOL CSubclassToolTipCtrl::AddRectTool( HWND hWin, LPTSTR pszText,
                                        LPCRECT lpRect, UINT nIDTool )
{
    TOOLINFO ti;
    FillInToolInfo(ti,hWin,nIDTool);
    ti.uFlags  |= TTF_SUBCLASS;
    ti.hinst    = AfxGetInstanceHandle();
    ti.lpszText = pszText;
    ::CopyRect(&ti.rect,lpRect);

    return (BOOL)SendMessage(TTM_ADDTOOL,0,(LPARAM)&ti);
}

// Implementation

/*
 * Function CSubclassToolTipCtrl::FillInToolInfo
 */
void CSubclassToolTipCtrl::FillInToolInfo(TOOLINFO& ti, HWND hWnd, UINT nIDTool) const
{
    ::ZeroMemory(&ti, sizeof(TOOLINFO));
    ti.cbSize   = sizeof(TOOLINFO);
    if (nIDTool == 0)
    {
        ti.hwnd = ::GetParent(hWnd);
        ti.uFlags = TTF_IDISHWND;
        ti.uId = (UINT)hWnd;
    }
    else
    {
        ti.hwnd = hWnd;
        ti.uFlags = 0;
        ti.uId = nIDTool;
    }
}

I added a minor improvement to the solution found in the Programming Windows With MFC book. I initialized the TOOLINFO structure to zero prior to using it. Initializing structures prior to using them is a good programming practice. If the structure definition is updated with the addition of new fields, without initializing the structure, you would have some fields unitialized with random values and this can lead to nasty hard to find bugs. By resetting the structure, you shield your code against that.

Conclusion

That is it! I hope you enjoyed this C++ Windows programming tutorial on my hyperlink control C++ class and I hope that the source code will be helpful to you in your projects. In the next section, you will find the books that I have consulted to build this C++ Windows programming tutorial. Those books are great and filled with Windows programming gems that you should know. It is strongly recommended that you get yourself a copy of these books especially since from time to time, you can find these books at a bargain price. Take the time to check the prices. This is maybe your lucky day today!

Bibliography

Revision history

  • 12-03-2005
    • Added alternatives that are WTL and comctlr32.dll version 6.
    • Added changes to make CHyperLink compatible with UNICODE.
    • Added an example on how to use CHyperLink with ToolTips.
  • 11-17-2005:
    • Original article.

Page 1 2

Source: Thanks to Olivier Langlois

http://www.olivierlanglois.net/cpp_hyperlink_control2.htm

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

Small C++ class to transform any static control into a hyperlink control for Windows

Small C++ class to transform any static control into a hyperlink control for Windows

Contents

Introduction

This small and efficient C++ class is compatible with Win32 API programs and MFC programs as well.

C++ hyperlink demo sample program preview

Prior to developing my own hyperlink control C++ implementation for Windows, I have been looking around on the net in search of already written hyperlink controls for Windows in C/C++. There is a lot around but none were good enough for my standards. Some are bloated with features that I do not need and want. Some are plagued with bugs. Some are simple but lack one or two features I wished to see. The best that I have found is the excellent code written by Neal Stublen. I have been inspired by the elegance that his solution offers which can be used with Win32 API programs and MFC programs as well. Unfortunately, it has a bug and misses three features I was looking for. For this reason, I decided to write my own hyperlink control C++ code based on Neal Stublen’s work. In this C++ Windows programming tutorial, I will mention hyperlink options that Microsoft offers, describe the features Neal did put in his code, the features that I added, the bug fix I propose to Neal’s code and some other improvements that I have added.

Microsoft options

After the initial release of this article, some readers pointed out that WTL is offering exactly what I was looking for. In retrospect, I still think that it was the right decision to write my own class. One benefit of WTL over my solution is that it is more complete and has more features. However, since WTL user’s goal is to create small and fast executable files, they would benefit from using my class over the WTL one *if* my class provides all the features they need. In some aspects, WTL implementation has some drawbacks that my class doesn’t have:

  1. It has much more code.
  2. It uses WTL messages dispatching scheme which might be faster and slimmer than the MFC one but it is not as efficient as a pure Window procedure that this class is using.
  3. It has tooltips but I didn’t see how you could customize it for sending the URL text in the status bar as easily as it is with my class.
  4. You must have WTL in your project to use their hyperlink class. Mine is working with a Win32 API C project, an MFC one and even with WTL.

I have never used WTL to write a program but if I would, I would use the class described in this article. Microsoft proposes another option for people looking for hyperlink controls. It added such a control to comctrl32.dll version 6 but this version is available only on XP and Microsoft states. An application that has to run on other Windows operating systems cannot rely on the new common control library being present and should not use the features that are available only in ComCtl32.dll, version 6. It might pose a problem if you don’t want to restrict your potential user base strictly to this target.

Features

First, the changes needed to a static control to become a hyperlink control that Neal addressed are:

  1. Clicking the text needs to open a browser window to the location specified by the text.
  2. The cursor needs to change from the standard arrow cursor to a pointing index finger when it moves over the control.
  3. The text in the control needs to be underlined when the cursor moves over the control.
  4. A hyperlink control needs to display text in a different color – black just won’t do.

The features that I added are:

  1. A hyperlink control once visited needs to change color.
  2. The hyperlink control should be accessible with keyboard.
  3. Install some kind of hooks to allow the programmer to perform some actions when the control has the focus or when the cursor is hovering over the hyperlink control.

Before describing how the new features have been implemented, let me introduce you to the major architectural change that the code underwent. I placed the code into a class. Here is the class definition:

class CHyperLink
{
public:
    CHyperLink(void);
    virtual ~CHyperLink(void);

    BOOL ConvertStaticToHyperlink(HWND hwndCtl, LPCTSTR strURL);
    BOOL ConvertStaticToHyperlink(HWND hwndParent, UINT uiCtlId, LPCTSTR strURL);

    BOOL setURL( LPCTSTR strURL);
    LPCTSTR getURL(void) const { return m_strURL; }

protected:
    /*
     * Override if you want to perform some action when the link has the focus
     * or when the cursor is over the link such as displaying the URL somewhere.
     */
    virtual void OnSelect(void)   {}
    virtual void OnDeselect(void) {}

    LPTSTR   m_strURL;                              // hyperlink URL

private:
    static COLORREF g_crLinkColor, g_crVisitedColor;// Hyperlink colors
    static HCURSOR  g_hLinkCursor;                  // Cursor for hyperlink
    static HFONT    g_UnderlineFont;                // Font for underline display
    static int      g_counter;                      // Global resources user counter
    BOOL     m_bOverControl;                        // cursor over control?
    BOOL     m_bVisited;                            // Has it been visited?
    HFONT    m_StdFont;                             // Standard font
    WNDPROC  m_pfnOrigCtlProc;

    void createUnderlineFont(void);
    static void createLinkCursor(void);
    void createGlobalResources(void)
    {
        createUnderlineFont();
        createLinkCursor();
    }
    static void destroyGlobalResources(void)
    {
        /*
         * No need to call DestroyCursor() for cursors acquired through
         * LoadCursor().
         */
        g_hLinkCursor   = NULL;
        DeleteObject(g_UnderlineFont);
        g_UnderlineFont = NULL;
    }

    void Navigate(void);

    static void DrawFocusRect(HWND hwnd);
    static LRESULT CALLBACK _HyperlinkParentProc(HWND hwnd, UINT message,
                                                 WPARAM wParam, LPARAM lParam);
    static LRESULT CALLBACK _HyperlinkProc(HWND hwnd, UINT message,
                                           WPARAM wParam, LPARAM lParam);
};

The reasons that motivated this change are:

  1. Allow the user to derive a new class to customize the control behavior when a hyperlink is selected or deselected.
  2. Reduce the number of GetProp() calls in the window procedures by fetching the pointer on an object containing all the needed variables with oneGetProp() call.

#1 can be achieved by overriding the OnSelect() and OnDeselect() functions. This will be demonstrated later when I will be presenting the demo application.

This brought me to introduce another improvement. Have you noticed that some members are static? This allows multiple hyperlink controls to share the same resources. Shared resources include the hand cursor and the underlined font. This block has been added to the ConvertStaticToHyperlink()function:

if( g_counter++ == 0 )
{
    createGlobalResources();
}

And this code has been added to the WM_DESTROY message handler in the control window procedure:

if( --CHyperLink::g_counter <= 0 )
{
    destroyGlobalResources();
}

To the first ConvertStaticToHyperlink() call, global resources will be allocated and when the last hyperlink control is destroyed, it will destroy the shared resources as well. The advantages to this approach are that it will make memory usage more efficient and the hand cursor will be loaded just once. Here is the new WM_SETCURSOR code:

case WM_SETCURSOR:
{
    SetCursor(CHyperLink::g_hLinkCursor);
    return TRUE;
}

Now let’s get back to the new features, the simplest one is to change the color of the hyperlink control when it is visited. A very simple change to theWM_CTLCOLORSTATIC handler is needed. It just checks a boolean variable state that is set to true when the link is visited. Here is the pertinent code:

inline void CHyperLink::Navigate(void)
{
    SHELLEXECUTEINFO sei;
    ::ZeroMemory(&sei,sizeof(SHELLEXECUTEINFO));
    sei.cbSize = sizeof( SHELLEXECUTEINFO );        // Set Size
    sei.lpVerb = TEXT( "open" );                    // Set Verb
    sei.lpFile = m_strURL;                          // Set Target To Open
    sei.nShow = SW_SHOWNORMAL;                      // Show Normal

    LASTERRORDISPLAYR(ShellExecuteEx(&sei));
    m_bVisited = TRUE;
}
case WM_CTLCOLORSTATIC:
{
    HDC hdc = (HDC) wParam;
    HWND hwndCtl = (HWND) lParam;
    CHyperLink *pHyperLink = (CHyperLink *)GetProp(hwndCtl,
                                                   PROP_OBJECT_PTR);

    if(pHyperLink)
    {
        LRESULT lr = CallWindowProc(pfnOrigProc, hwnd, message,
                                    wParam, lParam);
        if (!pHyperLink->m_bVisited)
        {
            // This is the most common case for static branch prediction
            // optimization
            SetTextColor(hdc, CHyperLink::g_crLinkColor);
        }
        else
        {
            SetTextColor(hdc, CHyperLink::g_crVisitedColor);
        }
        return lr;
    }
    break;
}

Now to support keyboard, the following messages must be handled:

  1. WM_KEYUP
  2. WM_SETFOCUS
  3. WM_KILLFOCUS

The hyperlink control will respond to a space key press. WM_SETFOCUS and WM_KILLFOCUS draw the focus rectangle. It is drawn against the parent window. The reason for doing so is because first, otherwise, the focus rectangle will be too close to the hyperlink text, and secondly, I played with making the hyperlink controls transparent by returning a hollow brush from the WM_CTLCOLOR_STATIC handler. When the parent was erasing the control background, it was messing with the focus rectangle. By drawing the focus rectangle against the parent window, it fixes these small problems.

Another point of interest is why choosing WM_KEYUP and WM_LBUTTONUP because at first, and in many hyperlink control implementations that I have seen, I used WM_LBUTTONDOWN? Well, the answer is simple. It is to be consistent with how IE hyperlinks and classic Windows controls behave. I am sure most of you have never paid attention, as I did, to this little detail so go try it out in IE, click on a hyperlink control and keep the button pressed. The link won’t be triggered until you release the mouse button. The same thing is true with dialog push buttons, if you focus on a pushbutton and press on space, the button won’t activate any action as long as the space is pressed. Now, during my research to figure out how to support the keyboard, I read the excellent Paul DiLascia article at MSDN. He is using a combination of WM_GETDLGCODE/WM_CHAR messages handlers. In WM_GETDLGCODE, he returns DLGC_WANTCHARS to signify to the dialog box manager that the control wants to receive WM_CHAR messages. I don’t agree with this approach and here are the reasons:

  1. Simplicity: one handler (WM_KEYUP) versus two (WM_GETDLGCODE/WM_CHAR).
  2. Correctness: you want the hyperlink control to be activated when you release the spacebar as other classic controls do and the problem with WM_CHARis that the control will receive multiple messages if the key remains pressed.
  3. Finally to back up these claims, Petzold uses WM_KEYUP in his PW book when he subclasses controls.

Anyway, here is the relevant code:

inline void CHyperLink::DrawFocusRect(HWND hwnd)
{
    HWND hwndParent = ::GetParent(hwnd);

    if( hwndParent )
    {
        // calculate where to draw focus rectangle, in screen coords
        RECT rc;
        GetWindowRect(hwnd, &rc);

        INFLATERECT(&rc,1,1);                    // add one pixel all around
                                                 // convert to parent window client coords
        ::ScreenToClient(hwndParent, (LPPOINT)&rc);
        ::ScreenToClient(hwndParent, ((LPPOINT)&rc)+1);
        HDC dcParent = GetDC(hwndParent);        // parent window's DC
        ::DrawFocusRect(dcParent, &rc);          // draw it!
        ReleaseDC(hwndParent,dcParent);
    }
}
case WM_KEYUP:
{
    if( wParam != VK_SPACE )
    {
        break;
    }
}
                   // Fall through
case WM_LBUTTONUP:
{
    pHyperLink->Navigate();
    return 0;
}
case WM_SETFOCUS:  // Fall through
case WM_KILLFOCUS:
{
    if( message == WM_SETFOCUS )
    {
        pHyperLink->OnSelect();
    }
    else           // WM_KILLFOCUS
    {
        pHyperLink->OnDeselect();
    }
    CHyperLink::DrawFocusRect(hwnd);
    return 0;
}

Have you noticed that both Navigate() and DrawFocusRect() are inline functions? Both functions are called from the hyperlink control window procedure. They are inline to optimize the window procedure by not calling unnecessary functions from it while keeping its readability to the maximum.

Now, let’s attack the bug fix. The control can lose the mouse capture in others ways than calling ReleaseCapture(). For instance, click on a link and keep the cursor over the link. When the web browser window pops up, it will break the mouse capture. Because the capture is broken, the control finds itself in an inconsistent state. The trick to fix that bug is to not assume that the control will keep the mouse capture until it releases it and to handle theWM_CAPTURECHANGED message. Here is the code:

case WM_MOUSEMOVE:
{
    if ( pHyperLink->m_bOverControl )
    {
        // This is the most common case for static branch prediction
        // optimization
        RECT rect;
        GetClientRect(hwnd,&rect);

        POINT pt = { LOWORD(lParam), HIWORD(lParam) };

        if (!PTINRECT(&rect,pt))
        {
            ReleaseCapture();
        }
    }
    else
    {
        pHyperLink->m_bOverControl = TRUE;
        SendMessage(hwnd, WM_SETFONT,
                    (WPARAM)CHyperLink::g_UnderlineFont, FALSE);
        InvalidateRect(hwnd, NULL, FALSE);
        pHyperLink->OnSelect();
        SetCapture(hwnd);
    }
    return 0;
}

case WM_CAPTURECHANGED:
{
    pHyperLink->m_bOverControl = FALSE;
    pHyperLink->OnDeselect();
    SendMessage(hwnd, WM_SETFONT,
                (WPARAM)pHyperLink->m_StdFont, FALSE);
    InvalidateRect(hwnd, NULL, FALSE);
    return 0;
}

To complete the window procedures topic, there is an important detail that needs to be highlighted. The processed messages are not passed back to the static control procedure because the static control does not need them. It does work fine but be aware that it could cause some problems if the static control is already subclassed. Consider the example where the static control would be already subclassed with the Tooltip control that needs to process mouse messages. In that situation, the Tooltip control would not work as expected. In the demo program section, I will show how you can use the Tooltip control with CHyperLink.

And finally, to speed the GetProp() calls, an ATOM is used instead of strings. A simple global object is used to store the Atom to be sure that it will be initialized prior to any use of the CHyperLink and that it will be present for the whole lifetime of the program. A GUID is appended to a meaningful string to ensure its uniqueness across the system:

/*
 * typedefs
 */
class CGlobalAtom
{
public:
    CGlobalAtom(void)
    { atom = GlobalAddAtom(TEXT("_Hyperlink_Object_Pointer_")
             TEXT("\\{AFEED740-CC6D-47c5-831D-9848FD916EEF}")); }
    ~CGlobalAtom(void)
    { DeleteAtom(atom); }

    ATOM atom;
};

/*
 * Local variables
 */
static CGlobalAtom ga;

#define PROP_OBJECT_PTR         MAKEINTATOM(ga.atom)
#define PROP_ORIGINAL_PROC      MAKEINTATOM(ga.atom)

Page 1 2

Source: Thanks to Olivier Langlois

http://www.olivierlanglois.net/hyperlinkdemo.htm

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

Real case example of using the undocumented MFC class CFixedAlloc

Real case example of using the undocumented MFC class CFixedAlloc

Contents

Introduction

This tutorial is a follow up of my tutorial ‘Enhance your dynamic memory allocation in C++ with an undocumented MFC class (CFixedAlloc)‘. I am proposing to apply CFixedAlloc class to the grid control from Chris Maunder. The changes have been made on version 2.26 of the control so you should check if a new version has been released hopefully with the optimization discussed in this tutorial or at least a variant of it.

This tutorial will first present a brief presentation of the aspects of Chris Maunder grid control classes that are important for this tutorial. Then I will present the methods that I used to measure the improvement resulting of applying CFixedAlloc. This will then be followed by a presentation of the code change required to apply CFixedAlloc and finally, I will present the optimization result from these changes.

Presentation of the CGrid control

This is a prime candidate for applying a fixed allocator optimization. Please consult my previous tutorial on the topic for a detailed coverage of the positive properties of such an allocator or the grid control page for an extended coverage on its architecture and its usage. What is important to know for this tutorial is that the grid control consist of an array of GRID_ROWGRID_ROW is also an array that contains cell objects. The cell class can be specialized with derived classes (useful cell specializations are provided with the control) and you can indicate to the control which type of cells that you want it to populate the grid by providing it a meta-class of the desired cell class with the help of the MFC RUNTIME_CLASSes.

Rows and cells are all dynamically allocated from the heap. It means that for a 64000×8 grid, the control is going to perform 64000 new for GRID_ROW and 64000×8 new for creating the cells.

Methods used for performance measurements

For measuring the time it takes to resize the grid, I have modified the dialog box event handling functions that control the size of the grid in the file GridCtrlDemoDlg.cpp:

void CGridCtrlDemoDlg::OnUpdateEditCols()
{
...
DWORD start = GetTickCount();
TRY {
    m_Grid.SetColumnCount(m_nCols);
}
CATCH (CMemoryException, e)
{
    e->ReportError();
    return;
}
END_CATCH
DWORD end = GetTickCount();
Trace(_T("Time spent in SetColumnCount(): %d\n"),end-start);
...
}
void CGridCtrlDemoDlg::OnUpdateEditRows()
{
...
DWORD start = GetTickCount();
TRY {
    m_Grid.SetRowCount(m_nRows);
}
CATCH (CMemoryException, e)
{
    e->ReportError();
    return;
}
END_CATCH
DWORD end = GetTickCount();
Trace(_T("Time spent in SetRowCount(): %d\n"),end-start);
...
}

For measuring the control memory usage I have simply used the task manager ‘Processes’ tab. Spot the ‘GridCtrlDemo.exe’ entry in the process list prior resizing the grid and then take note of the new memory usage value after the resizing.

CFixedAlloc application

Before applying the changes presented in this section, I suggest that you take measurements before so that you can compare the difference.

CGridCell class and its derived children classes and the GRID_ROW class are prime candidates CFixedAlloc optimization because of their frequent and numerous allocation/deallocation. Here are the neccessary changes for CGridCell:

GridCell.h:

#include "GridCellBase.h"
#include "fixalloc.h"
#define POOL_SIZE 1024

class CGridCell : public CGridCellBase
{
    friend class CGridCtrl;
    DECLARE_DYNCREATE(CGridCell)
    DECLARE_FIXED_ALLOC_NOSYNC(CGridCell)
    ...
};

class CGridDefaultCell : public CGridCell
{
    DECLARE_DYNCREATE(CGridDefaultCell)
    DECLARE_FIXED_ALLOC_NOSYNC(CGridDefaultCell)
    ...
};
GridCell.cpp:

IMPLEMENT_FIXED_ALLOC_NOSYNC(CGridCell,POOL_SIZE)
IMPLEMENT_FIXED_ALLOC_NOSYNC(CGridDefaultCell,POOL_SIZE)

First, note that you will have to update the include directories search path as described in my previous tutorial. Also, it is very important that you use the macros DECLARE_FIXED_ALLOC_NOSYNC() and IMPLEMENT_FIXED_ALLOC_NOSYNC() for all the classes deriving from CGridCell. Those are CGridCellCheck,CGridCellComboCGridCellDateTimeCGridCellNumeric and CGridURLCell. The reason for this is that the macro allocates POOL_SIZE blocks ofsizeof(classname used in the macros). If you do not overload the new and delete operators for a derived class, it will use the operators of the base class and it will corrupt the memory because the derived classes size is usually bigger than their base class.

For using the CFixedAlloc in GRID_ROW, you must modify the GridCtrl module:

GridCtrl.h:

class CFixedAllocGridRow : public CTypedPtrArray<CObArray, CGridCellBase*>
{
    DECLARE_FIXED_ALLOC_NOSYNC(CFixedAllocGridRow);
};

typedef CFixedAllocGridRow GRID_ROW;
GridCtrl.cpp:

IMPLEMENT_FIXED_ALLOC_NOSYNC(GRID_ROW,POOL_SIZE)

I have chosen the value 1024 for POOL_SIZE but feel free to experiment with that value.

Results

Here is a table comparing the results obtained with and without the CFixedAlloc modification for the SetRowCount() and SetColumnCount() operations. As you can see, the difference is very convincing.

SetRowCount(64000) SetColumnCount(6400)
t size t size
Without changes 359 35,428 KB 860 75,516 KB
With changes 157 30,168 KB 344 63,480 KB

Conclusion

Everything looks too good to be true. There is one disadvantage of incorporating the proposed optimization. While it is true that the grid resizing will be blazingly fast and use memory more efficiently, once the fixed allocator has allocated a pool of memory, it will never be released until the end of the program execution. If you are allocating memory for a 64000×16 grid once then you will use that memory even if you shrink back the grid to a 32×32 grid for the rest of the execution of the program. For some programs, it might be unacceptable. That being said, it is certainly possible to come up with a home-brew fixed size allocator with a little bit more of intelligence. Not too much to lose the benefits of CFixedAlloc but just enough to address the memory usage shrinking. The Loki framework from Andrei Alexandrescu and described in his book Modern C++ Design contains such allocator.

Before finishing, there are few points that are discussed in my previous tutorial that are worth mentionning again:

  • In the DEBUG build, the CFixedAlloc is not used by the macros (Probably to ease heap corruption tracking).
  • I have used VC++2003.NET for my testing. CFixedAlloc has been deprecated in VC++2005. Of course, since the class was not documented in the first place, there is nowhere in the product documentation something explaining why. Someone has reported to me that he did not witnesses a significant improvement from the optimization when compiled with VC++2005. One can suppose then that the reason for the deprecation is that Microsoft has significantly improved their Heap management functions (malloc,free) in MSCRT that made the usage of CFixedAlloc unnecessary.

Also, my blog is probably the best medium if you would like to provide feedback to this tutorial, you can do so here.

Source: Thanks to Olivier Langlois

http://www.olivierlanglois.net/Applying_CFixedAlloc.html

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

C++ Job interview question: Inheritance and object orientation source code example to create class object on heap vs stack

C++ Job interview question: Inheritance and object orientation source code example to create class object on heap vs stack

This may be a stupid example but does show the difference between stack and heap object creation using class object:

#include
using namespace std;

class MyClass {
public:
MyClass(int x) {}
MyClass() {}
};

int main() {

MyClass *myclass = new MyClass[10]; // creates class object on heap
int i;

int j[] = {1,2,3,4,5,6,7,8,9,10};

MyClass mc2[10] = {1,2,3,4,5,6,7,8,9,10}; //creates class object on stack

MyClass* mc[10];
for (int i=0; i < 10; i++) mc[i] = new MyClass(i); //it will call user-defined constructor here. return 0; }

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

Simplest C++ Multithreading with Thread classes, mutex, set, wait, lock, unlock defined

Simplest C++ Multithreading with Thread classes, mutex, set, wait, lock, unlock defined

I have searched high and low for the best and simplest multi threading explained within C++. As you know, I have already posted some articles on Linux processes and how deadlocks work. Theoretically, we are trying to prevent the Dead Diamond of Death syndrome. Both Java and C++ have potential solutions but Java has all these features built in natively. C++ needs a new set of classes defined which includes a specialized Thread class.
Using a set of mutex method, we can lock certain processes from subsequent messing up the state of a current thread. An example of mutex locking a storage block of code, look at:
int g_iStorage = 0;
CMutexClass MyMutex;

void StoreValue( int *pInt )
{
MyMutex.Lock(); //the gate keeper. only one thread
//allowed in at a time

g_iStorage = *pInt; //protected data, critical code section

MyMutex.Unlock(); //unblocks, allowing another thread to
//access g_iStorage

}

There are some other methods which work the same way Java’s Threading class and methods. These methods are explained below:
void Set() Sets an event state to signaled, notifying the blocked thread.
BOOL Wait() Places the calling thread in a blocked state until the event state is set to signaled. Returns TRUE on success, FALSE on failure.
void Reset() Resets a signaled event to unsignaled.
event object being used by a receiving thread::
CEventClass event;
.
.
//thread code

.
.
while(bContinueRunning)
{

event.Wait(); // wait for an event to occur

// perform some task

.
.
event.Reset(); // reset the event to un-signaled

}
.
.
Example of an event object used by one thread signaling another:
EventClass event;
.
.
// change some data

.
.
event.Set(); // notify thread that an event has occured,

// set event to signaled

There is more detailed info you could go into. I do believe if you know enough of above, you should be able to show some rudimentary knowledge in multithreading within C++. I would recommend following through with the link below as it is fairly close representation of how Java works.
To download and better understand how all this Thread classes work, go to http://www.codeproject.com/KB/threads/threadobject.aspx
It also contains a very good end to end set of source files to generate your own Thread classes which include the mutexes explained.

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!