Ejemplo n.º 1
0
int main()
{
    // print sin(abs(-0.5))
    std::cout << compose(Abs<double>(),Sine<double>())(-0.5)
              << "\n\n";

    // print abs() of some values
    print_values(Abs<double>());
    std::cout << '\n';

    // print sin() of some values
    print_values(Sine<double>());
    std::cout << '\n';

    // print sin(abs()) of some values
    print_values(compose(Abs<double>(),Sine<double>()));
    std::cout << '\n';

    // print abs(sin()) of some values
    print_values(compose(Sine<double>(),Abs<double>()));
    std::cout << '\n';

    // print sin(sin()) of some values
    print_values(compose(Sine<double>(),Sine<double>()));
}
Ejemplo n.º 2
0
void MCFVariables::print(IloCplex &cplex)
{
	print_values(cplex, &xs);
	print_values(cplex, &vs);

	for (auto &fs : fss) {
		print_values(cplex, &fs);
	}
}
Ejemplo n.º 3
0
int main(int argc, char **argv){
    double* b_1 =bessel_compute(.1);
    double* b_2 =bessel_compute(1);
    double* b_3 =bessel_compute(10);
    print_values(b_1,3,5,8,12,.1);
    print_values(b_2,3,5,8,12,1);    
    print_values(b_3,3,5,8,12,10);
    free(b_1);
    free(b_2);
    free(b_3);
    return 0;

}
Ejemplo n.º 4
0
/* Print out state, summarising long runs of the same value */
static void dump_mem_simple(const DBNZ_CELL_TYPE *state, size_t plen) {
  DBNZ_CELL_TYPE value = 0;
  size_t count = 0;
  size_t i;
  for (i = 0; i != plen; ++i) {
    if (state[i] == value) {
      ++count;
      continue;
    }
    print_values(count, value);
    count = 1;
    value = state[i];
  }
  print_values(count, value);
}
Ejemplo n.º 5
0
int main(void)
{
  int res, creating = 0;
  struct memory_content *mem;

  res = shmget(KEY, sizeof(struct memory_content), 0);

  if ((res < 0) && (errno == ENOENT)) {
    printf("Memory area does not exist. Creating...\n");
    res = shmget(KEY, sizeof(struct memory_content), IPC_CREAT | IPC_EXCL | 0644);
    if (res < 0) {
      perror("shmget");
      exit(1);
    }
    creating = 1;
  }

  mem = shmat(res, NULL, 0);
  if (!mem) {
    perror("shmat");
    exit(1);
  }

  if (creating) {
    printf("Setting values...\n");
    set_values(mem);
  }

  print_values(mem);
  mem->last_access = getpid();
  shmdt(mem);
  return 0;
}
int 
wpEditPost(char *username, char *password, wppost_t *post) {
	int retval = 0;
	xmlrpc_env env;
	xmlrpc_client *clientP;
	xmlrpc_server_info * serverInfoP;
	xmlrpc_value *paramArrayP = NULL;
	char *methodName = "metaWeblog.editPost";
	xmlrpc_value *resultP;

	wp_env_init(&env, &clientP);
	retval = wpCreatePostStruct(&env, username, password, post, &paramArrayP, 1);
	if (retval != 0) {
		fprintf(stderr, "Error creating post structure, exiting\n");
		goto out;
	}
	serverInfoP = xmlrpc_server_info_new(&env, post->url);
	xmlrpc_client_call2(&env, clientP, serverInfoP, methodName, paramArrayP, &resultP);
	print_values(&env, resultP);
	xmlrpc_DECREF(resultP);	
out:
	xmlrpc_DECREF(paramArrayP);
	wp_env_clean(&env, &clientP);
	return retval;
}
Ejemplo n.º 7
0
 int main ()
 {
 
    double a, b, c, x1, x2, D = -1.0 ;
 
    printf("For equation 0 = ax^2 + bx + c\n") ;
    
    while( D < 0 )
    {
    
    //get coefficients
       get_coefs(&a, &b, &c) ;
    
    //compute determinant
       D = comp_D(a, b, c) ;
    
    //compute roots
       get_roots(a, b, D, &x1, &x2) ;
    
    //print values
       print_values(x1, x2, D) ;
    
    } 
 	
 }
Ejemplo n.º 8
0
//prints all values of the entry with the given key
void get(char key[MAX_KEY], entry *entryHead) {
	entry *inputEntry = get_entry(entryHead, key);
	if (inputEntry == NULL) {
		printf("no such key\n");
	}
	else {
		print_values(inputEntry);
	}
}
Ejemplo n.º 9
0
void print_state(t_state *state)
{
	if (state == NULL)
	{
		return;
	}

	printf("== Environment ==\n");
	print_values(state->environ);
	printf("\n== Scopes ==\n");
	print_scopes(state->variables);
}
Ejemplo n.º 10
0
//prints keys and values of all the entries in the list
void list_entries(entry *entryHead) {
	
	if (entryHead == NULL) {
		printf("no entries\n");
		return;
	}
	
	entry *currentEntry = entryHead;
	
	while(currentEntry != NULL) {
		printf("%s ", currentEntry->key);
		print_values(currentEntry);
		currentEntry = currentEntry->next;
	}
}
Ejemplo n.º 11
0
Archivo: dbase.c Proyecto: OPSF/uClinux
/*
 * Insert a row into specified table
 * _h: structure representing database connection
 * _k: key names
 * _v: values of the keys
 * _n: number of key=value pairs
 */
int db_insert(db_con_t* _h, db_key_t* _k, db_val_t* _v, int _n)
{
	int off;
	off = snprintf(sql_buf, SQL_BUF_LEN, "insert into %s (", CON_TABLE(_h));
	off += print_columns(sql_buf + off, SQL_BUF_LEN - off, _k, _n);
	off += snprintf(sql_buf + off, SQL_BUF_LEN - off, ") values (");
	off += print_values(sql_buf + off, SQL_BUF_LEN - off, _v, _n);
	*(sql_buf + off++) = ')';
	*(sql_buf + off) = '\0';

	if(begin_transaction(_h, sql_buf)) return(-1);
	if (submit_query(_h, sql_buf) < 0) {
		LOG(L_ERR, "db_insert(): Error while inserting\n");
		return -2;
	}
	free_query(_h);
	commit_transaction(_h);
	return(0);
}
Ejemplo n.º 12
0
/*
 * Insert a row into specified table
 * _h: structure representing database connection
 * _k: key names
 * _v: values of the keys
 * _n: number of key=value pairs
 */
int db_insert(db_con_t* _h, db_key_t* _k, db_val_t* _v, int _n)
{
	int off, ret;

	if ((!_h) || (!_k) || (!_v) || (!_n)) {
		LOG(L_ERR, "db_insert: Invalid parameter value\n");
		return -1;
	}

	ret = snprintf(sql_buf, SQL_BUF_LEN, "insert into %s (", CON_TABLE(_h));
	if (ret < 0 || ret >= SQL_BUF_LEN) goto error;
	off = ret;

	ret = print_columns(sql_buf + off, SQL_BUF_LEN - off, _k, _n);
	if (ret < 0) return -1;
	off += ret;

	ret = snprintf(sql_buf + off, SQL_BUF_LEN - off, ") values (");
	if (ret < 0 || ret >= (SQL_BUF_LEN - off)) goto error;
	off += ret;

	ret = print_values(CON_CONNECTION(_h), sql_buf + off, SQL_BUF_LEN - off, _v, _n);
	if (ret < 0) return -1;
	off += ret;

	*(sql_buf + off++) = ')';
	*(sql_buf + off) = '\0';

	if (submit_query(_h, sql_buf) < 0) {
	        LOG(L_ERR, "db_insert: Error while submitting query\n");
		return -2;
	}
	return 0;

 error:
	LOG(L_ERR, "db_insert: Error in snprintf\n");
	return -1;
}
Ejemplo n.º 13
0
/*
 * Just like insert, but replace the row if it exists
 */
