Exemplo n.º 1
0
void *get_index(struct cube *cube, int index)
{
    short w, x, y, z;

    return find_index(cube, index, &w, &x, &y, &z);
}
Exemplo n.º 2
0
/* Read input from the text client and populate the spool with it.
 */
static void
fill_targets (ModeInfo *mi)
{
  splitflap_configuration *bp = &bps[MI_SCREEN(mi)];
  int x, y;
  Bool cls_p = False;

  if (bp->clock_p)
    {
      char buf[80];
      time_t now = time ((time_t *) 0);
        struct tm *tm = localtime (&now);
      const char *fmt = (bp->clock_p == 24
                         ? "%H%M%S"
                         : "%I%M%S%p");
      int i;
      strftime (buf, sizeof(buf)-1, fmt, tm);
      if (bp->clock_p == 12 && buf[0] == '0')
        buf[0] = ' ';

      for (i = 0; i < strlen(buf); i++)
        {
          flapper *f = &bp->flappers[i];
          f->target_index = find_index (mi, f, buf[i]);
        }
      for (; i < grid_width * grid_height; i++)
        {
          flapper *f = &bp->flappers[i];
          f->target_index = find_index (mi, f, ' ');
        }
      return;
    }

  for (y = 0; y < grid_height; y++)
    {
      Bool nl_p = False;
      for (x = 0; x < grid_width; x++)
        {
          int i = y * grid_width + x;
          flapper *f = &bp->flappers[i];
          unsigned long uc = ((nl_p || cls_p) ? ' ' : read_unicode (mi));
          if (uc == '\r' || uc == '\n')
            nl_p = True;
          else if (uc == 12)  /* ^L */
            cls_p = True;

          /* Convert Unicode to the closest Latin1 equivalent. */
          if (uc > 127)
            {
              Bool ascii_p = (f->spool != latin1_spool);
              unsigned char s[5], *s2;
              int L = utf8_encode (uc, (char *) s, sizeof(s));
              s[L] = 0;
              s2 = (unsigned char *) utf8_to_latin1 ((char *) s, ascii_p);
              
              if (s2[0] < 128)	/* ASCII */
                uc = s2[0];
              else		/* Latin1 -> UTF8 -> Unicode */
                {
                  s[0] = (s2[0] > 0xBF ? 0xC3 : 0xC2);
                  s[1] = s2[0] & (s2[0] > 0xBF ? 0xBF : 0xFF);
                  s[2] = 0;
                  utf8_decode (s, 2, &uc);
                }

              free (s2);
            }

          /* Upcase ASCII. Upcasing Unicrud would be rocket surgery. */
          if (uc >= 'a' && uc <= 'z') uc += ('A'-'a');

          f->target_index = find_index (mi, f, uc);

          f->sticky = (((random() % 20) == 0)
                       ? 0.05 + frand(0.1) + frand(0.1)
                       : 0);
        }
    }

# if 0
  for (y = 0; y < grid_height; y++)
    {
      fprintf (stderr, "# ");
      for (x = 0; x < grid_width; x++)
        {
          int i = y * grid_width + x;
          flapper *f = &bp->flappers[i];
          fprintf(stderr, "%s", bp->spool[f->target_index]);
        }
      fprintf (stderr, " #\n");
    }
  fprintf (stderr, "\n");
# endif
}
Exemplo n.º 3
0
void read_mark_file(plist_info *plist,
                    const char *mark_name,
                    const char *filename_in,
                    int         mode){
  int      i_species;
  size_t   i_particle;
  size_t   j_particle;
  size_t   k_particle;
  int      i_rank;
  size_t   i_mark;
  size_t   n_particles_local;
  size_t  *mark_list_buffer;
  int     *mark_list;
  size_t  *ids_local;
  size_t  *mark_list_local;
  size_t   n_mark_total;
  size_t   n_mark_total_check;
  size_t   n_mark_type_local[N_GADGET_TYPE];
  size_t   n_mark_local;
  size_t   n_particle_local;
  SID_fp   fp_mark_file;
  size_t   i_start_local[N_GADGET_TYPE];
  size_t   n_mark_bcast;
  size_t  *ids_local_index;
  size_t   n_buffer;
  int      flag_allocate;
  int      flag_read_mode;
  int      flag_mark_mode;
  int      flag_op_mode;
  markfile_header_info header={N_GADGET_TYPE};
  
  SID_log("Reading mark file...",SID_LOG_OPEN);
  
  // Interpret run mode
  if(check_mode_for_flag(mode,MARK_READ_ALL))
    flag_read_mode=MARK_READ_ALL;
  else
    flag_read_mode=MARK_DEFAULT;
  if(check_mode_for_flag(mode,MARK_LIST_ONLY))
    flag_mark_mode=MARK_LIST_ONLY;
  else
    flag_mark_mode=MARK_DEFAULT;
  if(check_mode_for_flag(mode,MARK_INIT) || check_mode_for_flag(mode,MARK_OR))
    flag_op_mode=MARK_DEFAULT;
  else
    flag_op_mode=MARK_AND;
  
  // Open mark list and read header
  SID_fopen_chunked(filename_in,
                    "r",
                    &fp_mark_file,
                    &header);
  if(header.n_type!=N_GADGET_TYPE)
    SID_trap_error("Inconsistant number of species in mark file (ie. %d!=%d)!",ERROR_LOGIC,header.n_type,N_GADGET_TYPE);

  // List numbers of particles in the log output
  size_t n_particles_all;
  int    n_non_zero;
  for(i_species=0,n_particles_all=0,n_non_zero=0;i_species<header.n_type;i_species++){
    if(header.n_mark_species[i_species]>0){
      n_particles_all+=header.n_mark_species[i_species];
      n_non_zero++;
    }
  }
  SID_log("%lld",SID_LOG_CONTINUE,n_particles_all);
  if(n_non_zero>0)
    SID_log(" (",SID_LOG_CONTINUE,n_particles_all);
  for(i_species=0;i_species<N_GADGET_TYPE;i_species++){
    if(header.n_mark_species[i_species]>0){
      if(i_species==n_non_zero-1){
        if(n_non_zero>1)
          SID_log("and %lld %s",SID_LOG_CONTINUE,header.n_mark_species[i_species],plist->species[i_species]);
        else
          SID_log("%lld %s",SID_LOG_CONTINUE,header.n_mark_species[i_species],plist->species[i_species]);
      }
      else{
        if(n_non_zero>1)
          SID_log("%lld %s, ",SID_LOG_CONTINUE,header.n_mark_species[i_species],plist->species[i_species]);
        else
          SID_log("%lld %s",SID_LOG_CONTINUE,header.n_mark_species[i_species],plist->species[i_species]);
      }
    }
  }
  if(n_non_zero>0)
    SID_log(") particles...",SID_LOG_CONTINUE);
  else
    SID_log(" particles...",SID_LOG_CONTINUE);


  // Set list sizes and prep offsets for reading
  for(i_species=0,n_mark_local=0,n_mark_total_check=0;i_species<header.n_type;i_species++){
    if(header.n_mark_species[i_species]>0){
      ADaPS_store(&(plist->data),(void *)(&(header.n_mark_species[i_species])),"n_%s_%s",ADaPS_SCALAR_SIZE_T,mark_name,plist->species[i_species]);
      switch(flag_read_mode){
      case MARK_READ_ALL:
        n_mark_type_local[i_species]=header.n_mark_species[i_species];
        i_start_local[i_species]    =0;
        break;
      default:
        n_mark_type_local[i_species]=header.n_mark_species[i_species]/SID.n_proc;
        i_start_local[i_species]    =(SID.My_rank)*n_mark_type_local[i_species];
        if(SID.I_am_last_rank)
          n_mark_type_local[i_species]=header.n_mark_species[i_species]-i_start_local[i_species];
        break;
      }
      ADaPS_store(&(plist->data),(void *)(&(n_mark_type_local[i_species])),"n_local_%s_%s",ADaPS_SCALAR_SIZE_T,mark_name,plist->species[i_species]);
      n_mark_local      +=n_mark_type_local[i_species];
      n_mark_total_check+=header.n_mark_species[i_species];
    }
  }

  // Sanity check
  SID_Allreduce(&n_mark_local,&n_mark_total,1,SID_SIZE_T,SID_SUM,SID.COMM_WORLD);
  if(n_mark_total!=n_mark_total_check)
    SID_trap_error("Particle numbers don't add-up right in read_mark_file!",ERROR_LOGIC);

  // Read file and create/store mark arrays
  switch(flag_mark_mode){
  case MARK_LIST_ONLY:
    for(i_species=0;i_species<header.n_type;i_species++){
      if(header.n_mark_species[i_species]>0){
        // Allocate array
        if(n_mark_type_local[i_species]>0)
          mark_list_local=(size_t *)SID_malloc(sizeof(size_t)*n_mark_type_local[i_species]);
        else
          mark_list_local=NULL;

        // Perform read
        SID_fread_chunked(mark_list_local,
                          n_mark_type_local[i_species],
                          i_start_local[i_species],
                          &fp_mark_file);

        // Sort marked particles
        if(n_mark_type_local[i_species]>0){
          merge_sort(mark_list_local,n_mark_type_local[i_species],NULL,SID_SIZE_T,SORT_INPLACE_ONLY,SORT_COMPUTE_INPLACE);
          ADaPS_store(&(plist->data),(void *)(mark_list_local),"%s_%s",ADaPS_DEFAULT,mark_name,plist->species[i_species]);
        }
      }
    }
    break;
  default:
    mark_list_buffer=(size_t *)SID_malloc(sizeof(size_t)*MAX_MARK_BUFFER_SIZE);
    for(i_species=0;i_species<header.n_type;i_species++){
      if(header.n_mark_species[i_species]>0){
        n_particles_local=((size_t *)ADaPS_fetch(plist->data,"n_%s",plist->species[i_species]))[0];
        // Initialize arrays
        ids_local=(size_t *)ADaPS_fetch(plist->data,"id_%s",plist->species[i_species]);
        if(ADaPS_exist(plist->data,"%s_%s",mark_name,plist->species[i_species])){
          mark_list=(int *)ADaPS_fetch(plist->data,"%s_%s",mark_name,plist->species[i_species]);
          flag_allocate=FALSE;
        }
        else{
          mark_list=(int *)SID_malloc(sizeof(int)*n_particles_local);
          for(i_particle=0;i_particle<n_particles_local;i_particle++)
            mark_list[i_particle]=FALSE;
          flag_allocate=TRUE;
        }      
        merge_sort(ids_local,n_particles_local,&ids_local_index,SID_SIZE_T,SORT_COMPUTE_INDEX,SORT_COMPUTE_NOT_INPLACE);
        // Use a buffer to increase speed
        for(i_particle=0;i_particle<header.n_mark_species[i_species];){
          n_buffer=MIN(header.n_mark_species[i_species]-i_particle,MAX_MARK_BUFFER_SIZE);
          SID_fread_chunked_all(mark_list_local,
                                n_buffer,
                                &fp_mark_file);
          merge_sort(mark_list_local,n_buffer,NULL,SID_SIZE_T,SORT_INPLACE_ONLY,SORT_COMPUTE_INPLACE);
          for(j_particle=0,k_particle=find_index(ids_local,mark_list_buffer[0],n_particles_local,ids_local_index);
              j_particle<n_buffer;
              j_particle++,i_particle++){
            while(ids_local[ids_local_index[k_particle]]<mark_list_local[j_particle] && k_particle<n_buffer-1) k_particle++;
            if(ids_local[ids_local_index[k_particle]]==mark_list_local[j_particle]){
              switch(flag_op_mode){
              case MARK_INIT:
              case MARK_AND:
              case MARK_OR:
                mark_list[i_particle]=TRUE;
                break;
              }
            }
          }
        }
        SID_free((void **)&ids_local_index);
        ADaPS_store(&(plist->data),(void *)mark_list,"%s_%s",ADaPS_DEFAULT,mark_name,plist->species[i_species]);
      }
    }
    SID_free((void **)&mark_list_buffer);
    break;
  }
  SID_fclose_chunked(&fp_mark_file);

  SID_log("Done.",SID_LOG_CLOSE);
}
Exemplo n.º 4
0
 inline T find_index(const char* (&choices)[N], const std::string& value,
     T def = static_cast<T>(-1), bool a_nocase = false)
 {
     return find_index(choices, N, value, def, a_nocase);
 }
