예제 #1
0
파일: code_base.c 프로젝트: aidanhs/teeterl
int code_base_load(code_base_t *self, named_tuples_t *nm_tuples,
	term_t module, term_t exports, term_t fun_table, term_t attrs, term_t preloaded, term_t misc)
{
	module_t *m;
	apr_pool_t *pool;
	
	apr_pool_create(&pool, 0);
	m = apr_palloc(pool, sizeof(*m));
	m->mod_pool = pool;
	m->literals = heap_make(pool);
	m->key.module = module;
	m->key.is_old = 0;
	m->code_size = 0;
	m->code = 0;
	m->exports = apr_hash_make(pool);
	m->nfuns = 0;
	m->funs = 0;
	m->files = 0;
	m->source = 0;

	if (preloaded != nil)
	{
		int i;
		int n = list_length(preloaded);
		term_t cons = preloaded;
		int ok = 1;
		m->code = apr_palloc(pool, n*sizeof(codel_t));
		m->code_size = n;
		i = 0;
		while (ok && is_cons(cons))
		{
			term_box_t *cbox = peel(cons);
			if (is_int(cbox->cons.head))
			{
				m->code[i].i = int_value(cbox->cons.head);
			}
			else if (is_tuple(cbox->cons.head))
			{
				term_box_t *tbox = peel(cbox->cons.head);
				if (tbox->tuple.size == 2)
				{
					term_t selector = tbox->tuple.elts[0];
					term_t value = tbox->tuple.elts[1];
					switch (selector)
					{
					case AT__:		// {'@',Offset}
						m->code[i].l = m->code + int_value(value);
						break;
					case A_T:		// {t,Literal}
						m->code[i].t = heap_marshal(value, m->literals);
						break;
					case A_B:
						m->code[i].bif = builtins[int_value(value)].entry;
						break;
					case A_N:		// {n,{N,F}}
						if (is_tuple(value))
						{
							term_box_t *vb = peel(value);
							if (vb->tuple.size == 2)
							{
								term_t name = vb->tuple.elts[0];
								term_t field = vb->tuple.elts[1];
								int index = named_tuples_set(nm_tuples, name, field);
								m->code[i].t = tag_int(index);
							}
							else
								ok = 0;
						}
						else
							ok = 0;
						break;
					default:
						ok = 0;
					}
				}
			}
			else if (is_bignum(cbox->cons.head))
			{
				mp_int mp = bignum_to_mp(cbox->cons.head);
                m->code[i].i = mp_get_int(&mp);
			}
			else
				ok = 0;

			i++;
			cons = cbox->cons.tail;
		}

		if (!ok)
		{
			apr_pool_destroy(pool);
			return 1;
		}
	}

	// misc:
	// source line info:
	// {file,Files}
	// {source,[{F,L,S,E}]}

	if (misc != nil)
	{
		term_t cons = misc;
		while (is_cons(cons))
		{
			term_box_t *cb = peel(cons);
			term_t t = cb->cons.head;
			if (is_tuple(t))
			{
				term_box_t *tb = peel(t);
				if (tb->tuple.size >= 2)
				{
					term_t selector = tb->tuple.elts[0];
					term_t info = tb->tuple.elts[1];
					switch (selector)
					{
					case A_FILES:
						m->files = source_files_names(info, pool);
						break;
					case A_SOURCE:
						m->source = source_line_blocks(info, pool);
						break;
					}
				}
			}
			cons = cb->cons.tail;
		}
	}

	if (fun_table != nil)
	{
		int i;
		int nfuns = list_length(fun_table);
		term_t cons = fun_table;
		int ok = 1;
		m->funs = apr_palloc(pool, nfuns*sizeof(fun_slot_t));
		m->nfuns = nfuns;
		for (i = 0; ok && i < nfuns; i++)
		{
			term_box_t *cbox = peel(cons);
			if (is_tuple(cbox->cons.head))
			{
				term_box_t *tbox = peel(cbox->cons.head);
				if (tbox->tuple.size == 2)
				{
					term_t uniq = tbox->tuple.elts[0];
					term_t offset = tbox->tuple.elts[1];
					if ((is_int(uniq) || is_bignum(uniq)) && is_int(offset))
					{
						fun_slot_t *slot = &m->funs[i];
						if (is_int(uniq))
							slot->uniq = int_value(uniq);
						else
						{
							mp_int mp = bignum_to_mp(uniq);
							slot->uniq = (uint)mp_get_int(&mp);
						}
						slot->entry = m->code + int_value(offset);
					}
					else
						ok = 0;

				}
				else
					ok = 0;
			}
			else
				ok = 0;

			cons = cbox->cons.tail;
		}

		if (!ok)
		{
			apr_pool_destroy(pool);
			return 1;
		}
	}

	//TODO: attrs ingnored

	if (exports != nil)
	{
		int ok = 1;
		term_t cons = exports;
		while (ok && is_cons(cons))
		{
			term_box_t *cbox = peel(cons);
			// {Function,Arity,Offset}
			if (is_tuple(cbox->cons.head))
			{
				term_box_t *tbox = peel(cbox->cons.head);
				if (tbox->tuple.size == 3)
				{
					term_t function = tbox->tuple.elts[0];
					term_t arity = tbox->tuple.elts[1];
					term_t offset = tbox->tuple.elts[2];
					if (is_atom(function) && is_int(arity) && is_int(offset))
					{
						export_t *exp = apr_palloc(pool, sizeof(*exp));
						exp->key.function = function;
						exp->key.arity = int_value(arity);
						exp->entry = m->code + int_value(offset);
						apr_hash_set(m->exports, &exp->key, sizeof(exp->key), exp);
					}
					else
						ok = 0;
				}
				else
					ok = 0;
			}
			else
				ok = 0;

			cons = cbox->cons.tail;
		}

		if (!ok)
		{
			apr_pool_destroy(pool);
			return 1;
		}
	}

	apr_hash_set(self->modules, &m->key, sizeof(m->key), m);
	return 0;
}
예제 #2
0
파일: Type.cpp 프로젝트: mfichman/jogo
bool Type::is_number() const { 
    return is_float() || is_int() || is_byte(); 
}
예제 #3
0
/* MAIN */
int
main( int argc, char **argv )
{
    size_t  results[] = {4255, 142803, 46838, 0}, i = 0,
            output = 0;
    const size_t b = 5;
    const char *count_bytes_files[] = {
            "/data/orig_breaks.txt", "/data/spawner_output.txt",
            "/data/zh_romance_of_three_kingdoms.txt", ""},
            *source_dir = getenv("SOURCE");
    char    buffer[BUFSIZ], tinybuffer[b], *locale = "root", *encoding = "UTF-8";
    OChar   obuffer[BUFSIZ], otinybuffer[b];
    struct  stat sts;
    time_t  now;
    FILE    *f;
    init_oly(argv[0], TEST_PKGDATADIR, encoding, locale);
    if (source_dir == NULL)
    {
        fprintf(stderr, "requires SOURCE environment variable, supplied by runtest. Exiting...\n");
        exit(EXIT_FAILURE);
    }
    plan(16);
    diag("----- Testing oly_timestamp function. -----");
    time(&now);
    is_double(((double)( now*1000)), oly_timestamp(), 1000.0, "Two times should be close enough.");

    diag("----- Testing count_file_bytes function. -----");
    for (i = 0; (results[i] != 0); i++) {
        strcpy(buffer, source_dir);
        strcat(buffer, count_bytes_files[i]);
        if (stat(buffer, &sts) == -1 && errno == ENOENT)
        {
            printf ("The file %s doesn't exist...\n", buffer);
        }
        f = fopen(buffer, "r");
        assert( count_file_bytes( f, &output ) == OLY_OKAY ) ;
        is_int(results[i], output, "File: %s", count_bytes_files[i]);
        fclose(f);
    }
    
    diag("----- Testing get_default_locale and get_default_encoding function. -----");
    is_unicode_string( u"root", 
            get_default_locale(), "For this test, default locale should be root.");
    is_unicode_string( u"UTF-8", 
            get_default_encoding(), "For this test, default encoding should be UTF-8.");
    
    diag("----- Testing char_default_locale and char_default_encoding function. -----");
    is_string( "root", 
            char_default_locale(), "For this test, default locale should be root.");
    is_string( "UTF-8", 
            char_default_encoding(), "For this test, default encoding should be UTF-8.");
    
    diag("----- ostr_to_cstr and cstr_to_ostr -----");
    is_unicode_string( u"Lorum ipsum etc...", 
            cstr_to_ostr( obuffer, BUFSIZ, "Lorum ipsum etc..."), 
            "Char to ochar with space, BUFSIZ = %i", BUFSIZ);
    is_unicode_string( u"Loru", 
            cstr_to_ostr( otinybuffer, b, "Lorum ipsum etc..." ), 
            "Char to ochar with tiny buffer of %i characters.", (int)b );
    is_unicode_string( u"", 
            cstr_to_ostr( otinybuffer, b, "" ), 
            "Char to ochar With empty string" );
    is_unicode_string( u"", 
            cstr_to_ostr( otinybuffer, b, NULL ), 
            "Char to ochar from null" );
    is_string( "Back the other way!", 
            ostr_to_cstr( buffer, BUFSIZ, u"Back the other way!" ), 
            "OChar to char, BUFSIZ = %i", BUFSIZ );
    is_string( "five", 
            ostr_to_cstr( tinybuffer, b, u"five characters is all that fits." ), 
            "OChar to char, buffer of %i OChars", (int)b );
    is_string( "", 
            ostr_to_cstr( tinybuffer, b, NULL ), 
            "Char to ochar a NULL from string." );
    is_string( "", 
            ostr_to_cstr( tinybuffer, b, u"" ), 
            "Char to ochar with an empty string." );


    exit(EXIT_SUCCESS);
}
예제 #4
0
파일: lp_solve.c 프로젝트: gtqite/ssc
static void print_statistics(lprec *lp)
{
  REAL *col, *RHSmin, *RHSmax, *OBJmin, *OBJmax, *MATmin, *MATmax;
  int *nz, ret, m, n, i, j, k, l, nRHSmin = 0, nRHSmax = 0, nOBJmin = 0, nOBJmax = 0, nMATmin = 0, nMATmax = 0, *rowRHSmin, *rowRHSmax, *colOBJmin, *colOBJmax, *rowMATmin, *rowMATmax, *colMATmin, *colMATmax;

  m = get_Nrows(lp);
  n = get_Ncolumns(lp);

  col = (REAL *) malloc((1 + m) * sizeof(*col));
  nz = (int *) malloc((1 + m) * sizeof(*RHSmin));
  RHSmin = (REAL *) malloc(nstats * sizeof(*RHSmin));
  RHSmax = (REAL *) malloc(nstats * sizeof(*RHSmax));
  rowRHSmin = (int *) malloc(nstats * sizeof(*RHSmin));
  rowRHSmax = (int *) malloc(nstats * sizeof(*RHSmax));
  OBJmin = (REAL *) malloc(nstats * sizeof(*OBJmin));
  OBJmax = (REAL *) malloc(nstats * sizeof(*OBJmax));
  colOBJmin = (int *) malloc(nstats * sizeof(*colOBJmin));
  colOBJmax = (int *) malloc(nstats * sizeof(*colOBJmax));
  MATmin = (REAL *) malloc(nstats * sizeof(*MATmin));
  MATmax = (REAL *) malloc(nstats * sizeof(*MATmax));
  rowMATmin = (int *) malloc(nstats * sizeof(*rowMATmin));
  rowMATmax = (int *) malloc(nstats * sizeof(*rowMATmax));
  colMATmin = (int *) malloc(nstats * sizeof(*colMATmin));
  colMATmax = (int *) malloc(nstats * sizeof(*colMATmax));

/*
  minmax(2.0, MATmin, MATmax, &nMATmin, &nMATmax, 1, rowMATmin, rowMATmax, 8, colMATmin, colMATmax);
  minmax(1.0, MATmin, MATmax, &nMATmin, &nMATmax, 2, rowMATmin, rowMATmax, 7, colMATmin, colMATmax);
  minmax(1.5, MATmin, MATmax, &nMATmin, &nMATmax, 3, rowMATmin, rowMATmax, 6, colMATmin, colMATmax);
  minmax(3.0, MATmin, MATmax, &nMATmin, &nMATmax, 4, rowMATmin, rowMATmax, 5, colMATmin, colMATmax);
  minmax(4.0, MATmin, MATmax, &nMATmin, &nMATmax, 5, rowMATmin, rowMATmax, 4, colMATmin, colMATmax);
  minmax(0.1, MATmin, MATmax, &nMATmin, &nMATmax, 6, rowMATmin, rowMATmax, 3, colMATmin, colMATmax);
  minmax(5.0, MATmin, MATmax, &nMATmin, &nMATmax, 7, rowMATmin, rowMATmax, 2, colMATmin, colMATmax);
  minmax(1.4, MATmin, MATmax, &nMATmin, &nMATmax, 8, rowMATmin, rowMATmax, 1, colMATmin, colMATmax);

  printminmax(MATmin, MATmax, nMATmin, nMATmax, rowMATmin, rowMATmax, colMATmin, colMATmax);
*/

  for (i = 1; i <= m; i++)
    minmax(get_rh(lp, i), RHSmin, RHSmax, &nRHSmin, &nRHSmax, i, rowRHSmin, rowRHSmax, 0, NULL, NULL);

  for (j = 1; j <= n; j++) {
    ret = get_columnex(lp, j, col, nz);
    for (i = 0; i < ret; i++)
      if (nz[i] == 0)
        minmax(col[i], OBJmin, OBJmax, &nOBJmin, &nOBJmax, 0, NULL, NULL, j, colOBJmin, colOBJmax);
      else
        minmax(col[i], MATmin, MATmax, &nMATmin, &nMATmax, nz[i], rowMATmin, rowMATmax, j, colMATmin, colMATmax);
  }

  printf("Constraints: %d\n", get_Nrows(lp));
  printf("Variables  : %d\n", get_Ncolumns(lp));
  for (j = k = l = 0, i = n; i >= 1; i--) {
    if (is_int(lp, i))
      j++;
    if (is_semicont(lp, i))
      k++;
    if (is_SOS_var(lp, i))
      l++;
  }
  printf("Integers   : %d\n", j);
  printf("Semi-cont  : %d\n", k);
  printf("SOS        : %d\n", l);
  k = get_nonzeros(lp);
  printf("Non-zeros  : %d\tdensity=%f%%\n", k, ((double) k) / (((double) m) * ((double) n)) * 100.0);

  printf("\nAbsolute Ranges:\n\n       Minima                                  Maxima\n");
  printf("\nMatrix Coeficients:\n");
  printminmax(lp, "A", MATmin, MATmax, nMATmin, nMATmax, rowMATmin, rowMATmax, colMATmin, colMATmax);

  printf("\nObj. Vector:\n");
  printminmax(lp, "c", OBJmin, OBJmax, nOBJmin, nOBJmax, NULL, NULL, colOBJmin, colOBJmax);

  printf("\nRHS Vector:\n");
  printminmax(lp, "b", RHSmin, RHSmax, nRHSmin, nRHSmax, rowRHSmin, rowRHSmax, NULL, NULL);

  free(col);
  free(nz);
  free(RHSmin);
  free(RHSmax);
  free(rowRHSmin);
  free(rowRHSmax);
  free(OBJmin);
  free(OBJmax);
  free(colOBJmin);
  free(colOBJmax);
  free(MATmin);
  free(MATmax);
  free(rowMATmin);
  free(rowMATmax);
  free(colMATmin);
  free(colMATmax);
}
예제 #5
0
파일: main.c 프로젝트: seppo0010/Euler
int is_pentagonal(int n) {
	return is_int((0.5+sqrt(0.25+6*(double)n)) / 3);
}
예제 #6
0
STATIC REAL scale(lprec *lp, REAL *scaledelta)
{
  int     i, j, nz, row_count, nzOF = 0;
  REAL    *row_max, *row_min, *scalechange = NULL, absval;
  REAL    col_max, col_min;
  MYBOOL  rowscaled, colscaled;
  MATrec  *mat = lp->matA;
  REAL    *value;
  int     *rownr;

  if(is_scaletype(lp, SCALE_NONE))
    return(0.0);

  if(!lp->scaling_used) {
    allocREAL(lp, &lp->scalars, lp->sum_alloc + 1, FALSE);
    for(i = 0; i <= lp->sum; i++) {
      lp->scalars[i] = 1;
    }
    lp->scaling_used = TRUE;
  }
#ifdef Paranoia
  else
    for(i = 0; i <= lp->sum; i++) {
      if(lp->scalars[i] == 0)
        report(lp, SEVERE, "scale: Zero-valued scalar found at index %d\n", i);
    }
#endif
  if(scaledelta == NULL)
    allocREAL(lp, &scalechange, lp->sum + 1, FALSE);
  else
    scalechange = scaledelta;

 /* Must initialize due to computation of scaling statistic - KE */
  for(i = 0; i <= lp->sum; i++)
    scalechange[i] = 1;

  row_count = lp->rows;
  allocREAL(lp, &row_max, row_count + 1, TRUE);
  allocREAL(lp, &row_min, row_count + 1, FALSE);

  /* Initialise min and max values of rows */
  for(i = 0; i <= row_count; i++) {
    if(is_scaletype(lp, SCALE_MEAN))
      row_min[i] = 0;             /* Carries the count of elements */
    else
      row_min[i] = lp->infinite;  /* Carries the minimum element */
  }

  /* Calculate row scaling data */
  for(j = 1; j <= lp->columns; j++) {

    absval = lp->orig_obj[j];
    if(absval != 0) {
      absval = scaled_mat(lp, absval, 0, j);
      accumulate_for_scale(lp, &row_min[0], &row_max[0], absval);
      nzOF++;
    }

    i = mat->col_end[j - 1];
    value = &(COL_MAT_VALUE(i));
    rownr = &(COL_MAT_ROWNR(i));
    nz = mat->col_end[j];
    for(; i < nz;
        i++, value += matValueStep, rownr += matRowColStep) {
      absval = scaled_mat(lp, *value, *rownr, j);
      accumulate_for_scale(lp, &row_min[*rownr], &row_max[*rownr], absval);
    }
  }

  /* Calculate scale factors for rows */
  i = 0;
  for(; i <= lp->rows; i++) {
    if(i == 0)
      nz = nzOF;
    else
      nz = mat_rowlength(lp->matA, i);
    absval = minmax_to_scale(lp, row_min[i], row_max[i], nz); /* nz instead of nzOF KJEI 20/05/2010 */
    if(absval == 0)
      absval = 1;
    scalechange[i] = absval;
  }

  FREE(row_max);
  FREE(row_min);

  /* Row-scale the matrix (including the objective function and Lagrangean constraints) */
  rowscaled = scale_updaterows(lp, scalechange, TRUE);

  /* Calculate column scales */
  i = 1;
  for(j = 1; j <= lp->columns; j++) {
    if(is_int(lp,j) && !is_integerscaling(lp)) { /* do not scale integer columns */
      scalechange[lp->rows + j] = 1;
    }
    else {
      col_max = 0;
      if(is_scaletype(lp, SCALE_MEAN))
        col_min = 0;
      else
        col_min = lp->infinite;

      absval = lp->orig_obj[j];
      if(absval != 0) {
        absval = scaled_mat(lp, absval, 0, j);
        accumulate_for_scale(lp, &col_min, &col_max, absval);
      }

      i = mat->col_end[j - 1];
      value = &(COL_MAT_VALUE(i));
      rownr = &(COL_MAT_ROWNR(i));
      nz = mat->col_end[j];
      for(; i < nz;
          i++, value += matValueStep, rownr += matRowColStep) {
        absval = scaled_mat(lp, *value, *rownr, j);
        accumulate_for_scale(lp, &col_min, &col_max, absval);
      }
      nz = mat_collength(lp->matA, j);
      if(fabs(lp->orig_obj[j]) > 0)
        nz++;
      scalechange[lp->rows + j] = minmax_to_scale(lp, col_min, col_max, nz);
    }
  }

  /* ... and then column-scale the already row-scaled matrix */
  colscaled = scale_updatecolumns(lp, &scalechange[lp->rows], TRUE);

  /* Create a geometric mean-type measure of the extent of scaling performed; */
  /* ideally, upon successive calls to scale() the value should converge to 0 */
  if(rowscaled || colscaled) {
    col_max = 0;
    for(j = 1; j <= lp->columns; j++)
      col_max += log(scalechange[lp->rows + j]);
    col_max = exp(col_max/lp->columns);

    i = 0;
    col_min = 0;
    for(; i <= lp->rows; i++)
      col_min += log(scalechange[i]);
    col_min = exp(col_min/row_count);
  }
  else {
    col_max = 1;
    col_min = 1;
  }

  if(scaledelta == NULL)
    FREE(scalechange);

  return(1 - sqrt(col_max*col_min));
}
예제 #7
0
파일: mpfx.cpp 프로젝트: CHolmes3/z3
bool mpfx_manager::is_abs_one(mpfx const & n) const {
    unsigned * w = words(n);
    return is_int(n) && w[m_frac_part_sz] == 1 && ::is_zero(m_int_part_sz - 1, w + m_frac_part_sz + 1);
}
예제 #8
0
파일: upnpc.c 프로젝트: HSAnet/miniupnp
/* sample upnp client program */
int main(int argc, char ** argv)
{
	char command = 0;
	char ** commandargv = 0;
	int commandargc = 0;
	struct UPNPDev * devlist = 0;
	char lanaddr[64];	/* my ip address on the LAN */
	int i;
	const char * rootdescurl = 0;
	const char * multicastif = 0;
	const char * minissdpdpath = 0;
	int retcode = 0;
	int error = 0;
	int ipv6 = 0;
	const char * description = 0;

#ifdef _WIN32
	WSADATA wsaData;
	int nResult = WSAStartup(MAKEWORD(2,2), &wsaData);
	if(nResult != NO_ERROR)
	{
		fprintf(stderr, "WSAStartup() failed.\n");
		return -1;
	}
#endif
    printf("upnpc : miniupnpc library test client, version %s.\n", MINIUPNPC_VERSION_STRING);
	printf(" (c) 2005-2014 Thomas Bernard.\n");
    printf("Go to http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/\n"
	       "for more information.\n");
	/* command line processing */
	for(i=1; i<argc; i++)
	{
		if(0 == strcmp(argv[i], "--help") || 0 == strcmp(argv[i], "-h"))
		{
			command = 0;
			break;
		}
		if(argv[i][0] == '-')
		{
			if(argv[i][1] == 'u')
				rootdescurl = argv[++i];
			else if(argv[i][1] == 'm')
				multicastif = argv[++i];
			else if(argv[i][1] == 'p')
				minissdpdpath = argv[++i];
			else if(argv[i][1] == '6')
				ipv6 = 1;
			else if(argv[i][1] == 'e')
				description = argv[++i];
			else
			{
				command = argv[i][1];
				i++;
				commandargv = argv + i;
				commandargc = argc - i;
				break;
			}
		}
		else
		{
			fprintf(stderr, "option '%s' invalid\n", argv[i]);
		}
	}

	if(!command
	   || (command == 'a' && commandargc<4)
	   || (command == 'd' && argc<2)
	   || (command == 'r' && argc<2)
	   || (command == 'A' && commandargc<6)
	   || (command == 'U' && commandargc<2)
	   || (command == 'D' && commandargc<1))
	{
		fprintf(stderr, "Usage :\t%s [options] -a ip port external_port protocol [duration]\n\t\tAdd port redirection\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -d external_port protocol <remote host>\n\t\tDelete port redirection\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -s\n\t\tGet Connection status\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -l\n\t\tList redirections\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -L\n\t\tList redirections (using GetListOfPortMappings (for IGD:2 only)\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -n ip port external_port protocol [duration]\n\t\tAdd (any) port redirection allowing IGD to use alternative external_port (for IGD:2 only)\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -N external_port_start external_port_end protocol [manage]\n\t\tDelete range of port redirections (for IGD:2 only)\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -r port1 [external_port1] protocol1 [port2 [external_port2] protocol2] [...]\n\t\tAdd all redirections to the current host\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -A remote_ip remote_port internal_ip internal_port protocol lease_time\n\t\tAdd Pinhole (for IGD:2 only)\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -U uniqueID new_lease_time\n\t\tUpdate Pinhole (for IGD:2 only)\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -C uniqueID\n\t\tCheck if Pinhole is Working (for IGD:2 only)\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -K uniqueID\n\t\tGet Number of packets going through the rule (for IGD:2 only)\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -D uniqueID\n\t\tDelete Pinhole (for IGD:2 only)\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -S\n\t\tGet Firewall status (for IGD:2 only)\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -G remote_ip remote_port internal_ip internal_port protocol\n\t\tGet Outbound Pinhole Timeout (for IGD:2 only)\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -P\n\t\tGet Presentation url\n", argv[0]);
		fprintf(stderr, "\nprotocol is UDP or TCP\n");
		fprintf(stderr, "Options:\n");
		fprintf(stderr, "  -e description : set description for port mapping.\n");
		fprintf(stderr, "  -6 : use ip v6 instead of ip v4.\n");
		fprintf(stderr, "  -u url : bypass discovery process by providing the XML root description url.\n");
		fprintf(stderr, "  -m address/interface : provide ip address (ip v4) or interface name (ip v4 or v6) to use for sending SSDP multicast packets.\n");
		fprintf(stderr, "  -p path : use this path for MiniSSDPd socket.\n");
		return 1;
	}

	if( rootdescurl
	  || (devlist = upnpDiscover(2000, multicastif, minissdpdpath,
	                             0/*sameport*/, ipv6, &error)))
	{
		struct UPNPDev * device;
		struct UPNPUrls urls;
		struct IGDdatas data;
		if(devlist)
		{
			printf("List of UPNP devices found on the network :\n");
			for(device = devlist; device; device = device->pNext)
			{
				printf(" desc: %s\n st: %s\n\n",
					   device->descURL, device->st);
			}
		}
		else if(!rootdescurl)
		{
			printf("upnpDiscover() error code=%d\n", error);
		}
		i = 1;
		if( (rootdescurl && UPNP_GetIGDFromUrl(rootdescurl, &urls, &data, lanaddr, sizeof(lanaddr)))
		  || (i = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr))))
		{
			switch(i) {
			case 1:
				printf("Found valid IGD : %s\n", urls.controlURL);
				break;
			case 2:
				printf("Found a (not connected?) IGD : %s\n", urls.controlURL);
				printf("Trying to continue anyway\n");
				break;
			case 3:
				printf("UPnP device found. Is it an IGD ? : %s\n", urls.controlURL);
				printf("Trying to continue anyway\n");
				break;
			default:
				printf("Found device (igd ?) : %s\n", urls.controlURL);
				printf("Trying to continue anyway\n");
			}
			printf("Local LAN ip address : %s\n", lanaddr);
			#if 0
			printf("getting \"%s\"\n", urls.ipcondescURL);
			descXML = miniwget(urls.ipcondescURL, &descXMLsize);
			if(descXML)
			{
				/*fwrite(descXML, 1, descXMLsize, stdout);*/
				free(descXML); descXML = NULL;
			}
			#endif

			switch(command)
			{
			case 'l':
				DisplayInfos(&urls, &data);
				ListRedirections(&urls, &data);
				break;
			case 'L':
				NewListRedirections(&urls, &data);
				break;
			case 'a':
				SetRedirectAndTest(&urls, &data,
						   commandargv[0], commandargv[1],
						   commandargv[2], commandargv[3],
						   (commandargc > 4)?commandargv[4]:"0",
						   description, 0);
				break;
			case 'd':
				RemoveRedirect(&urls, &data, commandargv[0], commandargv[1],
				               commandargc > 2 ? commandargv[2] : NULL);
				break;
			case 'n':	/* aNy */
				SetRedirectAndTest(&urls, &data,
						   commandargv[0], commandargv[1],
						   commandargv[2], commandargv[3],
						   (commandargc > 4)?commandargv[4]:"0",
						   description, 1);
				break;
			case 'N':
				if (commandargc < 3)
					fprintf(stderr, "too few arguments\n");

				RemoveRedirectRange(&urls, &data, commandargv[0], commandargv[1], commandargv[2],
						    commandargc > 3 ? commandargv[3] : NULL);
				break;
			case 's':
				GetConnectionStatus(&urls, &data);
				break;
			case 'r':
				i = 0;
				while(i<commandargc)
				{
					if(!is_int(commandargv[i])) {
						/* 1st parameter not an integer : error */
						fprintf(stderr, "command -r : %s is not an port number\n", commandargv[i]);
						retcode = 1;
						break;
					} else if(is_int(commandargv[i+1])){
						/* 2nd parameter is an integer : <port> <external_port> <protocol> */
						SetRedirectAndTest(&urls, &data,
								   lanaddr, commandargv[i],
								   commandargv[i+1], commandargv[i+2], "0",
								   description, 0);
						i+=3;	/* 3 parameters parsed */
					} else {
						/* 2nd parameter not an integer : <port> <protocol> */
						SetRedirectAndTest(&urls, &data,
								   lanaddr, commandargv[i],
								   commandargv[i], commandargv[i+1], "0",
								   description, 0);
						i+=2;	/* 2 parameters parsed */
					}
				}
				break;
			case 'A':
				SetPinholeAndTest(&urls, &data,
				                  commandargv[0], commandargv[1],
				                  commandargv[2], commandargv[3],
				                  commandargv[4], commandargv[5]);
				break;
			case 'U':
				GetPinholeAndUpdate(&urls, &data,
				                   commandargv[0], commandargv[1]);
				break;
			case 'C':
				for(i=0; i<commandargc; i++)
				{
					CheckPinhole(&urls, &data, commandargv[i]);
				}
				break;
			case 'K':
				for(i=0; i<commandargc; i++)
				{
					GetPinholePackets(&urls, &data, commandargv[i]);
				}
				break;
			case 'D':
				for(i=0; i<commandargc; i++)
				{
					RemovePinhole(&urls, &data, commandargv[i]);
				}
				break;
			case 'S':
				GetFirewallStatus(&urls, &data);
				break;
			case 'G':
				GetPinholeOutboundTimeout(&urls, &data,
							commandargv[0], commandargv[1],
							commandargv[2], commandargv[3],
							commandargv[4]);
				break;
			case 'P':
				printf("Presentation URL found:\n");
				printf("            %s\n", data.presentationurl);
				break;
			default:
				fprintf(stderr, "Unknown switch -%c\n", command);
				retcode = 1;
			}

			FreeUPNPUrls(&urls);
		}
		else
		{
			fprintf(stderr, "No valid UPNP Internet Gateway Device found.\n");
			retcode = 1;
		}
		freeUPNPDevlist(devlist); devlist = 0;
	}
	else
	{
		fprintf(stderr, "No IGD UPnP Device found on the network !\n");
		retcode = 1;
	}
