2009年7月22日 星期三

部落格使用table出現一堆

問: 我在文章裡放入表格時,出現了多餘的空白行。 我要如何刪除這些空白行?
答: 空白行是因為 Blogger 會在您文章的每行結尾插入<br />標記,這可在 設定 -> 格式 -> 轉換分行符號 中設定
Reference:
http://www.google.com/support/blogger/bin/answer.py?hl=b5&answer=41592

2009年7月21日 星期二

visual studio常用熱鍵(hotkey)

我個人常用的visual studio 2008熱鍵一覽表

Table 1: Visual Studio Hotkeys/Default Keybindings/Shortcut keys
基本設定
清單顯示熱鍵 Tools -> Customize... -> Toolbars -> Show shortcut keys in Screen Tips
源碼顯示行號 Tools -> Options... -> Text Editor -> C/C++ -> Display -> Line numbers
Build/Compile
Build CTRL+SHIFT+B or F7
Build CTRL+SHIFT+B or F7
Build CTRL+SHIFT+B or F7
Build CTRL+SHIFT+B or F7
Debugging/Running
Start with Debug F5
Debug.StartWithoutDebugging Global::Ctrl+F5
Toggle/Untoggle Breakpoint F9
Navigation
Edit.GoToDefinition F12 Go to definition
Edit.GoToReference Shift-F12 Finds a reference to the selected item or the item under the cursor.
Edit.GoToDeclaration Ctrl-F12 Displays the declaration of the selected symbol in the code.
Edit.GoTo Global::Ctrl+G Displays the Go to Line dialog. If the debugger is running, the dialog also lets you specify addresses or function names to go to.
Edit.GotoBrace Ctrl-] Moves the cursor to the matching brace in the document. If the cursor is on an opening brace, this will move to the corresponding closing brace and vice versa.
Edit.DocumentEnd Ctrl-End Moves the cursor to the end of the document.
Edit.DocumentStart Ctrl-Home Moves the cursor to the start of the document.
Edit.ToggleBookmark Ctrl+K, Ctrl+K or Ctrl+F2 Sets or removes a bookmark at the current line.
Edit.ClearBookmarks Text Editor::Ctrl+K, Ctrl+L Removes all unnamed bookmarks in the current document.
Edit.NextBookmark Text Editor::Ctrl+K, Ctrl+N or F2 Moves to the next bookmark in the document.
Edit.PreviousBookmark Text Editor::Ctrl+K, Ctrl+P Moves to the previous bookmark.
View.TaskList Ctrl+\, Ctrl+T Displays the TaskList window, which displays tasks, comments, shortcuts, warnings, and error messages.
Edit.ToggleTaskListShortcut Ctrl-K, Ctrl-H Sets or removes a shortcut in the tasklist to the current line.
Edit.ScrollLineDown Ctrl+Down Arrow Scrolls text down one line but does not move the cursor. This is useful for scrolling more text into view without losing your place. Available only in text editors.
Edit.ScrollLineUp Ctrl+Up Arrow Scrolls text up one line but does not move the cursor. Available only in text editors.
Edit.WordNext Ctrl+Right Arrow Moves the cursor one word to the right.
Edit.WordPrevious Ctrl+Left Arrow Moves the cursor one word to the left.
Edit.SelectCurrentWord Ctrl-W Selects the word containing the cursor or the word to the right of the cursor.
Code View
Edit.CollapsetoDefinitions Ctrl+M, Ctrl+O Automatically determines logical boundaries for creating regions in code, such as procedures, and then hides them. This collapses all such regions in the current document.
Edit.StopHidingCurrent Ctrl-M, Ctrl-U Removes the outlining information for the currently selected region.
Edit.StopOutlining Ctrl-M, Ctrl-P Removes all outlining information from the entire document.
Search and Replace
Edit.Find Ctrl-F Displays the Find dialog.
Edit.FindinFiles Ctrl-Shift-F Displays the Find in Files dialog.
Edit.FindNext F3 Finds the next occurrence of the previous search text.
Edit.FindPrevious Shift-F3 Finds the previous occurrence of the search text.
Edit.FindNextSelected Ctrl-F3 Finds the next occurrence of the currently selected text or the word under the cursor if there is no selection.
Edit.FindPreviousSelected Ctrl-Shift-F3 Finds the previous occurrence of the currently selected text or the word under the cursor.
Edit.Replace Global::Ctrl+H Displays the Replace dialog.
Edit.ReplaceinFiles Ctrl+Shift+H Displays the Replace in Files dialog.
Edit.IncrementalSearch Ctrl+I Starts an incremental search—after pressing Ctrl-I, you can type in text, and for each letter you type, VS.NET will find the first occurrence of the sequence of letters you have typed so far. This is a very convenient facility, as it lets you find text by typing in exactly as many characters as are required to locate the text and no more. If you press Ctrl-I a second time without typing any characters, it recalls the previous pattern. If you press it a third time or you press it when an incremental search has already found a match, VS.NET searches for the next occurrence.
Edit.ReverseIncrementalSearch Ctrl+Shift+I Performs an incremental search in reverse direction.
Edit.FindSymbol ALT+F12 Displays the Find Symbol dialog.
Edit.QuickFindSymbol Global::Shift+Alt+F12 Displays the Find Symbol Results window.
Window
Next IDE Window CTRL+F6 or Ctrl+Tab
IntelliSense
Edit.CompleteWord CTRL+SPACE or ALT+RIGHT ARROW Completes the current word or shows the IntelliSense completion list.
Edit.ListMembers Ctrl-J Lists members for statement completion when editing code.
Edit.QuickInfo CTRL+K, CTRL+I Displays the complete declaration of the identifier under cursor.
Editing
Edit.Comment-Selection CTRL+K, CTRL+C Comments selected text.
Edit.Uncomment-Selection CTRL+K, CTRL+U Uncomments selected text.
Edit.Cut Global::Shift+Del Cut the entire row from the document and past it to the clipboard.
Edit.LineCut Ctrl-L Cuts all selected lines or the current line if nothing has been selected to the clipboard.
Edit.WordDeleteToEnd Ctrl-Delete Deletes the word to the right of the cursor.
Edit.WordDeleteToStart Ctrl-Backspace Deletes the word to the left of the cursor.
Edit.LineOpenAbove Ctrl-Enter Inserts a blank line above the cursor.
Edit.LineOpenBelow Ctrl-Shift-Enter Inserts a blank line below the cursor.
Edit.WordTranspose Ctrl+Shift+T Moves the word containing the cursor after the next word.
Edit.LineTranspose Shift+Alt+T Moves the line containing the cursor below the next line.
Edit.MakeLowercase Ctrl-U Changes the selected text to lowercase characters.
Edit.MakeUppercase Ctrl-Shift-U Changes the selected text to uppercase characters.
Edit.FormatSelection Text Editor::Ctrl+K, Ctrl+F or Alt+F8 Format the code in the window to be nicely indented.
Edit.Insert Insert Toggles between insert and overtype insertion modes.
Reference:
http://dotnetbutchering.blogspot.com/2008/02/net-top-5-visual-studio-hotkeys.html http://www.mssoftwareconsulting.com/msswc/blog/post/Reformat-Code-in-Visual-Studio.aspx http://www.dofactory.com/ShortCutKeys/ShortCutKeys.aspx

Windows Socket Server/Client with Visual C++

/* Blocking Sockets in TCP/IP (The Server) */
#include <iostream>
#include <string>
#include <string.h>
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")
#define WSA_VERSION MAKEWORD(2, 2) // using winsock 2.2

using namespace std;

class TcpServer{
public:
 class InitSocketError{};
 class CreateSocketError{};
 class BindSocketError{};

 TcpServer()
 {
  initWinsock();
  _socket = tcpSocket();
  listenSocket(8888);
 }

 TcpServer(u_short port)
 {
  initWinsock();
  _socket = tcpSocket();
  listenSocket(port);
 }

 ~TcpServer()
 {
  endSocket();
 }

 SOCKET getSocket(){ return _socket; }
 void sendMessage();
private:
 SOCKET _socket;

 bool initWinsock();
 SOCKET tcpSocket();
 void listenSocket(u_short);
 void endSocket();

};

bool TcpServer::initWinsock()
{
 // Initialise Winsock
 WSADATA WsaData = { 0 };
 if(WSAStartup(WSA_VERSION, &WsaData) != 0)
 {
  // Tell the user that we could not find a usable WinSock DLL.
  if(LOBYTE(WsaData.wVersion) != LOBYTE(WSA_VERSION) ||
   HIBYTE(WsaData.wVersion) != HIBYTE(WSA_VERSION)){
    throw InitSocketError();
  }
  WSACleanup();
  system("PAUSE");
  return false;
 }
 return true;
}

SOCKET TcpServer::tcpSocket()
{
 _socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
 if(_socket==INVALID_SOCKET)
 {
  throw CreateSocketError();
  WSACleanup();
  system("PAUSE");
  return 0;
 }
 return _socket;
}

void TcpServer::listenSocket(u_short port)
{
 SOCKADDR_IN serverInf;
 serverInf.sin_family=AF_INET;
 serverInf.sin_addr.s_addr=INADDR_ANY;
 serverInf.sin_port=htons(port);

 if(bind(_socket,(SOCKADDR*)(&serverInf),sizeof(serverInf))==SOCKET_ERROR)
 {
  throw BindSocketError();
  WSACleanup();
  system("PAUSE");
  return;
 }
 listen(_socket,1);
}

void TcpServer::sendMessage()
{
 SOCKET TempSock=SOCKET_ERROR;
 while(TempSock==SOCKET_ERROR)
 {
  cout<<"Waiting for incoming connections...\r\n";
  TempSock=accept(_socket,NULL,NULL);
 }
 _socket=TempSock;

 cout<<"Client connected!\r\n\r\n";

 char *szMessage="Welcome to the server!\r\n";
 send(_socket, szMessage, strlen(szMessage), 0);
}


void TcpServer::endSocket()
{
 // Shutdown our socket
 shutdown(_socket, SD_SEND);
 // Close our socket entirely
 closesocket(_socket);
 // Cleanup Winsock
 WSACleanup();
}

int main()
{
 try{
  TcpServer *ts1 = new TcpServer(8888);
  ts1->sendMessage();  
  system("PAUSE");
 }catch(TcpServer::InitSocketError){
  cout<<"Winsock error - Winsock initialization failed\r\n";
  system("PAUSE");
 }catch(TcpServer::CreateSocketError){
  cout<<"Winsock error - Socket creation Failed, ec: "<<WSAGetLastError()<<endl;
  system("PAUSE");
 }catch(TcpServer::BindSocketError){
  std::cout<<"Unable to bind socket!\r\n";
  system("PAUSE");
 }

 return 0;
}
/* Blocking Sockets in TCP/IP (The Client) */
#include <iostream>
#include <string>
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")
#define WSA_VERSION MAKEWORD(2, 2) // using winsock 2.2

using namespace std;


class TcpClient
{
public:
 class InitSocketError{};
 class CreateSocketError{};
 class GetHostNameError{};
 class ConnectSocketError{};

 TcpClient()
 {
  string hostname = "localhost";
  initWinsock();
  _socket = tcpSocket();
  connectSocket(hostname, 8888);
 }

 TcpClient(string hostname, u_short hostport)
 {
  initWinsock();
  _socket = tcpSocket();
  connectSocket(hostname, hostport);
 }

 ~TcpClient()
 {
  endSocket();
 }

 SOCKET getSocket() { return _socket; }
 void recevMessage();

private:
 SOCKET _socket;

