コード例 #1
0
ファイル: Utils.cpp プロジェクト: sandeep-datta/winguide
CString GetConfiguredDateString()
{
	DateTimeFormat f;
	theApp.GetDateTimeFormat(f);

	return GetDateString(f.useSystemDateFormat ? NULL : (LPCTSTR)f.dateFormat);
}
コード例 #2
0
ファイル: epg.c プロジェクト: BackupTheBerlios/macvdr-svn
cString cEvent::ToDescr(void) const
{
  char vpsbuf[64] = "";
  if (Vps())
     sprintf(vpsbuf, "(VPS: %s) ", *GetVpsString());
  return cString::sprintf("%s %s-%s %s'%s'", *GetDateString(), *GetTimeString(), *GetEndTimeString(), vpsbuf, Title());
}
コード例 #3
0
ファイル: DocFileField.cpp プロジェクト: killbug2004/WSProf
void DocFileField::UpdateSaveDate(WordParserInfo& wpi)
{
    if ( wpi.m_FileSaveTime.wYear == 0)
        return;

    CStdString sInst = GetInst()->GetAllInstructionText().GetData();
    if (sInst.Find(L"SAVEDATE") < 0)
        return;

    int iPos = sInst.Find(L"@");
    if (iPos < 0)
        return;

    // strip out the format
    iPos = sInst.Find(L"\"", iPos);
    sInst = sInst.Right(sInst.length() - iPos - 1);
    iPos = sInst.Find(L"\"", 0);
    sInst = sInst.Left(iPos);

    CStdString sOut = GetDateString(sInst, wpi.m_FileSaveTime);
    if (sOut.IsEmpty())
        return;

    int iCount = the_RTFFieldResult->GetCount();
    for (int i=0; i<iCount; i++)
    {
        if (the_RTFFieldResult->At(i)->GetType() == rotPcdata)
        {
            ((RTFPCData*)the_RTFFieldResult->At(i))->SetContent(sOut.c_str());
        }
    }
}
コード例 #4
0
ファイル: OrderManagerDlg.cpp プロジェクト: cjm8374/JmPos
void COrderManagerDlg::OnBnClickedBtnOrdermgrOk()
{
	// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
	UpdateData(TRUE);

	if (m_nMode == PAY_MODE)
	{
		int nResult = AfxMessageBox(_T("계산을 완료 하시겠습니까?"), MB_OKCANCEL);
		if (nResult == IDOK)
		{
			CListCtrl* OrderList = (CListCtrl*)this->GetDlgItem(IDC_LIST_ORDERMGR_ORDERS);
			CString strOrder;
			for (int i = 0; i < OrderList->GetItemCount(); i++)
			{
				strOrder += OrderList->GetItemText(i, 0);
				strOrder += _T('|');
				strOrder += OrderList->GetItemText(i, 1);
				strOrder += _T('|');
				strOrder += OrderList->GetItemText(i, 2);
				strOrder += _T('|');
			}
			
			char szQuery[1024];
			sprintf_s(szQuery, "insert into tblSales (sale_date,sale_table,sale_menu,sale_total_price) values ('%s',%d,'%s',%d);"
				, GetDateString(), m_nTableIndex, strOrder, m_nTotalPrice);
			g_SqlMgr.execDML(szQuery);

			CString strTableIndex;
			strTableIndex.Format(_T("TABLE%d"), m_nTableIndex);
			theApp.WriteProfileStringA(strTableIndex, _T("Order"), _T(""));
		}
		else
		{
			return;
		}
	}
	else
	{
		CListCtrl* OrderList = (CListCtrl*)this->GetDlgItem(IDC_LIST_ORDERMGR_ORDERS);
		CString strOrder;
		for (int i = 0; i < OrderList->GetItemCount(); i++)
		{
			strOrder += OrderList->GetItemText(i, 0);
			strOrder += _T('|');
			strOrder += OrderList->GetItemText(i, 1);
			strOrder += _T('|');
			strOrder += OrderList->GetItemText(i, 2);
			strOrder += _T('|');
		}

		CString strTableIndex;
		strTableIndex.Format(_T("TABLE%d"), m_nTableIndex);
		theApp.WriteProfileStringA(strTableIndex, _T("Order"), strOrder);
	}

	OnOK();
}
コード例 #5
0
ファイル: TimedExecMain.cpp プロジェクト: doctorjbeam/Syslist
void CheckRun(bool IsStartup, bool ForceRun = false)	
{
	std::string LogPath;
	GetProcDir (LogPath);
	
	CFAbsoluteTime DeltaTime;
	CFAbsoluteTime NextTime;
	CFAbsoluteTime AlignTime;
	
	bool ShouldRun = ForceRun;
	if (ForceRun == false)
		ShouldRun = CheckTime (IsStartup, NextTime, DeltaTime, AlignTime);
	
	LogPath += '/';
	
	LogPath += LogFileName;
	
	std::ofstream LogStream;
	
	LogStream.open (LogFileName);
	
	LogStream << "SCATimeCheck Log" << std::endl;
	
	std::string TimeString;

	CFAbsoluteTime CurrTime;
	CurrTime = CFAbsoluteTimeGetCurrent();
	GetDateString(CurrTime, TimeString);
	
	LogStream << "Current Time is: " << TimeString << std::endl;
	
	if (ShouldRun) {
		
		LogStream << "It is time to run the Collector" << std::endl;
		
		long Status;
		
		Status = ExecuteCollector();
		
		if (Status == 0) {
			
			// Write back the aligned exec time if we suceeded.
			SyslistPrefs::setAlignTime (AlignTime);
			SyslistPrefs::Sync();
		}
			
		LogStream << "Collector returned: " << Status << std::endl;
	}
	else {
		LogStream << "It is not yet time to run the collector" << std::endl;
	}
		
	LogStream.close();

}
コード例 #6
0
ファイル: int.c プロジェクト: Azarien/open-watcom-v2
/*
 * setClockTime - set the current clock time
 */
