ArgvWToCommandLine - Opposite of CommandLineToArgvW

Purpose:

Read the argv array and create a space-separated single command line string for C/C++ programs.

This is opposite to what CommandLineToArgvW does.




LPWSTR ArgvWToCommandLine(int* argc, LPWSTR argv[])

{

    int lpCmdLineLen = 0;

    LPWSTR lpCmdLine = NULL;

    LPWSTR lpCmdLineIter = NULL;

    LPWSTR* argvIter = NULL;

    LPWSTR argvIterPtr = NULL;


    if (0 < *argc)

    {

        // Calculate string length for the new command line

        // +1 for space delimeters and for the terminating null character.

        for (argvIter = argv; *argvIter != argv[*argc]; argvIter++)

        {

            argvIterPtr = *argvIter;

            while (*argvIterPtr++)

            {

                lpCmdLineLen++;

            }

            lpCmdLineLen++;

        }


        /*SIMPLER VERSION

        for (argIndex = 0; argIndex < *argc; argIndex++)

        {

            lpCmdLineLen += strlen(argv[argIndex]) + 1;

        }*/


        lpCmdLine = (LPWSTR)LocalAlloc(

            LMEM_ZEROINIT,

            lpCmdLineLen * sizeof(char));


        if (lpCmdLine)

        {

            lpCmdLineIter = lpCmdLine;

            argvIter = argv;

            for (int argIndex = 0; argIndex < *argc; argIndex++)

            {

                while (*lpCmdLineIter)

                {

                    lpCmdLineIter++;

                }


                argvIterPtr = *argvIter;

                while (*argvIterPtr)

                {

                    *lpCmdLineIter++ = *argvIterPtr++;

                }


                if (argIndex + 1 < *argc)

                {

                    *lpCmdLineIter++ = TEXT(' ');

                }

                else

                {

                    *lpCmdLineIter = TEXT('\0');

                }

                argvIter++;

            }

        }

        else

        {

            SetLastError(ERROR_NOT_ENOUGH_MEMORY);

        }

    }

    else

    {

        SetLastError(ERROR_ARITHMETIC_OVERFLOW);

    }


    return (lpCmdLine);

}

