示例#1
0
    people * getContactFromNum(const QString & num) {
        for(std::vector<people *>::iterator it(this -> book.begin()); it != this -> book.end(); ++it) {
            for(std::vector<QString>::iterator vit((*it) -> cell.begin()); vit != (*it) -> cell.end(); ++vit) {
                if(*vit == num)
                    return *it;
            }

            for(std::vector<QString>::iterator vit((*it) -> home.begin()); vit != (*it) -> home.end(); ++vit) {
                if(*vit == num)
                    return *it;
            }
        }

        return 0;
    }
示例#2
0
 bool PadeConstraints::put(xmlNodePtr cur) {
   bool success=getVariables(cur);
   map<string,pair<string,RealType> >::iterator vit(inVars.find("B"));
   if(vit == inVars.end()) return false; //disaster, need to abort
   ID=(*vit).second.first; B=(*vit).second.second;
   return true;
 }
示例#3
0
	inline bool is_occupied()
	{
		if (boost::size(angles) <= 1)
		{
			return false;
		}

		std::sort(angles.begin(), angles.end(), angle_sort());

		typedef geometry::closing_iterator<collection_type const> closing_iterator;
		closing_iterator vit(angles);
		closing_iterator end(angles, true);

		closing_iterator prev = vit++;
		for( ; vit != end; prev = vit++)
		{
			if (! geometry::math::equals(prev->angle, vit->angle)
				&& ! prev->incoming
				&& vit->incoming)
			{
				return false;
			}
		}
		return true;
	}
示例#4
0
//-----------------------------------------------------------------------
Real
EBCellFAB::min(int a_comp) const
{
  CH_assert(isDefined());
  Real val = DBL_MAX;

  // Find the min on irregular cells.
  const EBISBox& ebbox = getEBISBox();
  const Box& box = BaseEBCellFAB<Real>::box();
  const IntVectSet validCells(box);
  for (VoFIterator vit(validCells, ebbox.getEBGraph()); vit.ok(); ++vit)
  {
    VolIndex vofi = vit();
    val = Min(val, (*this)(vofi, a_comp));
  }
  return val;
}
void TypeInferenceVisitor::processFunction(AstFunction* function) {
	Scope* scope = function->scope();
	Scope::VarIterator vit(scope);
	while(vit.hasNext()) {
		AstVar* var = vit.next();
		_types[var] = var->type();
	}
	function->node()->visit(this);
}
示例#6
0
void LanguageModelState::Print(const char *msg) {
  tprintf("%s VSEs (max_cost=%g prn_len=%d tot_len=%d):\n",
          msg, viterbi_state_entries_prunable_max_cost,
          viterbi_state_entries_prunable_length, viterbi_state_entries_length);
  ViterbiStateEntry_IT vit(&viterbi_state_entries);
  for (vit.mark_cycle_pt(); !vit.cycled_list(); vit.forward()) {
    vit.data()->Print("");
  }
}
 void OrbitalConstraintsBase::getParam(xmlNodePtr cur) 
 {
   const xmlChar* a=xmlGetProp(cur,(const xmlChar*)"id");
   const xmlChar* b=xmlGetProp(cur,(const xmlChar*)"name");
   if(a == NULL || b == NULL) return;
   RealType val;
   string vname((const char*)b);
   putContent(val,cur);
   map<string,pair<string,RealType> >::iterator vit(inVars.find(vname));
   if(vit == inVars.end()) {
     inVars[vname]=pair<string,RealType>((const char*)a,val);
   }
 }
