示例#1
0
void OfficeInputStream::initialize(const char *fileName, DocumentCache *cache) {
	PDFInputStream::initialize(NULL, cache);

	if (statusCode != 0) {
		int convTime = currentTimeMillis();

		pid_t child = fork();
		char *oldPath, *newPath;
		switch (child) {
			case -1:
				statusCode = 1;
				break;
			case 0:
#if 0
				oldPath = getenv("PATH");
				if (oldPath == NULL)
					newPath = duplicateString(getenv("HOME"));
				else
					newPath = concatenateStrings(getenv("HOME"), ":", oldPath);
				setenv("PATH", newPath, 1);
				setenv("WUMPUS_CONVERSION_TARGET", tempFileName, 1);
				statusCode = executeCommand(OOFFICE, "-headless", "-p", fileName, NULL, INPUT_CONVERSION_TIMEOUT);
#else
				oldPath = concatenateStrings(tempFileName, ".ps");
				statusCode = executeCommand(
						"abiword", "--disable-crash-dialog", "-p", oldPath, fileName, INPUT_CONVERSION_TIMEOUT);
				if (statusCode == 0)
					statusCode = executeCommand(
							"ps2pdf", oldPath, tempFileName, INPUT_CONVERSION_TIMEOUT);
				if (statusCode == 0)
					statusCode = executeCommand(
							"rm", oldPath, NULL, INPUT_CONVERSION_TIMEOUT);
				free(oldPath);
#endif
				exit(statusCode);
			default:
				waitpid(child, &statusCode, 0);
				break;
		} // end switch (child)

		if (statusCode == 0) {
			char *tempFile = duplicateString(tempFileName);
			PDFInputStream::initialize(tempFile, NULL);
			unlink(tempFile);
			free(tempFile);
			if ((statusCode == 0) && (cache != NULL)) {
				convTime = currentTimeMillis() - convTime;
				if (convTime < 0)
					convTime += 24 * 3600 * 1000;
				cache->addDocumentTextFromFile(originalFileName, tempFileName, convTime);
			}
		}
	} // end if (statusCode != 0)

	if (statusCode != 0) {
		inputFile = -1;
		unlink(tempFileName);
	}

} // end of initialize(char*, DocumentCache*)
示例#2
0
static inline void copySection0AndInjectSystemModules(FirmwareType firmType, bool loadFromStorage)
{
    u32 maxModuleSize = firmType == NATIVE_FIRM ? 0x80000 : 0x600000,
        srcModuleSize,
        dstModuleSize;
    const char *extModuleSizeError = "The external FIRM modules are too large.";

    for(u8 *src = (u8 *)firm + firm->section[0].offset, *srcEnd = src + firm->section[0].size, *dst = firm->section[0].address;
        src < srcEnd; src += srcModuleSize, dst += dstModuleSize, maxModuleSize -= dstModuleSize)
    {
        srcModuleSize = ((Cxi *)src)->ncch.contentSize * 0x200;
        const char *moduleName = ((Cxi *)src)->exHeader.systemControlInfo.appTitle;

        if(loadFromStorage)
        {
            char fileName[24] = "sysmodules/";

            //Read modules from files if they exist
            concatenateStrings(fileName, moduleName);
            concatenateStrings(fileName, ".cxi");

            dstModuleSize = getFileSize(fileName);

            if(dstModuleSize != 0)
            {
                if(dstModuleSize > maxModuleSize) error(extModuleSizeError);

                if(dstModuleSize <= sizeof(Cxi) + 0x200 ||
                   fileRead(dst, fileName, dstModuleSize) != dstModuleSize ||
                   memcmp(((Cxi *)dst)->ncch.magic, "NCCH", 4) != 0 ||
                   memcmp(moduleName, ((Cxi *)dst)->exHeader.systemControlInfo.appTitle, sizeof(((Cxi *)dst)->exHeader.systemControlInfo.appTitle)) != 0)
                    error("An external FIRM module is invalid or corrupted.");

                continue;
            }
        }

        const u8 *module;

        if(firmType == NATIVE_FIRM && memcmp(moduleName, "loader", 6) == 0)
        {
            module = injector_bin;
            dstModuleSize = injector_bin_size;
        }
        else
        {
            module = src;
            dstModuleSize = srcModuleSize;
        }

        if(dstModuleSize > maxModuleSize) error(extModuleSizeError);

        memcpy(dst, module, dstModuleSize);
    }
}
示例#3
0
文件: parameter.cpp 项目: mvila/child
 QString Parameter::toString(bool debug, short level) const {
     QString prefixes;
     if(isEscaped())
         prefixes += "\\";
     if(isParented())
         prefixes += "@";
     return concatenateStrings(prefixes + label(), ": ",
                               defaultValue() ? defaultValue()->toString(debug, level) : "");
 }