 bool initWinsock();
 SOCKET tcpSocket();
 bool connectSocket(string&, u_short);
 void endSocket();
};

bool TcpClient::initWinsock()
{
 // Initialise Winsock
 WSADATA WsaData = { 0 };
 if(WSAStartup(WSA_VERSION, &WsaData) != 0)
 {
  // Tell the user that we could not find a usable WinSock DLL.
  if(LOBYTE(WsaData.wVersion) != LOBYTE(WSA_VERSION) ||
   HIBYTE(WsaData.wVersion) != HIBYTE(WSA_VERSION)){
    throw InitSocketError();
  }

  WSACleanup();
  system("PAUSE");
  return false;
 }
 return true;
}

SOCKET TcpClient::tcpSocket()
{
 SOCKET tsocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
 if(tsocket == INVALID_SOCKET)
 {
  throw CreateSocketError();
  WSACleanup();
  system("PAUSE");
  return 0;
 }
 return tsocket;
}

bool TcpClient::connectSocket(string& hostname, u_short hostport)
{
 // Resolve IP address for hostname
 struct hostent *host;
 if((host=gethostbyname(hostname.c_str()))==NULL)
 {
  throw GetHostNameError();
  WSACleanup();
  system("PAUSE");
  return false;
 }

 // Setup our socket address structure
 SOCKADDR_IN SockAddr;
 SockAddr.sin_port=htons(hostport);
 SockAddr.sin_family=AF_INET;
 SockAddr.sin_addr.s_addr=*((unsigned long*)host->h_addr);

 // Attempt to connect to server
 if(connect(_socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr))!=0)
 {
  throw ConnectSocketError();
  WSACleanup();
  cout<<"exe\n";
  system("PAUSE");
  return false;
 }
 return true;
}

void TcpClient::recevMessage()
{
 // Display message from server
 char buffer[1000];
 memset(buffer,0,999);
 int inDataLength=recv(_socket, buffer, 1000, 0);
 cout<<buffer;
}

void TcpClient::endSocket()
{
 // Shutdown our socket
 shutdown(_socket, SD_SEND);
 // Close our socket entirely
 closesocket(_socket);
 // Cleanup Winsock
 WSACleanup();
}


int main()
{
 try{

  TcpClient *tc2 = new TcpClient("smtp.gmail.com", 587);
  tc2->recevMessage();

  TcpClient *tc1 = new TcpClient();
  tc1->recevMessage();

  system("PAUSE");
 }catch(TcpClient::InitSocketError){
  cout<<"Winsock error - Winsock initialization failed\r\n";
  system("PAUSE");
 }catch(TcpClient::CreateSocketError){
  cout<<"Winsock error - Socket creation Failed, ec: "<<WSAGetLastError()<<endl;
  system("PAUSE");
 }catch(TcpClient::GetHostNameError){
  cout<<"Failed to resolve hostname.\r\n";
  system("PAUSE");
 }catch(TcpClient::ConnectSocketError){
  std::cout<<"Failed to establish connection with server\r\n";
  system("PAUSE");
 }
 return 0;
}
/**********************************************
Non-Blocking Sockets in TCP/IP (The Server)
1) Initialise Winsock
2) Create a Socket
3) Fill out a SOCKADDR_IN struct
4) Listen on our socket
5) Accept a connection from the client 
***********************************************/

#include <iostream>
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")
#define WSA_VERSION MAKEWORD(2, 2) // using winsock 2.2

int main()
{
 WSADATA WsaDat;
 if(WSAStartup(WSA_VERSION, &WsaDat)!=0)
 {
  std::cout<<"WSA Initialization failed!\r\n";
  WSACleanup();
  system("PAUSE");
  return 0;
 }

 SOCKET Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
 if(Socket==INVALID_SOCKET)
 {
  std::cout<<"Socket creation failed.\r\n";
  WSACleanup();
  system("PAUSE");
  return 0;
 }

 SOCKADDR_IN serverInf;
 serverInf.sin_family=AF_INET;
 serverInf.sin_addr.s_addr=INADDR_ANY;
 serverInf.sin_port=htons(8888);

 if(bind(Socket,(SOCKADDR*)(&serverInf),sizeof(serverInf))==SOCKET_ERROR)
 {
  std::cout<<"Unable to bind socket!\r\n";
  WSACleanup();
  system("PAUSE");
  return 0;
 }

 listen(Socket,1);

 SOCKET TempSock=SOCKET_ERROR;
 while(TempSock==SOCKET_ERROR)
 {
  std::cout<<"Waiting for incoming connections...\r\n";
  TempSock=accept(Socket,NULL,NULL);
 }

 // If iMode!=0, non-blocking mode is enabled.
 u_long iMode=1;
 ioctlsocket(Socket,FIONBIO,&iMode);

 Socket=TempSock;
 std::cout<<"Client connected!\r\n\r\n";

 // Main loop
 for(;;)
 {
  char *szMessage="Welcome to the server!\r\n";
  send(Socket,szMessage,strlen(szMessage),0);

  int nError=WSAGetLastError();
  if(nError!=WSAEWOULDBLOCK&&nError!=0)
  {
   std::cout<<"Winsock error code: "<<nError<<"\r\n";
   std::cout<<"Client disconnected!\r\n";

   // Shutdown our socket
   shutdown(Socket,SD_SEND);

   // Close our socket entirely
   closesocket(Socket);

   break;
  }

  Sleep(1000);
 }

 WSACleanup();
 system("PAUSE");
 return 0;
}
/* Non-Blocking Sockets in TCP/IP (The Client) */
#include <iostream>
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")

#define WSA_VERSION MAKEWORD(2, 2) // using winsock 2.2
using namespace std;

class NonBlockTcpClient
{
public:
 class CreateSocketError{};
 class GetHostNameError{};
 class ConnectSocketError{};
 NonBlockTcpClient()
 {
  string hostname = "localhost";
  _socket = tcpSocket();
  connectSocket(hostname, 8888);
 }
 NonBlockTcpClient(string hostname, u_short hostport)
 {
  _socket = tcpSocket();
  connectSocket(hostname, hostport);
 }
 void sendMessage();
private:
 SOCKET _socket;

 SOCKET tcpSocket();
 bool connectSocket(string&, u_short);
};


SOCKET NonBlockTcpClient::tcpSocket()
{
 // Create our socket

 SOCKET Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
 if(Socket==INVALID_SOCKET)
 {
  throw CreateSocketError(); 
  return 0;
 }
 return Socket;
}

bool NonBlockTcpClient::connectSocket(string& hostname, u_short hostport)
{
 // Resolve IP address for hostname
 struct hostent *host;
 if((host=gethostbyname(hostname.c_str()))==NULL)
 {
  throw GetHostNameError();
  return false;
 }

 // Setup our socket address structure
 SOCKADDR_IN SockAddr;
 SockAddr.sin_port=htons(hostport);
 SockAddr.sin_family=AF_INET;
 SockAddr.sin_addr.s_addr=*((unsigned long*)host->h_addr);

 // Attempt to connect to server
 if(connect(_socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr))!=0)
 {
  throw ConnectSocketError();
  return false;
 }

 // If iMode!=0, non-blocking mode is enabled.
 u_long iMode=1;
 ioctlsocket(_socket,FIONBIO,&iMode);
 return true;
}

void NonBlockTcpClient::sendMessage()
{
 // Main loop
 for(;;)
 {
  // Display message from server
  char buffer[1000];
  memset(buffer,0,999);
  int inDataLength=recv(_socket,buffer,1000,0);
  std::cout<<buffer;

  int nError=WSAGetLastError();
  if(nError!=WSAEWOULDBLOCK&&nError!=0)
  {
   std::cout<<"Winsock error code: "<<nError<<"\r\n";
   std::cout<<"Server disconnected!\r\n";
   // Shutdown our socket
   shutdown(_socket,SD_SEND);

   // Close our socket entirely
   closesocket(_socket);

   break;
  }
  Sleep(1000);
 }
}

int main(void)
{
 /* initialize winsock */
 WSADATA WsaDat;
 if(WSAStartup(WSA_VERSION, &WsaDat)!=0)
 {
  std::cout<<"Winsock error - Winsock initialization failed\r\n";
  WSACleanup();
  system("PAUSE");
  return 0;
 }

 try{

  //NonBlockTcpClient *nbtc = new NonBlockTcpClient("smtp.gmail.com", 587); 
  //nbtc->sendMessage();
  NonBlockTcpClient *nbtcl = new NonBlockTcpClient(); 
  nbtcl->sendMessage();
 }catch(NonBlockTcpClient::CreateSocketError){
  cout<<"Winsock error - Socket creation Failed!\r\n";
  WSACleanup();
  system("PAUSE");
 }catch(NonBlockTcpClient::GetHostNameError){
  cout<<"Failed to resolve hostname.\r\n";
  WSACleanup();
  system("PAUSE");
 }catch(NonBlockTcpClient::ConnectSocketError){
  cout<<"Failed to establish connection with server\r\n";
  WSACleanup();
  system("PAUSE");
 }

 /* clean winsock */
 WSACleanup();
 system("PAUSE");
 return 0;
}

2009年7月16日 星期四

A simple program using smtp for sending gmail

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#using <System.dll>

using namespace System;
using namespace System::Net::Sockets;
using namespace System::Collections;
using namespace System::Collections::Generic;
using namespace System::Text;
using namespace System::IO;
using namespace System::Net;
using namespace System::Net::Mail;
using namespace System::Net::Mime;
using namespace System::Threading;
using namespace System::ComponentModel;

namespace GMailSend
{
 //array: http://msdn.microsoft.com/zh-tw/library/ms235236.aspx
 void Send(String^ from, String^ to, String^ subject, String^ body, 
  array<System::String ^>^ cc, int cc_num, array<System::String ^>^ bcc, int bcc_num, String^ host, int port, 
  String^ smtpUsername, String^ smtpPassword)
 {
  // Create mail message
  MailMessage^ message = gcnew MailMessage(from, to, subject, body);
  message->BodyEncoding = System::Text::Encoding::UTF8;

  if (cc != nullptr && cc_num > 0)
  {
   for(int i=0; i<cc_num; i++)
   {
    message->CC->Add(gcnew MailAddress(cc[i]));
   }
  }
  if (bcc != nullptr && bcc_num > 0)
  {
   for(int i=0; i<bcc_num; i++)
   {
    message->Bcc->Add(gcnew MailAddress(bcc[i]));
   }
  }

  // Send email
  SmtpClient^ client = gcnew SmtpClient(host, port);
  if (!String::IsNullOrEmpty(smtpUsername) && !String::IsNullOrEmpty(smtpPassword))
  {
   client->Credentials = gcnew NetworkCredential(smtpUsername, smtpPassword);
  }
  client->EnableSsl = true;
  client->Send(message);
 }

}

int _tmain(int argc, _TCHAR* argv[])
{


 GMailSend::Send("from@gmail.com","to@hotmail.com",  "testsubject", "testbodymessage", nullptr, 0, nullptr, 0, 
  "smtp.gmail.com", 587, "gmail_account", "gmail_password");


 system("pause");
 return 0;
}
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#using <System.dll>

using namespace System;
using namespace System::Net::Sockets;
using namespace System::Collections;
using namespace System::Collections::Generic;
using namespace System::Text;
using namespace System::IO;
using namespace System::Net;
using namespace System::Net::Mail;
using namespace System::Net::Mime;
using namespace System::Threading;
using namespace System::ComponentModel;


#define GMail_DEBUG

