示例#1
0
txn_entry_t * remove_transaction_log_entry(account_entry_t * ae, txn_entry_t * ti){
	// this is for refund

	alloc_node_t * an = get_head(ae->txn_log);
	while(an != NULL){
		txn_entry_t *te = (txn_entry_t *) an->contents;

		if(te->transaction_id == ti->transaction_id){
			// begin removal
			if(te->p != NULL)
				free(te->p);
			if(te->data_sz != 0)
				free(te->data);

			free(te);
			remove_node(ae->txn_log, an);

			return te;
		}
		an = an->next;
	}
	ERRNO = ERRNO_MP_NOT_FOUND;
	return NULL;
}
示例#2
0
uint32_t buffer_write(char* buffer, const unsigned char* buf, uint32_t len,
                      int on_full) {
  uint32_t free;
  uint32_t bytes;
  uint32_t head;
  uint32_t size;
  uint32_t written;

  if (is_full(buffer)) return on_full;
  free = get_free_space(buffer);
  bytes = free > len ? len : free;
  head = get_head(buffer);
  size = get_size(buffer);
  written = 0;
  while (written < bytes) {
    // TODO(ricow): consider using memmove here instead;
    char* value_pointer = buffer + kDataIndex + head;
    *value_pointer = buf[written];
    head = (head + 1) % size;
    written++;
  }
  set_head(buffer, head);
  return written;
}
示例#3
0
void test_add
    (
    void
    )
{
uint32_t arr[] = {0, 10, 20, 30, 40, 50, 60, 70, 80, 90};
uint32_t i;
list * new_list = make_new_list();
node * cur = NULL;
CU_ASSERT_PTR_NOT_NULL(new_list);
for(i = 0; i < 10; i++)
    {
    add(new_list, &(arr[i]));
    }
cur = get_head(new_list);
CU_ASSERT_PTR_NOT_NULL(cur);
i = 0;

while(cur != NULL)
    {
    CU_ASSERT_EQUAL(*(uint32_t *)cur->data, arr[i]);
    cur = cur->next;
    i++;
    }
cur = NULL;
cur = get_tail(new_list);
CU_ASSERT_PTR_NOT_NULL(cur);
i = 9;
while(cur != NULL)
    {
    CU_ASSERT_EQUAL(*(uint32_t *)cur->data, arr[i]);
    cur = cur->prev;
    i--;
    }
CU_ASSERT_EQUAL(new_list->size, 10);
}
示例#4
0
bool is_full(char* buffer) {
  return ((get_head(buffer) + 1) % get_size(buffer)) == get_tail(buffer);
}
示例#5
0
long long ut_get_group(struct upTree* ut, long long g1) {
    struct _upnode* n = get_head(ut, g1);
    return n->i;
}
示例#6
0
 const Iterator
 begin()
 {
     return Iterator(get_head());
 }