static void setClockTime( void )
{
    char        date[128];

    GetDateString( date );
    tSec1 = date[DATE_LEN - 2];
    tSec2 = date[DATE_LEN - 1];
    tMin1 = date[DATE_LEN - 5];
    tMin2 = date[DATE_LEN - 4];
    tHour1 = date[DATE_LEN - 8];
    tHour2 = date[DATE_LEN - 7];

} /* setClockTime */
コード例 #7
0
ファイル: eventlog.cpp プロジェクト: ChuckBolin/VB6
//writes message and/or time/date to log file
void CEventLog::LogData(string text, int status=0)
{
  if (log_file.size() <1) SetFilename("log.txt");
  ofstream file(log_file.c_str(), std::ios::app);
  if(file){
    switch(status)
    {
      case LOG_TEXT:
        file << text.c_str() << endl;
        break;
      case LOG_TEXT_TIME:
        file << GetTimeString() << ": " << text.c_str() << endl;
        break;  
      case LOG_TEXT_DATE:
        file << GetDateString() << ": " << text.c_str() << endl;
        break;  
      case LOG_TEXT_DATE_TIME:
        file << GetDateString() << ", " << GetTimeString() << ": "
			 << text.c_str() << endl;
        break;  
    }
  }
}
コード例 #8
0
void CRapiFileDialog::UpdateDialog(void)
{
    m_pathname.MakeAbsolute();
    m_currentpaths.clear();
    m_currentsizes.clear();
    m_currentdates.clear();

    GetFileList()->ClearAll();

    if(m_mode==REPORTMODE)
    {
        GetFileList()->SetWindowStyle(wxLC_REPORT|wxLC_SINGLE_SEL);
        GetFileList()->InsertColumn(0,wxT("Name"),wxLIST_FORMAT_LEFT,160);
        GetFileList()->InsertColumn(1,wxT("Size"));
        GetFileList()->InsertColumn(2,wxT("Date"));
    }
    else if(m_mode==ICONMODE)
    {
        GetFileList()->SetWindowStyle(wxLC_ICON|wxLC_SINGLE_SEL);
    }
    else if(m_mode==SMALLICONMODE)
    {
        GetFileList()->SetWindowStyle(wxLC_SMALL_ICON|wxLC_SINGLE_SEL);
    }
    else if(m_mode==LISTMODE)
    {
        GetFileList()->SetWindowStyle(wxLC_LIST|wxLC_SINGLE_SEL);
    }

    // Ensure we have a file type selection
    if(GetFilesOfType()->GetCount()==0)
    {
        AddFileType(wxT("All Files (*.*)"),wxT("*"));
    }
    if(GetFilesOfType()->GetSelection()==wxNOT_FOUND)
    {
        GetFilesOfType()->SetSelection(0);
    }
    
    // Get item names
    DWORD dwFound;
    LPCE_FIND_DATA pFoundDataArray=NULL;
    if(!g_RAPI.CeFindAllFiles(m_pathname.GetPath(true)+wxT("*"),FAF_ATTRIBUTES|FAF_SIZE_HIGH|FAF_SIZE_LOW|FAF_NAME|FAF_LASTWRITE_TIME,&dwFound,&pFoundDataArray))
    {
        GetFileList()->Enable(false);
    }
    else
    {
        GetFileList()->Enable(true);
    }

    if(pFoundDataArray)
    {
        wxString strMatch=m_filetypes[GetFilesOfType()->GetSelection()];

        // Fill in file list
        for(DWORD dw=0;dw<dwFound;dw++)
        {
            if(pFoundDataArray[dw].dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                // It's a folder
                wxFileName dname(m_pathname.GetPath(true)+pFoundDataArray[dw].cFileName,wxT(""));
                m_currentpaths.push_back(dname.GetPath(true));
                m_currentsizes.push_back(0);
                m_currentdates.push_back(pFoundDataArray[dw].ftLastWriteTime);
            }
            else
            {
                // It's a file
                wxFileName dname(m_pathname.GetPath(true)+pFoundDataArray[dw].cFileName);

                if(dname.GetFullName().Lower().Matches(strMatch.Lower()))
                {
                    m_currentpaths.push_back(dname.GetFullPath());
                    m_currentsizes.push_back(((wxUint64)pFoundDataArray[dw].nFileSizeLow)|(((wxUint64)pFoundDataArray[dw].nFileSizeHigh)<<32));
                    m_currentdates.push_back(pFoundDataArray[dw].ftLastWriteTime);
                }
            }
        }
        g_RAPI.CeRapiFreeBuffer(pFoundDataArray);
    }

    wxImageList *pilSmall=new wxImageList(16,16,true,1);
    pilSmall->Add(RapiFileDialogBitmapsFunc(0),wxColour(255,0,255));
    pilSmall->Add(RapiFileDialogBitmapsFunc(1),wxColour(255,0,255));
    pilSmall->Add(RapiFileDialogBitmapsFunc(2),wxColour(255,0,255));

    wxImageList *pilBig=new wxImageList(32,32,true,1);
    pilBig->Add(RapiFileDialogBitmapsLgFunc(0),wxColour(255,0,255));
    pilBig->Add(RapiFileDialogBitmapsLgFunc(1),wxColour(255,0,255));
    pilBig->Add(RapiFileDialogBitmapsLgFunc(2),wxColour(255,0,255));

    size_t i=0,count=m_currentpaths.size();
    for(i=0;i<count;i++)
    {
        if(m_currentpaths[i].Last()==wxT('\\'))
        {
            GetFileList()->InsertItem((long)i,wxFileName(m_currentpaths[i],wxT("")).GetDirs().Last(),0);
            GetFileList()->SetItemImage((long)i,0,1);
            if(m_mode==REPORTMODE)
            {
//              GetFileList()->SetItem((long)i,1,(const TCHAR *)GetSizeString(m_currentsizes[i]));
                GetFileList()->SetItem((long)i,2,(const TCHAR *)GetDateString(m_currentdates[i]));
            }

        }
        else
        {
            GetFileList()->InsertItem((long)i,wxFileName(m_currentpaths[i]).GetFullName(),2);
            if(m_mode==REPORTMODE)
            {
                GetFileList()->SetItem((long)i,1,(const TCHAR *)GetSizeString(m_currentsizes[i]));
                GetFileList()->SetItem((long)i,2,(const TCHAR *)GetDateString(m_currentdates[i]));
            }
        }

        if(m_currentpaths[i].Last()==m_pathname.GetFullPath())
        {
            GetFileList()->SetItemState((long)i,wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED,wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED);
        }
        GetFileList()->SetItemData((long)i,(long)i);
    }

    GetFileList()->AssignImageList(pilSmall,wxIMAGE_LIST_SMALL);
    GetFileList()->AssignImageList(pilBig,wxIMAGE_LIST_NORMAL);

    // Fill in Look-In Choice Box
    GetLookIn()->Clear();
    count=m_pathname.GetDirCount();
    
    wxString dir=wxT("\\");
    GetLookIn()->Append(dir);        

    for(i=0;i<count;i++)
    {
        dir=wxT("\\");
        for(size_t j=0;j<=i;j++)
        {
            dir+=m_pathname.GetDirs()[j];
            if(j!=i)
            {
                dir+=wxT("\\");
            }
        }
        GetLookIn()->Append(dir);
    }
    GetLookIn()->SetSelection((int)count);

    GetUp()->Enable(count>0);
    GetBack()->Enable(m_history.size()>1);
    GetOk()->Enable(m_pathname.GetFullPath().Last()!=wxT('\\'));

    GetFileList()->SortItems(ListCompareFunction,(long)this);
}
コード例 #9
0
unsigned long SendFile
  (
    struct AmmServer_Instance * instance,
    struct HTTPTransaction * transaction,
    char * verified_filename_pending_copy, // The filename to be served on the socket above
    unsigned int force_error_code
  )
{
 int clientsock = transaction->clientSock;
 unsigned int resourceCacheID=transaction->resourceCacheID;
 unsigned long start_at_byte = transaction->incomingHeader.range_start;
 unsigned long end_at_byte = transaction->incomingHeader.range_end;
 unsigned char keepalive = transaction->incomingHeader.keepalive;
 unsigned char compression_supported = transaction->incomingHeader.supports_compression ;


  struct HTTPHeader * request = &transaction->incomingHeader;

  char verified_filename[MAX_FILE_PATH+1]={0};
  char reply_header[MAX_HTTP_REQUEST_HEADER_REPLY+1]={0};

  if (verified_filename_pending_copy != 0)
  {
     strncpy(verified_filename,verified_filename_pending_copy,MAX_FILE_PATH);
  }



/*!   Start sending the header first..!
      Due to error messages also having body payloads they are also handled here , creating
      clutter in the code but this way there is no need to write the same thing twice..! !*/

/*! PRELIMINARY HEADER SENDING START ----------------------------------------------*/
  unsigned int WeWantA200OK=0;

  if (force_error_code!=0)
  {
    //We want to force a specific error_code!
    if (! SendErrorCodeHeader(instance,clientsock,force_error_code,verified_filename,instance->templates_root) ) { fprintf(stderr,"Failed sending error code %u\n",force_error_code); return 0; }
  } else
  if (!FilenameStripperOk(verified_filename))
  {
     //Unsafe filename , bad request :P
     if (! SendErrorCodeHeader(instance,clientsock,400,verified_filename,instance->templates_root) ) { fprintf(stderr,"Failed sending error code 400\n"); return 0; }
     //verified_filename should now point to the template file for 400 messages
  } else
   {
      //We have a legitimate file to send , if we want to send it all , we must emmit a 200 OK header
      //if we are serving it with an offset , we must emmit a 206 OK header!
      if ( (start_at_byte!=0) || (end_at_byte!=0) )
       {
         error("No checking on Range Provided is done , the underlying mechanisms are safe , but the header could potentially display wrong things ..");
         error("We dont know the filesize yet so can't fix it here..");

         //Range Accepted 206 OK header
         if (! SendSuccessCodeHeader(instance,clientsock,206,verified_filename)) { fprintf(stderr,"Failed sending Range Acknowledged success code \n"); return 0; }
       } else
       {
         //Normal 200 OK header
         /*! TODO Reorganize this : THIS SHOULD NOT BE SENT YET , SINCE WE MAY WANT TO EMMIT A 304 Not Modified Header if content is unmodified..!*/
         WeWantA200OK=1;
       }
   }
/*! PRELIMINARY HEADER SEND END ----------------------------------------------*/


  struct cache_item * cache = (struct cache_item *) instance->cache;

  int opres=0;
  unsigned int index=0;
  unsigned long cached_lSize=0;
  unsigned char cached_buffer_is_compressed = compression_supported;
  unsigned char free_cached_buffer_after_use=0;
  unsigned char serveAsRegularFile=0;
  char * cached_buffer = cache_GetResource(instance,request,resourceCacheID,verified_filename,MAX_FILE_PATH,&index,&cached_lSize,0,&cached_buffer_is_compressed,&free_cached_buffer_after_use,&serveAsRegularFile);

  if  (cached_buffer!=0) //If we have already a cached version of the file there is a change we might send a 304 Not Modified response
   {
      unsigned char ok_to_serve_not_modified = 1;

      /*OK We have a cached buffer on this page BUT a good question to ask is the following..
        Is it a regular file we are talking about , or a dynamic page ? */

      if (cache[index].dynamicRequestCallbackFunction!=0)
              {
                /*It seems we have ourselves a dynamic page..! Are we on a callback cooldown ? */
                /*The only built in way to serve a not modified response is if the request is too soon ( callback_every_x_msec callback cooldown ) ! */
                struct AmmServer_RH_Context * shared_context = cache[index].dynamicRequest;
                if ( shared_context->callback_cooldown ) { ok_to_serve_not_modified=1; } else // <- the dynamic page is still fresh.. so lets serve not modified..!
                                                         { ok_to_serve_not_modified=0; } // <- the dynamic page has expired is dynamic so it can't be cached
              } else
              {
                  //It seems we have ourselves a regular page
                  //ok_to_serve_not_modified already should equal 1 so leave this here as documentation.. :P
              }

      //The application might want the file to always be served as a fresh one..
      if ( cache[index].doNOTCacheRule ) { ok_to_serve_not_modified = 0; } /*We have written orders that we want this file to NEVER get cached.. EVER :P */
      if (force_error_code!=0) { ok_to_serve_not_modified = 0; } /*We want 404 etc messages to remain 404 :P , no point in serving 404 and then 304 ( that the 404 didn't change )*/

      if (ok_to_serve_not_modified)
      {
       //Check E-Tag here..!
       unsigned int cache_etag = cache_GetHashOfResource(instance,index);
       if ((request->eTag!=0)&&(cache_etag!=0))
        {
          char LocalETag[MAX_ETAG_SIZE]={0};
          snprintf(LocalETag,MAX_ETAG_SIZE,"%u%u%lu%lu",instance->cacheVersionETag,cache_etag,start_at_byte,end_at_byte);

          //fprintf(stderr,"E-Tag is `%s` , local hash is `%s` \n",request->eTag,LocalETag);
          if ( strncmp(request->eTag,LocalETag,request->eTagLength)==0 )
           {
              fprintf(stderr,"The content matches our ETag , we will reply with 304 NOT MODIFIED! :) \n");
              SendNotModifiedHeader(instance,clientsock);

              //The Etag is mandatory on 304 messages..!
              char ETagSendChunk[MAX_ETAG_SIZE+64]={0};
              snprintf(ETagSendChunk,MAX_ETAG_SIZE+64,"ETag: \"%s\" \n",LocalETag);
              if (!SendPart(instance,clientsock,ETagSendChunk,strlen(ETagSendChunk))) { fprintf(stderr,"Failed sending content length @  SendMemoryBlockAsFile ..!\n");  }

              WeWantA200OK=0;
              request->requestType=HEAD;
           }
             else
          {
            warning("eTag Mismatch\n"); // <- for now mismatches are probably bugs
          }
        }
     }
   }




   unsigned int have_last_modified=0;
   struct stat last_modified;

   if ( WeWantA200OK )
   {
       if (! SendSuccessCodeHeader(instance,clientsock,200,verified_filename)) { fprintf(stderr,"Failed sending success code \n"); freeMallocIfNeeded(cached_buffer,free_cached_buffer_after_use); return 0; }

       /* TODO : TEMPORARILY DISABLED LAST-MODIFIED :P
       if (stat(verified_filename, &last_modified))  { fprintf(stderr,"Could not stat modification time for file %s\n",verified_filename); } else
                                                     {  have_last_modified=1; }*/

       //TODO -> Check with last modified -> char * cached_buffer = CheckForCachedVersionOfThePage(request,verified_filename,&index,&cached_lSize,0,gzip_supported);
   }


   if (have_last_modified)
     {

       struct tm * ptm = gmtime ( &last_modified.st_mtime ); //This is not a particularly thread safe call , must add a mutex or something here..!
       //Last-Modified: Sat, 29 May 2010 12:31:35 GMT
       GetDateString(reply_header,MAX_HTTP_REQUEST_HEADER_REPLY,"Last-Modified",0,ptm->tm_wday,ptm->tm_mday,ptm->tm_mon,EPOCH_YEAR_IN_TM_YEAR+ptm->tm_year,ptm->tm_hour,ptm->tm_min,ptm->tm_sec);
       opres=send(clientsock,reply_header,strlen(reply_header),MSG_WAITALL|MSG_NOSIGNAL);  //Send filesize as soon as we've got it
       if (opres<=0) { fprintf(stderr,"Error sending Last-Modified header \n"); freeMallocIfNeeded(cached_buffer,free_cached_buffer_after_use); return 0; }
     }


                 //This used to also emmit --> Keep-Alive: timeout=5, max=100\n <--
                 /* RedBot says ( http://redbot.org/?uri=http%3A%2F%2Fammar.gr%3A8080%2F ) ..!
                     The Keep-Alive header is completely optional; it is defined primarily because the keep-alive connection token implies that such a header exists, not because anyone actually uses it.
                    Some implementations (e.g., Apache) do generate a Keep-Alive header to convey how many requests they're willing to serve on a single connection, what the connection timeout is and other information. However, this isn't usually used by clients.
                    It's safe to remove this header if you wish to save a few bytes in the response.*/
  if (keepalive) { if (!SendPart(instance,clientsock,"Connection: keep-alive\n",strlen("Connection: keep-alive\n")) ) { /*TODO : HANDLE failure to send Connection: Keep-Alive */}  } else
                 { if (!SendPart(instance,clientsock,"Connection: close\n",strlen("Connection: close\n"))) { /*TODO : HANDLE failure to send Connection: Close */}  }


if (request->requestType!=HEAD)
 {
  if ( (cached_buffer!=0) && //If we haven't got a buffer cached.. AND
        ( (!cache[index].doNOTCacheRule) /*If we dont forbid caching */ || ( (cache[index].doNOTCacheRule)&&(cache[index].dynamicRequestCallbackFunction!=0) ) /*Or we forbid caching but we are talking about a dynamic page*/)
     ) // its ok to serve a cached file..
   { /*!Serve cached file !*/
     //if (gzip_supported) { strcat(reply_header,"Content-encoding: gzip\n"); } // Cache can serve gzipped files
     //Last-Modified: Sat, 29 May 2010 12:31:35 GMT
     //GetDateString(reply_header,"Date",1,0,0,0,0,0,0,0);


     unsigned int  cache_etag = cache_GetHashOfResource(instance,index);
     if (cache_etag!=0)
     {
        snprintf(reply_header,MAX_HTTP_REQUEST_HEADER_REPLY,"ETag: \"%u%u%lu%lu\"\n", instance->cacheVersionETag,cache_etag,start_at_byte,end_at_byte);
        opres=ASRV_Send(instance,clientsock,reply_header,strlen(reply_header),MSG_WAITALL|MSG_NOSIGNAL);  //Send E-Tag as soon as we've got it
        if (opres<=0) { fprintf(stderr,"Error sending ETag header \n"); freeMallocIfNeeded(cached_buffer,free_cached_buffer_after_use); return 0; }

     }

     if (cached_lSize==0) { warning("Bug(?) detected , zero cache payload\n"); }


     if ( cached_buffer_is_compressed )
     {
        strncpy(reply_header,"Content-Encoding: deflate\n",MAX_HTTP_REQUEST_HEADER_REPLY);
        opres=ASRV_Send(instance,clientsock,reply_header,strlen(reply_header),MSG_WAITALL|MSG_NOSIGNAL);  //Send E-Tag as soon as we've got it
        if (opres<=0) { fprintf(stderr,"Error sending Compression header \n"); freeMallocIfNeeded(cached_buffer,free_cached_buffer_after_use); return 0; }
     }

    //THIS ALSO EXISTS IN THE TransmitFileToSocket  CODE
    //Send Content Length , as a range , or as the whole file!
      if ( (start_at_byte!=0) || (end_at_byte!=0) )
       {
         //error("Resource Content-Range response");
         //Content-Range: bytes 1000-3979/3980
         int endAtBytePrinted = end_at_byte;
         if (endAtBytePrinted == 0 ) { endAtBytePrinted = cached_lSize; }
          snprintf(reply_header,MAX_HTTP_REQUEST_HEADER_REPLY,"Content-Range: bytes %lu-%u/%lu\nContent-length: %lu\n\n",start_at_byte,endAtBytePrinted,cached_lSize,cached_lSize-start_at_byte);
       } else
       {
         //error("Resource Plain Content-Length ");
         //This is the last header part , so we are appending an extra \n to mark the end of the header
         snprintf(reply_header,MAX_HTTP_REQUEST_HEADER_REPLY,"Content-length: %u\n\n",(unsigned int) cached_lSize);
       }
     opres=ASRV_Send(instance,clientsock,reply_header,strlen(reply_header),MSG_WAITALL|MSG_NOSIGNAL);  //Send filesize as soon as we've got it
     if (opres<=0) { fprintf(stderr,"Error sending cached header \n"); freeMallocIfNeeded(cached_buffer,free_cached_buffer_after_use); return 0; }

     opres=ASRV_Send(instance,clientsock,cached_buffer,cached_lSize,MSG_WAITALL|MSG_NOSIGNAL);  //Send file as soon as we've got it
     freeMallocIfNeeded(cached_buffer,free_cached_buffer_after_use);

     if (opres<=0) { fprintf(stderr,"Error sending cached body\n"); return 0; }
     return 1;
   }
     else
  {
    /*!Serve file by reading it from disk !*/

    if ((cached_buffer==0)&&(cached_lSize==1)) { /*TODO : Cache indicates that file doesn't exist */ } else
    if ((cached_buffer==0)&&(cached_lSize==0)) { /*TODO : Cache indicates that file is not in cache :P */ }


     if ( !TransmitFileToSocket(instance,clientsock,verified_filename,start_at_byte,end_at_byte) )
      {
         fprintf(stderr,"Could not transmit file %s \n",verified_filename);
         return 0;
      }
      return 1;
  }
  //
} //we also want a body with that header END
 else
{
  //We only served a header so lets append the last new line char..!
  send(clientsock,"\n",strlen("\n"),MSG_WAITALL|MSG_NOSIGNAL);
  return 1; //This does not mean we failed..! 2016-04-03
}


 return 0;
}
コード例 #10
0
ファイル: date.c プロジェクト: GYGit/reactos
INT cmd_date (LPTSTR param)
{
    LPTSTR *arg;
    INT    argc;
    INT    i;
    BOOL   bPrompt = TRUE;
    INT    nDateString = -1;

    if (!_tcsncmp (param, _T("/?"), 2))
    {
        ConOutResPaging(TRUE,STRING_DATE_HELP4);
        return 0;
    }

    nErrorLevel = 0;

    /* build parameter array */
    arg = split (param, &argc, FALSE, FALSE);

    /* check for options */
    for (i = 0; i < argc; i++)
    {
        if (_tcsicmp (arg[i], _T("/t")) == 0)
            bPrompt = FALSE;
        if ((*arg[i] != _T('/')) && (nDateString == -1))
            nDateString = i;
    }

    if (nDateString == -1)
        ConOutPrintf(_T("%s"), GetDateString());

    if (!bPrompt)
    {
        freep (arg);
        return 0;
    }

    if (nDateString == -1)
    {
        while (TRUE)  /* forever loop */
        {
            TCHAR s[40];

            PrintDateString ();
            ConInString (s, 40);
            TRACE ("\'%s\'\n", debugstr_aw(s));
            while (*s && s[_tcslen (s) - 1] < _T(' '))
                s[_tcslen (s) - 1] = _T('\0');
            if (ParseDate (s))
            {
                freep (arg);
                return 0;
            }
            ConErrResPuts(STRING_DATE_ERROR);
        }
    }
    else
    {
        if (!ParseDate (arg[nDateString]))
        {
            while (TRUE)  /* forever loop */
            {
                TCHAR s[40];
                ConErrResPuts(STRING_DATE_ERROR);

                PrintDateString ();
                ConInString (s, 40);

                while (*s && s[_tcslen (s) - 1] < _T(' '))
                    s[_tcslen (s) - 1] = _T('\0');
                if (ParseDate (s))
                {
                    freep (arg);
                    return 0;
                }
            }
        }
    }

    freep (arg);
    return 0;
}
コード例 #11
0
ファイル: status.c プロジェクト: Azarien/open-watcom-v2
/*
 * UpdateStatusWindow - update the status window
 */
