Beispiel #1
0
  /*-------------------*/
  void end() {
    if (out.getLevel() == 0) return; 

    newline(); 
  }
static
SCIP_DECL_BRANCHEXECPS(branchExecpsMyfullstrong)
{  /*lint --e{715}*/

	SCIP_PROBDATA*	probdata;
   SCIP_VAR**	cands;
   int	ncands;
	SCIP_NODE*	childnode_0;		/* z_j = 0 */
	SCIP_NODE*	childnode_1;		/* z_j = 1 */

	/* probdata */
	int	p;
	int	ndep;
	SCIP_VAR**	var_z;		/* [p] 01 variables */

	/* "_" means the matrix for blas */
	SCIP_Real*	orig_Q_;		/* [p*p] <- (X^t) X */
	SCIP_Real*	orig_q;		/* [p]   <- (X^t) y */
	SCIP_Real	r;

	int*	Mdep;					/* [ndep] */
	int*	groupX;				/* [ndep*p] */

	int	dim;
	SCIP_Real	RSS;			/* residual sum of square */
	SCIP_Real	RSS_new;
	SCIP_Real*	a;				/* [dim] */

	int	ublb;
	int	*Branchz;			/* [3*p] */
	int	*Branchz_new;		/* [3*p] */

	SCIP_Real*	Q_;	/* sub matrix of orig_Q_ */
	SCIP_Real*	Xy;	/* sub vector of orig_q */ 

	int*	list;			/* list of candidate variables */

	int	i,j,t,memo,ct;
	int	ind;
	int	dpv;

#if MYPARA_LOG
	printf("[myfullstrong brnaching]");
	Longline();
#endif

   /* get branching rule data */
	/*
   SCIP_BRANCHRULEDATA* branchruledata;
   branchruledata = SCIPbranchruleGetData(branchrule);
   assert(branchruledata != NULL);
	*/
	
	/* get problem data*/
	probdata = SCIPgetProbData(scip);
   assert(probdata != NULL);

	p	=	SCIPprobdataGetNexvars(probdata);
	ndep	=	SCIPprobdataGetNdep(probdata);

	orig_Q_	=	SCIPprobdataGetQ(probdata);
	orig_q	=	SCIPprobdataGetq(probdata);
	r	=	SCIPprobdataGetr(probdata);
	var_z		=	SCIPprobdataGetVars_z(probdata);

	if( ndep ){
		Mdep		=	SCIPprobdataGetMdep(probdata);
		groupX	=	SCIPprobdataGetgroupX(probdata);
	}else{
		Mdep		=	NULL;
		groupX	=	NULL;
	}

	/* alloc */
	SCIP_CALL( SCIPallocBufferArray(scip, &list, p));
	SCIP_CALL( SCIPallocBufferArray(scip, &Branchz, 3*p));
	SCIP_CALL( SCIPallocBufferArray(scip, &Branchz_new, 3*p));

	
	GenerateZeroVecInt( p, list);
	GenerateZeroVecInt( 3*p, Branchz);

   /* get pseudo candidates (non-fixed integer variables) */
   SCIP_CALL( SCIPgetPseudoBranchCands(scip, &cands, NULL, &ncands) );
	
	for(i=0; i<ncands; i++){
		for(j=0; j<p; j++){
			if( cands[i]==var_z[j] ){
				list[j] = 1;
				break;	
			}
		}
	}

#if MYPARA_LOG
	printf("list:");
	printintv( p, list);
#endif

	/* get branching info */
	for(i=0; i<p; ++i){
		ublb					=	SCIPround(scip, SCIPcomputeVarUbLocal(scip, var_z[i]) 
								+	SCIPcomputeVarLbLocal(scip, var_z[i]));
		*(Branchz+(ublb*p)+i) 	= 	1;
	}

#if MYPARA_LOG
	for(i=0; i<3; i++){
		for(j=0; j<p; j++){
			printf("%d, ", *(Branchz+(i*p)+j));
		}
		newline();
	}
#endif
	
	RSS = -1.0;
	ind = -1;

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

		/* copy */
		for(j=0; j<(3*p); j++){
			Branchz_new[j] = Branchz[j];
		}

		/* 
		 * solve 
		 *   Q a = Xy
		 */

		if( list[i] == 1 ){

			Branchz_new[i] = 1;
			Branchz_new[p+i] = 0;
			
			if( ndep ){
				for(t=0; t<ndep; t++){
					memo = -1; 
					for(j=0; j<p; j++){
						if( *(groupX+(t*p)+j)==1 ){
							if( Branchz_new[j]==1 ) break;
							if( Branchz_new[p+j]==1 ) memo=j;
							if( j==Mdep[t] ){
								if( memo==-1 ){
									printf("error in branch_myfullstrong.c\n");
									stop();
								}
								*(Branchz_new+p+memo) = 0;
								*(Branchz_new+memo) = 1;
								break;
							}
						}
					}
				}
			}

			dim = p - sumint( &Branchz_new[0], p);
	
			/* alloc */
			SCIP_CALL( SCIPallocBufferArray( scip, &a, dim));
			SCIP_CALL( SCIPallocBufferArray( scip, &Q_, dim*dim));
			SCIP_CALL( SCIPallocBufferArray( scip, &Xy, dim));

			/* generate Q and Xy */
			/* Q */
			ct = 0;
			for(j=0; j<p; j++){
				if( (Branchz_new[j]==0) && (j != i) ){
					for(t=0; t<p; t++){
						if( (Branchz_new[t]==0) && (t != i ) ){
							Q_[ct++] = mat_( orig_Q_, p, j, t);
						}
					}
				}
			}

			if( ct != (dim*dim) ){
				printf("error in branch_myfullstrong.c\n");
				stop();
			}

			/* Xy */
			ct = 0;
			for(j=0; j<p; j++){
				if( (Branchz_new[j]==0) && (j != i) ){
					Xy[ct++] = orig_q[j];
				}
			}

			if( ct != dim ){
				printf("error in branch_myfullstrong.c\n");
				stop();
			}

			dpv = _dposv_( Q_, Xy, dim, a);

			if( dpv == 0 ){
				/* test */
				RSS_new = RSSvalue( dim, a, Xy, r);
				if( RSS_new > RSS ){
					RSS = RSS_new;
					ind = i;
				}
#if MYPARA_LOG
				printf("%d: RSS = %f\n", i, RSS_new);
#endif
			}

			/* free */
			SCIPfreeBufferArray(scip, &Q_);
			SCIPfreeBufferArray(scip, &Xy);
			SCIPfreeBufferArray(scip, &a);

		 }
	}

#if MYPARA_LOG
	printf("max->%dth var. \n", ind);
#endif

	if( ind == -1 ){
		/* free */
		SCIPfreeBufferArray(scip, &list);
		SCIPfreeBufferArray(scip, &Branchz);
		SCIPfreeBufferArray(scip, &Branchz_new);

   	*result = SCIP_DIDNOTRUN;
		return SCIP_OKAY;
	}

	SCIP_CALL( SCIPbranchVar( scip, var_z[ind], &childnode_0, NULL, &childnode_1));

	/* free */
	SCIPfreeBufferArray(scip, &list);
	SCIPfreeBufferArray(scip, &Branchz);
	SCIPfreeBufferArray(scip, &Branchz_new);

   *result = SCIP_BRANCHED;

   return SCIP_OKAY;
}
Beispiel #3
0
void
tokenize(Lexer& lex) {
  while (lex.head != lex.tail) {
    switch (*lex.head) {
    case ' ':
    case '\t':
      if (std::size_t n = space(lex))
        consume(lex, n);
      break;

    case '\n':
      if (std::size_t n = newline(lex))
        consume_newline(lex, n);
      break;

    case '(':
      save_unigraph(lex, Left_paren_tok);
      break;

    case ')':
      save_unigraph(lex, Right_paren_tok);
      break;

    case ':':
      save_unigraph(lex, Colon_tok);
      break;

    case '.':
      save_unigraph(lex, Dot_tok);
      break;

    case '=':
      if (symbol(lex, "=="))
        save_digraph(lex, Equal_equal_tok);
      else
        invalid_char(lex);
      break;

    case '!':
      if (symbol(lex, "!="))
        save_digraph(lex, Not_equal_tok);
      else
        invalid_char(lex);
      break;

    case '+':
      save_unigraph(lex, Plus_tok);
      break;

    case '*':
      save_unigraph(lex, Star_tok);
      break;

    case '/':
      save_unigraph(lex, Div_tok);
      break;

    case '-':
      if (symbol(lex, "->"))
        save_digraph(lex, Imp_tok);
      else
        save_unigraph(lex, Minus_tok);
      break;

    case '<':
      if (symbol(lex, "<->"))
        save_trigraph(lex, Iff_tok);
      else if (symbol(lex, "<="))
        save_digraph(lex, Less_equal_tok);
      else
        save_unigraph(lex, Less_tok);
      break;

    case '>':
      if (symbol(lex, ">="))
        save_digraph(lex, Greater_equal_tok);
      else
        save_unigraph(lex, Greater_tok);
      break;

    case '0': case '1': case '2': case '3': case '4':
    case '5': case '6': case '7': case '8': case '9': {
      std::size_t n = int_literal(lex);
      save_token(lex, Int_literal_tok, n);
      break;
    }

    default:
      // Check for keywords and identifiers.
      if (std::isalpha(*lex.head)) {
        if (std::size_t n = identifier(lex)) {
          save_identifier(lex, n);
          break;
        }
      }
      else {
        invalid_char(lex);
      }

      break;
    }
  }
}
Beispiel #4
0
inline void addedchar(WINDOW *win){
win->cursorx++;
win->line[win->cursory].touched=true;
if (win->cursorx > win->width)
newline(win);
};
Beispiel #5
0
void ili9340_newline(void){
	newline();
}
Beispiel #6
0
/*
 * The scanner
 *
 */
