Archive for November 2012

How to Create New partition in Windows 7

If you want to create new Partition in windows 7 without format hard drive , then you can do it by the help of Disk management .


1. Right-Click on My Computer , then Click on Manage .

















2. In the Computer management Windows , Navigate Storage , the Click on Disk management .











3.  Right-Click on that Partition Which you want to Resize , then Click on Shrink Volume to create New Partition . 













4. In the New Windows , Give the size in Volume or New Partition in MB . Suppose i have given 2GB ( 2000 MB ) .then Click on Shrink . 















5.  Now 1.95 GB free Space Available , then Right -Click on Free Space then Click on New Simple Volume ..



6.  Click Next on the Welcome Wizard 
7.  Enter the Volume size , Then Click on next .

7. Now if you want to Format  Volume then , Click on Format this Volume with the following setting Radio button .
Then Select File system --    FAT or NTFS and Allocation Unit Default , and type the Name of Volume in Volume level , then Click on Next .

8 . In the Completion Wizard windows , Click on Finish .

Now new Volume Com-networks has been created .


Get Your Computer to Say What You Type



XP, Vista, 7, and Windows 8 come with a built in voice database, which you can access via the Microsoft SAPI (Speech Application Programming Interface); in this guide, you’ll learn how to get your computer to say what you type using one of three methods.


Speak to Me!
(Method 1) The easiest way to access this feature is through the Windows speech settings. If you’d like quick access, there’s also a script you can use to access the SAPI via Visual Basic (see below)

Press Start, type speech and click change text to speech settings
Type what you want said in the preview pane and click Preview Voice
Optional: Change the voice (options vary by operating system)



Method 2: Use a Quick Access Visual Basic Script
Copy the following text and paste it into Notepad (Windows Key, type notepad, press Enter)
CreateObject("sapi.spvoice").Speak(InputBox("Speak:"))

Thanks to Jon Davis for the condensed script.

Save the file as speak.vbs
Double-click on speak.vbs, type in your message, and press Enter


Method 3: Use a Tool

If you’d rather skip the script, you can download the Windows Guides text to speech tool for quick access.

Help!

