示例#1
0
/* Wrapper for strdup */
char *
xstrdup(char *string)
{
	char *pointer;
	if ((pointer = strdup(string)) == NULL)
		xerr(1, "strdup");
	return pointer;
}
示例#2
0
/* Wrapper for malloc */
void *
xmalloc(size_t size)
{
	void *pointer;
	if ((pointer = malloc(size)) == NULL)
		xerr(1, "malloc");
	return pointer;
}
示例#3
0
文件: expand.c 项目: tizzybec/minix
static size_t
expand(char *buf, const char *execname, int what, size_t bl)
{
#ifdef __minix
	return 0;
#else
	const char *p, *ep;
	char *bp = buf;
	size_t len;
	char name[32];

	switch (what) {
	case 0:	/* HWCAP XXX: Not yet */
	case 1:	/* ISALIST XXX: Not yet */
		return 0;

	case 2:	/* ORIGIN */
		if (execname == NULL)
			xerr(1, "execname not specified in AUX vector");
		if ((ep = strrchr(p = execname, '/')) == NULL)
			xerr(1, "bad execname `%s' in AUX vector", execname);
		break;

	case 3:	/* OSNAME */
	case 4:	/* OSREL */
	case 5:	/* PLATFORM */
		len = sizeof(name);	
		if (sysctl(mib[what - 3], 2, name, &len, NULL, 0) == -1) {
			xwarn("sysctl");
			return 0;
		}
		ep = (p = name) + len - 1;
		break;
	default:
		return 0;
	}

	while (p != ep && bl)
		*bp++ = *p++, bl--;

	return bp - buf;
#endif
}
示例#4
0
int fcode_decode(int argc, char** argv)
{
    fcode_opt_t   cfg;
    memset(&cfg, 0, sizeof(cfg));
    cmdl_iter_t iter = cmdl_iter_init(argc, argv, 0);
    int r = cmdl_parse(&iter, &cfg, n_fcode_opt, fcode_opt);
    if (r == CMDL_RET_HELP) {
        return cmdl_help(&iter, 0, n_fcode_opt, fcode_opt);
    } else if (r < 0) {
        xerr("cmdl_parse() failed, ret=%d\n", r);
        return 1;
    }
    
    return mpeg2_motion_decode_test(&cfg);
}
示例#5
0
文件: xmsg.c 项目: dmilith/ekg2-bsd
static inline int xmsg_add_watch(session_t *s, const char *f)
{
	struct stat fs;
	const char *dir = xmsg_dirfix(f);

	if (!dir)
		return 0;
	else if (!stat(dir, &fs)) {
		if (!S_ISDIR(fs.st_mode))
			xerr("given path is a file, not a directory");
	} else {
		if (mkdir(dir, 0777))
			xerrn("mkdir failed");
	}

#ifdef HAVE_INOTIFY
	if ((s->priv = (void*) (long int) inotify_add_watch(in_fd, dir, (IN_CLOSE_WRITE|IN_MOVED_TO|IN_ONLYDIR))) == (void*) -1)
		xerrn("unable to add inotify watch");
	
	xdebug("inotify watch added: %d", (long int) s->priv);
#endif /*HAVE_INOTIFY*/
	
	return 0;
}
示例#6
0
文件: xmsg.c 项目: dmilith/ekg2-bsd
static TIMER_SESSION(xmsg_iterate_dir)
{
	const char *dir;
	DIR *d;
	struct dirent *de;
	int n = 0;
	const int maxn = session_int_get(s, "max_oneshot_files");

	if (type || !s || !session_connected_get(s))
		return -1;
	
	session_status_set(s, EKG_STATUS_AVAIL);
	if (!(dir = xmsg_dirfix(session_uid_get(s)+XMSG_UID_DIROFFSET))
			|| !(d = opendir(dir))) {

		xerr("unable to open specified directory");
		return 0;
	}
	
	while ((de = readdir(d))) {
		if (!xmsg_handle_file(s, de->d_name))
			n++;
		
		if ((maxn > 0) && n >= maxn) {
			const int i = session_int_get(s, "oneshot_resume_timer");
			if ((i > 0) && timer_add_session(s, "o", i, 0, xmsg_iterate_dir))
				xdebug("oneshot resume timer added");
			session_status_set(s, EKG_STATUS_AWAY);
			break;
		}
	}
	closedir(d);
	xdebug("processed %d files", n);

	return 0;
}
void MainWindow::setupLogErrorsTest(QCustomPlot *customPlot)
{
	customPlot->yAxis->setScaleType(QCPAxis::stLogarithmic);
	customPlot->yAxis->setSubTickCount(8);
	customPlot->yAxis->grid()->setSubGridVisible(true);
	int n = 11;
	QVector<double> x(n), y(n), yerr(n), xerr(n);
	for (int i=0; i<n; ++i)
	{
		x[i] = i;
		y[i] = i*0.1;
		yerr[i] = 0.5;
		xerr[i] = qAbs(qCos(i/2.0)*0.5);
	}
	customPlot->addGraph();
	customPlot->graph()->setScatterStyle(QCPScatterStyle::ssCross);
	customPlot->graph()->setDataBothError(x, y, xerr, yerr);
	customPlot->graph()->setErrorType(QCPGraph::etBoth);
	customPlot->graph()->setErrorBarSkipSymbol(true);

	//customPlot->rescaleAxes();
	customPlot->xAxis->setRange(0, 10);
	customPlot->yAxis->setRange(1, 10);
}
示例#8
0
int main(int argc, char **argv)
{
	int lines, row, col = 0;
	int i, opt;
	double av[3];
	static double max_scale = 0, scale_fact;
	long tmpdly;

	static const struct option longopts[] = {
		{"scale", required_argument, NULL, 's'},
		{"delay", required_argument, NULL, 'd'},
		{"help", no_argument, NULL, 'h'},
		{"version", no_argument, NULL, 'V'},
		{NULL, 0, NULL, 0}
	};
#ifdef HAVE_PROGRAM_INVOCATION_NAME
	program_invocation_name = program_invocation_short_name;
#endif
	setlocale (LC_ALL, "");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
	atexit(close_stdout);

	while ((opt =
		getopt_long(argc, argv, "s:d:Vh", longopts, NULL)) != -1)
		switch (opt) {
		case 's':
			max_scale = strtod_or_err(optarg, _("failed to parse argument"));
			if (max_scale < 0)
			        xerrx(EXIT_FAILURE, _("scale cannot be negative"));
			break;
		case 'd':
			tmpdly = strtol_or_err(optarg, _("failed to parse argument"));
			if (tmpdly < 1)
				xerrx(EXIT_FAILURE, _("delay must be positive integer"));
			else if (UINT_MAX < tmpdly)
				xerrx(EXIT_FAILURE, _("too large delay value"));
			dly = tmpdly;
			break;
		case 'V':
			printf(PROCPS_NG_VERSION);
			return EXIT_SUCCESS;
			break;
		case 'h':
			usage(stdout);
		default:
			usage(stderr);
		}

	if (argc > optind)
		if ((fd = open(argv[optind], 1)) == -1)
			xerr(EXIT_FAILURE, _("can not open tty"));

	setsize(0);

	if (max_scale == 0)
		max_scale = nrows;

	scale_fact = max_scale;

	setjmp(jb);
	col = 0;
	alrm(0);

	while (1) {

		if (scale_fact < max_scale)
			scale_fact *= 2.0;	/* help it drift back up. */

		loadavg(&av[0], &av[1], &av[2]);

		do {
			lines = av[0] * scale_fact;
			row = nrows - 1;

			while (0 <= --lines) {
				*(screen + row * ncols + col) = '*';
				if (--row < 0) {
					scale_fact /= 2.0;
					break;
				}
			}
		} while (0 <= lines);

		while (row >= 0)
			*(screen + row-- * ncols + col) = ' ';

		for (i = 1;; ++i) {
			char *p;
			row = nrows - (i * scale_fact);
			if (row < 0)
				break;
			if (*(p = screen + row * ncols + col) == ' ')
				*p = '-';
			else
				*p = '=';
		}

		if (++col == ncols) {
			--col;
			memmove(screen, screen + 1, scr_size - 1);

			for (row = nrows - 2; row >= 0; --row)
				*(screen + row * ncols + col) = ' ';
		}
		i = sprintf(screen, " %.2f, %.2f, %.2f", av[0], av[1], av[2]);
		if (i > 0)
			screen[i] = ' ';

		if (write(fd, "\033[H", 3) < 0)
			xerr(EXIT_FAILURE, _("writing to tty failed"));
		if (write(fd, screen, scr_size - 1) < 0)
			xerr(EXIT_FAILURE, _("writing to tty failed"));
		pause();
	}
}
示例#9
0
文件: https.c 项目: JinfengChen/pblat
void *netConnectHttpsThread(void *threadParam)
/* use a thread to run socket back to user */
{
/* child */

struct netConnectHttpsParams *params = threadParam;

pthread_detach(params->thread);  // this thread will never join back with it's progenitor

int fd=0;

char hostnameProto[256];

BIO *sbio;
SSL_CTX *ctx;
SSL *ssl;

openSslInit();

ctx = SSL_CTX_new(SSLv23_client_method());

fd_set readfds;
fd_set writefds;
int err;
struct timeval tv;


/* TODO checking certificates 

char *certFile = NULL;
char *certPath = NULL;
if (certFile || certPath)
    {
    SSL_CTX_load_verify_locations(ctx,certFile,certPath);
#if (OPENSSL_VERSION_NUMBER < 0x0090600fL)
    SSL_CTX_set_verify_depth(ctx,1);
#endif
    }

// verify paths and mode.

*/


sbio = BIO_new_ssl_connect(ctx);

BIO_get_ssl(sbio, &ssl);
if(!ssl) 
    {
    xerr("Can't locate SSL pointer");
    goto cleanup;
    }

/* Don't want any retries since we are non-blocking bio now */
//SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);


safef(hostnameProto,sizeof(hostnameProto),"%s:%d",params->hostName,params->port);
BIO_set_conn_hostname(sbio, hostnameProto);

BIO_set_nbio(sbio, 1);     /* non-blocking mode */

while (1) 
    {
    if (BIO_do_connect(sbio) == 1) 
	{
	break;  /* Connected */
	}
    if (! BIO_should_retry(sbio)) 
	{
	xerr("BIO_do_connect() failed");
	char s[256];	
	safef(s, sizeof s, "SSL error: %s", ERR_reason_error_string(ERR_get_error()));
	xerr(s);
	goto cleanup;
	}

    fd = BIO_get_fd(sbio, NULL);
    if (fd == -1) 
	{
	xerr("unable to get BIO descriptor");
	goto cleanup;
	}
    FD_ZERO(&readfds);
    FD_ZERO(&writefds);
    if (BIO_should_read(sbio)) 
	{
	FD_SET(fd, &readfds);
	}
    else if (BIO_should_write(sbio)) 
	{
	FD_SET(fd, &writefds);
	}
    else 
	{  /* BIO_should_io_special() */
	FD_SET(fd, &readfds);
	FD_SET(fd, &writefds);
	}
    tv.tv_sec = 10;  // timeout
    tv.tv_usec = 0;

    err = select(fd + 1, &readfds, &writefds, NULL, &tv);
    if (err < 0) 
	{
	xerr("select() error");
	goto cleanup;
	}

    if (err == 0) 
	{
	char s[256];	
	safef(s, sizeof s, "connection timeout to %s", params->hostName);
	xerr(s);
	goto cleanup;
	}
    }


/* TODO checking certificates 

if (certFile || certPath)
    if (!check_cert(ssl, host))
	return -1;

*/

/* we need to wait on both the user's socket and the BIO SSL socket 
 * to see if we need to ferry data from one to the other */


char sbuf[32768];  // socket buffer sv[1] to user
char bbuf[32768];  // bio buffer
int srd = 0;
int swt = 0;
int brd = 0;
int bwt = 0;
while (1) 
    {

    // Do NOT move this outside the while loop. 
    /* Get underlying file descriptor, needed for select call */
    fd = BIO_get_fd(sbio, NULL);
    if (fd == -1) 
	{
	xerr("BIO doesn't seem to be initialized in https, unable to get descriptor.");
	goto cleanup;
	}


    FD_ZERO(&readfds);
    FD_ZERO(&writefds);

    if (brd == 0)
	FD_SET(fd, &readfds);
    if (swt < srd)
	FD_SET(fd, &writefds);
    if (srd == 0)
	FD_SET(params->sv[1], &readfds);

    tv.tv_sec = 10;   // timeout
    tv.tv_usec = 0;

    err = select(max(fd,params->sv[1]) + 1, &readfds, &writefds, NULL, &tv);

    /* Evaluate select() return code */
    if (err < 0) 
	{
	xerr("error during select()");
	goto cleanup;
	}
    else if (err == 0) 
	{
	/* Timed out - just quit */
	xerr("https timeout expired");
	goto cleanup;
	}

    else 
	{
	if (FD_ISSET(params->sv[1], &readfds))
	    {
	    swt = 0;
	    srd = read(params->sv[1], sbuf, 32768);
	    if (srd == -1)
		{
		if (errno != 104) // udcCache often closes causing "Connection reset by peer"
		    xerrno("error reading https socket");
		goto cleanup;
		}
	    if (srd == 0) 
		break;  // user closed socket, we are done
	    }

	if (FD_ISSET(fd, &writefds))
	    {
	    int swtx = BIO_write(sbio, sbuf+swt, srd-swt);
	    if (swtx <= 0)
		{
		if (!BIO_should_write(sbio))
		    {
		    ERR_print_errors_fp(stderr);
		    xerr("Error writing SSL connection");
		    goto cleanup;
		    }
		}
	    else
		{
		swt += swtx;
		if (swt >= srd)
		    {
		    swt = 0;
		    srd = 0;
		    }
		}
	    }

	if (FD_ISSET(fd, &readfds))
	    {
	    bwt = 0;
	    brd = BIO_read(sbio, bbuf, 32768);

	    if (brd <= 0)
		{
		if (BIO_should_read(sbio))
		    {
		    brd = 0;
		    continue;
		    }
		else
		    {
		    if (brd == 0) break;
		    ERR_print_errors_fp(stderr);
		    xerr("Error reading SSL connection");
		    goto cleanup;
		    }
		}
	    // write the https data received immediately back on socket to user, and it's ok if it blocks.
	    while(bwt < brd)
		{
		int bwtx = write(params->sv[1], bbuf+bwt, brd-bwt);
		if (bwtx == -1)
		    {
		    if ((errno != 104)  // udcCache often closes causing "Connection reset by peer"
		     && (errno !=  32)) // udcCache often closes causing "Broken pipe"
			xerrno("error writing https data back to user socket");
		    goto cleanup;
		    }
		bwt += bwtx;
		}
	    brd = 0;
	    bwt = 0;
	    }
	}
    }

cleanup:

BIO_free_all(sbio);
close(params->sv[1]);  /* we are done with it */

return NULL;
}
示例#10
0
文件: forward.c 项目: ryo/netbsd-src
/*
 * forward -- display the file, from an offset, forward.
 *
 * There are eight separate cases for this -- regular and non-regular
 * files, by bytes or lines and from the beginning or end of the file.
 *
 * FBYTES	byte offset from the beginning of the file
 *	REG	seek
 *	NOREG	read, counting bytes
 *
 * FLINES	line offset from the beginning of the file
 *	REG	read, counting lines
 *	NOREG	read, counting lines
 *
 * RBYTES	byte offset from the end of the file
 *	REG	seek
 *	NOREG	cyclically read characters into a wrap-around buffer
 *
 * RLINES
 *	REG	mmap the file and step back until reach the correct offset.
 *	NOREG	cyclically read lines into a wrap-around array of buffers
 */
