Example #1
0
int main()
{
    void *data;
    char *command1, *command2, *def;
    int result;
    FILE *fp = fopen("treelog.txt", "w");
    RBtree *tree = malloc(sizeof(RBtree));
    init_tree(tree, vstrcmp, node_destroy, node_print);
    fprintf(fp, "Tree Height\n");
    while(1)
    {
        printf(">");
        command1 = malloc(sizeof(char)*10);
        command2 = malloc(sizeof(char)*50);
        def = malloc(sizeof(char)*1000);
        result = (parseline(command1, command2, def));


        switch(result) {
        case -1:
            printf("Error: invalid use of 'add'\n");
            free(command2);
            free(def);
            break;
        case -2:
            printf("Error: invalid use of 'delete'\n");
            free(command2);
            free(def);
            break;
        case -3:
            printf("Error: invalid use of 'find'\n");
            free(command2);
            free(def);
            break;
        case -4:
            printf("Error: command not recognized\n");
            free(command2);
            free(def);
            break;
        case -5:
            printf("Error: no filename given");
            free(command2);
            free(def);
        case 1:
            if(!insert_node(tree, command2, def))
            {
                printf("Added %s to dictionary\n", command2);
                printtolog(fp, tree);
            }
            else printf("Error - %s not added to dictionary\n", command2);
            break;
        case 2:
            free(def);
            if(!delete_node(tree, command2))
            {
                printf("Deleted %s from dictionary\n", command2);
                printtolog(fp, tree);
            }
            else printf("Error - %s not found\n", command2);
            free(command2);
            break;
        case 3:
            free(def);
            if(!find_node(tree, command2, &data))
            {
                printf("%s\n", command2);
                printf("%s\n", (char *)data);
            }
            else printf("%s not found in dictionary\n", command2);
            free(command2);
            break;
        case 4:
            free(command2);
            free(def);
            print_tree(tree, tree->root);
            break;
        case 5:
            free(command1);
            free(command2);
            free(def);
            destroy_tree(tree, tree->root);
            free(tree);
            fclose(fp);
            return 0;
            break;
        case 6:
            if(!readfile(tree, command2, fp))
                printf("File scanned to dictionary\n");
            else printf("Error - file not scanned\n");
            free(command2);
            break;
        case 7:
            find2(tree, tree->root, command2, def);
            free(command2);
            free(def);
            break;
        case 8:
            ptest(tree, command2, fp);
            free(command2);
            break;
        }

        free(command1);
    }
}
Example #2
0
int bts_delete_node(struct bts_tree * tree,
		uint32_t val) {

	struct node * curr;
	struct node * prev = NULL;

	curr = find_node(tree, val);
	printf(RED"\nDelete at %p val %i"RES,curr,curr->val);
	if (curr->left) {
		if (curr == tree->root) {
			tree->root = curr->left;
		}
		if (curr->left->right) {
			printf("\nByc tu!!");
			curr->left->right->parent = curr->parent;
			curr->left->right->left  = curr->left;
			curr->left->right->right = curr->right;
			if (curr->parent->right == curr) {
				curr->parent->right = curr->left->right;
			}
			else {
				curr->parent->left = curr->left->right;
				curr->left->right = NULL;//curr->left->right->left;
			}
		}
		else {
			curr->left->parent = curr->parent;
			curr->left->left  = curr->left;
			curr->left->right = curr->right;
			if (curr->parent->right == curr) {
				curr->parent->right = curr->left;
			}
			else {
				curr->parent->left = curr->left;
			}
		}

	}
	else if (curr->right) {
		if (curr == tree->root) {
			tree->root = curr->right;
		}
		if (curr->right->left) {
			curr->right->left->parent = curr->parent;
			curr->right->left->right  = curr->right;
			curr->right->left->left = curr->left;
			if (curr->parent->left == curr) {
				curr->parent->left = curr->right->left;
			}
			else {
				curr->parent->right = curr->right->right;
			}
		}
		else {
			curr->right->parent = curr->parent;
			curr->right->right  = curr->right;
			curr->right->left = curr->left;
			if (curr->parent->left == curr) {
				curr->parent->left = curr->right;
			}
			else {
				curr->parent->right = curr->right;
			}
		}
	}
	else {
		if (curr->parent->right == curr) {
			curr->parent->right = NULL;
		}
		else {
			curr->parent->left = NULL;
		}
	}

	traverse(tree,curr);
	free(curr);

ret:	
	return 0;
}
Example #3
0
static void
load_config (xmlNodePtr root, const char *type, const char *name)
{
  xmlNodePtr node;
  xmlNodePtr n;
  GObject *object;
  xmlChar *enabled_val = NULL;

  GST_INFO ("loading config %s %s", type, name);

  node = find_node (root, type, name);
  if (node == NULL) {
    GST_ERROR ("config: failed to find %s:%s", type, name);
    return;
  }

  object = gss_config_get (name);
  if (object == NULL) {
    GST_ERROR ("config: no object %s", name);
    return;
  }

  n = node->children;
  while (n) {
    if (n->type == XML_ELEMENT_NODE &&
        strcmp ((const char *) n->name, "name") == 0) {
      /* already set */
#if 0
    } else if (GSS_IS_ENCODER (object) && n->type == XML_ELEMENT_NODE &&
        strcmp ((const char *) n->name, "stream") == 0) {
      GssEncoder *encoder = GSS_ENCODER (object);
      GssStream *stream;
      xmlNodePtr n2;

      GST_INFO_OBJECT (object, "adding stream");
      stream = g_object_new (GSS_TYPE_STREAM, NULL);
      n2 = n->children;
      while (n2) {
        if (n2->type == XML_ELEMENT_NODE) {
          xmlChar *s;
          s = xmlNodeGetContent (n2);
          GST_DEBUG_OBJECT (stream, "setting %s:%s to %s",
              GST_OBJECT_NAME (stream), n2->name, s);
          g_object_set_as_string (G_OBJECT (stream), (char *) n2->name,
              (char *) s);
          xmlFree (s);
        }

        n2 = n2->next;
      }

      gss_encoder_add_stream (encoder, stream);
#endif
    } else if (n->type == XML_ELEMENT_NODE &&
        strcmp ((const char *) n->name, "enabled") == 0) {
      if (enabled_val) {
        xmlFree (enabled_val);
      }
      enabled_val = xmlNodeGetContent (n);
    } else if (n->type == XML_ELEMENT_NODE) {
      xmlChar *s;
      s = xmlNodeGetContent (n);
      GST_DEBUG_OBJECT (object, "setting %s:%s to %s", GST_OBJECT_NAME (object),
          n->name,
          gss_object_param_is_secure (object, (char *) n->name) ? "SECURE" :
          (char *) s);
      g_object_set_as_string (object, (char *) n->name, (char *) s);
      xmlFree (s);
    }
    n = n->next;
  }
  if (enabled_val) {
    g_object_set_as_string (object, "enabled", (char *) enabled_val);
    xmlFree (enabled_val);
  }
}
Example #4
0
/**Function********************************************************************

   Synopsis           [Looks up in the wff2nff memoization hash for
   the given entry]

   Description        [Looks up in the wff2nff memoization hash for
   the given entry]

   SideEffects        []

   SeeAlso            []

******************************************************************************/
static node_ptr w2w_wff2nnf_hash_lookup_entry(node_ptr wff, boolean polarity)
{
  nusmv_assert(wff2nnf_hash != (hash_ptr) NULL);
  return find_assoc(wff2nnf_hash, find_node(CONS, wff, (node_ptr) polarity));
}
Example #5
0
int main(void)
{
   dg_prob *dgp;
   dg_params *par;
   FILE *read_from, *write_to;
   int childpid, sender;

   char tcl_msg[MAX_LINE_LENGTH +1];
   char name[MAX_NAME_LENGTH +1], name2[MAX_NAME_LENGTH +1];
   char source[MAX_NAME_LENGTH +1], target[MAX_NAME_LENGTH +1];
   char title[MAX_TITLE_LENGTH +1], title2[MAX_TITLE_LENGTH +1];
   char fname[MAX_FILE_NAME_LENGTH +1];
   char old_weight[MAX_WEIGHT_LENGTH +1], new_weight[MAX_WEIGHT_LENGTH +1];
   char new_label[MAX_LABEL_LENGTH +1];
   char new_dash[MAX_DASH_PATTERN_LENGTH +1];
   char *str;
   int msgtag, keyword, key, r_bufid, s_bufid, bufid, bytes, len;

   int i, j, k, number, add_nodenum, change_nodenum, delete_nodenum;
   int add_edgenum, change_edgenum, delete_edgenum;
   int nodenum, new_nodenum, edgenum, new_edgenum, node_id, edge_id;
   int new_radius, old_deleted_nodenum;
   unsigned int id;
   win_desc *desc;
   dg_graph *g;
   dg_node *nodes, *nod;
   dg_edge *edges, *edg;
   window *win, *new_win, *source_win, *target_win;

   register_process();
   dgp = (dg_prob *) calloc(1, sizeof(dg_prob));

   /* receive parameters from the master */
   r_bufid = receive_msg(ANYONE, DG_DATA);
   bufinfo(r_bufid, &bytes, &msgtag, &dgp->master);
   receive_char_array((char *)&dgp->par, sizeof(dg_params));
   freebuf(r_bufid);
   par = &(dgp->par);
   echo_commands = par->echo_commands;

   /* fork the wish shell */
   childpid = start_child((char *)"wish", &read_from, &write_to);

   /* Source the tcl scripts into wish and invoke startUp*/
   spprint(write_to, "source %s/Init.tcl\n", par->source_path);
   spprint(write_to, "source %s/Tools.tcl\n", par->source_path);
   spprint(write_to, "source %s/NodeEdgeBasics.tcl\n", par->source_path);
   spprint(write_to, "source %s/FileMenu.tcl\n", par->source_path);
   spprint(write_to, "source %s/WindowMenu.tcl\n", par->source_path);
   spprint(write_to, "source %s/NodeMenu.tcl\n", par->source_path);
   spprint(write_to, "source %s/EdgeMenu.tcl\n", par->source_path);
   spprint(write_to, "source %s/CAppl.tcl\n", par->source_path);

   spprint(write_to, "Igd_StartUp\n");

   /* set application defaults to those stored in par */
   spprint(write_to,
	   "Igd_SetApplDefaults %i %i %i %i %i %i %i {%s} {%s} %i %i %i %f {%s} {%s} {%s}\n",
	   par->canvas_width, par->canvas_height, par->viewable_width,
	   par->viewable_height, par->disp_nodelabels,
	   par->disp_nodeweights, par->disp_edgeweights, par->node_dash,
	   par->edge_dash, par->node_radius, par->interactive_mode,
	   par->mouse_tracking, par->scale_factor, par->nodelabel_font,
	   par->nodeweight_font, par->edgeweight_font);

   /* invoke user initialization */
#ifdef USE_SYM_APPLICATION
   CALL_USER_FUNCTION( user_initialize_dg(&dgp->user) );
#endif

   while(TRUE){

      msgtag = 0;

      if (dgp->waiting_to_die){
	 for ( i = 0; i < dgp->window_num; ){
	    if ( ! dgp->windows[i]->wait_for_click ){
	       spprint(write_to, "Igd_QuitWindow %u\n",dgp->windows[i]->id);
	       free_window(&dgp->window_num, dgp->windows, i);
	    }else{
	       i++;
	    }
	 }
	 if ( ! dgp->window_num )
	    wait_for_you_can_die(dgp, write_to);
      }

      /* Interpret message coming from the tcl application. */
      if (fgets(tcl_msg, 80, read_from) != NULL) {
	 sscanf(tcl_msg, "%i", &msgtag);

	 switch(msgtag){

	  case IGDTOI_CLICK_HAPPENED:
	    /* if wait_for_click is 2, send a message to the owner */
	    fgets(name2, MAX_NAME_LENGTH +1, read_from);
	    sscanf(name2, "%u", &id);
	    for (i = dgp->window_num - 1; i >= 0; i-- )
	       if ( dgp->windows[i]->id == id )
		  break;
	    if ( i < 0 ) {
	       /* this should never happen */
	       printf("Window of id %u is not found\n", id);
	       break;
	    }
	    if ( dgp->windows[i]->wait_for_click == 2 ) {
	       s_bufid = init_send(DataInPlace);
	       send_str(name);
	       send_msg(dgp->windows[i]->owner_tid, ITOC_CLICK_HAPPENED); 
	       freebuf(s_bufid); 
	    }
	    dgp->windows[i]->wait_for_click = 0;
	    break;

	  case IGDTOI_QUIT_WINDOW:
	    /* delete data structure corresponding to this window */
	    fgets(name2, MAX_NAME_LENGTH +1, read_from);
	    sscanf(name2, "%u", &id);
	    for (i = dgp->window_num - 1; i >= 0; i-- )
	       if ( dgp->windows[i]->id == id )
		  break;
	    if ( i < 0 ) {
	       /* this should never happen */
	       printf("Window of id %u is not found\n", id);
	       break;
	    }
	    spprint(write_to, "Igd_QuitWindow %u\n", id);
	    free_window(&dgp->window_num, dgp->windows, i);
	    break;

	  case IGDTOI_QUIT_APPLICATION:
	    /* delete all windows */
	    for ( i = 0; i < dgp->window_num; ){
	       if ( ! dgp->windows[i]->wait_for_click ){
		  spprint(write_to, "Igd_QuitWindow %u\n",dgp->windows[i]->id);
		  free_window(&dgp->window_num, dgp->windows, i);
	       }else{
		  i++;
	       }
	    }
	    dgp->waiting_to_die = TRUE;
	    break;

	  case IGDTOI_TEXT_ENTERED:
	    fgets(name2, MAX_NAME_LENGTH +1, read_from);
	    sscanf(name2, "%u", &id);
	    for (i = dgp->window_num - 1; i >= 0; i-- )
	       if ( dgp->windows[i]->id == id )
		  break;
	    win = dgp->windows[i];
	    if ( i < 0 ) {
	       /* this should never happen */
	       printf("Window of id %u is not found\n", id);
	       break;
	    }
	    fgets(tcl_msg, MAX_LINE_LENGTH +1, read_from);
	    sscanf(tcl_msg, "%i", &win->text_length);
	    win->text = (char *) malloc( (win->text_length + 1) * CSIZE);
	    fread(win->text, CSIZE, win->text_length, read_from);
	    win->text[win->text_length] = 0;

	    /* invoke function that interprets the message */
#ifdef USE_SYM_APPLICATION
	    CALL_USER_FUNCTION( user_interpret_text(dgp->user,
						    win->text_length,
						    win->text,
						    win->owner_tid) );
#endif
	    break;

	  case IGDTOI_REQUEST_GRAPH:
	    fgets(name2, MAX_NAME_LENGTH +1, read_from);
	    sscanf(name2, "%u", &id);
	    for (i = dgp->window_num - 1; i >= 0; i-- )
	       if ( dgp->windows[i]->id == id )
		  break;
	    if ( i < 0 ) {
	       /* this should never happen */
	       printf("Window of id %u is not found\n", id);
	       break;
	    }
	    display_graph_on_canvas(dgp->windows[i], write_to);
	    break;

	  default:
	    printf("Unknown message type from IGD to I (%i)\n", msgtag);
	    break;
	 
	 } /* end switch */
      } /* end if */

      if (dgp->waiting_to_die)
	 continue;


      /* Interpret the message coming from the C application.

	 All the messages except INITIALIZE_WINDOW and COPY_GRAPH
	 and QUIT will be put on the pipe corresponding to the appropriate
	 window (messages are processed in FIFO order

	 In case of INITIALIZE_WINDOW the data structure associated
	 with a winow is created (including the pipes.

	 In case of COPY_GRAPH a message must be placed on both the
	 source and the target window's pipe.

	 In case of QUIT all data structures are disassembled and then
	 the tcl application is killed.                                   */

      r_bufid = nreceive_msg(ANYONE, ANYTHING);
      if (r_bufid > 0){
	 bufinfo(r_bufid, &bytes, &msgtag, &sender);
	 switch (msgtag){

	  case CTOI_INITIALIZE_WINDOW:

	    /* get the name of the new window */
	    receive_str(name);
	    receive_str(title);

	    /* if a window with this name already exists: error */
	    i = find_window(dgp->window_num, dgp->windows, name);
	    if ( i >= 0 ) {
	       INTERMED_ERROR(name, msgtag, sender,ITOC_WINDOW_ALREADY_EXISTS);
	       freebuf(r_bufid);
	       break;
	    }
	    /* allocate space for the new window */
	    win = init_dgwin(dgp, sender, name, title);

	    /* set up the window description */
	    receive_int_array(&number, 1);
	    copy_win_desc_from_par(win, &dgp->par);
	    for ( ; number > 0; number-- ) {
	       /* read out the key - value pairs */
	       receive_int_array(&key, 1);
	       set_window_desc_pvm(key, win);
	    }

	    freebuf(r_bufid);
	    break;


	  case CTOI_COPY_GRAPH:
	    /* Copy source's graph into target's window.
	       Here a message is placed onto both target's and source's
	       pipe so that they can wait for each other before the
	       actual copying happens (shake hands) */
	    
	    receive_str(target);
	    receive_str(source);

	    i = find_window(dgp->window_num, dgp->windows, target);
	    if (i < 0) { /* target doesn't exist, send error message */
	       INTERMED_ERROR(target, msgtag, sender,ITOC_WINDOW_DOESNT_EXIST);
	       freebuf(r_bufid);
	       break;
	    }
	    j = find_window(dgp->window_num, dgp->windows, source);
	    if (j < 0) { /* source doesn't exist, send error message */
	       INTERMED_ERROR(source, msgtag, sender,ITOC_WINDOW_DOESNT_EXIST);
	       freebuf(r_bufid);
	       break;
	    }
	    bufid = init_send(DataInPlace);
	    msgtag = WAITING_TO_GET_A_COPY;
	    send_int_array(&msgtag, 1);
	    send_str(source);
	    add_msg(dgp->windows[i], bufid);
	    setsbuf(0);

	    bufid = init_send(DataInPlace);
	    msgtag = WAITING_TO_BE_COPIED;
	    send_int_array(&msgtag, 1);
	    send_str(target);
	    add_msg(dgp->windows[j], bufid);
	    setsbuf(0);

	    freebuf(r_bufid);
	    break;


	  case CTOI_QUIT:
	    /* quit from all windows, disassemble data structures.
	     * (actually, this will happen on the top of the while loop...) */
	    if (! dgp->waiting_to_die)
	       dgp->waiting_to_die = TRUE;
	    freebuf(r_bufid);
	    break;

	  case CTOI_YOU_CAN_DIE:
	    /* quit from all windows, disassemble data structures.
	     * (actually, this will happen on the top of the while loop...)
	     * and die */
	    dgp->waiting_to_die = 2 * TRUE;
	    freebuf(r_bufid);
	    break;


	  default:
	    /* Check if window with name exists. If not, send back error
	       message. If yes, copy the message over to window's pipe. */
	    receive_str(name);
	    len = strlen(name);
	    i = find_window(dgp->window_num, dgp->windows, name);
	    if (i < 0){
	       /* there is no window of that name: send error message */
	       INTERMED_ERROR(name, msgtag, sender,ITOC_WINDOW_DOESNT_EXIST);
	       freebuf(r_bufid);
	       break;
	    }

	    add_msg(dgp->windows[i], r_bufid);
	    setrbuf(0);
	    break;
	 } /* end switch */
      } /* endif r_bufid > 0 */


      if (dgp->waiting_to_die)
	 continue;

      /* Process one message from each window's pipe. */

      for ( i = 0; i < dgp->window_num; i++ ) {

	 win = dgp->windows[i];

	 /* if wait_for_click is set, skip */
	 if ( win->wait_for_click )
	    continue;

	 /* if window is waiting to be copied or waiting to get a copy, skip */
	 if ( win->copy_status )
	    continue;

	 /* if no message in the pipe, skip */
	 if (win->buf.bufread == -1)
	    continue;

	 /* else: process the message .... */
	 msgtag = 0;
	 r_bufid = get_next_msg(win);
	 setrbuf(r_bufid);
	 bufinfo(r_bufid, &bytes, &msgtag, &sender);

	 if (msgtag == 0){
	    /* This means that the message was locally 'hand-packed' */
	    receive_int_array(&msgtag, 1);
	 }

	 switch ( msgtag ) {

	  case CTOI_USER_MESSAGE:
#ifdef USE_SYM_APPLICATION
	    user_dg_process_message(win->user, win, write_to);
#endif
	    break;

	  case CTOI_QUIT_WINDOW:
	    /* delete this window */
	    spprint(write_to, "Igd_QuitWindow %u\n", win->id);
	    free_window(&dgp->window_num, dgp->windows, i);
	    i--;
	    break;


	  case CTOI_CHANGE_WINDOW_DESC:
	    /* change window descriptions */
	    receive_int_array(&number, 1);
	    for ( ; number > 0; number-- ) {
	       /* read out the key - value pairs */
	       receive_int_array(&key, 1);
	       set_window_desc_pvm(key, win);
	    }
	    desc = &(win->desc);
	    if ( win->window_displayed ) {
	       spprint(write_to, "Igd_SetAndExecuteWindowDesc %u %i %i %i %i %i %i %i {%s} {%s} %i %i %i %f {%s} {%s} {%s}\n",
		       win->id, desc->canvas_width, desc->canvas_height,
		       desc->viewable_width, desc->viewable_height,
		       desc->disp_nodelabels, desc->disp_nodeweights,
		       desc->disp_edgeweights, desc->node_dash,
		       desc->edge_dash, desc->node_radius,
		       desc->interactive_mode, desc->mouse_tracking,
		       desc->scale_factor, desc->nodelabel_font,
		       desc->nodeweight_font, desc->edgeweight_font);
	    }
	    break;


	  case CTOI_SET_GRAPH:
	  case CTOI_SET_AND_DRAW_GRAPH:
	    /* define the graph corresponding to this window */
	    g = &(win->g);
	    FREE(g->nodes);
	    FREE(g->edges);

	    receive_int_array(&g->nodenum, 1);
	    if ( g->nodenum ) {
	       nodes = g->nodes =
		  (dg_node *) malloc(g->nodenum * sizeof(dg_node));
	       for ( j = 0; j < g->nodenum; j++ ) {
		  read_node_desc_from_pvm(nodes+j, win);
	       }
	    }

	    receive_int_array(&g->edgenum, 1);
	    if ( g->edgenum ) {
	       edges = g->edges =
		  (dg_edge *) malloc(g->edgenum * sizeof(dg_edge));
	       for ( j = 0; j < g->edgenum; j++ ) {
		  read_edge_desc_from_pvm(edges+j, win);
	       }
	    }

	    if ( msgtag == CTOI_SET_AND_DRAW_GRAPH || win->window_displayed )
	       display_graph_on_canvas(win, write_to);

	    break;


	  case CTOI_DRAW_GRAPH:
	    /* first erase/create the window itself, then display all the nodes
	       and edges */
	    display_graph_on_canvas(win, write_to);
	    break;


	  case CTOI_DELETE_GRAPH:
	    /* delete the data structure of the graph and erase its window
	     if open */
	    FREE(win->g.nodes);
	    FREE(win->g.edges);
	    win->g.nodenum = win->g.deleted_nodenum = 0;
	    win->g.edgenum = win->g.deleted_edgenum = 0;
	    if ( win->window_displayed ){
	       spprint(write_to, "Igd_EraseWindow %u\n", win->id);
	    }
	    break;


	  case CTOI_WAIT_FOR_CLICK_NO_REPORT:
	    /* window will not get any messages until the Continue button
	       is pressed. the window has to be open to have an effect */
	    if ( win->window_displayed ) {
	       win->wait_for_click = 1;
	       spprint(write_to, "Igd_CApplWaitForClick %u\n", win->id);
	    } else {
	       INTERMED_ERROR(win->name, msgtag, win->owner_tid,
			      ITOC_WINDOW_ISNT_DISPLAYED);
	    }
	    break;


	  case CTOI_WAIT_FOR_CLICK_AND_REPORT:
	    /* window will not get any messages until the Continue button
	       is pressed. the window has to be open to have an effect.
	       the owner gets a message */
	    if ( win->window_displayed ) {
	       win->wait_for_click = 2;
	       spprint(write_to, "Igd_CApplWaitForClick %u\n", win->id);
	    } else {
	       INTERMED_ERROR(win->name, msgtag, win->owner_tid,
			      ITOC_WINDOW_ISNT_DISPLAYED);
	    }
	    break;


	  case CTOI_SAVE_GRAPH_TO_FILE:
	    /* save the graph into a file (only if it is displayed!) */
	    receive_str(fname);
	    if ( win->window_displayed ) {
	       spprint(write_to, "Igd_SaveGraph %u {%s}\n", win->id, fname);
	    } else {
	       INTERMED_ERROR(win->name, msgtag, win->owner_tid,
			      ITOC_WINDOW_ISNT_DISPLAYED);
	    }
	    break;


	  case CTOI_SAVE_GRAPH_PS_TO_FILE:
	    /* save postscript of the picture displayed. works only if
	       window is displayed. */
	    receive_str(fname);
	    if ( win->window_displayed ) {
	       spprint(write_to, "Igd_SavePs %u {%s}\n", win->id, fname);
	    } else {
	       INTERMED_ERROR(win->name, msgtag, win->owner_tid,
			      ITOC_WINDOW_ISNT_DISPLAYED);
	    }
	    break;


	  case CTOI_CLONE_WINDOW:
	    /* clone this window. if window is not displayed, only the
	     graph data structure will be copied over. */
	    /* wait_for_click, copy_status and text will not be copied over. */
	    receive_str(name2);
	    receive_str(title2);

	    if ( find_window(dgp->window_num, dgp->windows, name2) >= 0 ) {
	       INTERMED_ERROR(win->name, msgtag, sender,
			      ITOC_WINDOW_ALREADY_EXISTS);
	       break;
	    }

	    new_win = init_dgwin(dgp, sender, name2, title2);
	    copy_window_structure(new_win, win);

	    if ( win->window_displayed ) {
	       spprint(write_to,
		       "Igd_CopyWindowDesc %u %u\n", new_win->id, win->id);
	       spprint(write_to,
		       "Igd_InitWindow %u {%s}\n", new_win->id, title2);
	       spprint(write_to, "Igd_DisplayWindow %u\n", new_win->id);
	       spprint(write_to, "Igd_EnableCAppl %u\n", new_win->id);
	       spprint(write_to, "Igd_CopyGraph %u %u\n", new_win->id,win->id);
	       new_win->window_displayed = 1;
	    }
	    break;
	    

	  case CTOI_RENAME_WINDOW:
	    /* change the title of the window */
	    receive_str(win->title);
	    if ( win->window_displayed ){
	       spprint(write_to,
		       "Igd_RenameWindow %u {%s}\n", win->id, win->title);
	    }
	    break;


	  case CTOI_RESIZE_VIEWABLE_WINDOW:
	    /* change the sizes of canvas */
	    receive_int_array(&win->desc.viewable_width, 1);
	    receive_int_array(&win->desc.viewable_height, 1);
	    if ( win->window_displayed ){
	       spprint(write_to, "Igd_ResizeViewableWindow %u %i %i\n",
		       win->id, win->desc.viewable_width,
		       win->desc.viewable_height);
	    }
	    break;


	  case CTOI_RESIZE_CANVAS:
	    /* change the size of the canvas */
	    receive_int_array(&win->desc.canvas_width, 1);
	    receive_int_array(&win->desc.canvas_height, 1);
	    if ( win->window_displayed ){
	       spprint(write_to, "Igd_ResizeCanvas %u %i %i\n", win->id,
		       win->desc.canvas_width, win->desc.canvas_height);
	    }
	    break;


	  case WAITING_TO_GET_A_COPY:
	    /* Read out the name of the source-graph from the pipe.
	       If the source-graph is waiting to be copied, source and
	       target have found each other */
	    receive_str(win->source) ;
	    win->copy_status = 2;

	    j = find_window(dgp->window_num, dgp->windows, win->source);
	    if ( j >= 0 && dgp->windows[j]->copy_status == 1 ) {
	       /* source graph exists and it is waiting to be copied */
	       source_win = dgp->windows[j];

	       /* copy the data structure */
	       copy_window_structure(win, source_win);

	       /* if the window is displayed, change picture */
	       if ( win->window_displayed ) {
		  display_graph_on_canvas(win, write_to);
	       }

	       /* zero out the copy stati */
	       win->copy_status = 0;
	       win->source[0] = 0;
	       source_win->copy_status = 0;
	       source_win->target[0] = 0;
	    }
	    break;


	  case WAITING_TO_BE_COPIED:
	    /* Read out the name of the target graph from the pipe.
	       If the target-graph is waiting to get a copy, source and
	       target have found each other. */
	    receive_str(win->target);
	    win->copy_status = 1;

	    j = find_window(dgp->window_num, dgp->windows, win->target);
	    if ( j >= 0 && dgp->windows[j]->copy_status == 2 ) {
	       /* target exists and waiting for a copy */
	       target_win = dgp->windows[j];

	       /* copy the data structure */
	       copy_window_structure(target_win, win);

	       /* if the target window is displayed, update the picture */
	       if ( target_win->window_displayed ) {
		  display_graph_on_canvas(target_win, write_to);
	       }

	       /* zero out the copy stati */
	       win->copy_status = 0;
	       win->target[0] = 0;
	       target_win->copy_status = 0;
	       target_win->source[0] = 0;
	    }
	    break;
	    

	  case CTOI_MODIFY_GRAPH:
	    /* Make changes in the graph. The data structure is updated,
	       and if the window is displayed, the picture gets updated, too */

	    /* The message is in keyword - description pairs, with the
	       END_OF_MESSAGE keyword at the end. We switch on the keyword */

	    do {
	       receive_int_array(&keyword, 1);

	       switch ( keyword ) {

		case MODIFY_ADD_NODES:
		  /* same format as in SET_GRAPH */
		  receive_int_array(&add_nodenum, 1);
		  if ( add_nodenum ) {
		     g = &(win->g);
		     nodenum = g->nodenum;
		     nodes = g->nodes = (dg_node *)
			realloc(g->nodes,
				(nodenum + add_nodenum) * sizeof(dg_node));
		     for (j = 0, new_nodenum = nodenum; j < add_nodenum; j++) {
			read_node_desc_from_pvm(nodes+new_nodenum, win);
			if (find_node(nodes[new_nodenum].node_id, g) < 0)
			   new_nodenum++;
		     }
		     g->nodenum = new_nodenum;

		     if ( win->window_displayed ) {
			for ( j = nodenum; j < new_nodenum; j++ ) {
			   nod = nodes + j;
			   spprint(write_to,
				   "Igd_MakeNode %u %i %i %i {%s} {%s} %i\n",
				   win->id, nod->node_id, nod->posx,
				   nod->posy, nod->label, nod->dash,
				   nod->radius);
			   if ( *nod->weight != 0 ){
			      spprint(write_to,
				      "Igd_MakeNodeWeight %u %i {%s}\n",
				      win->id, nod->node_id, nod->weight);
			   }
			}
		     }
		  }

		  break;


		case MODIFY_CHANGE_WEIGHTS_OF_NODES:
		  /* change weights of nodes. nodes not in the graph or nodes
		     already deleted are skipped, no error message is given. */
		  g = &(win->g);
		  receive_int_array(&change_nodenum, 1);
		  for ( j = 0; j < change_nodenum; j++ ) {
		     receive_int_array(&node_id, 1);
		     receive_str(new_weight);
		     if ( (k = find_node(node_id, g)) >= 0 ) {
			strcpy(g->nodes[k].weight, new_weight);
			if ( win->window_displayed ) {
			   strcpy(old_weight, g->nodes[k].weight);
			   if ( *old_weight != 0 ) {
			      if ( *new_weight != 0 ) {
				 spprint(write_to,
					 "Igd_ChangeOneNodeWeight %u %i {%s}\n"
					 , win->id, node_id, new_weight);
			      } else {
				 /* new weight == 0 */
				 spprint(write_to,
					 "Igd_DeleteNodeWeight %u %i\n",
					 win->id, node_id);
			      }
			   } else {
			      /* no weight before */
			      if ( *new_weight != 0 ) {
				 spprint(write_to,
					 "Igd_MakeNodeWeight %u %i {%s}\n",
					 win->id, node_id, new_weight);
			      }
			   }
			}
		     }
		  }
		  break;


		case MODIFY_CHANGE_LABELS_OF_NODES:
		  /* change labels of nodes. nodes not in the graph or nodes
		     already deleted are skipped, no error message is given */
		  g = &(win->g);
		  receive_int_array(&change_nodenum, 1);
		  for ( j = 0; j < change_nodenum; j++ ) {
		     receive_int_array(&node_id, 1);
		     receive_str(new_label);
		     if ( (k = find_node(node_id, g)) >= 0 ) {
			strcpy(g->nodes[k].label, new_label);
			if ( win->window_displayed ) {
			   spprint(write_to,
				   "Igd_ChangeOneNodeLabel %u %i {%s}\n",
				   win->id, node_id, new_label);
			}
		     }
		  }
		  break;


		case MODIFY_CHANGE_DASH_OF_NODES:
		  /* change dash pattern of individual nodes. nodes not in the
		     graph will not cause error messages */
		  g = &(win->g);
		  receive_int_array(&change_nodenum, 1);
		  for ( j = 0; j < change_nodenum; j++ ) {
		     receive_int_array(&node_id, 1);
		     receive_str(new_dash);
		     if ( (k = find_node(node_id, g)) >= 0 ) {
			strcpy(g->nodes[k].dash, new_dash);
			if ( win->window_displayed ){
			   spprint(write_to,
				   "Igd_ChangeOneNodeDash %u %i {%s}\n",
				   win->id, node_id, new_dash);
			}
		     }
		  }
		  break;


		case MODIFY_CHANGE_RADII_OF_NODES:
		  /* change radii of individual nodes. nodes not in the
		     graph will not cause error messages */
		  g = &(win->g);
		  receive_int_array(&change_nodenum, 1);
		  for ( j = 0; j < change_nodenum; j++ ) {
		     receive_int_array(&node_id, 1);
		     receive_int_array(&new_radius, 1);
		     if ( (k = find_node(node_id, g)) >= 0 ) {
			g->nodes[k].radius = new_radius;
			if ( win->window_displayed ){
			   spprint(write_to,
				   "Igd_ChangeOneNodeRadius %u %i %i\n",
				   win->id, node_id, new_radius);
			}
		     }
		  }
		  break;


		case MODIFY_DELETE_NODES:
		  /* nodes not in the graph will not cause error messages */
		  receive_int_array(&delete_nodenum, 1);
		  if ( delete_nodenum ) {
		     g = &(win->g);
		     old_deleted_nodenum = g->deleted_nodenum;
		     for ( j = 0; j < delete_nodenum; j++ ) {
			receive_int_array(&node_id, 1);
			if ( (k = find_node(node_id, g)) >= 0 ) {
			   g->nodes[k].deleted = 1;
			   g->deleted_nodenum++;
			   if ( win->window_displayed ){
			      spprint(write_to,
				      "Igd_DeleteNode %u %i\n", win->id,
				      node_id);
			   }
			}
		     }
		     if ( g->deleted_nodenum > old_deleted_nodenum ) { 
			/* mark edges that have at least one deleted endpoint
			   to be deleted. Igd_DeleteNode already took care of
			   deleting these edges from the picture */
			for (k=g->edgenum-1, edg=g->edges; k >= 0; k--, edg++)
			   if ( ! edg->deleted &&
				((find_node(edg->tail, g) < 0) ||
				 (find_node(edg->head, g) < 0))){
			      edg->deleted = 1;
			      g->deleted_edgenum++;
			   }
		     }
		     /* if too many nodes and/or edges have been deleted,
			compress the graph */
		     if ( g->deleted_nodenum > 0.1 * g->nodenum ||
			 g->deleted_edgenum > 0.1 * g->edgenum )
			compress_graph(g);
		  }
		     
		  break;


		case MODIFY_ADD_EDGES:
		  /* same format as in SET_GRAPH. Nonvalid edges (one or
		   both endpoints is not in the graph will not cause an error
		   message. */
		  receive_int_array(&add_edgenum, 1);
		  if ( add_edgenum ) {
		     g = &(win->g);
		     edgenum = g->edgenum;
		     edges = g->edges = (dg_edge *)
			realloc(g->edges,
				(edgenum+add_edgenum)*sizeof(dg_edge));
		     for (j = 0, new_edgenum = edgenum; j < add_edgenum; j++) {
			edg = edges + new_edgenum;
			read_edge_desc_from_pvm(edg, win);
			if ((find_edge(edg->edge_id, g) < 0) &&
			    (find_node(edg->tail, g) >= 0) &&
			    (find_node(edg->head, g) >= 0))
			   new_edgenum++;
		     }
		     g->edgenum = new_edgenum;

		     if ( win->window_displayed ) {
			for ( j = edgenum; j < new_edgenum; j++ ) {
			   edg = edges + j;
			   spprint(write_to, "Igd_MakeEdge %u %i %i %i {%s}\n",
				   win->id, edg->edge_id, edg->tail,
				   edg->head, edg->dash);
			   if ( *edg->weight != 0 ){
			      spprint(write_to,
				      "Igd_MakeEdgeWeight %u %i {%s}\n",
				      win->id, edg->edge_id, edg->weight);
			   }
			}
		     }
		  }

		  break;


		case MODIFY_CHANGE_WEIGHTS_OF_EDGES:
		  /* change weights of edges. edges not in the graph or edges
		     already deleted are skipped, no error message is given. */
		  g = &(win->g);
		  receive_int_array(&change_edgenum, 1);
		  for ( j = 0; j < change_edgenum; j++ ) {
		     receive_int_array(&edge_id, 1);
		     receive_str(new_weight);
		     if ( (k = find_edge(edge_id, g)) >= 0 ) {
			strcpy(g->edges[k].weight, new_weight);
			if ( win->window_displayed ) {
			   strcpy(old_weight, g->edges[k].weight);
			   if ( *old_weight != 0 ) {
			      if ( *new_weight != 0 ) {
				 spprint(write_to,
					 "Igd_ChangeOneEdgeWeight %u %i {%s}\n"
					 , win->id, edge_id, new_weight);
			      } else {
				 /* new weight : 0 */
				 spprint(write_to,
					 "Igd_DeleteEdgeWeight %u %i\n",
					 win->id, edge_id);
			      }
			   } else {
			      /* no weight before */
			      if ( *new_weight != 0 ) {
				 spprint(write_to,
					 "Igd_MakeEdgeWeight %u %i {%s}\n",
					 win->id, edge_id, new_weight);
			      }
			   }
			}
		     }
		  }

		  break;


		case MODIFY_CHANGE_DASH_OF_EDGES:
		  /* change dash pattern of individual edges. edges not in the
		     graph will not cause error messages */
		  g = &(win->g);
		  receive_int_array(&change_edgenum, 1);
		  for ( j = 0; j < change_edgenum; j++ ) {
		     receive_int_array(&edge_id, 1);
		     receive_str(new_dash);
		     if ( (k = find_edge(edge_id, g)) >= 0 ) {
			strcpy(g->edges[k].dash, new_dash);
			if ( win->window_displayed ){
			   spprint(write_to,
				   "Igd_ChangeOneEdgeDash %u %i {%s}\n",
				   win->id, edge_id, new_dash);
			}
		     }
		  }
		  
		  break;


		case MODIFY_DELETE_EDGES:
		  /* edges not in the graph will not cause error messages */
		  g = &(win->g);
		  receive_int_array(&delete_edgenum, 1);
		  for ( j = 0; j < delete_edgenum; j++ ) {
		     receive_int_array(&edge_id, 1);
		     if ( (k = find_edge(edge_id, g)) >= 0 ) {
			g->edges[k].deleted = 1;
			g->deleted_edgenum++;
			if ( win->window_displayed ) {
			   spprint(write_to, "Igd_DeleteEdge %u %i\n",
				   win->id, edge_id);
			}
		     }
		  }
		  /* if too many edges have been deleted, compress the
		     graph */
		  if ( g->deleted_edgenum > 0.1 * g->edgenum )
		     compress_graph(g);
		  
		  break;


		case MODIFY_DELETE_ALL_EDGES:
		  /* will delete all edges from the graph */
		  g = &(win->g);
		  if ( win->window_displayed ) {
		     for ( j = 0; j < g->edgenum; j++ ) 
			if ( ! g->edges[j].deleted ){
			   spprint(write_to, "Igd_DeleteEdge %u %i\n",
				   win->id, g->edges[j].edge_id);
			}
		  }
		  FREE(g->edges);
		  g->edgenum = 0;
		  
		  break;
		  
		case MODIFY_END_OF_MESSAGE:
		  break;
		  
		  
		default:
		  printf("Unrecognized keyword %i\n", keyword);
		  break;
		  
		  
	       } /* end switch (keyword) */
	       
	    } while ( keyword != MODIFY_END_OF_MESSAGE );

	    break;


	  case CTOI_CLEAR_MESSAGE:
	    if ( win->window_displayed ) {
	       spprint(write_to, "Igd_CApplClearCmsg %u\n", win->id);
	    }
	    break;

	  case CTOI_PRINT_MESSAGE:
	    if ( win->window_displayed ) {
	       str = malloc(bytes);
	       receive_str(str);
	       spprint(write_to, "Igd_CApplSetCmsg %u {%s}\n", win->id, str);
	       FREE(str);
	    }
	    break;

	  case CTOI_APPEND_MESSAGE:
	    if ( win->window_displayed ) {
	       str = malloc(bytes);
	       receive_str(str);
	       spprint(write_to, "Igd_CApplAppendCmsg %u {%s}\n", win->id,str);
	       FREE(str);
	    }
	    break;

	  default:
	    printf("Unknown message tag: %i\n", msgtag);
	    break;

	 } /* end switch (msgtag) */

	 freebuf(r_bufid);
      } /* end for */
      
   } /* end while */
   return(0);
}
Example #6
0
int main()
{
	int sel, code; 
	float grd;
	student stud, *ptr;

	head = NULL; 
	while(1) 
	{
		printf("\nMenu selections\n");
		printf("---------------\n");

		printf("1. Add student at the end\n");
		printf("2. Add student\n");
		printf("3. View all students\n");
		printf("4. View student\n");
		printf("5. Modify student\n");
		printf("6. Delete student\n");
		printf("7. Exit\n");

		printf("\nEnter choice: ");
		scanf("%d", &sel);

		switch(sel)
		{
			case 1: 
			case 2: /* To avoid the repetition of the same code we use the same case. Then, the if statement checks the user’s choice and calls the respective function. */
				getchar();

				printf("Name: ");
				gets(stud.name);
			
				printf("Code: ");
				scanf("%d", &stud.code);

				printf("Grade: "); 
				scanf("%f", &stud.grd);
		
				if(sel == 1)
					add_list_end(&stud);
				else
				{
					printf("\nEnter student code after which the new student will be added: ");  
					scanf("%d", &code);
					add_list(&stud, code);
				}
			break;

			case 3:
				if(head == NULL)
					printf("\nThe list is empty\n");
				else
					show_list();
			break;

			case 4:
				if(head == NULL)
					printf("\nThe list is empty\n");
				else
				{
					printf("\nEnter student code to search: "); 
					scanf("%d", &code); 
					ptr = find_node(code);
					if(ptr == NULL) 
						printf("\nStudent with code = %d does not exist\n", code);
					else
						printf("\nData:%s %.2f\n\n", ptr->name, ptr->grd);

				}
			break;

			case 5:
				if(head == NULL)
					printf("\nThe list is empty\n");
				else
				{
					printf("\nEnter student code to modify: "); 
					scanf("%d", &code); 
					
					printf("Enter new grade: "); 
					scanf("%f", &grd); 
					ptr = find_node(code);
					if(ptr != NULL)
						ptr->grd = grd;
					else
						printf("\nStudent with code = %d does not exist\n", code);
				}
			break;

			case 6:
				if(head == NULL)
					printf("\nThe list is empty\n");
				else
				{
					printf("\nEnter student code to delete: "); 
					scanf("%d", &code); 
					del_node(code); 
				}
			break;

			case 7:
				if(head != NULL)
					free_list();
			return 0; 

			default:
				printf("\nWrong choice\n");
			break;
		}
	} 
	return 0;
}
Example #7
0
NodeId
SignalSender::find_alive_node(const NodeBitmask& mask)
{
    FindAliveNode f;
    return find_node(mask, f);
}
Example #8
0
/*
 * Remove node 'x' from the tree. This function shall not be called if
 * node 'x' is not part of the tree.
 */
