示例#1
0
文件: abp.c 项目: pbmartins/AlgC
unsigned int ABPEvenCount (PtABPNode proot)
{
    PtABPNode node = proot;
    PtQueue queue;
    unsigned int count = 0;

    if (proot == NULL) {
        Error = ABP_EMPTY;
        return -1;
    }

    if ((queue = QueueCreate(sizeof(PtABPNode))) == NULL) {
        Error = NO_MEM;
        return -1;
    }

    QueueEnqueue(queue, &node);
    
    while (!QueueIsEmpty(queue)) {
        QueueDequeue(queue, &node);
        if (!(node->Elem & 1))
            count++;

        if (node->PtLeft != NULL)
            QueueEnqueue(queue, &(node->PtLeft));
        if (node->PtRight != NULL)
            QueueEnqueue(queue, &(node->PtRight));
    }

    QueueDestroy(&queue);
    Error = OK;
    return count;
}
示例#2
0
static void test_basics(void)
{
    Queue *q = QueueNew(free);

    assert_int_equal(0, QueueCount(q));
    assert_true(QueueIsEmpty(q));


    QueueEnqueue(q, xstrdup("hello"));
    assert_int_equal(1, QueueCount(q));
    assert_false(QueueIsEmpty(q));
    assert_string_equal("hello", QueueHead(q));


    QueueEnqueue(q, xstrdup("world"));
    assert_int_equal(2, QueueCount(q));
    assert_string_equal("hello", QueueHead(q));


    char *head = QueueDequeue(q);
    assert_string_equal("hello", head);
    free(head);


    assert_string_equal("world", QueueHead(q));
    head = QueueDequeue(q);
    assert_string_equal("world", head);
    free(head);


    QueueDestroy(q);
}
示例#3
0
static void test_destroy(void)
{
    Queue *q = QueueNew(free);

    QueueEnqueue(q, xstrdup("1"));
    QueueEnqueue(q, xstrdup("2"));
    QueueEnqueue(q, xstrdup("3"));

    assert_int_equal(3, QueueCount(q));

    QueueDestroy(q);
}
void findSSShortestPath(graphT g, int v, int **distance) {
// int* findSSShortestPath(graphT g, int v) {
    queueT queue = QueueInit(n);
    // GraphPrint(g);
    // int* distance = malloc(sizeof(int) * n);
    int* parent = malloc(sizeof(int) * n);
    for (int i = 0; i < n; ++i) {
        // distance[i] = INT_MAX;
        (*distance)[i] = INT_MAX;
        parent[i] = UNDEFINED;
    }
    // distance[v] = 0;
    (*distance)[v] = 0;
    // printArray(distance, n);
    QueueEnqueue(queue, v);
    // printf("Enqueued %d\n", v);
    while (!QueueIsEmpty(queue)){
        int t = QueueDequeue(queue);
        // printf("Dequeued %d\n", t);
        // printf("Neighbor of %d: \n", t);
        for (int i = 0; i < GraphOutDegreeForVertex(g, t); ++i) {
            int w = g->alist[t]->list[i];
            // printf("    %d\n", w);
            if ((*distance)[w] == INT_MAX){
            // if (distance[w] == INT_MAX){
                parent[w] = t;
                // distance[w] = distance[t] + 1;
                (*distance)[w] = (*distance)[t] + 1;
                QueueEnqueue(queue, w);
                // printf("Enqueued %d\n", w);
            }
        }
    }
    // printArray(distance, n);
    QueueDestroy(queue);
    free(parent);
}
示例#5
0
文件: abp.c 项目: pbmartins/AlgC
void ABPByLevel (PtABPNode proot) /* travessia por niveis - traversal by levels */
{
	PtABPNode Node = proot; PtQueue Queue;

	if (proot == NULL) { Error = ABP_EMPTY; return;	}	/* arvore vazia - empty tree */
	if ((Queue = QueueCreate (sizeof (PtABPNode))) == NULL) { Error = NO_MEM ; return; }

	QueueEnqueue (Queue, &Node);	/* armazenar a raiz - storing the root */

	while (!QueueIsEmpty (Queue))
	{
		QueueDequeue (Queue, &Node);	/* retirar o no - retrieve the node */
		printf ("%d ", Node->Elem);	/* imprimir o elemento - printing the element */

		/* armazenar a raiz da subarvore esquerda - storing the left subtree root */
		if (Node->PtLeft != NULL) QueueEnqueue (Queue, &Node->PtLeft);

		/* armazenar a raiz da subarvore direita - storing the right subtree root */
		if (Node->PtRight != NULL) QueueEnqueue (Queue, &Node->PtRight);
	}

	QueueDestroy (&Queue);	/* destruir a fila - releasing the queue */
    Error = OK;
}
示例#6
0
/*
 * Handles user reaction to incoming file request
 */
