示例#1
0
boolean_e formatDosToAmiga( fileplayer_s *players_file )
{
     clearErrorMessage();

     for ( int i = 0; i < TOTAL_PLAYERS; ++i )
     {
	  if ( EMPTY( players_file[i].last_name ) ) continue;

          unsigned int pos = nibble( players_file[i].position[0], n_High );

          if   ( pos != fpos_Pitcher )
          {
               acc_bat_stats_s *action = &(players_file[i].acc_stats.action.batting);

               if ( byte2int( action->acc_rbi ) >= STAT_CAP_AMOUNT ||
                    byte2int( action->acc_so  ) >= STAT_CAP_AMOUNT    )
               {
                    acc_pch_stats_s *pch = &(players_file[i].acc_stats.simulated.pitching);

                    unsigned int act_inn  = word2int( pch->acc_innings );
                    unsigned int act_hits = word2int( pch->acc_hits    );

                    if ( act_inn > 0  ||  act_hits > 0 )
                    {
                         sprintf( error_message, "ERROR: Player %.*s, %.*s requires overflow and has pitching stats.",
                                  sizeof(players_file[i].last_name),  players_file[i].last_name,
                                  sizeof(players_file[i].first_name), players_file[i].first_name );

                         return bl_False;
                    }
               }

               acc_stats_s *acc_stats = &(players_file[i].acc_stats);

               acc_stats_u sim = acc_stats->simulated;

               acc_stats->simulated = acc_stats->action;
               acc_stats->action    = sim;

               capStat( acc_stats->simulated.batting.acc_rbi, acc_stats->action.batting.acc_rbi );
               capStat( acc_stats->simulated.batting.acc_so,  acc_stats->action.batting.acc_so  );
          }
          else
          {
               acc_bat_stats_s *act = &(players_file[i].acc_stats.action.batting);
               acc_pch_stats_s *sim = &(players_file[i].acc_stats.simulated.pitching);

               unsigned char games = act->acc_games[0];

               act->acc_games[0] = 0;

               sim->acc_starts[0] = games;
          }

          acc_player_id_s *id_info = &(players_file[i].acc_stats.action.id_info);

          int player_id = word2int( id_info->player_id );

          if ( player_id == 0  ||  calcChecksum( player_id ) != byte2int( id_info->checksum ) )
          {
               sprintf( error_message, "ERROR: Player %.*s, %.*s has a player id checksum mismatch.",
                        sizeof(players_file[i].last_name),  players_file[i].last_name,
                        sizeof(players_file[i].first_name), players_file[i].first_name );

               return bl_False;
          }
     }

     return bl_True;
}
示例#2
0
文件: table.c 项目: sharugupta/OpenUH
static void
write_get_option (void)
{
	int i, j;
	FILE *f;
	f = begin_file("get_option.i");
	fprintf(f, "/* return option index */\n");
	fprintf(f, "extern int\n");
	fprintf(f, "get_option(int *argi, char *argv[])\n");
	fprintf(f, "{\n");
	fprintf(f, "/* don't reset optargs, as may contain needed info */\n");
	fprintf(f, "optargd = 0;\n");
	fprintf(f, "switch (argv[*argi][optindex]) {\n");
	i = 0;
	while (i < num_options) {
		if (options[i].internal) {
			/* skip */
			i++;
			continue;
		}
		if (find_by_flag(options[i].flag, i))
			continue;
		if (options[i].name[1] == '\0')	/* special case "-" */
			fprintf(f, "case '\\0':\n");
		else
			fprintf(f, "case '%c':\n", options[i].name[1]);
		while (1) {
		    switch (options[i].syntax) {
		    case normal:
		    	fprintf(f, "\tif (strcmp(argv[*argi],\"%s\") == 0) {\n",
				options[i].name);
			fprintf(f, "\t\tget_next_arg(argi);\n");
			fprintf(f, "\t\treturn %s;\n", options[i].flag);
			fprintf(f, "\t\t/* NOTREACHED */\n");
			fprintf(f, "\t}\n");
			break;
		    case oneletter:
			fprintf(f, "\tget_next_char(argv, argi);\n");
			fprintf(f, "\treturn %s;\n", options[i].flag);
			fprintf(f, "\t/* NOTREACHED */\n");
			break;
		    case oneletter_space:
		    case multiletter_space:
			if (options[i].syntax == multiletter_space) {
				char *temp = string_copy(options[i].name);
				int nil_index = options[i].num_letters+1;
				temp[nil_index] = NIL;
				fprintf(f, "\tif ((strncmp(argv[*argi],\"%s\",%d) == 0)\n",
					temp, nil_index);
				fprintf(f, "\t&& strcmp(next_string_after(\"%s\",argv,argi),\"%s\") == 0) {\n",
				    temp, options[i].name+nil_index);
				fprintf(f, "\t\tend_option(argv, argi, %d);\n", nil_index);
			} else {
				fprintf(f, "\tif (strcmp(next_string(argv,argi), \"%s\") == 0) {\n",
					options[i].name+2);
			}
			fprintf(f, "\t\toptargs = get_optarg(argv,argi);\n");
			fprintf(f, "\t\tget_next_arg(argi);\n");
			fprintf(f, "\t\treturn %s;\n", options[i].flag);
			fprintf(f, "\t\t/* NOTREACHED */\n");
			fprintf(f, "\t}\n");
			break;
		    case needs_string_or_dash:
		    case needs_string:
		    case needs_directory:
		    case needs_decimal:
		    case needs_directory_or_null:
			/* require this to be a separate arg */
			fprintf(f, "\tif (!is_new_arg) break;\n");
			/* for cases where base is > 1 letter,
			 * check that whole string matches */
			if (strlen(options[i].name) > 2) {
				fprintf(f, "\tif (strncmp(argv[*argi],\"%s\",%ld) == 0) {\n",
				    options[i].name, (long)strlen(options[i].name));
				fprintf(f, "\t\tend_option(argv, argi, %ld);\n",
					(long)strlen(options[i].name));
			} /* else -<single-letter> */
			if (options[i].syntax == needs_decimal) {
				fprintf(f, "\tif (is_decimal(next_string(argv,argi))) {\n");
			} else if (options[i].syntax == needs_directory
				   || options[i].syntax == needs_directory_or_null
				   ) {
			  fprintf(f, "\tif (!is_directory(next_string(argv,argi)) && fullwarn)\n");
			  fprintf(f, "\t\twarning(\"%%s is not a directory\", next_string(argv,argi));\n");
			  fprintf(f, "\tif (strcmp(next_string(argv,argi),\"-default_options\")) {\n" );

			}
			fprintf(f, "\t\toptargs = get_optarg(argv, argi);\n");
			if (options[i].syntax == needs_decimal) {
				fprintf(f, "\t\toptargd = atoi(optargs);\n");
			}
			fprintf(f, "\t\tget_next_arg(argi);\n");
			if (options[i].syntax == needs_string_or_dash)
			  fprintf(f, "\t\treturn add_string_option_or_dash(%s,optargs);\n", 
				  options[i].flag);
			else if (options[i].syntax == needs_directory)
			  fprintf(f, "\t\treturn add_any_string_option(%s,optargs);\n", 
				  options[i].flag);
			else
			  fprintf(f, "\t\treturn add_string_option(%s,optargs);\n", 
				  options[i].flag);
			fprintf(f, "\t\t/* NOTREACHED */\n");
			if (options[i].syntax != needs_string
			    && options[i].syntax != needs_string_or_dash
					) {
				fprintf(f, "\t}\n");
			}
			if (strlen(options[i].name) > 2) {
				fprintf(f, "\t}\n");
			}
			break;
		    case complicated:
			/* for cases where base is > 1 letter,
			 * check that whole string matches */
			if (strlen(options[i].name) > 2) {
				fprintf(f, "\tif (strncmp(argv[*argi],\"%s\",%ld) == 0) {\n",
				    options[i].name, (long)strlen(options[i].name));
			}
			fprintf(f, "\t\treturn parse_%s_option(argv, argi);\n",
				options[i].name+1);
			fprintf(f, "\t\t/* NOTREACHED */\n");
			if (strlen(options[i].name) > 2) {
				fprintf(f, "\t}\n");
			}
			break;
		    }
		    if (i+1 < num_options 
			&& options[i+1].name[1] == options[i].name[1])
		    { 
			/* stay within the case stm */
			i++;
		    } else {
			break;	/* goto next case */
		    }
		}
		fprintf(f, "\tbreak;\n");
		i++;
	}
	fprintf(f, "}\n");
	fprintf(f, "optargs = current_string(argv,argi);\n");
	fprintf(f, "get_next_arg(argi);\n");
	fprintf(f, "return O_Unrecognized;\n");
	fprintf(f, "}\n");

	/* now write alias routine */
	fprintf(f, "/* if alias, return real option index */\n");
	fprintf(f, "extern int\n");
	fprintf(f, "get_real_option_if_aliased(int flag)\n");
	fprintf(f, "{\n");
	fprintf(f, "  switch (flag) {\n");
	for (i = 0; i < num_options; i++) {
	    /* alias is option with:
	     * no action, one implies, all langs, no phases.
	     */
	    if (options[i].languages == get_language_mask(L_ALL)
		&& options[i].phases == 0
		&& EMPTY(options[i].action)
		&& options[i].implies != NULL
		&& options[i].implies->next == NULL)
	    {
		j = options[i].implies->info_index;
		if (options[i].syntax == normal
		 || options[i].syntax == oneletter)
		{
			if (options[j].syntax == normal) {
				fprintf(f, "\tcase %s: return %s;\n", 
					options[i].flag, 
					options[j].flag);
			}
			else if (options[j].syntax == needs_string ||
				 options[j].syntax == needs_string_or_dash) {
				fprintf(f, "\tcase %s: {\n", options[i].flag);
				fprintf(f, "\t\toptargs = \"%s\";\n",
					options[i].implies->name 
					  + strlen(options[j].name));
				fprintf(f, "\t\treturn add_string_option(%s,optargs);\n",
					options[j].flag);
				fprintf(f, "\t\t}\n");
			}
			else continue;	/* don't know how to handle */
		}
		else if (options[i].syntax == options[j].syntax) {
			/* will catch this on derived case */
			fprintf(f, "\tcase %s: return %s;\n", 
				options[i].flag, 
				options[j].flag);
		}
		else continue;	/* don't know how to handle */
	    }
	}
	fprintf(f, "\tdefault: return flag;\n");
	fprintf(f, "  }\n");
	fprintf(f, "}\n");
	fclose(f);
}
示例#3
0
ISC_TIMERFUNC_SCOPE void
isc__timermgr_destroy(isc_timermgr_t **managerp) {
	isc__timermgr_t *manager;
	isc_mem_t *mctx;

	/*
	 * Destroy a timer manager.
	 */

	REQUIRE(managerp != NULL);
	manager = (isc__timermgr_t *)*managerp;
	REQUIRE(VALID_MANAGER(manager));

	LOCK(&manager->lock);

#ifdef USE_SHARED_MANAGER
	manager->refs--;
	if (manager->refs > 0) {
		UNLOCK(&manager->lock);
		*managerp = NULL;
		return;
	}
	timermgr = NULL;
#endif /* USE_SHARED_MANAGER */

#ifndef USE_TIMER_THREAD
	isc__timermgr_dispatch((isc_timermgr_t *)manager);
#endif

	REQUIRE(EMPTY(manager->timers));
	manager->done = ISC_TRUE;

#ifdef USE_TIMER_THREAD
	XTRACE(isc_msgcat_get(isc_msgcat, ISC_MSGSET_TIMER,
			      ISC_MSG_SIGNALDESTROY, "signal (destroy)"));
	SIGNAL(&manager->wakeup);
#endif /* USE_TIMER_THREAD */

	UNLOCK(&manager->lock);

#ifdef USE_TIMER_THREAD
	/*
	 * Wait for thread to exit.
	 */
	if (isc_thread_join(manager->thread, NULL) != ISC_R_SUCCESS)
		UNEXPECTED_ERROR(__FILE__, __LINE__,
				 "isc_thread_join() %s",
				 isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL,
						ISC_MSG_FAILED, "failed"));
#endif /* USE_TIMER_THREAD */

	/*
	 * Clean up.
	 */
#ifdef USE_TIMER_THREAD
	(void)isc_condition_destroy(&manager->wakeup);
#endif /* USE_TIMER_THREAD */
	DESTROYLOCK(&manager->lock);
	isc_heap_destroy(&manager->heap);
	manager->common.impmagic = 0;
	manager->common.magic = 0;
	mctx = manager->mctx;
	isc_mem_put(mctx, manager, sizeof(*manager));
	isc_mem_detach(&mctx);

	*managerp = NULL;

#ifdef USE_SHARED_MANAGER
	timermgr = NULL;
#endif
}
示例#4
0
文件: lqmult.c 项目: hrautila/armas
/*
 * Blocked version for computing C = C*Q and C = C*Q.T from elementary reflectors
 * and scalar coefficients.
 *
 * Elementary reflectors and scalar coefficients are used to build block reflector T.
 * Matrix C is updated by applying block reflector T using compact WY algorithm.
 */