static void
remove_node(br_ssl_session_cache_lru *cc, uint32_t x)
{
	uint32_t alx, y, aly;

	/*
	 * Removal algorithm:
	 * ------------------
	 *
	 * - If we remove the root, then the tree becomes empty.
	 *
	 * - If the removed node has no child, then we can simply remove
	 *   it, with nothing else to do.
	 *
	 * - Otherwise, the removed node must be replaced by either its
	 *   rightmost left-descendent, or its leftmost right-descendent.
	 *   The replacement node itself must be removed from its current
	 *   place. By definition, that replacement node has either no
	 *   child, or at most a single child that will replace it in the
	 *   tree.
	 */

	/*
	 * Find node back and its ancestor link. If the node was the
	 * root, then alx is set to ADDR_NULL.
	 */
	find_node(cc, cc->store + x + SESSION_ID_OFF, &alx);

	/*
	 * Find replacement node 'y', and 'aly' is set to the address of
	 * the link to that replacement node. If the removed node has no
	 * child, then both 'y' and 'aly' are set to ADDR_NULL.
	 */
	y = find_replacement_node(cc, x, &aly);

	if (y != ADDR_NULL) {
		uint32_t z;

		/*
		 * The unlinked replacement node may have one child (but
		 * not two) that takes its place.
		 */
		z = get_left(cc, y);
		if (z == ADDR_NULL) {
			z = get_right(cc, y);
		}
		set_link(cc, aly, z);

		/*
		 * Link the replacement node in its new place, overwriting
		 * the current link to the node 'x' (which removes 'x').
		 */
		set_link(cc, alx, y);

		/*
		 * The replacement node adopts the left and right children
		 * of the removed node. Note that this also works even if
		 * the replacement node was a direct descendent of the
		 * removed node, since we unlinked it previously.
		 */
		set_left(cc, y, get_left(cc, x));
		set_right(cc, y, get_right(cc, x));
	} else {
		/*
		 * No replacement, we simply unlink the node 'x'.
		 */
		set_link(cc, alx, ADDR_NULL);
	}
}
Example #9
0
static void
lru_save(const br_ssl_session_cache_class **ctx,
	br_ssl_server_context *server_ctx,
	const br_ssl_session_parameters *params)
{
	br_ssl_session_cache_lru *cc;
	unsigned char id[SESSION_ID_LEN];
	uint32_t x, alx;

	cc = (br_ssl_session_cache_lru *)ctx;

	/*
	 * If the buffer is too small, we don't record anything. This
	 * test avoids problems in subsequent code.
	 */
	if (cc->store_len < LRU_ENTRY_LEN) {
		return;
	}

	/*
	 * Upon the first save in a session cache instance, we obtain
	 * a random key for our indexing.
	 */
	if (!cc->init_done) {
		br_hmac_drbg_generate(&server_ctx->eng.rng,
			cc->index_key, sizeof cc->index_key);
		cc->hash = br_hmac_drbg_get_hash(&server_ctx->eng.rng);
		cc->init_done = 1;
	}
	mask_id(cc, params->session_id, id);

	/*
	 * Look for the node in the tree. If the same ID is already used,
	 * then reject it. This is a collision event, which should be
	 * exceedingly rare.
	 * Note: we do NOT record the emplacement here, because the
	 * removal of an entry may change the tree topology.
	 */
	if (find_node(cc, id, NULL) != ADDR_NULL) {
		return;
	}

	/*
	 * Find some room for the new parameters. If the cache is not
	 * full yet, add it to the end of the area and bump the pointer up.
	 * Otherwise, evict the list tail entry. Note that we already
	 * filtered out the case of a ridiculously small buffer that
	 * cannot hold any entry at all; thus, if there is no room for an
	 * extra entry, then the cache cannot be empty.
	 */
	if (cc->store_ptr > (cc->store_len - LRU_ENTRY_LEN)) {
		/*
		 * Evict tail. If the buffer has room for a single entry,
		 * then this may also be the head.
		 */
		x = cc->tail;
		cc->tail = get_prev(cc, x);
		if (cc->tail == ADDR_NULL) {
			cc->head = ADDR_NULL;
		} else {
			set_next(cc, cc->tail, ADDR_NULL);
		}

		/*
		 * Remove the node from the tree.
		 */
		remove_node(cc, x);
	} else {
		/*
		 * Allocate room for new node.
		 */
		x = cc->store_ptr;
		cc->store_ptr += LRU_ENTRY_LEN;
	}

	/*
	 * Find the emplacement for the new node, and link it.
	 */
	find_node(cc, id, &alx);
	set_link(cc, alx, x);
	set_left(cc, x, ADDR_NULL);
	set_right(cc, x, ADDR_NULL);

	/*
	 * New entry becomes new list head. It may also become the list
	 * tail if the cache was empty at that point.
	 */
	if (cc->head == ADDR_NULL) {
		cc->tail = x;
	} else {
		set_prev(cc, cc->head, x);
	}
	set_prev(cc, x, ADDR_NULL);
	set_next(cc, x, cc->head);
	cc->head = x;

	/*
	 * Fill data in the entry.
	 */
	memcpy(cc->store + x + SESSION_ID_OFF, id, SESSION_ID_LEN);
	memcpy(cc->store + x + MASTER_SECRET_OFF,
		params->master_secret, MASTER_SECRET_LEN);
	br_enc16be(cc->store + x + VERSION_OFF, params->version);
	br_enc16be(cc->store + x + CIPHER_SUITE_OFF, params->cipher_suite);
}
Example #10
0
void * rbtree_lookup(struct rbtree * tree, void * key)
{
	struct rbtree_node * node = find_node(tree, key);
	return node == NULL ? NULL : node->data;
}
Example #11
0
void http_cb(http_req_t *req) {
   char *target, *p;
   xmlDoc *doc;
   xmlNode *rt, *wt, *cc;
   char buf[BUFSIZ];
   int i, j;

   if (req->state != HTTPST_DONE && req->state != HTTPST_ERR)
      return;

   target = (char*)http_getptr(req);
   if (!target)
      goto out;

   if (req->state == HTTPST_ERR) {
      if (!req->status)
         irc_privmsg(target, "HTTP Connection error");
      else
         irc_privmsg(target, "HTTP Error: %i",req->status);
      goto free_out;
   }

   doc = xmlReadMemory(req->rcontent, req->rcontentlen, req->uri, NULL, 
      XML_PARSE_RECOVER|XML_PARSE_NOERROR|XML_PARSE_NOWARNING|XML_PARSE_NONET);   
   if (!doc)
      goto free_out;
   rt = xmlDocGetRootElement(doc);
   wt = find_node(rt, "weather", XML_ELEMENT_NODE);

   buf[0] = '\0';
   cc = find_node(wt, "current_conditions", XML_ELEMENT_NODE);
   if (cc) {
      for (i = 0; pentries[i].name; ++i) {
         p = node_prop(find_node(cc, pentries[i].name, XML_ELEMENT_NODE),
               "data");
         if (p) {
            j = strlen(buf);
            if (j) {
               buf[j++] = ',';
               buf[j++] = ' ';
            }
            snprintf(buf+j, BUFSIZ-j-2, pentries[i].pat, p);
            xmlFree(p);
         }
      }
   }
   if (*buf) {
      p = node_prop(find_node(find_node(wt, "forecast_information",
         XML_ELEMENT_NODE), "city", XML_ELEMENT_NODE), "data");
      if (p) {
         irc_privmsg(target, "%s: %s", p, buf); 
         xmlFree(p);
      } else {
         irc_privmsg(target, "%s", buf);
      }
   } else {
      irc_privmsg(target, "No results");
   }
   xmlFreeDoc(doc);
free_out:
   xmlCleanupParser();
   free(target);
out:
   http_free(req);
}
Example #12
0
void my_callback(u_char *useless,const struct pcap_pkthdr* pkthdr,const u_char*
        packet)
{
	packet_num++;
	packet_len+=pkthdr->caplen;

    	static   int count = 0;
	//static int nn=0;
	static int i;
	static unsigned short eth_type;
	static int vlan_flag=0;
		//sem_getvalue(&shmp[i]->sem,&semnum);
		//printf("sem:%d\n",semnum);		
	//usleep(1000);
	static int semnum;
//	sem_getvalue(&bin_sem,&semnum);
	//	printf("sem:%d\n",semnum);
		//printf("mmmmmmmmmmmmmm\n");
		if(exitflag)
		{
			/*for(i=0;i<snortnum;++i)
			{
				memcpy(shmp[i]->data[shmp[i]->tail],"########",strlen("########"));
				shmp[i]->tail=(shmp[i]->tail+1)%shmp[i]->looplen;
				my_lock_release(shmp[i]);
			}
		
				sleep(4);

			for(i=0;i<snortnum;++i)
			{
				destroy_loop(shmp[i]);
				DeleteShm(shmid[i]);
			}*/
			for(i=0;i<PRO_MAX+2;++i)
			{
	
				printf("%s:%lld\n",pro_map[i],pronum[i]);
		  	 }
		   	printf("losepacket=%lld\n",losepacket);
			//sem_post(&bin_sem);
			 NS_TIME_END(time);
	
			speed1(NS_GET_TIMEP(time),packet_num,packet_len);

			printf("count=%d,\nfind_pro=%lld\n",count,find_pro);
	
				printf("exit\n");
			del_HB(&hb);
		
			acsmFree (acsm);
		//	exitflag=0;
			exit(0);
		} 
//return;
		 mac=(struct ether_header*)packet;
		 eth_type=ntohs(mac->ether_type);
		
		 if((eth_type==0x8100))
		 {
		 	vlan_flag=1;
		 	//msg("W:****0X%04X\n",eth_type);
		 	eth_type=(packet[16])*256+packet[17];
		 }
		 else
		 	vlan_flag=0;
		
		// msg("W:0X%04X\n",eth_type);
		 if((eth_type!=0x0800))//不是ip数据报
		       	return;
		 if(vlan_flag)
		 	ip=(struct ip*)(packet+size_mac+4);
	 	 else
 			ip=(struct ip*)(packet+size_mac);

		
		/*char ipdotdecs[20]={0};
	       char ipdotdecc[20]={0};
		inet_ntop(AF_INET,(void*)&(ip->ip_src),ipdotdecs,16);
			inet_ntop(AF_INET,(void*)&(ip->ip_dst),ipdotdecc,16);*/
//printf("%s-->%s: len:%d\n",ipdotdecs,ipdotdecc,pkthdr->caplen);

			
		if((ip->ip_p==6))//tcp
		{
		//	msg("EIStcp\n");
			//tcp=(struct fniff_tcp*)(packet+size_mac+size_ip);
			tcp=(struct fniff_tcp*)((char*)ip+size_ip);
			sd.b_ip=(ip->ip_src.s_addr);
			sd.l_ip=(ip->ip_dst.s_addr);
			if(sd.b_ip>sd.l_ip)
			{
				sd.b_port=ntohs(tcp->th_sport);
				sd.l_port=ntohs(tcp->th_dport);
			}
			else
			{
				sd.b_ip^=sd.l_ip;
				sd.l_ip^=sd.b_ip;
				sd.b_ip^=sd.l_ip;
			
				sd.b_port=ntohs(tcp->th_dport);
				sd.l_port=ntohs(tcp->th_sport);					
			}			
			hash=hash_HB(sd.b_ip,sd.b_port,sd.l_ip,sd.l_port);
		
			tcplen=ntohs(ip->ip_len)-(ip->ip_hl*4)-(tcp->th_off*4);
	
		//	msg("EIStcp11111111111\n");
		//	printf("ntohs(ip->ip_len)=%d\n",ntohs(ip->ip_len)+14);
			// packet.tcp_URG=tcp->th_flags&TH_URG;
			  ack=tcp->th_flags&TH_ACK;
			 // packet.tcp_PSH=tcp->th_flags&TH_PUSH;
			  rst=tcp->th_flags&TH_RST;
			  syn=tcp->th_flags&TH_SYN;
			  fin=tcp->th_flags&TH_FIN;
			 datalen=pkthdr->caplen;
		   
			ptcp=(unsigned char*)tcp+(tcp->th_off*4);     	

			temp=find_node(hb[hash].virtual_sn,&sd);  
		  
			if(temp==NULL&&syn&&!ack&&tcplen==0)//not find
		      	{
		      		//msg("E no\n");
		      		SN* q=get_node();
		      		q->sdipport=sd;
		      		q->state=1;
				insert_node(&(hb[hash].virtual_sn),q);
				hb[hash].virtual_sn_num++;
				//msg("**********=%ld\n",hb[hash].virtual_sn_num);
				#if 0				
				if(sd.b_port==21||sd.l_port==21)
				{
					q->state=10;			
					pronum[FTP]++;
				}
				else if(sd.b_port==80||sd.l_port==80)
				{
					q->state=10;
					pronum[HTTP]++;
				}
				memcpy(fortest,packet,pkthdr->caplen);
				#endif
		
		      	}
		      	else if(temp!=NULL)
		      	{
		      		// printf("state:%d\n",temp->state);
		      	
		      		if((temp->state==1)&&syn&&ack&&(tcplen==0))
		      		{
		      			//msg("W:my ooooooooooooooooooo\n");
		      			temp->state=2;
		      		}
		      		else if(temp->state==2&&ack&&!syn&&tcplen==0)
		      		{
		      			temp->state=3;
		      			//msg("W:its ===============================static\n");
		      				//msg("W:my hash:%u\n",hash);
		      		}
		      		else if(temp->state>=3&&temp->state<9)
		      		{
		      			//if(tcplen==0)
		      			//	return;
		      			//msg("W:my hash:%u\n",hash);
		      			//msg("+++++\n");
					//msg("ttttttttttttt\n");
		      			p=get_BC_node();
					//msg("mmmmmmmmm\n");
					if(p==NULL)
						{msg("EISget bc node error\n");exit(0);}
		      			
		      			p->datalen=pkthdr->caplen;
		      			p->tcplen=tcplen;
					//msg("tcplen=%d,pkthdr->caplen=%d\n",tcplen,pkthdr->caplen);
					if(tcplen<0)
					{
						msg("EIS tcp<0\n");
						exit(0);
					}				
		      			p->next=NULL;
		      			memcpy(p->buf,packet,pkthdr->caplen);
					p->ptcp=(unsigned char*)(p->buf)+(tcp->th_off*4)+((unsigned char*)tcp-(unsigned char*)mac);//ptcp;
		      			temp->tcp_content_len+=tcplen;			
		      			if(temp->bc_head==NULL)
		      			{
		      				temp->bc_head=temp->bc_tail=p;
		      			}
		      			else
		      			{
		      				temp->bc_tail->next=p;
		      				temp->bc_tail=p;
		      			}
		      			temp->state++;
		      			if((temp->state==9)||rst||fin||(temp->tcp_content_len>150))
		      			{
		      				//msg("EIS static\n");
						#if 0
		      				p=temp->bc_head;
		      				while(p!=NULL)
		      				{				
							if(p->tcplen!=0)
							acsmSearch(acsm,p->ptcp,p->tcplen,PrintMatch);
		      					p=p->next;
		      				}
						#else
						acSearch(acsm,temp->bc_head);
		      				acSearch(acsm,temp->bc_head);
						#endif
		      				i=getSummary(acsm->acsmPatterns,feature_num); 
						    		
		      				pronum[i]++;
						temp->proto=i;
		      				if(rst||fin)
		      				{
							temp->state=10;
							resume_BC_node(temp->bc_head);
		      					resume_node(temp);
		      					hb[hash].virtual_sn_num--;
		      					
							//msg("*********=%ld\n",hb[hash].virtual_sn_num);
							if(hb[hash].virtual_sn_num==0)
								hb[hash].virtual_sn=NULL;
		      					return;
		      				}
		      				temp->state=10;
		      				resume_BC_node(temp->bc_head);
			      			temp->bc_head=NULL;
			      			temp->bc_tail=NULL;
		      			}
		      			
		      		}
		      		else if(temp->state>=10)
		      		{	

		      			if(rst||fin)
					{
						//resume_node(temp);
						move_node(&(hb[hash].virtual_sn),temp);
						hb[hash].virtual_sn_num--;
						//msg("**************=%ld\n",hb[hash].virtual_sn_num);
						if(hb[hash].virtual_sn_num==0)
							hb[hash].virtual_sn=NULL;
						return;
					}
		      		} 
				else
				{
					msg("ggggggggggg\n");
				}
		      		
		      	}     	
			
			    
	     }//tcp
	     else if(ip->ip_p==1)//icmp
	     {
		//printf("2222\n");
	     	//static char pro_map[PRO_MAX+2][20]={"HTTP","FTP","POP3","SMTP","UNKOWN","UDP","ICMP"};
	 	pronum[PRO_MAX+1]++;
	    }
	    else if(ip->ip_p==17)//udp
	    	{
			//printf("1111111\n");
	    		pronum[PRO_MAX]++;
	    	}   
		else
		{
			printf("no\n");
		}
}
Example #13
0
template <class EXT_ID, class INT_ID, class COMPARE_KEYS, class ACE_LOCK> int
ACE_RB_Tree<EXT_ID, INT_ID, COMPARE_KEYS, ACE_LOCK>::insert_i (const EXT_ID &k,
                                                               const INT_ID &t,
                                                               ACE_RB_Tree_Node<EXT_ID, INT_ID> *&entry)
{
  ACE_TRACE ("ACE_RB_Tree<EXT_ID, INT_ID, COMPARE_KEYS, ACE_LOCK>::insert_i");

  // Find the closest matching node, if there is one.
  RB_SearchResult result = LEFT;
  ACE_RB_Tree_Node<EXT_ID, INT_ID> *current = find_node (k, result);
  if (current)
    {
      // If the keys match, just return a pointer to the node's item.
      if (result == EXACT)
        {
          entry = current;
          return 1;
        }
      // Otherwise if we're to the left of the insertion
      // point, insert into the right subtree.
      else if (result == LEFT)
        {
          if (current->right ())
            {
              // If there is already a right subtree, complain.
              ACE_ERROR_RETURN ((LM_ERROR,
                                 ACE_TEXT ("%p\n"),
                                 ACE_TEXT ("\nright subtree already present in ")
                                 ACE_TEXT ("ACE_RB_Tree<EXT_ID, INT_ID>::insert_i\n")),
                                -1);
            }
          else
            {
              // The right subtree is empty: insert new node there.
              ACE_RB_Tree_Node<EXT_ID, INT_ID> *tmp = 0;
              ACE_NEW_MALLOC_RETURN
                (tmp,
                 (reinterpret_cast<ACE_RB_Tree_Node<EXT_ID, INT_ID>*>
                   (this->allocator_->malloc (sizeof (*tmp)))),
                 (ACE_RB_Tree_Node<EXT_ID, INT_ID>) (k, t),
                 -1);
              current->right (tmp);

              // If the node was successfully inserted, set its parent, rebalance
              // the tree, color the root black, and return a pointer to the
              // inserted item.
              entry = current->right ();
              current->right ()->parent (current);
              RB_rebalance (current->right ());
              this->root_->color (ACE_RB_Tree_Node_Base::BLACK);
              ++this->current_size_;
              return 0;
            }
        }
      // Otherwise, we're to the right of the insertion point, so
      // insert into the left subtree.
      else // (result == RIGHT)
        {
          if (current->left ())
            // If there is already a left subtree, complain.
            ACE_ERROR_RETURN ((LM_ERROR,
                               ACE_TEXT ("%p\n"),
                               ACE_TEXT ("\nleft subtree already present in ")
                               ACE_TEXT ("ACE_RB_Tree<EXT_ID, INT_ID>::insert_i\n")),
                              -1);
          else
            {
              // The left subtree is empty: insert new node there.
              ACE_RB_Tree_Node<EXT_ID, INT_ID> *tmp = 0;
              ACE_NEW_MALLOC_RETURN
                (tmp,
                 (reinterpret_cast<ACE_RB_Tree_Node<EXT_ID, INT_ID>*>
                   (this->allocator_->malloc (sizeof (*tmp)))),
                 (ACE_RB_Tree_Node<EXT_ID, INT_ID>) (k, t),
                 -1);
              current->left (tmp);
              // If the node was successfully inserted, set its
              // parent, rebalance the tree, color the root black, and
              // return a pointer to the inserted item.
              entry = current->left ();
              current->left ()->parent (current);
              RB_rebalance (current->left ());
              this->root_->color (ACE_RB_Tree_Node_Base::BLACK);
              ++this->current_size_;
              return 0;
            }
        }
    }
  else
    {
      // The tree is empty: insert at the root and color the root black.
      ACE_NEW_MALLOC_RETURN
        (this->root_,
         (reinterpret_cast<ACE_RB_Tree_Node<EXT_ID, INT_ID>*>
           (this->allocator_->malloc (sizeof (ACE_RB_Tree_Node<EXT_ID, INT_ID>)))),
         (ACE_RB_Tree_Node<EXT_ID, INT_ID>) (k, t),
         -1);
      this->root_->color (ACE_RB_Tree_Node_Base::BLACK);
      ++this->current_size_;
      entry = this->root_;
      return 0;
    }
}
Example #14
0
/*****************************************************************************
 * NAME
 *    main
 * ARGUMENTS
 *    argc -
 *    argv -
 * DESCRIPTION
 *
 * RETURN VALUE
 *
 */