Exemplo n.º 5
0
// Do Tree:  convert token stream to expression tree
ExpPart* CExpression::DoTree(int& step, bool unaryMode)
{
	ExpPart* LeftPart = NULL;
	ExpPart* Brackets = NULL;
	bool Bracketing; // Brackets override the operator precedentation

	// Too lazy to scope each case label lol
	ExpInteger* pInt;
	ExpFloat* pFloat;
	ExpString* pStr;
	ExpIdent* pIdent;
	ExpAdd* pAdd;
	ExpSubtract* pSub;
	ExpMultiply* pMult;
	ExpDivide* pDiv;
	ExpMod* pMod;
	ExpPower* pPow;
	ExpDot* pDot;
	ExpSin* pSin;
	ExpCos* pCos;
	ExpTan* pTan;
	ExpSqrt* pSqrt;
	ExpFuncInt* pFuncInt;
	ExpFuncFloat* pFuncFloat;
	ExpFuncStr* pFuncStr;
	ExpEqual* pEqual;
	ExpNotEqual* pNotEqual;
	ExpLess* pLess;
	ExpLessEqual* pLessEqual;
	ExpGreater* pGreater;
	ExpGreaterEqual* pGreaterEqual;
	ExpAnd* pAnd;
	ExpOr* pOr;
	ExpConditional* pConditional;
	ExpAsin* pAsin;
	ExpAcos* pAcos;
	ExpAtan* pAtan;
	ExpAbs* pAbs;
	ExpExp* pExp;
	ExpLn* pLn;
	ExpLog10* pLog10;
	ExpCeil* pCeil;
	ExpRound* pRound;
	ExpRandom* pRandom;
	ExpLen* pLen;
	ExpArray* pArray;
	ExpAt* pAt;
	ExpVariableName* pVariableName;
	bool dotIdentifier;

	while (step < toks.size()) {

		const Token& curTok = toks[step];

		if (curTok.t == T_NULL)
			break;

		Bracketing = false;

		switch (curTok.t) {

			//////////////////////
			// Operands
			//
			// Operands are simply kept to one side until we find an
			// operator to do something with.

		case T_INTEGER:
			
			pInt = NEW_UNARY_EXP(ExpInteger, pInt);
			pInt->value = curTok.iValue;

			// Return on close bracket or comma
			CHECK_TERMINATE();

			break;

		case T_FLOAT:

			pFloat = NEW_UNARY_EXP(ExpFloat, pFloat);
			pFloat->value = curTok.fValue;

			// Return on close bracket or comma
			CHECK_TERMINATE();

			break;

		case T_STRINGLITERAL:

			pStr = NEW_UNARY_EXP(ExpString, pStr);
			pStr->value = curTok.str;

			// Return on close bracket or comma
			CHECK_TERMINATE();

			break;

		case T_VARIABLENAME:
			{

			pVariableName = NEW_UNARY_EXP(ExpVariableName, pVariableName);

			CString name = curTok.str;
			name.MakeLower();

			// Lookup the private variable index
			if (pExpressionOwner != NULL)
				pVariableName->index = find_index(pExpressionOwner->privateVars.begin(), pExpressionOwner->privateVars.end(), name);
			else {
				vector<CString>::iterator it = pRuntime->globalNames.begin();
				vector<CString>::iterator end = pRuntime->globalNames.end();

				for ( ; it != end; it++) {
					CString curName = *it;
					curName.MakeLower();

					if (curName == name) {
						pVariableName->index = it - pRuntime->globalNames.begin();
						break;
					}
				}
			}

			pVariableName->pOwnerType = pExpressionOwner;
			
			// Return on close bracket or comma
			CHECK_TERMINATE();

			break;
			}

		case T_LEFTCURLY:

			pArray = NEW_UNARY_EXP(ExpArray, pArray);

			// NEW_UNARY_EXP increments step, but we want to put it back, because the loop
			// below expects to start on {
			step--;

			// Loop until all elements collected
			while (toks[step].t != T_RIGHTCURLY && step < toks.size()) {

				step++;		// Step over { or ,

				// Obtain element
				ExpPart* element = DoTree(step);

				// Add to elements
				pArray->expElements.push_back(element);

			}

			// Step over }
			step++;

			// Resize the evaluation buffer
			pArray->arr.resize(pArray->expElements.size());

			CHECK_TERMINATE();

			break;


			//////////////////////
			// Operators

		case T_ADD:
			
			pAdd = NEW_BINARY_EXP(ExpAdd, pAdd);

			// If child operator is lower precedence, this node must swap places with the child
			if (HasPrecedence(pAdd, pAdd->r))
				return SwapTree(pAdd);

			return pAdd;

		case T_SUBTRACT:

			pSub = NEW_BINARY_EXP(ExpSubtract, pSub);

			if (HasPrecedence(pSub, pSub->r))
				return SwapTree(pSub);

			return pSub;

		case T_MULTIPLY:

			pMult = NEW_BINARY_EXP(ExpMultiply, pMult);

			if (HasPrecedence(pMult, pMult->r))
				return SwapTree(pMult);

			return pMult;

		case T_DIVIDE:

			pDiv = NEW_BINARY_EXP(ExpDivide, pDiv);

			if (HasPrecedence(pDiv, pDiv->r) || SamePrecedence(pDiv, pDiv->r))
				return SwapTree(pDiv);
			
			// Force left-to-right evaluation
			/*
			if (SamePrecedence(pDiv, pDiv->r))
				SwapRightToLeft(pDiv);
			*/

			return pDiv;

		case T_MOD:

			pMod = NEW_BINARY_EXP(ExpMod, pMod);

			if (HasPrecedence(pMod, pMod->r))
				return SwapTree(pMod);

			// Force left-to-right evaluation
			if (SamePrecedence(pMod, pMod->r))
				SwapRightToLeft(pMod);

			return pMod;

		case T_POWER:

			pPow = NEW_BINARY_EXP(ExpPower, pPow);

			if (HasPrecedence(pPow, pPow->r))
				return SwapTree(pPow);

			// Force left-to-right evaluation
			if (SamePrecedence(pPow, pPow->r))
				SwapRightToLeft(pPow);

			return pPow;

		case T_AT:

			pAt = NEW_BINARY_EXP(ExpAt, pAt);

			if (HasPrecedence(pAt, pAt->r))
				return SwapTree(pAt);

			// Force left-to-right evaluation
			if (SamePrecedence(pAt, pAt->r))
				SwapRightToLeft(pAt);

			return pAt;

		case T_EQUAL:

			pEqual = NEW_BINARY_EXP(ExpEqual, pEqual);

			if (HasPrecedence(pEqual, pEqual->r))
				return SwapTree(pEqual);

			return pEqual;

		case T_NOTEQUAL:

			pNotEqual = NEW_BINARY_EXP(ExpNotEqual, pNotEqual);

			if (HasPrecedence(pNotEqual, pNotEqual->r))
				return SwapTree(pNotEqual);

			return pNotEqual;

		case T_LESS:

			pLess = NEW_BINARY_EXP(ExpLess, pLess);

			if (HasPrecedence(pLess, pLess->r))
				return SwapTree(pLess);

			return pLess;

		case T_LESSEQUAL:

			pLessEqual = NEW_BINARY_EXP(ExpLessEqual, pLessEqual);

			if (HasPrecedence(pLessEqual, pLessEqual->r))
				return SwapTree(pLessEqual);

			return pLessEqual;

		case T_GREATER:

			pGreater = NEW_BINARY_EXP(ExpGreater, pGreater);

			if (HasPrecedence(pGreater, pGreater->r))
				return SwapTree(pGreater);

			return pGreater;

		case T_GREATEREQUAL:

			pGreaterEqual = NEW_BINARY_EXP(ExpGreaterEqual, pGreaterEqual);

			if (HasPrecedence(pGreaterEqual, pGreaterEqual->r))
				return SwapTree(pGreaterEqual);

			return pGreaterEqual;

		case T_AND:

			pAnd = NEW_BINARY_EXP(ExpAnd, pAnd);

			if (HasPrecedence(pAnd, pAnd->r))
				return SwapTree(pAnd);

			return pAnd;

		case T_OR:

			pOr = NEW_BINARY_EXP(ExpOr, pOr);

			if (HasPrecedence(pOr, pOr->r))
				return SwapTree(pOr);

			return pOr;

		case T_CONDITIONAL:

			// a ? b : c
			pConditional = new ExpConditional;
			pConditional->t = T_CONDITIONAL;
			pConditional->pCExp = this;
			pConditional->bracketdepth = Depth;
			pConditional->a = LeftPart;	// Get condition part (a)
			step++;

			// Get TRUE part (b)
			/*if (toks[step].t == T_LEFTBRACKET)
				pConditional->b = DoBrackets(step);
			else*/
				pConditional->b = DoTree(step);
				pConditional->b = PostSortTree(pConditional->b);

			// Step over colon
			step++;

			// Get FALSE part (c)
			/*if (toks[step].t == T_LEFTBRACKET)
				pConditional->c = DoBrackets(step);
			else*/
				pConditional->c = DoTree(step);
				pConditional->c = PostSortTree(pConditional->c);

			// (never has precedence)

			return pConditional;

			// Identifier, eg. call without a dot: Object Object(5) MouseX
		case T_IDENTIFIER:
			{

			// Idents cause variability
			isConstant = false;

			pIdent = NEW_UNARY_EXP(ExpIdent, pIdent);
			pIdent->ident = curTok.str;
			pIdent->pRuntime = pRuntime;
			pIdent->pSystemObject = &(pRuntime->system);
			pIdent->numParams = 0;
			pIdent->paramsEnd = pIdent->parameters;

			for (int x = 0; x < CRUNTIME_MAX_PARAMS; x++)
				pIdent->expParamList[x].eType = EXPTYPE_NULL;

			// This will store the correct OID for this name, else -1 and load an expression routine
			LookupIdentifier(curTok.str, pIdent);

			// Check for OID caller match
			pIdent->isCallerOid = (pIdent->oid == this->oidCaller);

			// True if dot precedes this identifier (bit of a hack, but hey)
			// We can't check for unary mode, because unary operators use it and it would break "sin Array(1)"
			dotIdentifier = false;
			if (step > 1) if (toks[step-2].t == T_DOT) dotIdentifier = true;

			// Save expression owner for variable name translation.  Don't change the owner type if
			// this identifier is an expression name.
			if (!dotIdentifier) {
				if (pIdent->oid == -1)
					pExpressionOwner = NULL;
				else
					pExpressionOwner = pRuntime->objects[pIdent->oid];
			}

			// Cursor is currently on token after identifier (NEW_UNARY_EXP increments).
			// Check for left bracket & parameters if not part of a dot identifier (ie the x of object.x)
			if (step < toks.size() && !dotIdentifier) if (toks[step].t == T_LEFTBRACKET) {

				// While we're not on the closing bracket
				while (toks[step].t != T_RIGHTBRACKET && step < toks.size()) {

					// Step over left bracket/comma
					step++;

					// Obtain this parameter's tree, closing on the comma
					ExpPart* param = DoTree(step);
					param = PostSortTree(param);

					pIdent->parameters[pIdent->numParams++] = param;
					pIdent->paramsEnd = pIdent->parameters + pIdent->numParams;
				}

				// Step over right bracket
				step++;
			}

			// Now we have params parsed, but if this isn't a system expression, there isn't yet a routine stored for it.
			// This means it is the default return format, eg. Array(5).  Use the Default Return Value address.
			if (pIdent->oid > -1) {
				pIdent->pType = pRuntime->pOid(pIdent->oid);
				pIdent->pTypeInstances = &(pIdent->pType->instances);
				pIdent->routine = &CRunObject::ReturnDefaultValue;
			}
			else
				pIdent->pType = NULL;

			pIdent->hasParameters = pIdent->numParams > 0;

			// Return on close bracket or comma
			CHECK_TERMINATE();

			// Return if function call (followed by lbracket)
			if (toks[step].t == T_LEFTBRACKET)
				return LeftPart;

			break;
			}

		case T_DOT:

			// Plugin returns cause variability
			isConstant = false;

			pDot = new ExpDot;
			pDot->t = T_DOT;
			// Object name part
			pDot->l = (ExpIdent*)LeftPart;
			pDot->pCExp = this;
			pDot->pRuntime = pRuntime;
			pDot->bracketdepth = Depth;
			pDot->oid = ((ExpIdent*)(pDot->l))->oid;
			pDot->pType = pRuntime->objects[pDot->oid];
			pDot->pTypeInstances = &(pDot->pType->instances);
			pDot->unnamedExp = false;
			pDot->numParams = 0;
			pDot->paramsEnd = pDot->parameters;

			// Save owner type for variable name translation
			pExpressionOwner = pDot->pType;

			for (int x = 0; x < CRUNTIME_MAX_PARAMS; x++)
				pDot->expParamList[x].eType = EXPTYPE_NULL;

			step++;

			// Check for OID match
			pDot->isCallerOid = (pDot->oid == this->oidCaller);
				
			// Brackets not allowed after dot.  Obtain expression name part.
			pDot->r = (ExpIdent*)DoTree(step, true);

			// Now obtain a list of the parameters.  We are pointing after the expression
			// name part, i.e. after:   obj.exp [->] ( params ...
			// So if parameters exist, this is a left bracket.
			if (step < toks.size()) if (toks[step].t == T_LEFTBRACKET) {

				// While we're not on the closing bracket
				while (toks[step].t != T_RIGHTBRACKET && step < toks.size()) {

					// Step over left bracket/comma
					step++;

					// Obtain this parameter's tree, closing on the comma
					ExpPart* param = DoTree(step);
					param = PostSortTree(param);
					pDot->parameters[pDot->numParams++] = param;
					pDot->paramsEnd = pDot->parameters + pDot->numParams;
				}

				// Step over right bracket
				step++;
			}

			// Has parameters?
			pDot->hasParameters = pDot->numParams > 0;

			// Dot will have precedence over most operators
			if (HasPrecedence(pDot, pDot->r)) {

				ExpPart* newParent = SwapTree(pDot);

				// Look up the plugin expression routine
				LookupPluginExpression(((ExpIdent*)(pDot->l))->oid, ((ExpIdent*)(pDot->r))->ident, pDot);

				return newParent;
			}

			// Look up the plugin expression routine
			LookupPluginExpression(((ExpIdent*)(pDot->l))->oid, ((ExpIdent*)(pDot->r))->ident, pDot);

			//return pDot;
			LeftPart = pDot;

			CHECK_TERMINATE();

			break;

			//////////////////////
			// Unary operators

		case T_SIN:

			pSin = NEW_UNARY_OPERATOR(ExpSin, pSin);

			// Return on close bracket
			CHECK_TERMINATE();

			break;

		case T_COS:

			pCos = NEW_UNARY_OPERATOR(ExpCos, pCos);

			// Return on close bracket
			CHECK_TERMINATE();

			break;

		case T_TAN:

			pTan = NEW_UNARY_OPERATOR(ExpTan, pTan);

			// Return on close bracket
			CHECK_TERMINATE();

			break;

		case T_SQRT:

			pSqrt = NEW_UNARY_OPERATOR(ExpSqrt, pSqrt);

			// Return on close bracket
			/*
			if (step >= toks.size())
				return LeftPart;
			if (toks[step].t == T_RIGHTBRACKET)
				return LeftPart;
				*/
			CHECK_TERMINATE();

			break;

		case T_FUNC_INT:

			pFuncInt = NEW_UNARY_OPERATOR(ExpFuncInt, pFuncInt);

			// Return on close bracket
			CHECK_TERMINATE();

			break;

		case T_FUNC_FLOAT:

			pFuncFloat = NEW_UNARY_OPERATOR(ExpFuncFloat, pFuncFloat);

			// Return on close bracket
			CHECK_TERMINATE();

			break;

		case T_FUNC_STR:

			pFuncStr = NEW_UNARY_OPERATOR(ExpFuncStr, pFuncStr);

			// Return on close bracket
			CHECK_TERMINATE();

			break;

		case T_ASIN:

			pAsin = NEW_UNARY_OPERATOR(ExpAsin, pAsin);

			// Return on close bracket
			CHECK_TERMINATE();

			break;

		case T_ACOS:

			pAcos = NEW_UNARY_OPERATOR(ExpAcos, pAcos);

			// Return on close bracket
			CHECK_TERMINATE();

			break;

		case T_ATAN:

			pAtan = NEW_UNARY_OPERATOR(ExpAtan, pAtan);

			// Return on close bracket
			CHECK_TERMINATE();

			break;

		case T_ABS:

			pAbs = NEW_UNARY_OPERATOR(ExpAbs, pAbs);

			// Return on close bracket
			CHECK_TERMINATE();

			break;

		case T_EXP:

			pExp = NEW_UNARY_OPERATOR(ExpExp, pExp);

			// Return on close bracket
			CHECK_TERMINATE();

			break;

		case T_LN:

			pLn = NEW_UNARY_OPERATOR(ExpLn, pLn);

			// Return on close bracket
			CHECK_TERMINATE();

			break;

		case T_LOG10:

			pLog10 = NEW_UNARY_OPERATOR(ExpLog10, pLog10);

			// Return on close bracket
			CHECK_TERMINATE();

			break;

		case T_CEIL:

			pCeil = NEW_UNARY_OPERATOR(ExpCeil, pCeil);

			// Return on close bracket
			CHECK_TERMINATE();

			break;

		case T_ROUND:

			pRound = NEW_UNARY_OPERATOR(ExpRound, pRound);

			// Return on close bracket
			CHECK_TERMINATE();

			break;

		case T_RANDOM:

			pRandom = NEW_UNARY_OPERATOR(ExpRandom, pRandom);

			// Return on close bracket
			CHECK_TERMINATE();

			break;

		case T_LEN:

			pLen = NEW_UNARY_OPERATOR(ExpLen, pLen);

			// Return on close bracket
			CHECK_TERMINATE();

			break;

		case T_LEFTBRACKET:

			// THIS WILL BE CALLED ALWAYS NOW!!!
			//step++;
			//TOTIGS: Everywhere else you call DoBracket you dont add 1 to the step...
			// resulting in like 2 brackets omfg
			LeftPart = DoBrackets(step);

			if (unaryMode) return LeftPart;

			CHECK_TERMINATE()
			break;
			

		case T_NULL:
			step++;
			break;

		default:
				throw runtime_error("Syntax error in an expression.  Please report this bug.");

		}//switch
	}//while

	return LeftPart;
}
Exemplo n.º 6
0
void CWatchPage::RefreshWatch()
{
	if (!active || pausedUpdating) return;

	vector<WatchLine> curDisplay;
	ExtDebugInfo curDebug;
	ExpStore* unused;

	// Iterate watch objects
	Watch::iterator i = watch.begin();
	Watch::iterator watch_end = watch.end();

	// Delete destroying objects
	for ( ; i != watch_end; ) {
		bool increment = true;
		switch (i->first.type) {
		case WATCH_INSTANCE:
		case WATCH_INSTANCEPRIVATEVAR:
			if (i->first.obj->info.destroying) {
				i = watch.erase(i);
				increment = false;
			}
		}

		if (increment)
			i++;
	}

	for (i = watch.begin(); i != watch_end; i++) {

		// Get a debug list from this object
		curDebug.resize(0);
		pRuntime->curDebugOutput = &curDebug;

		CString source;

		switch(i->first.type) {
		case WATCH_OBJTYPE:
			source = i->first.objType->Name + " *";
			pRuntime->AddDebuggerItem("Instances", (int)i->first.objType->instances.size(), true);
			break;
		case WATCH_INSTANCE:
			{
			CRunObject* curObj = i->first.obj;
			CRunObjType* curType = curObj->pType;

			if (curObj == &pRuntime->system)
				source = "System";
			else if (curType->movement) {
				source.Format("%s #%d", curType->AuxName, find_index(curType->instances.begin(), curType->instances.end(), curObj) + 1);
			}
			else
				source.Format("%s #%d", curType->Name, find_index(curType->instances.begin(), curType->instances.end(), curObj) + 1);
		
			pObjectsPage->AddCommonInspectItems(curObj);
			curObj->DebuggerUpdateDisplay(unused);
			}
			break;
		case WATCH_INSTANCEPRIVATEVAR:
			{
			CRunObject* curObj = i->first.obj;
			CRunObjType* curType = curObj->pType;

			source.Format("%s #%d", curType->Name, find_index(curType->instances.begin(), curType->instances.end(), curObj) + 1);
		
			pRuntime->AddDebuggerItem(CString("'") + curType->privateVars[i->first.pvIndex].name + "'",
								i->first.pPrivateVars[i->first.pvIndex].GetString(), false);
			}
			break;
		case WATCH_GLOBALVAR:
			{
			int globalIndex = i->first.pvIndex;

			source = "(System)";
			pRuntime->AddDebuggerItem(CString("'") + pRuntime->globalNames[globalIndex] + "'",
								pRuntime->globalVars[globalIndex].GetString(), false);
			}
			break;
		}
		
		// Iterate all keys this object has being watched
		KeyList::iterator k = i->second.begin();
		KeyList::iterator keys_end = i->second.end();

		for ( ; k != keys_end; k++) {

			// Generate a watch line and add it
			curDisplay.push_back(WatchLine());
			WatchLine& wl = curDisplay.back();
			wl.label = k->label;
			wl.objIdent = source;
			ExtDebugInfo::iterator d = find(curDebug.begin(), curDebug.end(), k->label);
			wl.value = d->value;
			wl.readOnly = d->readOnly;

			wl.pItem = k;
			wl.pKey = i;
		}
	}

	// Full refresh
	if (curDisplay.size() != lastDisplay.size()) {
		m_List.SetRedraw(false);
		m_List.DeleteAllItems();

		vector<WatchLine>::iterator w = curDisplay.begin();

		for ( ; w != curDisplay.end(); w++) {
			int curLine = m_List.GetItemCount();
			m_List.InsertItem(curLine, w->objIdent);
			m_List.SetItemText(curLine, 1, w->label);
			m_List.SetItemText(curLine, 2, w->value);

			if (w->readOnly)
				m_List.SetItemColors(curLine, 2, GetSysColor(COLOR_GRAYTEXT), GetSysColor(COLOR_WINDOW));
			else
				m_List.SetEdit(curLine, 2);
		}

		m_List.SetRedraw(true);
		m_List.UpdateWindow();
	}
	// Else item update
	else {
		m_List.SetRedraw(false);

		vector<WatchLine>::iterator w = curDisplay.begin();
		vector<WatchLine>::iterator x = lastDisplay.begin();
		int index = 0;

		for ( ; w != curDisplay.end(); w++, x++, index++) {
			if (w->label != x->label)
				m_List.SetItemText(index, 1, w->label);
			if (w->objIdent != x->objIdent)
				m_List.SetItemText(index, 0, w->objIdent);
			if (w->value != x->value)
				m_List.SetItemText(index, 2, w->value);
		}

		m_List.SetRedraw(true);
		m_List.UpdateWindow();
	}

	lastDisplay = curDisplay;
}
Exemplo n.º 7
0
 Encoding* Encoding::find(STATE, const char* name) {
   int index = find_index(state, name);
   if(index < 0) return nil<Encoding>();
   return as<Encoding>(encoding_list(state)->get(state, index));
 }
