26 December 2021

Simple MFC UDP example

 // SimpleUDPDlg.cpp : implementation file  
 //  
 #include "stdafx.h"  
 #include "SimpleUDP.h"  
 #include "SimpleUDPDlg.h"  
 #include "afxsock.h"  
 #include "ClientSend.h"  
 #ifdef _DEBUG  
 #define new DEBUG_NEW  
 #undef THIS_FILE  
 static char THIS_FILE[] = __FILE__;  
 #endif  
 #define ECHOMAX 1024  
 /////////////////////////////////////////////////////////////////////////////  
 // CAboutDlg dialog used for App About  
      HANDLE thr;  
      unsigned long id1;  
 class CAboutDlg : public CDialog  
 {  
 public:  
      CAboutDlg();  
 // Dialog Data  
      //{{AFX_DATA(CAboutDlg)  
      enum { IDD = IDD_ABOUTBOX };  
      //}}AFX_DATA  
      // ClassWizard generated virtual function overrides  
      //{{AFX_VIRTUAL(CAboutDlg)  
      protected:  
      virtual void DoDataExchange(CDataExchange* pDX);  // DDX/DDV support  
      //}}AFX_VIRTUAL  
 // Implementation  
 protected:  
      //{{AFX_MSG(CAboutDlg)  
      //}}AFX_MSG  
      DECLARE_MESSAGE_MAP()  
 };  
 CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)  
 {  
      //{{AFX_DATA_INIT(CAboutDlg)  
      //}}AFX_DATA_INIT  
 }  
 void CAboutDlg::DoDataExchange(CDataExchange* pDX)  
 {  
      CDialog::DoDataExchange(pDX);  
      //{{AFX_DATA_MAP(CAboutDlg)  
      //}}AFX_DATA_MAP  
 }  
 BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)  
      //{{AFX_MSG_MAP(CAboutDlg)  
           // No message handlers  
      //}}AFX_MSG_MAP  
 END_MESSAGE_MAP()  
 /////////////////////////////////////////////////////////////////////////////  
 // CSimpleUDPDlg dialog  
 CSimpleUDPDlg::CSimpleUDPDlg(CWnd* pParent /*=NULL*/)  
      : CDialog(CSimpleUDPDlg::IDD, pParent)  
 {  
      //{{AFX_DATA_INIT(CSimpleUDPDlg)  
           // NOTE: the ClassWizard will add member initialization here  
      //}}AFX_DATA_INIT  
      // Note that LoadIcon does not require a subsequent DestroyIcon in Win32  
      m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);  
 }  
 void CSimpleUDPDlg::DoDataExchange(CDataExchange* pDX)  
 {  
      CDialog::DoDataExchange(pDX);  
      //{{AFX_DATA_MAP(CSimpleUDPDlg)  
      DDX_Control(pDX, IDC_EDIT1, m_edit);  
      //}}AFX_DATA_MAP  
 }  
 BEGIN_MESSAGE_MAP(CSimpleUDPDlg, CDialog)  
      //{{AFX_MSG_MAP(CSimpleUDPDlg)  
      ON_WM_SYSCOMMAND()  
      ON_WM_PAINT()  
      ON_WM_QUERYDRAGICON()  
      ON_BN_CLICKED(IDC_BUTTON1, OnStart)  
      //}}AFX_MSG_MAP  
 END_MESSAGE_MAP()  
 /////////////////////////////////////////////////////////////////////////////  
 // CSimpleUDPDlg message handlers  
 UINT ReceiveData(LPVOID pParam)  
 {  
      CSimpleUDPDlg *dlg=(CSimpleUDPDlg*)pParam;  
      AfxSocketInit(NULL);  
      CSocket echoServer;   
       // Create socket for sending/receiving datagrams  
       if (echoServer.Create(514, SOCK_DGRAM, NULL)== 0) {  
           AfxMessageBox("Create() failed");  
       }  
      for(;;) { // Run forever  
   // Client address  
   SOCKADDR_IN echoClntAddr;   
   // Set the size of the in-out parameter  
   int clntAddrLen = sizeof(echoClntAddr);  
   // Buffer for echo string  
   char echoBuffer[ECHOMAX];   
   // Block until receive message from a client  
   int recvMsgSize = echoServer.ReceiveFrom(echoBuffer,   
       ECHOMAX, (SOCKADDR*)&echoClntAddr, &clntAddrLen, 0);  
   if (recvMsgSize < 0) {  
    AfxMessageBox("RecvFrom() failed");  
   }  
      echoBuffer[recvMsgSize]='\0';  
   dlg->m_edit.ReplaceSel(echoBuffer);  
      dlg->m_edit.ReplaceSel("\r\n");  
  }  
 }  
 BOOL CSimpleUDPDlg::OnInitDialog()  
 {  
      CDialog::OnInitDialog();  
      // Add "About..." menu item to system menu.  
      // IDM_ABOUTBOX must be in the system command range.  
      ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);  
      ASSERT(IDM_ABOUTBOX < 0xF000);  
      CMenu* pSysMenu = GetSystemMenu(FALSE);  
      if (pSysMenu != NULL)  
      {  
           CString strAboutMenu;  
           strAboutMenu.LoadString(IDS_ABOUTBOX);  
           if (!strAboutMenu.IsEmpty())  
           {  
                pSysMenu->AppendMenu(MF_SEPARATOR);  
                pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);  
           }  
      }  
      // Set the icon for this dialog. The framework does this automatically  
      // when the application's main window is not a dialog  
      SetIcon(m_hIcon, TRUE);               // Set big icon  
      SetIcon(m_hIcon, FALSE);          // Set small icon  
      thr=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ReceiveData,this,NULL,&id1);  
      // TODO: Add extra initialization here  
      return TRUE; // return TRUE unless you set the focus to a control  
 }  
 void CSimpleUDPDlg::OnSysCommand(UINT nID, LPARAM lParam)  
 {  
      if ((nID & 0xFFF0) == IDM_ABOUTBOX)  
      {  
           CAboutDlg dlgAbout;  
           dlgAbout.DoModal();  
      }  
      else  
      {  
           CDialog::OnSysCommand(nID, lParam);  
      }  
 }  
 // If you add a minimize button to your dialog, you will need the code below  
 // to draw the icon. For MFC applications using the document/view model,  
 // this is automatically done for you by the framework.  
 void CSimpleUDPDlg::OnPaint()   
 {  
      if (IsIconic())  
      {  
           CPaintDC dc(this); // device context for painting  
           SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);  
           // Center icon in client rectangle  
           int cxIcon = GetSystemMetrics(SM_CXICON);  
           int cyIcon = GetSystemMetrics(SM_CYICON);  
           CRect rect;  
           GetClientRect(&rect);  
           int x = (rect.Width() - cxIcon + 1) / 2;  
           int y = (rect.Height() - cyIcon + 1) / 2;  
           // Draw the icon  
           dc.DrawIcon(x, y, m_hIcon);  
      }  
      else  
      {  
           CDialog::OnPaint();  
      }  
 }  
 // The system calls this to obtain the cursor to display while the user drags  
 // the minimized window.  
 HCURSOR CSimpleUDPDlg::OnQueryDragIcon()  
 {  
      return (HCURSOR) m_hIcon;  
 }  
 void CSimpleUDPDlg::OnStart()   
 {  
      // TODO: Add your control notification handler code here  
      CClientSend send;  
      send.DoModal();  
 }  