int main(int argc, char ** argv)
{
char buffer[128];
char * p;
unsigned long value, size, type, prior;
unsigned long num = 0L;
unsigned long allocated = 0L;
unsigned long maxallocated = 0L;
struct treenode * t;
struct allocated * ap, * prevap;

unsigned cAdd = 0;
unsigned cReplace = 0;
unsigned cRemove = 0;

int k;
int fQuiet = FALSE;
while ((k = getopt(argc, argv, "q")) != EOF)
	{
	switch (k)
	{
	case 'q':
		fQuiet = TRUE;
		break;
	}
	}


while (fgets(buffer, 128, stdin) != NULL)
	{
	if ((++num % 1000) == 0)
	fprintf(stderr, "%lu\r", num);
	if (strncmp(buffer, "m ", 2) == 0)
	{
	size = strtoul(buffer+2, &p, 10);
	value = strtoul(p+1, &p, 16);
add_node:
	++cAdd;
	allocated += size;
	if (allocated > maxallocated)
		maxallocated = allocated;
	t = find_node(value);
	if (t == NULL)
		{
		fprintf(stderr, "find_node(value = %lu) [1] failed!\n", value);
		break;
		}
	ap = malloc(sizeof(struct allocated));
	if (ap == NULL)
		{
		fprintf(stderr, "Out of memory!\n");
		break;
		}
	ap->size = size;
	ap->type = MYALLOC;
	ap->line = num;
	ap->link = t->alloc;
	t->alloc = ap;
#ifdef DEBUG
	printf("Adding malloc(%8lu) %8lu [%ld]\n", size, value, num);
#endif
	}
	else if (strncmp(buffer, "r ", 2) == 0)
	{
	prior = strtoul(buffer+2, &p, 16);
	size = strtoul(p+1, &p, 10);
	value = strtoul(p+1, &p, 16);
	if (prior == 0L)
		goto add_node;
replace_node:
	++cReplace;
	t = find_node(prior);
	if (t == NULL)
		{
		fprintf(stderr, "find_node(prior = %lu) failed!\n", value);
		break;
		}
	for ( prevap = NULL, ap = t->alloc ; ap ; ap = ap->link )
		{
		if (ap->type != MYFREE)
		{
		if (prevap == NULL)
			t->alloc = ap->link;
		else
			prevap->link = ap->link;
		allocated -= ap->size;
		free(ap);
#ifdef DEBUG
		printf("Removing malloc() %8lu [realloc:%ld]\n", prior, num);
#endif
		break;
		}
		prevap = ap;
		}
	t = find_node(value);
	if (t == NULL)
		{
		fprintf(stderr, "find_node(value = %lu) [2] failed!\n", value);
		break;
		}
	ap = malloc(sizeof(struct allocated));
	if (ap == NULL)
		{
		fprintf(stderr, "Out of memory!\n");
		break;
		}
	allocated += size;
	if (allocated > maxallocated)
		maxallocated = allocated;
	ap->size = size;
	ap->type = MYALLOC;
	ap->line = num;
	ap->link = t->alloc;
	t->alloc = ap;
#ifdef DEBUG
	printf("Adding malloc(%8lu) %8lu [realloc:%ld]\n", size, value, num);
#endif
	}
	else if (strncmp(buffer, "f ", 2) == 0)
	{
	value = strtoul(buffer+2, &p, 16);
	size = 0L;
	type = MYFREE;
remove_node:
	++cRemove;
	t = find_node(value);
	if (t == NULL)
		{
		fprintf(stderr, "find_node(value = %lu) [3] failed!\n", value);
		break;
		}
	for ( prevap = NULL, ap = t->alloc ; ap ; ap = ap->link )
		{
		if (ap->type != MYFREE)
		{
		if (prevap == NULL)
			t->alloc = ap->link;
		else
			prevap->link = ap->link;
		allocated -= ap->size;
		free(ap);
#ifdef DEBUG
		printf("Removing malloc() %8lu [%ld] [free]\n", value, num);
#endif
		break;
		}
		prevap = ap;
		}
	if (ap == NULL)
		{
		ap = malloc(sizeof(struct allocated));
		if (ap == NULL)
		{
		fprintf(stderr, "Out of memory!\n");
		break;
		}
		ap->size = size;
		ap->type = MYFREE;
		ap->line = num;
		ap->link = t->alloc;
		t->alloc = ap;
#ifdef DEBUG
		printf("Adding free(%8lu) [%ld]\n", value, num);
#endif
		}
	}
	}
fprintf(stderr, "%lu\n", num);
if (!fQuiet)
	print_tree( &head );
if (cAdd != cRemove)
	printf("%u alloc, %u realloc, %u free\n", cAdd, cReplace, cRemove);
printf("%lu still allocated, %lu max allocated\n", allocated, maxallocated);
#ifdef DEBUG
dump_tree( &head, 0 );
#endif
return 0;
}
Example #15
0
BST* remove_node(BST *root, int val)
{
	BST *nodeToRemove = find_node(root, val);
	BST *toDeletePtr = root;
	
	if(root == NULL)
		return NULL;
	
	if(nodeToRemove->left != NULL)
		toDeletePtr = remove_node(root, nodeToRemove->left->data);
	if(nodeToRemove->right != NULL)
		toDeletePtr = remove_node(root, nodeToRemove->right->data);
	
	free(nodeToRemove);
	
	if(nodeToRemove == root)
		return NULL;
	else
	{
		while(toDeletePtr->left != nodeToRemove || toDeletePtr->right != nodeToRemove)
		{
			if(val < toDeletePtr->data)
				toDeletePtr = toDeletePtr->left;
			else if(val > toDeletePtr->data)
				toDeletePtr = toDeletePtr->right;
		}
		if(toDeletePtr->left == nodeToRemove)
			toDeletePtr->left = NULL;
		else if(toDeletePtr->right == nodeToRemove)
			toDeletePtr->right = NULL;
		
		return root;
	}
		
	// if(root == NULL)
		// return NULL;
	// BST* penultimate = NULL,
		 // travRoot = root;
	// char leftOrRight = 'n';
	
	// while(penultimate == NULL && travRoot != NULL)
	// {
		// if(val == travRoot->left->data)
		// {
			// leftOrRight = 'l';
			// penultimate = travRoot;
		// }
		// else if(val == travRoot->right->data)
		// {
			// leftOrRight = 'r';
			// penultimate = travRoot;
		// }
		// else if(val < travRoot->data)
			// travRoot = travRoot->left;
		// else if(val > travRoot->data)
			// travRoot = travRoot->right;
	// }
	
	// if(penultimate == NULL && travRoot == NULL)
	// {
		// printf("Value not found")
			// return;
	// }
	
	// travRoot = penultimate;
	
	// while(
	// {
		// while(travRoot->left != NULL)
		// {
			// travRoot = travRoot->left;
		// }
		// while(travRoot->right != NULL)
		// {
			// travRoot = travRoot->right;
		// }
		
	// }
}
Example #16
0
 iterator_t find(const comparator_type& compare, const FindKey& k, const Synchronized& sync) { return iterator_t(find_node(compare, k, sync)); }
