示例#1
0
optional<std::tuple<level_param_names, expr, expr>>
definition_cache::find(environment const & env, name const & n, expr const & pre_type, expr const & pre_value, bool is_trusted) {
    entry e;
    {
        lock_guard<mutex> lc(m_mutex);
        if (auto it = m_definitions.find(n)) {
            e = *it;
        } else {
            return optional<std::tuple<level_param_names, expr, expr>>();
        }
    }
    level_param_names ls;
    if (e.m_is_trusted == is_trusted &&
        expr_eq_modulo_placeholders_fn()(e.m_pre_type, pre_type) &&
        expr_eq_modulo_placeholders_fn()(e.m_pre_value, pre_value) &&
        get_fingerprint(env) == e.m_fingerprint &&
        check_dependencies(env, e.m_dependencies)) {
        return some(std::make_tuple(e.m_params, e.m_type, e.m_value));
    } else {
        return optional<std::tuple<level_param_names, expr, expr>>();
    }
}
示例#2
0
void
Quad1Mindlin :: computeBmatrixAt(GaussPoint *gp, FloatMatrix &answer, int li, int ui)
// Returns the [5x9] strain-displacement matrix {B} of the receiver,
// evaluated at gp.
{
    FloatArray n, ns;
    FloatMatrix dn, dns;

    this->interp_lin.evaldNdx( dn, * gp->giveNaturalCoordinates(),  FEIElementGeometryWrapper(this) );
    this->interp_lin.evalN( n, * gp->giveNaturalCoordinates(),  FEIElementGeometryWrapper(this) );

    answer.resize(5, 12);
    answer.zero();

    // enforce one-point reduced integration if requested
    if ( this->reducedIntegrationFlag ) {
        FloatArray lc(2);
        lc.zero(); // set to element center coordinates

        this->interp_lin.evaldNdx( dns, lc, FEIElementGeometryWrapper(this));
        this->interp_lin.evalN( ns, lc,  FEIElementGeometryWrapper(this));
     } else {
        dns = dn;
        ns = n;
    }

    ///@todo Check sign here
    for ( int i = 0; i < 4; ++i ) {
      answer(0, 2 + i * 3) =  dn(i, 0); // kappa_x = d(fi_y)/dx
      answer(1, 1 + i * 3) = -dn(i, 1); // kappa_y = -d(fi_x)/dy
      answer(2, 2 + i * 3) =  dn(i, 1); // kappa_xy=d(fi_y)/dy-d(fi_x)/dx
      answer(2, 1 + i * 3) = -dn(i, 0);

      answer(3, 0 + i * 3) = dns(i, 0); // gamma_xz = fi_y+dw/dx
      answer(3, 2 + i * 3) = ns(i);
      answer(4, 0 + i * 3) = dns(i, 1);// gamma_yz = -fi_x+dw/dy
      answer(4, 1 + i * 3) = -ns(i);
    }
}
示例#3
0
void TestListCounter::TestCtor()
{
	RTFfile theFile(new RTFFileContext);
	AutoDocFileReaderImpl4Tests reader(GET_TEST_FILE_PATH(_T("list_outline.doc")), &theFile);
	reader.Initialize();

	ListCounter lc(&theFile, 9, -1); // pick up the list for \ls9

	int iListID = theFile.GetListOverrideTable()->GetListOverrideWithLs(9)->m_lListID;

	assertTest(lc.m_vecLevelInfo.size() == 9);

	assertTest(lc.m_vecLevelInfo[0].m_vecFormatStr.size() == 2);
	assertTest(lc.m_vecLevelInfo[0].m_vecFormatStr[0] == LT_PLACEHOLDER + 0);
	assertTest(lc.m_vecLevelInfo[0].m_vecFormatStr[1] == LT_TEXT + _T('.'));
	assertTest(lc.m_vecLevelInfo[0].m_iNumberFormat == NUMBER_FORMAT_UPPERCASE_ROMAN_NUMERAL);
	assertTest(lc.m_vecLevelInfo[0].m_TrailingItem == TYPE_OF_CHAR_FOLLOWING_TAB);

	assertTest(lc.m_vecLevelInfo[1].m_vecFormatStr.size() == 3);
	assertTest(lc.m_vecLevelInfo[1].m_vecFormatStr[0] == LT_PLACEHOLDER + 0);
	assertTest(lc.m_vecLevelInfo[1].m_vecFormatStr[1] == LT_PLACEHOLDER + 1);
	assertTest(lc.m_vecLevelInfo[1].m_vecFormatStr[2] == LT_TEXT + _T('.'));
	assertTest(lc.m_vecLevelInfo[1].m_iNumberFormat == NUMBER_FORMAT_LOWERCASE_LETTER);

	assertTest(lc.m_vecLevelInfo[2].m_iNumberFormat == NUMBER_FORMAT_ARABIC);
	assertTest(lc.m_vecLevelInfo[3].m_iNumberFormat == NUMBER_FORMAT_LOWERCASE_LETTER);


	assertTest(lc.m_vecLevelInfo[8].m_vecFormatStr.size() == 3);
	assertTest(lc.m_vecLevelInfo[8].m_vecFormatStr[0] == LT_TEXT + _T('('));
	assertTest(lc.m_vecLevelInfo[8].m_vecFormatStr[1] == LT_PLACEHOLDER + 8);
	assertTest(lc.m_vecLevelInfo[8].m_vecFormatStr[2] == LT_TEXT + _T(')'));

	assertTest(lc.m_vecLevelInfo[0].m_iCount == 0);
	assertTest(lc.m_vecLevelInfo[1].m_iCount == 0);
	assertTest(lc.m_vecLevelInfo[7].m_iCount == 0);
	assertTest(lc.m_vecLevelInfo[8].m_iCount == 0);

}
示例#4
0
void TestListCounter::TestCreateListText()
{
	RTFfile theFile(new RTFFileContext);
	AutoDocFileReaderImpl4Tests reader(GET_TEST_FILE_PATH(_T("list_outline.doc")), &theFile);
	reader.Initialize();

	ListCounter lc(&theFile, 9, -1); // pick up the list for \ls9

	lc.StepLevel(9,0);
	RTFpn* pPn = lc.CreateListText(0);
	assertTest(pPn!=NULL);
	assertTest(pPn->GetCount()>0);

	RTFformatting form(theFile.GetFileContext());
	form.the_RTFpn = pPn;
	RTFchrfmt cf(theFile.GetFileContext());
	CWideString cws;
	assertTest (form.GetListNumber(&theFile, cws, cf));
	assertTest(cws == L"I.\t");


}
示例#5
0
int main (int argc, char *argv[])
{
	unsigned t;
	if (! threaded) {
		for(t = 1; t < argc; t++){
			lc(argv[t]);
		}
		printf("%10d total\n", total);
	} else {
		pthread_t threads[argc];
		void *status;
		int rc;

		pthread_mutex_init(&mutexsum, NULL);

		for(t = 1; t < argc; t++){
			// printf("In main: creating thread %d\n", t);
			rc = pthread_create(&threads[t], NULL, lc, (void *) argv[t]);
			if (rc){
				printf("ERROR; return code from pthread_create() is %d\n", rc);
				exit(-1);
			}
		}

		// Join
		for(t = 1; t < argc; t++){
			rc = pthread_join(threads[t], &status);
			if (rc){
				printf("ERROR; return code from pthread_join() is %d\n", rc);
				exit(-1);
			}
		}
		printf("%10d total\n", total);

		pthread_mutex_destroy(&mutexsum);
		pthread_exit(NULL);
	}
}
示例#6
0
文件: lc.c 项目: Keith-S-Thompson/lc
/* D I R E C T O R Y
 *
 *  directory() is used to open and read the directory and pass
 *  the filenames found to the routine lc();
 */
