TetrahedralityParamXYZ::TetrahedralityParamXYZ(SimInfo* info,
        const std::string& filename,
        const std::string& sele1,
        const std::string& sele2,
        RealType rCut,
        RealType voxelSize,
        RealType gaussWidth)
    : StaticAnalyser(info, filename),
      selectionScript1_(sele1), selectionScript2_(sele2),
      seleMan1_(info),  seleMan2_(info), evaluator1_(info), evaluator2_(info),
      rCut_(rCut), voxelSize_(voxelSize), gaussWidth_(gaussWidth) {

    evaluator1_.loadScriptString(sele1);
    if (!evaluator1_.isDynamic()) {
        seleMan1_.setSelectionSet(evaluator1_.evaluate());
    }
    evaluator2_.loadScriptString(sele2);
    if (!evaluator2_.isDynamic()) {
        seleMan2_.setSelectionSet(evaluator2_.evaluate());
    }

    Mat3x3d hmat = info->getSnapshotManager()->getCurrentSnapshot()->getHmat();

    nBins_(0) = int(hmat(0,0) / voxelSize);
    nBins_(1) = int(hmat(1,1) / voxelSize);
    nBins_(2) = int(hmat(2,2) / voxelSize);

    hist_.resize(nBins_(0));
    count_.resize(nBins_(0));
    for (int i = 0 ; i < nBins_(0); ++i) {
        hist_[i].resize(nBins_(1));
        count_[i].resize(nBins_(1));
        for(int j = 0; j < nBins_(1); ++j) {
            hist_[i][j].resize(nBins_(2));
            count_[i][j].resize(nBins_(2));
            std::fill(hist_[i][j].begin(), hist_[i][j].end(), 0.0);
            std::fill(count_[i][j].begin(), count_[i][j].end(), 0.0);

        }
    }

    setOutputName(getPrefix(filename) + ".Qxyz");
}
Example #2
0
void IrcChannelPrivate::addUser(const QString& name)
{
    Q_Q(IrcChannel);
    const QStringList prefixes = q->network()->prefixes();

    IrcUser* user = new IrcUser(q);
    IrcUserPrivate* priv = IrcUserPrivate::get(user);
    priv->channel = q;
    priv->setName(userName(name, prefixes));
    priv->setPrefix(getPrefix(name, prefixes));
    priv->setMode(getMode(q->network(), user->prefix()));
    activeUsers.prepend(user);
    userList.append(user);
    userMap.insert(user->name(), user);
    names = userMap.keys();

    foreach (IrcUserModel* model, userModels)
        IrcUserModelPrivate::get(model)->addUser(user);
}
Example #3
0
  PotDiff::PotDiff(SimInfo* info, const std::string& filename, 
                   const std::string& sele)
    : StaticAnalyser(info, filename), selectionScript_(sele), 
      seleMan_(info), evaluator_(info) {
    
    StuntDouble* sd;
    int i;
    
    setOutputName(getPrefix(filename) + ".potDiff");

    // The PotDiff is computed by negating the charge on the atom type
    // using fluctuating charge values.  If we don't have any
    // fluctuating charges in the simulation, we need to expand
    // storage to hold them.
    int storageLayout = info_->getStorageLayout();
    storageLayout |= DataStorage::dslFlucQPosition;
    storageLayout |= DataStorage::dslFlucQVelocity;
    storageLayout |= DataStorage::dslFlucQForce;
    info_->setStorageLayout(storageLayout);
    info_->setSnapshotManager(new SimSnapshotManager(info_, storageLayout));

    // now we have to figure out which AtomTypes to convert to fluctuating
    // charges
    evaluator_.loadScriptString(sele);    
    seleMan_.setSelectionSet(evaluator_.evaluate());
    for (sd = seleMan_.beginSelected(i); sd != NULL;
         sd = seleMan_.nextSelected(i)) {      
      AtomType* at = static_cast<Atom*>(sd)->getAtomType();
      FluctuatingChargeAdapter fqa = FluctuatingChargeAdapter(at);
      if (fqa.isFluctuatingCharge()) {
        selectionWasFlucQ_.push_back(true);
      } else {
        selectionWasFlucQ_.push_back(false);                
        // make a fictitious fluctuating charge with an unphysical
        // charge mass and slaterN, but we need to zero out the
        // electronegativity and hardness to remove the self
        // contribution:
        fqa.makeFluctuatingCharge(1.0e9, 0.0, 0.0, 1);
        sd->setFlucQPos(0.0);
      }
    }
    info_->getSnapshotManager()->advance();
  }
void SlicingSessionImplementation::generateSliceMenu(SuiListBox* suiBox) {
	ManagedReference<CreatureObject*> player = this->player.get();
	ManagedReference<TangibleObject*> tangibleObject = this->tangibleObject.get();

	if (player == NULL || tangibleObject == NULL)
		return;

	uint8 progress = getProgress();
	suiBox->removeAllMenuItems();

	StringBuffer prompt;
	prompt << "@slicing/slicing:";
	prompt << getPrefix(tangibleObject);

	if (progress == 0) {
		if (usedClamp)
			prompt << "clamp_" << firstCable;
		else if (usedNode)
			prompt << "analyze_" << nodeCable;
		else
			prompt << progress;

		suiBox->addMenuItem("@slicing/slicing:blue_cable", 0);
		suiBox->addMenuItem("@slicing/slicing:red_cable", 1);

		if (!usedClamp && !usedNode) {
			suiBox->addMenuItem("@slicing/slicing:use_clamp", 2);
			suiBox->addMenuItem("@slicing/slicing:use_analyzer", 3);
		}

	} else if (progress == 1) {
		prompt << progress;

		suiBox->addMenuItem((cableBlue) ? "@slicing/slicing:blue_cable_cut" : "@slicing/slicing:blue_cable", 0);
		suiBox->addMenuItem((cableRed) ? "@slicing/slicing:red_cable_cut" : "@slicing/slicing:red_cable", 1);
	}

	suiBox->setPromptText(prompt.toString());
	player->getPlayerObject()->addSuiBox(suiBox);
	player->sendMessage(suiBox->generateMessage());

}
Example #5
0
  Rattle::Rattle(SimInfo* info) : info_(info), maxConsIteration_(10), 
                                  consTolerance_(1.0e-6), doRattle_(false), 
                                  currConstraintTime_(0.0) {
    
    if (info_->getNGlobalConstraints() > 0)
      doRattle_ = true;
    
    if (!doRattle_) return;

    Globals* simParams = info_->getSimParams();

    if (simParams->haveDt()) {
      dt_ = simParams->getDt();
    } else {
      sprintf(painCave.errMsg,
	      "Rattle Error: dt is not set\n");
      painCave.isFatal = 1;
      simError();
    }    

    currentSnapshot_ = info_->getSnapshotManager()->getCurrentSnapshot();
    if (simParams->haveConstraintTime()){
      constraintTime_ = simParams->getConstraintTime();
    } else {
      constraintTime_ = simParams->getStatusTime();
    }

    constraintOutputFile_ = getPrefix(info_->getFinalConfigFileName()) + 
      ".constraintForces";


    // create ConstraintWriter  
    constraintWriter_ = new ConstraintWriter(info_, 
                                             constraintOutputFile_.c_str());

    if (!constraintWriter_){
      sprintf(painCave.errMsg, "Failed to create ConstraintWriter\n");
      painCave.isFatal = 1;
      simError();
    }
  }