Example #17
0
/**
 * Insert the element "data" into the list, such that its index is "index".
 * All elements that previously had indices "index" and above are moved
 * one position to the right.
 */
void bl_insert(bl* list, size_t index, const void* data) {
    bl_node* node;
    size_t nskipped;

    if (list->N == index) {
        bl_append(list, data);
        return;
    }

    node = find_node(list, index, &nskipped);

    list->last_access = node;
    list->last_access_n = nskipped;

    // if the node is full:
    //   if we're inserting at the end of this node, then create a new node.
    //   else, shift all but the last element, add in this element, and 
    //     add the last element to a new node.
    if (node->N == list->blocksize) {
        int localindex, nshift;
        bl_node* next = node->next;
        bl_node* destnode;
        localindex = index - nskipped;

        // if the next node exists and is not full, then insert the overflowing
        // element at the front.  otherwise, create a new node.
        if (next && (next->N < list->blocksize)) {
            // shift the existing elements up by one position...
            memmove(NODE_CHARDATA(next) + list->datasize,
                    NODE_CHARDATA(next),
                    next->N * list->datasize);
            destnode = next;
        } else {
            // create and insert a new node.
            bl_node* newnode = bl_new_node(list);
            newnode->next = next;
            node->next = newnode;
            if (!newnode->next)
                list->tail = newnode;
            destnode = newnode;
        }

        if (localindex == node->N) {
            // the new element becomes the first element in the destination node.
            memcpy(NODE_CHARDATA(destnode), data, list->datasize);
        } else {
            // the last element in this node is added to the destination node.
            memcpy(NODE_CHARDATA(destnode), NODE_CHARDATA(node) + (node->N-1)*list->datasize, list->datasize);
            // shift the end portion of this node up by one...
            nshift = node->N - localindex - 1;
            memmove(NODE_CHARDATA(node) + (localindex+1) * list->datasize,
                    NODE_CHARDATA(node) + localindex * list->datasize,
                    nshift * list->datasize);
            // insert the new element...
            memcpy(NODE_CHARDATA(node) + localindex * list->datasize, data, list->datasize);
        }

        destnode->N++;
        list->N++;

    } else {
        // shift...
        int localindex, nshift;
        localindex = index - nskipped;
        nshift = node->N - localindex;
        memmove(NODE_CHARDATA(node) + (localindex+1) * list->datasize,
                NODE_CHARDATA(node) + localindex * list->datasize,
                nshift * list->datasize);
        // insert...
        memcpy(NODE_CHARDATA(node) + localindex * list->datasize,
               data, list->datasize);
        node->N++;
        list->N++;
    }
}
Example #18
0
  node_type* find_node(const comparator_type& compare, const FindKey& k) const
	{
		return find_node(compare, k, synchronized_t());
	}