int db_replace(db_con_t* handle, db_key_t* keys, db_val_t* vals, int n)
{
	int off, ret;

	if (!handle || !keys || !vals) {
		LOG(L_ERR, "db_replace: Invalid parameter value\n");
		return -1;
	}

	ret = snprintf(sql_buf, SQL_BUF_LEN, "replace %s (", CON_TABLE(handle));
	if (ret < 0 || ret >= SQL_BUF_LEN) goto error;
	off = ret;

	ret = print_columns(sql_buf + off, SQL_BUF_LEN - off, keys, n);
	if (ret < 0) return -1;
	off += ret;

	ret = snprintf(sql_buf + off, SQL_BUF_LEN - off, ") values (");
	if (ret < 0 || ret >= (SQL_BUF_LEN - off)) goto error;
	off += ret;

	ret = print_values(CON_CONNECTION(handle), sql_buf + off, SQL_BUF_LEN - off, vals, n);
	if (ret < 0) return -1;
	off += ret;

	*(sql_buf + off++) = ')';
	*(sql_buf + off) = '\0';

	if (submit_query(handle, sql_buf) < 0) {
	        LOG(L_ERR, "db_replace: Error while submitting query\n");
		return -2;
	}
	return 0;

 error:
	LOG(L_ERR, "db_replace: Error in snprintf\n");
	return -1;
}
Ejemplo n.º 14
0
int main()
{
 std::ifstream _cfgFile;
 std::string _line;
 struc_tabColumn _cols;
 std::vector<struc_tabColumn> vecAllColsInfo;
 std::map<int,std::vector<std::string> > mapColValues;

 _cfgFile.open("./std.cfg");
 if(_cfgFile.is_open())
 {
   while(!_cfgFile.eof()){
       getline(_cfgFile,_line);
       parse_line(_line,_cols);
       vecAllColsInfo.push_back(_cols);
   }
 }

 generateColValues(vecAllColsInfo,mapColValues);
 print_values(vecAllColsInfo,mapColValues);

 return 0;
}
Ejemplo n.º 15
0
int
main(int argc, char *argv[])
{ 
    if (argc != 2) {
        fprintf(stderr, "Expected 2 arguments\n");
        exit(1);
    }
    char *fname = argv[1];

    Solver solver;
    solver_init(&solver);

    printf("reading %s\n", fname);
    solver_read_file(&solver, fname);

    const bool solution_found = solver_naive(&solver);
    if (solution_found) {
        print_values(solver.values, solver.n_variables);
    }
    write_results(&solver, solution_found);

    solver_destroy(&solver);
}
Ejemplo n.º 16
0
/**
* Function fmin contains Quasi-Newton function minimizer with
* inexact line search using Wolfe conditions and
* BFGS correction formula for Hessian update.
*
* The algorithm consists of the following steps (in the order of execution):
* - Initial step with Hessian being an identity matrix (see call1)
* - Line search test for step length satisfying Wolfe conditions (beginning of
*   call2)
* - Line search backtracking and reducing alpha (label40) if the current
*   direction
*   is not a gradient descent one or the function value has increased
* - Hessian update (labels 50-70) once all conditions are satisfied to assure
*   its
*   positive-definiteness
* - Update of a vector of independent variables (label30)
*
* Convergence is detected if the maximal gradient component falls below small
* constant (see label20)
*
* Requires:
*    \param _f Value of function to be minimized.
*    \param _x Vector of independent variables.
*    \param _g Vector containing the partial derivatives of _f with respect to
*    each independent variable. The gradient vector returned by \ref gradcalc.
* Pre:
*    Some class member variables can be initialized by user prior to calling
*    this function.
*    These control variables may change the behavior of fmin, they are:
*        maxfn  (maximal number of function evaluations, after which
*                minimization stops)
*        crit   (convergence criterion constant)
*        imax   (maximal number of function evaluations within one linear search*                before to stop)
*        iprint (flag to allow (=1) or supress (=0) printing intermediate
*                statistics
*        min_improve (stop after 10 iterations with overall function decrease
*                     less than this value)
*    The default values can be found in function set_defaults of class
*    fmm_control
* Modifies:
*    The Hessian matrix (and not its inverse) h
* Returns (via parameter vector x):
*    A vector x after a step of linear search in the direction of gradient
*    descent
\ingroup FMM
*/
void fmm::fmin(const double& _f, const dvector &_x, const dvector& _g)
{
  if (log_values_switch)
  {
    print_values(_f,_x,_g);
  }
  if (pfmintime==0) pfmintime=new adtimer;
  tracing_message(traceflag,"A3");

  /* Remember gradient and function values
     resulted from previous function evaluation */
  dvector& g=(dvector&) _g;
  double& f=(double&) _f;

  /* Create local vector x as a pointer to the argument vector _x */
  independent_variables& x= (independent_variables&) _x;
    #ifdef DIAG
      cout << "On entry to fmin: " << *this << endl;
    #endif
  tracing_message(traceflag,"A4");

#ifdef _MSC_VER
  SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, true);
#else
  /* Check the value of control variable ireturn:
        -1 (exit status)
         0 (initialization of function minimizer)
         1 (call1 - x update and convergence check)
         2 (call2 - line search and Hessian update)
         >=3 (derivative check)
  */
  if (ireturn <= 0 )
  {
    signal(SIGINT, &onintr);
  }
#endif

#ifdef __ZTC__
      if (ireturn <= 0 )
      {
        if (disp_inited == 0)
        {
          disp_open();
          disp_usebios();
        }
      }
#endif
  tracing_message(traceflag,"A5");
      if (ireturn ==1 && dcheck_flag ==0)
      {
        ireturn = 3;
      }
      if (ireturn >= 3)
      {
         /* Entering derivative check */
         derch(f, x, g, n, ireturn);
         return;
      }
      if (ireturn == 1) goto call1;
      if (ireturn == 2) goto call2;

     /* we are here because ireturn=0
        Start initializing function minimizer variables */
      fbest=1.e+100;
  tracing_message(traceflag,"A6");

      /* allocate Hessian
         h - object of class dfsdmat, the memory is allocated
             only for elements of lower triagonal matrix */
      if (!h) h.allocate(n);

      /* initialize w, the dvector of size 4*n:
         w(1,n) contains gradient vector in the point x_new = x_old + alpha*p_k
         w(n+1,2n) contains direction of linear search, i.e. transpose(p_k)
         w(2n+1,4n) are used for Hessian updating terms */
      w.initialize();

      /* alpha - the Newton step size */
      alpha=1.0; /* full Newton step at the beginning */
      ihflag=0;

      /* validity check for dimensions and indexing of
         independent vector and gradient vector
         Note, this function will work correctly only if
         indices start at 1  */
     if (n==0)
     {
       cerr << "Error -- the number of active parameters"
         " fmin must be > 0\n";
       ad_exit(1);
     }
  tracing_message(traceflag,"A7");
     if (x.indexmin() !=1)
     {
       cerr << "Error -- minimum valid index"
         " for independent_variables in fmin must be 1\n"
        << " it is " << x.indexmin() << "\n";
        ad_exit(1);
     }
     if (x.size() <n)
     {
       cerr << "Error -- the size of the independent_variables"
        " which is " << x.size() << " must be >= " << n << "\n"
        << " the number of independent variables in fmin\n";
        ad_exit(1);
     }
  tracing_message(traceflag,"A8");
     if (g.indexmin() !=1)
     {
       cerr << "Error -- minimum valid index"
         " for the gradient vector in fmin must be 1\n"
        << " it is " << g.indexmin() << "\n";
        ad_exit(1);
     }
     if (g.size() <n)
     {
       cerr << "Error -- the size of the gradient vector"
        " which is " << g.size() << " must be >=\n"
        << " the number of independent variables in fmin\n";
        ad_exit(1);
     }
     /* end of validity check */
  tracing_message(traceflag,"A9");

     /* xx is reserved for the updated values of independent variables,
        at the moment put the current values */
     for (i=1; i<=n; i++)
           xx.elem(i)=x.elem(i);
  tracing_message(traceflag,"A10");

      /* itn - iteration counter */
      itn=0;
      /* icc - obsolete calls counter? */
      icc=0;

       /* initialize funval vector,
          it will contain last 10 function values (10-th is the most recent)
          needed to stop minimization in case if f(1)-f(10)<min_improve  */
       for (i=1; i< 11; i++)
          funval.elem(i)=0.;
  tracing_message(traceflag,"A11");
      ihang = 0;  /* flag, =1 when function minimizer is not making progress */
      llog=1;
      np=n+1;
      n1=n-1;
      nn=n*np/2;
      is=n;
      iu=n;
      iv=n+n;
      ib=iv+n;
      iexit=0;    /* exit code */
  tracing_message(traceflag,"A12");

      /* Initialize hessian to the unit matrix */
      h.elem(1,1) = 1;
      for (i=2; i<=n; i++)
      {
        for ( j=1; j<i; j++)
        {
           h.elem(i,j)=0;
        }
        h.elem(i,i)=1;
      }
  tracing_message(traceflag,"A13");

      /* dmin - minimal element of hessian used to
         verify its positive definiteness */
      dmin=h.elem(1,1);
      for ( i=2; i<=n; i++)
      {
         if(h.elem(i,i)<dmin)
            dmin=h.elem(i,i);
      }
      if (dmin <= 0.)    /* hessian is not positive definite? */
         goto label7020; /* exit */
      if(dfn == 0.)
         z = 0.0;
  tracing_message(traceflag,"A14");
      for (i=1; i<=n; i++)
      {
        xsave.elem(i)=x.elem(i);
        x.elem(i)=xx.elem(i);
      }
      ireturn=1; /* upon next entry will go to call1 */
  tracing_message(traceflag,"A15");
      if (h.disk_save())
      {
        cout << "starting hessian save" << endl;
        h.save();
        cout << "finished hessian save" << endl;
      }
  tracing_message(traceflag,"A16");
      return;
      /* End of initialization */
  call1: /* first line search step and x update */
  tracing_message(traceflag,"A17");
      if (h.disk_save())
      {
        cout << "starting hessian restore" << endl;
        h.restore();
        cout << "finished hessian restore" << endl;
      }
  tracing_message(traceflag,"A18");
      for (i=1; i<=n; i++)
      {
        x.elem(i)=xsave.elem(i);
      }
      ireturn=3;
  tracing_message(traceflag,"A19");
      {
      }
      for ( i=1; i<=n; i++)
         gbest.elem(i)=g.elem(i);
  tracing_message(traceflag,"A20");
      funval.elem(10) = f;
      df=dfn;
      if(dfn == 0.0)
         df = f - z;
      if(dfn < 0.0)
         df=fabs(df * f);
      if(df <= 0.0)
         df=1.;