#ifdef _WIN32
	nResult = WSACleanup();
	if(nResult != NO_ERROR) {
		fprintf(stderr, "WSACleanup() failed.\n");
	}
#endif /* _WIN32 */
	return retcode;
}
예제 #9
0
int main(int argc, char *argv[])
{
  TermKey   *tk;
  TermKeyKey key;

  plan_tests(57);

  tk = termkey_new_abstract("vt100", TERMKEY_FLAG_UTF8);

  termkey_push_bytes(tk, "a", 1);

  is_int(termkey_getkey(tk, &key), TERMKEY_RES_KEY, "getkey yields RES_KEY low ASCII");
  is_int(key.type,           TERMKEY_TYPE_UNICODE, "key.type low ASCII");
  is_int(key.code.codepoint, 'a',                  "key.code.codepoint low ASCII");

  /* 2-byte UTF-8 range is U+0080 to U+07FF (0xDF 0xBF) */
  /* However, we'd best avoid the C1 range, so we'll start at U+00A0 (0xC2 0xA0) */

  termkey_push_bytes(tk, "\xC2\xA0", 2);

  is_int(termkey_getkey(tk, &key), TERMKEY_RES_KEY, "getkey yields RES_KEY UTF-8 2 low");
  is_int(key.type,           TERMKEY_TYPE_UNICODE, "key.type UTF-8 2 low");
  is_int(key.code.codepoint, 0x00A0,               "key.code.codepoint UTF-8 2 low");

  termkey_push_bytes(tk, "\xDF\xBF", 2);

  is_int(termkey_getkey(tk, &key), TERMKEY_RES_KEY, "getkey yields RES_KEY UTF-8 2 high");
  is_int(key.type,           TERMKEY_TYPE_UNICODE, "key.type UTF-8 2 high");
  is_int(key.code.codepoint, 0x07FF,               "key.code.codepoint UTF-8 2 high");

  /* 3-byte UTF-8 range is U+0800 (0xE0 0xA0 0x80) to U+FFFD (0xEF 0xBF 0xBD) */

  termkey_push_bytes(tk, "\xE0\xA0\x80", 3);

  is_int(termkey_getkey(tk, &key), TERMKEY_RES_KEY, "getkey yields RES_KEY UTF-8 3 low");
  is_int(key.type,           TERMKEY_TYPE_UNICODE, "key.type UTF-8 3 low");
  is_int(key.code.codepoint, 0x0800,               "key.code.codepoint UTF-8 3 low");

  termkey_push_bytes(tk, "\xEF\xBF\xBD", 3);

  is_int(termkey_getkey(tk, &key), TERMKEY_RES_KEY, "getkey yields RES_KEY UTF-8 3 high");
  is_int(key.type,           TERMKEY_TYPE_UNICODE, "key.type UTF-8 3 high");
  is_int(key.code.codepoint, 0xFFFD,               "key.code.codepoint UTF-8 3 high");

  /* 4-byte UTF-8 range is U+10000 (0xF0 0x90 0x80 0x80) to U+10FFFF (0xF4 0x8F 0xBF 0xBF) */

  termkey_push_bytes(tk, "\xF0\x90\x80\x80", 4);

  is_int(termkey_getkey(tk, &key), TERMKEY_RES_KEY, "getkey yields RES_KEY UTF-8 4 low");
  is_int(key.type,           TERMKEY_TYPE_UNICODE, "key.type UTF-8 4 low");
  is_int(key.code.codepoint, 0x10000,              "key.code.codepoint UTF-8 4 low");

  termkey_push_bytes(tk, "\xF4\x8F\xBF\xBF", 4);

  is_int(termkey_getkey(tk, &key), TERMKEY_RES_KEY, "getkey yields RES_KEY UTF-8 4 high");
  is_int(key.type,           TERMKEY_TYPE_UNICODE, "key.type UTF-8 4 high");
  is_int(key.code.codepoint, 0x10FFFF,             "key.code.codepoint UTF-8 4 high");

  /* Invalid continuations */

  termkey_push_bytes(tk, "\xC2!", 2);

  is_int(termkey_getkey(tk, &key), TERMKEY_RES_KEY, "getkey yields RES_KEY UTF-8 2 invalid cont");
  is_int(key.code.codepoint, 0xFFFD, "key.code.codepoint UTF-8 2 invalid cont");
  is_int(termkey_getkey(tk, &key), TERMKEY_RES_KEY, "getkey yields RES_KEY UTF-8 2 invalid after");
  is_int(key.code.codepoint, '!', "key.code.codepoint UTF-8 2 invalid after");

  termkey_push_bytes(tk, "\xE0!", 2);

  is_int(termkey_getkey(tk, &key), TERMKEY_RES_KEY, "getkey yields RES_KEY UTF-8 3 invalid cont");
  is_int(key.code.codepoint, 0xFFFD, "key.code.codepoint UTF-8 3 invalid cont");
  is_int(termkey_getkey(tk, &key), TERMKEY_RES_KEY, "getkey yields RES_KEY UTF-8 3 invalid after");
  is_int(key.code.codepoint, '!', "key.code.codepoint UTF-8 3 invalid after");

  termkey_push_bytes(tk, "\xE0\xA0!", 3);

  is_int(termkey_getkey(tk, &key), TERMKEY_RES_KEY, "getkey yields RES_KEY UTF-8 3 invalid cont 2");
  is_int(key.code.codepoint, 0xFFFD, "key.code.codepoint UTF-8 3 invalid cont 2");
  is_int(termkey_getkey(tk, &key), TERMKEY_RES_KEY, "getkey yields RES_KEY UTF-8 3 invalid after");
  is_int(key.code.codepoint, '!', "key.code.codepoint UTF-8 3 invalid after");

  termkey_push_bytes(tk, "\xF0!", 2);

  is_int(termkey_getkey(tk, &key), TERMKEY_RES_KEY, "getkey yields RES_KEY UTF-8 4 invalid cont");
  is_int(key.code.codepoint, 0xFFFD, "key.code.codepoint UTF-8 4 invalid cont");
  is_int(termkey_getkey(tk, &key), TERMKEY_RES_KEY, "getkey yields RES_KEY UTF-8 4 invalid after");
  is_int(key.code.codepoint, '!', "key.code.codepoint UTF-8 4 invalid after");

  termkey_push_bytes(tk, "\xF0\x90!", 3);

  is_int(termkey_getkey(tk, &key), TERMKEY_RES_KEY, "getkey yields RES_KEY UTF-8 4 invalid cont 2");
  is_int(key.code.codepoint, 0xFFFD, "key.code.codepoint UTF-8 4 invalid cont 2");
  is_int(termkey_getkey(tk, &key), TERMKEY_RES_KEY, "getkey yields RES_KEY UTF-8 4 invalid after");
  is_int(key.code.codepoint, '!', "key.code.codepoint UTF-8 4 invalid after");

  termkey_push_bytes(tk, "\xF0\x90\x80!", 4);

  is_int(termkey_getkey(tk, &key), TERMKEY_RES_KEY, "getkey yields RES_KEY UTF-8 4 invalid cont 3");
  is_int(key.code.codepoint, 0xFFFD, "key.code.codepoint UTF-8 4 invalid cont 3");
  is_int(termkey_getkey(tk, &key), TERMKEY_RES_KEY, "getkey yields RES_KEY UTF-8 4 invalid after");
  is_int(key.code.codepoint, '!', "key.code.codepoint UTF-8 4 invalid after");

  /* Partials */

  termkey_push_bytes(tk, "\xC2", 1);
  is_int(termkey_getkey(tk, &key), TERMKEY_RES_AGAIN, "getkey yields RES_AGAIN UTF-8 2 partial");

  termkey_push_bytes(tk, "\xA0", 1);
  is_int(termkey_getkey(tk, &key), TERMKEY_RES_KEY, "getkey yields RES_KEY UTF-8 2 partial");
  is_int(key.code.codepoint, 0x00A0, "key.code.codepoint UTF-8 2 partial");

  termkey_push_bytes(tk, "\xE0", 1);
  is_int(termkey_getkey(tk, &key), TERMKEY_RES_AGAIN, "getkey yields RES_AGAIN UTF-8 3 partial");

  termkey_push_bytes(tk, "\xA0", 1);
  is_int(termkey_getkey(tk, &key), TERMKEY_RES_AGAIN, "getkey yields RES_AGAIN UTF-8 3 partial");

  termkey_push_bytes(tk, "\x80", 1);
  is_int(termkey_getkey(tk, &key), TERMKEY_RES_KEY, "getkey yields RES_KEY UTF-8 3 partial");
  is_int(key.code.codepoint, 0x0800, "key.code.codepoint UTF-8 3 partial");

  termkey_push_bytes(tk, "\xF0", 1);
  is_int(termkey_getkey(tk, &key), TERMKEY_RES_AGAIN, "getkey yields RES_AGAIN UTF-8 4 partial");

  termkey_push_bytes(tk, "\x90", 1);
  is_int(termkey_getkey(tk, &key), TERMKEY_RES_AGAIN, "getkey yields RES_AGAIN UTF-8 4 partial");

  termkey_push_bytes(tk, "\x80", 1);
  is_int(termkey_getkey(tk, &key), TERMKEY_RES_AGAIN, "getkey yields RES_AGAIN UTF-8 4 partial");

  termkey_push_bytes(tk, "\x80", 1);
  is_int(termkey_getkey(tk, &key), TERMKEY_RES_KEY, "getkey yields RES_KEY UTF-8 4 partial");
  is_int(key.code.codepoint, 0x10000, "key.code.codepoint UTF-8 4 partial");

  termkey_destroy(tk);

  return exit_status();
}
예제 #10
0
파일: options.cpp 프로젝트: cpehle/lean
unsigned options::get_unsigned(name const & n, unsigned default_value) const {
    sexpr const & r = get_sexpr(n);
    return !is_nil(r) && is_int(r) ? static_cast<unsigned>(to_int(r)) : default_value;
}
int main(void) {
    /* NOTE: really large epsilon. This is because we are summing and the
     * the floating point rounding may effect the result when comparing with
     * MATLAB data. */
    const float64 eps = 1;

    plan(3 + 1);

    ndarray3* n = orion_read_mhd("test-data/ITK/HeadMRVolume/HeadMRVolume.mhd");

    array_float* scales = array_new_float( 10 );
    /* taken from MATLAB `sums` variable above */
    array_float* sums = array_new_float( 10 );

    array_add_float( scales, 1.50 );
    array_add_float(sums, 208564.0312 );
    array_add_float( scales, 1.75 );
    array_add_float(sums, 269313.5000 );
    array_add_float( scales, 2.00 );
    array_add_float(sums, 334097.3750 );
    array_add_float( scales, 2.25 );
    array_add_float(sums, 381097.5938 );
    array_add_float( scales, 2.50 );
    array_add_float(sums, 404807.3125 );
    array_add_float( scales, 3.00 );
    array_add_float(sums, 421116.8125 );
    array_add_float( scales, 4.00 );
    array_add_float(sums, 438598.1875 );

    array_orion_eig_feat_result* r = orion_computeEigenvaluesGaussianFilter(n, EIG_FEAT_METHOD_SORT_SATO, false, scales);

    size_t r_len = array_length_orion_eig_feat_result(r);

    {   /* 3 tests */
        /* sanity tests */
        is_int( array_length_float(scales)  ,  array_length_orion_eig_feat_result(r), "there are as many results as there are scales");

        orion_eig_feat_result* first_result = array_get_orion_eig_feat_result(r,0);
        is_double( array_get_float(scales,0), first_result->scale, 0, "the first scale is recorded in the result as expected");

        ndarray3* first_result_first_n = array_get_ndarray3(first_result->eig_feat,0);
        ok( ndarray3_is_same_size(n, first_result_first_n), "the size of the returned ndarray3 is the same");
    }

    {   /* 1 test */
        bool all_sums_expect = true;
        for( size_t r_idx = 0; r_idx < r_len && all_sums_expect; r_idx++ ) {
            orion_eig_feat_result* e =
                array_get_orion_eig_feat_result(r, r_idx);

            /* first eigenvalue */
            ndarray3* n_e = array_get_ndarray3(e->eig_feat,0);

            all_sums_expect &= fabs(
                                   ndarray3_sum_over_all_float64(n_e)
                                   - array_get_float(sums, r_idx)
                               ) < eps;

            /*[>DEBUG<]{
            float64 n_e_sum_got = ndarray3_sum_over_all_float64(n_e);
            float64 n_e_sum_expected = array_get_float(sums, r_idx);
            printf("i = %d; scale = %f; with sum for first eigenvalue: got = %f and expect %f : expected / got: %f\n",
            		r_idx,
            		array_get_orion_eig_feat_result(r, r_idx)->scale,
            		n_e_sum_got,
            		n_e_sum_expected,
            		n_e_sum_expected / n_e_sum_got
            		);
            }*/
        }

        ok( all_sums_expect, "The sum of the first eigenvalue is as is expected");
    }



    for( size_t r_idx = 0; r_idx < r_len; r_idx++ ) {
        orion_eig_feat_result* e = array_get_orion_eig_feat_result(r, r_idx);
        orion_eig_feat_result_free(e);
    }
    array_free_orion_eig_feat_result(r);
    array_free_float(scales);
    array_free_float(sums);
    ndarray3_free(n);

    return EXIT_SUCCESS;
}
예제 #12
0
파일: options.cpp 프로젝트: cpehle/lean
int options::get_int(name const & n, int default_value) const {
    sexpr const & r = get_sexpr(n);
    return !is_nil(r) && is_int(r) ? to_int(r) : default_value;
}
예제 #13
0
파일: main.c 프로젝트: queensun/qtun
int main(int argc, char* argv[])
{
#ifdef HAVE_EXECINFO_H
    signal(SIGSEGV, crash_sig);
    signal(SIGABRT, crash_sig);
    signal(SIGPIPE, SIG_IGN);
#endif

#ifdef WIN32
    HANDLE localfd;
    WSADATA wsa;
    enum_device_t devs[MAX_DEVICE_COUNT];
#else
    int localfd;
#endif
    char cmd[1024];
    int remotefd;
    library_conf_t conf;
    int opt;
    struct in_addr a;

    struct option long_options[] = {
        { "conf", 1, NULL, 'c' },
        { NULL,   0, NULL,  0  }
    };
    char short_options[512] = {0};
    longopt2shortopt(long_options, sizeof(long_options) / sizeof(struct option), short_options);
#ifdef HAVE_SYSLOG_H
    openlog(argv[0], LOG_PERROR | LOG_CONS | LOG_PID, LOG_LOCAL0);
#endif

    qtun = calloc(sizeof(*qtun), 1);

#ifdef WIN32
    remotefd = -1;
    localfd = INVALID_HANDLE_VALUE;
#else
    localfd = remotefd = -1;
#endif
    {
        char path[MAX_PATH] = {0};
#ifdef WIN32
        strcpy(path, argv[0]);
#elif defined(__APPLE__)
        char tmp_path[sizeof(path)] = {0};
        uint32_t len = sizeof(path);
        if (_NSGetExecutablePath(tmp_path, &len) == -1) {
            perror("_NSGetExecutablePath");
            return 1;
        }
        if (readlink(tmp_path, path, sizeof(path)) == -1) {
            if (errno == EINVAL) strcpy(path, tmp_path);
            else {
                perror("readlink");
                return 1;
            }
        }
#else
        if (readlink("/proc/self/exe", path, sizeof(path)) == -1)
        {
            perror("readlink");
            return 1;
        }
#endif
        init_path(path);
    }
    conf_init(&conf);

    while ((opt = getopt_long(argc, argv, short_options, long_options, NULL)) != -1)
    {
        switch (opt)
        {
        case 'c':
            {
                char* path = realpath(optarg, NULL);
                if (path == NULL) {
                    perror("realpath");
                    return 1;
                }
                strcpy(conf.conf_file, path);
                free(path);
            }
            break;
        default:
            fprintf(stderr, "param error\n");
            return 1;
        }
    }

#ifdef WIN32
    {
        size_t count = enum_devices(devs);
        if (count == 0)
        {
            fprintf(stderr, "have no QTun Virtual Adapter\n");
            return 1;
        }
        else if (count == 1)
        {
            strcpy(conf.dev_symbol, devs[0].dev_path);
            strcpy(conf.dev_name, devs[0].dev_name);
        }
        else
        {
            size_t i;
            char str[20] = { 0 };
            int n = -1;
            printf("Have Adapters:\n");
            for (i = 0; i < count; ++i)
            {
                printf("%lu: %s\n", i + 1, devs[i].dev_name);
            }
            printf("Choose One[1]: ");
            while (n == -1)
            {
                if (str[0] == '\n' && str[1] == 0) n = 1;
                else
                {
                    if (!is_int(str, sizeof(str))) continue;
                    n = atoi(str);
                    if (n < 1 || n > (int)count)
                    {
                        fprintf(stderr, "Invalid Number must >= 1 and <= %lu\n", count);
                        n = -1;
                        continue;
                    }
                }
            }
            strcpy(conf.dev_symbol, devs[n].dev_path);
            strcpy(conf.dev_name, devs[n].dev_name);
        }
    }
#endif
    
    init_lua();
    show_logo();
    script_load_config(qtun->lua, &conf, conf.conf_file);

#ifdef WIN32
    if (strlen(conf.dev_symbol) == 0)
    {
        fprintf(stderr, "Missing param [-e] or [--device]\n");
        return 1;
    }
#endif

#ifdef WIN32
    localfd = tun_open(conf.dev_symbol);
    if (localfd == INVALID_HANDLE_VALUE) return 1;
    fprintf(stdout, "%s opened\n", conf.dev_name);
#else
    memset(qtun->dev_name, 0, IFNAMSIZ);
    localfd = tun_open(qtun->dev_name);
    if (localfd == -1) return 1;
    syslog(LOG_INFO, "%s opened\n", qtun->dev_name);
#endif
    a.s_addr = conf.localip;

#ifdef WIN32
    WSAStartup(MAKEWORD(2, 2), &wsa);
#endif
    if (strlen(conf.server) == 0)
    {
        if (conf.netmask == 0 || conf.netmask > 31)
        {
#ifdef WIN32
            WSACleanup();
#endif

            fprintf(stderr, "netmask must > 0 and <= 31\n");
            return 1;
        }
        library_init(conf);
        if (conf.localip == 0)
        {
            fprintf(stderr, "localip is zero\n");
            return 1;
        }
        if (strlen(conf.signature_file) == 0) {
            fprintf(stderr, "missing signature file\n");
            return 1;
        }
        qtun->is_server = 1;
        remotefd = bind_and_listen(conf.server_port);
        if (remotefd == -1)
        {
#ifdef WIN32
            WSACleanup();
#endif
            return 1;
        }
#ifdef WIN32
        {
            a.s_addr = conf.localip;
            sprintf(cmd, "netsh interface ip set address name=\"%s\" static %s %s", conf.dev_name, inet_ntoa(a), STR_LEN2MASK(conf.netmask));
            SYSTEM_EXIT(cmd);
        }
#elif defined(__APPLE__)
        {
            sprintf(cmd, "ifconfig %s %s/%u up", qtun->dev_name, inet_ntoa(a), conf.netmask);
            SYSTEM_EXIT(cmd);
            a.s_addr = conf.localip & LEN2MASK(conf.netmask);
            sprintf(cmd, "route add -net %s/%u %s", inet_ntoa(a), conf.netmask, inet_ntoa(a));
            SYSTEM_EXIT(cmd);
        }
#else
        {
            sprintf(cmd, "ifconfig %s %s/%u up", qtun->dev_name, inet_ntoa(a), conf.netmask);
            SYSTEM_EXIT(cmd);
            a.s_addr = conf.localip & LEN2MASK(conf.netmask);
            sprintf(cmd, "route add -net %s/%u dev %s", inet_ntoa(a), conf.netmask, qtun->dev_name);
            SYSTEM_EXIT(cmd);
        }
#endif
        server_loop(remotefd, localfd);
    }
    else
    {
#ifdef unix
        unsigned char mask;
#endif
        int inited = 0;
        library_init(conf);
        qtun->is_server = 0;
        while (1)
        {
            remotefd = connect_server(conf.server, conf.server_port);
            if (remotefd == -1)
            {
                SLEEP(5);
                continue;
            }
            a.s_addr = qtun->localip;
            if (qtun->localip == 0)
            {
                fprintf(stderr, "localip is zero\n");
                return 1;
            }
            if (strlen(conf.signature_file) == 0) {
                fprintf(stderr, "missing signature file\n");
                return 1;
            }
            if (!inited)
            {
#ifdef WIN32
                {
                    sprintf(cmd, "netsh interface ip set address name=\"%s\" static %s %s", conf.dev_name, inet_ntoa(a), STR_LEN2MASK(conf.netmask));
                    SYSTEM_EXIT(cmd);
                }
#elif defined(__APPLE__)
                {
                    char ip1[16], ip2[16];
                    a.s_addr = qtun->localip;
                    strcpy(ip1, inet_ntoa(a));
                    a.s_addr = qtun->client.local_ip;
                    strcpy(ip2, inet_ntoa(a));
                    sprintf(cmd, "ifconfig %s inet %s %s up", qtun->dev_name, ip1, ip2);
                    SYSTEM_EXIT(cmd);
                    mask = netmask();
                    a.s_addr = qtun->localip & LEN2MASK(mask);
                    sprintf(cmd, "route add -net %s/%u %s", inet_ntoa(a), mask, ip2);
                    SYSTEM_EXIT(cmd);
                }
#else
                {
                    sprintf(cmd, "ifconfig %s %s up", qtun->dev_name, inet_ntoa(a));
                    SYSTEM_EXIT(cmd);
                    mask = netmask();
                    a.s_addr = qtun->localip & LEN2MASK(mask);
                    sprintf(cmd, "route add -net %s/%u dev %s", inet_ntoa(a), mask, qtun->dev_name);
                    SYSTEM_EXIT(cmd);
                }
#endif
                inited = 1;
            }
            client_loop(remotefd, localfd);
            close(remotefd);
            SYSLOG(LOG_WARNING, "retry");
        }
    }
#ifdef WIN32
    WSACleanup();
#endif

#ifdef HAVE_SYSLOG_H
    closelog();
#endif

    library_free();
    return 0;
}
예제 #14
0
int main(int argc, char **argv)
{
    int fd, i, num_loop, zero = 0;
    char c, lock_f[128];
    struct stat st;
    int *iptr;
    char *cptr;

    if(argc != 4) {
        printf("usage: %s <pathname> <loop number> <char>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    if(is_int(argv[2]))
        num_loop = atoi(argv[2]);

    c = argv[3][0];

    i = stat(argv[1], &st); /* first one will get -1*/

    snprintf(lock_f, sizeof(lock_f), "%s.lock", argv[1]);

    if((fd = open(argv[1], O_RDWR | O_CREAT, F_MODE)) < 0) {
        perror("open() failed\n");
        exit(EXIT_FAILURE);
    }

    if(i == -1) { /* initialze */
        write(fd, &zero, sizeof(int)); /* int counter*/
        for(i = 0; i < SIZE; i++) {
            write(fd, &zero, 1);
        }
    }

    iptr = (int *)mmap(NULL, SIZE+sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

    if(iptr == MAP_FAILED) {
        perror("mmap failed\n");
        exit(EXIT_FAILURE);
    }

    close(fd); /* POSIX recommendation */

    cptr = (char *)(&iptr[1]);

    my_lock_init(lock_f);
    setbuf(stdout, NULL); /* stdout unbuffer */

    for(i = 0; i < num_loop; i++) {
        my_lock_wait();

        if(*iptr >= (SIZE-1)) {
            my_lock_release();
            exit(EXIT_SUCCESS);
        }

        //
        for ( ; ; ) {
            if ((cptr[*iptr - 1]) == c && *iptr != 0) {
                my_lock_release();
                usleep(100);
                my_lock_wait();
            } else {
                break;
            }
        }

        cptr[*iptr] = c;
        printf("%c: %d\n", c, (*iptr)++);
        my_lock_release();
        // usleep(800000);
    }

    return 0;
}
예제 #15
0
파일: hhash.c 프로젝트: idtek/knot
int main(int argc, char *argv[])
{
	plan(11);

	/* Create memory pool context. */
	struct mempool *pool = mp_new(64 * 1024);
	knot_mm_t mm;
	mm.ctx = pool;
	mm.alloc = (knot_mm_alloc_t)mp_alloc;
	mm.free = NULL;

	/* Create hashtable */
	int ret = KNOT_EOK;
	uint16_t len = 0;
	const char *key = "mykey", *cur = NULL, *prev = NULL;
	value_t val = (void*)0xdeadbeef, *rval = NULL;
	hhash_iter_t it;
	hhash_t *tbl = hhash_create_mm(ELEM_COUNT, &mm);
	ok(tbl != NULL, "hhash: create");
	if (tbl == NULL) {
		return KNOT_ERROR; /* No point in testing further on. */
	}

	/* Generate random keys. */
	char *keys[ELEM_COUNT];
	unsigned nfilled = 0;
	for (unsigned i = 0; i < ELEM_COUNT; ++i) {
		keys[i] = test_randstr_mm(&mm);
	}

	/* Insert single element. */
	ret = hhash_insert(tbl, key, KEY_LEN(key), val);
	ok(ret == KNOT_EOK, "hhash: insert single element");

	/* Retrieve nonexistent element. */
	cur = "nokey";
	rval = hhash_find(tbl, cur, KEY_LEN(cur));
	ok(rval == NULL, "hhash: find non-existent element");

	/* Retrieve single element. */
	rval = hhash_find(tbl, key, KEY_LEN(key));
	ok(rval != NULL, "hhash: find existing element");

	/* Fill the table. */
	for (unsigned i = 0; i < ELEM_COUNT; ++i) {
		ret = hhash_insert(tbl, keys[i], KEY_LEN(keys[i]), keys[i]);
		if (ret != KNOT_EOK) {
			nfilled = i;
			break;
		}
	}

	/* Check all keys integrity. */
	unsigned nfound = 0;
	for (unsigned i = 0; i < nfilled; ++i) {
		rval = hhash_find(tbl, keys[i], KEY_LEN(keys[i]));
		if (!rval || memcmp(*rval, keys[i], KEY_LEN(keys[i])) != 0) {
			break; /* Mismatch */
		}
		++nfound;
	}
	is_int(nfilled, nfound, "hhash: found all inserted keys");

	/* Test keys order index. */
	hhash_build_index(tbl);
	hhash_iter_begin(tbl, &it, true);
	while (!hhash_iter_finished(&it)) {
		cur = hhash_iter_key(&it, &len);
		if (!str_check_sort(prev, cur)) {
			break;
		}
		prev = cur;
		int strl = strlen(cur);
		assert(strl + 1 == len);
		hhash_iter_next(&it);
	}
	ok(hhash_iter_finished(&it), "hhash: passed order index checks");

	/* Retrieve all keys. */
	nfound = 0;
	hhash_iter_begin(tbl, &it, false);
	while (!hhash_iter_finished(&it)) {
		cur = hhash_iter_key(&it, &len);
		if (hhash_find(tbl, cur, len) == NULL) {
			break;
		} else {
			++nfound;
		}
		hhash_iter_next(&it);
	}
	ok(hhash_iter_finished(&it), "hhash: found all iterated keys");
	is_int(tbl->weight, nfound, "hhash: all iterated keys found");

	/* Test find less or equal. */
	prev = "mykey0"; /* mykey should precede it */
	hhash_find_leq(tbl, prev, KEY_LEN(prev), &rval);
	ok(rval && *rval == val, "hhash: find less or equal");

	/* Delete key and retrieve it. */
	ret = hhash_del(tbl, key, KEY_LEN(key));
	ok(ret == KNOT_EOK, "hhash: remove key");
	rval = hhash_find(tbl, key, KEY_LEN(key));
	ok(rval == NULL, "hhash: find removed element");

	/* Free all memory. */
	mp_delete(mm.ctx);
	return KNOT_EOK;
}
예제 #16
0
파일: slab.c 프로젝트: dnstap/knot
int main(int argc, char *argv[])
{
	plan(4);

	// 1. Create slab cache
	srand(time(0));
	const unsigned pattern = 0xdeadbeef;
	slab_cache_t cache;
	int ret = slab_cache_init(&cache, sizeof(int));
	is_int(0, ret, "slab: created empty cache");

	// 2. Couple alloc/free
	bool valid_free = true;
	for(int i = 0; i < 100; ++i) {
		int* data = (int*)slab_cache_alloc(&cache);
		*data = pattern;
		slab_free(data);
		if (*data == pattern)
			valid_free = false;
	}

	// 5. Verify freed block
	ok(valid_free, "slab: freed memory is correctly invalidated");

	// 4. Reap memory
	slab_t* slab = cache.slabs_free;
	int free_count = 0;
	while (slab) {
		slab_t* next = slab->next;
		if (slab_isempty(slab)) {
			++free_count;
		}
		slab = next;
	}

	int reaped = slab_cache_reap(&cache);
	is_int(reaped, free_count, "slab: cache reaping works");

	// Stress cache
	int alloc_count = 73521;
	void** ptrs = alloca(alloc_count * sizeof(void*));
	int ptrs_i = 0;
	for(int i = 0; i < alloc_count; ++i) {
		double roll = rand() / (double) RAND_MAX;
		if ((ptrs_i == 0) || (roll < 0.6)) {
			int id = ptrs_i++;
			ptrs[id] = slab_cache_alloc(&cache);
			if (ptrs[id] == 0) {
				ptrs_i--;
			} else {
				int* data = (int*)ptrs[id];
				*data = pattern;
			}
		} else {
			slab_free(ptrs[--ptrs_i]);
		}
	}

	// 5. Delete cache
	slab_cache_destroy(&cache);
	is_int(0, cache.bufsize, "slab: freed cache");

	return 0;
}
예제 #17
0
int CurtisReidScales(lprec *lp, MYBOOL _Advanced, REAL *FRowScale, REAL *FColScale)
{
  int    i, row, col, ent, nz;
  REAL   *RowScalem2, *ColScalem2,
         *RowSum, *ColSum,
         *residual_even, *residual_odd;
  REAL   sk,   qk,     ek,
         skm1, qkm1,   ekm1,
         qkm2, qkqkm1, ekm2, ekekm1,
         absvalue, logvalue,
         StopTolerance;
  int    *RowCount, *ColCount, colMax;
  int    Result;
  MATrec *mat = lp->matA;
  REAL   *value;
  int    *rownr, *colnr;

  if(CurtisReidMeasure(lp, _Advanced, FRowScale, FColScale)<0.1*get_nonzeros(lp))
  return(0);

  /* Allocate temporary memory and find RowSum and ColSum measures */
  nz = get_nonzeros(lp);
  colMax = lp->columns;

  allocREAL(lp, &RowSum, lp->rows+1, TRUE);
  allocINT(lp,  &RowCount, lp->rows+1, TRUE);
  allocREAL(lp, &residual_odd, lp->rows+1, TRUE);

  allocREAL(lp, &ColSum, colMax+1, TRUE);
  allocINT(lp,  &ColCount, colMax+1, TRUE);
  allocREAL(lp, &residual_even, colMax+1, TRUE);

  allocREAL(lp, &RowScalem2, lp->rows+1, FALSE);
  allocREAL(lp, &ColScalem2, colMax+1, FALSE);

  /* Set origin for row scaling */
  for(i = 1; i <= colMax; i++) {
    absvalue=fabs(lp->orig_obj[i]);
    if(absvalue>0) {
      logvalue = log(absvalue);
      ColSum[i] += logvalue;
      RowSum[0] += logvalue;
      ColCount[i]++;
      RowCount[0]++;
    }
  }

  value = &(COL_MAT_VALUE(0));
  rownr = &(COL_MAT_ROWNR(0));
  colnr = &(COL_MAT_COLNR(0));
  for(i = 0; i < nz;
      i++, value += matValueStep, rownr += matRowColStep, colnr += matRowColStep) {
    absvalue=fabs(*value);
    if(absvalue>0) {
      logvalue = log(absvalue);
      ColSum[*colnr] += logvalue;
      RowSum[*rownr] += logvalue;
      ColCount[*colnr]++;
      RowCount[*rownr]++;
    }
  }

  /* Make sure we dont't have division by zero errors */
  for(row = 0; row <= lp->rows; row++)
    if(RowCount[row] == 0)
      RowCount[row] = 1;
  for(col = 1; col <= colMax; col++)
    if(ColCount[col] == 0)
      ColCount[col] = 1;

  /* Initialize to RowScale = RowCount-1 RowSum
                   ColScale = 0.0
                   residual = ColSum - ET RowCount-1 RowSum */

  StopTolerance= MAX(lp->scalelimit-floor(lp->scalelimit), DEF_SCALINGEPS);
  StopTolerance *= (REAL) nz;
  for(row = 0; row <= lp->rows; row++) {
    FRowScale[row] = RowSum[row] / (REAL) RowCount[row];
    RowScalem2[row] = FRowScale[row];
  }

  /* Compute initial residual */
  for(col = 1; col <= colMax; col++) {
    FColScale[col] = 0;
    ColScalem2[col] = 0;
    residual_even[col] = ColSum[col];

    if(lp->orig_obj[col] != 0)
      residual_even[col] -= RowSum[0] / (REAL) RowCount[0];

    i = mat->col_end[col-1];
    rownr = &(COL_MAT_ROWNR(i));
    ent = mat->col_end[col];
    for(; i < ent;
        i++, rownr += matRowColStep) {
      residual_even[col] -= RowSum[*rownr] / (REAL) RowCount[*rownr];
    }
  }

  /* Compute sk */
  sk = 0;
  skm1 = 0;
  for(col = 1; col <= colMax; col++)
    sk += (residual_even[col]*residual_even[col]) / (REAL) ColCount[col];

  Result = 0;
  qk=1; qkm1=0; qkm2=0;
  ek=0; ekm1=0; ekm2=0;

  while(sk>StopTolerance) {
  /* Given the values of residual and sk, construct
     ColScale (when pass is even)
     RowScale (when pass is odd)  */

    qkqkm1 = qk * qkm1;
    ekekm1 = ek * ekm1;
    if((Result % 2) == 0) { /* pass is even; construct RowScale[pass+1] */
      if(Result != 0) {
        for(row = 0; row <= lp->rows; row++)
          RowScalem2[row] = FRowScale[row];
        if(qkqkm1 != 0) {
          for(row = 0; row <= lp->rows; row++)
            FRowScale[row]*=(1 + ekekm1 / qkqkm1);
          for(row = 0; row<=lp->rows; row++)
            FRowScale[row]+=(residual_odd[row] / (qkqkm1 * (REAL) RowCount[row]) -
                             RowScalem2[row] * ekekm1 / qkqkm1);
        }
      }
    }
    else { /* pass is odd; construct ColScale[pass+1] */
      for(col = 1; col <= colMax; col++)
        ColScalem2[col] = FColScale[col];
      if(qkqkm1 != 0) {
        for(col = 1; col <= colMax; col++)
          FColScale[col] *= (1 + ekekm1 / qkqkm1);
        for(col = 1; col <= colMax; col++)
          FColScale[col] += (residual_even[col] / ((REAL) ColCount[col] * qkqkm1) -
                             ColScalem2[col] * ekekm1 / qkqkm1);
      }
    }

    /* update residual and sk (pass + 1) */
    if((Result % 2) == 0) { /* even */
       /* residual */
      for(row = 0; row <= lp->rows; row++)
        residual_odd[row] *= ek;

      for(i = 1; i <= colMax; i++)
        if(lp->orig_obj[i] != 0)
          residual_odd[0] += (residual_even[i] / (REAL) ColCount[i]);

      rownr = &(COL_MAT_ROWNR(0));
      colnr = &(COL_MAT_COLNR(0));
      for(i = 0; i < nz;
          i++, rownr += matRowColStep, colnr += matRowColStep) {
        residual_odd[*rownr] += (residual_even[*colnr] / (REAL) ColCount[*colnr]);
      }
      for(row = 0; row <= lp->rows; row++)
        residual_odd[row] *= (-1 / qk);

      /* sk */
      skm1 = sk;
      sk = 0;
      for(row = 0; row <= lp->rows; row++)
        sk += (residual_odd[row]*residual_odd[row]) / (REAL) RowCount[row];
    }
    else { /* odd */
      /* residual */
      for(col = 1; col <= colMax; col++)
        residual_even[col] *= ek;

      for(i = 1; i <= colMax; i++)
        if(lp->orig_obj[i] != 0)
          residual_even[i] += (residual_odd[0] / (REAL) RowCount[0]);

      rownr = &(COL_MAT_ROWNR(0));
      colnr = &(COL_MAT_COLNR(0));
      for(i = 0; i < nz;
          i++, rownr += matRowColStep, colnr += matRowColStep) {
        residual_even[*colnr] += (residual_odd[*rownr] / (REAL) RowCount[*rownr]);
      }
      for(col = 1; col <= colMax; col++)
        residual_even[col] *= (-1 / qk);

      /* sk */
      skm1 = sk;
      sk = 0;
      for(col = 1; col <= colMax; col++)
        sk += (residual_even[col]*residual_even[col]) / (REAL) ColCount[col];
    }

    /* Compute ek and qk */
    ekm2=ekm1;
    ekm1=ek;
    ek=qk * sk / skm1;

    qkm2=qkm1;
    qkm1=qk;
    qk=1-ek;

    Result++;
  }

  /* Synchronize the RowScale and ColScale vectors */
  ekekm1 = ek * ekm1;
  if(qkm1 != 0) {
  if((Result % 2) == 0) { /* pass is even, compute RowScale */
    for(row = 0; row<=lp->rows; row++)
      FRowScale[row]*=(1.0 + ekekm1 / qkm1);
    for(row = 0; row<=lp->rows; row++)
      FRowScale[row]+=(residual_odd[row] / (qkm1 * (REAL) RowCount[row]) -
                      RowScalem2[row] * ekekm1 / qkm1);
  }
  else { /* pass is odd, compute ColScale */
    for(col=1; col<=colMax; col++)
      FColScale[col]*=(1 + ekekm1 / qkm1);
    for(col=1; col<=colMax; col++)
      FColScale[col]+=(residual_even[col] / ((REAL) ColCount[col] * qkm1) -
                       ColScalem2[col] * ekekm1 / qkm1);
  }
  }

  /* Do validation, if indicated */
  if(FALSE && mat_validate(mat)){
    double check, error;

    /* CHECK: M RowScale + E ColScale = RowSum */
    error = 0;
    for(row = 0; row <= lp->rows; row++) {
      check = (REAL) RowCount[row] * FRowScale[row];
      if(row == 0) {
        for(i = 1; i <= colMax; i++) {
          if(lp->orig_obj[i] != 0)
            check += FColScale[i];
        }
      }
      else {
        i = mat->row_end[row-1];
        ent = mat->row_end[row];
        for(; i < ent; i++) {
          col = ROW_MAT_COLNR(i);
          check += FColScale[col];
        }
      }
      check -= RowSum[row];
      error += check*check;
    }

    /* CHECK: E^T RowScale + N ColScale = ColSum */
    error = 0;
    for(col = 1; col <= colMax; col++) {
      check = (REAL) ColCount[col] * FColScale[col];

      if(lp->orig_obj[col] != 0)
        check += FRowScale[0];

      i = mat->col_end[col-1];
      ent = mat->col_end[col];
      rownr = &(COL_MAT_ROWNR(i));
      for(; i < ent;
          i++, rownr += matRowColStep) {
        check += FRowScale[*rownr];
      }
      check -= ColSum[col];
      error += check*check;
    }
  }

  /* Convert to scaling factors (rounding to nearest power
     of 2 can optionally be done as a separate step later) */
  for(col = 1; col <= colMax; col++) {
    absvalue = exp(-FColScale[col]);
    if(absvalue < MIN_SCALAR) absvalue = MIN_SCALAR;
    if(absvalue > MAX_SCALAR) absvalue = MAX_SCALAR;
    if(!is_int(lp,col) || is_integerscaling(lp))
        FColScale[col] = absvalue;
    else
        FColScale[col] = 1;
  }
  for(row = 0; row <= lp->rows; row++) {
    absvalue = exp(-FRowScale[row]);
    if(absvalue < MIN_SCALAR) absvalue = MIN_SCALAR;
    if(absvalue > MAX_SCALAR) absvalue = MAX_SCALAR;
    FRowScale[row] = absvalue;
  }

 /* free temporary memory */
  FREE(RowSum);
  FREE(ColSum);
  FREE(RowCount);
  FREE(ColCount);
  FREE(residual_even);
  FREE(residual_odd);
  FREE(RowScalem2);
  FREE(ColScalem2);

  return(Result);

}
예제 #18
0
inline bool is_int (tree t) { return is_atomic (t) && is_int (t->label); }
예제 #19
0
int
main(void)
{
    pam_handle_t *pamh;
    struct pam_args *args;
    struct pam_conv conv = { NULL, NULL };
    bool status;
    struct vector *cells;
    char *program;
    struct output *seen;
    const char *argv_bool[2] = { NULL, NULL };
    const char *argv_err[2] = { NULL, NULL };
    const char *argv_empty[] = { NULL };
#ifdef HAVE_KRB5
    const char *argv_all[] = {
        "cells=stanford.edu,ir.stanford.edu", "debug", "expires=1d",
        "ignore_root", "minimum_uid=1000", "program=/bin/true"
    };
    char *krb5conf;
#else
    const char *argv_all[] = {
        "cells=stanford.edu,ir.stanford.edu", "debug", "expires=86400",
        "ignore_root", "minimum_uid=1000", "program=/bin/true"
    };
#endif

    if (pam_start("test", NULL, &conv, &pamh) != PAM_SUCCESS)
        sysbail("cannot create pam_handle_t");
    args = putil_args_new(pamh, 0);
    if (args == NULL)
        bail("cannot create PAM argument struct");

    plan(161);

    /* First, check just the defaults. */
    args->config = config_new();
    status = putil_args_defaults(args, options, optlen);
    ok(status, "Setting the defaults");
    ok(args->config->cells == NULL, "...cells default");
    is_int(false, args->config->debug, "...debug default");
    is_int(10, args->config->expires, "...expires default");
    is_int(true, args->config->ignore_root, "...ignore_root default");
    is_int(0, args->config->minimum_uid, "...minimum_uid default");
    ok(args->config->program == NULL, "...program default");

    /* Now parse an empty set of PAM arguments.  Nothing should change. */
    status = putil_args_parse(args, 0, argv_empty, options, optlen);
    ok(status, "Parse of empty argv");
    ok(args->config->cells == NULL, "...cells still default");
    is_int(false, args->config->debug, "...debug still default");
    is_int(10, args->config->expires, "...expires default");
    is_int(true, args->config->ignore_root, "...ignore_root still default");
    is_int(0, args->config->minimum_uid, "...minimum_uid still default");
    ok(args->config->program == NULL, "...program still default");

    /* Now, check setting everything. */
    status = putil_args_parse(args, 6, argv_all, options, optlen);
    ok(status, "Parse of full argv");
    if (args->config->cells == NULL)
        ok_block(4, false, "...cells is set");
    else {
        ok(args->config->cells != NULL, "...cells is set");
        is_int(2, args->config->cells->count, "...with two cells");
        is_string("stanford.edu", args->config->cells->strings[0],
                  "...first is stanford.edu");
        is_string("ir.stanford.edu", args->config->cells->strings[1],
                  "...second is ir.stanford.edu");
    }
    is_int(true, args->config->debug, "...debug is set");
    is_int(86400, args->config->expires, "...expires is set");
    is_int(true, args->config->ignore_root, "...ignore_root is set");
    is_int(1000, args->config->minimum_uid, "...minimum_uid is set");
    is_string("/bin/true", args->config->program, "...program is set");
    config_free(args->config);
    args->config = NULL;

    /* Test deep copying of defaults. */
    cells = vector_new();
    if (cells == NULL)
        sysbail("cannot allocate memory");
    vector_add(cells, "foo.com");
    vector_add(cells, "bar.com");
    options[0].defaults.list = cells;
    program = strdup("/bin/false");
    if (program == NULL)
        sysbail("cannot allocate memory");
    options[5].defaults.string = program;
    args->config = config_new();
    status = putil_args_defaults(args, options, optlen);
    ok(status, "Setting defaults with new defaults");
    if (args->config->cells == NULL)
        ok_block(4, false, "...cells is set");
    else {
        ok(args->config->cells != NULL, "...cells is set");
        is_int(2, args->config->cells->count, "...with two cells");
        is_string("foo.com", args->config->cells->strings[0],
                  "...first is foo.com");
        is_string("bar.com", args->config->cells->strings[1],
                  "...second is bar.com");
    }
    is_string("/bin/false", args->config->program,
              "...program is /bin/false");
    status = putil_args_parse(args, 6, argv_all, options, optlen);
    ok(status, "Parse of full argv after defaults");
    if (args->config->cells == NULL)
        ok_block(4, false, "...cells is set");
    else {
        ok(args->config->cells != NULL, "...cells is set");
        is_int(2, args->config->cells->count, "...with two cells");
        is_string("stanford.edu", args->config->cells->strings[0],
                  "...first is stanford.edu");
        is_string("ir.stanford.edu", args->config->cells->strings[1],
                  "...second is ir.stanford.edu");
    }
    is_int(true, args->config->debug, "...debug is set");
    is_int(86400, args->config->expires, "...expires is set");
    is_int(true, args->config->ignore_root, "...ignore_root is set");
    is_int(1000, args->config->minimum_uid, "...minimum_uid is set");
    is_string("/bin/true", args->config->program, "...program is set");
    is_string("foo.com", cells->strings[0], "...first cell after parse");
    is_string("bar.com", cells->strings[1], "...second cell after parse");
    is_string("/bin/false", program, "...string after parse");
    config_free(args->config);
    args->config = NULL;
    is_string("foo.com", cells->strings[0], "...first cell after free");
    is_string("bar.com", cells->strings[1], "...second cell after free");
    is_string("/bin/false", program, "...string after free");
    options[0].defaults.list = NULL;
    options[5].defaults.string = NULL;
    vector_free(cells);
    free(program);

    /* Test specifying the default for a vector parameter as a string. */
    options[0].type = TYPE_STRLIST;
    options[0].defaults.string = "foo.com,bar.com";
    args->config = config_new();
    status = putil_args_defaults(args, options, optlen);
    ok(status, "Setting defaults with string default for vector");
    if (args->config->cells == NULL)
        ok_block(4, false, "...cells is set");
    else {
        ok(args->config->cells != NULL, "...cells is set");
        is_int(2, args->config->cells->count, "...with two cells");
        is_string("foo.com", args->config->cells->strings[0],
                  "...first is foo.com");
        is_string("bar.com", args->config->cells->strings[1],
                  "...second is bar.com");
    }
    config_free(args->config);
    args->config = NULL;
    options[0].type = TYPE_LIST;
    options[0].defaults.string = NULL;

    /* Should be no errors so far. */
    ok(pam_output() == NULL, "No errors so far");

    /* Test various ways of spelling booleans. */
    args->config = config_new();
    TEST_BOOL("debug", args->config->debug, true);
    TEST_BOOL("debug=false", args->config->debug, false);
    TEST_BOOL("debug=true", args->config->debug, true);
    TEST_BOOL("debug=no", args->config->debug, false);
    TEST_BOOL("debug=yes", args->config->debug, true);
    TEST_BOOL("debug=off", args->config->debug, false);
    TEST_BOOL("debug=on", args->config->debug, true);
    TEST_BOOL("debug=0", args->config->debug, false);
    TEST_BOOL("debug=1", args->config->debug, true);
    TEST_BOOL("debug=False", args->config->debug, false);
    TEST_BOOL("debug=trUe", args->config->debug, true);
    TEST_BOOL("debug=No", args->config->debug, false);
    TEST_BOOL("debug=Yes", args->config->debug, true);
    TEST_BOOL("debug=OFF", args->config->debug, false);
    TEST_BOOL("debug=ON", args->config->debug, true);
    config_free(args->config);
    args->config = NULL;

    /* Test for various parsing errors. */
    args->config = config_new();
    TEST_ERROR("debug=", LOG_ERR,
               "invalid boolean in setting: debug=");
    TEST_ERROR("debug=truth", LOG_ERR,
               "invalid boolean in setting: debug=truth");
    TEST_ERROR("minimum_uid", LOG_ERR,
               "value missing for option minimum_uid");
    TEST_ERROR("minimum_uid=", LOG_ERR,
               "value missing for option minimum_uid=");
    TEST_ERROR("minimum_uid=foo", LOG_ERR,
               "invalid number in setting: minimum_uid=foo");
    TEST_ERROR("minimum_uid=1000foo", LOG_ERR,
               "invalid number in setting: minimum_uid=1000foo");
    TEST_ERROR("program", LOG_ERR, "value missing for option program");
    TEST_ERROR("cells", LOG_ERR, "value missing for option cells");
    config_free(args->config);
    args->config = NULL;

#ifdef HAVE_KRB5

    /* Test for Kerberos krb5.conf option parsing. */
    krb5conf = test_file_path("data/krb5-pam.conf");
    if (krb5conf == NULL)
        bail("cannot find data/krb5-pam.conf");
    if (setenv("KRB5_CONFIG", krb5conf, 1) < 0)
        sysbail("cannot set KRB5_CONFIG");
    krb5_free_context(args->ctx);
    status = krb5_init_context(&args->ctx);
    if (status != 0)
        bail("cannot parse test krb5.conf file");
    args->config = config_new();
    status = putil_args_defaults(args, options, optlen);
    ok(status, "Setting the defaults");
    status = putil_args_krb5(args, "testing", options, optlen);
    ok(status, "Options from krb5.conf");
    ok(args->config->cells == NULL, "...cells default");
    is_int(true, args->config->debug, "...debug set from krb5.conf");
    is_int(1800, args->config->expires, "...expires set from krb5.conf");
    is_int(true, args->config->ignore_root, "...ignore_root default");
    is_int(1000, args->config->minimum_uid,
           "...minimum_uid set from krb5.conf");
    ok(args->config->program == NULL, "...program default");
    status = putil_args_krb5(args, "other-test", options, optlen);
    ok(status, "Options from krb5.conf (other-test)");
    is_int(-1000, args->config->minimum_uid,
           "...minimum_uid set from krb5.conf other-test");

    /* Test with a realm set, which should expose more settings. */
    krb5_free_context(args->ctx);
    status = krb5_init_context(&args->ctx);
    if (status != 0)
        bail("cannot parse test krb5.conf file");
    args->realm = strdup("FOO.COM");
    if (args->realm == NULL)
        sysbail("cannot allocate memory");
    status = putil_args_krb5(args, "testing", options, optlen);
    ok(status, "Options from krb5.conf with FOO.COM");
    is_int(2, args->config->cells->count, "...cells count from krb5.conf");
    is_string("foo.com", args->config->cells->strings[0],
              "...first cell from krb5.conf");
    is_string("bar.com", args->config->cells->strings[1],
              "...second cell from krb5.conf");
    is_int(true, args->config->debug, "...debug set from krb5.conf");
    is_int(1800, args->config->expires, "...expires set from krb5.conf");
    is_int(true, args->config->ignore_root, "...ignore_root default");
    is_int(1000, args->config->minimum_uid,
           "...minimum_uid set from krb5.conf");
    is_string("/bin/false", args->config->program,
              "...program from krb5.conf");

    /* Test with a different realm. */
    free(args->realm);
    args->realm = strdup("BAR.COM");
    if (args->realm == NULL)
        sysbail("cannot allocate memory");
    status = putil_args_krb5(args, "testing", options, optlen);
    ok(status, "Options from krb5.conf with BAR.COM");
    is_int(2, args->config->cells->count, "...cells count from krb5.conf");
    is_string("bar.com", args->config->cells->strings[0],
              "...first cell from krb5.conf");
    is_string("foo.com", args->config->cells->strings[1],
              "...second cell from krb5.conf");
    is_int(true, args->config->debug, "...debug set from krb5.conf");
    is_int(1800, args->config->expires, "...expires set from krb5.conf");
    is_int(true, args->config->ignore_root, "...ignore_root default");
    is_int(1000, args->config->minimum_uid,
           "...minimum_uid set from krb5.conf");
    is_string("echo /bin/true", args->config->program,
              "...program from krb5.conf");
    config_free(args->config);
    args->config = config_new();
    status = putil_args_krb5(args, "other-test", options, optlen);
    ok(status, "Options from krb5.conf (other-test with realm)");
    ok(args->config->cells == NULL, "...cells is NULL");
    is_string("echo /bin/true", args->config->program,
              "...program from krb5.conf");
    config_free(args->config);
    args->config = NULL;

    /* Test for time parsing errors. */
    args->config = config_new();
    TEST_ERROR("expires=ft87", LOG_ERR,
               "bad time value in setting: expires=ft87");
    config_free(args->config);

    /* Test error reporting from the krb5.conf parser. */
    args->config = config_new();
    status = putil_args_krb5(args, "bad-number", options, optlen);
    ok(status, "Options from krb5.conf (bad-number)");
    seen = pam_output();
    is_string("invalid number in krb5.conf setting for minimum_uid: 1000foo",
              seen->lines[0].line, "...and correct error reported");
    is_int(LOG_ERR, seen->lines[0].priority, "...with correct priority");
    pam_output_free(seen);
    config_free(args->config);
    args->config = NULL;

    /* Test error reporting on times from the krb5.conf parser. */
    args->config = config_new();
    status = putil_args_krb5(args, "bad-time", options, optlen);
    ok(status, "Options from krb5.conf (bad-time)");
    seen = pam_output();
    if (seen == NULL)
        ok_block(2, false, "...no error output");
    else {
        is_string("invalid time in krb5.conf setting for expires: ft87",
                  seen->lines[0].line, "...and correct error reported");
        is_int(LOG_ERR, seen->lines[0].priority, "...with correct priority");
    }
    pam_output_free(seen);
    config_free(args->config);
    args->config = NULL;

    test_file_path_free(krb5conf);

#else /* !HAVE_KRB5 */

    skip_block(37, "Kerberos support not configured");

#endif

    putil_args_free(args);
    pam_end(pamh, 0);
    return 0;
}
예제 #20
0
static void basicCounterFunctionality(void)
{
  ph_counter_scope_t *scope;

  scope = ph_counter_scope_define(NULL, "test1", 24);
  is_true(scope != NULL);
  is_string("test1", ph_counter_scope_get_name(scope));

  uint8_t slot = ph_counter_scope_register_counter(scope, "dummy");
  is(0, slot);

  ph_counter_scope_add(scope, slot, 1);
  is(1, ph_counter_scope_get(scope, slot));

  ph_counter_scope_add(scope, slot, 1);
  is(2, ph_counter_scope_get(scope, slot));

  ph_counter_scope_add(scope, slot, 3);
  is(5, ph_counter_scope_get(scope, slot));

  /* register some more slots */
  const char *names[2] = {"sent", "recd"};
  is_true(ph_counter_scope_register_counter_block(
        scope, 2, slot + 1, names));

  ph_counter_block_t *block = ph_counter_block_open(scope);
  is_true(block != NULL);

  ph_counter_block_add(block, slot + 1, 3);
  is(3, ph_counter_scope_get(scope, slot + 1));

  // C++, clogging up code with casts since the last century
  uint8_t bulk_slots[2] = { (uint8_t)(slot + 1), (uint8_t)(slot + 2) };
  int64_t values[2] = { 1, 5 };
  ph_counter_block_bulk_add(block, 2, bulk_slots, values);
  is(4, ph_counter_scope_get(scope, slot + 1));
  is(5, ph_counter_scope_get(scope, slot + 2));

  uint8_t num_slots;
  int64_t view_slots[10];
  const char *view_names[10];

  num_slots = ph_counter_scope_get_view(scope, 10, view_slots, view_names);
  is(3, num_slots);
  is(5, view_slots[0]);
  is(4, view_slots[1]);
  is(5, view_slots[2]);
  is_string("dummy", view_names[0]);
  is_string("sent", view_names[1]);
  is_string("recd", view_names[2]);

  ph_counter_scope_t *kid_scope;

  // Verify that attempting to define the same scope twice fails
  kid_scope = ph_counter_scope_define(NULL, "test1", 24);
  is_true(kid_scope == NULL);

  // Get ourselves a real child
  kid_scope = ph_counter_scope_define(scope, "child", 8);
  is_true(kid_scope != NULL);
  is_string("test1.child",
      ph_counter_scope_get_name(kid_scope));

  ph_counter_scope_t *resolved;

  resolved = ph_counter_scope_resolve(NULL, "test1");
  is(scope, resolved);

  resolved = ph_counter_scope_resolve(NULL, "test1.child");
  is(kid_scope, resolved);

  ph_counter_scope_register_counter(kid_scope, "w00t");

  // Test iteration
  struct counter_name_val counter_data[16];
  int n_counters = 0;
  ph_counter_scope_iterator_t iter;

  // Collect all counter data; it is returned in an undefined order.
  // For the sake of testing we want to order it, so we collect the data
  // and then sort it
  ph_counter_scope_iterator_init(&iter);
  ph_counter_scope_t *iter_scope;
  while ((iter_scope = ph_counter_scope_iterator_next(&iter)) != NULL) {
    int i;

    if (strncmp(ph_counter_scope_get_name(iter_scope), "test1", 5)) {
      continue;
    }

    num_slots = ph_counter_scope_get_view(iter_scope, 10,
        view_slots, view_names);

    for (i = 0; i < num_slots; i++) {
      counter_data[n_counters].scope_name =
        ph_counter_scope_get_name(iter_scope);
      counter_data[n_counters].name = view_names[i];
      counter_data[n_counters].val = view_slots[i];
      n_counters++;
    }

    ph_counter_scope_delref(iter_scope);
  }

  qsort(counter_data, n_counters, sizeof(struct counter_name_val),
      compare_counter_name_val);

  struct counter_name_val expected_data[] = {
    { "test1", "dummy", 5 },
    { "test1", "recd", 5 },
    { "test1", "sent", 4 },
    { "test1.child", "w00t", 0 },
  };
  int num_expected = sizeof(expected_data) / sizeof(expected_data[0]);

  is_int(num_expected, n_counters);

  for (int i = 0; i < n_counters; i++) {
    is_string(expected_data[i].scope_name,
        counter_data[i].scope_name);
    is_string(expected_data[i].name,
        counter_data[i].name);
    is(expected_data[i].val, counter_data[i].val);

    diag("%s.%s = %" PRIi64, counter_data[i].scope_name,
        counter_data[i].name, counter_data[i].val);
  }
}
예제 #21
0
int
main(void)
{
    int i, count;
    unsigned int j;
    long lcount;
    char lgbuf[128];

    plan(8 +
         (18 + (ARRAY_SIZE(fp_formats) - 1) * ARRAY_SIZE(fp_nums)
          + (ARRAY_SIZE(int_formats) - 1) * ARRAY_SIZE(int_nums)
          + (ARRAY_SIZE(uint_formats) - 1) * ARRAY_SIZE(uint_nums)
          + (ARRAY_SIZE(llong_formats) - 1) * ARRAY_SIZE(llong_nums)
          + (ARRAY_SIZE(ullong_formats) - 1) * ARRAY_SIZE(ullong_nums)) * 2);

    is_int(4, test_snprintf(NULL, 0, "%s", "abcd"), "simple string length");
    is_int(2, test_snprintf(NULL, 0, "%d", 20), "number length");
    is_int(7, test_snprintf(NULL, 0, "Test %.2s", "abcd"), "limited string");
    is_int(1, test_snprintf(NULL, 0, "%c", 'a'), "character length");
    is_int(0, test_snprintf(NULL, 0, ""), "empty format length");

    test_format(true, "abcd", 4, "%s", "abcd");
    test_format(true, "20", 2, "%d", 20);
    test_format(true, "Test ab", 7, "Test %.2s", "abcd");
    test_format(true, "a", 1, "%c", 'a');
    test_format(true, "", 0, "");
    test_format(true, "abcdefghijklmnopqrstuvwxyz01234", 36, "%s", string);
    test_format(true, "abcdefghij", 10, "%.10s", string);
    test_format(true, "  abcdefghij", 12, "%12.10s", string);
    test_format(true, "    abcdefghijklmnopqrstuvwxyz0", 40, "%40s", string);
    test_format(true, "abcdefghij    ", 14, "%-14.10s", string);
    test_format(true, "              abcdefghijklmnopq", 50, "%50s", string);
    test_format(true, "%abcd%", 6, "%%%0s%%", "abcd");
    test_format(true, "", 0, "%.0s", string);
    test_format(true, "abcdefghijklmnopqrstuvwxyz  444", 32, "%.26s  %d",
                string, 4444);
    test_format(true, "abcdefghijklmnopqrstuvwxyz  -2.", 32, "%.26s  %.1f",
                string, -2.5);
    test_format(true, "abcdefghij4444", 14, "%.10s%n%d", string, &count, 4444);
    is_int(10, count, "correct output from %%n");
    test_format(true, "abcdefghijklmnopqrstuvwxyz01234", 36, "%n%s%ln",
                &count, string, &lcount);
    is_int(0, count, "correct output from two %%n");
    is_int(31, lcount, "correct output from long %%ln");
    test_format(true, "(null)", 6, "%s", NULL);

    for (i = 0; fp_formats[i] != NULL; i++)
        for (j = 0; j < ARRAY_SIZE(fp_nums); j++) {
            count = sprintf(lgbuf, fp_formats[i], fp_nums[j]);
            test_format(false, lgbuf, count, fp_formats[i], fp_nums[j]);
        }
    for (i = 0; int_formats[i] != NULL; i++)
        for (j = 0; j < ARRAY_SIZE(int_nums); j++) {
            count = sprintf(lgbuf, int_formats[i], int_nums[j]);
            test_format(false, lgbuf, count, int_formats[i], int_nums[j]);
        }
    for (i = 0; uint_formats[i] != NULL; i++)
        for (j = 0; j < ARRAY_SIZE(uint_nums); j++) {
            count = sprintf(lgbuf, uint_formats[i], uint_nums[j]);
            test_format(false, lgbuf, count, uint_formats[i], uint_nums[j]);
        }
    for (i = 0; llong_formats[i] != NULL; i++)
        for (j = 0; j < ARRAY_SIZE(llong_nums); j++) {
            count = sprintf(lgbuf, llong_formats[i], llong_nums[j]);
            test_format(false, lgbuf, count, llong_formats[i], llong_nums[j]);
        }
    for (i = 0; ullong_formats[i] != NULL; i++)
        for (j = 0; j < ARRAY_SIZE(ullong_nums); j++) {
            count = sprintf(lgbuf, ullong_formats[i], ullong_nums[j]);
            test_format(false, lgbuf, count, ullong_formats[i],
                        ullong_nums[j]);
        }

    return 0;
}
void getInitialPosition(Cell board[BOARD_HEIGHT][BOARD_WIDTH],Player * player,char * token){

	Position position;
	Direction direction;
	token = strtok(NULL, DELIMS);

	/*- get 'y' -*/
	if(is_int(token)){
		position.y= atoi(token);
		token = strtok(NULL,DELIMS);

	}
	else
	{
		printf("INVALID INPUT\n");
	}

	/*- get 'x' -*/
	if(is_int(token)){
		position.x = atoi(token);
		token = strtok(NULL,DELIMS);
	}
	else
	{
		printf("INVALID INPUT\n");
	}

	/*- get 'direction' -*/
	if(strcmp(token,"west") == 0)
	{
		direction = WEST;
	}
	else if(strcmp(token,"south") == 0)
	{
		direction = SOUTH;
	}
	else if(strcmp(token,"east") == 0)
	{
		direction = EAST;
	}
	else if(strcmp(token,"north") == 0)
	{
		direction = NORTH;
	}
	else
	{
		printf("Please enter the direction correctl (north,east,south,west).\n");
	}


	/* initialise player position on the board */
	initialisePlayer(player,&position,direction);

	if(placePlayer(board,position) == TRUE)
	{
		position.x = player->position.x;
		position.y = player->position.y;
		player->direction = direction;
		direction = atoi(token);
	}
	else{
		printf("INVALID INPUT\n");
	}
}
예제 #23
0
파일: main.cpp 프로젝트: CCJY/coliru
 int to_int() const
 {
     if( !is_int() ) throw std::logic_error( "not int" ) ;
     return i ;
 }
예제 #24
0
int
main(void)
{
    pid_t child;
    socket_type server, client;
    int status, flags;
    char buffer[20];
    ssize_t length;
    gss_buffer_desc result;

    alarm(20);

    plan(12);
    if (chdir(getenv("C_TAP_BUILD")) < 0)
        sysbail("can't chdir to C_TAP_BUILD");

    unlink("server-ready");
    child = fork();
    if (child < 0)
        sysbail("cannot fork");
    else if (child == 0) {
        server = create_server();
        send_regular_token(server);
        socket_close(server);
        exit(0);
    } else {
        client = create_client();
        length = read(client, buffer, 12);
        is_int(10, length, "received token has correct length");
        ok(memcmp(buffer, token, 10) == 0, "...and correct data");
        waitpid(child, NULL, 0);
        socket_close(client);
    }

    unlink("server-ready");
    child = fork();
    if (child < 0)
        sysbail("cannot fork");
    else if (child == 0) {
        server = create_server();
        send_hand_token(server);
        socket_close(server);
        exit(0);
    } else {
        client = create_client();
        status = token_recv(client, &flags, &result, 5, 0);
        is_int(TOKEN_OK, status, "received hand-rolled token");
        is_int(3, flags, "...with right flags");
        is_int(5, result.length, "...and right length");
        ok(memcmp(result.value, "hello", 5) == 0, "...and right data");
        free(result.value);
        waitpid(child, NULL, 0);
        socket_close(client);
    }

    /* Send a token with a length of one, but no following data. */
    unlink("server-ready");
    child = fork();
    if (child < 0)
        sysbail("cannot fork");
    else if (child == 0) {
        server = create_server();
        socket_xwrite(server, "\0\0\0\0\1", 5);
        socket_close(server);
        exit(0);
    } else {
        client = create_client();
        status = token_recv(client, &flags, &result, 200, 0);
        is_int(TOKEN_FAIL_EOF, status, "receive invalid token");
        waitpid(child, NULL, 0);
        socket_close(client);
    }

    /* Send a token larger than our token size limit. */
    unlink("server-ready");
    child = fork();
    if (child < 0)
        sysbail("cannot fork");
    else if (child == 0) {
        server = create_server();
        send_hand_token(server);
        socket_close(server);
        exit(0);
    } else {
        client = create_client();
        status = token_recv(client, &flags, &result, 4, 0);
        is_int(TOKEN_FAIL_LARGE, status, "receive too-large token");
        waitpid(child, NULL, 0);
        socket_close(client);
    }

    /* Send EOF when we were expecting a token. */
    unlink("server-ready");
    child = fork();
    if (child < 0)
        sysbail("cannot fork");
    else if (child == 0) {
        server = create_server();
        socket_close(server);
        exit(0);
    } else {
        client = create_client();
        status = token_recv(client, &flags, &result, 4, 0);
        is_int(TOKEN_FAIL_EOF, status, "receive end of file");
        waitpid(child, NULL, 0);
        socket_close(client);
    }

    /*
     * Test a timeout on sending a token.  We have to send a large enough
     * token that the network layer doesn't just buffer it.
     */
    unlink("server-ready");
    child = fork();
    if (child < 0)
        sysbail("cannot fork");
    else if (child == 0) {
        server = create_server();
        sleep(3);
        socket_close(server);
        exit(0);
    } else {
        result.value = bmalloc(8192 * 1024);
        memset(result.value, 'a', 8192 * 1024);
        result.length = 8192 * 1024;
        client = create_client();
        status = token_send(client, 3, &result, 1);
        free(result.value);
        is_int(TOKEN_FAIL_TIMEOUT, status, "can't send due to timeout");
        socket_close(client);
        waitpid(child, NULL, 0);
    }

    /* Test a timeout on receiving a token. */
    unlink("server-ready");
    child = fork();
    if (child < 0)
        sysbail("cannot fork");
    else if (child == 0) {
        server = create_server();
        sleep(3);
        socket_close(server);
        exit(0);
    } else {
        client = create_client();
        status = token_recv(client, &flags, &result, 200, 1);
        is_int(TOKEN_FAIL_TIMEOUT, status, "can't receive due to timeout");
        socket_close(client);
        waitpid(child, NULL, 0);
    }

    /* Special test for error handling when sending tokens. */
    server = open("/dev/full", O_RDWR);
    if (server < 0)
        skip("/dev/full not available");
    else {
        result.value = bmalloc(5);
        memcpy(result.value, "hello", 5);
        result.length = 5;
        status = token_send(server, 3, &result, 0);
        free(result.value);
        is_int(TOKEN_FAIL_SOCKET, status, "can't send due to system error");
        close(server);
    }

    unlink("server-ready");
    return 0;
}
예제 #25
0
static void tst1() {
    unsynch_mpq_manager nm;
    polynomial::manager m(nm);
    polynomial_ref x(m);
    x = m.mk_polynomial(m.mk_var());
    polynomial_ref p(m);
    p = 3*x - 2;

    algebraic_numbers::manager am(nm);
    scoped_anum_vector rs1(am);
    std::cout << "p: " << p << "\n";
    am.isolate_roots(p, rs1);
    display_anums(std::cout, rs1);
    SASSERT(rs1.size() == 1);
    std::cout.flush();

    p = (x^2) - 2;
    std::cout << "p: " << p << "\n";
    rs1.reset();
    am.isolate_roots(p, rs1);
    display_anums(std::cout, rs1);
    SASSERT(rs1.size() == 2);

    scoped_anum sqrt2(am);
    am.set(sqrt2, rs1[1]);

    scoped_mpq  q(nm);
    nm.set(q, 1, 3);
    scoped_anum aq(am);
    am.set(aq, q); // create algebraic number representing 1/3

    am.add(sqrt2, aq, aq);
    std::cout << "sqrt(2) + 1/3: ";
    am.display_decimal(std::cout, aq, 10); std::cout << " "; am.display_interval(std::cout, aq);
    std::cout << " "; am.display_root(std::cout, aq); std::cout << "\n";

    am.set(aq, q);
    am.add(rs1[0], aq, aq);
    std::cout << "-sqrt(2) + 1/3: ";
    am.display_decimal(std::cout, aq, 10); std::cout << " "; am.display_interval(std::cout, aq);
    std::cout << " "; am.display_root(std::cout, aq); std::cout << "\n";

    p = ((x^5) - x - 1)*(x-1)*(x-2);
    std::cout << "p: " << p << "\n";
    rs1.reset();
    am.isolate_roots(p, rs1);
    display_anums(std::cout, rs1);
    SASSERT(rs1.size() == 3);

    scoped_anum gauss(am);
    am.set(gauss, rs1[1]);

    std::cout << "compare(" << sqrt2 << ", " << gauss << "): " << am.compare(sqrt2, gauss) << "\n";

    statistics st;
    am.collect_statistics(st);
    st.display_smt2(std::cout);

    p = ((x^2) - 2)*((x^2) - 3);
    std::cout << "p: " << p << "\n";
    rs1.reset();
    am.isolate_roots(p, rs1);
    display_anums(std::cout, rs1);
    SASSERT(rs1.size() == 4);

    scoped_anum hidden_sqrt2(am);
    am.set(hidden_sqrt2, rs1[2]);

    std::cout << "compare(" << sqrt2 << ", " << hidden_sqrt2 << "): " << am.compare(sqrt2, hidden_sqrt2) << "\n";
    st.reset();
    am.collect_statistics(st);
    st.display_smt2(std::cout);

    std::cout << "sqrt(2)^4: " << (sqrt2^4) << "\n";

    SASSERT(is_int(power(sqrt2, 4)));
    SASSERT(power(sqrt2, 4) == 4);

    scoped_anum sqrt2_gauss(am);
    am.add(sqrt2, gauss, sqrt2_gauss);
    std::cout << "sqrt2 + gauss: " << sqrt2_gauss << " "; am.display_root(std::cout, sqrt2_gauss); std::cout << "\n";

    std::cout << "sqrt2*sqrt2: " << sqrt2*sqrt2 << "\n";
    std::cout << "sqrt2*sqrt2 == 2: " << (sqrt2*sqrt2 == 2) << std::endl;

    scoped_anum three(am);
    am.set(three, -3);

    std::cout << "(-3)^(1/5): " << root(three, 5) << "\n";
    std::cout << "sqrt(2)^(1/3): " << root(sqrt2, 3) << "\n";
    std::cout << "as-root-object(sqrt(2)^(1/3)): " << root_obj_pp(root(sqrt2, 3)) << "\n";
    std::cout << "(sqrt(2) + 1)^(1/3): " << root(sqrt2 + 1, 3) << "\n";
    std::cout << "as-root-object((sqrt(2) + 1)^(1/3)): " << root_obj_pp(root(sqrt2 + 1, 3)) << "\n";
    std::cout << "(sqrt(2) + gauss)^(1/5): " << root(sqrt2 + gauss, 5) << "\n";
    std::cout << "as-root-object(sqrt(2) + gauss)^(1/5): " << root_obj_pp(root(sqrt2 + gauss, 5)) << "\n";
    std::cout << "(sqrt(2) / sqrt(2)): " << sqrt2 / hidden_sqrt2 << "\n";
    std::cout << "(sqrt(2) / gauss): " << sqrt2 / gauss << "\n";
    std::cout << "(sqrt(2) / gauss) 30 digits: " << decimal_pp(sqrt2 / gauss, 30) << "\n";
    std::cout << "as-root-object(sqrt(2) / gauss): " << root_obj_pp(sqrt2 / gauss) << "\n";
    std::cout << "is_int(sqrt(2)^(1/3)): " << am.is_int(root(sqrt2, 3)) << "\n";

    scoped_anum tmp(am);
    scoped_anum four(am);
    am.set(four, 4);
    am.set(tmp, sqrt2);
    am.inv(tmp);
    std::cout << "1/sqrt(2): " << tmp << "\n";
    am.mul(tmp, four, tmp);
    std::cout << "4*1/sqrt(2): " << tmp << "  " << root_obj_pp(tmp) << "\n";
    am.mul(tmp, sqrt2, tmp);
    std::cout << "sqrt(2)*4*(1/sqrt2): " << tmp << "  " << root_obj_pp(tmp) << "\n";
    std::cout << "is_int(sqrt(2)*4*(1/sqrt2)): " << am.is_int(tmp) << ", after is-int: " << tmp << "\n";

    p = (998*x - 1414)*((x^2) - 15);
    std::cout << "p: " << p << "\n";
    rs1.reset();
    am.isolate_roots(p, rs1);

    std::cout << "is-rational(sqrt2): " << am.is_rational(sqrt2) << "\n";

    scoped_anum qr(am);
    am.set(qr, rs1[1]);

    std::cout << "qr: " << root_obj_pp(qr);
    std::cout << ", is-rational: " << am.is_rational(qr) << ", val: " << root_obj_pp(qr) << "\n";

    return;

    std::cout << "compare(" << sqrt2 << ", " << gauss << "): " << am.compare(sqrt2, gauss) << "\n";

    p = (x^16) - 136*(x^14) + 6476*(x^12) - 141912*(x^10) + 1513334*(x^8) - 7453176*(x^6) + 13950764*(x^4) - 5596840*(x^2) + 46225;
    std::cout << "p: " << p << "\n";
    rs1.reset();
    am.isolate_roots(p, rs1);
    display_anums(std::cout, rs1);
}
예제 #26
0
bool Formatter::is_number(ItRules::type value)
{
	return  is_double(value) || is_int(value) ;
}
예제 #27
0
	bool is_numeric() const { return is_int() || is_decimal(); }
예제 #28
0
/* A more readable lp-format report of the model; antiquated and not updated */
void REPORT_lp(lprec *lp)
{
  int  i, j;

  if(lp->outstream == NULL)
    return;

  if(lp->matA->is_roworder) {
    report(lp, IMPORTANT, "REPORT_lp: Cannot print lp while in row entry mode.\n");
    return;
  }

  fprintf(lp->outstream, "Model name: %s\n", get_lp_name(lp));
  fprintf(lp->outstream, "          ");

  for(j = 1; j <= lp->columns; j++)
    fprintf(lp->outstream, "%8s ", get_col_name(lp,j));

  fprintf(lp->outstream, "\n%simize  ", (is_maxim(lp) ? "Max" : "Min"));
  for(j = 1; j <= lp->columns; j++)
      fprintf(lp->outstream, "%8g ", get_mat(lp, 0, j));
  fprintf(lp->outstream, "\n");

  for(i = 1; i <= lp->rows; i++) {
    fprintf(lp->outstream, "%-9s ", get_row_name(lp, i));
    for(j = 1; j <= lp->columns; j++)
      fprintf(lp->outstream, "%8g ", get_mat(lp, i, j));
    if(is_constr_type(lp, i, GE))
      fprintf(lp->outstream, ">= ");
    else if(is_constr_type(lp, i, LE))
      fprintf(lp->outstream, "<= ");
    else
      fprintf(lp->outstream, " = ");
    fprintf(lp->outstream, "%8g", get_rh(lp, i));

    if(is_constr_type(lp, i, GE)) {
      if(get_rh_upper(lp, i) < lp->infinite)
        fprintf(lp->outstream, "  %s = %8g", "upbo", get_rh_upper(lp, i));
    }
    else if(is_constr_type(lp, i, LE)) {
      if(get_rh_lower(lp, i) > -lp->infinite)
        fprintf(lp->outstream, "  %s = %8g", "lowbo", get_rh_lower(lp, i));
    }
    fprintf(lp->outstream, "\n");
  }

  fprintf(lp->outstream, "Type      ");
  for(i = 1; i <= lp->columns; i++) {
    if(is_int(lp,i))
      fprintf(lp->outstream, "     Int ");
    else
      fprintf(lp->outstream, "    Real ");
  }

  fprintf(lp->outstream, "\nupbo      ");
  for(i = 1; i <= lp->columns; i++)
    if(get_upbo(lp, i) >= lp->infinite)
      fprintf(lp->outstream, "     Inf ");
    else
      fprintf(lp->outstream, "%8g ", get_upbo(lp, i));
  fprintf(lp->outstream, "\nlowbo     ");
  for(i = 1; i <= lp->columns; i++)
    if(get_lowbo(lp, i) <= -lp->infinite)
      fprintf(lp->outstream, "    -Inf ");
    else
      fprintf(lp->outstream, "%8g ", get_lowbo(lp, i));
  fprintf(lp->outstream, "\n");

  fflush(lp->outstream);
}