Example #19
0
NodeId
SignalSender::find_connected_node(const NodeBitmask& mask)
{
    FindConnectedNode f;
    return find_node(mask, f);
}
// Find and remove n from block list
void Block::find_remove( const Node *n ) {
  _nodes.remove(find_node(n));
}
Example #21
0
/**Function********************************************************************

   Synopsis           [Memoizes the given entry in the wff2nff memoization hash]

   Description        [Memoizes the given entry in the wff2nff memoization hash]

   SideEffects        []

   SeeAlso            []

******************************************************************************/
static void w2w_wff2nnf_hash_insert_entry(node_ptr wff, boolean polarity,
                                          node_ptr nnf)
{
  nusmv_assert(wff2nnf_hash != (hash_ptr) NULL);
  insert_assoc(wff2nnf_hash, find_node(CONS, wff, (node_ptr) polarity), nnf);
}
Example #22
0
bool MemoryDump::write_output(const cmd_opt &opt)
{
    try {
        std::ofstream ofile(opt.ofile, std::ofstream::trunc);
        min_size = total_size * opt.threshold;
        if (exporter == nullptr
            || export_type != opt.export_type) {
            delete exporter;
            export_type = opt.export_type;
            switch (export_type) {
            case EXPORT_DOT:
                exporter = new ExporterDot(total_size);
                break;
            case EXPORT_GML:
                exporter = new ExporterGML(total_size);
                break;
            case EXPORT_GRAPHML:
                exporter = new ExporterGraphML();
                break;
            default:
                exporter = new ExporterDot(total_size);
                export_type = EXPORT_DOT;
            }
        }
        else {
            switch (export_type) {
            case EXPORT_DOT:
            case EXPORT_GML:
                exporter->set_total_size(total_size);
                break;
            default:
                break;
            }
        }
        exporter->write_preamble(ofile);
        std::vector<Node*> selected_nodes;
        if (opt.nodes.empty() && opt.labels.empty()) {
            for (const auto &c : top_nodes) {
                selected_nodes.push_back(c.node);
            }
        }
        else {
            /* find the node pointed by opt.node */
            for (const auto &path : opt.nodes) {
                auto node = find_node(path.node);
                if (node == nullptr) {
                    std::cout << "No node found for path " << path.literal << std::endl;
                    continue;
                }
                selected_nodes.push_back(node);
            }

            for (const auto &label : opt.labels) {
                auto node = nodes.find(label);
                if (node != nodes.end()) {
                    std::cout << "Found node by label " << std::hex << label << std::dec << std::endl;
                    selected_nodes.push_back(&node->second);
                }
                else {
                    std::cout << "Label " << std::hex << label << std::dec << " was not found\n";
                }
            }
        }
        std::set<uintptr_t> declared_nodes;
        for (auto & node : selected_nodes) {
            write_node(*node, ofile, opt);
            declared_nodes.insert(node->label);
            draw_tree(*node, ofile, opt, declared_nodes);
        }
        for (auto & node : selected_nodes) {
            clear_visited(*node);
        }

        exporter->write_appendix(ofile);

    }
    catch (...) {
        std::cout << "Unexpected error hanppend while writing output" << std::endl;
    }

    return true;
}
Example #23
0
dnf_tree dnf_tree_make(const_hierarchy input,
                       const_node root,
                       int_list_list variable_mappings,
                       unsigned int *current_map)
{
    register unsigned int ix;
    register unsigned int iy;

    tv_term_list terms;
    dnf_tree result;
    dnf_tree kid_tree;
    int_list pos;
    int_list neg;
    array kids;
    node kid;

    if (NULL == (terms = rdup_tv_term_list(to_tv_dnf(root->constraints)->terms))) {
        return NULL;
    }
    if (NULL == (kids = array_new(dnf_tree_free, dnf_tree_copy))) {
        rfre_tv_term_list(terms);
        return NULL;
    }
    if (NULL == (result = dnf_tree_new(root->type, terms, kids))) {
        rfre_tv_term_list(terms);
        array_free(kids);
        return NULL;
    }

    for (ix = 0; ix < result->terms->sz; ix++) {
        pos = result->terms->arr[ix]->pos;
        neg = result->terms->arr[ix]->neg;
        for (iy = 0; iy < pos->sz; iy++) {
            pos->arr[iy] = variable_mappings->arr[*current_map]->arr[pos->arr[iy]];
        }
        for (iy = 0; iy < neg->sz; iy++) {
            neg->arr[iy] = variable_mappings->arr[*current_map]->arr[neg->arr[iy]];
        }
        result->terms->arr[ix]->pos = sort_int_list(result->terms->arr[ix]->pos);
        result->terms->arr[ix]->neg = sort_int_list(result->terms->arr[ix]->neg);
    }

    *current_map += 1;

    for (ix = 0; ix < root->edges->sz; ix++) {
        if (nodeNIL == (kid = find_node(input, root->edges->arr[ix]->type))) {
            assert(0); /* To Do: To internal error. */
            abort();
            break;
        }
        kid_tree = dnf_tree_make(input, kid, variable_mappings, current_map);
        if (NULL == kid_tree) {
            dnf_tree_free(result);
            return NULL;
        }
        if (!array_append(result->kids, kid_tree)) {
            dnf_tree_free(result);
            dnf_tree_free(kid_tree);
            return NULL;
        }
    }

    return result;
}
Example #24
0
int discrete_sh_start (const struct MachineSound *msound)
{
	struct discrete_sound_block *intf;
	int loop=0,loop2=0,search=0,failed=0;

	/* Initialise */
	intf = msound->sound_interface;
	node_count=0;

	/* Sanity check and node count */
	while(1)
	{
		/* Check the node parameter is a valid node */
		if(intf[node_count].node<NODE_START || intf[node_count].node>NODE_END)
		{
			logerror("discrete_sh_start() - Invalid node number on node %02d descriptor\n",node_count);
			return 1;
		}
		if(intf[node_count].type>DSO_OUTPUT)
		{
			logerror("discrete_sh_start() - Invalid function type on node %02d descriptor\n",node_count);
			return 1;
		}

		/* Node count must include the NULL node as well */
		if(intf[node_count].type==DSS_NULL)
		{
			node_count++;
			break;
		}

		node_count++;

		/* Sanity check */
		if(node_count>DISCRETE_MAX_NODES)
		{
			logerror("discrete_sh_start() - Upper limit of 255 nodes exceeded, have you terminated the interface block.");
			return 1;
		}
	}

	/* Allocate memory for the context array and the node execution order array */
	if((running_order=(struct node_description**)malloc(node_count*sizeof(struct node_description*)))==NULL)
	{
		logerror("discrete_sh_start() - Failed to allocate running order array.\n");
		return 1;
	}
	else
	{
		/* Initialise memory */
		memset(running_order,0,node_count*sizeof(struct node_description*));
	}

	if((node_list=(struct node_description*)malloc(node_count*sizeof(struct node_description)))==NULL)
	{
		logerror("discrete_sh_start() - Failed to allocate context list array.\n");
		return 1;
	}
	else
	{
		/* Initialise memory */
		memset(node_list,0,node_count*sizeof(struct node_description));
	}

	/* Work out the execution order */
	/* FAKE IT FOR THE MOMENT, EXECUTE IN ORDER */
	for(loop=0;loop<node_count;loop++)
	{
		running_order[loop]=&node_list[loop];
	}

	/* Configure the input node pointers, the find_node function wont work without the node ID setup beforehand */
	for(loop=0;loop<node_count;loop++) node_list[loop].node=intf[loop].node;
	failed=0;

	/* Duplicate node number test */
	for(loop=0;loop<node_count;loop++)
	{
		for(loop2=0;loop2<node_count;loop2++)
		{
			if(node_list[loop].node==node_list[loop2].node && loop!=loop2)
			{
				logerror("discrete_sh_start - Node NODE_%02d defined more than once\n",node_list[loop].node-NODE_00);
				failed=1;
			}
		}
	}

	/* Initialise and start all of the objects */
	for(loop=0;loop<node_count;loop++)
	{
		/* Configure the input node pointers */
		node_list[loop].node=intf[loop].node;
		node_list[loop].output=0;
		node_list[loop].input0=intf[loop].initial0;
		node_list[loop].input1=intf[loop].initial1;
		node_list[loop].input2=intf[loop].initial2;
		node_list[loop].input3=intf[loop].initial3;
		node_list[loop].input4=intf[loop].initial4;
		node_list[loop].input5=intf[loop].initial5;
		node_list[loop].input_node0=find_node(intf[loop].input_node0);
		node_list[loop].input_node1=find_node(intf[loop].input_node1);
		node_list[loop].input_node2=find_node(intf[loop].input_node2);
		node_list[loop].input_node3=find_node(intf[loop].input_node3);
		node_list[loop].input_node4=find_node(intf[loop].input_node4);
		node_list[loop].input_node5=find_node(intf[loop].input_node5);
		node_list[loop].name=intf[loop].name;
		node_list[loop].custom=intf[loop].custom;

		/* Check that all referenced nodes have actually been found */
		if(node_list[loop].input_node0==NULL && intf[loop].input_node0>=NODE_START && intf[loop].input_node0<=NODE_END)
		{
			logerror("discrete_sh_start - Node NODE_%02d referenced a non existant node NODE_%02d\n",node_list[loop].node-NODE_00,intf[loop].input_node0-NODE_00);
			failed=1;
		}
		if(node_list[loop].input_node1==NULL && intf[loop].input_node1>=NODE_START && intf[loop].input_node1<=NODE_END)
		{
			logerror("discrete_sh_start - Node NODE_%02d referenced a non existant node NODE_%02d\n",node_list[loop].node-NODE_00,intf[loop].input_node1-NODE_00);
			failed=1;
		}
		if(node_list[loop].input_node2==NULL && intf[loop].input_node2>=NODE_START && intf[loop].input_node2<=NODE_END)
		{
			logerror("discrete_sh_start - Node NODE_%02d referenced a non existant node NODE_%02d\n",node_list[loop].node-NODE_00,intf[loop].input_node2-NODE_00);
			failed=1;
		}
		if(node_list[loop].input_node3==NULL && intf[loop].input_node3>=NODE_START && intf[loop].input_node3<=NODE_END)
		{
			logerror("discrete_sh_start - Node NODE_%02d referenced a non existant node NODE_%02d\n",node_list[loop].node-NODE_00,intf[loop].input_node3-NODE_00);
			failed=1;
		}
		if(node_list[loop].input_node4==NULL && intf[loop].input_node4>=NODE_START && intf[loop].input_node4<=NODE_END)
		{
			logerror("discrete_sh_start - Node NODE_%02d referenced a non existant node NODE_%02d\n",node_list[loop].node-NODE_00,intf[loop].input_node4-NODE_00);
			failed=1;
		}
		if(node_list[loop].input_node5==NULL && intf[loop].input_node5>=NODE_START && intf[loop].input_node5<=NODE_END)
		{
			logerror("discrete_sh_start - Node NODE_%02d referenced a non existant node NODE_%02d\n",node_list[loop].node-NODE_00,intf[loop].input_node5-NODE_00);
			failed=1;
		}

		/* Try to find the simulation module in the module list table */
		search=0;
		while(1)
		{
			if(module_list[search].type==intf[loop].type)
			{
				node_list[loop].module=search;
				if(module_list[search].init)
					if(((*module_list[search].init)(&node_list[loop]))==1) failed=1;
				break;
			}
			else if(module_list[search].type==DSS_NULL)
			{
				if(intf[loop].type==DSS_NULL) break;
				else
				{
					logerror("discrete_sh_start() - Invalid DSS/DST/DSO module type specified in interface, item %02d\n",loop+1);
					failed=1;
					break;
				}
			}
			search++;
		}
	}
	/* Setup the output node */
	if((output_node=find_node(NODE_OP))==NULL)
	{
		logerror("discrete_sh_start() - Counldnt find an output node");
		failed=1;
	}

	/* Different setup for Mono/Stereo systems */
	if ((Machine->drv->sound_attributes&SOUND_SUPPORTS_STEREO) == SOUND_SUPPORTS_STEREO)
	{
		int vol[2];
		const char *stereo_names[2] = { "Discrete Left", "Discrete Right" };
		vol[0] = output_node->input2;
		vol[1] = output_node->input2;
		/* Initialise a stereo, stream, we always use stereo even if only a mono system */
		discrete_stream=stream_init_multi(2,stereo_names,vol,Machine->sample_rate,0,discrete_stream_update_stereo);
		discrete_stereo=1;
	}
	else
	{
		int vol;
		vol = output_node->input2;
		/* Initialise a stereo, stream, we always use stereo even if only a mono system */
		discrete_stream=stream_init("Discrete Sound",vol,Machine->sample_rate,0,discrete_stream_update_mono);
	}

	if(discrete_stream==-1)
	{
		logerror("discrete_sh_start - Stream init returned an error\n");
		failed=1;
	}

	/* Report success or fail */
	if(!failed) init_ok=1;
	return failed;
}
bool bst_contains(BST *tree, int item) {
  return (find_node(tree, item) != NULL);
}
Example #26
0
File: ini.c Project: vaughan0/vlib
const char* ini_lookup(INI* self, const char* section, const char* key) {
  INI_Node* snode = find_node(&self->root, section, 0);
  if (!snode) return NULL;
  INI_Node* dnode = find_node((INI_Node**)&snode->data, key, 0);
  return dnode ? dnode->data : NULL;
}
Example #27
0
/*
 * Add RPID element into existing PIDF document.
 */
