Exemplo n.º 1
0
static ZTHREAD proc_input_thread (void *arg)
{
    zbar_processor_t *proc = arg;
    zbar_thread_t *thread = &proc->input_thread;
    if(proc->window && proc_open(proc))
        goto done;

    _zbar_mutex_lock(&proc->mutex);
    thread->running = 1;
    _zbar_event_trigger(&thread->activity);
    zprintf(4, "spawned input thread\n");

    int rc = 0;
    while(thread->started && rc >= 0) {
        _zbar_mutex_unlock(&proc->mutex);
        rc = _zbar_processor_input_wait(proc, &thread->notify, -1);
        _zbar_mutex_lock(&proc->mutex);
    }

    _zbar_mutex_unlock(&proc->mutex);
    _zbar_processor_close(proc);
    _zbar_mutex_lock(&proc->mutex);

 done:
    thread->running = 0;
    _zbar_event_trigger(&thread->activity);
    _zbar_mutex_unlock(&proc->mutex);
    return(0);
}
Exemplo n.º 2
0
Arquivo: proc.c Projeto: reyk/snmpd
void
proc_connect(struct privsep *ps)
{
	struct imsgev		*iev;
	unsigned int		 src, dst, inst;

	/* Don't distribute any sockets if we are not really going to run. */
	if (ps->ps_noaction)
		return;

	for (dst = 0; dst < PROC_MAX; dst++) {
		/* We don't communicate with ourselves. */
		if (dst == PROC_PARENT)
			continue;

		for (inst = 0; inst < ps->ps_instances[dst]; inst++) {
			iev = &ps->ps_ievs[dst][inst];
			imsg_init(&iev->ibuf, ps->ps_pp->pp_pipes[dst][inst]);
			event_set(&iev->ev, iev->ibuf.fd, iev->events,
			    iev->handler, iev->data);
			event_add(&iev->ev, NULL);
		}
	}

	/* Distribute the socketpair()s for everyone. */
	for (src = 0; src < PROC_MAX; src++)
		for (dst = src; dst < PROC_MAX; dst++) {
			/* Parent already distributed its fds. */
			if (src == PROC_PARENT || dst == PROC_PARENT)
				continue;

			proc_open(ps, src, dst);
		}
}
Exemplo n.º 3
0
/* Performs DELETE VARIABLES command. */
int
cmd_delete_variables (struct lexer *lexer, struct dataset *ds)
{
  struct variable **vars;
  size_t var_cnt;
  bool ok;

  if (proc_make_temporary_transformations_permanent (ds))
    msg (SE, _("DELETE VARIABLES may not be used after TEMPORARY.  "
               "Temporary transformations will be made permanent."));

  if (!parse_variables (lexer, dataset_dict (ds), &vars, &var_cnt, PV_NONE))
    goto error;
  if (var_cnt == dict_get_var_cnt (dataset_dict (ds)))
    {
      msg (SE, _("DELETE VARIABLES may not be used to delete all variables "
                 "from the active dataset dictionary.  "
                 "Use NEW FILE instead."));
      goto error;
    }

  ok = casereader_destroy (proc_open (ds));
  ok = proc_commit (ds) && ok;
  if (!ok)
    goto error;
  dict_delete_vars (dataset_dict (ds), vars, var_cnt);

  free (vars);

  return CMD_SUCCESS;

 error:
  free (vars);
  return CMD_CASCADING_FAILURE;
}
Exemplo n.º 4
0
/* Perform BEGIN DATA...END DATA as a procedure in itself. */
int
cmd_begin_data (struct lexer *lexer, struct dataset *ds)
{
  struct dfm_reader *r;
  bool ok;

  if (!fh_is_locked (fh_inline_file (), FH_ACC_READ))
    {
      msg (SE, _("This command is not valid here since the current "
                 "input program does not access the inline file."));
      return CMD_CASCADING_FAILURE;
    }
  lex_match (lexer, T_ENDCMD);

  /* Open inline file. */
  r = dfm_open_reader (fh_inline_file (), lexer);
  r->flags |= DFM_SAW_BEGIN_DATA;
  r->flags &= ~DFM_CONSUME;

  /* Input procedure reads from inline file. */
  casereader_destroy (proc_open (ds));
  ok = proc_commit (ds);
  dfm_close_reader (r);

  return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
}
Exemplo n.º 5
0
static bool
run_reliability (struct dataset *ds, const struct reliability *reliability)
{
  struct dictionary *dict = dataset_dict (ds);
  bool ok;
  struct casereader *group;

  struct casegrouper *grouper = casegrouper_create_splits (proc_open (ds), dict);


  while (casegrouper_get_next_group (grouper, &group))
    {
      do_reliability (group, ds, reliability);

      reliability_statistics (reliability);

      if (reliability->summary & SUMMARY_TOTAL )
	reliability_summary_total (reliability);
    }

  ok = casegrouper_destroy (grouper);
  ok = proc_commit (ds) && ok;

  return ok;
}
Exemplo n.º 6
0
Arquivo: lxcfs.c Projeto: Blub/lxcfs
static int do_proc_open(const char *path, struct fuse_file_info *fi)
{
	int (*proc_open)(const char *path, struct fuse_file_info *fi);
	char *error;
	dlerror();    /* Clear any existing error */
	proc_open = (int (*)(const char *path, struct fuse_file_info *fi)) dlsym(dlopen_handle, "proc_open");
	error = dlerror();
	if (error != NULL) {
		fprintf(stderr, "proc_open: %s\n", error);
		return -1;
	}

	return proc_open(path, fi);
}
Exemplo n.º 7
0
Arquivo: proc.c Projeto: KnightKu/lmt
static int
proc_vscanf (pctx_t ctx, const char *path, const char *fmt, va_list ap)
{
    int n = -1;

    assert (ctx->pctx_magic == PCTX_MAGIC);
    assert (path || ctx->pctx_fp);
    assert (!ctx->pctx_dp);

    if (path) {
        if (proc_open (ctx, path) < 0)
            return -1;
    }
    n = vfscanf (ctx->pctx_fp, fmt, ap);
    if (path)
        proc_close (ctx);
    return n;
}
Exemplo n.º 8
0
Arquivo: proc.c Projeto: KnightKu/lmt
/* Returns -1 with errno == 0 for EOF
 * Trailing newlines are trimmed in the result.
 */
