Esempio n. 1
0
static long
archread(Chan *c, void *a, long n, vlong offset)
{
	char *buf, *p;
	int port;
	ushort *sp;
	ulong *lp;
	vlong *vp;
	IOMap *m;
	Rdwrfn *fn;

	switch((ulong)c->qid.path){

	case Qdir:
		return devdirread(c, a, n, archdir, narchdir, devgen);

	case Qiob:
		port = offset;
		checkport(offset, offset+n);
		for(p = a; port < offset+n; port++)
			*p++ = inb(port);
		return n;

	case Qiow:
		if(n & 1)
			error(Ebadarg);
		checkport(offset, offset+n);
		sp = a;
		for(port = offset; port < offset+n; port += 2)
			*sp++ = ins(port);
		return n;

	case Qiol:
		if(n & 3)
			error(Ebadarg);
		checkport(offset, offset+n);
		lp = a;
		for(port = offset; port < offset+n; port += 4)
			*lp++ = inl(port);
		return n;

	case Qmsr:
		if(n & 7)
			error(Ebadarg);
		vp = a;
		for(port = offset; port < offset+n; port += 8)
			if(rdmsr(port, vp++) < 0)
				error(Ebadarg);
		return n;

	case Qioalloc:
		break;

	default:
		if(c->qid.path < narchdir && (fn = readfn[c->qid.path]))
			return fn(c, a, n, offset);
		error(Eperm);
		break;
	}

	if((buf = malloc(n)) == nil)
		error(Enomem);
	p = buf;
	n = n/Linelen;
	offset = offset/Linelen;

	lock(&iomap);
	for(m = iomap.m; n > 0 && m != nil; m = m->next){
		if(offset-- > 0)
			continue;
		sprint(p, "%8lux %8lux %-12.12s\n", m->start, m->end-1, m->tag);
		p += Linelen;
		n--;
	}
	unlock(&iomap);

	n = p - buf;
	memmove(a, buf, n);
	free(buf);

	return n;
}
Esempio n. 2
0
void op_compins()
{
 ins(TRUE);
}
Esempio n. 3
0
 __inline void bi_ins(int u0, int v0) {  // bi-directional
     ins(u0, v0); ins(v0, u0);
 }
Esempio n. 4
0
enum KeyStatus ins(struct node *ptr, int key, int *upKey,struct node **newnode)
{
	struct node *newPtr, *lastPtr;
	int pos, i, n,splitPos;
	int newKey, lastKey;
	enum KeyStatus value;
//	printf("\n\n ptr: %d \n\n",ptr);
//	getch();
	if (ptr == NULL)
	{
		*newnode = NULL;
		*upKey = key;
		return InsertIt;
	}
	n = ptr->n;
	pos = searchPos(key, ptr->keys, n);
	if (pos < n && key == ptr->keys[pos])
		return Duplicate;
	value = ins(ptr->p[pos], key, &newKey, &newPtr);
	if (value != InsertIt)
		return value;
	/*If keys in node is less than M-1 where M is order of B tree*/
	if (n < M - 1)
	{
		pos = searchPos(newKey, ptr->keys, n);
		/*Shifting the key and pointer right for inserting the new key*/
		for (i=n; i>pos; i--)
		{
			ptr->keys[i] = ptr->keys[i-1];
			ptr->p[i+1] = ptr->p[i];
		}
		/*Key is inserted at exact location*/
		ptr->keys[pos] = newKey;
		ptr->p[pos+1] = newPtr;
		++ptr->n; /*incrementing the number of keys in node*/
		return Success;
	}/*End of if */
	/*If keys in nodes are maximum and position of node to be inserted is last*/
	if (pos == M - 1)
	{
		lastKey = newKey;
		lastPtr = newPtr;
	}
	else /*If keys in node are maximum and position of node to be inserted is not last*/
	{
		lastKey = ptr->keys[M-2];
		lastPtr = ptr->p[M-1];
		for (i=M-2; i>pos; i--)
		{
			ptr->keys[i] = ptr->keys[i-1];
			ptr->p[i+1] = ptr->p[i];
		}
		ptr->keys[pos] = newKey;
		ptr->p[pos+1] = newPtr;
	}
	splitPos = (M - 1)/2;
       (*upKey) = ptr->keys[splitPos];

	(*newnode)=(node *)malloc(sizeof(struct node));/*Right node after split*/
	ptr->n = splitPos; /*No. of keys for left splitted node*/
	(*newnode)->n = M-1-splitPos;/*No. of keys for right splitted node*/
	for (i=0; i < (*newnode)->n; i++)
	{
		(*newnode)->p[i] = ptr->p[i + splitPos + 1];
		if(i < (*newnode)->n - 1)
			(*newnode)->keys[i] = ptr->keys[i + splitPos + 1];
		else
			(*newnode)->keys[i] = lastKey;
	}
	(*newnode)->p[(*newnode)->n] = lastPtr;
	return InsertIt;
}
Esempio n. 5
0
astring &astring::inssubstr(int insbefore, const astring &src, int start, int count)
{
	normalize_substr(start, count, src.len());
	return ins(insbefore, src.m_text + start, count);
}
Esempio n. 6
0
void DrawLab::insDot(Point point)
 {
  ins(map(point));
 }
Esempio n. 7
0
static int
reset(Ether* ether)
{
	int i, t, slot;
	char *type;
	int port;
	enum { WantAny, Want10BT, Want10B2 };
	int want;
	uchar ea[6];
	char *p;

	if(ether->irq == 0)
		ether->irq = 10;
	if(ether->port == 0)
		ether->port = 0x240;
	port = ether->port;

	if(ioalloc(port, 0x10, 0, "3C589") < 0)
		return -1;

	type = nil;
	slot = -1;
	for(i = 0; tcmpcmcia[i] != nil; i++){
		type = tcmpcmcia[i];
		if((slot = pcmspecial(type, ether)) >= 0)
			break;
	}
	ether->type = type;	/* must be set before calling configASIC */
	if(slot < 0){
		iofree(port);
		return -1;
	}

	/*
	 * Read Ethernet address from card memory
	 * on 3C562, but only if the user has not 
	 * overridden it.
	 */
	memset(ea, 0, sizeof ea);
	if(memcmp(ea, ether->ea, 6) == 0 && strcmp(type, "3C562") == 0) {
		if(pcmcistuple(slot, 0x88, -1, ea, 6) == 6) {
			for(i = 0; i < 6; i += 2){
				t = ea[i];
				ea[i] = ea[i+1];
				ea[i+1] = t;
			}
			memmove(ether->ea, ea, 6);
		}
	}
	/*
	 * Allow user to specify desired media in plan9.ini
	 */
	want = WantAny;
	for(i = 0; i < ether->nopt; i++){
		if(cistrncmp(ether->opt[i], "media=", 6) != 0)
			continue;
		p = ether->opt[i]+6;
		if(cistrcmp(p, "10base2") == 0)
			want = Want10B2;
		else if(cistrcmp(p, "10baseT") == 0)
			want = Want10BT;
	}
	
	/* try configuring as a 10BaseT */
	if(want==WantAny || want==Want10BT){
		if(configASIC(ether, port, xcvr10BaseT) < 0){
			pcmspecialclose(slot);
			iofree(port);
			return -1;
		}
		delay(100);
		COMMAND(port, SelectRegisterWindow, Wdiagnostic);
		if((ins(port+MediaStatus)&linkBeatDetect) || want==Want10BT){
			COMMAND(port, SelectRegisterWindow, Wop);
			print("#l%d: xcvr10BaseT %s\n", ether->ctlrno, type);
			return 0;
		}
	}

	/* try configuring as a 10base2 */
	if(want==WantAny || want==Want10B2){
		COMMAND(port, GlobalReset, 0);
		if(configASIC(ether, port, xcvr10Base2) < 0){
			pcmspecialclose(slot);
			iofree(port);
			return -1;
		}
		print("#l%d: xcvr10Base2 %s\n", ether->ctlrno, type);
		return 0;
	}
	return -1;		/* not reached */
}
Esempio n. 8
0
	void addedge(int&a,int&b,int f){getp(a);getp(b);ins(a,b,f);ins(b,a,0);}