示例#8
0
文件: mesh.cpp 项目: skopp/rush
void RBExport::SmoothNormals( VertexPtrArray& vertexEntries )
{
    int nEntries = vertexEntries.size();
    for (int i = 0; i < nEntries; i++)
    {
        //  mark zero-ring as "unvisited"
        ExpVertex::ZeroRingIterator it( vertexEntries[i] );
        while (it)
        {
            it->bVisited = false;
            ++it;
        }
        //  average normals inside vertices which share smoothing groups
        it = ExpVertex::ZeroRingIterator( vertexEntries[i] );
        while (it)
        {   
            ExpVertex* pVertex = it;
            ++it;
            if (pVertex->bVisited)
            {
                continue;
            }
            //  vertex was not visited yet, so calculate average normal 
            Vec3 normal = Vec3::null;
            ExpVertex::ZeroRingIterator vit( pVertex );
            while (vit)
            {
                if (vit->smGroup&pVertex->smGroup)
                {
                    normal += vit->normal;
                }
                ++vit;
            }
            normal.normalize();
            //  assign averaged normal inside all vertices sharing this smoothing 
            vit = ExpVertex::ZeroRingIterator( pVertex );
            while (vit)
            {
                if (vit->smGroup&pVertex->smGroup)
                {
                     vit->normal   = normal;
                     vit->bVisited = true;
                }
                ++vit;
            }
        } 
    }
} // RBExport::SmoothNormals
示例#9
0
bool Ephemeris::saveState(ossimKeywordlist& kwl, const char* prefix) const
{
    std::string pfx;
    if (prefix)
    {
        pfx = prefix;
    }
    pfx += PREFIX;

    ossimDpt3d pos(_position[0], _position[1], _position[2]);
    ossimDpt3d vit(_vitesse[0], _vitesse[1], _vitesse[2]);
    JulianDate jd = _date.get_day0hTU();

    kwl.add(pfx.c_str(), DATE_JULIAN_KW,  jd.get_julianDate());
    kwl.add(pfx.c_str(), DATE_SECOND_KW,  _date.get_second());
    kwl.add(pfx.c_str(), DATE_DECIMAL_KW, _date.get_decimal());
    kwl.add(pfx.c_str(), POSITION_KW,     pos.toString(15).c_str());
    kwl.add(pfx.c_str(), VELOCITY_KW,     vit.toString(15).c_str());

    return true;
}
示例#10
0
bool testMobile2(){
	// pour une hauteur de 10m le mobile doit mettre 1.427s pour atteindre le sol
	int j=1427;
	Vecteur3D posi(0,0,10);	
	Vecteur3D vit(0,0,0);
	MobilePesant P("moto",12.5);
	P.set_vitesse(vit);
	P.set_position(posi);
	while( j != 0 )
	{	
		std::cout<<"\n";
		P.gravite(0.001);
		j=j-1;	
		std::cout<<" VALEUR DE Z DE X\n";
		std::cout<< P.get_position()[2];	
		
		
	}
	
	

return true;
}
示例#11
0
void genHardNegativesOnAnnotations(FeatGen* ldgFeatGen,const path& baseDir, datasets currDataset, bool writeOutWins, bool viz,string modelfile)
{
	vector<path> negativePaths;
	vector<path> negTrainPaths;
	vector<path> negTestPaths;
	FrameId firstTestFrame; // separates training and testing data
	string learnFileStem;
	vector<path> normPosWinPathsTrain; // if any use folder with normalized cropped windows
		vector<path> normPosWinPathsTest; // if any use folder with normalized cropped windows
	getLearnInfos(baseDir, currDataset, negativePaths, negTrainPaths, negTestPaths,normPosWinPathsTrain, normPosWinPathsTest, learnFileStem, firstTestFrame);

	path negTrainFolder = baseDir / "learning" / "train_neg_hard_annot";
	remove_all(negTrainFolder);
	create_directories(negTrainFolder);

	//std::ios_base::openmode mode = ;
	//fs::ofstream trainFile((baseDir / "learning" / learnFileStem).string(), std::ios_base::out | ios_base::app);
	//fs::ofstream trainFilesFile((baseDir / "learning" / learnFileStem).string() + ".files", std::ios_base::out | ios_base::app);

	fs::ofstream trainFileHard((baseDir / "learning" / learnFileStem).string() + "_hard_annot");


	if ( !(modelfile.length() > 0 ) )
	{
		modelfile = (baseDir / "learning" / learnFileStem).string() + ".model";
	}
	path mfp(modelfile);
	if ( !exists(mfp))
	{
		cerr << "Modelfile does not exist: " << modelfile << endl;
		exit(EXIT_FAILURE);
	}
	cout << "genHardNegativesOnAnnotations using model: " << modelfile << endl;
	Detector pd(ldgFeatGen);
	pd.setStartScale(1.0);
	pd.setScaleStep(1.04);
	pd.loadSVMWeights(modelfile);
	float decThresh = 0;

	int nww = ldgFeatGen->getWinW();
	int nwh = ldgFeatGen->getWinH();

	// use caltech annotations
	FrameId startFrame;
	startFrame.set= 0;
	startFrame.video= 0;
	startFrame.image= 0;

	size_t featSize = getFeatLen(ldgFeatGen);

			vector<path> annotFiles;
			annotFiles = findAllAnnotations(baseDir,startFrame);

			if ( annotFiles.size() == 0 )
			{
				cerr << "No annotations found." << endl;
				exit(EXIT_FAILURE);
			}

			for ( vector<path>::iterator it (annotFiles.begin()); it != annotFiles.end(); ++it)
			{
				path vbbFile = *it;
				path txtFolder = vbbFile.parent_path() / vbbFile.stem();

				vector<path> v;
				copy(directory_iterator(txtFolder),directory_iterator(),back_inserter(v));

				sort(v.begin(),v.end());
				int posTrainCounter = 0;
				cout << "0% ";
				cout.flush();
				for ( vector<path>::iterator vit (v.begin()); vit != v.end(); ++vit)
				{
					path txtFile = *vit; // annotation txtFile

					// corresponding image file
					path imgFile = baseDir / "videos" / txtFile.parent_path().parent_path().stem() / txtFile.parent_path().stem() / txtFile.filename().stem();
					bool isTrain = true;

					if (frameLTEQ(firstTestFrame,parseFrameFromPath(imgFile)))
					{
						isTrain = false;
					}

					if ( skipPath(imgFile,startFrame) )
						continue;

					if ( !isTrain ) continue;

					imgFile += findImageExtension(imgFile);

					if ( !exists(imgFile) || !is_regular_file(imgFile))
					{
						cerr << "Could not find corresponding image file " <<imgFile <<endl;
						cerr << "Export all .seq files using provided matlab code." << endl;
						exit(EXIT_FAILURE);
					}

					// parse annotations from txtFile
					fs::ifstream f(txtFile);
					if (!f)
					{
						cerr << "cannot open file " << txtFile << endl;
						exit(EXIT_FAILURE);
					}

					vector<Annotation> annots;

					string buffer;
					while (std::getline(f,buffer))
					{
						Annotation a = parseAnnotation(buffer);
						if ( a.type == "person" )
						{
							//printAnnotation(a);
							annots.push_back(a);
						}

					}

					// extract normalized bb images
					Mat img = imread(imgFile.string(), CV_LOAD_IMAGE_COLOR);

					posTrainCounter++;
					if ( (posTrainCounter % 100) == 0)
					{
						float donePerc = posTrainCounter / (float)v.size();
						cout << floor(donePerc * 100) << "% ";
						cout.flush();
					}


					path nf = imgFile;
					string filePre  = nf.parent_path().parent_path().stem().string() + nf.parent_path().stem().string() +  "_" + nf.filename().stem().string();

					vector< pair < Detection,double* > > detections;
					vector<Detection> alldetections;
					pd.detect(img,detections,alldetections,decThresh,true);

					vector<bool> rectIsUsed;
					rectIsUsed.resize(detections.size());
					for ( size_t i = 0; i < detections.size(); i++)
					{
						pair < Detection,double* > mp = detections[i];
						Detection det = mp.first;
						Rect r = det.r;
						double* f = mp.second;

						// check if rectangle is annotated object
						bool rectIsFree = true;
						for (vector<Annotation>::iterator ait (annots.begin()); ait != annots.end(); ++ait)
						{
							Annotation an = *ait;
							Rect a(an.x,an.y,an.width,an.height);

							// calc intersection area
							Rect inters =  a & r;
							if ( inters.area() > 0 )
							{
								// further analyze intersection

								double ratio1 = (double) inters.area() / (double) r.area();
								double ratio2 = (double) inters.area() / (double) a.area();

								double ratio = min(ratio1,ratio2);


								rectIsFree = !(ratio > 0.5);
								if ( !rectIsFree )
								{
									break;
								}
							}
						}
						rectIsUsed[i] = rectIsFree;

						if ( rectIsFree )
						{
							// save as negative example
							writeFeatToSVMStream(f,trainFileHard,featSize,false);
						}
						else
						{
							// save as positive example
							writeFeatToSVMStream(f,trainFileHard,featSize,true);
						}

						delete[] f;

					}


					if ( viz || writeOutWins )
					{
						Mat vizImg = img.clone();
						if ( alldetections.size() < 100 )
						{
							for ( vector< Detection >::iterator it(alldetections.begin()); it != alldetections.end(); it++)
							{
								Detection det = *it;
								Rect r = det.rNormWin;

								//cout << r.x << " " << r.y << " " << r.width << "x" << r.height << " scale:" << det.scale << " decisionValue:" << det.decisionValue << endl;
								rectangle(vizImg,r,Scalar(255,50,50),1,8);

							}
						}

						for ( size_t i = 0; i < detections.size(); i++)
						{
							Detection det = detections[i].first;
							Rect r = det.r;

							if ( rectIsUsed[i])
							{
								rectangle(vizImg,r,Scalar(0,0,255),1,8);
							}
							else
							{
								rectangle(vizImg,r,Scalar(0,255,255),1,8);
							}

						}

						displayAnnotations(vizImg,annots);

						if ( writeOutWins )
						{
							string fileNameOnly = (filePre +"_hard.png");
							path nwPath = negTrainFolder / fileNameOnly;
							imwrite(nwPath.string(),vizImg);
						}
						if ( viz )
						{
							imshow("negative training image",vizImg);
							waitKey(0);
							destroyWindow("negative training image");
						}
					}


				}


			}
			cout << "100% "<< endl;
	trainFileHard.close();
}
示例#12
0
	// return true if jsonp applied
	bool tryApplyJsonp(const DomainMap::JsonpConfig &config, bool *ok, QString *errorMessage)
	{
		*ok = true;

		// must be a GET
		if(requestData.method != "GET")
			return false;

		QString callbackParam = QString::fromUtf8(config.callbackParam);
		if(callbackParam.isEmpty())
			callbackParam = "callback";

		QString bodyParam;
		if(!config.bodyParam.isEmpty())
			bodyParam = QString::fromUtf8(config.bodyParam);

		QUrl uri = requestData.uri;
		QUrlQuery query(uri);

		// two ways to activate JSON-P:
		//   1) callback param present
		//   2) default callback specified in configuration and body param present
		if(!query.hasQueryItem(callbackParam) &&
			(config.defaultCallback.isEmpty() || bodyParam.isEmpty() || !query.hasQueryItem(bodyParam)))
		{
			return false;
		}

		QByteArray callback;
		if(query.hasQueryItem(callbackParam))
		{
			callback = parsePercentEncoding(query.queryItemValue(callbackParam, QUrl::FullyEncoded).toUtf8());
			if(callback.isEmpty())
			{
				log_debug("requestsession: id=%s invalid callback parameter, rejecting", rid.second.data());
				*ok = false;
				*errorMessage = "Invalid callback parameter.";
				return false;
			}

			query.removeAllQueryItems(callbackParam);
		}
		else
			callback = config.defaultCallback;

		QString method;
		if(query.hasQueryItem("_method"))
		{
			method = QString::fromLatin1(parsePercentEncoding(query.queryItemValue("_method", QUrl::FullyEncoded).toUtf8()));
			if(!validMethod(method))
			{
				log_debug("requestsession: id=%s invalid _method parameter, rejecting", rid.second.data());
				*ok = false;
				*errorMessage = "Invalid _method parameter.";
				return false;
			}

			query.removeAllQueryItems("_method");
		}

		HttpHeaders headers;
		if(query.hasQueryItem("_headers"))
		{
			QJsonParseError e;
			QJsonDocument doc = QJsonDocument::fromJson(parsePercentEncoding(query.queryItemValue("_headers", QUrl::FullyEncoded).toUtf8()), &e);
			if(e.error != QJsonParseError::NoError || !doc.isObject())
			{
				log_debug("requestsession: id=%s invalid _headers parameter, rejecting", rid.second.data());
				*ok = false;
				*errorMessage = "Invalid _headers parameter.";
				return false;
			}

			QVariantMap headersMap = doc.object().toVariantMap();

			QMapIterator<QString, QVariant> vit(headersMap);
			while(vit.hasNext())
			{
				vit.next();

				if(vit.value().type() != QVariant::String)
				{
					log_debug("requestsession: id=%s invalid _headers parameter, rejecting", rid.second.data());
					*ok = false;
					*errorMessage = "Invalid _headers parameter.";
					return false;
				}

				QByteArray key = vit.key().toUtf8();

				// ignore some headers that we explicitly set later on
				if(qstricmp(key.data(), "host") == 0)
					continue;
				if(qstricmp(key.data(), "accept") == 0)
					continue;

				headers += HttpHeader(key, vit.value().toString().toUtf8());
			}

			query.removeAllQueryItems("_headers");
		}

		QByteArray body;
		if(!bodyParam.isEmpty())
		{
			if(query.hasQueryItem(bodyParam))
			{
				body = parsePercentEncoding(query.queryItemValue(bodyParam, QUrl::FullyEncoded).toUtf8());
				if(body.isNull())
				{
					log_debug("requestsession: id=%s invalid body parameter, rejecting", rid.second.data());
					*ok = false;
					*errorMessage = "Invalid body parameter.";
					return false;
				}

				headers.removeAll("Content-Type");
				headers += HttpHeader("Content-Type", "application/json");

				query.removeAllQueryItems(bodyParam);
			}
		}
		else
		{
			if(query.hasQueryItem("_body"))
			{
				body = parsePercentEncoding(query.queryItemValue("_body").toUtf8());
				if(body.isNull())
				{
					log_debug("requestsession: id=%s invalid _body parameter, rejecting", rid.second.data());
					*ok = false;
					*errorMessage = "Invalid _body parameter.";
					return false;
				}

				query.removeAllQueryItems("_body");
			}
		}

		uri.setQuery(query);

		// if we have no query items anymore, strip the '?'
		if(query.isEmpty())
		{
			QByteArray tmp = uri.toEncoded();
			if(tmp.length() > 0 && tmp[tmp.length() - 1] == '?')
			{
				tmp.truncate(tmp.length() - 1);
				uri = QUrl::fromEncoded(tmp, QUrl::StrictMode);
			}
		}

		if(method.isEmpty())
			method = config.defaultMethod;

		requestData.method = method;

		requestData.uri = uri;

		headers += HttpHeader("Host", uri.host().toUtf8());
		headers += HttpHeader("Accept", "*/*");

		// carry over the rest of the headers
		foreach(const HttpHeader &h, requestData.headers)
		{
			if(qstricmp(h.first.data(), "host") == 0)
				continue;
			if(qstricmp(h.first.data(), "accept") == 0)
				continue;

			headers += h;
		}

		requestData.headers = headers;
		in += body;

		jsonpCallback = callback;
		jsonpExtendedResponse = (config.mode == DomainMap::JsonpConfig::Extended);

		return true;
	}