static int
__blk_lqmult_right(armas_x_dense_t *C, armas_x_dense_t *A, armas_x_dense_t *tau,
                   armas_x_dense_t *T, armas_x_dense_t *W, int flags, int lb, armas_conf_t *conf)
{
  armas_x_dense_t ATL, ABR, A00, A11, A12, A21, A22, AR, *Aref;
  armas_x_dense_t tT, tB, t0, t1, t2, Tcur, Wrk;
  armas_x_dense_t CL, CR, C0, C1, C2;
  int pAdir, pAstart, pStart, pDir, pCstart, pCdir;
  int mb, nb, cb, tb, transpose ;

  EMPTY(A00); EMPTY(C0); EMPTY(CL);

  if (flags & ARMAS_TRANS) {
    // from top-left to bottom-right to produce transpose sequence (C*Q.T)
    pAstart = ARMAS_PTOPLEFT;
    pAdir   = ARMAS_PBOTTOMRIGHT;
    pStart  = ARMAS_PTOP;
    pDir    = ARMAS_PBOTTOM;
    pCstart = ARMAS_PLEFT;
    pCdir   = ARMAS_PRIGHT;
    mb = cb = tb = nb = 0;
    Aref = &ABR;
    transpose = TRUE;
  } else {
    // from bottom-right to top-left to produce normal sequence (C*Q)
    pAstart = ARMAS_PBOTTOMRIGHT;
    pAdir   = ARMAS_PTOPLEFT;
    pStart  = ARMAS_PBOTTOM;
    pDir    = ARMAS_PTOP;
    pCstart = ARMAS_PRIGHT;
    pCdir   = ARMAS_PLEFT;
    mb = max(0, A->rows - A->cols);
    nb = max(0, A->cols - A->rows);
    cb = max(0, C->cols - A->rows);
    tb = max(0, armas_x_size(tau) - min(A->rows, A->cols));
    Aref = &ATL;
    transpose = FALSE;
  }

  __partition_2x2(&ATL,  __nil,
                  __nil, &ABR,  /**/  A, mb, nb, pAstart);
  __partition_1x2(&CL, &CR,     /**/  C, cb, pCstart);
  __partition_2x1(&tT, 
                  &tB,   /**/  tau, tb, pStart);
                 
  while (Aref->rows > 0 && Aref->cols > 0) {
    __repartition_2x2to3x3(&ATL,
                           &A00,  __nil, __nil,
                           __nil, &A11,  &A12,
                           __nil, &A21,  &A22,  /**/  A, lb, pAdir);
    __repartition_2x1to3x1(&tT,
                           &t0,
                           &t1,
                           &t2,     /**/ tau, lb, pDir);
    __repartition_1x2to1x3(&CL,
                           &C0, &C1, &C2, /**/ C, A11.cols, pCdir);
    // ---------------------------------------------------------------------------
    // build block reflector
    __merge1x2(&AR, &A11, &A12);
    armas_x_submatrix(&Tcur, T, 0, 0, A11.cols, A11.cols);
    armas_x_mscale(&Tcur, 0.0, ARMAS_ANY);
    __unblk_lq_reflector(&Tcur, &AR, &t1, conf);

    // compute Q*C or Q.T*C
    armas_x_submatrix(&Wrk, W, 0, 0, C1.rows, A11.cols);
    __update_lq_right(&C1, &C2, &A11, &A12, &Tcur, &Wrk, transpose, conf);
    // ---------------------------------------------------------------------------
    __continue_3x3to2x2(&ATL,  __nil,
                        __nil, &ABR, /**/  &A00, &A11, &A22,   A, pAdir);
    __continue_1x3to1x2(&CL, &CR,    /**/  &C0,  &C1,   C,   pCdir);
    __continue_3x1to2x1(&tT,
                        &tB,  /**/  &t0,  &t1,   tau, pDir);
  }
  return 0;
}
示例#5
0
void hud_scrollback_do_frame(float frametime)
{
	int i, k, x, y;
	int font_height = gr_get_font_height();

	k = Ui_window.process();
	switch (k) {
		case KEY_RIGHT:
		case KEY_TAB:
			if (Scrollback_mode == SCROLLBACK_MODE_OBJECTIVES) {
				Scrollback_mode = SCROLLBACK_MODE_MSGS_LOG;
				Scroll_max = hud_query_scrollback_size();
				hud_scroll_reset();

			} else if (Scrollback_mode == SCROLLBACK_MODE_MSGS_LOG) {
				Scrollback_mode = SCROLLBACK_MODE_EVENT_LOG;
				Scroll_max = Num_log_lines * gr_get_font_height();
				hud_scroll_reset();

			} else {
				Scrollback_mode = SCROLLBACK_MODE_OBJECTIVES;
				Scroll_max = Num_obj_lines * gr_get_font_height();
				Scroll_offset = 0;
			}

			break;

		case KEY_LEFT:
		case KEY_SHIFTED | KEY_TAB:
			if (Scrollback_mode == SCROLLBACK_MODE_OBJECTIVES) {
				Scrollback_mode = SCROLLBACK_MODE_EVENT_LOG;
				Scroll_max = Num_log_lines * gr_get_font_height();
				hud_scroll_reset();

			} else if (Scrollback_mode == SCROLLBACK_MODE_MSGS_LOG) {
				Scrollback_mode = SCROLLBACK_MODE_OBJECTIVES;
				Scroll_max = Num_obj_lines * gr_get_font_height();
				Scroll_offset = 0;

			} else {
				Scrollback_mode = SCROLLBACK_MODE_MSGS_LOG;
				Scroll_max = hud_query_scrollback_size();
				hud_scroll_reset();
			}

			break;

		case KEY_PAGEUP:
			hud_page_scroll_list(1);
			break;

		case KEY_PAGEDOWN:
			hud_page_scroll_list(0);
			break;

		case KEY_ENTER:
		case KEY_CTRLED | KEY_ENTER:
		case KEY_ESC:			
			hud_scrollback_exit();
			break;

		case KEY_F1:  // show help overlay
			break;

		case KEY_F2:  // goto options screen
			gameseq_post_event(GS_EVENT_OPTIONS_MENU);
			break;
	}	// end switch

	for (i=0; i<NUM_BUTTONS; i++){
		if (Buttons[gr_screen.res][i].button.pressed()){
			hud_scrollback_button_pressed(i);		
		}
	}

	GR_MAYBE_CLEAR_RES(Background_bitmap);
	if (Background_bitmap >= 0) {
		gr_set_bitmap(Background_bitmap);
		gr_bitmap(0, 0);
	}

	/*
	if ((Scrollback_mode == SCROLLBACK_MODE_OBJECTIVES) && (Status_bitmap >= 0)) {
		gr_set_bitmap(Status_bitmap);
		gr_bitmap(Hud_mission_log_status_coords[gr_screen.res][0], Hud_mission_log_status_coords[gr_screen.res][1]);
	}
	*/

	// draw the objectives key at the bottom of the ingame objectives screen
	if (Scrollback_mode == SCROLLBACK_MODE_OBJECTIVES) {
		ML_render_objectives_key();
	}

	Ui_window.draw();

	if (Scrollback_mode == SCROLLBACK_MODE_EVENT_LOG) {
		Buttons[gr_screen.res][SHOW_EVENTS_BUTTON].button.draw_forced(2);
		mission_log_scrollback(Scroll_offset, Hud_mission_log_list_coords[gr_screen.res][0], Hud_mission_log_list_coords[gr_screen.res][1], Hud_mission_log_list_coords[gr_screen.res][2], Hud_mission_log_list_coords[gr_screen.res][3]);

	} else if (Scrollback_mode == SCROLLBACK_MODE_OBJECTIVES) {
		Buttons[gr_screen.res][SHOW_OBJS_BUTTON].button.draw_forced(2);
		ML_objectives_do_frame(Scroll_offset);

	} else {
		line_node *node_ptr;

		Buttons[gr_screen.res][SHOW_MSGS_BUTTON].button.draw_forced(2);
//		y = ((LIST_H / font_height) - 1) * font_height;
		y = 0;
		if ( !EMPTY(&Msg_scrollback_used_list) && HUD_msg_inited ) {
			node_ptr = GET_FIRST(&Msg_scrollback_used_list);
			i = 0;
			while ( node_ptr != END_OF_LIST(&Msg_scrollback_used_list) ) {
				if ((node_ptr->source == HUD_SOURCE_HIDDEN) || (i++ < Scroll_offset)) {
					node_ptr = GET_NEXT(node_ptr);

				} else {
					int team = HUD_source_get_team(node_ptr->source);

					if (team >= 0)
					{
						gr_set_color_fast(iff_get_color_by_team(team, Player_ship->team, 0));
					}
					else
					{
						switch (node_ptr->source)
						{
							case HUD_SOURCE_TRAINING:
								gr_set_color_fast(&Color_bright_blue);
								break;
	
							case HUD_SOURCE_TERRAN_CMD:
								gr_set_color_fast(&Color_bright_white);
								break;
	
							case HUD_SOURCE_IMPORTANT:
							case HUD_SOURCE_FAILED:
							case HUD_SOURCE_SATISFIED:
								gr_set_color_fast(&Color_bright_white);
								break;
	
							default:
								gr_set_color_fast(&Color_text_normal);
								break;
						}
					}

					if (node_ptr->time)
						gr_print_timestamp(Hud_mission_log_list_coords[gr_screen.res][0], Hud_mission_log_list_coords[gr_screen.res][1] + y, node_ptr->time);

					x = Hud_mission_log_list2_coords[gr_screen.res][0] + node_ptr->x;
					gr_printf(x, Hud_mission_log_list_coords[gr_screen.res][1] + y, "%s", node_ptr->text);
					if (node_ptr->underline_width)
						gr_line(x, Hud_mission_log_list_coords[gr_screen.res][1] + y + font_height - 1, x + node_ptr->underline_width, Hud_mission_log_list_coords[gr_screen.res][1] + y + font_height - 1);

					if ((node_ptr->source == HUD_SOURCE_FAILED) || (node_ptr->source == HUD_SOURCE_SATISFIED)) {
						// draw goal icon
						if (node_ptr->source == HUD_SOURCE_FAILED)
							gr_set_color_fast(&Color_bright_red);
						else
							gr_set_color_fast(&Color_bright_green);

						i = Hud_mission_log_list_coords[gr_screen.res][1] + y + font_height / 2 - 1;
						gr_circle(Hud_mission_log_list2_coords[gr_screen.res][0] - 6, i, 5);

						gr_set_color_fast(&Color_bright);
						gr_line(Hud_mission_log_list2_coords[gr_screen.res][0] - 10, i, Hud_mission_log_list2_coords[gr_screen.res][0] - 8, i);
						gr_line(Hud_mission_log_list2_coords[gr_screen.res][0] - 6, i - 4, Hud_mission_log_list2_coords[gr_screen.res][0] - 6, i - 2);
						gr_line(Hud_mission_log_list2_coords[gr_screen.res][0] - 4, i, Hud_mission_log_list2_coords[gr_screen.res][0] - 2, i);
						gr_line(Hud_mission_log_list2_coords[gr_screen.res][0] - 6, i + 2, Hud_mission_log_list2_coords[gr_screen.res][0] - 6, i + 4);
					}

					y += font_height + node_ptr->y;
					node_ptr = GET_NEXT(node_ptr);
					if (y + font_height > Hud_mission_log_list_coords[gr_screen.res][3])
						break;
				}
			}
		}
	}

	gr_set_color_fast(&Color_text_heading);
	gr_print_timestamp(Hud_mission_log_time_coords[gr_screen.res][0], Hud_mission_log_time_coords[gr_screen.res][1] - font_height, Missiontime);
	gr_string(Hud_mission_log_time2_coords[gr_screen.res][0], Hud_mission_log_time_coords[gr_screen.res][1] - font_height, XSTR( "Current time", 289));
	gr_flip();
}
示例#6
0
文件: report.c 项目: jpmatsci/pcb
static int
ReportDialog (int argc, char **argv, Coord x, Coord y)
{
  void *ptr1, *ptr2, *ptr3;
  int type;
  char report[2048];

  type = SearchScreen (x, y, REPORT_TYPES, &ptr1, &ptr2, &ptr3);
  if (type == NO_TYPE)
    type =
      SearchScreen (x, y, REPORT_TYPES | LOCKED_TYPE, &ptr1, &ptr2, &ptr3);

  switch (type)
    {
    case VIA_TYPE:
      {
	PinType *via;
#ifndef NDEBUG
	if (gui->shift_is_pressed ())
	  {
	    __r_dump_tree (PCB->Data->via_tree->root, 0);
	    return 0;
	  }
#endif
	via = (PinType *) ptr2;
	if (TEST_FLAG (HOLEFLAG, via))
	  pcb_sprintf (&report[0], "%m+VIA ID# %ld; Flags:%s\n"
		   "(X,Y) = %$mD.\n"
		   "It is a pure hole of diameter %$mS.\n"
		   "Name = \"%s\"."
		   "%s", USER_UNITMASK, via->ID, flags_to_string (via->Flags, VIA_TYPE),
		   via->X, via->Y, via->DrillingHole, EMPTY (via->Name),
		   TEST_FLAG (LOCKFLAG, via) ? "It is LOCKED.\n" : "");
	else
	  pcb_sprintf (&report[0], "%m+VIA ID# %ld;  Flags:%s\n"
		   "(X,Y) = %$mD.\n"
		   "Copper width = %$mS. Drill width = %$mS.\n"
		   "Clearance width in polygons = %$mS.\n"
		   "Annulus = %$mS.\n"
		   "Solder mask hole = %$mS (gap = %$mS).\n"
		   "Name = \"%s\"."
		   "%s", USER_UNITMASK, via->ID, flags_to_string (via->Flags, VIA_TYPE),
		   via->X, via->Y,
		   via->Thickness,
		   via->DrillingHole,
		   via->Clearance / 2,
		   (via->Thickness - via->DrillingHole) / 2,
		   via->Mask,
		   (via->Mask - via->Thickness) / 2,
		   EMPTY (via->Name), TEST_FLAG (LOCKFLAG, via) ?
		   "It is LOCKED.\n" : "");
	break;
      }
    case PIN_TYPE:
      {
	PinType *Pin;
	ElementType *element;
#ifndef NDEBUG
	if (gui->shift_is_pressed ())
	  {
	    __r_dump_tree (PCB->Data->pin_tree->root, 0);
	    return 0;
	  }
#endif
	Pin = (PinType *) ptr2;
	element = (ElementType *) ptr1;

	PIN_LOOP (element);
	{
	  if (pin == Pin)
	    break;
	}
	END_LOOP;
	if (TEST_FLAG (HOLEFLAG, Pin))
	  pcb_sprintf (&report[0], "%m+PIN ID# %ld; Flags:%s\n"
		   "(X,Y) = %$mD.\n"
		   "It is a mounting hole. Drill width = %$mS.\n"
		   "It is owned by element %$mS.\n"
		   "%s", USER_UNITMASK, Pin->ID, flags_to_string (Pin->Flags, PIN_TYPE),
		   Pin->X, Pin->Y, Pin->DrillingHole,
		   EMPTY (element->Name[1].TextString),
		   TEST_FLAG (LOCKFLAG, Pin) ? "It is LOCKED.\n" : "");
	else
	  pcb_sprintf (&report[0],
		   "%m+PIN ID# %ld;  Flags:%s\n" "(X,Y) = %$mD.\n"
		   "Copper width = %$mS. Drill width = %$mS.\n"
		   "Clearance width to Polygon = %$mS.\n"
		   "Annulus = %$mS.\n"
		   "Solder mask hole = %$mS (gap = %$mS).\n"
		   "Name = \"%s\".\n"
		   "It is owned by element %s\n as pin number %s.\n"
		   "%s", USER_UNITMASK,
		   Pin->ID, flags_to_string (Pin->Flags, PIN_TYPE),
		   Pin->X, Pin->Y, Pin->Thickness,
		   Pin->DrillingHole,
		   Pin->Clearance / 2,
		   (Pin->Thickness - Pin->DrillingHole) / 2,
		   Pin->Mask,
		   (Pin->Mask - Pin->Thickness) / 2,
		   EMPTY (Pin->Name),
		   EMPTY (element->Name[1].TextString), EMPTY (Pin->Number),
		   TEST_FLAG (LOCKFLAG, Pin) ? "It is LOCKED.\n" : "");
	break;
      }
    case LINE_TYPE:
      {
	LineType *line;
#ifndef NDEBUG
	if (gui->shift_is_pressed ())
	  {
	    LayerType *layer = (LayerType *) ptr1;
	    __r_dump_tree (layer->line_tree->root, 0);
	    return 0;
	  }
#endif
	line = (LineType *) ptr2;
	pcb_sprintf (&report[0], "%m+LINE ID# %ld;  Flags:%s\n"
		 "FirstPoint(X,Y)  = %$mD, ID = %ld.\n"
		 "SecondPoint(X,Y) = %$mD, ID = %ld.\n"
		 "Width = %$mS.\nClearance width in polygons = %$mS.\n"
		 "It is on layer %d\n"
		 "and has name \"%s\".\n"
		 "%s", USER_UNITMASK,
		 line->ID, flags_to_string (line->Flags, LINE_TYPE),
		 line->Point1.X, line->Point1.Y, line->Point1.ID,
		 line->Point2.X, line->Point2.Y, line->Point2.ID,
		 line->Thickness, line->Clearance / 2,
		 GetLayerNumber (PCB->Data, (LayerType *) ptr1),
		 UNKNOWN (line->Number),
		 TEST_FLAG (LOCKFLAG, line) ? "It is LOCKED.\n" : "");
	break;
      }
    case RATLINE_TYPE:
      {
	RatType *line;
#ifndef NDEBUG
	if (gui->shift_is_pressed ())
	  {
	    __r_dump_tree (PCB->Data->rat_tree->root, 0);
	    return 0;
	  }
#endif
	line = (RatType *) ptr2;
	pcb_sprintf (&report[0], "%m+RAT-LINE ID# %ld;  Flags:%s\n"
		 "FirstPoint(X,Y)  = %$mD; ID = %ld; "
		 "connects to layer group %d.\n"
		 "SecondPoint(X,Y) = %$mD; ID = %ld; "
		 "connects to layer group %d.\n",
		 USER_UNITMASK, line->ID, flags_to_string (line->Flags, LINE_TYPE),
		 line->Point1.X, line->Point1.Y,
		 line->Point1.ID, line->group1,
		 line->Point2.X, line->Point2.Y,
		 line->Point2.ID, line->group2);
	break;
      }
    case ARC_TYPE:
      {
	ArcType *Arc;
	BoxType *box;
#ifndef NDEBUG
	if (gui->shift_is_pressed ())
	  {
	    LayerType *layer = (LayerType *) ptr1;
	    __r_dump_tree (layer->arc_tree->root, 0);
	    return 0;
	  }
#endif
	Arc = (ArcType *) ptr2;
	box = GetArcEnds (Arc);

	pcb_sprintf (&report[0], "%m+ARC ID# %ld;  Flags:%s\n"
		 "CenterPoint(X,Y) = %$mD.\n"
		 "Radius = %$mS, Thickness = %$mS.\n"
		 "Clearance width in polygons = %$mS.\n"
		 "StartAngle = %ma degrees, DeltaAngle = %ma degrees.\n"
		 "Bounding Box is %$mD, %$mD.\n"
		 "That makes the end points at %$mD and %$mD.\n"
		 "It is on layer %d.\n"
		 "%s", USER_UNITMASK, Arc->ID, flags_to_string (Arc->Flags, ARC_TYPE),
		 Arc->X, Arc->Y,
		 Arc->Width, Arc->Thickness,
		 Arc->Clearance / 2, Arc->StartAngle, Arc->Delta,
		 Arc->BoundingBox.X1, Arc->BoundingBox.Y1,
		 Arc->BoundingBox.X2, Arc->BoundingBox.Y2,
		 box->X1, box->Y1,
		 box->X2, box->Y2,
		 GetLayerNumber (PCB->Data, (LayerType *) ptr1),
		 TEST_FLAG (LOCKFLAG, Arc) ? "It is LOCKED.\n" : "");
	break;
      }
    case POLYGON_TYPE:
      {
	PolygonType *Polygon;
#ifndef NDEBUG
	if (gui->shift_is_pressed ())
	  {
	    LayerType *layer = (LayerType *) ptr1;
	    __r_dump_tree (layer->polygon_tree->root, 0);
	    return 0;
	  }
#endif
	Polygon = (PolygonType *) ptr2;

	pcb_sprintf (&report[0], "%m+POLYGON ID# %ld;  Flags:%s\n"
		 "Its bounding box is %$mD %$mD.\n"
		 "It has %d points and could store %d more\n"
		 "  without using more memory.\n"
		 "It has %d holes and resides on layer %d.\n"
		 "%s", USER_UNITMASK, Polygon->ID,
		 flags_to_string (Polygon->Flags, POLYGON_TYPE),
		 Polygon->BoundingBox.X1, Polygon->BoundingBox.Y1,
		 Polygon->BoundingBox.X2, Polygon->BoundingBox.Y2,
		 Polygon->PointN, Polygon->PointMax - Polygon->PointN,
		 Polygon->HoleIndexN,
		 GetLayerNumber (PCB->Data, (LayerType *) ptr1),
		 TEST_FLAG (LOCKFLAG, Polygon) ? "It is LOCKED.\n" : "");
	break;
      }
    case PAD_TYPE:
      {
	Coord len;
	PadType *Pad;
	ElementType *element;
#ifndef NDEBUG
	if (gui->shift_is_pressed ())
	  {
	    __r_dump_tree (PCB->Data->pad_tree->root, 0);
	    return 0;
	  }
#endif
	Pad = (PadType *) ptr2;
	element = (ElementType *) ptr1;

	PAD_LOOP (element);
	{
	  {
	    if (pad == Pad)
	      break;
	  }
	}
	END_LOOP;
	len = Distance (Pad->Point1.X, Pad->Point1.Y, Pad->Point2.X, Pad->Point2.Y);
	pcb_sprintf (&report[0], "%m+PAD ID# %ld;  Flags:%s\n"
		 "FirstPoint(X,Y)  = %$mD; ID = %ld.\n"
		 "SecondPoint(X,Y) = %$mD; ID = %ld.\n"
		 "Width = %$mS.  Length = %$mS.\n"
		 "Clearance width in polygons = %$mS.\n"
		 "Solder mask = %$mS x %$mS (gap = %$mS).\n"
		 "Name = \"%s\".\n"
		 "It is owned by SMD element %s\n"
		 "  as pin number %s and is on the %s\n"
		 "side of the board.\n"
		 "%s", USER_UNITMASK, Pad->ID,
		 flags_to_string (Pad->Flags, PAD_TYPE),
		 Pad->Point1.X, Pad->Point1.Y, Pad->Point1.ID,
		 Pad->Point2.X, Pad->Point2.Y, Pad->Point2.ID,
		 Pad->Thickness, len + Pad->Thickness,
		 Pad->Clearance / 2,
		 Pad->Mask, len + Pad->Mask,
		 (Pad->Mask - Pad->Thickness) / 2,
		 EMPTY (Pad->Name),
		 EMPTY (element->Name[1].TextString),
		 EMPTY (Pad->Number),
		 TEST_FLAG (ONSOLDERFLAG,
			    Pad) ? "solder (bottom)" : "component",
		 TEST_FLAG (LOCKFLAG, Pad) ? "It is LOCKED.\n" : "");
	break;
      }
    case ELEMENT_TYPE:
      {
	ElementType *element;
#ifndef NDEBUG
	if (gui->shift_is_pressed ())
	  {
	    __r_dump_tree (PCB->Data->element_tree->root, 0);
	    return 0;
	  }
#endif
	element = (ElementType *) ptr2;
	pcb_sprintf (&report[0], "%m+ELEMENT ID# %ld;  Flags:%s\n"
		 "BoundingBox %$mD %$mD.\n"
		 "Descriptive Name \"%s\".\n"
		 "Name on board \"%s\".\n"
		 "Part number name \"%s\".\n"
		 "It is %$mS tall and is located at (X,Y) = %$mD %s.\n"
		 "Mark located at point (X,Y) = %$mD.\n"
		 "It is on the %s side of the board.\n"
		 "%s", USER_UNITMASK,
		 element->ID, flags_to_string (element->Flags, ELEMENT_TYPE),
		 element->BoundingBox.X1, element->BoundingBox.Y1,
		 element->BoundingBox.X2, element->BoundingBox.Y2,
		 EMPTY (element->Name[0].TextString),
		 EMPTY (element->Name[1].TextString),
		 EMPTY (element->Name[2].TextString),
		 SCALE_TEXT (FONT_CAPHEIGHT, element->Name[1].Scale),
		 element->Name[1].X, element->Name[1].Y,
		 TEST_FLAG (HIDENAMEFLAG, element) ? ",\n  but it's hidden" : "",
		 element->MarkX, element->MarkY,
		 TEST_FLAG (ONSOLDERFLAG, element) ? "solder (bottom)" : "component",
		 TEST_FLAG (LOCKFLAG, element) ? "It is LOCKED.\n" : "");
	break;
      }
    case TEXT_TYPE:
#ifndef NDEBUG
      if (gui->shift_is_pressed ())
	{
	  LayerType *layer = (LayerType *) ptr1;
	  __r_dump_tree (layer->text_tree->root, 0);
	  return 0;
	}
#endif
    case ELEMENTNAME_TYPE:
      {
	char laynum[32];
	TextType *text;
#ifndef NDEBUG
	if (gui->shift_is_pressed ())
	  {
	    __r_dump_tree (PCB->Data->name_tree[NAME_INDEX (PCB)]->root, 0);
	    return 0;
	  }
#endif
	text = (TextType *) ptr2;

	if (type == TEXT_TYPE)
	  sprintf (laynum, "It is on layer %d.",
		   GetLayerNumber (PCB->Data, (LayerType *) ptr1));
	pcb_sprintf (&report[0], "%m+TEXT ID# %ld;  Flags:%s\n"
		 "Located at (X,Y) = %$mD.\n"
		 "Characters are %$mS tall.\n"
		 "Value is \"%s\".\n"
		 "Direction is %d.\n"
		 "The bounding box is %$mD %$mD.\n"
		 "%s\n"
		 "%s", USER_UNITMASK, text->ID, flags_to_string (text->Flags, TEXT_TYPE),
		 text->X, text->Y, SCALE_TEXT (FONT_CAPHEIGHT, text->Scale),
		 text->TextString, text->Direction,
		 text->BoundingBox.X1, text->BoundingBox.Y1,
		 text->BoundingBox.X2, text->BoundingBox.Y2,
		 (type == TEXT_TYPE) ? laynum : "It is an element name.",
		 TEST_FLAG (LOCKFLAG, text) ? "It is LOCKED.\n" : "");
	break;
      }
    case LINEPOINT_TYPE:
    case POLYGONPOINT_TYPE:
      {
	PointType *point = (PointType *) ptr2;
	pcb_sprintf (&report[0], "%m+POINT ID# %ld.\n"
		 "Located at (X,Y) = %$mD.\n"
		 "It belongs to a %s on layer %d.\n", USER_UNITMASK, point->ID,
		 point->X, point->Y,
		 (type == LINEPOINT_TYPE) ? "line" : "polygon",
		 GetLayerNumber (PCB->Data, (LayerType *) ptr1));
	break;
      }
    case NO_TYPE:
      report[0] = '\0';
      break;

    default:
      sprintf (&report[0], "Unknown\n");
      break;
    }

  if (report[0] == '\0')
    {
      Message (_("Nothing found to report on\n"));
      return 1;
    }
  /* create dialog box */
  gui->report_dialog ("Report", &report[0]);

  return 0;
}
示例#7
0
void sc_gui_update_editor_menu_cb(GObject *obj, const gchar *word, gint pos,
								  GeanyDocument *doc, gpointer user_data)
{
	gchar *search_word;

	g_return_if_fail(doc != NULL && doc->is_valid);

	/* hide the submenu in any case, we will reshow it again if we actually found something */
	gtk_widget_hide(sc_info->edit_menu);
	gtk_widget_hide(sc_info->edit_menu_sep);

	if (! sc_info->show_editor_menu_item)
		return;

	/* if we have a selection, prefer it over the current word */
	if (sci_has_selection(doc->editor->sci))
	{
		gint len = sci_get_selected_text_length(doc->editor->sci);
		search_word = g_malloc(len + 1);
		sci_get_selected_text(doc->editor->sci, search_word);
	}
	else
		search_word = g_strdup(word);

	/* ignore numbers or words starting with digits and non-text */
	if (EMPTY(search_word) || isdigit(*search_word) || ! sc_speller_is_text(doc, pos))
	{
		g_free(search_word);
		return;
	}

	/* ignore too long search words */
	if (strlen(search_word) > 100)
	{
		GtkWidget *menu_item;

		init_editor_submenu();
		menu_item = gtk_menu_item_new_with_label(
			_("Search term is too long to provide\nspelling suggestions in the editor menu."));
		gtk_widget_set_sensitive(menu_item, FALSE);
		gtk_widget_show(menu_item);
		gtk_container_add(GTK_CONTAINER(sc_info->edit_menu_sub), menu_item);

		menu_item = gtk_menu_item_new_with_label(_("Perform Spell Check"));
		gtk_widget_show(menu_item);
		gtk_container_add(GTK_CONTAINER(sc_info->edit_menu_sub), menu_item);
		g_signal_connect(menu_item, "activate", G_CALLBACK(perform_spell_check_cb), doc);

		g_free(search_word);
		return;
	}

	if (sc_speller_dict_check(search_word) != 0)
	{
		GtkWidget *menu_item, *menu;
		gchar *label;
		gsize n_suggs, i;
		gchar **suggs;

		suggs = sc_speller_dict_suggest(search_word, &n_suggs);

		clickinfo.pos = pos;
		clickinfo.doc = doc;
		setptr(clickinfo.word, search_word);

		menu = init_editor_submenu();

		for (i = 0; i < n_suggs; i++)
		{
			if (i > 0 && i % 10 == 0)
			{
				menu_item = gtk_menu_item_new();
				gtk_widget_show(menu_item);
				gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_item);

				menu_item = gtk_menu_item_new_with_label(_("More..."));
				gtk_widget_show(menu_item);
				gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_item);

				menu = gtk_menu_new();
				gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item), menu);
			}
			menu_item = gtk_menu_item_new_with_label(suggs[i]);
			gtk_widget_show(menu_item);
			gtk_container_add(GTK_CONTAINER(menu), menu_item);
			g_signal_connect(menu_item, "activate",
				G_CALLBACK(menu_suggestion_item_activate_cb), NULL);
		}
		if (suggs == NULL)
		{
			menu_item = gtk_menu_item_new_with_label(_("(No Suggestions)"));
			gtk_widget_set_sensitive(menu_item, FALSE);
			gtk_widget_show(menu_item);
			gtk_container_add(GTK_CONTAINER(sc_info->edit_menu_sub), menu_item);
		}
		menu_item = gtk_separator_menu_item_new();
		gtk_widget_show(menu_item);
		gtk_container_add(GTK_CONTAINER(sc_info->edit_menu_sub), menu_item);

		label = g_strdup_printf(_("Add \"%s\" to Dictionary"), search_word);
		menu_item = image_menu_item_new(GTK_STOCK_ADD, label);
		gtk_widget_show(menu_item);
		gtk_container_add(GTK_CONTAINER(sc_info->edit_menu_sub), menu_item);
		g_signal_connect(menu_item, "activate",
			G_CALLBACK(menu_addword_item_activate_cb), GINT_TO_POINTER(FALSE));

		menu_item = image_menu_item_new(GTK_STOCK_REMOVE, _("Ignore All"));
		gtk_widget_show(menu_item);
		gtk_container_add(GTK_CONTAINER(sc_info->edit_menu_sub), menu_item);
		g_signal_connect(menu_item, "activate",
			G_CALLBACK(menu_addword_item_activate_cb), GINT_TO_POINTER(TRUE));

		if (suggs != NULL)
			sc_speller_dict_free_string_list(suggs);

		g_free(label);
	}
	else
	{
		g_free(search_word);
	}
}
示例#8
0
文件: dqds.c 项目: hrautila/armas
/*
 * \brief Run Li's test from (1), section 3.3
 */ 
