Exemplo n.º 1
0
INT cmd_move (LPTSTR param)
{
    LPTSTR *arg;
    INT argc, i, nFiles;
    LPTSTR pszDest;
    TCHAR szDestPath[MAX_PATH];
    TCHAR szFullDestPath[MAX_PATH];
    TCHAR szSrcDirPath[MAX_PATH];
    TCHAR szSrcPath[MAX_PATH];
    TCHAR szFullSrcPath[MAX_PATH];
    DWORD dwFlags = 0;
    INT nOverwrite = 0;
    WIN32_FIND_DATA findBuffer;
    HANDLE hFile;

    /* used only when source and destination  directories are on different volume */
    HANDLE hDestFile = NULL;
    WIN32_FIND_DATA findDestBuffer;
    TCHAR szMoveDest[MAX_PATH];
    TCHAR szMoveSrc[MAX_PATH];
    LPTSTR pszDestDirPointer;
    LPTSTR pszSrcDirPointer;
    INT nDirLevel = 0;

    LPTSTR pszFile;
    BOOL OnlyOneFile;
    BOOL FoundFile;
    BOOL MoveStatus;
    DWORD dwMoveFlags = 0;
    DWORD dwMoveStatusFlags = 0;

    if (!_tcsncmp (param, _T("/?"), 2))
    {
#if 0
        ConOutPuts (_T("Moves files and renames files and directories.\n\n"
            "To move one or more files:\n"
            "MOVE [/N][/Y|/-Y][drive:][path]filename1[,...] destination\n"
            "\n"
            "To rename a directory:\n"
            "MOVE [/N][/Y|/-Y][drive:][path]dirname1 dirname2\n"
            "\n"
            "  [drive:][path]filename1  Specifies the location and name of the file\n"
            "                           or files you want to move.\n"
            "  /N                       Nothing. Don everthing but move files or directories.\n"
            "  /Y\n"
            "  /-Y\n"
            "..."));
#else
        ConOutResPaging(TRUE,STRING_MOVE_HELP2);
#endif
        return 0;
    }

    nErrorLevel = 0;
    arg = splitspace(param, &argc);

    /* read options */
    for (i = 0; i < argc; i++)
    {
        if (!_tcsicmp(arg[i], _T("/N")))
            dwFlags |= MOVE_NOTHING;
        else if (!_tcsicmp(arg[i], _T("/Y")))
            dwFlags |= MOVE_OVER_YES;
        else if (!_tcsicmp(arg[i], _T("/-Y")))
            dwFlags |= MOVE_OVER_NO;
        else
            break;
    }
    nFiles = argc - i;

    if (nFiles < 1)
    {
        /* there must be at least one pathspec */
        error_req_param_missing();
        freep(arg);
        return 1;
    }

    if (nFiles > 2)
    {
        /* there are more than two pathspecs */
        error_too_many_parameters(param);
        freep(arg);
        return 1;
    }

    /* If no destination is given, default to current directory */
    pszDest = (nFiles == 1) ? _T(".") : arg[i + 1];

    /* check for wildcards in source and destination */
    if (_tcschr(pszDest, _T('*')) != NULL || _tcschr(pszDest, _T('?')) != NULL)
    {
        /* '*'/'?' in dest, this doesnt happen.  give folder name instead*/
        error_invalid_parameter_format(pszDest);
        freep(arg);
        return 1;
    }
    if (_tcschr(arg[i], _T('*')) != NULL || _tcschr(arg[i], _T('?')) != NULL)
    {
        dwMoveStatusFlags |= MOVE_SOURCE_HAS_WILD;
    }

    /* get destination */
    GetFullPathName (pszDest, MAX_PATH, szDestPath, NULL);
    TRACE ("Destination: %s\n", debugstr_aw(szDestPath));

    /* get source folder */
    GetFullPathName(arg[i], MAX_PATH, szSrcDirPath, &pszFile);
    if (pszFile != NULL)
        *pszFile = _T('\0');
    TRACE ("Source Folder: %s\n", debugstr_aw(szSrcDirPath));

    hFile = FindFirstFile (arg[i], &findBuffer);
    if (hFile == INVALID_HANDLE_VALUE)
    {
        ErrorMessage (GetLastError (), arg[i]);
        freep (arg);
        return 1;
    }

    /* check for special cases "." and ".." and if found skip them */
    FoundFile = TRUE;
    while(FoundFile &&
          (_tcscmp(findBuffer.cFileName,_T(".")) == 0 ||
           _tcscmp(findBuffer.cFileName,_T("..")) == 0))
        FoundFile = FindNextFile (hFile, &findBuffer);

    if (!FoundFile)
    {
        /* what? we don't have anything to move? */
        error_file_not_found();
        FindClose(hFile);
        freep(arg);
        return 1;
    }

    OnlyOneFile = TRUE;
    /* check if there can be found files as files have first priority */
    if (findBuffer.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        dwMoveStatusFlags |= MOVE_SOURCE_IS_DIR;
    else
        dwMoveStatusFlags |= MOVE_SOURCE_IS_FILE;
    while(OnlyOneFile && FindNextFile(hFile,&findBuffer))
    {
        if (!(findBuffer.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
        {
            ConOutPrintf(_T(""));
            if (dwMoveStatusFlags & MOVE_SOURCE_IS_FILE) OnlyOneFile = FALSE;
            else
            {	/* this has been done this way so that we don't disturb other settings if they have been set before this */
                dwMoveStatusFlags |= MOVE_SOURCE_IS_FILE;
                dwMoveStatusFlags &= ~MOVE_SOURCE_IS_DIR;
            }
        }
    }
    FindClose(hFile);

    TRACE ("Do we have only one file: %s\n", OnlyOneFile ? "TRUE" : "FALSE");

    /* we have to start again to be sure we don't miss any files or folders*/
    hFile = FindFirstFile (arg[i], &findBuffer);
    if (hFile == INVALID_HANDLE_VALUE)
    {
        ErrorMessage (GetLastError (), arg[i]);
        freep (arg);
        return 1;
    }

    /* check for special cases "." and ".." and if found skip them */
    FoundFile = TRUE;
    while(FoundFile &&
          (_tcscmp(findBuffer.cFileName,_T(".")) == 0 ||
           _tcscmp(findBuffer.cFileName,_T("..")) == 0))
        FoundFile = FindNextFile (hFile, &findBuffer);

    if (!FoundFile)
    {
        /* huh? somebody removed files and/or folders which were there */
        error_file_not_found();
        FindClose(hFile);
        freep(arg);
        return 1;
    }

    /* check if source and destination paths are on different volumes */
    if (szSrcDirPath[0] != szDestPath[0])
        dwMoveStatusFlags |= MOVE_PATHS_ON_DIF_VOL;

    /* move it */
    do
    {
        TRACE ("Found file/directory: %s\n", debugstr_aw(findBuffer.cFileName));
        nOverwrite = 1;
        dwMoveFlags = 0;
        dwMoveStatusFlags &= ~MOVE_DEST_IS_FILE &
                            ~MOVE_DEST_IS_DIR &
                            ~MOVE_SRC_CURRENT_IS_DIR &
                            ~MOVE_DEST_EXISTS;
        _tcscpy(szFullSrcPath,szSrcDirPath);
        if (szFullSrcPath[_tcslen(szFullSrcPath) -  1] != _T('\\'))
            _tcscat (szFullSrcPath, _T("\\"));
        _tcscat(szFullSrcPath,findBuffer.cFileName);
        _tcscpy(szSrcPath, szFullSrcPath);

        if (IsExistingDirectory(szSrcPath))
        {
            /* source is directory */
            if (dwMoveStatusFlags & MOVE_SOURCE_IS_FILE)
            {
                dwMoveStatusFlags |= MOVE_SRC_CURRENT_IS_DIR; /* source is file but at the current round we found a directory */
                continue;
            }
            TRACE ("Source is dir: %s\n", debugstr_aw(szSrcPath));
            dwMoveFlags = MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH | MOVEFILE_COPY_ALLOWED;
        }

        /* if source is file we don't need to do anything special */
        if (IsExistingDirectory(szDestPath))
        {
            /* destination is existing directory */
            TRACE ("Destination is directory: %s\n", debugstr_aw(szDestPath));

            dwMoveStatusFlags |= MOVE_DEST_IS_DIR;

            /*build the dest string(accounts for *)*/
            _tcscpy (szFullDestPath, szDestPath);
            /*check to see if there is an ending slash, if not add one*/
            if (szFullDestPath[_tcslen(szFullDestPath) -  1] != _T('\\'))
                _tcscat (szFullDestPath, _T("\\"));
            _tcscat (szFullDestPath, findBuffer.cFileName);

            if (IsExistingFile(szFullDestPath) || IsExistingDirectory(szFullDestPath))
                dwMoveStatusFlags |= MOVE_DEST_EXISTS;

            dwMoveFlags |= MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH | MOVEFILE_COPY_ALLOWED;
        }
        if (IsExistingFile(szDestPath))
        {
            /* destination is a file */
            TRACE ("Destination is file: %s\n", debugstr_aw(szDestPath));

            dwMoveStatusFlags |= MOVE_DEST_IS_FILE | MOVE_DEST_EXISTS;
            _tcscpy (szFullDestPath, szDestPath);

            dwMoveFlags |= MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH | MOVEFILE_COPY_ALLOWED;
        }

        TRACE ("Move Status Flags: 0x%X\n",dwMoveStatusFlags);

        if (dwMoveStatusFlags & MOVE_SOURCE_IS_DIR &&
            dwMoveStatusFlags & MOVE_DEST_IS_DIR &&
            dwMoveStatusFlags & MOVE_SOURCE_HAS_WILD)
        {
            /* We are not allowed to have existing source and destination dir when there is wildcard in source */
            error_syntax(NULL);
            FindClose(hFile);
            freep(arg);
            return 1;
        }
        if (!(dwMoveStatusFlags & (MOVE_DEST_IS_FILE | MOVE_DEST_IS_DIR)))
        {
            /* destination doesn't exist */
            _tcscpy (szFullDestPath, szDestPath);
            if (dwMoveStatusFlags & MOVE_SOURCE_IS_FILE) dwMoveStatusFlags |= MOVE_DEST_IS_FILE;
            if (dwMoveStatusFlags & MOVE_SOURCE_IS_DIR) dwMoveStatusFlags |= MOVE_DEST_IS_DIR;

            dwMoveFlags |= MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH | MOVEFILE_COPY_ALLOWED;
        }

        if (dwMoveStatusFlags & MOVE_SOURCE_IS_FILE &&
            dwMoveStatusFlags & MOVE_DEST_IS_FILE &&
            !OnlyOneFile)
        {
            /*source has many files but there is only one destination file*/
            error_invalid_parameter_format(pszDest);
            FindClose(hFile);
            freep (arg);
            return 1;
        }

        /*checks to make sure user wanted/wants the override*/
        if ((dwFlags & MOVE_OVER_NO) &&
           (dwMoveStatusFlags & MOVE_DEST_EXISTS))
            continue;
        if (!(dwFlags & MOVE_OVER_YES) &&
            (dwMoveStatusFlags & MOVE_DEST_EXISTS))
            nOverwrite = MoveOverwrite (szFullDestPath);
        if (nOverwrite == PROMPT_NO || nOverwrite == PROMPT_BREAK)
            continue;
        if (nOverwrite == PROMPT_ALL)
            dwFlags |= MOVE_OVER_YES;

        ConOutPrintf (_T("%s => %s "), szSrcPath, szFullDestPath);

        /* are we really supposed to do something */
        if (dwFlags & MOVE_NOTHING)
            continue;

        /*move the file*/
        if (!(dwMoveStatusFlags & MOVE_SOURCE_IS_DIR &&
            dwMoveStatusFlags & MOVE_PATHS_ON_DIF_VOL))
            /* we aren't moving source folder to different drive */
            MoveStatus = MoveFileEx (szSrcPath, szFullDestPath, dwMoveFlags);
        else
        {	/* we are moving source folder to different drive */
            _tcscpy(szMoveDest, szFullDestPath);
            _tcscpy(szMoveSrc, szSrcPath);
            DeleteFile(szMoveDest);
            MoveStatus = CreateDirectory(szMoveDest, NULL); /* we use default security settings */
            if (MoveStatus)
            {
                _tcscat(szMoveDest,_T("\\"));
                _tcscat(szMoveSrc,_T("\\"));
                nDirLevel = 0;
                pszDestDirPointer = szMoveDest + _tcslen(szMoveDest);
                pszSrcDirPointer = szMoveSrc + _tcslen(szMoveSrc);
                _tcscpy(pszSrcDirPointer,_T("*.*"));
                hDestFile = FindFirstFile(szMoveSrc, &findDestBuffer);
                if (hDestFile == INVALID_HANDLE_VALUE)
                    MoveStatus = FALSE;
                else
                {
                    BOOL FirstTime = TRUE;
                    FoundFile = TRUE;
                    MoveStatus = FALSE;
                    while(FoundFile)
                    {
                        if (FirstTime)
                            FirstTime = FALSE;
                        else
                            FoundFile = FindNextFile (hDestFile, &findDestBuffer);

                        if (!FoundFile)
                        {
                            /* Nothing to do in this folder so we stop working on it */
                            FindClose(hDestFile);
                            (pszSrcDirPointer)--;
                            (pszDestDirPointer)--;
                            _tcscpy(pszSrcDirPointer,_T(""));
                            _tcscpy(pszDestDirPointer,_T(""));
                            if (nDirLevel > 0)
                            {
                                TCHAR szTempPath[MAX_PATH];
                                INT_PTR nDiff;

                                FoundFile = TRUE; /* we need to continue our seek for files */
                                nDirLevel--;
                                RemoveDirectory(szMoveSrc);
                                GetDirectory(szMoveSrc,szTempPath,0);
                                nDiff = _tcslen(szMoveSrc) - _tcslen(szTempPath);
                                pszSrcDirPointer = pszSrcDirPointer - nDiff;
                                _tcscpy(pszSrcDirPointer,_T(""));
                                GetDirectory(szMoveDest,szTempPath,0);
                                nDiff = _tcslen(szMoveDest) - _tcslen(szTempPath);
                                pszDestDirPointer = pszDestDirPointer - nDiff;
                                _tcscpy(pszDestDirPointer,_T(""));
                                if (szMoveSrc[_tcslen(szMoveSrc) -  1] != _T('\\'))
                                    _tcscat (szMoveSrc, _T("\\"));
                                if (szMoveDest[_tcslen(szMoveDest) -  1] != _T('\\'))
                                    _tcscat (szMoveDest, _T("\\"));
                                pszDestDirPointer = szMoveDest + _tcslen(szMoveDest);
                                pszSrcDirPointer = szMoveSrc + _tcslen(szMoveSrc);
                                _tcscpy(pszSrcDirPointer,_T("*.*"));
                                hDestFile = FindFirstFile(szMoveSrc, &findDestBuffer);
                                if (hDestFile == INVALID_HANDLE_VALUE)
                                    continue;
                                FirstTime = TRUE;
                            }
                            else
                            {
                                MoveStatus = TRUE; /* we moved everything so lets tell user about it */
                                RemoveDirectory(szMoveSrc);
                            }
                            continue;
                        }

                        /* if we find "." or ".." we'll skip them */
                        if (_tcscmp(findDestBuffer.cFileName,_T(".")) == 0 ||
                            _tcscmp(findDestBuffer.cFileName,_T("..")) == 0)
                            continue;

                        _tcscpy(pszSrcDirPointer, findDestBuffer.cFileName);
                        _tcscpy(pszDestDirPointer, findDestBuffer.cFileName);
                        if (IsExistingFile(szMoveSrc))
                        {
                            FoundFile = CopyFile(szMoveSrc, szMoveDest, FALSE);
                            if (!FoundFile) continue;
                            DeleteFile(szMoveSrc);
                        }
                        else
                        {
                            FindClose(hDestFile);
                            CreateDirectory(szMoveDest, NULL);
                            _tcscat(szMoveDest,_T("\\"));
                            _tcscat(szMoveSrc,_T("\\"));
                            nDirLevel++;
                            pszDestDirPointer = szMoveDest + _tcslen(szMoveDest);
                            pszSrcDirPointer = szMoveSrc + _tcslen(szMoveSrc);
                            _tcscpy(pszSrcDirPointer,_T("*.*"));
                            hDestFile = FindFirstFile(szMoveSrc, &findDestBuffer);
                            if (hDestFile == INVALID_HANDLE_VALUE)
                            {
                                FoundFile = FALSE;
                                continue;
                            }
                            FirstTime = TRUE;
                        }
                    }
                }
            }
        }
        if (MoveStatus)
            ConOutResPrintf(STRING_MOVE_ERROR1);
        else
            ConOutResPrintf(STRING_MOVE_ERROR2);
    }
    while ((!OnlyOneFile || dwMoveStatusFlags & MOVE_SRC_CURRENT_IS_DIR ) &&
            !(dwMoveStatusFlags & MOVE_SOURCE_IS_DIR) &&
            FindNextFile (hFile, &findBuffer));
    FindClose (hFile);

    if(hDestFile && hDestFile != INVALID_HANDLE_VALUE)
        FindClose(hDestFile);

    freep (arg);
    return 0;
}
void OpenSMOKE_CHEMKINInterpreter_ThermoData::ReadThermoData(const std::string file_name, ofstream *_fLog)
{
	const int SIZE = 400;
	char comment[SIZE];

	fLog = _fLog;

	ifstream fInput;
	openInputFileAndControl(fInput, file_name);

	// ---------------------------------------------------------------
	// Reading lines
	// ---------------------------------------------------------------
	lines.push_back("List of lines");

	while(!fInput.eof())
	{
		fInput.getline(comment, SIZE);
		lines.push_back(comment);
	}
	fInput.close();

	number_of_lines = lines.size()-1;

	// ---------------------------------------------------------------
	// Parsing lines
	// ---------------------------------------------------------------
	int i;
	for(i=1;i<=number_of_lines;i++)
	{
		if (CheckForBlankLine(lines[i]) == true)		indexBlankLines.Append(i);
		else if (CheckForCommentLine(lines[i]) == true)	indexCommentLines.Append(i);
		else if (CheckForEndLine(lines[i]) == true)		indexCommentLines.Append(i);		
		else											indexLines.Append(i);
	}

	int count_additional=0;
	for(i=1;i<=indexLines.Size();i++)
		count_additional += StringFind(lines[indexLines[i]], "1&");
	total_number_of_species = (indexLines.Size()-count_additional)/4;

	*fLog << " ----------------------------------------------------------------" << endl;
	*fLog << "                     Thermodynamic Database                      " << endl;
	*fLog << " ----------------------------------------------------------------" << endl;
	*fLog << "    Total number of full lines:    " << indexLines.Size()			<< endl;
	*fLog << "    Total number of blank lines:   " << indexBlankLines.Size()		<< endl;
	*fLog << "    Total number of comment lines: " << indexCommentLines.Size()	<< endl;
	*fLog << "    Total number of lines:         " << number_of_lines			<< endl;
	*fLog << "    Total number of species:       " << total_number_of_species			<< endl;
	*fLog << " ----------------------------------------------------------------" << endl;

	species = new OpenSMOKE_CHEMKINInterpreter_ThermoSpecies[total_number_of_species+1];
	
	vector<string> instructions;
	
	// ---------------------------------------------------------------
	// First line
	// ---------------------------------------------------------------
	SeparateInstructions(lines[indexLines[1]], instructions);
	if (instructions.size()-1 > 2)		ErrorMessage("Too many arguments in the first line");
	if (instructions[1] != "THERMO")	ErrorMessage("Expected: THERMO - Found: " + instructions[1]);
	if (instructions.size()-1 == 2)
		if (instructions[2] != "ALL")	ErrorMessage("Expected: ALL - Found: " + instructions[2]);

	// ---------------------------------------------------------------
	// Second line
	// ---------------------------------------------------------------
	SeparateInstructions(lines[indexLines[2]], instructions);
	if (instructions.size()-1 != 3)		ErrorMessage("Too many arguments in the second line");
	tmin  = atof(instructions[1].c_str());
	tmean = atof(instructions[2].c_str());
	tmax  = atof(instructions[3].c_str());

	int j=3;
	for(i=1;i<=total_number_of_species;i++)
	{
		species[i].AssignTemperatures(tmin, tmean, tmax);
		species[i].ReadMainData(lines[indexLines[j]], indexLines[j]);	j++;
		if (species[i].iContinuation==true)
		{	
			species[i].ReadAdditionalLine(lines[indexLines[j]]);		j++;
		}
		species[i].ReadFirstLine(lines[indexLines[j]]);					j++;
		species[i].ReadSecondLine(lines[indexLines[j]]);				j++;
		species[i].ReadThirdLine(lines[indexLines[j]]);					j++;

		species[i].Analyze();
	}
}
Exemplo n.º 3
0
	inline T OpenSMOKEVector<T, IndexPolicy>::GetValue(const int i) const
	{
		if( (i<IndexPolicy::index_) || (i>dimensions_-1+this->index_) )
			ErrorMessage("Vector index outside the ranges");
		return vector_[i];
	}
Exemplo n.º 4
0
double UNITS::LinearFactor () {
    
    double factor = 1;
    
    /// First convert all to meters
    switch (in) {
        case ANG:
            factor = 1E-10;
            break;
        case NM:
            factor = 1E-09;
            break;
        case MUM:
            factor = 1E-06;
            break;
        case MM:
            factor = 1E-03;
            break;
        case CM:
            factor = 1E-02;
            break;
        case M:
            factor = 1;
            break;
        case KM:
            factor = 1E+03;
            break;
        case UA:
            factor = 1.49597870700E11;
            break;
        case PC:
            factor = 3.08567758E16;
            break;
        case KPC:
            factor = 3.08567758E19;
            break;
        case MPC:
            factor = 3.08567758E22;
            break;              
        default:
            ErrorMessage();
            return factor;
    }
    
    
    switch (out) {
        case ANG:
            factor *= 1E+10;
            break;
        case NM:
            factor *= 1E+09;
            break;
        case MUM:
            factor *= 1E+06;
            break;
        case MM:
            factor *= 1E+03;
            break;
        case CM:
            factor *= 1E+02;
            break;
        case M:
            factor *= 1;
            break;
        case KM:
            factor *= 1E-03;
            break;
        case UA:
            factor *= 6.68458712E-12;
            break;
        case PC:
            factor *= 3.24077929E-17;
            break;
        case KPC:
            factor *= 3.24077929E-20;
            break;
        case MPC:
            factor *= 3.24077929E-23;
            break;              
        default:
            ErrorMessage();
            factor=1;
            return factor;
    }
    
    return factor;
}
Exemplo n.º 5
0
SndAiff::SndAiff(char* name, short mode, short channels, short bits,
		 SndObj** inputlist, float spos, int vecsize, float sr):
  SndFIO(name, mode, channels, bits, inputlist, spos, vecsize, sr)
{
	
  m_selfdesc = 1; // yes, this is a self-describing  format !!!!
  m_isaiff = false;
  if(m_mode != READ){     // OUTPUT
    m_framesize = (short)((m_bits/8)*m_channels);
    m_header = PutHeader();
		
    if(m_mode != APPEND){
      fwrite((char *)&m_form, sizFormHdr, 1, m_file); 
      fwrite((char *)&m_comm1, sizCommChunk1, 1, m_file);
      fwrite((char *)&m_comm2, sizCommChunk2, 1, m_file);
      fwrite((char *)&m_ssnd, sizSoundDataHdr, 1, m_file);
      m_datapos = ftell(m_file); 
      if(spos > 0) SetPos(spos);     
    }
  } // OUTPUT
	
  else {  // INPUT
		
    if(m_filestat==SFERROR) {
      m_dataframes = 0;
      m_sr = 0.f;
      m_bits = 0;
      m_channels = 0;
      m_error = 21;
      return;
    }
		
    int IDchk;
    fread(&IDchk, 4, 1, m_file);
    if(!is_aiff_form(IDchk)){
      m_filestat = SFERROR;
      m_sr = 0.f;
      m_bits = 0;
      m_channels = 0;
      m_dataframes = 0;
      m_error = 25;
      return;
    }
		
    fseek(m_file, 4, SEEK_CUR);
    fread(&IDchk, 4, 1, m_file);
    if(IDchk != *(int *) FORM_TYPE){
      m_filestat = SFERROR;
      m_sr = 0.f;
      m_bits = 0;
      m_channels = 0;
      m_dataframes =0;
      m_error = 26;
      m_output = 0;
      return;
    }
		
    fseek(m_file, 0, SEEK_SET);
    if(!ReadHeader()){
      m_dataframes = 0;
      m_error = 27;
      m_output = 0; 
      return; 
			
    }
    m_bits = m_header.size;
    m_channels = m_header.nchns;
    m_dataframes = m_header.numSampleFrames;
    int datasize = m_dataframes*m_channels*m_sampsize;
    m_isaiff = true;
    m_itemsleft = (datasize%m_buffsize)/m_sampsize;
    m_spos=spos;          
    m_datapos = ftell(m_file);
    if(spos > 0) SetPos(spos); 
		
    delete[] m_output;
    delete[] m_buffer;
		
    m_samples = m_vecsize*m_channels;
    if(!(m_output = new float[m_samples])){
      m_error = 1;
      cout << ErrorMessage();
      return;
    }
		
    m_buffsize = (m_bits/8)*m_samples;
    if(!(m_buffer = new char[m_buffsize])){
      m_error = 11;
      cout << ErrorMessage();
      return;
    }
		
    // these are the pointers used to read the buffer
    m_cp = (unsigned char *) m_buffer;
    m_sp = (short *) m_buffer;
    m_lp = (int *) m_buffer;
    m_s24p = (_24Bit *) m_buffer;
		
  }  // INPUT
	
}
Exemplo n.º 6
0
void ChangeEntry(void)
{
  int dbid;
  DB_LIST parent;
  char name[256];
  int etype;
  char *comment;
  char comval[256];
  int ival;
  double rval;
  char sval[256];
  char choice[10];
  int ret;

  printf("\n\n");
  
  printf("Change an entry\n");
  printf("---------------\n");

  dbid = ChooseDatabase();
  if(dbid==-1) return;
 
  parent = ChooseParentList(dbid);

  printf("\nChoose entry name ==> ");
  scanf("%s", name);

  etype = eXdbmGetEntryType(dbid, parent, name);
  if(etype==-1) {
    printf("\nerror ==> entry not defined\n");
    HitKey();
    return;
  }

  printf("\nEntry values :\n");
  printf(  "------------\n\n");

  printf("[NAME] = %s\n\n", name);

  comment = eXdbmGetEntryComment(dbid, parent, name);

  if(comment!=NULL) 
    printf("[COMMENT] = %s\n\n", comment);
  
  printf("Do you want to specify a new comment (y/n) ? ");
  scanf("%s", choice);

  comment = NULL;

  if(toupper(choice[0])=='Y') {
    printf("[COMMENT] = ");
    fgets(comval,256,stdin);
    comment = comval;
  }

  if(comment!=NULL)
    eXdbmChangeEntryComment(dbid, parent, name, comment);
 
  switch(etype) {
  case DBM_ENTRY_LIST :
    printf("[TYPE] = List\n\n");
    printf("Cannot change a list entry\n");
    break;
    
  case DBM_ENTRY_VAR_INT :
    printf("[TYPE] = integer variable\n\n");
    printf("[VALUE] = ");
    scanf("%d", &ival);
    ret = eXdbmChangeVarInt(dbid, parent, name, ival);
    if(ret==-1) {
      ErrorMessage();
      HitKey();
      return;
    }
    break;

  case DBM_ENTRY_VAR_REAL :
    printf("[TYPE] = real number variable\n\n");
    printf("[VALUE] = ");
    scanf("%lf", &rval);
    ret = eXdbmChangeVarReal(dbid, parent, name, rval);
    if(ret==-1) {
      ErrorMessage();
      HitKey();
      return;
    }
    break;

  case DBM_ENTRY_VAR_BOOL :
    printf("[TYPE] = boolean variable\n\n");
    printf("[VALUE] = ");
    scanf("%s", sval);
    if(strcmp(sval, "FALSE")==0)
      ret = eXdbmChangeVarBool(dbid, parent, name, 0);
    else
      ret = eXdbmChangeVarBool(dbid, parent, name, 1);

    if(ret==-1) {
      ErrorMessage();
      HitKey();
      return;
    }
    break;


  case DBM_ENTRY_VAR_STRING :
    printf("[TYPE] = string variable\n\n");
    printf("[VALUE] = ");
    fgets(sval,256,stdin);
    ret = eXdbmChangeVarString(dbid, parent, name, sval);
    if(ret==-1) {
      ErrorMessage();
      HitKey();
      return;
    }
    break;


  case DBM_ENTRY_VAR_IDENT :
    printf("[TYPE] = identifier variable\n\n");
    printf("[VALUE] = ");
    fgets(sval,256,stdin);
    ret = eXdbmChangeVarIdent(dbid, parent, name, sval);
    if(ret==-1) {
      ErrorMessage();
      HitKey();
      return;
    }
    break;

  }

  HitKey();

}
    Position Position::read(Kernel::Reader* reader)
    {
      Position result(Distance::_Meter,0,0,0) ;
      
      std::map<std::string,std::string>::const_iterator finder ; 

      finder = reader->getAttributes().find("x") ;
      if (finder != reader->getAttributes().end())
      {
        result.m_value.x = atof(finder->second.c_str()) ;
      }
      else
      {
        ErrorMessage("Model::Position::read required attribute : x") ;
      }

      finder = reader->getAttributes().find("y") ;
      if (finder != reader->getAttributes().end())
      {
        result.m_value.y = atof(finder->second.c_str()) ;
      }
      else
      {
        ErrorMessage("Model::Position::read required attribute : y") ;
      }

      finder = reader->getAttributes().find("z") ;
      if (finder != reader->getAttributes().end())
      {
        result.m_value.z = atof(finder->second.c_str()) ;
      }
      else
      {
        ErrorMessage("Model::Position::read required attribute : z") ;
      }
      
      finder = reader->getAttributes().find("unit") ;
      if (finder != reader->getAttributes().end())
      {
        if (finder->second == "LightYear")
        {
          result.m_unit = Distance::_LightYear ;
        }
        else if (finder->second == "Parsec")
        {
          result.m_unit = Distance::_Parsec ;
        }
        else if (finder->second == "Meter")
        {
          result.m_unit = Distance::_Meter ;
        }
        else 
        {
          ErrorMessage("Model::Position::read invalid unit : " + finder->second) ;
        }
      }
      else
      {
        ErrorMessage("Model::Position::read required attribute : unit") ;
      }
      
      // move out of node
      while (!reader->isEndNode() && reader->processNode())
      {}
      
      reader->processNode() ;
      
      return result ;            
    }   
Exemplo n.º 8
0
bool CSSOBuilder::LoginErrorMessage(int iSsoResult)
{
	if (iSsoResult == CANTLOGIN_MANDATORY_MISSING)
	{
		return ErrorMessage("CANT-LOGIN-MANDATORY-MISSING","Unable to log the user as their is a mandotory field missing");
	}
	else if (iSsoResult == CANTLOGIN_NOT_VALIDATED)
	{
		return ErrorMessage("CANT-LOGIN-NOT-VALIDATED","Unable to log the user as they need to validate their account");
	}
	else if (iSsoResult == CANTLOGIN_CHANGE_PASSWORD)
	{
		return ErrorMessage("CANT-LOGIN-CHANGE-PASSWORD","Unable to log the user as they need to change their password");
	}
	else if (iSsoResult == CANTLOGIN_NOT_REGISTERED)
	{
		return ErrorMessage("CANT-LOGIN-NOT-REGISTERED","Unable to log the user as their are not registered");
	}
	else if (iSsoResult == CANTLOGIN_SERVICE_AGREEMENT)
	{
		return ErrorMessage("CANT-LOGIN-SERVICE-AGREEMENT","Unable to log the user has not accepted their service agreement");
	}
	else if (iSsoResult == CANTLOGIN_GLOBAL_AGREEMENT)
	{
		return ErrorMessage("CANT-LOGIN-GLOBAL-AGREEMENT","Unable to log the user has not accepted their global agreement");
	}
	else if (iSsoResult == CANTLOGIN_SQBLOCK)
	{
		return ErrorMessage("CANT-LOGIN-SQBLOCK","Unable to log the user in as their was a secret question block");
	}
	else if (iSsoResult == CANTLOGIN_PASSBLOCK)
	{
		return ErrorMessage("CANT-LOGIN-PASSBLOCK","Unable to log the user in as their password has been blocked");
	}
	else if (iSsoResult == CANTLOGIN_BANNED)
	{
		return ErrorMessage("CANT-LOGIN-BANNED","Unable to log the user in as they were banned");
	}
	else if (iSsoResult == CANTLOGIN_INCORRECT_AUTHENTICATION_TYPE)
	{
		return ErrorMessage("INCORRECT-AUTHENTICATION-TYPE","Incorrect Authentication");
	}
	else if (iSsoResult == CANTLOGIN_NOT_VALID)
	{
		return ErrorMessage("CANT-LOGIN-NOT-VALID","The login is not valid");
	}

	return ErrorMessage("NO-SSO-RESULT","Unable to identify the result from Single Sign On");	

}
Exemplo n.º 9
0
SndFIO::SndFIO(char* name, short mode, short channels, short bits,
	       SndObj** inputlist, float spos, int vecsize, float sr) :
  SndIO(channels, bits,inputlist,vecsize,sr){

  m_name = name;
  m_mode = mode;
  m_spos = spos; 
  m_datapos = 0;
  m_filestat = WAITOPEN;
  m_selfdesc = 0;
  m_eof=0;

  char* s_temp;

 
  switch (mode){  // open modes

  case INSERT:
    s_temp="r+b";
    break;

  case OVERWRITE:  
    s_temp="wb";
    break;

  case APPEND:
    s_temp="ab";
    m_datapos = 0;
    break;

  case READ:
    s_temp= "rb";
    if(!m_selfdesc) m_bits = bits;
    else m_bits = 0;
    break;

  default:
    m_error = 8;
#ifdef DEBUG
    cout << ErrorMessage();
#endif
    return;

  } 

  // open file
  if ((m_file = fopen(name,s_temp)) != NULL) m_filestat=SFOPEN;
  else{
    m_filestat=SFERROR;
    m_error=12;
#ifdef DEBUG
    cout << ErrorMessage();
#endif
    return;
  } 



  if(m_bits>0){
    m_buffsize = (m_bits/8)*m_samples;
    if(!(m_buffer = new char[m_buffsize])){
      m_error = 11;
#ifdef DEBUG
      cout << ErrorMessage();
#endif
      return;
    }
 
    // these are the pointers used to read/write to the buffer
    m_cp = (unsigned char *) m_buffer;
    m_sp = (short *) m_buffer;
    m_lp = (int *) m_buffer;
    m_s24p = (_24Bit*) m_buffer; 
  }
  else {
    m_buffsize = 0;
    m_buffer = 0;
    m_cp = 0;
    m_sp = 0;
    m_lp = 0;
  }
  if(m_bits != 16 && m_bits != 8 && m_bits != 32
     && m_bits != 24){
    m_error = 13;
#ifdef DEBUG
    cout << ErrorMessage();
#endif
  }
  if(spos > 0) SetPos(spos);
  m_safe = m_file;
}
Exemplo n.º 10
0
/*********************************************************************************
bool CSSOBuilder::VerifyPostcode()
Author:		
Created:	
Returns:	false in case of an error
Purpose:	Verifies the postcode parameter
*********************************************************************************/
bool CSSOBuilder::VerifyPostcode()
{
	if (!m_InputContext.ParamExists("postcode"))
	{
		return ErrorMessage("NOPOSTCODE","failed to submit a postcode");
	}

	CUser* pViewingUser = m_InputContext.GetCurrentUser();

	if (pViewingUser == NULL)
	{
		return ErrorMessage("NOUSER","There was no user");
	}

	CPostcoder Postcoder(m_InputContext);

	CTDVString sPostcode;
	bool bGotPostcode = false;

	m_InputContext.GetParamString("postcode",sPostcode);
	
	if (sPostcode.GetLength() > 0)
	{
		Postcoder.MakePlaceRequest(sPostcode, bGotPostcode);
		if (bGotPostcode) 
		{
			CTDVString sPostcode;
			CTDVString sArea;
			CTDVString sAuthID;
			int iNode = 0;
			Postcoder.PlaceHitPostcode(sPostcode, sAuthID, sArea, iNode);
//			pViewingUser->SetPostcode(sPostcode);
//			pViewingUser->SetArea(sArea);
//			pViewingUser->SetTaxonomyNode(iNode);
//			pViewingUser->UpdateDetails();

			// Update the users details
			if (!Postcoder.UpdateUserPostCodeInfo(sPostcode,sArea,iNode))
			{
				CTDVString sMsg = "<NEWREGISTER><POSTCODE><POSTCODEERROR>";
				sMsg << sPostcode << "</POSTCODEERROR></POSTCODE></NEWREGISTER>";
				m_pPage->AddInside("H2G2",sMsg);
				return true;
			}

			//Generate NewRegister XML - synchronisation has already been done.
			return UserNewRegister(true,true,false);
		}
		else
		{
			CTDVString sMsg = "<NEWREGISTER><POSTCODE><BADPOSTCODE>";
			sMsg << sPostcode << "</BADPOSTCODE></POSTCODE></NEWREGISTER>";
			m_pPage->AddInside("H2G2",sMsg);
			return true;
		}
	}
	else
	{
		return ErrorMessage("NOPOSTCODE","Invalid postcode");
	}
}
Exemplo n.º 11
0
bool CSSOBuilder::UserNewRegister(bool bFirstTime, bool bCreateXML, bool bSynchronise )
{

	CUser* pUser = m_InputContext.GetCurrentUser();
	
	//there should be a user because they have just logged in!
	if (pUser == NULL)
	{
		return ErrorMessage("NOTSIGNEDIN","The user was not signed in");
	}
	
	//user has logged in successfully from the inputcontext and actually

	if (pUser->IsUserLoggedIn())
	{
		if ( bSynchronise ) 
		{
			//Synchronisation with SSO is done on creation of new user in DNA.
			//Synchronisation will also be done in CRipley::HandleRequest() if s_sync=1 specified.
			//Could have a flag on User indicating that it has been synchronised.
			if ( !pUser->IsSynchronised() )
			{
				pUser->SynchroniseWithProfile(false);
			}
		}

		if ( bCreateXML )
		{

			CTDVString sPassThrough, sURLParams;
			GetPassThrough(sPassThrough,sURLParams);
			
			CTDVString sNewRegister = "<NEWREGISTER STATUS='LOGGEDIN'>";
			if (!sPassThrough.IsEmpty())
			{
				sNewRegister << sPassThrough;
			}

			sNewRegister << "<USERID>" << pUser->GetUserID() << "</USERID>";

			sNewRegister << "<FIRSTTIME>";

			if (bFirstTime)
			{
				sNewRegister << "1";
			}
			else
			{
				sNewRegister << "0";
			}

			sNewRegister << "</FIRSTTIME></NEWREGISTER>";

			m_pPage->AddInside("H2G2",sNewRegister);
		}

		// Now set the h2g2 cookie if they are an editor so that 
		// the perl tools will work.
		CTDVString sCookie;
		if (pUser->GetIsEditor() && pUser->GetCookie(sCookie))
		{
			/*
			CTDVString sXML = "<SETCOOKIE><COOKIE>";
			sXML << sCookie << "</COOKIE>\n";
			sXML << "</SETCOOKIE>";			
			m_pPage->AddInside("H2G2",sXML);
			*/
			
			//declare cookie instance (can be more than one)
			CXMLCookie oXMLCookie ("", sCookie, "", false );	
					
			//add to page object 
			m_pPage->SetCookie( oXMLCookie );		
		}
		
	}
	else
	{
		return ErrorMessage("NOTLOGGEDIN","The user was not logged in");
	}
							
	return true;
}
Exemplo n.º 12
0
DWORD WINAPI MakeNSISProc(LPVOID p) {
	char buf[1024];
	STARTUPINFO si={sizeof(si),};
	SECURITY_ATTRIBUTES sa={sizeof(sa),};
	SECURITY_DESCRIPTOR sd={0,};
	PROCESS_INFORMATION pi={0,};
	HANDLE newstdout=0,read_stdout=0; 

	OSVERSIONINFO osv={sizeof(osv)};
	GetVersionEx(&osv);
	if (osv.dwPlatformId == VER_PLATFORM_WIN32_NT) {
		InitializeSecurityDescriptor(&sd,SECURITY_DESCRIPTOR_REVISION);
		SetSecurityDescriptorDacl(&sd,true,NULL,false);
		sa.lpSecurityDescriptor = &sd;
	}
	else sa.lpSecurityDescriptor = NULL;
	sa.bInheritHandle = true;
	if (!CreatePipe(&read_stdout,&newstdout,&sa,0)) {
		ErrorMessage(g_hwnd,"There was an error creating the pipe.");
		PostMessage(g_hwnd,WM_MAKENSIS_PROCESSCOMPLETE,0,0);
		return 1;
	}
	GetStartupInfo(&si);
	si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
	si.wShowWindow = SW_HIDE;
	si.hStdOutput = newstdout;
	si.hStdError = newstdout;
	if (!CreateProcess(NULL,g_script,NULL,NULL,TRUE,CREATE_NEW_CONSOLE,NULL,NULL,&si,&pi)) {
		char buf[MAX_STRING];
		wsprintf(buf,"Could not execute:\r\n %s.",g_script);
		ErrorMessage(g_hwnd,buf);
		CloseHandle(newstdout);
		CloseHandle(read_stdout);
		PostMessage(g_hwnd,WM_MAKENSIS_PROCESSCOMPLETE,0,0);
		return 1;
	}
	unsigned long exit=0,read,avail;
	my_memset(buf,0,sizeof(buf));
	while(1) {
		PeekNamedPipe(read_stdout,buf,sizeof(buf)-1,&read,&avail,NULL);
		if (read != 0) {
			my_memset(buf,0,sizeof(buf));
			if (avail > sizeof(buf)-1) 	{
				while (read >= sizeof(buf)-1) {
					ReadFile(read_stdout,buf,sizeof(buf)-1,&read,NULL);
					LogMessage(g_hwnd,buf);
					my_memset(buf,0,sizeof(buf));
				}
			}
			else {
				ReadFile(read_stdout,buf,sizeof(buf),&read,NULL);
				LogMessage(g_hwnd,buf);
			}			
		}
		GetExitCodeProcess(pi.hProcess,&exit);
		if (exit != STILL_ACTIVE) break;
		Sleep(TIMEOUT);
	}
	g_retcode = exit;
	CloseHandle(pi.hThread);
	CloseHandle(pi.hProcess);
	CloseHandle(newstdout);
	CloseHandle(read_stdout);
	PostMessage(g_hwnd,WM_MAKENSIS_PROCESSCOMPLETE,0,0);
	return 0;
}
Exemplo n.º 13
0
int main(int argc, char* argv[])
{
    string              argument;
    ParserClass         parser;
    
	OpenSMOKE_ReactingGas		mix;
    OpenSMOKE_GlobalKinetics    global;
    OpenSMOKE_CSTR				cstr;
	OpenSMOKE_GasStream			inlet;
	OpenSMOKE_GasStream			outlet;
	OpenSMOKE_2EModel			soot2EModel;


    // 0. Parser setup
    parser.setup(argc, argv, parser_options);


    // 1. Detailed kinetic scheme setup
    if (parser.parse("--kinetics", argument))
            mix.SetupBinary(argument);
    else    ErrorMessage("The --kinetics option is compulsory");


    // 2a. Global kinetic scheme setup
    global.assign_mix(&mix);
    if (parser.parse("--global", argument))
    {
		global.read_from_file(argument);
		cstr.SetGlobalKinetics();
	}

	// 2b. Soot 2E Model
	if (parser.parse("--soot2EModel", argument))
	{
		soot2EModel.assign_mixture(mix);
		soot2EModel.setupFromFile(argument);
		cstr.SetTwoEquationModel();
	}
    // 3. Inlet stream setup
    inlet.AssignKineticScheme(mix);
    if (parser.parse("--inlet", argument))
		inlet.DefineFromFile(argument);
    else    ErrorMessage("The --inlet option is compulsory");
	inlet.VideoSummary();

	// Output folder
    if (parser.parse("--output", argument))
		cstr.SetOutputFolder(argument);


    // 4. CSTR Setup
    cstr.AssignKineticScheme(mix);
    cstr.AssignGlobalKineticScheme(global);
	cstr.AssignSoot2EModel(soot2EModel);

	cstr.AssignInletFlows(inlet);
    if (parser.parse("--input", argument))
		cstr.DefineFromFile(argument);
    else    ErrorMessage("The --input option is compulsory");


    // 5. PFR Video Summary
    cstr.VideoSummary();

    // 6. PFR Solution
    cstr.Solve();

    // 7. Video Solution
    cstr.VideoFinalResult();

	// 8. Outlet Stream
	cstr.OutletStream(outlet);
	outlet.VideoSummary();

	// 9. Mass and Energy balance
	cstr.SummaryOnFile();
	cstr.MassAnalysis(outlet);
	cstr.EnergyAnalysis(outlet);

    OpenSMOKE_logo("OpenSMOKE_CSTR", "0.3", "January 2014");

    return 0;
}
Exemplo n.º 14
0
void LoadLayerTypeInfo(CCEtoODBDoc *doc, const char *filename)
{
   CWaitCursor();
   
	// try reading an xml layertype file first
	LayerTypeXMLReader reader(*doc);
	FileStatusTag retval = reader.open(filename);

	// if not successful, then assume its the old one
	if (retval == statusSucceeded)
	{
		// init
		for (int i=0; i<MAX_LAYERSETS; i++)
		{
			for (int j=0; j<MAX_LAYTYPE; j++)
			{
				doc->LayerTypeArray[i][j].color = RGB(255, 255, 255);
				doc->LayerTypeArray[i][j].show = false;
			}
		}

		//reader.setDoc(doc);

		retval = reader.parse();
		
		return;
	}

	FILE *stream;
   if ((stream = fopen(filename, "rt")) == NULL)
   {
      ErrorMessage(filename, "Unable to open file");
      return;
   }

   char     line[500], *tok;
   int      i, j;
   int      version = 1;

   if (fgets(line,500,stream) == NULL)
      return;

   if (strcmp(line, "! Layertype Information\n"))
   {
      if (!strcmp(line, "! Layertype Information V2\n"))
      {
         version = 2;
      }
      else
      if (!strcmp(line, "! Layertype Information V3\n"))
      {
         version = 3;
      }
      else
      {
         ErrorMessage("This is not a Layertype Information File");
         return;
      }
   }

   // init
   for (i=0; i<MAX_LAYERSETS; i++)
   {
      for (j=0; j<MAX_LAYTYPE; j++)
      {
         doc->LayerTypeArray[i][j].color = RGB(255, 255, 255);
         doc->LayerTypeArray[i][j].show = false;
      }
   }

   if (version == 1)
   {
      int red, green, blue;
      for (i=0; i<MAX_LAYERSETS; i++)  // Normal, Top, Bottom, Cust 1, 2, 3, 4, 5
      {
         j=0;
         while (j<31)   // this was 31 before version 2
         {
            if (fgets(line,500,stream) == NULL) return;
   
            if (line[0] == '!' || line[0] == '\n') continue; // remark

            if ((tok = strtok(line, " \t\n(),")) == NULL) continue;
            doc->LayerTypeArray[i][j].show = atoi(tok);

            if ((tok = strtok(NULL, " \t\n(),")) == NULL) continue;
            red = atoi(tok);

            if ((tok = strtok(NULL, " \t\n(),")) == NULL) continue;
            green = atoi(tok);

            if ((tok = strtok(NULL, " \t\n(),")) == NULL) continue;
            blue = atoi(tok);

            doc->LayerTypeArray[i][j].color = RGB(red, green, blue);

            j++;
         }
      }
   }
   else
   if (version >= 2)
   {
      int red, green, blue;
         
      while (fgets(line,500,stream) != NULL) 
      {
         if (line[0] == '!' || line[0] == '\n') continue; // remark

         if ((tok = strtok(line, " \t\n(),")) == NULL) continue;

         if (!STRCMPI(tok,".NAME"))
         {
            CString  colorsetname;
            if ((tok = strtok(NULL, " \t")) == NULL) continue;
            int id = atoi(tok);
            if ((tok = strtok(NULL, "\n")) == NULL) continue;
            colorsetname = tok;
            colorsetname = tok;
            colorsetname.TrimLeft();
            colorsetname.TrimRight();
            doc->CustomLayersetNames.SetAt(id, tok);
         }
         else
         {
            i = atoi(tok);
            if (i >= MAX_LAYERSETS)
               continue;

            if ((tok = strtok(NULL, " \t\n(),")) == NULL) continue;
            j = atoi(tok);
            if (j >= MAX_LAYTYPE)
               continue;

            if ((tok = strtok(NULL, " \t\n(),")) == NULL) continue;
            doc->LayerTypeArray[i][j].show = atoi(tok);

            if ((tok = strtok(NULL, " \t\n(),")) == NULL) continue;
            red = atoi(tok);

            if ((tok = strtok(NULL, " \t\n(),")) == NULL) continue;
            green = atoi(tok);

            if ((tok = strtok(NULL, " \t\n(),")) == NULL) continue;
            blue = atoi(tok);
            doc->LayerTypeArray[i][j].color = RGB(red, green, blue);
         }
      }
   }
   fclose(stream);
}
Exemplo n.º 15
0
void PrintValues(void)
{
  int dbid;
  DB_LIST parent;
  char name[256];
  int etype;
  char *comment;
  DB_LIST list;
  long ival;
  double rval;
  char *sval;

  printf("\n\n");
  
  printf("Values of an entry\n");
  printf("------------------\n");

  dbid = ChooseDatabase();
  if(dbid==-1) return;
 
  parent = ChooseParentList(dbid);

  printf("\nChoose entry name ==> ");
  scanf("%s", name);

  etype = eXdbmGetEntryType(dbid, parent, name);
  if(etype==-1) {
    ErrorMessage();
    HitKey();
    return;
  }

  printf("\nEntry values :\n");
  printf(  "------------\n\n");

  printf("[NAME] = %s\n\n", name);

  comment = eXdbmGetEntryComment(dbid, parent, name);
  if(comment!=NULL)
    printf("[COMMENT] = %s\n\n", comment);


  switch(etype) {
  case DBM_ENTRY_LIST :
    printf("[TYPE] = List\n\n");
    list = eXdbmGetList(dbid, parent, name);
    printf("Info : This list contains %d entries\n\n", list->current_order);
    break;
    
  case DBM_ENTRY_VAR_INT :
    printf("[TYPE] = integer variable\n\n");
    eXdbmGetVarInt(dbid, parent, name, &ival);
    printf("[VALUE] = %ld\n\n", ival);
    break;

  case DBM_ENTRY_VAR_REAL :
    printf("[TYPE] = real number variable\n\n");
    eXdbmGetVarReal(dbid, parent, name, &rval);
    printf("[VALUE] = %f\n\n", rval);
    break;

  case DBM_ENTRY_VAR_BOOL :
    printf("[TYPE] = boolean variable\n\n");
    eXdbmGetVarBool(dbid, parent, name, &ival);
    if(ival==0)
      printf("[VALUE] = FALSE\n\n");
    else 
      printf("[VALUE] = TRUE\n\n");
    break;

  case DBM_ENTRY_VAR_STRING :
    printf("[TYPE] = string variable\n\n");
    eXdbmGetVarString(dbid, parent, name, &sval);
    printf("[VALUE] = %s\n\n", sval);
    free(sval);
    break;

  case DBM_ENTRY_VAR_IDENT :
    printf("[TYPE] = identifier variable\n\n");
    eXdbmGetVarIdent(dbid, parent, name, &sval);
    printf("[VALUE] = %s\n\n", sval);
    free(sval);
    break;

  }

  HitKey();

}
Exemplo n.º 16
0
void CRusSemStructure::BuildMNAOutcoming(long ClauseNo)
{
 try {
  

  for (long NodeNo = 0;  NodeNo < m_Nodes.size(); NodeNo++)
    if (   IsInClause(NodeNo, ClauseNo)
		&& ( m_Nodes[NodeNo].m_NodeType == MNA ) 
		&& ( m_Nodes[NodeNo].m_MNAType != CHEMOborot)
	   )
	{
		long  PatternPoses;
		QWORD Grammems;
		GetMNAPattern(NodeNo, PatternPoses, Grammems);
		bool bAdjMNA = HasOutcomingSynRelation(NodeNo,"ОДНОР_ПРИЛ");
		
        // мы начинаем поиск левых потомков от оператора однородности 
		// (единственный правый потомок уже был присоединен в процедуре, которая ищет оператор однородности )
	    for (long LeftChildNo=NodeNo; LeftChildNo >= m_Clauses[ClauseNo].m_BeginNodeNo; LeftChildNo--)
		{
			// ищем запятую, союз  или какой другой  оператор однородности
			for (; LeftChildNo >= m_Clauses[ClauseNo].m_BeginNodeNo; LeftChildNo--)
				if (IsFiniteVerb(LeftChildNo))
					  goto NoMoreLeftChilds;
				else
					if (   IsCoordConj(LeftChildNo) 
						|| m_Nodes[LeftChildNo].HaveCommaAfter()
						|| (m_Nodes[LeftChildNo].m_NodeType == MNA)
						)
					break;
			if (LeftChildNo <  m_Clauses[ClauseNo].m_BeginNodeNo) break; // не нашли

			// ищем слово, которое согласовано со словом, которое стоит сразу же  за оператором однородности, по падежу
			// или вообще не имеет граммем (ИЛЕ)
			for (; LeftChildNo >= m_Clauses[ClauseNo].m_BeginNodeNo; LeftChildNo--)
				if (IsFiniteVerb(LeftChildNo))
					goto NoMoreLeftChilds;
				else
				if (   (m_Nodes[LeftChildNo].m_MainWordNo != -1)
					&& (   !m_Nodes[LeftChildNo].IsTimeRossNode() 
						|| m_Nodes[LeftChildNo].IsMainTimeRossNode()
					   )
					&& (    ((m_Nodes[LeftChildNo].m_Words[m_Nodes[LeftChildNo].m_MainWordNo].m_Poses & PatternPoses) > 0)
					    ||  (     ( ( PatternPoses & (1<<ADV) ) > 0)
							  &&  (    m_Nodes[LeftChildNo].HasSomePrep() //  в лесу
								    || m_Nodes[LeftChildNo].IsMainTimeRossNode() // 9 мая	
								  )
							  &&  !HasIncomingNotWeakSynRelation(LeftChildNo)
						    )
					   )
					&& (  ((m_Nodes[LeftChildNo].GetGrammems() & Grammems & rAllCases) > 0)
						|| (Grammems == 0)
						|| (( PatternPoses & (1<<ADV) ) > 0)
						|| ( m_Nodes[LeftChildNo].GetGrammems() & Grammems & _QM(rComparative)) 
						|| ( HasSynRelation (LeftChildNo, "АНАТ_СРАВН") && (Grammems & _QM(rComparative)))
						)
					&& (!bAdjMNA || ( m_Nodes[LeftChildNo].HasPOS(ADJ_FULL) || m_Nodes[LeftChildNo].HasPOS(ADJ_SHORT)) )	
				   )
				break;
			if (LeftChildNo <  m_Clauses[ClauseNo].m_BeginNodeNo) break; 

			if (FindFirstRelation(NodeNo, LeftChildNo) == -1)
			{
				AddRelation(CRusSemRelation(CValency(), NodeNo, LeftChildNo,  ""));
				m_Relations[m_Relations.size() - 1].m_CannotHaveOnlyCommaBetween = true;
			};


		};
		NoMoreLeftChilds:;
	
	};

	}
 catch (...)
 {
	 ErrorMessage ("BuildMNAOutcoming Failed");
	 throw;
 };

};
Exemplo n.º 17
0
void AddEntry(void)
{
  int dbid;
  DB_LIST parent;
  char name[256];
  int etype;
  char *comment;
  char comval[256];
  int ival;
  double rval;
  char sval[256];
  char choice[10];
  int ret;

  printf("\n\n");
  
  printf("Create an entry\n");
  printf("---------------\n");

  dbid = ChooseDatabase();
  if(dbid==-1) return;
 
  parent = ChooseParentList(dbid);

  printf("\nChoose entry name ==> ");
  scanf("%s", name);

  etype = eXdbmGetEntryType(dbid, parent, name);
  if(etype!=-1) {
    printf("\nerror ==> entry already defined\n");
    HitKey();
    return;
  }

  printf("\nEntry values :\n");
  printf(  "------------\n\n");

  printf("[NAME] = %s\n\n", name);

  printf("Do you want to specify a comment (y/n) ? ");
  scanf("%s", choice);

  comment = NULL;

  if(toupper(choice[0])=='Y') {
    printf("[COMMENT] = ");
    fgets(comval,256,stdin);
    comment = comval;
  }
  
  etype = 0;

  while(etype<1 || etype > 6) {
    printf("\nChoose the type of the entry :\n\n");
    printf("1 => integer\n");
    printf("2 => real\n");
    printf("3 => bool\n");
    printf("4 => string\n");
    printf("5 => idenfifier\n");
    printf("6 => list\n");
    
    printf("\n  Your choice ==> ");
    etype=0;
    scanf("%d", &etype);
    if(etype==0) scanf("%s", choice);
  }

  etype--;

  switch(etype) {
  case DBM_ENTRY_LIST :
    printf("[TYPE] = List\n\n");
    ret = eXdbmCreateList(dbid, parent, name, comment);
    if(ret==-1) {
      ErrorMessage();
      HitKey();
      return;
    }
    break;
    
  case DBM_ENTRY_VAR_INT :
    printf("[TYPE] = integer variable\n\n");
    printf("[VALUE] = ");
    scanf("%d", &ival);
    ret = eXdbmCreateVarInt(dbid, parent, name, comment, ival);
    if(ret==-1) {
      ErrorMessage();
      HitKey();
      return;
    }
    break;

  case DBM_ENTRY_VAR_REAL :
    printf("[TYPE] = real number variable\n\n");
    printf("[VALUE] = ");
    scanf("%lf", &rval);
    ret = eXdbmCreateVarReal(dbid, parent, name, comment, rval);
    if(ret==-1) {
      ErrorMessage();
      HitKey();
      return;
    }
    break;

  case DBM_ENTRY_VAR_BOOL :
    printf("[TYPE] = boolean variable\n\n");
    printf("[VALUE] = ");
    scanf("%s", sval);
    if(strcmp(sval, "FALSE")==0)
      ret = eXdbmCreateVarBool(dbid, parent, name, comment, 0);
    else
      ret = eXdbmCreateVarBool(dbid, parent, name, comment, 1);

    if(ret==-1) {
      ErrorMessage();
      HitKey();
      return;
    }
    break;


  case DBM_ENTRY_VAR_STRING :
    printf("[TYPE] = string variable\n\n");
    printf("[VALUE] = ");
    scanf("%s", sval);
    ret = eXdbmCreateVarString(dbid, parent, name, comment, sval);
    if(ret==-1) {
      ErrorMessage();
      HitKey();
      return;
    }
    break;


  case DBM_ENTRY_VAR_IDENT :
    printf("[TYPE] = identifier variable\n\n");
    printf("[VALUE] = ");
    scanf("%s", sval);
    ret = eXdbmCreateVarIdent(dbid, parent, name, comment, sval);
    if(ret==-1) {
      ErrorMessage();
      HitKey();
      return;
    }
    break;

  }

  HitKey();

}
Exemplo n.º 18
0
void CRusSemStructure::BuildMNAIncoming(long ClauseNo)
{
 UpdateBlockedRelations();
 try {
  for (long NodeNo = m_Clauses[ClauseNo].m_BeginNodeNo;  NodeNo < m_Clauses[ClauseNo].m_EndNodeNo; NodeNo++)
    if (m_Nodes[NodeNo].m_NodeType == MNA)
	  for (long i = m_Clauses[ClauseNo].m_BeginNodeNo;  i < m_Clauses[ClauseNo].m_EndNodeNo; i++)
		   if  (i != NodeNo)
			 for (size_t j=0; j < m_Nodes[i].m_OutRels.size();j++)
			 {
				long Count = 0;
				/*
				   считаем кол-во отношений с одинаковым названием (это варианты заполнения одной валентности)
				   идущих из узла i (потенциальный хозяин однородного ряда) в
				   в члены однородного ряда.
				   Норамально, когда все члены однородного ряда подчиняются узлу i.
				   		
				*/
			    for (size_t l=j; l < m_Nodes[i].m_OutRels.size();l++)
				  if(m_Relations[m_Nodes[i].m_OutRels[j]].m_Valency == m_Relations[m_Nodes[i].m_OutRels[l]].m_Valency)
				  {
					  long k=0;
					  for (; k < m_Nodes[NodeNo].m_OutRels.size(); k++)
						if (m_Relations[m_Nodes[NodeNo].m_OutRels[k]].m_TargetNodeNo == m_Relations[m_Nodes[i].m_OutRels[l]].m_TargetNodeNo)
							break;

					  if (k <	m_Nodes[NodeNo].m_OutRels.size())
						Count++;
				  };

				// Для простых операторов однородности нужно, чтобы хотя бы один узел входил  
				// в член однородного ряда,чтобы подчинить весь однородный ряд. Это сделано из-за случая:
				// 'я жил в Америке и России'. Здесь пропущен прдлог 'в' после союза, поэтому
				// 'России'не подсоединится к 'жить'.
				// Для сравнительного оборота такой эллипсис не возможен, например:
				// Я жил в Америке дольше, чем в России.
				// но возможны обороты:
				// Я не знаю человека, больше чем Вася (здесь "Вася" не стоит в рд.  или  вн.) 
				// Я не отдаю тебе охотнее его (здесь "его" стоит в рд.) 
				if (    (   (Count > 0)
					//	&& (m_Nodes[NodeNo].m_MNAType != CHEMOborot)
					   )
				   /*||  (   (Count > 1) // 
						&& (m_Nodes[NodeNo].m_MNAType == CHEMOborot)
					   )*/
				   )
				{
				  // если валентность слова А - непредложная, а оператору однородности приписан предлог
				  // (такой предлог может придти из синтаксиса), тогда считаем, что слово А
				  // не может управлят этим однородным рядом
				   if (m_Relations[m_Nodes[i].m_OutRels[j]].m_Valency.IsFromDict())
				   {
					  const CRossHolder* RossHolder =  m_Relations[m_Nodes[i].m_OutRels[j]].m_Valency.m_RossHolder;
					  const TCortege& C = m_Relations[m_Nodes[i].m_OutRels[j]].m_SynReal.m_Cortege;
					  bool IsPrepCortege =     RossHolder->IsLemGroupBegining(RossHolder->GetSynFet(C)) 
											|| (RossHolder->GetSynRel(C) == RossHolder->AdverbialGrpNo);
					  if (!IsPrepCortege && m_Nodes[NodeNo].HasSomePrep()) continue;

				   };
				    

				  AddRelation(CRusSemRelation(m_Relations[m_Nodes[i].m_OutRels[j]].m_Valency, i, NodeNo,  ""));
		          m_Relations[m_Relations.size() - 1].m_CannotHaveOnlyCommaBetween = true;
				  m_Relations[m_Relations.size() - 1].m_SynReal = m_Relations[m_Nodes[i].m_OutRels[j]].m_SynReal;
				  m_Relations[m_Relations.size() - 1].m_SyntacticRelation = m_Relations[m_Nodes[i].m_OutRels[j]].m_SyntacticRelation;
				  if (m_Nodes[NodeNo].m_MNAType == CHEMOborot)
					  m_Relations[m_Relations.size() - 1].m_SemFets = GetSemFetsOfFirstValency(NodeNo);
				};

		   };


 }
 catch (...)
 {
	 ErrorMessage ("BuildMNAIncoming Failed");
	 throw;
 };
};
Exemplo n.º 19
0
void DeleteEntry(void)
{
  int dbid;
  DB_LIST parent;
  char name[256];
  int etype;
  char *comment = NULL;
  char choice[10];
  int ret;

  printf("\n\n");
  
  printf("Delete an entry\n");
  printf("---------------\n");

  dbid = ChooseDatabase();
  if(dbid==-1) return;
 
  parent = ChooseParentList(dbid);

  printf("\nChoose entry name ==> ");
  scanf("%s", name);

  etype = eXdbmGetEntryType(dbid, parent, name);
  if(etype==-1) {
    printf("\nerror ==> entry not defined\n");
    HitKey();
    return;
  }

  printf("\nEntry values :\n");
  printf(  "------------\n\n");

  printf("[NAME] = %s\n\n", name);

  if(comment!=NULL)
    eXdbmChangeEntryComment(dbid, parent, name, comment);
 
  switch(etype) {
  case DBM_ENTRY_LIST :
    printf("[TYPE] = List\n\n");
    printf("Cannot change a list entry\n");
    break;
    
  case DBM_ENTRY_VAR_INT :
    printf("[TYPE] = integer variable\n\n");
    break;

  case DBM_ENTRY_VAR_REAL :
    printf("[TYPE] = real number variable\n\n");
    break;

  case DBM_ENTRY_VAR_BOOL :
    printf("[TYPE] = boolean variable\n\n");
    break;


  case DBM_ENTRY_VAR_STRING :
    printf("[TYPE] = string variable\n\n");
    break;


  case DBM_ENTRY_VAR_IDENT :
    printf("[TYPE] = identifier variable\n\n");
    break;

  }


  printf("Do you want to erase this variable (y/n) ? ");
  scanf("%s", choice);

  if(toupper(choice[0])=='Y') {
    ret = eXdbmDeleteEntry(dbid, parent, name);
    if(ret==-1) {
      ErrorMessage();
      HitKey();
      return;
    }
    printf("\nEntry deleted successfully\n");
  } else printf("\nEntry not deleted\n");
  
  HitKey();

}
Exemplo n.º 20
0
void SSCScore::GenerateScore(SSModule *callingMod)
{
	unsigned char *buffer;
	ScoreSectionPtr	sp;
	NoteEventPtr	np;
	char		*p;

	// Open the file
	buffer = SuckFilefromSpec(&scoreFileSpec);	// Locally implemented
	if (buffer == NULL) {
		ErrorMessage("Can't open score file");
		parList->itsOwner->AbortSynthesis();
		return;
	}
	
	p = (char *) buffer;
	// Reset vars
	nbrSections = 0;
	sections = NULL;
	AddSection();

	sp = sections;
	sp->sectionStart = 0.0;
	sp->tempoScale = 1.0;
	sp->tempoStart = 0.0;
	sp->timeStart = 0.0;

	while (*p && parList->itsOwner->windowState == WS_Synthesize) {
		if (isspace(*p))
			++p;
		else if (*p == ';' || *p == '#')
		{
			while (*p && *p != '\r' && *p != '\n')
				++p;
		}
		else if (*p == 't')	// tempo
		{
			ssfloat	p1,p2;
			Boolean	gotIt;
			++p;
			p = GrabParam(p,1,&p1,&gotIt);
			p = GrabParam(p,2,&p2,&gotIt);

			sp->timeStart = (p1 - sp->tempoStart) * sp->tempoScale + sp->timeStart;
			sp->tempoStart = p1;
			sp->tempoScale = 60 / p2;
			// np = AddNoteEvent(sp,NEF_Tempo,((int) p1)-1,p2,0,0);
			while (*p && *p != '\r' && *p != '\n')
				++p;
		}
		else if (*p == 'f')	// table  (f0 is used to create silence)
		{
			// !!! Add wave table event NEF_Function
			while (*p && *p != '\r' && *p != '\n')
				++p;
		}
		else if (*p == 'i')	// note event
		{
	//  If 'i', parse instrument  '+' in p2 = p2+p3   '.' = previous field  
									// '<' is for ramping (mark 'begin ramp')
									//  '>' treat as for ramping as well
			ssfloat	p1,p2,p3;
			ssfloat optP[16];
			int	nbrOpts = 0;
			int n,i;
			Boolean	gotIt;
			++p;
			p = GrabParam(p,1,&p1,&gotIt);
			p = GrabParam(p,2,&p2,&gotIt);
			p = GrabParam(p,3,&p3,&gotIt);
			n = 4;
			do {
				p = GrabParam(p,n,&optP[nbrOpts],&gotIt);
				++n;
				if (gotIt)
					++nbrOpts;
			} while (gotIt);
			np = AddNoteEvent(sp,0,(int) p1,p2,p3,nbrOpts);
			for (i = 0; i < nbrOpts; ++i)
				np->op[i] = optP[i];
		}
		else if (*p == 's')	// section end
		{
			ScoreSectionPtr	lastS = sp;
			AddSection();
			sp = sections + (nbrSections-1);
			sp->sectionStart = lastS->sectionStart+lastS->sectionLength;
			sp->tempoScale = 1.0;
			sp->tempoStart = 0.0;
			sp->timeStart = 0.0;
			while (*p && *p != '\r' && *p != '\n')
				++p;
		}
		else if (*p == 'e')	// end of score
		{			
			break;
		}
		else {
			ErrorMessage("Invalid line in score: %.20s",p);
			parList->itsOwner->AbortSynthesis();
		}
	}
  if (gDurationOverride) {
    ssfloat scoreDuration = (sp->sectionStart + sp->sectionLength)*sp->tempoScale;
    SSOutput *outMod = (SSOutput *) (parList->itsOwner->outMod);
    if (outMod != NULL && scoreDuration > outMod->sampleDuration)
    {
      LogMessage("Overriding duration %g -> %g\n", outMod->sampleDuration, scoreDuration);
      outMod->sampleDuration = scoreDuration;
      parList->itsOwner->mainInst->sampleDuration = scoreDuration;
    }
  }
	MyDisposePtr(buffer);
	buffer = NULL;
}
Exemplo n.º 21
0
double UNITS::TimeFactor() {
     
    double factor = 1;
     
    // First convert all to seconds.
    switch (in) {
        case S:
            factor = 1;
            break;
        case H:
            factor = 3600;
            break;
        case D:
            factor = 86400;
            break;
        case YR:
            factor = 3.1556926E+07;
            break;
        case KYR:
            factor = 3.1556926E+10;
            break;
        case MYR:
            factor = 3.1556926E+13;
            break;
        case GYR:
            factor = 3.1556926E+16;
            break;
        default:
            ErrorMessage();
            return factor;       
    }
     
    switch (out) {
        case S:
            factor *= 1;
            break;
        case H:
            factor *= 0.000277777778;
            break;
        case D:
            factor *= 1.15740741E-05;
            break;
        case YR:
            factor *= 3.16887646E-08;
            break;
        case KYR:
            factor *= 3.16887646E-11;
            break;
        case MYR:
            factor *= 3.16887646E-14;
            break;
        case GYR:
            factor *= 3.16887646E-17;
            break;
        default:
            ErrorMessage();
            factor = 1;
            return factor;       
    }
    
    return factor;
}
Exemplo n.º 22
0
void WorldDatabase::SetMailKey(int CharID, int IPAddress, int MailKey)
{
	char MailKeyString[17];

	if(RuleB(Chat, EnableMailKeyIPVerification) == true)
		sprintf(MailKeyString, "%08X%08X", IPAddress, MailKey);
	else
		sprintf(MailKeyString, "%08X", MailKey);

    std::string query = StringFormat("UPDATE character_data SET mailkey = '%s' WHERE id = '%i'",
                                    MailKeyString, CharID);
    auto results = QueryDatabase(query);
	if (!results.Success())
		Log.Out(Logs::General, Logs::Error, "WorldDatabase::SetMailKey(%i, %s) : %s", CharID, MailKeyString, results.ErrorMessage().c_str());

}
Exemplo n.º 23
0
int runSpecificGraphTest(char *command, char *infileName)
{
	char *commandLine[] = {
			"planarity", "-s", "C", "infile", "outfile", "outfile2"
	};
	char *outfileName = ConstructPrimaryOutputFilename(infileName, NULL, command[1]);
	char *outfile2Name = "";
	char *testfileName = strdup(outfileName);
	int Result = 0;

	if (testfileName == NULL)
		return -1;

	outfileName = strdup(strcat(outfileName, ".test.txt"));
	if (outfileName == NULL)
	{
		free(testfileName);
		return -1;
	}

	// 'planarity -s [-q] C I O [O2]': Specific graph
	commandLine[2] = command;
	commandLine[3] = infileName;
	commandLine[4] = outfileName;
	commandLine[5] = outfile2Name;

	Result = callSpecificGraph(6, commandLine);
	if (Result == OK || Result == NONEMBEDDABLE)
		Result = 0;
	else
	{
		ErrorMessage("Test failed (graph processor returned failure result).\n");
		Result = -1;
	}

	if (Result == 0)
	{
		if (FilesEqual(testfileName, outfileName) == TRUE)
		{
			Message("Test succeeded (result equal to exemplar).\n");
			unlink(outfileName);
		}
		else
		{
			ErrorMessage("Test failed (result not equal to exemplar).\n");
			Result = -1;
		}
	}

	// For graph drawing, secondary file is outfileName + ".render.txt"

	if (command[1] == 'd' && Result == 0)
	{
		outfile2Name = ConstructPrimaryOutputFilename(NULL, outfileName, command[1]);
		free(outfileName);
		outfileName = strdup(strcat(outfile2Name, ".render.txt"));

		free(testfileName);
		testfileName = ConstructPrimaryOutputFilename(infileName, NULL, command[1]);
		testfileName = strdup(strcat(testfileName, ".render.txt"));

		if (Result == 0)
		{
			if (FilesEqual(testfileName, outfileName) == TRUE)
			{
				Message("Test succeeded (secondary result equal to exemplar).\n");
				unlink(outfileName);
			}
			else
			{
				ErrorMessage("Test failed (secondary result not equal to exemplar).\n");
				Result = -1;
			}
		}
	}

	Message("\n");

	free(outfileName);
	free(testfileName);
	return Result;
}
Exemplo n.º 24
0
int GetSpellColumns(SharedDatabase *db) {

	const std::string query = "DESCRIBE spells_new";
	auto results = db->QueryDatabase(query);
	if(!results.Success()) {
        LogFile->write(EQEMuLog::Error, "Error in GetSpellColumns query '%s' %s", query.c_str(), results.ErrorMessage().c_str());
        return 0;
    }

	return results.RowCount();
}
Exemplo n.º 25
0
//
// This function is called whenever the selection in the WorkerView changes.
// If the selection changes to a worker, it displays that worker's access
// spec assignment.
//
void CPageAccess::ShowAssignedAccess()
{
	int		m, w, s, mgr_count, wkr_count, spec_count;
	Manager	*mgr;
	Worker	*wkr = NULL;
	Test_Spec *spec;

	// Clear the list of assigned access specs.
	m_LAssignedAccess.DeleteAllItems();

	// find out who is selected: All managers, a manager, or a worker.
	switch ( theApp.pView->m_pWorkerView->GetSelectedType() )
	{
	case ALL_MANAGERS:
		// Disable the Assigned Access Spec listbox if there are no workers.
		if ( !theApp.manager_list.WorkerCount() )
		{
			SetAssignedAccess( FALSE );
			return;
		}

		// Enable the Assigned Access Spec listbox.
		SetAssignedAccess( TRUE );

		// Only display items in the listbox if all the descended workers
		// have the same access spec list.
		if ( !theApp.manager_list.AreAccessSpecsIdentical() )
			return;

		// All access specs are the same.  Show the specs stored by any worker.

		// Find a manager with any non-client workers.
		mgr_count = theApp.manager_list.ManagerCount();
		for ( m = 0; m < mgr_count; m++ )
		{
			mgr = theApp.manager_list.GetManager( m );
			wkr_count = mgr->WorkerCount();
			if ( wkr_count > mgr->WorkerCount( GenericClientType ) )
				break;
		}

		// Find the manager's first non-client worker.
		for ( w = 0; w < wkr_count; w++ )
		{
			// Find the first non-client worker.
			wkr = mgr->GetWorker( w );
			if ( !IsType( wkr->Type(), GenericClientType ) )
				break;
		}
		break;

	case MANAGER:
		mgr = theApp.pView->m_pWorkerView->GetSelectedManager();
		wkr_count = mgr->WorkerCount();

		// Disable the access spec list if there are no non-client workers.
		if ( wkr_count == mgr->WorkerCount( GenericClientType ) )
		{
			SetAssignedAccess( FALSE );
			return;
		}

		// Enable the Assigned Access Spec listbox.
		SetAssignedAccess( TRUE );

		// Only display items in the listbox if all the descended workers
		// have the same access spec list.
		if ( !mgr->AreAccessSpecsIdentical() )
			return;

		// All the access specs are the same.

		// Find the first non-client worker.
		for ( w = 0; w < wkr_count; w++ )
		{
			wkr = mgr->GetWorker( w );
			if ( !IsType( wkr->Type(), GenericClientType ) )
				break;
		}
		break;

	case WORKER:

		wkr = theApp.pView->m_pWorkerView->GetSelectedWorker();

		if ( IsType( wkr->Type(), GenericClientType ) )
		{
			// Worker is a net client.  Display it's net server's spec 
			// assignment, but disable the view.
			wkr = wkr->net_partner;
			SetAssignedAccess( FALSE );
		}
		else
		{
			SetAssignedAccess( TRUE );
		}
		break;
	}
	if ( !wkr )
	{
		ErrorMessage( "No valid worker in CPageAccess::ShowAssignedAccess()." );
		return;
	}

	// Add the Access Spec to the assigned access spec list view.
	spec_count = wkr->AccessSpecCount();
	for ( s = 0; s < spec_count; s++ )
	{
		spec = wkr->GetAccessSpec( s );
		// Set the data portion to pointer to the access spec in the
		// worker's access spec list.
		m_LAssignedAccess.InsertItem( LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE,
			s, spec->name, NULL, LVIS_SELECTED, BLUE, 
			(ULONG_PTR)spec );
	}
}
Exemplo n.º 26
0
int main(void) 
{
  int choice;
  int ret;

  ret = eXdbmInit();
  if(ret==-1) {
    ErrorMessage();
    return(EXIT_FAILURE);
  }

  choice=-1;

  while(choice!=12) {
    choice = MainMenu();
    switch(choice) {
    case 1 : 
      OpenDatabase();
      break;

    case 2 :
      NewDatabase();
      break;

    case 3 : 
      CloseDatabase();
      break;

    case 4 :
      UpdateDatabase();
      break;

    case 5 : 
      BackupDatabase();
      break;

    case 6 :
      ReloadDatabase();
      break;

    case 7 :
      PrintDatabase();
      break;

    case 8 :
      PrintValues();
      break;

    case 9 :
      AddEntry();
      break;

    case 10:
      ChangeEntry();
      break;

    case 11 :
      DeleteEntry();
      break;
      
    }
  }

  printf("\n\nBye bye ...\n");

  return(1);
}
void OpenSMOKE_ShockTube_Geometry::Setup(const std::string fileName)
{
    int i;
    std::string label;
    std::string variable;
    std::string conversion_x;
    std::string conversion_y;
    BzzVector x_vector;
    BzzVector y_vector;

    ifstream fInput;
    openInputFileAndControl(fInput, fileName.c_str());

    fInput >> label;
    if (label != "X")
        ErrorMessage("Only the following options are available: X");

	fInput >> label;
    if (label != "SPACE")
        ErrorMessage("Only the following options are available: SPACE");

	fInput >> conversion_x;

	fInput >> label;
    if (label != "Y")
        ErrorMessage("Only the following options are available: X");

	fInput >> variable;
    if (variable != "DIAMETER" && variable != "AREA")
        ErrorMessage("Only the following options are available: DIAMETER || AREA");

	fInput >> conversion_y;


    for(;;)
    {
        fInput >> label;
        if (label == "//")  break;

        x_vector.Append( atof(label.c_str()) );
        
        fInput >> label;
        y_vector.Append( atof(label.c_str()) );
    }

	// Checking values
	if (x_vector[1] != 0.)	ErrorMessage("The abscissas must start from 0.0");
	if (y_vector[1] <= 0.)	ErrorMessage("The initial diameter must be larger than 0.0");

	// In case of linear profile
	if (x_vector.Size() == 2)
	{
		if (variable == "DIAMETER")
		{
			iKind = 1;

			x_vector *= OpenSMOKE_Conversions::conversion_length(1.0, conversion_x);
			y_vector *= OpenSMOKE_Conversions::conversion_length(1.0, conversion_y);

			D0 = y_vector[1];
			slope_diameter  =	(y_vector[2]-y_vector[1]) / x_vector[2];
		}
		else if (variable == "AREA")
		{
			iKind = 2;

			x_vector *= OpenSMOKE_Conversions::conversion_length(1.0, conversion_x);
			y_vector *= OpenSMOKE_Conversions::conversion_area(1.0, conversion_y);

			Area0 = y_vector[1];
			slope_area		=	(y_vector[2]-y_vector[1]) / x_vector[2];
		}
	}
	
    else 
	{
		if (variable == "DIAMETER")
		{
			iKind = 3;

			x_vector *= OpenSMOKE_Conversions::conversion_length(1.0, conversion_x);
			y_vector *= OpenSMOKE_Conversions::conversion_length(1.0, conversion_y);

			BzzVector z_vector(x_vector.Size());
			for(i=1;i<=x_vector.Size()-1;i++)
				z_vector[i] = (y_vector[i+1]-y_vector[i]) / (x_vector[i+1]-x_vector[i]);
			i = x_vector.Size();
			z_vector[i] = (y_vector[i]-y_vector[i-1]) /	(x_vector[i]-x_vector[i-1]);

			interpolation_diameter(x_vector, y_vector);
			interpolation_dDiameter(x_vector, z_vector);

		}
		else if (variable == "AREA")
		{
			iKind = 4;

			x_vector *= OpenSMOKE_Conversions::conversion_length(1.0, conversion_x);
			y_vector *= OpenSMOKE_Conversions::conversion_area(1.0, conversion_y);

			BzzVector z_vector(x_vector.Size());
			for(i=1;i<=x_vector.Size()-1;i++)
				z_vector[i] = (y_vector[i+1]-y_vector[i])/(x_vector[i+1]-x_vector[i]);
			i = x_vector.Size();
			z_vector[i] = (y_vector[i]-y_vector[i-1])/(x_vector[i]-x_vector[i-1]);
			
			interpolation_area(x_vector, y_vector);
			interpolation_dArea(x_vector, z_vector);
		}
	}
}
Exemplo n.º 28
0
DB_LIST ChooseParentList(DB_ID dbid)
{
  int choice = 0;
  char cbuf;
  char name[256];
  char path[16384];
  char searchpath[16384];
  DB_LIST current = NULL;
  DB_LIST newlist;

  strcpy(path, "Root:");

  while(1) {

    while (choice<1 || choice>5) {
    
      printf("\n");
      printf("Choose the parent's list of the entry : \n\n");
    
      printf("\nCurrent list = %s\n\n", path);

      printf("1) Root list\n");
      printf("2) Get sublist\n");
      printf("3) Search sublist recursively\n");
      printf("4) Enter full path of list\n");
      printf("\n5) Use the current list\n");
      printf("\n  Your choice ==> ");
      choice=0;
      scanf("%d", &choice);
      if(choice==0) scanf("%c", &cbuf);
    }

    switch(choice) {
    
    case 1 :
      strcpy(path,"Root:");
      current = NULL;
      break;

    case 2:
      printf("\nEnter sublist name ==> ");
      scanf("%s", name);
      newlist = eXdbmGetList(dbid, current, name);
      if(newlist==NULL) {
	ErrorMessage();
      } else {
	current = newlist;
	strcat(path,name);
	strcat(path,":");
      }
      break;
  
    case 3:
      printf("\nEnter sublist name ==> ");
      scanf("%s", name);
      newlist = eXdbmSearchList(dbid, current, name);
      if(newlist==NULL) {
	ErrorMessage();
      } else {
	current = newlist;
	strcat(path, "...:");
	strcat(path, name);
	strcat(path,":");
      }
      break;
 
    case 4:
      printf("\nEnter list path (except Root:) ==> ");
      scanf("%s", searchpath);
      newlist = eXdbmPathList(dbid, searchpath);
      if(newlist==NULL) {
	ErrorMessage();
      } else {
	current = newlist;
	strcpy(path, "Root:");
	strcat(path, searchpath);
	strcat(path, ":");
      }
      break;

    case 5:
      return(current);
    }
    choice=0;
  }
  
  return(NULL);
  
}
Exemplo n.º 29
0
	inline void OpenSMOKEVector<T, IndexPolicy>::SetValue(const int i, const T value)
	{
		if( (i<IndexPolicy::index_) || (i>dimensions_-1+this->index_) )
			ErrorMessage("Vector index outside the ranges");
		vector_[i] = value;
	}
void OpenSMOKE_SolidExperiment_DSmoke_Bio::ReadFromFile(const string filename)
{
	string dummy;
	double dummy_double;

	string x_type;
	string y_type;
	string x_units;
	string y_units;

	name_of_file = filename;
	ifstream fInput;
	openInputFileAndControl(fInput, filename);

	solid_names.push_back("solid names");
	solid_mass_fraction.push_back(0.);
	solid_index.push_back(-1);
	mass_ratio_names.push_back("mass ratio names");

	// TODO
	for(;;)
	{
		fInput >> dummy;
		if (dummy == "PRESSURE") break;

		if (dummy!="TEMPERATURE")	ErrorMessage("Expected: TEMPERATURE - Found: " + dummy);

		fInput >> dummy_double;
		fInput >> dummy;
		times.Append(OpenSMOKE_Conversions::conversion_time(dummy_double, dummy));
		fInput >> dummy_double;
		fInput >> dummy;
		temperatures.Append(OpenSMOKE_Conversions::conversion_temperature(dummy_double, dummy));
	}
	

	if (dummy!="PRESSURE")	ErrorMessage("Expected: PRESSURE - Found: " + dummy);
	fInput >> pressure_atm;
	fInput >> dummy;
	pressure_atm = OpenSMOKE_Conversions::conversion_pressure(pressure_atm, dummy)/101325.;

	for(;;)
	{
		fInput >> dummy;
		if (dummy == "X") break;
		if (dummy != "SOLID_MASS_FRACTION")	ErrorMessage("Expected: SOLID_MASS_FRACTION - Found: " + dummy);
		fInput >> dummy;
		solid_names.push_back(dummy);
		fInput >> dummy;
		solid_mass_fraction.push_back(atof(dummy.c_str()));
	}

	fInput >> x_type;	if (x_type != "TIME")	ErrorMessage("Expected: TIME - Found: " + x_type);
	fInput >> dummy;	if (dummy  != "UNITS")	ErrorMessage("Expected: UNITS - Found: " + dummy);
	fInput >> x_units;

	fInput >> dummy;
	if (dummy != "Y")			ErrorMessage("Expected: Y - Found: " + dummy);
	fInput >> y_type;
	if (y_type == "MASS_RATIO")
	{
		kind_of_experimental_data = DSMOKE_BIO_MASS_RATIO;
		for(;;)
		{
			fInput >> dummy;
			if (dummy == "UNITS") break;
			mass_ratio_names.push_back(dummy);
		}
	}