label20: /* check for convergence */
      ic=0; /* counter for number of calls */
      iconv = 1; /* convergence flag: 1 - convergence, 2 - not yet */
      for ( i=1; i<=9; i++)
         funval.elem(i)= funval.elem(i+1);
      funval.elem(10) = f;
      /* check if function value is improving */
      if ( itn>15 && fabs( funval.elem(1)-funval.elem(10))< min_improve )
         ihang = 1;
      gmax = 0;
      /* satisfy convergence criterion? */
      for ( i=1; i<=n; i++)
      {
        if(fabs(g.elem(i)) > crit) iconv = 2;
        if(fabs(g.elem(i)) > fabs(gmax) ) gmax = g.elem(i);
      }
      /* exit if either convergence or no improvement has been achieved
         during last 10 iterations */
      if( iconv == 1 || ihang == 1)
      {
         ireturn=-1;
         goto label92;
      }
      /* otherwise proceed to the Newton step (label21) */
      if(iprint == 0)
         goto label21; /* without printing */
      if(itn == 0)
         goto label7000; /* printing Initial statistics first */
#if defined(USE_DDOUBLE)
#undef double
      if(fmod(double(itn),double(iprint)) != 0)
         goto label21;
#define double dd_real
#else
      if(fmod(double(itn),double(iprint)) != 0)
         goto label21;
#endif
      if (llog) goto label7010;
#if defined (_MSC_VER) && !defined (__WAT32__)
        if (!scroll_flag) clrscr();
#endif
label7003: /* Printing table header */
      if (iprint>0)
      {
        if (ad_printf)
        {
          (*ad_printf)("%d variables; iteration %ld; function evaluation %ld",
           n, itn, ifn);
          if (pointer_to_phase)
          {
            (*ad_printf)("; phase %d", *pointer_to_phase);
          }
          (*ad_printf)(
           "\nFunction value %15.7le; maximum gradient component mag %12.4le\n",
#if defined(USE_DDOUBLE)
  #undef double
              double(f), double(gmax));
  #define double dd_real
#else
              f, gmax);
#endif
        }
      }
/*label7002:*/
      /* Printing Statistics table */
      if(iprint>0)
      {
        fmmdisp(x, g, n, this->scroll_flag,noprintx);
      }
label21 : /* Calculating Newton step */
      /* found good search direction, increment iteration number */
      itn=itn+1;
      for (i=1; i<=n; i++)
         x.elem(i)=xx.elem(i);
      w.elem(1)=-g.elem(1);
      pfmintime->get_elapsed_time_and_reset();

      /* solving system of linear equations H_(k+1) * (x_(k+1)-x(k)) = -g_k
         to get next search direction
         p_k = (x_(k+1)-x(k)) = - inv(H_(k+1)) * g_k */
      for (i=2; i<=n; i++)
      {
        i1=i-1;
        z=-g.elem(i);
        double * pd=&(h.elem(i,1));
        double * pw=&(w.elem(1));
        for (j=1; j<=i1; j++)
        {
          z-=*pd++ * *pw++;
        }
        w.elem(i)=z;
      }
      w.elem(is+n)=w.elem(n)/h.elem(n,n);
      {
        dvector tmp(1,n);
        tmp.initialize();
        for (i=1; i<=n1; i++)
        {
          j=i;
          double * pd=&(h.elem(n-j+1,n-1));
          double qd=w.elem(is+np-j);
          double * pt=&(tmp(1));
          for (int ii=1; ii<=n1; ii++)
          {
            *pt++ +=*pd-- * qd;
          }
          w.elem(is+n-i)=w.elem(n-i)/h.elem(n-i,n-i)-tmp(i);
        }
      }/* w(n+1,2n) now contains search direction
          with current Hessian approximation */
      gs=0.0;
      for (i=1; i<=n; i++)
         gs+=w.elem(is+i)*g.elem(i);/* gs = -inv(H_k)*g_k*df(x_k+alpha_k*p_k) */
      iexit=2;
      if(gs >= 0.0)
         goto label92; /* exit with error */
      gso=gs;
      /* compute new step length 0 < alpha <= 1 */
      alpha=-2.0*df/gs;
      if(alpha > 1.0)
        alpha=1.0;
      df=f;
      tot=0.0;
label30: /* Taking a step, updating x */
      iexit=3;
      if (ialph) { goto label92; } /* exit if step size too small */
      /* exit if number of function evaluations exceeded maxfn */
      if( ifn >= maxfn)
      {
        maxfn_flag=1;
        goto label92;
      }
      else
      {
        maxfn_flag=0;
        iexit=1;
      }
      if(quit_flag) goto label92;
      for (i=1; i<=n; i++)
      {
        /* w(n+1,2n) has the next direction to go */
        z=alpha*w.elem(is+i);
        /* new independent vector values */
        xx.elem(i)+=z;
      }
      for (i=1; i<=n; i++)
      { /* save previous values and update x return value */
        xsave.elem(i)=x.elem(i);
        gsave.elem(i)=g.elem(i);
        x.elem(i)=xx.elem(i);
        fsave = f;
      }
      fsave = f;
      ireturn=2;
      if (h.disk_save())
      {
        cout << "starting hessian save" << endl;
        h.save();
        cout << "finished hessian save" << endl;
      }
      return; // end of call1
  call2: /* Line search and Hessian update */
      if (h.disk_save())
      {
        cout << "starting hessian restore" << endl;
        h.restore();
        cout << "finished hessian restore" << endl;
      }
      /* restore x_k, g(x_k) and g(x_k+alpha*p_k) */
      for (i=1; i<=n; i++)
      {
        x.elem(i)=xsave.elem(i); //x_k
        w.elem(i)=g.elem(i);     //g(x_k+alpha*p_k)
        g.elem(i)=gsave.elem(i); //g(x_k)
      }
      fy = f;
      f = fsave; /* now fy is a new function value, f is the old one */
      ireturn=-1;
      /* remember current best function value, gradient and parameter values */
      if (fy <= fbest)
      {
        fbest=fy;
        for (i=1; i<=n; i++)
        {
          x.elem(i)=xx.elem(i);
          gbest.elem(i)=w.elem(i);
        }
      }
      /* what to do if CTRL-C keys were pressed */
      if (use_control_c==1)
      {
#if defined(__BORLANDC__)
         if ( kbhit() || ctlc_flag|| ifn == dcheck_flag )
#elif defined(_MSC_VER)
         //if ( kbhit() || ifn == dcheck_flag )
         if ( _kbhit() || ctlc_flag || ifn == dcheck_flag )
#else
         if(ctlc_flag || ifn == dcheck_flag )
#endif
         {
            int c=0;
            if (ifn != dcheck_flag)
            {
            #if defined(__DJGPP__)
              c = toupper(getxkey());
            #else
              c = toupper(getch());
            #endif
            }
            else
              c='C';
            if ( c == 'C')
            {
              for (i=1; i<=n; i++)
              {
                x.elem(i)=xx.elem(i);
              }
              ireturn = 3;
              derch(f, x , w, n, ireturn);
              return;
            }
            else if(c=='S')
            {
              //set convergence criteria to something high to stop now
              crit=100000.0;
              return;
            }
            else
            {
              if ( c == 'Q'|| c == 'N')
              {
                quit_flag=c;
                goto label92;
              }
              else
              {
                quit_flag=0;
              }
            }
         }
       }
       if (quit_flag)
       {
         if (quit_flag==1) quit_flag='Q';
         if (quit_flag==2) quit_flag='N';
         goto label92;
       }
      /* Otherwise, continue */
       /* Note, icc seems to be unused */
       icc+=1;
       if( icc >= 5)
          icc=0;
      /* ic - counter of calls without x update */
      ic++;
      if( ic >imax)
      {
         if (iprint>0)
         {
           if (ad_printf)
             (*ad_printf)("  ic > imax  in fminim is answer attained ?\n");
           fmmdisp(x, g, n, this->scroll_flag,noprintx);
         }
         ihflag=1;
         ihang=1;
         goto label92;
      }
      /* new function value was passed to fmin, will increment ifn */
      ifn++;

      gys=0.0;

      /* gys = transpose(p_k) * df(x_k+alpha_k*p_k) */
      for (i=1; i<= n; i++)
         gys+=w.elem(i)*w.elem(is+i);

      /* bad step; unless modified by the user, fringe default = 0 */
      if(fy>f+fringe)
      {
         goto label40; /* backtrack */
      }
      /* Otherwise verify if the search step length satisfies
         strong Wolfe condition */
      if(fabs(gys/gso)<=.9)
         goto label50; /* proceed to Hessian update */
/* or slightly modified constant in Wolfe condition for the number of
 calls > 4 */
      if(fabs(gys/gso)<=.95 && ic > 4)
         goto label50; /* proceed to Hessian update */
      if(gys>0.0) /* not a descent direction */
         goto label40; /* backtrack */
      tot+=alpha;
      z=10.0;
      if(gs<gys)
         z=gys/(gs-gys);
      if(z>10.0)
         z=10.0;
      /* increase step length */
      alpha=alpha*z;
      if (alpha == 0.)
      {
         ialph=1;
         #ifdef __ZTC__
         if (ireturn <= 0)
         {
           disp_close();
         }
         #endif
         return;
      }
      f=fy;
      gs=gys;
      goto label30; /* update x with new alpha */