static
void __dqds_li_test(int ping, armas_x_dense_t *Z, int N, DTYPE *emin, DTYPE *qmax)
{
    armas_x_dense_t sq, se, dq, de;
    DTYPE qk, qk1, ek, d, emn, qmx;
    int k;

    EMPTY(de); EMPTY(dq); EMPTY(se); EMPTY(sq);

    armas_x_row(&sq, Z, ping);
    armas_x_row(&dq, Z, 1 - ping);
    armas_x_row(&se, Z, 2 + ping);
    armas_x_row(&de, Z, 3 - ping);

    d = armas_x_get_at_unsafe(&sq, N-1);
    // run Li's reverse test
    for (k = N-1; k > 0; k--) {
        qk = armas_x_get_at_unsafe(&sq, k-1);
        ek = armas_x_get_at_unsafe(&se, k-1);
        if (ek <= EPS2*d) {
            armas_x_set_at_unsafe(&se, k-1, - __ZERO);
            d = qk;
        } else {
            d = qk * (d / (d + ek));
        }
    }
    // map Z -> ZZ and Li's test, update emin
    qmx = __ZERO;
    emn = armas_x_get_at_unsafe(&se, 0);
    d   = armas_x_get_at_unsafe(&sq, 0);
    for (k = 0; k < N-1; k++) {
        ek  = armas_x_get_at_unsafe(&se, k);
        qk1 = armas_x_get_at_unsafe(&sq, k+1);
        qk  = d + ek;
        if (ek < EPS2*d) {
            // Li's test eq.5 in (1), page 12
            //printf("..[li] ek=%13e < EPS2*d [%13e, %13e]\n", ek, d, EPS2*d);
            armas_x_set_at_unsafe(&se, k, - __ZERO);
            qk = d;
            ek = __ZERO;
            d  = qk1;
#if 0
            // this commented out as it seemed to true most of the time, even without any appearent underflow
        } else if (__SAFEMIN*qk1 <= qk && __SAFEMIN*qk <= qk1) {
            // test for underflow from (1) page 7
            //printf("..[li] underflow qk=%13e [%13e], qk1=%13e [%13e]\n", qk, __SAFEMIN*qk, qk1, __SAFEMIN*qk1);
            t  = qk1/qk;
            ek = ek*t;
            d  = d*t;
#endif
        } else {
            // standard dqd (dqds with zero shift)
            ek = qk1*(ek/qk);
            d  = qk1*(d/qk);
        }
        armas_x_set_at_unsafe(&dq, k, qk);
        armas_x_set_at_unsafe(&de, k, ek);
        emn = __MIN(emn, ek);
        qmx = __MAX(qmx, qk);
    }
    armas_x_set_at_unsafe(&dq, N-1, d);
    *emin = emn;
    *qmax = qmx;
}
示例#9
0
文件: dqds.c 项目: hrautila/armas
/*
 * \brief Top left of DQDS algorithm
 */
static
int __dqds_main(armas_x_dense_t *Z, int N)
{
    armas_x_dense_t sZ, sq, se;
    dmin_data_t dmind;
    DTYPE q0, q1, e0, emin, emax, qmin, qmax, sigma, dmin, cterm;
    int ip, iq, niter, maxiter, ncnt;

    EMPTY(sZ); EMPTY(se); EMPTY(sq);

    // test flipping 1.5*q(0) < q(N-1)
    q0 = armas_x_get_unsafe(Z, 0, 0);
    q1 = armas_x_get_unsafe(Z, 0, N-1);
    if (CFLIP*q0 < q1) {
        __dqds_flip(Z, N);
    }

#if 1
    // run Li's test and check for initial splitting;
    __dqds_li_test(PING, Z, N, &emin, &qmax);
    __dqds_li_test(PONG, Z, N, &emin, &qmax);
#endif
    armas_x_row(&sq, Z, 0);
    armas_x_row(&se, Z, 1);

    // find unreduce block and run dqds on the segment
    __DMIN_INIT(dmind);
    ip = 0; iq = N;
    maxiter = 10*N;
    dmind.cterm = __ZERO;
    sigma = __ZERO;

    for (niter = 0; niter < maxiter && iq > 0; niter++) {
        qmin = armas_x_get_unsafe(Z, 0, iq-1);
        qmax = qmin;
        emax = __ZERO;
        emin = iq > 1 ? armas_x_get_unsafe(Z, 2, iq-2) : __ZERO;

        for (ip = iq-1; ip > 0; ip--) {
            q0 = armas_x_get_unsafe(Z, 0, ip-1);
            e0 = armas_x_get_unsafe(Z, 2, ip-1);
            if (e0 <= __ZERO) {
                // e0 < 0.0 
                //printf("..[main] e0 <= 0.0 [%d], e0=%e\n", ip, e0);
                break;
            }
            if (qmin >= 4.0*emax) {
                emax = __MAX(emax, e0);
                qmin = __MIN(qmin, q0);
            }
            emin = __MIN(emin, e0);
            qmax = __MAX(qmax, q0+e0);
        }

        dmin = - __MAX(__ZERO, qmin - 2.0*__SQRT(qmin)*__SQRT(emax));
        dmind.dmin = dmin;
        dmind.qmax = qmax;
        dmind.emin = emin;

        // select subblock
        armas_x_submatrix(&sZ, Z, 0, ip, Z->rows, iq-ip);
        cterm = dmind.cterm;
        if ((ncnt = __dqds_segment(&sZ, iq-ip, sigma, dmin, &dmind, 0)) < 0) {
            //printf("..[main] subblock [%d,%d] not converged\n", ip, iq);
            return -1;
        } 
        //printf("..[main] new iq=%d, [ip=%d]\n", iq - ncnt, ip);
        iq -= ncnt;
        dmind.cterm = cterm;
    }
    return niter == maxiter ? -1 : 0;
}
示例#10
0
文件: file.c 项目: bert/pcb-rnd
/* ---------------------------------------------------------------------------
 * writes layer data
 */