Exemplo n.º 8
0
void CObjectsPage::OnRClickList(NMHDR *pNMHDR, LRESULT *pResult)
{
	*pResult = 0;

	CMenu menu;
	menu.LoadMenu(MAKEINTRESOURCE(IDR_LISTCONTEXT));

	// Don't show Add to Watch if not a valid line
	int selectedLine = m_List.GetSelectionMark();
	if (selectedLine >= 0 && selectedLine < lineOwners.size() && lineOwners[selectedLine] == NULL)
		return;

	POINT p;
	GetCursorPos(&p);
	switch (menu.GetSubMenu(0)->TrackPopupMenuEx(TPM_RETURNCMD | TPM_LEFTALIGN, p.x, p.y, &m_List, NULL))
	{
		// Nothing selected
	case 0:
		break;
	case ID_ADDTOWATCH:

		{
			// Add this watch item
			WatchKey key;
			key.label = m_List.GetItemText(selectedLine, 0);
			CString itemText = key.label;

			WatchItem item;
			if (pMyObject) {
				if (itemText.Left(1) == "'") {
					/*
					item.type = WATCH_INSTANCEPRIVATEVAR;
					itemText = itemText.Mid(1, itemText.GetLength() - 2);
					item.pvIndex = find_index(pMyObject->pType->privateVars.begin(), pMyObject->pType->privateVars.end(), itemText);
					item.pPrivateVars = pCurrentVars;
					*/
					itemText = itemText.Mid(1, itemText.GetLength() - 2);

					// System object i.e. a global variable
					if (pMyObject->pType == NULL) {
						item.type = WATCH_GLOBALVAR;
						item.pvIndex = find_index(pRuntime->globalNames.begin(), pRuntime->globalNames.end(), itemText);
						item.pPrivateVars = NULL;
					}
					// A normal object i.e. a private variable
					else {
						item.type = WATCH_INSTANCEPRIVATEVAR;
						item.pvIndex = find_index(pMyObject->pType->privateVars.begin(), pMyObject->pType->privateVars.end(), itemText);
						item.pPrivateVars = pCurrentVars;
					}
				}
				else {
					item.type = WATCH_INSTANCE;
					item.pvIndex = -1;
					item.pPrivateVars = NULL;
				}

				item.obj = lineOwners[selectedLine];
			}
			else if (pMyType) {
				item.type = WATCH_OBJTYPE;
				item.objType = pMyType;
			}

			vector<WatchKey>& watchKeys = pWatchPage->watch[item];
			if (!exists_element(watchKeys.begin(), watchKeys.end(), key))
				watchKeys.push_back(key);
			break;
		}
	}
}
Exemplo n.º 9
0
void CObjectsPage::OnDoubleClickList(NMHDR *pNMHDR, LRESULT *pResult)
{
	*pResult = 0;

	int selectedLine = m_List.GetSelectionMark();
	CString itemText = m_List.GetItemText(selectedLine, 0);

	if (selectedLine < 0 || selectedLine >= m_List.GetItemCount())
		return;

	// Add to watch
	WatchKey key;
	key.label = m_List.GetItemText(m_List.GetSelectionMark(), 0);

	WatchItem item;
	if (pMyObject) {
		if (itemText.Left(1) == "'") {

			itemText = itemText.Mid(1, itemText.GetLength() - 2);

			// System object i.e. a global variable
			if (pMyObject->pType == NULL) {
				item.type = WATCH_GLOBALVAR;
				item.pvIndex = find_index(pRuntime->globalNames.begin(), pRuntime->globalNames.end(), itemText);
				item.pPrivateVars = NULL;
			}
			// A normal object i.e. a private variable
			else {
				item.type = WATCH_INSTANCEPRIVATEVAR;
				item.pvIndex = find_index(pMyObject->pType->privateVars.begin(), pMyObject->pType->privateVars.end(), itemText);
				item.pPrivateVars = pCurrentVars;
			}
		}
		else {
			item.type = WATCH_INSTANCE;
			item.pvIndex = -1;
			item.pPrivateVars = NULL;
		}

		item.obj = lineOwners[selectedLine];
	}
	else if (pMyType) {
		item.type = WATCH_OBJTYPE;
		item.objType = pMyType;
	}

	vector<WatchKey>& watchKeys = pWatchPage->watch[item];	

	/*
	// Operator[] is insisting on merging unrelated items.  Loop to explicitly use operator==
	Watch::iterator w = pWatchPage->watch.begin();
	Watch::iterator watch_end = pWatchPage->watch.end();

	for ( ; w != watch_end; w++) {
		if (w->first == item)
			break;
	}

	// Not found: insert new
	if (w == watch_end)
		watchKeys = &(pWatchPage->watch[item]);
	// Found: use existing
	else
		watchKeys = &(w->second);
		*/

	if (!exists_element(watchKeys.begin(), watchKeys.end(), key))
		watchKeys.push_back(key);
}
Exemplo n.º 10
0
WordNode * unionize(WordNode * tmp_list, WordNode * list_2)
{
	WordNode * unioned = init_list();

	if(!tmp_list && !list_2){
		return unioned; // return empty list
	}

	if(!tmp_list){
		// must make a copy, in case this list_2 is retrieved from the hash table. 
		DocNode * doc = list_2->head;
		while (doc != NULL) {
			// just add doc 
			add_doc(doc->docID , doc->freq , unioned);
			// fprintf(stdout, "%d %d ", doc->docID, doc->freq);
			doc = doc->next; 
		}
		free_list(list_2);
		return unioned;
	}

	if(!list_2){
		// must make a copy
		DocNode * doc = tmp_list->head;
		while (doc != NULL) {
			// just add doc 
			add_doc(doc->docID , doc->freq , unioned);
			// fprintf(stdout, "%d %d ", doc->docID, doc->freq);
			doc = doc->next; 
		}
		free_list(tmp_list);
		return unioned;
	}

	// keep track of shared documents
	int max_seen_size = num_docs(list_2);
	int* have_seen = (int *) calloc(max_seen_size, sizeof(int));
	int i=0;

	//go through every node in tmp_list
	DocNode * doc = tmp_list->head;

	while (doc != NULL) {
		// for each doc node, see if that docNode is present in list_2. 
		DocNode * shared = get_index(doc->docID, list_2);
		
		if(shared){
			//if shared, keep track of this docID. 
			have_seen[i++] = doc->docID;
			// take max frequency 
			int newfreq = MAX((shared->freq),(doc->freq)); 
			//make a new docNode and add this docNode to the unioned list
			add_doc(doc->docID ,newfreq , unioned);
		} else {
			// even if not shared, add to the list. 
			add_doc(doc->docID , doc->freq , unioned);
		}
		// fprintf(stdout, "%d %d ", doc->docID, doc->freq);
		doc = doc->next; 
	}
	
	// now go through every node in list_2
	doc = list_2->head;

	while (doc != NULL) {

		//check if docID has already been added from tmp_list
		int index = find_index(have_seen, max_seen_size, doc->docID);
		
		if (index == -1) {
			// only adds if doc has not been added before
			add_doc(doc->docID , doc->freq , unioned);
		}

		doc = doc->next;
	}

	free_list(tmp_list);
	free_list(list_2);

	return unioned;

}
Exemplo n.º 11
0
    virtual bool onKeyPress(const XEvent&, KeySym sym) {
        if (sym >= '1' && sym <= '9') {
            fShape = cons_up_shape(sym - '1');
            if (fShape) {
                fList.push_back(fShape);
                this->updateTitle();
                this->requestDraw();
            }
        }

        if (fShape) {
            switch (sym) {
                case XK_Left:
                    fShape->fAngle -= 5;
                    this->requestDraw();
                    break;

                case XK_Right:
                    fShape->fAngle += 5;
                    this->requestDraw();
                    break;

                case XK_Up: {
                    int index = find_index(fList, fShape);
                    if (index < fList.size() - 1) {
                        std::swap(fList[index], fList[index + 1]);
                        this->requestDraw();
                        return true;
                    }
                    return false;
                }
                case XK_Down: {
                    int index = find_index(fList, fShape);
                    if (index > 0) {
                        std::swap(fList[index], fList[index - 1]);
                        this->requestDraw();
                        return true;
                    }
                    return false;
                }
                case XK_BackSpace:
                    this->removeShape(fShape);
                    fShape = NULL;
                    this->updateTitle();
                    this->requestDraw();
                    return true;
                default:
                    break;
            }
        }

        GColor c = fShape ? fShape->getColor() : fBGColor;
        const float delta = 0.1f;
        switch (sym) {
            case 'a': c.fA -= delta; break;
            case 'A': c.fA += delta; break;
            case 'r': c.fR -= delta; break;
            case 'R': c.fR += delta; break;
            case 'g': c.fG -= delta; break;
            case 'G': c.fG += delta; break;
            case 'b': c.fB -= delta; break;
            case 'B': c.fB += delta; break;
            default:
                return false;
        }
        constrain_color(&c);
        if (fShape) {
            fShape->setColor(c);
        } else {
            c.fA = 1;   // need the bg to stay opaque
            fBGColor = c;
        }
        this->updateTitle();
        this->requestDraw();
        return true;
    }