void
forward(FILE *fp, enum STYLE style, off_t off, struct stat *sbp)
{
	int ch, n;
	int kq=-1, action=USE_SLEEP;
	struct stat statbuf;
	struct kevent ev[2];

	switch(style) {
	case FBYTES:
		if (off == 0)
			break;
		if (S_ISREG(sbp->st_mode)) {
			if (sbp->st_size < off)
				off = sbp->st_size;
			if (fseeko(fp, off, SEEK_SET) == -1) {
				ierr();
				return;
			}
		} else while (off--)
			if ((ch = getc(fp)) == EOF) {
				if (ferror(fp)) {
					ierr();
					return;
				}
				break;
			}
		break;
	case FLINES:
		if (off == 0)
			break;
		for (;;) {
			if ((ch = getc(fp)) == EOF) {
				if (ferror(fp)) {
					ierr();
					return;
				}
				break;
			}
			if (ch == '\n' && !--off)
				break;
		}
		break;
	case RBYTES:
		if (S_ISREG(sbp->st_mode)) {
			if (sbp->st_size >= off &&
			    fseeko(fp, -off, SEEK_END) == -1) {
				ierr();
				return;
			}
		} else if (off == 0) {
			while (getc(fp) != EOF);
			if (ferror(fp)) {
				ierr();
				return;
			}
		} else {
			if (displaybytes(fp, off))
				return;
		}
		break;
	case RLINES:
		if (S_ISREG(sbp->st_mode)) {
			if (!off) {
				if (fseek(fp, 0L, SEEK_END) == -1) {
					ierr();
					return;
				}
			} else {
				if (rlines(fp, off, sbp))
					return;
			}
		} else if (off == 0) {
			while (getc(fp) != EOF);
			if (ferror(fp)) {
				ierr();
				return;
			}
		} else {
			if (displaylines(fp, off))
				return;
		}
		break;
	default:
		break;
	}

	if (fflag) {
		kq = kqueue();
		if (kq < 0)
			xerr(1, "kqueue");
		action = ADD_EVENTS;
	}

	for (;;) {
		while ((ch = getc(fp)) != EOF)  {
			if (putchar(ch) == EOF)
				oerr();
		}
		if (ferror(fp)) {
			ierr();
			return;
		}
		(void)fflush(stdout);
		if (!fflag)
			break;

		clearerr(fp);

		switch (action) {
		case ADD_EVENTS:
			n = 0;

			memset(ev, 0, sizeof(ev));
			if (fflag == 2 && fp != stdin) {
				EV_SET(&ev[n], fileno(fp), EVFILT_VNODE,
				    EV_ADD | EV_ENABLE | EV_CLEAR,
				    NOTE_DELETE | NOTE_RENAME, 0, 0);
				n++;
			}
			EV_SET(&ev[n], fileno(fp), EVFILT_READ,
			    EV_ADD | EV_ENABLE, 0, 0, 0);
			n++;

			if (kevent(kq, ev, n, NULL, 0, NULL) == -1) {
				close(kq);
				kq = -1;
				action = USE_SLEEP;
			} else {
				action = USE_KQUEUE;
			}
			break;

		case USE_KQUEUE:
			if (kevent(kq, NULL, 0, ev, 1, NULL) == -1)
				xerr(1, "kevent");

			if (ev[0].filter == EVFILT_VNODE) {
				/* file was rotated, wait until it reappears */
				action = USE_SLEEP;
			} else if (ev[0].data < 0) {
				/* file shrank, reposition to end */
				if (fseek(fp, 0L, SEEK_END) == -1) {
					ierr();
					return;
				}
			}
			break;

		case USE_SLEEP:
			/*
			 * We pause for one second after displaying any data
			 * that has accumulated since we read the file.
			 */
                	(void) sleep(1);

			if (fflag == 2 && fp != stdin &&
			    stat(fname, &statbuf) != -1) {
				if (statbuf.st_ino != sbp->st_ino ||
				    statbuf.st_dev != sbp->st_dev ||
				    statbuf.st_rdev != sbp->st_rdev ||
				    statbuf.st_nlink == 0) {
					fp = freopen(fname, "r", fp);
					if (fp == NULL) {
						ierr();
						goto out;
					}
					*sbp = statbuf;
					if (kq != -1)
						action = ADD_EVENTS;
				} else if (kq != -1)
					action = USE_KQUEUE;
			}
			break;
		}
	}
out:
	if (fflag && kq != -1)
		close(kq);
}
示例#11
0
文件: forward.c 项目: ryo/netbsd-src
/*
 * rlines -- display the last offset lines of the file.
 *
 * Non-zero return means than a (non-fatal) error occurred.
 */