static void
WriteLayerData (FILE * FP, Cardinal Number, LayerTypePtr layer)
{
  GList *n;
  /* write information about non empty layers */
  if (layer->LineN || layer->ArcN || layer->TextN || layer->PolygonN ||
      (layer->Name && *layer->Name))
    {
      fprintf (FP, "Layer(%i ", (int) Number + 1);
      PrintQuotedString (FP, (char *)EMPTY (layer->Name));
      fputs (")\n(\n", FP);
      WriteAttributeList (FP, &layer->Attributes, "\t");

      for (n = layer->Line; n != NULL; n = g_list_next (n))
	{
	  LineType *line = n->data;
          pcb_fprintf (FP, "\tLine[%mr %mr %mr %mr %mr %mr %s]\n",
                       line->Point1.X, line->Point1.Y,
                       line->Point2.X, line->Point2.Y,
                       line->Thickness, line->Clearance,
                       F2S (line, LINE_TYPE));
	}
      for (n = layer->Arc; n != NULL; n = g_list_next (n))
	{
	  ArcType *arc = n->data;
          pcb_fprintf (FP, "\tArc[%mr %mr %mr %mr %mr %mr %ma %ma %s]\n",
                       arc->X, arc->Y, arc->Width,
                       arc->Height, arc->Thickness,
                       arc->Clearance, arc->StartAngle,
                       arc->Delta, F2S (arc, ARC_TYPE));
	}
      for (n = layer->Text; n != NULL; n = g_list_next (n))
	{
	  TextType *text = n->data;
          pcb_fprintf (FP, "\tText[%mr %mr %d %d ",
                       text->X, text->Y,
                       text->Direction, text->Scale);
	  PrintQuotedString (FP, (char *)EMPTY (text->TextString));
	  fprintf (FP, " %s]\n", F2S (text, TEXT_TYPE));
	}
      for (n = layer->Polygon; n != NULL; n = g_list_next (n))
	{
	  PolygonType *polygon = n->data;
	  int p, i = 0;
	  Cardinal hole = 0;
	  fprintf (FP, "\tPolygon(%s)\n\t(", F2S (polygon, POLYGON_TYPE));
	  for (p = 0; p < polygon->PointN; p++)
	    {
	      PointTypePtr point = &polygon->Points[p];

	      if (hole < polygon->HoleIndexN &&
		  p == polygon->HoleIndex[hole])
		{
		  if (hole > 0)
		    fputs ("\n\t\t)", FP);
		  fputs ("\n\t\tHole (", FP);
		  hole++;
		  i = 0;
		}

	      if (i++ % 5 == 0)
		{
		  fputs ("\n\t\t", FP);
		  if (hole)
		    fputs ("\t", FP);
		}
              pcb_fprintf (FP, "[%mr %mr] ", point->X, point->Y);
	    }
	  if (hole > 0)
	    fputs ("\n\t\t)", FP);
	  fputs ("\n\t)\n", FP);
	}
      fputs (")\n", FP);
    }
}
示例#11
0
文件: dqds.c 项目: hrautila/armas
/*
 *  Z = q0,  q1,  ..., qn1,  qn    (N columns, 4 rows)
 *      qq0, qq1, ..., qqn1, qqn
 *      e0,  e1,  ..., en1,  0
 *      ee0, ee1, ..., een1, 0
 *
 * \return number of deflations
 */
static
int __dqds_goodstep(DTYPE *ssum, armas_x_dense_t *Z, int N, int pp, dmin_data_t *dmind)
{
    armas_x_dense_t sq, dq, se, de;
    int n, ncnt, nfail, newseg;
    DTYPE x, y, q0, q1, sigma, tau;

    EMPTY(de); EMPTY(dq); EMPTY(se); EMPTY(sq);

    sigma = *ssum;
    newseg = __SIGN(dmind->dmin);
    //printf("..[goodstep] entering ping=%d, N=%d, newseg=%d, sigma=%e, dmin=%e\n",
    //     pp, N, newseg, sigma, dmind->dmin);

    armas_x_row(&sq, Z, pp);
    armas_x_row(&dq, Z, 1 - pp);
    armas_x_row(&se, Z, 2 + pp);
    armas_x_row(&de, Z, 3 - pp);

    dmind->niter++;
    if (N == 1) {
        armas_x_set_unsafe(Z, 0, 0, armas_x_get_at_unsafe(&sq, 0)+(sigma+dmind->cterm));
        //printf("..[goodstep] deflated single valued vector eig=%9.6f\n", __SQRT(armas_x_get_unsafe(Z, 0, 0)));
        return 1;
    }

    // 1. Look for neglible E-values
    ncnt = 0;
    if (! newseg) {
        do {
            n = __dqds_neglible(Z, N-ncnt, pp, sigma+dmind->cterm);
            ncnt += n;
        } while (n != 0 && N-ncnt > 0);
    }
    if (N-ncnt == 0) {
        //printf("..[goodstep] deflated (%d) to zero length\n", ncnt);
        return ncnt;
    }
    // 2 test flipping 1.5*q(0) < q(N-1) if new segment or deflated values
    if (newseg || ncnt > 0) {
        q0 = armas_x_get_at_unsafe(&sq, 0);
        q1 = armas_x_get_at_unsafe(&sq, N-ncnt-1);
        if (CFLIP*q0 < q1) {
            //printf("..[goodstep] need flipping.. [0, %d]\n", N-ncnt-1);
            __dqds_flip(Z, N-ncnt);
        }
    }
    
    // 3a. if no overflow or no new segment, choose shift
    __dqds_shift(&tau, &sq, &se, &dq, &de, N-ncnt, ncnt, dmind);
    //printf("..[goodstep]: tau=%e [type=%d, dmin=%e,%e, dmin1=%e]\n", tau, t, dmind->ttype, dmind->dmin, dmind->dn, dmind->dmin1);
    
    // 4.  run dqds until dmin > 0
    nfail = 0;
    do {
        __dqds_sweep(&dq, &de, &sq, &se, N-ncnt, tau, dmind);
        if (dmind->dmin < __ZERO) {
            // failure here
            DTYPE en1 = armas_x_get_at_unsafe(&de, N-ncnt-2);
            if (dmind->dmin1 > __ZERO && en1 < __EPS*(sigma+dmind->dn1) &&
                __ABS(dmind->dn) < __EPS*sigma) {
                // convergence masked by negative d (section 6.4)
                armas_x_set_at_unsafe(&dq, N-ncnt-1, __ZERO);
                dmind->dmin = __ZERO;
                //printf("..[masked] dmin1 > %e, setting qn to zero.!\n", dmind->dmin1);
                // break out from loop
                //break;
            }
    
            nfail++;
            if (nfail > 1) {
                tau = __ZERO;
            } else if (dmind->dmin1 > __ZERO) {
                // late failure
                tau = (tau + dmind->dmin)*(1.0 - 2.0*__EPS);
                dmind->ttype -= 11;
            } else {
                tau *= 0.25;
                dmind->ttype -= 12;
            }
            //printf("..failure[%d]: tau=%e\n", nfail, tau);
            dmind->niter++;
            dmind->nfail++;
        }
    } while (dmind->dmin < __ZERO || dmind->dmin1 < __ZERO);

    // 5. update sigma; sequence of tau values.
    //    use cascaded summation from (2), algorithm 4.1
    //    this here is one step of the algorithm, error term
    //    is summated to dmind->cterm
 
    twosum(&x, &y, *ssum, tau);
    //printf("..[goodstep] 2sum x=%13e, y=%13e, a=%13e, b=%13e\n", x, y, *ssum, tau);
    *ssum = x;
    dmind->cterm += y;
    //printf("..[goodstep] 2sum c=%13e, eig=%13e\n", dmind->cterm, __SQRT(x+dmind->cterm));
    
    return ncnt;
}
示例#12
0
文件: file.c 项目: bert/pcb-rnd
/* ---------------------------------------------------------------------------
 * writes element data
 */