label40: /* new step is not acceptable, stepping back and
            start backtracking along the Newton direction
            trying a smaller value of alpha */
      for (i=1;i<=n;i++)
         xx.elem(i)-=alpha*w.elem(is+i);
      if (alpha == 0.)
      {
        ialph=1;
        return;
      }
      /* compute new alpha */
      z=3.0*(f-fy)/alpha+gys+gs;
      zz=dafsqrt(z*z-gs*gys);
      z=1.0-(gys+zz-z)/(2.0*zz+gys-gs);
      if (fabs(fy-1.e+95) < 1.e-66)
      {
        alpha*=.001;
      }
      else
      {
        if (z>10.0)
        {
          cout << "large z" << z << endl;
          z=10.0;
        }
        alpha=alpha*z;
      }
      if (alpha == 0.)
      {
         ialph=1;
        if (ialph)
        {
          if (ad_printf) (*ad_printf)("\nFunction minimizer: Step size"
            "  too small -- ialph=1");
        }
         return;
      }
      goto label30; /* update x with new alpha */
label50: /* compute Hessian updating terms */
      alpha+=tot;
      f=fy;
      df-=f;
      dgs=gys-gso;
      xxlink=1;
      if(dgs+alpha*gso>0.0)
         goto label52;
      for (i=1;i<=n;i++)
         w.elem(iu+i)=w.elem(i)-g.elem(i);
      /* now w(n+1,2n) = df(x_k+alpha_k*p_k)-df(x_k) */
      sig=1.0/(alpha*dgs);
      goto label70;
label52: /* compute Hessian updating terms */
      zz=alpha/(dgs-alpha*gso);
      z=dgs*zz-1.0;
      for (i=1;i<=n;i++)
         w.elem(iu+i)=z*g.elem(i)+w.elem(i);
      sig=1.0/(zz*dgs*dgs);
      goto label70;
label60: /* compute Hessian updating terms */
      xxlink=2;
      for (i=1;i<=n;i++)
         w.elem(iu+i)=g.elem(i);
      if(dgs+alpha*gso>0.0)
         goto label62;
      sig=1.0/gso;
      goto  label70;
label62: /* compute Hessian updating terms */
      sig=-zz;
      goto label70;
label65: /* save in g the gradient df(x_k+alpha*p_k) */
      for (i=1;i<=n;i++)
         g.elem(i)=w.elem(i);
      goto  label20; //convergence check
label70:  // Hessian update
      w.elem(iv+1)=w.elem(iu+1);
      pfmintime->get_elapsed_time_and_reset();
      for (i=2;i<=n;i++)
      {
         i1=i-1;
         z=w.elem(iu+i);
         double * pd=&(h.elem(i,1));
         double * pw=&(w.elem(iv+1));
         for (j=1;j<=i1;j++)
         {
           z-=*pd++ * *pw++;
         }
         w.elem(iv+i)=z;
      }
      pfmintime->get_elapsed_time_and_reset();
      for (i=1;i<=n;i++)
      {  /* BFGS updating formula */
         z=h.elem(i,i)+sig*w.elem(iv+i)*w.elem(iv+i);
         if(z <= 0.0)
            z=dmin;
         if(z<dmin)
            dmin=z;
         h.elem(i,i)=z;
         w.elem(ib+i)=w.elem(iv+i)*sig/z;
         sig-=w.elem(ib+i)*w.elem(ib+i)*z;
       }
      for (j=2;j<=n;j++)
      {
         double * pd=&(h.elem(j,1));
         double * qd=&(w.elem(iu+j));
         double * rd=&(w.elem(iv+1));
         for (i=1;i<j;i++)
         {
            *qd-=*pd * *rd++;
            *pd++ +=w.elem(ib+i)* *qd;
         }
      }
      if (xxlink == 1) goto label60;
      if (xxlink == 2) goto label65;
/*label90:*/
      for (i=1;i<=n;i++)
         g.elem(i)=w.elem(i);
label92: /* Exit with error */
      if (iprint>0)
      {
        if (ialph)
        {
          if (ad_printf)
           (*ad_printf)("\nFunction minimizer: Step size too small -- ialph=1");
        }
        if (ihang == 1)
        {
          if (ad_printf)
            (*ad_printf)(
           "Function minimizer not making progress ... is minimum attained?\n");
#if defined(USE_DDOUBLE)
#undef double
           if (ad_printf)
           (*ad_printf)("Minimprove criterion = %12.4le\n",double(min_improve));
#define double dd_real
#else
           if (ad_printf)
             (*ad_printf)("Minimprove criterion = %12.4le\n",min_improve);
#endif
        }
      }
      if(iexit == 2)
      {
        if (iprint>0)
        {
          if (ad_printf)
            (*ad_printf)("*** grad transpose times delta x greater >= 0\n"
           " --- convergence critera may be too strict\n");
          ireturn=-1;
        }
      }
#if defined (_MSC_VER) && !defined (__WAT32__)
        if (scroll_flag == 0) clrscr();
#endif
      if (maxfn_flag == 1)
      {
        if (iprint>0)
        {
          if (ad_printf)
            (*ad_printf)("Maximum number of function evaluations exceeded");
        }
      }
      if (iprint>0)
      {
        if (quit_flag == 'Q')
          if (ad_printf) (*ad_printf)("User initiated interrupt");
      }
      if(iprint == 0) goto label777;
      if (ad_printf) (*ad_printf)("\n - final statistics:\n");
      if (ad_printf)
        (*ad_printf)("%d variables; iteration %ld; function evaluation %ld\n",
                       n, itn, ifn);
#if defined(USE_DDOUBLE)
#undef double
      if (ad_printf)
        (*ad_printf)(
             "Function value %12.4le; maximum gradient component mag %12.4le\n",
             double(f), double(gmax));
      if (ad_printf)
        (*ad_printf)(
          "Exit code = %ld;  converg criter %12.4le\n",iexit,double(crit));
#define double dd_real
#else
      if (ad_printf)
        (*ad_printf)(
          "Function value %12.4le; maximum gradient component mag %12.4le\n",
          f, gmax);
      if (ad_printf)
        (*ad_printf)(
          "Exit code = %ld;  converg criter %12.4le\n",iexit,crit);
#endif
      fmmdisp(x, g, n, this->scroll_flag,noprintx);
label777: /* Printing final Hessian approximation */
         if (ireturn <= 0)
         #ifdef DIAG
           if (ad_printf) (*ad_printf)("Final values of h in fmin:\n");
           cout << h << "\n";
         #endif
         #ifdef __ZTC__
         {
           disp_close();
         }
         #endif
         return;
label7000:/* Printing Initial statistics */
      if (iprint>0)
      {
#if defined (_MSC_VER) && !defined (__WAT32__)
        if (!scroll_flag) clrscr();
#endif
        if (ad_printf) (*ad_printf)("\nInitial statistics: ");
      }
      goto label7003;
label7010:/* Printing Intermediate statistics */
   if (iprint>0)
   {
#if defined (_MSC_VER) && !defined (__WAT32__)
     if (!scroll_flag) clrscr();
#endif
     if (ad_printf) (*ad_printf)("\nIntermediate statistics: ");
   }
   llog=0;
   goto label7003;
label7020:/* Exis because Hessian is not positive definite */
  if (iprint > 0)
  {
    if (ad_printf) (*ad_printf)("*** hessian not positive definite\n");
  }
#ifdef __ZTC__
  if (ireturn <= 0)
  {
    disp_close();
  }