void PeerFileUser (UDWORD seq, Contact *cont, const char *reason, Server *serv)
{
    Event *event;

    if (!(event = QueueDequeue2 (serv->conn, QUEUE_USERFILEACK, seq, cont)))
    {
        rl_printf (i18n (2258, "No pending incoming file transfer request for %s with (sequence %ld) found.\n"),
                  cont ? cont->nick : "<?>", UD2UL (seq));
    }
    else
    {
        if (reason)
            event->opt = OptSetVals (event->opt, CO_FILEACCEPT, 0, CO_REFUSE, reason, 0);
        else
            event->opt = OptSetVals (event->opt, CO_FILEACCEPT, 1, 0);
        QueueEnqueue (event);
        QueueRelease (event);
    }
}
示例#7
0
int lcd_tick(int state){
    static unsigned short lcd_hold_time = 0;
    switch(state){// lcd actions
        case st_lcd_start:
            state = st_lcd_init;
            break;
        case st_lcd_init:
            if(!QueueIsEmpty(lcd_command_queue)){
                state = st_lcd_write;
            } else {
                state = st_lcd_wait;
            }
            break;
        case st_lcd_wait:
            if(!QueueIsEmpty(lcd_command_queue)){
                state = st_lcd_write;
            } else {
                state = st_lcd_wait;
            }
            break;
        case st_lcd_write:
            if( lcd_command_queue->buffer[lcd_command_queue->front] == lcd_write_locked || 
                lcd_command_queue->buffer[lcd_command_queue->front] == lcd_write_unlocked || 
                lcd_command_queue->buffer[lcd_command_queue->front] == lcd_write_invalid ||
                lcd_command_queue->buffer[lcd_command_queue->front] == lcd_write_added ||
                lcd_command_queue->buffer[lcd_command_queue->front] == lcd_write_add_exist ||
                lcd_command_queue->buffer[lcd_command_queue->front] == lcd_write_add_full ||
                lcd_command_queue->buffer[lcd_command_queue->front] == lcd_write_removed ||
                lcd_command_queue->buffer[lcd_command_queue->front] == lcd_write_remove_empty){
                    
                state = st_lcd_hold;
                lcd_hold_time = 0;
            } else {
                state = st_lcd_wait;
            }
            QueueDequeue(lcd_command_queue);                
            break;
        case st_lcd_hold:
            if(lcd_hold_time < 20){
                lcd_hold_time++;
                state = st_lcd_hold;
            } else {
                state = st_lcd_write;
                QueueEnqueue(lcd_command_queue, lcd_write_ready);
            }                
            break;
        default:
            state = st_lcd_start;
            break;
    }//end lcd transitions
    
    switch(state){
        case st_lcd_init:
            LCD_init();
            break;
        case st_lcd_write:
            if(lcd_command_queue->buffer[lcd_command_queue->front] == lcd_write_ready){
                LCD_ClearScreen();
                if(isTagDBEmpty()){
                    LCD_DisplayString(1, (const unsigned char*)"No Valid Keys");
                    LCD_DisplayString(17, (const unsigned char*)"Add w/ Master");
                } else {
                    LCD_DisplayString(1, (const unsigned char*)"Scan Key Tag");
                    if(current_lock_position == locked){
                        LCD_DisplayString(17, (const unsigned char*)"to Unlock");
                    } else if(current_lock_position == unlocked){
                        LCD_DisplayString(17, (const unsigned char*)"to Lock");
                    } else {
                        LCD_DisplayString(17, (const unsigned char*)"malfunction");
                    }
                }                
            } else if(lcd_command_queue->buffer[lcd_command_queue->front] == lcd_write_locked){
                LCD_ClearScreen();
                LCD_DisplayString(1, (const unsigned char*)"Locked by");
                LCD_DisplayString(17, (const unsigned char*)"Key# ");
                LCD_DisplayString(22, (const unsigned char*)tag_id);
            } else if(lcd_command_queue->buffer[lcd_command_queue->front] == lcd_write_unlocked){
                LCD_ClearScreen();
                LCD_DisplayString(1, (const unsigned char*)"Unlocked by");
                LCD_DisplayString(17, (const unsigned char*)"Key# ");
                LCD_DisplayString(22, (const unsigned char*)tag_id);
            } else if(lcd_command_queue->buffer[lcd_command_queue->front] == lcd_write_invalid){
                LCD_ClearScreen();
                LCD_DisplayString(1, (const unsigned char*)"Key Tag");
                LCD_DisplayString(17, (const unsigned char*)"Not Authorized");
            } else if(lcd_command_queue->buffer[lcd_command_queue->front] == lcd_write_master){
                LCD_ClearScreen();
                LCD_DisplayString(1, (const unsigned char*)"Master Key");
                LCD_DisplayString(17, (const unsigned char*)"Add or Remove");
            } else if(lcd_command_queue->buffer[lcd_command_queue->front] == lcd_write_add){
                LCD_ClearScreen();
                LCD_DisplayString(1, (const unsigned char*)"Scan the Tag");
                LCD_DisplayString(17, (const unsigned char*)"to be Added");
            } else if(lcd_command_queue->buffer[lcd_command_queue->front] == lcd_write_remove){
                LCD_ClearScreen();
                LCD_DisplayString(1, (const unsigned char*)valid_tag_db[current_remove_option]);
                LCD_DisplayString(17, (const unsigned char*)"Remove?");
            } else if(lcd_command_queue->buffer[lcd_command_queue->front] == lcd_write_malfunction){
                LCD_ClearScreen();
                LCD_DisplayString(1, (const unsigned char*)"Malfunction");
                LCD_DisplayString(17, (const unsigned char*)"Check Lock");
            } else if(lcd_command_queue->buffer[lcd_command_queue->front] == lcd_write_add_exist){
                LCD_ClearScreen();
                LCD_DisplayString(1, (const unsigned char*)"Key Tag Already");
                LCD_DisplayString(17, (const unsigned char*)"Added");
            } else if(lcd_command_queue->buffer[lcd_command_queue->front] == lcd_write_added){
                LCD_ClearScreen();
                LCD_DisplayString(1, (const unsigned char*)"Key# ");
                LCD_DisplayString(6, (const unsigned char*)tag_id);
                LCD_DisplayString(17, (const unsigned char*)"Added");
            }  else if(lcd_command_queue->buffer[lcd_command_queue->front] == lcd_write_add_full){
                LCD_ClearScreen();
                LCD_DisplayString(1, (const unsigned char*)"Over Max # Keys");
                LCD_DisplayString(17, (const unsigned char*)"Cannot Add");
            } else if(lcd_command_queue->buffer[lcd_command_queue->front] == lcd_write_removed){
                LCD_ClearScreen();
                LCD_DisplayString(1, (const unsigned char*)"Key Tag Removed");
            } else if(lcd_command_queue->buffer[lcd_command_queue->front] == lcd_write_remove_empty){
                LCD_ClearScreen();
                LCD_DisplayString(1, (const unsigned char*)"No Valid Keys");
                LCD_DisplayString(17, (const unsigned char*)"to Remove");
            }
            break;
        default:
            break;
    }//end lcd actions
    return state;
}    
示例#8
0
/*****************************************************************************
 * Render: displays previously rendered output
 *****************************************************************************
 * This function send the currently rendered image to adjust modified image,
 * waits until it is displayed and switch the two rendering buffers, preparing
 * next frame.
 *****************************************************************************/