static void
WriteElementData (FILE * FP, DataTypePtr Data)
{
  GList *n, *p;
  for (n = Data->Element; n != NULL; n = g_list_next (n))
    {
      ElementType *element = n->data;

      /* only non empty elements */
      if (!element->LineN && !element->PinN && !element->ArcN
	  && !element->PadN)
	continue;
      /* the coordinates and text-flags are the same for
       * both names of an element
       */
      fprintf (FP, "\nElement[%s ", F2S (element, ELEMENT_TYPE));
      PrintQuotedString (FP, (char *)EMPTY (DESCRIPTION_NAME (element)));
      fputc (' ', FP);
      PrintQuotedString (FP, (char *)EMPTY (NAMEONPCB_NAME (element)));
      fputc (' ', FP);
      PrintQuotedString (FP, (char *)EMPTY (VALUE_NAME (element)));
      pcb_fprintf (FP, " %mr %mr %mr %mr %d %d %s]\n(\n",
                   element->MarkX, element->MarkY,
                   DESCRIPTION_TEXT (element).X - element->MarkX,
                   DESCRIPTION_TEXT (element).Y - element->MarkY,
                   DESCRIPTION_TEXT (element).Direction,
                   DESCRIPTION_TEXT (element).Scale,
                   F2S (&(DESCRIPTION_TEXT (element)), ELEMENTNAME_TYPE));
      WriteAttributeList (FP, &element->Attributes, "\t");
      for (p = element->Pin; p != NULL; p = g_list_next (p))
	{
	  PinType *pin = p->data;
          pcb_fprintf (FP, "\tPin[%mr %mr %mr %mr %mr %mr ",
                       pin->X - element->MarkX,
                       pin->Y - element->MarkY,
                       pin->Thickness, pin->Clearance,
                       pin->Mask, pin->DrillingHole);
	  PrintQuotedString (FP, (char *)EMPTY (pin->Name));
	  fprintf (FP, " ");
	  PrintQuotedString (FP, (char *)EMPTY (pin->Number));
	  fprintf (FP, " %s]\n", F2S (pin, PIN_TYPE));
	}
      for (p = element->Pad; p != NULL; p = g_list_next (p))
	{
	  PadType *pad = p->data;
          pcb_fprintf (FP, "\tPad[%mr %mr %mr %mr %mr %mr %mr ",
                       pad->Point1.X - element->MarkX,
                       pad->Point1.Y - element->MarkY,
                       pad->Point2.X - element->MarkX,
                       pad->Point2.Y - element->MarkY,
                       pad->Thickness, pad->Clearance, pad->Mask);
	  PrintQuotedString (FP, (char *)EMPTY (pad->Name));
	  fprintf (FP, " ");
	  PrintQuotedString (FP, (char *)EMPTY (pad->Number));
	  fprintf (FP, " %s]\n", F2S (pad, PAD_TYPE));
	}
      for (p = element->Line; p != NULL; p = g_list_next (p))
	{
	  LineType *line = p->data;
          pcb_fprintf (FP, "\tElementLine [%mr %mr %mr %mr %mr]\n",
                       line->Point1.X - element->MarkX,
                       line->Point1.Y - element->MarkY,
                       line->Point2.X - element->MarkX,
                       line->Point2.Y - element->MarkY,
                       line->Thickness);
	}
      for (p = element->Arc; p != NULL; p = g_list_next (p))
	{
	  ArcType *arc = p->data;
          pcb_fprintf (FP, "\tElementArc [%mr %mr %mr %mr %ma %ma %mr]\n",
                       arc->X - element->MarkX,
                       arc->Y - element->MarkY,
                       arc->Width, arc->Height,
                       arc->StartAngle, arc->Delta,
                       arc->Thickness);
	}
      fputs ("\n\t)\n", FP);
    }
}
示例#13
0
static void print1opt(struct opt_spec *o, FILE *f, int helppos)
{
    int i, pos, len, helpwidth;
    const char *mv, *a, *b, *c;

    if (!(c = o->help))
        return;
    if (o->action == opt_text && EMPTY(o->lf)) {
        helppos = strspn(c, " ");
        pos = 0;
    }
    else {
        pos = globals.indent + strspn(c, " ");
        fprintf(f, "%*s", pos, "");
        mv = o->metavar ? o->metavar : "";
        len = strlen(mv);
        if (!EMPTY(o->sf)) {
            fprintf(f, "-%c%s", o->sf[0], mv);
            pos += 2 + len;
            for (i = 1; o->sf[i]; ++i) {
                fprintf(f, ", -%c%s", o->sf[i], mv);
                pos += 4 + len;
            }
            if (!EMPTY(o->lf)) {
                fputs(", ", f);
                pos += 2;
            }
        }
        if (!EMPTY(o->lf)) {
            fprintf(f, "%s", o->lf);
            pos += strlen(o->lf);
            if (len) {
                if (mv[0] != ' ') {
                    putc('=', f);
                    ++pos;
                }
                fputs(mv, f);
                pos += len;
            }
        }
        len = strlen(globals.helppfx);
        if (!helppos)
            helppos = pos + len <= globals.maxhelppos
                ? pos + len : globals.maxhelppos;
        if (pos + len > helppos) {
            putc('\n', f);
            pos = 0;
        }
        fprintf(f, "%*s", helppos - pos, globals.helppfx);
        pos = helppos;
    }
    helpwidth = globals.width - helppos;
    for (;;) {
        while (*c == ' ')
            ++c;
        if (!*c)
            break;
        if (*c == '\n') {
            putc(*c++, f);
            pos = 0;
            continue;
        }
        for (a = b = c; ; ) {
            while (*++c && *c != '\n' && *c != ' ')
                ;
            if (c - a > helpwidth) {
                c = b;
                break;
            }
            b = c;
            while (*c == ' ')
                ++c;
            if (!*c)
                break;
            if (*c == '\n') {
                ++c;
                break;
            }
        }
        if (b == a) {
            fprintf(f, "%*s%s\n", helppos - pos, "", a);
            pos = 0;
            break;
        }
        fprintf(f, "%*s%.*s\n", helppos - pos, "", (int)(b - a), a);
        pos = 0;
    }
    if (pos)
        putc('\n', f);
}
示例#14
0
int opt_parse(const char *usage, struct opt_spec *opts, char **argv)
{
    char *a, *b, save;
    struct opt_spec *o, *o2;
    int ret = 0, skipping = 0, nh, minh = INT_MAX;

    if (!(globals.prog = argv[0]))
        return 0;
    globals.argv = argv + 1;
    if (EMPTY(usage))
        globals.usage = "usage: %s [options]";
    else
        globals.usage = usage;
    globals.header.action = opt_text;
    if (opts->action == opt_text && EMPTY(opts->lf))
        globals.header.help = opts++->help;
    else
        globals.header.help = "options:";
    globals.opts = opts;
    for (o = opts; o->action; ++o) {
        if (o->action == opt_help) {
            if (EMPTY(o->help))
                o->help = "print this help message and exit";
            if (!EMPTY(o->sf))
                globals.helpsf = o->sf[0];
            else
                globals.helplf = o->lf;
        }
        else if (o->action == opt_version && EMPTY(o->help))
            o->help = "print the version number and exit";
        if (o->action != opt_text && !EMPTY(o->lf)
            && (nh = strspn(o->lf, "-")) < minh)
            minh = nh;
    }
    while ((a = *globals.argv++)) {
        if (!*a) {
            if (globals.opts1st) {
                ++ret;
                skipping = 1;
            }
            continue;
        }
        if (skipping) {
            ++ret;
            continue;
        }
        if (*a == '-' && a[1] == '-' && !a[2]) {
            *a = 0;
            skipping = 1;
            continue;
        }
        if ((nh = strspn(a, "-")) >= minh) {
            b = a + strcspn(a, "=");
            save = *b;
            *b = 0;
            o = b - a < 2 ? NULL : findlf(opts, a);
            if (o) {
                o2 = findlf(o + 1, a);
                if (o2) {
                    fprintf(
                        stderr, "%s: ambiguous option %s\n%*s(%s",
                        globals.prog,
                        a,
                        (int) strlen(globals.prog) + 2,
                        "",
                        o->lf
                    );
                    for (;;) {
                        o = o2;
                        o2 = findlf(o + 1, a);
                        if (!o2) {
                            fprintf(stderr, " or %s?)\n", o->lf);
                            exit(EXIT_FAILURE);
                        }
                        fprintf(stderr, ", %s", o->lf);
                    }
                }
                globals.curr = o;
                globals.sf[1] = 0;
                if (EMPTY(o->metavar)) {
                    if (save)
                        opt_err("option %s does not take a value");
                    skipping = o->action(NULL, o->data);
                }
                else {
                    if (save)
                        ++b;
                    else {
                        b = *globals.argv++;
                        if (!b)
                            opt_err("option %s requires a value");
                    }
                    skipping = o->action(b, o->data);
                    if (!save)
                        *b = 0;
                }
                *a = 0;
                continue;
            }
            if (nh >= 2)
                unknown(a);
            *b = save;
        }
        if (nh == 0 || !a[1]) {
            ++ret;
            skipping = globals.opts1st;
            continue;
        }
        *a = 0;
        while (*++a) {
            globals.sf[1] = *a;
            for (o = opts;
                 o->action && (!o->sf || !strchr(o->sf, *a)); ++o)
                ;
            if (!o->action)
                unknown(globals.sf);
            globals.curr = o;
            if (!EMPTY(o->metavar)) {
                b = a + 1;
                if (!*b) {
                    b = *globals.argv++;
                    if (!b)
                        opt_err("option %s requires a value");
                }
                skipping = o->action(b, o->data);
                if (b != a + 1)
                    *b = 0;
                break;
            }
            if ((skipping = o->action(NULL, o->data)))
                break;
        }
    }
    return ret;
}
示例#15
0
int TTY_Connect(int handle, char *host)
{
	double	start;
	ComPort	*p;
	char	*response = NULL;
	keydest_t	save_key_dest;
	char	dialstring[64];
	byte	b;

	p = handleToPort[handle];

	if ((p->modemStatus & MODEM_STATUS_MASK) != MODEM_STATUS_MASK)
	{
		Con_Printf ("Serial: line not ready (");
		if ((p->modemStatus & MSR_CTS) == 0)
			Con_Printf(" CTS");
		if ((p->modemStatus & MSR_DSR) == 0)
			Con_Printf(" DSR");
		if ((p->modemStatus & MSR_CD) == 0)
			Con_Printf(" CD");
		Con_Printf(" )");
		return -1;
	}

	// discard any scraps in the input buffer
	while (! EMPTY (p->inputQueue))
		DEQUEUE (p->inputQueue, b);

	CheckStatus (p);

	if (p->useModem)
	{
		save_key_dest = key_dest;
		key_dest = key_console;
		key_count = -2;

		Con_Printf ("Dialing...\n");
		sprintf(dialstring, "AT D%c %s\r", p->dialType, host);
		Modem_Command (p, dialstring);
		start = Sys_FloatTime();
		while(1)
		{
			if ((Sys_FloatTime() - start) > 60.0)
			{
				Con_Printf("Dialing failure!\n");
				break;
			}

			Sys_SendKeyEvents ();
			if (key_count == 0)
			{
				if (key_lastpress != K_ESCAPE)
				{
					key_count = -2;
					continue;
				}
				Con_Printf("Aborting...\n");
				while ((Sys_FloatTime() - start) < 5.0)
					;
				disable();
				p->outputQueue.head = p->outputQueue.tail = 0;
				p->inputQueue.head = p->inputQueue.tail = 0;
				outportb(p->uart + MODEM_CONTROL_REGISTER, inportb(p->uart + MODEM_CONTROL_REGISTER) & ~MCR_DTR);
				enable();
				start = Sys_FloatTime();
				while ((Sys_FloatTime() - start) < 0.75)
					;
				outportb(p->uart + MODEM_CONTROL_REGISTER, inportb(p->uart + MODEM_CONTROL_REGISTER) | MCR_DTR);
				response = "Aborted";
				break;
			}

			response = Modem_Response(p);
			if (!response)
				continue;
			if (Q_strncmp(response, "CONNECT", 7) == 0)
			{
				disable();
				p->modemRang = true;
				p->modemConnected = true;
				p->outputQueue.head = p->outputQueue.tail = 0;
				p->inputQueue.head = p->inputQueue.tail = 0;
				enable();
				key_dest = save_key_dest;
				key_count = 0;
				m_return_onerror = false;
				return 0;
			}
			if (Q_strncmp(response, "NO CARRIER", 10) == 0)
				break;
			if (Q_strncmp(response, "NO DIALTONE", 11) == 0)
				break;
			if (Q_strncmp(response, "NO DIAL TONE", 12) == 0)
				break;
			if (Q_strncmp(response, "NO ANSWER", 9) == 0)
				break;
			if (Q_strncmp(response, "BUSY", 4) == 0)
				break;
			if (Q_strncmp(response, "ERROR", 5) == 0)
				break;
		}
		key_dest = save_key_dest;
		key_count = 0;
		if (m_return_onerror)
		{
			key_dest = key_menu;
			m_state = m_return_state;
			m_return_onerror = false;
			Q_strncpy(m_return_reason, response, 31);
		}
		return -1;
	}
	m_return_onerror = false;
	return 0;
}
示例#16
0
文件: buffer.c 项目: bgamari/geda-pcb
/* Returns zero on success, non-zero on error.  */
int
LoadFootprintByName (BufferType *Buffer, char *Footprint)
{
  int i;
  FootprintHashEntry *fpe;
  LibraryMenuType *menu;
  LibraryEntryType *entry;
  char *with_fp = NULL;

  if (!footprint_hash)
    make_footprint_hash ();

  fpe = search_footprint_hash (Footprint);
  if (!fpe)
    {
      with_fp = Concat (Footprint, ".fp", NULL);
      fpe = search_footprint_hash (with_fp);
      if (fpe)
	Footprint = with_fp;
    }
  if (!fpe)
    {
      Message(_("Unable to load footprint %s\n"), Footprint);
      return 1;
    }

  menu = & Library.Menu[fpe->menu_idx];
  entry = & menu->Entry[fpe->entry_idx];

  if (entry->Template == (char *) -1)
    {
      i = LoadElementToBuffer (Buffer, entry->AllocatedMemory, true);
      if (with_fp)
	free (with_fp);
      return i ? 0 : 1;
    }
  else
    {
      char *args;

      args = Concat("'", EMPTY (entry->Template), "' '",
		    EMPTY (entry->Value), "' '", EMPTY (entry->Package), "'", NULL);
      i = LoadElementToBuffer (Buffer, args, false);

      free (args);
      if (with_fp)
	free (with_fp);
      return i ? 0 : 1;
    }

#ifdef DEBUG
  {
    int j;
    printf("Library path: %s\n", Settings.LibraryPath);
    printf("Library tree: %s\n", Settings.LibraryTree);

    printf("Library:\n");
    for (i=0; i<Library.MenuN; i++)
      {
	printf("  [%02d] Name: %s\n", i, Library.Menu[i].Name);
	printf("       Dir:  %s\n", Library.Menu[i].directory);
	printf("       Sty:  %s\n", Library.Menu[i].Style);
	for (j=0; j<Library.Menu[i].EntryN; j++)
	  {
	    printf("       [%02d] E: %s\n", j, Library.Menu[i].Entry[j].ListEntry);
	    if (Library.Menu[i].Entry[j].Template == (char *) -1)
	      printf("            A: %s\n", Library.Menu[i].Entry[j].AllocatedMemory);
	    else
	      {
		printf("            T: %s\n", Library.Menu[i].Entry[j].Template);
		printf("            P: %s\n", Library.Menu[i].Entry[j].Package);
		printf("            V: %s\n", Library.Menu[i].Entry[j].Value);
		printf("            D: %s\n", Library.Menu[i].Entry[j].Description);
	      }
	    if (j == 10)
	      break;
	  }
      }
  }
#endif
}
示例#17
0
qboolean TTY_OutputQueueIsEmpty(int handle)
{
	return EMPTY(handleToPort[handle]->outputQueue);
}
示例#18
0
文件: export.c 项目: 15ramky/geany
static void create_file_save_as_dialog(const gchar *extension, ExportFunc func,
									   gboolean show_zoom_level_checkbox)
{
	GtkWidget *dialog, *vbox;
	GeanyDocument *doc;
	ExportInfo *exi;

	g_return_if_fail(extension != NULL);

	doc = document_get_current();
	g_return_if_fail(doc != NULL);

	exi = g_new(ExportInfo, 1);
	exi->doc = doc;
	exi->export_func = func;
	exi->have_zoom_level_checkbox = FALSE;

	dialog = gtk_file_chooser_dialog_new(_("Export File"), GTK_WINDOW(geany->main_widgets->window),
				GTK_FILE_CHOOSER_ACTION_SAVE, NULL, NULL);
	gtk_window_set_modal(GTK_WINDOW(dialog), TRUE);
	gtk_window_set_destroy_with_parent(GTK_WINDOW(dialog), TRUE);
	gtk_window_set_skip_taskbar_hint(GTK_WINDOW(dialog), TRUE);
	gtk_window_set_type_hint(GTK_WINDOW(dialog), GDK_WINDOW_TYPE_HINT_DIALOG);
	gtk_widget_set_name(dialog, "GeanyExportDialog");

	gtk_dialog_add_buttons(GTK_DIALOG(dialog),
		GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT, NULL);
	gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_ACCEPT);

	/* file chooser extra widget */
	vbox = gtk_vbox_new(FALSE, 0);
	gtk_file_chooser_set_extra_widget(GTK_FILE_CHOOSER(dialog), vbox);
	{
		GtkWidget *check_line_numbers;

		check_line_numbers = gtk_check_button_new_with_mnemonic(_("_Insert line numbers"));
		gtk_widget_set_tooltip_text(check_line_numbers,
			_("Insert line numbers before each line in the exported document"));
		gtk_box_pack_start(GTK_BOX(vbox), check_line_numbers, FALSE, FALSE, 0);
		gtk_widget_show_all(vbox);

		ui_hookup_widget(dialog, check_line_numbers, "check_line_numbers");
	}
	if (show_zoom_level_checkbox)
	{
		GtkWidget *check_zoom_level;

		check_zoom_level = gtk_check_button_new_with_mnemonic(_("_Use current zoom level"));
		gtk_widget_set_tooltip_text(check_zoom_level,
			_("Renders the font size of the document together with the current zoom level"));
		gtk_box_pack_start(GTK_BOX(vbox), check_zoom_level, FALSE, FALSE, 0);
		gtk_widget_show_all(vbox);

		ui_hookup_widget(dialog, check_zoom_level, "check_zoom_level");
		exi->have_zoom_level_checkbox = TRUE;
	}

	g_signal_connect(dialog, "delete-event", G_CALLBACK(gtk_widget_hide_on_delete), NULL);
	g_signal_connect(dialog, "response", G_CALLBACK(on_file_save_dialog_response), exi);

	gtk_window_set_transient_for(GTK_WINDOW(dialog), GTK_WINDOW(geany->main_widgets->window));

	/* if the current document has a filename we use it as the default. */
	gtk_file_chooser_unselect_all(GTK_FILE_CHOOSER(dialog));
	if (doc->file_name != NULL)
	{
		gchar *base_name = g_path_get_basename(doc->file_name);
		gchar *file_name;
		gchar *locale_filename;
		gchar *locale_dirname;
		const gchar *suffix = "";

		if (g_str_has_suffix(doc->file_name, extension))
			suffix = "_export";

		file_name = g_strconcat(base_name, suffix, extension, NULL);
		locale_filename = utils_get_locale_from_utf8(doc->file_name);
		locale_dirname = g_path_get_dirname(locale_filename);
		/* set the current name to base_name.html which probably doesn't exist yet so
		 * gtk_file_chooser_set_filename() can't be used and we need
		 * gtk_file_chooser_set_current_folder() additionally */
		gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), locale_dirname);
		gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), file_name);
		g_free(locale_dirname);
		g_free(locale_filename);
		g_free(file_name);
		g_free(base_name);
	}
	else
	{
		const gchar *default_open_path = geany->prefs->default_open_path;
		gchar *fname = g_strconcat(GEANY_STRING_UNTITLED, extension, NULL);

		gtk_file_chooser_unselect_all(GTK_FILE_CHOOSER(dialog));
		gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), fname);

		/* use default startup directory(if set) if no files are open */
		if (!EMPTY(default_open_path) && g_path_is_absolute(default_open_path))
		{
			gchar *locale_path = utils_get_locale_from_utf8(default_open_path);
			gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), locale_path);
			g_free(locale_path);
		}
		g_free(fname);
	}
	gtk_dialog_run(GTK_DIALOG(dialog));
}
示例#19
0
文件: ceval.c 项目: brosner/cleese
static PyObject *
eval_frame(PyFrameObject *f)
{
	LOG("> eval_frame\n"); {
	PyObject **stack_pointer; /* Next free slot in value stack */
	register unsigned char *next_instr;
	register int opcode=0;	/* Current opcode */
	register int oparg=0;	/* Current opcode argument, if any */
	register enum why_code why; /* Reason for block stack unwind */
	register int err;	/* Error status -- nonzero if error */
	register PyObject *x;	/* Result object -- NULL if error */
	register PyObject *t, *u, *v;	/* Temporary objects popped off stack */
	register PyObject *w;
	register PyObject **fastlocals, **freevars;
	PyObject *retval = NULL;	/* Return value */
	PyThreadState *tstate = PyThreadState_GET();
	PyCodeObject *co;

	unsigned char *first_instr;
	PyObject *names;
	PyObject *consts;

/* Tuple access macros */

#define GETITEM(v, i) PyTuple_GET_ITEM((PyTupleObject *)(v), (i))

/* Code access macros */

#define INSTR_OFFSET()	(next_instr - first_instr)
#define NEXTOP()	(*next_instr++)
#define NEXTARG()	(next_instr += 2, (next_instr[-1]<<8) + next_instr[-2])
#define JUMPTO(x)	(next_instr = first_instr + (x))
#define JUMPBY(x)	(next_instr += (x))

/* OpCode prediction macros
	Some opcodes tend to come in pairs thus making it possible to predict
	the second code when the first is run.  For example, COMPARE_OP is often
	followed by JUMP_IF_FALSE or JUMP_IF_TRUE.  And, those opcodes are often
	followed by a POP_TOP.

	Verifying the prediction costs a single high-speed test of register
	variable against a constant.  If the pairing was good, then the
	processor has a high likelihood of making its own successful branch
	prediction which results in a nearly zero overhead transition to the
	next opcode.

	A successful prediction saves a trip through the eval-loop including
	its two unpredictable branches, the HASARG test and the switch-case.
*/

#define PREDICT(op)		if (*next_instr == op) goto PRED_##op
#define PREDICTED(op)		PRED_##op: next_instr++
#define PREDICTED_WITH_ARG(op)	PRED_##op: oparg = (next_instr[2]<<8) + \
				next_instr[1]; next_instr += 3

/* Stack manipulation macros */

#define STACK_LEVEL()	(stack_pointer - f->f_valuestack)
#define EMPTY()		(STACK_LEVEL() == 0)
#define TOP()		(stack_pointer[-1])
#define SECOND()	(stack_pointer[-2])
#define THIRD() 	(stack_pointer[-3])
#define FOURTH()	(stack_pointer[-4])
#define SET_TOP(v)	(stack_pointer[-1] = (v))
#define SET_SECOND(v)	(stack_pointer[-2] = (v))
#define SET_THIRD(v)	(stack_pointer[-3] = (v))
#define SET_FOURTH(v)	(stack_pointer[-4] = (v))
#define BASIC_STACKADJ(n)	(stack_pointer += n)
#define BASIC_PUSH(v)	(*stack_pointer++ = (v))
#define BASIC_POP()	(*--stack_pointer)

#define PUSH(v)		BASIC_PUSH(v)
#define POP()		BASIC_POP()
#define STACKADJ(n)	BASIC_STACKADJ(n)

/* Local variable macros */

#define GETLOCAL(i)	(fastlocals[i])

/* The SETLOCAL() macro must not DECREF the local variable in-place and
   then store the new value; it must copy the old value to a temporary
   value, then store the new value, and then DECREF the temporary value.
   This is because it is possible that during the DECREF the frame is
   accessed by other code (e.g. a __del__ method or gc.collect()) and the
   variable would be pointing to already-freed memory. */
#define SETLOCAL(i, value)	do { PyObject *tmp = GETLOCAL(i); \
				     GETLOCAL(i) = value; \
                                     Py_XDECREF(tmp); } while (0)

/* Start of code */

	if (f == NULL)
		return NULL;

	/* push frame */
	if (++tstate->recursion_depth > recursion_limit) {
		--tstate->recursion_depth;
		/* ERROR */
		tstate->frame = f->f_back;
		return NULL;
	}

	tstate->frame = f;

	/* tracing elided */

	co = f->f_code;
	names = co->co_names;
	consts = co->co_consts;
	fastlocals = f->f_localsplus;
	freevars = f->f_localsplus + f->f_nlocals;

	_PyCode_GETCODEPTR(co, &first_instr);

	/* An explanation is in order for the next line.

	   f->f_lasti now refers to the index of the last instruction
	   executed.  You might think this was obvious from the name, but
	   this wasn't always true before 2.3!  PyFrame_New now sets
	   f->f_lasti to -1 (i.e. the index *before* the first instruction)
	   and YIELD_VALUE doesn't fiddle with f_lasti any more.  So this
	   does work.  Promise. */
	next_instr = first_instr + f->f_lasti + 1;
	stack_pointer = f->f_stacktop;

	f->f_stacktop = NULL;	/* remains NULL unless yield suspends frame */

	why = WHY_NOT;
	err = 0;
	x = Py_None;	/* Not a reference, just anything non-NULL */
	w = NULL;

	for (;;) {

		/* Do periodic things.  Doing this every time through
		   the loop would add too much overhead, so we do it
		   only every Nth instruction.  We also do it if
		   ``things_to_do'' is set, i.e. when an asynchronous
		   event needs attention (e.g. a signal handler or
		   async I/O handler); see Py_AddPendingCall() and
		   Py_MakePendingCalls() above. */

		if (--_Py_Ticker < 0) {
			/* @@@ check for SETUP_FINALLY elided */

			_Py_Ticker = _Py_CheckInterval;
			tstate->tick_counter++;
			if (things_to_do) {
				if (Py_MakePendingCalls() < 0) {
					why = WHY_EXCEPTION;
					goto on_error;
				}
			}
		}

	fast_next_opcode:
		f->f_lasti = INSTR_OFFSET();

		/* Extract opcode and argument */

		opcode = NEXTOP();
		if (HAS_ARG(opcode))
			oparg = NEXTARG();

		/* Main switch on opcode */

		switch (opcode) {

		/* BEWARE!
		   It is essential that any operation that fails sets either
		   x to NULL, err to nonzero, or why to anything but WHY_NOT,
		   and that no operation that succeeds does this! */

		/* case STOP_CODE: this is an error! */

		case LOAD_FAST:
			x = GETLOCAL(oparg);
			if (x != NULL) {
				Py_INCREF(x);
				PUSH(x);
				goto fast_next_opcode;
			}
			/* ERROR? */
			break;

                case STORE_FAST:
                        v = POP();
                        SETLOCAL(oparg, v);
                        continue;

		case LOAD_CONST:
			x = GETITEM(consts, oparg);
			Py_INCREF(x);
			PUSH(x);
			goto fast_next_opcode;

		PREDICTED(POP_TOP);
		case POP_TOP:
			v = POP();
			Py_DECREF(v);
			goto fast_next_opcode;

		case UNARY_NOT:
			v = TOP();
			err = PyObject_IsTrue(v);
			Py_DECREF(v);
			if (err == 0) {
				Py_INCREF(Py_True);
				SET_TOP(Py_True);
				continue;
			}
			else if (err > 0) {
				Py_INCREF(Py_False);
				SET_TOP(Py_False);
				err = 0;
				continue;
			}
			STACKADJ(-1);
			break;

		case BINARY_MODULO:
			w = POP();
			v = TOP();
			x = PyNumber_Remainder(v, w);
			Py_DECREF(v);
			Py_DECREF(w);
			SET_TOP(x);
			if (x != NULL) continue;
			break;
			
		case BINARY_ADD:
			w = POP();
			v = TOP();
			if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
				/* INLINE: int + int */
				register long a, b, i;
				a = PyInt_AS_LONG(v);
				b = PyInt_AS_LONG(w);
				i = a + b;
				if ((i^a) < 0 && (i^b) < 0)
					goto slow_add;
				x = PyInt_FromLong(i);
			}
			else {
			  slow_add:
				Py_FatalError("slow add not supported.");
			}
			Py_DECREF(v);
			Py_DECREF(w);
			SET_TOP(x);
			if (x != NULL) continue;
			break;

                case STORE_SLICE+0:
                case STORE_SLICE+1:
                case STORE_SLICE+2:
                case STORE_SLICE+3:
                        if ((opcode-STORE_SLICE) & 2)
                                w = POP();
                        else
                                w = NULL;
                        if ((opcode-STORE_SLICE) & 1)
                                v = POP();
                        else
                                v = NULL;
                        u = POP();
                        t = POP();
                        err = assign_slice(u, v, w, t); /* u[v:w] = t */
                        Py_DECREF(t);
                        Py_DECREF(u);
                        Py_XDECREF(v);
                        Py_XDECREF(w);
                        if (err == 0) continue;
                        break;

                case STORE_SUBSCR:
                        w = POP();
                        v = POP();
                        u = POP();
                        /* v[w] = u */
                        err = PyObject_SetItem(v, w, u);
                        Py_DECREF(u);
                        Py_DECREF(v);
                        Py_DECREF(w);
                        if (err == 0) continue;
                        break;

                case BINARY_SUBSCR:
                        w = POP();
                        v = TOP();
                        if (PyList_CheckExact(v) && PyInt_CheckExact(w)) {
                                /* INLINE: list[int] */
                                long i = PyInt_AsLong(w);
                                if (i < 0)
                                        i += PyList_GET_SIZE(v);
                                if (i < 0 ||
                                    i >= PyList_GET_SIZE(v)) {
                                        /* ERROR */
                                        printf("list index out of range\n");
                                        x = NULL;
                                }
                                else {
                                        x = PyList_GET_ITEM(v, i);
                                        Py_INCREF(x);
                                }
                        }
                        else
                                x = PyObject_GetItem(v, w);
                        Py_DECREF(v);
                        Py_DECREF(w);
                        SET_TOP(x);
                        if (x != NULL) continue;
                        break;

		case BINARY_AND:
			w = POP();
			v = TOP();
			x = PyNumber_And(v, w);
			Py_DECREF(v);
			Py_DECREF(w);
			SET_TOP(x);
			if (x != NULL) continue;
			break;

		case PRINT_ITEM:
			v = POP();

			PyObject_Print(v);
			Py_DECREF(v);
			break;

		case PRINT_NEWLINE:
			printf("\n");
			break;

		case RETURN_VALUE:
			retval = POP();
			why = WHY_RETURN;
			break;

		case POP_BLOCK:
			{
				PyTryBlock *b = PyFrame_BlockPop(f);
				while (STACK_LEVEL() > b->b_level) {
					v = POP();
					Py_DECREF(v);
				}
			}
			break;

		case STORE_NAME:
			w = GETITEM(names, oparg);
			v = POP();
			if ((x = f->f_locals) == NULL) {
				/* ERROR */
				printf("STORE_NAME ERROR\n");
				break;
			}
			err = PyDict_SetItem(x, w, v);
			Py_DECREF(v);
			break;

		case LOAD_NAME:
			w = GETITEM(names, oparg);
			if ((x = f->f_locals) == NULL) {
				/* ERROR */
				printf("LOAD_NAME ERROR\n");
				break;
			}
			x = PyDict_GetItem(x, w);
			if (x == NULL) {
				x = PyDict_GetItem(f->f_globals, w);
				if (x == NULL) {
					x = PyDict_GetItem(f->f_builtins, w);
					if (x == NULL) {
						printf("can't find %s\n", ((PyStringObject *)w)->ob_sval);
						/* format_exc_check_arg */
						break;
					}
				}
			}
			Py_INCREF(x);
			PUSH(x);
			break;
			
		case LOAD_GLOBAL:
			w = GETITEM(names, oparg);
			if (PyString_CheckExact(w)) {
				/* Inline the PyDict_GetItem() calls.
				   WARNING: this is an extreme speed hack.
				   Do not try this at home. */
				long hash = ((PyStringObject *)w)->ob_shash;
				if (hash != -1) {
					PyDictObject *d;
					d = (PyDictObject *)(f->f_globals);
					x = d->ma_lookup(d, w, hash)->me_value;
					if (x != NULL) {
						Py_INCREF(x);
						PUSH(x);
						continue;
					}
					d = (PyDictObject *)(f->f_builtins);
					x = d->ma_lookup(d, w, hash)->me_value;
					if (x != NULL) {
						Py_INCREF(x);
						PUSH(x);
						continue;
					}
					goto load_global_error;
				}
			}
			/* This is the un-inlined version of the code above */
			x = PyDict_GetItem(f->f_globals, w);
			if (x == NULL) {
				x = PyDict_GetItem(f->f_builtins, w);
				if (x == NULL) {
				  load_global_error:
					printf("LOAD_GLOBAL ERROR %s", ((PyStringObject *)w)->ob_sval);
					break;
				}
			}
			Py_INCREF(x);
			PUSH(x);
			break;

		case LOAD_ATTR:
			w = GETITEM(names, oparg);
			v = TOP();
			x = PyObject_GetAttr(v, w);
			Py_DECREF(v);
			SET_TOP(x);
			if (x != NULL) continue;
			break;

		case IMPORT_NAME:
			w = GETITEM(names, oparg);
			x = PyDict_GetItemString(f->f_builtins, "__import__");
			if (x == NULL) {
				printf("__import__ not found");
				break;
			}
			u = TOP();
			w = Py_BuildValue("(O)", w);
			Py_DECREF(u);
			if (w == NULL) {
				u = POP();
				x = NULL;
				break;
			}
			x = PyEval_CallObject(x, w);
			Py_DECREF(w);
			SET_TOP(x);
			if (x != NULL) continue;
			break;

		case JUMP_FORWARD:
			JUMPBY(oparg);
			goto fast_next_opcode;

		PREDICTED_WITH_ARG(JUMP_IF_FALSE);
		case JUMP_IF_FALSE:
			w = TOP();
			if (w == Py_True) {
				PREDICT(POP_TOP);
				goto fast_next_opcode;
			}
			if (w == Py_False) {
				JUMPBY(oparg);
				goto fast_next_opcode;
			}
			err = PyObject_IsTrue(w);
			if (err > 0)
				err = 0;
			else if (err == 0)
				JUMPBY(oparg);
			else
				break;
			continue;
			
		case JUMP_ABSOLUTE:
			JUMPTO(oparg);
			continue;

		case SETUP_LOOP:
			PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg, STACK_LEVEL());
			continue;

		case CALL_FUNCTION:
			x = call_function(&stack_pointer, oparg);
			PUSH(x);
			if (x != NULL)
				continue;
			break;
			
		case MAKE_FUNCTION:
			v = POP(); /* code object */
			x = PyFunction_New(v, f->f_globals);
			Py_DECREF(v);
			/* XXX Maybe this should be a separate opcode? */
			if (x != NULL && oparg > 0) {
				v = PyTuple_New(oparg);
				if (v == NULL) {
					Py_DECREF(x);
					x = NULL;
			break;
				}
				while (--oparg >= 0) {
					w = POP();
					PyTuple_SET_ITEM(v, oparg, w);
				}
				err = PyFunction_SetDefaults(x, v);
				Py_DECREF(v);
			}
			PUSH(x);
			break;
			
		case SET_LINENO:
			break;

		default:
			printf("opcode: %d\n", opcode);
			Py_FatalError("unknown opcode");
		} /* switch */

	  on_error:
		
		if (why == WHY_NOT) {
			if (err == 0 && x != NULL) {
					continue; /* Normal, fast path */
			}
			why = WHY_EXCEPTION;
			x = Py_None;
			err = 0;
		}

		/* End the loop if we still have an error (or return) */

		if (why != WHY_NOT)
			break;

	} /* main loop */

	if (why != WHY_YIELD) {
		/* Pop remaining stack entries -- but when yielding */
		while (!EMPTY()) {
			v = POP();
			Py_XDECREF(v);
		}
	}

	if (why != WHY_RETURN && why != WHY_YIELD)
		retval = NULL;

	/* pop frame */
	--tstate->recursion_depth;
	tstate->frame = f->f_back;

	return retval;
}}
示例#20
0
文件: bpft.c 项目: DNS-OARC/dnscap
void prepare_bpft(void)
{
    unsigned  udp10_mbs, udp10_mbc, udp11_mbs, udp11_mbc;
    text_list bpfl;
    text_ptr  text;
    size_t    len;

    /* Prepare the must-be-set and must-be-clear tests. */
    udp10_mbs = udp10_mbc = udp11_mbs = udp11_mbc = 0U;
    if ((dir_wanted & DIR_INITIATE) != 0) {
        if ((dir_wanted & DIR_RESPONSE) == 0)
            udp10_mbc |= UDP10_QR_MASK;
    } else if ((dir_wanted & DIR_RESPONSE) != 0) {
        udp10_mbs |= UDP10_QR_MASK;
    }
    if ((msg_wanted & MSG_UPDATE) != 0) {
        if ((msg_wanted & (MSG_QUERY | MSG_NOTIFY)) == 0)
            udp10_mbs |= (ns_o_update << UDP10_OP_SHIFT);
    } else if ((msg_wanted & MSG_NOTIFY) != 0) {
        if ((msg_wanted & (MSG_QUERY | MSG_UPDATE)) == 0)
            udp10_mbs |= (ns_o_notify << UDP10_OP_SHIFT);
    } else if ((msg_wanted & MSG_QUERY) != 0) {
        udp10_mbc |= UDP10_OP_MASK;
    }
    if (err_wanted == ERR_NO) {
        udp10_mbc |= UDP10_TC_MASK;
        udp11_mbc |= UDP11_RC_MASK;
    }

    /*
 * Model
 * (vlan) and (transport)
 * (vlan) and ((icmp) or (frags) or (dns))
 * (vlan) and ((icmp) or (frags) or ((ports) and (hosts)))
 * (vlan) and ((icmp) or (frags) or (((tcp) or (udp)) and (hosts)))
 * [(vlan) and] ( [(icmp) or] [(frags) or] ( ( [(tcp) or] (udp) ) [and (hosts)] ) )
 */

    /* Make a BPF program to do early course kernel-level filtering. */
    INIT_LIST(bpfl);
    len = 0;
    if (!EMPTY(vlans_excl))
        len += text_add(&bpfl, "vlan and ("); /* vlan and ( transports ...  */
    else
        len += text_add(&bpfl, "("); /* ( transports ...  */
    if (wanticmp) {
        len += text_add(&bpfl, " ( ip proto 1 or ip proto 58 ) or");
    }
    if (wantfrags) {
        len += text_add(&bpfl, " ( ip[6:2] & 0x1fff != 0 or ip6[6] = 44 ) or");
    }
    len += text_add(&bpfl, " ("); /* ( dns ...  */
    len += text_add(&bpfl, " ("); /* ( ports ...  */
    if (wanttcp) {
        len += text_add(&bpfl, " ( tcp port %d ) or", dns_port);
        /* tcp packets can be filtered by initiators/responders, but
         * not mbs/mbc. */
    }
    len += text_add(&bpfl, " ( udp port %d", dns_port);
    if (!v6bug) {
        if (udp10_mbc != 0)
            len += text_add(&bpfl, " and udp[10] & 0x%x = 0",
                udp10_mbc);
        if (udp10_mbs != 0)
            len += text_add(&bpfl, " and udp[10] & 0x%x = 0x%x",
                udp10_mbs, udp10_mbs);
        if (udp11_mbc != 0)
            len += text_add(&bpfl, " and udp[11] & 0x%x = 0",
                udp11_mbc);
        /* Dead code, udp11_mbs never set
        if (udp11_mbs != 0)
            len += text_add(&bpfl, " and udp[11] & 0x%x = 0x%x",
                    udp11_mbs, udp11_mbs);
*/

        if (err_wanted != ERR_NO) {
            len += text_add(&bpfl, " and (");
            if ((err_wanted & ERR_TRUNC) != 0) {
                len += text_add(&bpfl, " udp[10] & 0x%x = 0x%x or", UDP10_TC_MASK, UDP10_TC_MASK);
            }
            len += text_add(&bpfl, " 0x%x << (udp[11] & 0xf) & 0x%x != 0 )", ERR_RCODE_BASE, err_wanted);
        }
    }
    len += text_add(&bpfl, " )"); /*  ... udp 53 ) */
    len += text_add(&bpfl, " )"); /*  ... ports ) */
    if (options.bpf_hosts_apply_all) {
        len += text_add(&bpfl, " )"); /*  ... dns ) */
        len += text_add(&bpfl, " )"); /* ... transport ) */
    }
    if (!EMPTY(initiators) || !EMPTY(responders)) {
        const char* or = "or", *lp = "(", *sep;
        endpoint_ptr ep;

        len += text_add(&bpfl, " and host");
        sep = lp;
        for (ep = HEAD(initiators);
             ep != NULL;
             ep = NEXT(ep, link)) {
            len += text_add(&bpfl, " %s %s", sep, ia_str(ep->ia));
            sep = or ;
        }
        for (ep = HEAD(responders);
             ep != NULL;
             ep = NEXT(ep, link)) {
            len += text_add(&bpfl, " %s %s", sep, ia_str(ep->ia));
            sep = or ;
        }
        len += text_add(&bpfl, " )");
    }
    if (!EMPTY(not_initiators) || !EMPTY(not_responders)) {
        const char* or = "or", *lp = "(", *sep;
        endpoint_ptr ep;

        len += text_add(&bpfl, " and not host");
        sep = lp;
        for (ep = HEAD(not_initiators);
             ep != NULL;
             ep = NEXT(ep, link)) {
            len += text_add(&bpfl, " %s %s", sep, ia_str(ep->ia));
            sep = or ;
        }
        for (ep = HEAD(not_responders);
             ep != NULL;
             ep = NEXT(ep, link)) {
            len += text_add(&bpfl, " %s %s", sep, ia_str(ep->ia));
            sep = or ;
        }
        len += text_add(&bpfl, " )");
    }
    if (!options.bpf_hosts_apply_all) {
        len += text_add(&bpfl, " )"); /*  ... dns ) */
        len += text_add(&bpfl, " )"); /* ... transport ) */
    }
    if (extra_bpf)
        len += text_add(&bpfl, " and ( %s )", extra_bpf);

    bpft = calloc(len + 1, sizeof(char));
    assert(bpft != NULL);
    for (text = HEAD(bpfl);
         text != NULL;
         text = NEXT(text, link))
        strcat(bpft, text->text);
    text_free(&bpfl);
    if (!EMPTY(vlans_incl)) {
        static char* bpft_vlan;
        len       = (2 * strlen(bpft)) + 64; /* add enough for the extra in snprintf() below */
        bpft_vlan = calloc(len, sizeof(char));
        assert(bpft_vlan != NULL);
        snprintf(bpft_vlan, len, "( %s ) or ( vlan and ( %s ) )", bpft, bpft);
        bpft = realloc(bpft, len);
        assert(bpft != NULL);
        strcpy(bpft, bpft_vlan);
        free(bpft_vlan);
    }
    if (dumptrace >= 1)
        fprintf(stderr, "%s: \"%s\"\n", ProgramName, bpft);
}
示例#21
0
static gint sc_speller_check_word(GeanyDocument *doc, gint line_number, const gchar *word,
						   gint start_pos, gint end_pos)
{
	gsize n_suggs = 0;
	gchar *word_to_check;
	gint offset;

	g_return_val_if_fail(sc_speller_dict != NULL, 0);
	g_return_val_if_fail(doc != NULL, 0);
	g_return_val_if_fail(word != NULL, 0);
	g_return_val_if_fail(start_pos >= 0 && end_pos >= 0, 0);

	if (EMPTY(word))
		return 0;

	/* ignore numbers or words starting with digits */
	if (isdigit(*word))
		return 0;

	/* ignore non-text */
	if (! sc_speller_is_text(doc, start_pos))
		return 0;

	/* strip punctuation and white space */
	word_to_check = strip_word(word, &offset);
	if (EMPTY(word_to_check))
	{
		g_free(word_to_check);
		return 0;
	}

	/* recalculate start_pos and end_pos */
	start_pos += offset;
	end_pos = start_pos + strlen(word_to_check);

	/* early out if the word is spelled correctly */
	if (enchant_dict_check(sc_speller_dict, word_to_check, -1) == 0)
	{
		g_free(word_to_check);
		return 0;
	}

	editor_indicator_set_on_range(doc->editor, GEANY_INDICATOR_ERROR, start_pos, end_pos);

	if (sc_info->use_msgwin && line_number != -1)
	{
		gsize j;
		gchar **suggs;
		GString *str;

		str = g_string_sized_new(256);
		suggs = enchant_dict_suggest(sc_speller_dict, word_to_check, -1, &n_suggs);
		if (suggs != NULL)
		{
			g_string_append_printf(str, "line %d: %s | ",  line_number + 1, word_to_check);

			g_string_append(str, _("Try: "));

			/* Now find the misspellings in the line, limit suggestions to a maximum of 15 (for now) */
			for (j = 0; j < MIN(n_suggs, 15); j++)
			{
				g_string_append(str, suggs[j]);
				g_string_append_c(str, ' ');
			}

			msgwin_msg_add(COLOR_RED, line_number + 1, doc, "%s", str->str);

			if (suggs != NULL && n_suggs > 0)
				enchant_dict_free_string_list(sc_speller_dict, suggs);
		}
		g_string_free(str, TRUE);
	}

	g_free(word_to_check);
	return n_suggs;
}
示例#22
0
/* _agstrcanon:
 * Canonicalize ordinary strings. 
 * Assumes buf is large enough to hold output.
 */