#endif
}
Ejemplo n.º 17
0
int
main (int argc, char *argv[]) 
{
	char *device = NULL;
	int command = -1;
	int o, longindex;
	int retval = 0;

	thresholds_t thresholds;
	values_t values;
	int fd;

	static struct option longopts[] = { 
		{"device", required_argument, 0, 'd'}, 
		{"immediate", no_argument, 0, 'i'}, 
		{"quiet-check", no_argument, 0, 'q'}, 
		{"auto-on", no_argument, 0, '1'}, 
		{"auto-off", no_argument, 0, '0'}, 
		{"nagios", no_argument, 0, 'n'}, 
		{"help", no_argument, 0, 'h'}, 
		{"version", no_argument, 0, 'V'},
		{0, 0, 0, 0}
	};

	/* Parse extra opts if any */
	argv=np_extra_opts (&argc, argv, progname);

	setlocale (LC_ALL, "");
	bindtextdomain (PACKAGE, LOCALEDIR);
	textdomain (PACKAGE);

	while (1) {
		
		o = getopt_long (argc, argv, "+d:iq10nhV", longopts, &longindex);

		if (o == -1 || o == EOF || o == 1)
			break;

		switch (o) {
		case 'd':
			device = optarg;
			break;
		case 'q':
			command = 3;
			break;
		case 'i':
			command = 2;
			break;
		case '1':
			command = 1;
			break;
		case '0':
			command = 0;
			break;
		case 'n':
			command = 4;
			break;
		case 'h':
			print_help ();
			return STATE_OK;
		case 'V':
			print_revision (progname, NP_VERSION);
			return STATE_OK;
		default:
			usage5 ();
		}
	}

	if (optind < argc) {
		device = argv[optind];
	}

	if (!device) {
		print_help ();
		return STATE_OK;
	}

	fd = open (device, O_RDONLY);

	if (fd < 0) {
		printf (_("CRITICAL - Couldn't open device %s: %s\n"), device, strerror (errno));
		return STATE_CRITICAL;
	}

	if (smart_cmd_simple (fd, SMART_CMD_ENABLE, 0, TRUE)) {
		printf (_("CRITICAL - SMART_CMD_ENABLE\n"));
		return STATE_CRITICAL;
	}

	switch (command) {
	case 0:
		retval = smart_cmd_simple (fd, SMART_CMD_AUTO_OFFLINE, 0, TRUE);
		break;
	case 1:
		retval = smart_cmd_simple (fd, SMART_CMD_AUTO_OFFLINE, 0xF8, TRUE);
		break;
	case 2:
		retval = smart_cmd_simple (fd, SMART_CMD_IMMEDIATE_OFFLINE, 0, TRUE);
		break;
	case 3:
		smart_read_values (fd, &values);
		smart_read_thresholds (fd, &thresholds);
		retval = values_not_passed (&values, &thresholds);
		break;
	case 4:
		smart_read_values (fd, &values);
		smart_read_thresholds (fd, &thresholds);
		retval = nagios (&values, &thresholds);
		break;
	default:
		smart_read_values (fd, &values);
		smart_read_thresholds (fd, &thresholds);
		print_values (&values, &thresholds);
		break;
	}
	close (fd);
	return retval;
}
Ejemplo n.º 18
0
/*----------------------------------------------------------*/
int main(int argc, char *argv[])
{
  xc_values_type xc;
  xc_lda_type lda_func;
  xc_gga_type gga_func;
  xc_hyb_gga_type hyb_gga_func;
  const xc_func_info_type *info;
  FLOAT *pv2rho = NULL;

  if(argc != 8){
    printf("Usage:\n%s funct pol rhoa rhob sigmaaa sigmaab sigmabb\n", argv[0]);
    return 1;
  }

  init_values(&xc, argv);

  if(xc.nspin == 1){
    xc.rho[0]   += xc.rho[1];
    xc.sigma[0] += 2.0*xc.sigma[1] + xc.sigma[2];
  }

  info = NULL;
  switch(xc_family_from_id(xc.functional))
    {
    case XC_FAMILY_LDA:
      if(xc.functional == XC_LDA_X)
	xc_lda_x_init(&lda_func, xc.nspin, 3, 0);
      else
	xc_lda_init(&lda_func, xc.functional, xc.nspin);
      info = lda_func.info;
      break;
    case XC_FAMILY_GGA:
      xc_gga_init(&gga_func, xc.functional, xc.nspin);
      info = gga_func.info;
      break;
    case XC_FAMILY_HYB_GGA:
      xc_hyb_gga_init(&hyb_gga_func, xc.functional, xc.nspin);
      info = hyb_gga_func.info;
      break;
    default:
      fprintf(stderr, "Functional '%d' not found\n", xc.functional);
      exit(1);  
    }
  if(info->provides & XC_PROVIDES_FXC){
    pv2rho = xc.v2rho;
  }

  switch(xc_family_from_id(xc.functional))
    {
    case XC_FAMILY_LDA:
      xc_lda(&lda_func, xc.rho, &xc.zk, xc.vrho, pv2rho, NULL);
      break;
    case XC_FAMILY_GGA:
      xc_gga(&gga_func, xc.rho, xc.sigma, &xc.zk, 
	     xc.vrho, xc.vsigma, pv2rho, xc.v2rhosigma, xc.v2sigma);
      xc_gga_end(&gga_func);
      break;
    case XC_FAMILY_HYB_GGA:
      xc_hyb_gga(&hyb_gga_func, xc.rho, xc.sigma, &xc.zk, xc.vrho, xc.vsigma);
      xc_hyb_gga_end(&hyb_gga_func);
      break;
    }

  if(xc.nspin == 1){
    xc.vrho[1] = xc.vrho[0];
    xc.zk *= xc.rho[0] ;
  }else{
    xc.zk *= (xc.rho[0] + xc.rho[1]);
  }

  print_values(&xc);

  return 0;
}
Ejemplo n.º 19
0
void MTZVariables::print(IloCplex &cplex)
{
	print_values(cplex, &xs);
	print_values(cplex, &vs);
	print_values(cplex, &us);
}
Ejemplo n.º 20
0
int main (int argc, char *argv[])
{
	int fd;
	int opt;
	int error;
	int errorcount = 0;
	int rawvalues[RESULT_SIZE];
	char *tty = DEFAULT_TTY;
	bool starttest = false;
	bool aborttest = false;
	bool switchbeep = false;
	struct smsstatus results;

/***************************************************************************
 * UPS QUERIES START
 ***************************************************************************/

	/* Interrupt the battery test. No return. */
	int query1[QUERY_SIZE] ={'\x44', /* D */
				 '\xff',
				 '\xff',
				 '\xff',
				 '\xff',
				 '\xc0',
				 '\x0d'};

	/* Return strange values
	 * 0x3b (;), 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 
         *           0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0xe5, 0x0d;
	 */
	int query2[QUERY_SIZE] ={'\x46', /* F */
				 '\xff',
				 '\xff',
				 '\xff',
				 '\xff',
				 '\xbe',
				 '\x0d'};

	/* Does nothing? */
	int query3[QUERY_SIZE] ={'\x47', /* G */
				 '\x01',
				 '\xff',
				 '\xff',
				 '\xff',
				 '\xbb',
				 '\x0d'};

	/* Return model name and firmware version?
	 * 0x3a (:), 0x53 (S), 0x45 (E), 0x4e (N), 0x4f (O), 0x49 (I), 
	 * 0x44 (D), 0x41 (A), 0x4c (L), 0x20, 0x20, 0x20, 0x20, 0x37 (7), 
	 * 0x2e (.), 0x30 (0), 0x62 (b), 0x0d;
	 */
	int query4[QUERY_SIZE] ={'\x49', /* I */
				 '\xff',
				 '\xff',
				 '\xff',
				 '\xff',
				 '\xbb',
				 '\x0d'};

	/* Switch the buzzer ON/OFF. No return. */
	int query5[QUERY_SIZE] ={'\x4d', /* M */
				 '\xff',
				 '\xff',
				 '\xff',
				 '\xff',
				 '\xb7',
				 '\x0d'};

	/* Return standard values
	 * 0x3d (=)	- Just a mark
	 * 0x08		- 0XAA	 - 
	 * 0x34 (4)	- 0X  AA - lastinputVac
	 * 0x08		- 0XBB   -
	 * 0x34 (4)	- 0X  BB - inputVac
	 * 0x04		- 0XCC   -
	 * 0x38 (8)	- 0X  CC - outputVac
	 * 0x01		- 0XDD   -
	 * 0x22 (")	- 0X  DD - outputpower
	 * 0x02		- 0XEE   -
	 * 0x58 (X)	- 0X  EE - outputHz
	 * 0x03		- 0XFF   -
	 * 0xe8		- 0X  FF - batterylevel
	 * 0x01		- 0XGG   -
	 * 0x7c (|)	- 0X  GG - temperatureC
	 * 0x29 ())	- HH     - State bits (beepon, shutdown, test, upsok, 
	 * 0x01		- ??	 - ??	boost, onacpower, lowbattery, onbattery)
	 * 0x0d		- Just a mark
	 */
	int query6[QUERY_SIZE] ={'\x51', /* Q */
				 '\xff',
				 '\xff',
				 '\xff',
				 '\xff',
				 '\xb3',
				 '\x0d'};

	/* Test the battery for 10 seconds. No return. */
	int query7[QUERY_SIZE] ={'\x54', /* T */
				 '\x00',
				 '\x10',
				 '\x00',
				 '\x00',
				 '\x9c',
				 '\x0d'};

/***************************************************************************
 * UPS QUERIES END
 ***************************************************************************/

	/* Command line parser */
	while ((opt = getopt(argc, argv, "abst:")) != -1) {
			switch (opt) {
				case 'a':
					aborttest = true;
				break;
				case 'b':
					switchbeep = true;
		           	break;
				case 's':
					starttest = true;
				break;
				case 't':
					tty = optarg;
		           	break;
				default: /* '?' */
					fprintf(stderr, "Usage: %s\n\t-s: Start battery test\n\t-a: "
						"Abort battery test\n\t-b: Switch buzzer ON/OFF\n\t-t: Path to TTY (Ex: /dev/ttyUSB0)\n", argv[0]);
					exit(EXIT_FAILURE);
			}
	}

	/* Avoid calling start and abort battery test simultaneosly */
	if (starttest && aborttest){
		printf ("ERROR: Can't start and abort battery test at same time.\n");
		exit(EXIT_FAILURE);
	}

	if ( (fd = open_config_tty(tty)) < 0){
		perror("open_port: Unable to open DEFAULT_TTY - ");
		return -1;
	}

	if (switchbeep)
		send_query (fd, query5);

	if (starttest)
		send_query (fd, query7);

	if (aborttest)
		send_query (fd, query1);

	/* Device Startup
         * This is done on the official software but looks not necessary
	 *

	send_query (fd, query3);
	send_query (fd, query4);
	get_results2(fd, rawvalues);
	send_query (fd, query4);
	get_results2(fd, rawvalues);
	send_query (fd, query2);
	get_results2(fd, rawvalues);
	send_query (fd, query6);
	get_results2(fd, rawvalues);

	*/

	while (errorcount < 2 ){

		send_query (fd, query6);
		if (get_results2(fd, rawvalues) < 0){
			perror("Error reading tty. ");
			return -1;
		}

//		printf("Errorcount: %d\n", errorcount);
		if ((error = check_results(rawvalues)) > 0){
//			printf("Error: %d\n", error);
			errorcount++;
			usleep (250000);
			continue;
		} else
			break;

	}
	if (errorcount > 1){
		perror("get_results: tty was opened but is sending incorrect values - ");
		return error;
	}


	results_to_human(rawvalues, &results);

	close_tty(fd);

	print_values(&results);

	exit(EXIT_SUCCESS);
}
Ejemplo n.º 21
0
void SCFVariables::print(IloCplex &cplex)
{
	print_values(cplex, &xs);
	print_values(cplex, &vs);
	print_values(cplex, &fs);
}
Ejemplo n.º 22
0
/** The get-recrod command */
int cmd_get_record (int argc, const char *argv[]) {
    if (OPTIONS.tenant[0] == 0) {
        fprintf (stderr, "%% No tenantid provided\n");
        return 1;
    }
    if (OPTIONS.host[0] == 0) {
        fprintf (stderr, "%% No hostid provided\n");
        return 1;
    }

    var *apires = api_get ("/%s/host/%s", OPTIONS.tenant, OPTIONS.host);
    
    if (OPTIONS.json) {
        var_dump (apires, stdout);
        var_free (apires);
        return 0;
    }
    
    #define Arr(x) var_get_array_forkey(apires,x)
    #define Vint(x) var_get_int_forkey(apires,x)
    #define Vstr(x) var_get_str_forkey(apires,x)
    #define Vfrac(x) var_get_double_forkey(apires,x)
    #define VDint(x,y) var_get_int_forkey(var_get_dict_forkey(apires,x),y)
    #define VDstr(x,y) var_get_str_forkey(var_get_dict_forkey(apires,x),y)
    #define VDfrac(x,y) var_get_double_forkey(var_get_dict_forkey(apires,x),y)
    #define VAfrac(x,y) var_get_double_atindex(var_get_array_forkey(apires,x),y)
    #define Vdone(x) var_delete_key(apires,x)
    /* -------------------------------------------------------------*/
    print_hdr ("HOST");
    print_value ("UUID", "%s", OPTIONS.host);
    print_value ("Hostname", "%s", Vstr("hostname"));
    print_value ("Address", "%s", VDstr("agent","ip"));
    print_value ("Status", "\033[1m%s\033[0m", Vstr("status"));
    
    print_array ("Problems", Arr("problems"));
    
    Vdone("hostname");
    Vdone("agent");
    Vdone("status");
    Vdone("problems");
    
    char uptimestr[128];
    uint64_t uptime = Vint("uptime"); Vdone("uptime");
    uint64_t u_days = uptime / 86400ULL;
    uint64_t u_hours = (uptime - (86400 * u_days)) / 3600ULL;
    uint64_t u_mins = (uptime - (86400 * u_days) - (3600 * u_hours)) / 60ULL;
    uint64_t u_sec = uptime % 60;
    
    if (u_days) {
        sprintf (uptimestr, "%llu day%s, %llu:%02llu:%02llu", u_days,
                 (u_days==1)?"":"s", u_hours, u_mins, u_sec);
    }
    else if (u_hours) {
        sprintf (uptimestr, "%llu:%02llu:%02llu", u_hours, u_mins, u_sec);
    }
    else {
        sprintf (uptimestr, "%llu minute%s, %llu second%s",
                 u_mins, (u_mins==1)?"":"s", u_sec, (u_sec==1)?"":"s");
    }
    
    print_value ("Uptime","%s",uptimestr);
    print_value ("OS/Hardware","%s %s (%s)", VDstr("os","kernel"),
                 VDstr("os","version"), VDstr("os","arch"));
    const char *dist = VDstr("os","distro");
    if (dist) print_value ("Distribution", "%s", dist);
    Vdone("os");
    
    /* -------------------------------------------------------------*/
    print_hdr ("RESOURCES");
    print_value ("Processes","\033[1m%llu\033[0m "
                             "(\033[1m%llu\033[0m running, "
                             "\033[1m%llu\033[0m stuck)",
                             VDint("proc","total"),
                             VDint("proc","run"),
                             VDint("proc","stuck"));
    Vdone("proc");
 
     print_value ("Load Average", "\033[1m%6.2f\033[0m / "
                                  "\033[1m%6.2f\033[0m / "
                                  "\033[1m%6.2f\033[0m",
                 VAfrac ("loadavg",0), VAfrac ("loadavg", 1),
                 VAfrac ("loadavg",2));
    Vdone ("loadavg");

    char cpubuf[128];
    sprintf (cpubuf, "\033[1m%6.2f \033[0m%%", Vfrac("pcpu"));
    
    char meter[32];
    strcpy (meter, "-[                      ]+");
    
    double iowait = VDfrac("io","pwait");
    double pcpu = Vfrac("pcpu"); Vdone("pcpu");
    double level = 4.5;
    
    int pos = 2;
    while (level < 100.0 && pos < 22) {
        if (level < pcpu) meter[pos++] = '#';
        else meter[pos++] = ' ';
        level += 4.5;
    }
    
    
    print_value ("CPU", "%-40s %s", cpubuf, meter);
    if (iowait>0.001) print_value ("CPU iowait", 
                                   "\033[1m%6.2f %%\033[0m", iowait);
    print_value ("Available RAM", "\033[1m%.2f\033[0m MB",
                 ((double)VDint("mem","total"))/1024.0);
    print_value ("Free RAM", "\033[1m%.2f\033[0m MB",
                 ((double)VDint("mem","free"))/1024.0);
    
    print_value ("Network in/out", "\033[1m%i\033[0m Kb/s "
                                   "(\033[1m%i\033[0m pps) / "
                                   "\033[1m%i\033[0m Kb/s "
                                   "(\033[1m%i\033[0m pps)",
                                   VDint("net","in_kbs"),
                                   VDint("net","in_pps"),
                                   VDint("net","out_kbs"),
                                   VDint("net","out_pps"));
    
    print_value ("Disk i/o", "\033[1m%i\033[0m rdops / "
                             "\033[1m%i\033[0m wrops",
                 VDint("io","rdops"), VDint("io","wrops"));
    
    Vdone("mem");
    Vdone("net");
    Vdone("io");
    Vdone("badness");

    print_values (apires, NULL);
    
    /* -------------------------------------------------------------*/
    print_hdr ("PROCESS LIST");
    
    const char *top_hdr[] = {"USER","PID","CPU","MEM","NAME",NULL};
    const char *top_fld[] = {"user","pid","pcpu","pmem","name",NULL};
    columnalign top_align[] = {CA_L, CA_R, CA_R, CA_R, CA_L, CA_NULL};
    vartype top_tp[] =
        {VAR_STR,VAR_INT,VAR_DOUBLE,VAR_DOUBLE,VAR_STR,VAR_NULL};
    int top_wid[] = {15, 7, 9, 9, 0, 0};
    int top_div[] = {0, 0, 0, 0, 0, 0};
    const char *top_suf[] = {"",""," %", " %", "", NULL};
    
    var *v_top = var_get_array_forkey (apires, "top");
    print_table (v_top, top_hdr, top_fld, 
                 top_align, top_tp, top_wid, top_suf, top_div);
    
    Vdone("top");
    /* -------------------------------------------------------------*/
    print_hdr ("STORAGE");
    
    const char *df_hdr[] = {"DEVICE","SIZE","FS","USED","MOUNTPOINT",NULL};
    const char *df_fld[] = {"device","size","fs","pused","mount",NULL};
    columnalign df_aln[] = {CA_L,CA_R,CA_L,CA_R,CA_L,CA_NULL};
    vartype df_tp[] = {VAR_STR,VAR_INT,VAR_STR,VAR_DOUBLE,VAR_STR,VAR_NULL};
    int df_wid[] = {12, 14, 6, 8, 0};
    int df_div[] = {0, (1024), 0, 0, 0, 0};
    const char *df_suf[] = {""," GB", "", " %", "", ""};
    
    var *v_df = var_get_array_forkey (apires, "df");
    
    /*print_generic_table (v_df);*/
    
    print_table (v_df, df_hdr, df_fld,
                 df_aln, df_tp, df_wid, df_suf, df_div);
    
    Vdone("df");
    
    /** Print any remaining table data */
    print_tables (apires);
        
    printf ("---------------------------------------------"
            "-----------------------------------\n");

    var_free (apires);
    print_done();
    return 0;    
}
Ejemplo n.º 23
0
int
HashmapCount(int verbose, struct cfg *cfg, char *args[])
{
	struct test t;
	char *mem = NULL;
	int ret = 0, fd = 0, data;
	int useal = atoi(args[0]);
	struct stat st;
	void *mm;

	if (useal) {
		if ((mem = malloc(0xFFFFFF)) == NULL ||
				(t.al = suba_init(mem, 0xFFFFFF, 1, 0)) == NULL) {
			AMSG("");
			ret = -1;
			goto err;
		}
	} else {
		t.al = NULL;
	}
	if ((t.words = hashmap_new(hash_str, (cmp_fn)strcmp, NULL, t.al)) == NULL ||
				(fd = open(args[1], 0)) == -1 ||
				fstat(fd, &st) == -1) {
		AMSG("");
		ret = -1;
		goto err;
	}
	if ((t.src = mm = mmap(NULL, (int)st.st_size,
					PROT_READ | PROT_WRITE,
					MAP_PRIVATE,
					fd, 0)) == NULL) {
		AMSG("");
		ret = -1;
		goto err;
	}

	t.slim = t.src + st.st_size;
	if (load_words(&t) == -1) {
		AMSG("");
		ret = -1;
		goto err;
	}

	if ((data = (int)hashmap_get(t.words, args[2])) == 0 ||
			atoi(args[3]) != data ||
			(data = (int)hashmap_get(t.words, args[4])) == 0 ||
			atoi(args[5]) != data) {
		errno = ERANGE;
		PMNF(errno, ": %d != %d", atoi(args[3]), data);
		ret = -1;
		goto err;
	}

if (verbose)
	print_values(t.words);
err:
	munmap(mm, st.st_size);
	if (fd)
		close(fd);
	hashmap_del(t.words, NULL, NULL, NULL);
	free(mem);

	cfg = NULL;
	return ret;
}
void *watch_process(void* _pid) {


  pid_t pid = *((pid_t*)_pid);
  printf("%d\n", pid);
  int retval, EventSet = PAPI_NULL;

  //char events_name[NB_EVENTS][PAPI_MAX_STR_LEN] = {"UNHALTED_CORE_CYCLES", "INSTRUCTION_RETIRED", "MEM_LOAD_RETIRED:L1D_HIT", "MEM_LOAD_RETIRED:L2_HIT", "LLC_REFERENCES"};
  //char events_name[NB_EVENTS][PAPI_MAX_STR_LEN] = {"UNHALTED_CORE_CYCLES", "INSTRUCTION_RETIRED", "MEM_LOAD_RETIRED:L2_HIT", "L2_RQSTS:LOADS", "L2_DATA_RQSTS:ANY"};
  //char events_name[NB_EVENTS][PAPI_MAX_STR_LEN] = {"UNHALTED_CORE_CYCLES", "INSTRUCTION_RETIRED", "L1I:READS", "L1D_CACHE_LD:MESI", "L1D_CACHE_ST:MESI"};
  //char events_name[NB_EVENTS][PAPI_MAX_STR_LEN] = {"UNHALTED_CORE_CYCLES", "INSTRUCTION_RETIRED", "L1D_CACHE_LD:MESI", "L1D_CACHE_ST:MESI", "L2_DATA_RQSTS:ANY" };
  char events_name[NB_EVENTS][PAPI_MAX_STR_LEN] = {"UNHALTED_CORE_CYCLES", "INSTRUCTION_RETIRED", "L1I:READS", "L1D_CACHE_LD:MESI", "L1D_CACHE_ST:MESI", "MEM_LOAD_RETIRED:L2_HIT", "L2_RQSTS:LOADS", "L2_DATA_RQSTS:ANY", "BR_INST_RETIRED:ALL_BRANCHES", "BR_INST_EXEC:ANY", "BR_MISP_EXEC:ANY" };
  unsigned int native_events[NB_EVENTS];
  long long values[NB_EVENTS];


  int err;
  /* Initialize the library */
  if ( (err = PAPI_library_init(PAPI_VER_CURRENT)) != PAPI_VER_CURRENT) {
    fprintf(stderr, "PAPI library init error! %d\n", err);
    exit(1);
  }

  if ( (err = PAPI_multiplex_init()) != PAPI_OK) {
    fprintf(stderr, "PAPI multiplex init error! %d\n", err);
    exit(1);
  }

  
  if (PAPI_thread_init(pthread_self) != PAPI_OK) {
    fprintf(stderr, "PAPI thread init error! %d\n", err);
    exit(1);
  }


  //sched_setaffinity(0, 0);
  //if ((retval = PAPI_set_granularity(PAPI_GRN_MAX)) != PAPI_OK) {
  //  fprintf(stderr, "PAPI set granurality error! %d, %d, %d, %d, %d\n", retval, PAPI_EINVAL, PAPI_ENOEVST, PAPI_ENOCMP, PAPI_EISRUN);
  //  exit(1);
  //}

  // Traduction des string en code
  name_to_code(events_name, NB_EVENTS, native_events);
  // Vérification des évènements
  check_events(native_events, NB_EVENTS);
  
  if (PAPI_create_eventset(&EventSet) != PAPI_OK) {    
    fprintf(stderr, "PAPI EventSet init error!\n");
    exit(1);
  }

  if ( (err = PAPI_assign_eventset_component( EventSet, 0 ) ) != PAPI_OK ) {
    fprintf(stderr, "PAPI assign component error!\n%s\n", PAPI_strerror(err));
    exit(1);
  }

  if ( ( err = PAPI_set_multiplex(EventSet) ) != PAPI_OK) {    
    fprintf(stderr, "PAPI set multiplex error!\n%s\n", PAPI_strerror(err));
    exit(1);
  }

  if ( (retval = PAPI_add_events(EventSet, native_events, NB_EVENTS) ) != PAPI_OK) {
    fprintf(stderr, "PAPI add events error!\n%s\n", PAPI_strerror(retval) );
    exit(1);
  }

  if (PAPI_attach(EventSet, pid) != PAPI_OK)
    exit(1);

  while(while_watch) {
    /* Start counting */
    if (PAPI_start(EventSet) != PAPI_OK) {
      fprintf(stderr, "PAPI start error!\n");
      exit(1);
    }
    usleep(1000000);

    if (PAPI_stop(EventSet, values) != PAPI_OK) {
      fprintf(stderr, "PAPI stop error!\n");
      exit(1);
    }

    print_values(events_name, values, NB_EVENTS);


  }

	return 0;
}
int
main (int argc, char *argv[]) 
{
	char *device = NULL;
	int o, longindex;
	int retval = 0;

	thresholds_t thresholds;
	values_t values;
	int fd;

	static struct option longopts[] = { 
		{"device", required_argument, 0, 'd'}, 
		{"immediate", no_argument, 0, 'i'}, 
		{"quiet-check", no_argument, 0, 'q'}, 
		{"auto-on", no_argument, 0, '1'}, 
		{"auto-off", no_argument, 0, '0'}, 
		{"nagios", no_argument, 0, 'n'}, /* DEPRECATED, but we still accept it */
		{"help", no_argument, 0, 'h'}, 
		{"version", no_argument, 0, 'V'},
		{0, 0, 0, 0}
	};

	/* Parse extra opts if any */
	argv=np_extra_opts (&argc, argv, progname);

	setlocale (LC_ALL, "");
	bindtextdomain (PACKAGE, LOCALEDIR);
	textdomain (PACKAGE);

	while (1) {
		
		o = getopt_long (argc, argv, "+d:iq10nhVv", longopts, &longindex);

		if (o == -1 || o == EOF || o == 1)
			break;

		switch (o) {
		case 'd':
			device = optarg;
			break;
		case 'q':
			fprintf (stderr, "%s\n", _("DEPRECATION WARNING: the -q switch (quiet output) is no longer \"quiet\"."));
			fprintf (stderr, "%s\n", _("Nagios-compatible output is now always returned."));
			break;
		case 'i':
		case '1':
		case '0':
			printf ("%s\n", _("SMART commands are broken and have been disabled (See Notes in --help)."));
			return STATE_CRITICAL;
			break;
		case 'n':
			fprintf (stderr, "%s\n", _("DEPRECATION WARNING: the -n switch (Nagios-compatible output) is now the"));
			fprintf (stderr, "%s\n", _("default and will be removed from future releases."));
			break;
		case 'v': /* verbose */
			verbose = TRUE;
			break;
		case 'h':
			print_help ();
			return STATE_OK;
		case 'V':
			print_revision (progname, NP_VERSION);
			return STATE_OK;
		default:
			usage5 ();
		}
	}

	if (optind < argc) {
		device = argv[optind];
	}

	if (!device) {
		print_help ();
		return STATE_OK;
	}

	fd = open (device, OPEN_MODE);

	if (fd < 0) {
		printf (_("CRITICAL - Couldn't open device %s: %s\n"), device, strerror (errno));
		return STATE_CRITICAL;
	}

	if (smart_cmd_simple (fd, SMART_CMD_ENABLE, 0, FALSE)) {
		printf (_("CRITICAL - SMART_CMD_ENABLE\n"));
		return STATE_CRITICAL;
	}

	smart_read_values (fd, &values);
	smart_read_thresholds (fd, &thresholds);
	retval = nagios (&values, &thresholds);
	if (verbose) print_values (&values, &thresholds);

	close (fd);
	return retval;
}
int main(int argc, char *argv[]) {

    int nx;
    int maxsteps;
    double threshold;
    FILE* outfile; /* NULL if output values are not to be printed */

    double *uk; 
    double *ukp1;
    double *temp; 
    double dx, dt;
    double start_time, end_time;
    double maxdiff;
    int step;

    int nthreads;

    parse_arguments(argc, argv, &nx, &maxsteps, &threshold, &outfile);

    /* could use omp_get_wtime but get_time is what sequential code uses */
    start_time = get_time();

    #pragma omp parallel 
    {
        #pragma omp single 
        {
            nthreads = omp_get_num_threads();
        }
    }
    if ((nx % nthreads) != 0) {
        fprintf(stderr, "Number of threads must evenly divide %d\n", nx);
        exit(EXIT_FAILURE);
    }

    /* uk, ukp1 have nx interior points plus fixed ends */
    uk = malloc(sizeof(*uk) * (nx+2)); 
    ukp1 = malloc(sizeof(*ukp1) * (nx+2));
    if ((uk == NULL) || (ukp1 == NULL)) {
        fprintf(stderr, "Unable to allocate memory\n");
        return EXIT_FAILURE;
    }
    dx = 1.0/nx;
    dt = 0.5*dx*dx;
    maxdiff = threshold;

    /* initialize(uk, ukp1, nx); */
    initialize_end_points(uk, ukp1, nx);
    /* remainder of initialize in parallel section */

    #pragma omp parallel
    {
        int step_local; 
        double maxdiff_local;
        double diff;

        int my_id = omp_get_thread_num();
        int loop_start = 1 + my_id * (nx/nthreads);
        int loop_limit = loop_start + (nx/nthreads);
        maxdiff = threshold;

        initialize_local_section(uk, ukp1, loop_start, loop_limit);
        #pragma omp barrier

        for (step_local = 0; (step_local < maxsteps) && (maxdiff >= threshold);
                ++step_local) 
        {
            #pragma omp barrier
            #pragma omp single
            {
                maxdiff = 0.0;
            }
 
            /* compute new values and check for convergence */
            maxdiff_local = 0.0;
            /* for (int i = 1; i < nx-1; ++i) */
            for (int i = loop_start; i < loop_limit; ++i) {
                ukp1[i]=uk[i]+ (dt/(dx*dx))*(uk[i+1]-2*uk[i]+uk[i-1]);
                diff = fabs(uk[i] - ukp1[i]);
                if (diff > maxdiff_local) maxdiff_local = diff;
            }
            #pragma omp critical
            {
                if (maxdiff_local > maxdiff) maxdiff = maxdiff_local;
            }

            /* "copy" ukp1 to uk by swapping pointers */
            #pragma omp barrier
            #pragma omp single
            {
                temp = ukp1; ukp1 = uk; uk = temp;
            }
        }
        /* save count of steps in shared variable */
        #pragma omp single
        {
            step = step_local;
        }
    }

    end_time = get_time();

    if (outfile != NULL) {
        print_values(outfile, uk, nx);
        fclose(outfile);
    }

    printf("OpenMP program, SPMD-style v2 (%d threads):\n", nthreads);
    printf("nx = %d, maxsteps = %d, threshold = %g\n", nx, maxsteps, threshold);
    if (maxdiff < threshold) {
        printf("converged in %d iterations\n", step);
    }
    else {
        printf("failed to converge in %d iterations, maxdiff = %g\n", 
                step, maxdiff);
    }
    printf("execution time = %g\n", end_time - start_time);

    /* clean up and end */
    free(uk);
    free(ukp1);
    return EXIT_SUCCESS;
}
Ejemplo n.º 27
0
static void echo_query(NODE *n)
{
   switch(n -> kind){
      case N_CREATETABLE:            /* for CreateTable() */
         printf("create table %s (", n -> u.CREATETABLE.relname);
         print_attrtypes(n -> u.CREATETABLE.attrlist);
         printf(")");
         printf(";\n");
         break;
      case N_CREATEINDEX:            /* for CreateIndex() */
         printf("create index %s(%s);\n", n -> u.CREATEINDEX.relname,
               n -> u.CREATEINDEX.attrname);
         break;
      case N_DROPINDEX:            /* for DropIndex() */
         printf("drop index %s(%s);\n", n -> u.DROPINDEX.relname,
               n -> u.DROPINDEX.attrname);
         break;
      case N_DROPTABLE:            /* for DropTable() */
         printf("drop table %s;\n", n -> u.DROPTABLE.relname);
         break;
      case N_LOAD:            /* for Load() */
         printf("load %s(\"%s\");\n",
               n -> u.LOAD.relname, n -> u.LOAD.filename);
         break;
      case N_HELP:            /* for Help() */
         printf("help");
         if(n -> u.HELP.relname != NULL)
            printf(" %s", n -> u.HELP.relname);
         printf(";\n");
         break;
      case N_PRINT:            /* for Print() */
         printf("print %s;\n", n -> u.PRINT.relname);
         break;
      case N_SET:                                 /* for Set() */
         printf("set %s = \"%s\";\n", n->u.SET.paramName, n->u.SET.string);
         break;
      case N_QUERY:            /* for Query() */
         printf("select ");
         print_relattrs(n -> u.QUERY.relattrlist);
         printf("\n from ");
         print_relations(n -> u.QUERY.rellist);
         printf("\n");
         if (n->u.QUERY.conditionlist) {
            printf("where ");
            print_conditions(n->u.QUERY.conditionlist);
         }
         printf(";\n");
         break;
      case N_INSERT:            /* for Insert() */
         printf("insert into %s values ( ",n->u.INSERT.relname);
         print_values(n -> u.INSERT.valuelist);
         printf(");\n");
         break;
      case N_DELETE:            /* for Delete() */
         printf("delete %s ",n->u.DELETE.relname);
         if (n->u.DELETE.conditionlist) {
            printf("where ");
            print_conditions(n->u.DELETE.conditionlist);
         }
         printf(";\n");
         break;
      case N_UPDATE:            /* for Update() */
         {
            printf("update %s set ",n->u.UPDATE.relname);
            print_relattr(n->u.UPDATE.relattr);
            printf(" = ");
            struct node *rhs = n->u.UPDATE.relorvalue;

            /* The RHS can be either a relation.attribute or a value */
            if (rhs->u.RELATTR_OR_VALUE.relattr) {
               /* Print out the relation.attribute */
               print_relattr(rhs->u.RELATTR_OR_VALUE.relattr);
            } else {
               /* Print out the value */
               print_value(rhs->u.RELATTR_OR_VALUE.value);
            }
            if (n->u.UPDATE.conditionlist) {
               printf("where ");
               print_conditions(n->u.UPDATE.conditionlist);
            }
            printf(";\n");
            break;
         }
      default:   // should never get here
         break;
   }
   fflush(stdout);
}
Ejemplo n.º 28
0
int main(int argc, char *argv[]) {

    int nx;
    int maxsteps;
    double threshold;
    FILE* outfile; /* NULL if output values are not to be printed */

    double *uk; 
    double *ukp1;
    double *temp; 
    double dx, dt;
    double start_time, end_time;
    double maxdiff, diff;
    int step;

    parse_arguments(argc, argv, &nx, &maxsteps, &threshold, &outfile);

    start_time = get_time();

    /* uk, ukp1 have nx interior points plus fixed ends */
    uk = malloc(sizeof(*uk) * (nx+2));
    ukp1 = malloc(sizeof(*ukp1) * (nx+2));
    if ((uk == NULL) || (ukp1 == NULL)) {
        fprintf(stderr, "Unable to allocate memory\n");
        return EXIT_FAILURE;
    }
    dx = 1.0/nx;
    dt = 0.5*dx*dx;
    maxdiff = threshold;

    initialize(uk, ukp1, nx);

    for (step = 0; (step < maxsteps) && (maxdiff >= threshold); ++step) {

        /* compute new values */
        for (int i = 1; i <= nx; ++i) {
          ukp1[i]=uk[i]+ (dt/(dx*dx))*(uk[i+1]-2*uk[i]+uk[i-1]);
        }

        /* check for convergence */
        maxdiff = 0.0;
        for (int i = 1; i <= nx; ++i) {
            diff = fabs(uk[i] - ukp1[i]);
            if (diff > maxdiff) maxdiff = diff;
        }

        /* "copy" ukp1 to uk by swapping pointers */
        temp = ukp1; ukp1 = uk; uk = temp;
    }

    end_time = get_time();

    if (outfile != NULL) {
        print_values(outfile, uk, nx);
        fclose(outfile);
    }

    printf("sequential program:\n");
    printf("nx = %d, maxsteps = %d, threshold = %g\n", nx, maxsteps, threshold);
    if (maxdiff < threshold) {
        printf("converged in %d iterations\n", step);
    }
    else {
        printf("failed to converge in %d iterations, maxdiff = %g\n", 
                step, maxdiff);
    }
    printf("execution time = %g\n", end_time - start_time);

    /* clean up and end */
    free(uk);
    free(ukp1);
    return EXIT_SUCCESS;
}