String^ showUsage() {
 StringBuilder^ sb = gcnew StringBuilder();

 sb->AppendLine( "Usage: MailSharp [options] ToAddress" );
 sb->AppendLine( "\t-a File to attach." );
 sb->AppendLine( "\t-f From address" );
 sb->AppendLine( "\t-b Body message" );
 sb->AppendLine( "\t-s Subject");
 sb->AppendLine( "\t-S SMTP server host" );
 sb->AppendLine( "\t-U Username for SMTP server authentication" );
 sb->AppendLine( "\t-p Password for SMTP server authentication" );
 sb->AppendLine( "\t-P SMTP server port" );
 sb->AppendLine( "\t-l Use SSL" );
 sb->AppendLine( "\t-h Help/Usage");
 sb->AppendLine();
 sb->AppendLine( "Example:" );
 sb->AppendLine( "\tFor GMail" );
 sb->AppendLine( "\tMailSharp -f your_name@gmail.com -b MessageBody -s TestSubject -S smtp.gmail.com -P 587 -l -U your_gmail -p your_gmail_password -t someone@somewhere.com" );
#ifdef GMail_DEBUG 
 // Display the number of characters in the StringBuilder and its string.
 Console::WriteLine("{0} chars: {1}", sb->Length, sb->ToString());
#endif

 return sb->ToString();
}




int _tmain(int argc, _TCHAR* argv[])
{

 //showUsage();
 MailAddress^ from = nullptr;
 MailAddress^ to = nullptr;
 MailMessage^ message = gcnew MailMessage();
 SmtpClient^ client = gcnew SmtpClient();
 NetworkCredential^ myCred = gcnew NetworkCredential();
 bool bShowUsage=false;

 try{
  if ( argc > 0 ) {
   for ( int i=0; i<argc; i++ ) {
    if( argv[i][0] == '-' ){
     switch ( argv[i][1] ) {
     case 'S': // server host
      i++;
      if ( i<argc ) {
       client->Host = gcnew String(argv[i]);
      } else
       throw gcnew Exception( "-S was specified, but no value." );
      break;
     case 'P': // server port
      i++;
      if ( i<argc ) {
       client->Port= Convert::ToInt32( gcnew String(argv[i]) );
      } else
       throw gcnew Exception( "-P was specified, but no value." );
      break;
     case 'T': // timeout
      i++;
      if ( i<argc ) {
       client->Timeout = Convert::ToInt32( gcnew String(argv[i]) );
      } else
       throw gcnew Exception( "-T was specified, but no value." );
      break;
     case 'U': // username for smtp server authentication
      i++;
      if ( i<argc )
       myCred->UserName = gcnew String(argv[i]);
      else
       throw gcnew Exception( "-U was specified, but no value." );
      break;
     case 'p': // password for smtp server authentication
      i++;
      if ( i<argc )
       myCred->Password = gcnew String(argv[i]);
      else
       throw gcnew Exception( "-p was specified, but no value." );
      break;
     case 'l': // use SSL
      client->EnableSsl = true;
      break;
     case 's': // subject
      i++; // next one is subject.
      if ( i<argc ) {
       message->Subject = gcnew String(argv[i]);
       message->SubjectEncoding = System::Text::Encoding::UTF8;
      } else
       throw gcnew Exception( "-s was specified, but no value." );
      break;
     case 'a': // attachment
      i++; // next one is attachment filename.
      if ( i<argc ) {
       // Add attachment.
       Attachment^ data = gcnew Attachment( gcnew String(argv[i]), MediaTypeNames::Application::Octet);
       message->Attachments->Add(data);
      } else
       throw gcnew Exception( "-a was specified, but no value." );
      break;
     case 'b': // body message.
      i++; // next one is body message
      if ( i<argc ) {
       message->Body = gcnew String(argv[i]);
       message->BodyEncoding =  System::Text::Encoding::UTF8;
      } else
       throw gcnew Exception( "-b was specified, but no value." );
      break;
     case 'f': // from address
      i++;
      if ( i<argc ) {
       // Specify the e-mail sender.
       // Create a mailing address that includes a UTF8 character
       // in the display name.
       // from = new MailAddress( "someone@gmail.com", "someone", System.Text.Encoding.UTF8);
       from = gcnew MailAddress( gcnew String(argv[i]) );
      } else
       throw gcnew Exception( "-f was specified, but no value." );
      break;
     case 'h': // show help/usage
      bShowUsage=true;
      break;
     case 't':
      i++;
      to = gcnew MailAddress( gcnew String(argv[i]) );
      break;
     }//end of switch
    }//end of check '-'
   }//end of for
  } else
   throw gcnew Exception("No arguments.");
 }catch(Exception^ ex){
  Console::WriteLine( ex->Message );
  bShowUsage = true;
 }

 try {
  if ( bShowUsage == true )
   throw gcnew Exception( showUsage() );

  if ( from==nullptr )
   throw gcnew Exception( "Must specify from address (-f)." );

  // Set destinations for the e-mail message.
  if ( to == nullptr )
   throw gcnew Exception("At least, must specify to address");

  if ( client->Host == String::Empty )
   throw gcnew Exception("Must specify SMTP Server (-S)." );

  // Specify the message content.
  message->From = from;
  message->To->Add( to );

  // Credentials are necessary if the server requires the client
  // to authenticate before it will send e-mail on the client's behalf.
  //client.UseDefaultCredentials = false;
  client->Credentials = myCred;

  // Send.
  // If you need asynchronous sample, please visit the reference above.
  client->Send(message);

  Console::WriteLine("Done.");
 } catch ( Exception^ ex ) {
  Console::WriteLine( "Exception was raised when sending...");
  Console::WriteLine( ex->Message );
 } finally {
  // Clean up.
  message->~MailMessage();
 }


 system("pause");
 return 0;
}

parse command line in Win32 API

#include "stdafx.h"
#include <stdio.h>
#include <string>
#include <stdlib.h>

// 出處:http://www.codeguru.com/cpp/w-p/win32/comments.php/c1427/?thread=3545
// A Simple Win32 Command-Line Parser

#include <windows.h>

char **argv = NULL;

/*******************************************************
WIN32 command line parser function
********************************************************/
int ParseCommandline()
{
 int    argc, BuffSize, i;
 WCHAR  *wcCommandLine;
 LPWSTR *argw;

 // Get a WCHAR version of the parsed commande line
 wcCommandLine = GetCommandLineW(); 
 argw = CommandLineToArgvW( wcCommandLine, &argc);

 // Create the first dimension of the double array
 argv = (char **)GlobalAlloc( LPTR, argc + 1 );

 // convert eich line of wcCommandeLine to MultiByte and place them
 // to the argv[] array
 for( i=0; i<argc; i++)
 {
  BuffSize = WideCharToMultiByte( CP_ACP, WC_COMPOSITECHECK, argw[i], -1, NULL, 0, NULL, NULL );
  argv[i] = (char *)GlobalAlloc( LPTR, BuffSize );  
  WideCharToMultiByte( CP_ACP, WC_COMPOSITECHECK, argw[i], BuffSize * sizeof( WCHAR ) ,argv[i], BuffSize, NULL, NULL );
 }

 // return the number of argument
 return argc;
}

//Command Line argument parsing 
//linux: getopt
//windows ?
int main( int argc, char **argv ) {
 argc = ParseCommandline();
 for(int i=0; i<argc; i++){
  printf("%s\n", argv[i]);
 }
 system("pause");
 return 0;
} 

port scanner/firewall

Port Scan wiki: http://en.wikipedia.org/wiki/Port_scanner background: http://en.wikipedia.org/wiki/Internet_Protocol_Suite common application ports: http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers tools: http://en.wikipedia.org/wiki/Nmap keyword: ICMP(關掉可以防一些port scan?) 查看Ports的方法: windows: 指令:netstat[-a] [-e] [-n] [-s] [-p protocol] [-r] [interval] C:>netstat -a (可查看所有與電腦的連線狀態,不過太繁雜了) C:>netstat -p tcp (可查看與電腦的tcp的連線狀態) C:>netstat -p udp (可查看與電腦的udp的連線狀態) Linux: 指令:netstat(本機端) yslinnote@~> netstat -t (可查看與電腦的tcp的連線狀態) yslinnote@~> netstat -u (可查看與電腦的udp的連線狀態) 指令:nmap(遠端) nmap localhost(查詢自己所有開放的port,結果與netstat類似)   nmap IP(查詢某特定IP開放的port)   nmap 192.168.1.0(查詢192.168.1.0~192.168.1.254開放的port)   nmap 192.168.0-10(查詢192.168.1.0~192.168.1.10開放的port)   nmap -sT/-sU IP(查詢某特定IP開放有關TCP/UDP的port) simple code: 參考來源: http://indeepnight.blogspot.com/2007/05/port-scanner.html

perl

# 純量陣列以 @ 開頭。
my @array;
my @array=qw(a b c d);

# qw 函數會將其後的每個元素用逗點隔開,效果就像下面這行。
my @array=("a","b","c","d");

# 當然你也可以一個個元素宣告,下面就是存取每一個元素的方法。
# 因為陣列中的每一個元素都是純量變數,所以要以 $ 開頭,
# 剛開始容易搞混,請注意。
$array[0]="a"; $array[1]="b"; $array[2]="c"; $array[3]="d";

# 使用for loop印出陣列內每個元素的值。
for($i=0; $i<=$#array; $i++) {
print "$array[$i]\n";
}

2009年7月15日 星期三

如何貼上彩色的source code到blogger上

1.vim的方法 產生html格式的.vimrc,打開vim輸入下列指令 :runtime! syntax/2html.vim 2.c# code format http://www.manoli.net/csharpformat/ 3.C++2HTML http://www.bedaux.net/cpp2html/ 4.CppToHtml http://www.dynawest.cz/cpptohtml/ 5.CodeHighlighter http://www.actiprosoftware.com/Products/DotNet/ASPNET/CodeHighlighter/pastecode.aspx 6.SyntaxHighlighter http://code.google.com/p/syntaxhighlighter/ 教學: http://blog.xuite.net/joy715/blog/13350414 http://sharedderrick.blogspot.com/2007/12/blogger-syntaxhighlighter.html http://screamlab-ncku-2008.blogspot.com/2009/03/blog-syntaxhighlighter.html 支援語言一覽 http://alexgorbatchev.com/wiki/SyntaxHighlighter:Brushes 我個人偏好6.SyntaxHighlighter 並且使用 http://centricle.com/tools/html-entities/來將code轉成html語法

test c# code


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace WindowsFormsApplication4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent("");
          printf("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
        }

    }
}
fffff
function test() : String
{
printf("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");

 return 10;
}

2009年7月13日 星期一

visual C++的String^, std::string, char *的互相轉換

Unmanaged to Managed: ------------------------------------ char* su; String^ sm = gcnew String(su); wchar_t* su; String^ sm = gcnew String(su); std::string su; String^ sm = gcnew String(su.c_str()); std::wstring su; String^ sm = gcnew String(su.c_str()); Managed to Unmanaged: ------------------------------------ Wide string version: String^ sm = "Hello"; pin_ptr pu = PtrToStringChars(sm); // PtrToStringChars is an inline function in vcclr.h, and it returns // a raw pointer to the internal representation of the String. // After pinning "p", it can be passed to unmanaged code: wchar_t* su = pu; // when "pu" goes out of scope, "su" becomes invalid! Ansi (8-bit) version: ScopedHGlobal s_handle(Marshal::StringToHGlobalAnsi(sm)); char* su = s_handle.c_str(); // when "s_handle" goes out of scope, "su" becomes invalid! Where ScopedHGlobal is a helper class written by myself: using namespace System::Runtime::InteropServices; public ref class ScopedHGlobal { public: ScopedHGlobal(IntPtr p) : ptr(p) { } ~ScopedHGlobal() { Marshal::FreeHGlobal(ptr); } char* c_str() { return reinterpret_cast(ptr.ToPointer()); } private: System::IntPtr ptr; }; 參考 http://www.pcreview.co.uk/forums/thread-2221676.php

