Saturday, 13 December 2014

Matrix Tracing


A very clean single function to solve HackerRank's contest that has been explained in V. Anton Spraul vedio.

Problem Statement
A word from the English dictionary is taken and arranged as a matrix. e.g. "MATHEMATICS"
MATHE 
ATHEM 
THEMA 
HEMAT 
EMATI 
MATIC 
ATICS
There are many ways to trace this matrix in a way that helps you construct this word. You start tracing the matrix from the top-left position and at each iteration, you either move RIGHT or DOWN, and ultimately reach the bottom-right of the matrix. It is assured that any such tracing generates the same word. How many such tracings can be possible for a given word of length m+n-1 written as a matrix of size m * n? 

Solution:
int trace(int row, int col)
{
static int count = 0;

if (row == 1 && col == 1)
count++;
else
{
if (row <= 0 || col <= 0)
return -1;
trace(row, col - 1);
trace(row - 1, col);
}
return count;
}

Input:
  trace( 4 , 3 );

Output:
  10

Explain:
  Recursive upward traversal as shown in the next figure.



Tuesday, 17 September 2013

Web 3.0 Concepts


Understanding the New Web Era "Web 3.0"
http://readwrite.com/2009/05/13/understanding_the_new_web_era_web_30_linked_data_s#awesm=~ohCmbY4oUQFEdI

Data Sets:
They are distributed all over the world and containing all kinds of information. They Contain knowledge about a particular domain, like books, music, encyclopedic data, companies, you name it.
Also, they could re-use existing ontologies, like OpenCalai, Freebase, DBepia.


Semantic Web:
It aims to invisibly annotate web pages with a set of meta-attributes and categories to enable machines to interpret text and put it in some kind of context.
Approaches, like microformats, simplify the markup process and thus help bootstrap this problem.
As of today, Facebook has marked up all events with the hCalendar microformat including marking up their venues with hCard as well.

Liked Data:
It is the interconnection between independent data-sets, so, machine could traverse this independent web of noiseless, structured information to gather semantic knowledge of arbitrary entities and domains.

Web of Data
It is about the massive, freely accessible knowledge base, that is resulted from linked-data concept, and is forming the foundation of a new generation of applications and services.

LOD: Linking Open Data
It is a project that introduced standardiztion to link between data sets.


Real world Applications: 
* Google new features of WEB3.0:
 - Search Options
 - Rich Snippets
 - Google Squared

* DBpedia: 
 - It is a crowd-sourced community effort to extract structured information from Wikipedia and make this information available on the Web.
 - http://dbpedia.org/About

* openCalai:
 - Using a mix of natural language processing, AI techniques, and a massive databases, Reuters' solution extracts important bits of information from raw HTML pages. People, Companies, Places, and Events are really at the heart of many business articles, so being able to instantly identify them in the text is a big deal. From better search to better cross-linking and more intelligent browsing, the Calais API is an invitation to tap into one of the most powerful and pragmatic semantic platforms that exists and works today.
 - It enables publishers to connect to the Linked Data web standard that Sir Tim-Berners Lee and others in the Semantic Web community have been promoting over the past few years.
 - http://readwrite.com/2009/01/14/calais_4_linked_data#awesm=~ohGzx4dCP3hzXN
 - http://readwrite.com/2008/02/05/reuters_calais#feed=/tag/semantic-web&awesm=~ohHwSqmU1k9TJb




Thursday, 12 September 2013

Free Antivirus Software


Best Free Antivirus Software:

- avast!
- Microsoft Security Essentials
- Avira
- Malwarebytes
- AVG Anti-Virus
- Comodo
- ClamAV
- Trend Micro

Not free:

- Online Armor ++
- Sophos
- Panda
- Norton
- MacAffee
- KasperSky

Notes:

- AV_TEST: The Independent IT-Security Institute. It is an independent organization which evaluates and 

rates antivirus and security suite software.