void UpdateStatusWindow( void )
{
    char        *str, *ptr;
    char        result[5 * MAX_STR];
    char        *res;
    int         digits;
    long        num;
    bool        use_num;
    int         line;
    char        numstr[12];
    int         format;
    char        c;

    if( BAD_ID( status_window_id ) ||
        EditFlags.DisplayHold ||
        EditFlags.Quiet ||
        !EditFlags.StatusInfo ||
        EditVars.StatusString == NULL ) {
        return;
    }

    res = result;
    line = 1;
    format = FMT_LEFT;
    EditFlags.ModeInStatusLine = false;
    for( str = EditVars.StatusString; (c = *str) != '\0'; ++str ) {
        if( c == '$' ) {
            str++;
            ptr = str;
            while( isdigit( *str ) ) {
                str++;
            }
            if( ptr != str ) {
                digits = strtoul( ptr, NULL, 10 );
            } else {
                digits = 0;
            }
            use_num = false;
            num = 0;
            c = *str;
            if( c == '\0' )
                break;
            switch( c ) {
            case '$':
                *res++ = '$';
                break;
            case 'c':
                *res++ = ',';
                break;
            case 'n':
                *res = 0;
                StatusLine( line, result, format );
                res = result;
                line++;
                break;
            case 'L':
                num = CurrentPos.line;
                use_num = true;
                break;
            case 'C':
                num = VirtualColumnOnCurrentLine( CurrentPos.column );
                use_num = true;
                break;
            case 'D':
#ifdef __WIN__
                GetDateString( res );
#else
                GetDateTimeString( res );
#endif
                res += strlen( res );
                break;
            case 'T':
                GetTimeString( res );
                res += strlen( res );
                break;
            case 'M':
                /* print the desired mode */
                EditFlags.ModeInStatusLine = true;
                GetModeString( res );
                res += strlen( res );
                break;
#ifdef __WIN__
            case 'H':
                GetMenuHelpString( res );
                res += strlen( res );
                break;
            case '[':
                *res++ = STATUS_ESC_CHAR;
                *res++ = STATUS_NEXT_BLOCK;
                break;
            case '|':
                *res++ = STATUS_ESC_CHAR;
                *res++ = STATUS_FORMAT_CENTER;
                break;
            case '>':
                *res++ = STATUS_ESC_CHAR;
                *res++ = STATUS_FORMAT_RIGHT;
                break;
            case '<':
                *res++ = STATUS_ESC_CHAR;
                *res++ = STATUS_FORMAT_LEFT;
                break;
#else
            case '|':
                format = FMT_CENTRE;
                break;
            case '>':
                format = FMT_RIGHT;
                break;
            case '<':
                format = FMT_LEFT;
                break;
#endif
            }
            if( use_num ) {
                ltoa( num, numstr, 10 );
                digits -= strlen( numstr );
                while( digits > 0 ) {
                    *res++ = ' ';
                    digits--;
                }
                ptr = numstr;
                while( *ptr != '\0' ) {
                    *res++ = *ptr++;
                }
            }
        } else {
            *res++ = c;
        }
    }
    *res = 0;
    if( res != result ) {
        StatusLine( line, result, format );
    }

} /* UpdateStatusWindow */
コード例 #12
0
/*----------------------------------------------------------------------------------------------
	Called by the framework to initialize the dialog. All one-time initialization should be
	done here (that is, all controls have been created and have valid hwnd's, but they
	need initial values.)

	See ${AfDialog#FWndProc}
	@param hwndCtrl (not used)
	@param lp (not used)

	@return true if Successful
----------------------------------------------------------------------------------------------*/
bool GeneralPropDlgTab::OnInitDlg(HWND hwndCtrl, LPARAM lp)
{
	HICON hicon = m_ppropd->GetIconHandle();
	if (hicon)
	{
		::SendMessage(::GetDlgItem(m_hwnd, kridGeneralPropTabObjIcon), STM_SETICON,
			(WPARAM)hicon, (LPARAM)0);
	}

	m_hfontLarge = AfGdi::CreateFont(16, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE, ANSI_CHARSET,
		OUT_CHARACTER_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, VARIABLE_PITCH | FF_SWISS,
		_T("MS Sans Serif"));
	if (m_hfontLarge)
	{
		::SendMessage(::GetDlgItem(m_hwnd, kridGeneralPropTabBigName), WM_SETFONT,
			(WPARAM)m_hfontLarge, false);
	}
	::SetWindowText(::GetDlgItem(m_hwnd, kridGeneralPropTabBigName), m_ppropd->GetName());

	// Replace the kctidGeneralPropTabName editbox with a bespoke version, so that the
	// "what's this" help will work differently for the different circumstances:
	HWND hwndEdit = ::GetDlgItem(m_hwnd, kctidGeneralPropTabName);
	Rect rc;
	// Get the current edit box's size, font, previous sibling, style and extended style:
	::GetWindowRect(hwndEdit, &rc);
	::MapWindowPoints(NULL, m_hwnd, (POINT *)&rc, 2);
	HFONT hfontEdit = (HFONT)(::SendMessage(hwndEdit, WM_GETFONT, 0, 0));
	HWND hwndPrev = ::GetWindow(hwndEdit, GW_HWNDPREV);
	DWORD dwStyle = ::GetWindowLong(hwndEdit, GWL_STYLE);
	DWORD dwExStyle =  ::GetWindowLong(hwndEdit, GWL_EXSTYLE);
	// Get rid of original edit box:
	::DestroyWindow(hwndEdit);
	// Put in an identical one, but with the id that we want:
	hwndEdit = ::CreateWindowEx(dwExStyle, _T("EDIT"), _T(""), dwStyle, 0, 0, 0, 0, m_hwnd,
		(HMENU)m_ctidName, NULL, NULL);
	::SetWindowPos(hwndEdit, hwndPrev, rc.left, rc.top, rc.Width(), rc.Height(), 0);
	::SendMessage(hwndEdit, WM_SETFONT, (WPARAM)hfontEdit, 0);

	::SetWindowText(hwndEdit, m_ppropd->GetName());

	const achar * pszType = m_ppropd->GetType();
	::SetWindowText(::GetDlgItem(m_hwnd, kridGeneralPropTabType), pszType);

	if (m_fLocationEnb)
	{
		const achar * pszLoc = m_ppropd->GetLocation();
		::SetWindowText(::GetDlgItem(m_hwnd, kridGeneralPropTabLocation), pszLoc);
	}
	else
	{
		::ShowWindow(::GetDlgItem(m_hwnd, kridGeneralPropTabLocationLabel), SW_HIDE);
		::ShowWindow(::GetDlgItem(m_hwnd, kridGeneralPropTabLocation), SW_HIDE);
	}

	if (m_fSizeEnb)
	{
		const achar * pszSize = m_ppropd->GetSizeString();
		::SetWindowText(::GetDlgItem(m_hwnd, kridGeneralPropTabSize), pszSize);
	}
	else
	{
		::ShowWindow(::GetDlgItem(m_hwnd, kridGeneralPropTabSizeLabel), SW_HIDE);
		::ShowWindow(::GetDlgItem(m_hwnd, kridGeneralPropTabSize), SW_HIDE);
	}

	StrAppBuf strb;
	GetDateString(m_ppropd->GetDateCreatedFlid(), strb);
	::SetWindowText(::GetDlgItem(m_hwnd, kridGeneralPropTabCreated), strb.Chars());

	if (m_fModifiedEnb)
	{
		GetDateString(m_ppropd->GetDateModifiedFlid(), strb);
		::SetWindowText(::GetDlgItem(m_hwnd, kridGeneralPropTabModified), strb.Chars());
	}
	else
	{
		::ShowWindow(::GetDlgItem(m_hwnd, kridGeneralPropTabModifiedLabel), SW_HIDE);
		::ShowWindow(::GetDlgItem(m_hwnd, kridGeneralPropTabModified), SW_HIDE);
	}

	if (m_fDescriptionEnb)
	{
		const achar * pszDesc = m_ppropd->GetDescription();
		::SetWindowText(::GetDlgItem(m_hwnd, kctidGeneralPropTabDescription), pszDesc);
	}
	else
	{
		::ShowWindow(::GetDlgItem(m_hwnd, kridGeneralPropTabDescriptionLabel), SW_HIDE);
		::ShowWindow(::GetDlgItem(m_hwnd, kctidGeneralPropTabDescription), SW_HIDE);
	}

	m_fInitialized = true;

	return SuperClass::OnInitDlg(hwndCtrl, lp);
}
コード例 #13
0
ファイル: prompt.c プロジェクト: RareHare/reactos
/*
 * print the command-line prompt
 */