void run_test()
{
  typedef mtl::dense2D<ScalarType>        MTL4DenseMatrix;
  typedef mtl::compressed2D<ScalarType>   MTL4SparseMatrix;
  
  //
  // Create and fill dense matrices from the MTL4 library:
  //
  mtl::dense2D<ScalarType>   mtl4_densemat(5, 5);
  mtl::dense2D<ScalarType>   mtl4_densemat2(5, 5);
  mtl4_densemat(0,0) = 2.0;   mtl4_densemat(0,1) = -1.0;
  mtl4_densemat(1,0) = -1.0;  mtl4_densemat(1,1) =  2.0;  mtl4_densemat(1,2) = -1.0;
  mtl4_densemat(2,1) = -1.0;  mtl4_densemat(2,2) = -1.0;  mtl4_densemat(2,3) = -1.0;
  mtl4_densemat(3,2) = -1.0;  mtl4_densemat(3,3) =  2.0;  mtl4_densemat(3,4) = -1.0;
                              mtl4_densemat(4,4) = -1.0;  mtl4_densemat(4,4) = -1.0;
  
  
  //
  // Create and fill sparse matrices from the MTL4 library:
  //
  MTL4SparseMatrix mtl4_sparsemat;
  set_to_zero(mtl4_sparsemat);  
  mtl4_sparsemat.change_dim(5, 5);

  MTL4SparseMatrix mtl4_sparsemat2;
  set_to_zero(mtl4_sparsemat2);  
  mtl4_sparsemat2.change_dim(5, 5);
  
  {
    mtl::matrix::inserter< MTL4SparseMatrix >  ins(mtl4_sparsemat);
    typedef typename mtl::Collection<MTL4SparseMatrix>::value_type  ValueType;
    ins(0,0) <<  ValueType(2.0);   ins(0,1) << ValueType(-1.0);
    ins(1,1) <<  ValueType(2.0);   ins(1,2) << ValueType(-1.0);
    ins(2,2) << ValueType(-1.0);   ins(2,3) << ValueType(-1.0);
    ins(3,3) <<  ValueType(2.0);   ins(3,4) << ValueType(-1.0);
    ins(4,4) << ValueType(-1.0);
  }
  
  //
  // Create and fill a few vectors from the MTL4 library:
  //
  mtl::dense_vector<ScalarType> mtl4_rhs(5, 0.0);
  mtl::dense_vector<ScalarType> mtl4_result(5, 0.0);
  mtl::dense_vector<ScalarType> mtl4_temp(5, 0.0);
  

  mtl4_rhs(0) = 10.0;
  mtl4_rhs(1) = 11.0;
  mtl4_rhs(2) = 12.0;
  mtl4_rhs(3) = 13.0;
  mtl4_rhs(4) = 14.0;
  
  //
  // Let us create the ViennaCL analogues:
  //
  viennacl::vector<ScalarType> vcl_rhs(5);
  viennacl::vector<ScalarType> vcl_result(5);
  viennacl::matrix<ScalarType> vcl_densemat(5, 5);
  viennacl::compressed_matrix<ScalarType> vcl_sparsemat(5, 5);

  //
  // Directly copy the MTL4 objects to ViennaCL objects
  //
  viennacl::copy(&(mtl4_rhs[0]), &(mtl4_rhs[0]) + 5, vcl_rhs.begin());  //method 1: via iterator interface (cf. std::copy())
  viennacl::copy(mtl4_rhs, vcl_rhs);  //method 2: via built-in wrappers (convenience layer)
  
  viennacl::copy(mtl4_densemat, vcl_densemat);
  viennacl::copy(mtl4_sparsemat, vcl_sparsemat);
  
  // For completeness: Copy matrices from ViennaCL back to Eigen:
  viennacl::copy(vcl_densemat, mtl4_densemat2);
  viennacl::copy(vcl_sparsemat, mtl4_sparsemat2);
  
  //
  // Run matrix-vector products and compare results:
  //
  mtl4_result = mtl4_densemat * mtl4_rhs;
  vcl_result = viennacl::linalg::prod(vcl_densemat, vcl_rhs);
  viennacl::copy(vcl_result, mtl4_temp);
  mtl4_result -= mtl4_temp;
  std::cout << "Difference for dense matrix-vector product: " << mtl::two_norm(mtl4_result) << std::endl;
  mtl4_result = mtl4_densemat2 * mtl4_rhs - mtl4_temp;
  std::cout << "Difference for dense matrix-vector product (MTL4->ViennaCL->MTL4): "
            << mtl::two_norm(mtl4_result) << std::endl;
  
  //
  // Same for sparse matrix:
  //          
  mtl4_result = mtl4_sparsemat * mtl4_rhs;
  vcl_result = viennacl::linalg::prod(vcl_sparsemat, vcl_rhs);
  viennacl::copy(vcl_result, mtl4_temp);
  mtl4_result -= mtl4_temp;
  std::cout << "Difference for sparse matrix-vector product: " << mtl::two_norm(mtl4_result) << std::endl;
  mtl4_result = mtl4_sparsemat2 * mtl4_rhs - mtl4_temp;
  std::cout << "Difference for sparse matrix-vector product (MTL4->ViennaCL->MTL4): "
            << mtl::two_norm(mtl4_result) << std::endl;
            
  //
  // Please have a look at the other tutorials on how to use the ViennaCL types
  //
}
Esempio n. 10
0
int
nrrdArithIterAffine(Nrrd *nout, NrrdIter *minIn,
                    NrrdIter *in, NrrdIter *maxIn,
                    NrrdIter *minOut, NrrdIter *maxOut, int clamp) {
  static const char me[]="nrrdArithInterAffine";
  double (*ins)(void *v, size_t I, double d),
    mini, vin, maxi, mino, maxo, vout;
  const Nrrd *nin;
  char *contA, *contB, *contC, *contD, *contE;
  size_t I, N;

  if (!(nout && minIn && in && maxIn && minOut && maxOut)) {
    biffAddf(NRRD, "%s: got NULL pointer", me);
    return 1;
  }
  nin = (_NRRD_ITER_NRRD(in)
         ? _NRRD_ITER_NRRD(in)
         : (_NRRD_ITER_NRRD(minIn)
            ? _NRRD_ITER_NRRD(minIn)
            : (_NRRD_ITER_NRRD(maxIn)
               ? _NRRD_ITER_NRRD(maxIn)
               : (_NRRD_ITER_NRRD(minOut)
                  ? _NRRD_ITER_NRRD(minOut)
                  : _NRRD_ITER_NRRD(maxOut)))));
  if (!nin) {
    biffAddf(NRRD, "%s: can't operate solely on fixed values", me);
    return 1;
  }
  if (nrrdCopy(nout, nin)) {
    biffAddf(NRRD, "%s: couldn't initialize output", me);
    return 1;
  }
  N = nrrdElementNumber(nin);
  ins = nrrdDInsert[nout->type];
  for (I=0; I<N; I++) {
    mini = nrrdIterValue(minIn);
    vin = nrrdIterValue(in);
    maxi = nrrdIterValue(maxIn);
    mino = nrrdIterValue(minOut);
    maxo = nrrdIterValue(maxOut);
    vout = AIR_AFFINE(mini, vin, maxi, mino, maxo);
    if (clamp) {
      double mmin = AIR_MIN(mino, maxo);
      double mmax = AIR_MAX(mino, maxo);
      vout = AIR_CLAMP(mmin, vout, mmax);
    }
    ins(nout->data, I, vout);
  }
  contA = nrrdIterContent(in);
  contB = nrrdIterContent(minIn);
  contC = nrrdIterContent(maxIn);
  contD = nrrdIterContent(maxOut);
  contE = nrrdIterContent(maxOut);
  /* HEY: same annoyance about order of arguments as in function above */
  if (_nrrdContentSet_va(nout, "affine", contA, "%s,%s,%s,%s",
                         contB, contC, contD, contE)) {
    biffAddf(NRRD, "%s:", me);
    free(contA); free(contB); free(contC); free(contD); free(contE); return 1;
  }
  free(contA); free(contB); free(contC); free(contD); free(contE);

  return 0;
}
Esempio n. 11
0
int
main(int argc, char *argv[]) {
  char *me, *outS;
  hestOpt *hopt;
  hestParm *hparm;
  airArray *mop;

  char *err, done[13];
  Nrrd *nin, *nblur, *nout;
  NrrdKernelSpec *kb0, *kb1, *k00, *k11, *k22;
  NrrdResampleContext *rsmc;
  int E;
  unsigned int sx, sy, sz, xi, yi, zi, ai;
  gageContext *ctx;
  gagePerVolume *pvl;
  const double *gvec, *gmag, *evec0, *eval;
  double (*ins)(void *v, size_t I, double d);
  double (*lup)(const void *v, size_t I);
  double dotmax, dotpow, gmmax, evalshift, gmpow, _dotmax, _gmmax, scl, clamp;

  me = argv[0];
  mop = airMopNew();
  hparm = hestParmNew();
  hopt = NULL;
  airMopAdd(mop, hparm, (airMopper)hestParmFree, airMopAlways);
  hestOptAdd(&hopt, "i", "nin", airTypeOther, 1, 1, &nin, NULL,
             "input volume", NULL, NULL, nrrdHestNrrd);
  hestOptAdd(&hopt, "kb0", "kernel", airTypeOther, 1, 1, &kb0,
             "guass:3,5", "kernel to use for pre-process blurring",
             NULL, NULL, nrrdHestKernelSpec);
  hestOptAdd(&hopt, "kb1", "kernel", airTypeOther, 1, 1, &kb1,
             "cubic:1.5,1,0", "kernel to use for pos-process blurring",
             NULL, NULL, nrrdHestKernelSpec);
  hestOptAdd(&hopt, "k00", "kernel", airTypeOther, 1, 1, &k00,
             "cubic:1,0", "k00", NULL, NULL, nrrdHestKernelSpec);
  hestOptAdd(&hopt, "k11", "kernel", airTypeOther, 1, 1, &k11,
             "cubicd:1,0", "k00", NULL, NULL, nrrdHestKernelSpec);
  hestOptAdd(&hopt, "k22", "kernel", airTypeOther, 1, 1, &k22,
             "cubicdd:1,0", "k00", NULL, NULL, nrrdHestKernelSpec);
  hestOptAdd(&hopt, "dotmax", "dot", airTypeDouble, 1, 1, &dotmax, "5",
             "max effective value of dot(gvec, evec0)");
  hestOptAdd(&hopt, "evs", "shift", airTypeDouble, 1, 1, &evalshift, "0",
             "negative shift to avoid changing mostly flat regions");
  hestOptAdd(&hopt, "clamp", "clamp", airTypeDouble, 1, 1, &clamp, "nan",
             "if it exists, data value can't be forced below this");
  hestOptAdd(&hopt, "dotpow", "pow", airTypeDouble, 1, 1, &dotpow, "1",
             "exponent for dot");
  hestOptAdd(&hopt, "gmmax", "dot", airTypeDouble, 1, 1, &gmmax, "2",
             "max effective value of gmag");
  hestOptAdd(&hopt, "gmpow", "pow", airTypeDouble, 1, 1, &gmpow, "1",
             "exponent for gmag");
  hestOptAdd(&hopt, "scl", "scale", airTypeDouble, 1, 1, &scl, "0.1",
             "how much to scale hack to decrease input value");
  hestOptAdd(&hopt, "o", "filename", airTypeString, 1, 1, &outS, "-",
             "fixed volume output");
  hestParseOrDie(hopt, argc-1, argv+1, hparm,
                 me, vhInfo, AIR_TRUE, AIR_TRUE, AIR_TRUE);
  airMopAdd(mop, hopt, (airMopper)hestOptFree, airMopAlways);
  airMopAdd(mop, hopt, (airMopper)hestParseFree, airMopAlways);

  if (!( 3 == nin->dim
         && nrrdTypeBlock != nin->type )) {
    fprintf(stderr, "%s: need a 3-D scalar nrrd (not %u-D %s)", me,
            nin->dim, airEnumStr(nrrdType, nin->type));
    airMopError(mop); return 1;
  }

  nblur = nrrdNew();
  airMopAdd(mop, nblur, (airMopper)nrrdNuke, airMopAlways);
  if (nrrdCopy(nblur, nin)) {
    airMopAdd(mop, err = biffGetDone(NRRD), airFree, airMopAlways);
    fprintf(stderr, "%s: couldn't allocate output:\n%s", me, err);
    airMopError(mop); return 1;
  }

  fprintf(stderr, "%s: pre-blurring ... ", me);
  fflush(stderr);
  rsmc = nrrdResampleContextNew();
  airMopAdd(mop, rsmc, (airMopper)nrrdResampleContextNix, airMopAlways);
  E = AIR_FALSE;
  if (!E) E |= nrrdResampleDefaultCenterSet(rsmc, nrrdCenterCell);
  if (!E) E |= nrrdResampleNrrdSet(rsmc, nin);
  for (ai=0; ai<3; ai++) {
    if (!E) E |= nrrdResampleKernelSet(rsmc, ai, kb0->kernel, kb0->parm);
    if (!E) E |= nrrdResampleSamplesSet(rsmc, ai, nin->axis[ai].size);
    if (!E) E |= nrrdResampleRangeFullSet(rsmc, ai);
  }
  if (!E) E |= nrrdResampleBoundarySet(rsmc, nrrdBoundaryBleed);
  if (!E) E |= nrrdResampleTypeOutSet(rsmc, nrrdTypeDefault);
  if (!E) E |= nrrdResampleRenormalizeSet(rsmc, AIR_TRUE);
  if (!E) E |= nrrdResampleExecute(rsmc, nblur);
  if (E) {
    airMopAdd(mop, err = biffGetDone(NRRD), airFree, airMopAlways);
    fprintf(stderr, "%s: error resampling nrrd:\n%s", me, err);
    airMopError(mop);
    return 1;
  }
  fprintf(stderr, "done.\n");

  ctx = gageContextNew();
  airMopAdd(mop, ctx, (airMopper)gageContextNix, airMopAlways);
  gageParmSet(ctx, gageParmRenormalize, AIR_TRUE);
  gageParmSet(ctx, gageParmCheckIntegrals, AIR_TRUE);
  E = 0;
  if (!E) E |= !(pvl = gagePerVolumeNew(ctx, nblur, gageKindScl));
  if (!E) E |= gagePerVolumeAttach(ctx, pvl);
  if (!E) E |= gageKernelSet(ctx, gageKernel00, k00->kernel, k00->parm);
  if (!E) E |= gageKernelSet(ctx, gageKernel11, k11->kernel, k11->parm);
  if (!E) E |= gageKernelSet(ctx, gageKernel22, k22->kernel, k22->parm);
  if (!E) E |= gageQueryItemOn(ctx, pvl, gageSclGradVec);
  if (!E) E |= gageQueryItemOn(ctx, pvl, gageSclGradMag);
  if (!E) E |= gageQueryItemOn(ctx, pvl, gageSclHessEvec0);
  if (!E) E |= gageQueryItemOn(ctx, pvl, gageSclHessEval);
  if (!E) E |= gageUpdate(ctx);
  if (E) {
    airMopAdd(mop, err = biffGetDone(GAGE), airFree, airMopAlways);
    fprintf(stderr, "%s: trouble:\n%s\n", me, err);
    airMopError(mop); return 1;
  }
  gvec = gageAnswerPointer(ctx, pvl, gageSclGradVec);
  gmag = gageAnswerPointer(ctx, pvl, gageSclGradMag);
  evec0 = gageAnswerPointer(ctx, pvl, gageSclHessEvec0);
  eval = gageAnswerPointer(ctx, pvl, gageSclHessEval);

  nout = nrrdNew();
  airMopAdd(mop, nout, (airMopper)nrrdNuke, airMopAlways);
  if (nrrdCopy(nout, nin)) {
    airMopAdd(mop, err = biffGetDone(NRRD), airFree, airMopAlways);
    fprintf(stderr, "%s: couldn't allocate output:\n%s", me, err);
    airMopError(mop); return 1;
  }

  if (!(nout->type == nin->type && nblur->type == nin->type)) {
    fprintf(stderr, "%s: whoa, types (%s %s %s) not all equal\n", me,
            airEnumStr(nrrdType, nin->type),
            airEnumStr(nrrdType, nblur->type),
            airEnumStr(nrrdType, nout->type));
  }
  ins = nrrdDInsert[nout->type];
  lup = nrrdDLookup[nout->type];
  sx = nin->axis[0].size;
  sy = nin->axis[1].size;
  sz = nin->axis[2].size;

  gageProbe(ctx, 0, 0, 0);
  _dotmax = ELL_3V_DOT(gvec, evec0);
  _gmmax = *gmag;

  fprintf(stderr, "%s: hacking       ", me);
  fflush(stderr);
  for (zi=0; zi<sz; zi++) {
    fprintf(stderr, "%s", airDoneStr(0, zi, sz-1, done));
    fflush(stderr);
    for (yi=0; yi<sy; yi++) {
      for (xi=0; xi<sx; xi++) {
        size_t si;
        double dot, evl, gm, shift, in, out, mode;

        gageProbe(ctx, xi, yi, zi);
        si = xi + sx*(yi + sy*zi);

        dot = ELL_3V_DOT(gvec, evec0);
        _dotmax = AIR_MAX(_dotmax, dot);
        dot = AIR_ABS(dot);
        dot = 1 - AIR_MIN(dot, dotmax)/dotmax;
        dot = pow(dot, dotpow);

        evl = AIR_MAX(0, eval[0] - evalshift);
        mode = airMode3_d(eval);
        evl *= AIR_AFFINE(-1, mode, 1, 0, 1);

        _gmmax = AIR_MAX(_gmmax, *gmag);
        gm = 1 - AIR_MIN(*gmag, gmmax)/gmmax;
        gm = pow(gm, gmpow);

        shift = scl*gm*evl*dot;
        if (AIR_EXISTS(clamp)) {
          in = lup(nin->data, si);
          out = in - shift;
          out = AIR_MAX(out, clamp);
          shift = AIR_MAX(0, in - out);
        }

        ins(nout->data, si, shift);
      }
    }
  }
  fprintf(stderr, "\n");
  fprintf(stderr, "%s: max dot seen: %g\n", me, _dotmax);
  fprintf(stderr, "%s: max gm seen: %g\n", me, _gmmax);

  fprintf(stderr, "%s: post-blurring ... ", me);
  fflush(stderr);
  E = AIR_FALSE;
  if (!E) E |= nrrdResampleNrrdSet(rsmc, nout);
  for (ai=0; ai<3; ai++) {
    if (!E) E |= nrrdResampleKernelSet(rsmc, ai, kb1->kernel, kb1->parm);
    if (!E) E |= nrrdResampleSamplesSet(rsmc, ai, nout->axis[ai].size);
    if (!E) E |= nrrdResampleRangeFullSet(rsmc, ai);
  }
  if (!E) E |= nrrdResampleExecute(rsmc, nblur);
  if (E) {
    airMopAdd(mop, err = biffGetDone(NRRD), airFree, airMopAlways);
    fprintf(stderr, "%s: error resampling nrrd:\n%s", me, err);
    airMopError(mop);
    return 1;
  }
  fprintf(stderr, "done.\n");

  for (zi=0; zi<sz; zi++) {
    for (yi=0; yi<sy; yi++) {
      for (xi=0; xi<sx; xi++) {
        size_t si;
        double in, shift;

        si = xi + sx*(yi + sy*zi);
        in = lup(nin->data, si);
        shift = lup(nblur->data, si);
        ins(nout->data, si, in - shift);
      }
    }
  }

  if (nrrdSave(outS, nout, NULL)) {
    airMopAdd(mop, err = biffGetDone(NRRD), airFree, airMopAlways);
    fprintf(stderr, "%s: couldn't save output:\n%s", me, err);
    airMopError(mop); return 1;
  }

  airMopOkay(mop);
  exit(0);
}
Esempio n. 12
0
/*
******** nrrdArithTerneryOp
**
** HEY: UNTESTED UNTESTED UNTESTED UNTESTED UNTESTED UNTESTED UNTESTED
**
** this is a simplified version of nrrdArithIterTernaryOp, written after
** that, in a hurry, to operate directly on three nrrds, instead with
** the NrrdIter nonsense
*/
int
nrrdArithTernaryOp(Nrrd *nout, int op, const Nrrd *ninA,
                   const Nrrd *ninB, const Nrrd *ninC) {
  static const char me[]="nrrdArithTernaryOp";
  char *contA, *contB, *contC;
  size_t N, I, size[NRRD_DIM_MAX];
  double (*ins)(void *v, size_t I, double d),
    (*lupA)(const void *v, size_t I), (*lupB)(const void *v, size_t I),
    (*lupC)(const void *v, size_t I),
    (*top)(double a, double b, double c), valA, valB, valC;

  if (!( nout && !nrrdCheck(ninA) && !nrrdCheck(ninB) && !nrrdCheck(ninC) )) {
    biffAddf(NRRD, "%s: NULL pointer or invalid args", me);
    return 1;
  }
  if (!( nrrdSameSize(ninA, ninB, AIR_TRUE) &&
         nrrdSameSize(ninA, ninC, AIR_TRUE) )) {
    biffAddf(NRRD, "%s: size mismatch between arguments", me);
    return 1;
  }
  if (airEnumValCheck(nrrdTernaryOp, op)) {
    biffAddf(NRRD, "%s: ternary op %d invalid", me, op);
    return 1;
  }

  nrrdAxisInfoGet_nva(ninA, nrrdAxisInfoSize, size);
  if (!( nout == ninA || nout == ninB || nout == ninC)) {
    if (_nrrdMaybeAllocMaybeZero_nva(nout, ninA->type, ninA->dim, size,
                                     AIR_FALSE /* zero when no realloc */)) {
      biffAddf(NRRD, "%s: couldn't allocate output nrrd", me);
      return 1;
    }
    if (nrrdAxisInfoCopy(nout, ninA, NULL, NRRD_AXIS_INFO_NONE)) {
      biffAddf(NRRD, "%s:", me);
      return 1;
    }
    nrrdBasicInfoCopy(nout, ninA, (NRRD_BASIC_INFO_DATA_BIT
                                   | NRRD_BASIC_INFO_TYPE_BIT
                                   | NRRD_BASIC_INFO_DIMENSION_BIT
                                   | NRRD_BASIC_INFO_CONTENT_BIT
                                   | NRRD_BASIC_INFO_COMMENTS_BIT
                                   | (nrrdStateKeyValuePairsPropagate
                                      ? 0
                                      : NRRD_BASIC_INFO_KEYVALUEPAIRS_BIT)));
  }
  nrrdBasicInfoInit(nout,
                    NRRD_BASIC_INFO_ALL ^ (NRRD_BASIC_INFO_OLDMIN_BIT
                                           | NRRD_BASIC_INFO_OLDMAX_BIT));
  top = _nrrdTernaryOp[op];

  N = nrrdElementNumber(ninA);
  lupA = nrrdDLookup[ninA->type];
  lupB = nrrdDLookup[ninB->type];
  lupC = nrrdDLookup[ninC->type];
  ins = nrrdDInsert[nout->type];
  for (I=0; I<N; I++) {
    /* HEY: there is a loss of precision issue here with 64-bit ints */
    valA = lupA(ninA->data, I);
    valB = lupB(ninB->data, I);
    valC = lupC(ninC->data, I);
    ins(nout->data, I, top(valA, valB, valC));
  }

  contA = _nrrdContentGet(ninA);
  contB = _nrrdContentGet(ninB);
  contC = _nrrdContentGet(ninC);
  if (_nrrdContentSet_va(nout, airEnumStr(nrrdTernaryOp, op),
                         contA, "%s,%s", contB, contC)) {
    biffAddf(NRRD, "%s:", me);
    free(contA); free(contB); free(contC); return 1;
  }
  free(contA);
  free(contB);
  free(contC);

  return 0;
}
Esempio n. 13
0
/*
******** nrrdArithGamma()
**
** map the values in a nrrd through a power function; essentially:
** val = pow(val, 1/gamma), but this is after the val has been normalized
** to be in the range of 0.0 to 1.0 (assuming that the given min and
** max really are the full range of the values in the nrrd).  Thus,
** the given min and max values are fixed points of this
** transformation.  Using a negative gamma means that after the pow()
** function has been applied, the value is inverted with respect to
** min and max (like in xv).
*/
int
nrrdArithGamma(Nrrd *nout, const Nrrd *nin,
               const NrrdRange *_range, double Gamma) {
  static const char me[]="nrrdArithGamma", func[]="gamma";
  double val, min, max;
  size_t I, num;
  NrrdRange *range;
  airArray *mop;
  double (*lup)(const void *, size_t);
  double (*ins)(void *, size_t, double);

  if (!(nout && nin)) {
    /* _range can be NULL */
    biffAddf(NRRD, "%s: got NULL pointer", me);
    return 1;
  }
  if (!( AIR_EXISTS(Gamma) )) {
    biffAddf(NRRD, "%s: gamma doesn't exist", me);
    return 1;
  }
  if (!( nrrdTypeBlock != nin->type && nrrdTypeBlock != nout->type )) {
    biffAddf(NRRD, "%s: can't deal with %s type", me,
             airEnumStr(nrrdType, nrrdTypeBlock));
    return 1;
  }
  if (nout != nin) {
    if (nrrdCopy(nout, nin)) {
      biffAddf(NRRD, "%s: couldn't initialize by copy to output", me);
      return 1;
    }
  }
  mop = airMopNew();
  if (_range) {
    range = nrrdRangeCopy(_range);
    nrrdRangeSafeSet(range, nin, nrrdBlind8BitRangeState);
  } else {
    range = nrrdRangeNewSet(nin, nrrdBlind8BitRangeTrue);
  }
  airMopAdd(mop, range, (airMopper)nrrdRangeNix, airMopAlways);
  min = range->min;
  max = range->max;
  if (min == max) {
    /* this is stupid.  We want min < max to avoid making NaNs */
    max += 1;
  }
  lup = nrrdDLookup[nin->type];
  ins = nrrdDInsert[nout->type];
  Gamma = 1/Gamma;
  num = nrrdElementNumber(nin);
  if (Gamma < 0.0) {
    Gamma = -Gamma;
    for (I=0; I<num; I++) {
      val = lup(nin->data, I);
      val = AIR_AFFINE(min, val, max, 0.0, 1.0);
      val = pow(val, Gamma);
      val = AIR_AFFINE(1.0, val, 0.0, min, max);
      ins(nout->data, I, val);
    }
  } else {
    for (I=0; I<num; I++) {
      val = lup(nin->data, I);
      val = AIR_AFFINE(min, val, max, 0.0, 1.0);
      val = pow(val, Gamma);
      val = AIR_AFFINE(0.0, val, 1.0, min, max);
      ins(nout->data, I, val);
    }
  }
  if (nrrdContentSet_va(nout, func, nin, "%g,%g,%g", min, max, Gamma)) {
    biffAddf(NRRD, "%s:", me);
    airMopError(mop); return 1;
  }
  if (nout != nin) {
    nrrdAxisInfoCopy(nout, nin, NULL, NRRD_AXIS_INFO_NONE);
  }
  /* basic info handled by nrrdCopy above */

  airMopOkay(mop);
  return 0;
}
Esempio n. 14
0
int
mossLinearTransform (Nrrd *nout, Nrrd *nin, float *bg,
                     double *mat, mossSampler *msp,
                     double xMin, double xMax,
                     double yMin, double yMax,
                     int xSize, int ySize) {
  char me[]="mossLinearTransform", err[BIFF_STRLEN];
  int ncol, xi, yi, ci, ax0, xCent, yCent;
  float *val, (*ins)(void *v, size_t I, float f), (*clamp)(float val);
  double inv[6], xInPos, xOutPos, yInPos, yOutPos;

  if (!(nout && nin && mat && msp && !mossImageCheck(nin))) {
    sprintf(err, "%s: got NULL pointer or bad image", me);
    biffAdd(MOSS, err); return 1;
  }
  if (mossSamplerImageSet(msp, nin, bg) || mossSamplerUpdate(msp)) {
    sprintf(err, "%s: trouble with sampler", me);
    biffAdd(MOSS, err); return 1;
  }
  if (!( xMin != xMax && yMin != yMax && xSize > 1 && ySize > 1 )) {
    sprintf(err, "%s: bad args: {x,y}Min == {x,y}Max or {x,y}Size <= 1", me);
    biffAdd(MOSS, err); return 1;
  }
  ax0 = MOSS_AXIS0(nin);
  if (!( AIR_EXISTS(nin->axis[ax0+0].min)
         && AIR_EXISTS(nin->axis[ax0+0].max)
         && AIR_EXISTS(nin->axis[ax0+1].min)
         && AIR_EXISTS(nin->axis[ax0+1].max) )) {
    sprintf(err, "%s: input axis min,max not set on axes %d and %d", me,
            ax0+0, ax0+1); biffAdd(MOSS, err); return 1;
  }

  ncol = MOSS_NCOL(nin);
  if (mossImageAlloc(nout, nin->type, xSize, ySize, ncol)) {
    sprintf(err, "%s: ", me); biffAdd(MOSS, err); return 1;
  }
  val = (float*)calloc(ncol, sizeof(float));
  if (nrrdCenterUnknown == nout->axis[ax0+0].center)
    nout->axis[ax0+0].center = _mossCenter(nin->axis[ax0+0].center);
  xCent = nout->axis[ax0+0].center;
  if (nrrdCenterUnknown == nout->axis[ax0+1].center)
    nout->axis[ax0+1].center = _mossCenter(nin->axis[ax0+1].center);
  yCent = nout->axis[ax0+1].center;
  nout->axis[ax0+0].min = xMin;
  nout->axis[ax0+0].max = xMax;
  nout->axis[ax0+1].min = yMin;
  nout->axis[ax0+1].max = yMax;
  ins = nrrdFInsert[nin->type];
  clamp = nrrdFClamp[nin->type];
  
  if (mossSamplerSample(val, msp, 0, 0)) {
    sprintf(err, "%s: trouble in sampler", me);
    free(val); biffAdd(MOSS, err); return 1;
  }

  mossMatInvert(inv, mat);
  for (yi=0; yi<ySize; yi++) {
    yOutPos = NRRD_POS(yCent, yMin, yMax, ySize, yi);
    for (xi=0; xi<xSize; xi++) {
      /*
      mossVerbose = ( (36 == xi && 72 == yi) ||
                      (37 == xi && 73 == yi) ||
                      (105 == xi && 175 == yi) );
      */
      xOutPos = NRRD_POS(xCent, xMin, xMax, xSize, xi);
      mossMatApply(&xInPos, &yInPos, inv, xOutPos, yOutPos);
      xInPos = NRRD_IDX(xCent, nin->axis[ax0+0].min, nin->axis[ax0+0].max,
                        nin->axis[ax0+0].size, xInPos);
      yInPos = NRRD_IDX(yCent, nin->axis[ax0+1].min, nin->axis[ax0+1].max,
                        nin->axis[ax0+1].size, yInPos);
      mossSamplerSample(val, msp, xInPos, yInPos);
      for (ci=0; ci<ncol; ci++) {
        ins(nout->data, ci + ncol*(xi + xSize*yi), clamp(val[ci]));
      }
    }
  }

  free(val);
  return 0;
}
Esempio n. 15
0
int main()
{
	struct student s;
	struct student s1[10];
	int n,d,ch2,ch1;
	printf("enter the number of records  to be entered");
	scanf("%d",&n);
	printf("choose the way to operate:\n 1.with pointer\n 2. without pointer");
	scanf("%d",&ch1);
	switch(ch1)
	{
	case 1:
		{
			input_p(&s,n);

			do
				{
				printf("choose the operation to perform:\n 1.display all\n 2.display particular\n 3.delete\n 4.insert\n 5.bubble sort\n 6.selection sort\n 7.binary seach");
				scanf("%d",&ch2);
				switch(ch2)
				{
					case 1:
						display_all_p(&s,n);
					break;
					case 2:
						printf("enter the record to be displayed");
						scanf("%d",&d);
						display_part_p(&s,d);
					break;
					case 3:
						printf("\n enter the record to be deleted");
						scanf("%d",&d);
						del_p(&s,d,n);
					break;
					case 4:
						printf("\n enter the position at which record is to be inserted");
						scanf("%d",&d);
						ins_p(&s,d,n);
					break;
					case 5:
						printf("you chose to sort the records by their roll no using bubble sort");
						bubblesort(&s,n);

						break;
					case 6:
						printf("you chose to sort the records by their roll no using selection sort");
						selection_sort(&s,n);

						break;
					case 7:
						printf("you chose to search a record using binary search by their roll no");

						bin_search(&s,n);
						break;
					default:
						break;
				}
			}while(ch2!=8);

		}
		break;
	case 2:
		{
			input(s1,n);
			do
			{
				printf("choose the operation to perform:\n 1.display all\n 2.display particular\n 3.delete\n 4.insert\n 5. exit");
				scanf("%d",&ch2);
				switch(ch2)
				{
					case 1:
						display_all(s1,n);
					break;
					case 2:
						printf("enter the record to be displayed");
						scanf("%d",&d);
						display_part(s1,d);

					break;
					case 3:
						printf("\n enter the record to be deleted");
						scanf("%d",&d);
						del(s1,d,n);
					break;
					case 4:
						printf("\n enter the position at which record is to be inserted");
						scanf("%d",&d);
						ins(s1,d,n);
					break;
					default:
						printf("please enter a valid input");
						break;
				}
			}while(ch2!=5);
		}
		break;
	default:
		break;

	}
	getchar();
	return 0;
}
Esempio n. 16
0
	ctlr = ether->ctlr;

	SELECT_BANK(0);
	status = ins(port + Eph);

	if (status & EphCntRol) {
		/* read the counter register even if we don't need it */
		/* otherwise we will keep getting this interrupt */
		n = ins(port + Counter);
		ctlr->col += (n & CntColMask) >> CntColShr;
		ctlr->mcol += (n & CntMColMask) >> CntMColShr;
		ctlr->dfr += (n & CntDtxMask) >> CntDtxShr;
	}

	/* if there was a transmit error, Tcr is disabled */
	outs(port + Tcr, ins(port + Tcr) | TcrEnable);

	/* clear a link error interrupt */
	SELECT_BANK(1);
	outs(port + Control, CtlAutoRls);
	outs(port + Control, CtlAutoRls | CtlTeEnable | CtlCrEnable);

	SELECT_BANK(2);
}