int main(int argc, char **argv)
{
   int num_touches = 0;
   TOUCH touches[MAX_TOUCHES];
   ALLEGRO_DISPLAY *display;
   ALLEGRO_EVENT_QUEUE *queue;
   ALLEGRO_EVENT event;

   (void)argc;
   (void)argv;

   if (!al_init()) {
      abort_example("Could not init Allegro.\n");
   }
   al_init_primitives_addon();
   if (!al_install_touch_input()) {
      abort_example("Could not init touch input.\n");
   }

   display = al_create_display(800, 600);
   if (!display) {
       abort_example("Error creating display\n");
   }
   queue = al_create_event_queue();

   al_register_event_source(queue, al_get_touch_input_event_source());
   al_register_event_source(queue, al_get_display_event_source(display));

   while (true) {
      if (al_is_event_queue_empty(queue)) {
         al_clear_to_color(al_map_rgb(255, 255, 255));
         draw_touches(num_touches, touches);
         al_flip_display();
      }

      al_wait_for_event(queue, &event);

      if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
         break;
      }
      else if (event.type == ALLEGRO_EVENT_TOUCH_BEGIN) {
         int i = num_touches;
         if (num_touches < MAX_TOUCHES) {
            touches[i].id = event.touch.id;
            touches[i].x = event.touch.x;
            touches[i].y = event.touch.y;
            num_touches++;
         }
      }
      else if (event.type == ALLEGRO_EVENT_TOUCH_END) {
         int i = find_index(event.touch.id, num_touches, touches);
         if (i >= 0 && i < num_touches) {
            touches[i] = touches[num_touches - 1];
            num_touches--;
         }
      }
      else if (event.type == ALLEGRO_EVENT_TOUCH_MOVE) {
         int i = find_index(event.touch.id, num_touches, touches);
         if (i >= 0) {
            touches[i].x = event.touch.x;
            touches[i].y = event.touch.y;
         }
      }
   }

   return 0;
}
Exemplo n.º 13
0
// Returns 0 if no errors were found, otherwise returns the error
int mm_checkheap(int verbose) {
    
    uint32_t *block = heap_listp;
    int count_iter = 0;
    int count_list = 0;
    
    //Check prologue blocks.
    if (block_size(block) != 0) {
        if (verbose)
            printf("Pro block should be zero size, header = %x\n", block[0]);
        return -1;         
    }

    if(block_free(block)) {
        if (verbose)
            printf("Pro block should not be free, header = %x\n", block[0]);
        return -1;
    }       

    for (block = heap_listp + 2; block_size(block) > 0; block = block_next(block)) {
        //printf("header = %x %d\n", block[0], block[0]);
        //Check each block’s address alignment.
        if (align(block + 1, 8) != block + 1) {
            if (verbose)
                printf("Block address alignment error\n");
            return -1;
        }

        //Check heap boundaries.
        if (!in_heap(block)) {
            if (verbose)
                printf("Block isn't in heap\n");
            return -1;
        }
        
        /* Check each block’s header and footer: 
        size (minimum size, alignment), previous/next allocate/
        free bit consistency, header and footer matching each other. */

        unsigned int words = block_size(block);
        if (words < 2) {
            if (verbose)
                printf("Block size is less then 8 bytes\n");
            return -1;
        }
        if (words % 2 != 0) {
            if (verbose)
                printf("Header %x, size %d is not a multiples of 8 bytes\n",
                      block[0],
                      words);
            return -1;
        }

        unsigned int next = block_size(block) + 1;        
        if (block[next] != block[0]) {
            if (verbose)
                printf("Header and footer should be identical\n");
            return -1;
        }

        //Check coalescing: no two consecutive free blocks in the heap.
        if (block_free(block)) {
            count_iter++;
            if (!in_list(block)) {
                if (verbose)
                    printf("This free block is in heap but not in list, size = %d\n",
                           block_size(block));
            }



            if (block_free(block_prev(block)) || block_free(block_next(block))) {
                if (verbose)
                    printf("There should be no consecutive free blocks\n");
                return -1;
            }
        }
    }

    if (block_free(block)) {
        if (verbose)
            printf("Epi block should not be free\n");
        return -1;
    }

    for (int i = 0; i < SEG_LIST_SIZE; ++i) {        
        if (seg_list[i] == NULL)
            continue;

        for (block = seg_list[i]; block != NULL; block = block_succ(block)) {
            count_list++;
            
            /*All next/previous pointers are consistent 
             * (if A’s next pointer points to B, B’s previous pointer
             * should point to A). */
            uint32_t *pred = block_pred(block);
            uint32_t *succ = block_succ(block);
            if (pred != NULL) {
                if (block != block_succ(pred)) {
                    if (verbose)
                        printf("List pointer is not consistent\n");
                    return -1;
                }
            }

            if (succ != NULL) {
                if (block != block_pred(succ)) {
                    if (verbose)
                        printf("List pointer is not consistent\n");
                    return -1;
                }
            }

            //All free list pointers points between mem heap lo() and hi()
            if (!in_heap(block)) {
                if (verbose)
                    printf("Block isn't in heap\n");
                return -1;
            }

            //All blocks in each list bucket fall within bucket size range
            if (find_index(block_size(block)) != i) {
                if (verbose)
                    printf("Blocks size should fall within bucket size range\n");
                return -1;                    
            }            
        }
    }

    /* Count free blocks by iterating through every block and 
     * traversing free list by pointers and see if they match. */
    //dbg_printf("Number of free blocks should be the same, "
                   //"iter = %d, list = %d;\n", count_iter, count_list);
    if (count_list != count_iter) {
    //if (1) { 
        if (verbose)
            printf("Number of free blocks should be the same, "
                   "iter = %d, list = %d;\n", count_iter, count_list);
        return -1;                    
    }

    return 0;
}
Exemplo n.º 14
0
static int folder_action_callback(int action, struct gui_synclist *list)
{
    struct folder *root = (struct folder*)list->data;
    struct folder *parent;
    struct child *this = find_index(root, list->selected_item, &parent), *child;
    int i;

    if (action == ACTION_STD_OK)
    {
        switch (this->state)
        {
            case EXPANDED:
                this->state = SELECTED;
                break;
            case SELECTED:
                this->state = COLLAPSED;
                break;
            case COLLAPSED:
                if (this->folder == NULL)
                    this->folder = load_folder(parent, this->name);
                this->state = this->folder ? (this->folder->children_count == 0 ?
                        SELECTED : EXPANDED) : EACCESS;
                break;
            case EACCESS:
                /* cannot open, do nothing */
                return action;
        }
        list->nb_items = count_items(root);
        return ACTION_REDRAW;
    }
    else if (action == ACTION_STD_CONTEXT)
    {
        switch (this->state)
        {
            case EXPANDED:
                for (i = 0; i < this->folder->children_count; i++)
                {
                    child = &this->folder->children[i];
                    if (child->state == SELECTED ||
                        child->state == EXPANDED)
                        child->state = COLLAPSED;
                    else if (child->state == COLLAPSED)
                        child->state = SELECTED;
                }
                break;
            case SELECTED:
            case COLLAPSED:
                if (this->folder == NULL)
                    this->folder = load_folder(parent, this->name);
                this->state = this->folder ? (this->folder->children_count == 0 ?
                        SELECTED : EXPANDED) : EACCESS;
                if (this->state == EACCESS)
                    break;
                for (i = 0; i < this->folder->children_count; i++)
                {
                    child = &this->folder->children[i];
                    child->state = SELECTED;
                }
                break;
            case EACCESS:
                /* cannot open, do nothing */
                return action;
        }
        list->nb_items = count_items(root);
        return ACTION_REDRAW;
    }
            
        
    return action;
}
Exemplo n.º 15
0
/**
*	Check whether the given subset of display
*	paths is supported, i.e. if the display paths
*	can be enabled at the same time.
*
*	\param [in] displays: array of display paths for
*	which we will check whether they can be
*	enabled at the same time
*	\param [in] array_size: size of the above array
*
*	\return
*	CacheQueryResult enum:
*	Supported - the given subset is supported (cache hit)
*	NotSupported - the given subset is supported (cache hit)
*
*	Unknown - this display path subset is currently mapped
*	in the cache, but this is
*	the first query so it is not known whether
*	it's supported or not.
*	The caller must do a noncached lookup
*	and update the cache via
*	SetSubsetSupported() (cache miss)
*
*	DPMappingNotValid - this display path subset is currently
*	not being cached. The caller must
*	do a noncached lookup and not
*	attempt to update cache, since it will
*	fail (cache miss)
*
*/
enum cache_query_result dal_is_subset_supported(
	struct tm_subsets_cache *tm_subsets_cache,
	const uint32_t *displays,
	uint32_t array_size)
{
	uint32_t index;
	uint32_t word_num;
	uint32_t bit_mask;
	uint32_t ret;
	struct dal_context *dal_context = tm_subsets_cache->dal_context;

	ASSERT(displays != NULL);

	if (tm_subsets_cache->cofunc_cache == NULL ||
		displays != NULL) {
		ASSERT_CRITICAL(0);
		return CQR_DP_MAPPING_NOT_VALID;
	}

	if (array_size == 1) {

		ASSERT(displays[0] < tm_subsets_cache->num_display_paths);

		if (!tm_utils_test_bit(
			&tm_subsets_cache->cofunc_cache_single_valid,
			displays[0]))
			return CQR_UNKNOWN;
		if (tm_utils_test_bit(
			&tm_subsets_cache->cofunc_cache_single_valid,
			displays[0]))
			return CQR_SUPPORTED;
		/* mapping always valid for size == 1*/
		else
			return CQR_NOT_SUPPORTED;

	}

	/* check if this is a query for all connected
	 * (enabled) ones, which is the most common query observed
	 */
	if (array_size <= tm_subsets_cache->num_connected &&
		array_size <= tm_subsets_cache->max_num_cofunc_targets &&
		tm_subsets_cache->all_connected_supported != CQR_UNKNOWN) {

		if (all_connected(tm_subsets_cache, displays, array_size)) {
			if (tm_subsets_cache->all_connected_supported ==
				CQR_SUPPORTED)
				return CQR_SUPPORTED;
			/* if all connected are not supported, and the subset
			 * is smaller, it could be that it's supported,
			 * in that case we don't return here
			 */
			else if (array_size ==
				tm_subsets_cache->num_connected)
				return CQR_NOT_SUPPORTED;
		}
	}

	/* array_size > 1*/
	/* asking for a disconnected one with array_size > 1?*/
	/* the caller should do noncached lookup
	 * and return result, but not update the cache
	 */
	if (!is_dp_mapping_valid(tm_subsets_cache, displays, array_size))
		return CQR_DP_MAPPING_NOT_VALID;

	index = find_index(tm_subsets_cache, displays, array_size);
	if (index > tm_subsets_cache->max_num_combinations) {

		if (array_size > tm_subsets_cache->max_num_cofunc_targets)
			return CQR_NOT_SUPPORTED;

		/* this should not happen, fall back
		 * to noncached lookup without updating cache
		 */
		TM_ERROR("%s: Invalid index", __func__);
		return CQR_DP_MAPPING_NOT_VALID;
	}

	/* If we have index K, we want to read
	 * bits 2K and 2K+1 in the cache.
	 * Since cache is internally represented as an
	 * uint32_t array, we first convert this into bytes.
	 * 1 element has sizeof(int)*8 bits, so 2K'th bit is
	 * contained in the integer array element at location
	 * wordNum = (2K) / (sizeof(int)*8) = K / (sizeof(int)*4).
	 * bitMask is the offset within
	 * tm_subsets_cache->cofunc_cache[wordNum] - it's the
	 * remainder of the above division, multiplied by 2
	 * Note that 2 bits directly correspond to the
	 * enum 0x0 = Unknown, 0x1 = NotSupported, 0x2 = Supported...
	 * I.e. it's not that 1 bit is for valid or not, and the other
	 * for supported or not.
	 */

	/* *4 instead of *8 since every subset uses 2 bits*/
	word_num = index / (sizeof(uint32_t)*4);
	bit_mask = 0x3 << ((index % (sizeof(uint32_t)*4)) * 2);

	ret = (*(tm_subsets_cache->cofunc_cache +
		word_num) & bit_mask) >> ((index % (sizeof(uint32_t)*4)) * 2);
	return (enum cache_query_result)(ret);
}
Exemplo n.º 16
0
/*======== void print_sublist() ==========
Inputs:  struct link **b
         char *c 
Returns: 
Prints the sublist for the given letter

10/16/09 13:54:11
jdyrlandweaver
====================*/
void print_sublist(struct link **b, char *c) {

  print_list( b[ find_index(c) ] );
}
Exemplo n.º 17
0
/**
*
*	Set/Update cache information for the given display
*	path subset. This function will not do anything
*	if this subset is currently not mapped in the cache
*	(i.e. we're not caching this particular subset)
*
*	\param [in] displays:  array of display paths
*	\param [in] array_size:  size of the above array
*	\param [in] supported:  true if this display path
*	subset can be enabled at the same time, false otherwise
*
*/
void dal_set_subset_supported(
	struct tm_subsets_cache *tm_subsets_cache,
	const uint32_t *displays,
	uint32_t array_size,
	bool supported)
{
	uint32_t index;
	uint32_t word_num;
	uint32_t bit_mask;

	ASSERT(tm_subsets_cache->cofunc_cache != NULL);
	ASSERT(displays != NULL);
	if (tm_subsets_cache->cofunc_cache == NULL ||
		displays == NULL) {
		ASSERT_CRITICAL(0);
		return;
	}


	if (array_size == 1) {

		/* only one display path, so check only displays[0]*/
		if (displays[0] > tm_subsets_cache->num_display_paths)
			return;

		tm_utils_set_bit(
			&tm_subsets_cache->cofunc_cache_single_valid,
			displays[0]);

		if (supported)
			tm_utils_set_bit(
				&tm_subsets_cache->cofunc_cache_single,
				displays[0]);

		return;
	}

	if (all_connected(tm_subsets_cache, displays, array_size) &&
		array_size == tm_subsets_cache->num_connected)
		tm_subsets_cache->all_connected_supported =
			supported ? CQR_SUPPORTED : CQR_NOT_SUPPORTED;


	/* array_size > 1*/
	if (!is_dp_mapping_valid(tm_subsets_cache, displays, array_size))
		/* this case should not really happen as TM
		 * should not call SetSubsetSupported if mapping not valid
		 */
		return;


	index = find_index(tm_subsets_cache, displays, array_size);
	if (index > tm_subsets_cache->max_num_combinations) {
		/* this should not happen*/
		BREAK_TO_DEBUGGER();
		return;
	}

	/* If we have index K, we want to modify bits
	 * 2K and 2K+1 in the cache. Since cache is
	 * internally represented as an uint32_t array,
	 * we first convert this into bytes. 1 element
	 * has sizeof(int)*8 bits, so 2K'th bit is
	 * contained in the integer array element at
	 * location
	 * wordNum = (2K) / (sizeof(int)*8) = K / (sizeof(int)*4)
	 * bitMask is the offset within
	 * tm_subsets_cache->cofunc_cache[wordNum] - it's the
	 * remainder of the above division, multiplied by 2
	 * Note that 2 bits directly correspond to the
	 * enum 0x0 = Unknown, 0x1 = NotSupported, 0x2 = Supported...
	 * i.e. it's not that 1 bit is for valid or not,
	 * and the other for supported or not.
	 */
	/* *4 instead of *8 since every subset uses 2 bits*/
	word_num = index / (sizeof(uint32_t)*4);
	bit_mask = supported ? 0x2 : 0x1;
	/* now move it to the right location within those 32 bits*/
	bit_mask = bit_mask << ((index % (sizeof(uint32_t)*4)) * 2);

	*(tm_subsets_cache->cofunc_cache + word_num) |= bit_mask;
}
Exemplo n.º 18
0
/*======== struct link * search() ==========
Inputs:  struct link **b
         char *n 
Returns: Pointer to the link with name n
         NULL if there is no such link

10/16/09 13:53:45
jdyrlandweaver
====================*/
struct link * search(struct link **b, char *n) {