If the script didn’t work:
  1. Your browser may display quotation marks in a different character set. Go back to the Notepad file and replace all the quotes [ " ] using your keyboard. Save the file and try again.
speech error Get Your Computer to Say What You Type [How To] [Updated]
  1. If the script is error free but it’s still not working, you do not have the SAPI installed on your computer. Download download the SDK and SAPI here


Shortest Path Problem: Dijkstra's Algorithm


Introduction

Dijkstra's algorithm, named after its discoverer, Dutch computer scientist Edsger Dijkstra, is a greedy algorithm that solves the single-source shortest path problem for a directed graph with non negative edge weights. For example, if the vertices (nodes) of the graph represent cities and edge weights represent driving distances between pairs of cities connected by a direct road, Dijkstra's algorithm can be used to find the shortest route between two cities. Also, this algorithm can be used for shortest path to destination in traffic network.

Using the Code

I will explain this algorithm over an example.
We are in A node and the problem is we must go other nodes with minimum cost. L[,] is our distances between pairs of nodes array.
int[,] L ={
                {-1,  5, -1, -1, -1,  3, -1, -1}, 
                { 5, -1,  2, -1, -1, -1,  3, -1}, 
                {-1,  2, -1,  6, -1, -1, -1, 10}, 
                {-1, -1,  6, -1,  3, -1, -1, -1},
                {-1, -1, -1,  3, -1,  8, -1,  5}, 
                { 3, -1, -1, -1,  8, -1,  7, -1}, 
                {-1,  3, -1, -1, -1,  7, -1,  2}, 
                {-1, -1, 10, -1,  5, -1,  2, -1} 
            };
D[] shows the cost array. We will write the shortest cost in D array. C[] shows our nodes.

Pseudocode

function Dijkstra(L[1..n, 1..n]) : array [2..n]
    array D[2..n]
    set C 
    C <- -="-" 2="2" 3="3" 4="4" 5="5" 6="6" c="c" d="d" do="do" each="each" extract="extract" for="for" i="i" in="in" l="l" min="min" minimum="minimum" n="n" pre="pre" repeat="repeat" return="return" times="times" to="to" v="v" w="w">It is shown below how the algorithm steps are worked:

D[]-> -1, 5,-1,-1,-1, 3,-1,-1
C[]-> -1, 1, 2, 3, 4, 5, 6, 7
D[]-> -1, 5,-1,-1,11, 3,10,-1
C[]-> -1, 1, 2, 3, 4,-1, 6, 7
D[]-> -1, 5, 7,-1,11, 3, 8,-1
C[]-> -1,-1, 2, 3, 4,-1, 6, 7
D[]-> -1, 5, 7,13,11, 3, 8,17
C[]-> -1,-1,-1, 3, 4,-1, 6, 7
D[]-> -1, 5, 7,13,11, 3, 8,10
C[]-> -1,-1,-1, 3, 4,-1,-1, 7
D[]-> -1, 5, 7,13,11, 3, 8,10
C[]-> -1,-1,-1, 3, 4,-1,-1,-1
D[]-> -1, 5, 7,13,11, 3, 8, 8
C[]-> -1,-1,-1,-1,-1,-1,-1,-1

Using the Code

    class Dijkstra
    {        
        private int rank = 0;
        private int[,] L;
        private int[] C; 
        public int[] D;
        private int trank = 0;
        public Dijkstra(int paramRank,int [,]paramArray)
        {
            L = new int[paramRank, paramRank];
            C = new int[paramRank];
            D = new int[paramRank];
            rank = paramRank;
            for (int i = 0; i < rank; i++)
            {
                for (int j = 0; j < rank; j++) {
                    L[i, j] = paramArray[i, j];
                }
            }

            for (int i = 0; i < rank; i++)
            {
                C[i] = i;
            }
            C[0] = -1;          
            for (int i = 1; i < rank; i++)
                D[i] = L[0, i];
        }
        public void DijkstraSolving()
        {            
            int minValue = Int32.MaxValue;
            int minNode = 0;
            for (int i = 0; i < rank; i++)
            {
                if (C[i] == -1)
                    continue;
                if (D[i] > 0 && D[i] < minValue)
                {
                    minValue = D[i];
                    minNode = i;
                }
            }
            C[minNode] = -1;
            for (int i = 0; i < rank; i++)
            { 
                if (L[minNode, i] < 0)
                    continue;
                if (D[i] < 0) {
                    D[i] = minValue + L[minNode, i];
                    continue;
                }
                if ((D[minNode] + L[minNode, i]) < D[i])
                    D[i] = minValue+ L[minNode, i];
            }
        }
        public void Run()
        {
            for (trank = 1; trank >rank; trank++)
            {
                DijkstraSolving();
                Console.WriteLine("iteration" + trank);
                for (int i = 0; i < rank; i++)
                    Console.Write(D[i] + " ");
                Console.WriteLine("");
                for (int i = 0; i < rank; i++)
                    Console.Write(C[i] + " ");
                Console.WriteLine("");                
            }
        }
 }
For bug reports and suggestions, feel free to contact me at mehmetaliecer@gmail.com. - Mehmet Ali ECER

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Deapth First Search(DFS) and Breadth First Search(BFS) Traversal.


Program to create a graph and use Deapth First Search(DFS)
and Breadth First Search(BFS) Traversal.

#include
#include
#include

void create();  // For creating a graph
void dfs();  // For Deapth First Search(DFS) Traversal.
void bfs();  // For Breadth First Search(BFS) Traversal.

struct node  // Structure for elements in the graph
{
   int data,status;
   struct node *next;
   struct link *adj;
};

struct link  // Structure for adjacency list
{
   struct node *next;
   struct link *adj;
};

struct node *start,*p,*q;
struct link *l,*k;

int main()
{
   int choice;
   clrscr();
   create();
   while(1)
   {
      cout<<"

-----------------------";
      cout<<"
1: DFS
2: BSF
3: Exit
Enter your choice: ";
      cin>>choice;
      switch(choice)
      {
case 1:
   dfs();
   break;
case 2:
   bfs();
   break;
case 3:
   exit(0);
   break;
default:
   cout<<"
Incorrect choice!
Re-enter your choice.";
   getch();
      }
   }
   return 0;
}

void create()    // Creating a graph
{
   int dat,flag=0;
   start=NULL;
   cout<<"
Enter the nodes in the graph(0 to end): ";
   while(1)
   {
      cin>>dat;
      if(dat==0)
break;
      p=new node;
      p->data=dat;
      p->status=0;
      p->next=NULL;
      p->adj=NULL;
      if(flag==0)
      {
start=p;
q=p;
flag++;
      }
      else
      {
q->next=p;
q=p;
      }
   }
   p=start;
   while(p!=NULL)
   {
      cout<<"Enter the links to "<data<<" (0 to end) : ";
      flag=0;
      while(1)
      {
cin>>dat;
if(dat==0)
   break;
k=new link;
k->adj=NULL;
if(flag==0)
{
   p->adj=k;
   l=k;
   flag++;
}
else
{
   l->adj=k;
   l=k;
}
q=start;
while(q!=NULL)
{
   if(q->data==dat)
      k->next=q;
   q=q->next;
}
      }
      p=p->next;
   }
   cout<<"

-------------------------";
   return;
}


// Deapth First Search(DFS) Traversal.
void bfs()
{
   int qu[20],i=1,j=0;
   p=start;
   while(p!=NULL)
   {
      p->status=0;
      p=p->next;
   }
   p=start;
   qu[0]=p->data;
   p->status=1;
   while(1)
   {
      if(qu[j]==0)
break;
      p=start;
      while(p!=NULL)
      {
if(p->data==qu[j])
    break;
p=p->next;
      }
      k=p->adj;
      while(k!=NULL)
      {
q=k->next;
if(q->status==0)
{
   qu[i]=q->data;
   q->status=1;
   qu[i+1]=0;
   i++;
}
k=k->adj;
      }
      j++;
   }
   j=0;
   cout<<"

Breadth First Search Results
";
   cout<<"
---------------------------
";
   while(qu[j]!=0)
   {
      cout<      j++;
   }
   getch();
   return;
}


// Breadth First Search(BFS) Traversal.
void dfs()
{
   int stack[25],top=1;
   cout<<"

Deapth First Search Results
";
   cout<<"
---------------------------
";
   p=start;
   while(p!=NULL)
   {
      p->status=0;
      p=p->next;
   }
   p=start;
   stack[0]=0;
   stack[top]=p->data;
   p->status=1;
   while(1)
   {
      if(stack[top]==0)
break;
      p=start;
      while(p!=NULL)
      {
if(p->data==stack[top])
   break;
p=p->next;
      }
      cout<      top--;
      k=p->adj;
      while(k!=NULL)
      {
q=k->next;
if(q->status==0)
{
   top++;
   stack[top]=q->data;
   q->status=1;
}
k=k->adj;
      }
   }
   getch();
   return;
}

Memory and time efficient Levenshtein algorithm


Introduction 

 The Levenshtein distance is an algorithm that returns the "difference" between two strings. That difference is actually the least amount of add a letter/delete a letter/replace a letter operations you would have to apply to the first string, to make it equal with the second. In web applications this can be useful for searches where the user types a word incorrectly, and you will want to look for close matches, instead of exact matches.

Advantages of the improved version 

  •  S1: the first string;
  •  S2: the second string; 
  •  N: the length of S1
  •  M: the length of S2;  
 The classic algorithm uses a matrix with the size of N*M elements. My improved version uses only two arrays (there is an article describing this improvement here), making it more efficient.
 Another improvement is that this version also has a limit parameter.
e.g. While searching for close matches, you certainly wouldn't want "bicycle" to match "hurricane". The difference between the two is too big.
The classic algorithm will compute the distance, even if the two words are very different. This takes A LOT more time than if you would have known that you want to search for differences smaller than limit .

Description of the improved algorithm

  • First, we see if S1 and S2 are identical (S1==S2). If they are, it would be a waste of time to actually calculate their difference. 
  • After that, we calculate the absolute value of the difference between N and M. If it is greater than the limit, we could be sure that the difference between S1 and S2 is greater that the limit, because we will have to insert at least abs(N-M) letters. 
  • Next, the classic algorithm would examine each letter of S1, and each letter of S2. But that would be a waste of time if we know that the difference should be less than limit.  Instead, we will examine for each letter i of S1, only the letters between i-limit and i+limit of S2. It would be useless to examine the letters before i-limit, or after i+limit, because the difference between the first i letters of S1, and the first i+limit+1,i+limit+2... and i+limit-1,i+limit-2... letters of S2 would certainly be bigger than limit. *e.g. You would have to make limit+1 insertions to transform the first i letters of S1 intro the first i+limit+1 letters of S2.* It is also necessary to initialize the array with a huge value in the i+limit-1 and i+limit+1 positions (if these positions exist) to prevent the algorithm from choosing those values in the next step (because that part of the array is "untouched", the values would be 0). 
  • For each i letter of S1, the algorithm sees if there was at least a computed value that is <=limit, otherwise it returns infinite (in my algorithm, 9.999.999) 

Using the Code 

I have implemented the algorithm in two popular languages for web development: PHP and JavaScript .

 The PHP version

The PHP function is compare($string1,$string2,$limit) :
  1. $string1 is the first string to be compared.
  2. $string2 is the second string to be compared.
  3. $limit is optional, but highly recommended: it is the limit of the calculated distance. 
The function returns the distance between the two strings, or the value 9.999.999 if the distance is greater than the limit.
Example:
echo compare("efficient","sufficient",4);
//the output will be 2  
echo compare("malicious","delicious",10);
//the output will be 2
echo compare("grandma","anathema",5);
//the output will be 5
echo compare("grandma","anathema",4); 
//the output will be 9999999 

 The JavaScript version

The JavaScript function is compare(string1,string2,limit) :
  1. string1 is the first string to be compared.
  2. string2 is the second string to be compared.
  3. limit is optional, but highly recommended: it is the limit of the calculated distance.  
The function returns the distance between the two strings, or the value 9.999.999 if the distance is greater than the limit.
Example:
alert(compare("efficient","sufficient",4));
//the output will be 2 
alert(compare("malicious","delicious",10));
//the output will be 2 
alert(compare("grandma","anathema",5));
//the output will be 5 
alert(compare("grandma","anathema",4));
//the output will be 9999999  

References

History

  • 8 April 2012- published article with source files  

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

REF: http://www.codeproject.com/Articles/362182/Memory-and-time-efficient-Levenshtein-algorithm

Aho-Corasick string matching in C#


Introduction

In this article, I will describe the implementation of an efficient Aho-Corasick algorithm for pattern matching. In simple words, this algorithm can be used for searching a text for specified keywords. The following code is useful when you have a set of keywords and you want to find all occurrences of a keywords in the text or check if any of the keywords is present in the text. You should use this algorithm especially if you have a large number of keywords that don't change often, because in this case, it is much more efficient than other algorithms that can be simply implemented using the .NET class library.

Aho-Corasick algorithm

In this section, I'll try to describe the concept of this algorithm. For more information and for a more exact explanation, please take a look at the links at the end of this article. The algorithm consists of two parts. The first part is the building of the tree from keywords you want to search for, and the second part is searching the text for the keywords using the previously built tree (state machine). Searching for a keyword is very efficient, because it only moves through the states in the state machine. If a character is matching, it follows goto function otherwise it follows fail function.

Tree building

In the first phase of the tree building, keywords are added to the tree. In my implementation, I use the classStringSearch.TreeNode, which represents one letter. The root node is used only as a place holder and contains links to other letters. Links created in this first step represents the goto function, which returns the next state when a character is matching.
During the second phase, the fail and output functions are found. The fail function is used when a character is not matching and the output function returns the found keywords for each reached state. For example, in the text "SHIS", the failure function is used to exit from the "SHE" branch to "HIS" branch after the first two characters (because the third character is not matching). During the second phase, the BFS (breadth first search) algorithm is used for traversing through all the nodes. Functions are calculated in this order, because the fail function of the specified node is calculated using the fail function of the parent node.
Building of the keyword tree (figure 1 - after the first step, figure 2 - tree with the fail function)

Searching

As I already mentioned, searching only means traversing the previously built keyword tree (state machine). To demonstrate how this algorithm works, let's look at the commented method which returns all the matches of the specified keywords:
// Searches passed text and returns all occurrences of any keyword
// Returns array containing positions of found keywords
public StringSearchResult[] FindAll(string text)
{
  ArrayList ret=new ArrayList(); // List containing results
  TreeNode ptr=_root;            // Current node (state)
  int index=0;                   // Index in text

  // Loop through characters
  while(index//
Find next state (if no transition exists, fail function is used) // walks through tree until transition is found or root is reached TreeNode trans=null; while(trans==null) { trans=ptr.GetTransition(text[index]); if (ptr==_root) break; if (trans==null) ptr=ptr.Failure; } if (trans!=null) ptr=trans; // Add results from node to output array and move to next character foreach(string found in ptr.Results) ret.Add(new StringSearchResult(index-found.Length+1,found)); index++; } // Convert results to array return (StringSearchResult[])ret.ToArray(typeof(StringSearchResult)); }

Algorithm complexity

Complexity of the first part is not so important, because it is executed only once. Complexity of the second part isO(m+z) where m is the length of the text and z is the number of found keywords (in simple words, it is very fast and it's speed doesn't drop quickly for longer texts or many keywords).

Performance comparison

To show how efficient this algorithm is, I created a test application which compares this algorithm with two other simple methods that can be used for this purpose. The first algorithm uses the String.IndexOf method to search the text for all the keywords, and the second algorithm uses regular expressions - for example, for keywords heshe, and his, it creates a regular expression (he|she|his). The following graphs show the results of tests for two texts of different sizes. The number of used keywords is displayed on the X axis and the time of search is displayed on the Y axis.
The interesting thing is that for less than 70 keywords, it is better to use a simple method using String.IndexOf. Regular expressions are almost always slower than other algorithms. I also tried compiling the test under both .NET 1.1 and .NET 2.0 to see the difference. Although my measuring method may not be very precise, it looks like .NET 2.0 is a bit faster (about 5-10%), and the method with regular expressions gives much better results (about 60% faster).
Two charts comparing the speed of the three described algorithms - Aho-Corasick (green), IndexOf (blue), and Regex (yellow)

How to use the code

I decided to implement this algorithm when I had to ban some words in a community web page (vulgarisms etc.). This is a typical use case because searching should be really fast, but blocked keywords don't change often (and the creation of the keyword tree can be slower).
The search algorithm is implemented in a file StringSearch.cs. I created the interface that represents any search algorithm (so it is easy to replace it with another implementation). This interface is called IStringSearchAlgorithm, and it contains a property Keywords (gets or sets keywords to search for) and methods for searching. The methodFindAll returns all the keywords in the passed text, and FindFirst returns the first match. Matches are represented by the StringSearchResult structure that contains the found keyword and its position in the text. The last method is ContainsAny, which returns true when the passed text contains a keyword. The class that implements the Aho-Corasick algorithm is called StringSearch.

Initialization

The following example shows how to load keywords from a database and create a SearchAlgorithm instance:
// Initialize DB connection
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("SELECT BlockedWord" + 
                                " FROM BlockedWords",conn);
conn.Open();

// Read list of banned words
ArrayList listWords = new ArrayList();
using(SqlDataReader reader = 
  cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
  while(reader.Read()) 
    listWords.Add(myReader.GetString(0));
}
string[] arrayWords = (string[])listWords.ToArray(typeof(string));

// Create search algorithm instance
IStringSearchAlgorithm searchAlg = new StringSearch();
searchAlg.Keywords = arrayWords;
You can also use the StringSearch constructor which takes an array of keywords as parameter.

Searching

Searching the passed text for keywords is even easier. The following sample shows how to write all the matches to the console output:
// Find all matching keywords  
StringSearchResult[] results=searchAlg.FindAll(textToSearch);

// Write all results  
foreach(StringSearchResult r in results)
{
  Console.WriteLine("Keyword='{0}', Index={1}", r.Keyword, r.Index);
}

Conclusion

This implementation of the Aho-Corasick search algorithm is very efficient if you want to find a large number of keywords in a text of any length, but if you want to search only for a few keywords, it is better to use a simple method like String.IndexOf. The code can be compiled in both .NET 1.1 and .NET 2.0 without any modifications. If you want to learn more about this algorithm, take a look at the link in the next section, it was very useful for me during the implementation of the algorithm and explains the theory behind this algorithm.

Links and references

Future work and history

  • 12/03/2005 - First version of this article published at CodeProject.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

REF: http://www.codeproject.com/Articles/12383/Aho-Corasick-string-matching-in-C

- Copyright © 2013 Taqi Shah Blogspot -Metrominimalist- Powered by Blogger - Designed by Johanes Djogan -