int
proc_gets (pctx_t ctx, const char *path, char *buf, int len)
{
    int i, ret = 0;

    assert (ctx->pctx_magic == PCTX_MAGIC);
    assert (path || ctx->pctx_fp);
    assert (!ctx->pctx_dp);

    if (path) {
        if (proc_open (ctx, path) < 0)
            return -1;
    }
    errno = 0;
    if (!fgets (buf, len, ctx->pctx_fp))
        ret = -1;
    if (path)
        proc_close (ctx);
    if (ret == 0 && (i = strlen (buf)) > 0 && buf[i - 1] == '\n')
        buf[i - 1] = '\0';
    return ret;
}
Exemplo n.º 9
0
Arquivo: proc.c Projeto: koue/httpd
void
proc_init(struct privsep *ps, struct privsep_proc *procs, unsigned int nproc,
    int argc, char **argv, enum privsep_procid proc_id)
{
	struct privsep_proc	*p = NULL;
	unsigned int		 proc;
	unsigned int		 src, dst;

	if (proc_id == PROC_PARENT) {
		privsep_process = PROC_PARENT;
		proc_setup(ps, procs, nproc);

		/* Open socketpair()s for everyone. */
		for (src = 0; src < PROC_MAX; src++)
			for (dst = 0; dst < PROC_MAX; dst++)
				proc_open(ps, src, dst);

		/* Engage! */
		proc_exec(ps, procs, nproc, argc, argv);
		return;
	}

	/* Initialize a child */
	for (proc = 0; proc < nproc; proc++) {
		if (procs[proc].p_id != proc_id)
			continue;
		p = &procs[proc];
		break;
	}
	if (p == NULL || p->p_init == NULL)
		fatalx("%s: process %d missing process initialization",
		    __func__, proc_id);

	p->p_init(ps, p);

	fatalx("failed to initiate child process");
}
Exemplo n.º 10
0
TCN_IMPLEMENT_CALL(jint, OS, info)(TCN_STDARGS,
                                   jlongArray inf)
{
    jint rv;
    int  i;
    jsize ilen = (*e)->GetArrayLength(e, inf);
    jlong *pvals = (*e)->GetLongArrayElements(e, inf, NULL);

    UNREFERENCED(o);
    if (ilen < 16) {
        return APR_EINVAL;
    }
    for (i = 0; i < 16; i++)
        pvals[i] = 0;
#if defined(__linux__)
    {
        struct sysinfo info;
        if (sysinfo(&info))
            rv = apr_get_os_error();
        else {
            pvals[0] = (jlong)(info.totalram  * info.mem_unit);
            pvals[1] = (jlong)(info.freeram   * info.mem_unit);
            pvals[2] = (jlong)(info.totalswap * info.mem_unit);
            pvals[3] = (jlong)(info.freeswap  * info.mem_unit);
            pvals[4] = (jlong)(info.sharedram * info.mem_unit);
            pvals[5] = (jlong)(info.bufferram * info.mem_unit);
            pvals[6] = (jlong)(100 - (info.freeram * 100 / info.totalram));
            rv = APR_SUCCESS;
        }
    }
#elif defined(sun)
    {
        /* static variables with basic procfs info */
        static long creation = 0;              /* unix timestamp of process creation */
        static int psinf_fd = 0;               /* file descriptor for the psinfo procfs file */
        static int prusg_fd = 0;               /* file descriptor for the usage procfs file */
        static size_t rss = 0;                 /* maximum of resident set size from previous calls */
        /* static variables with basic kstat info */
        static kstat_ctl_t *kstat_ctl = NULL;  /* kstat control object, only initialized once */
        static kstat_t *kstat_cpu[MAX_CPUS];   /* array of kstat objects for per cpu statistics */
        static int cpu_count = 0;              /* number of cpu structures found in kstat */
        static kid_t kid = 0;                  /* kstat ID, for which the kstat_ctl holds the correct chain */
        /* non-static variables - general use */
        int res = 0;                           /* general result state */
        /* non-static variables - sysinfo/swapctl use */
        long ret_sysconf;                      /* value returned from sysconf call */
        long tck_dividend;                     /* factor used by transforming tick numbers to milliseconds */
        long tck_divisor;                      /* divisor used by transforming tick numbers to milliseconds */
        long sys_pagesize = sysconf(_SC_PAGESIZE); /* size of a system memory page in bytes */
        long sys_clk_tck = sysconf(_SC_CLK_TCK); /* number of system ticks per second */
        struct anoninfo info;                  /* structure for information about sizes in anonymous memory system */
        /* non-static variables - procfs use */
        psinfo_t psinf;                        /* psinfo structure from procfs */
        prusage_t prusg;                       /* usage structure from procfs */
        size_t new_rss = 0;                    /* resident set size read from procfs */
        time_t now;                            /* time needed for calculating process creation time */
        /* non-static variables - kstat use */
        kstat_t *kstat = NULL;                 /* kstat working pointer */
        cpu_sysinfo_t cpu;                     /* cpu sysinfo working pointer */
        kid_t new_kid = 0;                     /* kstat ID returned from chain update */
        int new_kstat = 0;                     /* flag indicating, if kstat structure has changed since last call */

        rv = APR_SUCCESS;

        if (sys_pagesize <= 0) {
            rv = apr_get_os_error();
        }
        else {
            ret_sysconf = sysconf(_SC_PHYS_PAGES);
            if (ret_sysconf >= 0) {
                pvals[0] = (jlong)((jlong)sys_pagesize * ret_sysconf);
            }
            else {
                rv = apr_get_os_error();
            }
            ret_sysconf = sysconf(_SC_AVPHYS_PAGES);
            if (ret_sysconf >= 0) {
                pvals[1] = (jlong)((jlong)sys_pagesize * ret_sysconf);
            }
            else {
                rv = apr_get_os_error();
            }
            res=swapctl(SC_AINFO, &info);
            if (res >= 0) {
                pvals[2] = (jlong)((jlong)sys_pagesize * info.ani_max);
                pvals[3] = (jlong)((jlong)sys_pagesize * info.ani_free);
                pvals[6] = (jlong)(100 - (jlong)info.ani_free * 100 / info.ani_max);
            }
            else {
                rv = apr_get_os_error();
            }
        }

        if (psinf_fd == 0) {
            psinf_fd = proc_open("psinfo");
        }
        res = proc_read(&psinf, PSINFO_T_SZ, psinf_fd);
        if (res >= 0) {
            new_rss = psinf.pr_rssize*1024;
            pvals[13] = (jlong)(new_rss);
            if (new_rss > rss) {
                rss = new_rss;
            }
            pvals[14] = (jlong)(rss);
        }
        else {
            psinf_fd = 0;
            rv = apr_get_os_error();
        }
        if (prusg_fd == 0) {
            prusg_fd = proc_open("usage");
        }
        res = proc_read(&prusg, PRUSAGE_T_SZ, prusg_fd);
        if (res >= 0) {
            if (creation <= 0) {
                time(&now);
                creation = (long)(now - (prusg.pr_tstamp.tv_sec -
                                         prusg.pr_create.tv_sec));
            }
            pvals[10] = (jlong)(creation);
            pvals[11] = (jlong)((jlong)prusg.pr_stime.tv_sec * 1000 +
                                (prusg.pr_stime.tv_nsec / 1000000));
            pvals[12] = (jlong)((jlong)prusg.pr_utime.tv_sec * 1000 +
                                (prusg.pr_utime.tv_nsec / 1000000));
            pvals[15] = (jlong)(prusg.pr_majf);
        }
        else {
            prusg_fd = 0;
            rv = apr_get_os_error();
        }

        if (sys_clk_tck <= 0) {
            rv = apr_get_os_error();
        }
        else {
            tck_dividend = 1000;
            tck_divisor = sys_clk_tck;
            for (i = 0; i < 3; i++) {
                if (tck_divisor % 2 == 0) {
                    tck_divisor = tck_divisor / 2;
                    tck_dividend = tck_dividend / 2;
                }
                if (tck_divisor % 5 == 0) {
                    tck_divisor = tck_divisor / 5;
                    tck_dividend = tck_dividend / 5;
                }
            }
            if (kstat_ctl == NULL) {
                kstat_ctl = kstat_open();
                kid = kstat_ctl->kc_chain_id;
                new_kstat = 1;
            } else {
                new_kid = kstat_chain_update(kstat_ctl);
                if (new_kid < 0) {
                    res=kstat_close(kstat_ctl);
                    kstat_ctl = kstat_open();
                    kid = kstat_ctl->kc_chain_id;
                    new_kstat = 1;
                } else if (new_kid > 0 && kid != new_kid) {
                    kid = new_kid;
                    new_kstat = 1;
                }
            }
            if (new_kstat) {
                cpu_count = 0;
                for (kstat = kstat_ctl->kc_chain; kstat; kstat = kstat->ks_next) {
                    if (strncmp(kstat->ks_name, "cpu_stat", 8) == 0) {
                        kstat_cpu[cpu_count++]=kstat;
                    }
                }
            }
            for (i = 0; i < cpu_count; i++) {
                new_kid = kstat_read(kstat_ctl, kstat_cpu[i], NULL);
                if (new_kid >= 0) {
                    cpu = ((cpu_stat_t *)kstat_cpu[i]->ks_data)->cpu_sysinfo;
                    if ( tck_divisor == 1 ) {
                        pvals[7] += (jlong)(((jlong)cpu.cpu[CPU_IDLE]) * tck_dividend);
                        pvals[7] += (jlong)(((jlong)cpu.cpu[CPU_WAIT]) * tck_dividend);
                        pvals[8] += (jlong)(((jlong)cpu.cpu[CPU_KERNEL]) * tck_dividend);
                        pvals[9] += (jlong)(((jlong)cpu.cpu[CPU_USER]) * tck_dividend);
                    } else {
                        pvals[7] += (jlong)(((jlong)cpu.cpu[CPU_IDLE]) * tck_dividend / tck_divisor);
                        pvals[7] += (jlong)(((jlong)cpu.cpu[CPU_WAIT]) * tck_dividend / tck_divisor);
                        pvals[8] += (jlong)(((jlong)cpu.cpu[CPU_KERNEL]) * tck_dividend / tck_divisor);
                        pvals[9] += (jlong)(((jlong)cpu.cpu[CPU_USER]) * tck_dividend / tck_divisor);
                    }
                }
            }
        }

        /*
         * The next two are not implemented yet for Solaris
         * inf[4]  - Amount of shared memory
         * inf[5]  - Memory used by buffers
         *
         */
    }

#elif defined(DARWIN)

    uint64_t mem_total;
    size_t len = sizeof(mem_total);

    vm_statistics_data_t vm_info;
    mach_msg_type_number_t info_count = HOST_VM_INFO_COUNT;

    sysctlbyname("hw.memsize", &mem_total, &len, NULL, 0);
    pvals[0] = (jlong)mem_total;

    host_statistics(mach_host_self (), HOST_VM_INFO, (host_info_t)&vm_info, &info_count);
    pvals[1] = (jlong)(((double)vm_info.free_count)*vm_page_size);
    pvals[6] = (jlong)(100 - (pvals[1] * 100 / mem_total));
    rv = APR_SUCCESS;

/* DARWIN */
#else
    rv = APR_ENOTIMPL;
#endif
   (*e)->ReleaseLongArrayElements(e, inf, pvals, 0);
    return rv;
}
Exemplo n.º 11
0
void
proc_init(struct privsep *ps, struct privsep_proc *procs, u_int nproc)
{
	u_int			 i, j, src, dst;
	struct privsep_pipes	*pp;

	/*
	 * Allocate pipes for all process instances (incl. parent)
	 *
	 * - ps->ps_pipes: N:M mapping
	 * N source processes connected to M destination processes:
	 * [src][instances][dst][instances], for example
	 * [PROC_RELAY][3][PROC_CA][3]
	 *
	 * - ps->ps_pp: per-process 1:M part of ps->ps_pipes
	 * Each process instance has a destination array of socketpair fds:
	 * [dst][instances], for example
	 * [PROC_PARENT][0]
	 */
	for (src = 0; src < PROC_MAX; src++) {
		/* Allocate destination array for each process */
		if ((ps->ps_pipes[src] = calloc(ps->ps_ninstances,
		    sizeof(struct privsep_pipes))) == NULL)
			fatal("proc_init: calloc");

		for (i = 0; i < ps->ps_ninstances; i++) {
			pp = &ps->ps_pipes[src][i];

			for (dst = 0; dst < PROC_MAX; dst++) {
				/* Allocate maximum fd integers */
				if ((pp->pp_pipes[dst] =
				    calloc(ps->ps_ninstances,
				    sizeof(int))) == NULL)
					fatal("proc_init: calloc");

				/* Mark fd as unused */
				for (j = 0; j < ps->ps_ninstances; j++)
					pp->pp_pipes[dst][j] = -1;
			}
		}
	}

	/*
	 * Setup and run the parent and its children
	 */
	privsep_process = PROC_PARENT;
	ps->ps_instances[PROC_PARENT] = 1;
	ps->ps_title[PROC_PARENT] = "parent";
	ps->ps_pid[PROC_PARENT] = getpid();
	ps->ps_pp = &ps->ps_pipes[privsep_process][0];

	for (i = 0; i < nproc; i++) {
		/* Default to 1 process instance */
		if (ps->ps_instances[procs[i].p_id] < 1)
			ps->ps_instances[procs[i].p_id] = 1;
		ps->ps_title[procs[i].p_id] = procs[i].p_title;
	}

	proc_open(ps, NULL, procs, nproc);

	/* Engage! */
	for (i = 0; i < nproc; i++)
		ps->ps_pid[procs[i].p_id] = (*procs[i].p_init)(ps, &procs[i]);
}
Exemplo n.º 12
0
pid_t
proc_run(struct privsep *ps, struct privsep_proc *p,
    struct privsep_proc *procs, u_int nproc,
    void (*init)(struct privsep *, struct privsep_proc *, void *), void *arg)
{
	pid_t			 pid;
	struct passwd		*pw;
	const char		*root;
	struct control_sock	*rcs;
	u_int			 n;

	if (ps->ps_noaction)
		return (0);

	proc_open(ps, p, procs, nproc);

	/* Fork child handlers */
	switch (pid = fork()) {
	case -1:
		fatal("proc_run: cannot fork");
	case 0:
		/* Set the process group of the current process */
		setpgrp(0, getpid());
		break;
	default:
		return (pid);
	}

	pw = ps->ps_pw;

	if (p->p_id == PROC_CONTROL && ps->ps_instance == 0) {
		if (control_init(ps, &ps->ps_csock) == -1)
			fatalx(p->p_title);
		TAILQ_FOREACH(rcs, &ps->ps_rcsocks, cs_entry)
			if (control_init(ps, rcs) == -1)
				fatalx(p->p_title);
	}

	/* Change root directory */
	if (p->p_chroot != NULL)
		root = p->p_chroot;
	else
		root = pw->pw_dir;

	if (chroot(root) == -1)
		fatal("proc_run: chroot");
	if (chdir("/") == -1)
		fatal("proc_run: chdir(\"/\")");

	privsep_process = p->p_id;

	setproctitle("%s", p->p_title);

	if (setgroups(1, &pw->pw_gid) ||
	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
		fatal("proc_run: cannot drop privileges");

	/* Fork child handlers */
	for (n = 1; n < ps->ps_instances[p->p_id]; n++) {
		if (fork() == 0) {
			ps->ps_instance = p->p_instance = n;
			break;
		}
	}

#ifdef DEBUG
	log_debug("%s: %s %d/%d, pid %d", __func__, p->p_title,
	    ps->ps_instance + 1, ps->ps_instances[p->p_id], getpid());
#endif

	event_init();

	signal_set(&ps->ps_evsigint, SIGINT, proc_sig_handler, p);
	signal_set(&ps->ps_evsigterm, SIGTERM, proc_sig_handler, p);
	signal_set(&ps->ps_evsigchld, SIGCHLD, proc_sig_handler, p);
	signal_set(&ps->ps_evsighup, SIGHUP, proc_sig_handler, p);
	signal_set(&ps->ps_evsigpipe, SIGPIPE, proc_sig_handler, p);
	signal_set(&ps->ps_evsigusr1, SIGUSR1, proc_sig_handler, p);

	signal_add(&ps->ps_evsigint, NULL);
	signal_add(&ps->ps_evsigterm, NULL);
	signal_add(&ps->ps_evsigchld, NULL);
	signal_add(&ps->ps_evsighup, NULL);
	signal_add(&ps->ps_evsigpipe, NULL);
	signal_add(&ps->ps_evsigusr1, NULL);

	proc_listen(ps, procs, nproc);

	if (p->p_id == PROC_CONTROL && ps->ps_instance == 0) {
		TAILQ_INIT(&ctl_conns);
		if (control_listen(&ps->ps_csock) == -1)
			fatalx(p->p_title);
		TAILQ_FOREACH(rcs, &ps->ps_rcsocks, cs_entry)
			if (control_listen(rcs) == -1)
				fatalx(p->p_title);
	}
Exemplo n.º 13
0
int
cmd_t_test (struct lexer *lexer, struct dataset *ds)
{
  bool ok;
  const struct dictionary *dict = dataset_dict (ds);
  struct tt tt;
  int mode_count = 0;

  /* Variables pertaining to the paired mode */
  const struct variable **v1 = NULL;
  size_t n_v1;
  const struct variable **v2 = NULL;
  size_t n_v2;
	  
  size_t n_pairs = 0;
  vp *pairs = NULL;


  /* One sample mode */
  double testval = SYSMIS;

  /* Independent samples mode */
  const struct variable *gvar;
  union value gval0;
  union value gval1;
  bool cut = false;

  tt.wv = dict_get_weight (dict);
  tt.dict = dict;
  tt.confidence = 0.95;
  tt.exclude = MV_ANY;
  tt.missing_type = MISS_ANALYSIS;
  tt.n_vars = 0;
  tt.vars = NULL;
  tt.mode = MODE_undef;

  lex_match (lexer, T_EQUALS);

  for (; lex_token (lexer) != T_ENDCMD; )
    {
      lex_match (lexer, T_SLASH);
      if (lex_match_id (lexer, "TESTVAL"))
	{
	  mode_count++;
	  tt.mode = MODE_SINGLE;
	  lex_match (lexer, T_EQUALS);
	  lex_force_num (lexer);
	  testval = lex_number (lexer);
	  lex_get (lexer);
	}
      else if (lex_match_id (lexer, "GROUPS"))
	{
	  mode_count++;
	  cut = false;
	  tt.mode = MODE_INDEP;
	  lex_match (lexer, T_EQUALS);

	  if (NULL == (gvar = parse_variable (lexer, dict)))
	    goto parse_failed;
      
	  if (lex_match (lexer, T_LPAREN))
	    {

	      value_init (&gval0, var_get_width (gvar));
	      parse_value (lexer, &gval0, gvar);
	      cut = true;
	      if (lex_match (lexer, T_COMMA))
		{
		  value_init (&gval1, var_get_width (gvar));
		  parse_value (lexer, &gval1, gvar);
		  cut = false;
		}

	      lex_force_match (lexer, T_RPAREN);
	    }
	  else
	    {
	      value_init (&gval0, 0);
	      value_init (&gval1, 0);
	      gval0.f = 1.0;
	      gval1.f = 2.0;
	      cut = false;
	    }

	  if ( cut == true && var_is_alpha (gvar))
	    {
	      msg (SE, _("When applying GROUPS to a string variable, two "
			 "values must be specified."));
	      goto parse_failed;
	    }
	}
      else if (lex_match_id (lexer, "PAIRS"))
	{
	  bool with = false;
	  bool paired = false;

	  if (tt.n_vars > 0)
	    {
	      msg (SE, _("VARIABLES subcommand may not be used with PAIRS."));
	      goto parse_failed;
	    }

	  mode_count++;
	  tt.mode = MODE_PAIRED;
	  lex_match (lexer, T_EQUALS);

	  if (!parse_variables_const (lexer, dict,
				      &v1, &n_v1,
				      PV_NO_DUPLICATE | PV_NUMERIC))
	    goto parse_failed;

	  if ( lex_match (lexer, T_WITH))
	    {
	      with = true;
	      if (!parse_variables_const (lexer, dict,
					  &v2, &n_v2,
					  PV_NO_DUPLICATE | PV_NUMERIC))
		goto parse_failed;

	      if (lex_match (lexer, T_LPAREN)
		  && lex_match_id (lexer, "PAIRED")
		  && lex_match (lexer, T_RPAREN))
		{
		  paired = true;
		  if (n_v1 != n_v2)
		    {
		      msg (SE, _("PAIRED was specified but the number of variables "
				 "preceding WITH (%zu) did not match the number "
				 "following (%zu)."),
			   n_v1, n_v2);
		      goto parse_failed;
		    }
		}
	    }
	  {
	    int i;

	    if ( !with )
	      n_pairs = (n_v1 * (n_v1 - 1)) / 2.0;
	    else if ( paired )
	      n_pairs = n_v1;
	    else
	      n_pairs = n_v1 * n_v2;
	  
	    pairs = xcalloc (n_pairs, sizeof *pairs);

	    if ( with)
	      {
		int x = 0;
		if (paired)
		  {
		    for (i = 0 ; i < n_v1; ++i)
		      {
			vp *pair = &pairs[i];
			(*pair)[0] = v1[i];
			(*pair)[1] = v2[i];
		      }	
		  }
		else
		  {
		    for (i = 0 ; i < n_v1; ++i)
		      {
			int j;
			for (j = 0 ; j < n_v2; ++j)
			  {
			    vp *pair = &pairs[x++];
			    (*pair)[0] = v1[i];
			    (*pair)[1] = v2[j];
			  }
		      }
		  }
	      }
	    else
	      {
		int x = 0;
		for (i = 0 ; i < n_v1; ++i)
		  {
		    int j;

		    for (j = i + 1 ; j < n_v1; ++j)
		      {
			vp *pair = &pairs[x++];
			(*pair)[0] = v1[i];
			(*pair)[1] = v1[j];
		      }
		  }
	      }

	  }
	}
      else if (lex_match_id (lexer, "VARIABLES"))
	{
	  if ( tt.mode == MODE_PAIRED)
	    {
	      msg (SE, _("VARIABLES subcommand may not be used with PAIRS."));
	      goto parse_failed;
	    }

	  lex_match (lexer, T_EQUALS);

	  if (!parse_variables_const (lexer, dict,
				      &tt.vars,
				      &tt.n_vars,
				      PV_NO_DUPLICATE | PV_NUMERIC))
	    goto parse_failed;
	}
      else if ( lex_match_id (lexer, "MISSING"))
	{
          lex_match (lexer, T_EQUALS);
          while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
            {
	      if (lex_match_id (lexer, "INCLUDE"))
		{
		  tt.exclude = MV_SYSTEM;
		}
	      else if (lex_match_id (lexer, "EXCLUDE"))
		{
		  tt.exclude = MV_ANY;
		}
	      else if (lex_match_id (lexer, "LISTWISE"))
		{
		  tt.missing_type = MISS_LISTWISE;
		}
	      else if (lex_match_id (lexer, "ANALYSIS"))
		{
		  tt.missing_type = MISS_ANALYSIS;
		}
	      else
		{
                  lex_error (lexer, NULL);
		  goto parse_failed;
		}
	      lex_match (lexer, T_COMMA);
	    }
	}
      else if (lex_match_id (lexer, "CRITERIA"))
	{
          lex_match (lexer, T_EQUALS);
	  if ( lex_force_match_id (lexer, "CIN"))
	    if ( lex_force_match (lexer, T_LPAREN))
	      {
		lex_force_num (lexer);
		tt.confidence = lex_number (lexer);
		lex_get (lexer);
		lex_force_match (lexer, T_RPAREN);
	      }
	}
      else 
	{
	  lex_error (lexer, NULL);
	  goto parse_failed;
	}
    }

  if ( mode_count != 1)
    {
      msg (SE, _("Exactly one of TESTVAL, GROUPS and PAIRS subcommands "
		 "must be specified."));
      goto parse_failed;
    }

  if (tt.n_vars == 0 && tt.mode != MODE_PAIRED)
    {
      lex_sbc_missing ("VARIABLES");
      goto parse_failed;
    }



  /* Deal with splits etc */
  {
    struct casereader *group;
    struct casegrouper *grouper = casegrouper_create_splits (proc_open (ds), dict);

    while (casegrouper_get_next_group (grouper, &group))
      {
	if ( tt.mode == MODE_SINGLE)
	  {
	    if ( tt.missing_type == MISS_LISTWISE )
	      group  = casereader_create_filter_missing (group,
							 tt.vars, tt.n_vars,
							 tt.exclude,
							 NULL,  NULL);
	    one_sample_run (&tt, testval, group);
	  }
	else if ( tt.mode == MODE_PAIRED)
	  {
	    if ( tt.missing_type == MISS_LISTWISE )
	      {
		group  = casereader_create_filter_missing (group,
							   v1, n_v1,
							   tt.exclude,
							   NULL,  NULL);
		group  = casereader_create_filter_missing (group,
							   v2, n_v2,
							   tt.exclude,
							   NULL,  NULL);
	      }

	    paired_run (&tt, n_pairs, pairs, group);
	  }
	else /* tt.mode == MODE_INDEP */
	  {
	    if ( tt.missing_type == MISS_LISTWISE )
	      {
		group  = casereader_create_filter_missing (group,
							   tt.vars, tt.n_vars,
							   tt.exclude,
							   NULL,  NULL);

		group  = casereader_create_filter_missing (group,
							   &gvar, 1,
							   tt.exclude,
							   NULL,  NULL);

	      }

	    indep_run (&tt, gvar, cut, &gval0, &gval1, group);
	  }
      }

    ok = casegrouper_destroy (grouper);
    ok = proc_commit (ds) && ok;
  }

  free (pairs);
  free (v1);
  free (v2);

  free (tt.vars);

  return ok ? CMD_SUCCESS : CMD_FAILURE;

 parse_failed:
  return CMD_FAILURE;
}
Exemplo n.º 14
0
int zbar_processor_init (zbar_processor_t *proc,
                         const char *dev,
                         int enable_display)
{
    if(proc->video)
        zbar_processor_set_active(proc, 0);

    if(proc->window && !proc->input_thread.started)
        _zbar_processor_close(proc);

    _zbar_mutex_lock(&proc->mutex);
    _zbar_thread_stop(&proc->input_thread, &proc->mutex);
    _zbar_thread_stop(&proc->video_thread, &proc->mutex);

    _zbar_processor_lock(proc);
    _zbar_mutex_unlock(&proc->mutex);

    if(proc->window) {
        zbar_window_destroy(proc->window);
        proc->window = NULL;
    }

    int rc = 0;
    if(proc->video) {
        zbar_video_destroy(proc->video);
        proc->video = NULL;
    }

    if(!dev && !enable_display)
        /* nothing to do */
        goto done;

    if(enable_display) {
        proc->window = zbar_window_create();
        if(!proc->window) {
            rc = err_capture(proc, SEV_FATAL, ZBAR_ERR_NOMEM,
                             __func__, "allocating window resources");
            goto done;
        }
    }

    if(dev) {
        proc->video = zbar_video_create();
        if(!proc->video) {
            rc = err_capture(proc, SEV_FATAL, ZBAR_ERR_NOMEM,
                             __func__, "allocating video resources");
            goto done;
        }
        if(proc->req_width || proc->req_height)
            zbar_video_request_size(proc->video,
                                     proc->req_width, proc->req_height);
        if(proc->req_intf)
            zbar_video_request_interface(proc->video, proc->req_intf);
        if((proc->req_iomode &&
            zbar_video_request_iomode(proc->video, proc->req_iomode)) ||
           zbar_video_open(proc->video, dev)) {
            rc = err_copy(proc, proc->video);
            goto done;
        }
    }

    /* spawn blocking video thread */
    int video_threaded = (proc->threaded && proc->video &&
                          zbar_video_get_fd(proc->video) < 0);
    if(video_threaded &&
       _zbar_thread_start(&proc->video_thread, proc_video_thread, proc,
                          &proc->mutex)) {
        rc = err_capture(proc, SEV_ERROR, ZBAR_ERR_SYSTEM, __func__,
                         "spawning video thread");
        goto done;
    }

    /* spawn input monitor thread */
    int input_threaded = (proc->threaded &&
                          (proc->window ||
                           (proc->video && !video_threaded)));
    if(input_threaded &&
       _zbar_thread_start(&proc->input_thread, proc_input_thread, proc,
                          &proc->mutex)) {
        rc = err_capture(proc, SEV_ERROR, ZBAR_ERR_SYSTEM, __func__,
                         "spawning input thread");
        goto done;
    }

    if(proc->window && !input_threaded &&
       (rc = proc_open(proc)))
        goto done;

    if(proc->video && proc->force_input) {
        if(zbar_video_init(proc->video, proc->force_input))
            rc = err_copy(proc, proc->video);
    }
    else if(proc->video) {
        int retry = -1;
        if(proc->window) {
            retry = zbar_negotiate_format(proc->video, proc->window);
            if(retry)
                fprintf(stderr,
                        "WARNING: no compatible input to output format\n"
                        "...trying again with output disabled\n");
        }
        if(retry)
            retry = zbar_negotiate_format(proc->video, NULL);

        if(retry) {
            zprintf(1, "ERROR: no compatible %s format\n",
                    (proc->video) ? "video input" : "window output");
            rc = err_capture(proc, SEV_ERROR, ZBAR_ERR_UNSUPPORTED,
                             __func__, "no compatible image format");
        }
    }

 done:
    _zbar_mutex_lock(&proc->mutex);
    proc_leave(proc);
    return(rc);
}
Exemplo n.º 15
0
/* Parses and executes the AGGREGATE procedure. */
int
cmd_aggregate (struct lexer *lexer, struct dataset *ds)
{
  struct dictionary *dict = dataset_dict (ds);
  struct agr_proc agr;
  struct file_handle *out_file = NULL;
  struct casereader *input = NULL, *group;
  struct casegrouper *grouper;
  struct casewriter *output = NULL;

  bool copy_documents = false;
  bool presorted = false;
  bool saw_direction;
  bool ok;

  memset(&agr, 0 , sizeof (agr));
  agr.missing = ITEMWISE;
  agr.src_dict = dict;
  subcase_init_empty (&agr.sort);

  /* OUTFILE subcommand must be first. */
  lex_match (lexer, T_SLASH);
  if (!lex_force_match_id (lexer, "OUTFILE"))
    goto error;
  lex_match (lexer, T_EQUALS);
  if (!lex_match (lexer, T_ASTERISK))
    {
      out_file = fh_parse (lexer, FH_REF_FILE, dataset_session (ds));
      if (out_file == NULL)
        goto error;
    }

  if (out_file == NULL && lex_match_id (lexer, "MODE"))
    {
      lex_match (lexer, T_EQUALS);
      if (lex_match_id (lexer, "ADDVARIABLES"))
	{
	  agr.add_variables = true;

	  /* presorted is assumed in ADDVARIABLES mode */
	  presorted = true;
	}
      else if (lex_match_id (lexer, "REPLACE"))
	{
	  agr.add_variables = false;
	}
      else
	goto error;
    }

  if ( agr.add_variables )
    agr.dict = dict_clone (dict);
  else
    agr.dict = dict_create (dict_get_encoding (dict));

  dict_set_label (agr.dict, dict_get_label (dict));
  dict_set_documents (agr.dict, dict_get_documents (dict));

  /* Read most of the subcommands. */
  for (;;)
    {
      lex_match (lexer, T_SLASH);

      if (lex_match_id (lexer, "MISSING"))
	{
	  lex_match (lexer, T_EQUALS);
	  if (!lex_match_id (lexer, "COLUMNWISE"))
	    {
	      lex_error_expecting (lexer, "COLUMNWISE", NULL);
              goto error;
	    }
	  agr.missing = COLUMNWISE;
	}
      else if (lex_match_id (lexer, "DOCUMENT"))
        copy_documents = true;
      else if (lex_match_id (lexer, "PRESORTED"))
        presorted = true;
      else if (lex_force_match_id (lexer, "BREAK"))
	{
          int i;

	  lex_match (lexer, T_EQUALS);
          if (!parse_sort_criteria (lexer, dict, &agr.sort, &agr.break_vars,
                                    &saw_direction))
            goto error;
          agr.break_var_cnt = subcase_get_n_fields (&agr.sort);

	  if  (! agr.add_variables)
	    for (i = 0; i < agr.break_var_cnt; i++)
	      dict_clone_var_assert (agr.dict, agr.break_vars[i]);

          /* BREAK must follow the options. */
          break;
	}
      else
        goto error;

    }
  if (presorted && saw_direction)
    msg (SW, _("When PRESORTED is specified, specifying sorting directions "
               "with (A) or (D) has no effect.  Output data will be sorted "
               "the same way as the input data."));

  /* Read in the aggregate functions. */
  lex_match (lexer, T_SLASH);
  if (!parse_aggregate_functions (lexer, dict, &agr))
    goto error;

  /* Delete documents. */
  if (!copy_documents)
    dict_clear_documents (agr.dict);

  /* Cancel SPLIT FILE. */
  dict_set_split_vars (agr.dict, NULL, 0);

  /* Initialize. */
  agr.case_cnt = 0;

  if (out_file == NULL)
    {
      /* The active dataset will be replaced by the aggregated data,
         so TEMPORARY is moot. */
      proc_cancel_temporary_transformations (ds);
      proc_discard_output (ds);
      output = autopaging_writer_create (dict_get_proto (agr.dict));
    }
  else
    {
      output = any_writer_open (out_file, agr.dict);
      if (output == NULL)
        goto error;
    }

  input = proc_open (ds);
  if (!subcase_is_empty (&agr.sort) && !presorted)
    {
      input = sort_execute (input, &agr.sort);
      subcase_clear (&agr.sort);
    }

  for (grouper = casegrouper_create_vars (input, agr.break_vars,
                                          agr.break_var_cnt);
       casegrouper_get_next_group (grouper, &group);
       casereader_destroy (group))
    {
      struct casereader *placeholder = NULL;
      struct ccase *c = casereader_peek (group, 0);

      if (c == NULL)
        {
          casereader_destroy (group);
          continue;
        }

      initialize_aggregate_info (&agr);

      if ( agr.add_variables )
	placeholder = casereader_clone (group);

      {
	struct ccase *cg;
	for (; (cg = casereader_read (group)) != NULL; case_unref (cg))
	  accumulate_aggregate_info (&agr, cg);
      }


      if  (agr.add_variables)
	{
	  struct ccase *cg;
	  for (; (cg = casereader_read (placeholder)) != NULL; case_unref (cg))
	    dump_aggregate_info (&agr, output, cg);

	  casereader_destroy (placeholder);
	}
      else
	{
	  dump_aggregate_info (&agr, output, c);
	}
      case_unref (c);
    }
  if (!casegrouper_destroy (grouper))
    goto error;

  if (!proc_commit (ds))
    {
      input = NULL;
      goto error;
    }
  input = NULL;

  if (out_file == NULL)
    {
      struct casereader *next_input = casewriter_make_reader (output);
      if (next_input == NULL)
        goto error;

      dataset_set_dict (ds, agr.dict);
      dataset_set_source (ds, next_input);
      agr.dict = NULL;
    }
  else
    {
      ok = casewriter_destroy (output);
      output = NULL;
      if (!ok)
        goto error;
    }

  agr_destroy (&agr);
  fh_unref (out_file);
  return CMD_SUCCESS;

error:
  if (input != NULL)
    proc_commit (ds);
  casewriter_destroy (output);
  agr_destroy (&agr);
  fh_unref (out_file);
  return CMD_CASCADING_FAILURE;
}