PJ_DEF(pj_status_t) pjrpid_add_element(pjpidf_pres *pres, 
				       pj_pool_t *pool,
				       unsigned options,
				       const pjrpid_element *elem)
{
    pj_xml_node *nd_person, *nd_activities, *nd_activity, *nd_note;
    pj_xml_attr *attr;

    PJ_ASSERT_RETURN(pres && pool && options==0 && elem, PJ_EINVAL);

    PJ_UNUSED_ARG(options);

    /* Check if we need to add RPID information into the PIDF document. */
    if (elem->id.slen==0 && 
	elem->activity==PJRPID_ACTIVITY_UNKNOWN &&
	elem->note.slen==0)
    {
	/* No RPID information to be added. */
	return PJ_SUCCESS;
    }

    /* Add <note> to <tuple> */
    if (elem->note.slen != 0) {
	pj_xml_node *nd_tuple;

	nd_tuple = find_node(pres, "tuple");

	if (nd_tuple) {
	    nd_note = pj_xml_node_new(pool, &NOTE);
	    pj_strdup(pool, &nd_note->content, &elem->note);
	    pj_xml_add_node(nd_tuple, nd_note);
	    nd_note = NULL;
	}
    }

    /* Update namespace */
    update_namespaces(pres, pool);

    /* Add <person> */
    nd_person = pj_xml_node_new(pool, &DM_PERSON);
    if (elem->id.slen != 0) {
	attr = pj_xml_attr_new(pool, &ID, &elem->id);
    } else {
	pj_str_t person_id;
	/* xs:ID must start with letter */
	//pj_create_unique_string(pool, &person_id);
	person_id.ptr = (char*)pj_pool_alloc(pool, PJ_GUID_STRING_LENGTH+2);
	person_id.ptr += 2;
	pj_generate_unique_string(pool->factory->inst_id, &person_id);
	person_id.ptr -= 2;
	person_id.ptr[0] = 'p';
	person_id.ptr[1] = 'j';
	person_id.slen += 2;

	attr = pj_xml_attr_new(pool, &ID, &person_id);
    }
    pj_xml_add_attr(nd_person, attr);
    pj_xml_add_node(pres, nd_person);

    /* Add <activities> */
    nd_activities = pj_xml_node_new(pool, &RPID_ACTIVITIES);
    pj_xml_add_node(nd_person, nd_activities);

    /* Add the activity */
    switch (elem->activity) {
    case PJRPID_ACTIVITY_AWAY:
	nd_activity = pj_xml_node_new(pool, &RPID_AWAY);
	break;
    case PJRPID_ACTIVITY_BUSY:
	nd_activity = pj_xml_node_new(pool, &RPID_BUSY);
	break;
    case PJRPID_ACTIVITY_UNKNOWN:
    default:
	nd_activity = pj_xml_node_new(pool, &RPID_UNKNOWN);
	break;
    }
    pj_xml_add_node(nd_activities, nd_activity);

    /* Add custom text if required. */
    if (elem->note.slen != 0) {
	nd_note = pj_xml_node_new(pool, &DM_NOTE);
	pj_strdup(pool, &nd_note->content, &elem->note);
	pj_xml_add_node(nd_person, nd_note);
    }

    /* Done */
    return PJ_SUCCESS;
}
Example #28
0
/*this fucntion is already serialized in the function that calls this 
  so from here on out there is no worry about locking*/