2009年6月29日 星期一

個人vim常用指令列表

command


"常用指令 "[K] "函式查詢 "若您在 VIM 中撰寫 C/C++ 程式,可以在 C/C++ 標準函式厙提供的函式名字上按「K」,便可以呼叫出 man page "[=] "自動程式縮排對齊 "若您在 VIM 中撰寫 C/C++ "程式,可以利用「gg」指令將游標移到視窗最上方、利用「v」切換到選取模式、再用「G」將游標移到檔案尾端 "(即達到全選的功能),最後按「=」,VIM 便會幫你的程式做自動對齊 "[:set all] "顯示所有vim支援的參數 "[:version] "顯示讀取的vimrc順序和路徑 set [cmd]? 查看這個指令的目前設定 補全 CTRL-X CTRL-L 整行补全 CTRL-X CTRL-N 根据当前文件里关键字补全 CTRL-X CTRL-K 根据字典补全 CTRL-X CTRL-T 根据同义词字典补全 CTRL-X CTRL-I 根据头文件内关键字补全 CTRL-X CTRL-] 根据标签补全 CTRL-X CTRL-F 补全文件名 CTRL-X CTRL-D 补全宏定义 CTRL-X CTRL-V 补全vim命令 CTRL-X CTRL-U 用户自定义补全方式 CTRL-X CTRL-S 拼写建议 gQ 進入 Ex 模式,輸入 visual 可以返回正常模式。可以按tab補完 qq 打開紀錄器,再按一次q關閉紀錄,紀錄中無法使用下列查詢歷史指令 q: 打開Ex command-line視窗必且列出所有Ex歷史指令 q/ 打開一個視窗顯示紀錄過的搜尋字串 q? 同上 多窗口命令(:h q_wi) CTRL-W s 或 :split 将窗口分割成两部分 (split) :split {file} 分隔窗口并在其中一个编辑 {file} CTRL-W v 或 :vsplit 将窗口分割成两部分 (vsplit) :vsplit {file} 同上,但垂直分割 :vertical {cmd} 使命令 {cmd} 垂直分割 :sf[ind] {file} 分割窗口,从 {path} 中找到文件 {file} 并编辑之。 CTRL-W ] 分割窗口并跳转到光标下的标签 CTRL-W f 分割窗口并编辑光标下的文件名 (file) CTRL-W ^ 分割窗口并编辑轮换文件 CTRL-W n 或 :new 创建新空白窗口 (new) CTRL-W q 或 :q[uit] 退出编辑并关闭窗口 (quit) CTRL-W c 或 :cl[ose] 隐藏当前缓冲区并关闭窗口 (close) CTRL-W o 或 :on[ly] 使当前窗口成为唯一窗口 (only) CTRL-W j 跳转到下方窗口 CTRL-W k 跳转到上方窗口 CTRL-W CTRL-W 移动光标至下方窗口 (折转) (Wrap) CTRL-W W 移动光标至上方窗口 (折转) (wrap) CTRL-W t 跳转到顶端窗口 (top) CTRL-W b 跳转到底端窗口 (bottom) CTRL-W p 跳转到上一次激活的窗口 (previous) CTRL-W r 向下旋转窗口 (rotate) CTRL-W R 向上旋转窗口 (Rotate) CTRL-W x 将当前窗口与下一个窗口对调 (eXchange) CTRL-W = 使所有窗口等高 CTRL-W - 减少当前窗口高度 CTRL-W + 增加当前窗口高度 CTRL-W _ 设置当前窗口高度 (缺省: 很高) 折叠(:h q_fo) set foldmethod=manual 手动折叠 set foldmethod=indent 按照缩进折叠 set foldmethod=expr 按照表达式 'foldexpr' 折叠 set foldmethod=syntax 按照语法区域折叠 set foldmethod=marker 按照标志 'foldmarkers' 折叠 zf{motion} 操作符: 手动定义一个折叠 (fold) :{range}fold 将范围 {range} 包括的行定义为一个折叠 zd 删除光标下的一个折叠 (delete) zD 删除光标下的所有折叠 (Delete) zo 打开光标下的折叠 (open) zO 打开光标下的所有折叠 (Open) zc 关闭光标下的一个折叠 (close) zC 关闭光标下的所有折叠 (Close) zm 折起更多: 减少 'foldlevel' (more) zM 关闭所有折叠: 置 'foldlevel' 为 0 zr 减少折叠: 增加 'foldlevel' (reduce) zR 打开所有折叠: 置 'foldlevel' 为最大 zn 不折叠: 复位 'foldenable' (none) zN 正常折叠: 置位 'foldenable' (Normal) zi 反转 'foldenable' (invert) diff使用(:h diff) command line進入diff模式 vimdiff file1 file2 [file3 [file4]] 或 vim -d file1 file2 [file3 [file4]] 已在Vim中时,你可以用3种方式进入 diff 模式。 :diffsplit {filename} *:diffs* *:diffsplit* 对 {filename} 开一个新窗口。当前的和新开的窗口被设定了和 "vimdiff" 一样的参数。参考 'diffexpr'。 *:difft* *:diffthis* :diffthis 使当前窗口成为 diff 窗口的一部分。设定了和 "vimdiff" 同样的 参数。 :diffpatch {patchfile} *:diffp* *:diffpatch* 使用当前的缓冲,用 {patchfile} 给它打上补丁并打开一个缓冲显示 结果。设定了和 "vimdiff" 同样的参数。 {patchfile} 可以是任何一种 "patch" 程序认识的或 'patchexpr' 可以处理的格式。 备注: {patchfile} 只能包含一个文件的比较结果,即当前文件的。如 果 {patchfile} 也包含了其他文件的比较,结果将不可预知。Vim 改 变目录到 /tmp 以避免当前目录被意外的打补丁。但它仍可能导致若干 ".rej" 文件产生。当绝对路径名出现时,这些文件可能被打补丁。 要垂直分割窗口,加上 |:vertical|。如: :vert diffsplit main.c :vert diffpatch /tmp/diff 但你改变文本时,Vim 试图使比较保持更新。插入或删除行一般会使 diff 正确的更新。 在一行里的改动和更复杂的改动将不会使比较更新。要强制刷新比较使用: :diffupdate 有两条命令可用于在 diffs 之间跳转: [c 向后至上一个更改的开始。当加上个数字后,便重复执行相应 次。 ]c 向前至下一个更改的开始。当加上个数字后,便重复执行相应 次。 拷貝diffs :[range]diffg[et] [bufspec] 用另一个缓冲来修改当前的缓冲,消除不同之处。如果给定 [bufspec],就使用该缓冲。否则,它仅当有另一个在 diff 模式下 的缓冲时才起作用。 [range] 参考下面。 :[range]diffpu[t] [bufspec] 用当前缓冲来修改另一个缓冲,消除不同之处。就象 ":diffget" 但更改的是另一个缓冲,而不是当前的。 [range] 参考下面。 do 同 ":diffget" 但没有参数和范围。"o" 表示 "obtain" ("dg" 是不能这样使用的。那可能是 "dgg" 的开始!)。 dp 同 ":diffput" 但没有参数和范围。 参数 [bufspec] 可以是一个缓冲的序号,一个缓冲名称或缓冲名称的一部分的模式,如: :diffget 使用另一个进入 diff 模式的缓冲 :diffget 3 使用3号缓冲 :diffget v2 使用缓冲名同 "v2" 匹配的,并进入 diff 模式的( 如,"file.c.v2") 正規表示式(:help pattern) 用:grep或vimgrep來查找檔案內容 :cd ~/src/vim70 :vimgrep /\<main\>/ ./*.c 查所有目前目錄下的.c檔,中含有main的位置 :cw 開啟 要恢复上次的编辑环境,我们需要保存两种不同的信息,一种是会话(session)信息,另外一种是viminfo信息。 * 会话信息中保存了所有窗口的视图,外加全局设置。 * viminfo信息中保存了命令行历史(history)、搜索字符串历史(search)、输入行历史、非空的寄存器内容(register)、文件的位置标记(mark)、最近搜索/替换的模式、缓冲区列表、全局变量等信息。 :mksession [file] '貯存session文件 :source [file] '载入会话文件 :wviminfo [file] '貯存viminfo文件 :rviminfo [file] '读入viminfo文件 :h 'sessionoptions' session file中貯存哪些訊息,是由sessionoptions決定的 :h 21.3 :wviminfo貯存哪些內容與保存的數量,由viminfo決定 ' specify how many files for which you save marks (a-z) f option controls whether global marks (A-Z and 0-9) are stored < option controls how many lines are saved for each of the registers : number of lines to save from the command line history @ number of lines to save from the input line history / number of lines to save from the search history r removable media, for which no marks will be stored (can be used several times) ! global variables that start with an uppercase letter and don't contain lowercase letters h disable 'hlsearch' highlighting when starting % the buffer list (only restored when starting Vim without file arguments) c convert the text using 'encoding' n name used for the viminfo file (must be the last option) quickfix :set makeprg=gcc\ -Wall\ -ohello\ hello.c :make 經過上面步驟產生error可以用下面的顯示 :cc 显示目前指到详细错误信息 ( :help :cc ) :cp 跳到上一个错误 ( :help :cp ) :cp :cprevious :cn 跳到下一个错误 ( :help :cn ) :cN :cNext :cl 列出所有错误 ( :help :cl ) :cl :clist :cw 如果有错误列表,则打开quickfix窗口 ( :help :cw ) :cw :cwindow :col 到前一个旧的错误列表 ( :help :col ) :colder :col :cnew 到后一个较新的错误列表 ( :help :cnew ) :cnewer :cnew 產生html格式的.vimrc :runtime! syntax/2html.vim

note