static subpicture_t *Filter( filter_t *p_filter, mtime_t date )
{
    filter_sys_t *p_sys = p_filter->p_sys;

    /* We might need to open these at any time. */
    vlc_mutex_lock( &p_sys->lock );
    if( p_sys->i_inputfd == -1 )
    {
        p_sys->i_inputfd = vlc_open( p_sys->psz_inputfile, O_RDONLY | O_NONBLOCK );
        if( p_sys->i_inputfd == -1 )
        {
            msg_Warn( p_filter, "Failed to grab input file: %s (%m)",
                      p_sys->psz_inputfile );
        }
        else
        {
            msg_Info( p_filter, "Grabbed input file: %s",
                      p_sys->psz_inputfile );
        }
    }

    if( p_sys->i_outputfd == -1 )
    {
        p_sys->i_outputfd = vlc_open( p_sys->psz_outputfile,
                                  O_WRONLY | O_NONBLOCK );
        if( p_sys->i_outputfd == -1 )
        {
            if( errno != ENXIO )
            {
                msg_Warn( p_filter, "Failed to grab output file: %s (%m)",
                          p_sys->psz_outputfile );
            }
        }
        else
        {
            msg_Info( p_filter, "Grabbed output file: %s",
                      p_sys->psz_outputfile );
        }
    }
    vlc_mutex_unlock( &p_sys->lock );

    /* Read any waiting commands */
    if( p_sys->i_inputfd != -1 )
    {
        char p_buffer[1024];
        ssize_t i_len = read( p_sys->i_inputfd, p_buffer, 1024 );
        if( i_len == -1 )
        {
            /* We hit an error */
            if( errno != EAGAIN )
            {
                msg_Warn( p_filter, "Error on input file: %m" );
                close( p_sys->i_inputfd );
                p_sys->i_inputfd = -1;
            }
        }
        else if( i_len == 0 )
        {
            /* We hit the end-of-file */
        }
        else
        {
            BufferAdd( &p_sys->input, p_buffer, i_len );
        }
    }

    /* Parse any complete commands */
    char *p_end, *p_cmd;
    while( ( p_end = memchr( p_sys->input.p_begin, '\n',
                             p_sys->input.i_length ) ) )
    {
        commanddesc_t *p_cur = NULL;
        bool b_found = false;
        size_t i_index = 0;

        *p_end = '\0';
        p_cmd = BufferGetToken( &p_sys->input );

        msg_Info( p_filter, "Search command: %s", p_cmd );
        for( i_index = 0; i_index < p_sys->i_commands; i_index++ )
        {
            p_cur = p_sys->pp_commands[i_index];
            if( !strncmp( p_cur->psz_command, p_cmd, strlen(p_cur->psz_command) ) )
            {
                p_cmd[strlen(p_cur->psz_command)] = '\0';
                b_found = true;
                break;
            }
        }

        if( !b_found )
        {
            /* No matching command */
            msg_Err( p_filter, "Got invalid command: %s", p_cmd );
            BufferPrintf( &p_sys->output, "FAILURE: %d Invalid Command\n", VLC_EGENERIC );
        }
        else
        {
            msg_Info( p_filter, "Got valid command: %s", p_cmd );

            command_t *p_cmddesc = malloc( sizeof( command_t ) );
            if( !p_cmddesc )
                return NULL;

            p_cmd = p_cmd + strlen(p_cur->psz_command) +1;
            p_cmddesc->p_command = p_cur;
            p_cmddesc->p_command->pf_parser( p_cmd, p_end,
                                             &p_cmddesc->params );

            if( p_cmddesc->p_command->b_atomic && p_sys->b_atomic )
                QueueEnqueue( &p_sys->atomic, p_cmddesc );
            else
                QueueEnqueue( &p_sys->pending, p_cmddesc );
        }

        BufferDel( &p_sys->input, p_end - p_sys->input.p_begin + 1 );
    }

    /* Process any pending commands */
    command_t *p_command = NULL;
    while( (p_command = QueueDequeue( &p_sys->pending )) )
    {
        p_command->i_status =
            p_command->p_command->pf_execute( p_filter, &p_command->params,
                                              &p_command->results );
        QueueEnqueue( &p_sys->processed, p_command );
    }

    /* Output any processed commands */
    while( (p_command = QueueDequeue( &p_sys->processed )) )
    {
        if( p_command->i_status == VLC_SUCCESS )
        {
            const char *psz_success = "SUCCESS:";
            const char *psz_nl = "\n";
            BufferAdd( &p_sys->output, psz_success, 8 );
            p_command->p_command->pf_unparse( &p_command->results,
                                              &p_sys->output );
            BufferAdd( &p_sys->output, psz_nl, 1 );
        }
        else
        {
            BufferPrintf( &p_sys->output, "FAILURE: %d\n",
                          p_command->i_status );
        }
    }

    /* Try emptying the output buffer */
    if( p_sys->i_outputfd != -1 )
    {
        ssize_t i_len = write( p_sys->i_outputfd, p_sys->output.p_begin,
                              p_sys->output.i_length );
        if( i_len == -1 )
        {
            /* We hit an error */
            if( errno != EAGAIN )
            {
                msg_Warn( p_filter, "Error on output file: %m" );
                close( p_sys->i_outputfd );
                p_sys->i_outputfd = -1;
            }
        }
        else
        {
            BufferDel( &p_sys->output, i_len );
        }
    }

    if( !p_sys->b_updated )
        return NULL;

    subpicture_t *p_spu = NULL;
    overlay_t *p_overlay = NULL;

    p_spu = p_filter->pf_sub_buffer_new( p_filter );
    if( !p_spu )
    {
        msg_Err( p_filter, "cannot allocate subpicture" );
        return NULL;
    }

    p_spu->b_absolute = true;
    p_spu->i_start = date;
    p_spu->i_stop = 0;
    p_spu->b_ephemer = true;

    subpicture_region_t **pp_region = &p_spu->p_region;
    while( (p_overlay = ListWalk( &p_sys->overlays )) )
    {
        subpicture_region_t *p_region;

        *pp_region = p_region = subpicture_region_New( &p_overlay->format );
        if( !p_region )
            break;

        msg_Dbg( p_filter, "Displaying overlay: %4.4s, %d, %d, %d",
                 (char*)&p_overlay->format.i_chroma, p_overlay->i_x, p_overlay->i_y,
                 p_overlay->i_alpha );

        if( p_overlay->format.i_chroma == VLC_CODEC_TEXT )
        {
            p_region->psz_text = strdup( p_overlay->data.p_text );
            p_region->p_style = text_style_Duplicate( p_overlay->p_fontstyle );
        }
        else
        {
            /* FIXME the copy is probably not needed anymore */
            picture_Copy( p_region->p_picture, p_overlay->data.p_pic );
        }
        p_region->i_x = p_overlay->i_x;
        p_region->i_y = p_overlay->i_y;
        p_region->i_align = SUBPICTURE_ALIGN_LEFT | SUBPICTURE_ALIGN_TOP;
        p_region->i_alpha = p_overlay->i_alpha;
        pp_region = &p_region->p_next;
    }

    p_sys->b_updated = false;
    return p_spu;
}
示例#9
0
VOID NTAPI ComPrint (
  PUCHAR fmt,
  ...
)
{
  va_list args;
  UCHAR str[1024] = { 0 };
  int i, len, j;
  ULONG64 tsc = RegGetTSC ();

#ifdef USE_COM_PRINTS
  if (g_bDisableComOutput)
    return;
#endif

  va_start (args, fmt);
  CmAcquireSpinLock (&g_ComSpinLock);

#ifdef COMPRINT_OVERFLOW_PROTECTION

  if (SkippedLines) {
    if (tsc - QueueGetLast () <= COMPRINT_SLEEP) {
      SkippedLines++;
      //if (SkippedLines % 100 == 0) _ComPrint (">>> still skipping...\n");
      CmReleaseSpinLock (&g_ComSpinLock);
      return;
    } else {
      QueueSize = 0;
      QueueHead = QueueTail = 0;
      snprintf ((PUCHAR) & str, sizeof (str), ">>> %d lines skipped, continuing normal output...\n", SkippedLines);
      _ComPrint (str);
      str[0] = 0;
      SkippedLines = 0;

    }

  }

  if ((QueueSize == COMPRINT_QUEUE_SZ)
      && (tsc - QueueGetFirst () <= COMPRINT_QUEUE_TH)) {
    // suppress Com output...
    if (!SkippedLines)
      _ComPrint (">>> Supressing further output temporarily...\n");
    SkippedLines++;
    CmReleaseSpinLock (&g_ComSpinLock);
    return;
  }

  if (QueueSize == COMPRINT_QUEUE_SZ)
    QueueDequeue ();            // make space
  QueueEnqueue (tsc);

#endif

  tsc >>= 10;                   // don't be too precise when displaying the time deltas...

#ifndef USE_LOCAL_DBGPRINTS
  if (tsc > LastTsc)
    snprintf ((PUCHAR) & str, sizeof (str), "+% 8x <%02X>:  ", tsc - LastTsc, g_BpId);
  else
    snprintf ((PUCHAR) & str, sizeof (str), "-% 8x <%02X>:  ", LastTsc - tsc, g_BpId);

  len = (int) strlen (str);
  _ComPrint (str);
#endif

  vsnprintf ((PUCHAR) & str, sizeof (str), (PUCHAR) fmt, args);
  len = (int) strlen (str);

  _ComPrint (str);
  LastTsc = tsc;
  CmReleaseSpinLock (&g_ComSpinLock);
}
示例#10
0
int main()
{
	int i,r;
	printf("Testing Queue\n");
	Queue* queue = CreateQueue();

	printf("Inserting values\n");
	for(i = 0; i < 5 ; i++)
	{	
		printf("%d\n",i);
		int result = QueueEnqueue(queue, i);
		if(result == 0)
		{
			printf("%d\n",i);
		}
		else
		{
			printf("Error in enqueuing queue\n");
		}
	}

	printf("Removing values\n");
	for(i = 0; i < 5 ; i++)
	{
		int result =QueueDequeue(queue, &r);
		if(result == 0)
		{
			printf("%d\n",r);
		}
		else
		{
			printf("Error in dequeuing queue\n");
		}
	}

	DeleteQueue(queue);

	printf("\nTesting Stack\n");

	Stack* stack = CreateStack();
	for(i = 0; i < 5 ; i++)
	{
		int result = StackPush(stack, i);
		if(result == 0)
		{
			printf("%d\n",i);
		}
		else
		{
			printf("Error in pushing to stack");
		}
	}

	for(i = 0; i < 5 ; i++)
	{
		int result = StackPop(stack, &r);
		if(result == 0)
		{
			printf("%d\n",r);
		}
		else
		{
			printf("Error in popping values");
		}
	}
	
	DeleteStack(stack); 
	return 0;
}
示例#11
0
int main(void)
{
    char c = '\0';
    double result = 0.0;
    int state = 0;

    char* inputBuffer = NULL;
    size_t inputCount = 0;

    struct Queue inputCharQueue = { 0 };
    if ( QueueNew(&inputCharQueue, sizeof(char)) != 0) {
        return EXIT_FAILURE;
    }

    while (state != STATE_QUIT)
    {    
        printf("Please enter an RPN expression: ");

        while ((c = getchar()) != '\n' && c != EOF) {
            (void) QueueEnqueue(&inputCharQueue, &c);
        }
        inputCount = QueueGetCount(&inputCharQueue);    

        char* newBuffer = (char*)realloc(inputBuffer, (inputCount + 1) * sizeof(char));
        if (!newBuffer) {
            state = STATE_OUT_OF_MEMORY;
            break;
        }
        inputBuffer = newBuffer;

        for (size_t i = 0u; i < inputCount; ++i) {
            (void) QueueDequeue(&inputCharQueue, &inputBuffer[i]);
        }
        inputBuffer[inputCount] = '\0';

        state = RPNEvaluate(inputBuffer, &result);
        if (state == STATE_SUCCESS) {
            printf("Value of expression: %g\n", result);
        }
        else if (state == STATE_OVERFLOW) {
            fprintf(stderr, "Error: too many operands in the expression.\n");
        }
        else if (state == STATE_UNDERFLOW) {
            fprintf(stderr, "Error: not enough operands in the expression.\n");
        }
        else if (state == STATE_INVALID_FORMAT) {
            fprintf(stderr, "Error: expression is in invalid format.\n");
        }
        else if (state == STATE_OUT_OF_MEMORY) {
            fprintf(stderr, "Error: computer out of memory.\n");
        }
        else if (state == STATE_NOT_SUPPORTED) {
            fprintf(stderr, "Error: operator not supported.\n");
        }
        else if (state == STATE_INVALID_OPERAND) {
            fprintf(stderr, "Error: invalid operand.\n");
        }
        else if (state == STATE_QUIT) {
            printf("Thank you for using our application!\n");
        }
        else {
            fprintf(stderr, "Internal error has occured. Please contact your software vendor.\n");
        }
    }

    free(inputBuffer);
    QueueDispose(&inputCharQueue);

    getchar();
    return EXIT_SUCCESS;
}
示例#12
0
void PeerFileResend (Event *event)
{
    Contact *cont;
    Connection *fpeer = event->conn;
    Packet *pak;
    Event *event2;
    int rc;
    const char *opt_text;
    
    if (!fpeer)
    {
        EventD (event);
        return;
    }
    
    ASSERT_FILEDIRECT (fpeer);

    cont = event->cont;
    assert (cont);
    
    if (!OptGetStr (event->opt, CO_FILENAME, &opt_text))
        opt_text = "";

    if (event->attempts >= MAX_RETRY_P2PFILE_ATTEMPTS || (!event->pak && !event->seq))
    {
        rl_log_for (cont->nick, COLCONTACT);
        rl_printf (i18n (2168, "File transfer #%ld (%s) dropped after %ld attempts because of timeout.\n"),
                   UD2UL (event->seq), opt_text, UD2UL (event->attempts));
        TCPClose (fpeer);
    }
    else if (!(fpeer->connect & CONNECT_MASK))
    {
        rl_log_for (cont->nick, COLCONTACT);
        rl_printf (i18n (2072, "File transfer #%ld (%s) canceled because of closed connection.\n"),
                   UD2UL (event->seq), opt_text);
    }
    else if (~fpeer->connect & CONNECT_OK)
    {
        if (!event->seq)
            event->attempts++;
        event->due = time (NULL) + 20;
        QueueEnqueue (event);
        return;
    }
    else if (!event->seq)
    {
        fpeer->oscar_dc_seq = 0;
        PeerPacketSend (fpeer, event->pak);
        PacketD (event->pak);
        event->pak = NULL;
    }
    else if (event->seq != fpeer->oscar_dc_seq)
    {
        event->due = time (NULL) + 10;
        QueueEnqueue (event);
        return;
    }
    else if (event->pak)
    {
        Connection *ffile;
        struct stat finfo;
        
        PeerPacketSend (fpeer, event->pak);
        PacketD (event->pak);
        event->pak = NULL;
        QueueEnqueue (event);
        
        ffile = ServerChild (fpeer->serv, fpeer->cont, TYPE_FILE);
        fpeer->oscar_file = ffile;

        if (stat (opt_text, &finfo))
        {
            rc = errno;
            rl_printf (i18n (2071, "Couldn't stat file %s: %s (%d)\n"),
                      s_wordquote (opt_text), strerror (rc), rc);
        }
        ffile->oscar_file_len = finfo.st_size;

        ffile->sok = open (opt_text, O_RDONLY);
        if (ffile->sok == -1)
        {
            int rc = errno;
            rl_log_for (cont->nick, COLCONTACT);
            rl_printf (i18n (2083, "Cannot open file %s: %s (%d).\n"),
                      opt_text, strerror (rc), rc);
            TCPClose (fpeer);
            ConnectionD (ffile);
            ConnectionD (fpeer);
            return;
        }
        return;
    }
    else if (!fpeer->oscar_file || fpeer->connect & CONNECT_SELECT_W)
    {
        event->attempts++;
        event->due = time (NULL) + 3;
        QueueEnqueue (event);
        return;
    }
    else
    {
        int len = 0;

        pak = PeerPacketC (fpeer, 6);
        len = read (fpeer->oscar_file->sok, pak->data + 1, 2048);
        if (len == -1)
        {
            len = errno;
            rl_log_for (cont->nick, COLCONTACT);
            rl_printf (i18n (2086, "Error while reading file %s: %s (%d).\n"),
                      opt_text, strerror (len), len);
            TCPClose (fpeer);
        }
        else
        {
            pak->len += len;
            fpeer->oscar_file->oscar_file_done += len;
            PeerPacketSend (fpeer, pak);
            PacketD (pak);

            if (len > 0)
            {
                if (fpeer->oscar_file->oscar_file_len)
                    ReadLinePromptUpdate (s_sprintf ("[%s%ld %02d%%%s] %s%s",
                                  COLCONTACT, UD2UL (fpeer->oscar_file->oscar_file_done), (int)((100.0 * fpeer->oscar_file->oscar_file_done) / fpeer->oscar_file->oscar_file_len),
                                  COLNONE, COLSERVER, i18n (2467, "climm>")));
                else
                    ReadLinePromptUpdate (s_sprintf ("[%s%ld%s] %s%s",
                                  COLCONTACT, UD2UL (fpeer->oscar_file->oscar_file_done),
                                  COLNONE, COLSERVER, i18n (2467, "climm>")));
                event->attempts = 0;
                QueueEnqueue (event);
                return;
            }

            ReadLinePromptReset ();
            rl_log_for (cont->nick, COLCONTACT);
            rl_printf (i18n (2087, "Finished sending file %s.\n"), opt_text);
            ConnectionD (fpeer->oscar_file);
            fpeer->oscar_dc_seq++;
            event2 = QueueDequeue (fpeer, QUEUE_PEER_FILE, fpeer->oscar_dc_seq);
            if (event2)
            {
                QueueEnqueue (event2);
                QueueRetry (fpeer, QUEUE_PEER_FILE, fpeer->cont);
                return;
            }
            else
            {
                rl_log_for (cont->nick, COLCONTACT);
                rl_printf (i18n (2088, "Finished sending all %d files.\n"), fpeer->oscar_dc_seq - 1);
                ConnectionD (fpeer);
            }
        }
    }
    EventD (event);
}
示例#13
0
void PeerFileTO (Event *event)
{
    QueueEnqueue (event);
    QueueRelease (event);
    event->callback = NULL;
}
示例#14
0
int main()
{
	struct timeval t1, t2;
	double elapsedTime;
	srand(time(NULL));
	int i;
	int r;
	int result; 

	printf("Testing Queue\n");
	// start timer
	gettimeofday(&t1, NULL);
	Queue* queue = CreateQueue();

	for(i = 0; i < NO_OF_ELEMENTS ; i++)
	{
		// Generate a random value and put that to stack
		r = rand();	
		result = QueueEnqueue(queue, r);
		if(result != 0)
		{
			printf("Error in enqueuing queue\n");
		}
	}

	for(i = 0; i < NO_OF_ELEMENTS ; i++)
	{
		result =QueueDequeue(queue, &r);
		if(result != 0)
		{
			printf("Error in dequeuing queue\n");
		}
	}

	DeleteQueue(queue);

	// Time calculation
	gettimeofday(&t2, NULL);
	elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0;
	elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0;
	printf("Elapsed time %f\nQueue testing completed...\n", elapsedTime);
	
	printf("\nTesting Stack\n");
	// start timer
	gettimeofday(&t1, NULL);

	Stack* stack = CreateStack();
	for(i = 0; i < NO_OF_ELEMENTS ; i++)
	{
		// Generate a random value and put that to stack
		r = rand();	
		result = StackPush(stack, r);
		if(result != 0)
		{
			printf("Error in pushing to stack");
		}
	}

	for(i = 0; i < NO_OF_ELEMENTS ; i++)
	{
		result = StackPop(stack, &r);
		if(result != 0)
		{
			printf("Error in poping stack");
		}
	}
	
	DeleteStack(stack); 

	// Time calculation
	gettimeofday(&t2, NULL);
	elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0;
	elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0;

	printf("Elapsed time %f\nStack testing completed...\n", elapsedTime);

	return 0;
}
示例#15
0
void main(void)
{
	while(1)
	{
		char chc;
		printf("(1)Linked List, (2)Queue: ");
		scanf("%c", &chc);
		if(chc == '1')
		{

			LinkedListHeader list;

			LinkedListContruct(&list);

			bool quit = false;
			char keuze;

			while(1)
			{
				fflush(stdin);

				printf("1 = count, 2 = add front, 3 = add rear, 4 = find index, 5 = print all, 6 = quit: , 7 = Deep Copy");
				scanf("%c", &keuze);

				switch(keuze)
				{
				case '1':
					printf("%d", LinkedListCount(&list));
					break;
				case '2':
					{
					LinkedListNode *eerst = (LinkedListNode*)malloc(sizeof(LinkedListNode));
					printf("Waarde die je wilt invoegen: ");
					scanf("%d", &eerst->data);
					LinkedListAddFront(&list, eerst);
					}
					break;
				case '3':
					{
					LinkedListNode *laatst = (LinkedListNode*)malloc(sizeof(LinkedListNode));
					printf("Waarde die je wilt invoegen: ");
					scanf("%d", &laatst->data);
					LinkedListAddRear(&list, laatst);
					}
					break;
				case '4':
					{
						int index = 0;
						printf("index: ");
						scanf("%d", &index);
						LinkedListNode *node = LinkedListItem(&list, index);
						if(node != NULL)
							printf("Index %d heeft als waarde %d", index, node->data);
					}
					break;
				case '5':
					{
						int cnt = 1;
						while(1)
						{
							LinkedListNode *node = LinkedListItem(&list, cnt);
							if(node != NULL)
							{
								printf("Op index %d is het getal %d\n", cnt, node->data);
								cnt++;
							}
							else
								break;
						}
					}
					break;
				case '6':
					quit = true;
					break;
				case '7':
					{
						LinkedListHeader copiedHeader = {0};
						LinkedListContruct(&copiedHeader);
						LinkedListDeepCopy(&list, &copiedHeader);
						//Gekopieerd. _getch() wordt aangeroepen om te kijken of het ook werkt
						_getch();
					}
					break;
				default:
					break;
				}

				printf("\n");

				if(quit)
				{
					LinkedListDestruct(&list);
					break;
				}
			}
		}
		if(chc == '2')
		{
			QueueHeader header = {0};

			QueueInit(&header);

			bool quit = false;
			char keuze;

			while(1)
			{
				fflush(stdin);

				printf("1=enqueue, 2=dequeue, 3=peek, 4=isempty, 5=count,6=quit: ");
				scanf("%c", &keuze);

				switch(keuze)
				{
				case '1':
					{
						QueueNode *node = (QueueNode*)malloc(sizeof(QueueNode));
						int num = 0;
						printf("Getal om te queuen: ");
						scanf("%d", &num);
						node->number = num;
						QueueEnqueue(&header, node);
					}
					break;
				case '2':
					{
						QueueNode node = QueueDequeue(&header);
						if(!node.isEmpty)
							printf("Het volgende deel van de queue is %d" , node.number);
						else
							printf("De queue is leeg!");
					}
					break;
				case '3':
					{
						QueueNode node = QueuePeek(&header);
						if(!node.isEmpty)
							printf("Na het spieken blijkt dat het volgend nummer %d is" , node.number);
						else
							printf("de queue is leeg!");
					}
					break;
				case '4':
					if(QueueIsEmpty(&header))
						printf("ja");
					else
						printf("nee");
					break;
				case '5':
					{
						int num = 0;
						if(QueueCount(&header, &num))
							printf("Er staan %d nummers in de rij", num);
						else
							printf("Er staan geen nummers meer in de rij");
					}
					break;
				case '6':
					quit = true;
					break;
				default:
					break;
				}

				printf("\n");

				if(quit)
				{
					QueueDestruct(&header);
					break;
				}
			}
		}
	}
}
示例#16
0
int lock_controller_tick(int state){
    switch(state){ // lock transitions
        case st_lock_start:
            state = st_lock_init;
            break;
        case st_lock_init:
            state = st_lock_idle;
            break;
        case st_lock_idle:
            if(!QueueIsEmpty(lock_command_queue)){
                state = st_lock_try1;
            } else {
                state = st_lock_idle;
            }
            break;
        case st_lock_try1:
            state = st_lock_verify1;
            break;
        case st_lock_verify1:
            if( (lock_command_queue->buffer[lock_command_queue->front] == lc_lock) && (current_lock_position == locked) ){
                state = st_lock_idle;
                QueueDequeue(lock_command_queue);
                QueueEnqueue(sound_command_queue, snd_locked);
                QueueEnqueue(lcd_command_queue, lcd_write_locked);
            } else if( (lock_command_queue->buffer[lock_command_queue->front] == lc_unlock) && (current_lock_position == unlocked) ){
                state = st_lock_idle;
                QueueDequeue(lock_command_queue);
                QueueEnqueue(sound_command_queue, snd_unlocked);
                QueueEnqueue(lcd_command_queue, lcd_write_unlocked);
            } else {
                state = st_lock_try2;
            }
            break;
        case st_lock_try2:
            state = st_lock_verify2;
            break;
        case st_lock_verify2:
            if( (lock_command_queue->buffer[lock_command_queue->front] == lc_lock) && (current_lock_position == locked) ){
                state = st_lock_idle;
                QueueDequeue(lock_command_queue);
                QueueEnqueue(sound_command_queue, snd_locked);
                QueueEnqueue(lcd_command_queue, lcd_write_locked);
            } else if( (lock_command_queue->buffer[lock_command_queue->front] == lc_unlock) && (current_lock_position == unlocked) ){
                state = st_lock_idle;
                QueueDequeue(lock_command_queue);
                QueueEnqueue(sound_command_queue, snd_unlocked);
                QueueEnqueue(lcd_command_queue, lcd_write_unlocked);
            } else {
                state = st_lock_idle;
                QueueDequeue(lock_command_queue);
                QueueEnqueue(sound_command_queue, snd_malfunction);
                QueueEnqueue(lcd_command_queue, lcd_write_malfunction);
            }
            break;
        default:
            state = st_lock_start;
            break;
    }// end lock transitions
    
    switch(state){ // lock actions
        case st_lock_try1:
            if(lock_command_queue->buffer[lock_command_queue->front] == lc_lock){
                PORTA |= 0x08;
            } else if(lock_command_queue->buffer[lock_command_queue->front] == lc_unlock){
                PORTA |= 0x02;
            }                
            break;
        case st_lock_verify1:
            if(lock_command_queue->buffer[lock_command_queue->front] == lc_lock){
                PORTA &= ~(0x08);
            } else if(lock_command_queue->buffer[lock_command_queue->front] == lc_unlock){
                PORTA &= ~(0x02);
            }            
            break;
        case st_lock_try2:
            if(lock_command_queue->buffer[lock_command_queue->front] == lc_lock){
                PORTA |= 0x08;
            } else if(lock_command_queue->buffer[lock_command_queue->front] == lc_unlock){
                PORTA |= 0x02;
            }
            break;
        case st_lock_verify2:
            if(lock_command_queue->buffer[lock_command_queue->front] == lc_lock){
                PORTA &= ~(0x08);
            } else if(lock_command_queue->buffer[lock_command_queue->front] == lc_unlock){
                PORTA &= ~(0x02);
            }
            break;
        default:
            break;
    }// end lock actions
    return state;
}
示例#17
0
int main_controller_tick(int state){
    static unsigned short main_hold_time = 0;
    switch(state){//main_task transitions/actions
        case st_main_start:
            state = st_main_init;
            break;
        case st_main_init:
            SPI_Master_Init();
            PCD_Init();
            state = st_main_wait_new;
            QueueEnqueue(lcd_command_queue, lcd_write_ready);
            break;
        case st_main_wait_new:
            if(PICC_IsNewCardPresent()){
                storeTagID();
                PICC_HaltA();
                state = st_main_checkID;
            } else {
                state = st_main_wait_new;
            }
            break;
        case st_main_checkID:
            if(isMaster(tag_id)){
                state = st_main_master;
                QueueEnqueue(lcd_command_queue, lcd_write_master);
            } else if(search_valid_tag(tag_id) != -1){
                state = st_main_hold;
                main_hold_time = 0;
                if(current_lock_position == locked || current_lock_position == malfunction){
                    QueueEnqueue(lock_command_queue, lc_unlock);
                } else if(current_lock_position == unlocked){
                    QueueEnqueue(lock_command_queue, lc_lock);
                }
            } else {
                state = st_main_hold;
                main_hold_time = 0;
                QueueEnqueue(lcd_command_queue, lcd_write_invalid);
            }
            break;
        case st_main_master:
            if(!(PIND & 0x10)){
                if(isTagDBFull()){
                    state = st_main_hold;
                    main_hold_time = 0;
                    QueueEnqueue(lcd_command_queue, lcd_write_add_full);
                } else {
                    state = st_main_add_pressed;
                    QueueEnqueue(lcd_command_queue, lcd_write_add);
                }                    
            } else if(!(PIND & 0x40)){
                if(isTagDBEmpty()){
                    state = st_main_hold;
                    main_hold_time = 0;
                    QueueEnqueue(lcd_command_queue, lcd_write_remove_empty);
                } else {
                    state = st_main_rm_pressed;
                    current_remove_option = 0;
                    QueueEnqueue(lcd_command_queue, lcd_write_remove);
                }                    
            } else {
                state = st_main_master;
            }
            break;
        case st_main_add_pressed:
            if(PIND & 0x10){
                state = st_main_add_tag;
            } else {
                state = st_main_add_pressed;
            }
            break;
        case st_main_add_tag:
            if(PICC_IsNewCardPresent()){
                storeTagID();
                PICC_HaltA();
                if(isMaster(tag_id)){
                    state = st_main_add_tag;
                } else if(search_valid_tag(tag_id) == -1){
                    state = st_main_hold;
                    main_hold_time = 0;
                    add_valid_tag(tag_id);
                    QueueEnqueue(lcd_command_queue, lcd_write_added);
                } else {
                    state = st_main_hold;
                    main_hold_time = 0;
                    QueueEnqueue(lcd_command_queue, lcd_write_add_exist);
                }
            } else {
                state = st_main_add_tag;
            }
            break;
        case st_main_rm_pressed:
            if(PIND & 0x40){
                state = st_main_rm_tag;
            } else {
                state = st_main_rm_pressed;
            }
            break;
        case st_main_rm_tag:
            if(!(PIND & 0x10)){
                current_remove_option = (current_remove_option + (numValidKeys - 1)) % numValidKeys;
                QueueEnqueue(lcd_command_queue, lcd_write_remove);
                state = st_main_lr_pressed;
            } else if(!(PIND & 0x40)){
                current_remove_option = (current_remove_option + 1) % numValidKeys;
                QueueEnqueue(lcd_command_queue, lcd_write_remove);
                state = st_main_lr_pressed;
            } else if(!(PIND & 0x20)){
                remove_valid_tag(current_remove_option);
                QueueEnqueue(lcd_command_queue, lcd_write_removed);
                state = st_main_hold;
                main_hold_time = 0;
            } else {
                state = st_main_rm_tag;
            }
            break;
        case st_main_lr_pressed:
            if( (PIND & 0x10) && (PIND & 0x40) ){
                state = st_main_rm_tag;
            } else {
                state = st_main_lr_pressed;
            }
            break;
        case st_main_hold:
            if(main_hold_time < 20){
                main_hold_time++;
                state = st_main_hold;
            } else {
                state = st_main_wait_new;
            }
            break;
        default:
            state = st_main_start;
            break;
    }//end main_task transitions/actions
    return state;
};
示例#18
0
int BFS(Graph *graph, BFSVertex *start, List *hops)
{
	Queue queue;
	AdjList *adjlist = NULL;
	AdjList *adjlist_Clear = NULL;
	BFSVertex *vertex_Clear = NULL;
	BFSVertex *vertex_Adj = NULL;
	ListElmt *element = NULL;
	ListElmt *member = NULL;

	for (element = ListHead(&GraphAdjLists(graph)); element != NULL; element = ListNext(element))
	{
		vertex_Clear = ((AdjList*)ListData(element))->vertex;
		if (graph->match(vertex_Clear, start))
		{
			vertex_Clear->color = gray;
			vertex_Clear->nHops = 0;
		}
		else
		{
			vertex_Clear->color = white;
			vertex_Clear->nHops = -1;
		}
	}

	QueueInit(&queue, NULL);
	if (GraphAdjList(graph, start, &adjlist_Clear) != 0)
	{
		QueueDestroy(&queue);
		return -1;
	}
	if (QueueEnqueue(&queue, adjlist_Clear) != 0)
	{
		QueueDestroy(&queue);
		return -1;
	}

	while (QueueSize(&queue) > 0)
	{
		adjlist = QueuePeek(&queue);
		for (member = ListHead(&adjlist->Adjacent); member != NULL; member = ListNext(member))
		{
			vertex_Adj = ListData(member);

			if (GraphAdjList(graph, vertex_Adj, &adjlist_Clear))
			{
				QueueDestroy(&queue);
				return -1;
			}
			vertex_Clear = adjlist_Clear->vertex;

			if (vertex_Clear->color == white)
			{
				vertex_Clear->color = gray;
				vertex_Clear->nHops = ((BFSVertex*)adjlist->vertex)->nHops + 1;

				if (QueueEnqueue(&queue, adjlist_Clear) != 0)
				{
					QueueDestroy(&queue);
					return -1;
				}
			}
		}
		if (QueueDequeue(&queue, (void**)&adjlist) == 0)
		{
			((BFSVertex*)adjlist->vertex)->color = black;
		}
		else
		{
			QueueDestroy(&queue);
			return -1;
		}
	}
	QueueDestroy(&queue);

	ListInit(hops, NULL);
	for (element = ListHead(&GraphAdjLists(graph)); element != NULL; element = ListNext(element))
	{
		vertex_Clear = ((AdjList*)ListData(element))->vertex;
		if (vertex_Clear->nHops != -1)
		{
			if (ListInsert_Next(hops, ListTail(hops), vertex_Clear) != 0)
			{
				ListDestory(hops);
				return -1;
			}
		}
	}

	return 0;
}