C# Program to count Files and Directories with ReparsePoint recursively.

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace CountFilesWithReparseData
{
    class Program
    {
        public static string windowsSourceFolderPath;
        public static bool windowsIgnoreHiddenFiles = false;
        public static ConsoleColor originalForegroundColor;
        public static Dictionary<string, Dictionary<string, bool>> localFilesMetaInfo = new Dictionary<string, Dictionary<string, bool>>();
        public static int totalSourceFolderFolderCount = 0;
        public static int totalSourceFileCount = 0;
        public static int ReparseData_Directories = 0;
        public static int ReparseData_Files = 0;
        public static int ProgressLogTimeDelayFileCount = 0;
        public static int PathTooLongItems = 0;
        static void Main(string[] args)
        {
            string rootFolderpath = string.Empty;

            originalForegroundColor = Console.ForegroundColor;
            Console.SetWindowSize(Console.WindowWidth * 2, Console.WindowHeight * 2);
            Console.WriteLine();
            Console.WriteLine("Please enter the windows path where you want to count the files with ReparseData:");

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine();
            Console.Write("Example 1: ");
            Console.ForegroundColor = originalForegroundColor;
            Console.WriteLine("C:/MigrationData/BigFolder/");
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write("Example 2: ");
            Console.ForegroundColor = originalForegroundColor;
            Console.WriteLine(@"\\Kakinada\Jagannaikpur\");


            Console.WriteLine();
            Console.Write("Enter here >> ");
            windowsSourceFolderPath = Console.ReadLine();
            Console.WriteLine("Path entered = "+ windowsSourceFolderPath);

            // Print START time
            Console.WriteLine();
            Console.Write("Counting started at ");
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.Write(DateTime.Now);
            Console.ForegroundColor = originalForegroundColor;

            // Process the path
            CountFilesWithReparseData();

            // Print END time
            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Counting ended at ");
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine(DateTime.Now);
            Console.ForegroundColor = originalForegroundColor;

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("=============");
            Console.WriteLine("R E S U L T");
            Console.WriteLine("=============");
            Console.WriteLine();
            Console.WriteLine("Total Folder count = "+ totalSourceFolderFolderCount);
            Console.WriteLine("Total File   count = " + totalSourceFileCount);
            if (PathTooLongItems > 0)
            {
                Console.WriteLine("Skipped " + PathTooLongItems + " items and subitems because of PathTooLong >256 characters exception");
            }
            Console.WriteLine();
            Console.WriteLine("Total Folder count (with ReparseData) = "+ ReparseData_Directories);
            Console.WriteLine("Total Folder count (with ReparseData) = "+ ReparseData_Files);
            Console.WriteLine();

            // Don't close the console window.
            Console.ReadKey();
        }

        public static void WalkDirectoryTree(System.IO.DirectoryInfo dir)
        {
            List<DirectoryInfo> dirs = null;
            try
            {
                dirs = dir.GetDirectories().ToList();
            }
            catch (Exception ex)
            {
                Console.WriteLine(" ");
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message + " Skipping this folder.");
                Console.ForegroundColor = originalForegroundColor;
                Console.WriteLine(" ");
                return;
            }

            if (dirs != null)
            {
                var filtered = !(windowsIgnoreHiddenFiles) ? dirs : dirs.Where(f => !f.Attributes.HasFlag(FileAttributes.Hidden));
                foreach (DirectoryInfo subDir in filtered)
                {
                    string path = string.Empty;
                    try
                    {
                        path = subDir.FullName;
                    }
                    catch (PathTooLongException)
                    {
                        PathTooLongItems++;
                    }

                    if (!localFilesMetaInfo.ContainsKey(path))
                    {
                        ++totalSourceFolderFolderCount;
                        if ((ProgressLogTimeDelayFileCount++)%100 == 0)
                        {
                            string currentTimeStamp = string.Format("[{0:dd-MMM/HH:mm:ss}] ", DateTime.Now);
                            Console.Write("\r" + currentTimeStamp + " Indexing " + (totalSourceFolderFolderCount) + " Local folders.");
                        }

                        if (HasReparseData(path))
                        {
                            ReparseData_Directories++;
                        }

                        localFilesMetaInfo.Add(path, new Dictionary<string, bool>());
                    }
                    WalkDirectoryTree(subDir);
                }
            }
        }

        public static bool HasReparseData(string path)
        {
            if (String.IsNullOrEmpty(path))
                return false;

            FileInfo pathInfo = new FileInfo(path);
            return pathInfo.Attributes.HasFlag(FileAttributes.ReparsePoint);
        }

        public static void CountFilesWithReparseData()
        {
            Console.WriteLine(" ");

            // Index folders first
            localFilesMetaInfo.Add(windowsSourceFolderPath, new Dictionary<string, bool>());
            Console.WriteLine();
            WalkDirectoryTree(new DirectoryInfo(windowsSourceFolderPath));

            Console.WriteLine();
            foreach (KeyValuePair<string, Dictionary<string, bool>> uniqueLocalFolder in localFilesMetaInfo)
            {
                DirectoryInfo DirInfo = new DirectoryInfo(uniqueLocalFolder.Key);
                FileInfo[] sfilesList;
                try
                {
                    sfilesList = DirInfo.GetFiles();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(" ");
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(ex.Message + " Skipping this file.");
                    Console.ForegroundColor = originalForegroundColor;
                    Console.WriteLine(" ");
                    continue;
                }

                sfilesList = (windowsIgnoreHiddenFiles) ? sfilesList.Where(f => !f.Attributes.HasFlag(FileAttributes.Hidden)).ToArray() : sfilesList;
                int sourceFolder_fCount = sfilesList.Length;
                foreach (var fileInfo in sfilesList)
                {
                    ++totalSourceFileCount;
                    if ((ProgressLogTimeDelayFileCount++) % 100 == 0)
                    {
                        string currentTimeStamp = string.Format("[{0:dd-MMM/HH:mm:ss}] ", DateTime.Now);
                        Console.Write("\r" + currentTimeStamp + " Indexing " + (totalSourceFileCount) + " Local files.");
                    }

                    string path = string.Empty;
                    try
                    {
                        path = fileInfo.FullName;
                    }
                    catch (PathTooLongException ex)
                    {
                        PathTooLongItems++;
                    }

                    if (HasReparseData(path))
                    {
                        ReparseData_Files++;
                    }
                }
            }
        }
    }
}

Add two numbers represented by linked lists (in reverse order)



// Definition for singly-linked list.
struct ListNode 
{
     int val;
     struct ListNode *next;
};

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) 
{    
    int a=0;
    int b=0;
    int sum=0;
    int carry=0;
    struct ListNode* resultRoot = NULL;
    struct ListNode* previousNode = NULL;
    
    if(l1 == NULL)
    return l2;
    
    if(l2 == NULL)
    return l1;
    
    while(l1 != NULL || l2 != NULL || carry > 0)
    {
        struct ListNode* node = (struct ListNode *)malloc(sizeof(struct ListNode));
        
        a = (l1 != NULL)? l1->val: 0;
        b = (l2 != NULL)? l2->val: 0;
        
        sum   = (carry+a+b)%10;
        carry = ((carry+a+b)>9)?1:0;
        
        node->val = sum;
        node->next = NULL;
        
        // For the first node.
        if (resultRoot == NULL)
        {
            resultRoot = node;
            previousNode = node;
        }
        else
        {
            previousNode->next = node;
            previousNode = node;
        }
        
        l1= (l1!=NULL)? l1->next: l1;
        l2= (l2!=NULL)? l2->next: l2;
    }
    
    return resultRoot;
}