- http://www.techsupportalert.com/best-free-anti-virus-software.htm
- The biggest win for Comodo Internet Security Complete 2013 isn't in features, but in support.
- Process Tamer:
Is a tiny (140k) and super efficient utility for Microsoft Windows XP/2K/NT/Vista/Win7 that runs in 

your system tray and constantly monitors the cpu usage of other processes. When it sees a process that is 

overloading your cpu, it reduces the priority of that process temporarily, until its cpu usage returns to a 

reasonable level.
- It is not a good idea to have more than one antivirus program running at the same time.
- If you’re even just a little bit cautious and knowledgeable about internet security, Microsoft Security 

Essentials should work just fine for you.
- Microsoft Active Protection Service is the online community that helps you choose how to respond to 

potential threats.
- Microsoft boost MSE:
* http://blogs.msdn.com/b/securitytipstalk/archive/2010/09/08/do-i-need-both-microsoft-security-

essentials-and-another-antivirus-software-program.aspx
* http://news.softpedia.com/news/Microsoft-Security-Essentials-Needs-to-Fly-Solo-155974.shtml

Monday, 18 March 2013

Cross Browser Support for inline-block Styling

Just I have a great thanks for the next two articles, they illuminate the way of bug free CSS across browsers.

Issac Schlueter
satzansatz.de



Sunday, 24 February 2013

How to set asp:CreateUserWizardas's CreateUserButton as default button of asp:Panel?



The Problem: Is to set CreateUserButton of <asp:CreateUserWizardas> as a DefaultButton of a <asp:Panel>. What to write in place of question marks of the next script? 

    <asp:Panel runat="server" ID="WizardPanel" DefaultButton="???????????????!!!!!!!!!!?">
<asp:CreateUserWizard ID="RegisterUser" runat="server" Width="449px" .......
.........................

<input type="submit" name="ctl00$ContentForm$RegisterUser$__CustomNav0$StepNextButtonButton" value="موافق" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$ContentForm$RegisterUser$__CustomNav0$StepNextButtonButton&quot;, &quot;&quot;, true, &quot;RegisterUser&quot;, &quot;&quot;, false, false))" id="ctl00_ContentForm_RegisterUser___CustomNav0_StepNextButtonButton" class="myButton" />

</asp:CreateUserWizard>
    </asp:Panel>

[*]--------------------------------------------------------------------------------------------------
The following are some approaches that don't succeed: ... but number 4 is succeeded.
[1]--------------------------------------------------------------------------------------------------
Panel1.DefaultButton = ((Button)RegisterUserStep1.CustomNavigationTemplateContainer.FindControl("StepNextButton")).ID;
Description: 
Try to set DefaultButton programatically, but FindControl() returns nothing.
[2]--------------------------------------------------------------------------------------------------
    LookForDefaultButton(this.RegisterUser.Controls);
    protected bool LookForDefaultButton(ControlCollection collection)
    {
        foreach (Control ctrl in collection)
        {
            if (ctrl.GetType() == typeof(Button) && (ctrl as Button).ID == "StepNextButton1")
            {
                this.WizardPanel.DefaultButton = ctrl.UniqueID;
                return true;
            }
            else
                if (LookForDefaultButton(ctrl.Controls))
                    return true;

        }
        return false;
    }
Description: 
Try to set DefaultButton programatically, but <asp:Panel> issued exception of IButtonControl required.
[3]--------------------------------------------------------------------------------------------------
    <asp:Button ID="RegisterPanel" runat="server" style="display:none;" 
    ValidationGroup="RegisterUser" 
    CausesValidation="true"
    OnClientClick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$ContentForm$RegisterUser$__CustomNav0$StepNextButtonButton&quot;, &quot;&quot;, true, &quot;RegisterUser&quot;, &quot;&quot;, false, false)); return;"
    />