示例#7
0
文件: directory.cpp 项目: asir6/Colt
WT_Result WT_Directory::serialize(WT_File & file) const
{
    if (file.heuristics().target_version() >= REVISION_WHEN_PACKAGE_FORMAT_BEGINS)
        return WT_Result::Toolkit_Usage_Error;

    WT_BlockRef *   current     = (WT_BlockRef *) get_head();
    WT_Integer32    item_count  = count();

    WD_CHECK (file.dump_delayed_drawable());

    WT_Boolean compressor_stop_flag = WD_False;

    //by turning on the file heuristics to not allow compression
    //we will be writing this opcode in uncompressed form always

    compressor_stop_flag = file.heuristics().allow_data_compression();
    file.heuristics().set_allow_data_compression(WD_False);

    if (file.heuristics().allow_binary_data())
    {
        WT_Integer32 directory_opcode_size = 0;

        WT_BlockRef *   currentitem     = (WT_BlockRef *) get_head();
        while (currentitem)
        {
            directory_opcode_size +=
                currentitem->get_total_binary_opcode_size();
            currentitem = (WT_BlockRef *) currentitem->next();
        }

        directory_opcode_size += sizeof(WT_Unsigned_Integer16); //for opcode
        directory_opcode_size += sizeof(WT_Integer32);          //for blockref count
        directory_opcode_size += sizeof(WT_Unsigned_Integer32); //for blockref list file offset
        directory_opcode_size += sizeof(WT_Byte); //for '}'
        WD_CHECK (file.write((WT_Byte) '{'));
        WD_CHECK((file.stream_tell_action())(file,
            (unsigned long *)&m_file_offset));

        ((WT_Directory *) this)->m_file_offset -= sizeof(WT_Byte); //we omit '}'

        WD_CHECK (file.write((WT_Integer32) directory_opcode_size));
        WD_CHECK (file.write((WT_Unsigned_Integer16) WD_EXBO_DIRECTORY));
        WD_CHECK (file.write((WT_Integer32) item_count));

        if(item_count > 0) {
            WD_CHECK(file.set_block_size_for_tail_blockref(
                ((WT_Directory *) this)->get_file_offset()));
        }

        while (current != WD_Null)
        {
            WD_CHECK(current->serialize(file, WD_True, WD_False));
            current = (WT_BlockRef *) current->next();
        }
        WD_CHECK (file.write((WT_Unsigned_Integer32)
            (((WT_Directory *) this)->get_file_offset())));
        WD_CHECK (file.write("}"));
    }
    else { //ASCII

        // New way
        WD_CHECK (file.dump_delayed_drawable());
        WD_CHECK (file.write_tab_level());
        WD_CHECK((file.stream_tell_action())(file,
            (unsigned long *)&m_file_offset));

        //reduce the file offset by the size of characters that would
        //have been possibly written by the call to write_tab_level fn.
        ((WT_Directory *) this)->m_file_offset -=
            ((file.tab_level() + (int)strlen(WD_NEWLINE) ) * sizeof(WT_Byte));

        WD_CHECK (file.write("(Directory "));
        WD_CHECK (file.write_padded_ascii(item_count));
        WD_CHECK (file.write((WT_Byte) ' '));
        if(item_count > 0) {
            WD_CHECK( file.set_block_size_for_tail_blockref(
                ((WT_Directory *) this)->get_file_offset()) );
        }

        while (current != WD_Null)
        {
            {
                WD_CHECK( current->serialize(file, WD_True, WD_False) );
            }

            current = (WT_BlockRef *) current->next();

            if (current)
                WD_CHECK (file.write((WT_Byte) ' '));
        }
        WD_CHECK (file.write((WT_Byte) ' '));
        WD_CHECK (file.write_padded_ascii((WT_Unsigned_Integer32)
            ((WT_Directory *) this)->get_file_offset()));
        WD_CHECK (file.write(")"));
    }

    file.heuristics().set_allow_data_compression(compressor_stop_flag);
    return WT_Result::Success;
}
示例#8
0
ParseExp::Result 
ParseExp::ParseExpImpl(POETCode* input, POETCode* bop, POETCode* inherit, int *p_lineno)
{
  if (inherit == 0) {
    POETCode* p_uop = exp_uop->get_entry().get_code();
    for (POETCode* cur = 0; ((cur=get_head(p_uop))!=0); p_uop = get_tail(p_uop)) 
    {
       POETCode* p_input = MatchOp(cur, input);
       if (p_input != 0) {
          Result resOfRest = ParseItemType(p_input, p_lineno);
          if (resOfRest.first != 0) {
             if (buildUop->get_entry().get_code()!=0) {
                XformVar* xvar = dynamic_cast<XformVar*>(buildUop->get_entry().get_code());
                if (xvar == 0) INCORRECT_XVAR(buildUop);
                inherit = xvar->eval(PAIR(cur,resOfRest.first),false);
             }
             else {
                CodeVar* cvar = dynamic_cast<CodeVar*>(parseUop->get_entry().get_code());
                if (cvar == 0) INCORRECT_CVAR(parseUop);
                inherit = CODE_REF(cvar, PAIR(cur,resOfRest.first));
             }
             input = resOfRest.second;
          }
          break;
       }
    }
  }
  if (inherit == 0)  {
     Result res = ParseItemType(input, p_lineno);
     inherit = res.first; input = res.second;
  }
  if (inherit == 0) { return Result(0,input); }
  if (get_tail(input) != 0) {
     POETCode* p_bop = bop;
     for (POETCode* cur_bop=0; (cur_bop = get_head(p_bop)) != 0; p_bop = get_tail(p_bop) )
     {
        for (POETCode* cur = 0; (cur = get_head(cur_bop)) != 0; cur_bop = get_tail(cur_bop)) 
        {
           POETCode* p_input = MatchOp(cur, input);
           if (p_input != 0) { 
              Result resOfTail = ParseExpImpl(p_input,get_tail(p_bop),0, p_lineno);
              if (resOfTail.first != 0) {
                 POETCode* first1 = 0;
                 if (buildBop->get_entry().get_code()!=0) {
                    XformVar* xvar = dynamic_cast<XformVar*>(buildBop->get_entry().get_code());
                    if (xvar == 0) INCORRECT_XVAR(buildBop);
                    first1 = xvar->eval(TUPLE3(cur,inherit,resOfTail.first),false);
                 } 
                 else {
                    CodeVar* cvar = dynamic_cast<CodeVar*>(parseBop->get_entry().get_code());
                    if (cvar == 0) INCORRECT_XVAR(parseBop);
                    first1=CODE_REF(cvar,TUPLE3(cur,inherit,resOfTail.first));
                 }
                 return ParseExpImpl(resOfTail.second,bop,first1, p_lineno);
              }
              return Result(inherit,input);
           }
        }
     }
   }
   return Result(inherit, input) ;
}
示例#9
0
文件: 01list.c 项目: Rovi/TarenaCode
int main()
{
    //创建单链表, 并且初始化
    List list;
    list.head = NULL;
    list.tail = NULL;
    list.cnt = 0;


    printf("%s\n", empty(&list) ? "空" : "没空");
    printf("%s\n", full(&list) ? "满" : "没满");
    printf("链表中有%d个元素\n", size(&list));
    printf("----------------\n");
    push_head(&list, 11);
    travel(&list);
    push_head(&list, 22);
    travel(&list);
    push_head(&list, 33);
    travel(&list);
    printf("链表中有%d个元素\n", size(&list));
    printf("----------------\n");

    push_tail(&list, 44);
    travel(&list);
    push_tail(&list, 55);
    travel(&list);
    push_tail(&list, 66);
    travel(&list);

    printf("链表中有%d个元素\n", size(&list));
    printf("----------------\n");
    insert(&list, 77, -2);
    printf("链表中有%d个元素\n", size(&list));
    travel(&list);
    insert(&list, 88, 0);
    printf("链表中有%d个元素\n", size(&list));
    travel(&list);
    insert(&list, 99, 5);
    printf("链表中有%d个元素\n", size(&list));
    travel(&list);
    insert(&list, 100, 2);
    printf("链表中有%d个元素\n", size(&list));
    travel(&list);

    printf("--------------------\n");
    printf("头节点元素值: %d\n", get_head(&list));
    printf("尾节点元素值: %d\n", get_tail(&list));

    printf("--------------------\n");
    pop_head(&list);
    printf("链表中有%d个元素\n", size(&list));
    printf("头节点元素值: %d\n", get_head(&list));
    printf("尾节点元素值: %d\n", get_tail(&list));
    printf("--------------------\n");
    pop_tail(&list);
    printf("链表中有%d个元素\n", size(&list));
    printf("头节点元素值: %d\n", get_head(&list));
    printf("尾节点元素值: %d\n", get_tail(&list));

    printf("--------------------\n");
    del(&list, -2);
    travel(&list);

    del(&list, 0);
    travel(&list);

    del(&list, 4);
    travel(&list);

    del(&list, 1);
    travel(&list);

    del(&list, 2);
    travel(&list);

    del(&list, 7);
    travel(&list);
    printf("--------------------\n");
    reverse_list(&list);
    printf("链表中有%d个元素\n", size(&list));
    printf("头节点元素值: %d\n", get_head(&list));
    printf("尾节点元素值: %d\n", get_tail(&list));
    travel(&list);
    printf("--------------------\n");
    reverse_travel_list(&list);
    printf("=====清空========\n");
    clear(&list);
    return 0;
}
示例#10
0
bool is_first(linkedlist_t* list, node* n)
{
    if(n == get_head(list))
        return TRUE;
    return FALSE;
}
示例#11
0
int request_cs(const void * self) {
	if (done_count == 0) {
		inc_lamport_time();
		return 0;
	}
	Message * msg = (Message *) calloc(1, sizeof(Message));
	memset(msg, 0, sizeof(Message));
	inc_lamport_time();
	init_message(msg, NULL, CS_REQUEST);
	queue_push(my_local_id, get_lamport_time());
	for (local_id id_from = 1; id_from <= num_proc; id_from++) {
		if (id_from != my_local_id) {
			send(NULL, id_from, msg);
		}
	}

	local_id from;

	int count_reply = num_proc - 2;

	while (1) {
		memset(msg, 0, sizeof(Message));
		receive_any(&from, msg);
//		printf("%d: type message %d\n", my_local_id, msg->s_header.s_type);
		switch (msg->s_header.s_type) {
		case CS_REPLY: {
			count_reply--;
//			printf("%d: reply head - %d\n", my_local_id, get_head());
			if (count_reply <= 0 && get_head() == my_local_id) {
				return 0;
			}
			break;
		}
		case CS_REQUEST: {
//			printf("%d: request\n", my_local_id);
			queue_push(from, msg->s_header.s_local_time);
			memset(msg, 0, sizeof(Message));
			inc_lamport_time();
			init_message(msg, NULL, CS_REPLY);
			send(NULL, from, msg);
			break;
		}
		case CS_RELEASE: {
//			printf("%d: release\n", my_local_id);
			next_proc();
			if (get_head() == my_local_id) {
				return 0;
			}
			break;
		}
		case DONE: {
			done_count--;
			if (done_count <= 0) {
				return 0;
			}
			break;
		}
		default:
			fprintf(stderr, "unknown type message: %d\n", msg->s_header.s_type);
		}
	}

	free(msg);
	return 0;
}
示例#12
0
文件: write_emu.c 项目: dgesswein/mfm
int get_lba(DRIVE_PARAMS *drive_params) {
   return (get_cyl() * drive_params->num_head + get_head()) *
       drive_params->num_sectors + sector;
}
示例#13
0
文件: write_emu.c 项目: dgesswein/mfm
void process_field(DRIVE_PARAMS *drive_params, 
   uint8_t track[], int trk_offset, int length, 
   FIELD_L field_def[], int a1_list[], int *a1_list_ndx, int a1_list_len)
{
   int ndx = 0;
   uint64_t value;
   int i;
   int data_set;
   int crc_start = 0;
   int crc_end = -1;
   int field_filled = 0;

//printf("Process field called start %d\n",trk_offset);

   while (field_def[ndx].len_bytes != -1) {
      data_set = 0;
      switch (field_def[ndx].type) {
         case FIELD_FILL:
            if (field_def[ndx].byte_offset_bit_len +
                field_def[ndx].len_bytes > length) {
               msg(MSG_FATAL, "Track overflow field fill %d, %d, %d\n",
                 field_def[ndx].byte_offset_bit_len, field_def[ndx].len_bytes,
                 length);
               exit(1);
            }
            memset(&track[field_def[ndx].byte_offset_bit_len], 
               field_def[ndx].value, field_def[ndx].len_bytes);
            data_set = 1;
            if (field_def[ndx].op != OP_SET) {
               msg(MSG_FATAL, "Only OP_SET currently supported for FIELD_FILL\n");
               exit(1);
            }
         break;
         case FIELD_CYL:
            value = get_cyl();
         break;
         case FIELD_HEAD:
            value = get_head();
         break;
         case FIELD_SECTOR:
            value = get_sector();
         break;
         case FIELD_LBA:
            value = get_lba(drive_params);
         break;
         case FIELD_HDR_CRC:
            if (crc_end == -1) {
               crc_end = field_def[ndx].byte_offset_bit_len - 1;
            }
            value = get_check_value(&track[crc_start], crc_end - crc_start + 1,
               &drive_params->header_crc,
               mfm_controller_info[drive_params->controller].header_check);
         break;
         case FIELD_DATA_CRC:
            if (crc_end == -1) {
               crc_end = field_def[ndx].byte_offset_bit_len - 1;
            }
            value = get_check_value(&track[crc_start], crc_end - crc_start + 1,
               &drive_params->data_crc,
               mfm_controller_info[drive_params->controller].data_check);
         break;
         case FIELD_MARK_CRC_START:
            crc_start = field_def[ndx].byte_offset_bit_len;
            data_set = 1;
         break;
         case FIELD_MARK_CRC_END:
            crc_end = field_def[ndx].byte_offset_bit_len;
            data_set = 1;
         break;
         case FIELD_TRK_DATA:
            get_data(drive_params, &track[field_def[ndx].byte_offset_bit_len]);
            data_set = 1;
            inc_sector(drive_params);
         break;
         case FIELD_BAD_BLOCK:
            value = 0;
         break;
         case FIELD_A1:
            if (*a1_list_ndx >= a1_list_len) {
               msg(MSG_FATAL, "A1 list overflow\n");
               exit(1);
            }      
            a1_list[(*a1_list_ndx)++] = trk_offset + 
                field_def[ndx].byte_offset_bit_len;
            value = 0xa1;
         break;
         default:
            msg(MSG_FATAL, "Unknown field_def type %d\n",field_def[ndx].type);
            exit(1);
      }
      if (data_set) {
         field_filled = MAX(field_filled, field_def[ndx].byte_offset_bit_len + field_def[ndx].len_bytes - 1);
      } else if (!data_set && field_def[ndx].bit_list == NULL) {
         field_filled = MAX(field_filled, field_def[ndx].byte_offset_bit_len + field_def[ndx].len_bytes - 1);
//printf("value %lld len %d %d %d\n",value, field_def[ndx].byte_offset_bit_len , field_def[ndx].len_bytes, length);
         if (field_def[ndx].byte_offset_bit_len + field_def[ndx].len_bytes 
              > length) {
            msg(MSG_FATAL, "Track overflow field update %d %d %d\n", 
               field_def[ndx].byte_offset_bit_len, field_def[ndx].len_bytes, length);
            exit(1);
         }
         value <<= (sizeof(value) - field_def[ndx].len_bytes) * 8;
         for (i = 0; i < field_def[ndx].len_bytes; i++) {
            int wbyte = (value >> (sizeof(value)*8 - 8));
            if (field_def[ndx].op == OP_XOR) {
               track[field_def[ndx].byte_offset_bit_len + i] ^= wbyte;
            } else {
               track[field_def[ndx].byte_offset_bit_len + i] = wbyte;
            }
            value <<= 8;
         }
      } else {
示例#14
0
文件: solver.c 项目: badosu/rubik-2d
void frontier_pop() {
  get_head();
  frontier->prev = NULL;
  frontier = frontier->next;
}
示例#15
0
文件: job.c 项目: cheetah0216/logdb
static int handle_udp(struct sockaddr_in *client_addr, char *pkg, int len)
{
    ++recv_pkg_count;

    log_debug("recv pkg from %s, len: %d\n%s", addrtostr(client_addr), len, \
            hex_dump_str(pkg, len));

    int ret;

    char *p = pkg;
    int left = len;

    struct protocol_head head;
    ret = get_head(&head, (void **)&p, &left);
    if (ret < 0)
        return -__LINE__;

    if (head.command == COMMAND_SQL)
    {
        ret = push_sql(p, left);
        if (ret < 0)
        {
            log_error("push to queue fail: %d", ret);
            NEG_RET(reply(&head, client_addr, RESULT_INTERNAL_ERROR));

            return -__LINE__;
        }
    }
    else
    {
        struct sockaddr_in real_client_addr;
        if (head.echo_len == sizeof(struct inner_addr))
        {
            struct inner_addr *addr = (struct inner_addr *)head.echo;
            bzero(&real_client_addr, sizeof(real_client_addr));
            real_client_addr.sin_addr.s_addr = addr->ip;
            real_client_addr.sin_port        = addr->port;
        }

        global_sequence_has_generated = 0;

        uint64_t hash_key = 0;
        char *s = pkgtostr(&real_client_addr, p, left, &hash_key);
        if (s == NULL)
        {
            if (global_sequence_has_generated)
            {
                sequence_dec();
            }

            NEG_RET(reply(&head, client_addr, RESULT_PKG_FMT_ERROR));

            return -__LINE__;
        }

        ret = process_one_record(s, hash_key);
        if (ret < 0)
        {
            log_error("process one record fail: %d", ret);
            NEG_RET(reply(&head, client_addr, RESULT_INTERNAL_ERROR));

            return -__LINE__;
        }
    }

    NEG_RET(reply(&head, client_addr, RESULT_OK));

    return 0;
}
示例#16
0
bool is_empty(char* buffer) {
  return get_head(buffer) == get_tail(buffer);
}
/**
 * Counts number of SNR values in a GSV sentence above certain limits.
 * Takes the first sentence of a GSV, counts the number of other sentences 
 * reads next sentences directly from file and tokenises them.
 * iterates through the 1-3 sentences in the list, counting SNR values.
 * @param in_sentence pointer to first tokenised sentence
 * @param pointer to the stream that generated the sentence
 * @return an integer representing the fix quality
 */
int make_gsv(list_ptr in_sentence, stream_ptr stream) {

  //Get the number of GSV lines from second token in the sentence
  int num_lines = atoi(get_head(&in_sentence)->next->node_data);
  int good_snr_count = 0;
  int min_snr_count = 0;

  //Make a list to hold GSVs, up to 3
  list_ptr gsv_lines;
  init_list(&gsv_lines);

  //passed in sentence tokens added to GSV list
  node_ptr original_line;
  init_node(&original_line, in_sentence);
  add_to_list(&original_line, &gsv_lines);

  //Add the other gsv lines to the list
  int i;
  for (i = 1; i < num_lines; i++) {
    node_ptr gsv_line;
    init_node(&gsv_line, parseSentence(read_sentence(stream)));
    add_to_list(&gsv_line, &gsv_lines);

  }


  //Iterator for the GSV lines
  node_ptr gsv_iterator = get_head(&gsv_lines);

  //Iterator for sentence tokens in the GSV lines
  node_ptr sentence_token;
  while (gsv_iterator != NULL) {

    int tokencount = 0; //track number of tokens encountered
    int snr_value_token = 7; // first SNR in a line is 7th token

    //get first token in sentence
    sentence_token = get_head((list_ptr *) & gsv_iterator->node_data);


    //go through each sentence and count values for good/min fix
    while (sentence_token != NULL) {

      if (tokencount == snr_value_token) {

        if (!(strcmp(sentence_token->node_data, "") == 0)) {
          int snr = atoi(sentence_token->node_data);

          if (snr >= 35) {
            good_snr_count++;
          }
          if ((snr >= 30) && (snr < 35)) {
            min_snr_count++;
          }

        }

        snr_value_token += 4; //next SNR in line : every 4 tokens
      }


      sentence_token = sentence_token->next;
      tokencount++;
    }
    gsv_iterator = gsv_iterator -> next;
  }


  if (good_snr_count >= 3) {
    return 2;
  } else if ((good_snr_count + min_snr_count) >= 3) {
    return 1;
  } else {
    return 0;
  }

}
示例#18
0
/*
*Purpose: Moves the 2 snakes according to the user input
* Inputs: s1,s2: Pointers to the queue containing the snake coordinates
*         snake1, snake2: Coordinates of heads of the snakes
*         snake1dir, snake2dir: Initial direction of movement
*         r: Coordinates of reward
*         p: Current points of the players
* Outputs: 1: if user quits game
		   0: otherwise	
*/
int play(Queue *s1, Queue *s2, coord* snake1, coord *snake2, char *snake1dir, char *snake2dir, reward *r,Points* p )
{
		int ch;
		int set_dir1=0;
		int set_dir2=0;
		int iter;
	for (iter=0; iter<2; iter++)
	{
		ch=getch();						
		
		//Get the new head of the snake:
		switch (ch)
		{
				case (int)'q': return 1;
				
				case (int)'w': if (((*snake1dir=='r')||(*snake1dir=='l'))&&(set_dir1==0))
							{
								if (snake1->y==0)
									snake1->y = HEIGHT;
								else
									snake1->y--;
								*snake1dir = 'u';
								set_dir1=1;
							}
							break;
				
				case (int)'s':  if (((*snake1dir=='r')||(*snake1dir=='l'))&&(set_dir1==0))
							{
								if (snake1->y==HEIGHT)
									snake1->y = 0;
								else
									snake1->y++;
								set_dir1=1;
								*snake1dir = 'd';
							}
							break;
								
				case (int)'a': if (((*snake1dir=='u')||(*snake1dir=='d'))&&(set_dir1==0))
							{
								if (snake1->x==0)
									snake1->x = WIDTH;
								else
									snake1->x--;
								set_dir1=1;
								*snake1dir = 'l';
							}
							break;
				
				case (int)'d': if (((*snake1dir=='u')||(*snake1dir=='d'))&&(set_dir1==0))
							{
								if (snake1->x==WIDTH)
									snake1->x = 0;
								else
									snake1->x++;
								set_dir1=1;
								*snake1dir = 'r';
							}
							break;
				case 259: if (((*snake2dir=='r')||(*snake2dir=='l'))&&(set_dir2==0))
							{
								if (snake2->y==0)
									snake2->y = HEIGHT;
								else
									snake2->y--;
								*snake2dir = 'u';
								set_dir2=1;
							}
							break;
				case 258 : if (((*snake2dir=='r')||(*snake2dir=='l'))&&(set_dir2==0))
							{
								if (snake2->y==HEIGHT)
									snake2->y = 0;
								else
									snake2->y++;
								set_dir2=1;
								*snake2dir = 'd';
							}
							break;
				case 260 : if (((*snake2dir=='u')||(*snake2dir=='d'))&&(set_dir2==0))
							{
								if (snake2->x==0)
									snake2->x = WIDTH;
								else
									snake2->x--;
								set_dir2=1;
								*snake2dir = 'l';
							}
							break;		
							
				case 261: if (((*snake2dir=='u')||(*snake2dir=='d'))&&(set_dir2==0))
							{
								if (snake2->x==WIDTH)
									snake2->x = 0;
								else
									snake2->x++;
								set_dir2=1;
								*snake2dir = 'r';
							}
							break;
			}
		}
		if (set_dir1==0)
		{
			switch(*snake1dir)
			{
				case 'l': if (snake1->x==0)
							snake1->x = WIDTH;
						else
							snake1->x--;
						break;
				case 'r': if (snake1->x==WIDTH)
							snake1->x = 0;
						else
							snake1->x++;
						break;
				case 'u': if (snake1->y==0)
							snake1->y = HEIGHT;
						else
							snake1->y--;
						break;
				case 'd': if (snake1->y==HEIGHT)
							snake1->y = 0;
						else
							snake1->y++;
						break;
			}
		}
		if (set_dir2==0)
		{
			switch(*snake2dir)
			{
				case 'l': if (snake2->x==0)
							snake2->x = WIDTH;
						else
							snake2->x--;
						break;
				case 'r': if (snake2->x==WIDTH)
							snake2->x = 0;
						else
							snake2->x++;
						break;
				case 'u': if (snake2->y==0)
							snake2->y = HEIGHT;
						else
							snake2->y--;
						break;
				case 'd': if (snake2->y==HEIGHT)
							snake2->y = 0;
						else
							snake2->y++;
						break;
			}
		}
	
		//Push the new head onto the queue:
		s1 = queue_push(s1, *snake1);
		s2 = queue_push(s2, *snake2);
		int flag=0, i, check=-1;
	
		//Check if the snakes have eaten the reward:
		for (i=0; i<r->rewnum; i++)
		{
			if ((r->rewcoord[i].x==snake2->x)&&(r->rewcoord[i].y==snake2->y))
			{
				r = mk_reward(s1, s2, r, i);
				p->s2_points++;
				flag=1;
				break;
			}
		}
		//If snake2 has not eaten reward, then pop out its tail from queue:
		if (flag==0)
			s2 = queue_pop(s2);
		flag=0;
		coord s1_head = get_head(s1);
		for (i=0; i<r->rewnum; i++)
		{
			if ((r->rewcoord[i].x==snake1->x)&&(r->rewcoord[i].y==snake1->y))
			{
				r = mk_reward(s1, s2, r, i);
				p->s1_points++;
				flag=1;
				break;
			}
		}
		
		//If snake1 has not eaten reward, then pop out its tail from queue:
		if (flag==0)
			s1 = queue_pop(s1);
				
	return 0;
}
示例#19
0
  virtual void visitOperator(POETOperator *op)
  {
     switch (op->get_op()) {
     case POET_OP_TUPLE: {
       parseTuple(op->get_arg(0));
       break;
      }
     case TYPE_LIST1:
     case TYPE_LIST: {
         POETCode* arg = op->get_arg(0);
         POETCode* matchSave = fullmatch; fullmatch = EMPTY;
         std::vector<POETCode*> match_res;
         do {
            POETCode* r1_first=match_eval(arg);
            if (r1_first == 0)  { 
                fullmatch = matchSave;
                if (fullmatch != 0) {
                    res = Vector2List(match_res); 
                    if (res == EMPTY && op->get_op() == TYPE_LIST1)
                         PARSE_MISMATCH(r1,op,lineno);
                    return; 
                   }
                else PARSE_MISMATCH(r1,op,lineno);
            }
            match_res.push_back(r1_first);
         } while (r1 != 0);
         fullmatch = matchSave;
         if (match_res.size() == 0) PARSE_MISMATCH(r1,op,lineno);
         res = Vector2List(match_res);
         assert(res != EMPTY);
         return;
       }
     case TYPE_TOR: {
        POETCode* r1_first = get_head(r1);
        if (r1_first->get_enum() == SRC_CVAR &&
             static_cast<CodeVar*>(r1_first)->get_parseInfo() != EMPTY) 
            { /*QY: r1_first is already parsed and is not a token*/  
              if (!match_eval(op)) PARSE_MISMATCH(r1,op,lineno);
              return;
            }
 
         if (!backtrack) {
            POETTypeTor* tor = static_cast<POETTypeTor*>(op);
            POETCode* arg = tor->get_parseInfo(this, r1);
            apply(arg, fullmatch); 
            if (fullmatch != 0) fullmatch=EMPTY; 
            return;
         }
         else  {
            POETCode* r1save = r1;
            size_t size = op->numOfArgs();
            for (unsigned i = 0; i < size; ++i) {
               POETCode* arg = op->get_arg(i);
               POETCode* filter = 0;
               switch (arg->get_enum()) {
               case SRC_STRING: if (arg != EMPTY) filter = arg; break;
               case SRC_CVAR:
                 filter=static_cast<CodeVar*>(arg)->get_parseInfo();
                 if (filter != 0 && filter->get_enum() == SRC_LIST)
                    filter = static_cast<POETList*>(filter)->get_first();
                 else filter = 0;
                 break;
               default: ; /* no filtering */
               }
               if (filter != 0 && filter->get_enum()==SRC_STRING && filter != r1_first) {
                 continue;
               }
               try { apply(arg, EMPTY);
                    if (res != 0) return; }
               catch (ParseError err) { r1 = r1save; }
            }
         }
         PARSE_MISMATCH(r1,op,lineno);
         return;
      }
     case POET_OP_EXP: {
       ParseExp::Result exp_res = ParseExp::inst()->parse(r1, &lineno);
       res = exp_res.first;
       if (res == 0) PARSE_MISMATCH(r1,op,lineno); 
       if (fullmatch != 0) r1 = exp_res.second;
       else if (exp_res.second != 0 && exp_res.second != EMPTY) 
             { PARSE_MISMATCH_LEFT(exp_res.second,lineno); }
       else r1 = 0;
       break;
       }
     case POET_OP_LIST1:
     case POET_OP_LIST: {
       POETParseList* oplist = dynamic_cast<POETParseList*>(op);
       assert(oplist != 0);
       std::string sepString;
       POETCode* sep = op->get_arg(1);
       if (sep != 0) { 
           sep  = eval_AST(sep);  
           POETString* sep1 = AST2String(sep);
           if (sep1 == 0) INCORRECT_STRING(sep);
           sepString = sep1->get_content();
       }
       else sep = EMPTY;
       if (IS_SPACE(sepString)) sep = EMPTY;
       try { parseList(oplist, op->get_arg(0), sep); }
       catch (ParseError err) { 
           if (op->get_op() == POET_OP_LIST && backtrack && fullmatch != 0) res = EMPTY; 
           else throw err; }
       break;
     }
     default:
        defaultVisit(eval_AST(op));
     }
  }
示例#20
0
文件: Edge.cpp 项目: robert333/graph
Vertex::Index Edge::get_neighbour(Vertex::Index const node_id) const
{
	assert(node_id == get_tail() or node_id == get_head());
	return (node_id == get_tail()) ? get_head() : get_tail();
}
示例#21
0
double perform_trial(int numpoints, int dimension, position *node_location) {

  init_heap_vars(numpoints, (numpoints * (numpoints - 1)) / 2);  // initialize the heap variables
  node *heap = (node *) malloc(sizeof(node) * numpoints);  // create heap
  int location[numpoints];  // create array, indexed by name, that remembers the index of each element in the heap
  node *graph = (node *) malloc(sizeof(node) * numpoints);  // initialize graph
    
  /*
   * (i)     create struct node for each graph node
   * (ii)    intialize distance values 
   * (iii)   create V-S list
   * (iv)    initialize heap to empty
   * (v)     initialize array to hold distnace values
   */
     
  for(int i = 0; i < numpoints; i++) {   
    graph[i].name = i;  // name each node
    graph[i].dist = -1;  // here all edges are positive so we'll let -1 = infinity
    insert_list(i);  // initially every node is in V-S, list.c maintains a LL with V-S
    location[i] = -1;  // initially no node is in the heap
    heap[i].dist = 100000;  // set heap to empty
    heap[i].name = 100000;
  }  
    
  
  graph[0].dist = 0;  // set distance to first node to 0
  insert(graph[0], heap, location);  // insert first node into the heap

  while(size_heap() != 0) {
    node v = delete_min(heap, location);  // take smallest node from the heap
    // ensure heap wasn't somehow empty
    if(v.dist == -100.) {
      break;
    } 
    delete_list(v.name);  // delete the node from V-S
    list_node *ptr = get_head();  // get head node from V-S
    while(ptr != NULL) {
      int current_name = ptr->name;  // get name of current element
            
      // found a node, check for update
       double check_val = 0;
      // just generate a random edge since each edge is only examined once
      if(dimension == 1) {
        //check_val = (double)rand()/(double)RAND_MAX;
        check_val = fabs(node_location[v.name].x-node_location[current_name].x);
      } else if(dimension == 2) {
        double parameter = pow((node_location[v.name].x-node_location[current_name].x), 2.)
                           + pow((node_location[v.name].y-node_location[current_name].y), 2.);
        check_val = sqrt(parameter);
      } else if(dimension == 3) {
        double parameter = pow((node_location[v.name].x-node_location[current_name].x), 2.)
                           + pow((node_location[v.name].y-node_location[current_name].y), 2.)
                           + pow((node_location[v.name].z-node_location[current_name].z), 2.);
        check_val = sqrt(parameter);
      } else if(dimension == 4) {
        double parameter = pow((node_location[v.name].x-node_location[current_name].x), 2.)
                           + pow((node_location[v.name].y-node_location[current_name].y), 2.)
                           + pow((node_location[v.name].z-node_location[current_name].z), 2.)
                           + pow((node_location[v.name].w-node_location[current_name].w), 2.);
        check_val = sqrt(parameter);
      }
                
      // check if we need to update
      if(((graph[current_name].dist > check_val) || graph[current_name].dist == -1)) {
        // perform update
        graph[current_name].dist = check_val;
        // insert/update element in the heap
        node change_node = graph[current_name];
        change(change_node, heap, location);
      }
      ptr = ptr->next;
    }  
  }

  // sum and print the edges in the MST
  double sum = sum_MST(numpoints, graph);

  free(heap);  // free heap
  free(graph);  // free graph
  free_list();  // free list

  return sum;

}
示例#22
0
文件: Edge.cpp 项目: robert333/graph
bool Edge::is_valid() const
{
	return get_tail() != Vertex::invalid_index()
		   and get_head() != Vertex::invalid_index()
		   and get_tail() != get_head();
}
示例#23
0
文件: Edge.cpp 项目: robert333/graph
bool Edge::operator==(Edge const& other_edge) const
{
	return get_tail() == other_edge.get_tail() and get_head() == other_edge.get_head();
}
示例#24
0
int ut_are_together(struct upTree* ut, long long g1, long long g2) {
    struct _upnode* head1 = get_head(ut, g1);
    struct _upnode* head2 = get_head(ut, g2);
    return head1 == head2;
}