a.vim : Alternate Files quickly (.c --> .h etc) [ 版本與更新日期 ] a.vim 2.18 2007-06-07 [ 插件的功能 ] A few of quick commands to swtich between source files and header files quickly. [ 插件的下載地址 ] http://www.vim.org/scripts/script.php?script_id=31 [ 備註或特別提醒 ] bufexplorer.zip : Buffer Explorer / Browser [ 版本與更新日期 ] bufexplorer.zip 7.2.2 2008-11-19 [ 插件的功能 ] 列出目前開啟的buffer,可以很容易切換或刪除buffer. 有了tab似乎不在這麼需要 :tab ball (可以把所有buffer轉成tab開啟) [ 插件的下載地址 ] http://www.vim.org/scripts/script.php?script_id=42 c.vim : C/C++ IDE -- Write and run programs. Insert statements, idioms, comments etc. [ 版本與更新日期 ] cvim.zip 5.5 2009-02-17 [ 插件的功能 ] 自動compile和run還有簡易輸入各種statements和comments [ 插件的下載地址 ] http://vim.sourceforge.net/scripts/script.php?script_id=213 cscope_maps.vim [ 版本與更新日期 ] [ 插件的功能 ] 可以使用<C-]>和<C-T>的熱鍵來收尋c變數的定義與使用的檔案位置 [ 插件的下載地址 ] http://cscope.sourceforge.net/cscope_maps.vim ctags http://ctags.sourceforge.net (可apt-get install) cscope http://cscope.sourceforge.net/ (可apt-get install) [ 備註或特別提醒 ] 需安裝ctags 需安裝cscope taglist.vim : Source code browser (supports C/C++, java, perl, python, tcl, sql, php, etc) [ 版本與更新日期 ] taglist_45.zip 4.5 2007-09-21 [ 插件的功能 ] 實現類或者函數列表功能,支持 C/C++, Java, Perl, Python, TCL, SQL, PHP 等語言,它可以在VIM中創建一個窗口,列出編輯的源文件中的類、 函數、變量定義列表,而且更方便的是這個列表 也插入在了右鍵菜單中,分類存放, 訪問非常方便。 [ 插件的下載地址 ] http://www.vim.org/scripts/script.php?script_id=273 [ 備註或特別提醒 ] 依賴於 Exuberant Ctags,可以在 http://ctags.sourceforge.net 下載。 mru.vim : Plugin to manage Most Recently Used (MRU) files [ 版本與更新日期 ] mru.vim 3.2 2008-09-23 [ 插件的功能 ] manage Most Recently Used (MRU) files [ 插件的下載地址 ] http://www.vim.org/scripts/script.php?script_id=521 genutils : General utility functions [ 版本與更新日期 ] genutils-2.4.zip 2.4 2007-06-12 [ 插件的功能 ] The new version requires Vim 7.0 and it employs the new autoload mechanism. 所以有些新的套件需要用這個plugin裡的函式 [ 插件的下載地址 ] http://www.vim.org/scripts/script.php?script_id=197 lookupfile : Lookup files using Vim7 ins-completion [ 版本與更新日期 ] lookupfile-1.8.zip 1.8 2007-09-13 [ 插件的功能 ] [ 插件的下載地址 ] http://www.vim.org/scripts/script.php?script_id=1581 [ 備註或特別提醒 ] 需要安裝genutils.vim netrw.vim : Network oriented reading, writing, and browsing (keywords: netrw ftp scp) [ 版本與更新日期 ] netrw.vba.gz 135 2009-01-14 (vim 7.0有預設安裝) [ 插件的功能 ] Netrw supports reading and writing files across networks. Browsing directories. [ 插件的下載地址 ] http://www.vim.org/scripts/script.php?script_id=1075 [ 備註或特別提醒 ] 最新版要vim7.2才能裝 [ 版本與更新日期 ] [ 插件的功能 ] [ 插件的下載地址 ] [ 備註或特別提醒 ] SuperTab continued. : Do all your insert-mode completion with Tab. [ 版本與更新日期 ] supertab.vim 0.49 2009-02-05 [ 插件的功能 ] 自动补全直接按Tab就好了,想bash shell一样 [ 插件的下載地址 ] http://www.vim.org/scripts/script.php?script_id=1643 CRefVim : a C-reference manual especially designed for Vim [ 版本與更新日期 ] crefvim.zip 1.0.4 2004-11-28 [ 插件的功能 ] crefvim 查阅C语言参考手册,所有库函数的标准说明。 [ 插件的下載地址 ] http://www.vim.org/scripts/script.php?script_id=614 [ 備註或特別提醒 ] 第一次使用需輸入:helptags ~/.vim/doc ManPageView : Viewer for manpages, gnu info, perldoc, and php (unix/linux/cygwin) [ 版本與更新日期 ] manpageview.vba.gz 22 2008-11-26 7.2 [ 插件的功能 ] manpageview 在vim中查看manpage [ 插件的下載地址 ] http://www.vim.org/scripts/script.php?script_id=489 word_complete.vim : automatically offers word completion as you type [ 版本與更新日期 ] word_complete.vim 1.1 2006-12-06 [ 插件的功能 ] Insert模式下在輸入的時候自動補全單詞,如果補全正確可以按Tab鍵接受, 否則可以不管它繼續輸入或者按Ctrl-n, Ctrl-p切換補全。 注意是輸入三個字符後才開始補全。 [ 插件的下載地址 ] http://www.vim.org/scripts/script.php?script_id=73 Mark : a little script to highlight several words in different colors simultaneously [ 版本與更新日期 ] mark.vim 1.1.8-g 2008-04-25 [ 插件的功能 ] 顯示多個serach的結果,用不同的顏色,提供類似*和#的功能熱鍵 [ 插件的下載地址 ] http://www.vim.org/scripts/script.php?script_id=1238 MultipleSearch : Highlight multiple searches at the same time, each with a different color. [ 版本與更新日期 ] MultipleSearch.zip 1.3 2008-09-23 [ 插件的功能 ] 顯示多個serach的結果,用不同的顏色 [ 插件的下載地址 ] http://www.vim.org/scripts/download_script.php?src_id=9276 SearchComplete : Tab completion of words inside of a search ('/') [ 版本與更新日期 ] SearchComplete.vim 1.1 2002-11-08 [ 插件的功能 ] 按tab自動補齊search字串 [ 插件的下載地址 ] http://www.vim.org/scripts/script.php?script_id=474 FencView.vim : Autodetect multiple encodings [ 版本與更新日期 ] fencview.vim 4.6 2008-12-11 [ 插件的功能 ] 可以自動偵測檔案的encodings [ 插件的下載地址 ] http://www.vim.org/scripts/script.php?script_id=1708 number marks : showing marks using number array in color, easy to trace. [ 版本與更新日期 ] marks_corey.zip 1.2 2008-04-14 [ 插件的功能 ] 這個腳本顯示用帶顏色的數字標明的marks,並且向前或者向後移動。 可以保存到文件,下次可以重現原來在多個文件裡面的marks。 比較清晰顯示你標記的代碼在前後的位置,有數字嘛! [ 插件的下載地址 ] http://www.vim.org/scripts/script.php?script_id=2194    matrix.vim : Matrix screensaver for VIM [ 版本與更新日期 ] matrix.vim 1.10 2008-05-14 [ 插件的功能 ] 駭客任務的入侵畫面,還蠻有趣的,當作螢幕保護程式吧,哈哈 [ 插件的下載地址 ] http://www.vim.org/scripts/script.php?script_id=1189 vcscommand (配合subversion/cvs使用) [ 版本與更新日期 ] [ 插件的功能 ] [ 插件的下載地址 ] [ 備註或特別提醒 ] http://www.vim.org/scripts/script.php?script_id=39 matchit.zip 1.13.2 2008-01-29 [ 版本與更新日期 ] [ 插件的功能 ] [ 插件的下載地址 ] [ 備註或特別提醒 ] http://www.vim.org/scripts/script.php?script_id=90 vcscommand.zip beta29 2009-02-13 [ 版本與更新日期 ] [ 插件的功能 ] [ 插件的下載地址 ] [ 備註或特別提醒 ] http://www.vim.org/scripts/script.php?script_id=1863 tlib.vba.gz 0.31 2009-02-25 7.0 [ 版本與更新日期 ] [ 插件的功能 ] [ 插件的下載地址 ] [ 備註或特別提醒 ] http://www.vim.org/scripts/script.php?script_id=861 Viki.vba.gz 3.11 2009-03-20 need tlib

plugin command