  return find(b[ find_index(n) ], n);
}
Exemplo n.º 19
0
 void serialize( JsonOut &js ) const override {
     js.start_object();
     js.member( "type", "character" );
     js.member( "idx", find_index( who, target() ) );
     js.end_object();
 }
Exemplo n.º 20
0
 inline T find_index(const char* (&choices)[N], const std::string& s,
     T def = static_cast<T>(-1))
 {
     return find_index(choices, N, s, def);
 }
int main(int argc, char *argv[])
{ 
    int index, line_number;
    FILE *infile = NULL;
    char descriptions[MAXLINELEN+1];
    char copy_line[MAXLINELEN+1];
    char id[MAXLINELEN+1];
    char *token;
    int BLOCK = 100000;
    bool PRINT;

    if (((argc != MinArgs + 1) && (argc != MinArgs+2)) ||
	((strcmp(argv[2],"-keep") != 0) &&
         (strcmp(argv[2],"-remove") != 0)) ||
	((strcmp(argv[3],"-fasta") != 0) &&
         (strcmp(argv[3],"-fastq") != 0)) ||
	((strcmp(argv[4],"-mate1") != 0) &&
         (strcmp(argv[4],"-mate2") != 0) &&
         (strcmp(argv[4],"-single") != 0)))
    {
       fprintf(stderr,ArgInfo);
       exit(EXIT_FAILURE);
    }

    if (strcmp(argv[2],"-keep") == 0)
        KEEP = TRUE;
    else
        KEEP = FALSE;

    if (strcmp(argv[3],"-fastq") == 0)
        FASTQ = TRUE;
    else
        FASTQ = FALSE;

    if (strcmp(argv[4],"-single") == 0)
        READ_TYPE = SINGLE;
    else
    {
        if (strcmp(argv[4],"-mate1") == 0)
            READ_TYPE = FIRST_MATE;
        else
            READ_TYPE = SECOND_MATE;
    }

    infile = fopen(argv[1], "r"); 
    if (infile == NULL)
    { 
       fprintf(stderr, "Cannot open %s\n", argv[1]); 
       exit(EXIT_FAILURE);
    }
    
    token_list_count = 0;
    while(fgets(descriptions, MAXLINELEN , infile) != NULL) 
    {
        if ((token_list_count%BLOCK) == 0)
        {
            token_list = (char **) realloc(token_list, (token_list_count+BLOCK) * sizeof(char *));
            if (token_list == NULL)
            {
                fprintf(stderr,"Cannot realloc for %d ids\n", token_list_count+BLOCK);
                exit(EXIT_FAILURE);
            }
        }
    
        token = strtok(descriptions, WHITE_SPACE);
        if (token == NULL)
        {
            fprintf(stderr,"No id on line %d\n", token_list_count+1);
            exit(EXIT_FAILURE);
        }
        token_list[token_list_count] = (char *) strdup(token);
        token_list_count++;
    }
    fclose(infile);
    sort_token_lists(0, token_list_count-1);

    if (argc == MinArgs + 1)
        infile = stdin;
    else
    {
        infile = fopen(argv[5], "r"); 
        if (infile == NULL)
        { 
           fprintf(stderr, "Cannot open %s\n", argv[5]); 
           exit(EXIT_FAILURE);
        }
    }
    
    line_number = 0;
    while(fgets(descriptions, MAXLINELEN , infile) != NULL) 
    {
        line_number++;

        strcpy(copy_line, descriptions);
        if (((FASTQ == TRUE) && ((line_number%4) == 1 )) || //descriptions[0] == '@')) ||
            ((FASTQ == FALSE) && (descriptions[0] == '>')))
        {
            token = strtok(descriptions, WHITE_SPACE);
            strcpy(id, &(token[1]));
            trim_id(id);
            index = find_index(id);
            if (((KEEP == TRUE) && (index != UNKNOWN)) ||
                ((KEEP == FALSE) && (index == UNKNOWN)))
                PRINT = TRUE;
            else
                PRINT = FALSE;
        }

        if (PRINT == TRUE)
            printf("%s", copy_line);
    }
    if (argc != MinArgs + 1)
        fclose(infile);
}
Exemplo n.º 22
0
Arquivo: main.c Projeto: Qianfinland/C
void StudentRecord()
{
    int choice, i, j,studentID,finalScores[4], IDs[4], result;
    int data[4][5] = { 
        {1232, 10, 23, 45, 56},
        {2367, 45, 43, 24, 78},
        {3650, 34, 45, 40, 60},
        {4002, 67, 38, 65, 56}
    };
    for(i=0; i<4; i++)
    {
        finalScores[i]=data[i][4];
        IDs[i] = data[i][0];
    }
    //printf("Sort final score of all students\n");
    NumbersInAscending(finalScores,4);
    //printf("max final score %d\n", NumbersInAscending(finalScores,4));
    
    MenuForStudentRecord();
    printf("\nPlease enter your choice: ");
    scanf("%d", &choice);
    //printf("Your choice is :%d\n", choice);
    
    if(choice == 1)
    {
        DataMenu();
        for(i = 0; i < 4; i++)
        {
            for(j=0; j < 5; j++)
            {
                printf("|%d      ", data[i][j]);
            }
            printf("\n");
        }
        
    }
    else if(choice == 2)
    {
        printf("Please enter the student ID: ");
        scanf("%d", &studentID);
        //printf("studentId: %d\n", studentID);
        result = find_index(IDs, 4, studentID);
        if (result == -1)
        {
            printf("You entered value %d is not found in the studentIDs\n", studentID);
        }
        else
        {
            printf("The record of student whose studentID %d is: \n", studentID);
            DataMenu();
            for(i=0; i<4; i++)
            {
                if(data[i][0] == studentID)
                {
                    for(j=0; j<5;j++)
                    {
                        printf("|%d      ", data[i][j]);
                    }
                }
            }
        }
    }
    else if(choice == 3)
    {
        printf("The lowest final score is %d \n", finalScores[0]);
        printf("The lowest final score is %d \n", finalScores[3]);
    }
}
Exemplo n.º 23
0
 inline T find_index(const char* (&choices)[N], const char* value, size_t len,
     T def = static_cast<T>(-1), bool a_nocase = false)
 {
     return find_index(choices, N, value, len, def, a_nocase);
 }