示例#13
0
bool M2RequestPacket::fromByteArray(const QByteArray &in)
{
	int start = 0;
	int end = in.indexOf(' ');
	if(end == -1)
		return false;

	sender = in.mid(start, end - start);

	start = end + 1;
	end = in.indexOf(' ', start);
	if(end == -1)
		return false;

	id = in.mid(start, end - start);

	start = end + 1;
	end = in.indexOf(' ', start);
	if(end == -1)
		return false;

	QByteArray path_only = in.mid(start, end - start);

	start = end + 1;
	TnetString::Type type;
	int offset, size;
	if(!TnetString::check(in, start, &type, &offset, &size))
		return false;

	if(type != TnetString::Hash && type != TnetString::ByteArray)
		return false;

	bool ok;
	QVariant vheaders = TnetString::toVariant(in, start, type, offset, size, &ok);
	if(!ok)
		return false;

	QVariantMap headersMap;
	if(type == TnetString::Hash)
	{
		headersMap = vheaders.toMap();
	}
	else // ByteArray
	{
		QJson::Parser parser;
		vheaders = parser.parse(vheaders.toByteArray(), &ok);
		if(!ok)
			return false;

		headersMap = vheaders.toMap();
	}

	QMap<QString, QByteArray> m2headers;
	QMapIterator<QString, QVariant> vit(headersMap);
	while(vit.hasNext())
	{
		vit.next();

		if(vit.value().type() != QVariant::String)
			return false;

		m2headers[vit.key()] = vit.value().toString().toUtf8();
	}

	start = offset + size + 1;
	if(!TnetString::check(in, start, &type, &offset, &size))
		return false;

	if(type != TnetString::ByteArray)
		return false;

	body = TnetString::toByteArray(in, start, offset, size, &ok);
	if(!ok)
		return false;

	scheme = m2headers.value("URL_SCHEME");

	QByteArray m2method = m2headers.value("METHOD");

	if(m2method == "JSON")
	{
		QJson::Parser parser;
		QVariant vdata = parser.parse(body, &ok);
		if(!ok)
			return false;

		if(vdata.type() != QVariant::Map)
			return false;

		QVariantMap data = vdata.toMap();
		if(!data.contains("type") || data["type"].type() != QVariant::String)
			return false;

		QString type = data["type"].toString();
		if(type != "disconnect")
			return false;

		isDisconnect = true;
		return true;
	}

	method = QString::fromLatin1(m2method);
	path = m2headers.value("URI");

	QByteArray uploadStartRaw = m2headers.value("x-mongrel2-upload-start");
	QByteArray uploadDoneRaw = m2headers.value("x-mongrel2-upload-done");
	if(!uploadDoneRaw.isEmpty())
	{
		// these headers must match for the packet to be valid. not
		//   sure why mongrel2 can't enforce this for us but whatever
		if(uploadStartRaw != uploadDoneRaw)
			return false;

		uploadFile = QString::fromUtf8(uploadDoneRaw);
		uploadDone = true;
	}
	else if(!uploadStartRaw.isEmpty())
	{
		uploadFile = QString::fromUtf8(uploadStartRaw);
	}

	QSet<QString> skipHeaders;
	skipHeaders += "x-mongrel2-upload-start";
	skipHeaders += "x-mongrel2-upload-done";

	headers.clear();
	QMapIterator<QString, QByteArray> it(m2headers);
	while(it.hasNext())
	{
		it.next();

		QString key = it.key();
		if(isAllCaps(key) || skipHeaders.contains(key))
			continue;

		headers += HttpHeader(makeMixedCaseHeader(key).toLatin1(), it.value());
	}

	return true;
}
示例#14
0
bool SpirValidation::runOnModule(Module& M) {
  // Holder for initialized data in the module
  DataHolder Data;

  // Initialize instruction verifiers.
  InstructionExecutorList iel;
  // Bitcast instruction verifier.
  VerifyBitcast vb(&ErrHolder);
  iel.push_back(&vb);
  // Call instruction verifier.
  VerifyCall vc(&ErrHolder);
  iel.push_back(&vc);
  // Instruction type verifier.
  VerifyInstructionType vit(&ErrHolder, &Data);
  iel.push_back(&vit);

  // Initialize function verifiers.
  FunctionExecutorList fel;
  // Function prototype verifier.
  VerifyFunctionPrototype vfp(&ErrHolder, &Data);
  fel.push_back(&vfp);

  // Initialize module verifiers.
  ModuleExecutorList mel;
  // Module triple and target data layout verifier.
  VerifyTripleAndDataLayout vtdl(&ErrHolder, &Data);
  mel.push_back(&vtdl);
  // Module metadata kernels verifier.
  VerifyMetadataKernels vkmd(&ErrHolder, &Data);
  mel.push_back(&vkmd);
  // Module OCL version verifier.
  VerifyMetadataVersions voclv(
    &ErrHolder, VerifyMetadataVersions::VERSION_OCL);
  mel.push_back(&voclv);
  // Module SPIR version verifier.
  VerifyMetadataVersions vspirv(
    &ErrHolder, VerifyMetadataVersions::VERSION_SPIR);
  mel.push_back(&vspirv);
  // Module metadata optional core features verifier.
  VerifyMetadataCoreFeatures vmdcf(&ErrHolder, &Data);
  mel.push_back(&vmdcf);
  // Module metadata KHR extensions verifier.
  VerifyMetadataKHRExtensions vmdext(&ErrHolder, &Data);
  mel.push_back(&vmdext);
  // Module metadata compiler options verifier.
  VerifyMetadataCompilerOptions vmdco(&ErrHolder, &Data);
  mel.push_back(&vmdco);

  // Initialize basic block iterator.
  BasicBlockIterator BBI(iel);

  // Initialize function iterator.
  FunctionIterator FI(fel, &BBI);

  // Initialize module iterator.
  ModuleIterator MI(mel, &FI);

  // Run validation.
  MI.execute(M);

  return false;
}
示例#15
0
  bool
    LRTwoBodyJastrow::put(xmlNodePtr cur, VarRegistry<RealType>& vlist) {
      
      if(skRef == 0) {
        app_error() << "  LRTowBodyJastrow should not be used for non periodic systems." << endl;
        return false;
      }
      
      std::map<int,std::vector<int>*>& kpts_sorted(skRef->KLists.kpts_sorted);
      Fk_symm.resize(kpts_sorted.size());
      
      bool foundCoeff=false;
      xmlNodePtr tcur=cur->children;
      while(tcur != NULL) {
        string cname((const char*)(tcur->name));
        if(cname == "parameter") {
          const xmlChar* kptr=xmlGetProp(tcur,(const xmlChar *)"name");
          const xmlChar* idptr=xmlGetProp(tcur,(const xmlChar *)"id");
          if(idptr!= NULL && kptr != NULL) {
            int ik=atoi((const char*)kptr);
            if(ik<Fk_symm.size()) { // only accept valid ik 
              RealType x;
              putContent(x,tcur);
              Fk_symm[ik]=x;
              vlist.add((const char*)idptr,Fk_symm.data()+ik);
            }
            foundCoeff=true;
          }
        }
        tcur=tcur->next;
      }
      
      Fk.resize(NumKpts);
      if(foundCoeff) {
        reset();
      } else {
        std::map<int,std::vector<int>*>::iterator it(kpts_sorted.begin());
        int uniqueK=0;
        while(it != kpts_sorted.end()) {
          std::vector<int>::iterator vit((*it).second->begin());
          int ik=(*vit);
          Fk_symm[uniqueK]=Fk[ik]=-1.0*handler->Fk[ik];
          ++vit;
          while(vit != (*it).second->end()) {
            int ik=(*vit);
            Fk[ik]=-1.0*handler->Fk[ik];
            ++vit;
          }
          ++it;++uniqueK;
        }
        char coeffname[128];
        for(int ik=0; ik<Fk_symm.size(); ik++) {
          sprintf(coeffname,"rpa_k%d",ik);
	  
          vlist.add(coeffname,Fk_symm.data()+ik);
	  
          std::ostringstream kname,val;
          kname << ik;
          val<<Fk_symm[ik];
          xmlNodePtr p_ptr = xmlNewTextChild(cur,NULL,(const xmlChar*)"parameter",
					     (const xmlChar*)val.str().c_str());
          xmlNewProp(p_ptr,(const xmlChar*)"id",(const xmlChar*)coeffname);
          xmlNewProp(p_ptr,(const xmlChar*)"name",(const xmlChar*)kname.str().c_str());
        }
      }
      
      app_log() << "  Long-range Two-Body Jastrow coefficients " << endl;
      for(int ikpt=0; ikpt<NumKpts; ikpt++) {
        app_log() <<  skRef->KLists.ksq[ikpt] << " " << Fk[ikpt] << endl;
      }
      return true;
    }
