Ejemplo n.º 1
0
int
zlib_output_buffer::write(const char *buffer, int len)
{
  assert(stream.avail_in == 0);

  if (len > 0)
  {
    int status;

    stream.next_in = (Bytef *)buffer;
    stream.avail_in = len;

    for (status = deflate(&stream, Z_NO_FLUSH);
         status == Z_OK && stream.avail_in > 0;
         status = deflate(&stream, Z_NO_FLUSH)) {
      flush_output();
    }

    if (status != Z_OK) {
      throw xml_writer::write_error("deflate failed");
    }

    if (stream.avail_out == 0) {
      flush_output();
    }
  }

  return len;
}
//
// compress() is the public function used to compress
// a single file.  It has to take care of opening the
// input and output files and setting up the buffers for
// Zlib.  It then calls deflate() repeatedly until all
// input and output processing has been done, and finally
// closes the files and cleans up the Zlib structures.
//
void CStdCompress::CompressFile( const char *input,
                                 const char *output,
                                 int level )
{

try
{
    err = Z_OK;
    avail_in = 0;
    avail_out = output_length;
    next_out = output_buffer;
    m_AbortFlag = 0;

    fin  = fopen( input, "rb" );
    fout = fopen( output, "wb" );
    length = filelength( fileno( fin ) );
    deflateInit( this, level );
    for ( ; ; ) {
        if ( m_AbortFlag )
            break;
        if ( !load_input() )
            break;
        err = deflate( this, Z_NO_FLUSH );
        flush_output();
        if ( err != Z_OK )
            break;
        progress( percent() );
    }
    for ( ; ; ) {
        if ( m_AbortFlag )
            break;
        err = deflate( this, Z_FINISH );
        if ( !flush_output() )
            break;
        if ( err != Z_OK )
            break;
    }
    progress( percent() );
    deflateEnd( this );
    if ( m_AbortFlag )
        status( "User Abort" );
    else if ( err != Z_OK && err != Z_STREAM_END )
        status( "Zlib Error" );
    else {
        status( "Success" );
        err = Z_OK;
    }
    fclose( fin );
    fclose( fout );
    fin = 0;
    fout = 0;

	if(err != Z_OK && !m_AbortFlag)
		THROW_ERROR(Std_Err_ZLIB_lCompress, Std_Err_ZLIB_strCompress);
}
catch(CStdErrorInfo oError)
{RELAY_ERROR(oError);}
catch(...)
{THROW_ERROR(Std_Err_ZLIB_lUnspecifiedError, Std_Err_ZLIB_strUnspecifiedError);}
}
Ejemplo n.º 3
0
static void output_commit_title(struct merge_options *o, struct commit *commit)
{
	int i;
	flush_output(o);
	for (i = o->call_depth; i--;)
		fputs("  ", stdout);
	if (commit->util)
		printf("virtual %s\n", (char *)commit->util);
	else {
		printf("%s ", find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
		if (parse_commit(commit) != 0)
			printf("(bad commit)\n");
		else {
			const char *s;
			int len;
			for (s = commit->buffer; *s; s++)
				if (*s == '\n' && s[1] == '\n') {
					s += 2;
					break;
				}
			for (len = 0; s[len] && '\n' != s[len]; len++)
				; /* do nothing */
			printf("%.*s\n", len, s);
		}
	}
}
Ejemplo n.º 4
0
void write_byte(uint8_t byte) {
    out_buf[out_buf_len++] = byte;

    if (out_buf_len >= BUF_SIZE) {
        flush_output();
    }
}
Ejemplo n.º 5
0
static void output(struct merge_options *o, int v, const char *fmt, ...)
{
	int len;
	va_list ap;

	if (!show(o, v))
		return;

	strbuf_grow(&o->obuf, o->call_depth * 2 + 2);
	memset(o->obuf.buf + o->obuf.len, ' ', o->call_depth * 2);
	strbuf_setlen(&o->obuf, o->obuf.len + o->call_depth * 2);

	va_start(ap, fmt);
	len = vsnprintf(o->obuf.buf + o->obuf.len, strbuf_avail(&o->obuf), fmt, ap);
	va_end(ap);

	if (len < 0)
		len = 0;
	if (len >= strbuf_avail(&o->obuf)) {
		strbuf_grow(&o->obuf, len + 2);
		va_start(ap, fmt);
		len = vsnprintf(o->obuf.buf + o->obuf.len, strbuf_avail(&o->obuf), fmt, ap);
		va_end(ap);
		if (len >= strbuf_avail(&o->obuf)) {
			die("this should not happen, your snprintf is broken");
		}
	}
	strbuf_setlen(&o->obuf, o->obuf.len + len);
	strbuf_add(&o->obuf, "\n", 1);
	if (!o->buffer_output)
		flush_output(o);
}
Ejemplo n.º 6
0
/*
 * This implements the "Secure Attention Key" ---  the idea is to
 * prevent trojan horses by killing all processes associated with this
 * tty when the user hits the "Secure Attention Key".  Required for
 * super-paranoid applications --- see the Orange Book for more details.
 * 
 * This code could be nicer; ideally it should send a HUP, wait a few
 * seconds, then send a INT, and then a KILL signal.  But you then
 * have to coordinate with the init process, since all processes associated
 * with the current tty must be dead before the new getty is allowed
 * to spawn.
 */
void do_SAK( struct tty_struct *tty)
{
#ifdef TTY_SOFT_SAK
	tty_hangup(tty);
#else
	struct task_struct **p;
	int line = tty->line;
	int session = tty->session;
	int		i;
	struct file	*filp;
	
	flush_input(tty);
	flush_output(tty);
 	for (p = &LAST_TASK ; p > &FIRST_TASK ; --p) {
		if (!(*p))
			continue;
		if (((*p)->tty == line) ||
		    ((session > 0) && ((*p)->session == session)))
			send_sig(SIGKILL, *p, 1);
		else {
			for (i=0; i < NR_OPEN; i++) {
				filp = (*p)->filp[i];
				if (filp && (filp->f_op == &tty_fops) &&
				    (MINOR(filp->f_rdev) == line)) {
					send_sig(SIGKILL, *p, 1);
					break;
				}
			}
		}
	}
#endif
}
Ejemplo n.º 7
0
int
zlib_output_buffer::close(void)
{
  int status;

  assert(stream.avail_in == 0);

  for (status = deflate(&stream, Z_FINISH);
       status == Z_OK;
       status = deflate(&stream, Z_FINISH)) {
    flush_output();
  }

  if (status == Z_STREAM_END) {
    out->write(outbuf, sizeof(outbuf) - stream.avail_out);
  }
  else {
    throw xml_writer::write_error("deflate failed");
  }

  if (deflateEnd(&stream) != Z_OK) {
    throw xml_writer::write_error("deflateEnd failed");
  }

  return out->close();
}
Ejemplo n.º 8
0
/* return 1 on success, 0 on failure */
int play_frame(void)
{
	unsigned char *audio;
	int mc;
	size_t bytes;
	debug("play_frame");
	/* The first call will not decode anything but return MPG123_NEW_FORMAT! */
	mc = mpg123_decode_frame(mh, &framenum, &audio, &bytes);
	/* Play what is there to play (starting with second decode_frame call!) */
	if(bytes)
	{
		if(param.frame_number > -1) --frames_left;
		if(fresh && framenum >= param.start_frame)
		{
			fresh = FALSE;
		}
		/* Normal flushing of data, includes buffer decoding. */
		if(flush_output(ao, audio, bytes) < (int)bytes && !intflag)
		{
			error("Deep trouble! Cannot flush to my output anymore!");
			safe_exit(133);
		}
		if(param.checkrange)
		{
			long clip = mpg123_clip(mh);
			if(clip > 0) fprintf(stderr,"%ld samples clipped\n", clip);
		}
	}
	/* Special actions and errors. */
	if(mc != MPG123_OK)
	{
		if(mc == MPG123_ERR || mc == MPG123_DONE)
		{
			if(mc == MPG123_ERR) error1("...in decoding next frame: %s", mpg123_strerror(mh));
			return 0;
		}
		if(mc == MPG123_NO_SPACE)
		{
			error("I have not enough output space? I didn't plan for this.");
			return 0;
		}
		if(mc == MPG123_NEW_FORMAT)
		{
			long rate;
			int channels, format;
			mpg123_getformat(mh, &rate, &channels, &format);
			if(param.verbose > 2) fprintf(stderr, "\nNote: New output format %liHz %ich, format %i\n", rate, channels, format);

			if(!param.quiet)
			{
				fprintf(stderr, "\n");
				if(param.verbose) print_header(mh);
				else print_header_compact(mh);
			}
			reset_audio(rate, channels, format);
		}
	}
	return 1;
}
Ejemplo n.º 9
0
static void isig(int sig, struct tty_struct *tty)
{
	kill_pg(tty->pgrp, sig, 1);
	if (!L_NOFLSH(tty)) {
		flush_input(tty);
		flush_output(tty);
	}
}
Ejemplo n.º 10
0
int main(int argc, char *argv[]) {
  if (argc < 4) {
    fprintf(stderr, "Usage %s infile outfile threads\n", argv[0]);
    exit(-1);
  }
  int fd_in = open(argv[1], O_RDONLY);
  int fd_out = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, S_IRWXU);

  unsigned long uncomp_array_size = atol(argv[3]);
  lz4_uncompression_work *uncomp_array;
  pthread_t lz4uncomp_thread[uncomp_array_size];
  unsigned long uncomp_ptr;
  unsigned long total_bytes = 0;
  uncomp_array = new lz4_uncompression_work[uncomp_array_size];
  for (unsigned long i = 0; i < uncomp_array_size; i++) {
    uncomp_array[i].fd_in = fd_in;
    if(pthread_create(&lz4uncomp_thread[i],
		      NULL,
		      lz4_uncomp_service_start,
		      &uncomp_array[i]) != 0) {
      printf("failed to launch exec thread\n");
      exit(-1);
    }
  }
  unsigned long nextbytes;
  unsigned char header[11];
  read_from_file(fd_in, header, 11);
  nextbytes = uncomp_array[0].startup(header);
  for (unsigned long i = 1; i < uncomp_array_size; i++) {
    (void) uncomp_array[i].startup(header);
  }
  for (unsigned long i = 0; i < uncomp_array_size; i++) {
    total_bytes += nextbytes;
    nextbytes = uncomp_array[i].fill(nextbytes);
    uncomp_array[i].busy = true;
  }
  uncomp_ptr = 0;
  while (uncomp_array[uncomp_ptr].fillbytes) {
    while (uncomp_array[uncomp_ptr].busy);
    /* Write Block */
    flush_output(fd_out,
                 (char *) uncomp_array[uncomp_ptr].uncomp_data,
                 uncomp_array[uncomp_ptr].uncomp_bytes);
    total_bytes += nextbytes;
    nextbytes = uncomp_array[uncomp_ptr].fill(nextbytes);
    uncomp_array[uncomp_ptr].busy = true;
    uncomp_ptr = (uncomp_ptr + 1) % uncomp_array_size;
  }
  for (unsigned long i = 0; i < uncomp_array_size; i++) {
    uncomp_array[i].shutdown();
    uncomp_array[i].terminate = true;
    pthread_join(lz4uncomp_thread[i], NULL);
  }
  printf("Decompressed %lu\n", total_bytes);
  return 0;
}
int friends_data_store (struct connection *c, int op, const char *key, int len, int flags, int expire, int bytes)
{
  int user_id = 0;
  struct keep_mc_store *Data = 0;

  //key[len] = 0;

  if (verbosity > 0) {
    fprintf (stderr, "mc_store: op=%d, key=\"%s\", flags=%d, expire=%d, bytes=%d, noreply=%d\n", op, key, flags, expire, bytes, 0);
  }

  if (bytes >= 0 && bytes < 1048576) {
    if (sscanf (key, "userlist%d", &user_id) == 1 && user_id < 0) {
      if (!c->Tmp) {
        c->Tmp = alloc_head_buffer();
        assert (c->Tmp);
      }
      Data = (struct keep_mc_store *) c->Tmp->start;
      Data->magic = FRIENDS_STORE_MAGIC;
      Data->list_id = user_id;
      Data->num = np_news_parse_list (userlist, MAX_USERLIST_NUM, 1, &c->In, bytes);
      advance_write_ptr (c->Tmp, sizeof (struct keep_mc_store));
      if (Data->num > 0 && user_id < 0) {
        write_out (c->Tmp, userlist, Data->num * 4);
      }
    } else {
      advance_skip_read_ptr (&c->In, bytes);
    }
  } else {
    advance_skip_read_ptr (&c->In, bytes);
  }

  if (!Data || Data->num <= 0 || user_id >= 0) {
    write_out (&c->Out, "NOT_STORED\r\n", 12);
    flush_output (c);
    free_tmp_buffers (c);
  } else {
    write_out (&c->Out, "STORED\r\n", 8);
    flush_output (c);
  }

  return bytes;
}
Ejemplo n.º 12
0
void set_default_output_function ( void (*user_function) (const char *) )
{
   struct warn_specific_data *wt = &warn_defaults;

   if ( wt == NULL )
      return ;

   if ( wt->buffered )
      flush_output();
   wt->output_function = user_function;
}
Ejemplo n.º 13
0
int mpl_postsolve(MPL *mpl)
{     if (!(mpl->phase == 3 && !mpl->flag_p))
         xfault("mpl_postsolve: invalid call sequence\n");
      /* set up error handler */
      if (setjmp(mpl->jump)) goto done;
      /* perform postsolving */
      postsolve_model(mpl);
      flush_output(mpl);
      /* postsolving phase has been finished */
      xprintf("Model has been successfully processed\n");
done: /* return to the calling program */
      return mpl->phase;
}
Ejemplo n.º 14
0
void output_handler() {
  LIST_ITERATOR *sock_i = newListIterator(socket_list);
  SOCKET_DATA     *sock = NULL; 

  ITERATE_LIST(sock, sock_i) {
    /* if the player quits or get's disconnected */
    if(sock->closed)
      continue;
    
    /* Send all new data to the socket and close it if any errors occour */
    if (!flush_output(sock))
      close_socket(sock, FALSE);
  } deleteListIterator(sock_i);
}
Ejemplo n.º 15
0
static void pty_close(struct tty_struct * tty, struct file * filp)
{
	if (!tty || (tty->count > 1))
		return;
	wake_up_interruptible(&tty->read_q.proc_list);
	if (!tty->link)
		return;
	wake_up_interruptible(&tty->link->write_q.proc_list);
	if (IS_A_PTY_MASTER(tty->line)) {
		tty_hangup(tty->link);
		flush_input(tty);
		flush_output(tty);
	}
}
Ejemplo n.º 16
0
/** 
 * @brief Вывод на печать в стиле printf.
 */