01 October 2020

Create Bitmap example

 #include <stdio.h>  
 const int BYTES_PER_PIXEL = 3; /// red, green, & blue  
 const int FILE_HEADER_SIZE = 14;  
 const int INFO_HEADER_SIZE = 40;  
 void generateBitmapImage(unsigned char* image, int height, int width, char* imageFileName);  
 unsigned char* createBitmapFileHeader(int height, int stride);  
 unsigned char* createBitmapInfoHeader(int height, int width);  
 int main()  
 {  
   int height = 361;  
   int width = 867;  
   unsigned char image[361][867][BYTES_PER_PIXEL];  
   char* imageFileName = (char*)"c:\\Work\\bitmapImage.bmp";  
   int i, j;  
   for (i = 0; i < height; i++) {  
     for (j = 0; j < width; j++) {  
       image[i][j][2] = (unsigned char)(i * 255 / height);       ///red  
       image[i][j][1] = (unsigned char)(j * 255 / width);       ///green  
       image[i][j][0] = (unsigned char)((i + j) * 255 / (height + width)); ///blue  
     }  
   }  
   generateBitmapImage((unsigned char*)image, height, width, imageFileName);  
   printf("Image generated!!");  
 }  
 void generateBitmapImage(unsigned char* image, int height, int width, char* imageFileName)  
 {  
   int widthInBytes = width * BYTES_PER_PIXEL;  
   unsigned char padding[3] = { 0, 0, 0 };  
   int paddingSize = (4 - (widthInBytes) % 4) % 4;  
   int stride = (widthInBytes)+paddingSize;  
   FILE* imageFile = fopen(imageFileName, "wb");  
   unsigned char* fileHeader = createBitmapFileHeader(height, stride);  
   fwrite(fileHeader, 1, FILE_HEADER_SIZE, imageFile);  
   unsigned char* infoHeader = createBitmapInfoHeader(height, width);  
   fwrite(infoHeader, 1, INFO_HEADER_SIZE, imageFile);  
   int i;  
   for (i = 0; i < height; i++) {  
     fwrite(image + (i * widthInBytes), BYTES_PER_PIXEL, width, imageFile);  
     fwrite(padding, 1, paddingSize, imageFile);  
   }  
   fclose(imageFile);  
 }  
 unsigned char* createBitmapFileHeader(int height, int stride)  
 {  
   int fileSize = FILE_HEADER_SIZE + INFO_HEADER_SIZE + (stride * height);  
   static unsigned char fileHeader[] = {  
     0,0,   /// signature  
     0,0,0,0, /// image file size in bytes  
     0,0,0,0, /// reserved  
     0,0,0,0, /// start of pixel array  
   };  
   fileHeader[0] = (unsigned char)('B');  
   fileHeader[1] = (unsigned char)('M');  
   fileHeader[2] = (unsigned char)(fileSize);  
   fileHeader[3] = (unsigned char)(fileSize >> 8);  
   fileHeader[4] = (unsigned char)(fileSize >> 16);  
   fileHeader[5] = (unsigned char)(fileSize >> 24);  
   fileHeader[10] = (unsigned char)(FILE_HEADER_SIZE + INFO_HEADER_SIZE);  
   return fileHeader;  
 }  
 unsigned char* createBitmapInfoHeader(int height, int width)  
 {  
   static unsigned char infoHeader[] = {  
     0,0,0,0, /// header size  
     0,0,0,0, /// image width  
     0,0,0,0, /// image height  
     0,0,   /// number of color planes  
     0,0,   /// bits per pixel  
     0,0,0,0, /// compression  
     0,0,0,0, /// image size  
     0,0,0,0, /// horizontal resolution  
     0,0,0,0, /// vertical resolution  
     0,0,0,0, /// colors in color table  
     0,0,0,0, /// important color count  
   };  
   infoHeader[0] = (unsigned char)(INFO_HEADER_SIZE);  
   infoHeader[4] = (unsigned char)(width);  
   infoHeader[5] = (unsigned char)(width >> 8);  
   infoHeader[6] = (unsigned char)(width >> 16);  
   infoHeader[7] = (unsigned char)(width >> 24);  
   infoHeader[8] = (unsigned char)(height);  
   infoHeader[9] = (unsigned char)(height >> 8);  
   infoHeader[10] = (unsigned char)(height >> 16);  
   infoHeader[11] = (unsigned char)(height >> 24);  
   infoHeader[12] = (unsigned char)(1);  
   infoHeader[14] = (unsigned char)(BYTES_PER_PIXEL * 8);  
   return infoHeader;  
 }  