static int
rlines(FILE *fp, off_t off, struct stat *sbp)
{
	off_t file_size;
	off_t file_remaining;
	char *p = NULL;
	char *start = NULL;
	off_t mmap_size;
	off_t mmap_offset;
	off_t mmap_remaining = 0;

#define MMAP_MAXSIZE  (10 * 1024 * 1024)

	if (!(file_size = sbp->st_size))
		return 0;
	file_remaining = file_size;

	if (file_remaining > MMAP_MAXSIZE) {
		mmap_size = MMAP_MAXSIZE;
		mmap_offset = file_remaining - MMAP_MAXSIZE;
	} else {
		mmap_size = file_remaining;
		mmap_offset = 0;
	}

	while (off) {
		start = mmap(NULL, (size_t)mmap_size, PROT_READ,
			     MAP_FILE|MAP_SHARED, fileno(fp), mmap_offset);
		if (start == MAP_FAILED) {
			xerr(0, "%s", fname);
			return 1;
		}

		mmap_remaining = mmap_size;
		/* Last char is special, ignore whether newline or not. */
		for (p = start + mmap_remaining - 1 ; --mmap_remaining ; )
			if (*--p == '\n' && !--off) {
				++p;
				break;
			}

		file_remaining -= mmap_size - mmap_remaining;

		if (off == 0)
			break;

		if (file_remaining == 0)
			break;

		if (munmap(start, mmap_size)) {
			xerr(0, "%s", fname);
			return 1;
		}

		if (mmap_offset >= MMAP_MAXSIZE) {
			mmap_offset -= MMAP_MAXSIZE;
		} else {
			mmap_offset = 0;
			mmap_size = file_remaining;
		}
	}

	/*
	 * Output the (perhaps partial) data in this mmap'd block.
	 */
	WR(p, mmap_size - mmap_remaining);
	file_remaining += mmap_size - mmap_remaining;
	if (munmap(start, mmap_size)) {
		xerr(0, "%s", fname);
		return 1;
	}

	/*
	 * Set the file pointer to reflect the length displayed.
	 * This will cause the caller to redisplay the data if/when
	 * needed.
	 */
	if (fseeko(fp, file_remaining, SEEK_SET) == -1) {
		ierr();
		return 1;
	}
	return 0;
}
示例#12
0
文件: xmsg.c 项目: dmilith/ekg2-bsd
static COMMAND(xmsg_msg)
{
	char fn[sizeof(XMSG_TMPFILE_PATH)];
	int fd;
	char *msg = (char*) params[1];
	const char *uid;
	int fs;
	int n;
	const char *msgcmd = session_get(session, "send_cmd");
	char *msgx = NULL, *mymsg;
	
	if (!(uid = get_uid(session, target))) {
		printq("invalid_session");
		return -1;
	}

	if (!msgcmd || *msgcmd == '\0') {
		printq("xmsg_nosendcmd", session_name(session));
		return -1;
	}
	
	xstrcpy(fn, XMSG_TMPFILE_PATH);
	
	fd = mkstemp(fn);
	if (fd == -1)
		xerrn("Unable to create temp file");
	{
		const char *charset = session_get(session, "charset");

		if (charset)
			msgx = ekg_convert_string(msg, NULL, charset);
		mymsg = (msgx ? msgx : msg);
	}
	fs = xstrlen(mymsg);

	while (fs > 0) {
		if ((n = write(fd, mymsg, fs)) == -1) {
			unlink(fn);
			close(fd);
			xfree(msgx);
			xerrn("Unable to write message into temp file");
		}
		fs -= n;
		mymsg += n;
	}

	xfree(msgx);	
	close(fd);
	if ((command_exec_format(NULL, session, 1, "!^%s \"%s\" \"%s\"", msgcmd, target+XMSG_UID_DIROFFSET, fn)))
		xerr("msgcmd exec failed");
	
	{
		char **rcpts	= xcalloc(2, sizeof(char *));
		int class	= (xstrcmp(name, "chat") ? EKG_MSGCLASS_SENT : EKG_MSGCLASS_SENT_CHAT);

		rcpts[0]	= xstrdup(uid);
		rcpts[1]	= NULL;

		protocol_message_emit(session, session->uid, rcpts, params[1], NULL, time(NULL), class, NULL, EKG_NO_BEEP, 0);

		array_free(rcpts);
	}
			
	return 0;
}
示例#13
0
文件: xmsg.c 项目: dmilith/ekg2-bsd
static int xmsg_handle_file(session_t *s, const char *fn)
{
	const int nounlink = !session_int_get(s, "unlink_sent");
	const int utb = session_int_get(s, "unlink_toobig");
	const int maxfs = session_int_get(s, "max_filesize");
	const char *dfsuffix = session_get(s, "dotfile_suffix");
	char *namesep = (char*) session_get(s, "name_separator");
	char *dir;
	int dirlen;

	char *msg = NULL;
	int err, fs;
	time_t ft = 0;
	
	if (*fn == '.') /* we're skipping ALL dotfiles */
		return -1;
	dir = (char*) xmsg_dirfix(session_uid_get(s)+XMSG_UID_DIROFFSET);
	dirlen = xstrlen(dir);
		/* first check if buffer is long enough to fit the whole path for dotfile */
	if (strlcpy(dir+dirlen+1, fn, PATH_MAX-dirlen-2-xstrlen(dfsuffix)) >= PATH_MAX-dirlen-2-xstrlen(dfsuffix))
		xerr("Buffer too small for: fn = %s, len(fn) = %d, dirlen = %d, dfsuffixlen = %d", fn, xstrlen(fn), dirlen, xstrlen(dfsuffix));

		/* then fill in middle part of path */
	dir[dirlen] = '/';
		/* and take a much closer look the file */	
	xdebug("s = %s, d = %s, fn = %s", session_uid_get(s), dir, fn);
	if ((err = xmsg_checkoutfile(dir, &msg, &fs, &ft, maxfs))) {
		if (err == EFBIG) {
			print((utb ? "xmsg_toobigrm" : "xmsg_toobig"), fn, session_name(s));
			if (utb) {
				unlink(dir);
				return -1;
			} /* else we need to create the dotfile first */
		} else if (err != ENOENT && err != EINVAL)
			return -1;
	} else if (!nounlink && (utb == (err == EFBIG)))
		unlink(dir);

		/* here: dir = dotf */
	memmove(dir+dirlen+2, dir+dirlen+1, xstrlen(dir) - dirlen);
	dir[dirlen+1] = '.';
	xstrcpy(dir+xstrlen(dir), dfsuffix); /* we've already checked whether it fits */
	
	{
		struct stat st;
		int r;
		
		if (nounlink || !utb) {
			r = !(stat(dir, &st) || S_ISDIR(st.st_mode));
		} else
			r = 0;
		
		if (err == ENOENT) {
			if (r) /* clean up stale dotfile */
				unlink(dir);
			xfree(msg);
			return -1;
		} else if (r) {
			xfree(msg); /* XXX: I think that we rather shouldn't first read, then check if it is needed,
					at least for nounlink mode */
			return -1;
		} else if ((nounlink && !(utb && err == EFBIG)) || (!utb && err == EFBIG))
			close(open(dir, O_WRONLY|O_CREAT|O_TRUNC|O_NOFOLLOW, 0600));
	}
	
	if (err == EFBIG)
		return -1;
	else if (err == EINVAL)
		xdebug("empty file, not submitting");
	else {
		char *uid	= xmalloc(strlen(fn) + 6);
		char *msgx	= NULL;

		{
			const char *charset = session_get(s, "charset");

			if (charset && (msgx = ekg_convert_string(msg, charset, NULL)))
				xfree(msg);
			else
				msgx = msg;
		}

		xstrcpy(uid, "xmsg:");
		xstrcat(uid, fn);
		if (namesep) {
			char *p, *q = NULL;

			for (p = namesep; *p; p++) {
				char *r = xstrrchr(uid+XMSG_UID_DIROFFSET, *p);
				if (r > q)
					q = r;
			}
			if (q)
				*q = '\0';
		}

		protocol_message_emit(s, uid, NULL, msgx, NULL, ft, EKG_MSGCLASS_CHAT, NULL, EKG_TRY_BEEP, 0);

		xfree(msgx);
		xfree(uid);
	}
	
	return 0;
}
void srcPositionStudy(Int_t binWidth, TString source, TString geometry) {

  int numFiles = 200; 

  TString simLocation;
  TChain *chain = new TChain("anaTree");

  if (geometry==TString("2011-2012")) simLocation = TString(getenv("SIM_2011_2012"));
  else if (geometry==TString("2012-2013")) simLocation = TString(getenv("SIM_2012_2013"));
  else if (geometry==TString("2012-2013_ISOBUTANE")) simLocation = TString(getenv("SIM_2012_2013_ISOBUTANE"));
  else { std::cout << "BAD GEOMETRY\n"; exit(0); }

  for (int i=0; i<numFiles; i++) {
    chain->AddFile(TString::Format("%s/%s/analyzed_%i.root",simLocation.Data(),source.Data(),i));
  }
  

  Double_t maxEn = 1500.;
  Double_t minEn = 0.;
  Double_t fidMax = 55.;
  Int_t nHists = (int)(fidMax/binWidth);
  
  
  
  std::vector <TH1D*> histsE(nHists, 0);
  std::vector <TH1D*> histsW(nHists, 0);
  std::vector <Double_t> rmin(nHists,0);
  std::vector <Double_t> rmax(nHists,0);
  std::vector <Double_t> rmid(nHists,0);

  //final means and errors
  std::vector < Double_t > EastMeans(nHists,0.);
  std::vector < Double_t > WestMeans(nHists,0.);
  
  std::vector < Double_t > EastMeanErrors(nHists,0.);
  std::vector < Double_t > WestMeanErrors(nHists,0.);

  for (Int_t i=0; i<nHists; i++) {

    rmin[i] = i*binWidth;
    rmax[i] = (i+1)*binWidth;
    rmid[i] = (double)rmin[i] + (double)binWidth/2.;

    histsE[i] = new TH1D(TString::Format("his%iE",i), 
			 TString::Format("%s %i mm radius bins East", source.Data(),binWidth),
			550, 0., 1100.);
    histsW[i] = new TH1D(TString::Format("his%iW",i), 
			 TString::Format("%s %i mm radius bins West", source.Data(),binWidth),
			550, 0., 1100.);

    histsE[i]->SetLineColor(i+1);
    histsW[i]->SetLineColor(i+1);
  }

  Double_t primPos[4];

  // Set the addresses of the information read in from the simulation file
  chain->SetBranchAddress("MWPCEnergy",&mwpcE);
  chain->SetBranchAddress("time",&Time);
  chain->SetBranchAddress("Edep",&edep);
  chain->SetBranchAddress("EdepQ",&edepQ);
  chain->SetBranchAddress("MWPCPos",&mwpc_pos);
  chain->SetBranchAddress("ScintPos",&scint_pos);
  chain->SetBranchAddress("primKE",&primKE);
  chain->SetBranchAddress("primTheta",&primTheta);
  chain->SetBranchAddress("primPos",&primPos);


  //Get total number of events in TChain
  UInt_t nevents = chain->GetEntries();
  cout << "events = " << nevents << endl;

  for (Int_t i=0; i<nevents; i++) {
    
    chain->GetEvent(i);

    Int_t nBin = primPos[3]*1000./binWidth;

    if (edepQ.EdepQE>0. && primKE<maxEn && primKE>minEn && mwpcE.MWPCEnergyE>0.1 && primTheta>TMath::Pi()/2.) histsE[nBin]->Fill(edepQ.EdepQE);
    if (edepQ.EdepQW>0. && primKE<maxEn && primKE>minEn && mwpcE.MWPCEnergyW>0.1 && primTheta<TMath::Pi()/2.) histsW[nBin]->Fill(edepQ.EdepQW);

    if (i%100000==0) std::cout << "*";
  }
  
  std::cout << std::endl;

  TCanvas *c1 = new TCanvas("c1","c1",1600,1200);
  c1->Divide(2,2);
  //TCanvas *c2 = new TCanvas("c2");
  
  //histsE[1]->Draw("SAME");
  
  Double_t refMeanE = 0., refMeanW = 0.; //This will hold the mean of the center pixel

  std::cout << nHists << endl;  
  for (Int_t i=0; i<nHists; i++) {
    c1->cd(1);
    histsE[i]->Draw("SAME");
    
    EastMeans[i] = histsE[i]->GetMean();
    EastMeanErrors[i] = EastMeans[i]>0. ? EastMeans[i]/sqrt(histsE[i]->GetEntries()) : 0.;
    //cout << EastMeans[i][0] << " " << EastMeans[i][1] << endl;

    c1->cd(2);
    histsW[i]->Draw("SAME");
    
    WestMeans[i] = histsW[i]->GetMean();
    WestMeanErrors[i] = WestMeans[i]>0. ? WestMeans[i]/sqrt(histsW[i]->GetEntries()) : 0.;

    if (i==0) { refMeanE = EastMeans[i], refMeanW = WestMeans[i]; }
  }

  

  //TCanvas *c3 = new TCanvas("c3");
  c1->cd(3);

  std::vector <Double_t> xerr(nHists,0.);
  
  TGraphErrors *gEast = new TGraphErrors(11, &rmax[0],&EastMeans[0],&xerr[0],&EastMeanErrors[0]);
  gEast->SetMarkerStyle(21);
  gEast->SetTitle(TString::Format("East %s Mean EQ vs. position",source.Data()));
  gEast->GetXaxis()->SetTitle("Position Bin Edge (mm)");
  gEast->GetYaxis()->SetTitle("Energy (keV)");
  gEast->Draw("AP");

  TLine *eastLine = new TLine(gEast->GetXaxis()->GetXmin(),refMeanE,gEast->GetXaxis()->GetXmax(),refMeanE);
  eastLine->SetLineStyle(2);
  eastLine->Draw();
 

  //TCanvas *c4 = new TCanvas("c4");
  c1->cd(4);

  TGraphErrors *gWest = new TGraphErrors(11, &rmax[0],&WestMeans[0],&xerr[0],&WestMeanErrors[0]);
  gWest->SetMarkerStyle(21);
  gWest->SetTitle(TString::Format("West %s Mean EQ vs. position",source.Data()));
  gWest->GetXaxis()->SetTitle("Position Bin Edge (mm)");
  gWest->GetYaxis()->SetTitle("Energy (keV)");
  gWest->Draw("AP");

  TLine *westLine = new TLine(gWest->GetXaxis()->GetXmin(),refMeanW,gWest->GetXaxis()->GetXmax(),refMeanW);
  westLine->SetLineStyle(2);
  westLine->Draw();

  
    


}
示例#15
0
void checkIntercalibration(std::vector<float> constant, std::vector<float> const_uncert, const std::string& outputdir, const std::string& runName, const std::string& tag){

  TCanvas* canny = new TCanvas("canny", "",200,200);

  int n=4;
  float vv[4] = { 0.05,1.05,2.05,3.05 };
  std::vector<float> x(&vv[0], &vv[0]+4);
  std::vector<float> xerr (4,0);

  TGraphErrors* graf = new TGraphErrors(n,&(x[0]),&(constant[0]),&(xerr[0]),&(const_uncert[0]));
  graf->SetMarkerStyle(20);
  graf->SetMarkerSize(0.5);
  graf->SetMarkerColor(38);



  float vv2[4] = { -0.05,0.95,1.95,2.95 };
  std::vector<float> x2(&vv2[0], &vv2[0]+4);
  float constantBTF[4] = {1.10023,0.9082,1.02656,0.984356};
  float constantBTF_uncert[4] = {0.0012271,0.00130331,0.00118187,0.00121551};

  TGraphErrors* graf2 = new TGraphErrors(n,&(x2[0]),&(constantBTF[0]),&(xerr[0]),&(constantBTF_uncert[0]));
  graf2->SetMarkerStyle(21);
  graf2->SetMarkerSize(0.5);
  graf2->SetMarkerColor(46);





  TMultiGraph *multi= new TMultiGraph();
  multi->Add(graf);
  multi->Add(graf2);
  multi->SetTitle(" ;Channel Nr.; Correction Factor");
  multi->Draw("AP");



  multi->GetYaxis()->SetRangeUser(0.85,1.15);
  // multi->GetYaxis()->SetRangeUser(0.1,3.5);
  multi->Draw("AP");
  canny->Update();


  TLine* lin = new TLine(-0.2,1.,3.2,1.);
  lin->SetLineColor(kRed);
  lin->Draw();

  TLegend* leg = new TLegend(0.6, 0.9-0.06*2, 0.9, 0.9); 
  leg->AddEntry(graf,"H4","P");
  leg->AddEntry(graf2,"Frascati","P");
  leg->SetFillColor(0);
  leg->Draw("same");

  if(savePlots==1){  canny->SaveAs( Form( "%s/chaInt_corrPlot_%s_%s.pdf", outputdir.c_str(), runName.c_str(), tag.c_str()  ));
    canny->SaveAs( Form( "%s/chaInt_corrPlot_%s_%s.eps", outputdir.c_str(), runName.c_str(), tag.c_str()  ));
}

  delete canny;

}