示例#4
0
void appendString( char **aString, char *aAddString )
{
	char *string;

	if( *aString == NULL ) {
		*aString = duplicateString( aAddString );
	} else {
		string = concatenateStrings( *aString, aAddString );
		freeString( aString );
		*aString = string;
	}
}
示例#5
0
std::ostream & operator <<(std::ostream & os, const Parser & parser)
{
    // Header
    std::string strTerminals = concatenateStrings(parser.getGrammar().terminals) + parser.getOptions().endOfInputToken + '|';
    std::string strIntermediates = concatenateStrings(parser.getGrammar().intermediates, parser.getGrammar().START_RULE);

    os << "     |" << CENTER("Actions", std::max(strTerminals.length(), 7u)) << '|';
    os <<             CENTER("Branchs", std::max(strIntermediates.length(), 7u)) << '|' << std::endl;
    os << "State|" << strTerminals << strIntermediates << std::endl;
    os << std::setfill('-') << std::setw(strTerminals.length() + strIntermediates.length() + 6) << '-' << std::setfill(' ') << std::endl;

    // Table
    auto maxSizeIntermediate = std::to_string(parser.getStates().size()).length();
    auto eoit = parser.getOptions().endOfInputToken;
    for(const auto & state : parser.getStates())
    {
        os << std::left << std::setw(5) << state->numState << '|';

        // Action
        for(const auto & terminal : parser.getGrammar().terminals)
            printStateActions(os, state->getAction(terminal, eoit), terminal.length());
        printStateActions(os, state->getAction(eoit, eoit), eoit.length());

        // Goto
        for(const auto & intermediate : parser.getGrammar().intermediates)
            if(intermediate != parser.getGrammar().START_RULE)
                printStateBranches(os, state->getGoto(intermediate), std::max(intermediate.length(), maxSizeIntermediate));

        os << std::endl;
    }
    os << std::endl;

    // Print items sets
    for(const auto & state : parser.getStates())
        os << *state << std::endl;

    return os;
}
static int setFactorColumnName(SEXP dfNames, size_t dfIndex, SEXP levelNames, size_t levelIndex,
                               SEXP resultNames, size_t resultIndex)
{
  if (dfNames != R_NilValue) {
    char* colName = concatenateStrings(CHAR(STRING_ELT(dfNames, dfIndex)), CHAR(STRING_ELT(levelNames, levelIndex)));
    if (colName == NULL) return ENOMEM;
    
    SET_STRING_ELT(resultNames, resultIndex, Rf_mkChar(colName));
    free(colName);
  } else {
    SET_STRING_ELT(resultNames, resultIndex, STRING_ELT(levelNames, levelIndex));
  }
  
  return 0;
}
示例#7
0
void
Distance::initOptions(Options *options, TrajectoryAnalysisSettings * /*settings*/)
{
    static const char *const desc[] = {
        "g_dist can calculate the distance between two positions as",
        "a function of time. The total distance and its",
        "x, y and z components are plotted."
    };

    options->setDescription(concatenateStrings(desc));

    options->addOption(FileNameOption("o").filetype(eftPlot).outputFile()
                           .store(&fnDist_).defaultBasename("dist")
                           .description("Computed distances"));
    options->addOption(SelectionOption("select").required().valueCount(2)
                           .store(sel_));
}
示例#8
0
文件: whs.cpp 项目: gmargari/wumpus
static void startWumpus() {
	char *exe = evaluateRelativePathName(wumpusDir, "bin/wumpus");
	char *configFile = evaluateRelativePathName(wumpusDir, "wumpus.cfg");
	configFile = concatenateStringsAndFree(duplicateString("--config="), configFile);
	char *passwordFile = evaluateRelativePathName(wumpusDir, "wumpus.passwd");
	passwordFile = concatenateStringsAndFree(duplicateString("PASSWORD_FILE="), passwordFile);
	char *baseDir = concatenateStrings("BASE_DIRECTORY=", homeDir);
	char *databaseDir = evaluateRelativePathName(homeDir, ".wumpusdb");
	databaseDir = concatenateStringsAndFree(duplicateString("DIRECTORY="), databaseDir);
	int fd = open("/dev/null", O_RDWR);
	if (fd > 0)
		dup2(fd, fileno(stdout));
	signal(SIGINT, SIG_IGN);
	execl(exe, exe, configFile, passwordFile, baseDir, databaseDir,
			"MONITOR_FILESYSTEM=false", "FSCHANGE_FILE=/dev/null", NULL);
	perror("startWumpus()");
	exit(1);
} // end of startWumpus()
示例#9
0
static int answer_to_connection(
    void *cls, struct MHD_Connection *connection,
    const char *url,
    const char *method, const char *version,
    const char *upload_data,
    size_t *upload_data_size, void **con_cls
)