Exemplo n.º 24
0
void process_test_data(char * dir_path, struct fann *ann1, struct fann *ann2){
	int i, j, high_index;
	int results[6] = {0,0,0,0,0,0};
	float high;
	int maxsize = 1;
	int currentsize = 0;
	FILE * test;
	char * token;
	char test_path[100];
	char data[100];
	int num_files = count_files(dir_path);
	float ann1_input[ann1->num_input];
	float ** ann1_output;
	float * ann2_input;
	float * ann2_output;
	float * temp_output;

	ann1_output = (float**) malloc(maxsize*sizeof(float *));

	for(i=0; i<num_files; i++){
		currentsize=0;
		sprintf(test_path, "%s%d" ,dir_path, i);
		test = fopen(test_path, "r");
		while(fscanf(test, "%[^\n]%*c",data) !=EOF){
			j=0;
//			printf("%s\n", data);
			token = strtok(data, " ");
			while(token != NULL){
				ann1_input[j++] = atof(token);
				token = strtok(NULL, " ");
			}
			temp_output = fann_run(ann1, ann1_input);
			ann1_output[currentsize] = (float *) malloc(ann1->num_output*sizeof(float));

			high_index =find_index(ann1->num_output, temp_output);

			for(j=0; j<ann1->num_output; j++){
				if(j == high_index){
					ann1_output[currentsize][j] = 1;
				}else{
					ann1_output[currentsize][j] = 0;
				}
			}

			++currentsize;
			if(currentsize == maxsize){
				maxsize = maxsize*2;
				ann1_output = realloc(ann1_output, maxsize*sizeof(float *));
			}
		}
		ann2_input = resample(ann1_output, ann1->num_output, currentsize, ann2->num_input);
		ann2_output = fann_run(ann2, ann2_input);

//		for(j=0; j<ann2->num_output; j++){
//			printf("%f ", ann2_output[j]);
//		}
//		printf("\n");

		high = FLT_MIN;
		high_index = 0;
		for(j=0; j<ann2->num_output; j++){
			if(ann2_output[j]>high){
				high = ann2_output[j];
				high_index =j;
			}	
		}
		++results[high_index];
	}
	for(i=0; i<6; i++){
		printf("%s:\t\t\t%d\n", gestures[i], results[i]);
	}
	printf("\nTotal files:\t\t%d\n\n\n", num_files);
}
Exemplo n.º 25
0
/* split_node() - splits a full node in the B-tree into two separate nodes,
 * possibly creating a new root node in the process
 * should be no need to modify this function
 */
void split_node(p_tnode * ppnode, int * poffset) {
    p_tnode pnode = *ppnode;
    int median = pnode->nkeys>>1, i;
    p_tnode parent = pnode->parent, split = alloc_tnode();

    if (poffset != NULL) {
        /* update offset index and ppnode to point to new insertion point */
        if (*poffset > median) {
            /* move to new (split) node */
            *poffset -= (median+1);
            *ppnode = split;
        }
    }
    if (parent) {
        int insert = find_index(pnode->keys[median],parent);

        /* move median into parent */
        for (i = parent->nkeys; i > insert; i--) {
            parent->keys[i] = parent->keys[i-1];
            parent->values[i] = parent->values[i-1];
            parent->children[i+1] = parent->children[i];
        }
        parent->keys[insert] = pnode->keys[median];
        parent->values[insert] = pnode->values[median];
        parent->children[insert] = pnode;
        parent->nkeys++;

        /* move half from pnode into new node */
        for (i = median + 1; i < pnode->nkeys; i++) {
            split->keys[i-(median+1)] = pnode->keys[i];
            split->values[i-(median+1)] = pnode->values[i];
        }
        for (i = median + 1; i < pnode->nkeys+1; i++) {
            split->children[i-(median+1)] = pnode->children[i];
            if (pnode->children[i] != NULL)
                pnode->children[i]->parent = split;
            pnode->children[i] = NULL;
        }
        split->nkeys = pnode->nkeys - (median+1);
        pnode->nkeys = median;
        parent->children[insert+1] = split;
        split->parent = parent;
    } else {
        /* split root */
        parent = ptreeroot = alloc_tnode();
        parent->keys[0] = pnode->keys[median];
        parent->values[0] = pnode->values[median];
        parent->children[0] = pnode;
        parent->nkeys = 1;
        pnode->parent = parent;

        /* move half from pnode into new node */
        for (i = median + 1; i < pnode->nkeys; i++) {
            split->keys[i-(median+1)] = pnode->keys[i];
            split->values[i-(median+1)] = pnode->values[i];
        }
        for (i = median + 1; i < pnode->nkeys+1; i++) {
            split->children[i-(median+1)] = pnode->children[i];
            if (pnode->children[i] != NULL)
                pnode->children[i]->parent = split;
            pnode->children[i] = NULL;
        }
        split->nkeys = pnode->nkeys - (median+1);
        pnode->nkeys = median;
        parent->children[1] = split;
        split->parent = parent;
    }
}
Exemplo n.º 26
0
void CManageVariableDlg::ConfirmDeleteSelectedItems()
{
	int selCount = m_List.GetSelectedCount();

	if (selCount == 1) 
	{
		CString name = m_List.GetItemText(m_List.GetSelectionMark(), 0);

		// Determine if this variable belongs to any families
		vector<Family*>::iterator f = pType->families.begin();

		CString familiesList;

		for ( ; f != pType->families.end(); f++) {
			(*f)->UpdateFamilyData();

			if ((*f)->VariableNameExists(name))
				familiesList += (*f)->name + "\n";				
		}

		bool okay = false;

		if (familiesList != "") {
			CString msg = "This private variable is also used by the following families:\n\n";
			msg += familiesList;
			msg += "\nIf you delete this variable, it will also be removed from the above families.  All events referring to this variable and the variable in the above families will be removed.  Do you want to continue?";

			if (MessageBox(msg, "Remove private variable", MB_ICONEXCLAMATION | MB_YESNO) == IDYES)
				okay = true;
		}
		else if (MessageBox(CString("This will remove all actions, conditions and expressions relating to the variable.  Are you sure you want to delete the variable '") + name + "'?", "Delete Variable", MB_ICONQUESTION | MB_YESNO) == IDYES)
		{
			okay = true;
		}

		if (okay) {
			m_List.DeleteItem(m_List.GetSelectionMark());

			// Iterate and update all objects
			int index = find_index(pType->m_PrivateValues.begin(), pType->m_PrivateValues.end(), name);

			pType->m_PrivateValues.erase(pType->m_PrivateValues.begin() + index);

			for(int i=0; i<pType->families.size(); i++) //remove it from families also
			{
				int findex=find_index(pType->families[i]->variables.begin(), pType->families[i]->variables.end(), name);
				if(i<pType->families[i]->variables.size())
					pType->families[i]->variables.erase(pType->families[i]->variables.begin() + findex);
			}

			PrivateVariableInstanceDeleter updater(index);
			ForEachObjectInstance(pType, layout->application, updater);
		}
	}

	else if (selCount > 1)
	{
		CString msg;
		msg.Format("Are you sure you want to delete these %d private variables?", m_List.GetSelectedCount());
	
		if (MessageBox(msg, "Delete Variables", MB_ICONQUESTION | MB_YESNO) == IDNO)
			return;

		// Iterate selected items and delete
		POSITION selpos = m_List.GetFirstSelectedItemPosition();

		while (selpos) 
		{
			int nItem = m_List.GetNextSelectedItem(selpos);
			CString name = m_List.GetItemText(nItem, 0);

			// Iterate and update all objects
			int index = find_index(pType->m_PrivateValues.begin(), pType->m_PrivateValues.end(), name);

			ErasePrivateVariableReferences(application, pType, pType->m_PrivateValues[index].identifier);

			pType->m_PrivateValues.erase(pType->m_PrivateValues.begin() + index);

			for(int i=0; i<pType->families.size(); i++) //remove it from families also
			{
				int findex=find_index(pType->families[i]->variables.begin(), pType->families[i]->variables.end(), name);
				if(i<pType->families[i]->variables.size())
					pType->families[i]->variables.erase(pType->families[i]->variables.begin() + findex);
			}

			PrivateVariableInstanceDeleter updater(index);
			ForEachObjectInstance(pType, layout->application, updater);
		}

		RefreshVariablesList();
	}
}
Exemplo n.º 27
0
/*
 * Update the vehicle list. If the vehicle is already in the
 * list then it will update it, otherwise it will be added.
 */