03 June 2020

Easy way of finding centriod using octave

Octave code:
A=[10 11; 20 21; 30 31; 40 41; 50 51; 60 61; 70 71]
PB = [1 1 3 3 2 2 2]

C = A (PB==3,:)
D = mean(C)
SD = size(C,1)

Results:
A =

   10   11
   20   21
   30   31
   40   41
   50   51
   60   61
   70   71

PB =

   1   1   3   3   2   2   2

C =

   30   31
   40   41

D =

   35   36

SD =  2

Simplified code:

for i=1:K
    centroids(i,:) = mean( X(idx==i,:) );
endfor

02 June 2020

Array indexing in Octave

A=[10 11; 20 21; 30 31; 40 41; 60 61; 60 61; 70 71]
PB = [1 3 5]
B = [1 2 3 4 7]
C = A (B(PB),:)
D = mean(C)

A =

   10   11
   20   21
   30   31
   40   41
   60   61
   60   61
   70   71

PB =

   1   3   5

B =

   1   2   3   4   7

C =

   10   11
   30   31
   70   71

D =

   36.667   37.667

25 April 2020

WPF update user interface in multithreading mode

   public partial class Window1 : Window  
   {  
     public Class1 c;  
     public Window1()  
     {  
       InitializeComponent();  
       c = new Class1();  
       c.Class1Event += C_Class1Event;  
      }  
     private void C_Class1Event(object sender, Class1EventArgs e)  
     {//Triggered from a different thread  

       this.Dispatcher.Invoke((Action)(() =>  
       {//this refer to form in WPF application   
         imgShirt.Source = new BitmapImage(new Uri(System.AppDomain.CurrentDomain.BaseDirectory + @"\images2.jpg", UriKind.RelativeOrAbsolute));  
       }));  

     }  
     private void Change_Click(object sender, RoutedEventArgs e)  
     {  
       c.Start();  
     }  
     private void Change2_Click(object sender, RoutedEventArgs e)  
     {//Called from the same thread  
       Uri fileUri = new Uri(System.AppDomain.CurrentDomain.BaseDirectory + @"\images.jpg", UriKind.RelativeOrAbsolute);  
       imgShirt.Source = new BitmapImage(fileUri);  
     }  
   }  
   public class Class1  
   {  
     public event EventHandler<Class1EventArgs> Class1Event;  
     public Class1()  
     {  
     }  
     public void Start()  
     {  
       Task.Run(() => {  
         Class1EventArgs e = new Class1EventArgs();  
         Class1Event(this, e);  
       });  
     }  
   }  
   public class Class1EventArgs : EventArgs  
   {  
   }  