static char *_agstrcanon(char *arg, char *buf)
{
    char *s, *p;
    unsigned char uc;
    int cnt = 0, dotcnt = 0;
    int needs_quotes = FALSE;
    int maybe_num;
    int backslash_pending = FALSE;
    static const char *tokenlist[]	/* must agree with scan.l */
	= { "node", "edge", "strict", "graph", "digraph", "subgraph",
	NIL(char *)
    };
    const char **tok;

    if (EMPTY(arg))
	return "\"\"";
    s = arg;
    p = buf;
    *p++ = '\"';
    uc = *(unsigned char *) s++;
    maybe_num = isdigit(uc) || (uc == '.') || (uc == '-');
    while (uc) {
	if (uc == '\"') {
	    *p++ = '\\';
	    needs_quotes = TRUE;
	} 
	else if (maybe_num) {
	    if (uc == '-') {
		if (cnt) {
		    maybe_num = FALSE;
		    needs_quotes = TRUE;
		}
	    }
	    else if (uc == '.') {
		if (dotcnt++) {
		    maybe_num = FALSE;
		    needs_quotes = TRUE;
		}
	    }
	    else if (!isdigit(uc)) {
		maybe_num = FALSE;
		needs_quotes = TRUE;
	    }
	}
	else if (!ISALNUM(uc))
	    needs_quotes = TRUE;
	*p++ = (char) uc;
	uc = *(unsigned char *) s++;
	cnt++;
	
	/* If breaking long strings into multiple lines, only allow breaks after a non-id char, not a backslash, where the next char is an
 	 * id char.
	 */
	if (Max_outputline) {
            if (uc && backslash_pending && !(is_id_char(p[-1]) || (p[-1] == '\\')) && is_id_char(uc)) {
        	*p++ = '\\';
        	*p++ = '\n';
        	needs_quotes = TRUE;
        	backslash_pending = FALSE;
		cnt = 0;
            } else if (uc && (cnt >= Max_outputline)) {
        	if (!(is_id_char(p[-1]) || (p[-1] == '\\')) && is_id_char(uc)) {
	            *p++ = '\\';
    	            *p++ = '\n';
	            needs_quotes = TRUE;
		    cnt = 0;
        	} else {
                    backslash_pending = TRUE;
        	}
	    }
	}
    }
    *p++ = '\"';
    *p = '\0';
    if (needs_quotes || ((cnt == 1) && ((*arg == '.') || (*arg == '-'))))
	return buf;

    /* Use quotes to protect tokens (example, a node named "node") */
    /* It would be great if it were easier to use flex here. */
    for (tok = tokenlist; *tok; tok++)
	if (!strcasecmp(*tok, arg))
	    return buf;
    return arg;
}
示例#23
0
文件: lqmult.c 项目: hrautila/armas
/*
 * Unblocked algorith for computing C = Q.T*C and C = Q*C.
 *
 * Q = H(k)H(k-1)...H(1) where elementary reflectors H(i) are stored on i'th row
 * right of diagonal in A.
 *
 * Progressing A from top-left to bottom-right i.e from smaller row numbers
 * to larger, produces H(k)...H(2)H(1) == Q. and C = Q*C
 *
 * Progressing from bottom-right to top-left produces H(k)H(k-1)...H(1) == Q.T and C = Q.T*C
 */