Description: 
Try to Invok "WebForm_DoPostBackWithOptions" statment through a brooker button "RegisterUser", but causes a lot of problems with validation and postback.
[4]--------------------------------------------------------------------------------------------------
<div id="ctl00_ContentForm_WizardPanel" onkeypress="javascript:return WebForm_FireDefaultButton(event, 'ctl00_ContentForm_RegisterUser___CustomNav0_StepNextButtonButton')">
Description:
Use <div> instead of <asp:Panel> to do the same job "Invoking WebForm_FireDefaultButton() at client" without a brooker button. All validation and postback done without any problem.

Sunday, 1 July 2012

C++ GUI Libraries


MFC is a C++ framework provided by Microsoft with its famous IDE "Visual Studio", I wish to find another GUI framework, with new look and feel. I googled the internet and found some ...

First, that is a list of all toolkits available as a GUI library: http://www.atai.org/guitool/

Second, those are a recommended set of them ....


I didn't use any of them till now but I plan to do.

Friday, 20 January 2012

MFC "encountered an improper argument" message

Hi there,

The story:

My MFC application "Schedule" that I work in 2 years ago faced by a very strange bug, the application is built using VC++, VS2008 on vista platform and configured to target vista platform by assigning WINVER=0x0600, _WIN32_WINNT=0x0600, _WIN32_WINDOWS=0x0410.

It runs perfectly on whatever machine running WinXP/Vista, other O.S.s are not available to test on. An overseas customer claimed a bug when she tried to save documents, her machine was HP-dv6000 with WinXP installed. I tolled her to upgrade the machine up to WinXP-SP3, but she upgraded up to Windows7 and the bug still exist.

The Bug is such a message says "encountered an improper argument", it emerged when she tried to save/open a file.

I googled every where but nobody has solution or a resolution, even in 2009 Microsoft tolled somebody that this issue is solved in VS2010, others talk about resource conflictions according to windows upgrades.

After long time I decided to investigate, where I spent 12 hours of digging into MFC source code and files, and then discovered the problem.

It was the following statement that throws exception because of an invalided resource ID.

ENSURE(title.LoadString(nIDSTitle = bReplace ? AFX_IDS_SAVEFILE : AFX_IDS_SAVEFILECOPY));

"title" is a CString object that has to displayed in title bar of CFileDialog, it then be loaded first from a string resource AFX_IDS_SAVEFILE or AFX_IDS_SAVEFILECOPY which are not exist at the machine of the customer.

I successfully simulated the same bug on my own machine using the following lines of code.

CString temp;

ENSURE(temp.LoadString(0xF012));// 0xF012 is invalide

What is ENSURE()?

#define ENSURE(cond) ENSURE_THROW(cond, ::AfxThrowInvalidArgException() )

The following paragraph describes what is the macro ENSURE, I cut this paragraph from MSN and past it here.

The purpose of these macros is to improve the validation of parameters. The macros prevent further processing of incorrect parameters in your code. Unlike the ASSERT macros, the ENSURE macros throw an exception in addition to generating an assertion.

The macros behave in two ways, according to the project configuration. The macros call ASSERT and then throw an exception if the assertion fails. Thus, in Debug configurations (that is, where _DEBUG is defined) the macros produce an assertion and exception while in Release configurations, the macros produce only the exception (ASSERT does not evaluate the expression in Release configurations).

The macro ENSURE_ARG acts like the ENSURE macro.

To solve this bug I made two steps, First: I replaced CWinAPP::OnFileOpen using the following code:

//---------------------------------------------------------------------

void CScheduleApp::OnMyFileOpen()