void dprintf(const char *format, ...)
{
	va_list va;

	va_start(va, format);
	debug_output_pos += vsnprintf(debug_output + debug_output_pos, 
								  sizeof(debug_output) - debug_output_pos, 
								  format, va);
	if (debug_output_pos > sizeof(debug_output))
		debug_output_pos = sizeof(debug_output);
	va_end(va);

	if (debug_output[debug_output_pos - 1] == '\n' && !debug_buffer_output)
		flush_output();
}
Ejemplo n.º 17
0
void
packet_decoder :: add_output( char * c, int len )
{
    while ( len > 0 )
    {
        int tocopy = len;
        if ( tocopy > ( output_max - output_pos ))
            tocopy = output_max - output_pos;
        memcpy( output_buffer + output_pos, c, tocopy );
        output_pos += tocopy;
        len -= tocopy;
        if ( output_pos == output_max )
            flush_output();
    }
}
Ejemplo n.º 18
0
int mpl_generate(MPL *mpl, char *file)
{     if (!(mpl->phase == 1 || mpl->phase == 2))
         fault("mpl_generate: invalid call sequence");
      /* set up error handler */
      if (setjmp(mpl->jump)) goto done;
      /* generate model */
      mpl->phase = 3;
      open_output(mpl, file);
      generate_model(mpl);
      flush_output(mpl);
      /* build problem instance */
      build_problem(mpl);
      /* generation phase has been finished */
      print("Model has been successfully generated");
done: /* return to the calling program */
      return mpl->phase;
}
Ejemplo n.º 19
0
void do_tty_hangup(struct tty_struct * tty, struct file_operations *fops)
{
	int i;
	struct file * filp;
	struct task_struct *p;
	int dev;

	if (!tty)
		return;
	dev = MKDEV(TTY_MAJOR,tty->line);
	for (filp = first_file, i=0; i<nr_files; i++, filp = filp->f_next) {
		if (!filp->f_count)
			continue;
		if (filp->f_rdev != dev)
			continue;
		if (filp->f_inode && filp->f_inode->i_rdev == CONSOLE_DEV)
			continue;
		if (filp->f_op != &tty_fops)
			continue;
		filp->f_op = fops;
	}
	flush_input(tty);
	flush_output(tty);
	wake_up_interruptible(&tty->secondary.proc_list);
	if (tty->session > 0) {
		kill_sl(tty->session,SIGHUP,1);
		kill_sl(tty->session,SIGCONT,1);
	}
	tty->session = 0;
	tty->pgrp = -1;
 	for_each_task(p) {
		if (p->tty == tty->line)
			p->tty = -1;
	}
	if (tty->hangup)
		(tty->hangup)(tty);
}
Ejemplo n.º 20
0
Archivo: ps2.c Proyecto: sjrct/Frosk
void detect_ps2(void)
{
	// disable ps/2 devices
	outb(PS2_CMND, 0xAD);
	outb(PS2_CMND, 0xA7);

	flush_output();

	// disable interrupts and translation
	chg_config(0x43, 0);

	// ps/2 controller self test
	outb(PS2_CMND, 0xAA);
	do_assert(wait_read());

	if (inb(PS2_DATA) != 0x55) {
		kputs("PS/2 Controller self test failed.\n");
		return;
	}

	// individual device detection
	detect_device(0, 0xAE, 0xAB, 0x10);
	detect_device(1, 0xA8, 0xA9, 0x20);
}
Ejemplo n.º 21
0
int mpl_read_data(MPL *mpl, char *file)
#if 0 /* 02/X-2008 */
{     if (mpl->phase != 1)
#else
{     if (!(mpl->phase == 1 || mpl->phase == 2))
#endif
         xfault("mpl_read_data: invalid call sequence\n");
      if (file == NULL)
         xfault("mpl_read_data: no input filename specified\n");
      /* set up error handler */
      if (setjmp(mpl->jump)) goto done;
      /* process data section */
      mpl->phase = 2;
      xprintf("Reading data section from %s...\n", file);
      mpl->flag_d = 1;
      open_input(mpl, file);
      /* in this case the keyword 'data' is optional */
      if (is_literal(mpl, "data"))
      {  get_token(mpl /* data */);
         if (mpl->token != T_SEMICOLON)
            error(mpl, "semicolon missing where expected");
         get_token(mpl /* ; */);
      }
      data_section(mpl);
      /* process end statement */
      end_statement(mpl);
      xprintf("%d line%s were read\n",
         mpl->line, mpl->line == 1 ? "" : "s");
      close_input(mpl);
done: /* return to the calling program */
      return mpl->phase;
}

/*----------------------------------------------------------------------
-- mpl_generate - generate model.
--
-- *Synopsis*
--
-- #include "glpmpl.h"
-- int mpl_generate(MPL *mpl, char *file);
--
-- *Description*
--
-- The routine mpl_generate generates the model using its description
-- stored in the translator database. This phase means generating all
-- variables, constraints, and objectives, executing check and display
-- statements, which precede the solve statement (if it is presented),
-- and building the problem instance.
--
-- The character string file specifies the name of output text file, to
-- which output produced by display statements should be written. It is
-- allowed to specify NULL, in which case the output goes to stdout via
-- the routine print.
--
-- This routine should be called once after the routine mpl_read_model
-- or mpl_read_data and if one of the latters returned the code 2.
--
-- *Returns*
--
-- The routine mpl_generate returns one of the following codes:
--
-- 3 - model has been successfully generated. In this case the calling
--     program may call other api routines to obtain components of the
--     problem instance from the translator database.
-- 4 - processing failed due to some errors. In this case the calling
--     program should call the routine mpl_terminate to terminate model
--     processing. */

int mpl_generate(MPL *mpl, char *file)
{     if (!(mpl->phase == 1 || mpl->phase == 2))
         xfault("mpl_generate: invalid call sequence\n");
      /* set up error handler */
      if (setjmp(mpl->jump)) goto done;
      /* generate model */
      mpl->phase = 3;
      open_output(mpl, file);
      generate_model(mpl);
      flush_output(mpl);
      /* build problem instance */
      build_problem(mpl);
      /* generation phase has been finished */
      xprintf("Model has been successfully generated\n");
done: /* return to the calling program */
      return mpl->phase;
}

/*----------------------------------------------------------------------
-- mpl_get_prob_name - obtain problem (model) name.
--
-- *Synopsis*
--
-- #include "glpmpl.h"
-- char *mpl_get_prob_name(MPL *mpl);
--
-- *Returns*
--
-- The routine mpl_get_prob_name returns a pointer to internal buffer,
-- which contains symbolic name of the problem (model).
--
-- *Note*
--
-- Currently MathProg has no feature to assign a symbolic name to the
-- model. Therefore the routine mpl_get_prob_name tries to construct
-- such name using the name of input text file containing model section,
-- although this is not a good idea (due to portability problems). */

char *mpl_get_prob_name(MPL *mpl)
{     char *name = mpl->mpl_buf;
      char *file = mpl->mod_file;
      int k;
      if (mpl->phase != 3)
         xfault("mpl_get_prob_name: invalid call sequence\n");
      for (;;)
      {  if (strchr(file, '/') != NULL)
            file = strchr(file, '/') + 1;
         else if (strchr(file, '\\') != NULL)
            file = strchr(file, '\\') + 1;
         else if (strchr(file, ':') != NULL)
            file = strchr(file, ':') + 1;
         else
            break;
      }
      for (k = 0; ; k++)
      {  if (k == 255) break;
         if (!(isalnum((unsigned char)*file) || *file == '_')) break;
         name[k] = *file++;
      }
      if (k == 0)
         strcpy(name, "Unknown");
      else
         name[k] = '\0';
      xassert(strlen(name) <= 255);
      return name;
}
Ejemplo n.º 22
0
void classic_BP_test()
	{
	int neuronsOfLayer[] = {2, 10, 9, 1}; // first = input layer, last = output layer
	int numLayers = sizeof (neuronsOfLayer) / sizeof (int);
	NNET *Net = create_NN(numLayers, neuronsOfLayer);
	LAYER lastLayer = Net->layers[numLayers - 1];
	double errors[dim_K];

	int userKey = 0;
	#define M	50			// how many errors to record for averaging
	double errors1[M], errors2[M]; // two arrays for recording errors
	double sum_err1 = 0.0, sum_err2 = 0.0; // sums of errors
	int tail = 0; // index for cyclic arrays (last-in, first-out)

	for (int i = 0; i < M; ++i) // clear errors to 0.0
		errors1[i] = errors2[i] = 0.0;

	// start_NN_plot();
	start_W_plot();
	// start_K_plot();
	start_output_plot();
	start_LogErr_plot();
	// plot_ideal();
	printf("Press 'Q' to quit\n\n");
	start_timer();

	char status[1024], *s;
	for (int i = 1; 1; ++i)
		{
		s = status + sprintf(status, "[%05d] ", i);

		// Create random K vector
		for (int k = 0; k < 2; ++k)
			K[k] = (rand() / (float) RAND_MAX);
		// printf("*** K = <%lf, %lf>\n", K[0], K[1]);

		//		if ((i % 4) == 0)
		//			K[0] = 1.0, K[1] = 0.0;
		//		if ((i % 4) == 1)
		//			K[0] = 0.0, K[1] = 0.0;
		//		if ((i % 4) == 2)
		//			K[0] = 0.0, K[1] = 1.0;
		//		if ((i % 4) == 3)
		//			K[0] = 1.0, K[1] = 1.0;

		ForwardPropMethod(Net, 2, K); // dim K = 2

		// Desired value = K_star
		double training_err = 0.0;
		for (int k = 0; k < 1; ++k) // output has only 1 component
			{
			// double ideal = K[k];				/* identity function */
			#define f2b(x) (x > 0.5f ? 1 : 0)	// convert float to binary
			// ^ = binary XOR
			double ideal = ((double) (f2b(K[0]) ^ f2b(K[1]))); // ^ f2b(K[2]) ^ f2b(K[3])))
			// #define Ideal ((double) (f2b(K[k]) ^ f2b(K[2]) ^ f2b(K[3])))
			// double ideal = 1.0f - (0.5f - K[0]) * (0.5f - K[1]);
			// printf("*** ideal = %lf\n", ideal);

			// Difference between actual outcome and desired value:
			double error = ideal - lastLayer.neurons[k].output;
			errors[k] = error; // record this for back-prop

			training_err += fabs(error); // record sum of errors
			}
		// printf("sum of squared error = %lf  ", training_err);

		// update error arrays cyclically
		// (This is easier to understand by referring to the next block of code)
		sum_err2 -= errors2[tail];
		sum_err2 += errors1[tail];
		sum_err1 -= errors1[tail];
		sum_err1 += training_err;
		// printf("sum1, sum2 = %lf %lf\n", sum_err1, sum_err2);

		double mean_err = (i < M) ? (sum_err1 / i) : (sum_err1 / M);
		if (mean_err < 2.0)
			s += sprintf(s, "mean |e|=%1.06lf, ", mean_err);
		else
			s += sprintf(s, "mean |e|=%e, ", mean_err);

		// record new error in cyclic arrays
		errors2[tail] = errors1[tail];
		errors1[tail] = training_err;
		++tail;
		if (tail == M) // loop back in cycle
			tail = 0;

		// plot_W(Net);
		back_prop(Net, errors);
		// plot_W(Net);
		// pause_graphics();

		if ((i % 200) == 0)
			{
			// Testing set
			double test_err = 0.0;
			#define numTests 50
			for (int j = 0; j < numTests; ++j)
				{
				// Create random K vector
				for (int k = 0; k < 2; ++k)
					K[k] = ((double) rand() / (double) RAND_MAX);
				// plot_tester(K[0], K[1]);

				ForwardPropMethod(Net, 2, K);

				// Desired value = K_star
				double single_err = 0.0;
				for (int k = 0; k < 1; ++k)
					{
					// double ideal = 1.0f - (0.5f - K[0]) * (0.5f - K[1]);
					double ideal = (double) (f2b(K[0]) ^ f2b(K[1]));
					// double ideal = K[k];				/* identity function */

					// Difference between actual outcome and desired value:
					double error = ideal - lastLayer.neurons[k].output;

					single_err += fabs(error); // record sum of errors
					}
				test_err += single_err;
				}
			test_err /= ((double) numTests);
			if (test_err < 2.0)
				s += sprintf(s, "random test |e|=%1.06lf, ", test_err);
			else
				s += sprintf(s, "random test |e|=%e, ", test_err);
			if (test_err < ErrorThreshold)
				break;
			}

		if (i > 50 && (isnan(mean_err) || mean_err > 10.0))
			{
			re_randomize(Net, numLayers, neuronsOfLayer);
			sum_err1 = 0.0; sum_err2 = 0.0;
			tail = 0;
			for (int j = 0; j < M; ++j) // clear errors to 0.0
				errors1[j] = errors2[j] = 0.0;
			i = 1;

			restart_LogErr_plot();
			start_timer();
			printf("\n****** Network re-randomized.\n");
			}

		if ((i % 50) == 0)
			{
			double ratio = (sum_err2 - sum_err1) / sum_err1;
			if (ratio > 0)
				s += sprintf(s, "|e| ratio=%e", ratio);
			else
				s += sprintf(s, "|e| ratio=\x1b[31m%e\x1b[39;49m", ratio);
			//if (isnan(ratio))
			//	break;
			}

		if ((i % 10) == 0) // display status periodically
			{
			printf("%s\n", status);
			// plot_NN(Net);
			plot_W(Net);
			plot_LogErr(mean_err, ErrorThreshold);
			plot_output(Net, ForwardPropMethod);
			flush_output();
			// plot_trainer(0);		// required to clear the window
			// plot_K();
			userKey = delay_vis(0);
			}

		// if (ratio - 0.5f < 0.0000001)	// ratio == 0.5 means stationary
		// if (test_err < 0.01)

		if (userKey == 1)
			break;
		else if (userKey == 3)			// Re-start with new random weights
			{
			re_randomize(Net, numLayers, neuronsOfLayer);
			sum_err1 = 0.0; sum_err2 = 0.0;
			tail = 0;
			for (int j = 0; j < M; ++j) // clear errors to 0.0
				errors1[j] = errors2[j] = 0.0;
			i = 1;

			restart_LogErr_plot();
			start_timer();
			printf("\n****** Network re-randomized.\n");
			userKey = 0;
			beep();
			// pause_key();
			}
		}

	end_timer(NULL);
	beep();
	// plot_output(Net, ForwardPropMethod);
	flush_output();
	plot_W(Net);

	if (userKey == 0)
		pause_graphics();
	else
		quit_graphics();
	free_NN(Net, neuronsOfLayer);
	}
Ejemplo n.º 23
0
int tty_ioctl(struct inode * inode, struct file * file,
	unsigned int cmd, unsigned long arg)
{
	struct tty_struct * tty;
	struct tty_struct * other_tty;
	struct tty_struct * termios_tty;
	pid_t pgrp;
	int dev;
	int termios_dev;
	int retval;

	if (MAJOR(file->f_rdev) != TTY_MAJOR) {
		printk("tty_ioctl: tty pseudo-major != TTY_MAJOR\n");
		return -EINVAL;
	}
	dev = MINOR(file->f_rdev);
	tty = TTY_TABLE(dev);
	if (!tty)
		return -EINVAL;
	if (IS_A_PTY(dev))
		other_tty = tty_table[PTY_OTHER(dev)];
	else
		other_tty = NULL;
	if (IS_A_PTY_MASTER(dev)) {
		termios_tty = other_tty;
		termios_dev = PTY_OTHER(dev);
	} else {
		termios_tty = tty;
		termios_dev = dev;
	}
	switch (cmd) {
		case TCGETS:
			retval = verify_area(VERIFY_WRITE, (void *) arg,
					     sizeof (struct termios));
			if (retval)
				return retval;
			memcpy_tofs((struct termios *) arg,
				    termios_tty->termios,
				    sizeof (struct termios));
			return 0;
		case TCSETSF:
		case TCSETSW:
		case TCSETS:
			retval = check_change(termios_tty, termios_dev);
			if (retval)
				return retval;
			if (cmd == TCSETSF || cmd == TCSETSW) {
				if (cmd == TCSETSF)
					flush_input(termios_tty);
				wait_until_sent(termios_tty, 0);
			}
			return set_termios(termios_tty, (struct termios *) arg,
					   termios_dev);
		case TCGETA:
			return get_termio(termios_tty,(struct termio *) arg);
		case TCSETAF:
		case TCSETAW:
		case TCSETA:
			retval = check_change(termios_tty, termios_dev);
			if (retval)
				return retval;
			if (cmd == TCSETAF || cmd == TCSETAW) {
				if (cmd == TCSETAF)
					flush_input(termios_tty);
				wait_until_sent(termios_tty, 0);
			}
			return set_termio(termios_tty, (struct termio *) arg,
					  termios_dev);
		case TCXONC:
			retval = check_change(tty, dev);
			if (retval)
				return retval;
			switch (arg) {
			case TCOOFF:
				stop_tty(tty);
				break;
			case TCOON:
				start_tty(tty);
				break;
			case TCIOFF:
				if (STOP_CHAR(tty) != __DISABLED_CHAR)
					put_tty_queue(STOP_CHAR(tty),
						      &tty->write_q);
				break;
			case TCION:
				if (START_CHAR(tty) != __DISABLED_CHAR)
					put_tty_queue(START_CHAR(tty),
						      &tty->write_q);
				break;
			default:
				return -EINVAL;
			}
			return 0;
		case TCFLSH:
			retval = check_change(tty, dev);
			if (retval)
				return retval;
			switch (arg) {
			case TCIFLUSH:
				flush_input(tty);
				break;
			case TCIOFLUSH:
				flush_input(tty);
				/* fall through */
			case TCOFLUSH:
				flush_output(tty);
				break;
			default:
				return -EINVAL;
			}
			return 0;
		case TIOCEXCL:
			set_bit(TTY_EXCLUSIVE, &tty->flags);
			return 0;
		case TIOCNXCL:
			clear_bit(TTY_EXCLUSIVE, &tty->flags);
			return 0;
		case TIOCSCTTY:
			if (current->leader &&
			    (current->session == tty->session))
				return 0;
			/*
			 * The process must be a session leader and
			 * not have a controlling tty already.
			 */
			if (!current->leader || (current->tty >= 0))
				return -EPERM;
			if (tty->session > 0) {
				/*
				 * This tty is already the controlling
				 * tty for another session group!
				 */
				if ((arg == 1) && suser()) {
					/*
					 * Steal it away
					 */
					struct task_struct *p;

					for_each_task(p)
						if (p->tty == dev)
							p->tty = -1;
				} else
					return -EPERM;
			}
			current->tty = dev;
			tty->session = current->session;
			tty->pgrp = current->pgrp;
			return 0;
		case TIOCGPGRP:
			retval = verify_area(VERIFY_WRITE, (void *) arg,
					     sizeof (pid_t));
			if (retval)
				return retval;
			if (current->tty != termios_dev)
				return -ENOTTY;
			put_fs_long(termios_tty->pgrp, (pid_t *) arg);
			return 0;
		case TIOCSPGRP:
			retval = check_change(termios_tty, termios_dev);
			if (retval)
				return retval;
			if ((current->tty < 0) ||
			    (current->tty != termios_dev) ||
			    (termios_tty->session != current->session))
				return -ENOTTY;
			pgrp = get_fs_long((pid_t *) arg);
			if (pgrp < 0)
				return -EINVAL;
			if (session_of_pgrp(pgrp) != current->session)
				return -EPERM;
			termios_tty->pgrp = pgrp;
			return 0;
		case TIOCOUTQ:
			retval = verify_area(VERIFY_WRITE, (void *) arg,
					     sizeof (unsigned long));
			if (retval)
				return retval;
			put_fs_long(CHARS(&tty->write_q),
				    (unsigned long *) arg);
			return 0;
		case TIOCINQ:
			retval = verify_area(VERIFY_WRITE, (void *) arg,
					     sizeof (unsigned long));
			if (retval)
				return retval;
			if (L_ICANON(tty))
				put_fs_long(inq_canon(tty),
					(unsigned long *) arg);
			else
				put_fs_long(CHARS(&tty->secondary),
					(unsigned long *) arg);
			return 0;
		case TIOCSTI:
			if ((current->tty != dev) && !suser())
				return -EPERM;
			retval = verify_area(VERIFY_READ, (void *) arg, 1);
			if (retval)
				return retval;
			put_tty_queue(get_fs_byte((char *) arg), &tty->read_q);
			TTY_READ_FLUSH(tty);
			return 0;
		case TIOCGWINSZ:
			retval = verify_area(VERIFY_WRITE, (void *) arg,
					     sizeof (struct winsize));
			if (retval)
				return retval;
			memcpy_tofs((struct winsize *) arg, &tty->winsize,
				    sizeof (struct winsize));
			return 0;
		case TIOCSWINSZ:
			if (IS_A_PTY_MASTER(dev))
				set_window_size(other_tty,(struct winsize *) arg);
			return set_window_size(tty,(struct winsize *) arg);
		case TIOCLINUX:
			switch (get_fs_byte((char *)arg))
			{
				case 0: 
					return do_screendump(arg);
				case 1: 
					return do_get_ps_info(arg);
#ifdef CONFIG_SELECTION
				case 2:
					return set_selection(arg);
				case 3:
					return paste_selection(tty);
				case 4:
					unblank_screen();
					return 0;
#endif /* CONFIG_SELECTION */
				default: 
					return -EINVAL;
			}
		case TIOCCONS:
			if (IS_A_CONSOLE(dev)) {
				if (!suser())
					return -EPERM;
				redirect = NULL;
				return 0;
			}
			if (redirect)
				return -EBUSY;
			if (!suser())
				return -EPERM;
			if (IS_A_PTY_MASTER(dev))
				redirect = other_tty;
			else if (IS_A_PTY_SLAVE(dev))
				redirect = tty;
			else
				return -ENOTTY;
			return 0;
		case FIONBIO:
			arg = get_fs_long((unsigned long *) arg);
			if (arg)
				file->f_flags |= O_NONBLOCK;
			else
				file->f_flags &= ~O_NONBLOCK;
			return 0;
		case TIOCNOTTY:
			if (current->tty != dev)
				return -ENOTTY;
			if (current->leader)
				disassociate_ctty(0);
			current->tty = -1;
			return 0;
		case TIOCGETD:
			retval = verify_area(VERIFY_WRITE, (void *) arg,
					     sizeof (unsigned long));
			if (retval)
				return retval;
			put_fs_long(tty->disc, (unsigned long *) arg);
			return 0;
		case TIOCSETD:
			retval = check_change(tty, dev);
			if (retval)
				return retval;
			arg = get_fs_long((unsigned long *) arg);
			return tty_set_ldisc(tty, arg);
		case TIOCGLCKTRMIOS:
			arg = get_fs_long((unsigned long *) arg);
			retval = verify_area(VERIFY_WRITE, (void *) arg,
					     sizeof (struct termios));
			if (retval)
				return retval;
			memcpy_tofs((struct termios *) arg,
				    &termios_locked[termios_dev],
				    sizeof (struct termios));
			return 0;
		case TIOCSLCKTRMIOS:
			if (!suser())
				return -EPERM;
			arg = get_fs_long((unsigned long *) arg);
			memcpy_fromfs(&termios_locked[termios_dev],
				      (struct termios *) arg,
				      sizeof (struct termios));
			return 0;
		case TIOCPKT:
			if (!IS_A_PTY_MASTER(dev))
				return -ENOTTY;
			retval = verify_area(VERIFY_READ, (void *) arg,
					     sizeof (unsigned long));
			if (retval)
				return retval;
			if (get_fs_long(arg)) {
				if (!tty->packet) {
					tty->packet = 1;
					tty->link->ctrl_status = 0;
				}
			} else
				tty->packet = 0;
			return 0;
		case TCSBRK: case TCSBRKP:
			retval = check_change(tty, dev);
			if (retval)
				return retval;
			wait_until_sent(tty, 0);
			if (!tty->ioctl)
				return 0;
			tty->ioctl(tty, file, cmd, arg);
			return 0;
		default:
			if (tty->ioctl) {
				retval = (tty->ioctl)(tty, file, cmd, arg);
				if (retval != -EINVAL)
					return retval;
			}
			if (ldiscs[tty->disc].ioctl) {
				retval = (ldiscs[tty->disc].ioctl)
					(tty, file, cmd, arg);
				return retval;
			}
			return -EINVAL;
	}
Ejemplo n.º 24
0
static exit_values_ty indent_main_loop(
    BOOLEAN * pbreak_line)
{
    codes_ty         hd_type         = code_eof;
    char           * t_ptr           = NULL;
    codes_ty         type_code       = start_token;
    exit_values_ty   file_exit_value = total_success;
    int              dec_ind         = 0; /* current indentation for declarations */

    BOOLEAN          scase           = false; /* true when we've just see a "case";
                                               * determines what to do with the
                                               * following colon */
    BOOLEAN          flushed_nl;              /* Used when buffering up comments to remember that
                                               * a newline was passed over */
    BOOLEAN          sp_sw           = false; /* true when in the expression part of if(...),
                                               * while(...), etc. */
    BOOLEAN          force_nl        = false;

    /* last_token_ends_sp: True if we have just encountered the end of an if (...),
     * etc. (i.e. the ')' of the if (...) was the last token).  The variable is
     * set to 2 in the middle of the main token reading loop and is decremented
     * at the beginning of the loop, so it will reach zero when the second token
     * after the ')' is read.
     */

    BOOLEAN          last_token_ends_sp = false;

    BOOLEAN          last_else = false; /* true if last keyword was an else */

    for (;;)
    {
        /* this is the main loop.  it will go until
         * we reach eof */

        BOOLEAN is_procname_definition;
        bb_code_ty can_break = bb_none;

        if (type_code != newline)
        {
            can_break = parser_state_tos->can_break;
        }

        parser_state_tos->last_saw_nl = false;
        parser_state_tos->can_break = bb_none;

        type_code = lexi (); /* lexi reads one token.  "token" points to
                              * the actual characters. lexi returns a code
                              * indicating the type of token */

        /* If the last time around we output an identifier or
         * a paren, then consider breaking the line here if it's
         * too long.
         *
         * A similar check is performed at the end of the loop, after
         * we've put the token on the line. */

        if ((settings.max_col > 0) &&
            (buf_break != NULL) &&
            ( ( (parser_state_tos->last_token == ident) &&
                (type_code != comma) &&
                (type_code != semicolon) &&
                (type_code != newline) &&
                (type_code != form_feed) &&
                (type_code != rparen) &&
                (type_code != struct_delim)) ||
              ( (parser_state_tos->last_token == rparen) &&
                (type_code != comma) &&
                (type_code != rparen) ) ) &&
            (output_line_length () > settings.max_col))
        {
            *pbreak_line = true;
        }

        if (last_token_ends_sp > 0)
        {
            last_token_ends_sp--;
        }

        is_procname_definition =
                (((parser_state_tos->procname[0] != '\0') &&
                  parser_state_tos->in_parameter_declaration) ||
                 (parser_state_tos->classname[0] != '\0'));

        /* The following code moves everything following an if (), while (),
         * else, etc. up to the start of the following stmt to a buffer. This
         * allows proper handling of both kinds of brace placement.
         */

        flushed_nl = false;

        /* Don't force a newline after an unbraced if, else, etc. */
        if (settings.allow_single_line_conditionals &&
            (parser_state_tos->last_token == rparen ||
            parser_state_tos->last_token == sp_else))
            force_nl = false;

        /* Don't force a newline after '}' in a block initializer */
        if (parser_state_tos->block_init           &&
            parser_state_tos->last_token == rbrace &&
            *token == ',')
            force_nl = false;

        if (!search_brace(&type_code, &force_nl, &flushed_nl, &last_else,
                          &is_procname_definition, pbreak_line))
        {
            /* Hit EOF unexpectedly in comment. */
            return indent_punt;
        }
        
        if (type_code == code_eof)
        {
            /* we got eof */
            if (s_lab != e_lab || s_code != e_code || s_com != e_com)   /* must dump end of line */
            {
                dump_line(true, &paren_target, pbreak_line);
            }

            if (parser_state_tos->tos > 1)      /* check for balanced braces */
            {
                ERROR (_("Unexpected end of file"), 0, 0);
                file_exit_value = indent_error;
            }

            if (settings.verbose)
            {
                printf (_("There were %d non-blank output lines and %d comments\n"),
                        (int) out_lines, (int) com_lines);
                if (com_lines > 0 && code_lines > 0)
                {
                    printf (_("(Lines with comments)/(Lines with code): %6.3f\n"),
                            (1.0 * com_lines) / code_lines);
                }
            }
            flush_output ();

            return file_exit_value;                                              /* RETURN */
        }

        if ((type_code != comment) &&
            (type_code != cplus_comment) &&
            (type_code != newline) &&
            (type_code != preesc) &&
            (type_code != form_feed))
        {
            if (force_nl &&
                (type_code != semicolon) &&
                ( (type_code != lbrace) ||
                  (!parser_state_tos->in_decl && !settings.btype_2) ||
                  (parser_state_tos->in_decl && !settings.braces_on_struct_decl_line) ||
                  (parser_state_tos->last_token == rbrace)))
            {
                if (settings.verbose && !flushed_nl)
                {
                    WARNING (_("Line broken 2"), 0, 0);
                }

                flushed_nl = false;
                dump_line(true, &paren_target, pbreak_line);
                parser_state_tos->want_blank = false;
                force_nl = false;
            }

            parser_state_tos->in_stmt = true;   /* turn on flag which causes
                                                 * an extra level of
                                                 * indentation. this is
                                                 * turned off by a ; or } */
            if (s_com != e_com)
            {
                /* the code has an embedded comment in the
                 * line. Move it from the com buffer to the
                 * code buffer.
                 *
                 * Do not add a space before the comment if it is the first
                 * thing on the line.
                 */

                if (e_code != s_code)
                {
                    set_buf_break (bb_embedded_comment_start, paren_target);
                    *e_code++ = ' ';
                    embedded_comment_on_line = 2;
                }
                else
                {
                    embedded_comment_on_line = 1;
                }

                for (t_ptr = s_com; *t_ptr; ++t_ptr)
                {
                    check_code_size();
                    *e_code++ = *t_ptr;
                }

                set_buf_break (bb_embedded_comment_end, paren_target);
                *e_code++ = ' ';
                *e_code = '\0'; /* null terminate code sect */
                parser_state_tos->want_blank = false;
                e_com = s_com;
            }
        }
        else if ((type_code != comment) &&
                 (type_code != cplus_comment) &&
                 !(settings.break_function_decl_args &&
                   (parser_state_tos->last_token == comma)) &&
                 !( (parser_state_tos->last_token == comma) &&
                    !settings.leave_comma))
        {
            /* preserve force_nl thru a comment but
             * cancel forced newline after newline, form feed, etc.
             * however, don't cancel if last thing seen was comma-newline
             * and -bc flag is on. */

            force_nl = false;
        }
        else
        {
          /* what ? */
        }

        /* Main switch on type of token scanned */

        check_code_size();
        
        /* now, decide what to do with the token */

        handle_the_token(type_code, &scase, &force_nl, &sp_sw, &flushed_nl,
                         &hd_type, &dec_ind, &last_token_ends_sp, &file_exit_value,
                         can_break, &last_else, is_procname_definition,
                         pbreak_line);
        
        *e_code = '\0';         /* make sure code section is null terminated */

        if ((type_code != comment) &&
            (type_code != cplus_comment) &&
            (type_code != newline) &&
            (type_code != preesc) &&
            (type_code != form_feed))
        {
            parser_state_tos->last_token = type_code;
        }

        /* Now that we've put the token on the line (in most cases),
         * consider breaking the line because it's too long.
         *
         * Don't consider the cases of `unary_op', newlines,
         * declaration types (int, etc.), if, while, for,
         * identifiers (handled at the beginning of the loop),
         * periods, or preprocessor commands. */

        if ((settings.max_col > 0) && (buf_break != NULL))
        {
            if ( ( (type_code == binary_op) ||
                   (type_code == postop) ||
                   (type_code == question) ||
                   ((type_code == colon) && (scase || (squest <= 0))) ||
                   (type_code == semicolon) ||
                   (type_code == sp_nparen) ||
                   (type_code == sp_else) ||
                   ((type_code == ident) && (*token == '\"')) ||
                   (type_code == struct_delim) ||
                   (type_code == comma)) &&
                 (output_line_length () > settings.max_col))
            {
                *pbreak_line = true;
            }
        }
    }                           /* end of main infinite loop */
}
Ejemplo n.º 25
0
/*
 * Merge the commits h1 and h2, return the resulting virtual
 * commit object and a flag indicating the cleanness of the merge.
 */
int merge_recursive(struct merge_options *o,
		    struct commit *h1,
		    struct commit *h2,
		    struct commit_list *ca,
		    struct commit **result)
{
	struct commit_list *iter;
	struct commit *merged_common_ancestors;
	struct tree *mrtree = mrtree;
	int clean;

	if (show(o, 4)) {
		output(o, 4, "Merging:");
		output_commit_title(o, h1);
		output_commit_title(o, h2);
	}

	if (!ca) {
		ca = get_merge_bases(h1, h2, 1);
		ca = reverse_commit_list(ca);
	}

	if (show(o, 5)) {
		output(o, 5, "found %u common ancestor(s):", commit_list_count(ca));
		for (iter = ca; iter; iter = iter->next)
			output_commit_title(o, iter->item);
	}

	merged_common_ancestors = pop_commit(&ca);
	if (merged_common_ancestors == NULL) {
		/* if there is no common ancestor, make an empty tree */
		struct tree *tree = xcalloc(1, sizeof(struct tree));

		tree->object.parsed = 1;
		tree->object.type = OBJ_TREE;
		pretend_sha1_file(NULL, 0, OBJ_TREE, tree->object.sha1);
		merged_common_ancestors = make_virtual_commit(tree, "ancestor");
	}

	for (iter = ca; iter; iter = iter->next) {
		const char *saved_b1, *saved_b2;
		o->call_depth++;
		/*
		 * When the merge fails, the result contains files
		 * with conflict markers. The cleanness flag is
		 * ignored, it was never actually used, as result of
		 * merge_trees has always overwritten it: the committed
		 * "conflicts" were already resolved.
		 */
		discard_cache();
		saved_b1 = o->branch1;
		saved_b2 = o->branch2;
		o->branch1 = "Temporary merge branch 1";
		o->branch2 = "Temporary merge branch 2";
		merge_recursive(o, merged_common_ancestors, iter->item,
				NULL, &merged_common_ancestors);
		o->branch1 = saved_b1;
		o->branch2 = saved_b2;
		o->call_depth--;

		if (!merged_common_ancestors)
			die("merge returned no commit");
	}

	discard_cache();
	if (!o->call_depth)
		read_cache();

	clean = merge_trees(o, h1->tree, h2->tree, merged_common_ancestors->tree,
			    &mrtree);

	if (o->call_depth) {
		*result = make_virtual_commit(mrtree, "merged tree");
		commit_list_insert(h1, &(*result)->parents);
		commit_list_insert(h2, &(*result)->parents->next);
	}
	flush_output(o);
	return clean;
}
Ejemplo n.º 26
0
void modem_loop(modem_rx_cb_t cb)
{
#define BIT_1 0
#define BIT_2 1
#define BIT_3 2
#define BIT_4 3
#define BIT_5 4
#define WAIT_FOR_DATA 5
    int state = 0, recvd = 0;
    uint64_t mark;
    static uint8_t indata[1024], decdata[512], pktdata[1024], outdata[32768];
    buffer_t inbuf, decbuf, pktbuf, outbuf;

    buffer_init(&inbuf, indata, sizeof(indata));
    buffer_init(&decbuf, decdata, sizeof(decdata));
    buffer_init(&pktbuf, pktdata, sizeof(pktdata));
    buffer_init(&outbuf, outdata, sizeof(outdata));

    while (1)
    {
        uint8_t u_sample;
        size_t bytes = 1;

        if (ready_to_read() == 0) {
            // transmit(STDERR, "flush!\n", 7, NULL);
            flush_output();
        }

        if (get_byte(&u_sample) != 0)
            break;
//        if (receive(STDIN, &u_sample, 1, &bytes) != 0 || bytes != 1)
//            break;
        recvd++;

        buffer_write_bytes(&inbuf, &u_sample, 1);
        
        // process samples every 0.01 ms
        if (buffer_read_remaining(&inbuf) / 8 >= SAMPLES_PER_ITER)
        {
            modem_decode(&inbuf, &decbuf);

            while (state != WAIT_FOR_DATA && buffer_read_remaining(&decbuf) >= 8)
            {
                uint8_t bit;
                bit = buffer_read_bit(&decbuf);

                switch (state)
                {
                case BIT_1:
                    state = BIT_2;
                    mark = buffer_read_tell(&decbuf);
                    if (bit != 1)
                        goto reset;
                    break;
                case BIT_2:
                    state = BIT_3;
                    if (bit != 0)
                        goto reset;
                    break;
                case BIT_3:
                    state = BIT_4;
                    if (bit != 0)
                        goto reset;
                    break;
                case BIT_4:
                    state = BIT_5;
                    if (bit != 1)
                        goto reset;
                    break;
                case BIT_5:
                    state = WAIT_FOR_DATA;
                    if (bit != 1)
                        goto reset;
                    break;
                }
                
                continue;
reset:
                state = BIT_1;
                buffer_read_seek(&decbuf, mark);
            }

            if (state == WAIT_FOR_DATA && buffer_read_remaining(&decbuf) > FRAME_SIZE)
            {
                int result = frame_decode(&decbuf, &pktbuf);
                if (result == FRAME_FAIL)
                {
                    goto reset;
                }
                else if (result == FRAME_END)
                {
                    // XXX send packet to callback
                    cb(pktdata, buffer_read_remaining(&pktbuf) / 8);

                    buffer_init(&pktbuf, pktdata, sizeof(pktdata));
                }

                state = BIT_1;
            }
        }

        if (buffer_read_remaining(&outbuf) == 0)
            modem_encode_frame(&outbuf);

        if (buffer_read_remaining(&outbuf) > 0)
            buffer_read_bytes(&outbuf, &u_sample, 1);
        else
            u_sample = _modem_encode(1);

        write_byte(u_sample);
//        transmit(STDOUT, &u_sample, 1, &bytes);
    }
}
Ejemplo n.º 27
0
/** 
 * @brief Включает и выключает буферизацию вывода.
 * 
 * @param do_buffering Если 0, отключает буферизацию и отправляет текущее содержимое.
 *                     В противном случае включает буферизацию.
 */
void dprintf_ob(int do_buffering)
{
	debug_buffer_output = do_buffering;
	if (!debug_buffer_output)
		flush_output();
}
Ejemplo n.º 28
0
int ZlibEngine::filetofile( const char *input,
                      const char *output,
                      int level,
					  bool deflation)
{
    err = Z_OK;
    avail_in = 0;
    avail_out = output_length;
    next_out = output_buffer;
    m_AbortFlag = 0;

    fin  = fopen( input, "rb" );
    fout = fopen( output, "wb" );
	
	statResult = stat(input,&fileStatus); length = fileStatus.st_size;
	if (deflation)
		deflateInit( this, level);
	else
		inflateInit( this );
    for ( ; ; ) {
        if ( m_AbortFlag )
            break;
        if ( !load_input() )
            break;
		if (deflation)
			err = deflate( this, Z_NO_FLUSH );
		else
			err = inflate( this, Z_NO_FLUSH );
        flush_output();
        if ( err != Z_OK )
            break;
        progress( percent() );
    }
    for ( ; ; ) {
        if ( m_AbortFlag )
            break;
		if (deflation)
			err = deflate( this, Z_FINISH );
		else
			err = inflate( this, Z_FINISH );
        if ( !flush_output() )
            break;
        if ( err != Z_OK )
            break;
    }
    progress( percent() );
	if (deflation)
		deflateEnd( this );
	else
		inflateEnd( this );
    if ( m_AbortFlag )
        status( (char *)"User Abort" );
    else if ( err != Z_OK && err != Z_STREAM_END )
        status( (char *)"Zlib Error" );
    else {
        status( (char *)"Success" );
        err = Z_OK;
    }
    if ( fin )
        fclose( fin );
    fin = 0;
    if ( fout )
        fclose( fout );
    fout = 0;
    if ( m_AbortFlag )
        return Z_USER_ABORT;
    else
        return err;
}
Ejemplo n.º 29
0
int tty_ioctl(struct inode * inode, struct file * file,
	unsigned int cmd, unsigned int arg)
{
	struct tty_struct * tty;
	struct tty_struct * other_tty;
	int pgrp;
	int dev;

	if (MAJOR(file->f_rdev) != 4) {
		printk("tty_ioctl: tty pseudo-major != 4\n");
		return -EINVAL;
	}
	dev = MINOR(file->f_rdev);
	tty = TTY_TABLE(dev);
	if (!tty)
		return -EINVAL;

	if (IS_A_PTY(dev))
		other_tty = tty_table[PTY_OTHER(dev)];
	else
		other_tty = NULL;
		
	switch (cmd) {
		case TCGETS:
			return get_termios(tty,(struct termios *) arg);
		case TCSETSF:
			flush_input(tty);
		/* fallthrough */
		case TCSETSW:
			wait_until_sent(tty);
		/* fallthrough */
		case TCSETS:
			return set_termios(tty,(struct termios *) arg, dev);
		case TCGETA:
			return get_termio(tty,(struct termio *) arg);
		case TCSETAF:
			flush_input(tty);
		/* fallthrough */
		case TCSETAW:
			wait_until_sent(tty); /* fallthrough */
		case TCSETA:
			return set_termio(tty,(struct termio *) arg, dev);
		case TCXONC:
			switch (arg) {
			case TCOOFF:
				tty->stopped = 1;
				TTY_WRITE_FLUSH(tty);
				return 0;
			case TCOON:
				tty->stopped = 0;
				TTY_WRITE_FLUSH(tty);
				return 0;
			case TCIOFF:
				if (STOP_CHAR(tty))
					put_tty_queue(STOP_CHAR(tty),
						      &tty->write_q);
				return 0;
			case TCION:
				if (START_CHAR(tty))
					put_tty_queue(START_CHAR(tty),
						      &tty->write_q);
				return 0;
			}
			return -EINVAL; /* not implemented */
		case TCFLSH:
			if (arg==0)
				flush_input(tty);
			else if (arg==1)
				flush_output(tty);
			else if (arg==2) {
				flush_input(tty);
				flush_output(tty);
			} else
				return -EINVAL;
			return 0;
		case TIOCEXCL:
			return -EINVAL; /* not implemented */
		case TIOCNXCL:
			return -EINVAL; /* not implemented */
		case TIOCSCTTY:
			return -EINVAL; /* set controlling term NI */
		case TIOCGPGRP:
			verify_area((void *) arg,4);
			put_fs_long(tty->pgrp,(unsigned long *) arg);
			return 0;
		case TIOCSPGRP:
			if ((current->tty < 0) ||
			    (current->tty != dev) ||
			    (tty->session != current->session))
				return -ENOTTY;
			pgrp=get_fs_long((unsigned long *) arg);
			if (pgrp < 0)
				return -EINVAL;
			if (session_of_pgrp(pgrp) != current->session)
				return -EPERM;
			tty->pgrp = pgrp;			
			return 0;
		case TIOCOUTQ:
			verify_area((void *) arg,4);
			put_fs_long(CHARS(&tty->write_q),
				    (unsigned long *) arg);
			return 0;
		case TIOCINQ:
			verify_area((void *) arg,4);
			if (L_CANON(tty) && !tty->secondary.data)
				put_fs_long(0, (unsigned long *) arg);
			else
				put_fs_long(CHARS(&tty->secondary),
					(unsigned long *) arg);
			return 0;
		case TIOCSTI:
			return -EINVAL; /* not implemented */
		case TIOCGWINSZ:
			return get_window_size(tty,(struct winsize *) arg);
		case TIOCSWINSZ:
			if (IS_A_PTY_MASTER(dev))
				set_window_size(other_tty,(struct winsize *) arg);
			return set_window_size(tty,(struct winsize *) arg);
		case TIOCGSOFTCAR:
			return -EINVAL; /* not implemented */
		case TIOCSSOFTCAR:
			return -EINVAL; /* not implemented */
		case TIOCLINUX:
			switch (get_fs_byte((char *)arg))
			{
				case 0: 
					return do_screendump(arg);
				case 1: 
					return do_get_ps_info(arg);
				default: 
					return -EINVAL;
			}
		case TIOCCONS:
			if (!IS_A_PTY(dev))
				return -EINVAL;
			if (redirect)
				return -EBUSY;
			if (!suser())
				return -EPERM;
			if (IS_A_PTY_MASTER(dev))
				redirect = other_tty;
			else
				redirect = tty;
			return 0;
		case FIONBIO:
			if (arg)
				file->f_flags |= O_NONBLOCK;
			else
				file->f_flags &= ~O_NONBLOCK;
			return 0;
		case TIOCNOTTY:
			if (MINOR(file->f_rdev) != current->tty)
				return -EINVAL;
			current->tty = -1;
			if (current->leader) {
				if (tty->pgrp > 0)
					kill_pg(tty->pgrp, SIGHUP, 0);
				tty->pgrp = -1;
				tty->session = 0;
			}
			return 0;

	       case TIOCPKT:
			{
			   int on;
			   if (!IS_A_PTY_MASTER(dev))
			     return (-EINVAL);
			   verify_area ((unsigned long *)arg, sizeof (int));
			   on=get_fs_long ((unsigned long *)arg);
			   if (on )
			     tty->packet = 1;
			   else
			     tty->packet = 0;
			   return (0);
			}

		default:
			if (tty->ioctl)
				return (tty->ioctl)(tty, file, cmd, arg);
			else
				return -EINVAL;
	}
}
Ejemplo n.º 30
0
void buffer_loop(audio_output_t *ao, sigset_t *oldsigset)
{
	int bytes, outbytes;
	int my_fd = buffermem->fd[XF_READER];
	txfermem *xf = buffermem;
	int done = FALSE;
	int preload;

	catchsignal (SIGINT, catch_interrupt);
	catchsignal (SIGUSR1, catch_usr1);
	sigprocmask (SIG_SETMASK, oldsigset, NULL);

	xfermem_putcmd(my_fd, XF_CMD_WAKEUP);

	debug("audio output: waiting for cap requests");
	/* wait for audio setup queries */
	while(1)
	{
		int cmd;
		cmd = xfermem_block(XF_READER, xf);
		if(cmd == XF_CMD_AUDIOCAP)
		{
			ao->rate     = xf->rate;
			ao->channels = xf->channels;
			ao->format   = ao->get_formats(ao);
			debug3("formats for %liHz/%ich: 0x%x", ao->rate, ao->channels, ao->format);
			xf->format = ao->format;
			xfermem_putcmd(my_fd, XF_CMD_AUDIOCAP);
		}
		else if(cmd == XF_CMD_WAKEUP)
		{
			debug("got wakeup... leaving config mode");
			xfermem_putcmd(buffermem->fd[XF_READER], XF_CMD_WAKEUP);
			break;
		}
		else
		{
			error1("unexpected command %i", cmd);
			return;
		}
	}

	/* Fill complete buffer on first run before starting to play.
	 * Live mp3 streams constantly approach buffer underrun otherwise. [dk]
	 */
	preload = (int)(param.preload*xf->size);
	if(preload > xf->size) preload = xf->size;
	if(preload < 0) preload = 0;

	for (;;) {
		if (intflag) {
			debug("handle intflag... flushing");
			intflag = FALSE;
			ao->flush(ao);
			/* Either prepare for waiting or empty buffer now. */
			if(!xf->justwait) xf->readindex = xf->freeindex;
			else
			{
				int cmd;
				debug("Prepare for waiting; draining command queue. (There's a lot of wakeup commands pending, usually.)");
				do
				{
					cmd = xfermem_getcmd(my_fd, FALSE);
					/* debug1("drain: %i",  cmd); */
				} while(cmd > 0);
			}
			if(xf->wakeme[XF_WRITER]) xfermem_putcmd(my_fd, XF_CMD_WAKEUP);
		}
		if (usr1flag) {
			debug("handling usr1flag");
			usr1flag = FALSE;
			/*   close and re-open in order to flush
			 *   the device's internal buffer before
			 *   changing the sample rate.   [OF]
			 */
			/* writer must block when sending SIGUSR1
			 * or we will lose all data processed 
			 * in the meantime! [dk]
			 */
			xf->readindex = xf->freeindex;
			/* We've nailed down the new starting location -
			 * writer is now safe to go on. [dk]
			 */
			if (xf->wakeme[XF_WRITER])
				xfermem_putcmd(my_fd, XF_CMD_WAKEUP);
			ao->rate = xf->rate; 
			ao->channels = xf->channels; 
			ao->format = xf->format;
			if (reset_output(ao) < 0) {
				error1("failed to reset audio: %s", strerror(errno));
				exit(1);
			}
		}
		if ( (bytes = xfermem_get_usedspace(xf)) < outburst ) {
			/* if we got a buffer underrun we first
			 * fill 1/8 of the buffer before continue/start
			 * playing */
			if (preload < xf->size>>3)
				preload = xf->size>>3;
			if(preload < outburst)
				preload = outburst;
		}
		debug1("bytes: %i", bytes);
		if(xf->justwait || bytes < preload) {
			int cmd;
			if (done && !bytes) { 
				break;
			}
			
			if(xf->justwait || !done) {

				/* Don't spill into errno check below. */
				errno = 0;
				cmd = xfermem_block(XF_READER, xf);
				debug1("got %i", cmd);
				switch(cmd) {

					/* More input pending. */
					case XF_CMD_WAKEUP_INFO:
						continue;
					/* Yes, we know buffer is low but
					 * know we don't care.
					 */
					case XF_CMD_WAKEUP:
						break;	/* Proceed playing. */
					case XF_CMD_ABORT: /* Immediate end, discard buffer contents. */
						return; /* Cleanup happens outside of buffer_loop()*/
					case XF_CMD_TERMINATE: /* Graceful end, playing stuff in buffer and then return. */
						debug("going to terminate");
						done = TRUE;
						break;
					case XF_CMD_RESYNC:
						debug("ordered resync");
						if (param.outmode == DECODE_AUDIO) ao->flush(ao);

						xf->readindex = xf->freeindex;
						if (xf->wakeme[XF_WRITER]) xfermem_putcmd(my_fd, XF_CMD_WAKEUP);
						continue;
						break;
					case -1:
						if(intflag || usr1flag) /* Got signal, handle it at top of loop... */
						{
							debug("buffer interrupted");
							continue;
						}
						if(errno)
							error1("Yuck! Error in buffer handling... or somewhere unexpected: %s", strerror(errno));
						done = TRUE;
						xf->readindex = xf->freeindex;
						xfermem_putcmd(xf->fd[XF_READER], XF_CMD_TERMINATE);
						break;
					default:
						fprintf(stderr, "\nEh!? Received unknown command 0x%x in buffer process.\n", cmd);
				}
			}
		}
		/* Hack! The writer issues XF_CMD_WAKEUP when first adjust 
		 * audio settings. We do not want to lower the preload mark
		 * just yet!
		 */
		if (xf->justwait || !bytes)
			continue;
		preload = outburst; /* set preload to lower mark */
		if (bytes > xf->size - xf->readindex)
			bytes = xf->size - xf->readindex;
		if (bytes > outburst)
			bytes = outburst;

		/* The output can only take multiples of framesize. */
		bytes -= bytes % ao->framesize;

		debug("write");
		outbytes = flush_output(ao, (unsigned char*) xf->data + xf->readindex, bytes);

		if(outbytes < bytes)
		{
			if(outbytes < 0) outbytes = 0;
			if(!intflag && !usr1flag) {
				error1("Ouch ... error while writing audio data: %s", strerror(errno));
				/*
				 * done==TRUE tells writer process to stop
				 * sending data. There might be some latency
				 * involved when resetting readindex to 
				 * freeindex so we might need more than one
				 * cycle to terminate. (The number of cycles
				 * should be finite unless I managed to mess
				 * up something. ;-) [dk]
				 */
				done = TRUE;	
				xf->readindex = xf->freeindex;
				xfermem_putcmd(xf->fd[XF_READER], XF_CMD_TERMINATE);
			}
			else debug("buffer interrupted");
		}
		bytes = outbytes;

		xf->readindex = (xf->readindex + bytes) % xf->size;
		if (xf->wakeme[XF_WRITER])
			xfermem_putcmd(my_fd, XF_CMD_WAKEUP);
	}
}