void directory(char *dname)
{
    register char *nbp;
    register char *nep;
    FILE *fd;
    int i;
    struct direct dir;

    /* add a slash to the end of the directory name */
    nbp = dname + strlen(dname);
    *nbp++ = '/';
    *nbp = '\0';

    if ((nbp + NAME_MAX + 2) >= (dname + BUFSIZE))  { /* dname too long */
        (void) fprintf(stderr, "%s: dirname too long: %s\n",
                       Progname, dname);
        return;
    }

    if ((fd = fopen(dname, "r")) == (FILE *) NULL) { /* open the directory */
        (void) fprintf(stderr, "%s: can't open %s\n", Progname, dname);
        return;
    }

    while (fread((char *) &dir, sizeof(dir), 1, fd) > 0) {
        if (dir.d_ino == 0
            || strcmp(dir.d_name, ".") == 0
            || strcmp(dir.d_name, "..") == 0)
            continue;
        for (i = 0, nep = nbp; i < NAME_MAX; i++)
            *nep++ = dir.d_name[i];
        *nep++ = '\0';
        lc(dname, 2);
    }
    (void) fclose(fd);
    *--nbp = '\0';     /* restore dname */
    return;
}
示例#7
0
static inline void DoSplit0(C* res, const TChr* ptr, TDelim& d, size_t maxFields, int options) {
    typedef typename TSelectType<TSameType<TChr, wchar16>::Result, Wtroka, Stroka>::TResult TString;
    res->clear();

    if (!ptr) {
        return;
    }

    typedef TContainerConsumer<C> TConsumer;
    TConsumer cc(res);

    if (maxFields) {
        TLimitingConsumer<TConsumer, const TChr> lc(maxFields, &cc);

        DoSplit1(lc, d, ptr, options);

        if (lc.Last) {
            res->push_back(TString(lc.Last));
        }
    } else {
        DoSplit1(cc, d, ptr, options);
    }
}
Foam::tmp<Foam::vectorField> Foam::toroidalCS::localToGlobal
(
    const vectorField& local,
    bool translate
) const
{
    const scalarField r = local.component(vector::X);

    const scalarField theta =
        local.component(vector::Y)*mathematicalConstant::pi/180.0;

    const scalarField phi =
        local.component(vector::Z)*mathematicalConstant::pi/180.0;

    const scalarField rprime = radius_ + r*sin(phi);

    vectorField lc(local.size());
    lc.replace(vector::X, rprime*cos(theta));
    lc.replace(vector::Y, rprime*sin(theta));
    lc.replace(vector::Z, r*cos(phi));

    return coordinateSystem::localToGlobal(lc, translate);
}
示例#9
0
void NegRep::computeExactFlags() {
  if (!child->flagsComputed())
    child->computeExactFlags();

  if (child->sign() == 0) {
    reduceToZero();
    return;
  }

  if (rationalReduceFlag) {
    if (child->ratFlag()>0 && child->ratValue() != NULL) {
      BigRat val = -(*(child->ratValue()));
      reduceToBigRat(val);
      ratFlag() = child->ratFlag()+1;
      return;
    } else
      ratFlag() = -1;
  }

  sign() = -child->sign();
  uMSB() = child->uMSB();
  lMSB() = child->lMSB();

  // length() = child->length();
  measure() = child->measure();
  u25() = child->u25();
  l25() = child->l25();
  v2p() = child->v2p();
  v2m() = child->v2m();
  v5p() = child->v5p();
  v5m() = child->v5m();
  high() = child->high();
  low() = child->low();
  lc()  = child->lc();
  tc()  = child->tc();
  flagsComputed() = true;
}//NegRep::computeExactFlags
示例#10
0
const std::string ExprRep::dump(int level) const {
  std::ostringstream ost;
  if (level == OPERATOR_ONLY) {
    ost << op();
  } else if (level == VALUE_ONLY) {
    ost << appValue();
  } else if (level == OPERATOR_VALUE) {
    ost << op() << "[val: " << appValue() << "]";
  } else if (level == FULL_DUMP) {
    ost << op()
    << "[val: "  << appValue() << "; "
    << "kp: " << knownPrecision() << "; "
#ifdef CORE_DEBUG
    << "r: " << relPrecision() << "; "
    << "a: " << absPrecision() << "; "
#endif
    << "lMSB: " << lMSB() << "; "
    << "uMSB: " << uMSB() << "; "
    << "sign: " << sign() << "; "
    // << "length: " << length() << "; "
    << "measure: " << measure() << "; "
    << "d_e: " << d_e() << "; "
    << "u25: " << u25() << "; "
    << "l25: " << l25() << "; "
    << "v2p: " << v2p() << "; "
    << "v2m: " << v2m() << "; "
    << "v5p: " << v5p() << "; "
    << "v5m: " << v5m() << "; "
    << "high: " << high() << "; "
    << "low: " << low() << "; "
    << "lc: " << lc() << "; "
    << "tc: " << tc()
    << "]";
  }
  return std::string(ost.str());
  // note that str() return an array not properly terminated!
}
示例#11
0
// Act upon an ls command
// Convert the first parameter into an absolute path, then list the files in that path
void SimpleShell::ls_command( string parameters, StreamOutput *stream )
{
    string path, opts;
    while(!parameters.empty()) {
        string s = shift_parameter( parameters );
        if(s.front() == '-') {
            opts.append(s);
        } else {
            path = s;
            if(!parameters.empty()) {
                path.append(" ");
                path.append(parameters);
            }
            break;
        }
    }

    path = absolute_from_relative(path);

    DIR *d;
    struct dirent *p;
    d = opendir(path.c_str());
    if (d != NULL) {
        while ((p = readdir(d)) != NULL) {
            stream->printf("%s", lc(string(p->d_name)).c_str());
            if(p->d_isdir) {
                stream->printf("/");
            } else if(opts.find("-s", 0, 2) != string::npos) {
                stream->printf(" %d", p->d_fsize);
            }
            stream->printf("\r\n");
        }
        closedir(d);
    } else {
        stream->printf("Could not open directory %s\r\n", path.c_str());
    }
}
示例#12
0
void ExprRep::reduceToZero() {
  appValue() = CORE_REAL_ZERO;
  appComputed() = true;
  flagsComputed() = true;
  knownPrecision() = CORE_negInfty;
#ifdef CORE_DEBUG
  relPrecision() = EXTLONG_ZERO;
  absPrecision() = CORE_negInfty;
  //  numNodes() = 0;
#endif

  d_e() = EXTLONG_ONE;
  visited() = false;
  sign() = 0;
  uMSB() = CORE_negInfty;
  lMSB() = CORE_negInfty;
  // length() = 0; 	// fixed? original = 1
  measure() = EXTLONG_ZERO;

  // BFMSS[2,5] bound.
  u25() = l25() = v2p() = v2m() = v5p() = v5m() = EXTLONG_ZERO;

  low() = EXTLONG_ONE;		// fixed? original = 0
  high() = lc() = tc() = EXTLONG_ZERO;

  if (rationalReduceFlag) {
    if (ratFlag() > 0) {
      ratFlag() ++;
      if (ratValue() == NULL)
        ratValue() = new BigRat(0);
      else
        *(ratValue()) = 0;
    } else
      ratFlag() = 1;
  }
}
示例#13
0
static void windowLoad(struct Window *window)
{
	for (int i = 0; i < MAX_NAME_SIZE; i++)
		name[i] = ' ';
	name[MAX_NAME_SIZE] = '\0';

	position = 0;

	window_set_click_config_provider(sWindow, clickConfigProviderName);

	sNameTitle = text_layer_create(GRect(0, 30, 144, 50));
	text_layer_set_font(sNameTitle, fonts_get_system_font(FONT_KEY_GOTHIC_28_BOLD));
	text_layer_set_text_alignment(sNameTitle, GTextAlignmentCenter);
	text_layer_set_text(sNameTitle, lc(LC_ADD_NAME));
	layer_add_child(window_get_root_layer(window), text_layer_get_layer(sNameTitle));

	sName = text_layer_create(GRect(10, 80, 124, 25));
	text_layer_set_font(sName, sFont);
	text_layer_set_text(sName, name);
	layer_add_child(window_get_root_layer(window), text_layer_get_layer(sName));

	sInverterLayer = inverter_layer_create(grectNameLayerForInverterLayer());
	layer_add_child(window_get_root_layer(window), inverter_layer_get_layer(sInverterLayer));
}
示例#14
0
// Computes the root bit bound of the expression.
// In effect, computeBound() returns the current value of low.
extLong ExprRep::computeBound() {
  extLong measureBd = measure();
  // extLong cauchyBd = length();
  extLong ourBd = (d_e() - EXTLONG_ONE) * high() + lc();
  // BFMSS[2,5] bound.
  extLong bfmsskBd;
  if (v2p().isInfty() || v2m().isInfty())
    bfmsskBd = CORE_INFTY;
  else
    bfmsskBd = l25() + u25() * (d_e() - EXTLONG_ONE) - v2() - ceilLg5(v5());

  // since we might compute \infty - \infty for this bound
  if (bfmsskBd.isNaN())
    bfmsskBd = CORE_INFTY;

  extLong bd = core_min(measureBd,
                        // core_min(cauchyBd,
                        core_min(bfmsskBd, ourBd));
#ifdef CORE_SHOW_BOUNDS
    std::cout << "Bounds (" << measureBd <<
                    "," << bfmsskBd << ", " << ourBd << "),  ";
    std::cout << "MIN = " << bd << std::endl;
    std::cout << "d_e= " << d_e() << std::endl;
#endif

#ifdef CORE_DEBUG_BOUND
  // Some statistics about which one is/are the winner[s].
  computeBoundCallsCounter++;
  int number_of_winners = 0;
  std::cerr << " New contest " << std::endl;
  if (bd == bfmsskBd) {
    BFMSS_counter++;
    number_of_winners++;
    std::cerr << " BFMSS is the winner " << std::endl;
  }
  if (bd == measureBd) {
    Measure_counter++;
    number_of_winners++;
    std::cerr << " measureBd is the winner " << std::endl;
  }
  /*  if (bd == cauchyBd) {
      Cauchy_counter++;
      number_of_winners++;
      std::cerr << " cauchyBd is the winner " << std::endl;
    }
   */
  if (bd == ourBd) {
    LiYap_counter++;
    number_of_winners++;
    std::cerr << " ourBd is the winner " << std::endl;
  }

  assert(number_of_winners >= 1);

  if (number_of_winners == 1) {
    if (bd == bfmsskBd) {
      BFMSS_only_counter++;
      std::cerr << " BFMSSBd is the only winner " << std::endl;
    } else if (bd == measureBd) {
      Measure_only_counter++;
      std::cerr << " measureBd is the only winner " << std::endl;
    }
    /* else if (bd == cauchyBd) {
      Cauchy_only_counter++;
      std::cerr << " cauchyBd is the only winner " << std::endl;
    } */
    else if (bd == ourBd) {
      LiYap_only_counter++;
      std::cerr << " ourBd is the only winner " << std::endl;
    }
  }
#endif

  return bd;
}//computeBound()
示例#15
0
// This only copies the current information of the argument e to
// 	*this ExprRep.
void ExprRep::reduceTo(const ExprRep *e) {
  if (e->appComputed()) {
    appValue() = e->appValue();
    appComputed() = true;
    flagsComputed() = true;
    knownPrecision() = e->knownPrecision();
#ifdef CORE_DEBUG
    relPrecision() = e->relPrecision();
    absPrecision() = e->absPrecision();
    numNodes() = e->numNodes();
#endif

  }
  d_e() = e->d_e();
  //visited() = e->visited();
  sign() = e->sign();
  uMSB() = e->uMSB();
  lMSB() = e->lMSB();
  // length() = e->length(); 	// fixed? original = 1
  measure() = e->measure();

  // BFMSS[2,5] bound.
  u25() = e->u25();
  l25() = e->l25();
  v2p() = e->v2p();
  v2m() = e->v2m();
  v5p() = e->v5p();
  v5m() = e->v5m();

  high() = e->high();
  low() = e->low();		// fixed? original = 0
  lc() = e->lc();
  tc() = e->tc();

  // Chee (Mar 23, 2004), Notes on ratFlag():
  // ===============================================================
  // For more information on the use of this flag, see progs/pentagon.
  // This is an integer valued member of the NodeInfo class.
  // Its value is used to determine whether
  // we can ``reduce'' an Expression to a single node containing
  // a BigRat value.  This reduction is done if the global variable
  // rationalReduceFlag=true.  The default value is false.
  // This is the intepretation of ratFlag:
  //	ratFlag < 0 means irrational
  //	ratFlag = 0 means not initialized
  //	ratFlag > 0 means rational
  // Currently, ratFlag>0 is an upper bound on the size of the expression,
  // since we recursively compute
  // 		ratFlag(v) = ratFlag(v.lchild)+ratFlag(v.rchild) + 1.
  // PROPOSAL: if ratFlag() > RAT_REDUCE_THRESHHOLD
  // 	then we automatically do a reduction.  We must determine
  // 	an empirical value for RAT_REDUCE_THRESHOLD

  if (rationalReduceFlag) {
    ratFlag() = e->ratFlag();

    if (e->ratFlag() > 0 && e->ratValue() != NULL) {
      ratFlag() ++;
      if (ratValue() == NULL)
        ratValue() = new BigRat(*(e->ratValue()));
      else
        *(ratValue()) = *(e->ratValue());
    } else
      ratFlag() = -1;
  }
}
示例#16
0
/* Obtain a sequence of random numbers.  */
static void
randget_lc (gmp_randstate_t rstate, mp_ptr rp, unsigned long int nbits)
{
  unsigned long int rbitpos;
  int chunk_nbits;
  mp_ptr tp;
  mp_size_t tn;
  gmp_rand_lc_struct *p;
  TMP_DECL;

  p = (gmp_rand_lc_struct *) RNG_STATE (rstate);

  TMP_MARK;

  chunk_nbits = p->_mp_m2exp / 2;
  tn = BITS_TO_LIMBS (chunk_nbits);

  tp = (mp_ptr) TMP_ALLOC (tn * BYTES_PER_MP_LIMB);

  rbitpos = 0;
  while (rbitpos + chunk_nbits <= nbits)
    {
      mp_ptr r2p = rp + rbitpos / GMP_NUMB_BITS;

      if (rbitpos % GMP_NUMB_BITS != 0)
	{
	  mp_limb_t savelimb, rcy;
	  /* Target of new chunk is not bit aligned.  Use temp space
	     and align things by shifting it up.  */
	  lc (tp, rstate);
	  savelimb = r2p[0];
	  rcy = mpn_lshift (r2p, tp, tn, rbitpos % GMP_NUMB_BITS);
	  r2p[0] |= savelimb;
	  /* bogus */
	  if ((chunk_nbits % GMP_NUMB_BITS + rbitpos % GMP_NUMB_BITS)
	      > GMP_NUMB_BITS)
	    r2p[tn] = rcy;
	}
      else
	{
	  /* Target of new chunk is bit aligned.  Let `lc' put bits
	     directly into our target variable.  */
	  lc (r2p, rstate);
	}
      rbitpos += chunk_nbits;
    }

  /* Handle last [0..chunk_nbits) bits.  */
  if (rbitpos != nbits)
    {
      mp_ptr r2p = rp + rbitpos / GMP_NUMB_BITS;
      int last_nbits = nbits - rbitpos;
      tn = BITS_TO_LIMBS (last_nbits);
      lc (tp, rstate);
      if (rbitpos % GMP_NUMB_BITS != 0)
	{
	  mp_limb_t savelimb, rcy;
	  /* Target of new chunk is not bit aligned.  Use temp space
	     and align things by shifting it up.  */
	  savelimb = r2p[0];
	  rcy = mpn_lshift (r2p, tp, tn, rbitpos % GMP_NUMB_BITS);
	  r2p[0] |= savelimb;
	  if (rbitpos + tn * GMP_NUMB_BITS - rbitpos % GMP_NUMB_BITS < nbits)
	    r2p[tn] = rcy;
	}
      else
	{
	  MPN_COPY (r2p, tp, tn);
	}
      /* Mask off top bits if needed.  */
      if (nbits % GMP_NUMB_BITS != 0)
	rp[nbits / GMP_NUMB_BITS]
	  &= ~(~CNST_LIMB (0) << nbits % GMP_NUMB_BITS);
    }

  TMP_FREE;
}
// When a command is received, if it is a Gcode, dispatch it as an object via an event
void GcodeDispatch::on_console_line_received(void *line)
{
    SerialMessage new_message = *static_cast<SerialMessage *>(line);
    string possible_command = new_message.message;

    int ln = 0;
    int cs = 0;

    // just reply ok to empty lines
    if(possible_command.empty()) {
        new_message.stream->printf("ok\r\n");
        return;
    }

try_again:

    char first_char = possible_command[0];
    unsigned int n;

    if(first_char == '$') {
        // ignore as simpleshell will handle it
        return;

    }else if(islower(first_char)) {
        // ignore all lowercase as they are simpleshell commands
        return;
    }

    if ( first_char == 'G' || first_char == 'M' || first_char == 'T' || first_char == 'S' || first_char == 'N' ) {

        //Get linenumber
        if ( first_char == 'N' ) {
            Gcode full_line = Gcode(possible_command, new_message.stream, false);
            ln = (int) full_line.get_value('N');
            int chksum = (int) full_line.get_value('*');

            //Catch message if it is M110: Set Current Line Number
            if ( full_line.has_m ) {
                if ( full_line.m == 110 ) {
                    currentline = ln;
                    new_message.stream->printf("ok\r\n");
                    return;
                }
            }

            //Strip checksum value from possible_command
            size_t chkpos = possible_command.find_first_of("*");
            possible_command = possible_command.substr(0, chkpos);
            //Calculate checksum
            if ( chkpos != string::npos ) {
                for (auto c = possible_command.cbegin(); *c != '*' && c != possible_command.cend(); c++)
                    cs = cs ^ *c;
                cs &= 0xff;  // Defensive programming...
                cs -= chksum;
            }
            //Strip line number value from possible_command
            size_t lnsize = possible_command.find_first_not_of("N0123456789.,- ");
            possible_command = possible_command.substr(lnsize);

        } else {
            //Assume checks succeeded
            cs = 0x00;
            ln = currentline + 1;
        }

        //Remove comments
        size_t comment = possible_command.find_first_of(";(");
        if( comment != string::npos ) {
            possible_command = possible_command.substr(0, comment);
        }

        //If checksum passes then process message, else request resend
        int nextline = currentline + 1;
        if( cs == 0x00 && ln == nextline ) {
            if( first_char == 'N' ) {
                currentline = nextline;
            }

            while(possible_command.size() > 0) {
                // assumes G or M are always the first on the line
                size_t nextcmd = possible_command.find_first_of("GM", 2);
                string single_command;
                if(nextcmd == string::npos) {
                    single_command = possible_command;
                    possible_command = "";
                } else {
                    single_command = possible_command.substr(0, nextcmd);
                    possible_command = possible_command.substr(nextcmd);
                }


                if(!uploading || upload_stream != new_message.stream) {
                    // Prepare gcode for dispatch
                    Gcode *gcode = new Gcode(single_command, new_message.stream);

                    if(THEKERNEL->is_halted()) {
                        // we ignore all commands until M999, unless it is in the exceptions list (like M105 get temp)
                        if(gcode->has_m && gcode->m == 999) {
                            if(THEKERNEL->is_halted()) {
                                THEKERNEL->call_event(ON_HALT, (void *)1); // clears on_halt
                                new_message.stream->printf("WARNING: After HALT you should HOME as position is currently unknown\n");
                            }
                            new_message.stream->printf("ok\n");
                            delete gcode;
                            continue;

                        }else if(!is_allowed_mcode(gcode->m)) {
                            // ignore everything, return error string to host
                            if(THEKERNEL->is_grbl_mode()) {
                                new_message.stream->printf("error:Alarm lock\n");

                            }else{
                                new_message.stream->printf("!!\r\n");
                            }
                            delete gcode;
                            continue;
                        }
                    }

                    if(gcode->has_g) {
                        if(gcode->g == 53) { // G53 makes next movement command use machine coordinates
                            // this is ugly to implement as there may or may not be a G0/G1 on the same line
                            // valid version seem to include G53 G0 X1 Y2 Z3 G53 X1 Y2
                            if(possible_command.empty()) {
                                // use last gcode G1 or G0 if none on the line, and pass through as if it was a G0/G1
                                // TODO it is really an error if the last is not G0 thru G3
                                if(modal_group_1 > 3) {
                                    delete gcode;
                                    new_message.stream->printf("ok - Invalid G53\r\n");
                                    return;
                                }
                                // use last G0 or G1
                                gcode->g= modal_group_1;

                            }else{
                                delete gcode;
                                // extract next G0/G1 from the rest of the line, ignore if it is not one of these
                                gcode = new Gcode(possible_command, new_message.stream);
                                possible_command= "";
                                if(!gcode->has_g || gcode->g > 1) {
                                    // not G0 or G1 so ignore it as it is invalid
                                    delete gcode;
                                    new_message.stream->printf("ok - Invalid G53\r\n");
                                    return;
                                }
                            }
                            // makes it handle the parameters as a machine position
                            THEROBOT->next_command_is_MCS= true;

                        }

                        // remember last modal group 1 code
                        if(gcode->g < 4) {
                            modal_group_1= gcode->g;
                        }
                    }

                    if(gcode->has_m) {
                        switch (gcode->m) {
                            case 28: // start upload command
                                delete gcode;

                                this->upload_filename = "/sd/" + single_command.substr(4); // rest of line is filename
                                // open file
                                upload_fd = fopen(this->upload_filename.c_str(), "w");
                                if(upload_fd != NULL) {
                                    this->uploading = true;
                                    new_message.stream->printf("Writing to file: %s\r\nok\r\n", this->upload_filename.c_str());
                                } else {
                                    new_message.stream->printf("open failed, File: %s.\r\nok\r\n", this->upload_filename.c_str());
                                }

                                // only save stuff from this stream
                                upload_stream= new_message.stream;

                                //printf("Start Uploading file: %s, %p\n", upload_filename.c_str(), upload_fd);
                                continue;

                            case 30: // end of program
                                if(!THEKERNEL->is_grbl_mode()) break; // Special case M30 as it is also delete sd card file so only do this if in grbl mode
                                // fall through to M2
                            case 2:
                                {
                                    modal_group_1= 1; // set to G1
                                    // issue M5 and M9 in case spindle and coolant are being used
                                    Gcode gc1("M5", &StreamOutput::NullStream);
                                    THEKERNEL->call_event(ON_GCODE_RECEIVED, &gc1);
                                    Gcode gc2("M9", &StreamOutput::NullStream);
                                    THEKERNEL->call_event(ON_GCODE_RECEIVED, &gc2);
                                }
                                break;

                            case 112: // emergency stop, do the best we can with this
                                // this is also handled out-of-band (it is now with ^X in the serial driver)
                                // disables heaters and motors, ignores further incoming Gcode and clears block queue
                                THEKERNEL->call_event(ON_HALT, nullptr);
                                THEKERNEL->streams->printf("ok Emergency Stop Requested - reset or M999 required to exit HALT state\r\n");
                                delete gcode;
                                return;

                            case 117: // M117 is a special non compliant Gcode as it allows arbitrary text on the line following the command
                            {    // concatenate the command again and send to panel if enabled
                                string str= single_command.substr(4) + possible_command;
                                PublicData::set_value( panel_checksum, panel_display_message_checksum, &str );
                                delete gcode;
                                new_message.stream->printf("ok\r\n");
                                return;
                            }

                            case 1000: // M1000 is a special command that will pass thru the raw lowercased command to the simpleshell (for hosts that do not allow such things)
                            {
                                // reconstruct entire command line again
                                string str= single_command.substr(5) + possible_command;
                                while(is_whitespace(str.front())){ str= str.substr(1); } // strip leading whitespace

                                delete gcode;

                                if(str.empty()) {
                                    SimpleShell::parse_command("help", "", new_message.stream);

                                }else{
                                    string args= lc(str);
                                    string cmd = shift_parameter(args);
                                    // find command and execute it
                                    if(!SimpleShell::parse_command(cmd.c_str(), args, new_message.stream)) {
                                        new_message.stream->printf("Command not found: %s\n", cmd.c_str());
                                    }
                                }

                                new_message.stream->printf("ok\r\n");
                                return;
                            }

                            case 500: // M500 save volatile settings to config-override
                                THEKERNEL->conveyor->wait_for_idle(); //just to be safe as it can take a while to run
                                //remove(THEKERNEL->config_override_filename()); // seems to cause a hang every now and then
                                __disable_irq();
                                {
                                    FileStream fs(THEKERNEL->config_override_filename());
                                    fs.printf("; DO NOT EDIT THIS FILE\n");
                                    // this also will truncate the existing file instead of deleting it
                                }
                                // replace stream with one that writes to config-override file
                                gcode->stream = new AppendFileStream(THEKERNEL->config_override_filename());
                                // dispatch the M500 here so we can free up the stream when done
                                THEKERNEL->call_event(ON_GCODE_RECEIVED, gcode );
                                delete gcode->stream;
                                delete gcode;
                                __enable_irq();
                                new_message.stream->printf("Settings Stored to %s\r\nok\r\n", THEKERNEL->config_override_filename());
                                continue;

                            case 501: // load config override
                            case 504: // save to specific config override file
                                {
                                    string arg= get_arguments(single_command + possible_command); // rest of line is filename
                                    if(arg.empty()) arg= "/sd/config-override";
                                    else arg= "/sd/config-override." + arg;
                                    //new_message.stream->printf("args: <%s>\n", arg.c_str());
                                    SimpleShell::parse_command((gcode->m == 501) ? "load_command" : "save_command", arg, new_message.stream);
                                }
                                delete gcode;
                                new_message.stream->printf("ok\r\n");
                                return;

                            case 502: // M502 deletes config-override so everything defaults to what is in config
                                remove(THEKERNEL->config_override_filename());
                                delete gcode;
                                new_message.stream->printf("config override file deleted %s, reboot needed\r\nok\r\n", THEKERNEL->config_override_filename());
                                continue;

                            case 503: { // M503 display live settings and indicates if there is an override file
                                FILE *fd = fopen(THEKERNEL->config_override_filename(), "r");
                                if(fd != NULL) {
                                    fclose(fd);
                                    new_message.stream->printf("; config override present: %s\n",  THEKERNEL->config_override_filename());

                                } else {
                                    new_message.stream->printf("; No config override\n");
                                }
                                gcode->add_nl= true;
                                break; // fall through to process by modules
                            }

                        }
                    }

                    //printf("dispatch %p: '%s' G%d M%d...", gcode, gcode->command.c_str(), gcode->g, gcode->m);
                    //Dispatch message!
                    THEKERNEL->call_event(ON_GCODE_RECEIVED, gcode );

                    if (gcode->is_error) {
                        // report error
                        if(THEKERNEL->is_grbl_mode()) {
                            new_message.stream->printf("error: ");
                        }else{
                            new_message.stream->printf("Error: ");
                        }

                        if(!gcode->txt_after_ok.empty()) {
                            new_message.stream->printf("%s\r\n", gcode->txt_after_ok.c_str());
                            gcode->txt_after_ok.clear();

                        }else{
                            new_message.stream->printf("unknown\r\n");
                        }

                        // we cannot continue safely after an error so we enter HALT state
                        new_message.stream->printf("Entering Alarm/Halt state\n");
                        THEKERNEL->call_event(ON_HALT, nullptr);

                    }else{

                        if(gcode->add_nl)
                            new_message.stream->printf("\r\n");

                        if(!gcode->txt_after_ok.empty()) {
                            new_message.stream->printf("ok %s\r\n", gcode->txt_after_ok.c_str());
                            gcode->txt_after_ok.clear();

                        } else {
                            if(THEKERNEL->is_ok_per_line() || THEKERNEL->is_grbl_mode()) {
                                // only send ok once per line if this is a multi g code line send ok on the last one
                                if(possible_command.empty())
                                    new_message.stream->printf("ok\r\n");
                            } else {
                                // maybe should do the above for all hosts?
                                new_message.stream->printf("ok\r\n");
                            }
                        }
                    }

                    delete gcode;

                } else {
                    // we are uploading and it is the upload stream so so save it
                    if(single_command.substr(0, 3) == "M29") {
                        // done uploading, close file
                        fclose(upload_fd);
                        upload_fd = NULL;
                        uploading = false;
                        upload_filename.clear();
                        upload_stream= nullptr;
                        new_message.stream->printf("Done saving file.\r\nok\r\n");
                        continue;
                    }

                    if(upload_fd == NULL) {
                        // error detected writing to file so discard everything until it stops
                        new_message.stream->printf("ok\r\n");
                        continue;
                    }

                    single_command.append("\n");
                    static int cnt = 0;
                    if(fwrite(single_command.c_str(), 1, single_command.size(), upload_fd) != single_command.size()) {
                        // error writing to file
                        new_message.stream->printf("Error:error writing to file.\r\n");
                        fclose(upload_fd);
                        upload_fd = NULL;
                        continue;

                    } else {
                        cnt += single_command.size();
                        if (cnt > 400) {
                            // HACK ALERT to get around fwrite corruption close and re open for append
                            fclose(upload_fd);
                            upload_fd = fopen(upload_filename.c_str(), "a");
                            cnt = 0;
                        }
                        new_message.stream->printf("ok\r\n");
                        //printf("uploading file write ok\n");
                    }
                }
            }

        } else {
            //Request resend
            new_message.stream->printf("rs N%d\r\n", nextline);
        }

    } else if( (n=possible_command.find_first_of("XYZF")) == 0 || (first_char == ' ' && n != string::npos) ) {
        // handle pycam syntax, use last modal group 1 command and resubmit if an X Y Z or F is found on its own line
        char buf[6];
        snprintf(buf, sizeof(buf), "G%d ", modal_group_1);
        possible_command.insert(0, buf);
        goto try_again;

        // Ignore comments and blank lines
    } else if ( first_char == ';' || first_char == '(' || first_char == ' ' || first_char == '\n' || first_char == '\r' ) {
        new_message.stream->printf("ok\r\n");
    }
}
示例#18
0
文件: fullcalib.cpp 项目: emblem/aril
bool photometric_calibration(CalibModel &model, CvCapture *capture, 
			     int nbImages, bool cache)
{

  if (cache) model.map.load();

  const char *win = "BazAR";

  IplImage*gray=0;

  cvNamedWindow(win, CV_WINDOW_AUTOSIZE);
  cvNamedWindow("LightMap", CV_WINDOW_AUTOSIZE);

  IplImage* frame = 0;
  IplImage* display=cvCloneImage(cvQueryFrame(capture));

  int nbHomography =0;
  LightCollector lc(model.map.reflc);
  IplImage *lightmap = cvCreateImage(cvGetSize(model.map.map.getIm()), IPL_DEPTH_8U, 
				     lc.avgChannels);
  while (1)
    {
      // acquire image
      frame = cvQueryFrame( capture );
      /*
	if (frame) cvReleaseImage(&frame);
	frame = cvLoadImage("model.bmp",1);
      */
      if( !frame )
	break;

      // convert it to gray levels, if required
      if (frame->nChannels >1) {
	if( !gray ) 
	  gray = cvCreateImage( cvGetSize(frame), IPL_DEPTH_8U, 1 );
	cvCvtColor(frame, gray, CV_RGB2GRAY);
      } else {
	gray = frame;
      }

      // run the detector
      if (model.detector.detect(gray)) {
	// 2d homography found
	nbHomography++;

	// Computes 3D pose and surface normal
	model.augm.Clear();
	add_detected_homography(model.detector, model.augm);
	model.augm.Accomodate(4, 1e-4);
	CvMat *mat = model.augm.GetObjectToWorld();
	float normal[3];
	for (int j=0;j<3;j++) normal[j] = cvGet2D(mat, j, 2).val[0];
	cvReleaseMat(&mat);

	// average pixels over triangles
	lc.averageImage(frame,model.detector.H);

	// add observations
	if (!model.map.isReady())
	  model.map.addNormal(normal, lc, 0);

	if (!model.map.isReady() && nbHomography >= nbImages) {
	  if (model.map.computeLightParams()) {
	    model.map.save();
	    const float *gain = model.map.getGain(0);
	    const float *bias = model.map.getBias(0);
	    cout << "Gain: " << gain[0] << ", " << gain[1] << ", " << gain[2] << endl;
	    cout << "Bias: " << bias[0] << ", " << bias[1] << ", " << bias[2] << endl;
	  }
	} 
      } 
		
      if (model.map.isReady()) {
	double min, max;
	IplImage *map = model.map.map.getIm();
	cvSetImageCOI(map, 2);
	cvMinMaxLoc(map, &min, &max);
	cvSetImageCOI(map, 0);
	assert(map->nChannels == lightmap->nChannels);
	cvConvertScale(map, lightmap, 128, 0);
	cvShowImage("LightMap", lightmap);
	augment_scene(model, frame, display);
      } else {
	cvCopy(frame,display);
	if (model.detector.object_is_detected)
	  lc.drawGrid(display, model.detector.H);
      }

      cvShowImage(win, display);

      int k=cvWaitKey(10);
      if (k=='q' || k== 27)
	break;
    }

  cvReleaseImage(&lightmap);
  cvReleaseImage(&display);
  if (frame->nChannels > 1)
    cvReleaseImage(&gray);
  return 0;
}
示例#19
0
文件: randraw.c 项目: mahdiz/mpclib
void
_gmp_rand (mp_ptr rp, gmp_randstate_t rstate, unsigned long int nbits)
{
  mp_size_t rn;			/* Size of R.  */

  rn = (nbits + GMP_NUMB_BITS - 1) / GMP_NUMB_BITS;

  switch (rstate->_mp_alg)
    {
    case GMP_RAND_ALG_LC:
      {
	unsigned long int rbitpos;
	int chunk_nbits;
	mp_ptr tp;
	mp_size_t tn;
	TMP_DECL (lcmark);

	TMP_MARK (lcmark);

	chunk_nbits = rstate->_mp_algdata._mp_lc->_mp_m2exp / 2;
	tn = (chunk_nbits + GMP_NUMB_BITS - 1) / GMP_NUMB_BITS;

	tp = (mp_ptr) TMP_ALLOC (tn * BYTES_PER_MP_LIMB);

	rbitpos = 0;
	while (rbitpos + chunk_nbits <= nbits)
	  {
	    mp_ptr r2p = rp + rbitpos / GMP_NUMB_BITS;

	    if (rbitpos % GMP_NUMB_BITS != 0)
	      {
		mp_limb_t savelimb, rcy;
		/* Target of of new chunk is not bit aligned.  Use temp space
		   and align things by shifting it up.  */
		lc (tp, rstate);
		savelimb = r2p[0];
		rcy = mpn_lshift (r2p, tp, tn, rbitpos % GMP_NUMB_BITS);
		r2p[0] |= savelimb;
/* bogus */	if ((chunk_nbits % GMP_NUMB_BITS + rbitpos % GMP_NUMB_BITS)
		    > GMP_NUMB_BITS)
		  r2p[tn] = rcy;
	      }
	    else
	      {
		/* Target of of new chunk is bit aligned.  Let `lc' put bits
		   directly into our target variable.  */
		lc (r2p, rstate);
	      }
	    rbitpos += chunk_nbits;
	  }

	/* Handle last [0..chunk_nbits) bits.  */
	if (rbitpos != nbits)
	  {
	    mp_ptr r2p = rp + rbitpos / GMP_NUMB_BITS;
	    int last_nbits = nbits - rbitpos;
	    tn = (last_nbits + GMP_NUMB_BITS - 1) / GMP_NUMB_BITS;
	    lc (tp, rstate);
	    if (rbitpos % GMP_NUMB_BITS != 0)
	      {
		mp_limb_t savelimb, rcy;
		/* Target of of new chunk is not bit aligned.  Use temp space
		   and align things by shifting it up.  */
		savelimb = r2p[0];
		rcy = mpn_lshift (r2p, tp, tn, rbitpos % GMP_NUMB_BITS);
		r2p[0] |= savelimb;
		if (rbitpos + tn * GMP_NUMB_BITS - rbitpos % GMP_NUMB_BITS < nbits)
		  r2p[tn] = rcy;
	      }
	    else
	      {
		MPN_COPY (r2p, tp, tn);
	      }
	    /* Mask off top bits if needed.  */
	    if (nbits % GMP_NUMB_BITS != 0)
	      rp[nbits / GMP_NUMB_BITS]
		&= ~ ((~(mp_limb_t) 0) << nbits % GMP_NUMB_BITS);
	  }

	TMP_FREE (lcmark);
	break;
      }

    default:
      ASSERT (0);
      break;
    }
}
示例#20
0
int main(int argc, char **argv) {
	bool die(false);
	string filename("snapshot");
	string suffix(".png");
	int i_snap(0),iter(0);
	
	Mat depthMat(Size(640,480),CV_16UC1);
	Mat depthf  (Size(640,480),CV_8UC1);
	Mat rgbMat(Size(640,480),CV_8UC3,Scalar(0));
	Mat ownMat(Size(640,480),CV_8UC3,Scalar(0));
	
	Freenect::Freenect<MyFreenectDevice> freenect;
	MyFreenectDevice& device = freenect.createDevice(0);
	
	device.setTiltDegrees(10.0);
	
	bool registered  = false;
	Mat blobMaskOutput = Mat::zeros(Size(640,480),CV_8UC1),outC;
	Point midBlob;
	
	int startX = 200, sizeX = 180, num_x_reps = 18, num_y_reps = 48;
	double	height_over_num_y_reps = 480/num_y_reps,
			width_over_num_x_reps = sizeX/num_x_reps;
	
	
	vector<double> _d(num_x_reps * num_y_reps); //the descriptor
	Mat descriptorMat(_d);

//	CvNormalBayesClassifier classifier;	//doesnt work
	CvKNearest classifier;
//	CvSVM classifier;	//doesnt work
//	CvBoost classifier;	//only good for 2 classes
//	CvDTree classifier;
	
	
	vector<vector<double> > training_data;
	vector<int>				label_data;
	PCA pca;
	Mat labelMat, dataMat; 
	vector<float> label_counts(4);
	
	bool trained = false, loaded = false;
 	
	device.startVideo();
	device.startDepth();
    while (!die) {
    	device.getVideo(rgbMat);
    	device.getDepth(depthMat);
//        cv::imshow("rgb", rgbMat);
    	depthMat.convertTo(depthf, CV_8UC1, 255.0/2048.0);
				
        cv::imshow("depth",depthf);
		
		//interpolation & inpainting
		{
			Mat _tmp,_tmp1; // = (depthMat - 400.0);          //minimum observed value is ~440. so shift a bit
			Mat(depthMat - 400.0).convertTo(_tmp1,CV_64FC1);
			_tmp.setTo(Scalar(2048), depthMat > 750.0);   //cut off at 600 to create a "box" where the user interacts
//			_tmp.convertTo(depthf, CV_8UC1, 255.0/1648.0);  //values are 0-2048 (11bit), account for -400 = 1648

			//quadratic interpolation
//			cv::pow(_tmp,2.0,_tmp1);
//			_tmp1 = _tmp1 * 4.0;
			
//			try {
//				cv:log(_tmp,_tmp1);
//			}
//			catch (cv::Exception e) {
//				cerr << e.what() << endl;
//				exit(0);
//			}
			
			Point minLoc; double minval,maxval;
			minMaxLoc(_tmp1, &minval, &maxval, NULL, NULL);
			_tmp1.convertTo(depthf, CV_8UC1, 255.0/maxval);
			
			Mat small_depthf; resize(depthf,small_depthf,Size(),0.2,0.2);
			cv::inpaint(small_depthf,(small_depthf == 255),_tmp1,5.0,INPAINT_TELEA);
			
			resize(_tmp1, _tmp, depthf.size());
			_tmp.copyTo(depthf, (depthf == 255));
		}

		{
//			Mat smallDepth = depthf; //cv::resize(depthf,smallDepth,Size(),0.5,0.5);
//			Mat edges; //Laplacian(smallDepth, edges, -1, 7, 1.0);
//			Sobel(smallDepth, edges, -1, 1, 1, 7);
			//medianBlur(edges, edges, 11);
//			for (int x=0; x < edges.cols; x+=20) {
//				for (int y=0; y < edges.rows; y+=20) {
//					//int nz = countNonZero(edges(Range(y,MIN(y+20,edges.rows-1)),Range(x,MIN(x+20,edges.cols-1))));
//					Mat _i = edges(Range(y,MIN(y+20,edges.rows-1)),Range(x,MIN(x+20,edges.cols-1)));
//					medianBlur(_i, _i, 7);
//					//rectangle(edges, Point(x,y), Point(x+20,y+20), Scalar(nz), CV_FILLED);
//				}
//			}
		
//			imshow("edges", edges);
		}
				
		cvtColor(depthf, outC, CV_GRAY2BGR);
		
		Mat blobMaskInput = depthf < 120; //anything not white is "real" depth, TODO: inpainting invalid data
		vector<Point> ctr,ctr2;

		//closest point to the camera
		Point minLoc; double minval,maxval;
		minMaxLoc(depthf, &minval, &maxval, &minLoc, NULL, blobMaskInput);
		circle(outC, minLoc, 5, Scalar(0,255,0), 3);
		
		blobMaskInput = depthf < (minval + 18);
		
		Scalar blb = refineSegments(Mat(),blobMaskInput,blobMaskOutput,ctr,ctr2,midBlob); //find contours in the foreground, choose biggest
//		if (blobMaskOutput.data != NULL) {
//			imshow("first", blobMaskOutput);
//		}
		/////// blb :
		//blb[0] = x, blb[1] = y, blb[2] = 1st blob size, blb[3] = 2nd blob size.
		

		
		if(blb[0]>=0 && blb[2] > 500) { //1st blob detected, and is big enough
			//cvtColor(depthf, outC, CV_GRAY2BGR);
			
			Scalar mn,stdv;
			meanStdDev(depthf,mn,stdv,blobMaskInput);
			
			//cout << "min: " << minval << ", max: " << maxval << ", mean: " << mn[0] << endl;
			
			//now refining blob by looking at the mean depth value it has...
			blobMaskInput = depthf < (mn[0] + stdv[0]);
			
			//(very simple) bias with hand color
			{
				Mat hsv; cvtColor(rgbMat, hsv, CV_RGB2HSV);
				Mat _col_p(hsv.size(),CV_32FC1);
				int jump = 5;
				for (int x=0; x < hsv.cols; x+=jump) {
					for (int y=0; y < hsv.rows; y+=jump) {
						Mat _i = hsv(Range(y,MIN(y+jump,hsv.rows-1)),Range(x,MIN(x+jump,hsv.cols-1)));
						Scalar hsv_mean = mean(_i);
						Vec2i u; u[0] = hsv_mean[0]; u[1] = hsv_mean[1];
						Vec2i v; v[0] = 120; v[1] = 110;
						rectangle(_col_p, Point(x,y), Point(x+jump,y+jump), Scalar(1.0-MIN(norm(u-v)/125.0,1.0)), CV_FILLED);
					}
				}
				//			hsv = hsv - Scalar(0,0,255);
				Mat _t = (Mat_<double>(2,3) << 1, 0, 15,    0, 1, -20);
				Mat col_p(_col_p.size(),CV_32FC1);
				warpAffine(_col_p, col_p, _t, col_p.size());
				GaussianBlur(col_p, col_p, Size(11.0,11.0), 2.5);
				imshow("hand color",col_p);
				//			imshow("rgb",rgbMat);
				Mat blobMaskInput_32FC1; blobMaskInput.convertTo(blobMaskInput_32FC1, CV_32FC1, 1.0/255.0);
				blobMaskInput_32FC1 = blobMaskInput_32FC1.mul(col_p, 1.0);
				blobMaskInput_32FC1.convertTo(blobMaskInput, CV_8UC1, 255.0);
				
				blobMaskInput = blobMaskInput > 128;
				
				imshow("blob bias", blobMaskInput);
			}
			
			
			blb = refineSegments(Mat(),blobMaskInput,blobMaskOutput,ctr,ctr2,midBlob);
			
			imshow("blob", blobMaskOutput);
			
			if(blb[0] >= 0 && blb[2] > 300) {
				//draw contour
				Scalar color(0,0,255);
				for (int idx=0; idx<ctr.size()-1; idx++)
					line(outC, ctr[idx], ctr[idx+1], color, 1);
				line(outC, ctr[ctr.size()-1], ctr[0], color, 1);
				
				if(ctr2.size() > 0) {	//second blob detected
					Scalar color2(255,0,255);
					for (int idx=0; idx<ctr2.size()-1; idx++)
						line(outC, ctr2[idx], ctr2[idx+1], color2, 2);
					line(outC, ctr2[ctr2.size()-1], ctr2[0], color2, 2);
				}
								
				//blob center
				circle(outC, Point(blb[0],blb[1]), 50, Scalar(255,0,0), 3);
				
				{
					Mat hsv; cvtColor(rgbMat, hsv, CV_RGB2HSV);
					Scalar hsv_mean,hsv_stddev; meanStdDev(hsv, hsv_mean, hsv_stddev, blobMaskOutput);
					stringstream ss; ss << hsv_mean[0] << "," << hsv_mean[1] << "," << hsv_mean[2];
					putText(outC, ss.str(), Point(blb[0],blb[1]), CV_FONT_HERSHEY_PLAIN, 1.0, Scalar(0,255,255));
				}
				
				
				Mat blobDepth,blobEdge; 
				depthf.copyTo(blobDepth,blobMaskOutput);
				Laplacian(blobDepth, blobEdge, 8);
//				equalizeHist(blobEdge, blobEdge);//just for visualization
				
				Mat logPolar(depthf.size(),CV_8UC1);
				cvLogPolar(&((IplImage)blobEdge), &((IplImage)logPolar), Point2f(blb[0],blb[1]), 80.0);
				
//				for (int i=0; i<num_x_reps+1; i++) {
//					//verical lines
//					line(logPolar, Point(startX+i*width_over_num_x_reps, 0), Point(startX+i*width_over_num_x_reps,479), Scalar(255), 1);
//				}
//				for(int i=0; i<num_y_reps+1; i++) {			
//					//horizontal
//					line(logPolar, Point(startX, i*height_over_num_y_reps), Point(startX+sizeX,i*height_over_num_y_reps), Scalar(255), 1);
//				}
				
				double total = 0.0;
				
				//histogram
				for (int i=0; i<num_x_reps; i++) {
					for(int j=0; j<num_y_reps; j++) {
						Mat part = logPolar(
										Range(j*height_over_num_y_reps,(j+1)*height_over_num_y_reps),
										 Range(startX+i*width_over_num_x_reps,startX+(i+1)*width_over_num_x_reps)
										 );
						
//						int count = countNonZero(part); //TODO: use calcHist
//						_d[i*num_x_reps + j] = count;

						Scalar mn = mean(part);						
//						part.setTo(Scalar(mn[0])); //for debug: show the value in the image
						_d[i*num_x_reps + j] = mn[0];
						
						
						total += mn[0];
					}
				}
				
				descriptorMat = descriptorMat / total;
				
				/*
				Mat images[1] = {logPolar(Range(0,30),Range(0,30))};
				int nimages = 1;
				int channels[1] = {0};
				int dims = 1;
				float range_0[]={0,256};
				float* ranges[] = { range_0 };
				int histSize[1] = { 5 };
				
				calcHist(, <#int nimages#>, <#const int *channels#>, <#const Mat mask#>, <#MatND hist#>, <#int dims#>, <#const int *histSize#>, <#const float **ranges#>, <#bool uniform#>, <#bool accumulate#>)
				*/
				
//				Mat _tmp(logPolar.size(),CV_8UC1);
//				cvLogPolar(&((IplImage)logPolar), &((IplImage)_tmp),Point2f(blb[0],blb[1]), 80.0, CV_WARP_INVERSE_MAP);
//				imshow("descriptor", _tmp);
//				imshow("logpolar", logPolar);
			}
		}
		
		if(trained) {
			Mat results(1,1,CV_32FC1);
			Mat samples; Mat(Mat(_d).t()).convertTo(samples,CV_32FC1);
			
			Mat samplesAfterPCA = samples; //pca.project(samples);
			
			classifier.find_nearest(&((CvMat)samplesAfterPCA), 1, &((CvMat)results));
//			((float*)results.data)[0] = classifier.predict(&((CvMat)samples))->value;
			
			Mat lc(label_counts); lc *= 0.9;
			
//			label_counts[(int)((float*)results.data)[0]] *= 0.9;
			label_counts[(int)((float*)results.data)[0]] += 0.1;
			Point maxLoc;
			minMaxLoc(lc, NULL, NULL, NULL, &maxLoc);
			int res = maxLoc.y;
			
			stringstream ss; ss << "prediction: ";
			if (res == LABEL_OPEN) {
				ss << "Open hand";
			}
			if (res == LABEL_FIST) {
				ss << "Fist";
			}
			if (res == LABEL_THUMB) {
				ss << "Thumb";
			}
			if (res == LABEL_GARBAGE) {
				ss << "Garbage";
			}
			putText(outC, ss.str(), Point(20,50), CV_FONT_HERSHEY_PLAIN, 3.0, Scalar(0,0,255), 2);
		}
		
		stringstream ss; ss << "samples: " << training_data.size();
		putText(outC, ss.str(), Point(30,outC.rows - 30), CV_FONT_HERSHEY_PLAIN, 2.0, Scalar(0,0,255), 1);
		
		imshow("blobs", outC);
		
		char k = cvWaitKey(5);
		if( k == 27 ){
			break;
		}
		if( k == 8 ) {
			std::ostringstream file;
			file << filename << i_snap << suffix;
			cv::imwrite(file.str(),rgbMat);
			i_snap++;
		}
		if (k == 'g') {
			//put into training as 'garbage'
			training_data.push_back(_d);
			label_data.push_back(LABEL_GARBAGE);
			cout << "learn grabage" << endl;
		}
		if(k == 'o') {
				//put into training as 'open'
			training_data.push_back(_d);
			label_data.push_back(LABEL_OPEN);
			cout << "learn open" << endl;
		}
		if(k == 'f') {
			//put into training as 'fist'
			training_data.push_back(_d);
			label_data.push_back(LABEL_FIST);
			cout << "learn fist" << endl;
		}
		if(k == 'h') {
			//put into training as 'thumb'
			training_data.push_back(_d);
			label_data.push_back(LABEL_THUMB);
			cout << "learn thumb" << endl;
		}
		if (k=='t') {
			//train model
			cout << "train model" << endl;
			if(loaded != true) {
				dataMat = Mat(training_data.size(),_d.size(),CV_32FC1);	//descriptors as matrix rows
				for (uint i=0; i<training_data.size(); i++) {
					Mat v = dataMat(Range(i,i+1),Range::all());
					Mat(Mat(training_data[i]).t()).convertTo(v,CV_32FC1,1.0);
				}
				Mat(label_data).convertTo(labelMat,CV_32FC1);
			}
			
//			pca = pca(dataMat,Mat(),CV_PCA_DATA_AS_ROW,15);
			Mat dataAfterPCA = dataMat;
//			pca.project(dataMat,dataAfterPCA);
			
			classifier.train(&((CvMat)dataAfterPCA), &((CvMat)labelMat));
			
			trained = true;
		}
//		if(k=='p' && trained) {
//			//predict
//			Mat results(1,1,CV_32FC1);
//			Mat samples(1,64,CV_32FC1); Mat(Mat(_d).t()).convertTo(samples,CV_32FC1);
//			classifier.find_nearest(&((CvMat)samples), 1, &((CvMat)results));
//			cout << "prediction: " << ((float*)results.data)[0] << endl;
//		}
		if(k=='s') {
			cout << "save training data" << endl;
//			classifier.save("knn-classifier-open-fist-thumb.yaml"); //not implemented
			dataMat = Mat(training_data.size(),_d.size(),CV_32FC1);	//descriptors as matrix rows
			for (uint i=0; i<training_data.size(); i++) {
				Mat v = dataMat(Range(i,i+1),Range::all());
				Mat(Mat(training_data[i]).t()).convertTo(v,CV_32FC1,1.0);
			}
			Mat(label_data).convertTo(labelMat,CV_32FC1);

			FileStorage fs;
			fs.open("data-samples-labels.yaml", CV_STORAGE_WRITE);
			if (fs.isOpened()) {
				fs << "samples" << dataMat;
				fs << "labels" << labelMat;

				fs << "startX" << startX;
				fs << "sizeX" << sizeX;
				fs << "num_x_reps" << num_x_reps;
				fs << "num_y_reps" << num_y_reps;
				
				loaded = true;
				fs.release();
			} else {
				cerr << "can't open saved data" << endl;
			}
		}
		if(k=='l') {
			cout << "try to load training data" << endl;
			FileStorage fs;
			fs.open("data-samples-labels.yaml", CV_STORAGE_READ);
			if (fs.isOpened()) {
				fs["samples"] >> dataMat;
				fs["labels"] >> labelMat;
				fs["startX"] >> startX;
				fs["sizeX"] >> sizeX;
				fs["num_x_reps"] >> num_x_reps;
				fs["num_y_reps"] >> num_y_reps;
				height_over_num_y_reps = 480/num_y_reps;
				width_over_num_x_reps = sizeX/num_x_reps;
				
				loaded = true;
				fs.release();			
			} else {
示例#21
0
文件: lc.c 项目: borgella/ShellOS
int main(int agrc, char*argv[]){
	char tampon[LIMITE];
	getcwd(tampon,256);
    lc(tampon);
    return 0;
}
DWORD WINAPI ShowOptHelp(LPVOID p)
{
	if(lOptHelp){
		// ”же идет!
		return 0;
	}
	SimpleTracker lc(lOptHelp);
	AFX_MANAGE_STATE(AfxGetStaticModuleState());
	COptWinds* pParams=(COptWinds*)p;
	HWND hTestWnd=pParams->pWT->GetSafeHwnd();
	CWnd* pWnd=pParams->pW;
	if(!p){
		return 0;
	}
	HWND hParentWnd=pWnd->GetSafeHwnd();
	MSG msg;
	::PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
	::SendMessage(::GetDesktopWindow(), WM_SYSCOMMAND, (WPARAM) SC_HOTKEY, (LPARAM)hTestWnd);
	CStringArray* pInfos=pParams->pD;
	//pWnd->EnableWindow(FALSE);
	BOOL bStop=0;
	for(int i=0;i<pInfos->GetSize();i++){
		CRect rtDesktop;
		CWnd::GetDesktopWindow()->GetWindowRect(&rtDesktop);
		CRect rtTipInClientXY(rtDesktop);
		rtTipInClientXY.DeflateRect(rtDesktop.Width()/3,rtDesktop.Height()/4,rtDesktop.Width()/3,rtDesktop.Height()/4);
		
	
		CSplashScreenEx *pSplash=new CSplashScreenEx();
		pSplash->Create(pWnd,"CSplashScreenEx dynamic text:",0, CSS_FADE | CSS_CENTERAPP | CSS_SHADOW);//CSS_CHILD
		//pSplash->SetBitmap(IDB_SPLASH,255,0,255);
		//pSplash->SetTextFont("Impact",100,CSS_TEXT_NORMAL);
		rtTipInClientXY.OffsetRect(-rtTipInClientXY.left,-rtTipInClientXY.top);
		pSplash->SetTextRect(rtTipInClientXY);
		pSplash->SetTextColor(GetSysColor(COLOR_INFOTEXT));
		pSplash->SetBgColor(GetSysColor(COLOR_INFOBK));
		pSplash->SetTextFormat(DT_LEFT|DT_WORDBREAK|DT_NOPREFIX|DT_TOP);
		pSplash->SetTextDefaultFont(pWnd->GetFont());

		CString sLine=pInfos->GetAt(i);
		CString sText=CDataXMLSaver::GetInstringPart("TEXT[[","]]",sLine);
		CString sTitle=CDataXMLSaver::GetInstringPart("TITLE[[","]]",sLine);
		CString sFooter=CDataXMLSaver::GetInstringPart("FOOTER[[","]]",sLine);
		int lWait=atol(CDataXMLSaver::GetInstringPart("WAIT[[","]]",sLine));
		
		CPoint pt;
		pt.x=atol(CDataXMLSaver::GetInstringPart("X[[","]]",sLine));
		pt.y=atol(CDataXMLSaver::GetInstringPart("Y[[","]]",sLine));

		CString sH=CDataXMLSaver::GetInstringPart("H[[","]]",sLine);
		if(atol(sH)>0){
			rtTipInClientXY.bottom=rtTipInClientXY.top+atol(sH);
		}
		

		BOOL bClient=1;
		CString sID=CDataXMLSaver::GetInstringPart("ID[[","]]",sLine);
		if(sID!=""){
			if(sID=="SCREEN"){
				bClient=0;
				CRect rtFull;
				//GetWindowRect(GetDesktopWindow(),&rtFull);
				::SystemParametersInfo(SPI_GETWORKAREA,0,&rtFull,0);
				if(pt.x<0){
					pt.x+=rtFull.Width()-rtTipInClientXY.Width();
				}else{
					pt.x+=rtFull.left;
				}
				if(pt.y<0){
					pt.y+=rtFull.Height()-rtTipInClientXY.Height();
				}else{
					pt.y+=rtFull.top;
				}
			}else{
				int iID=atol(sID);
				if(iID!=0){
					CWnd* pID=pWnd->GetDlgItem(iID);
					CRect rtID;
					pID->GetWindowRect(&rtID);
					pWnd->ScreenToClient(&rtID);
					pt.x+=rtID.left;
					pt.y+=rtID.top;
				}
			}
		}
		if(sTitle!=""){
			pSplash->SetTitle(sTitle);
		}
		if(sFooter!=""){
			pSplash->SetFooter(sFooter);
		}
		sText.Replace("\\n","\n");
		pSplash->SetText(sText);
		if(pt.x && pt.y){
			if(bClient){
				pWnd->ClientToScreen(&pt);
			}
			pSplash->SetPosition(pt.x,pt.y,rtTipInClientXY.Width(),sH=="AUTO"?0:rtTipInClientXY.Height());
		}
		pSplash->Show();
		BOOL bRet=0;
		DWORD dwTime=GetTickCount();
		while(lOptHelp && (bRet = GetMessage(&msg, NULL, 0, 0)) != 0){
			if(!IsWindow(hTestWnd) || !IsWindow(hParentWnd)){
				bStop=1;
				break;
			}
			if((lWait && int(GetTickCount()-dwTime)>lWait)){
				break;
			}
			if(msg.hwnd==pSplash->GetSafeHwnd()){
				pSplash->PreTranslateMessage(&msg);
			}
			if(pSplash->IsWasLclick()){
				break;
			}
			if (msg.message==WM_QUIT || bRet == -1){
				break;
			}
			TranslateMessage(&msg); 
			DispatchMessage(&msg); 
		}
		::SendMessage(::GetDesktopWindow(), WM_SYSCOMMAND, (WPARAM) SC_HOTKEY, (LPARAM)hTestWnd);
		pSplash->Hide();
		if(bStop==1){
			break;
		}
	}
	::SendMessage(::GetDesktopWindow(), WM_SYSCOMMAND, (WPARAM) SC_HOTKEY, (LPARAM)hTestWnd);
	delete pParams;
	return 0;
}
示例#23
0
void
manage_request()
{
    ntlmhdr *fast_header;
    char buf[BUFFER_SIZE];
    const char *ch;
    char *ch2, *decoded, *cred = NULL;
    int plen;

    if (fgets(buf, BUFFER_SIZE, stdin) == NULL) {
        fprintf(stderr, "fgets() failed! dying..... errno=%d (%s)\n", errno,
                strerror(errno));
        exit(1);		/* BIIG buffer */
    }
    debug("managing request\n");
    ch2 = memchr(buf, '\n', BUFFER_SIZE);	/* safer against overrun than strchr */
    if (ch2) {
        *ch2 = '\0';		/* terminate the string at newline. */
        ch = ch2;
    }
    debug("ntlm authenticator. Got '%s' from Squid\n", buf);

    if (memcmp(buf, "KK ", 3) == 0) {	/* authenticate-request */
        /* figure out what we got */
        decoded = base64_decode(buf + 3);
        /* Note: we don't need to manage memory at this point, since
         *  base64_decode returns a pointer to static storage.
         */

        if (!decoded) {		/* decoding failure, return error */
            SEND("NA Packet format error, couldn't base64-decode");
            return;
        }
        /* fast-track-decode request type. */
        fast_header = (struct _ntlmhdr *) decoded;

        /* sanity-check: it IS a NTLMSSP packet, isn't it? */
        if (memcmp(fast_header->signature, "NTLMSSP", 8) != 0) {
            SEND("NA Broken authentication packet");
            return;
        }
        switch (le32toh(fast_header->type)) {
        case NTLM_NEGOTIATE:
            SEND("NA Invalid negotiation request received");
            return;
            /* notreached */
        case NTLM_CHALLENGE:
            SEND("NA Got a challenge. We refuse to have our authority disputed");
            return;
            /* notreached */
        case NTLM_AUTHENTICATE:
            /* check against the DC */
            plen = strlen(buf) * 3 / 4;		/* we only need it here. Optimization */
            signal(SIGALRM, timeout_during_auth);
            alarm(30);
            cred = ntlm_check_auth((ntlm_authenticate *) decoded, plen);
            alarm(0);
            signal(SIGALRM, SIG_DFL);
            if (got_timeout != 0) {
                fprintf(stderr, "ntlm-auth[%ld]: Timeout during authentication.\n", (long)getpid());
                SEND("BH Timeout during authentication");
                got_timeout = 0;
                return;
            }
            if (cred == NULL) {
                int smblib_err, smb_errorclass, smb_errorcode, nb_error;
                if (ntlm_errno == NTLM_LOGON_ERROR) {	/* hackish */
                    SEND("NA Logon Failure");
                    return;
                }
                /* there was an error. We have two errno's to look at.
                 * libntlmssp's erno is insufficient, we'll have to look at
                 * the actual SMB library error codes, to acually figure
                 * out what's happening. The thing has braindamaged interfacess..*/
                smblib_err = SMB_Get_Last_Error();
                smb_errorclass = SMBlib_Error_Class(SMB_Get_Last_SMB_Err());
                smb_errorcode = SMBlib_Error_Code(SMB_Get_Last_SMB_Err());
                nb_error = RFCNB_Get_Last_Error();
                debug("No creds. SMBlib error %d, SMB error class %d, SMB error code %d, NB error %d\n",
                      smblib_err, smb_errorclass, smb_errorcode, nb_error);
                /* Should I use smblib_err? Actually it seems I can do as well
                 * without it.. */
                if (nb_error != 0) {	/* netbios-level error */
                    send_bh_or_ld("NetBios error!",
                                  (ntlm_authenticate *) decoded, plen);
                    fprintf(stderr, "NetBios error code %d (%s)\n", nb_error,
                            RFCNB_Error_Strings[abs(nb_error)]);
                    return;
                }
                switch (smb_errorclass) {
                case SMBC_SUCCESS:
                    debug("Huh? Got a SMB success code but could check auth..");
                    SEND("NA Authentication failed");
                    /*
                     * send_bh_or_ld("SMB success, but no creds. Internal error?",
                     * (ntlm_authenticate *) decoded, plen);
                     */
                    return;
                case SMBC_ERRDOS:
                    /*this is the most important one for errors */
                    debug("DOS error\n");
                    switch (smb_errorcode) {
                        /* two categories matter to us: those which could be
                         * server errors, and those which are auth errors */
                    case SMBD_noaccess:	/* 5 */
                        SEND("NA Access denied");
                        return;
                    case SMBD_badformat:
                        SEND("NA bad format in authentication packet");
                        return;
                    case SMBD_badaccess:
                        SEND("NA Bad access request");
                        return;
                    case SMBD_baddata:
                        SEND("NA Bad Data");
                        return;
                    default:
                        send_bh_or_ld("DOS Error",
                                      (ntlm_authenticate *) decoded, plen);
                        return;
                    }
                case SMBC_ERRSRV:	/* server errors */
                    debug("Server error");
                    switch (smb_errorcode) {
                        /* mostly same as above */
                    case SMBV_badpw:
                        SEND("NA Bad password");
                        return;
                    case SMBV_access:
                        SEND("NA Server access error");
                        return;
                    default:
                        send_bh_or_ld("Server Error",
                                      (ntlm_authenticate *) decoded, plen);
                        return;
                    }
                case SMBC_ERRHRD:	/* hardware errors don't really matter */
                    send_bh_or_ld("Domain Controller Hardware error",
                                  (ntlm_authenticate *) decoded, plen);
                    return;
                case SMBC_ERRCMD:
                    send_bh_or_ld("Domain Controller Command Error",
                                  (ntlm_authenticate *) decoded, plen);
                    return;
                }
                SEND("BH unknown internal error.");
                return;
            }

            lc(cred);		/* let's lowercase them for our convenience */
            SEND2("AF %s", cred);
            return;
        default:
            SEND("BH unknown authentication packet type");
            return;
        }


        return;
    }
    if (memcmp(buf, "YR", 2) == 0) {	/* refresh-request */
        dc_disconnect();
        ch = obtain_challenge();
        /* Robert says we can afford to wait forever. I'll trust him on this
         * one */
        while (ch == NULL) {
            sleep(30);
            ch = obtain_challenge();
        }
        SEND2("TT %s", ch);
        return;
    }
    SEND("BH Helper detected protocol error");
    return;
    /********* END ********/


}
示例#24
0
int main(int argc, char **argv)
{
  FILE *fpIn, *fpOut, *fpInList, *fpOutList, *fpXml;
  meta_parameters *meta;
  extern int currArg; /* from cla.h in asf.h... initialized to 1 */
  logflag = 0;
  
  // Parse command line args
  while (currArg < (argc-2)) {
    char *key=argv[currArg++];
    if (strmatch(key,"-log")) {
      sprintf(logFile, "%s", argv[currArg]);
      logflag = 1;
    }
    else {
      printf("\n   ***Invalid option:  %s\n\n",
	     argv[currArg-1]);
      usage(argv[0]);
    }
  }
  if ((argc-currArg) < 2) {
    printf("Insufficient arguments.\n");
    usage(argv[0]);
  }
  
  asfSplashScreen(argc, argv);
  
  char *listInFile = (char *) MALLOC(sizeof(char)*(strlen(argv[1])+1));
  strcpy(listInFile, argv[1]);
  char *outFile = (char *) MALLOC(sizeof(char)*(strlen(argv[2])+1));
  strcpy(outFile, argv[2]);
  
  // Setup file names
  char outDirName[512], outFileName[512];
  split_dir_and_file(outFile, outDirName, outFileName);
  char *tmpDir = (char *) MALLOC(sizeof(char)*512);
  sprintf(tmpDir, "%smeasures-", outDirName);
  char *tsdir = time_stamp_dir();
  strcat(tmpDir, tsdir);
  FREE(tsdir);
  create_clean_dir(tmpDir);
  char *isoStr = iso_date();

  // Read header information
  char inFile[512], imgFile[768], metaFile[768];
  char listOutFile[768], citation[50], start[30], end[30], first[30];
  char header[120], baseName[512], dirName[512], ext[5];
  float x_pix, y_pix, x_map_ll, y_map_ll, x_map_ur, y_map_ur, inc, cat;
  double lat, lon, height, x, y, z;
  int ii, kk, nFiles=0, num = 1, sample_count, line_count;
  image_data_type_t image_data_type;
  sprintf(listOutFile, "%s%crgps.xml", tmpDir, DIR_SEPARATOR);

  // Preparing map projection information
  project_parameters_t pps;
  projection_type_t proj_type;
  datum_type_t datum;
  spheroid_type_t spheroid;
  read_proj_file("polar_stereographic_north_ssmi.proj", 
     &pps, &proj_type, &datum, &spheroid);
  pps.ps.false_easting = 0.0;
  pps.ps.false_northing = 0.0;
  meta_projection *proj = meta_projection_init();
  proj->type = proj_type;
  proj->datum = HUGHES_DATUM;
  proj->spheroid = HUGHES_SPHEROID;
  proj->param = pps;
  strcpy(proj->units, "meters");
  proj->hem = 'N';
  spheroid_axes_lengths(spheroid, &proj->re_major, &proj->re_minor);
  FREE(proj);

  // Set up supplemental file names: water mask, lat/lon, x/y grids
  char maskFile[768], latFile[768], lonFile[768], xFile[768], yFile[768]; 
  sprintf(maskFile, "%s%cwater_mask.img", tmpDir, DIR_SEPARATOR);
  sprintf(latFile, "%s%clatitude.img", tmpDir, DIR_SEPARATOR);
  sprintf(lonFile, "%s%clongitude.img", tmpDir, DIR_SEPARATOR);
  sprintf(xFile, "%s%cxgrid.img", tmpDir, DIR_SEPARATOR);
  sprintf(yFile, "%s%cygrid.img", tmpDir, DIR_SEPARATOR);

  // Generating output XML file
  fpInList = FOPEN(listInFile, "r");
  fpOutList = FOPEN(listOutFile, "w");
  fprintf(fpOutList, "<netcdf>\n");
  fprintf(fpOutList, "  <data>\n");
  fprintf(fpOutList, "    <latitude>%s</latitude>\n", latFile);
  fprintf(fpOutList, "    <longitude>%s</longitude>\n", lonFile);
  fprintf(fpOutList, "    <xgrid>%s</xgrid>\n", xFile);
  fprintf(fpOutList, "    <ygrid>%s</ygrid>\n", yFile);
  fprintf(fpOutList, "    <mask>%s</mask>\n", maskFile);
  
  julian_date jdStart, jdEnd, jdRef;
  hms_time hms;
  hms.hour = 0;
  hms.min = 0;
  hms.sec = 0.0;

  asfPrintStatus("Working through the file list:\n");
  int myrFlag=FALSE, divFlag=FALSE, vrtFlag=FALSE, shrFlag=FALSE;
  int firstYear, firstDay, startYear, startDay, endYear, endDay;
  double westBoundLon, eastBoundLon, northBoundLat, southBoundLat;
  double minLat=90.0, maxLat=-90.0, minLon=180.0, maxLon=-180.0;

  while (fgets(inFile, 512, fpInList)) {

    chomp(inFile);
    char inDirName[512], inFileName[512];
    split_dir_and_file(inFile, inDirName, inFileName);

    // Preparing map projection information
    project_parameters_t pps;
    projection_type_t proj_type;
    datum_type_t datum;
    spheroid_type_t spheroid;
    read_proj_file("polar_stereographic_north_ssmi.proj", 
       &pps, &proj_type, &datum, &spheroid);
    pps.ps.false_easting = 0.0;
    pps.ps.false_northing = 0.0;
    meta_projection *proj = meta_projection_init();
    proj->type = proj_type;
    proj->datum = HUGHES_DATUM;
    proj->spheroid = HUGHES_SPHEROID;
    proj->param = pps;
    strcpy(proj->units, "meters");
    proj->hem = 'N';
    spheroid_axes_lengths(spheroid, &proj->re_major, &proj->re_minor);

    // Sort out dates
    startYear = subInt(inFileName, 0, 4);
    startDay = subInt(inFileName, 4, 3);
    endYear = subInt(inFileName, 8, 4);
    endDay = subInt(inFileName, 12, 3);
    if (nFiles == 0) {
      firstYear = startYear;
      firstDay = startDay;
    }
    sprintf(citation, "%d%03d to %d%03d", startYear, startDay, endYear, endDay);
    rgps2iso_date(startYear, (double) startDay, start);
    rgps2iso_date(endYear, (double) endDay, end);
    rgps2iso_date(firstYear, (double) firstDay, first);
    
    // Read header information
    FILE *fpIn = FOPEN(inFile, "r");
    fgets(header, 100, fpIn);
    sscanf(header, "%f %f %f %f %f %f", &x_pix, &y_pix, &x_map_ll, &y_map_ll, 
      &x_map_ur, &y_map_ur);
    fgets(header, 100, fpIn);
    int params = sscanf(header, "%f %f %d %d", 
      &inc, &cat, &sample_count, &line_count);
    if (params == 3) {
      sscanf(header, "%f %d %d", &cat, &sample_count, &line_count);
      inc = 0;
    }
    else if (params == 2) {
      sscanf(header, "%d %d", &sample_count, &line_count);
      inc = 0;
      cat = 1;
    }
    num = (int) cat;
    if (num > 1)
      asfPrintError("Multiband imagery (%s) not supported for netCDF "
        "generation!\n", inFile);

    /*  
    printf("x_pix: %f, y_pix: %f\n", x_pix, y_pix);
    printf("x_map_ll: %f, y_map_ll: %f\n", x_map_ll, y_map_ll);
    printf("x_map_ur: %f, y_map_ur: %f\n", x_map_ur, y_map_ur);
    printf("sample_count: %d, line_count: %d\n\n", sample_count, line_count);
    */
      
    // Check extension
    split_base_and_ext(inFileName, 1, '.', baseName, ext);
    asfPrintStatus("Processing %s ...\n", inFileName);
    sprintf(imgFile, "%s%c%s_%s.img", tmpDir, DIR_SEPARATOR, baseName, &ext[1]);
    sprintf(metaFile, "%s%c%s_%s.meta", tmpDir, DIR_SEPARATOR, baseName, 
      &ext[1]);
    
    jdRef.year = firstYear;
    jdRef.jd = 1;
    jdStart.year = startYear;
    jdStart.jd = startDay;
    jdEnd.year = endYear;
    jdEnd.jd = endDay;
    double startSec = date2sec(&jdStart, &hms) - date2sec(&jdRef, &hms);
    double endSec = date2sec(&jdEnd, &hms) - date2sec(&jdRef, &hms);
    if (strcmp_case(ext, ".MYR") == 0) {
      fprintf(fpOutList, "    <multiyear_ice_fraction start=\"%.0f\" end=\"%.0f"
        "\">%s</multiyear_ice_fraction>\n", startSec, endSec, imgFile);
      image_data_type = MULTIYEAR_ICE_FRACTION;
      myrFlag = TRUE;
    }
    else if (strcmp_case(ext, ".DIV") == 0) {
      fprintf(fpOutList, "    <divergence start=\"%.0f\" end=\"%.0f\">%s"
        "</divergence>\n", startSec, endSec, imgFile);
      image_data_type = DIVERGENCE;
      divFlag = TRUE;
    }
    else if (strcmp_case(ext, ".VRT") == 0) {
      fprintf(fpOutList, "    <vorticity start=\"%.0f\" end=\"%.0f\">%s"
        "</vorticity>\n", startSec, endSec, imgFile);
      image_data_type = VORTICITY;
      vrtFlag = TRUE;
    }
    else if (strcmp_case(ext, ".SHR") == 0) {
      fprintf(fpOutList, "    <shear start=\"%.0f\" end=\"%.0f\">%s</shear>", 
        startSec, endSec, imgFile);
      image_data_type = SHEAR;
      shrFlag = TRUE;
    }

    // Generate basic metadata
    meta = raw_init();
    meta->general->line_count = line_count;
    meta->general->sample_count = sample_count;
    meta->general->band_count = 1;
    meta->general->data_type = REAL32;
    meta->general->image_data_type = image_data_type;
    strcpy(meta->general->basename, inFile);
    meta->general->x_pixel_size = x_pix*1000.0;
    meta->general->y_pixel_size = y_pix*1000.0;
    meta->general->start_line = 0;
    meta->general->start_sample = 0;
    meta->general->no_data = MAGIC_UNSET_DOUBLE;
    strcpy(meta->general->sensor, "RGPS MEaSUREs");
    char *tmp = image_data_type2str(meta->general->image_data_type);
    sprintf(meta->general->bands, "%s", lc(tmp));
    FREE(tmp);
    sprintf(meta->general->acquisition_date, "%s", baseName);
    
    // Sort out map projection
    proj->startX = x_map_ll*1000.0;
    proj->startY = y_map_ur*1000.0;
    proj->perX = x_pix*1000.0;
    proj->perY = -y_pix*1000.0;
    meta->projection = proj;
    meta_write(meta, metaFile);
    strcpy(meta->general->bands, "water mask");
    sprintf(metaFile, "%s%cwater_mask.meta", tmpDir, DIR_SEPARATOR);
    meta_write(meta, metaFile);  
    sprintf(metaFile, "%s%c%s_%s.meta", tmpDir, DIR_SEPARATOR, baseName, 
      &ext[1]);
    
    float *floatBuf = (float *) MALLOC(sizeof(float)*sample_count);

    // Write gridded data to ASF internal format
    fpOut = FOPEN(imgFile, "wb");
    for (ii=0; ii<line_count; ii++) {
      for (kk=0; kk<sample_count; kk++) {
	      ASF_FREAD(&floatBuf[kk], sizeof(float), 1, fpIn);
	      ieee_big32(floatBuf[kk]);
        if (floatBuf[kk] > 10000000000.0 || 
          FLOAT_EQUIVALENT(floatBuf[kk], 10000000000.0))
          floatBuf[kk] = MAGIC_UNSET_DOUBLE;
      }
      put_float_line(fpOut, meta, line_count-ii-1, floatBuf);
    }
    FCLOSE(fpOut);
    FREE(floatBuf);
    
    double lat1, lon1, lat2, lon2, lat3, lon3, lat4, lon4;
    proj_to_latlon(proj, x_map_ll*1000.0, y_map_ll*1000.0, 0.0, 
      &lat1, &lon1, &height);
    proj_to_latlon(proj, x_map_ll*1000.0, y_map_ur*1000.0, 0.0, 
      &lat2, &lon2, &height);
    proj_to_latlon(proj, x_map_ur*1000.0, y_map_ur*1000.0, 0.0, 
      &lat3, &lon3, &height);
    proj_to_latlon(proj, x_map_ur*1000.0, y_map_ll*1000.0, 0.0, 
      &lat4, &lon4, &height);
    westBoundLon = minValue(lon1*R2D, lon2*R2D, lon3*R2D, lon4*R2D);
    eastBoundLon = maxValue(lon1*R2D, lon2*R2D, lon3*R2D, lon4*R2D);
    northBoundLat = maxValue(lat1*R2D, lat2*R2D, lat3*R2D, lat4*R2D);
    southBoundLat = minValue(lat1*R2D, lat2*R2D, lat3*R2D, lat4*R2D);
    if (westBoundLon < minLon)
      minLon = westBoundLon;
    if (eastBoundLon > maxLon)
      maxLon = eastBoundLon;
    if (southBoundLat < minLat)
      minLat = southBoundLat;
    if (northBoundLat > maxLat)
      maxLat = northBoundLat;

    meta_free(meta);
    nFiles++;
  }
  FCLOSE(fpInList);
  
  fprintf(fpOutList, "  </data>\n");
  fprintf(fpOutList, "  <metadata>\n");
  fprintf(fpOutList, "    <time>\n");
  fprintf(fpOutList, "      <axis type=\"string\" definition=\"name of axis\">T"
    "</axis>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">serial date</long_name>\n");
  fprintf(fpOutList, "      <references type=\"string\" definition=\"reference "
    "of the value\">start time of 3-day average</references>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">time</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">seconds since %d-01-01T00:00:00Z</units>\n",
    firstYear);
  fprintf(fpOutList, "      <bounds type=\"string\" definition=\"variable "
    "containing data range\">time_bounds</bounds>\n");
  fprintf(fpOutList, "      <FillValue type=\"double\" definition=\"default "
    "value\">0</FillValue>\n");
  fprintf(fpOutList, "    </time>\n");
  fprintf(fpOutList, "    <time_bounds>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">serial date</long_name>\n");
  fprintf(fpOutList, "      <references type=\"string\" definition=\"reference "
    "of the value\">start and end time of 3-day average</references>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">time</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">seconds since %d-01-01T00:00:00Z</units>\n",
    firstYear);
  fprintf(fpOutList, "      <FillValue type=\"double\" definition=\"default "
    "value\">0</FillValue>\n");
  fprintf(fpOutList, "    </time_bounds>\n");
  fprintf(fpOutList, "    <latitude>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">latitude</long_name>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">latitude</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">degrees_north</units>\n");
  fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
    "value\">-999</FillValue>\n");
  fprintf(fpOutList, "      <valid_min type=\"float\" definition=\"minimum "
    "valid value\">-90.0</valid_min>\n");
  fprintf(fpOutList, "      <valid_max type=\"float\" definition=\"minimum "
    "valid value\">90.0</valid_max>\n");
  fprintf(fpOutList, "    </latitude>\n");
  fprintf(fpOutList, "    <longitude>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">longitude</long_name>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">longitude</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">degrees_east</units>\n");
  fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
    "value\">-999</FillValue>\n");
  fprintf(fpOutList, "      <valid_min type=\"float\" definition=\"minimum "
    "valid value\">-180.0</valid_min>\n");
  fprintf(fpOutList, "      <valid_max type=\"float\" definition=\"minimum "
    "valid value\">180.0</valid_max>\n");
  fprintf(fpOutList, "    </longitude>\n");
  fprintf(fpOutList, "    <xgrid>\n");
  fprintf(fpOutList, "      <axis type=\"string\" definition=\"name of axis\">X"
    "</axis>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">projection_grid_x_center</long_name>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">projection_x_coordinate"
    "</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">meters</units>\n");
  fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
    "value\">NaN</FillValue>\n");
  fprintf(fpOutList, "    </xgrid>\n");
  fprintf(fpOutList, "    <ygrid>\n");
  fprintf(fpOutList, "      <axis type=\"string\" definition=\"name of axis\">Y"
    "</axis>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">projection_grid_y_center</long_name>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">projection_y_coordinate"
    "</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">meters</units>\n");
  fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
    "value\">NaN</FillValue>\n");
  fprintf(fpOutList, "    </ygrid>\n");
  fprintf(fpOutList, "    <Polar_Stereographic>\n");
  fprintf(fpOutList, "      <grid_mapping_name>polar_stereographic"
    "</grid_mapping_name>\n");
  fprintf(fpOutList, "      <straight_vertical_longitude_from_pole>%.1f"
    "</straight_vertical_longitude_from_pole>\n", pps.ps.slon);
  fprintf(fpOutList, "      <longitude_of_central_meridian>90.0"
    "</longitude_of_central_meridian>\n");
  fprintf(fpOutList, "      <standard_parallel>%.1f</standard_parallel>\n", 
    pps.ps.slat);
  fprintf(fpOutList, "      <false_easting>%.1f</false_easting>\n", 
    pps.ps.false_easting);
  fprintf(fpOutList, "      <false_northing>%.1f</false_northing>\n",
    pps.ps.false_northing);
  fprintf(fpOutList, "      <projection_x_coordinate>xgrid"
    "</projection_x_coordinate>\n");
  fprintf(fpOutList, "      <projection_y_coordinate>ygrid"
    "</projection_y_coordinate>\n");
  fprintf(fpOutList, "      <units>meters</units>\n");
  fprintf(fpOutList, "    </Polar_Stereographic>\n");
  fprintf(fpOutList, "    <mask>\n");
  fprintf(fpOutList, "      <coordinates type=\"string\" definition=\""
    "coordinate reference\">ygrid xgrid</coordinates>\n");
  fprintf(fpOutList, "      <grid_mapping type=\"string\" definition=\"\">"
    "Polar_Stereographic</grid_mapping>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">projection_grid_y_center</long_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">1</units>\n");
  fprintf(fpOutList, "      <units_description type=\"string\" definition=\""
    "descriptive information about dimensionless quantity\">unitless"
    "</units_description>\n");
  fprintf(fpOutList, "      <FillValue type=\"int\" definition=\"default "
    "value\">0</FillValue>\n");
  fprintf(fpOutList, "    </mask>\n");
  if (myrFlag) {
    fprintf(fpOutList, "    <multiyear_ice_fraction>\n");
    fprintf(fpOutList, "      <cell_methods type=\"string\" definition=\""
      "characteristic of a field that is represented by cell values\">area: "
      "multiyear ice fraction value</cell_methods>\n");
    fprintf(fpOutList, "      <coordinates type=\"string\" definition=\""
      "coordinate reference\">ygrid xgrid</coordinates>\n");
    fprintf(fpOutList, "      <grid_mapping type=\"string\" definition=\"\">"
      "Polar_Stereographic</grid_mapping>\n");
    fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
      "descriptive name\">RGPS MEaSUREs multiyear ice fraction</long_name>\n");
    fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
      "dimensional quantity\">1</units>\n");
    fprintf(fpOutList, "      <units_description type=\"string\" definition=\""
      "descriptive information about dimensionless quantity\">unitless"
      "</units_description>\n");
    fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
      "value\">NaN</FillValue>\n");
    fprintf(fpOutList, "    </multiyear_ice_fraction>\n");
  }
  if (divFlag) {
    fprintf(fpOutList, "    <divergence>\n");
    fprintf(fpOutList, "      <cell_methods type=\"string\" definition=\""
      "characteristic of a field that is represented by cell values\">area: "
      "divergence value</cell_methods>\n");
    fprintf(fpOutList, "      <coordinates type=\"string\" definition=\""
      "coordinate reference\">ygrid xgrid</coordinates>\n");
    fprintf(fpOutList, "      <grid_mapping type=\"string\" definition=\"\">"
      "Polar_Stereographic</grid_mapping>\n");
    fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
      "descriptive name\">RGPS MEaSUREs divergence</long_name>\n");
    fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
      "dimensional quantity\">1</units>\n");
    fprintf(fpOutList, "      <units_description type=\"string\" definition=\""
      "descriptive information about dimensionless quantity\">unitless"
      "</units_description>\n");
    fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
      "value\">NaN</FillValue>\n");
    fprintf(fpOutList, "    </divergence>\n");
  }
  if (vrtFlag) {
    fprintf(fpOutList, "    <vorticity>\n");
    fprintf(fpOutList, "      <cell_methods type=\"string\" definition=\""
      "characteristic of a field that is represented by cell values\">area: "
      "vorticity value</cell_methods>\n");
    fprintf(fpOutList, "      <coordinates type=\"string\" definition=\""
      "coordinate reference\">ygrid xgrid</coordinates>\n");
    fprintf(fpOutList, "      <grid_mapping type=\"string\" definition=\"\">"
      "Polar_Stereographic</grid_mapping>\n");
    fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
      "descriptive name\">RGPS MEaSUREs vorticity</long_name>\n");
    fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
      "dimensional quantity\">1</units>\n");
    fprintf(fpOutList, "      <units_description type=\"string\" definition=\""
      "descriptive information about dimensionless quantity\">unitless"
      "</units_description>\n");
    fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
      "value\">NaN</FillValue>\n");
    fprintf(fpOutList, "    </vorticity>\n");
  }
  if (shrFlag) {
    fprintf(fpOutList, "    <shear>\n");
    fprintf(fpOutList, "      <cell_methods type=\"string\" definition=\""
      "characteristic of a field that is represented by cell values\">area: "
      "shear value</cell_methods>\n");
    fprintf(fpOutList, "      <coordinates type=\"string\" definition=\""
      "coordinate reference\">ygrid xgrid</coordinates>\n");
    fprintf(fpOutList, "      <grid_mapping type=\"string\" definition=\"\">"
      "Polar_Stereographic</grid_mapping>\n");
    fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
      "descriptive name\">RGPS MEaSUREs shear</long_name>\n");
    fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
      "dimensional quantity\">1</units>\n");
    fprintf(fpOutList, "      <units_description type=\"string\" definition=\""
      "descriptive information about dimensionless quantity\">unitless"
      "</units_description>\n");
    fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
      "value\">NaN</FillValue>\n");
    fprintf(fpOutList, "    </shear>\n");
  }
  fprintf(fpOutList, "  </metadata>\n");
  fprintf(fpOutList, "  <parameter>\n");
  if (myrFlag)
    fprintf(fpOutList, "    <multiyear_ice_fraction type=\"float\"/>\n");
  if (divFlag)
    fprintf(fpOutList, "    <divergence type=\"float\"/>\n");
  if (vrtFlag)
    fprintf(fpOutList, "    <vorticity type=\"float\"/>\n");
  if (shrFlag)
    fprintf(fpOutList, "    <shear type=\"float\"/>\n");
  fprintf(fpOutList, "  </parameter>\n");
  
  char startStr[15], endStr[15];
  jdStart.year = firstYear;
  jdStart.jd = firstDay;
  jdEnd.year = endYear;
  jdEnd.jd = endDay;
  jd2date(&jdStart, startStr);
  jd2date(&jdEnd, endStr);
  if (firstYear != endYear || firstDay != endDay)
    sprintf(citation, "%s to %s", startStr, endStr);
  else
    sprintf(citation, "%s", startStr);
  fprintf(fpOutList, "  <root>\n");
  fprintf(fpOutList, "    <Conventions>CF-1.6</Conventions>\n");
  fprintf(fpOutList, "    <institution>Alaska Satellite Facility</institution>\n");
  fprintf(fpOutList, "    <title>Kwok, Ron. 2008. MEaSUREs Small-Scale Kinematics"
    " of Arctic Ocean Sea Ice, Version 01, %s. Jet Propulsion Laboratory "
    "Pasadena, CA USA and Alaska Satellite Facility Fairbanks, AK USA. "
    "Digital media.</title>\n", citation);
  fprintf(fpOutList, "    <source>Products derived from RADARSAT-1 SWB imagery at "
    "100 m resolution</source>\n");
  fprintf(fpOutList, "    <comment>Imagery the products are derived from: Copyright "
    "Canadian Space Agency (1996 to 2008)</comment>\n");
  fprintf(fpOutList, "    <reference>Documentation available at: www.asf.alaska.edu"
    "</reference>\n");
  fprintf(fpOutList, "    <history>%s: netCDF file created.</history>\n", isoStr);
  fprintf(fpOutList, "  </root>\n");
  fprintf(fpOutList, "</netcdf>\n");
  FCLOSE(fpOutList);

  // Generate supplemental files: water mask, lat/lon, x/y grids
  asfPrintStatus("Generating supplemental files ...\n");
  float *floatBuf = (float *) MALLOC(sizeof(float)*sample_count);
  float *maskBuf = (float *) MALLOC(sizeof(float)*sample_count);
  float *latBuf = (float *) MALLOC(sizeof(float)*sample_count);
  float *lonBuf = (float *) MALLOC(sizeof(float)*sample_count);
  float *xBuf = (float *) MALLOC(sizeof(float)*sample_count);
  float *yBuf = (float *) MALLOC(sizeof(float)*sample_count);
  meta = meta_read(metaFile);
  
  fpIn = FOPEN(inFile, "r");
  fgets(header, 100, fpIn);
  sscanf(header, "%f %f %f %f %f %f", &x_pix, &y_pix, &x_map_ll, &y_map_ll, 
    &x_map_ur, &y_map_ur);
  fgets(header, 100, fpIn);
  sscanf(header, "%d %d", &sample_count, &line_count);
  
  FILE *fpMask = FOPEN(maskFile, "wb");
  FILE *fpLat = FOPEN(latFile, "wb");
  FILE *fpLon = FOPEN(lonFile, "wb");
  FILE *fpXgrid = FOPEN(xFile, "wb");
  FILE *fpYgrid = FOPEN(yFile, "wb");
  for (ii=0; ii<line_count; ii++) {
    for (kk=0; kk<sample_count; kk++) {
      ASF_FREAD(&floatBuf[kk], sizeof(float), 1, fpIn);
      ieee_big32(floatBuf[kk]);
    }
    for (kk=0; kk<sample_count; kk++) {
      meta_get_latLon(meta, line_count-ii-1, kk, 0.0, &lat, &lon);
      latlon_to_proj(meta->projection, 'R', lat*D2R, lon*D2R, 0.0, &x, &y, &z);
      latBuf[kk] = lat;
      lonBuf[kk] = lon;
      xBuf[kk] = x;
      yBuf[kk] = y;
      if (floatBuf[kk] < 10000000000.0) {
        maskBuf[kk] = 1.0;
      }
      else if (floatBuf[kk] > 10000000000.0) {
        maskBuf[kk] = 1.0;
      }
      else {
        maskBuf[kk] = 0.0;
      }
    }
    put_float_line(fpMask, meta, line_count-ii-1, maskBuf);
    put_float_line(fpLat, meta, line_count-ii-1, latBuf);
    put_float_line(fpLon, meta, line_count-ii-1, lonBuf);
    put_float_line(fpXgrid, meta, line_count-ii-1, xBuf);
    put_float_line(fpYgrid, meta, line_count-ii-1, yBuf);
  }
  FCLOSE(fpIn);
  FCLOSE(fpMask);
  FCLOSE(fpLat);
  FCLOSE(fpLon);
  FREE(floatBuf);
  FREE(maskBuf);
  FREE(latBuf);
  FREE(lonBuf);
  FREE(xBuf);
  FREE(yBuf);
  meta_write(meta, latFile);
  meta_write(meta, lonFile);
  meta_write(meta, xFile);
  meta_write(meta, yFile);

  // Write ISO meatadata for netCDF
  asfPrintStatus("Generating metadata for netCDF file ...\n");

  char *ncXmlBase = get_basename(outFile);
  char *ncXmlFile = appendExt(outFile, ".xml");
  fpXml = FOPEN(ncXmlFile, "w");
  fprintf(fpXml, "<rgps>\n");
  fprintf(fpXml, "  <granule>%s</granule>\n", ncXmlBase);
  fprintf(fpXml, "  <metadata_creation>%s</metadata_creation>\n", isoStr);
  fprintf(fpXml, "  <metadata>\n");
  fprintf(fpXml, "    <product>\n");
  fprintf(fpXml, "      <file type=\"string\" definition=\"name of product "
    "file\">%s.nc</file>\n", ncXmlBase);
  if (divFlag && vrtFlag && shrFlag)
    fprintf(fpXml, "      <type type=\"string\" definition=\"product type\">"
    "divergence, vorticity, shear</type>\n");
  else if (myrFlag)
    fprintf(fpXml, "      <type type=\"string\" definition=\"product type\">"
    "multiyear ice fraction</type>\n");
  fprintf(fpXml, "      <format type=\"string\" definition=\"name of the data "
    "format\">netCDF</format>\n");

  fpInList = FOPEN(listInFile, "r");
  while (fgets(inFile, 512, fpInList)) {
    chomp(inFile);
    split_dir_and_file(inFile, dirName, baseName);
    fprintf(fpXml, "      <source type=\"string\" definition=\"name of the data"
    " source\">%s</source>\n", baseName);
  }
  FCLOSE(fpInList);

  fprintf(fpXml, "      <cell_size_x type=\"double\" definition=\"cell size "
    "in x direction\" units=\"m\">%.2f</cell_size_x>\n", x_pix*1000.0);
  fprintf(fpXml, "      <cell_size_y type=\"double\" definition=\"cell size "
    "in y direction\" units=\"m\">%.2f</cell_size_y>\n", y_pix*1000.0);
  fprintf(fpXml, "      <map_x_lower_left type=\"double\" definition=\"x "
    "coordinate of lower left corner\" units=\"m\">%.6f</map_x_lower_left>\n",
    x_map_ll*1000.0);
  fprintf(fpXml, "      <map_y_lower_left type=\"double\" definition=\"y "
    "coordinate of lower left corner\" units=\"m\">%.6f</map_y_lower_left>\n",
    y_map_ll*1000.0);
  fprintf(fpXml, "      <map_x_upper_right type=\"double\" definition=\"x "
    "coordinate of upper right corner\" units=\"m\">%.6f</map_x_upper_right>"
    "\n", x_map_ur*1000.0);
  fprintf(fpXml, "      <map_y_upper_right type=\"double\" definition=\"y "
    "coordinate of upper right corner\" units=\"m\">%.6f</map_y_upper_right>"
    "\n", y_map_ur*1000.0);
  fprintf(fpXml, "      <cell_dimension_x type=\"int\" definition=\"cell "
    "dimension in x direction\">%d</cell_dimension_x>\n", 
    sample_count);
  fprintf(fpXml, "      <cell_dimension_y type=\"int\" definition=\"cell "
    "dimension in y direction\">%d</cell_dimension_y>\n",
      line_count);
  fprintf(fpXml, "      <projection_string type=\"string\" definition=\"map "
    "projection information as well known text\">%s</projection_string>\n", 
  meta2esri_proj(meta, NULL));
  fprintf(fpXml, "    </product>\n");
  fprintf(fpXml, "  </metadata>\n");
  fprintf(fpXml, "  <extent>\n");
  fprintf(fpXml, "    <product>\n");
  fprintf(fpXml, "      <westBoundLongitude>%.5f</westBoundLongitude>\n",
    minLon);
  fprintf(fpXml, "      <eastBoundLongitude>%.5f</eastBoundLongitude>\n",
    maxLon);
  fprintf(fpXml, "      <northBoundLatitude>%.5f</northBoundLatitude>\n",
    maxLat);
  fprintf(fpXml, "      <southBoundLatitude>%.5f</southBoundLatitude>\n",
    minLat);
  fprintf(fpXml, "      <start_datetime>%s</start_datetime>\n", first);
  fprintf(fpXml, "      <end_datetime>%s</end_datetime>\n", end);
  fprintf(fpXml, "    </product>\n");
  fprintf(fpXml, "  </extent>\n");
  fprintf(fpXml, "</rgps>\n");
  FCLOSE(fpXml);
  FREE(ncXmlBase);
  FREE(ncXmlFile);
  meta_free(meta);

  // Export to netCDF
  asfPrintStatus("Exporting to netCDF file ...\n");
  export_netcdf_xml(listOutFile, outFile);

  // Clean up
  remove_dir(tmpDir);
  FREE(tmpDir);
  FREE(outFile);
  FREE(listInFile);
  FREE(isoStr);

  return 0;
}
示例#25
0
void SqrtRep::computeExactFlags() {
  if (!child->flagsComputed())
    child->computeExactFlags();

  if (rationalReduceFlag)
    ratFlag() = -1;

  sign() = child->sign();
  if (sign() < 0)
    core_error("squareroot is called with negative operand.",
               __FILE__, __LINE__, true);

  uMSB() = child->uMSB() / EXTLONG_TWO;
  lMSB() = child->lMSB() / EXTLONG_TWO;

  // length() = child->length();
  measure() = child->measure();

  // BFMSS[2,5] bound.
  if (child->v2p() + ceilLg5(child->v5p()) + child->u25() >=
      child->v2m() + ceilLg5(child->v5m()) + child->l25()) {
    extLong vtilda2 = child->v2p() + child->v2m();
    v2p() = vtilda2 / EXTLONG_TWO;
    v2m() = child->v2m();
    extLong vmod2;
    if (v2p().isInfty())
      vmod2 = CORE_INFTY;
    else
      vmod2 = vtilda2 - EXTLONG_TWO*v2p(); // == vtilda2 % 2
    extLong vtilda5 = child->v5p() + child->v5m();
    v5p() = vtilda5 / EXTLONG_TWO;
    v5m() = child->v5m();
    extLong vmod5;
    if (v5p().isInfty())
      vmod5 = CORE_INFTY;
    else
      vmod5 = vtilda5 - EXTLONG_TWO*v5p(); // == vtilda5 % 2
    u25() = (child->u25() + child->l25() + vmod2 + ceilLg5(vmod5) + EXTLONG_ONE) / EXTLONG_TWO;
    l25() = child->l25();
  } else {
    extLong vtilda2 = child->v2p() + child->v2m();
    v2p() = child->v2p();
    v2m() = vtilda2 / EXTLONG_TWO;
    extLong vmod2;
    if (v2m().isInfty())
      vmod2 = CORE_INFTY;
    else
      vmod2 = vtilda2 - EXTLONG_TWO*v2m(); // == vtilda2 % 2
    extLong vtilda5 = child->v5p() + child->v5m();
    v5p() = child->v5p();
    v5m() = vtilda5 / EXTLONG_TWO;
    u25() = child->u25();
    extLong vmod5;
    if (v5m().isInfty())
      vmod5 = CORE_INFTY;
    else
      vmod5 = vtilda5 - EXTLONG_TWO*v5m(); // == vtilda5 % 2
    l25() = (child->u25() + child->l25() + vmod2 + ceilLg5(vmod5) + EXTLONG_ONE) / EXTLONG_TWO;
  }

  high() = (child->high() +EXTLONG_ONE)/EXTLONG_TWO;
  low() = child->low() / EXTLONG_TWO;
  lc() = child->lc();
  tc() = child->tc();
  flagsComputed() = true;
}// SqrtRep::computeExactFlags
示例#26
0
void
Quad1MindlinShell3D :: computeBmatrixAt(GaussPoint *gp, FloatMatrix &answer, int li, int ui)
{
    FloatArray n, ns;
    FloatMatrix dn, dns;
    const FloatArray &localCoords = gp->giveNaturalCoordinates();

    this->interp.evaldNdx( dn, localCoords, FEIVertexListGeometryWrapper(lnodes) );
    this->interp.evalN( n, localCoords,  FEIVoidCellGeometry() );

    answer.resize(8, 4 * 5);
    answer.zero();

    // enforce one-point reduced integration if requested
    if ( this->reducedIntegrationFlag ) {
        FloatArray lc(2);
        lc.zero(); // set to element center coordinates

        this->interp.evaldNdx( dns, lc, FEIVertexListGeometryWrapper(lnodes) );
        this->interp.evalN( ns, lc,  FEIVoidCellGeometry() );
    } else {
        dns = dn;
        ns = n;
    }


    // Note: This is just 5 dofs (sixth column is all zero, torsional stiffness handled separately.)
    for ( int i = 0; i < 4; ++i ) {
        ///@todo Check the rows for both parts here, to be consistent with _3dShell material definition
        // Part related to the membrane (columns represent coefficients for D_u, D_v)
        answer(0, 0 + i * 5) = dn(i, 0);//eps_x = du/dx
        answer(1, 1 + i * 5) = dn(i, 1);//eps_y = dv/dy
        answer(2, 0 + i * 5) = dn(i, 1);//gamma_xy = du/dy+dv/dx
        answer(2, 1 + i * 5) = dn(i, 0);

        // Part related to the plate (columns represent the dofs D_w, R_u, R_v)
        ///@todo Check sign here
        answer(3 + 0, 2 + 2 + i * 5) = dn(i, 0);// kappa_x = d(fi_y)/dx
        answer(3 + 1, 2 + 1 + i * 5) =-dn(i, 1);// kappa_y = -d(fi_x)/dy
        answer(3 + 2, 2 + 2 + i * 5) = dn(i, 1);// kappa_xy=d(fi_y)/dy-d(fi_x)/dx
        answer(3 + 2, 2 + 1 + i * 5) =-dn(i, 0);

        // shear strains
        answer(3 + 3, 2 + 0 + i * 5) = dns(i, 0);// gamma_xz = fi_y+dw/dx
        answer(3 + 3, 2 + 2 + i * 5) = ns(i);
        answer(3 + 4, 2 + 0 + i * 5) = dns(i, 1);// gamma_yz = -fi_x+dw/dy
        answer(3 + 4, 2 + 1 + i * 5) = -ns(i);
    }


#if 0
    // Experimental MITC4 support.
    // Based on "Short communication A four-node plate bending element based on mindling/reissner plate theory and a mixed interpolation"
    // KJ Bathe, E Dvorkin

    double x1, x2, x3, x4;
    double y1, y2, y3, y4;
    double Ax, Bx, Cx, Ay, By, Cy;

    double r = localCoords[0];
    double s = localCoords[1];

    x1 = lnodes[0][0];
    x2 = lnodes[1][0];
    x3 = lnodes[2][0];
    x4 = lnodes[3][0];

    y1 = lnodes[0][1];
    y2 = lnodes[1][1];
    y3 = lnodes[2][1];
    y4 = lnodes[3][1];

    Ax = x1 - x2 - x3 + x4;
    Bx = x1 - x2 + x3 - x4;
    Cx = x1 + x2 - x3 - x4;

    Ay = y1 - y2 - y3 + y4;
    By = y1 - y2 + y3 - y4;
    Cy = y1 + y2 - y3 - y4;

    FloatMatrix jac;
    this->interp.giveJacobianMatrixAt(jac, localCoords, FEIVertexListGeometryWrapper(lnodes) );
    double detJ = jac.giveDeterminant();

    double rz = sqrt( sqr(Cx + r*Bx) + sqr(Cy + r*By)) / ( 16 * detJ );
    double sz = sqrt( sqr(Ax + s*Bx) + sqr(Ay + s*By)) / ( 16 * detJ );

    // TODO: Not sure about this part (the reference is not explicit about these angles. / Mikael
    // Not sure about the transpose either.
    OOFEM_WARNING("The MITC4 implementation isn't verified yet. Highly experimental");
    FloatArray dxdr = {jac(0,0), jac(0,1)};
    dxdr.normalize();
    FloatArray dxds = {jac(1,0), jac(1,1)};
    dxds.normalize();

    double c_b = dxdr(0); //cos(beta);
    double s_b = dxdr(1); //sin(beta);
    double c_a = dxds(0); //cos(alpha);
    double s_a = dxds(1); //sin(alpha);

    // gamma_xz = "fi_y+dw/dx" in standard formulation
    answer(6, 2 + 5*0) = rz * s_b * ( (1+s)) - sz * s_a * ( (1+r));
    answer(6, 2 + 5*1) = rz * s_b * (-(1+s)) - sz * s_a * ( (1-r));
    answer(6, 2 + 5*2) = rz * s_b * (-(1-s)) - sz * s_a * (-(1-r));
    answer(6, 2 + 5*3) = rz * s_b * ( (1-s)) - sz * s_a * (-(1+r));

    answer(6, 3 + 5*0) = rz * s_b * (y2-y1) * 0.5 * (1+s) - sz * s_a * (y4-y1) * 0.5 * (1+r); // tx1
    answer(6, 4 + 5*0) = rz * s_b * (x1-x2) * 0.5 * (1+s) - sz * s_a * (x1-x4) * 0.5 * (1+r); // ty1

    answer(6, 3 + 5*1) = rz * s_b * (y2-y1) * 0.5 * (1+s) - sz * s_a * (y3-x2) * 0.5 * (1+r); // tx2
    answer(6, 4 + 5*1) = rz * s_b * (x1-x2) * 0.5 * (1+s) - sz * s_a * (x2-x3) * 0.5 * (1+r); // ty2

    answer(6, 3 + 5*2) = rz * s_b * (y3-y4) * 0.5 * (1-s) - sz * s_a * (y3-y2) * 0.5 * (1-r); // tx3
    answer(6, 4 + 5*2) = rz * s_b * (x4-x3) * 0.5 * (1-s) - sz * s_a * (x2-x3) * 0.5 * (1-r); // ty3

    answer(6, 3 + 5*3) = rz * s_b * (y3-y4) * 0.5 * (1-s) - sz * s_a * (y4-y1) * 0.5 * (1-r); // tx4
    answer(6, 4 + 5*3) = rz * s_b * (x4-x3) * 0.5 * (1-s) - sz * s_a * (x1-x4) * 0.5 * (1-r); // ty4

    // gamma_yz = -fi_x+dw/dy in standard formulation
    answer(7, 2 + 5*0) = - rz * c_b * ( (1+s)) + sz * c_a * ( (1+r));
    answer(7, 2 + 5*1) = - rz * c_b * (-(1+s)) + sz * c_a * ( (1-r));
    answer(7, 2 + 5*2) = - rz * c_b * (-(1-s)) + sz * c_a * (-(1-r));
    answer(7, 2 + 5*3) = - rz * c_b * ( (1-s)) + sz * c_a * (-(1+r));

    answer(7, 3 + 5*0) = - rz * c_b * (y2-y1) * 0.5 * (1+s) + sz * c_a * (y4-y1) * 0.5 * (1+r); // tx1
    answer(7, 4 + 5*0) = - rz * c_b * (x1-x2) * 0.5 * (1+s) + sz * c_a * (x1-x4) * 0.5 * (1+r); // ty1

    answer(7, 3 + 5*1) = - rz * c_b * (y2-y1) * 0.5 * (1+s) + sz * c_a * (y3-x2) * 0.5 * (1+r); // tx2
    answer(7, 4 + 5*1) = - rz * c_b * (x1-x2) * 0.5 * (1+s) + sz * c_a * (x2-x3) * 0.5 * (1+r); // ty2

    answer(7, 3 + 5*2) = - rz * c_b * (y3-y4) * 0.5 * (1-s) + sz * c_a * (y3-y2) * 0.5 * (1-r); // tx3
    answer(7, 4 + 5*2) = - rz * c_b * (x4-x3) * 0.5 * (1-s) + sz * c_a * (x2-x3) * 0.5 * (1-r); // ty3

    answer(7, 3 + 5*3) = - rz * c_b * (y3-y4) * 0.5 * (1-s) + sz * c_a * (y4-y1) * 0.5 * (1-r); // tx4
    answer(7, 4 + 5*3) = - rz * c_b * (x4-x3) * 0.5 * (1-s) + sz * c_a * (x1-x4) * 0.5 * (1-r); // ty4
#endif
}
示例#27
0
int	WINAPI WKPluginShowEventX(char szEvent[128],HWND pParent,COleDateTime dt,BOOL bAskMenu)
{
	static long l=0;
	if(l>0){
		return 0;
	}
	SimpleTracker lc(l);

	CString sEventName=_l2("Scheduled event");
	HINSTANCE hLLHookInst=GetModuleHandle("WP_KeyMaster.wkp");
	_WKIHOTKEYS_GetHotkeyDscByID fpHk=(_WKIHOTKEYS_GetHotkeyDscByID)GetProcAddress(hLLHookInst,"WKIHOTKEYS_GetHotkeyDscByID");
	BOOL bDef=(strcmp(szEvent,DEF_ID)==0);
	if(fpHk){
		char szTitle[256]={0};
		if((*fpHk)(szEvent,szTitle,sizeof(szTitle))){
			sEventName=szTitle;
		}else{
			sEventName=_l2("Attention! Time has come!");
		}
	}
	_GetReminder fp=(_GetReminder)GetProcAddress(hRemin,"GetReminder");
	_IsReminderFamilyPresent fpPr=(_IsReminderFamilyPresent)GetProcAddress(hRemin,"IsReminderFamilyPresent");
	CString sRMKey=szEvent;
	// Возможно нужен выбор?
	CStringArray aTitles;
	CStringArray aKeys;
	if(bDef){
		aTitles.SetAtGrow(0,_l2("Add new reminder"));
		aKeys.SetAtGrow(0,sRMKey);
	}else{
		aTitles.SetAtGrow(0,_l2("Add new schedule"));
		aKeys.SetAtGrow(0,sRMKey);
	}
	CString sSelectedKey="";
	if(bAskMenu){
		int iMaxIndex=0;
		if(fpPr && (*fpPr)(sRMKey,&iMaxIndex)){
			aKeys[0]="";
			for(int i=0;i<=iMaxIndex;i++){
				if(fp){
					CWPReminder rem;
					strcpy(rem.szKey,GetNextPrefixedId(sRMKey,i));
					if((*fp)(rem.szKey,rem)){
						AddMapItems(aKeys,aTitles, rem.szKey, GetRemDsc(rem,TRUE));
					}
				}
			}
		}
		if(aKeys.GetSize()==1){
			sRMKey=aKeys[0];
		}else{
			CMenu menu;
			menu.CreatePopupMenu();
			CPoint pt;
			GetCursorPos(&pt);
			for(int i=0;i<aKeys.GetSize();i++){
				AddMenuString(&menu,WM_USER+i,aTitles[i]);
			}
			AddMenuString(&menu,WM_USER+aKeys.GetSize()+1,_l2("Close menu"));
			int iNum=::TrackPopupMenu(menu.GetSafeHmenu(), TPM_RETURNCMD|TPM_NONOTIFY|TPM_RIGHTBUTTON, pt.x, pt.y, 0, pParent, NULL);
			if(iNum==0 || iNum<WM_USER || iNum>=WM_USER+aKeys.GetSize()){
				return 0;
			}
			sSelectedKey=aKeys[iNum-WM_USER];
			if(sSelectedKey==""){
				sSelectedKey=calcNextPrefixedId(sRMKey);
			}
			sRMKey=sSelectedKey;
		}
	}
	BOOL bNewReminder=0;
	CWPReminder rem;
	memset(&rem,0,sizeof(CWPReminder));
	if(fp && sRMKey!=""){
		strcpy(rem.szKey,sRMKey);
		if(!(*fp)(rem.szKey,rem)){
			// Создаем новый!
			bNewReminder=1;
			//COleDateTime dt=COleDateTime::GetCurrentTime();
			dt=dt+COleDateTimeSpan(0,0,1,0);
			dt.GetAsSystemTime(rem.EventTime);
			rem.bActPopup=bDef;
			rem.bActSound=bActSound;
			rem.bLoopSound=bLoopSound;
			strcpy(rem.szText,sEventName);
			strcpy(rem.szSoundPath,szWavFilePath);
			if(!bDef){
				// Здесь именно оригинальный Id-Event!!!
				strcpy(rem.szReserved,szEvent);
			}
			_PutReminder fp2=(_PutReminder)GetProcAddress(hRemin,"PutReminder");
			if(fp2){
				(*fp2)(rem.szKey,rem);
			}
		}
	}
#ifdef _DEBUG
	WKGetPluginContainer()->ShowAlert(rem.szKey,"opened reminder");
#endif
	_CallModifyReminder fp1=(_CallModifyReminder)GetProcAddress(hRemin,"CallModifyReminder");
	if(fp1){
		int iRes=(*fp1)(rem.szKey,pParent,0);
		if(iRes==IDCANCEL && bNewReminder){
			_RemoveReminder fp3=(_RemoveReminder)GetProcAddress(hRemin,"RemoveReminder");
			if(fp3){
				(*fp3)(rem.szKey);
			}
		}
	}
	return 1;
}
示例#28
0
int main(void) {
    plan(60);

    /* lowercase */
    char test[100];
    ok(lc(NULL) == NULL, "lc(NULL)");
    strcpy(test, "Yes"); like(lc(test), "yes", "lc(yes)");
    strcpy(test, "YES"); like(lc(test), "yes", "lc(YES)");
    strcpy(test, "yeS"); like(lc(test), "yes", "lc(yeS)");


    /* trim */
    strcpy(test, "    text  "); like(ltrim(test), "text  ",   "ltrim()");
    strcpy(test, "    text  "); like(rtrim(test), "    text", "rtrim()");
    strcpy(test, "    text  "); like(trim(test),  "text",     "trim()");
    char *test2;
    test2 = strdup("   text   ");  like(trim(test2),  "text", "trim()");
    free(test2);

    /* parse_yes_or_no */
    ok(parse_yes_or_no(NULL,    GM_ENABLED)  == GM_ENABLED, "parse_yes_or_no 1");
    ok(parse_yes_or_no(NULL,    GM_DISABLED) == GM_DISABLED, "parse_yes_or_no 2");
    strcpy(test, "");      ok(parse_yes_or_no(test, GM_ENABLED)  == GM_ENABLED, "parse_yes_or_no 3");
    strcpy(test, "");      ok(parse_yes_or_no(test, GM_DISABLED) == GM_DISABLED, "parse_yes_or_no 4");
    strcpy(test, "yes");   ok(parse_yes_or_no(test, GM_ENABLED)  == GM_ENABLED, "parse_yes_or_no 5");
    strcpy(test, "true");  ok(parse_yes_or_no(test, GM_ENABLED)  == GM_ENABLED, "parse_yes_or_no 6");
    strcpy(test, "Yes");   ok(parse_yes_or_no(test, GM_ENABLED)  == GM_ENABLED, "parse_yes_or_no 7");
    strcpy(test, "1");     ok(parse_yes_or_no(test, GM_ENABLED)  == GM_ENABLED, "parse_yes_or_no 8");
    strcpy(test, "On");    ok(parse_yes_or_no(test, GM_ENABLED)  == GM_ENABLED, "parse_yes_or_no 9");
    strcpy(test, "Off");   ok(parse_yes_or_no(test, GM_ENABLED)  == GM_DISABLED, "parse_yes_or_no 10");
    strcpy(test, "false"); ok(parse_yes_or_no(test, GM_ENABLED)  == GM_DISABLED, "parse_yes_or_no 11");
    strcpy(test, "no");    ok(parse_yes_or_no(test, GM_ENABLED)  == GM_DISABLED, "parse_yes_or_no 12");
    strcpy(test, "0");     ok(parse_yes_or_no(test, GM_ENABLED)  == GM_DISABLED, "parse_yes_or_no 13");


    /* trim */
    ok(trim(NULL) == NULL, "trim(NULL)");
    strcpy(test, " test "); like(trim(test), "^test$", "trim(' test ')");
    strcpy(test, "\ntest\n"); like(trim(test), "^test$", "trim('\\ntest\\n')");

    /* reading keys */
    mod_gm_opt_t *mod_gm_opt;
    mod_gm_opt = malloc(sizeof(mod_gm_opt_t));
    int rc = set_default_options(mod_gm_opt);

    ok(rc == 0, "setting default options");
    mod_gm_opt->keyfile = strdup("t/data/test1.key");
    read_keyfile(mod_gm_opt);
    //printf_hex(mod_gm_opt->crypt_key, 32);
    test[0]='\x0';
    int i = 0;
    char hex[4];
    for(i=0; i<32; i++) {
        hex[0] = '\x0';
        snprintf(hex, 4, "%02x", mod_gm_opt->crypt_key[i]);
        strncat(test, hex, 4);
    }
    like(test, "3131313131313131313131313131313131313131313131313131313131310000", "read keyfile t/data/test1.key");

    free(mod_gm_opt->keyfile);
    mod_gm_opt->keyfile = strdup("t/data/test2.key");
    read_keyfile(mod_gm_opt);

    like(mod_gm_opt->crypt_key, "abcdef", "reading keyfile t/data/test2.key");

    free(mod_gm_opt->keyfile);
    mod_gm_opt->keyfile = strdup("t/data/test3.key");
    read_keyfile(mod_gm_opt);
    //printf_hex(mod_gm_opt->crypt_key, 32);
    like(mod_gm_opt->crypt_key, "11111111111111111111111111111111", "reading keyfile t/data/test3.key");
    ok(strlen(mod_gm_opt->crypt_key) == 32, "key size for t/data/test3.key");


    /* encrypt */
    char * key       = "test1234";
    char * encrypted = malloc(GM_BUFFERSIZE);
    char * text      = "test message";
    char * base      = "a7HqhQEE8TQBde9uknpPYQ==";
    mod_gm_crypt_init(key);
    int len;
    len = mod_gm_encrypt(&encrypted, text, GM_ENCODE_AND_ENCRYPT);
    ok(len == 24, "length of encrypted only");
    like(encrypted, base, "encrypted string");

    /* decrypt */
    char * decrypted = malloc(GM_BUFFERSIZE);
    mod_gm_decrypt(&decrypted, encrypted, GM_ENCODE_AND_ENCRYPT);
    like(decrypted, text, "decrypted text");
    free(decrypted);
    free(encrypted);

    /* base 64 */
    char * base64 = malloc(GM_BUFFERSIZE);
    len = mod_gm_encrypt(&base64, text, GM_ENCODE_ONLY);
    ok(len == 16, "length of encode only");
    like(base64, "dGVzdCBtZXNzYWdl", "base64 only string");

    /* debase 64 */
    char * debase64 = malloc(GM_BUFFERSIZE);
    mod_gm_decrypt(&debase64, base64, GM_ENCODE_ONLY);
    like(debase64, text, "debase64 text");
    free(debase64);
    free(base64);


    /* file_exists */
    ok(file_exists("01_utils") == 1, "file_exists('01_utils')");
    ok(file_exists("non-exist") == 0, "file_exists('non-exist')");

    /* nr2signal */
    char * signame1 = nr2signal(9);
    like(signame1, "SIGKILL", "get SIGKILL for 9");
    free(signame1);

    char * signame2 = nr2signal(15);
    like(signame2, "SIGTERM", "get SIGTERM for 15");
    free(signame2);


    /* string2timeval */
    struct timeval t;
    string2timeval("100.50", &t);
    ok(t.tv_sec  == 100, "string2timeval 1");
    ok(t.tv_usec == 50, "string2timeval 2");

    string2timeval("100", &t);
    ok(t.tv_sec  == 100, "string2timeval 3");
    ok(t.tv_usec == 0, "string2timeval 4");

    string2timeval("", &t);
    ok(t.tv_sec  == 0, "string2timeval 5");
    ok(t.tv_usec == 0, "string2timeval 6");

    string2timeval(NULL, &t);
    ok(t.tv_sec  == 0, "string2timeval 7");
    ok(t.tv_usec == 0, "string2timeval 8");

    /* command line parsing */
    mod_gm_free_opt(mod_gm_opt);
    mod_gm_opt = renew_opts();
    strcpy(test, "server=host:4730");
    parse_args_line(mod_gm_opt, test, 0);
    like(mod_gm_opt->server_list[0], "host:4730", "server=host:4730");
    ok(mod_gm_opt->server_num == 1, "server_number = %d", mod_gm_opt->server_num);

    mod_gm_free_opt(mod_gm_opt);
    mod_gm_opt = renew_opts();
    strcpy(test, "server=:4730");
    parse_args_line(mod_gm_opt, test, 0);
    like(mod_gm_opt->server_list[0], "localhost:4730", "server=:4730");
    ok(mod_gm_opt->server_num == 1, "server_number = %d", mod_gm_opt->server_num);

    mod_gm_free_opt(mod_gm_opt);
    mod_gm_opt = renew_opts();
    strcpy(test, "server=localhost:4730");
    parse_args_line(mod_gm_opt, test, 0);
    strcpy(test, "server=localhost:4730");
    parse_args_line(mod_gm_opt, test, 0);
    like(mod_gm_opt->server_list[0], "localhost:4730", "duplicate server");
    ok(mod_gm_opt->server_num == 1, "server_number = %d", mod_gm_opt->server_num);

    mod_gm_free_opt(mod_gm_opt);
    mod_gm_opt = renew_opts();
    strcpy(test, "server=localhost:4730,localhost:4730,:4730,host:4730,");
    parse_args_line(mod_gm_opt, test, 0);
    like(mod_gm_opt->server_list[0], "localhost:4730", "duplicate server");
    like(mod_gm_opt->server_list[1], "host:4730", "duplicate server");
    ok(mod_gm_opt->server_num == 2, "server_number = %d", mod_gm_opt->server_num);

    /* escape newlines */
    char * escaped = gm_escape_newlines(" test\n", GM_DISABLED);
    is(escaped, " test\\n", "untrimmed escape string");
    free(escaped);
    escaped = gm_escape_newlines(" test\n", GM_ENABLED);
    is(escaped, "test", "trimmed escape string");
    free(escaped);

    /* md5 sum */
    char * sum = NULL;
    strcpy(test, "");
    sum = md5sum(test);
    like(sum, "d41d8cd98f00b204e9800998ecf8427e", "md5sum()");
    free(sum);

    strcpy(test, "The quick brown fox jumps over the lazy dog.");
    sum = md5sum(test);
    like(sum, "e4d909c290d0fb1ca068ffaddf22cbd0", "md5sum()");
    free(sum);

    mod_gm_free_opt(mod_gm_opt);

    return exit_status();
}
示例#29
0
void ReadAnimalsData(lhVec& landHerbs, whVec& waterHerbs, lcVec& landCarns, wcVec& waterCarns, waterVec& wv){
     ifstream myfile("EcosystemFile.txt");
     int waterLines = ReadWaterAreas();
     int grassLines = ReadGrassAreas();
     int algaeLines = ReadAlgaeAreas();
     int animalsLines = ReadAnimalsNumber();
     string line;
     vector <int> values(7);
     char gender;
     if (myfile.is_open()){
        for (int i = 0; i < waterLines + grassLines + algaeLines + animalsLines + 6; i++){
            getline(myfile, line);
            if (i > waterLines + grassLines + algaeLines + 5){
                int found = line.find('|');
                string typeFeeding(line.begin()+ found +1, line.begin()+ found + 1 + 9);
                line.erase(found, 10);
                gender = line[found + 1];
                line.erase(found, 2);
                for (int k = 0; k < line.size(); k++){
                    if (line[k] == ',' || line[k]== '|') line[k] = ' ';
                }
                istringstream iss(line);
                for (int j = 0; j < 7; j++){
                    int val;
                    iss >> val;
                    values[j] = val;
                }
                if (typeFeeding == "herbivore"){
                    bool inWater = false;
                    shared_ptr<Herbivore> h (new Herbivore(values[0], values[1], gender, values[2], values[3], values[4], values[5], values[6]));
                    for(int m = 0; m < wv.size(); m++){
                        if (wv[m]->HasThisCoordinate(*h)){
                            inWater = true;
                            break;
                        }
                    }
                    if (inWater){
                        shared_ptr<WaterHerbivore> wh (new WaterHerbivore(values[0], values[1], gender, values[2], values[3], values[4], values[5], values[6]));
                        waterHerbs.push_back(wh);
                    } else {
                        shared_ptr<LandHerbivore> lh (new LandHerbivore(values[0], values[1], gender, values[2], values[3], values[4], values[5], values[6]));
                        landHerbs.push_back(lh);
                    }
                }
                else if(typeFeeding == "carnivore"){
                    bool inWater = false;
                    shared_ptr<Carnivore> c (new Carnivore(values[0], values[1], gender, values[2], values[3], values[4], values[5], values[6]));
                    for(int m = 0; m < wv.size(); m++){
                        if (wv[m]->HasThisCoordinate(*c)){
                            inWater = true;
                            break;
                        }
                    }
                    if (inWater){
                         shared_ptr<WaterCarnivore> wc (new WaterCarnivore(values[0], values[1], gender, values[2], values[3], values[4], values[5], values[6]));
                         waterCarns.push_back(wc);
                    }else{
                        shared_ptr<LandCarnivore> lc (new LandCarnivore(values[0], values[1], gender, values[2], values[3], values[4], values[5], values[6]));
                        landCarns.push_back(lc);
                    }
                }
            }
        }
    }
示例#30
0
ContourConrec::Result
ContourConrec::compute( NdArray::RawViewInterface * view )
{
    // if no input view was set, we are done
    if ( ! view || m_levels.size() == 0 ) {
        Result result( m_levels.size() );
        return result;
    }

    // the c-algorithm conrec() needs the levels in sorted order (to make things little
    // bit faster), but we would like to report the results in the same order that the
    // levels were requested. So we need to sort the levels, call the conrec(), and
    // then we need to 'unsort' the results...
    typedef std::pair < double, size_t > DI;
    std::vector < DI > tmpLevels( m_levels.size() );
    for ( size_t i = 0 ; i < m_levels.size() ; ++i ) {
        tmpLevels[i].first = m_levels[i];
        tmpLevels[i].second = i;
    }
    auto sort1 = [] ( const DI & a, const DI & b ) {
        return a.first < b.first;
    };
    std::sort( tmpLevels.begin(), tmpLevels.end(), sort1 );
    std::vector < double > sortedRawLevels( m_levels.size() );
    for ( size_t i = 0 ; i < m_levels.size() ; ++i ) {
        sortedRawLevels[i] = tmpLevels[i].first;
    }

    auto m_nRows = view-> dims()[1];
    auto m_nCols = view-> dims()[0];

    // make x coordinates
    VD xcoords( m_nCols );
    for ( int col = 0 ; col < m_nCols ; ++col ) {
        xcoords[col] = col;
    }

    // make y coordinates
    VD ycoords( m_nRows );
    for ( int row = 0 ; row < m_nRows ; ++row ) {
        ycoords[row] = row;
    }

    Result result1 =
        conrecFaster(
            view,
            0,
            m_nCols - 1,
            0,
            m_nRows - 1,
            xcoords,
            ycoords,
            m_levels.size(),
            & sortedRawLevels[0] );

    Result result;
    QRectF rect( 0, 0, m_nCols, m_nRows);
    for( size_t i = 0 ; i < m_levels.size() ; ++ i ) {
        Carta::Lib::Algorithms::LineCombiner lc( rect, m_nRows+1, m_nCols + 1, 1e-9);
        std::vector < QPolygonF > & v = result1[i];
        for( QPolygonF & poly : v) {
            for( int i = 0 ; i < poly.size() - 1 ; ++ i ) {
                lc.add( poly[i], poly[i+1]);
            }
        }
        result.push_back( lc.getPolygons());
        qDebug() << "compress" << v.size() << "-->" << result.back().size();
    }

//    Result result =
//        conrecFaster(
//            view,
//            0,
//            m_nCols - 1,
//            0,
//            m_nRows - 1,
//            xcoords,
//            ycoords,
//            m_levels.size(),
//            & sortedRawLevels[0] );


    // now we 'unsort' the contours based on the requested order
    Result unsortedResult( m_levels.size() );
    for ( size_t i = 0 ; i < m_levels.size() ; ++i ) {
        unsortedResult[tmpLevels[i].second] = result[i];
    }

    return unsortedResult;
} // compute