示例#16
0
Expression::Ptr ExpressionFactory::createExpression(const Tokenizer::Ptr &tokenizer,
                                                    const StaticContext::Ptr &context,
                                                    const QXmlQuery::QueryLanguage lang,
                                                    const SequenceType::Ptr &requiredType,
                                                    const QUrl &queryURI,
                                                    const QXmlName &initialTemplateName)
{
    Q_ASSERT(context);
    Q_ASSERT(requiredType);
    Q_ASSERT(queryURI.isValid());

    Tokenizer::Ptr effectiveTokenizer(tokenizer);
#ifdef Patternist_DEBUG
    effectiveTokenizer = Tokenizer::Ptr(new TokenRevealer(queryURI, tokenizer));
#endif

    OptimizationPasses::Coordinator::init();

    const ParserContext::Ptr info(new ParserContext(context, lang, effectiveTokenizer.data()));
    info->initialTemplateName = initialTemplateName;

    effectiveTokenizer->setParserContext(info);

    const int bisonRetval = QPatternist::XPathparse(info.data());

    Q_ASSERT_X(bisonRetval == 0, Q_FUNC_INFO,
               "We shouldn't be able to get an error, because we throw exceptions.");
    Q_UNUSED(bisonRetval); /* Needed when not compiled in debug mode, since bisonRetval won't
                            * be used in the Q_ASSERT_X above. */

    Expression::Ptr result(info->queryBody);

    if(!result)
    {
        context->error(QtXmlPatterns::tr("A library module cannot be evaluated "
                                         "directly. It must be imported from a "
                                         "main module."),
                       ReportContext::XPST0003,
                       QSourceLocation(queryURI, 1, 1));
    }

    /* Optimization: I think many things are done in the wrong order below. We
     * probably want everything typechecked before compressing, since we can
     * have references all over the place(variable references, template
     * invocations, function callsites). This could even be a source to bugs.
     */

    /* Here, we type check user declared functions and global variables. This
     * means that variables and functions that are not used are type
     * checked(which they otherwise wouldn't have been), and those which are
     * used, are type-checked twice, unfortunately. */

    const bool hasExternalFocus = context->contextItemType();

    if(lang == QXmlQuery::XSLT20)
    {
        /* Bind xsl:call-template instructions to their template bodies.
         *
         * We do this before type checking and compressing them, because a
         * CallTemplate obviously needs its template before being compressed.
         *
         * Also, we do this before type checking and compressing user
         * functions, since they can contain template call sites.
         */
        for(int i = 0; i < info->templateCalls.count(); ++i)
        {
            CallTemplate *const site = info->templateCalls.at(i)->as<CallTemplate>();
            const QXmlName targetName(site->name());
            const Template::Ptr t(info->namedTemplates.value(targetName));

            if(t)
                site->setTemplate(t);
            else
            {
                context->error(QtXmlPatterns::tr("No template by name %1 exists.").arg(formatKeyword(context->namePool(), targetName)),
                               ReportContext::XTSE0650,
                               site);
            }
        }
    }

    /* Type check and compress user functions. */
    {
        const UserFunction::List::const_iterator end(info->userFunctions.constEnd());
        UserFunction::List::const_iterator it(info->userFunctions.constBegin());

        /* If the query has a focus(which is common, in the case of a
         * stylesheet), we must ensure that the focus isn't visible in the
         * function body. */
        StaticContext::Ptr effectiveContext;

        if(hasExternalFocus)
        {
            effectiveContext = StaticContext::Ptr(new StaticFocusContext(ItemType::Ptr(),
                                                                         context));
        }
        else
            effectiveContext = context;

        for(; it != end; ++it)
        {
            pDebug() << "-----      User Function Typecheck      -----";
            registerLastPath((*it)->body());

            /* We will most likely call body()->typeCheck() again, once for
             * each callsite. That is, it will be called from
             * UserFunctionCallsite::typeCheck(), which will be called
             * indirectly when we check the query body. */
            const Expression::Ptr typeCheck((*it)->body()->typeCheck(effectiveContext,
                                                                     (*it)->signature()->returnType()));
            /* We don't have to call (*it)->setBody(typeCheck) here since it's
             * only used directly below. */
            processTreePass(typeCheck, UserFunctionTypeCheck);
            pDebug() << "------------------------------";

            pDebug() << "-----      User Function Compress      -----";
            const Expression::Ptr comp(typeCheck->compress(effectiveContext));
            (*it)->setBody(comp);
            processTreePass(comp, UserFunctionCompression);
            pDebug() << "------------------------------";
        }
    }

    /* Type check and compress global variables. */
    {
        const VariableDeclaration::Stack::const_iterator vend(info->variables.constEnd());
        VariableDeclaration::Stack::const_iterator vit(info->variables.constBegin());
        for(; vit != vend; ++vit)
        {
            Q_ASSERT(*vit);
            /* This is a bit murky, the global variable will have it
             * Expression::typeCheck() function called from all its references,
             * but we also want to check it here globally, so we do
             * typechecking using a proper focus. */
            if((*vit)->type == VariableDeclaration::ExternalVariable)
                continue;

            pDebug() << "-----      Global Variable Typecheck      -----";
            Q_ASSERT((*vit)->expression());
            /* We supply ZeroOrMoreItems, meaning the variable can evaluate to anything. */
            // FIXME which is a source to bugs
            // TODO What about compressing variables?
            const Expression::Ptr
            nev((*vit)->expression()->typeCheck(context, CommonSequenceTypes::ZeroOrMoreItems));
            processTreePass(nev, GlobalVariableTypeCheck);
            pDebug() << "------------------------------";
        }
    }

    /* Do all tests specific to XSL-T. */
    if(lang == QXmlQuery::XSLT20)
    {
        /* Type check and compress named templates. */
        {
            pDebug() << "Have " << info->namedTemplates.count() << "named templates";

            QMutableHashIterator<QXmlName, Template::Ptr> it(info->namedTemplates);

            while(it.hasNext())
            {
                it.next();
                processNamedTemplate(it.key(), it.value()->body, TemplateInitial);

                it.value()->body = it.value()->body->typeCheck(context, CommonSequenceTypes::ZeroOrMoreItems);
                processNamedTemplate(it.key(), it.value()->body, TemplateTypeCheck);

                it.value()->body = it.value()->body->compress(context);
                processNamedTemplate(it.key(), it.value()->body, TemplateCompress);

                it.value()->compileParameters(context);
            }
        }

        /* Type check and compress template rules. */
        {
            QHashIterator<QXmlName, TemplateMode::Ptr> it(info->templateRules);

            /* Since a pattern can exist of AxisStep, its typeCheck() stage
             * requires a focus. In the case that we're invoked with a name but
             * no focus, this will yield a compile error, unless we declare a
             * focus manually. This only needs to be done for the pattern
             * expression, since the static type of the pattern is used as the
             * static type for the focus of the template body. */
            StaticContext::Ptr patternContext;
            if(hasExternalFocus)
                patternContext = context;
            else
                patternContext = StaticContext::Ptr(new StaticFocusContext(BuiltinTypes::node, context));

            /* For each template pattern. */
            while(it.hasNext())
            {
                it.next();
                const TemplateMode::Ptr &mode = it.value();
                const int len = mode->templatePatterns.count();
                TemplatePattern::ID currentTemplateID = -1;
                bool hasDoneItOnce = false;

                /* For each template pattern. */
                for(int i = 0; i < len; ++i)
                {
                    /* We can't use references for these two members, since we
                     * assign to them. */
                    const TemplatePattern::Ptr &pattern = mode->templatePatterns.at(i);
                    Expression::Ptr matchPattern(pattern->matchPattern());

                    processTemplateRule(pattern->templateTarget()->body,
                                        pattern, mode->name(), TemplateInitial);

                    matchPattern = matchPattern->typeCheck(patternContext, CommonSequenceTypes::ZeroOrMoreItems);
                    matchPattern = matchPattern->compress(patternContext);
                    pattern->setMatchPattern(matchPattern);

                    if(currentTemplateID == -1 && hasDoneItOnce)
                    {
                        currentTemplateID = pattern->id();
                        continue;
                    }
                    else if(currentTemplateID == pattern->id() && hasDoneItOnce)
                    {
                        hasDoneItOnce = false;
                        continue;
                    }

                    hasDoneItOnce = true;
                    currentTemplateID = pattern->id();
                    Expression::Ptr body(pattern->templateTarget()->body);

                    /* Patterns for a new template has started, we must
                     * deal with the body & parameters. */
                    {
                        /* TODO type is wrong, it has to be the union of all
                         * patterns. */
                        const StaticContext::Ptr focusContext(new StaticFocusContext(matchPattern->staticType()->itemType(),
                                                                                     context));
                        body = body->typeCheck(focusContext, CommonSequenceTypes::ZeroOrMoreItems);

                        pattern->templateTarget()->compileParameters(focusContext);
                    }

                    processTemplateRule(body, pattern, mode->name(), TemplateTypeCheck);

                    body = body->compress(context);

                    pattern->templateTarget()->body = body;
                    processTemplateRule(body, pattern, mode->name(), TemplateCompress);
                }

                mode->finalize();
            }
        }

        /* Add templates in mode #all to all other modes.
         *
         * We do this after the templates has been typechecked and compressed,
         * since otherwise it will be done N times for the built-in templates,
         * where N is the count of different templates, instead of once. */
        {
            const QXmlName nameModeAll(QXmlName(StandardNamespaces::InternalXSLT,
                                                StandardLocalNames::all));
            const TemplateMode::Ptr &modeAll = info->templateRules[nameModeAll];

            Q_ASSERT_X(modeAll, Q_FUNC_INFO,
                       "We should at least have the builtin templates.");
            QHashIterator<QXmlName, TemplateMode::Ptr> it(info->templateRules);

            while(it.hasNext())
            {
                it.next();

                /* Don't add mode #all to mode #all. */
                if(it.key()  == nameModeAll)
                    continue;

                it.value()->addMode(modeAll);
            }
        }
    }

    /* Type check and compress the query body. */
    {
        pDebug() << "----- Initial AST build. -----";
        processTreePass(result, QueryBodyInitial);
        pDebug() << "------------------------------";

        pDebug() << "-----     Type Check     -----";
        registerLastPath(result);
        result->rewrite(result, result->typeCheck(context, requiredType), context);
        processTreePass(result, QueryBodyTypeCheck);
        pDebug() << "------------------------------";

        pDebug() << "-----      Compress      -----";
        result->rewrite(result, result->compress(context), context);
        processTreePass(result, QueryBodyCompression);
        pDebug() << "------------------------------";
    }

    return result;
}
示例#17
0
bool FixupCommand::handleCommand(const QString &command, const QCommandLineParser &cmd)
{
	QList<QuickMod> mods = readMultipleMods(cmd);

	out << "You will now be prompted for all missing info for QuickMod files in the current directory. Just leave a blank line to not set a value." << endl << flush;

	QuickModWriter writer(this);

	QListIterator<QuickMod> it(mods);
	while (it.hasNext())
	{
		QuickMod mod = it.next();

		out << "Fixing " << mod.name << endl << flush;

		if (cmd.isSet("browser") && !mod.urls["website"].isEmpty() && false)
		{
			QDesktopServices::openUrl(mod.urls["website"].first());
		}

		if (mod.description.isEmpty())
		{
			mod.description = getCommandLineInput("Description:");
		}
		if (mod.urls["website"].isEmpty())
		{
			mod.urls["website"] = QStringList() << getCommandLineInput("Website URL:");
		}
		if (mod.urls["icon"].isEmpty())
		{
			mod.urls["icon"] = QStringList() << getCommandLineInput("Icon URL:");
		}
		if (mod.urls["logo"].isEmpty())
		{
			mod.urls["logo"] = QStringList() << getCommandLineInput("Logo URL:");
		}
		if (mod.modId.isEmpty())
		{
			mod.modId = getCommandLineInput("Mod ID:");
		}
		if (mod.nemName.isEmpty())
		{
			mod.nemName = getCommandLineInput("NEM name:");
		}
		if (mod.tags.isEmpty())
		{
			mod.tags = getCommandLineInput("Tags (tag1,tag2...tagN):").split(',', QString::SkipEmptyParts);
		}
		if (mod.categories.isEmpty())
		{
			mod.categories = getCommandLineInput("Categories (cat1,cat2...catN):").split(',', QString::SkipEmptyParts);
		}
		if (mod.references.isEmpty())
		{
			const QStringList references = getCommandLineInput("References (name1[:url1],name2[:url2]...nameN[:urlN]):").split(',', QString::SkipEmptyParts);
			foreach (const QString &ref, references)
			{
				const QStringList r = ref.split(':', QString::SkipEmptyParts);
				const QString name = r.at(0);
				QString url;
				if (r.size() == 0)
				{
					continue;
				}
				else if (r.size() == 1)
				{
					url = "http://localhost/quickmod/" + name + ".json";
				}
				else
				{
					url = r.at(1);
				}
				mod.references.insert(name, url);
			}
		}
		if (mod.authors.isEmpty())
		{
			const QStringList authors = getCommandLineInput("Authors (title1:name1a,name1b;title2:name2a,name2b):").split(';', QString::SkipEmptyParts);
			foreach (const QString &authorsRole, authors)
			{
				const QStringList a = authorsRole.split(':');
				if (a.size() < 2)
				{
					continue;
				}
				mod.authors.insert(a.at(0), QString(authorsRole).remove(a.at(0) + ':').split(',', QString::SkipEmptyParts));
			}
		}
		QMutableListIterator<QuickModVersion> vit(mod.versions);
		while (vit.hasNext())
		{
			QuickModVersion version = vit.next();

			out << " Version " << version.name << endl << flush;

			if (version.sha1.isEmpty() && !cmd.isSet("no-checksums"))
			{
				version.sha1 = getCommandLineInput(" Checksum:");
			}

			vit.setValue(version);
		}

		QString error;
		if (!writer.write(mod, QDir::current(), &error))
		{
			out << "There was an error trying to write the QuickMod file:" << endl << error << endl;
			return false;
		}
	}

	return true;
}
示例#18
0
void
KContainer::BuildKLists(ParticleLayout_t& lattice, bool useSphere)
{
  TinyVector<int,DIM+1> TempActualMax;
  TinyVector<int,DIM> kvec;
  TinyVector<RealType,DIM> kvec_cart;
  RealType modk2;
  vector<TinyVector<int,DIM> > kpts_tmp;
  VContainer_t kpts_cart_tmp;
  SContainer_t ksq_tmp;
  // reserve the space for memory efficiency
#if OHMMS_DIM ==3
  int numGuess=(2*mmax[0]+1)*(2*mmax[1]+1)*(2*mmax[2]+1);
  if(useSphere)
  {
    //Loop over guesses for valid k-points.
    for(int i=-mmax[0]; i<=mmax[0]; i++)
    {
      kvec[0] = i;
      for(int j=-mmax[1]; j<=mmax[1]; j++)
      {
        kvec[1] = j;
        for(int k=-mmax[2]; k<=mmax[2]; k++)
        {
          kvec[2] = k;
          //Do not include k=0 in evaluations.
          if(i==0 && j==0 && k==0)
            continue;
          //Convert kvec to Cartesian
          kvec_cart = lattice.k_cart(kvec);
          //Find modk
          modk2 = dot(kvec_cart,kvec_cart);
          if(modk2>kcut2)
            continue; //Inside cutoff?
          //This k-point should be added to the list
          kpts_tmp.push_back(kvec);
          kpts_cart_tmp.push_back(kvec_cart);
          ksq_tmp.push_back(modk2);
          //Update record of the allowed maximum translation.
          for(int idim=0; idim<3; idim++)
            if(abs(kvec[idim]) > TempActualMax[idim])
              TempActualMax[idim] = abs(kvec[idim]);
        }
      }
    }
  }
  else
  {
    // Loop over all k-points in the parallelpiped and add them to kcontainer
    // note layout is for interfacing with fft, so for each dimension, the
    // positive indexes come first then the negative indexes backwards
    // e.g.    0, 1, .... mmax, -mmax+1, -mmax+2, ... -1
    const int idimsize = mmax[0]*2;
    const int jdimsize = mmax[1]*2;
    const int kdimsize = mmax[2]*2;
    for (int i = 0; i < idimsize; i++)
    {
      kvec[0] = i;
      if (kvec[0] > mmax[0])
        kvec[0] -= idimsize;
      for (int j = 0; j < jdimsize; j++)
      {
        kvec[1] = j;
        if (kvec[1] > mmax[1])
          kvec[1] -= jdimsize;
        for (int k = 0; k < kdimsize; k++)
        {
          kvec[2] = k;
          if (kvec[2] > mmax[2])
            kvec[2] -= kdimsize;
          // get cartesian location and modk2
          kvec_cart = lattice.k_cart(kvec);
          modk2 = dot(kvec_cart, kvec_cart);
          // add k-point to lists
          kpts_tmp.push_back(kvec);
          kpts_cart_tmp.push_back(kvec_cart);
          ksq_tmp.push_back(modk2);
        }
      }
    }
    // set allowed maximum translation
    TempActualMax[0] = mmax[0];
    TempActualMax[1] = mmax[1];
    TempActualMax[2] = mmax[2];
  }
#elif OHMMS_DIM == 2
  int numGuess=(2*mmax[0]+1)*(2*mmax[1]+1);
  if(useSphere)
  {
    //Loop over guesses for valid k-points.
    for(int i=-mmax[0]; i<=mmax[0]; i++)
    {
      kvec[0] = i;
      for(int j=-mmax[1]; j<=mmax[1]; j++)
      {
        kvec[1] = j;
        //Do not include k=0 in evaluations.
        if(i==0 && j==0)
          continue;
        //Convert kvec to Cartesian
        kvec_cart = lattice.k_cart(kvec);
        //Find modk
        modk2 = dot(kvec_cart,kvec_cart);
        if(modk2>kcut2)
          continue; //Inside cutoff?
        //This k-point should be added to the list
        kpts_tmp.push_back(kvec);
        kpts_cart_tmp.push_back(kvec_cart);
        ksq_tmp.push_back(modk2);
        //Update record of the allowed maximum translation.
        for(int idim=0; idim<3; idim++)
          if(abs(kvec[idim]) > TempActualMax[idim])
            TempActualMax[idim] = abs(kvec[idim]);
      }
    }
  }
  else
  {
    // Loop over all k-points in the parallelpiped and add them to kcontainer
    // note layout is for interfacing with fft, so for each dimension, the
    // positive indexes come first then the negative indexes backwards
    // e.g.    0, 1, .... mmax, -mmax+1, -mmax+2, ... -1
    const int idimsize = mmax[0]*2;
    const int jdimsize = mmax[1]*2;
    for (int i = 0; i < idimsize; i++)
    {
      kvec[0] = i;
      if (kvec[0] > mmax[0])
        kvec[0] -= idimsize;
      for (int j = 0; j < jdimsize; j++)
      {
        kvec[1] = j;
        if (kvec[1] > mmax[1])
          kvec[1] -= jdimsize;
        // get cartesian location and modk2
        kvec_cart = lattice.k_cart(kvec);
        modk2 = dot(kvec_cart, kvec_cart);
        // add k-point to lists
        kpts_tmp.push_back(kvec);
        kpts_cart_tmp.push_back(kvec_cart);
        ksq_tmp.push_back(modk2);
      }
    }
    // set allowed maximum translation
    TempActualMax[0] = mmax[0];
    TempActualMax[1] = mmax[1];
  }
//#elif OHMMS_DIM == 1
//add one-dimension
#else
#error "OHMMS_DIM != 2 || OHMMS_DIM != 3"
#endif
  //Update a record of the number of k vectors
  numk = kpts_tmp.size();
  std::map<int,std::vector<int>*>  kpts_sorted;
//create the map: use simple integer with resolution of 0.001 in ksq
  for(int ik=0; ik<numk; ik++)
  {
    int k_ind=static_cast<int>(ksq_tmp[ik]*1000);
    std::map<int,std::vector<int>*>::iterator it(kpts_sorted.find(k_ind));
    if(it == kpts_sorted.end())
    {
      std::vector<int>* newSet=new std::vector<int>;
      kpts_sorted[k_ind]=newSet;
      newSet->push_back(ik);
    }
    else
    {
      (*it).second->push_back(ik);
    }
  }
  std::map<int,std::vector<int>*>::iterator it(kpts_sorted.begin());
  kpts.resize(numk);
  kpts_cart.resize(numk);
  ksq.resize(numk);
  kshell.resize(kpts_sorted.size()+1,0);
  int ok=0, ish=0;
  while(it != kpts_sorted.end())
  {
    std::vector<int>::iterator vit((*it).second->begin());
    while(vit != (*it).second->end())
    {
      int ik=(*vit);
      kpts[ok]=kpts_tmp[ik];
      kpts_cart[ok]=kpts_cart_tmp[ik];
      ksq[ok]=ksq_tmp[ik];
      ++vit;
      ++ok;
    }
    kshell[ish+1]=kshell[ish]+(*it).second->size();
    ++it;
    ++ish;
  }
  it=kpts_sorted.begin();
  std::map<int,std::vector<int>*>::iterator e_it(kpts_sorted.end());
  while(it != e_it)
  {
    delete it->second;
    it++;
  }
  //Finished searching k-points. Copy list of maximum translations.
  mmax[DIM] = 0;
  for(int idim=0; idim<DIM; idim++)
  {
    mmax[idim] = TempActualMax[idim];
    mmax[DIM]=std::max(mmax[idim],mmax[DIM]);
    //if(mmax[idim] > mmax[DIM]) mmax[DIM] = mmax[idim];
  }
  //Now fill the array that returns the index of -k when given the index of k.
  minusk.resize(numk);
  // Create a map from the hash value for each k vector to the index
  std::map<int, int> hashToIndex;
  for (int ki=0; ki<numk; ki++)
  {
    hashToIndex[GetHashOfVec(kpts[ki], numk)] = ki;
  }
  // Use the map to find the index of -k from the index of k
  for(int ki=0; ki<numk; ki++)
  {
    minusk[ki] = hashToIndex[ GetHashOfVec(-1 * kpts[ki], numk) ];
  }
}
示例#19
0
QMimeSource* UMLClipboard::copy(bool fromView/*=false*/) {
    //Clear previous copied data
    m_AssociationList.clear();
    m_ItemList.clear();
    m_ObjectList.clear();
    m_ViewList.clear();

    UMLDrag *data = 0;
    QPixmap* png = 0;

    UMLListView * listView = UMLApp::app()->getListView();
    UMLListViewItemList selectedItems;
    selectedItems.setAutoDelete(false);

    if(fromView) {
        m_type = clip4;
        UMLView *view = UMLApp::app()->getCurrentView();
        view->checkSelections();
        if(!view->getSelectedWidgets(m_WidgetList)) {
            return 0;
        }
        //if there is no selected widget then there is no copy action
        if(!m_WidgetList.count()) {
            return 0;
        }
        m_AssociationList = view->getSelectedAssocs();
        view->copyAsImage(png);

    } else { //if the copy action is being performed from the ListView
        if(!listView->getSelectedItems(selectedItems)) {
            return 0;
        }
        //Set What type of copy operation are we performing and
        //also fill m_ViewList with all the selected Diagrams
        setCopyType(selectedItems);

        //if we are copying a diagram or part of a diagram, select the items
        //on the ListView that correspond to a UseCase, Actor or Concept
        //in the Diagram
        if(m_type == clip2) {
            //Fill the member lists with all the object and stuff to be copied
            //to the clipboard
            selectedItems.clear();
            //For each selected view select all the Actors, USe Cases and Concepts
            //widgets in the ListView
            for (UMLViewListIt vit(m_ViewList); vit.current(); ++vit) {
                UMLObjectList objects = vit.current()->getUMLObjects();
                for (UMLObjectListIt oit(objects); oit.current(); ++oit) {
                    UMLObject *o = oit.current();
                    UMLListViewItem *item = listView->findUMLObject(o);
                    if(item) {
                        listView->setSelected(item, true);
                    }
                }
            }
            if(!listView->getSelectedItems(selectedItems)) {
                return 0;
            }
        }
        if(!fillSelectionLists(selectedItems)) {
            return 0;
        }
    }
    int i =0;
    switch(m_type) {
    case clip1:
        data = new UMLDrag(m_ObjectList);
        break;
    case clip2:
        data = new UMLDrag(m_ObjectList, m_ItemList, m_ViewList);
        break;
    case clip3:
        data = new UMLDrag(m_ItemList);
        break;
    case clip4:
        if(png) {
            UMLView *view = UMLApp::app()->getCurrentView();
            data = new UMLDrag(m_ObjectList, m_WidgetList,
                               m_AssociationList, *png, view->getType());
        } else {
            return 0;
        }
        break;
    case clip5:
        data = new UMLDrag(m_ObjectList, i);
        // The int i is used to differentiate
        // which UMLDrag constructor gets called.
        break;
    }

    return (QMimeSource*)data;
}
示例#20
0
Expression::Ptr ExpressionFactory::createExpression(const QString &expr,
                                                    const StaticContext::Ptr &context,
                                                    const LanguageAccent lang,
                                                    const SequenceType::Ptr &requiredType,
                                                    const QUrl &queryURI)
{
    pDebug() << Q_FUNC_INFO << queryURI;
    Q_ASSERT(context);
    Q_ASSERT(requiredType);
    Q_ASSERT(queryURI.isValid());

    OptimizationPasses::Coordinator::init();

    ParserContext::Ptr info(new ParserContext(context, lang,
                                              Tokenizer::Ptr(new XQueryTokenizer(expr, queryURI))));

    const int bisonRetval = XPathparse(info.data());

    Q_ASSERT_X(bisonRetval == 0, Q_FUNC_INFO,
               "We shouldn't be able to get an error, because we throw exceptions.");
    Q_UNUSED(bisonRetval); /* Needed when not compiled in debug mode, since bisonRetval won't
                            * be used in the Q_ASSERT_X above. */

    Expression::Ptr result(info->queryBody);

    if(!result)
    {
        context->error(QtXmlPatterns::tr("A library module cannot be evaluated "
                                         "directly. It must be imported from a "
                                         "main module."),
                       ReportContext::XPST0003,
                       QSourceLocation(queryURI, 1, 1));
    }

    /* Here, we type check user declared functions and global variables. This means
     * that variables and functions that are not used are type checked(which they otherwise
     * wouldn't have been), and those which are used, are type-checked twice, unfortunately. */

    const UserFunction::List::const_iterator end(info->userFunctions.constEnd());
    UserFunction::List::const_iterator it(info->userFunctions.constBegin());
    for(; it != end; ++it)
    {
        pDebug() << "-----      User Function Typecheck      -----";
        registerLastPath((*it)->body());

        /* We will most likely call body()->typeCheck() again, once for each callsite. That is, it will
         * be called from UserFunctionCallsite::typeCheck(), which will be called indirectly when
         * we check the query body. */
        const Expression::Ptr typeCheck((*it)->body()->typeCheck(context, (*it)->signature()->returnType()));
        /* We don't have to call (*it)->setBody(typeCheck) here since it's only used directly below. */
        processTreePass(typeCheck, UserFunctionTypeCheck);
        pDebug() << "------------------------------";

        pDebug() << "-----      User Function Compress      -----";
        const Expression::Ptr comp(typeCheck->compress(context));
        (*it)->setBody(comp);
        processTreePass(comp, UserFunctionCompression);
        pDebug() << "------------------------------";
    }

    const VariableDeclaration::Stack::const_iterator vend(info->variables.constEnd());
    VariableDeclaration::Stack::const_iterator vit(info->variables.constBegin());
    for(; vit != vend; ++vit)
    {
        Q_ASSERT(*vit);
        /* If it's already used, it will be typeChecked later on. */
        if((*vit)->isUsed() || (*vit)->type == VariableDeclaration::ExternalVariable)
            continue;

        pDebug() << "-----      Global Variable Typecheck      -----";
        Q_ASSERT((*vit)->expression());
        /* We supply ZeroOrMoreItems, meaning the variable can evaluate to anything. */
        // FIXME which is a source to bugs
        // TODO What about compressing variables?
        const Expression::Ptr
        nev((*vit)->expression()->typeCheck(context, CommonSequenceTypes::ZeroOrMoreItems));
        processTreePass(nev, GlobalVariableTypeCheck);
        pDebug() << "------------------------------";
    }

    pDebug() << "----- Initial AST build. -----";
    processTreePass(result, QueryBodyInitial);
    pDebug() << "------------------------------";

    pDebug() << "-----     Type Check     -----";
    registerLastPath(result);
    result->rewrite(result, result->typeCheck(context, requiredType), context);
    processTreePass(result, QueryBodyTypeCheck);
    pDebug() << "------------------------------";

    pDebug() << "-----      Compress      -----";
    result->rewrite(result, result->compress(context), context);
    processTreePass(result, QueryBodyCompression);
    pDebug() << "------------------------------";

    return result;
}