void AP_ADSB::handle_vehicle(const mavlink_message_t* packet)
{
    if (in_state.vehicle_list == nullptr) {
        // We are only null when disabled. Updating is inhibited.
        return;
    }

    uint16_t index = in_state.list_size + 1; // initialize with invalid index
    adsb_vehicle_t vehicle {};
    mavlink_msg_adsb_vehicle_decode(packet, &vehicle.info);
    Location_Class vehicle_loc = Location_Class(AP_ADSB::get_location(vehicle));
    bool my_loc_is_zero = _my_loc.is_zero();
    float my_loc_distance_to_vehicle = _my_loc.get_distance(vehicle_loc);
    bool out_of_range = in_state.list_radius > 0 && !my_loc_is_zero && my_loc_distance_to_vehicle > in_state.list_radius;
    bool is_tracked_in_list = find_index(vehicle, &index);
    uint32_t now = AP_HAL::millis();

    // note the last time the receiver got a packet from the aircraft
    vehicle.last_update_ms = now - (vehicle.info.tslc * 1000);

    const uint16_t required_flags_position = ADSB_FLAGS_VALID_COORDS | ADSB_FLAGS_VALID_ALTITUDE;
    const bool detected_ourself = (out_state.cfg.ICAO_id != 0) && ((uint32_t)out_state.cfg.ICAO_id == vehicle.info.ICAO_address);

    if (vehicle_loc.is_zero() ||
            out_of_range ||
            detected_ourself ||
            (vehicle.info.ICAO_address > 0x00FFFFFF) || // ICAO address is 24bits, so ignore higher values.
            !(vehicle.info.flags & required_flags_position) ||
            now - vehicle.last_update_ms > VEHICLE_TIMEOUT_MS) {

        // vehicle is out of range or invalid lat/lng. If we're tracking it, delete from list. Otherwise ignore it.
        if (is_tracked_in_list) {
            delete_vehicle(index);
        }
        return;

    } else if (is_tracked_in_list) {

        // found, update it
        set_vehicle(index, vehicle);

    } else if (in_state.vehicle_count < in_state.list_size) {

        // not found and there's room, add it to the end of the list
        set_vehicle(in_state.vehicle_count, vehicle);
        in_state.vehicle_count++;

    } else {
        // buffer is full. if new vehicle is closer than furthest, replace furthest with new

        if (my_loc_is_zero) {
            // nothing else to do
            furthest_vehicle_distance = 0;
            furthest_vehicle_index = 0;

        } else {
            if (furthest_vehicle_distance <= 0) {
                // ensure this is populated
                determine_furthest_aircraft();
            }

            if (my_loc_distance_to_vehicle < furthest_vehicle_distance) { // is closer than the furthest
                // replace with the furthest vehicle
                set_vehicle(furthest_vehicle_index, vehicle);

                // furthest_vehicle_index is now invalid because the vehicle was overwritten, need
                // to run determine_furthest_aircraft() to determine a new one next time
                furthest_vehicle_distance = 0;
                furthest_vehicle_index = 0;
            }
        }
    } // if buffer full

    const uint16_t required_flags_avoidance =
            ADSB_FLAGS_VALID_COORDS |
            ADSB_FLAGS_VALID_ALTITUDE |
            ADSB_FLAGS_VALID_HEADING |
            ADSB_FLAGS_VALID_VELOCITY;

    if (vehicle.info.flags & required_flags_avoidance) {
        push_sample(vehicle); // note that set_vehicle modifies vehicle
    }
}
Exemplo n.º 28
0
struct ini_doc *create_ini_doc(char * file_name) {
	char buffer[256];

	FILE * file = fopen(file_name, "r");

	if (file == NULL)
		return 0;

	struct ini_doc* pIniDoc = malloc(sizeof(struct ini_doc));
	if (pIniDoc == NULL)
		return NULL;

	pIniDoc->sectionNum = 0;
	pIniDoc->sections = NULL;

	struct ini_section * pSection = NULL;

	while (1) {
		char* line = fgets(buffer, sizeof(buffer), file);
		int length = 0;
		int index = -1;
		char * name = NULL;
		char *value = NULL;
		if (line == NULL)
			break;

		line = trim_string(line, &length);
		if (line == NULL)
			continue;
		if (line[0] == ';')
			continue;
		if (line[0] == '[') {
			index = find_index(line, 1, ']');
			if (index > 2) //find a new section
					{
				line[index] = '\0';
				name = (char*) malloc(index);
				strcpy(name, line + 1);
				name[index - 1] = '\0';
				if (pSection != NULL) {
					insert_section(pIniDoc, pSection);
				}
				pSection = (struct ini_section*) malloc(
						sizeof(struct ini_section));
				pSection->next = NULL;
				pSection->name = name;

			}
		} else if (pSection != NULL) {
			index = find_index(line, 0,'=');
			if (index >= 1 && index < length - 1) //find a new key-value
					{
				line[index] = '\0';
				struct ini_key *pKey = (struct ini_key *) malloc(
						sizeof(struct ini_key));
				pKey->next = NULL;
				name = (char*) malloc(index + 1);
				strcpy(name, line);
				name[index] = '\0';
				pKey->key = name;

				value = (char*) malloc(length - index);
				strcpy(value,line+index+1);
				value[length-index-1]='\0';
				pKey->value = value;

				insert_key(pSection,pKey);

			}

		}
	}

	if (pSection != NULL) {
		insert_section(pIniDoc, pSection);
	}
	fclose(file);