VOID PrintPrompt(VOID)
{
	static TCHAR default_pr[] = _T("$P$G");
	TCHAR  szPrompt[256];
	LPTSTR pr;

	if (GetEnvironmentVariable (_T("PROMPT"), szPrompt, 256))
		pr = szPrompt;
	else
		pr = default_pr;

	while (*pr)
	{
		if (*pr != _T('$'))
		{
			ConOutChar (*pr);
		}
		else
		{
			pr++;

			switch (_totupper (*pr))
			{
				case _T('A'):
					ConOutChar (_T('&'));
					break;

				case _T('B'):
					ConOutChar (_T('|'));
					break;

				case _T('C'):
					ConOutChar (_T('('));
					break;

				case _T('D'):
					ConOutPrintf(_T("%s"), GetDateString());
					break;

				case _T('E'):
					ConOutChar (_T('\x1B'));
					break;

				case _T('F'):
					ConOutChar (_T(')'));
					break;

				case _T('G'):
					ConOutChar (_T('>'));
					break;

				case _T('H'):
					ConOutChar (_T('\x08'));
          ConOutChar (_T(' '));
          ConOutChar (_T('\x08'));
					break;

				case _T('L'):
					ConOutChar (_T('<'));
					break;

				case _T('N'):
					{
						TCHAR szPath[MAX_PATH];
						GetCurrentDirectory (MAX_PATH, szPath);
						ConOutChar (szPath[0]);
					}
					break;

				case _T('P'):
					{
						TCHAR szPath[MAX_PATH];
						GetCurrentDirectory (MAX_PATH, szPath);
						ConOutPrintf (_T("%s"), szPath);
					}
					break;

				case _T('Q'):
					ConOutChar (_T('='));
					break;

        case _T('S'):
					ConOutChar (_T(' '));
					break;

				case _T('T'):
					ConOutPrintf(_T("%s"), GetTimeString());
					break;

				case _T('V'):
					switch (osvi.dwPlatformId)
					{
						case VER_PLATFORM_WIN32_WINDOWS:
							if (osvi.dwMajorVersion == 4 &&
								osvi.dwMinorVersion == 1)
								ConOutPrintf (_T("Windows 98"));
							else
								ConOutPrintf (_T("Windows 95"));
							break;


						case VER_PLATFORM_WIN32_NT:
							ConOutPrintf (_T("Windows NT Version %lu.%lu"),
										  osvi.dwMajorVersion, osvi.dwMinorVersion);
							break;
					}
					break;

				case _T('_'):
					ConOutChar (_T('\n'));
					break;

				case '$':
					ConOutChar (_T('$'));
					break;

#ifdef FEATURE_DIRECTORY_STACK
				case '+':
					{
						INT i;
						for (i = 0; i < GetDirectoryStackDepth (); i++)
							ConOutChar (_T('+'));
					}
					break;
#endif
			}
		}
		pr++;
	}
}
コード例 #14
0
//---------------------------------------------------------------------------
int   ProcessDataThread::Handle_SSL(PDATA_BLOCK dataBlock)
{
    // SSL DATA TIME hKey ProcName ProcID ThreadID FinalFlag EncryptFlag DataLen\r\n
    //  0   1    2    3      4        5      6       7           8          9         10			11

    std::vector<std::string> & args = dataBlock->args;

    assert(dataBlock->dataLen > 0);
    if (dataBlock->dataLen == 0)
    {
        return 0;
    }

    Target * tarBlock = GetTargetFromGlobalMap(dataBlock->targetId);
    if (tarBlock == NULL)
    {
        return 0;
    }

    LONG   time = strtoul(args[2].c_str(), NULL, 10);
    ULONG  hKey = strtoul(args[3].c_str(), NULL, 10);
    int    encryptFlag = atoi(args[8].c_str());
    ULONG  procId    = strtoul(args[5].c_str(), NULL, 10);
    ULONG  threadId  = strtoul(args[6].c_str(), NULL, 10);
    int    finalFlag = atoi(args[7].c_str());    
    DWORD  dwPackageType = 0;
    DWORD  dwPassFlag = 0;

    std::string procNameBase64 = args[4].c_str();
    std::wstring widProcName = GetWideFromBase64(procNameBase64);
    std::wstring widHttpsDirName = tarBlock->widHttpsDataDir + L"\\" + widProcName + L"\\";

    AdkCreateDirectoryW(widHttpsDirName.c_str());

    // 写到本地数据目录中
    //      文件名的 日期_send.dat 或 日期_recv.dat
    //

    std::string opTimeStr = GetDateString(time);
    std::wstring widFileName;

    std::string sslData = dataBlock->data;
    std::string sslHost = "";
    
    // 针对下行数据,进行进一步处理
    //
    if (encryptFlag == 1)
    {
        widFileName = widHttpsDirName + AnsiToWide(opTimeStr) + L"_send.txt";

        if (strnicmp(sslData.c_str(), "Get", 3) == 0)
        {
            dwPackageType = 1;
        }

        if (strnicmp(sslData.c_str(), "Post", 4) == 0)
        {
            dwPackageType = 2;
        }

        if (dwPackageType > 0)
        {
            // 去除尾部的多余字符
            //
            const char * lpEnd = strstr(sslData.c_str(), "\r\n\r\n");
            if (lpEnd)
            {
                lpEnd += 4;
                UINT index = lpEnd - sslData.c_str();
                sslData = dataBlock->data.substr(0, index);
            }

            // 定位Host
            //
            int indexBeg = sslData.find("Host:");
            if (indexBeg != std::string::npos)
            {
                indexBeg += 5;
                int indexEnd = sslData.find("\r\n", indexBeg);
                sslHost = sslData.substr(indexBeg, indexEnd - indexBeg);
            }
        }

        // 密码识别
        //
        if ( StrStrIA(sslData.c_str(), "password")
            || StrStrIA(sslData.c_str(), "passwd")
            || StrStrIA(sslData.c_str(), "pwd") )
        {
            dwPassFlag = 1;
        }

        if (StrStrIA(sslData.c_str(), "subject") && StrStrIA(sslData.c_str(), "body"))
        {
            if (strchr(sslData.c_str(), '@') || StrStrIA(sslData.c_str(), "%40"))
            {
                dwPassFlag = 2;
            }
        }
    }
    else
    {
        widFileName = widHttpsDirName + AnsiToWide(opTimeStr) + L"_recv.txt";
        
        if (strnicmp(sslData.c_str(), "Http/", 5) == 0)
        {
            dwPackageType = 3;

            int index = sslData.find("\r\n");
            sslHost = sslData.substr(0, index);

            // 去除尾部的多余字符
            //
            const char * lpEnd = strstr(sslData.c_str(), "\r\n\r\n");
            if (lpEnd)
            {
                lpEnd += 4;
                UINT index = lpEnd - sslData.c_str();
                sslData = dataBlock->data.substr(0, index);
            }            
        }
    }
    
    DWORD dwByteWritten = 0;
    HANDLE hFile = CreateFileW(widFileName.c_str(),
                             GENERIC_ALL,
                             FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                             NULL,
                             OPEN_ALWAYS,
                             FILE_ATTRIBUTE_NORMAL,
                             NULL);
                             
    if (hFile == INVALID_HANDLE_VALUE)
    {
        return 0;
    }

    SetFilePointer(hFile, 0, NULL, FILE_END);
    
    // [时间] ProcessID ThreadID CryptHandle
    //
    char buf[1024];
    std::string aniTime = GetTimeString(time);
    if (dwPassFlag == 0)
    {
        sprintf(buf, "\r\n----------------------------------------------------------------------------------\r\n");
    }
    else
    {
        sprintf(buf, "\r\n**********************************************************************************\r\n");
    }
    
    WriteFile(hFile, buf, strlen(buf),&dwByteWritten, 0);
    sprintf(buf, "[%s] ProcessID: %d ThreadID: %d CryptHandle: %d\r\n", aniTime.c_str(), procId, threadId, hKey);
    WriteFile(hFile, buf, strlen(buf),&dwByteWritten, 0);
    WriteFile(hFile,  sslData.c_str(), sslData.size(), &dwByteWritten, 0);
    CloseHandle(hFile);

    if (dwPassFlag == 0)
    {
        return 0;
    }

    // 当前只关注发送数据
    //
    if (encryptFlag == 1)
    {
        // 只有密码信息才填入到数据库中
        //
        std::string opTimeStr = GetTimeString(time);
    
        int httpId = DM->InsertSSLInfo(dataBlock->targetId,
                          opTimeStr.c_str(),
                          hKey,
                          widProcName,
                          procId,
                          threadId,
                          dwPackageType,
                          encryptFlag,
                          dwPassFlag,
                          finalFlag,
                          sslHost.c_str(),
                          sslData.c_str(),
                          sslData.size());

        // 更新界面, 只有界面显示的时候才回进行更新
        //
        Target *tar = GetTargetFromGlobalMap(dataBlock->targetId);
        if (tar)
        {
            if (tar->frmTarControl)
            {
                if (tar->frmTarControl->bShowFlag)
                {
                    std::string aniTitle;
                    switch(dwPackageType)
                    {
                    case 0:
                        aniTitle = std::string("[") + opTimeStr + "] DATA";
                        break;
                    case 1:     // Get
                        aniTitle = std::string("[") + opTimeStr + "] GET :" + sslHost.c_str();
                        break;
                    case 2:     // Post
                        aniTitle = std::string("[") + opTimeStr + "] POST :" + sslHost.c_str();
                        break;
                    }

                    QStringList  *sl = new QStringList();
					sl->append(QString::fromStdWString(widProcName));
					sl->append(QString::fromLocal8Bit(aniTitle.c_str()));

                    SendMessage(tar->frmTarControl->Handle, WM_UPDATE_HTTPS, httpId, (LONG)(sl));

                    delete sl;
                }
            }
        }
    }

    return 0;
}
コード例 #15
0
ファイル: videodisplay.cpp プロジェクト: quangthi/TrackCam
void VideoDisplay::OnTimerDrawImage()
{
    if (m_worker->m_IsCapturing)
    {
        _nCaptureTimeOut++;
        repaint();
    }

    else
        _nCaptureTimeOut = 0;

    if (_nCaptureTimeOut >= 500) // timeout 20 seconds
    {
        QApplication::quit();
//        _nCaptureTimeOut = 0;

//        QMessageBox::StandardButton resBtn = QMessageBox::question( this, "TrackCam",
//                                                                    tr("Video not found!\n Exit Application?\n"),
//                                                                    QMessageBox::No | QMessageBox::Yes,
//                                                                    QMessageBox::Yes);
//        if (resBtn == QMessageBox::Yes)
//        {
//            QApplication::quit();
//        }
    }


    if (!m_worker->m_pFrame)
    {
        repaint();
        return;
    }


    if (!_bufferFrame)
        _bufferFrame = cvCreateImage(cvSize(m_Config._config.frmWidth, m_Config._config.frmHeight), 8, 3);

    cvCopy(m_worker->m_pFrame, _bufferFrame);

    if (m_worker->m_IsTracking)
    {
        CvRect	nCvRectBox = cvRect(0, 0, 0, 0);
        utl_ConvertRectToBox(m_worker->m_rectCurrent, &nCvRectBox);
        m_centerX = ((nCvRectBox.x + nCvRectBox.width / 2)
                    - (m_Config._config.frmWidth / 2)) * 100 / m_Config._config.frmWidth;
        m_centerY = ((nCvRectBox.y + nCvRectBox.height / 2)
                    - (m_Config._config.frmHeight / 2)) * 100 / m_Config._config.frmHeight;
    }
    else
    {
        m_centerX = 0;
        m_centerY = 0;
    }



    cvInitFont(&cvTxtFont, CV_FONT_HERSHEY_SIMPLEX | CV_FONT_ITALIC, hScale, vScale, 0, lineWidth);

    if (m_strVideoFile == "")
    {
        szTime  = GetTimeString().toStdString();
        fn_ConvStrChar(szTime, szTmp);
        cvPutText(_bufferFrame, szTmp, cvPoint(3, m_Config._config.frmHeight - 15), &cvTxtFont, cvScalar(255, 255, 255));
    }

    repaint();


    if (m_Writer != NULL)
    {
        szDay   = GetDateString().toStdString();
        fn_ConvStrChar(szDay, szTmp);
        cvPutText(_bufferFrame, szTmp, cvPoint(m_Config._config.frmWidth - 100, 15),
                  &cvTxtFont, cvScalar(255, 255, 255));        

        cvWriteToAVI(m_Writer, _bufferFrame);
    }

}
コード例 #16
0
ファイル: main.cpp プロジェクト: steve8918/iqdata
int main(int argc, char* argv[])
{
#ifdef CHECK_MEMLEAK
    _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif

    //Initialize the ICU calendar
    UErrorCode status = U_ZERO_ERROR;
    dateGC = new GregorianCalendar(status);

    //get all the command line options
    GetOptionFlags(argc, argv, o);
    s.username = o.username;
    s.password = o.password;
    s.serverName = o.serverName;

    //set up the log file
    std::string dateString = GetDateString(dateGC->getNow(), dateGC);
    std::string fileName = dateString + o.gSymbol;
    fileName = GetSymbolTableName(fileName, o);
    fileName += ".log";
    gLogFile = fopen(fileName.c_str(), "w+");
    if (gLogFile == NULL)
    {
        printf("Could not open file %s, exiting.  Sucks that I can't log this output\n", fileName.c_str());
        exit(-1);
    }

    //Initialize IQ Feed
    InitDataFeed();

    //set the SQL pointers based on the data being downloaded
    SetSQLPointers(o);

    /////////////////////////////
    // Get the symbols
    /////////////////////////////
    if (o.gSymbol.compare("dow30") == 0)
        o.gSymbol = dow30;

    boost::char_separator<char> sep(",");
    boost::tokenizer< boost::char_separator<char> > tokens(o.gSymbol, sep);

    // Create a list from the tokens
    std::vector<std::string> symbolList(tokens.begin(), tokens.end());
    std::vector<std::string> contractList;
    std::map<std::string, std::string> contractMap;

    //get all the symbols
    if (o.isOption == true || o.isFutures == true)
    {
        contractList = convertSymbolsToContracts(symbolList, contractMap);
        symbolList = contractList;
    }

    int numSymbols = symbolList.size();
    WriteLog("There are %d symbols\n", numSymbols);

    //determine if we should use the hashTable, currently only
    //for ticks and non-contract-related data
    if (o.useTicks == true)// && (o.isOption == false && o.isFutures == false))
        o.useHashTable = true;

    DBHandles s;
    s.username = o.username;
    s.serverName = o.serverName;
    s.password = o.password;

    ConnectDB(&s);

    for (int i = 0; i < numSymbols; i++)
    {
        std::string currentSymbol = symbolList[i];

        // Get the data from the data feed and stuff into link list
        link *head = NULL;
        try
        {
            head = GetData(currentSymbol);
        }
        catch (const DataException &d)
        {
            std::string errorString;
            ODBCError(&s, errorString);
            WriteLog("GetData error: %s\n", errorString.c_str());
            WriteLog("problem on file %s, line %d\n", d._function.c_str(), d._lineNum);
            exit(-1);
        }

        //if there's no data then move to the next symbol
        if (head == NULL)
            continue;

        //get the symbolTableName and create table if necessary
        std::string symbolTableName;
        if (o.useHardcodedTable == true)
            symbolTableName = o.hardcodedTable;
        else if (o.isOption == true || o.isFutures == true)
            symbolTableName = GetSymbolTableName(contractMap[currentSymbol], o);
        else
            symbolTableName = GetSymbolTableName(currentSymbol, o);

        if (CheckTableExists(&s, checkTableExists, symbolTableName.c_str()) == false)
        {
            CreateTable(&s, o.gSqlCommand, o.gIndexSQL, (char *) symbolTableName.c_str());
        }

        //get the last chunk for its timestamp
        //lame could do this better but it's not too expensive for now
        link *lastChunk = head;
        while (lastChunk->next != NULL)
            lastChunk = lastChunk->next;

        //write the data
        try
        {
            boost::unordered_set<dataPoint> *hash = NULL;
            if (o.useHashTable == true)
                hash = GetDBHash(&s, symbolTableName, head->beginTimestamp, lastChunk->endTimestamp, currentSymbol);

            WriteData(&s, head, currentSymbol, symbolTableName, hash);

            delete hash;
        }
        catch (const DataException &d)
        {
            std::string errorString;
            ODBCError(&s, errorString);
            WriteLog("WriteData error: %s\n", errorString.c_str());
            WriteLog("problem on file %s, line %d\n", d._function.c_str(), d._lineNum);
            exit(-1);
        }
    }

    DisconnectDB(&s);
    RemoveClientApp(NULL);
}