void printList(struct ListNode* root)
{
 while(root!=NULL)
 {
  printf("%d ",root->val);
  root = root->next;
 }
 printf("\n");
}

main()
{
 // List-1 (9,9,9)
 struct ListNode* node1 = (struct ListNode *)malloc(sizeof(struct ListNode));
 node1->val=9;
 node1->next=(struct ListNode *)malloc(sizeof(struct ListNode));
 node1->next->val=9;
 node1->next->next=(struct ListNode *)malloc(sizeof(struct ListNode));
 node1->next->next->val=9;
 node1->next->next->next=NULL; 
 printList(node1);
 
 // List-1 (9,9,9)
 struct ListNode* node2 = (struct ListNode *)malloc(sizeof(struct ListNode));
 node2->val=9;
 node2->next=(struct ListNode *)malloc(sizeof(struct ListNode));
 node2->next->val=9;
 node2->next->next=(struct ListNode *)malloc(sizeof(struct ListNode));
 node2->next->next->val=9;
 node2->next->next->next=NULL;
 printList(node2);
 
 // Sum of both lists.
 printList(addTwoNumbers(node1,node2));
}

Get DLL version programatically : C#

 using System;  
 using System.Diagnostics;  
 namespace KnowDllVersionByFilePath  
 {  
   class Program  
   {  
     static void Main(string[] args)  
     {  
       // Get the version of the DLL executing  
       // Assembly assembly = Assembly.LoadFrom("Microsoft.SharePoint.dll");  
       // Version ver = assembly.GetName().Version;  
       string fileV =  
         @"C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.SharePoint\v4.0_16.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.dll";  
       string fileVersion = FileVersionInfo.GetVersionInfo(fileV).FileVersion;  
       string productVersion = FileVersionInfo.GetVersionInfo(fileV).ProductVersion;  
       Console.WriteLine("File Version = "+fileVersion);  
       Console.WriteLine("Product Version = " + productVersion);  
       Console.ReadKey();  
     }  
   }  
 }  

Create a 2GB file instantaneously : C#

 using System;  
 using System.Collections.Generic;  
 using System.Globalization;  
 using System.IO;  
 using System.Linq;  
 using System.Text;  
 using System.Threading.Tasks;  
 using System.Text.RegularExpressions;  
 namespace ConsoleApplication3  
 {  
   class Program  
   {  
     static void Main(string[] args)  
     {  
       // Create a file of size 2 GB instantaneously (for testing purposes)  
       FileStream fs = new FileStream(@"D:\huge_dummy_file", FileMode.CreateNew);  
       fs.Seek(2048L * 1024 * 1024, SeekOrigin.Begin);  
       fs.WriteByte(0);  
       fs.Close();  
     }  
   }  
 }  

Regex to filter stack trace : C#


string message = stackTrace;
string pattern = "(\\r\\n   )?at (.*?)\\((.*?)\\)";
string replacement = "";
message = Regex.Replace(message, pattern, replacement);




The below text:

"The Stack Trace is at Google.LoaderAPI.Show()\r\n   at Google.Seed(unit code, ^alternativeSource erld)\r\n   at Google.Seed(unit code, ^alternativeSource erld)\r\n   at Google.Seed(unit code, ^alternativeSource erld)\r\n   at Google.Seed(unit code, ^alternativeSource erld)\r\n   at Google.Seed(unit code, ^alternativeSource erld)\r\n   at Google.Seed(unit code, ^alternativeSource erld)\r\n   at Google.Seed(unit code)\r\n   at Google.Seed(unit code, ^alternativeSource erld)\r\n   at Google.Seed(unit code, ^alternativeSource erld)\r\n   at Google.Seed(unit code, ^alternativeSource erld)\r\n   at Google.Seed(unit code, ^alternativeSource erld)\r\n   at Google.Seed(unit code, ^alternativeSource erld)\r\n   at Google.LoaderAPI.Show(someArugments)"


Will be converted as:
 "The Stack Trace is"


Pattern:
(\\r\\n   )?at (.*?)\\((.*?)\\)


Explanation:
(\\r\\n   )?      -----> Optional "\r\n"
at  
(.*?)               ------> anything
\\(                  --------> "("
(.*?)               ------> anything
\\)                  --------> ")"

Find maximum difference between two numbers in an array (or) find max profit that can be made in given stock rates for few consecutuve days


int MaxDiff(int arr[], int siz)
{
    int i,j;
    int maxDiff = 0;
    int minNum  = arr[0];
    
    for(i=1;i<siz;i++)
    {
        if( (arr[i]-minNum) >  maxDiff )
            maxDiff = (arr[i]-minNum);

        if(arr[i] < minNum)
           minNum = arr[i];
    }

    return maxDiff;
}