gasnete_coll_local_tree_geom_t *gasnete_coll_tree_geom_create_local(gasnete_coll_tree_type_t in_type, int rootrank, gasnete_coll_team_t team, gasnete_coll_tree_geom_t *base_geom)  {
  gasnete_coll_local_tree_geom_t *geom;
  int i;
  gasnete_coll_tree_type_t intype_copy;
  tree_node_t *allnodes = (tree_node_t*) team->tree_construction_scratch;
  tree_node_t rootnode,mynode;
  gasneti_assert(rootrank<team->total_ranks && rootrank >=0);
  gasneti_assert_always(in_type);
  intype_copy = in_type;
  geom = (gasnete_coll_local_tree_geom_t*)gasneti_malloc(sizeof(gasnete_coll_local_tree_geom_t));
  gasneti_assert_always(in_type==intype_copy);
  
  switch (in_type->tree_class) {
#if 1
  case GASNETE_COLL_NARY_TREE:
      gasneti_assert(in_type->num_params ==1);
      allnodes =  allocate_nodes((tree_node_t**) &team->tree_construction_scratch, team, rootrank);
      rootnode = make_nary_tree(allnodes, team->total_ranks, in_type->params[0]);
       geom->rotation_points = (int*) gasneti_malloc(sizeof(int)*1);
       geom->num_rotations = 1;
       geom->rotation_points[0] = rootrank;
      break;
    case GASNETE_COLL_KNOMIAL_TREE:
      gasneti_assert(in_type->num_params ==1);
       allnodes = allocate_nodes((tree_node_t**) &team->tree_construction_scratch, team, rootrank);
      rootnode = make_knomial_tree(allnodes, team->total_ranks, in_type->params[0]);
       geom->rotation_points = (int*) gasneti_malloc(sizeof(int)*1);
       geom->num_rotations = 1;
       geom->rotation_points[0] = rootrank;
      break;
    case GASNETE_COLL_FLAT_TREE:
      allocate_nodes((tree_node_t**) &team->tree_construction_scratch , team, rootrank);
      rootnode = make_flat_tree(team->tree_construction_scratch, team->total_ranks);
      geom->rotation_points = (int*) gasneti_malloc(sizeof(int)*1);
      geom->num_rotations = 1;
      geom->rotation_points[0] = rootrank;
      break;
    case GASNETE_COLL_RECURSIVE_TREE:
      gasneti_assert(in_type->num_params ==1);
      allnodes = allocate_nodes((tree_node_t**) &team->tree_construction_scratch, team, rootrank);
      rootnode = make_recursive_tree(allnodes, team->total_ranks, in_type->params[0]);
      geom->rotation_points = (int*) gasneti_malloc(sizeof(int)*1);
      geom->num_rotations = 1;
      geom->rotation_points[0] = rootrank;
      break;
    case GASNETE_COLL_FORK_TREE:
      allnodes = allocate_nodes((tree_node_t**) &team->tree_construction_scratch, team, rootrank);
      rootnode = make_fork_tree(allnodes, team->total_ranks, in_type->params, in_type->num_params);
       geom->rotation_points = (int*) gasneti_malloc(sizeof(int)*1);
       geom->num_rotations = 1;
       geom->rotation_points[0] = rootrank;
      break;
    case GASNETE_COLL_HIERARCHICAL_TREE:
#if 0
      allnodes = team->tree_construction_scratch = allocate_nodes(allnodes, team, 0);
      rootnode = make_hiearchical_tree(in_type, allnodes, team->total_ranks);
       /* XXX ADD CODE TO GET ROTATION POINTS*/
      break;
#else
       gasneti_fatalerror("HIERARCHICAL_TREE not yet fully supported");
#endif
#endif
    default:
       gasneti_fatalerror("unknown tree type");
      break;
  }
  
  rootnode = setparents(rootnode);
  mynode = find_node(rootnode, team->myrank);

  geom->root = rootrank;
  geom->tree_type = in_type;
  geom->total_size = team->total_ranks;
  geom->parent = GET_PARENT_ID(mynode);
  geom->child_count = GET_NUM_CHILDREN(mynode);
  geom->mysubtree_size = treesize(mynode);
  geom->parent_subtree_size = treesize(mynode->parent);
  geom->children_reversed = mynode->children_reversed;
  if(rootrank != team->myrank) {
    geom->num_siblings = GET_NUM_CHILDREN(mynode->parent);
    geom->sibling_id = -1;
    geom->sibling_offset = 0;
    for(i=0; i<geom->num_siblings; i++) {
      int tmp_id;
      if(mynode->parent->children_reversed==1) {
        tmp_id = geom->num_siblings-1-i;
      } else {
        tmp_id =i;
      }
      if(GET_NODE_ID(GET_CHILD_IDX(mynode->parent, tmp_id))==team->myrank) {
        geom->sibling_id = tmp_id;
        break;
      } else {
        geom->sibling_offset += treesize(GET_CHILD_IDX(mynode->parent, tmp_id));
      }
    }
  } else {
    geom->num_siblings = 0;
    geom->sibling_id = 0;
    geom->sibling_offset = 0;
    /***** THIS NEEDS TO BE TAKEN OUT
      The DFS ordering that we impose on the trees will mean that this no longer needs to be kept around
      but it's in here for now for backward compatability sake until we make the neccessary changes to all the other collective algorithms
      ****/
    geom->dfs_order = (gasnet_node_t*) gasneti_malloc(sizeof(gasnet_node_t)*team->total_ranks);
    for(i=0; i<team->total_ranks; i++) {
      geom->dfs_order[i] = (i+rootrank)%team->total_ranks;
    }
  }
  geom->seq_dfs_order = 1;
  geom->child_list = (gasnet_node_t*) gasneti_malloc(sizeof(gasnet_node_t)*geom->child_count);
  geom->subtree_sizes = (gasnet_node_t*) gasneti_malloc(sizeof(gasnet_node_t)*geom->child_count);
  geom->child_offset = (gasnet_node_t*) gasneti_malloc(sizeof(gasnet_node_t)*geom->child_count);
  geom->grand_children = (gasnet_node_t*)gasneti_malloc(sizeof(gasnet_node_t)*geom->child_count); 
  geom->num_non_leaf_children=0;
  geom->num_leaf_children=0;
  geom->child_contains_wrap = 0;
  for(i=0; i<geom->child_count; i++) {
    geom->child_list[i] = GET_NODE_ID(GET_CHILD_IDX(mynode,i));
    geom->subtree_sizes[i] = treesize(GET_CHILD_IDX(mynode,i));
    geom->grand_children[i] = GET_NUM_CHILDREN(GET_CHILD_IDX(mynode, i));
    if(geom->subtree_sizes[i] > 1) {
      geom->num_non_leaf_children++;
    } else {
      geom->num_leaf_children++;
    }
    if(geom->child_list[i]+geom->subtree_sizes[i] > geom->total_size) {
      geom->child_contains_wrap = 1;
    }
    
  }
  gasneti_assert((geom->num_leaf_children+geom->num_non_leaf_children) == geom->child_count);
  
  if(mynode->children_reversed==1) {
    size_t temp_offset = 0;
    for(i=geom->child_count-1; i>=0; i--) {
      geom->child_offset[i] = temp_offset; 
      temp_offset+=geom->subtree_sizes[i];
    }
  } else {
    size_t temp_offset = 0;
    for(i=0; i<geom->child_count; i++) {
      geom->child_offset[i] = temp_offset; 
      temp_offset+=geom->subtree_sizes[i];
    }
  }

#if 0
  /* Not using the reference counts for now */
  gasneti_weakatomic_set(&(geom->ref_count), 0, 0);
  geom->base_geom = base_geom;
#endif

#if 0  
  gasnete_coll_print_tree(geom, gasneti_mynode);
#endif
  return geom;
}
Example #29
0
/*---------------------------------------------------------------------------*/
void
nodes_set_leds(int x, int y, int leds)
{
  find_node(x, y)->leds = leds;
}
Example #30
0
int main(void) 
{
	int i;
	DARR *sturoot;

   if ((sturoot = load_darr("db.db")) == NULL){
      printf("load db error.\n");
      if ((sturoot = create_darr(sizeof(struct stu))) == NULL) {
         printf("create date error.\n");
         return -1; 
      }   
   }   

	/* 
	** 0,q for exit; 1,f for find; 2, i for insert; 3,d for delete, 4, l for list, 5, e for erase;
	** 6, a for delete duplication; 7, u for update, 8, s for sort, 9 for Save data, @ for Load data;
	*/
	while ((i = read_select()) != '0' && i != 'q' && i != 'Q')			/* 主循环,获取控制输入*/
		switch (i){
		case '1': case 'F': case 'f':
				printf("Please enter the search condition: [ID],[Name],[Scope]\n");
				{
					struct stu tmp, *ret;
					if (getline(&tmp) == 0) {
						printf("Input Format wrong!\n");
					} else if ((ret =(struct stu *)find_node(sturoot,&tmp,cmp)) == NULL)
						printf("Record is not exist!");
					else
						print_node(ret);
				}
				any_key();
				break;
		case '2': case 'I': case 'i':
				if (sturoot == NULL) {
					printf("Datebase is empty, System will re-create it.\n");
      			if ((sturoot = create_darr(sizeof(struct stu))) == NULL) {
         			printf("DB is empty,create date error.\n");
         			return -1; 
      			}
				}	   
				printf("Please enter the new record: 'ID,Name,Scope:'\n");
				{
					struct stu tmp;
					if (getline(&tmp) == 0) 
						printf("Input Format wrong!\n");
					else if (inserd_node(sturoot,&tmp,0) == -1)
						printf("Input Error!");
					else
						printf("Insert OK!");
				}
				any_key();
				break;
		case '3': case 'D': case 'd':
				printf("Please enter the condition : [ID],[Name],[Scope]\n");
				{
					struct stu tmp;
					if (getline(&tmp) == 0) 
						printf("Input Format wrong!");
					else
						delete_node(sturoot,&tmp, &cmp);
				}
				any_key();
				break;
		case '4': case 'L': case 'l':
				travel(sturoot,print_node);
				any_key();
				break;
		case '5': case 'E': case 'e':
				erase(sturoot);
				printf("All data has erase!!");
				sturoot = NULL;
				any_key();
				break;
#if 0
		case '6': case 'A': case 'a':
				printf("Please enter the condition: [ID],[Name],[Scope]\n");
				{
					struct stu tmp;
					if (getline(&tmp) == 0) {
						printf("Input Format wrong!");
					} else if (delete(&sturoot, &tmp, DELETE_ALL_YES) == 0)
						printf("Record is not exist!");
				}
				any_key();
				break;
#endif
		case '7': case 'U': case 'u':
				{
					struct stu tmp_from, tmp_to, *tmp_find;
					printf("Please enter the condition: [ID],[Name],[Scope]\n");
					if (getline(&tmp_from) == 0) {
						printf("Input Format wrong!");
					} else if ((tmp_find = (struct stu *)find_node(sturoot,&tmp_from,cmp)) != NULL) {
						print_node(tmp_find);
						printf("Please enter the new data: [ID],[Name],[Scope]\n");
						if (getline(&tmp_to) == 0) 
							printf("Input Format wrong!");
						else if (update_node(tmp_find, &tmp_to) == 0)
							printf("Update Succeed.");
					} else 
							printf("Record is not exist!");
				}
				any_key();
				break;
		case '8': case 'S': case 's':
				{
					int sel;
					int (*fun)(const void *, const void*);
					printf("Please select sort by:\n1[by ID]\t2[by name]\t3[by scope]:");
					if ((sel=get_num()) <= 3 && sel >= 1) {
						switch (sel) {
							case 1:
								fun = cmp_id;
								break;
							case 2:
								fun = cmp_name;
								break;
							case 3:
								fun = cmp_scope;
								break;
						}
						darr_sort(sturoot,fun);
						printf("Sort Succeed.");
					} else
						printf("Select wrong.");
				}
				any_key();
				break;
		case '9':
				if (save_darr(sturoot, "db.db") == -1)
					fprintf(stderr, "Open file failed.\n");
				any_key();
				break;
		default:
				break;
		}

	return 0;
}