static int
__unblk_lqmult_left(armas_x_dense_t *C, armas_x_dense_t *A, armas_x_dense_t *tau,
                    armas_x_dense_t *W, int flags, armas_conf_t *conf)
{
  armas_x_dense_t ATL, ABR, A00, a11, a12, A22, *Aref;
  armas_x_dense_t tT, tB, t0, t1, t2, w12;
  armas_x_dense_t CT, CB, C0, c1, C2;
  int pAdir, pAstart, pStart, pDir;
  int mb, nb, tb, cb;

  EMPTY(A00); EMPTY(a11);

  if (flags & ARMAS_TRANS) {
    pAstart = ARMAS_PBOTTOMRIGHT;
    pAdir   = ARMAS_PTOPLEFT;
    pStart  = ARMAS_PBOTTOM;
    pDir    = ARMAS_PTOP;
    mb = max(0, A->rows - A->cols);
    nb = max(0, A->cols - A->rows);
    cb = max(0, C->rows - A->rows);
    tb = max(0, armas_x_size(tau) - A->rows);
    Aref = &ATL;
  } else {
    pAstart = ARMAS_PTOPLEFT;
    pAdir   = ARMAS_PBOTTOMRIGHT;
    pStart  = ARMAS_PTOP;
    pDir    = ARMAS_PBOTTOM;
    mb = nb = tb = cb = 0;
    Aref = &ABR;
  }

  __partition_2x2(&ATL,  __nil,
                  __nil, &ABR,   /**/  A, mb, nb, pAstart);
  __partition_2x1(&CT, 
                  &CB,   /**/  C,   cb, pStart);
  __partition_2x1(&tT, 
                  &tB,   /**/  tau, tb, pStart);
                 
  armas_x_submatrix(&w12, W, 0, 0, C->cols, 1);

  while (Aref->rows > 0 && Aref->cols > 0) {
    __repartition_2x2to3x3(&ATL,
                           &A00,  __nil, __nil,
                           __nil, &a11,  &a12,
                           __nil, __nil, &A22,  /**/  A, 1, pAdir);
    __repartition_2x1to3x1(&CT,
                           &C0,
                           &c1,
                           &C2,     /**/ C, 1, pDir);
    __repartition_2x1to3x1(&tT,
                           &t0,
                           &t1,
                           &t2,     /**/ tau, 1, pDir);
    // ---------------------------------------------------------------------------
    __apply_householder2x1(&t1, &a12, &c1, &C2, &w12, ARMAS_LEFT, conf);
    // ---------------------------------------------------------------------------
    __continue_3x3to2x2(&ATL,  __nil,
                        __nil, &ABR, /**/  &A00, &a11, &A22,   A, pAdir);
    __continue_3x1to2x1(&CT,
                        &CB,  /**/  &C0,  &c1,   C,   pDir);
    __continue_3x1to2x1(&tT,
                        &tB,  /**/  &t0,  &t1,   tau, pDir);
  }
  return 0;
}
示例#24
0
/***
 *** Task Manager.
 ***/
static void
dispatch(isc_taskmgr_t *manager) {
	isc_task_t *task;
#ifndef ISC_PLATFORM_USETHREADS
	unsigned int total_dispatch_count = 0;
	isc_tasklist_t ready_tasks;
#endif /* ISC_PLATFORM_USETHREADS */

	REQUIRE(VALID_MANAGER(manager));

	/*
	 * Again we're trying to hold the lock for as short a time as possible
	 * and to do as little locking and unlocking as possible.
	 *
	 * In both while loops, the appropriate lock must be held before the
	 * while body starts.  Code which acquired the lock at the top of
	 * the loop would be more readable, but would result in a lot of
	 * extra locking.  Compare:
	 *
	 * Straightforward:
	 *
	 *	LOCK();
	 *	...
	 *	UNLOCK();
	 *	while (expression) {
	 *		LOCK();
	 *		...
	 *		UNLOCK();
	 *
	 *	       	Unlocked part here...
	 *
	 *		LOCK();
	 *		...
	 *		UNLOCK();
	 *	}
	 *
	 * Note how if the loop continues we unlock and then immediately lock.
	 * For N iterations of the loop, this code does 2N+1 locks and 2N+1
	 * unlocks.  Also note that the lock is not held when the while
	 * condition is tested, which may or may not be important, depending
	 * on the expression.
	 *
	 * As written:
	 *
	 *	LOCK();
	 *	while (expression) {
	 *		...
	 *		UNLOCK();
	 *
	 *	       	Unlocked part here...
	 *
	 *		LOCK();
	 *		...
	 *	}
	 *	UNLOCK();
	 *
	 * For N iterations of the loop, this code does N+1 locks and N+1
	 * unlocks.  The while expression is always protected by the lock.
	 */

#ifndef ISC_PLATFORM_USETHREADS
	ISC_LIST_INIT(ready_tasks);
#endif
	LOCK(&manager->lock);
	while (!FINISHED(manager)) {
#ifdef ISC_PLATFORM_USETHREADS
		/*
		 * For reasons similar to those given in the comment in
		 * isc_task_send() above, it is safe for us to dequeue
		 * the task while only holding the manager lock, and then
		 * change the task to running state while only holding the
		 * task lock.
		 */
		while ((EMPTY(manager->ready_tasks) ||
		        manager->exclusive_requested) &&
		  	!FINISHED(manager)) 
	  	{
			XTHREADTRACE(isc_msgcat_get(isc_msgcat,
						    ISC_MSGSET_GENERAL,
						    ISC_MSG_WAIT, "wait"));
			WAIT(&manager->work_available, &manager->lock);
			XTHREADTRACE(isc_msgcat_get(isc_msgcat,
						    ISC_MSGSET_TASK,
						    ISC_MSG_AWAKE, "awake"));
		}
#else /* ISC_PLATFORM_USETHREADS */
		if (total_dispatch_count >= DEFAULT_TASKMGR_QUANTUM ||
		    EMPTY(manager->ready_tasks))
			break;
#endif /* ISC_PLATFORM_USETHREADS */
		XTHREADTRACE(isc_msgcat_get(isc_msgcat, ISC_MSGSET_TASK,
					    ISC_MSG_WORKING, "working"));

		task = HEAD(manager->ready_tasks);
		if (task != NULL) {
			unsigned int dispatch_count = 0;
			isc_boolean_t done = ISC_FALSE;
			isc_boolean_t requeue = ISC_FALSE;
			isc_boolean_t finished = ISC_FALSE;
			isc_event_t *event;

			INSIST(VALID_TASK(task));

			/*
			 * Note we only unlock the manager lock if we actually
			 * have a task to do.  We must reacquire the manager
			 * lock before exiting the 'if (task != NULL)' block.
			 */
			DEQUEUE(manager->ready_tasks, task, ready_link);
			manager->tasks_running++;
			UNLOCK(&manager->lock);

			LOCK(&task->lock);
			INSIST(task->state == task_state_ready);
			task->state = task_state_running;
			XTRACE(isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL,
					      ISC_MSG_RUNNING, "running"));
			isc_stdtime_get(&task->now);
			do {
				if (!EMPTY(task->events)) {
					event = HEAD(task->events);
					DEQUEUE(task->events, event, ev_link);

					/*
					 * Execute the event action.
					 */
					XTRACE(isc_msgcat_get(isc_msgcat,
							    ISC_MSGSET_TASK,
							    ISC_MSG_EXECUTE,
							    "execute action"));
					if (event->ev_action != NULL) {
						UNLOCK(&task->lock);
						(event->ev_action)(task,event);
						LOCK(&task->lock);
					}
					dispatch_count++;
#ifndef ISC_PLATFORM_USETHREADS
					total_dispatch_count++;
#endif /* ISC_PLATFORM_USETHREADS */
				}

				if (task->references == 0 &&
				    EMPTY(task->events) &&
				    !TASK_SHUTTINGDOWN(task)) {
					isc_boolean_t was_idle;

					/*
					 * There are no references and no
					 * pending events for this task,
					 * which means it will not become
					 * runnable again via an external
					 * action (such as sending an event
					 * or detaching).
					 *
					 * We initiate shutdown to prevent
					 * it from becoming a zombie.
					 *
					 * We do this here instead of in
					 * the "if EMPTY(task->events)" block
					 * below because:
					 *
					 *	If we post no shutdown events,
					 *	we want the task to finish.
					 *
					 *	If we did post shutdown events,
					 *	will still want the task's
					 *	quantum to be applied.
					 */
					was_idle = task_shutdown(task);
					INSIST(!was_idle);
				}

				if (EMPTY(task->events)) {
					/*
					 * Nothing else to do for this task
					 * right now.
					 */
					XTRACE(isc_msgcat_get(isc_msgcat,
							      ISC_MSGSET_TASK,
							      ISC_MSG_EMPTY,
							      "empty"));
					if (task->references == 0 &&
					    TASK_SHUTTINGDOWN(task)) {
						/*
						 * The task is done.
						 */
						XTRACE(isc_msgcat_get(
							       isc_msgcat,
							       ISC_MSGSET_TASK,
							       ISC_MSG_DONE,
							       "done"));
						finished = ISC_TRUE;
						task->state = task_state_done;
					} else
						task->state = task_state_idle;
					done = ISC_TRUE;
				} else if (dispatch_count >= task->quantum) {
					/*
					 * Our quantum has expired, but
					 * there is more work to be done.
					 * We'll requeue it to the ready
					 * queue later.
					 *
					 * We don't check quantum until
					 * dispatching at least one event,
					 * so the minimum quantum is one.
					 */
					XTRACE(isc_msgcat_get(isc_msgcat,
							      ISC_MSGSET_TASK,
							      ISC_MSG_QUANTUM,
							      "quantum"));
					task->state = task_state_ready;
					requeue = ISC_TRUE;
					done = ISC_TRUE;
				}
			} while (!done);
			UNLOCK(&task->lock);

			if (finished)
				task_finished(task);

			LOCK(&manager->lock);
			manager->tasks_running--;
#ifdef ISC_PLATFORM_USETHREADS
			if (manager->exclusive_requested &&
			    manager->tasks_running == 1) {
				SIGNAL(&manager->exclusive_granted);
			}
#endif /* ISC_PLATFORM_USETHREADS */
			if (requeue) {
				/*
				 * We know we're awake, so we don't have
				 * to wakeup any sleeping threads if the
				 * ready queue is empty before we requeue.
				 *
				 * A possible optimization if the queue is
				 * empty is to 'goto' the 'if (task != NULL)'
				 * block, avoiding the ENQUEUE of the task
				 * and the subsequent immediate DEQUEUE
				 * (since it is the only executable task).
				 * We don't do this because then we'd be
				 * skipping the exit_requested check.  The
				 * cost of ENQUEUE is low anyway, especially
				 * when you consider that we'd have to do
				 * an extra EMPTY check to see if we could
				 * do the optimization.  If the ready queue
				 * were usually nonempty, the 'optimization'
				 * might even hurt rather than help.
				 */
#ifdef ISC_PLATFORM_USETHREADS
				ENQUEUE(manager->ready_tasks, task,
					ready_link);
#else
				ENQUEUE(ready_tasks, task, ready_link);
#endif
			}
		}
	}