{   int r;
    tString u=newString(url);
    u.lower();
    if(compare(u,pagepath)==0) {
        tString s=concatenateStrings(page1,toString(stack,false),page2);
        char* p=s.mbs();
        MHD_Response * response = MHD_create_response_from_buffer (strlen(p),(void*)p,MHD_RESPMEM_MUST_COPY);
        delete[] p;
        r=MHD_queue_response (connection, MHD_HTTP_OK, response);
        MHD_destroy_response (response);
    }
    return r;
}
示例#10
0
void generateCodeForSearchPathInclude(const char* header, char*** codeLines, unsigned* numLines) {
	char* relativeInclude = concatenateStrings(3, "#include <", header, ">");
	addCodeLine(relativeInclude, codeLines, numLines);
	free(relativeInclude);
}
static int createMatrix(SEXP x, size_t numRows, SEXP resultExpr, const column_type* columnTypes, SEXP dropPatternExpr)
{
  SEXP names = rc_getNames(x);
  int protectCount = 0;
  if (names != R_NilValue) {
    names = PROTECT(names);
    ++protectCount;
  }
  double* result = REAL(resultExpr);
  SEXP resultNames = VECTOR_ELT(rc_getDimNames(resultExpr), 1);
  
  size_t numColumns = (size_t) rc_getLength(x);
  size_t resultCol = 0;
  
  for (size_t i = 0; i < numColumns; ++i) {
    SEXP col = VECTOR_ELT(x, i);
    switch (columnTypes[i]) {
      case REAL_VECTOR:
      if (dropPatternExpr == R_NilValue || LOGICAL(VECTOR_ELT(dropPatternExpr, i))[0] == FALSE) {
        memcpy(result + numRows * resultCol, (const double*) REAL(col), numRows * sizeof(double));
        if (names != R_NilValue) SET_STRING_ELT(resultNames, resultCol, STRING_ELT(names, i));
        ++resultCol; 
      }
      break;
      
      case INTEGER_VECTOR:
      case LOGICAL_VECTOR:
      if (dropPatternExpr == R_NilValue || LOGICAL(VECTOR_ELT(dropPatternExpr, i))[0] == FALSE) {
        int* colData = INTEGER(col);
        for (size_t j = 0; j < numRows; ++j) result[j + numRows * resultCol] = (double) colData[j];
        if (names != R_NilValue) SET_STRING_ELT(resultNames, resultCol, STRING_ELT(names, i));
        ++resultCol;
      }
      break;
      
      
      case REAL_MATRIX:
      {
        size_t numElementCols = INTEGER(rc_getDims(col))[1];
        double* colData = REAL(col);
        SEXP colNames = rc_getDimNames(col) == R_NilValue ? R_NilValue : VECTOR_ELT(rc_getDimNames(col), 1);
        int* dropPattern = dropPatternExpr == R_NilValue ? NULL : INTEGER(VECTOR_ELT(dropPatternExpr, i));
        
        for (size_t j = 0; j < numElementCols; ++j) {
          if (dropPattern == NULL || dropPattern[j] == FALSE) {
            memcpy(result + numRows * resultCol, colData + numRows * j, numRows * sizeof(double));
            if (names != R_NilValue && colNames != R_NilValue) {
              char* colName = concatenateStrings(CHAR(STRING_ELT(names, i)), CHAR(STRING_ELT(colNames, j)));
              SET_STRING_ELT(resultNames, resultCol, Rf_mkChar(colName));
              free(colName);
            } else if (names != R_NilValue) {
              char buffer[21];
              snprintf(buffer, 21, "%zu", j + 1);
              char* colName = concatenateStrings(CHAR(STRING_ELT(names, i)), buffer);
              SET_STRING_ELT(resultNames, resultCol, Rf_mkChar(colName));
              free(colName);
            } else if (colNames != R_NilValue) {
              SET_STRING_ELT(resultNames, resultCol, STRING_ELT(colNames, j));
            }
            ++resultCol;
          }
        }
      }
      break;
      
      case INTEGER_MATRIX:
      case LOGICAL_MATRIX:
      {
        size_t numElementCols = INTEGER(rc_getDims(col))[1];
        int* colData = INTEGER(col);
        SEXP colNames = rc_getDimNames(col) == R_NilValue ? R_NilValue : VECTOR_ELT(rc_getDimNames(col), 1);
        int* dropPattern = dropPatternExpr == R_NilValue ? NULL : INTEGER(VECTOR_ELT(dropPatternExpr, i));
        
        for (size_t j = 0; j < numElementCols; ++j) {
          if (dropPattern == NULL || dropPattern[j] == FALSE) {
            for (size_t k = 0; k < numRows; ++k) result[k + numRows * resultCol] = colData[k + numRows * j];
            if (names != R_NilValue && colNames != R_NilValue) {
              char* colName = concatenateStrings(CHAR(STRING_ELT(names, i)), CHAR(STRING_ELT(colNames, j)));
              SET_STRING_ELT(resultNames, resultCol, Rf_mkChar(colName));
              free(colName);
            } else if (names != R_NilValue) {
              char buffer[21];
              snprintf(buffer, 21, "%zu", j + 1);
              char* colName = concatenateStrings(CHAR(STRING_ELT(names, i)), buffer);
              SET_STRING_ELT(resultNames, resultCol, Rf_mkChar(colName));
              free(colName);
            } else if (colNames != R_NilValue) {
              SET_STRING_ELT(resultNames, resultCol, STRING_ELT(colNames, j));
            }
            ++resultCol;
          }
        }
      }
      break;
      
      
      case FACTOR:
      {
        SEXP levels = rc_getLevels(col);
        size_t levelsLength = (size_t) rc_getLength(levels);
        int* colData = INTEGER(col);
        size_t numLevelsPerFactor;
        
        if (dropPatternExpr == R_NilValue) {
          numLevelsPerFactor = levelsLength;
          if (numLevelsPerFactor <= 2) {
            int levelToKeep = numLevelsPerFactor == 2 ? 2 : 1;
            for (size_t j = 0; j < numRows; ++j) result[j + numRows * resultCol] = (colData[j] == levelToKeep ? 1 : 0);
            if (setFactorColumnName(names, i, levels, levelToKeep - 1, resultNames, resultCol) != 0) { UNPROTECT(protectCount); return ENOMEM; }
            ++resultCol;
          } else {
            for (int j = 0; j < (int) levelsLength; ++j) {
              for (size_t k = 0; k < numRows; ++k) result[k + numRows * resultCol] = (colData[k] == (j + 1) ? 1 : 0);
              if (setFactorColumnName(names, i, levels, j, resultNames, resultCol) != 0) { UNPROTECT(protectCount); return ENOMEM; }
              ++resultCol;
            }
          }
        } else {
          numLevelsPerFactor = 0;
          int* factorInstanceCounts = INTEGER(VECTOR_ELT(dropPatternExpr, i));
          for (size_t j = 0; j < levelsLength; ++j) if (factorInstanceCounts[j] > 0) ++numLevelsPerFactor;
          
          if (numLevelsPerFactor == 2) {
            int lastIndex;
            // skip until we find the last level that is actually in the column, make that 1
            for (lastIndex = levelsLength - 1; factorInstanceCounts[lastIndex] == 0 && lastIndex >= 0; --lastIndex) { /* */ }
            // R has factors coded with 1 based indexing
            ++lastIndex;
            for (size_t j = 0; j < numRows; ++j) result[j + numRows * resultCol] = (colData[j] == lastIndex ? 1 : 0);
            if (setFactorColumnName(names, i, levels, lastIndex - 1, resultNames, resultCol) != 0) { UNPROTECT(protectCount); return ENOMEM; }
            ++resultCol;
          } else if (numLevelsPerFactor > 2) {
            for (int j = 0; j < (int) levelsLength; ++j) {
              if (factorInstanceCounts[j] > 0) {
                for (size_t k = 0; k < numRows; ++k) result[k + numRows * resultCol] = (colData[k] == (j + 1) ? 1 : 0);
                if (setFactorColumnName(names, i, levels, j, resultNames, resultCol) != 0) { UNPROTECT(protectCount); return ENOMEM; }
                ++resultCol;
              }
            }
          }
        }
      }
      break;
      
      default:
      break;
    }
  } // close for loop over columns
  
  UNPROTECT(protectCount);
  
  return 0;
}
示例#12
0
static void TermCompletionOnAll(char *lineBeforeCaret, char *lineAfterCaret, char *defaultPattern, char **wk_buf, unsigned int *cursor,
                                unsigned int *cursor_max)
{
    if (defaultPattern)
    {
        int numberWordFound = 0;

        char **completionDictionaryFunctions = NULL;

        int sizecompletionDictionaryFunctions = 0;

        char **completionDictionaryCommandWords = NULL;

        int sizecompletionDictionaryCommandWords = 0;

        char **completionDictionaryMacros = NULL;

        int sizecompletionDictionaryMacros = 0;

        char **completionDictionaryVariables = NULL;

        int sizecompletionDictionaryVariables = 0;

        char **completionDictionaryHandleGraphicsProperties = NULL;

        int sizecompletionDictionaryHandleGraphicsProperties = 0;

        char **completionDictionaryFields = NULL;

        int sizecompletionDictionaryFields = 0;

        completionDictionaryFields = completionOnFields(lineBeforeCaret, defaultPattern, &sizecompletionDictionaryFields);

        if (!completionDictionaryFields && strcmp(defaultPattern, ""))
        {
            completionDictionaryFunctions = completionOnFunctions(defaultPattern, &sizecompletionDictionaryFunctions);
            completionDictionaryCommandWords = completionOnCommandWords(defaultPattern, &sizecompletionDictionaryCommandWords);
            completionDictionaryMacros = completionOnMacros(defaultPattern, &sizecompletionDictionaryMacros);
            completionDictionaryVariables = completionOnVariablesWithoutMacros(defaultPattern, &sizecompletionDictionaryVariables);
            completionDictionaryHandleGraphicsProperties =
                completionOnHandleGraphicsProperties(defaultPattern, &sizecompletionDictionaryHandleGraphicsProperties);
        }

        numberWordFound = sizecompletionDictionaryFunctions + sizecompletionDictionaryCommandWords +
                          sizecompletionDictionaryMacros + sizecompletionDictionaryVariables +
                          sizecompletionDictionaryHandleGraphicsProperties + sizecompletionDictionaryFields;

        if (numberWordFound > 0)
        {
            if (numberWordFound == 1)
            {
                char **completionDictionary = NULL;

                char *new_line = NULL;

                if (completionDictionaryFields)
                {
                    completionDictionary = completionDictionaryFields;
                }
                if (completionDictionaryFunctions)
                {
                    completionDictionary = completionDictionaryFunctions;
                }
                if (completionDictionaryCommandWords)
                {
                    completionDictionary = completionDictionaryCommandWords;
                }
                if (completionDictionaryMacros)
                {
                    completionDictionary = completionDictionaryMacros;
                }
                if (completionDictionaryVariables)
                {
                    completionDictionary = completionDictionaryVariables;
                }
                if (completionDictionaryHandleGraphicsProperties)
                {
                    completionDictionary = completionDictionaryHandleGraphicsProperties;
                }

                new_line = completeLine(lineBeforeCaret, completionDictionary[0], NULL, defaultPattern, FALSE, lineAfterCaret);
                if (new_line)
                {
                    char buflinetmp[WK_BUF_SIZE + 1];

                    strcpy(buflinetmp, new_line);
                    FREE(new_line);

                    backspace(*cursor);
                    erase_nchar(*cursor_max);
                    *cursor = *cursor_max = 0;

                    CopyLineAtPrompt(wk_buf, buflinetmp, cursor, cursor_max);
                }

                freeArrayOfString(completionDictionary, 1);
            }
            else
            {
                char *commonAll = NULL;

                if (completionDictionaryFields)
                {
                    commonAll = getCommonPart(completionDictionaryFields, sizecompletionDictionaryFields);
                    displayCompletionDictionary(completionDictionaryFields, sizecompletionDictionaryFields, (char *)_("Scilab Fields"));
                    freeArrayOfString(completionDictionaryFields, sizecompletionDictionaryFields);
                }
                else
                {
                    char *commonFunctions = getCommonPart(completionDictionaryFunctions, sizecompletionDictionaryFunctions);

                    char *commonCommandWords = getCommonPart(completionDictionaryCommandWords, sizecompletionDictionaryCommandWords);

                    char *commonMacros = getCommonPart(completionDictionaryMacros, sizecompletionDictionaryMacros);

                    char *commonVariables = getCommonPart(completionDictionaryVariables, sizecompletionDictionaryVariables);

                    char *commonHandleGraphicsProperties =
                        getCommonPart(completionDictionaryHandleGraphicsProperties, sizecompletionDictionaryHandleGraphicsProperties);

                    int sizecommonsDictionary = 0;

                    char **commonsDictionary = concatenateStrings(&sizecommonsDictionary, commonFunctions,
                                               commonMacros, commonCommandWords, commonVariables, commonHandleGraphicsProperties);

                    if (sizecommonsDictionary > 0)
                    {
                        if (sizecommonsDictionary == 1)
                        {
                            commonAll = strdup(commonsDictionary[0]);
                        }
                        else
                        {
                            commonAll = getCommonPart(commonsDictionary, sizecommonsDictionary);
                        }
                        freeArrayOfString(commonsDictionary, sizecommonsDictionary);
                    }

                    displayCompletionDictionary(completionDictionaryFunctions, sizecompletionDictionaryFunctions, (char *)_("Scilab Function"));
                    displayCompletionDictionary(completionDictionaryCommandWords, sizecompletionDictionaryCommandWords, (char *)_("Scilab Command"));
                    displayCompletionDictionary(completionDictionaryMacros, sizecompletionDictionaryMacros, (char *)_("Scilab Macro"));
                    displayCompletionDictionary(completionDictionaryVariables, sizecompletionDictionaryVariables, (char *)_("Scilab Variable"));
                    displayCompletionDictionary(completionDictionaryHandleGraphicsProperties, sizecompletionDictionaryHandleGraphicsProperties,
                                                (char *)_("Graphics handle field"));
                    freeArrayOfString(completionDictionaryFunctions, sizecompletionDictionaryFunctions);
                    freeArrayOfString(completionDictionaryCommandWords, sizecompletionDictionaryCommandWords);
                    freeArrayOfString(completionDictionaryMacros, sizecompletionDictionaryMacros);
                    freeArrayOfString(completionDictionaryVariables, sizecompletionDictionaryVariables);
                    freeArrayOfString(completionDictionaryHandleGraphicsProperties, sizecompletionDictionaryHandleGraphicsProperties);
                }

                printf("\n");

                backspace(*cursor);
                erase_nchar(*cursor_max);
                *cursor = *cursor_max = 0;

                printPrompt(WRITE_PROMPT);

                if (commonAll)
                {
                    char *new_line = NULL;

                    new_line = completeLine(lineBeforeCaret, commonAll, NULL, defaultPattern, FALSE, lineAfterCaret);
                    if (new_line)
                    {
                        char buflinetmp[WK_BUF_SIZE + 1];

                        strcpy(buflinetmp, new_line);
                        FREE(new_line);

                        CopyLineAtPrompt(wk_buf, buflinetmp, cursor, cursor_max);
                    }

                    FREE(commonAll);
                    commonAll = NULL;
                }
            }
        }
    }
}
示例#13
0
文件: section.cpp 项目: mvila/liu
 QString Section::toString(bool debug, short level) const {
     QString str;
     if(hasLabel()) str += QString("    ").repeated(level - 1) + label()->toString(debug, level) + ":";
     str = concatenateStrings(str, "\n", lines()->join("\n", QString("    ").repeated(level), "", debug, level));
     return str;
 }