int mcy_lex(void)
{
	static const WCHAR ustr_dot1[] = { '.', '\n', 0 };
	static const WCHAR ustr_dot2[] = { '.', '\r', '\n', 0 };
	static int isinit = 0;
	int ch;

	if(!isinit)
	{
		isinit++;
		set_codepage(WMC_DEFAULT_CODEPAGE);
		add_token(tok_keyword,	ustr_codepages,		tCODEPAGE,	0, NULL, 0);
		add_token(tok_keyword,	ustr_facility,		tFACILITY,	0, NULL, 1);
		add_token(tok_keyword,	ustr_facilitynames,	tFACNAMES,	0, NULL, 1);
		add_token(tok_keyword,	ustr_language,		tLANGUAGE,	0, NULL, 1);
		add_token(tok_keyword,	ustr_languagenames,	tLANNAMES,	0, NULL, 1);
		add_token(tok_keyword,	ustr_messageid,		tMSGID,		0, NULL, 1);
		add_token(tok_keyword,	ustr_messageidtypedef,	tTYPEDEF,	0, NULL, 1);
		add_token(tok_keyword,	ustr_outputbase,	tBASE,		0, NULL, 1);
		add_token(tok_keyword,	ustr_severity,		tSEVERITY,	0, NULL, 1);
		add_token(tok_keyword,	ustr_severitynames,	tSEVNAMES,	0, NULL, 1);
		add_token(tok_keyword,	ustr_symbolicname,	tSYMNAME,	0, NULL, 1);
		add_token(tok_severity,	ustr_error,		0x03,		0, NULL, 0);
		add_token(tok_severity,	ustr_warning,		0x02,		0, NULL, 0);
		add_token(tok_severity,	ustr_informational,	0x01,		0, NULL, 0);
		add_token(tok_severity,	ustr_success,		0x00,		0, NULL, 0);
		add_token(tok_facility,	ustr_application,	0xFFF,		0, NULL, 0);
		add_token(tok_facility,	ustr_system,		0x0FF,		0, NULL, 0);
		add_token(tok_language,	ustr_english,		0x409,		437, ustr_msg00001, 0);
	}

	empty_unichar_stack();

	while(1)
	{
		if(want_line)
		{
			while((ch = get_unichar()) != '\n')
			{
				if(ch == EOF)
					xyyerror("Unexpected EOF\n");
				push_unichar(ch);
			}
			newline();
			push_unichar(ch);
			push_unichar(0);
			if(!unistrcmp(ustr_dot1, get_unichar_stack()) || !unistrcmp(ustr_dot2, get_unichar_stack()))
			{
				want_line = 0;
				/* Reset the codepage to our default after each message */
				set_codepage(WMC_DEFAULT_CODEPAGE);
				return tMSGEND;
			}
			mcy_lval.str = xunistrdup(get_unichar_stack());
			return tLINE;
		}

		ch = get_unichar();

		if(ch == EOF)
			return EOF;

		if(ch == '\n')
		{
			newline();
			if(want_nl)
			{
				want_nl = 0;
				return tNL;
			}
			continue;
		}

		if(isisochar(ch))
		{
			if(want_file)
			{
				int n = 0;
				while(n < 8 && isisochar(ch))
				{
					int t = char_table[ch];
					if((t & CH_PUNCT) || !(t & CH_SHORTNAME))
						break;

					push_unichar(ch);
					n++;
					ch = get_unichar();
				}
				unget_unichar(ch);
				push_unichar(0);
				want_file = 0;
				mcy_lval.str = xunistrdup(get_unichar_stack());
				return tFILE;
			}

			if(char_table[ch] & CH_IDENT)
			{
				token_t *tok;
				while(isisochar(ch) && (char_table[ch] & (CH_IDENT|CH_NUMBER)))
				{
					push_unichar(ch);
					ch = get_unichar();
				}
				unget_unichar(ch);
				push_unichar(0);
				if(!(tok = lookup_token(get_unichar_stack())))
				{
					mcy_lval.str = xunistrdup(get_unichar_stack());
					return tIDENT;
				}
				switch(tok->type)
				{
				case tok_keyword:
					return tok->token;

				case tok_language:
					codepage = tok->codepage;
					/* Fall through */
				case tok_severity:
				case tok_facility:
					mcy_lval.tok = tok;
					return tTOKEN;

				default:
					internal_error(__FILE__, __LINE__, "Invalid token type encountered\n");
				}
			}

			if(isspace(ch))	/* Ignore space */
				continue;

			if(isdigit(ch))
				return scan_number(ch);
		}

		switch(ch)
		{
		case ':':
		case '=':
		case '+':
		case '(':
		case ')':
			return ch;
		case ';':
			while(ch != '\n' && ch != EOF)
			{
				push_unichar(ch);
				ch = get_unichar();
			}
			newline();
			push_unichar(ch);	/* Include the newline */
			push_unichar(0);
			mcy_lval.str = xunistrdup(get_unichar_stack());
			return tCOMMENT;
		default:
			xyyerror("Invalid character '%c' (0x%04x)\n", isisochar(ch) && isprint(ch) ? ch : '.', ch);
		}
	}
}
Beispiel #7
0
int
main(void)
{
  u2_init();
#ifdef BOOTLOADER
  putstr("\nUSRP N210 UDP bootloader\n");
#else
  putstr("\nTxRx-UHD-ZPU\n");
#endif
  printf("FPGA compatibility number: %d\n", USRP2_FPGA_COMPAT_NUM);
  printf("Firmware compatibility number: %d\n", USRP2_FW_COMPAT_NUM);
  
#ifdef BOOTLOADER
  //load the production FPGA image or firmware if appropriate
  do_the_bootload_thing();
  //if we get here we've fallen through to safe firmware
  set_default_mac_addr();
  set_default_ip_addr();
#endif

  print_mac_addr(ethernet_mac_addr()); newline();
  print_ip_addr(get_ip_addr()); newline();

  //1) register the addresses into the network stack
  register_addrs(ethernet_mac_addr(), get_ip_addr());
  pkt_ctrl_program_inspector(get_ip_addr(), USRP2_UDP_DSP0_PORT);

  //2) register callbacks for udp ports we service
  init_udp_listeners();
  register_udp_listener(USRP2_UDP_CTRL_PORT, handle_udp_ctrl_packet);
  register_udp_listener(USRP2_UDP_DSP0_PORT, handle_udp_data_packet);
  register_udp_listener(USRP2_UDP_ERR0_PORT, handle_udp_data_packet);
  register_udp_listener(USRP2_UDP_DSP1_PORT, handle_udp_data_packet);
#ifdef USRP2P
  register_udp_listener(USRP2_UDP_UPDATE_PORT, handle_udp_fw_update_packet);
#endif

  //3) set the routing mode to slave to set defaults
  pkt_ctrl_set_routing_mode(PKT_CTRL_ROUTING_MODE_SLAVE);

  //4) setup ethernet hardware to bring the link up
  ethernet_register_link_changed_callback(link_changed_callback);
  ethernet_init();

  while(true){

    size_t num_lines;
    void *buff = pkt_ctrl_claim_incoming_buffer(&num_lines);
    if (buff != NULL){
        handle_inp_packet((uint32_t *)buff, num_lines);
        pkt_ctrl_release_incoming_buffer();
    }

    pic_interrupt_handler();
    int pending = pic_regs->pending;		// poll for under or overrun

    if (pending & PIC_UNDERRUN_INT){
      pic_regs->pending = PIC_UNDERRUN_INT;	// clear interrupt
      putchar('U');
    }

    if (pending & PIC_OVERRUN_INT){
      pic_regs->pending = PIC_OVERRUN_INT;	// clear interrupt
      putchar('O');
    }
  }
}
Beispiel #8
0
tbreak(){
	register *i, j, pad;
	int res;

	trap = 0;
	if(nb)return;
	if((dip == d) && (v.nl == -1)){
		newline(1);
		return;
	}
	if(!nc){
		setnel();
		if(!wch)return;
		if(pendw)getword(1);
		movword();
	}else if(pendw && !brflg){
		getword(1);
		movword();
	}
	*linep = dip->nls = 0;
#ifdef NROFF
	if(dip == d)horiz(po);
#endif
	if(lnmod)donum();
	lastl = ne;
	if(brflg != 1){
		totout = 0;
	}else if(ad){
		if((lastl = (ll - un)) < ne)lastl = ne;
	}
	if(admod && ad && (brflg != 2)){
		lastl = ne;
		adsp = adrem = 0;
#ifdef NROFF
		if(admod == 1)un +=  quant(nel/2,t.Adj);
#endif
#ifndef NROFF
		if(admod == 1)un += nel/2;
#endif
		else if(admod ==2)un += nel;
	}
	totout++;
	brflg = 0;
	if((lastl+un) > dip->maxl)dip->maxl = (lastl+un);
	horiz(un);
#ifdef NROFF
	if(adrem%t.Adj)res = t.Hor; else res = t.Adj;
#endif
	for(i = line;nc > 0;){
		if(((j = *i++) & CMASK) == ' '){
			pad = 0;
			do{
				pad += width(j);
				nc--;
			  }while(((j = *i++) & CMASK) == ' ');
			i--;
			pad += adsp;
			--nwd;
			if(adrem){
				if(adrem < 0){
#ifdef NROFF
					pad -= res;
					adrem += res;
				}else if((totout&01) ||
					((adrem/res)>=(nwd))){
					pad += res;
					adrem -= res;
#endif
#ifndef NROFF
					pad--;
					adrem++;
				}else{
					pad++;
					adrem--;
#endif
				}
			}
			horiz(pad);
		}else{
			pchar(j);
			nc--;
		}
	}
	if(ic){
		if((j = ll - un - lastl + ics) > 0)horiz(j);
		pchar(ic);
	}
	if(icf)icf++;
		else ic = 0;
	ne = nwd = 0;
	un = in;
	setnel();
	newline(0);
	if(dip != d){if(dip->dnl > dip->hnl)dip->hnl = dip->dnl;}
	else{if(v.nl > dip->hnl)dip->hnl = v.nl;}
	for(j=ls-1; (j >0) && !trap; j--)newline(0);
	spread = 0;
}
Beispiel #9
0
int brw_disasm (FILE *file, struct brw_instruction *inst, int gen)
{
    int	err = 0;
    int space = 0;

    if (inst->header.predicate_control) {
	string (file, "(");
	err |= control (file, "predicate inverse", pred_inv, inst->header.predicate_inverse, NULL);
	format (file, "f%d", gen >= 7 ? inst->bits2.da1.flag_reg_nr : 0);
	if (inst->bits2.da1.flag_subreg_nr)
	    format (file, ".%d", inst->bits2.da1.flag_subreg_nr);
	if (inst->header.access_mode == BRW_ALIGN_1)
	    err |= control (file, "predicate control align1", pred_ctrl_align1,
			    inst->header.predicate_control, NULL);
	else
	    err |= control (file, "predicate control align16", pred_ctrl_align16,
			    inst->header.predicate_control, NULL);
	string (file, ") ");
    }

    err |= print_opcode (file, inst->header.opcode);
    err |= control (file, "saturate", saturate, inst->header.saturate, NULL);
    err |= control (file, "debug control", debug_ctrl, inst->header.debug_control, NULL);

    if (inst->header.opcode == BRW_OPCODE_MATH) {
	string (file, " ");
	err |= control (file, "function", math_function,
			inst->header.destreg__conditionalmod, NULL);
    } else if (inst->header.opcode != BRW_OPCODE_SEND &&
	       inst->header.opcode != BRW_OPCODE_SENDC) {
	err |= control (file, "conditional modifier", conditional_modifier,
			inst->header.destreg__conditionalmod, NULL);

        /* If we're using the conditional modifier, print which flags reg is
         * used for it.  Note that on gen6+, the embedded-condition SEL and
         * control flow doesn't update flags.
         */
	if (inst->header.destreg__conditionalmod &&
            (gen < 6 || (inst->header.opcode != BRW_OPCODE_SEL &&
                         inst->header.opcode != BRW_OPCODE_IF &&
                         inst->header.opcode != BRW_OPCODE_WHILE))) {
	    format (file, ".f%d", gen >= 7 ? inst->bits2.da1.flag_reg_nr : 0);
	    if (inst->bits2.da1.flag_subreg_nr)
		format (file, ".%d", inst->bits2.da1.flag_subreg_nr);
        }
    }

    if (inst->header.opcode != BRW_OPCODE_NOP) {
	string (file, "(");
	err |= control (file, "execution size", exec_size, inst->header.execution_size, NULL);
	string (file, ")");
    }

    if (inst->header.opcode == BRW_OPCODE_SEND && gen < 6)
	format (file, " %d", inst->header.destreg__conditionalmod);

    if (opcode[inst->header.opcode].nsrc == 3) {
       pad (file, 16);
       err |= dest_3src (file, inst);

       pad (file, 32);
       err |= src0_3src (file, inst);

       pad (file, 48);
       err |= src1_3src (file, inst);

       pad (file, 64);
       err |= src2_3src (file, inst);
    } else {
       if (opcode[inst->header.opcode].ndst > 0) {
	  pad (file, 16);
	  err |= dest (file, inst);
       } else if (gen == 7 && (inst->header.opcode == BRW_OPCODE_ELSE ||
			       inst->header.opcode == BRW_OPCODE_ENDIF ||
			       inst->header.opcode == BRW_OPCODE_WHILE)) {
	  format (file, " %d", inst->bits3.break_cont.jip);
       } else if (gen == 6 && (inst->header.opcode == BRW_OPCODE_IF ||
			       inst->header.opcode == BRW_OPCODE_ELSE ||
			       inst->header.opcode == BRW_OPCODE_ENDIF ||
			       inst->header.opcode == BRW_OPCODE_WHILE)) {
	  format (file, " %d", inst->bits1.branch_gen6.jump_count);
       } else if ((gen >= 6 && (inst->header.opcode == BRW_OPCODE_BREAK ||
                                inst->header.opcode == BRW_OPCODE_CONTINUE ||
                                inst->header.opcode == BRW_OPCODE_HALT)) ||
                  (gen == 7 && inst->header.opcode == BRW_OPCODE_IF)) {
	  format (file, " %d %d", inst->bits3.break_cont.uip, inst->bits3.break_cont.jip);
       } else if (inst->header.opcode == BRW_OPCODE_JMPI) {
	  format (file, " %d", inst->bits3.d);
       }

       if (opcode[inst->header.opcode].nsrc > 0) {
	  pad (file, 32);
	  err |= src0 (file, inst);
       }
       if (opcode[inst->header.opcode].nsrc > 1) {
	  pad (file, 48);
	  err |= src1 (file, inst);
       }
    }

    if (inst->header.opcode == BRW_OPCODE_SEND ||
	inst->header.opcode == BRW_OPCODE_SENDC) {
	enum brw_message_target target;

	if (gen >= 6)
	    target = inst->header.destreg__conditionalmod;
	else if (gen == 5)
	    target = inst->bits2.send_gen5.sfid;
	else
	    target = inst->bits3.generic.msg_target;

	newline (file);
	pad (file, 16);
	space = 0;

	if (gen >= 6) {
	   err |= control (file, "target function", target_function_gen6,
			   target, &space);
	} else {
	   err |= control (file, "target function", target_function,
			   target, &space);
	}

	switch (target) {
	case BRW_SFID_MATH:
	    err |= control (file, "math function", math_function,
			    inst->bits3.math.function, &space);
	    err |= control (file, "math saturate", math_saturate,
			    inst->bits3.math.saturate, &space);
	    err |= control (file, "math signed", math_signed,
			    inst->bits3.math.int_type, &space);
	    err |= control (file, "math scalar", math_scalar,
			    inst->bits3.math.data_type, &space);
	    err |= control (file, "math precision", math_precision,
			    inst->bits3.math.precision, &space);
	    break;
	case BRW_SFID_SAMPLER:
	    if (gen >= 7) {
		format (file, " (%d, %d, %d, %d)",
			inst->bits3.sampler_gen7.binding_table_index,
			inst->bits3.sampler_gen7.sampler,
			inst->bits3.sampler_gen7.msg_type,
			inst->bits3.sampler_gen7.simd_mode);
	    } else if (gen >= 5) {
		format (file, " (%d, %d, %d, %d)",
			inst->bits3.sampler_gen5.binding_table_index,
			inst->bits3.sampler_gen5.sampler,
			inst->bits3.sampler_gen5.msg_type,
			inst->bits3.sampler_gen5.simd_mode);
	    } else if (0 /* FINISHME: is_g4x */) {
		format (file, " (%d, %d)",
			inst->bits3.sampler_g4x.binding_table_index,
			inst->bits3.sampler_g4x.sampler);
	    } else {
		format (file, " (%d, %d, ",
			inst->bits3.sampler.binding_table_index,
			inst->bits3.sampler.sampler);
		err |= control (file, "sampler target format",
				sampler_target_format,
				inst->bits3.sampler.return_format, NULL);
		string (file, ")");
	    }
	    break;
	case BRW_SFID_DATAPORT_READ:
	    if (gen >= 6) {
		format (file, " (%d, %d, %d, %d)",
			inst->bits3.gen6_dp.binding_table_index,
			inst->bits3.gen6_dp.msg_control,
			inst->bits3.gen6_dp.msg_type,
			inst->bits3.gen6_dp.send_commit_msg);
	    } else if (gen >= 5 /* FINISHME: || is_g4x */) {
		format (file, " (%d, %d, %d)",
			inst->bits3.dp_read_gen5.binding_table_index,
			inst->bits3.dp_read_gen5.msg_control,
			inst->bits3.dp_read_gen5.msg_type);
	    } else {
		format (file, " (%d, %d, %d)",
			inst->bits3.dp_read.binding_table_index,
			inst->bits3.dp_read.msg_control,
			inst->bits3.dp_read.msg_type);
	    }
	    break;

	case BRW_SFID_DATAPORT_WRITE:
	    if (gen >= 7) {
		format (file, " (");

		err |= control (file, "DP rc message type",
				dp_rc_msg_type_gen6,
				inst->bits3.gen7_dp.msg_type, &space);

		format (file, ", %d, %d, %d)",
			inst->bits3.gen7_dp.binding_table_index,
			inst->bits3.gen7_dp.msg_control,
			inst->bits3.gen7_dp.msg_type);
	    } else if (gen == 6) {
		format (file, " (");

		err |= control (file, "DP rc message type",
				dp_rc_msg_type_gen6,
				inst->bits3.gen6_dp.msg_type, &space);

		format (file, ", %d, %d, %d, %d)",
			inst->bits3.gen6_dp.binding_table_index,
			inst->bits3.gen6_dp.msg_control,
			inst->bits3.gen6_dp.msg_type,
			inst->bits3.gen6_dp.send_commit_msg);
	    } else {
		format (file, " (%d, %d, %d, %d)",
			inst->bits3.dp_write.binding_table_index,
			(inst->bits3.dp_write.last_render_target << 3) |
			inst->bits3.dp_write.msg_control,
			inst->bits3.dp_write.msg_type,
			inst->bits3.dp_write.send_commit_msg);
	    }
	    break;

	case BRW_SFID_URB:
	    if (gen >= 5) {
		format (file, " %d", inst->bits3.urb_gen5.offset);
	    } else {
		format (file, " %d", inst->bits3.urb.offset);
	    }

	    space = 1;
	    if (gen >= 5) {
		err |= control (file, "urb opcode", urb_opcode,
				inst->bits3.urb_gen5.opcode, &space);
	    }
	    err |= control (file, "urb swizzle", urb_swizzle,
			    inst->bits3.urb.swizzle_control, &space);
	    err |= control (file, "urb allocate", urb_allocate,
			    inst->bits3.urb.allocate, &space);
	    err |= control (file, "urb used", urb_used,
			    inst->bits3.urb.used, &space);
	    err |= control (file, "urb complete", urb_complete,
			    inst->bits3.urb.complete, &space);
	    break;
	case BRW_SFID_THREAD_SPAWNER:
	    break;
	case GEN7_SFID_DATAPORT_DATA_CACHE:
	    format (file, " (%d, %d, %d)",
		    inst->bits3.gen7_dp.binding_table_index,
		    inst->bits3.gen7_dp.msg_control,
		    inst->bits3.gen7_dp.msg_type);
	    break;


	default:
	    format (file, "unsupported target %d", target);
	    break;
	}
	if (space)
	    string (file, " ");
	if (gen >= 5) {
	   format (file, "mlen %d",
		   inst->bits3.generic_gen5.msg_length);
	   format (file, " rlen %d",
		   inst->bits3.generic_gen5.response_length);
	} else {
	   format (file, "mlen %d",
		   inst->bits3.generic.msg_length);
	   format (file, " rlen %d",
		   inst->bits3.generic.response_length);
	}
    }
    pad (file, 64);
    if (inst->header.opcode != BRW_OPCODE_NOP) {
	string (file, "{");
	space = 1;
	err |= control(file, "access mode", access_mode, inst->header.access_mode, &space);
	if (gen >= 6)
	    err |= control (file, "write enable control", wectrl, inst->header.mask_control, &space);
	else
	    err |= control (file, "mask control", mask_ctrl, inst->header.mask_control, &space);
	err |= control (file, "dependency control", dep_ctrl, inst->header.dependency_control, &space);

	if (gen >= 6)
	    err |= qtr_ctrl (file, inst);
	else {
	    if (inst->header.compression_control == BRW_COMPRESSION_COMPRESSED &&
		opcode[inst->header.opcode].ndst > 0 &&
		inst->bits1.da1.dest_reg_file == BRW_MESSAGE_REGISTER_FILE &&
		inst->bits1.da1.dest_reg_nr & (1 << 7)) {
		format (file, " compr4");
	    } else {
		err |= control (file, "compression control", compr_ctrl,
				inst->header.compression_control, &space);
	    }
	}

	err |= control (file, "thread control", thread_ctrl, inst->header.thread_control, &space);
	if (gen >= 6)
	    err |= control (file, "acc write control", accwr, inst->header.acc_wr_control, &space);
	if (inst->header.opcode == BRW_OPCODE_SEND ||
	    inst->header.opcode == BRW_OPCODE_SENDC)
	    err |= control (file, "end of thread", end_of_thread,
			    inst->bits3.generic.end_of_thread, &space);
	if (space)
	    string (file, " ");
	string (file, "}");
    }
    string (file, ";");
    newline (file);
    return err;
}
Beispiel #10
0
static void act8()
{ 
		NLA = 7;
		newline ();   
	}