#ifndef ISC_PLATFORM_USETHREADS
	ISC_LIST_APPENDLIST(manager->ready_tasks, ready_tasks, ready_link);
#endif
	UNLOCK(&manager->lock);
}
示例#25
0
文件: table.c 项目: sharugupta/OpenUH
/*
 * Read table from stdin, without assuming options section is sorted.
 */
static void read_table(void) 
{
	char line[512];
	char line2[512];
        char *option_lines[MAX_OPTIONS];
        int option_line_count = 0;
	char *p;
	int section = 0;
	int i = num_options;
        int j;

	strcpy(options[i].flag, "O_Unrecognized");
	options[i].internal = TRUE;
	strcpy(options[i].name, "");
	options[i].implies = NULL;
	i++;

        option_line_count = 0;
        while (get_line(line) != EOF) {
            char* s;

	    if (EMPTY(line)) 
              continue;
	    else if (line[0] == '%')
              continue;
	    else if (line[0] == ' ' && line[1] == NIL)
              continue;
	    else if (line[0] == '\t')
                internal_error("unexpected line (help msg?): %s", line);
	    else if (line[0] != '-' && line[0] != 'I')
                internal_error("unexpected line: [%s]", line);

	    if (get_line(line2) == EOF)
                internal_error("unexpected EOF for line2");

            s = malloc(strlen(line) + strlen(line2) + 4);
            if (s == NULL)
              internal_error("memory allocation failed");
	    sprintf(s, "%s %c %s", line, FIELD_DIVIDER, line2);

            option_lines[option_line_count] = s;
            INCREMENT_INDEX(option_line_count, MAX_OPTIONS);
        }
         
        qsort(option_lines, option_line_count, sizeof(char*),
              reverse_strcmp);

        /* Process the option lines */
        for (j = 0; j < option_line_count; ++j) {
          /* <name> <action> <langs> <phases> <implies> */
            p = strtok(option_lines[j], SPACE);
            if (*p == 'I') {
              options[i].internal = TRUE;
              p++;
            } else
              options[i].internal = FALSE;
            if (*p != '-') 
              internal_error("MISSING - : %s", p);
            options[i].syntax = 
              set_option_name(options[i].name, p, &options[i].num_letters);
            if (options[i].syntax == normal 
                && strlen(options[i].name) == 2)
              options[i].syntax = oneletter;
            set_flag_name(&options[i]);
            p = strtok(NULL, SPACE); 
            store_string(options[i].action, p, ";");
            if (strncmp(p, "toggle", 6) == 0)
              options[i].toggle = TRUE;
            else
              options[i].toggle = FALSE;
            if (!table_for_phase) {
              p = strtok(NULL, SPACE); 
              options[i].languages = create_lang_field(p);
              if ( options[i].internal ) {
                options[i].languages |=
                  get_language_mask ( L_internal );
              }
              p = strtok(NULL, SPACE); 
              options[i].phases = create_phase_field(p);
            }
            options[i].implies = create_option_list(&p,i);
            options[i].help = create_help_msg(p);
            INCREMENT_INDEX(i, MAX_OPTIONS);
        }

	check_dups();
	

        num_options = i;
}
示例#26
0
void copy_to_cooked(struct tty_struct * tty)
{
	signed char c;

	while (!EMPTY(tty->read_q) && !FULL(tty->secondary)) {
		GETCH(tty->read_q,c);
		if (c==13)
			if (I_CRNL(tty))
				c=10;
			else if (I_NOCR(tty))
				continue;
			else ;
		else if (c==10 && I_NLCR(tty))
			c=13;
		if (I_UCLC(tty))
			c=tolower(c);
		if (L_CANON(tty)) {
			if (c==KILL_CHAR(tty)) {
				/* deal with killing the input line */
				while(!(EMPTY(tty->secondary) ||
				        (c=LAST(tty->secondary))==10 ||
				        c==EOF_CHAR(tty))) {
					if (L_ECHO(tty)) {
						if (c<32)
							PUTCH(127,tty->write_q);
						PUTCH(127,tty->write_q);
						tty->write(tty);
					}
					DEC(tty->secondary.head);
				}
				continue;
			}
			if (c==ERASE_CHAR(tty)) {
				if (EMPTY(tty->secondary) ||
				   (c=LAST(tty->secondary))==10 ||
				   c==EOF_CHAR(tty))
					continue;
				if (L_ECHO(tty)) {
					if (c<32)
						PUTCH(127,tty->write_q);
					PUTCH(127,tty->write_q);
					tty->write(tty);
				}
				DEC(tty->secondary.head);
				continue;
			}
			if (c==STOP_CHAR(tty)) {
				tty->stopped=1;
				continue;
			}
			if (c==START_CHAR(tty)) {
				tty->stopped=0;
				continue;
			}
		}
		if (L_ISIG(tty)) {
			if (c==INTR_CHAR(tty)) {
				tty_intr(tty,INTMASK);
				continue;
			}
			if (c==QUIT_CHAR(tty)) {
				tty_intr(tty,QUITMASK);
				continue;
			}
		}
		if (c==10 || c==EOF_CHAR(tty))
			tty->secondary.data++;
		if (L_ECHO(tty)) {
			if (c==10) {
				PUTCH(10,tty->write_q);
				PUTCH(13,tty->write_q);
			} else if (c<32) {
				if (L_ECHOCTL(tty)) {
					PUTCH('^',tty->write_q);
					PUTCH(c+64,tty->write_q);
				}
			} else
				PUTCH(c,tty->write_q);
			tty->write(tty);
		}
		PUTCH(c,tty->secondary);
	}
	wake_up(&tty->secondary.proc_list);
}
示例#27
0
int
res_nupdate(res_state statp, ns_updrec *rrecp_in, ns_tsig_key *key) {
	ns_updrec *rrecp;
	u_char answer[PACKETSZ];
	u_char *packet;
	struct zonegrp *zptr, tgrp;
	LIST(struct zonegrp) zgrps;
	int nzones = 0, nscount = 0, n;
	union res_sockaddr_union nsaddrs[MAXNS];

	packet = malloc(NS_MAXMSG);
	if (packet == NULL) {
		DPRINTF(("malloc failed"));
		return (0);
	}
	/* Thread all of the updates onto a list of groups. */
	INIT_LIST(zgrps);
	memset(&tgrp, 0, sizeof (tgrp));
	for (rrecp = rrecp_in; rrecp;
	     rrecp = LINKED(rrecp, r_link) ? NEXT(rrecp, r_link) : NULL) {
		int nscnt;
		/* Find the origin for it if there is one. */
		tgrp.z_class = rrecp->r_class;
		nscnt = res_findzonecut2(statp, rrecp->r_dname, tgrp.z_class,
					 RES_EXHAUSTIVE, tgrp.z_origin,
					 sizeof tgrp.z_origin, 
					 tgrp.z_nsaddrs, MAXNS);
		if (nscnt <= 0) {
			DPRINTF(("res_findzonecut failed (%d)", nscnt));
			goto done;
		}
		tgrp.z_nscount = nscnt;
		/* Find the group for it if there is one. */
		for (zptr = HEAD(zgrps); zptr != NULL; zptr = NEXT(zptr, z_link))
			if (ns_samename(tgrp.z_origin, zptr->z_origin) == 1 &&
			    tgrp.z_class == zptr->z_class)
				break;
		/* Make a group for it if there isn't one. */
		if (zptr == NULL) {
			zptr = malloc(sizeof *zptr);
			if (zptr == NULL) {
				DPRINTF(("malloc failed"));
				goto done;
			}
			*zptr = tgrp;
			zptr->z_flags = 0;
			INIT_LINK(zptr, z_link);
			INIT_LIST(zptr->z_rrlist);
			APPEND(zgrps, zptr, z_link);
		}
		/* Thread this rrecp onto the right group. */
		APPEND(zptr->z_rrlist, rrecp, r_glink);
	}

	for (zptr = HEAD(zgrps); zptr != NULL; zptr = NEXT(zptr, z_link)) {
		/* Construct zone section and prepend it. */
		rrecp = res_mkupdrec(ns_s_zn, zptr->z_origin,
				     zptr->z_class, ns_t_soa, 0);
		if (rrecp == NULL) {
			DPRINTF(("res_mkupdrec failed"));
			goto done;
		}
		PREPEND(zptr->z_rrlist, rrecp, r_glink);
		zptr->z_flags |= ZG_F_ZONESECTADDED;

		/* Marshall the update message. */
		n = res_nmkupdate(statp, HEAD(zptr->z_rrlist),
				  packet, NS_MAXMSG);
		DPRINTF(("res_mkupdate -> %d", n));
		if (n < 0)
			goto done;

		/* Temporarily replace the resolver's nameserver set. */
		nscount = res_getservers(statp, nsaddrs, MAXNS);
		res_setservers(statp, zptr->z_nsaddrs, zptr->z_nscount);

		/* Send the update and remember the result. */
		if (key != NULL) {
#ifdef _LIBC
			DPRINTF(("TSIG is not supported\n"));
			RES_SET_H_ERRNO(statp, NO_RECOVERY);
			goto done;
#else
			n = res_nsendsigned(statp, packet, n, key,
					    answer, sizeof answer);
#endif
		} else
			n = res_nsend(statp, packet, n, answer, sizeof answer);
		if (n < 0) {
			DPRINTF(("res_nsend: send error, n=%d (%s)\n",
				 n, strerror(errno)));
			goto done;
		}
		if (((HEADER *)answer)->rcode == NOERROR)
			nzones++;

		/* Restore resolver's nameserver set. */
		res_setservers(statp, nsaddrs, nscount);
		nscount = 0;
	}
 done:
	while (!EMPTY(zgrps)) {
		zptr = HEAD(zgrps);
		if ((zptr->z_flags & ZG_F_ZONESECTADDED) != 0)
			res_freeupdrec(HEAD(zptr->z_rrlist));
		UNLINK(zgrps, zptr, z_link);
		free(zptr);
	}
	if (nscount != 0)
		res_setservers(statp, nsaddrs, nscount);

	free(packet);
	return (nzones);
}
示例#28
0
static void ISR_16550 (ComPort *p)
{
	int		count;
	byte	source;
	byte	b;

	disable();
	while((source = inportb (p->uart + INTERRUPT_ID_REGISTER) & 0x07) != 1)
	{
		switch (source)
		{
			case IIR_RX_DATA_READY_INTERRUPT:
				do
				{
					b = inportb (p->uart + RECEIVE_BUFFER_REGISTER);
					if (!FULL(p->inputQueue))
					{
						ENQUEUE (p->inputQueue, b);
					}
					else
					{
						p->lineStatus |= LSR_OVERRUN_ERROR;
						p->statusUpdated = true;
					}
				} while (inportb (p->uart + LINE_STATUS_REGISTER) & LSR_DATA_READY);
				break;

			case IIR_TX_HOLDING_REGISTER_INTERRUPT:
				count = 16;
				while ((! EMPTY(p->outputQueue)) && count--)
				{
					DEQUEUE (p->outputQueue, b);
					outportb (p->uart + TRANSMIT_HOLDING_REGISTER, b);
				}
				break;

			case IIR_MODEM_STATUS_INTERRUPT:
				p->modemStatus = (inportb (p->uart + MODEM_STATUS_REGISTER) & MODEM_STATUS_MASK) | p->modemStatusIgnore;
				p->statusUpdated = true;
				break;

			case IIR_LINE_STATUS_INTERRUPT:
				p->lineStatus = inportb (p->uart + LINE_STATUS_REGISTER);
				p->statusUpdated = true;
				break;
		}
		source = inportb (p->uart + INTERRUPT_ID_REGISTER) & 0x07;
	}

	// check for lost IIR_TX_HOLDING_REGISTER_INTERRUPT on 16550a!
	if (inportb (p->uart + LINE_STATUS_REGISTER ) & LSR_TRANSMITTER_EMPTY)
	{
		count = 16;
		while ((! EMPTY(p->outputQueue)) && count--)
		{
			DEQUEUE (p->outputQueue, b);
			outportb (p->uart + TRANSMIT_HOLDING_REGISTER, b);
		}
	}

	outportb (0x20, 0x20);
}
示例#29
0
 /*!
  * Add a new element to the set, even if the element already exists in the set.
  *
  *  @param[in] key      The element to add.
  */
 void Add(KEY key)                                     { _map.Add(key, EMPTY()); }
示例#30
0
文件: vte.c 项目: Aligorith/geany
void vte_init(void)
{
	if (vte_info.have_vte == FALSE)
	{	/* vte_info.have_vte can be false even if VTE is compiled in, think of command line option */
		geany_debug("Disabling terminal support");
		return;
	}

	if (!EMPTY(vte_info.lib_vte))
	{
		module = g_module_open(vte_info.lib_vte, G_MODULE_BIND_LAZY);
	}
#ifdef VTE_MODULE_PATH
	else
	{
		module = g_module_open(VTE_MODULE_PATH, G_MODULE_BIND_LAZY);
	}
#endif

	if (module == NULL)
	{
		gint i;
		const gchar *sonames[] = {
#if GTK_CHECK_VERSION(3, 0, 0)
			"libvte2_90.so", "libvte2_90.so.9",
#else
			"libvte.so", "libvte.so.4", "libvte.so.8", "libvte.so.9",
#endif
			NULL
		};

		for (i = 0; sonames[i] != NULL && module == NULL; i++)
		{
			module = g_module_open(sonames[i], G_MODULE_BIND_LAZY);
		}
	}

	if (module == NULL)
	{
		vte_info.have_vte = FALSE;
		geany_debug("Could not load libvte.so, embedded terminal support disabled");
		return;
	}
	else
	{
		vf = g_new0(struct VteFunctions, 1);
		if (vte_register_symbols(module))
			vte_info.have_vte = TRUE;
		else
		{
			vte_info.have_vte = FALSE;
			g_free(vf);
			/* FIXME: is closing the module safe? see vte_close() and test on FreeBSD */
			/*g_module_close(module);*/
			module = NULL;
			return;
		}
	}

	create_vte();

	/* setup the F10 menu override (so it works before the widget is first realised). */
	override_menu_key();
}