示例#14
0
/**
 * @brief Main unit testing routine
 */
int main (){

  OBString *str1, *str2, *str3, *null_str;
  OBVector *tokens;
  const char *contents;

  str1 = createString("Hello, World!");

  /* Test createString and getCString */
  contents = getCString(str1);
  assert(strcmp(contents, "Hello, World!") == 0);
  

  /* Test copySubstring and stringLength */
  str2 = copySubstring(str1, 0, 5);
  contents = getCString(str2);
  assert(strcmp(contents, "Hello") == 0);

  release((obj *)str2);

  str2 = copySubstring(str1, -15, 7);
  contents = getCString(str2);
  assert(strcmp(contents, "Hello") == 0);

  release((obj *)str2);

  str2 = copySubstring(str1, 0, stringLength(str1));
  contents = getCString(str2);
  assert(strcmp(contents, "Hello, World!") == 0);

  release((obj *)str2);

  null_str = copySubstring(str1, 20, 2);
  assert(stringLength(null_str) == 0);

  /* Test charAtStringIndex */
  assert(charAtStringIndex(str1, 0) == 'H');
  assert(charAtStringIndex(str1, -5) == 'o');
  assert(charAtStringIndex(str1, -20) == '\0');
  assert(charAtStringIndex(str1, 20) == '\0');
  assert(charAtStringIndex(null_str, 0) == '\0');

  /* Test String Concatenation */
  str2 = createString(" And hello again!");
  str3 = concatenateStrings(str1, str2);
  contents = getCString(str3);
  assert(strcmp(contents, "Hello, World! And hello again!") == 0);

  release((obj *)str2);

  str2 = concatenateStrings(null_str, str1);
  contents = getCString(str2);
  assert(strcmp(contents, "Hello, World!") == 0);

  /* Test String Comparision */
  assert(compare((obj *)str1, (obj *)str2) == OB_EQUAL_TO);
  assert(compare((obj *)str1, (obj *)str3) == OB_LESS_THAN);
  assert(compare((obj *)str1, (obj *)null_str) == OB_GREATER_THAN);

  release((obj *)str2);
  release((obj *)str3);

  /* Test String Splits */
  str2 = createString("Testing string split   into#!many");
  tokens = splitString(str2, " ");
  assert(strcmp(getCString((OBString *)objAtVectorIndex(tokens, 0)), "Testing")
         == 0);
  assert(strcmp(getCString((OBString *)objAtVectorIndex(tokens, 3)),
                           "into#!many") == 0);

  release((obj *)tokens);

  tokens = splitString(str2, "#!");
  assert(strcmp(getCString((OBString *)objAtVectorIndex(tokens, 0)),
                           "Testing string split   into") == 0);
  assert(strcmp(getCString((OBString *)objAtVectorIndex(tokens, 1)), "many")
         == 0);

  release((obj *)tokens);

  /* Test String Search */

  assert(findSubstring(str2, "Testing") != 0);
  assert(findSubstring(str2, "#!many") != 0);
  assert(findSubstring(str2, "Hello World") == 0);

  /* Test Regex Match */
  str3 = matchStringRegex(str1, "[Hh]el{1,2}.");
  assert(strcmp(getCString(str3), "Hello") == 0);
  release((obj *)str3);

  str3 = matchStringRegex(str2, " *into[#!]{2,2}.*$");
  assert(strcmp(getCString(str3), "   into#!many") == 0);

  release((obj *)str3);
  release((obj *)str2);
  release((obj *)str1);
  release((obj *)null_str);
    
  /* TESTS COMPLETE */
  printf("OBString_test: TESTS PASSED\n");

  return 0;
}
示例#15
0
文件: utils.cpp 项目: gmargari/wumpus
char *concatenateStringsAndFree(char *s1, char *s2) {
	char *result = concatenateStrings(s1, s2);
	free(s1);
	free(s2);
	return result;
} // end of concatenateStringsAndFree(char*, char*)
示例#16
0
/*--------------------------------------------------------------------------*/
static void TermCompletionOnAll(char *lineBeforeCaret, char *lineAfterCaret, char *defaultPattern)
{
    if (defaultPattern)
    {
        int numberWordFound = 0;
        char **completionDictionaryFunctions = NULL;
        int sizecompletionDictionaryFunctions = 0;

        char **completionDictionaryCommandWords = NULL;
        int sizecompletionDictionaryCommandWords = 0;

        char **completionDictionaryMacros = NULL;
        int sizecompletionDictionaryMacros = 0;

        char **completionDictionaryVariables = NULL;
        int sizecompletionDictionaryVariables = 0;

        char **completionDictionaryHandleGraphicsProperties = NULL;
        int sizecompletionDictionaryHandleGraphicsProperties = 0;

        char **completionDictionaryFields = NULL;
        int sizecompletionDictionaryFields = 0;

        completionDictionaryFields = completionOnFields(lineBeforeCaret, defaultPattern, &sizecompletionDictionaryFields);

        if ((completionDictionaryFields == NULL) && strcmp(defaultPattern, ""))
        {
            completionDictionaryFunctions = completionOnFunctions(defaultPattern, &sizecompletionDictionaryFunctions);
            completionDictionaryCommandWords = completionOnCommandWords(defaultPattern, &sizecompletionDictionaryCommandWords);
            completionDictionaryMacros = completionOnMacros(defaultPattern, &sizecompletionDictionaryMacros);
            completionDictionaryVariables = completionOnVariablesWithoutMacros(defaultPattern, &sizecompletionDictionaryVariables);
            completionDictionaryHandleGraphicsProperties = completionOnHandleGraphicsProperties(defaultPattern, &sizecompletionDictionaryHandleGraphicsProperties);
        }
        numberWordFound = sizecompletionDictionaryFunctions + sizecompletionDictionaryCommandWords +
                          sizecompletionDictionaryMacros + sizecompletionDictionaryVariables +
                          sizecompletionDictionaryHandleGraphicsProperties + sizecompletionDictionaryFields;

        if (numberWordFound > 0)
        {
            if (numberWordFound == 1)
            {
                char **completionDictionary = NULL;
                char *new_line = NULL;

                if (completionDictionaryFields)
                {
                    completionDictionary = completionDictionaryFields;
                }
                if (completionDictionaryFunctions)
                {
                    completionDictionary = completionDictionaryFunctions;
                }
                if (completionDictionaryCommandWords)
                {
                    completionDictionary = completionDictionaryCommandWords;
                }
                if (completionDictionaryMacros)
                {
                    completionDictionary = completionDictionaryMacros;
                }
                if (completionDictionaryVariables)
                {
                    completionDictionary = completionDictionaryVariables;
                }
                if (completionDictionaryHandleGraphicsProperties)
                {
                    completionDictionary = completionDictionaryHandleGraphicsProperties;
                }

                new_line = completeLine(lineBeforeCaret, completionDictionary[0], NULL, defaultPattern, FALSE, lineAfterCaret);
                if (new_line)
                {
                    clearCurrentLine();
                    copyLine(new_line);
                    FREE(new_line);
                }
            }
            else
            {
                char *commonAll = NULL;
                if (completionDictionaryFields)
                {
                    commonAll = getCommonPart(completionDictionaryFields, sizecompletionDictionaryFields);
                    displayCompletionDictionary(completionDictionaryFields, sizecompletionDictionaryFields, (char *)_("Scilab Fields"));
                    freeArrayOfString(completionDictionaryFields, sizecompletionDictionaryFields);
                }
                else
                {
                    char *commonFunctions = getCommonPart(completionDictionaryFunctions, sizecompletionDictionaryFunctions);
                    char *commonCommandWords = getCommonPart(completionDictionaryCommandWords, sizecompletionDictionaryCommandWords);
                    char *commonMacros = getCommonPart(completionDictionaryMacros, sizecompletionDictionaryMacros);
                    char *commonVariables = getCommonPart(completionDictionaryVariables, sizecompletionDictionaryVariables);
                    char *commonHandleGraphicsProperties = getCommonPart(completionDictionaryHandleGraphicsProperties, sizecompletionDictionaryHandleGraphicsProperties);

                    int sizecommonsDictionary = 0;
                    char **commonsDictionary = concatenateStrings(&sizecommonsDictionary, commonFunctions,
                                               commonMacros, commonCommandWords, commonVariables, commonHandleGraphicsProperties);

                    if (sizecommonsDictionary > 0)
                    {
                        if (sizecommonsDictionary == 1)
                        {
                            commonAll = strdup(commonsDictionary[0]);
                        }
                        else
                        {
                            commonAll = getCommonPart(commonsDictionary, sizecommonsDictionary);
                        }
                        freeArrayOfString(commonsDictionary, sizecommonsDictionary);
                    }

                    displayCompletionDictionary(completionDictionaryFunctions, sizecompletionDictionaryFunctions, (char *)_("Scilab Function"));
                    displayCompletionDictionary(completionDictionaryCommandWords, sizecompletionDictionaryCommandWords, (char *)_("Scilab Command"));
                    displayCompletionDictionary(completionDictionaryMacros, sizecompletionDictionaryMacros, (char *)_("Scilab Macro"));
                    displayCompletionDictionary(completionDictionaryVariables, sizecompletionDictionaryVariables, (char *)_("Scilab Variable"));
                    displayCompletionDictionary(completionDictionaryHandleGraphicsProperties, sizecompletionDictionaryHandleGraphicsProperties, (char *)_("Graphics handle field"));
                    freeArrayOfString(completionDictionaryFunctions, sizecompletionDictionaryFunctions);
                    freeArrayOfString(completionDictionaryCommandWords, sizecompletionDictionaryCommandWords);
                    freeArrayOfString(completionDictionaryMacros, sizecompletionDictionaryMacros);
                    freeArrayOfString(completionDictionaryVariables, sizecompletionDictionaryVariables);
                    freeArrayOfString(completionDictionaryHandleGraphicsProperties, sizecompletionDictionaryHandleGraphicsProperties);
                }

                displayPrompt();
                newLine();

                if (commonAll)
                {
                    char *newline = NULL;

                    newline = completeLine(lineBeforeCaret, commonAll, NULL, defaultPattern, FALSE, lineAfterCaret);

                    if (newline)
                    {
                        clearCurrentLine();
                        copyLine(newline);
                        FREE(newline);
                    }
                    FREE(commonAll);
                    commonAll = NULL;
                }
            }
        }
    }
}
示例#17
0
QVariant QgsAggregateCalculator::calculate( QgsAggregateCalculator::Aggregate aggregate, QgsFeatureIterator& fit, QVariant::Type resultType,
    int attr, QgsExpression* expression, const QString& delimiter, QgsExpressionContext* context, bool* ok )
{
  if ( ok )
    *ok = false;

  switch ( resultType )
  {
    case QVariant::Int:
    case QVariant::UInt:
    case QVariant::LongLong:
    case QVariant::ULongLong:
    case QVariant::Double:
    {
      bool statOk = false;
      QgsStatisticalSummary::Statistic stat = numericStatFromAggregate( aggregate, &statOk );
      if ( !statOk )
        return QVariant();

      if ( ok )
        *ok = true;
      return calculateNumericAggregate( fit, attr, expression, context, stat );
    }

    case QVariant::Date:
    case QVariant::DateTime:
    {
      bool statOk = false;
      QgsDateTimeStatisticalSummary::Statistic stat = dateTimeStatFromAggregate( aggregate, &statOk );
      if ( !statOk )
        return QVariant();

      if ( ok )
        *ok = true;
      return calculateDateTimeAggregate( fit, attr, expression, context, stat );
    }

    default:
    {
      // treat as string
      if ( aggregate == StringConcatenate )
      {
        //special case
        if ( ok )
          *ok = true;
        return concatenateStrings( fit, attr, expression, context, delimiter );
      }

      bool statOk = false;
      QgsStringStatisticalSummary::Statistic stat = stringStatFromAggregate( aggregate, &statOk );
      if ( !statOk )
        return QVariant();

      if ( ok )
        *ok = true;
      return calculateStringAggregate( fit, attr, expression, context, stat );
    }
  }

  return QVariant();
}
示例#18
0
void
Angle::initOptions(Options *options, TrajectoryAnalysisSettings * /*settings*/)
{
    static const char *const desc[] = {
        "g_angle computes different types of angles between vectors.",
        "It supports both vectors defined by two positions and normals of",
        "planes defined by three positions.",
        "The z axis or the local normal of a sphere can also be used as",
        "one of the vectors.",
        "There are also convenience options 'angle' and 'dihedral' for",
        "calculating bond angles and dihedrals defined by three/four",
        "positions.[PAR]",
        "The type of the angle is specified with [TT]-g1[tt] and [TT]-g2[tt].",
        "If [TT]-g1[tt] is [TT]angle[tt] or [TT]dihedral[tt], [TT]-g2[tt]",
        "should not be specified.",
        "In this case, [TT]-group1[tt] should specify one selection,",
        "and it should contain triplets or quartets of positions that define",
        "the angles to be calculated.[PAR]",
        "If [TT]-g1[tt] is [TT]vector[tt] or [TT]plane[tt], [TT]-group1[tt]",
        "should specify a selection that has either pairs ([TT]vector[tt])",
        "or triplets ([TT]plane[tt]) of positions. For vectors, the positions",
        "set the endpoints of the vector, and for planes, the three positions",
        "are used to calculate the normal of the plane. In both cases,",
        "[TT]-g2[tt] specifies the other vector to use (see below).[PAR]",
        "With [TT]-g2 vector[tt] or [TT]-g2 plane[tt], [TT]-group2[tt] should",
        "specify another set of vectors. Both selections should specify the",
        "same number of vectors.[PAR]",
        "With [TT]-g2 sphnorm[tt], [TT]-group2[tt] should specify a single",
        "position that is the center of the sphere. The second vector is then",
        "calculated as the vector from the center to the midpoint of the",
        "positions specified by [TT]-group1[tt].[PAR]",
        "With [TT]-g2 z[tt], [TT]-group2[tt] is not necessary, and angles",
        "between the first vectors and the positive Z axis are calculated.[PAR]",
        "With [TT]-g2 t0[tt], [TT]-group2[tt] is not necessary, and angles",
        "are calculated from the vectors as they are in the first frame.[PAR]",
        "There are two options for output:",
        "[TT]-oav[tt] writes an xvgr file with the time and the average angle",
        "for each frame.",
        "[TT]-oall[tt] writes all the individual angles."
        /* TODO: Consider if the dump option is necessary and how to best
         * implement it.
           "[TT]-od[tt] can be used to dump all the individual angles,",
           "each on a separate line. This format is better suited for",
           "further processing, e.g., if angles from multiple runs are needed."
         */
    };
    static const char *const cGroup1TypeEnum[] =
    { "angle", "dihedral", "vector", "plane" };
    static const char *const cGroup2TypeEnum[] =
    { "none", "vector", "plane", "t0", "z", "sphnorm" };

    options->setDescription(concatenateStrings(desc));

    options->addOption(FileNameOption("oav").filetype(eftPlot).outputFile()
                           .store(&fnAverage_).defaultBasename("angaver")
                           .description("Average angles as a function of time"));
    options->addOption(FileNameOption("oall").filetype(eftPlot).outputFile()
                           .store(&fnAll_).defaultBasename("angles")
                           .description("All angles as a function of time"));
    // TODO: Add histogram output.

    options->addOption(StringOption("g1").enumValue(cGroup1TypeEnum)
                           .defaultEnumIndex(0).store(&g1type_)
                           .description("Type of analysis/first vector group"));
    options->addOption(StringOption("g2").enumValue(cGroup2TypeEnum)
                           .defaultEnumIndex(0).store(&g2type_)
                           .description("Type of second vector group"));

    // TODO: Allow multiple angles to be computed in one invocation.
    // Most of the code already supports it, but requires a solution for
    // Redmine issue #1010.
    // TODO: Consider what is the best way to support dynamic selections.
    // Again, most of the code already supports it, but it needs to be
    // considered how should -oall work, and additional checks should be added.
    sel1info_ = options->addOption(SelectionOption("group1")
                                       .required().onlyStatic().storeVector(&sel1_)
                                       .description("First analysis/vector selection"));
    sel2info_ = options->addOption(SelectionOption("group2")
                                       .onlyStatic().storeVector(&sel2_)
                                       .description("Second analysis/vector selection"));
}
char * MidiAnalyzerResults::stringResults( enum MidiFrameType mFrameType, union stash mStash1 )
{	
	char * result = NULL;
	char * frameType = NULL;
	char channelNum[1024];
	int charsPrinted;
	S8 channel = mStash1.channel;
	
	const int size = 1024;
	char buffer[size];
	int nchars;
	
	char number_str[128];
	AnalyzerHelpers::GetNumberString( localFrame.mData1, localDisplay_base, 8, number_str, 128 );

	// Makes a string describing the message type (data, command, what command).
	switch (mFrameType) {
	case Command:
		frameType = strdup( "Command" );
		charsPrinted = sprintf(channelNum, " Channel: %i", channel);
		result = concatenateStrings( frameType, channelNum, charsPrinted );
		return result;
		break;
	case Data:
		result = strdup( "Data" );
		return result;
		break;
	// End misc
	// Start data
	case Key:
		nchars = snprintf(buffer, size, "Key Channel: %i [%s]", channel, number_str);
		if (nchars >= 0 && nchars < size) {
			result = (char *) malloc ( nchars + 1 );
			strcpy (result, buffer);
		} else result = strdup( "Internal Error" );
		return result;
		break;
	case Velocity:
		nchars = snprintf(buffer, size, "Velocity Channel: %i [%s]", channel, number_str);
		if (nchars >= 0 && nchars < size) {
			result = (char *) malloc ( nchars + 1 );
			strcpy (result, buffer);
		} else result = strdup( "Internal Error" );
		return result;
		break;
	case Touch:
		nchars = snprintf(buffer, size, "Touch Channel: %i [%s]", channel, number_str);
		if (nchars >= 0 && nchars < size) {
			result = (char *) malloc ( nchars + 1 );
			strcpy (result, buffer);
		} else result = strdup( "Internal Error" );
		return result;
		break;
	case ControllerNum:
		nchars = snprintf(buffer, size, "ControllerNum Channel: %i [%s]", channel, number_str);
		if (nchars >= 0 && nchars < size) {
			result = (char *) malloc ( nchars + 1 );
			strcpy (result, buffer);
		} else result = strdup( "Internal Error" );
		return result;
		break;
	case ControllerValue:
		nchars = snprintf(buffer, size, "ControllerValue Channel: %i [%s]", channel, number_str);
		if (nchars >= 0 && nchars < size) {
			result = (char *) malloc ( nchars + 1 );
			strcpy (result, buffer);
		} else result = strdup( "Internal Error" );
		return result;
		break;
	case InstrumentNum:
		nchars = snprintf(buffer, size, "InstrumentNum Channel: %i [%s]", channel, number_str);
		if (nchars >= 0 && nchars < size) {
			result = (char *) malloc ( nchars + 1 );
			strcpy (result, buffer);
		} else result = strdup( "Internal Error" );
		return result;
		break;
	case Pressure:
		nchars = snprintf(buffer, size, "Pressure Channel: %i [%s]", channel, number_str);
		if (nchars >= 0 && nchars < size) {
			result = (char *) malloc ( nchars + 1 );
			strcpy (result, buffer);
		} else result = strdup( "Internal Error" );
		return result;
		break;
	case LSB:
		nchars = snprintf(buffer, size, "LSB Channel: %i [%s]", channel, number_str);
		if (nchars >= 0 && nchars < size) {
			result = (char *) malloc ( nchars + 1 );
			strcpy (result, buffer);
		} else result = strdup( "Internal Error" );
		return result;
		break;
	case MSB:
		nchars = snprintf(buffer, size, "MSB Channel: %i [%s]", channel, number_str);
		if (nchars >= 0 && nchars < size) {
			result = (char *) malloc ( nchars + 1 );
			strcpy (result, buffer);
		} else result = strdup( "Internal Error" );
		return result;
		break;
	case orphanedData:
		nchars = snprintf(buffer, size, "orphanedData Channel: %i [%s]", channel, number_str);
		if (nchars >= 0 && nchars < size) {
			result = (char *) malloc ( nchars + 1 );
			strcpy (result, buffer);
		} else result = strdup( "Internal Error" );
		return result;
		break;

	
	// End data
	// Start commands
	case NoteOff:
		frameType = strdup( "NoteOff" );
		charsPrinted = sprintf(channelNum, " Channel: %i", channel);
		result = concatenateStrings( frameType, channelNum, charsPrinted );
		return result;
		break;
	case NoteOn:
		frameType = strdup( "NoteOn" );
		charsPrinted = sprintf(channelNum, " Channel: %i", channel);
		result = concatenateStrings( frameType, channelNum, charsPrinted );
		return result;
		break;
	case Aftertouch:
		frameType = strdup( "Aftertouch" );
		charsPrinted = sprintf(channelNum, " Channel: %i", channel);
		result = concatenateStrings( frameType, channelNum, charsPrinted );
		return result;
		break;
	case ContinuousController:
		frameType = strdup( "ContinuousController" );
		charsPrinted = sprintf(channelNum, " Channel: %i", channel);
		result = concatenateStrings( frameType, channelNum, charsPrinted );
		return result;
		break;
	case PatchChange:
		frameType = strdup( "PatchChange" );
		charsPrinted = sprintf(channelNum, " Channel: %i", channel);
		result = concatenateStrings( frameType, channelNum, charsPrinted );
		return result;
		break;
	case ChannelPressure:
		frameType = strdup( "ChannelPressure" );
		charsPrinted = sprintf(channelNum, " Channel: %i", channel);
		result = concatenateStrings( frameType, channelNum, charsPrinted );
		return result;
		break;
	case PitchBend:
		frameType = strdup( "PitchBend" );
		charsPrinted = sprintf(channelNum, " Channel: %i", channel);
		result = concatenateStrings( frameType, channelNum, charsPrinted );
		return result;
		break;
	// End commands
	// Start non-musical commands.  They do not have channels.
	case BeginSystemExclusiveMessage:
		result = strdup( "BeginSystemExclusiveMessage" );
		return result;
		break;
	case MIDITimeCodeQuarterFrame:
		result = strdup( "MIDITimeCodeQuarterFrame" );
		return result;
		break;
	case SongPositionPointer:
		result = strdup( "SongPositionPointer" );
		return result;
		break;
	case SongSelect:
		result = strdup( "SongSelect" );
		return result;
		break;
	case F4:
		result = strdup( "F4" );
		return result;
		break;
	case F5:
		result = strdup( "F5" );
		return result;
		break;
	case TuneRequest:
		result = strdup( "TuneRequest" );
		return result;
		break;
	case EndSystemExclusiveMessage:
		result = strdup( "EndSystemExclusiveMessage" );
		return result;
		break;
	case TimingClock:
		result = strdup( "TimingClock" );
		return result;
		break;
	case F9:
		result = strdup( "F9" );
		return result;
		break;
	case Start_:
		result = strdup( "Start" );
		return result;
		break;
	case Continue:
		result = strdup( "Continue" );
		return result;
		break;
	case Stop_:
		result = strdup( "Stop" );
		return result;
		break;
	case FD:
		result = strdup( "FD" );
		return result;
		break;
	case ActiveSensing:
		result = strdup( "ActiveSensing" );
		return result;
		break;
	case SystemReset:
		result = strdup( "SystemReset" );
		return result;
		break;
	// non-musical commands
	// Start errors
	case error:
		result = strdup( "Error" );
		return result;
		break;
	default:
		result = strdup( "Internal Error, no match" );
		return result;
		break;
	}
}