示例#1
0
void FreeParkingLot(ParkingLot * parkinglot)
{
  FreeDecoder( GetDecoder( parkinglot ), GetVertices( parkinglot ) );
  FreeGraph( GetGraph( parkinglot ) ) ;
  freeLinkedList( GetAccesses( parkinglot) );
  freeLinkedList( GetQueueHead(parkinglot) );
  FreeParkedCars( GetParkedListHead(parkinglot) );
  free(parkinglot);
}
示例#2
0
/* DO NOT CHANGE
 *
 * Test code.
 */
int main(void)
{
    node *oldList=NULL, *newList=NULL, *sortList=NULL;
    int i;

    /* seed random number generator */
    srand(time(NULL));

    /* Create a linked list */
    for(i=0; i<=N; i++){
        oldList = inserthead(oldList, 10*(N-i));
    }

    /* Print this linked list */
    printf("Old linked list: \n");
    printLinkedList(oldList);
    printf("\n");

    /* Copy linked list to a new one */
    newList = copyLinkedList(oldList);

    /* Print copied linked list */
    printf("Copied linked list: \n");
    printLinkedList(newList);
    printf("\n");

    /* Update values in linked lists */
    modifyLinkedList(oldList,-1);
    modifyLinkedList(newList,1);

    /* Print updated old linked list */
    printf("Numbers should be 1 less: \n");
    printLinkedList(oldList);
    printf("\n");

    /* Print updated new linked list */
    printf("Numbers should be 1 more: \n");
    printLinkedList(newList);
    printf("\n");

    /* Create a sorted linked list */
    for(i=0; i<=N; i++){
        sortList = sortedInsert(sortList, rand()%N);
    }

    /* Print updated old linked list */
    printf("Numbers should be in sorted order: \n");
    printLinkedList(sortList);
    printf("\n");

    /* Free created lists */
    freeLinkedList(oldList);
    freeLinkedList(newList);
    freeLinkedList(sortList);

    return 0;
}
示例#3
0
/* DO NOT CHANGE
 *
 * freeLinkedList is recursive function.  It frees all of the nodes in a singly linked list
 * that is provided as a parameter.
 */