\ : mean it start is a leader , mru.vim (Plugin to manage Most Recently Used (MRU) files) :MRU (list and edit files from the MRU list) o (open the file name under the cursor in the MRU window in a new window) t (open a file from the MRU window in a new tab) u (press the 'u' key in the MRU window to update the file list) q (close the MRU window) :MRU vim (specify a partial file name and only one matching filename is found, then the ":MRU" command will edit that file) :MRU vim<Tab> (enter a partial file name and then press <Tab> to complete file names) :MRU vim<Ctrl-D> (enter a partial file name and then press <Ctrl-D> to list all the matching file names) .vimrc "The list of recently edited file names is stored in the file specified by the MRU_File variable "The default setting for this variable is $HOME/.vim_mru_files for Unix-like systems let MRU_File = 'd:\myhome\_vim_mru_files' "set the 'MRU_Max_Entries' variable to remember more file names let MRU_Max_Entries = 20 "exclude file names matching a list of patterns "you can set the MRU_Exclude_Files variable to a list of Vim regular expressions "not include files in the temporary (/tmp, /var/tmp and d:\temp) directories let MRU_Exclude_Files = '^/tmp/.*\|^/var/tmp/.*' "add only file names matching a set of patterns to the MRU list "add only .c and .h files to the MRU list let MRU_Include_Files = '\.c$\|\.h$' "The default height of the MRU window is 8 let MRU_Window_Height = 15 "MRU plugin to reuse the current window let MRU_Use_Current_Window = 1 "zero to keep the MRU window open after select a file from MRU let MRU_Auto_Close = 0 "don't use the "File->Recent Files" menu and want to disable it, set it zero let MRU_Add_Menu = 0 a.vim (Alternate Files quickly (.c --> .h etc)) :A switches to the header file corresponding to the current file being edited (or vise versa) :AS splits and switches :AV vertical splits and switches :AT new tab and switches :AN cycles through matches :IH switches to file under cursor :IHS splits and switches :IHV vertical splits and switches :IHT new tab and switches :IHN cycles through matches <Leader>ih switches to file under cursor <Leader>is switches to the alternate file of file under cursor (e.g. on <foo.h> switches to foo.cpp) <Leader>ihn cycles through matches E.g. if you are editing foo.c and need to edit foo.h simply execute :A and you will be editting foo.h, to switch back to foo.c execute :A again. c.vim Alt-F9 write buffer and compile F9 compile and link Ctrl-F9 run executable Shift-F9 command line arguments cscope_maps.vim <C-]> (search the word under cursor) <C-T> (go back to where you were before the search) " 's' symbol: find all references to the token under cursor nmap <C-\>s :cs find s <C-R>=expand("<cword>")<CR><CR> " 'g' global: find global definition(s) of the token under cursor nmap <C-\>g :cs find g <C-R>=expand("<cword>")<CR><CR> " 'c' calls: find all calls to the function name under cursor nmap <C-\>c :cs find c <C-R>=expand("<cword>")<CR><CR> " 't' text: find all instances of the text under cursor nmap <C-\>t :cs find t <C-R>=expand("<cword>")<CR><CR> " 'e' egrep: egrep search for the word under cursor nmap <C-\>e :cs find e <C-R>=expand("<cword>")<CR><CR> " 'f' file: open the filename under cursor nmap <C-\>f :cs find f <C-R>=expand("<cfile>")<CR><CR> " 'i' includes: find files that include the filename under cursor nmap <C-\>i :cs find i ^<C-R>=expand("<cfile>")<CR>$<CR> " 'd' called: find functions that function under cursor calls nmap <C-\>d :cs find d <C-R>=expand("<cword>")<CR><CR> cscope -Rbkq -R: 在生成索引文件时,搜索子目录树中的代码 -b: 只生成索引文件,不进入cscope的界面 -k: 在生成索引文件时,不搜索/usr/include目录 -q: 生成cscope.in.out和cscope.po.out文件,加快cscope的索引速度 #!/bin/sh find . -name ”*.h” -o -name ”*.c” -o -name ”*.cc” > cscope.files cscope -bkq -i cscope.files ctags -R "生成tags可以cscope可以與ctags搭配使用 CRefVim : a C-reference manual especially designed for Vim <Leader>cr normal mode: get help for word under cursor Memory aid cr: (c)-(r)eference <Leader>cr visual mode: get help for visually selected text Memory aid cr: (c)-(r)eference <Leader>cw: prompt for word CRefVim should search for Memory aid cw: (c)-reference (w)hat <Leader>cc: jump to table of contents of the C-reference manual Memory aid cc: (c)-reference (c)ontents netrw.vim (:help netrw-browse) Enter the explore mode :NetrwClean[!] ...........................................|netrw-clean| :NetrwSettings ...........................................|netrw-settings| :Explore[!] [dir] Explore directory of current file......|netrw-explore| :Hexplore[!] [dir] Horizontal Split & Explore.............|netrw-explore| :Nexplore[!] [dir] Vertical Split & Explore...............|netrw-explore| :Pexplore[!] [dir] Vertical Split & Explore...............|netrw-explore| :Rexplore Return to Explorer.....................|netrw-explore| :Sexplore[!] [dir] Split & Explore directory .............|netrw-explore| :Texplore[!] [dir] Tab & Explore..........................|netrw-explore| :Vexplore[!] [dir] Vertical Split & Explore...............|netrw-explore| In the explore mode <F1> Causes Netrw to issue help <cr> Netrw will enter the directory or read the file |netrw-cr| <del> Netrw will attempt to remove the file/directory |netrw-del| - Makes Netrw go up one directory |netrw--| a Toggles between normal display, |netrw-a| hiding (suppress display of files matching g:netrw_list_hide) showing (display only files which match g:netrw_list_hide) c Make browsing directory the current directory |netrw-c| d Make a directory |netrw-d| D Attempt to remove the file(s)/directory(ies) |netrw-D| gb Go to previous bookmarked directory |netrw-gb| gh Quick hide/unhide of dot-files |netrw-gh| gi Display information on file |netrw-qf| <c-h> Edit file hiding list |netrw-ctrl-h| i Cycle between thin, long, wide, and tree listings |netrw-i| <c-l> Causes Netrw to refresh the directory listing |netrw-ctrl-l| mb Bookmark current directory |netrw-mb| mc Copy marked files to marked-file target directory |netrw-mc| md Apply diff to marked files (up to 3) |netrw-md| me Place marked files on arg list and edit them |netrw-me| mf Mark a file |netrw-mf| mh Toggle marked file suffices' presence on hiding list |netrw-mh| mm Move marked files to marked-file target directory |netrw-mm| mp Print marked files |netrw-mp| mr Mark files satisfying a |regexp| |netrw-mr| mt Current browsing directory becomes markfile target |netrw-mt| mT Apply ctags to marked files |netrw-mT| mu Unmark all marked files |netrw-mu| mx Apply arbitrary shell command to marked files |netrw-mx| mz Compress/decompress marked files |netrw-mz| o Enter the file/directory under the cursor in a new |netrw-o| browser window. A horizontal split is used. O Obtain a file specified by cursor |netrw-O| p Preview the file |netrw-p| P Browse in the previously used window |netrw-P| q List bookmarked directories and history |netrw-qb| r Reverse sorting order |netrw-r| R Rename the designed file(s)/directory(ies) |netrw-R| s Select sorting style: by name, time, or file size |netrw-s| S Specify suffix priority for name-sorting |netrw-S| t Enter the file/directory under the cursor in a new tab|netrw-t| u Change to recently-visited directory |netrw-u| U Change to subsequently-visited directory |netrw-U| v Enter the file/directory under the cursor in a new |netrw-v| browser window. A vertical split is used. x View file with an associated program |netrw-x| REMOTE EDITING :e dav://machine[:port]/path uses cadaver :e fetch://[user@]machine/path uses fetch :e ftp://[user@]machine[[:#]port]/path uses ftp autodetects <.netrc> :e http://[user@]machine/path uses http uses wget :e rcp://[user@]machine/path uses rcp :e rsync://[user@]machine[:port]/path uses rsync :e scp://[user@]machine[[:#]port]/path uses scp :e sftp://[user@]machine/path uses sftp REMOTE READING :Nread ? give help :Nread "machine:path" uses rcp :Nread "machine path" uses ftp with <.netrc> :Nread "machine id password path" uses ftp :Nread "dav://machine[:port]/path" uses cadaver :Nread "fetch://[user@]machine/path" uses fetch :Nread "ftp://[user@]machine[[:#]port]/path" uses ftp autodetects <.netrc> :Nread "http://[user@]machine/path" uses http uses wget :Nread "rcp://[user@]machine/path" uses rcp :Nread "rsync://[user@]machine[:port]/path" uses rsync :Nread "scp://[user@]machine[[:#]port]/path" uses scp :Nread "sftp://[user@]machine/path" uses sftp REMOTE WRITING :Nwrite ? give help :Nwrite "machine:path" uses rcp :Nwrite "machine path" uses ftp with <.netrc> :Nwrite "machine id password path" uses ftp :Nwrite "dav://machine[:port]/path" uses cadaver :Nwrite "ftp://[user@]machine[[:#]port]/path" uses ftp autodetects <.netrc> :Nwrite "rcp://[user@]machine/path" uses rcp :Nwrite "rsync://[user@]machine[:port]/path" uses rsync :Nwrite "scp://[user@]machine[[:#]port]/path" uses scp :Nwrite "sftp://[user@]machine/path" uses sftp http: not supported! REMOTE DIRECTORY BROWSING :e [protocol]://[user]@hostname/path/ :Nread [protocol]://[user]@hostname/path/ LOCAL DIRECTORY BROWSING :e /some/path/to/a/directory ctags :tag {ident} "跳转到指定的标签, ident可以是正規表示式 :tags "显示标签栈 CTRL-] "跳转到当前光标下的标签 CTRL-T "跳到标签栈中较早的标签 cd ~/src/vim70 ctags –R src ""在~/src/vim70/目錄下生成一個名為tags的檔案 這個檔案中包含~/src/vim70/src/目錄下所有.c.h檔案的標籤 :cd ~/src/vim70 "切换当前目录为~/src/vim70 :set tags=tags "设置tags选项为当前目录下的tags文件 :tag main "查詢tags中所有含有main的檔案位置 lookupfile.vim : Lookup files using Vim7 ins-completion :LookupFile Lookup files from tag files. :LUBufs Lookup loaded files (buffers) using |bufname()|. :LUWalk Lookup files using |glob()|. 可以用ctags生成的tags文件,但速度較慢 改用下面的script會比較快,輸出仍然是ctags格式 #!/bin/sh # generate tag file for lookupfile plugin echo -e "!_TAG_FILE_SORTED\t2\t/2=foldcase/" > filenametags find . -not -regex '.*\.\(png\|gif\)' -type f -printf "%f\t%p\t1\n" | \ sort -f >> filenametags vim要設定 :let g:LookupFile_TagExpr = '"./filenametags"' (這樣才會改用filenametags,否則預設是tags) SuperTab continued. : Do all your insert-mode completion with Tab. 只要按tab不用按ctrl-N, ctrl-P ManPageView : Viewer for manpages, gnu info, perldoc, and php (unix/linux/cygwin) :Man topic :Man topic booknumber :Man booknumber topic :Man topic(booknumber) word_complete.vim : automatically offers word completion as you type "To activate, choose "Word Completion" from the Tools menu, or type :call DoWordComplete() "To make it stop, choose "Tools/Stop Completion," or type :call EndWordComplete() Mark : a little script to highlight several words in different colors simultaneously Normal \m mark or unmark the word under or before the cursor \r manually input a regular expression \n clear current mark (i.e. the mark under the cursor), or clear all marks Visual \m mark or unmark a visual selection \r manually input a regular expression Searching: Normal \* jump to the next occurrence of current mark \# jump to the previous occurrence of current mark \/ jump to the next occurrence of ANY mark \? jump to the previous occurrence of ANY mark * behaviors vary, please refer to the table on # line 123 MultipleSearch : Highlight multiple searches at the same time, each with a different color. see :h MultipleSearch SearchComplete : Tab completion of words inside of a search ('/') when / search, you can enter tab to make word complete automatically FencView.vim : Autodetect multiple encodings :FencAutoDetect Auto detect the file encoding. Built-in detected encodings: :FencView Open the encoding list window, matrix.vim : Matrix screensaver for VIM :Matrix 開啟此模組 number marks : showing marks using number array in color, easy to trace. 1:make a mark, or delete it: ctrl + F2 mm 2:move to ahead mark: shift + F2 mv 3:move to next mark: F2 mb 4:delete all marks: F4 5:moving a mark: m. (press m. at the one mark, and move the cursor to another line, press m. again. ) " If you want to save the marks to a file. Do it like below: " Put the one line " let g:Signs_file_path_corey='c:\' " into your gvimrc or _vimrc, change it to your path. :call Save_signs_to_file() # Save marks. :call Load_signs_from_file() # reload signs.

2009年6月20日 星期六

My blogger css example

#page



.narrowcolumn




#sidebar .widget


#sidebar .widget-content


#sidebar h2


#kotakkanan


#kotakkanan1




#footer .widget


.date-header


.post-body


.post


.post-title


.post-title a:hover只是把原本的功能加上hover的功能


.post div





.post-footer .span




.post blockquote


.post blockquote p


.post img


.post .pic


#comments h4


#comments h4 strong


#comments-block


#comments-block dt


#comments-block dd



#comments-block dd p


.deleted-comment





#blog-pager


small

h1


h1 a


.description


h2


h2 a


h3


h3 a


acronym
a

.widecolumn .post




h2


h3


h3.comments


p img


img.centered
img.alignright
img.alignleft

.alignright


.alignleft


.title h1


.title h1 a


.title


.description


.kosong


    #siderbar ul


      #siderbar ul ol


  • #siderbar ul li


    #siderbar ul p



      #siderbar ul ul


      #siderbar ul ol


        #siderbar ul ul ul


    1. #siderbar ul ol li


  1. ol li

    • #siderbar ul ul li


    1. #siderbar ul ol li


.entry form



abbr
blockquote

blockquote cite

.center



hr

2009年6月4日 星期四

C/C++的const總介紹

const.c