static void
transmit(Ether* ether)
{
	Smc91xx* ctlr;
	int port, n;
Esempio n. 17
0
static int32_t
archread(Chan *c, void *a, int32_t n, int64_t offset)
{
	char *buf, *p;
	int port;
	uint16_t *sp;
	uint32_t *lp;
	IOMap *map;
	Rdwrfn *fn;

	switch((uint32_t)c->qid.path){

	case Qdir:
		return devdirread(c, a, n, archdir, narchdir, devgen);

	case Qiob:
		port = offset;
		checkport(offset, offset+n);
		for(p = a; port < offset+n; port++)
			*p++ = inb(port);
		return n;

	case Qiow:
		if(n & 1)
			error(Ebadarg);
		checkport(offset, offset+n);
		sp = a;
		for(port = offset; port < offset+n; port += 2)
			*sp++ = ins(port);
		return n;

	case Qiol:
		if(n & 3)
			error(Ebadarg);
		checkport(offset, offset+n);
		lp = a;
		for(port = offset; port < offset+n; port += 4)
			*lp++ = inl(port);
		return n;

	case Qioalloc:
		break;

	default:
		if(c->qid.path < narchdir && (fn = readfn[c->qid.path]))
			return fn(c, a, n, offset);
		error(Eperm);
		break;
	}

	if((buf = malloc(n)) == nil)
		error(Enomem);
	p = buf;
	n = n/Linelen;
	offset = offset/Linelen;

	switch((uint32_t)c->qid.path){
	case Qioalloc:
		lock(&iomap);
		for(map = iomap.map; n > 0 && map != nil; map = map->next){
			if(offset-- > 0)
				continue;
			sprint(p, "%#8lux %#8lux %-12.12s\n", map->start, map->end-1, map->tag);
			p += Linelen;
			n--;
		}
		unlock(&iomap);
		break;
	case Qmapram:
/* shit */
#ifdef NOTYET
		for(mp = rmapram.map; mp->size; mp++){
			/*
			 * Up to MemMinMiB is already set up.
			 */
			if(mp->addr < MemMinMiB*MiB){
				if(mp->addr+mp->size <= MemMinMiB*MiB)
					continue;
				pa = MemMinMiB*MiB;
				size = mp->size - MemMinMiB*MiB-mp->addr;
			}
			else{
				pa = mp->addr;
				size = mp->size;
			}
#endif
		error("Not yet");
	
		break;
	}

	n = p - buf;
	memmove(a, buf, n);
	free(buf);

	return n;
}

static int32_t
archwrite(Chan *c, void *a, int32_t n, int64_t offset)
{
	char *p;
	int port;
	uint16_t *sp;
	uint32_t *lp;
	Rdwrfn *fn;

	switch((uint32_t)c->qid.path){

	case Qiob:
		p = a;
		checkport(offset, offset+n);
		for(port = offset; port < offset+n; port++)
			outb(port, *p++);
		return n;

	case Qiow:
		if(n & 1)
			error(Ebadarg);
		checkport(offset, offset+n);
		sp = a;
		for(port = offset; port < offset+n; port += 2)
			outs(port, *sp++);
		return n;

	case Qiol:
		if(n & 3)
			error(Ebadarg);
		checkport(offset, offset+n);
		lp = a;
		for(port = offset; port < offset+n; port += 4)
			outl(port, *lp++);
		return n;

	default:
		if(c->qid.path < narchdir && (fn = writefn[c->qid.path]))
			return fn(c, a, n, offset);
		error(Eperm);
		break;
	}
	return 0;
}
Esempio n. 18
0
/*
	Insert x in B-tree with root t.  If not completely successful, the
	 integer *y and the pointer *u remain to be inserted.
*/
status ins(btuple_t x, long t, btuple_t *y, long *u)
{
 long tnew, p_final, *p;
 int i, j, *n;
 btuple_t *k;
 btuple_t xnew, k_final;
 status code;
 node nod, newnod;

	/*  Examine whether t is a pointer member in a leaf  */
	if (t == NIL){
		*u = NIL;
		 *y = x;
		 return(INSERTNOTCOMPLETE);
	}
	readnode(t, &nod);
	n = & nod.cnt;
	k = nod.tuple;
	p = nod.ptr;
	/*  Select pointer p[i] and try to insert x in  the subtree of whichp[i]
	  is  the root:  */
	i = binsearch(x, k, *n);
	if (i < *n && strcmp(x.index,k[i].index) == 0)
	  return(DUPLICATEKEY);
	code = ins(x, p[i], &xnew, &tnew);
	if (code != INSERTNOTCOMPLETE)
	  return code;
	/* Insertion in subtree did not completely succeed; try to insert xnew and
	tnew in the current node:  */
	if (*n < MM){
		i = binsearch(xnew, k, *n);
		for (j = *n; j > i; j--){
			k[j] = k[j-1];
			p[j+1] = p[j];
		}
	  k[i] = xnew;
	  p[i+1] = tnew;
	  ++*n;
	  writenode(t, &nod);
	  return(SUCCESS);
	}
	/*  The current node was already full, so split it.  Pass item k[M] in the
	 middle of the augmented sequence back through parameter y, so that it
	 can move upward in the tree.  Also, pass a pointer to the newly created
	 node back through u.  Return INSERTNOTCOMPLETE, to report that insertion
	 was not completed:    */
	if (i == MM){
	  k_final = xnew;
	  p_final = tnew;
	 }else{
		  k_final = k[MM-1];
		  p_final = p[MM];
		  for (j=MM-1; j>i; j--){
			  k[j] = k[j-1];
			  p[j+1] = p[j];
		  }
			k[i] = xnew;
			p[i+1] = tnew;
	}
	*y = k[M];
	*n = M;
	*u = getnode(); newnod.cnt = M;
	for (j=0; j< M-1; j++){
		newnod.tuple[j] = k[j+M+1];
		newnod.ptr[j] = p[j+M+1];
	}
	newnod.ptr[M-1] = p[MM];
	newnod.tuple[M-1] = k_final;
	newnod.ptr[M] = p_final;
	writenode(t, &nod);
	writenode(*u, &newnod);
	return(INSERTNOTCOMPLETE);
}
Esempio n. 19
0
void DrawLab::insZoomDot(Point point)
 {
  ins(mapZoom(point));
 }
Esempio n. 20
0
void IMG_createslice(Image_t *img, const char *name, uaddr_t addr) {
    assert(img != NULL);
    #if 1

    //printf("creating slice for %s\n", name);
    // Create module if not created yet
    sqlq_t sqsel(img->db, "SELECT modid FROM tab_module WHERE name = @N");
    sqsel.bind_str(1, name);
    int modid = sqsel.answer();
    if (modid == 0) {
        sqlq_t ssi(img->db, "INSERT INTO tab_module(name) VALUES(@A)");
        ssi.bind_str(1, name);
        ssi.run();
        modid = sqsel.answer();
        if (modid == 0) {
            printf("ERROR\n");
        }
    }
    // get segment for this slice
    sqlq_t segq(img->db, "SELECT segid FROM tab_segment WHERE address <= @A AND address + size > @B");
    segq.bind_int(1, addr);
    segq.bind_int(2, addr);
    int segid = segq.answer();
    if (segid == 0) {
        return;
    }

    // adjust previous slices' sizes

    int secid = uaddr_sec(addr);
    int secsize = IMG_getsecsize(img, secid);
    uaddr_t secstart = uaddr_mk(secid, 0);
    uaddr_t secend = uaddr_mk(secid, secsize);
    // passa por todos os slices deste seg
    sqlq_t sq(img->db, "SELECT address,size FROM tab_modslice WHERE address >= @A AND address < @B ORDER BY address ASC");
    sq.bind_int(1, secstart);
    sq.bind_int(2, secend);
    int size = secend - addr;
    while(sq.step()) {
        int this_start = sq.col_int(0);
        int this_size = sq.col_int(1);
        int this_end = this_start + this_size;
        if (this_end <= addr) {
            // do nothing
        // Achei um slice antes do meu que tem que ser cortado
        } else if (this_start < addr && this_end > addr) {
            //if (this_start > addr) {
            // muda o size do atual
            sqlq_t upd(img->db, "update tab_modslice set size=@a where address=@b");
            uaddr_t this_new_end = addr;
            int this_new_size = this_new_end - this_start;

            upd.bind_int(1, this_new_size);
            upd.bind_int(2, this_start);
            if (!upd.run()) {
                printf("; update slice size error\n");
            }
            //size = this_end - addr;
            //break;
        // Achei um slice depois do meu, entao vou me aparar
        } else if (addr < this_start) {
            size = this_start - addr;
            break;
        } else {
            printf("SLICE POSITIONING ERROR\n");
        }
    }
    // Insert this slice
    sqlq_t ins(img->db, "INSERT INTO tab_modslice(address, size, module, segment) VALUES(@A, @B, @C, @D)");
    ins.bind_int(1, addr);
    ins.bind_int(2, size);
    ins.bind_int(3, modid);
    ins.bind_int(4, segid);
    if (!ins.run()) {
        printf("; Create slice error\n");
    } else {
        //printf("; Created slice %s\n", name);
    }
    #endif

    #if 0

    sqlq_t s(img->db, "INSERT INTO tab_modslice(address, size, module, segment) VALUES(@A, @B, @C, @D, @E, @F)");
    s.bind_str(1, name);
    s.bind_str(2, sclass);
    s.bind_int(3, align);
    s.bind_int(4, use);
    s.bind_int(5, addr);
    s.bind_int(6, priority);
    if (!s.run()) {
        printf("; Create segment error\n");
    } else {
        printf("; Created segment %s\n", name);
    }
    #endif
}
Esempio n. 21
0
int main()
{
	struct bnode *root_pointer = NULL, *p, *s, *t;
	struct student *k;
	int n, i, q;

	do
	{
		printf("vuvedete:\n 1 za vuvejdane\n 2 za tursene\n 3 za iztrivane\n 4 za krai\n");
		scanf("%d", &i);
		if (i == 1)
		{

			p = (struct bnode*)malloc(sizeof(struct bnode));
			k = (struct student*)malloc(sizeof(struct student));
			p->st = k;

			printf("vuvedete fakulteten nomer:");
			scanf("%d", &p->st->fnum);
			printf("vuvedete first name:");
			fflush(stdin);
			fgets(p->st->fname, 20, stdin);
			printf("vuvedete last name:");
			fflush(stdin);
			fgets(p->st->lname, 20, stdin);
			p->left = NULL;
			p->right = NULL;

			if (root_pointer != NULL)
			{
				ins(root_pointer, p);
			}
			else
			{
				root_pointer = p;
				root_pointer->left = NULL;
				root_pointer->right = NULL;
			}
		}
		if (i == 2)
		{
			printf("vuvedete fakulteten nomer za tursene:");
			scanf("%d", &q);
			s = search(root_pointer, q);

			if (s != NULL)
			{
				puts(s->st->fname);
				puts(s->st->lname);
			}
			else
			{
				printf("durvoto e prazno ili fakultetniq nomer ne e nameren");
			}
		}
		if (i == 3)
		{
			printf("vuvedete fakulteten nomer za triene:");
			scanf("%d", &q);

			root_pointer = del(root_pointer, q);
		}
	} while (i != 4);

	getch();
	return 0;
}
Esempio n. 22
0
bool ServiceOptions::bindServiceObject(CORBA::ORB_ptr orb, 
                                       CORBA::Object_ptr object,
                                       PortableServer::Servant p_servant,
                                       const char* objName,
                                       bool rebind)
{
 if(is_set("with-naming")) {
     CosNaming::Name name;
     name.length(1);
     name[0].id=CORBA::string_dup(objName);
     name[0].kind=CORBA::string_dup("");
     CORBA::Object_var obj ;
     try {
        obj = orb->resolve_initial_references("NameService");
     }catch(const CORBA::ORB::InvalidName& ex){
        std::cerr << argv()[0] << ": can't resolve `NameService'" << std::endl;
        return false;
     }
     CosNaming::NamingContext_var nc;
     try {
        nc = CosNaming::NamingContext::_narrow(obj.in());
     }catch(const CORBA::SystemException& ex){
        std::cerr << argv()[0] << ": can't narrow naming service" << std::endl;
        return false;
     }
     try {
        if(rebind){
          nc->rebind(name,object);
        }else{
          try{
            nc->bind(name,object);
          }catch(const CosNaming::NamingContext::AlreadyBound&){
            std::cerr<<argv()[0]<<":can't bind "<<objName<<" (AlreadyBound)"<< std::endl;
            return false;
          }
        }
     }catch(const CosNaming::NamingContext::CannotProceed&){
        std::cerr<<argv()[0]<<": can't bind "<<objName<<" (CannotProceed)"<< std::endl;
        return false;
     }catch(const CosNaming::NamingContext::InvalidName&){
        std::cerr<<argv()[0]<<":can't bind "<<objName<<" (InvalidName)"<< std::endl;
        return false;
     }
     std::cout<<argv()[0]<<": binding completed successfully"<<std::endl;
 }
 CORBA::String_var ior ;
 try {
   ior = orb->object_to_string(object);
 }catch(const CORBA::SystemException& ex){
#ifdef CORBA_SYSTEM_EXCEPTION_IS_STREAMBLE
   std::cerr << ex << std::endl;
#else
   std::cerr << "CORBA::SystemException" << std::endl; 
#endif
   return false;
 }
 const char* fname = get_ior_fname(objName);
 if (fname!=NULL && strcmp(fname,"")!=0) {
    std::ofstream ofs (fname);
    if (ofs.bad()) {
       std::cerr << argv()[0] << ": can't open file " << fname <<  std::endl;
       perror(argv()[0]);
       return false;
    }
    ofs << ior.in();
    ofs.close();
 }
 if (is_set("ior-stdout")) {
    std::cout << ior << std::flush;
 }
#ifdef ORBACUS
 CORBA::Object_var bmgrObj = orb->resolve_initial_references("BootManager");
 OB::BootManager_var bootManager = OB::BootManager::_narrow(bmgrObj);
 PortableServer::ObjectId_var oid = PortableServer::string_to_ObjectId(objName);
 bootManager -> add_binding(oid.in(),object);
#elif defined(OMNIORB)
 PortableServer::POA_var objPOA = p_servant->_default_POA();
 CORBA::String_var objPOAName = objPOA->the_name();
 if (strcmp(objPOAName.in(),"omniINSPOA")!=0) {
   CORBA::Object_var insPOAObj = orb->resolve_initial_references("omniINSPOA");
   PortableServer::POA_var insPOA = PortableServer::POA::_narrow(insPOAObj);
   PortableServer::POAManager_var insPOAManager=insPOA->the_POAManager();
   insPOAManager->activate();
   PortableServer::ObjectId_var oid = 
                          PortableServer::string_to_ObjectId(objName);
   insPOA->activate_object_with_id(oid.in(),p_servant);
 }
#elif defined(RSSH_TAO)
#ifdef TAO_HAVE_IORTABLE_ADAPTER
 CORBA::Object_var table = orb->resolve_initial_references ("IORTable");
 IORTable::Table_var adapter = IORTable::Table::_narrow (table.in());
 if (CORBA::is_nil(adapter.in())) {
   cerr<<argv()[0]<<": nil IORTable reference"<<endl;
 } else {
   adapter->bind (objName, ior.in ());
 }
#else
 ACE_CString ins(objName);
 if (orb->_tao_add_to_IOR_table(ins,object)!=0) {
   return false;
 }
#endif
#elif defined(MICO)
  // create persistent POA with name as service name if we have no one.
 PortableServer::POA_var objPOA = p_servant->_default_POA();
 CORBA::String_var objPOAName = objPOA->the_name();
 std::cerr << "existent OBJPOAName=" << objPOAName.in() << std::endl;
 std::cerr << "objName=" << objName << std::endl;
 if (strcmp(objPOAName.in(),objName)!=0) {
   CORBA::Object_var rootPOAObj = orb->resolve_initial_references ("RootPOA");
   PortableServer::POA_var rootPOA = PortableServer::POA::_narrow(rootPOAObj);
   CORBA::PolicyList pl;
   pl.length (2);                              
   pl[0] = rootPOA->create_lifespan_policy (PortableServer::PERSISTENT);
   pl[1] = rootPOA->create_id_assignment_policy (PortableServer::USER_ID);
   PortableServer::POA_var objPOA = rootPOA->create_POA(objName,
			                  PortableServer::POAManager::_nil (),
			                  pl);
   PortableServer::POAManager_var objPOAManager = objPOA->the_POAManager ();   
   PortableServer::ObjectId_var objId =
                           PortableServer::string_to_ObjectId (objName);
   objPOA->activate_object_with_id (objId.in(), p_servant);
   objPOAManager->activate();
 }else{
   //PortbaobjPOA
 }  
#endif
 return true;
}
Esempio n. 23
0
static uint16_t
ioget16(uintptr_t p, void *j)
{
	return ins(p);
}
Esempio n. 24
0
int main(int argc, char *argv[])
{
    setIO("sample");
    n = gi;
    l = n;
    for(int i = 1; i<=n-1; ++i)
    {
        int x = gi,y = gi;
        add(x,y);
        add(y,x);
    }
    CLEAR(f,1);
    CLEAR(son,0);
    CLEAR(deep,0);
    f[1] = false,tim = 0,deep[1] = 1;
    dfs(1);
    tot = 0;
    int tmp = build(0,1,n);
    for(int i = 1; i<=n; ++i) c[i] = tmp;
    m = gi;
    for(int i = 1; i<=m; ++i)
    {
        int x = gi,y = gi;
        ins(point[x],point[y],1);
        ins(point[y],point[x],1);
    }
    int count = gi;
    while(count--)
    {
        int opt = gi,x= gi,y=gi;
        if(opt == 1)
        {
            ins(point[x],point[y],1);
            ins(point[y],point[x],1);
        }
        if(opt == 2)
        {
            ins(point[x],point[y],-1);
            ins(point[y],point[x],-1);
        }
        if(opt == 3)
        {
            if(point[x]>point[y]) swap(x,y);
            if(point[x]+son[x]-1>=point[y]) //case 1:y belongs to x
            {
                tmp = lca(x,y);
                int x1,x2,y1,y2;
                x1 = point[tmp]-1;
                x2 = point[tmp]+son[tmp];
                y1 = point[y];
                y2 = y1 + son[y]-1;
                printf("%d\n",getsum(y2,1,x1)-getsum(y1-1,1,x1)+getsum(y2,x2,n)-getsum(y1-1,x2,n));
            }
            else { //case 2:y not belongs to x
                int x1,x2,y1,y2;
                x1 = point[x];
                x2 = x1 + son[x]-1;
                y1 = point[y];
                y2 = y1 + son[y]-1;
                printf("%d\n",getsum(y2,x1,x2)-getsum(y1-1,x1,x2));
            }
        }
    }
    closeIO();
    return EXIT_SUCCESS;
}
Esempio n. 25
0
void op_ins()
{
 ins(FALSE);
}
Esempio n. 26
0
int
tenTripleCalc(Nrrd *nout, int ttype, const Nrrd *nten) {
  static const char me[]="tenTripleCalc";
  size_t II, NN, size[NRRD_DIM_MAX];
  double (*ins)(void *, size_t, double), (*lup)(const void *, size_t);

  if (!( nout && nten )) {
    biffAddf(TEN, "%s: got NULL pointer", me);
    return 1;
  }
  if (airEnumValCheck(tenTripleType, ttype)) {
    biffAddf(TEN, "%s: got invalid %s (%d)", me,
             tenTripleType->name, ttype);
    return 1;
  }
  if (tenTensorCheck(nten, nrrdTypeDefault, AIR_FALSE, AIR_TRUE)) {
    biffAddf(TEN, "%s: didn't get a valid DT array", me);
    return 1;
  }
  if (!( nrrdTypeFloat == nten->type ||
         nrrdTypeDouble == nten->type )) {
    biffAddf(TEN, "%s: need input type %s or %s, not %s\n", me,
             airEnumStr(nrrdType, nrrdTypeFloat),
             airEnumStr(nrrdType, nrrdTypeFloat),
             airEnumStr(nrrdType, nten->type));
  }

  nrrdAxisInfoGet_nva(nten, nrrdAxisInfoSize, size);
  size[0] = 3;
  if (nrrdMaybeAlloc_nva(nout, nten->type, nten->dim, size)) {
    biffMovef(TEN, NRRD, "%s: couldn't alloc output", me);
    return 1;
  }

  NN = nrrdElementNumber(nten)/7;
  lup = nrrdDLookup[nten->type];
  ins = nrrdDInsert[nten->type];
  for (II=0; II<NN; II++) {
    double ten[7], trip[3];
    unsigned int vv;
    for (vv=0; vv<7; vv++) {
      ten[vv] = lup(nten->data, vv + 7*II);
    }
    tenTripleCalcSingle_d(trip, ttype, ten);
    for (vv=0; vv<3; vv++) {
      ins(nout->data, vv + 3*II, trip[vv]);
    }
  }
  if (nrrdAxisInfoCopy(nout, nten, NULL, (NRRD_AXIS_INFO_SIZE_BIT))) {
    biffMovef(TEN, NRRD, "%s: couldn't copy axis info", me);
    return 1;
  }
  nout->axis[0].kind = nrrdKindUnknown;
  if (nrrdBasicInfoCopy(nout, nten,
                        NRRD_BASIC_INFO_ALL ^ NRRD_BASIC_INFO_SPACE)) {
    biffAddf(TEN, "%s:", me);
    return 1;
  }

  return 0;
}
Esempio n. 27
0
QString VideoMetaDataUtil::GetArtPath(const QString &pathname,
                                      const QString &type)
{
    QString basename = pathname.section('/', -1);

    if (basename == pathname)
    {
        LOG(VB_GENERAL, LOG_WARNING, LOC +
                "Programmer Error: Cannot determine art path\n\t\t\t"
                "until the ProgramInfo pathname has been fully resolved.");
        return QString();
    }

    art_path_map_lock.lockForRead();
    ArtList ret(art_path_map.values(basename));
    art_path_map_lock.unlock();
    for (ArtList::const_iterator i = ret.begin();
            i != ret.end(); ++i)
    {
        if ((*i).first == type)
            return (*i).second;
    }

    QString fn = basename;
    fn.prepend("%");

    QString dbcolumn;
    if (type == "Coverart")
        dbcolumn = "coverfile";
    else if (type == "Fanart")
        dbcolumn = "fanart";
    else if (type == "Banners")
        dbcolumn = "banner";
    else if (type == "Screenshots")
        dbcolumn = "screenshot";

    QString querystr = QString("SELECT %1 "
        "FROM videometadata WHERE filename "
        "LIKE :FILENAME").arg(dbcolumn);

    MSqlQuery query(MSqlQuery::InitCon());
    query.prepare(querystr);
    query.bindValue(":FILENAME", fn);

    QString artpath;
    if (query.exec() && query.next())
        artpath = query.value(0).toString();

    if (!artpath.startsWith('/') && pathname.startsWith("myth://"))
    {
        QString workURL = pathname;
        QUrl baseURL(workURL);
        baseURL.setUserName(type);
        QString finalURL =
            baseURL.toString(QUrl::RemovePath) + '/' + artpath;
        artpath = finalURL;
    }

    ArtPair ins(type, artpath);
    art_path_map_lock.lockForWrite();
    art_path_map.insert(basename, ins);
    art_path_map_lock.unlock();

    return artpath;
}
Esempio n. 28
0
int Edit::processEvent (const Event& event)
{
    if (event.key > 0  &&  event.key < 256  &&  isprint (event.key)) {
	processText (event);
	return 1;
    }

    switch (event.key) {

    case KB_UP:
    case KB_KP_UP:
	up ();
	break;

    case KB_DOWN:
    case KB_KP_DOWN:
	down ();
	break;

    case KB_LEFT:
    case KB_KP_LEFT:
	left ();
	break;

    case KB_RIGHT:
    case KB_KP_RIGHT:
	right ();
	break;

    case KB_BKSPACE:
	backSpace ();
	break;

    case KB_TAB:
	tab ();
	break;

    case KB_HOME:
    case KB_KP_HOME:
	home ();
	break;

    case KB_END:
    case KB_KP_END:
	end ();
	break;

    case KB_INS:
    case KB_KP_INS:
	ins ();
	break;

    case KB_DEL:
    case KB_KP_DEL:
	del ();
	break;

    case KB_ESC:
	mExitKey = KB_ESC;
	postEvent (Event (EV_QUIT));
	break;

    case KB_ENTER:
	strncpy (mpRealText, mpText, mLength);
	mpRealText[mLength] = '\0';
	if (mpHist != 0)
	    mpHist->add (mpText);
	mExitKey = KB_ENTER;
	postEvent (Event (EV_QUIT));
	break;

    case EV_COLOR_CHANGE:
	draw ();
	return Popup::processEvent (event);

    default:
        return Popup::processEvent (event);
    }

    return 1;
}
Esempio n. 29
0
void avl_any_insert(avl_any *t, any x)
{
    assert(t!=NULL);
    t->root = ins(t, x, t->root);
}
Esempio n. 30
0
bool UT_ByteBuf::append(const UT_Byte * pValue, UT_uint32 length)
{
	return ins(m_iSize,pValue,length);
}