void freeLinkedList(node *head){
    if(head != NULL)
    {
        freeLinkedList(head->next);
        free(head);
    }
}
示例#4
0
void testMultiThreadedAdd() {
    printf("\n\nShould see messages in the correct order\n\n");
    
    int num_producers = 2;
    int num_consumers = 4;
    linked_list* list = initLinkedList();
    
    pthread_t* producers = malloc(sizeof(pthread_t) * num_producers);
    for (int i =0; i < num_producers; i++) {
        pthread_create(&(producers[i]), NULL, testProducer, list);
    }

    pthread_t* consumers = malloc(sizeof(pthread_t) * num_consumers);
    for (int i =0; i < num_consumers; i++) {
        pthread_create(&(consumers[i]), NULL, testConsumer, list);
    }

    for (int i =0; i < num_producers; i++) {
        pthread_join(producers[i], NULL);
    }

    for (int i =0; i < num_consumers; i++) {
        pthread_join(consumers[i], NULL);
    }

    free(producers);
    free(consumers);
    freeLinkedList(list);
}
示例#5
0
static int _testForeachOverEmptyList(void) {
  LinkedList l = newLinkedList();
  linkedListForeach(l, _linkedListEmptyCallback, NULL);
  assertIntEquals(_gNumForeachCallbacksMade, 0);
  freeLinkedList(l);
  return 0;
}
示例#6
0
// Note that this method skips hidden files
LinkedList listDirectory(const CharString directory) {
  LinkedList items = newLinkedList();
  CharString filename;

#if UNIX
  DIR* directoryPtr = opendir(directory->data);
  if(directoryPtr == NULL) {
    freeLinkedList(items);
    return 0;
  }
  struct dirent* entry;
  while((entry = readdir(directoryPtr)) != NULL) {
    if(entry->d_name[0] != '.') {
      filename = newCharStringWithCString(entry->d_name);
      linkedListAppend(items, filename);
    }
  }
  closedir(directoryPtr);

#elif WINDOWS
  WIN32_FIND_DATAA findData;
  HANDLE findHandle;
  CharString searchString = newCharString();

  snprintf(searchString->data, searchString->length, "%s\\*", directory->data);
  findHandle = FindFirstFileA((LPCSTR)(searchString->data), &findData);
  freeCharString(searchString);
  if(findHandle == INVALID_HANDLE_VALUE) {
    freeLinkedList(items);
    return 0;
  }
  do {
    if(findData.cFileName[0] != '.') {
      filename = newCharString();
      strncpy(filename->data, findData.cFileName, filename->length);
      linkedListAppend(items, filename);
    }
  } while(FindNextFileA(findHandle, &findData) != 0);

  FindClose(findHandle);

#else
  logUnsupportedFeature("List directory contents");
#endif

  return items;
}
示例#7
0
static int _testListInvalidDirectory(void) {
  CharString c = newCharStringWithCString("invalid");
  LinkedList l = listDirectory(c);
  assertIntEquals(linkedListLength(l), 0);
  freeLinkedList(l);
  freeCharString(c);
  return 0;
}
示例#8
0
void freePriority_queue(Priority_queue_p pq) {
	int i = 0;
	for(i = 0; i < PRIORITY_COUNT; i++) {
		freeLinkedList(pq->Queue_List[i]);
	}
	free(pq);
	pq = NULL;
}
示例#9
0
static int _testAppendNullItemToList(void) {
  LinkedList l = newLinkedList();
  linkedListAppend(l, NULL);
  assertIsNull(l->item);
  assertIsNull(l->nextItem);
  assertIntEquals(linkedListLength(l), 0);
  freeLinkedList(l);
  return 0;
}
示例#10
0
static int _testNewLinkedList(void) {
  LinkedList l = newLinkedList();
  assertNotNull(l);
  assertIsNull(l->nextItem);
  assertIntEquals(linkedListLength(l), 0);
  assert(l->item == NULL);
  freeLinkedList(l);
  return 0;
}
示例#11
0
文件: cawax_test.c 项目: danhng/cawax
int test_processSignal() {
	int linesRead = 0;
	LinkedList * signal = readFile("Michael_Williamson_Train.csv", 10, &linesRead);
	exportToC4_5Data(TrainDataStemFile, processSignal(signal), FALSE, FALSE);

	LinkedList * testData = readFile("Michael_Williamson_Test.csv", 10, &linesRead);
	exportToC4_5Data("cawax_test.data", processSignal(testData), TRUE, TRUE);
	freeLinkedList(signal);
	return 0;
}
示例#12
0
int main(void) {
  struct Node *head = createLinkedList();
  assert(head != NULL);

  printf("%.3lf\n", fun(head));

  freeLinkedList(head);

  return 0;
}
示例#13
0
boolByte programOptionsParseConfigFile(ProgramOptions self, const CharString filename) {
  boolByte result = false;
  File configFile = NULL;
  LinkedList configFileLines = NULL;
  CharString* argvCharStrings;
  int argc;
  char** argv;
  int i;

  if(filename == NULL || charStringIsEmpty(filename)) {
    logCritical("Cannot read options from empty filename");
    return false;
  }

  configFile = newFileWithPath(filename);
  if(configFile == NULL || configFile->fileType != kFileTypeFile) {
    logCritical("Cannot read options from non-existent file '%s'", filename->data);
    freeFile(configFile);
    return false;
  }

  configFileLines = fileReadLines(configFile);
  if(configFileLines == NULL) {
    logInternalError("Could not split config file lines");
    return false;
  }
  else if(linkedListLength(configFileLines) == 0) {
    logInfo("Config file '%s' is empty", filename->data);
    freeLinkedList(configFileLines);
    freeFile(configFile);
    return true;
  }
  else {
    // Don't need the file anymore, it can be freed here
    freeFile(configFile);
  }

  argvCharStrings = (CharString*)linkedListToArray(configFileLines);
  argc = linkedListLength(configFileLines);
  argv = (char**)malloc(sizeof(char*) * (argc + 1));
  // Normally this would be the application name, don't care about it here
  argv[0] = NULL;
  for(i = 0; i < argc; i++) {
    argv[i + 1] = argvCharStrings[i]->data;
  }
  argc++;
  result = programOptionsParseArgs(self, argc, argv);

  freeLinkedListAndItems(configFileLines, (LinkedListFreeItemFunc)freeCharString);
  free(argvCharStrings);
  free(argv);
  return result;
}
示例#14
0
文件: main.cpp 项目: xiaohuazhu/Shell
int main() {
    Node<int> *lists[3] = {
        createLinkedList({1, 2, 3, 4, 5}),
        createLinkedList({6, 2, 3, 4, 5}),
        createLinkedList({7, 8, 4, 5})
    };

    findInLists(lists, 3);

    for (auto list: lists) {
        freeLinkedList(list);
    }
    return 0;
}
示例#15
0
void testApplyFunc() {
    int vals[] = {1,2,3,4,5};
    linked_list* list = initLinkedList();
    for (int i = 0; i < sizeof(vals) / sizeof(vals[0]); i++) {
        addToTail(list, &(vals[i]));
    }
    printf("Should see :\n");
    for (int i = 0; i < sizeof(vals) / sizeof(vals[0]); i++) {
        printf("%d, ", vals[i]);
    }
    printf("\nActual:\n");
    applyFunc(list, intPrinter);
    printf("\n");
    freeLinkedList(list);
}
示例#16
0
int main()
{
    Node* list = createLinkedList();
    
    list = insertNode(list, 3);
    list = insertNode(list, 1);
    list = insertNode(list, 2);
    list = insertNode(list, 6);
    list = insertNode(list, 7);
    
    printLinkedList(list);
    
    list = reverseList(list);
    
    printLinkedList(list);
    
    list = freeLinkedList(list);
    
    return 0;
}
示例#17
0
void freeProgramOption(ProgramOption self) {
  if(self != NULL) {
    freeCharString(self->name);
    freeCharString(self->help);
    switch(self->type) {
      case kProgramOptionTypeString:
        freeCharString(self->_data.string);
        break;
      case kProgramOptionTypeList:
        // Note: This will not actually free the associated strings for this
        // option. This is ok if the list items are parsed from argv/argc, but
        // otherwise memory could be leaked here.
        freeLinkedList(self->_data.list);
        break;
      default:
        break;
    }
    free(self);
  }
}
示例#18
0
int main(void) {
  struct Node *head = createLinkedList();
  assert(head != NULL);

  printf("Enter where you want to delete (1 <= n <= %d): ", NUM_MAXINDEX);

  int n;
  scanf("%d", &n);

  if (n < 1 || n > NUM_MAXINDEX) {
    puts("Input Error");
    return 1;
  }
  head = deleteNode(head, n);

  printLinkedList(head);

  freeLinkedList(head);

  return 0;
}
示例#19
0
int main(){
	HASH *hash;
	D_LIST *list;
	int size = 30;
	int i = 0;
	BST_TREE *tree = BST_Create(cmpID);
	list = createDoublyList();
	hash = createHashTable(size);
	readFile(hash, list, tree);
	process(hash, list, tree);
	
	
	hash = freeData(hash);
	freeLinkedList(list);
	tree = BST_Destroy(tree);
    
	printf("\n\t\tEnd of the program!\n" );
#ifdef _MSC_VER
    printf( _CrtDumpMemoryLeaks() ? "No Memory Leak\n" : "Memory Leak\n");
#endif
	getch();
    
}
示例#20
0
int main(void) {
  struct Node *head = NULL;
  int number;
  do {
    printf("Please enter a number to be insert (end with -1): ");

    scanf("%d", &number);
    if (number == -1)
      break;

    head = insertNode(head, number);
  } while (1);

  printLinkedList(head);

  head = deleteDuplicateNode(head);
  
  if (head != NULL)
    printLinkedList(head);

  freeLinkedList(head);

  return 0;
}
示例#21
0
void basicTest() {
    CASE cases[] = {
        {ADD_FRONT, 2, SUCCESS},
        {ADD_FRONT, 1, SUCCESS},
        {ADD_FRONT, 0, SUCCESS},
        {ADD_BACK, 3, SUCCESS},
        {ADD_BACK, 4, SUCCESS},
        {SIZE, 0, 5},
        {REMOVE_FRONT, 0, 0},
        {REMOVE_FRONT, 0, 1},
        {REMOVE_BACK, 0, 4},
        {SIZE, 0, 2},
        {REMOVE_BACK, 0, 3},
        {REMOVE_BACK, 0, 2},
        {SIZE, 0, 0},
    };
    linked_list* list = initLinkedList();
    for (int i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
        if (runTestCase(&(cases[i]), list)) {
            printf("failure on case: %d\n", i);
        }
    }
    freeLinkedList(list);
}
示例#22
0
/* 	Deallocate all the links and the linked list itself.

	param: 	v		pointer to the dynamic array
	pre:	v is not null
	post:	the memory used by v->data is freed
*/
void deleteLinkedList(struct linkedList *lst)
{
	assert (lst != 0);
	freeLinkedList(lst);
	free(lst);
}
示例#23
0
int mrsWatsonMain(ErrorReporter errorReporter, int argc, char** argv) {
  ReturnCodes result;
  // Input/Output sources, plugin chain, and other required objects
  SampleSource inputSource = NULL;
  SampleSource outputSource = NULL;
  AudioClock audioClock;
  PluginChain pluginChain;
  CharString pluginSearchRoot = newCharString();
  boolByte shouldDisplayPluginInfo = false;
  MidiSequence midiSequence = NULL;
  MidiSource midiSource = NULL;
  unsigned long maxTimeInMs = 0;
  unsigned long maxTimeInFrames = 0;
  unsigned long tailTimeInMs = 0;
  unsigned long tailTimeInFrames = 0;
  unsigned long processingDelayInFrames;
  ProgramOptions programOptions;
  ProgramOption option;
  Plugin headPlugin;
  SampleBuffer inputSampleBuffer = NULL;
  SampleBuffer outputSampleBuffer = NULL;
  TaskTimer initTimer, totalTimer, inputTimer, outputTimer = NULL;
  LinkedList taskTimerList = NULL;
  CharString totalTimeString = NULL;
  boolByte finishedReading = false;
  SampleSource silentSampleInput;
  SampleSource silentSampleOutput;
  unsigned int i;

  initTimer = newTaskTimerWithCString(PROGRAM_NAME, "Initialization");
  totalTimer = newTaskTimerWithCString(PROGRAM_NAME, "Total Time");
  taskTimerStart(initTimer);
  taskTimerStart(totalTimer);

  initEventLogger();
  initAudioSettings();
  initAudioClock();
  audioClock = getAudioClock();
  initPluginChain();
  pluginChain = getPluginChain();
  programOptions = newMrsWatsonOptions();
  inputSource = sampleSourceFactory(NULL);

  if(!programOptionsParseArgs(programOptions, argc, argv)) {
    printf("Run with '--help' to see possible options\n");
    printf("Or run with '--help full' to see extended help for all options\n");
    return RETURN_CODE_INVALID_ARGUMENT;
  }

  // These options conflict with standard processing (more or less), so check to see if the user wanted one
  // of these and then exit right away.
  if(argc == 1) {
    printf("%s needs at least a plugin, input source, and output source to run.\n\n", PROGRAM_NAME);
    printMrsWatsonQuickstart(argv[0]);
    return RETURN_CODE_NOT_RUN;
  }
  else if(programOptions->options[OPTION_HELP]->enabled) {
    printMrsWatsonQuickstart(argv[0]);
    if(charStringIsEmpty(programOptionsGetString(programOptions, OPTION_HELP))) {
      printf("All options, where <argument> is required and [argument] is optional:\n");
      programOptionsPrintHelp(programOptions, false, DEFAULT_INDENT_SIZE);
    }
    else {
      if(charStringIsEqualToCString(programOptionsGetString(programOptions, OPTION_HELP), "full", true)) {
        programOptionsPrintHelp(programOptions, true, DEFAULT_INDENT_SIZE);
      }
      // Yeah this is a bit silly, but the performance obviously doesn't matter
      // here and I don't feel like cluttering up this already huge function
      // with more variables.
      else if(programOptionsFind(programOptions, programOptionsGetString(programOptions, OPTION_HELP))) {
        programOptionPrintHelp(programOptionsFind(programOptions, programOptionsGetString(programOptions, OPTION_HELP)),
          true, DEFAULT_INDENT_SIZE, 0);
      }
      else {
        printf("Invalid option '%s', try running --help full to see help for all options\n",
          programOptionsGetString(programOptions, OPTION_HELP)->data);
      }
    }
    return RETURN_CODE_NOT_RUN;
  }
  else if(programOptions->options[OPTION_VERSION]->enabled) {
    printVersion();
    return RETURN_CODE_NOT_RUN;
  }
  else if(programOptions->options[OPTION_COLOR_TEST]->enabled) {
    printTestPattern();
    return RETURN_CODE_NOT_RUN;
  }
  // See if we are to make an error report and make necessary changes to the
  // options for good diagnostics. Note that error reports cannot be generated
  // for any of the above options which return with RETURN_CODE_NOT_RUN.
  else if(programOptions->options[OPTION_ERROR_REPORT]->enabled) {
    errorReporterInitialize(errorReporter);
    programOptions->options[OPTION_VERBOSE]->enabled = true;
    programOptions->options[OPTION_LOG_FILE]->enabled = true;
    programOptions->options[OPTION_DISPLAY_INFO]->enabled = true;
    // Shell script with original command line arguments
    errorReporterCreateLauncher(errorReporter, argc, argv);
    // Rewrite some paths before any input or output sources have been opened.
    _remapFileToErrorReport(errorReporter, programOptions->options[OPTION_INPUT_SOURCE], true);
    _remapFileToErrorReport(errorReporter, programOptions->options[OPTION_OUTPUT_SOURCE], false);
    _remapFileToErrorReport(errorReporter, programOptions->options[OPTION_MIDI_SOURCE], true);
    _remapFileToErrorReport(errorReporter, programOptions->options[OPTION_LOG_FILE], false);
  }

  // Read in options from a configuration file, if given
  if(programOptions->options[OPTION_CONFIG_FILE]->enabled) {
    if(!programOptionsParseConfigFile(programOptions, programOptionsGetString(programOptions, OPTION_CONFIG_FILE))) {
      return RETURN_CODE_INVALID_ARGUMENT;
    }
  }

  // Parse these options first so that log messages displayed in the below
  // loop are properly displayed
  if(programOptions->options[OPTION_VERBOSE]->enabled) {
    setLogLevel(LOG_DEBUG);
  }
  else if(programOptions->options[OPTION_QUIET]->enabled) {
    setLogLevel(LOG_ERROR);
  }
  else if(programOptions->options[OPTION_LOG_LEVEL]->enabled) {
    setLogLevelFromString(programOptionsGetString(programOptions, OPTION_LOG_LEVEL));
  }
  if(programOptions->options[OPTION_COLOR_LOGGING]->enabled) {
    // If --color was given but with no string argument, then force color. Otherwise
    // colors will be provided automatically anyways.
    if(charStringIsEmpty(programOptionsGetString(programOptions, OPTION_COLOR_LOGGING))) {
      programOptionsSetCString(programOptions, OPTION_COLOR_LOGGING, "force");
    }
    setLoggingColorEnabledWithString(programOptionsGetString(programOptions, OPTION_COLOR_LOGGING));
  }
  if(programOptions->options[OPTION_LOG_FILE]->enabled) {
    setLogFile(programOptionsGetString(programOptions, OPTION_LOG_FILE));
  }

  // Parse other options and set up necessary objects
  for(i = 0; i < programOptions->numOptions; i++) {
    option = programOptions->options[i];
    if(option->enabled) {
      switch(option->index) {
        case OPTION_BLOCKSIZE:
          setBlocksize((const unsigned long)programOptionsGetNumber(programOptions, OPTION_BLOCKSIZE));
          break;
        case OPTION_CHANNELS:
          setNumChannels((const unsigned long)programOptionsGetNumber(programOptions, OPTION_CHANNELS));
          break;
        case OPTION_DISPLAY_INFO:
          shouldDisplayPluginInfo = true;
          break;
        case OPTION_INPUT_SOURCE:
          freeSampleSource(inputSource);
          inputSource = sampleSourceFactory(programOptionsGetString(programOptions, OPTION_INPUT_SOURCE));
          break;
        case OPTION_MAX_TIME:
          maxTimeInMs = (const unsigned long)programOptionsGetNumber(programOptions, OPTION_MAX_TIME);
          break;
        case OPTION_MIDI_SOURCE:
          midiSource = newMidiSource(guessMidiSourceType(programOptionsGetString(
            programOptions, OPTION_MIDI_SOURCE)),
            programOptionsGetString(programOptions, OPTION_MIDI_SOURCE));
          break;
        case OPTION_OUTPUT_SOURCE:
          outputSource = sampleSourceFactory(programOptionsGetString(programOptions, OPTION_OUTPUT_SOURCE));
          break;
        case OPTION_PLUGIN_ROOT:
          charStringCopy(pluginSearchRoot, programOptionsGetString(programOptions, OPTION_PLUGIN_ROOT));
          break;
        case OPTION_SAMPLE_RATE:
          setSampleRate(programOptionsGetNumber(programOptions, OPTION_SAMPLE_RATE));
          break;
        case OPTION_TAIL_TIME:
          tailTimeInMs = (long)programOptionsGetNumber(programOptions, OPTION_TAIL_TIME);
          break;
        case OPTION_TEMPO:
          setTempo(programOptionsGetNumber(programOptions, OPTION_TEMPO));
          break;
        case OPTION_TIME_SIGNATURE:
          if(!setTimeSignatureFromString(programOptionsGetString(programOptions, OPTION_TIME_SIGNATURE))) {
            return RETURN_CODE_INVALID_ARGUMENT;
          }
          break;
        case OPTION_ZEBRA_SIZE:
          setLoggingZebraSize((int)programOptionsGetNumber(programOptions, OPTION_ZEBRA_SIZE));
          break;
        default:
          // Ignore -- no special handling needs to be performed here
          break;
      }
    }
  }

  if(programOptions->options[OPTION_LIST_PLUGINS]->enabled) {
    listAvailablePlugins(pluginSearchRoot);
    return RETURN_CODE_NOT_RUN;
  }
  if(programOptions->options[OPTION_LIST_FILE_TYPES]->enabled) {
    sampleSourcePrintSupportedTypes();
    return RETURN_CODE_NOT_RUN;
  }

  printWelcomeMessage(argc, argv);
  if((result = setupInputSource(inputSource)) != RETURN_CODE_SUCCESS) {
    logError("Input source could not be opened, exiting");
    return result;
  }
  if((result = buildPluginChain(pluginChain, programOptionsGetString(programOptions, OPTION_PLUGIN),
    pluginSearchRoot)) != RETURN_CODE_SUCCESS) {
    logError("Plugin chain could not be constructed, exiting");
    return result;
  }
  if(midiSource != NULL) {
    result = setupMidiSource(midiSource, &midiSequence);
    if(result != RETURN_CODE_SUCCESS) {
      logError("MIDI source could not be opened, exiting");
      return result;
    }
  }

  // Copy plugins before they have been opened
  if(programOptions->options[OPTION_ERROR_REPORT]->enabled) {
    if(errorReporterShouldCopyPlugins()) {
      if(!errorReporterCopyPlugins(errorReporter, pluginChain)) {
        logWarn("Failed copying plugins to error report directory");
      }
    }
  }

  // Initialize the plugin chain after the global sample rate has been set
  result = pluginChainInitialize(pluginChain);
  if(result != RETURN_CODE_SUCCESS) {
    logError("Could not initialize plugin chain");
    return result;
  }

  // Display info for plugins in the chain before checking for valid input/output sources
  if(shouldDisplayPluginInfo) {
    pluginChainInspect(pluginChain);
  }

  // Execute any parameter changes
  if(programOptions->options[OPTION_PARAMETER]->enabled) {
    if(!pluginChainSetParameters(pluginChain, programOptionsGetList(programOptions, OPTION_PARAMETER))) {
      return RETURN_CODE_INVALID_ARGUMENT;
    }
  }

  // Setup output source here. Having an invalid output source should not cause the program
  // to exit if the user only wants to list plugins or query info about a chain.
  if((result = setupOutputSource(outputSource)) != RETURN_CODE_SUCCESS) {
    logError("Output source could not be opened, exiting");
    return result;
  }

  // Verify input/output sources. This must be done after the plugin chain is initialized
  // otherwise the head plugin type is not known, which influences whether we must abort
  // processing.
  if(programOptions->options[OPTION_ERROR_REPORT]->enabled) {
    if(charStringIsEqualToCString(inputSource->sourceName, "-", false) ||
       charStringIsEqualToCString(outputSource->sourceName, "-", false)) {
      printf("ERROR: Using stdin/stdout is incompatible with --error-report\n");
      return RETURN_CODE_NOT_RUN;
    }
    if(midiSource != NULL && charStringIsEqualToCString(midiSource->sourceName, "-", false)) {
      printf("ERROR: MIDI source from stdin is incompatible with --error-report\n");
      return RETURN_CODE_NOT_RUN;
    }
  }
  if(outputSource == NULL) {
    logInternalError("Default output sample source was null");
    return RETURN_CODE_INTERNAL_ERROR;
  }
  if(inputSource == NULL || inputSource->sampleSourceType == SAMPLE_SOURCE_TYPE_SILENCE) {
    // If the first plugin in the chain is an instrument, use the silent source as our input and
    // make sure that there is a corresponding MIDI file
    headPlugin = pluginChain->plugins[0];
    if(headPlugin->pluginType == PLUGIN_TYPE_INSTRUMENT) {
      if(midiSource == NULL) {
        // I guess some instruments (like white noise generators etc.) don't necessarily
        // need MIDI, actually this is most useful for our internal plugins and generators.
        // Anyways, this should only be a soft warning for those who know what they're doing.
        logWarn("Plugin chain contains an instrument, but no MIDI source was supplied");
        if(maxTimeInMs == 0) {
          // However, if --max-time wasn't given, then there is effectively no input source
          // and thus processing would continue forever. That won't work.
          logError("No valid input source or maximum time, don't know when to stop processing");
          return RETURN_CODE_MISSING_REQUIRED_OPTION;
        }
        else {
          // If maximum time was given and there is no other input source, then use silence
          inputSource = newSampleSourceSilence();
        }
      }
    }
    else {
      logError("Plugin chain contains only effects, but no input source was supplied");
      return RETURN_CODE_MISSING_REQUIRED_OPTION;
    }
  }

  inputSampleBuffer = newSampleBuffer(getNumChannels(), getBlocksize());
  inputTimer = newTaskTimerWithCString(PROGRAM_NAME, "Input Source");
  outputSampleBuffer = newSampleBuffer(getNumChannels(), getBlocksize());
  outputTimer = newTaskTimerWithCString(PROGRAM_NAME, "Output Source");

  // Initialization is finished, we should be able to free this memory now
  freeProgramOptions(programOptions);

  // If a maximum time was given, figure it out here
  if(maxTimeInMs > 0) {
    maxTimeInFrames = (unsigned long)(maxTimeInMs * getSampleRate()) / 1000l;
  }

  processingDelayInFrames = pluginChainGetProcessingDelay(pluginChain);
  // Get largest tail time requested by any plugin in the chain
  tailTimeInMs += pluginChainGetMaximumTailTimeInMs(pluginChain);
  tailTimeInFrames = (unsigned long)(tailTimeInMs * getSampleRate()) / 1000l + processingDelayInFrames;
  pluginChainPrepareForProcessing(pluginChain);

  // Update sample rate on the event logger
  setLoggingZebraSize((long)getSampleRate());
  logInfo("Starting processing input source");
  logDebug("Sample rate: %.0f", getSampleRate());
  logDebug("Blocksize: %d", getBlocksize());
  logDebug("Channels: %d", getNumChannels());
  logDebug("Tempo: %.2f", getTempo());
  logDebug("Processing delay frames: %lu", processingDelayInFrames);
  logDebug("Time signature: %d/%d", getTimeSignatureBeatsPerMeasure(), getTimeSignatureNoteValue());
  taskTimerStop(initTimer);

  silentSampleInput = sampleSourceFactory(NULL);
  silentSampleOutput = sampleSourceFactory(NULL);
  // Main processing loop
  while(!finishedReading) {
    taskTimerStart(inputTimer);
    finishedReading = !readInput(inputSource, silentSampleInput, inputSampleBuffer, tailTimeInFrames);

    // TODO: For streaming MIDI, we would need to read in events from source here
    if(midiSequence != NULL) {
      LinkedList midiEventsForBlock = newLinkedList();
      // MIDI source overrides the value set to finishedReading by the input source
      finishedReading = !fillMidiEventsFromRange(midiSequence, audioClock->currentFrame, getBlocksize(), midiEventsForBlock);
      linkedListForeach(midiEventsForBlock, _processMidiMetaEvent, &finishedReading);
      pluginChainProcessMidi(pluginChain, midiEventsForBlock);
      freeLinkedList(midiEventsForBlock);
    }
    taskTimerStop(inputTimer);

    if(maxTimeInFrames > 0 && audioClock->currentFrame >= maxTimeInFrames) {
      logInfo("Maximum time reached, stopping processing after this block");
      finishedReading = true;
    }

    pluginChainProcessAudio(pluginChain, inputSampleBuffer, outputSampleBuffer);

    taskTimerStart(outputTimer);
    if(finishedReading) {
      outputSampleBuffer->blocksize = inputSampleBuffer->blocksize;//The input buffer size has been adjusted.
      logDebug("Using buffer size of %d for final block", outputSampleBuffer->blocksize);
    }
    writeOutput(outputSource, silentSampleOutput, outputSampleBuffer, processingDelayInFrames);
    taskTimerStop(outputTimer);
    advanceAudioClock(audioClock, outputSampleBuffer->blocksize);
  }

  // Close file handles for input/output sources
  silentSampleInput->closeSampleSource(silentSampleInput);
  silentSampleOutput->closeSampleSource(silentSampleOutput);
  inputSource->closeSampleSource(inputSource);
  outputSource->closeSampleSource(outputSource);

  // Print out statistics about each plugin's time usage
  // TODO: On windows, the total processing time is stored in clocks and not milliseconds
  // These values must be converted using the QueryPerformanceFrequency() function
  audioClockStop(audioClock);
  taskTimerStop(totalTimer);

  if(totalTimer->totalTaskTime > 0) {
    taskTimerList = newLinkedList();
    linkedListAppend(taskTimerList, initTimer);
    linkedListAppend(taskTimerList, inputTimer);
    linkedListAppend(taskTimerList, outputTimer);
    for(i = 0; i < pluginChain->numPlugins; i++) {
      linkedListAppend(taskTimerList, pluginChain->audioTimers[i]);
      linkedListAppend(taskTimerList, pluginChain->midiTimers[i]);
    }

    totalTimeString = taskTimerHumanReadbleString(totalTimer);
    logInfo("Total processing time %s, approximate breakdown:", totalTimeString->data);
    linkedListForeach(taskTimerList, _printTaskTime, totalTimer);
  }
  else {
    // Woo-hoo!
    logInfo("Total processing time <1ms. Either something went wrong, or your computer is smokin' fast!");
  }
  freeTaskTimer(initTimer);
  freeTaskTimer(inputTimer);
  freeTaskTimer(outputTimer);
  freeTaskTimer(totalTimer);
  freeLinkedList(taskTimerList);
  freeCharString(totalTimeString);

  if(midiSequence != NULL) {
    logInfo("Read %ld MIDI events from %s",
      midiSequence->numMidiEventsProcessed,
      midiSource->sourceName->data);
  }
  else {
    logInfo("Read %ld frames from %s",
      inputSource->numSamplesProcessed / getNumChannels(),
      inputSource->sourceName->data);
  }
  logInfo("Wrote %ld frames to %s",
    outputSource->numSamplesProcessed / getNumChannels(),
    outputSource->sourceName->data);

  // Shut down and free data (will also close open files, plugins, etc)
  logInfo("Shutting down");
  freeSampleSource(inputSource);
  freeSampleSource(outputSource);
  freeSampleBuffer(inputSampleBuffer);
  freeSampleBuffer(outputSampleBuffer);
  pluginChainShutdown(pluginChain);
  freePluginChain(pluginChain);

  if(midiSource != NULL) {
    freeMidiSource(midiSource);
  }
  if(midiSequence != NULL) {
    freeMidiSequence(midiSequence);
  }

  freeAudioSettings();
  logInfo("Goodbye!");
  freeEventLogger();
  freeAudioClock(getAudioClock());

  if(errorReporter->started) {
    errorReporterClose(errorReporter);
  }
  freeErrorReporter(errorReporter);

  return RETURN_CODE_SUCCESS;
}
示例#24
0
void quitFunction(){
	freeLinkedList();
}
示例#25
0
文件: main.c 项目: PierreGts/SDA
int main(int argc, char** argv)
{
    // Parse command line input
    if (argc  != 6)
    {
        fprintf(stderr, "%s is expecting exactly five parameters: "
                        "(1) a .csv file containing the cities and their coordinates, "
                        "(2) the first latitude, (3) the first longitude, "
                        "(4) the second latitude and (5) the second longitude\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    char* fileName = argv[1];
    double latitudeA = strtod(argv[2], NULL);
    double longitudeA = strtod(argv[3], NULL);
    double latitudeB = strtod(argv[4], NULL);
    double longitudeB = strtod(argv[5], NULL);

    // Compute min/max latitude/longitude
    double latitudeMin = (latitudeA < latitudeB)? latitudeA: latitudeB;
    double latitudeMax = (latitudeA < latitudeB)? latitudeB: latitudeA;
    double longitudeMin = (longitudeA < longitudeB)? longitudeA: longitudeB;
    double longitudeMax = (longitudeA < longitudeB)? longitudeB: longitudeA;

    // Parse csv file
    LinkedList* cities = parseCsv(fileName);
    size_t nbCities = sizeOfLinkedList(cities);
    printf("Number of cities: %lu\n", nbCities);

    // Compute the cities in the box
    LinkedList* citiesInBox = findCities(cities, latitudeMin, latitudeMax,
                                         longitudeMin, longitudeMax);
    if(!citiesInBox)
    {
        fprintf(stderr, "Allocation error while finding the cities. Exiting...\n");
        exit(EXIT_FAILURE);
    }

    // Print stuff
    nbCities = sizeOfLinkedList(citiesInBox);
    printf("Number of cities after filtering: %lu\n", nbCities);
    if(nbCities <= 50)
    {
        LLNode* node = citiesInBox->head;
        City* city;
        while(node != NULL)
        {
            city = (City*)node->value;
            printf("%s (%f, %f)\n", city->name, city->latitude, city->longitude);
            node = node->next;
        }
    }

    // Free the linked list: the name must be freed beforehand
    freeLinkedList(citiesInBox, false);
    LLNode* node = cities->head;
    City* city;
    while(node != NULL)
    {
        city = (City*)node->value;
        free(city->name);
        node = node->next;
    }
    freeLinkedList(cities, true);

    exit(EXIT_SUCCESS);
}
示例#26
0
static int _testFreeNullLinkedList(void) {
  freeLinkedList(NULL);
  return 0;
}
示例#27
0
文件: Driver.c 项目: inochi108/OS_HW2
void main(void) {

	srand(time(NULL));
	char processNameSetUp[10] = "Process";
	int i = 0;
	FIFO_queue_p PCBContainer = createLinkedList();
	PCB_p tempPCB;
	int PCBCounter = 0;
	int loopCounter = 0;
	int numberOfPCB = 0;

	FILE* outFile = fopen("scheduleTrace.txt", "w+");
	fprintf(outFile, "Group 5: Nok Him Nam, Jowy Tran, Mark Johnson, David Humphreys\nDate (DD/MM/YY) : 28/ 01/ 2015\nAssignment : Problem 2 - Scheduling\n");

	//Create CPU
	CPU_instance_p testingCPU = createCPU();

	//Master CPU Loop
	while (loopCounter <= MAX_NUMBER_OF_RUNTIME) {

		if (loopCounter % PRINT_EVERY_xTIMES == 0) {
			fprintf(outFile, "\n__________NEXT TIME QUANTUM  : %d___________\n", loopCounter);
		}

		numberOfPCB = rand() % 6;

		//While the number of PCBs created is less than 30, create more PCBs
		if (PCBCounter < MAX_NUMBER_OF_PCB && PCBCounter + numberOfPCB <= MAX_NUMBER_OF_PCB) {

			if (loopCounter % PRINT_EVERY_xTIMES == 0) {
				//fprintf(outFile, "\n__________NEXT TIME QUANTUM  : %d___________\n", loopCounter);
				fprintf(outFile, "//----------------------------------\n");
				fprintf(outFile, "We are creating %d PCBs \n\n", numberOfPCB);
			}

			for (i = 0; i < numberOfPCB; i++) {

				sprintf(processNameSetUp, "Process%d", PCBCounter);

				enqueue(PCBContainer, tempPCB = createPCB(processNameSetUp, PCBCounter, rand() % 15,
					0, 1000 * PCBCounter, ready));
				if (loopCounter % PRINT_EVERY_xTIMES == 0) {
					toStringFileVersion(tempPCB, outFile);
				}

				strcpy(processNameSetUp, "Process");
				PCBCounter++;
			}
		} else if(PCBCounter == MAX_NUMBER_OF_PCB && loopCounter % 4 == 0) {
			fprintf(outFile, "We are done creating PCBs\n");
		}

		if (loopCounter % PRINT_EVERY_xTIMES == 0) {
			fprintf(outFile, "//----------------------------------\n");
		}

		//If we have started a running processes, increment the PC value to simulate running
		if (testingCPU->runningProcess != NULL) {
			testingCPU->runningProcess->pc += rand() % 1000 + 3000;

			//strcpy(testingCPU->systemStack->name, testingCPU->runningProcess->name);
			testingCPU->systemStack->pc = testingCPU->runningProcess->pc;
		}
		//else, create a temp "fake" processs PCB till a "real" one is created
		else {
			testingCPU->runningProcess = createPCB("Default", 0, 0, 0, 0, running);
			testingCPU->systemStack = createPCB("Default", 0, 0, 0, 0, running);
		}

		//Simulate Timer Interrupt
		timerISR(testingCPU, PCBContainer);

		if (loopCounter % PRINT_EVERY_xTIMES == 0) {
			//PRINT RESULTS AFTER TIMER ISR
			fprintf(outFile, "\nRunning process: \n");
			//printf("//--------------------------------------\n");
			toStringFileVersion(testingCPU->runningProcess, outFile);
			fprintf(outFile, "//---------------------------------------\n\n");
			fprintf(outFile, "State of the Ready Queue: \n\n");
			printListFileVersion(testingCPU->readQueue_p, outFile);
			fprintf(outFile, "\n\n");
		}

		//pseudo halt for debug screen
		//getchar();

		//one run has passed
		loopCounter++;
		
	}

	//free used memory
	freeLinkedList(PCBContainer);
	freeCPU(testingCPU);
}
示例#28
0
文件: lab03b.c 项目: xtrm0/labs-aed
/*
 * Function:
 *   main
 */
int main(int argc, char *argv[])
{
  FILE * fp;
  LinkedList * lp;

  int sentido = ASCENDENTE;
  int parametro = ID;

  char extOut[] = ".sort";
  char * fileNameIn;
  char * fileNameOut;


  /* Check number of arguments                                    */
  if(argc < 2)
  {
    printf("Usage: lab03b [filename] [arguments opcions]\n");
    exit(1);
  }

    /* Open input file                                              */
  fileNameIn = argv[1];

  argv++;                       /* increments index of argv to point to the
                                   second argument */
  while (*(++argv)) {
    if (strcmp(*argv, "-id") == 0)
      parametro = ID;
    else if (strcmp(*argv, "-age") == 0)
      parametro = AGE;
    else if (strcmp(*argv, "-height") == 0)
       parametro = HEIGHT;
    else if (strcmp(*argv, "-weight") == 0)
       parametro = WEIGHT;
     else if (strcmp(*argv, "-a") == 0)
      sentido = ASCENDENTE;
    else if (strcmp(*argv, "-d") == 0)
      sentido = DESCENDENTE;
    else {
      fprintf(stderr, "Wrong arguments\n");
      exit(3);
    }
  }

  fp  = fopen(fileNameIn, "r");
  if(fp == NULL)
  {
    printf("Open error of input file.\n");
    exit(2);
  }


  /* Read input file and construct linked list with entries       */
  lp = readEntryFile2LinkedList(fp , parametro, sentido);


  /* Close input file                                             */
  fclose(fp);


  /* Determine output filename                                    */
  fileNameOut = (char *) malloc(sizeof(char) * 
                                 (strlen(fileNameIn) + 
                                  strlen(extOut) + 1));
  if(fileNameOut == NULL)
  {
    printf("Memory allocation error for fileNameOut.\n");
    exit(1);
  }

  strcpy(fileNameOut, fileNameIn);
  strcat(fileNameOut, extOut);


  /* Open output file                                             */
  fp  = fopen(fileNameOut, "w");

  if(fp == NULL)
  {
    printf("Open error of input file.\n");
    exit(2);
  }


  /* Write entries to output file                                 */
  writeEntryFile(lp, fp);


  /* Free space allocated to fileNameOut                          */
  free(fileNameOut);


  /* Close output file                                            */
  fclose(fp);


  /* Free linked list with entries                                */
  freeLinkedList(lp, freeEntryItem);


  return 0;
}
void runApplicationTest(char *applicationPath, const char *testName, LinkedList testArguments, ReturnCodes expectedResultCode, boolByte anazyleOutput) {
  char** applicationArguments;
  ArgumentsCopyData argumentsCopyData;
  int resultCode = -1;
  LinkedList defaultArguments = getDefaultArguments(testName);
  LinkedList arguments = _appendLinkedLists(defaultArguments, testArguments);
  CharString failedAnalysisFunctionName = newCharString();
  unsigned long failedAnalysisSample;

  // Remove any output files which may have been left from previous tests
  foreachItemInList(defaultArguments, _removeOutputFile, NULL);

#if WINDOWS
#else
  mkdir("out", 0755);
#endif

#if WINDOWS
  logUnsupportedFeature("Application testing");
#else
  int numArgs = numItemsInList(arguments);
  // Add two extra items to the array, one for the application path and another for a NULL object.
  // These are required for the calls to the execv* functions.
  applicationArguments = (char**)malloc(sizeof(char*) * (numArgs + 2));
  applicationArguments[0] = applicationPath;
  applicationArguments[numArgs + 1] = NULL;
  argumentsCopyData.currentIndex = 1;
  argumentsCopyData.outArray = applicationArguments;
  foreachItemInList(arguments, _copyArgumentToArray, &argumentsCopyData);
  printf("  %s: ", testName);

  pid_t forkedPid = fork();
  if(forkedPid == 0) {
    resultCode = execvp(applicationPath, applicationArguments);
    exit(resultCode);
  }
  else {
    int statusLoc;
    waitpid(forkedPid, &statusLoc, 0);
    if(WIFEXITED(statusLoc)) {
      resultCode = WEXITSTATUS(statusLoc);
    }
  }
#endif

  if(resultCode == expectedResultCode) {
    if(anazyleOutput) {
      if(analyzeFile(_getTestOutputFilename(testName, "pcm"), failedAnalysisFunctionName, &failedAnalysisSample)) {
        testsPassed++;
        foreachItemInList(defaultArguments, _removeOutputFile, NULL);
        printTestSuccess();
      }
      else {
        printTestFail();
        printf("    in test '%s', while analyzing output for %s at sample %lu.\n",
          testName, failedAnalysisFunctionName->data, failedAnalysisSample);
        testsFailed++;
      }
    }
    else {
      testsPassed++;
      foreachItemInList(defaultArguments, _removeOutputFile, NULL);
      printTestSuccess();
    }
  }
  else {
    printTestFail();
    printf("    in %s. Expected result code %d, got %d.\n", testName, expectedResultCode, resultCode);
    testsFailed++;
  }

  freeLinkedList(defaultArguments);
  freeLinkedList(testArguments);
  freeLinkedList(arguments);
}
示例#30
0
/**
 * Main, uses getopt to check for -t arguments, puts all filepath arguments in a list
 * and starts to search through each filepath for the file until the list is empty.
 * Then prints the list with all hits and frees all allocated memory.
 */
int main(int argc, char *argv[]) {

	int c;
	int fileType = 0;
	int firstArg = 1;

	while ((c = getopt(argc, argv, "t:")) != -1) {
		char* str = optarg;

		switch (c) {
		case 't':
			firstArg = optind;
			if (*str == 'd') {
				fileType = 1;
			} else if (*str == 'f') {
				fileType = 2;
			} else if (*str == 'l') {
				fileType = 3;
			}
			break;
		case '?':
			if (optopt == 'c')
				fprintf(stderr, "Option -%c requires an argument.\n", optopt);
			else if (isprint(optopt))
				fprintf(stderr, "Unknown option `-%c'.\n", optopt);
			else
				fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt);
			return 1;
		default:
			abort();
		}
	}

	// Create linked lists to store paths.
	linkedList dirList = empty();
	linkedList dirsWithFile = empty();

	// Add path arguments to dirList
	char *searchDir;
	while (firstArg < argc - 1) {
		searchDir = calloc(1, sizeof(char[strlen(argv[firstArg]) + 1]));
		strcpy(searchDir, argv[firstArg]);
		insert(dirList, searchDir);
		firstArg++;
	}

	// Search for file in each path.
	linkedList node = dirList;
	while (node->next != NULL) {
		node = node->next;
		if (searchForFile((char*) node->data, argv[argc - 1], fileType,
				dirList)) {
			addDirToList((char*) node->data, dirsWithFile);
		}
	}

	// Print paths where file was found
	print_list(dirsWithFile);

	freeLinkedList(dirList);
	freeLinkedList(dirsWithFile);

	return 0;
}