簡單的介紹C中const的用法  1 int main()  2 {  3   const char ch = 'a';  4   const int a[5] = {1, 2, 3, 4, 5};    5   int b[5] = {6, 7, 8, 9, 10};    6   int c[4][4] = {{11,12,13,14},{15,16,17,18},{19,20,21,22},{23,24,25,26}};  7   const int *p1 = a;                8   int *const p2 = a;                9   const int * const p3 = b; 10   const int ** const p4 = c; 11 12   ch = 'b';//error: ch is const, can't be modified 13   p1 = &a[2]; //ok, *p1 is const, p1 is not 14   *p1 = 5;//error, *p1 is const, a[2] is const 15   *(p1 + 2) = 1; //error, *p1 is const 16   p1 = &b[2];//ok 17   *p1 = 4;//error, *p1 is const 18   p2 = &b[4];//error, p2 is const 19   p2++;//error, p2 is const 20   *p2 = 10;//error, *p2 is not const, p2 is, but a[0] is const 21   p2 = &a[5];//error, p2 is const 22   p3 = &b[1];//error, p3 is const 23   *p3 = 3;//error, *p3 is const 24   p4 = b;//error, p4 is const 25   *(*p4+2) = 10; //error, **p4 is const 26   *p4 = b; 27   printf("%d", **p4); //6, *p4 = b 28   **p4 = 10;//error, **p4 is const 29    30   return 0; 31 } 32 --------------------------------------------------------------------------------------

const.cpp


簡單的介紹C++中const的用法  1 /*  2  * =====================================================================================  3  *  4  *       Filename:  const.cpp  5  *  6  *    Description:    7  *  8  *        Version:  1.0  9  *        Created:  06/04/2009 09:01:15 PM 10  *       Revision:  none 11  *       Compiler:  gcc 12  * 13  *         Author:  YOUR NAME (), 14  *        Company:   15  * 16  * ===================================================================================== 17  */ 18 #include <stdio.h> 19 #include <stdlib.h> 20 class Ball { 21   static const int ID = 100;//initialize only once, can't modify anymore 22   //const int ID2; //can't modify it anymore, and initialize 23   char *name; 24   int money; 25   mutable int bonus; 26   public: 27   Ball(){ 28     name = (char *)malloc(8); 29     name[0] = 'y'; 30     name[1] = 's'; 31   } 32   int setID(int id){ 33     //ID = 200;//error, ID is const 34   } 35   void showID(){ 36     printf("ID:%d\n", ID); 37   } 38   const char* getConstName() { return name; } 39   char* getName() { return name; } 40   int getMoney() const { 41     //money++;//error, function is const, can't modify any its class member 42     bonus++;//ok, it is mutable, can be used in const function 43     return money+bonus; } 44 }; 45 int main() 46 { 47   Ball b = Ball(); 48   b.showID(); 49   printf("name:%s\n", b.getName()); 50   b.getName()[2]='l'; 51   printf("name:%s\n", b.getName()); 52   //b.getConstName()[2]='l';//error, return const can't modify 53   printf("money:%d\n", b.getMoney()); 54 55   return 0; 56 } 57 --------------------------------------------------------------------------------------

const.cpp


簡單的介紹C++中const templates的iterator用法,還有其中content為const時如何去掉const來呼叫  1 #include <iostream>  2 #include <vector>  3 #include <map>  4 #include <string>  5  6 using namespace std;  7  8 class Symbolic{  9     public: 10         Symbolic(int v, string e){ 11             value_ = v; 12             expr_ = e; 13         } 14 15         void Print(){ 16             cout<<"value:"<<value_<<", "<<expr_<<endl; 17         } 18          19         void constPrint() const{ 20             cout<<"value:"<<value_<<", "<<expr_<<endl; 21         } 22     private: 23         int value_; 24         string expr_; 25 }; 26 27 void vectorPrint(const vector<const Symbolic *>& v) 28 { 29     /* const_iterator for const template iteration */ 30     vector<const Symbolic *>::const_iterator v_iter; 31     for(v_iter = v.begin(); v_iter != v.end(); v_iter++){ 32         /* make const member to be normal */ 33         const_cast<Symbolic *>(*v_iter)->Print(); 34         /* const class pointer only can call const function */ 35         (*v_iter)->constPrint(); 36     } 37 38 } 39 40 void mapPrint(const map<int, char>& m) 41 { 42     /* const_iterator for const template iteration */ 43     map<int, char>::const_iterator m_iter; 44     for(m_iter = m.begin(); m_iter != m.end(); m_iter++){ 45         cout<<"index:"<<m_iter->first<<" -> "<<m_iter->second<<endl; 46     } 47 } 48 49 int main() 50 { 51     vector<Symbolic *> constraints; 52 53     constraints.push_back(new Symbolic(1, "x")); 54     constraints.push_back(new Symbolic(2, "y")); 55     constraints.push_back(new Symbolic(3, "z")); 56 57     /* make its member to be const access */ 58     vector<const Symbolic*> cs(constraints.begin(), 59                            constraints.end()); 60     /* print its value and make it const to be sure that we don't modify it */ 61     vectorPrint(cs); 62 63 64     map<int, char> symb; 65 66     symb[1] = 'a'; 67     symb[2] = 'b'; 68     symb[3] = 'c'; 69 70     mapPrint(symb); 71 72     return 0; 73 }

2009年5月16日 星期六

gcc/g++使用-finstrument-functions來觀察code每個function的呼叫

man gcc可以找到-finstrument-functions的一些相關說明,簡單看到下面的敘述 Generate instrumentation calls for entry and exit to functions. 所以重要的是可以將每一個function call的呼叫攔截,加上我們自己的codes,有點LD_PRELOAD的意味存在。 以下介紹兩個例子,gcc和g++的寫法有點不同。 yslinnote@linux1 ~> gcc -finstrument-functions hello.c -o hello /*hello.c*/ #include <stdio.h> #define DUMP(func, call) \ printf("%s: func = %p, called by = %p\n", __FUNCTION__, func, call) /* 每個函式進入時會呼叫此函式 */ void __attribute__((__no_instrument_function__)) __cyg_profile_func_enter(void *this_func, void *call_site) { DUMP(this_func, call_site); } /* 每個函式離開時會呼叫此函式 */ void __attribute__((__no_instrument_function__)) __cyg_profile_func_exit(void *this_func, void *call_site) { DUMP(this_func, call_site); } int main() { puts("Hello World!"); return 0; }

yslinnote@linux1 ~> gcc -finstrument-functions hello.cc -o hello
/*hello.cc*/ #include <stdio.h> #define DUMP(func, call) \ printf("%s: func = %p, called by = %p\n", __FUNCTION__, func, call) #ifdef __cplusplus extern "C" { void __cyg_profile_func_enter(void *this_fn, void *call_site) __attribute__((no_instrument_function)); void __cyg_profile_func_exit(void *this_fn, void *call_site) __attribute__((no_instrument_function)); } #endif int main() { puts("Hello World!"); return 0; } /* 每個函式進入時會呼叫此函式 */ void __cyg_profile_func_enter(void *this_func, void *call_site) { DUMP(this_func, call_site); } /* 每個函式離開時會呼叫此函式 */ void __cyg_profile_func_exit(void *this_func, void *call_site) { DUMP(this_func, call_site); } error: can't set 'no_instrument_function' attribute after definition 要是出現上面的錯誤,表示你在c++的code中多加了__attribute__((no_instrument_function)), 只要在開頭宣告有加就好了。畢竟這是c的code。

2009年4月10日 星期五

.vimrc設定檔

  1 "for cscope.vim   2 "you should install cscope   3   4 " for taglist.vim   5 " you should install taglist   6 "可以在左邊顯示這個c source file用到的變數和函式名稱   7 let Tlist_Inc_Winwidth = 0   8 nnoremap <silent> <F1> :TlistToggle<cr>   9 "nnoremap <silent> <F2> :wincmd p<cr>  10  11 "顯示行號  12 map <F2> : set nu!<BAR>set nonu?<CR>   13 "按 F3 會在 searching highlight 及非 highlight 間切換  14 map <F3> : set hls!<BAR>set hls?<CR>  15 "使用貼上模式,避免貼上時影響縮排格式(Toggle on/off paste mode)  16 map <F4> : set paste!<BAR>set paste?<CR>  17 set pastetoggle=<F4>  18  19 "vim -b : edit binary using xxd-format!  20 augroup Binary  21     au!  22     au BufReadPre  *.bin let &bin=1  23     au BufReadPost *.bin if &bin | %!xxd  24     au BufReadPost *.bin set ft=xxd | endif  25     au BufWritePre *.bin if &bin | %!xxd -r  26     au BufWritePre *.bin endif  27     au BufWritePost *.bin if &bin | %!xxd  28     au BufWritePost *.bin set nomod | endif  29 augroup END  30  31 "按照對應的檔案格式,編譯與執行程式  32 "scripts % mean the file name  33 autocmd BufRead,BufNewFile *.cvc3   map <F5> :% w !clear; cvc3<CR>  34 "autocmd BufRead,BufNewFile *.c map <F5> :w \| !gcc -g % && clear ; ./a.out<CR>  35 autocmd BufRead,BufNewFile *.asm    map <F5> :w \| !nasm -o a.out -f elf -g % && ./a.out<CR>  36 " compiling languages  37 autocmd BufRead,BufNewFile *.c  map <F5> :w \| !gcc -g % -L/usr/local/lib -L. -I/usr/local/include -I. && ./a.out<CR>  38 autocmd BufRead,BufNewFile *.cpp    map <F5> :w \| !g++ -g % -L/usr/local/lib -L. -I/usr/local/include -I. && ./a.out<CR>  39 ":% w !clear; gcc -g %; ./a.out<CR>  40 autocmd BufRead,BufNewFile *.cvcl   map <F5> :% w !clear; cvcl<CR>  41 autocmd BufRead,BufNewFile *.pl     map <F5> :% w !clear; perl<CR>  42 autocmd BufRead,BufNewFile *.py     map <F5> :% w !clear; python<CR>  43 autocmd BufRead,BufNewFile *.rb     map <F5> :w \| !clear; ruby %<CR>  44 autocmd BufRead,BufNewFile *.sh     map <F5> :% w !clear; sh<CR>  45  46 "按照對應的檔案格式,讀取基本的程式碼格式  47 autocmd BufRead,BufNewFile *.c      map <F6> :r ~/std.c<CR>  48 autocmd BufRead,BufNewFile *.cpp    map <F6> :r ~/std.cpp<CR>  49 " 單鍵 <F7> 控制 syntax on/off。倒斜線是 Vim script 的折行標誌  50 " 按一次 <F7> 是 on 的話,再按一次則是 off,再按一次又是 on。  51 " 原因是有時候顏色太多會妨礙閱讀。  52 map <F7> :if exists("syntax_on") <BAR>  53 \ syntax off <BAR><CR>  54 \ else <BAR>  55 \ syntax enable <BAR>  56 \ endif <CR>  57  58 "設定高亮顯示當前行  59 "map <F8> :set cursorline!<CR><Bar>:echo "Highlight active cursor line: " . strpart("OffOn", 3 * &cursorline, 3)<CR>  60 if &background== "light"  61     "顯示當行用底線  62     "highlight comment cterm=none ctermbg=darkblue guibg=darkblue  63     highlight CursorLine cterm=none ctermbg=lightblue  64 else  65 "    highlight comment cterm=none ctermbg=green  66     "顯示當行用高亮  67     highlight CursorLine cterm=none ctermbg=darkblue  68 endif  69 set cursorline!  70  71 "cppcomplete use <F8> and <F9> like vim Ctrl+N and Ctrl+P and  72 "you must exectute 'ctags -n -f cppcomplete.tags --fields=+ai --C++-types=+p * -L cscope.files'  73 "<F8>Ctrl+N  74 "<F9>Ctrl+P  75  76  77 "?建一???文件,?建一?viminfo文件  78 map <F8> :mksession! vim70.vim<cr>:wviminfo! vim70.viminfo<cr>  79 "讀取??文件與viminfo文件  80 map <F9> :source vim70.vim<cr>:rviminfo! vim70.viminfo<cr>  81  82 "檔案寫入日期方便作日記  83 map <F10> :read !date<CR>  84 "呼叫 xxd 做 16 進位顯示  85 map <F11> :%!xxd<CR>  86 "恢復正常模式  87 map <F12> :%!xxd -r<CR>  88  89 "vmap (visual選取模式熱鍵)  90 "插入修改或編輯code的作者相關資訊  91 "add code資訊  92 vmap <F2> xi/* Added by yslin on:<Esc>:read !date <CR>kJ$a BEGIN */<CR>/*<CR>   Please add your  93 \comment here<CR><Esc>a*/<CR>#if 1<CR><CR>#endif<CR>/* Added by yslin on:<Esc>:read !date <CR  94 \>kJ$a END */<CR><ESC>  95 "modify code資訊  96 vmap <F3> xi/* Modified by yslin on:<CR><Esc>k:read !date <CR>k<CR>kJ$a BEGIN */<CR>/*<CR>    97 \Please add your comment here<CR><Esc>a*/<CR>#if 1<CR>#else<CR>#endif<CR>/* Modified by yslin  98 \ on:<Esc>:read !date <CR>kJ$a END<ESC>J$a*/<CR><ESC>  99 "delete code資訊 100 vmap <F4> xi/* Deleted by yslin on:<CR><Esc>k:read !date <CR>k<CR>kJ$a BEGIN */<CR>/*<CR> Ple 101 \ase add your comment here<CR><Esc>a*/<CR>#if 0<CR>#endif<CR>/* Deleted by yslin on:<Esc>:read 102 \!date <CR>kJ$a END<ESC>J$a*/<CR><ESC> 103 "copyright宣告 104 vmap <F5> xi/*<CR> * Copyright(c) 2005-2009 yslin NCTU<CR>*<CR>* 105 \Authored by yslin on:<Esc>:read !date <CR>kJ$a<CR>*<CR>* @desc:<CR>*<CR>* @history<CR>*/<CR><Esc> 106 "函式功能宣告 107 vmap <F6> xi/* Function authored by yslin on:<Esc>:read !date <CR>kJ$a */<CR>/*<CR> * @desc:<CR>* @param:<CR>* @return:<CR>*/<CR><Esc> 108 109 "vim開啟新頁面的熱鍵 110 " CTRL+i is previous tab 111 map <C-i> :tabp<CR> 112 113 " CTRL+n is next tab 114 map <C-o> :tabn<CR> 115 116 " CTRL-Tab is Next window 117 noremap <C-Tab> :tabn<CR> 118 inoremap <C-Tab> <C-O>:tabn<CR> 119 cnoremap <C-Tab> <C-C>:tabn<CR> 120 121 " CTRL-F4 is Close window 122 noremap <C-F4> :tabc 123 inoremap <C-F4> <C-O>:tabc 124 cnoremap <C-F4> <C-C>:tabc 125 126 " CTRL+N is new tab 127 noremap <C-N> :tabe<CR> 128 inoremap <C-N> <C-O>:tabe<CR> 129 cnoremap <C-N> <C-C>:tabe<CR> 130 131 " CTRL+d is close tab 132 noremap <C-D> :tabc<CR> 133 134 ":tabs 顯示所有標籤頁 135 ":tabm [N] 移動到第N順位 136 137 "Set mapleader 138 let mapleader = "," 139 140 141 "Fast reloading of the .vimrc 142 map <silent> <leader>ss :source ~/.vimrc<cr> 143 "Fast editing of .vimrc 144 map <silent> <leader>se :e ~/.vimrc<cr> 145 "Fast updating of doc 146 map <silent> <leader>h :helptags ~/.vim/doc<cr> 147 "When .vimrc is edited, reload it 148 autocmd! bufwritepost .vimrc source ~/.vimrc 149 150 151 "對.viki自動進入viki編輯模式 152 au BufRead,BufNewFile *.viki set ft=viki 153 154 "you should get plugin c.vim 155 "Restart gVim/Vim generate the help tags 156 " :helptags ~/.vim/doc 157 "and look at csupport help with 158 " :help csupport 159 "   Alt-F9   write buffer and compile 160 "       F9   compile and link 161 "  Ctrl-F9   run executable 162 " Shift-F9   command line arguments 163 map  <buffer>  <silent>ec   :call C_Compile()<CR>:redraw<CR>:call C_HlMessage()<CR> 164 map  <buffer>  <silent>el   :call C_Link()<CR>:redraw<CR>:call C_HlMessage()<CR> 165 map  <buffer>  <silent>er   :call C_Run()<CR> 166 map  <buffer>  <silent>ea   :call C_Arguments()<CR> 167 168 """""""""""""""""""""""""""""" 169 " netrw setting 170 """""""""""""""""""""""""""""" 171 let g:netrw_winsize = 30 172 nmap <silent> <leader>fe :Sexplore!<cr>  173 174 175 """""""""""""""""""""""""""""" 176 " lookupfile setting 177 """""""""""""""""""""""""""""" 178 let g:LookupFile_MinPatLength = 2               "最少?入2?字符才?始查找 179 let g:LookupFile_PreserveLastPattern = 0        "不保存上次查找的字符串 180 let g:LookupFile_PreservePatternHistory = 1     "保存查找?史 181 let g:LookupFile_AlwaysAcceptFirst = 1          "回?打?第一?匹配?目 182 let g:LookupFile_AllowNewFiles = 0              "不允??建不存在的文件 183 if filereadable("./filenametags")                "?置tag文件的名字 184     let g:LookupFile_TagExpr = '"./filenametags"' 185 endif 186 "映射LookupFile?,lf 187 nmap <silent> <leader>lf <Plug>LookupFile<cr> 188 "映射LUBufs?,lb 189 nmap <silent> <leader>lb :LUBufs<cr> 190 "映射LUWalk?,lw 191 nmap <silent> <leader>lw :LUWalk<cr> 192 " lookup file with ignore case 193 function! LookupFile_IgnoreCaseFunc(pattern) 194     let _tags = &tags 195     try 196         let &tags = eval(g:LookupFile_TagExpr) 197         let newpattern = '\c' . a:pattern 198         let tags = taglist(newpattern) 199     catch 200         echohl ErrorMsg | echo "Exception: " . v:exception | echohl NONE 201         return "" 202     finally 203         let &tags = _tags 204     endtry 205 206     " Show the matches for what is typed so far. 207     let files = map(tags, 'v:val["filename"]') 208     return files 209 endfunction 210 let g:LookupFile_LookupFunc = 'LookupFile_IgnoreCaseFunc'  211 212 "word_complete.vim 213 "If you want to activate word completion for every buffer, add the line 214 "autocmd BufEnter * call DoWordComplete() 215 "close this function now, it is suitable for slowly typing 216 "autocmd BufEnter * call EndWordComplete() 217 218 "fencview.vim 自動偵測檔案的encodings 219 let g:fencview_autodetect = 1 220 "可以設定哪些檔案才自動偵測 221 "g:fencview_auto_patterns 222 "(default: '*.txt,*.htm{l\=}') 223 224 225 226 "語法高亮度 227 syntax on 228 "把 tab 展開成空白. 229 "set et 230 "相反地設定 231 "set noet 232 233 "啟用vi兼容模式,可以讓古老的vi script可以使用 234 "set compatible 235 "叫vim不要使用與vi兼容的模式, 否則很多 vim 的新功能就不能使用, ex: filetype 236 set nocompatible 237 238 "設定:wviminfo viminfo要存的資訊 239 set viminfo='1000,f1,<500,:500,@500,/500,s30 240 "設定filetype可以自動辨識該檔案類型, ex: .c .cpp可以開啟各自的語法亮度 241 filetype on 242 "可以定義對各個特別的文件作特殊的熱鍵或是設定 243 filetype plugin on 244 filetype plugin indent on 245 "insert模式,start:可以刪除到這行開頭. eol:可以刪除到上一行的行尾. indent:換行時可以自動縮排 246 set backspace=indent,eol,start 247 248 "每輸入一個字元就找符合該字的位置 249 set incsearch 250 "將search到的字元用高亮度顯示 251 set hlsearch 252 "決定高亮的顏色 253 "highlight Search term=reverse ctermbg=yellow ctermfg=grey 254 "搜尋時不區分大小寫 255 set ignorecase 256 "收尋時不缺分大小寫,除非出現一個大寫後,才區分大小寫 257 set smartcase 258 259 "讓 VIM 中的 keyword 以較暗沉的顏色表現出來,適用於亮色系的背景 260 "set background=light 261 "讓 VIM 中的 keyword 以較亮眼的顏色表現出來,適用於暗色系的背景 262 set background=dark 263 "每行左邊顯示行號 264 set number 265 "右下角顯示目前遊標的行列位置 266 set ruler 267 "右下角ruler的左邊顯示輸入的指令 268 set showcmd 269 "輸入對應括號時,會跳回前一個括號顯示配對的情況 270 set showmatch 271 "左下角會顯示目前的模式(Visual, Select, Insert) 272 set showmode 273 "一行若是太長,則向右延伸到螢幕外邊 274 set nowrap 275 276 "保存50個命令和50個查找模式的歷史 277 set history=50 278 279 "tab鍵縮排縮幾個空白長度 280 set shiftwidth=4 281 set tabstop=4 282 "自動縮排 283 set autoindent 284 set cindent 285 286 "設定vim不使用modeline(在檔案開頭設定一些參數),來對文件作特殊的設置(set XX) 287 set nomodeline 288 289 290 "set encoding=cp950 291 "you should set putty the same as .vimrc and argument as below, so you can see correct encoding 292 "檔案預設編碼 293 set fileencoding=utf-8 294 "所有可使用的編碼 295 set fileencodings=ucs-bom,utf-8,gbk,big5,utf8 296 "可使用的檔案格式 fileformat 297 set ffs=unix,dos 298 "預設的檔案格式 (r 與 n ^M) 299 set ff=unix 300 "設定 vim 內部如何表示字元 301 set encoding=utf-8 302 "終端機編碼 303 set termencoding=utf-8 304 305 306 " by smartboy 307 "let &termencoding = &encoding 308 "set encoding=utf-8 309 "set fileencoding=big5 310 "set fileencodings=ucs-bom,utf-8,big5,gb2312,korea,gb18030,latin1 311 312 313 augroup filetypedetect 314   au! BufRead,BufNewFile *.spt setfiletype snippet 315 augroup END  316 317 autocmd Filetype cpp,c,java,cs set omnifunc=cppcomplete#Complete  318 319 " for txl syntax highlighting 320 au BufNewFile,BufRead *.Txl,*.txl,*.Grammar,*.grammar,*.Rules,*.rules,*.Module,*.module,*.Mod,*.mod,*.Grm,*.grm,*.Rul,*.rul set ft=txl 321 322 " for snippetEmu 323 "imap <F2> <Plug>Jumper 324 "let g:snip_start_tag = "@" 325 "let g:snip_end_tag= "@" 326 327 "" for tSkeleton 328 "autocmd BufNewFile *.pl        TSkeletonSetup perl.pl 329 "autocmd BufNewFile *.py        TSkeletonSetup python.py 330 "let g:tskelDateFormat = "%b-%d-%Y" 331 "let g:tskelUserName    = "Li-Wen Hsu" 332 "let g:tskelUserEmail = "lwhsu@lwhsu.org" 333 "let g:tskelUserWWW = "http://lwhsu.org" 334 335 " for python.vim 336 "au FileType python source ~/.vim/plugin/python.vim 337 " for *.py 338 "au BufRead,BufNewFile *.py set ai et nu sw=4 ts=4 tw=79 339 340 " for SuperTab & pyCallTips 341 let g:SuperTabDefaultCompletionType = "<C-N>" 342 343 " ins-completion options 344 hi Pmenu ctermbg=DarkBlue ctermfg=Grey 345 hi PmenuSel ctermbg=DarkGreen ctermfg=white 346 "set pumheight=16 347 348 nmap l <End> 349 highlight SpellErrors ctermfg=Red guifg=Red cterm=underline gui=underline  term=reverse 350 "highlight Normal ctermbg=black ctermfg=white 351 "highlight Folded ctermbg=black ctermfg=darkcyan 352 "set cursorline 353 "highlight CursorLine cterm=none ctermbg=darkblue 354 "set cursorcolumn 355 "highlight CursorLine cterm=none ctermbg=blue 356 "map <F3> :set cursorline!<CR><Bar>:echo "Highlight active cursor line: " . strpart("OffOn", 3 * &cursorline, 3)<CR> 357 358 359 " 360 361 highlight LineNr term=bold cterm=NONE ctermfg=yellow ctermbg=none gui=NONE guifg=DarkGrey guibg=NONE  362 "map <F4> :set number!<CR><Bar>:echo "Line Number: " . strpart("OffOn", 3 * &number, 3)<CR> 363 364 "set foldmethod=indent 365 366 " spelling check 367 "map <F2> :set spell!<CR><Bar>:echo "Spell check: " . strpart("OffOn", 3 * &spell, 3)<CR> 368 369 "autocmd BufRead,BufNewFile *.c     map <F5> :w !gcc a.c<CR> " doesn't work 370