Beispiel #11
0
static void act3()
{ 
		NLA = 3;
		newline ();   
	}
 bool next() { return write(',') && newline(); }
Beispiel #13
0
void inputdata2(pointptr2 treenode)
{
  /* input the names and character state data for species */
  /* used in Mix & Penny */
  long i, j, l;
  char k;
  Char charstate;
  /* possible states are '0', '1', 'P', 'B', and '?' */

  if (printdata)
    headings(chars, "Characters", "----------");
  for (i = 0; i < (chars); i++)
    extras[i] = 0;
  for (i = 1; i <= spp; i++) {
    initname(i-1);
    if (printdata) {
      for (j = 0; j < nmlngth; j++)
        putc(nayme[i - 1][j], outfile);
    }
    fprintf(outfile, "   ");
    for (j = 0; j < (words); j++) {
      treenode[i - 1]->fulstte1[j] = 0;
      treenode[i - 1]->fulstte0[j] = 0;
      treenode[i - 1]->empstte1[j] = 0;
      treenode[i - 1]->empstte0[j] = 0;
    }
    for (j = 1; j <= (chars); j++) {
      k = (j - 1) % bits + 1;
      l = (j - 1) / bits + 1;
      do {
        if (eoln(infile)) 
          scan_eoln(infile);
        charstate = gettc(infile);
        if (charstate == '\n' || charstate == '\t')
          charstate = ' ';
      } while (charstate == ' ');
      if (charstate == 'b')          charstate = 'B';
      if (charstate == 'p')          charstate = 'P';
      if (charstate != '0' && charstate != '1' && charstate != '?' &&
          charstate != 'P' && charstate != 'B') {
        printf("\n\nERROR: Bad character state: %c ",charstate);
        printf("at character %ld of species %ld\n\n", j, i);
        exxit(-1);
      }
      if (printdata) {
        newline(outfile, j, 55, nmlngth + 3);
        putc(charstate, outfile);
        if (j % 5 == 0)
          putc(' ', outfile);
      }
      if (charstate == '1') {
        treenode[i-1]->fulstte1[l-1] =
          ((long)treenode[i-1]->fulstte1[l-1]) | (1L << k);
        treenode[i-1]->empstte1[l-1] =
          treenode[i-1]->fulstte1[l-1];
      }
      if (charstate == '0') {
        treenode[i-1]->fulstte0[l-1] =
          ((long)treenode[i-1]->fulstte0[l-1]) | (1L << k);
        treenode[i-1]->empstte0[l-1] =
          treenode[i-1]->fulstte0[l-1];
      }
      if (charstate == 'P' || charstate == 'B')
        extras[j-1] += weight[j-1];
    }
    scan_eoln(infile);
    if (printdata)
      putc('\n', outfile);
  }
  fprintf(outfile, "\n\n");
}  /* inputdata2 */
Beispiel #14
0
void inputdata(pointptr treenode,boolean dollo,boolean printdata,FILE *outfile)
{
  /* input the names and character state data for species */
  /* used in Dollop, Dolpenny, Dolmove, & Move */
  long i, j, l;
  char k;
  Char charstate;
  /* possible states are '0', '1', 'P', 'B', and '?' */

  if (printdata)
    headings(chars, "Characters", "----------");
  for (i = 0; i < (chars); i++)
    extras[i] = 0;
  for (i = 1; i <= spp; i++) {
    initname(i-1);
    if (printdata) {
      for (j = 0; j < nmlngth; j++)
        putc(nayme[i - 1][j], outfile);
      fprintf(outfile, "   ");
    }
    for (j = 0; j < (words); j++) {
      treenode[i - 1]->stateone[j] = 0;
      treenode[i - 1]->statezero[j] = 0;
    }
    for (j = 1; j <= (chars); j++) {
      k = (j - 1) % bits + 1;
      l = (j - 1) / bits + 1;
      do {
        if (eoln(infile)) 
          scan_eoln(infile);
        charstate = gettc(infile);
      } while (charstate == ' ' || charstate == '\t');
      if (charstate == 'b')
        charstate = 'B';
      if (charstate == 'p')
        charstate = 'P';
      if (charstate != '0' && charstate != '1' && charstate != '?' &&
          charstate != 'P' && charstate != 'B') {
        printf("\n\nERROR: Bad character state: %c ",charstate);
        printf("at character %ld of species %ld\n\n", j, i);
        exxit(-1);
      }
      if (printdata) {
        newline(outfile, j, 55, nmlngth + 3);
        putc(charstate, outfile);
        if (j % 5 == 0)
          putc(' ', outfile);
      }
      if (charstate == '1')
        treenode[i - 1]->stateone[l - 1] =
          ((long)treenode[i - 1]->stateone[l - 1]) | (1L << k);
      if (charstate == '0')
        treenode[i - 1]->statezero[l - 1] =
          ((long)treenode[i - 1]->statezero[l - 1]) | (1L << k);
      if (charstate == 'P' || charstate == 'B') {
        if (dollo)
          extras[j - 1] += weight[j - 1];
        else {
          treenode[i - 1]->stateone[l - 1] =
            ((long)treenode[i - 1]->stateone[l - 1]) | (1L << k);
          treenode[i - 1]->statezero[l - 1] =
            ((long)treenode[i - 1]->statezero[l - 1]) | (1L << k);
        }
      }
    }
    scan_eoln(infile);
    if (printdata)
      putc('\n', outfile);
  }
  if (printdata)
    fprintf(outfile, "\n\n");
}  /* inputdata */
void RecordOutputMgr::reportOverlapDetail(const Record *keyRecord, const Record *hitRecord, int hitIdx)
{
	//get the max start and min end as strings.
	const_cast<Record *>(hitRecord)->undoZeroLength();


	const QuickString *startStr = NULL;
	const QuickString *endStr = NULL;
	int maxStart = 0;
	int minEnd = 0;

	int keyStart = keyRecord->getStartPos();
	int keyEnd = keyRecord->getEndPos();
	int hitStart = hitRecord->getStartPos();
	int hitEnd = hitRecord->getEndPos();

	if (  keyStart>= hitStart) {
		//the key start is after the hit start, but we need to check and make sure the hit end is at least after the keyStart.
		//The reason for this is that, in some rare cases, such as both the key and hit having been zero length intervals,
		//the normal process for intersection that allows us to simply report the maxStart and minEnd do not necessarily apply.
		if (hitEnd >= keyStart) {
			//this is ok. We have a normal intersection where the key comes after the hit.
			maxStart = keyStart;
			startStr = &(keyRecord->getStartPosStr());
			minEnd = min(keyEnd, hitEnd);
			endStr = keyRecord->getEndPos() < hitRecord->getEndPos() ? &(keyRecord->getEndPosStr()) : &(hitRecord->getEndPosStr());
		} else {
			//this is the weird case of not a "real" intersection. The keyStart is greater than the hitEnd. So just report the key as is.
			maxStart = keyStart;
			minEnd = keyEnd;
			startStr = &(keyRecord->getStartPosStr());
			endStr = &(keyRecord->getEndPosStr());
		}

	} else {
		//all of the above, but backwards. keyStart is before hitStart.
		if (keyEnd >= hitStart) {
			//normal intersection, key first
			maxStart = hitStart;
			startStr = &(hitRecord->getStartPosStr());
			minEnd = min(keyEnd, hitEnd);
			endStr = keyRecord->getEndPos() < hitRecord->getEndPos() ? &(keyRecord->getEndPosStr()) : &(hitRecord->getEndPosStr());
		} else {
			//this is the weird case of not a "real" intersection. The hitStart is greater than the keyEnd. So just report the hit as is.
			maxStart = hitStart;
			minEnd = hitEnd;
			startStr = &(hitRecord->getStartPosStr());
			endStr = &(hitRecord->getEndPosStr());
		}
	}


	if (!(static_cast<ContextIntersect *>(_context))->getWriteA() && !(static_cast<ContextIntersect *>(_context))->getWriteB()
			&& !(static_cast<ContextIntersect *>(_context))->getWriteOverlap() && !(static_cast<ContextIntersect *>(_context))->getLeftJoin()) {
		printKey(keyRecord, *startStr, *endStr);
		newline();
		if (needsFlush()) flush();
	}
	else if (((static_cast<ContextIntersect *>(_context))->getWriteA() &&
			(static_cast<ContextIntersect *>(_context))->getWriteB()) || (static_cast<ContextIntersect *>(_context))->getLeftJoin()) {
		printKey(keyRecord);
		tab();
		addDbFileId(hitRecord->getFileIdx());
		hitRecord->print(_outBuf);
		newline();
		if (needsFlush()) flush();
	}
	else if ((static_cast<ContextIntersect *>(_context))->getWriteA()) {
		printKey(keyRecord);
		newline();
		if (needsFlush()) flush();
	}
	else if ((static_cast<ContextIntersect *>(_context))->getWriteB()) {
		printKey(keyRecord, *startStr, *endStr);
		tab();
		addDbFileId(hitRecord->getFileIdx());
		hitRecord->print(_outBuf);
		newline();
		if (needsFlush()) flush();
	}
	else if ((static_cast<ContextIntersect *>(_context))->getWriteOverlap()) {
		int printOverlapBases = 0;
		if (_context->getObeySplits()) {
			printOverlapBases = _context->getSplitBlockInfo()->getOverlapBases(hitIdx);
		} else {
			printOverlapBases = minEnd - maxStart;
		}
		printKey(keyRecord);
		tab();
		addDbFileId(hitRecord->getFileIdx());
		hitRecord->print(_outBuf);
		tab();
		int2str(printOverlapBases, _outBuf, true);
		newline();
		if (needsFlush()) flush();
	}
	const_cast<Record *>(hitRecord)->adjustZeroLength();
}
Beispiel #16
0
static void do_display(const struct termios *mode, int all)
{
	int i;
	tcflag_t *bitsp;
	unsigned long mask;
	int prev_type = control;

	display_speed(mode, 1);
	if (all)
		display_window_size(1);
#ifdef __linux__
	wrapf("line = %u;\n", mode->c_line);
#else
	newline();
#endif

	for (i = 0; i != CIDX_min; ++i) {
		char ch;
		/* If swtch is the same as susp, don't print both */
#if VSWTCH == VSUSP
		if (i == CIDX_swtch)
			continue;
#endif
		/* If eof uses the same slot as min, only print whichever applies */
#if VEOF == VMIN
		if (!(mode->c_lflag & ICANON)
		 && (i == CIDX_eof || i == CIDX_eol)
		) {
			continue;
		}
#endif
		ch = mode->c_cc[control_info[i].offset];
		if (ch == _POSIX_VDISABLE)
			strcpy(G.buf, "<undef>");
		else
			visible(ch, G.buf, 0);
		wrapf("%s = %s;", nth_string(control_name, i), G.buf);
	}
#if VEOF == VMIN
	if ((mode->c_lflag & ICANON) == 0)
#endif
		wrapf("min = %u; time = %u;", mode->c_cc[VMIN], mode->c_cc[VTIME]);
	newline();

	for (i = 0; i < NUM_mode_info; ++i) {
		if (mode_info[i].flags & OMIT)
			continue;
		if (mode_info[i].type != prev_type) {
			newline();
			prev_type = mode_info[i].type;
		}

		bitsp = get_ptr_to_tcflag(mode_info[i].type, mode);
		mask = mode_info[i].mask ? mode_info[i].mask : mode_info[i].bits;
		if ((*bitsp & mask) == mode_info[i].bits) {
			if (all || (mode_info[i].flags & SANE_UNSET))
				wrapf("-%s"+1, nth_string(mode_name, i));
		} else {
			if ((all && mode_info[i].flags & REV)
			 || (!all && (mode_info[i].flags & (SANE_SET | REV)) == (SANE_SET | REV))
			) {
				wrapf("-%s", nth_string(mode_name, i));
			}
		}
	}
	newline();
}
Beispiel #17
0
unsigned long
process_raf(FILE *inptr,unsigned long offset,
            struct image_summary *summary_entry,
            char *parent_name,int indent)
{
    unsigned long start_of_jpeg,jpeg_length,max_offset;
    unsigned long table1_offset,table2_offset;
    unsigned long table1_length,table2_length;
    unsigned long CFA_offset,CFA_length;
    unsigned long unknown2,CFA_primaryarraywidth,CFA_fullarraywidth;
    unsigned long Secondary_offset,Secondary_length;
    unsigned long unknown3,Secondary_arraywidth,Secondary_fullarraywidth;
    unsigned long unused_value;
    struct image_summary *tmp_summary_entry;
    int unused;
    char *fullname = CNULL;
    int chpr = 0;
    unsigned short tag;
    

    CFA_primaryarraywidth = Secondary_offset = table1_offset = table2_offset =  0UL;

    /* Record the primary for the image summary                       */
    if(((summary_entry == NULL) || summary_entry->entry_lock) ||
                        (summary_entry->imageformat != IMGFMT_NOIMAGE))
    {
        summary_entry = new_summary_entry(summary_entry,FILEFMT_RAF,IMGFMT_RAF);
    }
    if(summary_entry)
    {
        summary_entry->imageformat = IMGFMT_RAF;
        summary_entry->imagesubformat = IMGSUBFMT_CFA;
        summary_entry->entry_lock = lock_number(summary_entry);
    }
    chpr = newline(chpr);

    /* A short section of zeros; why?                                 */
    if((PRINT_SECTION))
    {
        print_tag_address(SECTION,offset,indent,"@");
        chpr += printf("<Offset Directory>");
        chpr = newline(chpr);
    }

    /* Some sort of ID or version?                                    */
    print_tag_address(ENTRY,offset,indent + SMALLINDENT,"@");
    if((PRINT_TAGINFO))
    {
        if((PRINT_LONGNAMES))
            chpr += printf("%s.",parent_name);
        chpr += printf("%-*.*s",TAGWIDTH,TAGWIDTH,"HeaderVersion");
    }
    if((PRINT_VALUE))
    {
        chpr += printf(" = ");
        print_ascii(inptr,4,offset);
    }
    chpr = newline(chpr);
    offset += 4;

    /* A 20 bytes section of zeros. Unknown                     */
    if((PRINT_SECTION))
    {
        print_tag_address(ENTRY,offset,indent + SMALLINDENT,"@");
        if((PRINT_VALUE))
            print_ubytes(inptr,20,offset);
        chpr = newline(chpr);
    }

    /* A jpeg reduced resolution image, complete with EXIF            */
    start_of_jpeg = read_ulong(inptr,TIFF_MOTOROLA,RAF_JPEGLOC);
    print_tag_address(ENTRY,RAF_JPEGLOC,indent + SMALLINDENT,"@");
    if((PRINT_TAGINFO))
    {
        if((PRINT_LONGNAMES))
            chpr += printf("%s.",parent_name);
        chpr += printf("%-*.*s",TAGWIDTH,TAGWIDTH,"JpegImageOffset");
    }
    if((PRINT_VALUE))
        chpr += printf(" = @%lu",start_of_jpeg);
    chpr = newline(chpr);
    print_tag_address(ENTRY,RAF_JPEGLOC + 4,indent + SMALLINDENT,"@");
    jpeg_length = read_ulong(inptr,TIFF_MOTOROLA,RAF_JPEGLOC + 4);
    if((PRINT_TAGINFO))
    {
        if((PRINT_LONGNAMES))
            chpr += printf("%s.",parent_name);
        chpr += printf("%-*.*s",TAGWIDTH,TAGWIDTH,"JpegImageLength");
    }
    if((PRINT_VALUE))
        chpr += printf(" = %lu",jpeg_length);
    chpr = newline(chpr);

    /* An offset to what may be a white balance table                 */
    print_tag_address(ENTRY,RAF_JPEGLOC + 8,indent + SMALLINDENT,"@");
    table1_offset = read_ulong(inptr,TIFF_MOTOROLA,RAF_JPEGLOC + 8);
    table1_length = read_ulong(inptr,TIFF_MOTOROLA,HERE);
    if((PRINT_TAGINFO))
    {
        if((PRINT_LONGNAMES))
            chpr += printf("%s.",parent_name);
        chpr += printf("%-*.*s",TAGWIDTH,TAGWIDTH,"Table1Offset");
    }
    if((PRINT_VALUE))
        chpr += printf(" = @%lu",table1_offset);
    chpr = newline(chpr);

    /* The length of the table; probably also the number of rows in   */
    /* the CFA array                                                  */
    print_tag_address(ENTRY,RAF_JPEGLOC + 12,indent + SMALLINDENT,"@");
    table1_length = read_ulong(inptr,TIFF_MOTOROLA,RAF_JPEGLOC + 12);
    if((PRINT_TAGINFO))
    {
        if((PRINT_LONGNAMES))
            chpr += printf("%s.",parent_name);
        chpr += printf("%-*.*s",TAGWIDTH,TAGWIDTH,"Table1Length");
    }
    if((PRINT_VALUE))
        chpr += printf(" = %lu",table1_length);
    chpr = newline(chpr);

    /* If there is a second table, this must be an SR Super CCD with  */
    /* a secondary CFA table containing the data for the secondary    */
    /* photodiodes. The start offset for the secondary data is offset */
    /* one row (2944 bytes) from the start of the primary data,       */
    /* suggesting that the primary and secondary CFA arrays are       */
    /* interleaved by rows (of 1472 unsigned shorts)                  */

    table2_offset = read_ulong(inptr,TIFF_MOTOROLA,RAF_JPEGLOC + 36);
    table2_length = read_ulong(inptr,TIFF_MOTOROLA,HERE);
    if(table2_offset == 0)
    {
        print_tag_address(ENTRY,RAF_JPEGLOC + 16,indent + SMALLINDENT,"@");
        CFA_offset = read_ulong(inptr,TIFF_MOTOROLA,RAF_JPEGLOC + 16);
        CFA_length = read_ulong(inptr,TIFF_MOTOROLA,HERE);
        Secondary_length = 0;
        if((PRINT_TAGINFO))
        {
            if((PRINT_LONGNAMES))
                chpr += printf("%s.",parent_name);
            chpr += printf("%-*.*s",TAGWIDTH,TAGWIDTH,"CFAOffset");
        }
        if((PRINT_VALUE))
            chpr += printf(" = @%lu",CFA_offset);
        chpr = newline(chpr);
        print_tag_address(ENTRY,RAF_JPEGLOC + 20,indent + SMALLINDENT,"@");
        if((PRINT_TAGINFO))
        {
            if((PRINT_LONGNAMES))
                chpr += printf("%s.",parent_name);
            chpr += printf("%-*.*s",TAGWIDTH,TAGWIDTH,"CFALength");
        }
        if((PRINT_VALUE))
            chpr += printf(" = %lu",CFA_length);
        chpr = newline(chpr);
        for(unused = 24; unused < 64; unused += 4)
        {
            print_tag_address(ENTRY,RAF_JPEGLOC + unused,indent + SMALLINDENT,"@");
            unused_value = read_ulong(inptr,TIFF_MOTOROLA,(unsigned long)(RAF_JPEGLOC + unused));
            if((PRINT_TAGINFO))
            {
                if((PRINT_LONGNAMES))
                    chpr += printf("%s.",parent_name);
                chpr += printf("%s%-2d%*.*s","unused",(unused - 24)/4 + 1,TAGWIDTH-8,TAGWIDTH-8," ");
            }
            if((PRINT_VALUE))
                chpr += printf(" = %lu",unused_value);
            chpr = newline(chpr);
        }
    }
    else
    {
        /* No secondary; easy.                                        */
        CFA_offset = read_ulong(inptr,TIFF_MOTOROLA,RAF_JPEGLOC + 16);
        CFA_length = read_ulong(inptr,TIFF_MOTOROLA,RAF_JPEGLOC + 20);

        print_tag_address(ENTRY,RAF_JPEGLOC + 16,indent + SMALLINDENT,"@");
        if((PRINT_TAGINFO))
        {
            if((PRINT_LONGNAMES))
                chpr += printf("%s.",parent_name);
            chpr += printf("%-*.*s",TAGWIDTH,TAGWIDTH,"CFA_Offset");
        }
        if((PRINT_VALUE))
            chpr += printf(" = @%lu",CFA_offset);
        chpr = newline(chpr);

        print_tag_address(ENTRY,RAF_JPEGLOC + 20,indent + SMALLINDENT,"@");
        if((PRINT_TAGINFO))
        {
            if((PRINT_LONGNAMES))
                chpr += printf("%s.",parent_name);
            chpr += printf("%-*.*s",TAGWIDTH,TAGWIDTH,"CFA_length");
        }
        if((PRINT_VALUE))
            chpr += printf(" = @%lu",CFA_length);
        chpr = newline(chpr);

        print_tag_address(ENTRY,RAF_JPEGLOC + 24,indent + SMALLINDENT,"@");
        unknown2 = read_ulong(inptr,TIFF_MOTOROLA,RAF_JPEGLOC + 24);
        if((PRINT_TAGINFO))
        {
            if((PRINT_LONGNAMES))
                chpr += printf("%s.",parent_name);
            chpr += printf("%-*.*s",TAGWIDTH,TAGWIDTH,"unknown2");
        }
        if((PRINT_VALUE))
            chpr += printf(" = %lu",unknown2);
        chpr = newline(chpr);

        CFA_primaryarraywidth = read_ulong(inptr,TIFF_MOTOROLA,RAF_JPEGLOC + 28);
        print_tag_address(ENTRY,RAF_JPEGLOC + 28,indent + SMALLINDENT,"@");
        if((PRINT_TAGINFO))
        {
            /* Array width in 16 bit unsigned shorts                  */
            if((PRINT_LONGNAMES))
                chpr += printf("%s.",parent_name);
            chpr += printf("%-*.*s",TAGWIDTH,TAGWIDTH,"CFAPrimaryArrayWidth");
        }
        if((PRINT_VALUE))
            chpr += printf(" = %lu",CFA_primaryarraywidth);
        chpr = newline(chpr);

        print_tag_address(ENTRY,RAF_JPEGLOC + 32,indent + SMALLINDENT,"@");
        CFA_fullarraywidth = read_ulong(inptr,TIFF_MOTOROLA,RAF_JPEGLOC + 32);
        if((PRINT_TAGINFO))
        {
            /* Array width in bytes                                   */
            if((PRINT_LONGNAMES))
                chpr += printf("%s.",parent_name);
            chpr += printf("%-*.*s",TAGWIDTH,TAGWIDTH,"CFAFullArrayWidth");
        }
        if((PRINT_VALUE))
            chpr += printf(" = %lu",CFA_fullarraywidth);
        chpr = newline(chpr);

        print_tag_address(ENTRY,RAF_JPEGLOC + 36,indent + SMALLINDENT,"@");
        if((PRINT_TAGINFO))
        {
            if((PRINT_LONGNAMES))
                chpr += printf("%s.",parent_name);
            chpr += printf("%-*.*s",TAGWIDTH,TAGWIDTH,"Table2Offset");
        }
        if((PRINT_VALUE))
            chpr += printf(" = @%lu",table2_offset);
        chpr = newline(chpr);
        print_tag_address(ENTRY,RAF_JPEGLOC + 40,indent + SMALLINDENT,"@");
        if((PRINT_TAGINFO))
        {
            if((PRINT_LONGNAMES))
                chpr += printf("%s.",parent_name);
            chpr += printf("%-*.*s",TAGWIDTH,TAGWIDTH,"Table2Length");
        }
        if((PRINT_VALUE))
            chpr += printf(" = %lu",table2_length);
        chpr = newline(chpr);

        /* It appears that the secondary CFA data is interlaced by    */
        /* row with the primary data.                                 */
        Secondary_offset = read_ulong(inptr,TIFF_MOTOROLA,RAF_JPEGLOC + 44);
        Secondary_length = read_ulong(inptr,TIFF_MOTOROLA,HERE);
        print_tag_address(ENTRY,RAF_JPEGLOC + 44,indent + SMALLINDENT,"@");
        if((PRINT_TAGINFO))
        {
            if((PRINT_LONGNAMES))
                chpr += printf("%s.",parent_name);
            chpr += printf("%-*.*s",TAGWIDTH,TAGWIDTH,"CFASecondaryOffset**");
        }
        if((PRINT_VALUE))
            chpr += printf(" = @%lu",Secondary_offset);
        chpr = newline(chpr);
        print_tag_address(ENTRY,RAF_JPEGLOC + 48,indent + SMALLINDENT,"@");
        if((PRINT_TAGINFO))
        {
            if((PRINT_LONGNAMES))
                chpr += printf("%s.",parent_name);
            chpr += printf("%-*.*s",TAGWIDTH,TAGWIDTH,"CFASecondaryLength**");
        }
        if((PRINT_VALUE))
            chpr += printf(" = %lu",Secondary_length);
        chpr = newline(chpr);

        unknown3 = read_ulong(inptr,TIFF_MOTOROLA,RAF_JPEGLOC + 52);
        Secondary_arraywidth = read_ulong(inptr,TIFF_MOTOROLA,RAF_JPEGLOC + 56);
        Secondary_fullarraywidth = read_ulong(inptr,TIFF_MOTOROLA,RAF_JPEGLOC + 60);
        print_tag_address(ENTRY,RAF_JPEGLOC + 52,indent + SMALLINDENT,"@");
        if((PRINT_TAGINFO))
        {
            if((PRINT_LONGNAMES))
                chpr += printf("%s.",parent_name);
            chpr += printf("%-*.*s",TAGWIDTH,TAGWIDTH,"unknown3");
        }
        if((PRINT_VALUE))
            chpr += printf(" = %lu",unknown3);
        chpr = newline(chpr);
        print_tag_address(ENTRY,RAF_JPEGLOC + 56,indent + SMALLINDENT,"@");
        if((PRINT_TAGINFO))
        {
            if((PRINT_LONGNAMES))
                chpr += printf("%s.",parent_name);
            chpr += printf("%-*.*s",TAGWIDTH,TAGWIDTH,"CFASecondaryArrayWidth");
        }
        if((PRINT_VALUE))
            chpr += printf(" = %lu",Secondary_arraywidth);
        chpr = newline(chpr);
        print_tag_address(ENTRY,RAF_JPEGLOC + 60,indent + SMALLINDENT,"@");
        if((PRINT_TAGINFO))
        {
            if((PRINT_LONGNAMES))
                chpr += printf("%s.",parent_name);
            /* I dunno what to call this...                           */
            chpr += printf("%-*.*s",TAGWIDTH,TAGWIDTH,"CFASecondaryFullArrayWidth");
        }
        if((PRINT_VALUE))
            chpr += printf(" = %lu",Secondary_fullarraywidth);
        chpr = newline(chpr);
    }
    if((PRINT_SECTION))
    {
        print_tag_address(SECTION,RAF_JPEGLOC + 63,indent,"@");
        chpr += printf("</Offset Directory>");
        chpr = newline(chpr);
    }

    /* Finish the summary entry                                       */
    if(summary_entry)
    {
        if(summary_entry->length <= 0)
            summary_entry->length = CFA_length + Secondary_length;
        if(summary_entry->offset <= 0)
            summary_entry->offset = CFA_offset;
        /* Not really compression; just record the presence of the    */
        /* secondary                                                  */
        if(Secondary_offset)
            summary_entry->compression = 1;
        else
            summary_entry->compression = 0;

        /* These aren't really pixel sizes, since the actual number   */
        /* of columns is half the arraywidth, and the array will have */
        /* to be rotated 45 degrees. And then there is the secondary  */
        /* pixel data...                                              */
        /* It's what we know, and post-processing can do what it      */
        /* wants.                                                     */
        if(CFA_primaryarraywidth)
        {
            summary_entry->pixel_width = CFA_primaryarraywidth;
            summary_entry->pixel_height = table1_length;
            summary_entry->primary_width = CFA_primaryarraywidth;
            summary_entry->primary_height = table1_length;
        }
        else
        {
            /* No size provided; this is the best we can do.          */
            summary_entry->pixel_width = (CFA_length + Secondary_length)/table1_length;
            summary_entry->pixel_height = table1_length;
            summary_entry->primary_width = summary_entry->pixel_width;
            summary_entry->primary_height = table1_length;
        }
        summary_entry->subfiletype = PRIMARY_TYPE;
    }
    
    /* Now display the offset sections, starting with the jpeg image  */
    /* (but only if showing sections)                                 */
    if((PRINT_SECTION))
    {
        print_tag_address(SECTION,start_of_jpeg,indent,"@");
        chpr += printf("#### Start of Jpeg Image, length %lu",jpeg_length);
        chpr = newline(chpr);
    }

    /* Is this really a jpeg section?                             */
    tag = read_ushort(inptr,TIFF_MOTOROLA,start_of_jpeg);
    if(tag == JPEG_SOI)
    {
        /* If so, process it regardless of output options, to pick up */
        /* information for the image summary                          */
        fullname = splice(parent_name,".","JPEG");
        max_offset = process_jpeg_segments(inptr,start_of_jpeg,JPEG_SOI,jpeg_length,
                                                summary_entry,fullname,"@",SMALLINDENT);
        print_jpeg_status();
        if(summary_entry)
        { 
            /* The jpeg summary entry should be next in the chain;    */
            /* there may be others following; mark the jpeg entry so  */
            /* that it will show up in the format summary.            */
            if((tmp_summary_entry = summary_entry->next_entry))
                tmp_summary_entry->filesubformat |= FILESUBFMT_JPEG;
        }
    }
    else
        dumpsection(inptr,start_of_jpeg,jpeg_length,indent + SMALLINDENT);

    if((PRINT_SECTION))
    {
        print_tag_address(SECTION,start_of_jpeg + jpeg_length - 1,indent,"@");
        chpr += printf("#### End of Jpeg Image, length %lu",jpeg_length);
        chpr = newline(chpr);

        print_tag_address(SECTION,table1_offset,indent,"@");
        chpr += printf("<Table 1> length %lu",table1_length);
        chpr = newline(chpr);
        if((PRINT_VALUE))
            dumpsection(inptr,table1_offset,table1_length,indent + SMALLINDENT);
        print_tag_address(SECTION,table1_offset + table1_length - 1,indent,"@");
        chpr += printf("</Table 1>");
        chpr = newline(chpr);

        if(table2_offset)
        {
            print_tag_address(SECTION,table2_offset,indent,"@");
            chpr += printf("<Table 2> length %lu",table2_length);
            chpr = newline(chpr);
            if((PRINT_VALUE))
                dumpsection(inptr,table2_offset,table2_length,indent + SMALLINDENT);
            print_tag_address(SECTION,table2_offset + table2_length - 1,indent,"@");
            chpr += printf("</Table 2>");
            chpr = newline(chpr);
        }

        /* The full CFA, with secondary if present                    */
        print_tag_address(SECTION,CFA_offset,indent,"@");
        chpr += printf("<CFA Image> length %lu",CFA_length + Secondary_length);
        chpr = newline(chpr);
        if((PRINT_VALUE))
            dumpsection(inptr,CFA_offset,CFA_length + Secondary_length,indent + SMALLINDENT);
        print_tag_address(SECTION,CFA_offset + CFA_length + Secondary_length - 1,indent,"@");
        chpr += printf("</CFA Image>");
        chpr = newline(chpr);

    }
    
    setcharsprinted(chpr);
    return(get_filesize(inptr));
}
Beispiel #18
0
int main(int argc, char ** argv) {

	/* I have a bad habit of being very C99, so this may not be everything */
	/* The default terminal is ANSI */
	char term[1024] = {'a','n','s','i', 0};
	int k, ttype;
	uint32_t option = 0, done = 0, sb_mode = 0, do_echo = 0;
	/* Various pieces for the telnet communication */
	char sb[1024] = {0};
	char sb_len   = 0;

	if (argc > 1) {
		if (!strcmp(argv[1], "-t")) {
			/* Yes, I know, lame way to get arguments, whatever, we only want one of them. */
			telnet = 1;

			/* Set the default options */
			set_options();

			/* Let the client know what we're using */
			for (option = 0; option < 256; option++) {
				if (telnet_options[option]) {
					send_command(telnet_options[option], option);
					fflush(stdout);
				}
			}
			for (option = 0; option < 256; option++) {
				if (telnet_willack[option]) {
					send_command(telnet_willack[option], option);
					fflush(stdout);
				}
			}

			/* Set the alarm handler to execute the longjmp */
			signal(SIGALRM, SIGALRM_handler);

			/* Negotiate options */
			if (!setjmp(environment)) {
				/* We will stop handling options after one second */
				alarm(1);

				/* Let's do this */
				while (!feof(stdin) && !done) {
					/* Get either IAC (start command) or a regular character (break, unless in SB mode) */
					unsigned char i = getchar();
					unsigned char opt = 0;
					if (i == IAC) {
						/* If IAC, get the command */
						i = getchar();
						switch (i) {
							case SE:
								/* End of extended option mode */
								sb_mode = 0;
								if (sb[0] == TTYPE) {
									/* This was a response to the TTYPE command, meaning
									 * that this should be a terminal type */
									alarm(0);
									strcpy(term, &sb[2]);
									goto ready;
								}
								break;
							case NOP:
								/* No Op */
								send_command(NOP, 0);
								fflush(stdout);
								break;
							case WILL:
							case WONT:
								/* Will / Won't Negotiation */
								opt = getchar();
								if (!telnet_willack[opt]) {
									/* We default to WONT */
									telnet_willack[opt] = WONT;
								}
								send_command(telnet_willack[opt], opt);
								fflush(stdout);
								if ((i == WILL) && (opt == TTYPE)) {
									/* WILL TTYPE? Great, let's do that now! */
									printf("%c%c%c%c%c%c", IAC, SB, TTYPE, SEND, IAC, SE);
									fflush(stdout);
								}
								break;
							case DO:
							case DONT:
								/* Do / Don't Negotation */
								opt = getchar();
								if (!telnet_options[opt]) {
									/* We default to DONT */
									telnet_options[opt] = DONT;
								}
								send_command(telnet_options[opt], opt);
								if (opt == ECHO) {
									/* We don't really need this, as we don't accept input, but,
									 * in case we do in the future, set our echo mode */
									do_echo = (i == DO);
								}
								fflush(stdout);
								break;
							case SB:
								/* Begin Extended Option Mode */
								sb_mode = 1;
								sb_len  = 0;
								memset(sb, 0, 1024);
								break;
							case IAC: 
								/* IAC IAC? That's probably not right. */
								done = 1;
								break;
							default:
								break;
						}
					} else if (sb_mode) {
						/* Extended Option Mode -> Accept character */
						if (sb_len < 1023) {
							/* Append this character to the SB string,
							 * but only if it doesn't put us over
							 * our limit; honestly, we shouldn't hit
							 * the limit, as we're only collecting characters
							 * for a terminal type, but better safe than
							 * sorry (and vulernable).
							 */
							sb[sb_len] = i;
							sb_len++;
						}
					}
				}
			}
		}
	} else {
		/* We are running standalone, retrieve the
		 * terminal type from the environment. */
		char * nterm = getenv("TERM");
		strcpy(term, nterm);
	}

	/*
	 * Labels. Yes, and I used a goto.
	 * If you're going to complain about this, you
	 * really need to reevaluate your approach to getting
	 * things done. This works, it works well, and there
	 * is absolutely, positively nothing wrong with using
	 * goto in C, so I'm going to do it.
	 */
ready:

	/* Convert the entire terminal string to lower case */
	for (k = 0; k < strlen(term); ++k) {
		term[k] = tolower(term[k]);
	}

	/* Do our terminal detection */
	if (strstr(term, "xterm")) {
		ttype = 1; /* 256-color, spaces */
	} else if (strstr(term, "linux")) {
		ttype = 3; /* Spaces and blink attribute */
	} else if (strstr(term, "vtnt")) {
		ttype = 5; /* Extended ASCII fallback == Windows */
	} else if (strstr(term, "cygwin")) {
		ttype = 5; /* Extended ASCII fallback == Windows */
	} else if (strstr(term, "vt220")) {
		ttype = 6; /* No color support */
	} else if (strstr(term, "fallback")) {
		ttype = 4; /* Unicode fallback */
	} else if (strstr(term, "rxvt")) {
		ttype = 3; /* Accepts LINUX mode */
	} else {
		ttype = 2; /* Everything else */
	}

	int always_escape = 0; /* Used for text mode */
	/* Accept ^C -> restore cursor */
	signal(SIGINT, SIGINT_handler);
	switch (ttype) {
		case 1:
			colors[',']  = "\033[48;5;17m";  /* Blue background */
			colors['.']  = "\033[48;5;15m";  /* White stars */
			colors['\''] = "\033[48;5;0m";   /* Black border */
			colors['@']  = "\033[48;5;230m"; /* Tan poptart */
			colors['$']  = "\033[48;5;175m"; /* Pink poptart */
			colors['-']  = "\033[48;5;162m"; /* Red poptart */
			colors['>']  = "\033[48;5;9m";   /* Red rainbow */
			colors['&']  = "\033[48;5;202m"; /* Orange rainbow */
			colors['+']  = "\033[48;5;11m";  /* Yellow Rainbow */
			colors['#']  = "\033[48;5;10m";  /* Green rainbow */
			colors['=']  = "\033[48;5;33m";  /* Light blue rainbow */
			colors[';']  = "\033[48;5;19m";  /* Dark blue rainbow */
			colors['*']  = "\033[48;5;8m";   /* Gray cat face */
			colors['%']  = "\033[48;5;175m"; /* Pink cheeks */
			break;
		case 2:
			colors[',']  = "\033[104m";      /* Blue background */
			colors['.']  = "\033[107m";      /* White stars */
			colors['\''] = "\033[40m";       /* Black border */
			colors['@']  = "\033[47m";       /* Tan poptart */
			colors['$']  = "\033[105m";      /* Pink poptart */
			colors['-']  = "\033[101m";      /* Red poptart */
			colors['>']  = "\033[101m";      /* Red rainbow */
			colors['&']  = "\033[43m";       /* Orange rainbow */
			colors['+']  = "\033[103m";      /* Yellow Rainbow */
			colors['#']  = "\033[102m";      /* Green rainbow */
			colors['=']  = "\033[104m";      /* Light blue rainbow */
			colors[';']  = "\033[44m";       /* Dark blue rainbow */
			colors['*']  = "\033[100m";      /* Gray cat face */
			colors['%']  = "\033[105m";      /* Pink cheeks */
			break;
		case 3:
			colors[',']  = "\033[25;44m";    /* Blue background */
			colors['.']  = "\033[5;47m";     /* White stars */
			colors['\''] = "\033[25;40m";    /* Black border */
			colors['@']  = "\033[5;47m";     /* Tan poptart */
			colors['$']  = "\033[5;45m";     /* Pink poptart */
			colors['-']  = "\033[5;41m";     /* Red poptart */
			colors['>']  = "\033[5;41m";     /* Red rainbow */
			colors['&']  = "\033[25;43m";    /* Orange rainbow */
			colors['+']  = "\033[5;43m";     /* Yellow Rainbow */
			colors['#']  = "\033[5;42m";     /* Green rainbow */
			colors['=']  = "\033[25;44m";    /* Light blue rainbow */
			colors[';']  = "\033[5;44m";     /* Dark blue rainbow */
			colors['*']  = "\033[5;40m";     /* Gray cat face */
			colors['%']  = "\033[5;45m";     /* Pink cheeks */
			break;
		case 4:
			colors[',']  = "\033[0;34;44m";  /* Blue background */
			colors['.']  = "\033[1;37;47m";  /* White stars */
			colors['\''] = "\033[0;30;40m";  /* Black border */
			colors['@']  = "\033[1;37;47m";  /* Tan poptart */
			colors['$']  = "\033[1;35;45m";  /* Pink poptart */
			colors['-']  = "\033[1;31;41m";  /* Red poptart */
			colors['>']  = "\033[1;31;41m";  /* Red rainbow */
			colors['&']  = "\033[0;33;43m";  /* Orange rainbow */
			colors['+']  = "\033[1;33;43m";  /* Yellow Rainbow */
			colors['#']  = "\033[1;32;42m";  /* Green rainbow */
			colors['=']  = "\033[1;34;44m";  /* Light blue rainbow */
			colors[';']  = "\033[0;34;44m";  /* Dark blue rainbow */
			colors['*']  = "\033[1;30;40m";  /* Gray cat face */
			colors['%']  = "\033[1;35;45m";  /* Pink cheeks */
			output = "██";
			break;
		case 5:
			colors[',']  = "\033[0;34;44m";  /* Blue background */
			colors['.']  = "\033[1;37;47m";  /* White stars */
			colors['\''] = "\033[0;30;40m";  /* Black border */
			colors['@']  = "\033[1;37;47m";  /* Tan poptart */
			colors['$']  = "\033[1;35;45m";  /* Pink poptart */
			colors['-']  = "\033[1;31;41m";  /* Red poptart */
			colors['>']  = "\033[1;31;41m";  /* Red rainbow */
			colors['&']  = "\033[0;33;43m";  /* Orange rainbow */
			colors['+']  = "\033[1;33;43m";  /* Yellow Rainbow */
			colors['#']  = "\033[1;32;42m";  /* Green rainbow */
			colors['=']  = "\033[1;34;44m";  /* Light blue rainbow */
			colors[';']  = "\033[0;34;44m";  /* Dark blue rainbow */
			colors['*']  = "\033[1;30;40m";  /* Gray cat face */
			colors['%']  = "\033[1;35;45m";  /* Pink cheeks */
			output = "\333\333";
			break;
		case 6:
			colors[',']  = "::";             /* Blue background */
			colors['.']  = "@@";             /* White stars */
			colors['\''] = "  ";             /* Black border */
			colors['@']  = "##";             /* Tan poptart */
			colors['$']  = "??";             /* Pink poptart */
			colors['-']  = "<>";             /* Red poptart */
			colors['>']  = "##";             /* Red rainbow */
			colors['&']  = "==";             /* Orange rainbow */
			colors['+']  = "--";             /* Yellow Rainbow */
			colors['#']  = "++";             /* Green rainbow */
			colors['=']  = "~~";             /* Light blue rainbow */
			colors[';']  = "$$";             /* Dark blue rainbow */
			colors['*']  = ";;";             /* Gray cat face */
			colors['%']  = "()";             /* Pink cheeks */
			always_escape = 1;
			break;
		default:
			break;
	}

	/* Attempt to set terminal title */
	printf("\033kNyanyanyanyanyanyanya...\033\134");
	printf("\033]1;Nyanyanyanyanyanyanya...\007");
	printf("\033]2;Nyanyanyanyanyanyanya...\007");

	/* Clear the screen */
	printf("\033[H\033[2J\033[?25l");

	/* Display the MOTD */
	int countdown_clock = 5;
	for (k = 0; k < countdown_clock; ++k) {
		newline(3);
		printf("                             \033[1mNyancat Telnet Server\033[0m");
		newline(2);
		printf("                   written and run by \033[1;32mKevin Lange\033[1;34m @kevinlange\033[0m");
		newline(2);
		printf("        If things don't look right, try:");
		newline(1);
		printf("                TERM=fallback telnet ...");
		newline(2);
		printf("        Or on Windows:");
		newline(1);
		printf("                telnet -t vtnt ...");
		newline(2);
		printf("        Problems? I am also a webserver:");
		newline(1);
		printf("                \033[1;34mhttp://miku.acm.uiuc.edu\033[0m");
		newline(2);
		printf("        This is a telnet server, remember your escape keys!");
		newline(1);
		printf("                \033[1;31m^]quit\033[0m to exit");
		newline(2);
		printf("        Starting in %d...                \n", countdown_clock-k);

		fflush(stdout);
		usleep(400000);
		printf("\033[H"); /* Reset cursor */
	}

	/* Clear the screen again */
	printf("\033[H\033[2J\033[?25l");

	/* Store the start time */
	time_t start, current;
	time(&start);

	int playing = 1; /* Animation should continue [left here for modifications] */
	size_t i = 0;    /* Current frame # */
	char last = 0;   /* Last color index rendered */
	size_t y, x;     /* x/y coordinates of what we're drawing */
	while (playing) {
		/* Render the frame */
		for (y = MIN_ROW; y < MAX_ROW; ++y) {
			for (x = MIN_COL; x < MAX_COL; ++x) {
				if (always_escape) {
					/* Text mode (or "Always Send Color Escapse") */
					printf("%s", colors[frames[i][y][x]]);
				} else {
					if (frames[i][y][x] != last && colors[frames[i][y][x]]) {
						/* Normal Mode, send escape (because the color changed) */
						last = frames[i][y][x];
						printf("%s%s", colors[frames[i][y][x]], output);
					} else {
						/* Same color, just send the output characters */
						printf("%s", output);
					}
				}
			}
			/* End of row, send newline */
			newline(1);
		}
		/* Get the current time for the "You have nyaned..." string */
		time(&current);
		double diff = difftime(current, start);
		/* Now count the length of the time difference so we can center */
		int nLen = digits((int)diff);
		int width = (80 - 29 - nLen) / 2;
		/* Spit out some spaces so that we're actually centered */
		while (width > 0) {
			printf(" ");
			width--;
		}
		/* You have nyaned for [n] seconds!
		 * The \033[J ensures that the rest of the line has the dark blue
		 * background, and the \033[1;37m ensures that our text is bright white
		 */
		printf("\033[1;37mYou have nyaned for %0.0f seconds!\033[J", diff);
		/* Reset the last color so that the escape sequences rewrite */
		last = 0;
		/* Update frame crount */
		++i;
		if (!frames[i]) {
			/* Loop animation */
			i = 0;
		}
		/* Reset cursor */
		printf("\033[H");
		/* Wait */
		usleep(90000);
	}
	return 0;
}
Beispiel #19
0
static void handle_inp_packet(uint32_t *buff, size_t num_lines){

  //test if its an ip recovery packet
  typedef struct{
      padded_eth_hdr_t eth_hdr;
      char code[4];
      union {
        struct ip_addr ip_addr;
      } data;
  }recovery_packet_t;
  recovery_packet_t *recovery_packet = (recovery_packet_t *)buff;
  if (recovery_packet->eth_hdr.ethertype == 0xbeee && strncmp(recovery_packet->code, "addr", 4) == 0){
      printf("Got ip recovery packet: "); print_ip_addr(&recovery_packet->data.ip_addr); newline();
      set_ip_addr(&recovery_packet->data.ip_addr);
      return;
  }

  //pass it to the slow-path handler
  handle_eth_packet(buff, num_lines);
}
int main (int argc, char **argv) {

  uint num_keys = 150;
  if (argc > 1) {
    num_keys = atoi (argv[1]);
  }

  srandom (time (NULL));

  merkle_tree *tree = New merkle_tree_disk ("/tmp/index.mrk", 
					    "/tmp/internal.mrk",
					    "/tmp/leaf.mrk", true);

  // if a trace is provided, execute the trace
  if (argc > 2) {
    str filename = argv[2];
    str file = file2str (filename);
    rxx newline ("\\n");
    vec<str> lines;
    split (&lines, newline, file);
    
    for (uint i = 0; i < lines.size(); i++) {
      if (i > num_keys) {
	warn << "did enough keys!\n";
	exit(0);
      }
      static const rxx space_rx ("\\s+");
      vec<str> parts;
      split (&parts, space_rx, lines[i]);
      if (parts.size() != 2) {
	continue;
      }
      chordID c;
      str2chordID (parts[1], c);
      if (parts[0] == "I") {
	warn << i << ") going to insert " << c << "\n";
	tree->insert (c);
      } else {
	warn << i << ") going to remove " << c << "\n";
	tree->remove (c);
      }
      tree->check_invariants ();
    }
    exit(0);
  }


  //tree->dump ();

  // inserts

  chordID c;
  for (uint i = 0; i < num_keys; i++) {
    c = make_randomID ();
    warn << "inserting " << c << " (" << i << ")\n";
    tree->insert (c);
    tree->check_invariants();
  }

  // lookups

  merkle_node_disk *n = (merkle_node_disk *) tree->lookup (to_merkle_hash (c));

  warn << "found node " << n->count << ": \n";

  if (n->isleaf ()) {
    merkle_key *k = n->keylist.first ();
    while (k != NULL) {
      warn << "\t" << k->id << "\n";
      k = n->keylist.next (k);
    }
  }

  tree->lookup_release (n);

  assert (tree->key_exists (c));

  // remove

  tree->remove (c);

  assert (!tree->key_exists (c));

  //tree->dump ();

  chordID min = c;
  chordID max = ((chordID) 1) << 156;
  vec<chordID> keys = tree->get_keyrange (min, max, 65);
  for (uint i = 0; i < keys.size (); i++) {
    warn << "Found key " << keys[i] << " in range [" 
	 << min << "," << max << "]\n";
  }
  delete tree;
  tree = NULL;

  unlink("/tmp/index.mrk");
  unlink("/tmp/internal.mrk");
  unlink("/tmp/leaf.mrk");
}
Beispiel #21
0
void
openplt(long n0, long n1, int sq0off, int sq1off, 
	char *xtitle, char *ytitle)
{
  char *getenv(), *sptr;
  time_t tt;

  tt = time(NULL);

  if (strlen(lvstr)>0) {
    sscanf(lvstr,"%lg %lg %lg",&elinval[0],&elinval[1],&elinval[2]);
  }
  else if ((sptr=getenv("LINEVAL"))!=NULL && strlen(sptr)>0) {
    sscanf(sptr,"%lg %lg %lg",&elinval[0],&elinval[1],&elinval[2]);
  }
	
  printf("%%!PS-Adobe-2.0\n");
  printf("%%%%Creator: plalign\n");
  printf("%%%%CreationDate: %s",ctime(&tt));
  printf("%%%%DocumentFonts: Courier\n");
  printf("%%%%Pages: 1\n");
  printf("%%%%BoundingBox: 18 18 564 588\n");
  printf("%%%%EndComments\n");
  printf("%%%%EndProlog\n");
  printf("%%%%Page: 1 1\n");
  printf("/Courier findfont 14 scalefont setfont\n");
  printf("/vcprint { gsave 90 rotate dup stringwidth pop 2 div neg 0 rmoveto\n");
  printf("show newpath stroke grestore } def\n");
  printf("/hcprint { gsave dup stringwidth pop 2 div neg 0 rmoveto\n");
  printf("show newpath stroke grestore } def\n");
  printf("/hrprint { gsave dup stringwidth pop neg 0 rmoveto\n");
  printf("show newpath stroke grestore } def\n");
  printf("/hprint { gsave show newpath stroke grestore } def\n");

  pmaxx = n0;
  pmaxy = n1;

  fxscal = (double)(max_x-1)/(double)(n1);
  fyscal = (double)(max_y-1)/(double)(n0);

  if (fxscal > fyscal) fxscal = fyscal;
  else fyscal = fxscal;

  if (fyscal * n0 < (double)max_y/5.0) 
    fyscal = (double)(max_y-1)/((double)(n0)*5.0);

  fxscal *= 0.9; fxoff = (double)(max_x-1)/11.0;
  fyscal *= 0.9; fyoff = (double)(max_y-1)/11.0;

  printf("%% openplt - frame - %ld %ld\n", n0, n1);
  linetype(0);
  printf("gsave\n");
  printf("currentlinewidth 1.5 mul setlinewidth\n");
  newline();
  move(SX(0),SY(0));
  draw(SX(0),SY(n1+1));
  draw(SX(n0+1),SY(n1+1));
  draw(SX(n0+1),SY(0));
  draw(SX(0),SY(0));
  clsline(n0,n1,100000);
  printf("grestore\n");
  xaxis(n0,sq1off, xtitle);
  yaxis(n1,sq0off, ytitle);
  legend();
  printf("%% openplt done\n");
}
Beispiel #22
0
/*
 *   Now we have the main procedure.
 */