Example #6
0
void IrcChannelPrivate::setUsers(const QStringList& users)
{
    Q_Q(IrcChannel);
    const QStringList prefixes = q->network()->prefixes();

    qDeleteAll(userList);
    userMap.clear();
    userList.clear();
    activeUsers.clear();

    foreach (const QString& name, users) {
        IrcUser* user = new IrcUser(q);
        IrcUserPrivate* priv = IrcUserPrivate::get(user);
        priv->channel = q;
        priv->setName(userName(name, prefixes));
        priv->setPrefix(getPrefix(name, prefixes));
        priv->setMode(getMode(q->network(), user->prefix()));
        activeUsers.append(user);
        userList.append(user);
        userMap.insert(user->name(), user);
    }
Example #7
0
  RCorrFuncZ::RCorrFuncZ(SimInfo* info, const std::string& filename, 
                         const std::string& sele1, const std::string& sele2,
                         int nZbins)
    : AutoCorrFunc(info, filename, sele1, sele2, 
                   DataStorage::dslPosition | DataStorage::dslAmat){

    setCorrFuncType("Mean Square Displacement binned by Z");
    setOutputName(getPrefix(dumpFilename_) + ".rcorrZ");
    positions_.resize(nFrames_);
    zBins_.resize(nFrames_);
    nZBins_ = nZbins;
 
    histograms_.resize(nTimeBins_);
    counts_.resize(nTimeBins_);
    for (int i = 0; i < nTimeBins_; i++) {
      histograms_[i].resize(nZBins_);
      counts_[i].resize(nZBins_);
      std::fill(histograms_[i].begin(), histograms_[i].end(), 0.0);
      std::fill(counts_[i].begin(), counts_[i].end(), 0);
    }
  }
Example #8
0
void Player::pickUpAction(bool extended) {
    auto items = creature->getPickUpOptions();
    const Square* square = creature->getConstSquare();
    if (square->getApplyType(creature)) {
        string question = getSquareQuestion(*square->getApplyType(creature), square->getName());
        if (!question.empty() && (items.empty() || model->getView()->yesOrNoPrompt(question))) {
            creature->applySquare();
            return;
        }
    }
    vector<View::ListElem> names;
    vector<vector<Item*> > groups;
    getItemNames(creature->getPickUpOptions(), names, groups);
    if (names.empty())
        return;
    int index = 0;
    if (names.size() > 1) {
        Optional<int> res = model->getView()->chooseFromList("Choose an item to pick up:", names);
        if (!res)
            return;
        else
            index = *res;
    }
    int num = groups[index].size();
    if (num < 1)
        return;
    if (extended && num > 1) {
        Optional<int> res = model->getView()->getNumber("Pick up how many " + groups[index][0]->getName(true) + "?",
                            1, num);
        if (!res)
            return;
        num = *res;
    }
    vector<Item*> pickUpItems = getPrefix(groups[index], 0, num);
    if (creature->canPickUp(pickUpItems)) {
        creature->privateMessage("You pick up " + getPluralName(groups[index][0], num));
        creature->pickUp(pickUpItems);
    }
}
Example #9
0
  const RegisteredPrefixId*
  registerPrefix(const Name& prefix,
                 shared_ptr<InterestFilterRecord> filter,
                 const RegisterPrefixSuccessCallback& onSuccess,
                 const RegisterPrefixFailureCallback& onFailure,
                 uint64_t flags,
                 const nfd::CommandOptions& options)
  {
    nfd::ControlParameters params;
    params.setName(prefix);
    params.setFlags(flags);

    auto prefixToRegister = make_shared<RegisteredPrefix>(prefix, filter, options);

    m_face.m_nfdController->start<nfd::RibRegisterCommand>(
      params,
      [=] (const nfd::ControlParameters&) { this->afterPrefixRegistered(prefixToRegister, onSuccess); },
      [=] (const nfd::ControlResponse& resp) { onFailure(prefixToRegister->getPrefix(), resp.getText()); },
      options);

    return reinterpret_cast<const RegisteredPrefixId*>(prefixToRegister.get());
  }
Example #10
0
  GofXyz::GofXyz(SimInfo* info, const std::string& filename, 
		 const std::string& sele1, const std::string& sele2, 
		 const std::string& sele3, RealType len, int nrbins)
    : RadialDistrFunc(info, filename, sele1, sele2, nrbins), len_(len), 
      halfLen_(len/2), evaluator3_(info), seleMan3_(info) {
    
    setOutputName(getPrefix(filename) + ".gxyz");
    
    evaluator3_.loadScriptString(sele3);
    if (!evaluator3_.isDynamic()) {
      seleMan3_.setSelectionSet(evaluator3_.evaluate());
    }    
    
    deltaR_ =  len_ / nBins_;
    
    histogram_.resize(nBins_);
    for (int i = 0 ; i < nBins_; ++i) {
      histogram_[i].resize(nBins_);
      for(int j = 0; j < nBins_; ++j) {
	histogram_[i][j].resize(nBins_);
      }
    }    
  }
  BondAngleDistribution::BondAngleDistribution(SimInfo* info, 
                                               const string& filename, 
                                               const string& sele, 
                                               double rCut, int nbins) 
  : StaticAnalyser(info, filename), selectionScript_(sele),  evaluator_(info), 
    seleMan_(info) {
    
    setOutputName(getPrefix(filename) + ".bad");
    
    evaluator_.loadScriptString(sele);
    if (!evaluator_.isDynamic()) {
      seleMan_.setSelectionSet(evaluator_.evaluate());
    }
    
    // Set up cutoff radius and order of the Legendre Polynomial:

    rCut_ = rCut;
    nBins_ = nbins;


    // Theta can take values from 0 to 180    
    deltaTheta_ = (180.0) / nBins_;
    histogram_.resize(nBins_);
  }
optional<ReadvertiseAction>
HostToGatewayReadvertisePolicy::handleNewRoute(const RibRouteRef& ribRoute) const
{
  auto ribEntryName = ribRoute.entry->getName();
  if (scope_prefix::LOCALHOST.isPrefixOf(ribEntryName) ||
      ribEntryName == RibManager::LOCALHOP_TOP_PREFIX) {
    return nullopt;
  }

  // find out the shortest identity whose name is a prefix of the RIB entry name
  auto prefixToAdvertise = ribEntryName;
  ndn::security::pib::Identity signingIdentity;
  bool isFound = false;

  for (const auto& identity : m_keyChain.getPib().getIdentities()) {
    auto prefix = identity.getName();

    // ignore the identity name's last component if it is "nrd"
    if (!prefix.empty() && IGNORE_COMPONENT == prefix.at(-1)) {
      prefix = prefix.getPrefix(-1);
    }

    if (prefix.isPrefixOf(prefixToAdvertise)) {
      isFound = true;
      prefixToAdvertise = prefix;
      signingIdentity = identity;
    }
  }

  if (isFound) {
    return ReadvertiseAction{prefixToAdvertise, ndn::security::signingByIdentity(signingIdentity)};
  }
  else {
    return nullopt;
  }
}
Example #13
0
QualifiedName ParserVocabulary::resolveQualifiedName(const QualifiedNameOrIndex &nameOrIndex) const {
    assert(nameOrIndex._nameSurrogateIndex == INDEX_NOT_SET);
    std::string prefix, namespaceName, localName;

    if (nameOrIndex._prefix._stringIndex == INDEX_NOT_SET) {
        OCTETS2STRING(nameOrIndex._prefix._literalCharacterString, prefix);
    } else {
        prefix = getPrefix(nameOrIndex._prefix._stringIndex);
    }

    if (nameOrIndex._namespaceName._stringIndex == INDEX_NOT_SET) {
        OCTETS2STRING(nameOrIndex._namespaceName._literalCharacterString, namespaceName);
    } else {
        namespaceName = getNamespaceName(nameOrIndex._namespaceName._stringIndex);
    }

    if (nameOrIndex._localName._stringIndex == INDEX_NOT_SET) {
        OCTETS2STRING(nameOrIndex._localName._literalCharacterString, localName);
    } else {
        localName = getLocalName(nameOrIndex._localName._stringIndex);
    }

    return QualifiedName(prefix, namespaceName, localName);
}
Example #14
0
QString RealFormat::getSignificandPrefix(const RawFloatIO& io) const
{
  return getPrefix(io.signSignificand, significandbase,
                   mode == Complement2);
}
Example #15
0
bool convert(const std::string &filename) {
	
	std::string file    = removePath(filename);
	std::string outFile = getPrefix(filename, '.') + ".cfrt";
	
	/* Retrieve file format */
	FREE_IMAGE_FORMAT fif = FreeImage_GetFileType(filename.c_str(), 0);
	if (fif == FIF_UNKNOWN) fif = FreeImage_GetFIFFromFilename(filename.c_str());
	if (fif == FIF_UNKNOWN) {
		std::cout << "Unknown file format " << file << std::endl;
		return false;
	}
	
	/* Load image */
	FIBITMAP *dib = nullptr;
	if (FreeImage_FIFSupportsReading(fif)) dib = FreeImage_Load(fif, filename.c_str());
	if (!dib) {
		std::cout << "Failed to load " << file << std::endl;
		return false;
	}
	
	/* Convert to standard format if necessary */
	if (FreeImage_GetImageType(dib) != FIT_BITMAP) {
		FIBITMAP *tmp = dib;
		dib = FreeImage_ConvertToStandardType(dib);
		FreeImage_Unload(tmp);
		if (!dib) {
			std::cout << "Failed to convert " << file << " to standard type." << std::endl;
			return false;
		}
	}
	
	/* Convert bpp if needed */
	unsigned int bpp = FreeImage_GetBPP(dib);
	if (bpp <= 8) {
		FIBITMAP *tmp = dib;
		dib = FreeImage_ConvertToGreyscale(dib);
		FreeImage_Unload(tmp);
		bpp = 8;
		if (!dib || FreeImage_GetBPP(dib) != 8) bpp = 0;
	} else if (bpp > 32) {
		FIBITMAP *tmp = dib;
		dib = FreeImage_ConvertTo32Bits(dib);
		FreeImage_Unload(tmp);
		bpp = 32;
		if (!dib || FreeImage_GetBPP(dib) != 32) bpp = 0;
	}
	
	/* Get image information */
	unsigned int width  = FreeImage_GetWidth(dib);
	unsigned int height = FreeImage_GetHeight(dib);
	unsigned int bytes    = 1;
	unsigned int channels = 0;
	switch (bpp) {
		case 8:  channels = 1; break;
		case 24: channels = 3; break;
		case 32: channels = 4; break;
		default: bpp = 0;
	}
	
	/* Check if image is valid */
	if (!dib || bpp == 0 || width == 0 || height == 0 || !FreeImage_HasPixels(dib)) {
		if (dib) FreeImage_Unload(dib);
		std::cout << "Invalid image " << file << std::endl;
		return false;
	}
	
	std::cout << file << " Loaded. Converting.\n";
	
	/* Create CFR texture */
	CFR::Texture texture(
		width, height, 1,
		channels, bytes
	);
	
	/* Set texture pixels */
	for (unsigned int y = 0; y < height; y++) {
		BYTE* bits = FreeImage_GetScanLine(dib, height - y - 1);
		for (unsigned int x = 0; x < width; x++) {
			CFR::Pixel8 pixel(0, 0, 0, 0);
			BYTE *p = bits + (channels * x);
			if (channels >= 1) pixel.r = p[FI_RGBA_RED];
			if (channels >= 2) pixel.g = p[FI_RGBA_GREEN];
			if (channels >= 3) pixel.b = p[FI_RGBA_BLUE];
			if (channels >= 4) pixel.a = p[FI_RGBA_ALPHA];
			texture.setPixel8(pixel, x, y, 0);
		}
	}
	
	/* Unload image */
	FreeImage_Unload(dib);
	
	/* Save texture */
	try {
		texture.saveToFile(outFile);
	} catch (CFR::Exception &fail) {
		std::cout << "Failed to save " << removePath(outFile) << ": " << fail.what() << std::endl;
	}
	
	return true;
}
QtGuiApplication::QtGuiApplication(const QString& filename, QString defaultPrefix)
{
  init();
  prefix_=getPrefix(filename,defaultPrefix);
  read(prefix_+"/"+filename);
}
Example #17
0
/*
 * Subclasses should override this method to write their XML attributes
 * to the XMLOutputStream.  Be sure to call your parents implementation
 * of this method as well.  For example:
 *
 *   SBase::writeAttributes(stream);
 *   stream.writeAttribute( "id"  , mId   );
 *   stream.writeAttribute( "name", mName );
 *   ...
 */
void Text::writeAttributes (XMLOutputStream& stream) const
{
  GraphicalPrimitive1D::writeAttributes(stream);
  std::ostringstream os;
  RelAbsVector tmp(0.0,0.0);
  // x and y are not optional
  os.str("");
  os << this->mX;
  stream.writeAttribute("x", getPrefix(), os.str());
  os.str("");
  os << this->mY;
  stream.writeAttribute("y", getPrefix(), os.str());
  if(this->mZ!=tmp)
  {
      os.str("");
      os << this->mZ;
      stream.writeAttribute("z", getPrefix(), os.str());
  }
  if(this->isSetFontFamily())
  {
      stream.writeAttribute("font-family", getPrefix(), this->mFontFamily);
  }
  if(this->isSetFontSize())
  {
      std::ostringstream os;
      os << this->getFontSize();
      stream.writeAttribute("font-size", getPrefix(), os.str());
  }
  switch(this->mFontStyle)
  {
      // if it has been set to normal, we
      // have to write it because otherwise it is assumed to
      // be inherited
      case Text::STYLE_UNSET:
          break;
      case Text::STYLE_NORMAL:
          stream.writeAttribute("font-style", getPrefix(), std::string("normal"));
          break;
      case Text::STYLE_ITALIC:
          stream.writeAttribute("font-style", getPrefix(), std::string("italic"));
          break;
  }
  switch(this->mFontStyle)
  {
      case Text::WEIGHT_UNSET:
          break;
      case Text::WEIGHT_NORMAL:
          // if it has been set to normal, we
          // have to write it because otherwise it is assumed to
          // be inherited
          stream.writeAttribute("font-weight", getPrefix(), std::string("normal"));
          break;
      case Text::WEIGHT_BOLD:
          stream.writeAttribute("font-weight", getPrefix(), std::string("bold"));
          break;
  }
  if(this->isSetTextAnchor())
  {
      switch(this->mTextAnchor)
      {
          // if it has been set to normal, we
          // have to write it because otherwise it is assumed to
          // be inherited
          case Text::ANCHOR_START:
              stream.writeAttribute("text-anchor", getPrefix(), std::string("start"));
              break;
          case Text::ANCHOR_END:
              stream.writeAttribute("text-anchor", getPrefix(), std::string("end"));
              break;
          case Text::ANCHOR_MIDDLE:
              stream.writeAttribute("text-anchor", getPrefix(), std::string("middle"));
              break;
          case Text::ANCHOR_UNSET:
              break;
      }
  }
  if(this->isSetVTextAnchor())
  {
      switch(this->mVTextAnchor)
      {
          // if it has been set to normal, we
          // have to write it because otherwise it is assumed to
          // be inherited
          case Text::ANCHOR_TOP:
              stream.writeAttribute("vtext-anchor", getPrefix(), std::string("top"));
              break;
          case Text::ANCHOR_BOTTOM:
              stream.writeAttribute("vtext-anchor", getPrefix(), std::string("bottom"));
              break;
          case Text::ANCHOR_MIDDLE:
              stream.writeAttribute("vtext-anchor", getPrefix(), std::string("middle"));
              break;
           /*   
          case Text::ANCHOR_BASELINE:
              stream.writeAttribute("vtext-anchor",std::string("baseline"));
              break;
          */    
          case Text::ANCHOR_UNSET:
              break;
      }
  }
}
Example #18
0
void Cmd::executeVersion() {
	bool havemedia = false;
	bool havebackend = false;
	bool havedb = false;
	printf("Disko the embedded GUI framework\n");
	printf(" version:       %s\n", DISKO_VERSION_STR);
	printf(" prefix:        %s\n", getPrefix());
	printf(" media support: ");
#ifdef __HAVE_XINE__
	printf("xine");
	havemedia = true;
#endif
#ifdef __HAVE_GSTREAMER__
	if(havemedia) {
		printf(", gstreamer");
	} else {
		printf("gstreamer");
		havemedia=true;
	}
#endif
#ifdef __HAVE_MXIER__
	if(havemedia) {
		printf(", alsa mixing");
	} else {
		printf("alsa mixing");
		havemedia=true;
	}
#endif
	if(!havemedia) {
		printf("none\n");
	} else {
		printf("\n");
	}
	printf(" gfx support:   ");
#ifdef __HAVE_FBDEV__
	printf("fbdev");
	havebackend = true;
#endif
#ifdef __HAVE_DIRECTFB__
	if(havebackend) {
		printf(", directfb");
	} else {
		printf("directfb");
		havebackend = true;
	}
#endif
#ifdef __HAVE_XLIB__
	if(havebackend) {
		printf(", x11");
	} else {
		printf("x11");
		havebackend = true;
	}
#endif
	if(!havebackend) {
		printf("none\n");
	} else {
		printf("\n");
	}
	printf(" db support:    ");

#ifdef __ENABLE_SQLITE__
	printf("sqlite");
	havedb = true;
#endif
#ifdef __ENABLE_MYSQL__
	if(havedb) {
		printf(", mysql");
	} else {
		printf("mysql");
		havedb = true;
	}
#endif
#ifdef __ENABLE_FREETDS__
	if(havedb) {
		printf(", freetds");
	} else {
		printf("freetds");
		havedb = true;
	}
#endif
	if(!havedb) {
		printf("none\n");
	} else {
		printf("\n");
	}
#ifdef __HAVE_CURL__
	printf(" curl support:  no\n");
#else
	printf(" curl support:  yes\n");
#endif
#ifdef __HAVE_DL__
	printf(" dynamic libs:  yes\n");
#else
	printf(" dynamic libs:  no\n");
#endif
#ifdef __HAVE_MMSCRYPT__
	printf(" ssl support:   yes\n");
#else
	printf(" ssl support:   no\n");
#endif
	printf("\n");
	exit(0);
}
/*
 * Subclasses should override this method to write their XML attributes
 * to the XMLOutputStream.  Be sure to call your parents implementation
 * of this method as well.  For example:
 *
 *   SBase::writeAttributes(stream);
 *   stream.writeAttribute( "id"  , mId   );
 *   stream.writeAttribute( "name", mName );
 *   ...
 */
void ColorDefinition::writeAttributes (XMLOutputStream& stream) const
{
  SBase::writeAttributes(stream);
  stream.writeAttribute("id", getPrefix(), this->getId());
  stream.writeAttribute("value", getPrefix(), this->createValueString());
}
Example #20
0
// Parsing
QHash<QString, QVariant> ParserPrivate::parse(QStringList argv)
{
	QHash<QString, QVariant> map;

	QStringListIterator it(argv);
	QString programName = it.next();

	QString optionPrefix;
	QString flagPrefix;
	QListIterator<ParameterDefinition *> positionals(m_positionals);
	QStringList expecting;

	getPrefix(optionPrefix, flagPrefix);

	while (it.hasNext())
	{
		QString arg = it.next();

		if (!expecting.isEmpty())
		// we were expecting an argument
		{
			QString name = expecting.first();

			if (map.contains(name))
				throw ParsingError(
					QString("Option %2%1 was given multiple times").arg(name, optionPrefix));

			map[name] = QVariant(arg);

			expecting.removeFirst();
			continue;
		}

		if (arg.startsWith(optionPrefix))
		// we have an option
		{
			// qDebug("Found option %s", qPrintable(arg));

			QString name = arg.mid(optionPrefix.length());
			QString equals;

			if ((m_argStyle == ArgumentStyle::Equals ||
				 m_argStyle == ArgumentStyle::SpaceAndEquals) &&
				name.contains("="))
			{
				int i = name.indexOf("=");
				equals = name.mid(i + 1);
				name = name.left(i);
			}

			if (m_longLookup.contains(name))
			{
				ParameterDefinition *param = m_longLookup[name];

				if (map.contains(param->name))
					throw ParsingError(QString("Option %2%1 was given multiple times")
										   .arg(param->name, optionPrefix));

				if (param->type == DefinitionType::Switch)
					map[param->name] = !param->defaultValue.toBool();
				else // if (param->type == DefinitionType::Option)
				{
					if (m_argStyle == ArgumentStyle::Space)
						expecting.append(param->name);
					else if (!equals.isNull())
						map[param->name] = equals;
					else if (m_argStyle == ArgumentStyle::SpaceAndEquals)
						expecting.append(param->name);
					else
						throw ParsingError(QString("Option %2%1 reqires an argument.")
											   .arg(name, optionPrefix));
				}

				continue;
			}

			// We need to fall through if the prefixes match
			if (optionPrefix != flagPrefix)
				throw ParsingError(QString("Unknown Option %2%1").arg(name, optionPrefix));
		}

		if (arg.startsWith(flagPrefix))
		// we have (a) flag(s)
		{
			// qDebug("Found flags %s", qPrintable(arg));

			QString flags = arg.mid(flagPrefix.length());
			QString equals;

			if ((m_argStyle == ArgumentStyle::Equals ||
				 m_argStyle == ArgumentStyle::SpaceAndEquals) &&
				flags.contains("="))
			{
				int i = flags.indexOf("=");
				equals = flags.mid(i + 1);
				flags = flags.left(i);
			}

			for (int i = 0; i < flags.length(); i++)
			{
				QChar flag = flags.at(i);

				if (!m_flagLookup.contains(flag))
					throw ParsingError(QString("Unknown flag %2%1").arg(flag, flagPrefix));

				ParameterDefinition *param = m_flagLookup[flag];

				if (map.contains(param->name))
					throw ParsingError(QString("Option %2%1 was given multiple times")
										   .arg(param->name, optionPrefix));

				if (param->type == DefinitionType::Switch)
					map[param->name] = !param->defaultValue.toBool();
				else // if (param->type == DefinitionType::Option)
				{
					if (m_argStyle == ArgumentStyle::Space)
						expecting.append(param->name);
					else if (!equals.isNull())
						if (i == flags.length() - 1)
							map[param->name] = equals;
						else
							throw ParsingError(QString("Flag %4%2 of Argument-requiring Option "
													   "%1 not last flag in %4%3")
												   .arg(param->name, flag, flags, flagPrefix));
					else if (m_argStyle == ArgumentStyle::SpaceAndEquals)
						expecting.append(param->name);
					else
						throw ParsingError(QString("Option %1 reqires an argument. (flag %3%2)")
											   .arg(param->name, flag, flagPrefix));
				}
			}

			continue;
		}

		// must be a positional argument
		if (!positionals.hasNext())
			throw ParsingError(QString("Too many positional arguments: '%1'").arg(arg));

		ParameterDefinition *param = positionals.next();

		map[param->name] = arg;
	}

	// check if we're missing something
	if (!expecting.isEmpty())
		throw ParsingError(QString("Was still expecting arguments for %2%1").arg(
			expecting.join(QString(", ") + optionPrefix), optionPrefix));

	// fill out gaps
	for (QListIterator<ParameterDefinition *> it(m_definitions); it.hasNext();)
	{
		ParameterDefinition *param = it.next();
		if (!map.contains(param->name))
		{
			if (isRequired(param))
				throw ParsingError(
					QStringLiteral("Missing mandatory argument '%1'").arg(param->name));
			else
				map[param->name] = param->defaultValue;
		}
	}

	return map;
}
Example #21
0
//~~ void CodeCommonEventFiles() [StateChartCoderBase] ~~

wxFileName aFilename = myFilename;
std::set<wxString> theCommonEvents = commonEvents();
std::set<wxString> aSet = myAdeStatechart->GetTrigger();
aSet.insert(theCommonEvents.begin(), theCommonEvents.end());
aFilename.SetFullName(getPrefix()+wxS("_events.h"));

boost::interprocess::named_semaphore aSem(boost::interprocess::open_or_create_t(), (::wxGetUserId() + wxS("_ACF_events")).utf8_str(), 1);
aSem.wait();

wxTextFile aTextFile(aFilename.GetFullPath());
if (aTextFile.Exists())
{
	aTextFile.Open();

	for (wxString line = aTextFile.GetFirstLine(); !aTextFile.Eof(); line = aTextFile.GetNextLine())
	{
		char found[200];
		if (sscanf(line.utf8_str(), "extern const char* %s", found) == 1)
		{
			wxString aString(found, wxConvUTF8);
			aString.RemoveLast(); //semicolon
			aSet.insert(aString);
		}
	}
}

std::ofstream out;
out.open(aFilename.GetFullPath().utf8_str());
PrintHeader(out, aFilename.GetFullName());
Example #22
0
int main( int argc, char **argv){

	filePointer = (FILE *) malloc(10 * sizeof(FILE)); 
	int nextHopOctet1 = 0,nextHopOctet2 = 0,nextHopOctet3 = 0,nextHopOctet4 = 0;
	int i = 0, j = 0;
	tempStr = (char *)calloc(1,2*sizeof(char));
	charToStr = (char *)calloc(1,sizeof(char));
	nextHop = (char *)calloc(1,15*sizeof(char));
	data = (char *)calloc(1,20*sizeof(char));
	data1 = (char *)calloc(1,20*sizeof(char));
	mdata = (char *)calloc(1,20*sizeof(char));
	mdata1 = (char *)calloc(1,20*sizeof(char));
	trie = (BiTrie *)calloc(1,sizeof(BiTrie));
	mtrie = (mTrie *)calloc(1,sizeof(mTrie));
	node = (struct TrieNode *)calloc(1,sizeof(struct TrieNode));
	mnode = (struct mTrieNode *)calloc(1,sizeof(struct mTrieNode));
	mflag = (char *)calloc(1,2*sizeof(char));
	tempNode2 = (struct TrieNode *)calloc(1,sizeof(struct TrieNode));
	tempNode1 = (struct TrieNode *)calloc(1,sizeof(struct TrieNode));
	mtempNode2 = (struct mTrieNode *)calloc(1,sizeof(struct mTrieNode));
	mtempNode1 = (struct mTrieNode *)calloc(1,sizeof(struct mTrieNode));
	nextHop1 = (char *)calloc(1,20*sizeof(char));
	mprefixFinal = (char **)calloc(16,sizeof(char *));
	mlookupFinal = (char **)calloc(16,sizeof(char *));
	muprefixFinal = (char **)calloc(16,sizeof(char *));
	lookupfile = (char *)calloc(1,10*sizeof(char));
	updatefile = (char *)calloc(1,10*sizeof(char));
	prefixfile = (char *)calloc(1,10*sizeof(char));
	
	for(i = 0; i<16 ; i++) 
		if( (mprefixFinal[i] = (char *)calloc(3,sizeof(char))) == NULL )
			  fprintf(stderr, "\nMemory cannot be allocated");

	for(i = 0; i<16 ; i++) 
		if( (mlookupFinal[i] = (char *)calloc(3,sizeof(char))) == NULL )
			  fprintf(stderr, "\nMemory cannot be allocated");
	for(i = 0; i<16 ; i++) 
		if( (muprefixFinal[i] = (char *)calloc(3,sizeof(char))) == NULL )
			  fprintf(stderr, "\nMemory cannot be allocated");
	i = 0;

	BiTrieInit(trie);
	mTrieInit(mtrie);

	strcpy(prefixfile,argv[1]);
	filePointer = fopen(prefixfile, "r+");
	
	
	if( filePointer == NULL) 
		fprintf(stderr,"\nMemory cannot be allocated to filepointer");

	else 
	while( !feof(filePointer) ) {
		
		c = (char)getc(filePointer);
		sprintf(charToStr,"%c",c);
		strcat(tempStr,charToStr);
		
		if( c == '.' || c == ' ' || c == '/' || c == '\n') {

			i++;
			if(i == 1) {
				prefixOctet1 = atoi(tempStr);
				strcpy(tempStr,initializer);
			}
			if(i == 2) {
				prefixOctet2 = atoi(tempStr);
				strcpy(tempStr,initializer);
			}
			if(i == 3) {
				prefixOctet3 = atoi(tempStr);
				strcpy(tempStr,initializer);
			}
			if(i == 4) {
				prefixOctet4 = atoi(tempStr);
				strcpy(tempStr,initializer);
			}
		
			if(i == 5) {
				prefixLength = atoi(tempStr);
				strcpy(tempStr,initializer);
			}
			if(i == 6) {
				nextHopOctet1 = atoi(tempStr);
				strcpy(tempStr,initializer);
			}
			if(i == 7) {
				nextHopOctet2 = atoi(tempStr);
				strcpy(tempStr,initializer);
			}
			if(i == 8) {
				nextHopOctet3 = atoi(tempStr);
				strcpy(tempStr,initializer);
			}
			if(i == 9) {
				nextHopOctet4 = atoi(tempStr);
				strcpy(tempStr,initializer);
			}
		
		}
			if (c == '\n' ) {
				i = 0;
				strcpy(nextHop,initializer);
				strcpy(data,initializer);
				strcpy(mdata,initializer);
				
			//	printf("\n prefix %d.%d.%d.%d/%d  nextHop %d.%d.%d.%d", prefixOctet1,prefixOctet2, prefixOctet3, prefixOctet4, prefixLength, nextHopOctet1,nextHopOctet2,nextHopOctet3,nextHopOctet4);
				if(prefixLength <= 1 || prefixLength >= 31) {		
					badprefixCount++;
					continue;
				}
				getPrefix(prefixOctet1, prefixOctet2,prefixOctet3,prefixOctet4 ,prefixLength, prefixFinal, mprefixFinal);
				prefixCount++;
				sprintf(nextHop,"%d.%d.%d.%d",nextHopOctet1,nextHopOctet2,nextHopOctet3,nextHopOctet4);
				
				//printf(" prefixFinal : ");
				//for(j = 0 ; j< prefixLength; j++)
					//printf("%d", prefixFinal[j]);
				
				rdtsc(p);
				
				for(j = 0 ; j< prefixLength; j++){
			
					data = NULL;
					
					if( j == 0 && prefixCount > 1) trie->curRoot = trie->root;
					
					if(j == prefixLength -1) {
						data = (char *)calloc(1,20*sizeof(char));
						strcpy(data,nextHop);
					}
					
					if(prefixFinal[j] == 0){	
						trie->curRoot = BiTrieInsert(trie,trie->curRoot,data,0);
						continue;
					}
					
					else {
						if(prefixFinal[j] == 1){
							 trie->curRoot = BiTrieInsert(trie,trie->curRoot,data,1);
						 	 continue;
						}						
					}
				}
				
				rdtsc(q);
				unisum += (q-p);
				rdtsc(r);
				for(j = 0 ; j< mprefixLength; j++){
			
					mdata = NULL;
					
					if( j == 0 && prefixCount > 1) mtrie->curRoot = mtrie->root;
					
					if(j == mprefixLength -1) {
						mdata = (char *)calloc(1,20*sizeof(char));
						strcpy(mdata,nextHop);
					}
					
					if(strcmp(mprefixFinal[j],"00") == 0){	
						mtrie->curRoot = mTrieInsert(mtrie,mtrie->curRoot,mdata,"00",0);
						continue;
					}
					
					if(strcmp(mprefixFinal[j],"01") == 0){	
						mtrie->curRoot = mTrieInsert(mtrie,mtrie->curRoot,mdata,"01",0);
						continue;
					}
					
					if(strcmp(mprefixFinal[j],"10") == 0){	
						mtrie->curRoot = mTrieInsert(mtrie,mtrie->curRoot,mdata,"10",0);
						continue;
					}
					
					if(strcmp(mprefixFinal[j],"11") == 0){	
						mtrie->curRoot = mTrieInsert(mtrie,mtrie->curRoot,mdata,"11",0);
						continue;
					}
					
					else {
						if(strcmp(mprefixFinal[j],"0") == 0){
							 mTrieInsert(mtrie,mtrie->curRoot,mdata,"00",1);
						 	 mTrieInsert(mtrie,mtrie->curRoot,mdata,"01",1);
						 	 
						 	 continue;
						}
						else if(strcmp(mprefixFinal[j],"1") == 0){
							 mTrieInsert(mtrie,mtrie->curRoot,mdata,"10",1);
						 	 mTrieInsert(mtrie,mtrie->curRoot,mdata,"11",1);
						 	 
						 	 continue;
						}
					}
				}
			
				rdtsc(s);
				multisum += (s-r);
			}
		}	
		
	printf("\n-------------------------------------------------------------");	
		
	printf("\nThe total number of nodes in the unibit trie before update is %ld", trie->size);
	printf("\nThe total number of nodes in the multibit trie before update is %ld", mtrie->size);
	printf("\n-------------------------------------------------------------");	
	printf("\nThe total number of prefixes outside specified lengths is %ld", badprefixCount);
	printf("\nThe total time taken to construct unibit trie is %llu cycles", unisum);
	printf("\nThe total time taken to construct multibit trie is %llu cycles", multisum);
	printf("\n-------------------------------------------------------------");	
	printf("\nTotal number of loaded prefixes is %ld", prefixCount);
	printf("\nTotal number of prefixes (loaded + bad) is %ld", prefixCount + badprefixCount);
	printf("\nThe size of the unibit trie is %ld bytes or %ld MB ",(trie->size)*(sizeof(struct TrieNode)), (trie->size)*(sizeof(struct TrieNode))/(1024*1024) );
	printf("\nThe size of the multibit trie is %ld bytes or %ld MB",(mtrie->size)*(sizeof(struct mTrieNode)),(mtrie->size)*(sizeof(struct mTrieNode))/(1024*1024));
	printf("\n-------------------------------------------------------------");	
	
	printf("\nPlease Enter: \n1.Longest Prefix Match \n2.Update \n3.Exit\n");
	
	while(o = getchar()) {
		
		if(o == '1'){
			//printf("\nLooking up...");
			printf("\n--------------");
			printf("\nPlease Enter the filename: ");
			scanf("%s",lookupfile);
			ParseLookup(lookupfile);
		}
		else if(o == '2'){
			//printf("\nUpdating...");
			printf("\n--------------");
			printf("\nPlease Enter the filename: ");
			scanf("%s", updatefile);
			ParseUpdate(updatefile);
		}
		else if(o == '3')
			return 0;
	
		else 
			continue;
	
	
	printf("\n-----------------------------------------------------------------------");
	printf("\n Longest Prefix Match stats");
	printf("\n-----------------------------------------------------------------------");
	printf("\nNumber of addresses looked up is %ld", lookupCount);
	printf("\nThe Median time taken to perform lpm for unibit tries is %u cycles", ulpmmedian);
	printf("\nThe Median time taken to perform lpm for multi bit tries is %u cycles", mlpmmedian);
	printf("\n-----------------------------------------------------------------------");
	printf("\nThe Mean time taken to perform lpm for unibit tries is %u cycles", ulpmmean);
	printf("\nThe Mean time taken to perform lpm for multi bit tries is %u cycles", mlpmmean);
	printf("\n-----------------------------------------------------------------------");
	printf("\nThe Min time taken to perform lpm for unibit tries is %u cycles", ulpmmin);
	printf("\nThe Min time taken to perform lpm for multi bit tries is %u cycles", mlpmmin);
	printf("\n-----------------------------------------------------------------------");
	printf("\nThe Max time taken to perform lpm for unibit tries is %u cycles", ulpmmax);
	printf("\nThe Max time taken to perform lpm for multi bit tries is %u cycles", mlpmmax);
	
	printf("\n-----------------------------------------------------------------------");
	printf("\n Update and Delete stats");
	printf("\n-----------------------------------------------------------------------");
	printf("\nThe Total number of values  updated/deleted is %ld", uprefixCount);
	printf("\nThe Total number of new unibit  nodes created is %d\n", newnodes);
	printf("\nThe Total number of new multibit nodes created is %d\n", mnewnodes);
	printf("\n-----------------------------------------------------------------------");
	printf("\nThe Median time taken to perform updates for unibit tries is %u cycles", uupdatemedian);
	printf("\nThe Median time taken to perform updates for multi bit tries is %u cycles", mupdatemedian);
	printf("\n-----------------------------------------------------------------------");
	printf("\nThe Mean time taken to perform updates for unibit tries is %u cycles", uupdatemean);
	printf("\nThe Mean time taken to perform updates for multi bit tries is %u cycles", mupdatemean);
	printf("\n-----------------------------------------------------------------------");
	printf("\nThe Min time taken to perform updates for unibit tries is %u cycles", uupdatemin);
	printf("\nThe Min time taken to perform updates for multi bit tries is %u cycles", mupdatemin);
	printf("\n-----------------------------------------------------------------------");	
	printf("\nThe Max time taken to perform updates for unibit tries is %u cycles", uupdatemax);
	printf("\nThe Max time taken to perform updates for multi bit tries is %u cycles", mupdatemax);
	printf("\n-------------------------------------------------------------");	
	

	printf("\n\nThe total number of nodes in the trie after update is %ld", trie->size);
	printf("\n\nThe total number of nodes in the multibit trie after update is %ld", mtrie->size);
	printf("\nThe size of the unibit trie is %ld bytes or %ld MB ",(trie->size)*(sizeof(struct TrieNode)), (trie->size)*(sizeof(struct TrieNode))/(1024*1024) );
	printf("\nThe size of the multibit trie is %ld bytes or %ld MB",(mtrie->size)*(sizeof(struct mTrieNode)),(mtrie->size)*(sizeof(struct mTrieNode))/(1024*1024));
	
	
	
	
	//printf("\nThe lengths of different arrays are %llu, %llu, %llu, %llu\n",ulpmcount, mlpmcount, uupdatecount, mupdatecount);
	
	printf("\n-------------------------------------------------------------");	
	
	printf("\nPlease Enter: \n1.Longest Prefix Match \n2.Update \n3.Exit\n");
	
	}
	
	return 0;
	
}
Example #23
0
GIF_RETVAL decompress(JNIEnv *env, jobject currBlock, GifDecoder *decoder) {
    unsigned char *output, *outPtr;
    unsigned int i = 0; // Counter for decoded pixels
    GIF_RETVAL retval = STATUS_OK;

    if(decoder->stateVars.forceRGB) {
        output = malloc(decoder->currentHeight*decoder->currentWidth);
    } else {
        decoder->jByteOut = (*env)->GetObjectField(env, currBlock, img_GIF_gb_imageDataID);
        output = (*env)->GetPrimitiveArrayCritical(env, decoder->jByteOut, 0);
    }

    outPtr = output + decoder->pixelsDecoded;

    for(;;) {
        int savedBlockSize = *(decoder->inputPtr);
        int blockSize = savedBlockSize;
        DecompressInfo *di = &decoder->decompress;

        if(decoder->bytesInBuffer < savedBlockSize + 1) { // Cannot read next block
            retval = STATUS_BUFFER_EMPTY;
            break;
        }

        decoder->inputPtr++;
        decoder->bytesInBuffer--;

        if(savedBlockSize == 0) { // Frame completed
            decoder->state = STATE_BLOCK_BEGINNING;
            (*env)->SetBooleanField(env, currBlock, img_GIF_gb_completedID, TRUE);
            // Pass control to java code - need to call imageComplete and create new GifGraphicBlock
            retval = STATUS_FRAME_COMPLETED;
            break;
        }

        if(decoder->doProcessing) {
            unsigned char *savedPtr = decoder->inputPtr;
            for(;;) {
                if(di->shiftState < di->currCodeSize) {
                    // Need to read at least one more byte
                    di->accumbits |= (*(decoder->inputPtr++) << di->shiftState);
                    di->shiftState += 8;
                    blockSize--;
                } else {
                    di->currCode = di->accumbits & codeMasks[di->currCodeSize];
                    di->accumbits >>= di->currCodeSize;
                    di->shiftState -= di->currCodeSize;

                    // Check if we need to increase code size
                    if(++di->currKnownCode > di->maxCodeMinusOne && di->currCodeSize < MAX_BITS) {
                        unsigned int maxCodePlusOne = di->maxCodeMinusOne + 2;
                        di->currCodeSize++;
                        di->maxCodeMinusOne = (maxCodePlusOne << 1) - 2;
                    }

                    // Now process the obtained code
                    if (di->currCode == di->eoiCode) { // EOI encountered, stop processing
                        decoder->inputPtr += blockSize;
                        // Ensure that no more data will be decoded
                        di->shiftState = 0;
                        blockSize = 0;
                        decoder->doProcessing = FALSE;
                    } else if(di->currCode == di->clearCode) { // Clear code - reset code size
                        resetDecompressorState(decoder);
                    } else { // Regular code
                        if(di->currCode < di->clearCode) { // It is just a scalar pixel
                            outPtr[i++] = di->currCode;
                        } else { // Search for prefix for this code
                            // Code not added yet, corresponding prefix is the last code,
                            // suffix is the first character of the last code
                            if(di->prefix[di->currCode] == IMPOSSIBLE_CODE) {
                                di->currPrefix = di->lastCode;
                                di->suffix[di->currKnownCode] =
                                    di->stack[di->stackPointer++] = getPrefix(di->lastCode, di);
                            } else { // Set prefix to current code
                                di->currPrefix = di->currCode;
                            }

                            pushStack(di);

                            // Now pop the stack to get the output
                            while (di->stackPointer)
                                outPtr[i++] = di->stack[--(di->stackPointer)];
                        }

                        if(di->lastCode != IMPOSSIBLE_CODE) {
                            // Set prefix to last code and update suffix
                            di->prefix[di->currKnownCode] = di->lastCode;

                            // Suffix depends on wether it is a special case or not
                            if(di->currCode == di->currKnownCode) {
                                di->suffix[di->currKnownCode] = getPrefix(di->lastCode, di);
                            } else {
                                di->suffix[di->currKnownCode] = getPrefix(di->currCode, di);
                            }
                        }

                        // Save the last code
                        di->lastCode = di->currCode;
                    }
                }

                // Break if no more bytes to load in this block
                if(!blockSize && di->shiftState < di->currCodeSize)
                    break;
            } // while

        } else {
Example #24
0
// parsing
QHash<QString, QVariant> Parser::parse(QStringList argv)
{
	QHash<QString, QVariant> map;

	QStringListIterator it(argv);
	QString programName = it.next();

	QString optionPrefix;
	QString flagPrefix;
	QListIterator<PositionalDef *> positionals(m_positionals);
	QStringList expecting;

	getPrefix(optionPrefix, flagPrefix);

	while (it.hasNext())
	{
		QString arg = it.next();

		if (!expecting.isEmpty())
		// we were expecting an argument
		{
			QString name = expecting.first();
			/*
						if (map.contains(name))
							throw ParsingError(
								QString("Option %2%1 was given multiple times").arg(name,
			   optionPrefix));
			*/
			map[name] = QVariant(arg);

			expecting.removeFirst();
			continue;
		}

		if (arg.startsWith(optionPrefix))
		// we have an option
		{
			// qDebug("Found option %s", qPrintable(arg));

			QString name = arg.mid(optionPrefix.length());
			QString equals;

			if ((m_argStyle == ArgumentStyle::Equals ||
				 m_argStyle == ArgumentStyle::SpaceAndEquals) &&
				name.contains("="))
			{
				int i = name.indexOf("=");
				equals = name.mid(i + 1);
				name = name.left(i);
			}

			if (m_options.contains(name))
			{
				/*
				if (map.contains(name))
					throw ParsingError(QString("Option %2%1 was given multiple times")
										   .arg(name, optionPrefix));
*/
				OptionDef *option = m_options[name];
				if (option->type == otSwitch)
					map[name] = true;
				else // if (option->type == otOption)
				{
					if (m_argStyle == ArgumentStyle::Space)
						expecting.append(name);
					else if (!equals.isNull())
						map[name] = equals;
					else if (m_argStyle == ArgumentStyle::SpaceAndEquals)
						expecting.append(name);
					else
						throw ParsingError(QString("Option %2%1 reqires an argument.")
											   .arg(name, optionPrefix));
				}

				continue;
			}

			throw ParsingError(QString("Unknown Option %2%1").arg(name, optionPrefix));
		}

		if (arg.startsWith(flagPrefix))
		// we have (a) flag(s)
		{
			// qDebug("Found flags %s", qPrintable(arg));

			QString flags = arg.mid(flagPrefix.length());
			QString equals;

			if ((m_argStyle == ArgumentStyle::Equals ||
				 m_argStyle == ArgumentStyle::SpaceAndEquals) &&
				flags.contains("="))
			{
				int i = flags.indexOf("=");
				equals = flags.mid(i + 1);
				flags = flags.left(i);
			}

			for (int i = 0; i < flags.length(); i++)
			{
				QChar flag = flags.at(i);

				if (!m_flags.contains(flag))
					throw ParsingError(QString("Unknown flag %2%1").arg(flag, flagPrefix));

				OptionDef *option = m_flags[flag];
				/*
								if (map.contains(option->name))
									throw ParsingError(QString("Option %2%1 was given multiple
				   times")
														   .arg(option->name, optionPrefix));
				*/
				if (option->type == otSwitch)
					map[option->name] = true;
				else // if (option->type == otOption)
				{
					if (m_argStyle == ArgumentStyle::Space)
						expecting.append(option->name);
					else if (!equals.isNull())
						if (i == flags.length() - 1)
							map[option->name] = equals;
						else
							throw ParsingError(QString("Flag %4%2 of Argument-requiring Option "
													   "%1 not last flag in %4%3")
												   .arg(option->name, flag, flags, flagPrefix));
					else if (m_argStyle == ArgumentStyle::SpaceAndEquals)
						expecting.append(option->name);
					else
						throw ParsingError(QString("Option %1 reqires an argument. (flag %3%2)")
											   .arg(option->name, flag, flagPrefix));
				}
			}

			continue;
		}

		// must be a positional argument
		if (!positionals.hasNext())
			throw ParsingError(QString("Don't know what to do with '%1'").arg(arg));

		PositionalDef *param = positionals.next();

		map[param->name] = arg;
	}

	// check if we're missing something
	if (!expecting.isEmpty())
		throw ParsingError(QString("Was still expecting arguments for %2%1").arg(
			expecting.join(QString(", ") + optionPrefix), optionPrefix));

	while (positionals.hasNext())
	{
		PositionalDef *param = positionals.next();
		if (param->required)
			throw ParsingError(
				QString("Missing required positional argument '%1'").arg(param->name));
		else
			map[param->name] = param->def;
	}

	// fill out gaps
	QListIterator<OptionDef *> iter(m_optionList);
	while (iter.hasNext())
	{
		OptionDef *option = iter.next();
		if (!map.contains(option->name))
			map[option->name] = option->def;
	}

	return map;
}
Example #25
0
void ParseUpdate(char *updatefile){
	
	uupdatecount = mupdatecount = uupdatemedian  = mupdatemedian = uprefixCount =  0;
	char k=0;
	int j = 0;
	tempStr3 = (char *)calloc(1,2*sizeof(char));
	charToStr3 = (char *)calloc(1,sizeof(char));
	filePointer3 = (FILE *) calloc(1,10 * sizeof(FILE)); 
	
	filePointer3 = fopen(updatefile, "r+");
	
	if( filePointer3 == NULL) 
		fprintf(stderr,"\nMemory cannot be allocated to filepointer3");
	
	else 
		while( !feof(filePointer3) ) {
		
			e = (char)getc(filePointer3);
			
			if (e == 'W' || e == 'A') { 
				fseek(filePointer3,10,SEEK_CUR);
				continue;
			}
		
			else {
			
				sprintf(charToStr3,"%c",e);
				strcat(tempStr3,charToStr3);
		
				if( e == '.' || e == '\n' || e == '/' || e == ' ') {

					k++;
					if(k == 1) {
						uprefixOctet1 = atoi(tempStr3);
						strcpy(tempStr3,initializer);
					}
				
					if(k == 2) {
						uprefixOctet2 = atoi(tempStr3);
						strcpy(tempStr3,initializer);
					}
				
					if(k == 3) {
						uprefixOctet3 = atoi(tempStr3);
						strcpy(tempStr3,initializer);
					}
				
					if(k == 4) {
						uprefixOctet4 = atoi(tempStr3);
						strcpy(tempStr3,initializer);
					}
			
					if(k == 5) {
						uprefixLength = atoi(tempStr3);
						strcpy(tempStr3,initializer);
					}
					if(k == 6) {
						unextHopOctet1 = atoi(tempStr3);
						strcpy(tempStr3,initializer);
					}
					if(k == 7) {
						unextHopOctet2 = atoi(tempStr3);
						strcpy(tempStr3,initializer);
					}
					if(k == 8) {
						unextHopOctet3 = atoi(tempStr3);
						strcpy(tempStr3,initializer);
					}
					if(k == 9) {
						unextHopOctet4 = atoi(tempStr3);
						strcpy(tempStr3,initializer);
					}
		
				}
			}
		
		if (e == '\n' ) {
			k = 0;
			
			if(uprefixLength < 2 || uprefixLength > 30) 
				continue;
			
			u = u1 = v = v1 = g = g1 = h = h1 = 0;
				
			getPrefix(uprefixOctet1, uprefixOctet2,uprefixOctet3,uprefixOctet4 ,uprefixLength, uprefixFinal, muprefixFinal);
			uprefixCount++;
			
			if(unextHopOctet1 == 0 && unextHopOctet2 == 0 && unextHopOctet3 == 0 && unextHopOctet4 == 0 ){
				printf("\n\nDeleting nextHop at %d.%d.%d.%d/%d ", uprefixOctet1,uprefixOctet2, uprefixOctet3, uprefixOctet4, uprefixLength);
				//getPrefix(uprefixOctet1, uprefixOctet2,uprefixOctet3,uprefixOctet4 ,uprefixLength, uprefixFinal, muprefixFinal);
				rdtsc(u);
				deleteNode(uprefixFinal,trie->root,uprefixLength);
				rdtsc(u1);
				updateuniarray[uupdatecount++] = (u1 - u);
				rdtsc(v);
				mdeleteNode(muprefixFinal,mtrie->root,muprefixLength);
				rdtsc(v1);
				
				updatemultiarray[mupdatecount++] = (v1 - v);
			}
			else {
				printf("\n\nUpdating nextHop at %d.%d.%d.%d/%d ", uprefixOctet1,uprefixOctet2, uprefixOctet3, uprefixOctet4, uprefixLength, unextHopOctet1,unextHopOctet2,unextHopOctet3,unextHopOctet4);
				
				//getPrefix(uprefixOctet1, uprefixOctet2,uprefixOctet3,uprefixOctet4 ,uprefixLength, uprefixFinal, muprefixFinal);
				
				strcpy(nextHop1, initializer);
				sprintf(nextHop1,"%d.%d.%d.%d",unextHopOctet1,unextHopOctet2,unextHopOctet3,unextHopOctet4);
				
				if(uprefixLength % 2 == 0)
					muprefixLength = uprefixLength / 2;
				else 
					muprefixLength = (uprefixLength/2) + 1;
			
				rdtsc(g);
				for(j = 0 ; j< uprefixLength; j++){
			
					data1 = NULL;
					
					if( j == 0 ) tempNode2 = trie->root;
					
					if(j == uprefixLength -1) {
						data1 = (char *)calloc(1,20*sizeof(char));
						strcpy(data1,nextHop1);
					}
					
					if(uprefixFinal[j] == 0){	
						tempNode2 = updateNode(trie,tempNode2,data1,0);
						if(j == uprefixLength - 1){
							printf("\nReplacing nextHop");
							printf("\nThe previous value at this address was %s", tempNode2->data );
							if((tempNode2->data = (char *)calloc(1,20*sizeof(char)))==NULL)
								fprintf(stderr,"Memory could not be allocated using calloc to newdata");
							strcpy(tempNode2->data,nextHop1);
							printf("\nThe new value at this address is %s", tempNode2->data );
						}
						continue;
					}
					
					else {
						if(uprefixFinal[j] == 1){
							 tempNode2 = updateNode(trie,tempNode2,data1,1);
							 if(j == uprefixLength - 1 ){
							 	printf("\nReplacing nextHop");
							 	printf("\nThe previous value at this address was %s", tempNode2->data );
								if((tempNode2->data = (char *)calloc(1,20*sizeof(char)))==NULL)
									fprintf(stderr,"Memory could not be allocated using calloc to newdata");
							strcpy(tempNode2->data,nextHop1);
							printf("\nThe new value at this address is %s", tempNode2->data );
							}
						 	 continue;
						}						
					}
				}
				
				rdtsc(g1);
				updateuniarray[uupdatecount++] = (g1 - g);
				rdtsc(h);
				for(j = 0 ; j< muprefixLength; j++){
			
					mdata1 = NULL;
					
					if( j == 0 ) mtempNode2 = mtrie->root;
					
					if(j == muprefixLength -1) {
						mdata1 = (char *)calloc(1,20*sizeof(char));
						strcpy(mdata1,nextHop1);
					}
					
					if(strcmp(muprefixFinal[j], "00") == 0){	
						mtempNode2 = mupdateNode(mtrie,mtempNode2,mdata1,"00",0);
						if(j == muprefixLength - 1){
							printf("\nReplacing nextHop");
							printf("\nThe previous value at this address was %s", mtempNode2->pdata );
							if((mtempNode2->pdata = (char *)calloc(1,20*sizeof(char)))==NULL)
								fprintf(stderr,"Memory could not be allocated using calloc to mtempNode2->pdata");
							strcpy(mtempNode2->pdata,nextHop1);
							printf("\nThe new value at this address is %s", mtempNode2->pdata );
						}
						continue;
					}
					
					else if(strcmp(muprefixFinal[j], "01") == 0){	
						mtempNode2 = mupdateNode(mtrie,mtempNode2,mdata1,"01",0);
						if(j == muprefixLength - 1){
							printf("\nReplacing nextHop");
							printf("\nThe previous value at this address was %s", mtempNode2->pdata );
							if((mtempNode2->pdata = (char *)calloc(1,20*sizeof(char)))==NULL)
								fprintf(stderr,"Memory could not be allocated using calloc to mtempNode2->pdata");
							strcpy(mtempNode2->pdata,nextHop1);
							printf("\nThe new value at this address is %s", mtempNode2->pdata );
						}
						continue;
					}
					
					else if(strcmp(muprefixFinal[j], "10") == 0){	
						mtempNode2 = mupdateNode(mtrie,mtempNode2,mdata1,"10",0);
						if(j == muprefixLength - 1){
							printf("\nReplacing nextHop");
							printf("\nThe previous value at this address was %s", mtempNode2->pdata );
							if((mtempNode2->pdata = (char *)calloc(1,20*sizeof(char)))==NULL)
								fprintf(stderr,"Memory could not be allocated using calloc to mtempNode2->pdata");
							strcpy(mtempNode2->pdata,nextHop1);
							printf("\nThe new value at this address is %s", mtempNode2->pdata );
						}
						continue;
					}
					
					else if(strcmp(muprefixFinal[j], "11") == 0){	
						mtempNode2 = mupdateNode(mtrie,mtempNode2,mdata1,"11",0);
						if(j == muprefixLength - 1){
							printf("\nReplacing nextHop");
							printf("\nThe previous value at this address was %s", mtempNode2->pdata );
							if((mtempNode2->pdata = (char *)calloc(1,20*sizeof(char)))==NULL)
								fprintf(stderr,"Memory could not be allocated using calloc to mtempNode2->pdata");
							strcpy(mtempNode2->pdata,nextHop1);
							printf("\nThe new value at this address is %s", mtempNode2->pdata );
						}
						continue;
					}
					else {
						if(strcmp(muprefixFinal[j], "0") == 0){	
							 mupdateNode(mtrie,mtempNode2,mdata1,"00",1);
							 mupdateNode(mtrie,mtempNode2,mdata1,"01",1);
						
						if(j == muprefixLength - 1){
							printf("\nReplacing nextHop");
							printf("\nThe previous value at this address was %s", mtempNode2->first->sdata );
							
							if((mtempNode2->first->sdata = (char *)calloc(1,20*sizeof(char)))==NULL)
								fprintf(stderr,"Memory could not be allocated using calloc to mtempNode2->first->sdata");
							
							strcpy(mtempNode2->first->sdata,nextHop1);
							printf("\nThe new value at this address is %s", mtempNode2->first->sdata );
							
							printf("\nThe previous value at this address was %s", mtempNode2->second->sdata );
							
							if((mtempNode2->second->sdata = (char *)calloc(1,20*sizeof(char)))==NULL)
								fprintf(stderr,"Memory could not be allocated using calloc to mtempNode2->first->sdata");
							
							strcpy(mtempNode2->second->sdata,nextHop1);
							printf("\nThe new value at this address is %s", mtempNode2->second->sdata );
						
						}
						continue;
					}	
					
						else if(strcmp(muprefixFinal[j], "1") == 0){	
							 mupdateNode(mtrie,mtempNode2,mdata1,"10",1);
							 mupdateNode(mtrie,mtempNode2,mdata1,"11",1);
						
						if(j == muprefixLength - 1){
							printf("\nReplacing nextHop");
							printf("\nThe previous value at this address was %s", mtempNode2->third->sdata );
							
							if((mtempNode2->third->sdata = (char *)calloc(1,20*sizeof(char)))==NULL)
								fprintf(stderr,"Memory could not be allocated using calloc to mtempNode2->third->sdata");
							
							strcpy(mtempNode2->third->sdata,nextHop1);
							printf("\nThe new value at this address is %s", mtempNode2->third->sdata );
							
							printf("\nThe previous value at this address was %s", mtempNode2->fourth->sdata );
							
							if((mtempNode2->fourth->sdata = (char *)calloc(1,20*sizeof(char)))==NULL)
								fprintf(stderr,"Memory could not be allocated using calloc to mtempNode2->fourth->sdata");
							
							strcpy(mtempNode2->fourth->sdata,nextHop1);
							printf("\nThe new value at this address is %s", mtempNode2->fourth->sdata );
						
						}
						continue;
					}	
					
					}
				}
				rdtsc(h1);
				updatemultiarray[mupdatecount++] = (h1 - h);
				unextHopOctet1 = unextHopOctet2 = unextHopOctet3 = unextHopOctet4 = 0;
			}
				
				
		}		
	}
	
	uupdatemedian = getMedian(updateuniarray,uupdatecount);
	mupdatemedian = getMedian(updatemultiarray,mupdatecount);	
	uupdatemean = getMean(updateuniarray,uupdatecount);
	mupdatemean = getMean(updatemultiarray,mupdatecount);	
	uupdatemin = getMin(updateuniarray,uupdatecount);
	mupdatemin = getMin(updatemultiarray,mupdatecount);	
	uupdatemax = getMax(updateuniarray,uupdatecount);
	mupdatemax = getMax(updatemultiarray,mupdatecount);	
	
}
Example #26
0
void ParseLookup(char *lookupfile){
	
	ulpmcount = mlpmcount = ulpmmedian = mlpmmedian= lookupCount = 0;
	k = 0;
	tempStr2 = (char *)calloc(1,2*sizeof(char));
	charToStr2 = (char *)calloc(1,sizeof(char));
	filePointer2 = (FILE *) calloc(1,10 * sizeof(FILE)); 

	filePointer2 = fopen(lookupfile, "r+");
	//printf("\n\nInside ParseLookup() lookup.txt starts here\n\n");

	if( filePointer2 == NULL) 
		fprintf(stderr,"\nMemory cannot be allocated to filepointer2");
	
	else 
	while( !feof(filePointer2) ) {
		
		d = (char)getc(filePointer2);
		sprintf(charToStr2,"%c",d);
		strcat(tempStr2,charToStr2);
		
		if( d == '.' || d == '\n') {

			k++;
			if(k == 1) {
				lookupOctet1 = atoi(tempStr2);
				strcpy(tempStr2,initializer);
			}
			if(k == 2) {
				lookupOctet2 = atoi(tempStr2);
				strcpy(tempStr2,initializer);
			}
			if(k == 3) {
				lookupOctet3 = atoi(tempStr2);
				strcpy(tempStr2,initializer);
			}
			if(k == 4) {
				lookupOctet4 = atoi(tempStr2);
				strcpy(tempStr2,initializer);
			}
		
		
		}
			if (d == '\n' ) {		
				k = 0;
				printf("\nAddress %d.%d.%d.%d  ", lookupOctet1, lookupOctet2,lookupOctet3,lookupOctet4 );
				getPrefix(lookupOctet1, lookupOctet2,lookupOctet3,lookupOctet4 ,lookupLength, lookupFinal, mlookupFinal);
				getLongestPrefixMatch(lookupFinal, mlookupFinal);
			}
	}
	
	 
	ulpmmedian = getMedian(lpmuniarray,ulpmcount);
	mlpmmedian = getMedian(lpmmultiarray,mlpmcount);
	ulpmmean = getMean(lpmuniarray,ulpmcount);
	mlpmmean = getMean(lpmmultiarray,mlpmcount);
	ulpmmin = getMin(lpmuniarray,ulpmcount);
	mlpmmin = getMin(lpmmultiarray,mlpmcount);
	ulpmmax = getMax(lpmuniarray,ulpmcount);
	mlpmmax = getMax(lpmmultiarray,mlpmcount);
}
Example #27
0
unsigned int getPrefix(Node signature) {
    typeMetadata t = getTypes(signature);
    return getPrefix(t.name, t.inTypes);
}
bool TClntOptIA_PD::modifyPrefixes(TClntIfaceMgr::PrefixModifyMode mode)
{
    bool status = false;
    EState state = STATE_NOTCONFIGURED;
    SPtr<TClntOptIAPrefix> prefix;
    string action;
    switch(mode) {
      case TClntIfaceMgr::PREFIX_MODIFY_ADD:
        action = "addition";
        state = STATE_CONFIGURED;
        break;
      case TClntIfaceMgr::PREFIX_MODIFY_UPDATE:
        action = "update";
        state = STATE_CONFIGURED;
        break;
      case TClntIfaceMgr::PREFIX_MODIFY_DEL:
        action = "delete";
        state = STATE_NOTCONFIGURED;
        break;
    }
    
    if ( (mode==TClntIfaceMgr::PREFIX_MODIFY_ADD) || (mode==TClntIfaceMgr::PREFIX_MODIFY_UPDATE) ) {
      if ( (T1==0) && (T2==0) ) {
        firstPrefix();
        if (prefix = getPrefix()) {
          T1 = prefix->getPref()/2;
          T2 = (int)((prefix->getPref())*0.7);
          Log(Notice) << "Server set T1 and T2 to 0. Choosing default (50%, 70% * prefered-lifetime): T1=" << T1 
                      << ", T2=" << T2 << LogEnd;
        }
      }
    }

    this->firstPrefix();
    while (prefix = this->getPrefix() ) {
	switch (mode) {
    case TClntIfaceMgr::PREFIX_MODIFY_ADD:
	    ClntAddrMgr().addPrefix(this->DUID, this->Prefix, this->Iface, this->IAID, this->T1, this->T2,
                           prefix->getPrefix(), prefix->getPref(), prefix->getValid(), prefix->getPrefixLength(), false);
	    status = ClntIfaceMgr().addPrefix(this->Iface, prefix->getPrefix(), prefix->getPrefixLength(),
                                     prefix->getPref(), prefix->getValid());
        Log(Debug) << "RENEW will be sent (T1) after " << T1 << ", REBIND (T2) after " << T2 << " seconds." << LogEnd;
	    action = "addition";
	    break;
	case TClntIfaceMgr::PREFIX_MODIFY_UPDATE:
	    ClntAddrMgr().updatePrefix(this->DUID, this->Prefix, this->Iface, this->IAID, this->T1, this->T2,
				  prefix->getPrefix(), prefix->getPref(), prefix->getValid(), prefix->getPrefixLength(), false);
	    status = ClntIfaceMgr().updatePrefix(this->Iface, prefix->getPrefix(), prefix->getPrefixLength(),
					    prefix->getPref(), prefix->getValid());
        Log(Debug) << "RENEW will be sent (T1) after " << T1 << ", REBIND (T2) after " << T2 << " seconds." << LogEnd;
	    action = "update";
	    break;
	case TClntIfaceMgr::PREFIX_MODIFY_DEL:
	    ClntAddrMgr().delPrefix(ClntCfgMgr().getDUID(), this->IAID, prefix->getPrefix(), false);
	    status = ClntIfaceMgr().delPrefix(this->Iface, prefix->getPrefix(), prefix->getPrefixLength() );
	    action = "delete";
	    break;
	}
	
	if (!status) {
	    string tmp = error_message();
	    Log(Error) << "Prefix error encountered during prefix " << action << " operation: " << tmp << LogEnd;
            // Let's pretend it was configured and renew it
	    // setState(STATE_FAILED);
	    //return true;
	}
    }

    setState(state);
    return true;
}
Example #29
0
unsigned int getPrefix(std::string signature) {
    return getPrefix(parseSerpent(signature));
}