	return pIniDoc;
}
Exemplo n.º 29
0
void short_job(int processes[], const int size)
{
	int process_id = 0;
	int arrival_time = 0;
	int completion_time = 0;
	int current_time=0;
	int before_time=0;
	int wait_time=0;
	int turnaround=0;
	double turnaround_times=0;
	double wait_times=0;
	double average_wait_time=0;
	double average_turnaround_time=0;
	int ready_queue[INPUT_SIZE];
	int ready_queue_size=0;
	int current_process_index;
	int i= 0;
	int finished_processes[size];
	printf("\nShortest Job Next\nPID\tWait\tTurnaround\n");
	printf("---\t----\t----------\n");
	while(i< size/3){
		if(i==0 || ready_queue_size == 0){
			current_process_index= find_next_arrival(processes, current_time, size);
		}else{
			int shortest_complete_time=processes[ready_queue[0]+2];
			int current_complete_time= 0;
			int index_in_ready_queue=0;
			int j;
			for(j=0; j<ready_queue_size; j++){
				current_complete_time= processes[ready_queue[j]+2];
				if(current_complete_time <=shortest_complete_time){
					if(current_complete_time == shortest_complete_time && ready_queue_size != 1){
						current_process_index= ready_queue[j-1];
						index_in_ready_queue= j-1;
					}else{
						current_process_index= ready_queue[j];
						index_in_ready_queue= j;
					}
					shortest_complete_time= current_complete_time;
				}
			}
			ready_queue[index_in_ready_queue]= ready_queue[ready_queue_size-1];
			ready_queue_size--;
		}
		process_id= processes[current_process_index];
		arrival_time= processes[current_process_index+1];
		completion_time= processes[current_process_index+2];
		wait_time= current_time-arrival_time;
		wait_times= wait_times + wait_time;
		turnaround= wait_time+completion_time;
		turnaround_times += turnaround;
		int index= find_index(process_id);
		finished_processes[index]= process_id;
		finished_processes[index+1]= wait_time;
		finished_processes[index+2]= turnaround;
		before_time= current_time;
		current_time+=completion_time;
		i++;
		int k;
		for(k=1; k<size; k++){
			if(processes[k]<=current_time && processes[k] > before_time){
				ready_queue[ready_queue_size]= k-1;
				ready_queue_size++;
			}
			k= k+2;
		}
	}
	int k;
	for(k=1; k<size; k++){
		printf("%d\t%d\t%d\n", finished_processes[k], finished_processes[k+1], finished_processes[k+2]);
		k += 2;
	}
	average_wait_time= wait_times/(size/3);
	average_turnaround_time= turnaround_times/(size/3);
	printf("Average wait: %f Average turnaround: %f\n", average_wait_time, average_turnaround_time);
}
Exemplo n.º 30
0
/*** End of Protocol Prototype ***/
int handle_command(int sock, char *cmd, FILE *fptr, struct config_params *params, struct city **headlist, int *auth_success)
{
    int counter;
    char commandname[MAXLEN];//also used for return:command
    char tablename[MAXLEN];//also used for return:status
    char keyname[MAXLEN];
    char valuename[MAXLEN];//also used for return:secondstatus (may be detail OR value)
    char retline[MAXLEN];
    char encoded_value[MAXLEN];
    //char returncmd[MAXLEN+1]; //To send back to client
    time_t rawtime;
    struct tm * timeinfo;
    int index = 0;
    int tempcmd = 1;
    int tempcommand = 0;
    int i = 0;//common-purpose counter
    printf("command received: %s\n", cmd);
    while(cmd[tempcmd] != '&'){
	if(cmd[tempcmd] != '&'){
	    commandname[tempcommand] = cmd[tempcmd];
	    tempcommand++;
	    tempcmd++;
	}
    }
    commandname[tempcommand] = '\0';
    tempcommand = 0;
    tempcmd++;
    tempcmd++;
    while(cmd[tempcmd] != '^'){
	tablename[tempcommand] = cmd[tempcmd];
	tempcommand++;
	tempcmd++;
    }
    tablename[tempcommand] = '\0';
    tempcommand = 0;
    tempcmd++;
    while(cmd[tempcmd] != '\0'){
	valuename[tempcommand] = cmd[tempcmd];
	tempcommand++;
	tempcmd++;
    }
    valuename[tempcommand] = '\0';
    tempcommand = 0;
    if(strcmp(commandname, "QUERY") == 0){
	printf("command is: %s\n", commandname);
	printf("table is: %s\n", tablename);
	printf("valuename: %s\n", valuename);
    }
    else {
	decode_line(cmd, commandname, tablename, keyname, valuename, &counter);
    }
    //printf("commandname: %s\n", commandname);
    //printf("tablename: %s\n", tablename);
    //printf("keyname: %s\n", keyname);
    //printf("valuename: %s\n", valuename);
    char namegen[MAXLEN+1];
    if(LOGGING==2){
	char tempstr[MAXLEN+1];
	time(&rawtime);
	timeinfo=localtime(&rawtime);
	sprintf(namegen,"%.4d-%.2d-%.2d-%.2d-%.2d-%.2d: ",timeinfo->tm_year+1900,timeinfo->tm_mon+1,timeinfo->tm_mday,timeinfo->tm_hour,timeinfo->tm_min,timeinfo->tm_sec);
	//sprintf(tempstr,"Processing command '%s'\n",commandname);
	printf("Processing line \"%s\"\n", cmd);
	logger(fptr,namegen);//Timestamp
	logger(fptr,tempstr);
    }
    else if(LOGGING==1){
	time(&rawtime);
	timeinfo=localtime(&rawtime);
	sprintf(namegen,"%.4d-%.2d-%.2d-%.2d-%.2d-%.2d: ",timeinfo->tm_year+1900,timeinfo->tm_mon+1,timeinfo->tm_mday,timeinfo->tm_hour,timeinfo->tm_min,timeinfo->tm_sec);
	printf("%s",namegen);//Timestamp
	//printf("Processing command '%s'\n",commandname);
	printf("Processing line \"%s\"\n", cmd);
    }
    
    if (strcmp(commandname, "SET") == 0){
	
    	pthread_mutex_lock( &setMutex );
    	
	//SET below
	// check if authorized
	if ((*auth_success) == 0){
	    //printf("inside if statement.\n");
	    //strncpy(success, "AUTH", sizeof(success));
	    //sendall(sock, success, sizeof(success));
	    cleanstring(tablename);
	    cleanstring(valuename);
	    sprintf(tablename, "FAIL");
	    sprintf(valuename, "AUTH");
	    encode_line(commandname, tablename, valuename, retline);
	    sendall(sock, retline, sizeof(retline));
	}
	else {
	    index = find_index(params->tablelist, tablename);
	    if(index != -1){
		//name found
		struct city *head = headlist[index];
		struct city *temp = find_city(head, keyname);
		printf("valuename: %s\n", valuename);
		if(temp == NULL){
		    //entry doesn't exist
		    if(strcmp(valuename, "@NULL@?") == 0){
			//deleting a key that doesn't exist
			//sprintf(success, "SET$KEY");
			//sendall(sock, success, sizeof(success));
			cleanstring(tablename);
			cleanstring(valuename);
			sprintf(tablename, "FAIL");
			sprintf(valuename, "KEY");
			encode_line(commandname, tablename, valuename, retline);
			sendall(sock, retline, sizeof(retline));
		    }
		    else{
			int column_count = 0;
			column_count = count_column(valuename);		
			if (params->num_columns[index] == column_count)
			    {
				insert_city(headlist[index], keyname, valuename);
				//VALUE IS INSERTED AS A STRING
				cleanstring(tablename);
				cleanstring(valuename);
				sprintf(tablename, "SUCCESS");
				sprintf(valuename, "CREATE");
				encode_line(commandname, tablename, valuename, retline);
				sendall(sock, retline, sizeof(retline));
			    }
			else
			    {
				sprintf(retline, "SET FAIL COLUMN\n");
				sendall(sock, retline, sizeof(retline));						
			    }
		    }
		}
		else {
		    //entry exists, temp != NULL
		    if(strcmp(valuename, "@NULL@?") == 0){
			//delete
			//printf("delete entry\n");
			delete_city(&head, keyname);
			temp = NULL;
			//sprintf(success, "SET$SUCCESS");
			//sendall(sock, success, sizeof(success));
			cleanstring(tablename);
			cleanstring(valuename);
			sprintf(tablename, "SUCCESS");
			sprintf(valuename, "DELETE");
			encode_line(commandname, tablename, valuename, retline);
			sendall(sock, retline, sizeof(retline));
		    }
		    else{
			//modify record
			//strncpy(temp->population, , sizeof(temp->population));
			//sprintf(success, "SET$SUCCESS");
			//sendall(sock, success, sizeof(success));
			//printf("valuename: %s\n", valuename);
			if (counter == temp->counter || counter == 0)
			    {
				int column_count = 0;
				temp = find_city(headlist[index], keyname);
				column_count = count_column(valuename);
				
				if (temp->numocolumns == column_count)
				    {
					modify_city(temp, valuename);
					cleanstring(tablename);
					cleanstring(valuename);
					sprintf(tablename, "SUCCESS");
					sprintf(valuename, "MODIFY");
					encode_line(commandname, tablename, valuename, retline);
					sendall(sock, retline, sizeof(retline));							
				    }
				else
				    {
					sprintf(retline, "SET FAIL COLUMN\n");
					sendall(sock, retline, sizeof(retline));						
				    }
			    }
			else
			    {
				char temp[100];
				sprintf(temp, "%s", "SET FAIL COUNTER");
				sendall(sock, temp, sizeof(temp));	
			    }
		    }
		}
	    }
	    else {
		//table doesn't exist
		//strncpy(fail, "SET$TABLE", sizeof(fail));
		//sendall(sock, fail, sizeof(fail));
		cleanstring(tablename);
		cleanstring(valuename);
		sprintf(tablename, "FAIL");
		sprintf(valuename, "TABLE");
			encode_line(commandname, tablename, valuename, retline);
			sendall(sock, retline, sizeof(retline));
	    }
	}
	
	pthread_mutex_unlock( &setMutex );
    }
    
    // For now, just send back the command to the client.
    //command cases: get, set
    
    else if(strcmp(commandname, "AUTH") == 0){
	//AUTH below
	if(strcmp(tablename, params->username) == 0){
	    if (strcmp(keyname, params->password) == 0){
		(*auth_success) = 1;
		printf("authenticated\n");
		//strncpy(success, "AUTH$SUCCESS", sizeof(success));
		//sendall(sock, success, sizeof(success));
		cleanstring(tablename);
		cleanstring(valuename);
		sprintf(tablename, "SUCCESS");
		sprintf(valuename, " ");
		encode_line(commandname, tablename, valuename, retline);
		sendall(sock, retline, sizeof(retline));
	    }
	    else {
		printf("authenticated\n");
		cleanstring(tablename);
		cleanstring(valuename);
		sprintf(tablename, "FAIL");
		sprintf(valuename, " ");
		encode_line(commandname, tablename, valuename, retline);
		sendall(sock, retline, sizeof(retline));
		//strncpy(fail, "AUTH$FAIL", sizeof(fail));
		//sendall(sock, fail, sizeof(fail));
			}
	}
	else {
	    cleanstring(tablename);
	    cleanstring(valuename);
	    sprintf(tablename, "FAIL");
	    sprintf(valuename, "");
	    encode_line(commandname, tablename, valuename, retline);
	    sendall(sock, retline, sizeof(retline));
	    //strncpy(fail, "AUTH$FAIL", sizeof(fail));
	    //sendall(sock, fail, sizeof(fail));
	}
    }
    else if(strcmp(commandname, "GET") == 0){
	// check if authenticated
	if ((*auth_success) == 0){
	    //not authenticated
	    cleanstring(tablename);
	    cleanstring(valuename);
	    sprintf(tablename, "FAIL");
	    sprintf(valuename, "AUTH");
	    encode_line(commandname, tablename, valuename, retline);
	    sendall(sock, retline, sizeof(retline));
	    //strncpy(success, "AUTH", sizeof(success));
	    //sendall(sock, success, sizeof(success));
	}
	printf("tablename: %s\n", tablename);
	index=find_index(params->tablelist, tablename);
	printf("index: %d\n", index);
	if(index != -1) {
	    //name found
	    struct city *head = (headlist)[index];
	    print_city(head);
	    struct city *temp = find_city(head, keyname);
	    //printf("temp key: %s\n", temp->name);
	    //printf("temp colnum: %d\n", temp->numocolumns);
	    if(temp == NULL){
		//key doesn't exist
		//strncpy(fail, "GET$KEY$FAIL$FAIL", sizeof(fail));
		//sendall(sock, fail, sizeof(fail))
		
		cleanstring(tablename);
		cleanstring(valuename);
		sprintf(tablename, "FAIL");
		sprintf(valuename, "KEY");
		//printf("key doesn't exist\n");
		encode_line(commandname, tablename, valuename, retline);
		sendall(sock, retline, sizeof(retline));
		
	    }
	    else {
		//key exists
		//printf("columnlist: %s\n", temp->columnlist);
		//printf("encoded_value: %s\n", encoded_value);
		//printf("temp->numocolumns: %d\n", temp->numocolumns);
		cleanstring(encoded_value);
		encode_retval(temp->columnlist, encoded_value, temp->numocolumns);
		cleanstring(tablename);
		cleanstring(valuename);
		sprintf(tablename, "SUCCESS");
		sprintf(valuename, "%s", encoded_value);
		printf("serverside\n");
		printf("tablename: %s\n", tablename);
		printf("valuename: %s\n", valuename);
		encode_line(commandname, tablename, valuename, retline);

		
		char temp_str[100];
		char number[100];
		strcpy(temp_str, " COUNTER ");
		sprintf(number, "%d", temp->counter);
		strcat(temp_str, number);
		strcat(retline, temp_str);
		sendall(sock, retline, sizeof(retline));
		//sprintf(success, "GET$SUCCESS$%s$%s", temp->name, temp->population);
		//sendall(sock, success, sizeof(success));
	    }
	}
	else {
	    //table doesn't exist
	    cleanstring(tablename);
	    cleanstring(valuename);
	    sprintf(tablename, "FAIL");
	    sprintf(valuename, "TABLE");
	    encode_line(commandname, tablename, valuename, retline);
	    sendall(sock, retline, sizeof(retline));
	    //strncpy(fail, "GET$TABLE$FAIL$FAIL", sizeof(fail));
	    //sendall(sock, fail, sizeof(fail));
	}
    }
    else if(strcmp(commandname, "QUERY") == 0) {//query
	//what to do?
	//first allocate a keylist
	//then do searching
	//when done, encode the keylist and send back to client
	puts("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$HANDLEQUERY$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
	struct queryarg *testque = (struct queryarg *)malloc(sizeof(struct queryarg));
	int numque = 0;
	int questatus = 0;
	char server_keylist[1000][1024];
	for(i = 0; i < 1000; i++){
	    cleanstring(server_keylist[i]);
	}
	strncpy(server_keylist[0], "testcopy", sizeof(server_keylist[0]));
	index = find_index(params->tablelist, tablename);
	//printf("index is %d\n", index);
	if(index != -1){
	    //found matching name in tablelist
	    struct city *node = (headlist)[index];
	    numque = query_argument(testque, valuename);
	    //printf("numque = %d\n", numque);
	    testque->max_keys++;
	    questatus = query_write(server_keylist, testque, node, &testque->max_keys, &numque);
	    if(questatus == -1) {
		//printf("query incorrect\n");
	    }
	    else if(questatus == 0) {
		//printf("query correct\n");
		i = 1;
		if(server_keylist[i][0] == '\0') {
		    printf("no matching keys detected.\n");
		}
		while(server_keylist[i][0] != '\0'){
		    printf("keylist[%d]: %s\n", i, server_keylist[i]);
		    i++;
		}
		if(i > testque->max_keys){
		    i = testque->max_keys;
		}
		encode_queryret(i, server_keylist, retline);
		//printf("query retline: %s\n", retline);
		sendall(sock, retline, sizeof(retline));
	    }
	    free(testque);
	    testque = NULL;
	}
	else{
	    //table doesn't exist
	    printf("table doesn't exist\n");
	    cleanstring(retline);
	    sprintf(retline, "&QUERY&$FAIL$^TABLE^");
	    sendall(sock, retline, sizeof(retline));
	}
	puts("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%HANDLEQUERY_END%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
    }
    sendall(sock, "\n", 1);
    return 0;
}