void
dosection(sectiontype *s, int c)
{
   charusetype *cu;
   integer prevptr;
   int np;
   int k;
   integer thispage = 0;
   char buf[104];

   dopsfont(s);
#ifdef HPS
	 if (HPS_FLAG) pagecounter = 0;
#endif

   if (multiplesects) {
     setup();
   }
   cmdout("TeXDict");
   cmdout("begin");
   numout(hpapersize);
   numout(vpapersize);
   doubleout(mag);
   numout((integer)DPI);
   numout((integer)VDPI);
   snprintf(buf, sizeof(buf), "(%.99s)", fulliname);
   cmdout(buf);
   newline();
   cmdout("@start");
   if (multiplesects)
      cmdout("bos");
/*
 *   We insure raster is even-word aligned, because download might want that.
 */
   if (bytesleft & 1) {
      bytesleft--;
      raster++;
   }
   cleanres();
   cu = (charusetype *) (s + 1);
   psfont = 1;
   while (cu->fd) {
      if (cu->psfused)
         cu->fd->psflag = EXISTS;
      download(cu++, psfont++);
   }
   fonttableout();
   if (! multiplesects) {
      cmdout("end");
      setup();
   }
   for (cu=(charusetype *)(s+1); cu->fd; cu++)
      cu->fd->psflag = 0;
   while (c > 0) {
      c--;
      prevptr = s->bos;
      if (! reverse)
         fseek(dvifile, (long)prevptr, 0);
      np = s->numpages;
      while (np-- != 0) {
         if (reverse)
            fseek(dvifile, (long)prevptr, 0);
         pagenum = signedquad();
	 if ((evenpages && (pagenum & 1)) || (oddpages && (pagenum & 1)==0) ||
	  (pagelist && !InPageList(pagenum))) {
	    if (reverse) {
               skipover(36);
               prevptr = signedquad()+1;
	    } else {
               skipover(40);
	       skippage();
	       skipnop();
	    }
	    ++np;	/* this page wasn't counted for s->numpages */
	    continue;
	 }
/*
 *   We want to take the base 10 log of the number.  It's probably
 *   small, so we do it quick.
 */
         if (! quiet) {
            int t = pagenum, i = 0;
            if (t < 0) {
               t = -t;
               i++;
            }
            do {
               i++;
               t /= 10;
            } while (t > 0);
            if (pagecopies < 20)
               i += pagecopies - 1;
            if (i + prettycolumn > STDOUTSIZE) {
               fprintf(stderr, "\n");
               prettycolumn = 0;
            }
            prettycolumn += i + 1;
#ifdef SHORTINT
            fprintf(stderr, "[%ld", pagenum);
#else  /* ~SHORTINT */
            fprintf(stderr, "[%d", pagenum);
#endif /* ~SHORTINT */
            fflush(stderr);
         }
         skipover(36);
         prevptr = signedquad()+1;
         for (k=0; k<pagecopies; k++) {
            if (k == 0) {
               if (pagecopies > 1)
                  thispage = ftell(dvifile);
            } else {
               fseek(dvifile, (long)thispage, 0);
               if (prettycolumn + 1 > STDOUTSIZE) {
                  fprintf(stderr, "\n");
                  prettycolumn = 0;
               }
               fprintf(stderr, ".");
               fflush(stderr);
               prettycolumn++;
            }
            dopage();
         }
         if (! quiet) {
            fprintf(stderr, "] ");
            fflush(stderr);
            prettycolumn += 2;
         }
         if (! reverse)
            skipnop();
      }
   }
   if (! multiplesects && ! disablecomments) {
      newline();
      fprintf(bitfile, "%%%%Trailer\n");
   }
   if (multiplesects) {
      if (! disablecomments) {
         newline();
         fprintf(bitfile, "%%DVIPSSectionTrailer\n");
      }
      cmdout("eos");
      cmdout("end");
   }
#ifdef HPS
   if (HPS_FLAG) cmdout("\nend"); /* close off HPSDict */
#endif
   if (multiplesects && ! disablecomments) {
      newline();
      fprintf(bitfile, "%%DVIPSEndSection\n");
      linepos = 0;
   }
}
Beispiel #23
0
void commands(void)
{
    unsigned int *a1;
    int c;
    int temp;
    char lastsep;

    for (;;) {
        if (pflag) {
            pflag = 0;
            addr1 = addr2 = dot;
            print();
        }
        c = '\n';
        for (addr1 = 0;;) {
            lastsep = c;
            a1 = address();
            c = getchr();
            if (c!=',' && c!=';')
                break;
            if (lastsep==',')
                error(Q);
            if (a1==0) {
                a1 = zero+1;
                if (a1>dol)
                    a1--;
            }
            addr1 = a1;
            if (c==';')
                dot = a1;
        }
        if (lastsep!='\n' && a1==0)
            a1 = dol;
        if ((addr2=a1)==0) {
            given = 0;
            addr2 = dot;
        }
        else
            given = 1;
        if (addr1==0)
            addr1 = addr2;
        switch(c) {

        case 'a':
            add(0);
            continue;

        case 'c':
            nonzero();
            newline();
            rdelete(addr1, addr2);
            append(gettty, addr1-1);
            continue;

        case 'd':
            nonzero();
            newline();
            rdelete(addr1, addr2);
            continue;

        case 'E':
            fchange = 0;
            c = 'e';
        case 'e':
            setnoaddr();
            if (vflag && fchange) {
                fchange = 0;
                error(Q);
            }
            filename(c);
            init();
            addr2 = zero;
            goto caseread;

        case 'f':
            setnoaddr();
            filename(c);
            puts(savedfile);
            continue;

        case 'g':
            global(1);
            continue;

        case 'i':
            add(-1);
            continue;


        case 'j':
            if (!given)
                addr2++;
            newline();
            join();
            continue;

        case 'k':
            nonzero();
            if ((c = getchr()) < 'a' || c > 'z')
                error(Q);
            newline();
            names[c-'a'] = *addr2 & ~01;
            anymarks |= 01;
            continue;

        case 'm':
            move(0);
            continue;

        case 'n':
            listn++;
            newline();
            print();
            continue;

        case '\n':
            if (a1==0) {
                a1 = dot+1;
                addr2 = a1;
                addr1 = a1;
            }
            if (lastsep==';')
                addr1 = a1;
            print();
            continue;

        case 'l':
            listf++;
        case 'p':
        case 'P':
            newline();
            print();
            continue;

        case 'Q':
            fchange = 0;
        case 'q':
            setnoaddr();
            newline();
            quit(0);

        case 'r':
            filename(c);
caseread:
            if ((io = open(file, 0)) < 0) {
                lastc = '\n';
                error(file);
            }
            setwide();
            squeeze(0);
            ninbuf = 0;
            c = zero != dol;
            append(getfile, addr2);
            exfile();
            fchange = c;
            continue;

        case 's':
            nonzero();
            substitute(globp!=0);
            continue;

        case 't':
            move(1);
            continue;

        case 'u':
            nonzero();
            newline();
            if ((*addr2&~01) != subnewa)
                error(Q);
            *addr2 = subolda;
            dot = addr2;
            continue;

        case 'v':
            global(0);
            continue;

        case 'W':
            wrapp++;
        case 'w':
            setwide();
            squeeze(dol>zero);
            if ((temp = getchr()) != 'q' && temp != 'Q') {
                peekc = temp;
                temp = 0;
            }
            filename(c);
            if(!wrapp ||
                    ((io = open(file,1)) == -1) ||
                    ((lseek(io, 0L, 2)) == -1))
                if ((io = creat(file, 0666)) < 0)
                    error(file);
            wrapp = 0;
            if (dol > zero)
                putfile();
            exfile();
            if (addr1<=zero+1 && addr2==dol)
                fchange = 0;
            if (temp == 'Q')
                fchange = 0;
            if (temp)
                quit(0);
            continue;

        case '=':
            setwide();
            squeeze(0);
            newline();
            count = addr2 - zero;
            putd();
            putchr('\n');
            continue;

        case '!':
            callunix();
            continue;

        case EOF:
            return;

        }
        error(Q);
    }
}
Beispiel #24
0
Datei: waddch.c Projekt: 8l/FUZIX
int waddch(WINDOW *win, int c)
{
  int x = win->_curx;
  int y = win->_cury;
  int newx;
  int ch = c;
  int ts = win->_tabsize;

  ch &= (A_ALTCHARSET | 0xff);
  if (y > win->_maxy || x > win->_maxx || y < 0 || x < 0) return(ERR);
  switch (ch) {
      case '\t':
	for (newx = ((x / ts) + 1) * ts; x < newx; x++) {
		if (waddch(win, ' ') == ERR) return(ERR);
		if (win->_curx == 0)	/* if tab to next line */
			return(OK);	/* exit the loop */
	}
	return(OK);

      case '\n':
	if (NONL) x = 0;
	if ((y = newline(win, y)) < 0) return (ERR);
	break;

      case '\r':	x = 0;	break;

      case '\b':
	if (--x < 0)		/* no back over left margin */
		x = 0;
	break;

      case 0x7f:
	{
		if (waddch(win, '^') == ERR) return(ERR);
		return(waddch(win, '?'));
	}

      default:
	if (ch < ' ') {		/* handle control chars */
		if (waddch(win, '^') == ERR) return(ERR);
		return(waddch(win, c + '@'));
	}
	ch |= (win->_attrs & ATR_MSK);
	if (win->_line[y][x] != ch) {	/* only if data change */
		if (win->_minchng[y] == _NO_CHANGE)
			win->_minchng[y] = win->_maxchng[y] = x;
		else if (x < win->_minchng[y])
			win->_minchng[y] = x;
		else if (x > win->_maxchng[y])
			win->_maxchng[y] = x;
	}			/* if */
	*(*(win->_line + y)  + x++) = ch;
	if (x > win->_maxx) {	/* wrap around test */
		x = 0;
		if ((y = newline(win, y)) < 0) return(ERR);
	}
	break;

  }				/* switch */
  win->_curx = x;
  win->_cury = y;

  return(OK);
}
Beispiel #25
0
// see .h file for usage
bool ldp::pre_search(const char* pszFrame, bool block_until_search_finishes)
{
	char frame[FRAME_ARRAY_SIZE] = { 0 };
	Uint16 frame_number = 0;	// frame to search to
	bool result = false;
	char s1[81] = { 0 };

	// safety check, if they try to search without checking the search result ...
	if (m_status == LDP_SEARCHING)
	{
		if (m_bVerbose) printline("LDP : tried to search without checking for search result first! that's bad!");
		if (m_bVerbose) printline(frame);
		
		// this is definitely a Daphne bug if this happens, so log it!
		m_bug_log.push_back("LDP.CPP, pre_search() : tried to search without checking for search result first!");
		return false;
	}
	// end safety check

	// Get the frame that we are on now, before we do the seek
	// This is needed in order to calculate artificial seek delay
	// We must do this before we change 'm_status' due to the way get_current_frame is designed
	m_last_seeked_frame = m_uCurrentFrame;

	// we copy here so that we can safely null-terminate
	strncpy(frame, pszFrame, 5);
	frame[5] = 0;	// terminate the string ...
	frame_number = (Uint16) atoi(frame);

	// If we're seeking to the frame we're already on, then don't seek
	// This optimizes performance for many games and especially improves the coin insert delay
	//  for Dragon's Lair 2.
	if ((m_status == LDP_PAUSED) && (frame_number == m_uCurrentFrame))
	{
		if (m_bVerbose) printline("LDP NOTE: ignoring seek because we're already on that frame");
		m_status = LDP_PAUSED;	// just to be safe
		return true;
	}

	m_status = LDP_SEARCHING;	// searching can take a while

	// If we need to alter the frame # before searching
	if (need_frame_conversion())
	{
		Uint16 unadjusted_frame = frame_number;
		frame_number = (Uint16) do_frame_conversion(frame_number);
		framenum_to_frame(frame_number, frame);
		sprintf(s1, "Search to %d (formerly %d) received", frame_number, unadjusted_frame);
	}
	else
	{
		sprintf(s1, "Search to %d received", frame_number);
	}

	if (m_bVerbose) outstr(s1);

	// notify us if we're still using outdated blocking searching
	if (block_until_search_finishes && m_bVerbose ) outstr(" [blocking] ");

	// if it's Dragon's Lair/Space Ace, print the board we are on
	if ((g_game->get_game_type() == GAME_LAIR) || (g_game->get_game_type() == GAME_DLE1)
		|| (g_game->get_game_type() == GAME_DLE2)
		|| (g_game->get_game_type() == GAME_ACE))
	{
		Uint8 *cpumem = get_cpu_mem(0);	// get the memory for the first (and only)
		outstr(" - ");
		print_board_info(cpumem[0xA00E], cpumem[0xA00F], cpumem[Z80_GET_IY]);
	}
	else
	{
		if (m_bVerbose) newline();
	}

	// If the user requested a delay before seeking, make it now
	if (search_latency > 0)
	{
#ifdef DEBUG
		// search latency needs to be reworked so that think() is getting called ...
		assert(false);
#endif
//		make_delay(get_search_latency());
		if (m_bVerbose) printline("WARNING : search latency needs to be redesigned, it is currently disabled");
	}

	m_last_try_frame = (Uint16) atoi(frame);	// the last frame we tried to seek to becomes this current one

	// HERE IS WHERE THE SEARCH ACTUALLY TAKES PLACE

	int difference = frame_number - m_uCurrentFrame;	// how many frames we'd have to skip

	// if the player supports skipping AND user has requested the we skip instead of searching when possible
	// AND if we can skip forward instead of seeking ...
	if (skipping_supported && skip_instead_of_search && ((difference <= max_skippable_frames) && (difference > 1)))
	{
		result = pre_skip_forward((Uint16) difference);
	}

	// otherwise do a regular search
	else
	{
		result = nonblocking_search(frame);
		m_dont_get_search_result = false;	// it's now ok to get the search result

		// if search succeeded
		if (result)
		{
			// if we are to block until the search finishes, then wait here (this is bad, don't do this!)
			// This is only here for backward compatibility!
			if (block_until_search_finishes)
			{
				unsigned int cur_time = refresh_ms_time();
				unsigned int uLastTime = cur_time;	// used to compute m_uBlockedMsSincePlay
				int ldp_stat = -1;

				// we know we may be waiting for a while, so we pause the cpu timer to avoid getting a flood after the seek completes
				cpu_pause();

				// wait for player to change its status or for us to timeout
				while (elapsed_ms_time(cur_time) < 7000)
				{
					ldp_stat = get_status();	// get_status does some stuff that needs to get done, so we don't just read m_status instead

					// if the search is finished
					if (ldp_stat != LDP_SEARCHING)
					{
						break;
					}

					// Since the cpu is paused, we should not use think_delay
					// Also, blocking seeking may be used for skipping in noldp mode for cpu games like super don,
					//  so we cannot use think_delay here.
					MAKE_DELAY(1);

					// VLDP relies on our timers for its timing, so we need to keep the time moving forward during
					//  this period where we're paused. (and we can't use think_delay or pre_think because it can
					//  cause vblank events which can cause irqs while the cpu is supposed to be paused)
					unsigned int uCurTimeTmp = refresh_ms_time();
					m_uBlockedMsSincePlay += (uCurTimeTmp - uLastTime);	// since we're blocked, the blockmssinceplay must increase
					uLastTime = uCurTimeTmp;
					think();
				}

				cpu_unpause();	// done with the delay, so we can unpause

				// if we didn't succeed, then return an error
				if (ldp_stat != LDP_PAUSED)
				{
					if (m_bVerbose) printline("LDP : blocking search didn't succeed");
					result = false;
				}
			} // end if we were doing a blocking styled search
		} // if the initial search command was accepted

		// else if search failed immediately
		else
		{
			if (m_bVerbose) printline("LDP : search failed immediately");
			m_status = LDP_ERROR;
		}

	} // end regular search (instead of skipping)

	return(result);
}
Beispiel #26
0
void casetl(void)
{
	int j;
	int w[3];
	Tchar buf[LNSIZE];
	Tchar *tp;
	Tchar i, delim;

 	/*
 	 * bug fix
 	 *
 	 * if .tl is the first thing in the file, the p1
 	 * doesn't come out, also the pagenumber will be 0
 	 *
 	 * tends too confuse the device filter (and the user as well)
 	 */
 	if (dip == d && numtabp[NL].val == -1)
 		newline(1);
	dip->nls = 0;
	skip();
	if (ismot(delim = getch())) {
		ch = delim;
		delim = '\'';
	} else 
		delim = cbits(delim);
	tp = buf;
	numtabp[HP].val = 0;
	w[0] = w[1] = w[2] = 0;
	j = 0;
	while (cbits(i = getch()) != '\n') {
		if (cbits(i) == cbits(delim)) {
			if (j < 3)
				w[j] = numtabp[HP].val;
			numtabp[HP].val = 0;
			if (w[j] != 0)
				*tp++ = WORDSP;
			j++;
			*tp++ = 0;
		} else {
			if (cbits(i) == pagech) {
				setn1(numtabp[PN].val, numtabp[findr('%')].fmt,
				      i&SFMASK);
				continue;
			}
			numtabp[HP].val += width(i);
			if (tp < &buf[LNSIZE-10]) {
				if (cbits(i) == ' ' && *tp != WORDSP)
					*tp++ = WORDSP;
				*tp++ = i;
			} else {
				ERROR "Overflow in casetl" WARN;
			}
		}
	}
	if (j<3)
		w[j] = numtabp[HP].val;
	*tp++ = 0;
	*tp++ = 0;
	*tp = 0;
	tp = buf;
	if (NROFF)
		horiz(po);
	while (i = *tp++)
		pchar(i);
	if (w[1] || w[2])
		horiz(j = quant((lt - w[1]) / 2 - w[0], HOR));
	while (i = *tp++)
		pchar(i);
	if (w[2]) {
		horiz(lt - w[0] - w[1] - w[2] - j);
		while (i = *tp++)
			pchar(i);
	}
	newline(0);
	if (dip != d) {
		if (dip->dnl > dip->hnl)
			dip->hnl = dip->dnl;
	} else {
		if (numtabp[NL].val > dip->hnl)
			dip->hnl = numtabp[NL].val;
	}
}
Beispiel #27
0
void
emulate(void)
{
	char buf[BUFS+1];
	int n;
	int c;
	int standout = 0;
	int insmode = 0;

	for (;;) {
		if (x > xmax || y > ymax) {
			x = 0;
			newline();
		}
		buf[0] = get_next_char();
		buf[1] = '\0';
		switch(buf[0]) {

		case '\000':		/* nulls, just ignore 'em */
			break;

		case '\007':		/* bell */
			ringbell();
			break;

		case '\t':		/* tab modulo 8 */
			x = (x|7)+1;
			break;

		case '\033':
			switch(get_next_char()) {

			case 'j':
				get_next_char();
				break;

			case '&':	/* position cursor &c */
				switch(get_next_char()) {

				case 'a':
					for (;;) {
						n = number(buf, nil);
						switch(buf[0]) {

						case 'r':
						case 'y':
							y = n;
							continue;

						case 'c':
							x = n;
							continue;

						case 'R':
						case 'Y':
							y = n;
							break;

						case 'C':
							x = n;
							break;
						}
						break;
					}
					break;

				case 'd':	/* underline stuff */
					if ((n=get_next_char())>='A' && n <= 'O')
						standout++;
					else if (n == '@')
						standout = 0;
					break;

				default:
					get_next_char();
					break;

				}
				break;

			case 'i':	/* back tab */
				if (x>0)
					x = (x-1) & ~07;
				break;

			case 'H':	/* home cursor */
			case 'h':
				x = 0;
				y = 0;
				break;

			case 'L':	/* insert blank line */
				scroll(y, ymax, y+1, y);
				break;

			case 'M':	/* delete line */
				scroll(y+1, ymax+1, y, ymax);
				break;

			case 'J':	/* clear to end of display */
				xtipple(Rpt(pt(0, y+1),
					    pt(xmax+1, ymax+1)));
				/* flow */
			case 'K':	/* clear to EOL */
				xtipple(Rpt(pt(x, y),
					    pt(xmax+1, y+1)));
				break;

			case 'P':	/* delete char */
				bitblt(&screen, pt(x, y),
					&screen, Rpt(pt(x+1, y),
					pt(xmax+1, y+1)),
				        S);
				xtipple(Rpt(pt(xmax, y),
					    pt(xmax+1, y+1)));
				break;

			case 'Q':	/* enter insert mode */
				insmode++;
				break;

			case 'R':	/* leave insert mode */
				insmode = 0;
				break;

			case 'S':	/* roll up */
				scroll(1, ymax+1, 0, ymax);
				break;

			case 'T':
				scroll(0, ymax, 1, 0);
				break;

			case 'A':	/* upline */
			case 't':
				if (y>0)
					y--;
				if (olines > 0)
					olines--;
				break;

			case 'B':
			case 'w':
				y++;	/* downline */
				break;

			case 'C':	/* right */
			case 'v':
				x++;
				break;

			case 'D':	/* left */
			case 'u':
				x--;

			}
			break;

		case '\b':		/* backspace */
			if(x > 0)
				--x;
			break;

		case '\n':		/* linefeed */
			newline();
			standout = 0;
			if( ttystate[cs->raw].nlcr )
				x = 0;
			break;

		case '\r':		/* carriage return */
			x = 0;
			standout = 0;
			if( ttystate[cs->raw].crnl )
				newline();
			break;

		default:		/* ordinary char */
			n = 1;
			c = 0;
			while (!cs->raw && host_avail() && x+n<=xmax && n<BUFS
			    && (c = get_next_char())>=' ' && c<'\177') {
				buf[n++] = c;
				c = 0;
			}
			buf[n] = 0;
			if (insmode) {
				bitblt(&screen, pt(x+n, y), &screen,
					Rpt(pt(x, y), pt(xmax-n+1, y+1)), S);
			}
			xtipple(Rpt(pt(x,y), pt(x+n, y+1)));
			string(&screen, pt(x, y), font, buf, DxorS);
			if (standout)
				rectf(&screen,
				      Rpt(pt(x,y),pt(x+n,y+1)),
				      DxorS);
			x += n;
			peekc = c;
			break;
		}
	}
}
void RecordOutputMgr::printRecord(RecordKeyVector &keyList, RecordKeyVector *blockList)
{
	if (needsFlush()) {
		flush();
	}

	//The first time we print a record is when we print any header, because the header
	//hasn't been read from the query file until after the first record has also been read.
	checkForHeader();

	const_cast<Record *>(keyList.getKey())->undoZeroLength();
	_currBamBlockList = blockList;

	if (_context->getProgram() == ContextBase::INTERSECT || _context->getProgram() == ContextBase::SUBTRACT) {
		if (_printable) {
			if (keyList.empty()) {
				if ((static_cast<ContextIntersect *>(_context))->getWriteAllOverlap())
				{
					// -wao the user wants to force the reporting of 0 overlap
					if (printKeyAndTerminate(keyList)) {
						_currBamBlockList = NULL;
						const_cast<Record *>(keyList.getKey())->adjustZeroLength();

						return;
					}
					tab();
					// need to add a dummy file id if multiple DB files are used
					if (_context->getNumInputFiles() > 2) {
						_outBuf.append('.');
						tab();
					}
					null(false, true);
					tab();
					_outBuf.append('0');
					newline();
					if (needsFlush()) flush();
				}
				else if ((static_cast<ContextIntersect *>(_context))->getLeftJoin()) 
				{
					if (printKeyAndTerminate(keyList)) {
						_currBamBlockList = NULL;

						const_cast<Record *>(keyList.getKey())->adjustZeroLength();
						return;
					}
					tab();
					// need to add a dummy file id if multiple DB files are used
					if (_context->getNumInputFiles() > 2) {
						_outBuf.append('.');
						tab();
					}
					null(false, true);
					newline();
					if (needsFlush()) flush();
					_currBamBlockList = NULL;

					return;
				}
			} else {
				if (printBamRecord(keyList, true) == BAM_AS_BAM) {
					_currBamBlockList = NULL;

					const_cast<Record *>(keyList.getKey())->adjustZeroLength();
					return;
				}
				int hitIdx = 0;
				for (RecordKeyVector::const_iterator_type iter = keyList.begin(); iter != keyList.end(); iter = keyList.next()) {
					reportOverlapDetail(keyList.getKey(), *iter, hitIdx);
					hitIdx++;
				}
			}
		} else { // not printable
			reportOverlapSummary(keyList);
		}
		_currBamBlockList = NULL;
	} else if (_context->getProgram() == ContextBase::SAMPLE) {
		if (!printKeyAndTerminate(keyList)) {
			newline();
		}
	} else { // if (_context->getProgram() == ContextBase::MAP || _context->getProgram() == ContextBase::MERGE) {
		printKeyAndTerminate(keyList);
	}
	_currBamBlockList = NULL;
	const_cast<Record *>(keyList.getKey())->adjustZeroLength();

}
Beispiel #29
0
int
text()
{
	tchar i;
	static int	spcnt;

	nflush++;
	numtab[HP].val = 0;
	if ((dip == d) && (numtab[NL].val == -1)) {
		newline(1); 
		return (0);
	}
	setnel();
	if (ce || !fi) {
		nofill();
		return (0);
	}
	if (pendw)
		goto t4;
	if (pendt)
		if (spcnt)
			goto t2; 
		else 
			goto t3;
	pendt++;
	if (spcnt)
		goto t2;
	while ((cbits(i = GETCH())) == ' ') {
		spcnt++;
		numtab[HP].val += sps;
		widthp = sps;
	}
	if (nlflg) {
t1:
		nflush = pendt = ch = spcnt = 0;
		callsp();
		return (0);
	}
	ch = i;
	if (spcnt) {
t2:
		tbreak();
		if (nc || wch)
			goto rtn;
		un += spcnt * sps;
		spcnt = 0;
		setnel();
		if (trap)
			goto rtn;
		if (nlflg)
			goto t1;
	}
t3:
	if (spread)
		goto t5;
	if (pendw || !wch)
t4:
		if (getword(0))
			goto t6;
	if (!movword())
		goto t3;
t5:
	if (nlflg)
		pendt = 0;
	adsp = adrem = 0;
	if (ad) {
		if (nwd == 1)
			adsp = nel; 
		else 
			adsp = nel / (nwd - 1);
		adsp = (adsp / HOR) * HOR;
		adrem = nel - adsp*(nwd-1);
	}
	brflg = 1;
	tbreak();
	spread = 0;
	if (!trap)
		goto t3;
	if (!nlflg)
		goto rtn;
t6:
	pendt = 0;
	ckul();
rtn:
	nflush = 0;

	return (0);
}
Beispiel #30
0
void RichTextHtmlEdit::insertFromMimeData(const QMimeData *source) {
	QString uri;
	QString title;
	QRegExp newline(QLatin1String("[\\r\\n]"));

#ifndef QT_NO_DEBUG
	qWarning() << "RichTextHtmlEdit::insertFromMimeData" << source->formats();
	foreach(const QString &format, source->formats())
		qWarning() << format << decodeMimeString(source->data(format));
#endif

	if (source->hasImage()) {
		QImage img = qvariant_cast<QImage>(source->imageData());
		QString html = Log::imageToImg(img);
		if (! html.isEmpty())
			insertHtml(html);
		return;
	}

	QString mozurl = decodeMimeString(source->data(QLatin1String("text/x-moz-url")));
	if (! mozurl.isEmpty()) {
		QStringList lines = mozurl.split(newline);
		qWarning() << mozurl << lines;
		if (lines.count() >= 2) {
			uri = lines.at(0);
			title = lines.at(1);
		}
	}

	if (uri.isEmpty())
		uri = decodeMimeString(source->data(QLatin1String("text/x-moz-url-data")));
	if (title.isEmpty())
		title = decodeMimeString(source->data(QLatin1String("text/x-moz-url-desc")));

	if (uri.isEmpty()) {
		QStringList urls;
#ifdef Q_OS_WIN
		urls = decodeMimeString(source->data(QLatin1String("application/x-qt-windows-mime;value=\"UniformResourceLocatorW\""))).split(newline);
		if (urls.isEmpty())
#endif
			urls = decodeMimeString(source->data(QLatin1String("text/uri-list"))).split(newline);
		if (! urls.isEmpty())
			uri = urls.at(0);
		uri = urls.at(0).trimmed();
	}

	if (uri.isEmpty()) {
		QUrl url(source->text(), QUrl::StrictMode);
		if (url.isValid() && ! url.isRelative()) {
			uri = url.toString();
		}
	}

#ifdef Q_OS_WIN
	if (title.isEmpty() && source->hasFormat(QLatin1String("application/x-qt-windows-mime;value=\"FileGroupDescriptorW\""))) {
		QByteArray qba = source->data(QLatin1String("application/x-qt-windows-mime;value=\"FileGroupDescriptorW\""));
		if (qba.length() == sizeof(FILEGROUPDESCRIPTORW)) {
			const FILEGROUPDESCRIPTORW *ptr = reinterpret_cast<const FILEGROUPDESCRIPTORW *>(qba.constData());
			title = QString::fromWCharArray(ptr->fgd[0].cFileName);
			if (title.endsWith(QLatin1String(".url"), Qt::CaseInsensitive))
				title = title.left(title.length() - 4);
		}
	}
#endif

	if (! uri.isEmpty()) {
		if (title.isEmpty())
			title = uri;
		uri = Qt::escape(uri);
		title = Qt::escape(title);

		insertHtml(QString::fromLatin1("<a href=\"%1\">%2</a>").arg(uri, title));
		return;
	}

	QString html = decodeMimeString(source->data(QLatin1String("text/html")));
	if (! html.isEmpty()) {
		insertHtml(html);
		return;
	}

	QTextEdit::insertFromMimeData(source);
}