{

//manual open using CFileDialog

CString strDocFileName = _T("");

CFileDialog *pDlg;

pDlg = new CFileDialog (TRUE,_T("yps"),strDocFileName,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,

_T("File (*.yps)|*.yps|All Files (*.*)|*.*||"),NULL);

//

m_strCurFolder = m_strCurFolder.IsEmpty() ? GetParentFolder():m_strCurFolder;

pDlg->m_ofn.lpstrInitialDir = m_strCurFolder.GetBuffer(MAX_PATH);

pDlg->m_ofn.lpstrTitle = _T("فتح");

if(pDlg->DoModal()==IDOK)

{

strDocFileName = pDlg->GetPathName();

//the next line is optained from the following mfc source file

//C:\Program Files\Microsoft Visual Studio 9.0\VC\atlmfc\src\mfc\docmgr.cpp

AfxGetApp()->OpenDocumentFile(strDocFileName);

}

m_strCurFolder.ReleaseBuffer();

delete pDlg;

//Keep track of obtained folder as default for next open operation

m_strCurFolder = strDocFileName.IsEmpty() ? m_strCurFolder:

(strDocFileName.IsEmpty() ? _T(""):strDocFileName.Left(strDocFileName.ReverseFind('\\')+1));

//AfxMessageBox(m_strCurFolder);

theApp.WriteString(_T("CurUserFolder"),m_strCurFolder);

}

//---------------------------------------------------------------------

Second: I override CDocumment::DoSave() funtion to prevent it from calling AfxGetApp()->DoPromptFileName that uses the buggy resource, here is the code:

//---------------------------------------------------------------------

BOOL CScheduleDoc::DoSave(LPCTSTR lpszPathName, BOOL bReplace)

{

CString newName = lpszPathName;

if (newName.IsEmpty())

{

CDocTemplate* pTemplate = GetDocTemplate();

ASSERT(pTemplate != NULL);

newName = m_strPathName;

if (bReplace && newName.IsEmpty())

{

newName = m_strTitle;

// check for dubious filename

int iBad = newName.FindOneOf(_T(":/\\"));

if (iBad != -1)

newName.ReleaseBuffer(iBad);

// append the default suffix if there is one

CString strExt;

if (pTemplate->GetDocString(strExt, CDocTemplate::filterExt) &&

!strExt.IsEmpty())

{

ASSERT(strExt[0] == '.');

int iStart = 0;

newName += strExt.Tokenize(_T(";"), iStart);

}

}

//Replace the bug lines with a new technique

//if (!AfxGetApp()->DoPromptFileName(newName,

// bReplace ? AFX_IDS_SAVEFILE : AFX_IDS_SAVEFILECOPY,

// OFN_HIDEREADONLY | OFN_PATHMUSTEXIST, FALSE, pTemplate))

// return FALSE; // don't even attempt to save

if(!MyDoPromptFileName(newName,bReplace))

return false;

}

CWaitCursor wait;

if (!OnSaveDocument(newName))

{

if (lpszPathName == NULL)

{

// be sure to delete the file

TRY

{

CFile::Remove(newName);

}

CATCH_ALL(e)

{

//the normal place for the following Macro is in mfc\stdafx.h

//I bring it here becuase it is used only here and I have no plan to use it anywhere

#define DELETE_EXCEPTION(e) do { if(e) { e->Delete(); } } while (0)

//

TRACE(traceAppMsg, 0, "Warning: failed to delete file after failed SaveAs.\n");

DELETE_EXCEPTION(e);

}

END_CATCH_ALL

}

return FALSE;

}

// reset the title and change the document name

if (bReplace)

SetPathName(newName);

return TRUE; // success

}

BOOL CScheduleDoc::MyDoPromptFileName(CString& fileName, bool bReplace)

{

CFileDialog *pDlg;

pDlg = new CFileDialog (FALSE,_T("yps"),fileName,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,

_T("Timetable File (*.yps)|*.yps|All Files (*.*)|*.*||"),NULL);

CString title = bReplace ? _T("حفظ جدول الحصص"):_T("حفظ جدول الحصص في ملف آخر");

pDlg->m_ofn.lpstrTitle = title;

if(pDlg->DoModal()!=IDOK)

return FALSE;

fileName=pDlg->GetPathName();

return TRUE;

}

//---------------------------------------------------------------------