31 January 2020

How to deserialize Xml with different namespaces / prefixes


Specify the namespace in the child element
 [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]  
 [System.SerializableAttribute()]  
 [System.Diagnostics.DebuggerStepThroughAttribute()]  
 [System.ComponentModel.DesignerCategoryAttribute("code")]  
 [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]  
 [System.Xml.Serialization.XmlRootAttribute(Namespace= "http://search.yahoo.com/mrss/", IsNullable=false)]  
 public partial class group {  
   private groupContent[] contentField;  
   /// <remarks/>  
   [System.Xml.Serialization.XmlElementAttribute("content")]  
   public groupContent[] content {  
     get {  
       return this.contentField;  
     }  
     set {  
       this.contentField = value;  
     }  
   }  
 }  
Use the XmlElement tag and specify the namespace in the parent node
   /// <remarks/>  
   public string pubDate {  
     get {  
       return this.pubDateField;  
     }  
     set {  
       this.pubDateField = value;  
     }  
   }  
   [XmlElement("group", Namespace = "http://search.yahoo.com/mrss/")]  
   public group group  
   {  
     get  
     {  
       return this.groupField;  
     }  
     set  
     {  
       this.groupField = value;  
     }  
   }  
 }  
Note: If you want to use the Visual Studio xsd.exe to generate the C# class, you need to strip off the elements with different namespace for xsd.exe to work. You can add the separate elements manually after.

14 April 2019

C++ Use Boost property_tree to manipulate xml files


#include "pch.h"
#include <iostream>
#include <string>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>

using namespace std;
int main()
{
 string path = "C:\\Work\\Students.xml";
 string path2 = "C:\\Work\\Students2.xml";
 try
 {
  std::cout << "Using property tree to manipulate XML files\n";
  //how to load an xml file
  boost::property_tree::ptree pt;
  read_xml(path, pt);

  boost::property_tree::ptree& Students = pt.get_child("Students");

  //how to remove a node using Id
  for (auto it = Students.begin(); it != Students.end();)
  {
   int id = it->second.get(".Id");
   if (id == 1)
   {
    it = Students.erase(it);
    
   }
   else
   {
    ++it;
   }
  }
  //how to add nodes
  for (auto data : { 3, 4, 5 })
  {
   boost::property_tree::ptree& Student = Students.add("Student", "");
   Student.add(".Id", data);
   Student.add("LastName", "McDonalds");
   Student.add("FirstName", "Robert");
  }

  //how to save
  write_xml(path2, pt, std::locale(), boost::property_tree::xml_writer_make_settings('\t', 1));

 }
 catch (exception e)
 {
  string s = e.what();
  std::cout << s;
 }
}