void SpringEmbedderFRExact::call(GraphAttributes &AG) { const Graph &G = AG.constGraph(); if(G.empty()) return; // all edges straight-line AG.clearAllBends(); ArrayGraph component(AG); component.m_useNodeWeight = m_useNodeWeight; EdgeArray<edge> auxCopy(G); Array<DPoint> boundingBox(component.numberOfCCs()); int i; for(i = 0; i < component.numberOfCCs(); ++i) { component.initCC(i); if (component.numberOfNodes() >= 2) { initialize(component); #ifdef OGDF_SSE3_EXTENSIONS if(System::cpuSupports(cpufSSE3)) mainStep_sse3(component); else #endif mainStep(component); } double minX, maxX, minY, maxY; minX = maxX = component.m_x[0]; minY = maxY = component.m_y[0]; for(int vCopy = 0; vCopy < component.numberOfNodes(); ++vCopy) { node v = component.original(vCopy); AG.x(v) = component.m_x[vCopy]; AG.y(v) = component.m_y[vCopy]; if(AG.x(v)-AG.width (v)/2 < minX) minX = AG.x(v)-AG.width(v) /2; if(AG.x(v)+AG.width (v)/2 > maxX) maxX = AG.x(v)+AG.width(v) /2; if(AG.y(v)-AG.height(v)/2 < minY) minY = AG.y(v)-AG.height(v)/2; if(AG.y(v)+AG.height(v)/2 > maxY) maxY = AG.y(v)+AG.height(v)/2; } minX -= m_minDistCC; minY -= m_minDistCC; for(int vCopy = 0; vCopy < component.numberOfNodes(); ++vCopy) { node v = component.original(vCopy); AG.x(v) -= minX; AG.y(v) -= minY; } boundingBox[i] = DPoint(maxX - minX, maxY - minY); } Array<DPoint> offset(component.numberOfCCs()); TileToRowsCCPacker packer; packer.call(boundingBox,offset,m_pageRatio); // The arrangement is given by offset to the origin of the coordinate // system. We still have to shift each node and edge by the offset // of its connected component. for(i = 0; i < component.numberOfCCs(); ++i) { const SList<node> &nodes = component.nodesInCC(i); const double dx = offset[i].m_x; const double dy = offset[i].m_y; // iterate over all nodes in ith CC for(node v : nodes) { AG.x(v) += dx; AG.y(v) += dy; } } }
void load_construction(JsonObject &jo) { construction *con = new construction; JsonArray temp; con->description = _(jo.get_string("description").c_str()); con->difficulty = jo.get_int("difficulty"); con->time = jo.get_int("time"); temp = jo.get_array("tools"); while (temp.has_more()) { std::vector<component> tool_choices; JsonArray ja = temp.next_array(); while (ja.has_more()) { std::string name = ja.next_string(); tool_choices.push_back(component(name, 1)); } con->tools.push_back(tool_choices); } temp = jo.get_array("components"); while (temp.has_more()) { std::vector<component> comp_choices; JsonArray ja = temp.next_array(); while (ja.has_more()) { JsonArray comp = ja.next_array(); std::string name = comp.get_string(0); int quant = comp.get_int(1); comp_choices.push_back(component(name, quant)); } con->components.push_back(comp_choices); } con->pre_terrain = jo.get_string("pre_terrain", ""); if (con->pre_terrain.size() > 1 && con->pre_terrain[0] == 'f' && con->pre_terrain[1] == '_') { con->pre_is_furniture = true; } else { con->pre_is_furniture = false; } con->post_terrain = jo.get_string("post_terrain", ""); if (con->post_terrain.size() > 1 && con->post_terrain[0] == 'f' && con->post_terrain[1] == '_') { con->post_is_furniture = true; } else { con->post_is_furniture = false; } con->pre_flags = jo.get_tags("pre_flags"); std::string prefunc = jo.get_string("pre_special", ""); if (prefunc == "check_empty") { con->pre_special = &construct::check_empty; } else if (prefunc == "check_support") { con->pre_special = &construct::check_support; } else { // should probably print warning if not "" con->pre_special = &construct::check_nothing; } std::string postfunc = jo.get_string("post_special", ""); if (postfunc == "done_tree") { con->post_special = &construct::done_tree; } else if (postfunc == "done_trunk_log") { con->post_special = &construct::done_trunk_log; } else if (postfunc == "done_trunk_plank") { con->post_special = &construct::done_trunk_plank; } else if (postfunc == "done_vehicle") { con->post_special = &construct::done_vehicle; } else if (postfunc == "done_deconstruct") { con->post_special = &construct::done_deconstruct; } else { // ditto, should probably warn here con->post_special = &construct::done_nothing; } con->id = constructions.size(); constructions.push_back(con); constructions_by_desc[con->description].push_back(con); }
// add or remove a timestep void DrawMolecule::addremove_ts() { int numcomp = components(); for (int i=0; i<numcomp; i++) component(i)->change_traj(); }
void FdOutput::log(const char* channelName, LogLevel level, const char* msg, time_t time) { char timeStamp[32]; tm currentTime; currentTime = *localtime(&time); const char *color = NULL; if ( _colorize ) { sprintf(timeStamp, "%s%02i:%02i:%02i%s ", kGreenColor, currentTime.tm_hour, currentTime.tm_min, currentTime.tm_sec, kNormalColor); switch(level) { case LL_CRITICAL: case LL_ERROR: color = kRedColor; break; case LL_WARNING: color = kYellowColor; break; case LL_NOTICE: case LL_INFO: case LL_DEBUG: default: break; } } else { sprintf(timeStamp, "%02i:%02i:%02i ", currentTime.tm_hour, currentTime.tm_min, currentTime.tm_sec); } std::ostringstream ss; ss << timeStamp; ss << '[' << channelName; if ( likely(_logComponent) ) ss << "/" << component(); ss << "] "; if ( unlikely(_logContext) ) ss << "(" << fileName() << ':' << lineNum() << ") "; #ifndef _WIN32 // THREAD ID /* char tid[16] = ""; snprintf(tid,15,"%lu",pthread_self()); ss << "[tid:" << tid << "] "; */ #endif if( color ) ss << color; ss << msg; if ( color ) ss << kNormalColor; ss << std::endl; std::string out = ss.str(); write(_fdOut, out.c_str(), out.length()); }
/** * Calculates Shortest Path Related metrics of the graph. The * function runs a BFS from each node to find out the shortest * distances to other nodes in the graph. The maximum of this distance * is called the eccentricity of that node. The maximum eccentricity * in the graph is called diameter and the minimum eccentricity is * called the radius of the graph. Central points are those nodes * having eccentricity equals to radius. */ void mitk::ConnectomicsStatisticsCalculator::CalculateShortestPathMetrics() { //for all vertices: VertexIteratorType vi, vi_end; //store the eccentricities in a vector. m_VectorOfEccentrities.resize( m_NumberOfVertices ); m_VectorOfEccentrities90.resize( m_NumberOfVertices ); m_VectorOfAveragePathLengths.resize( m_NumberOfVertices ); //assign diameter and radius while iterating over the ecccencirities. m_Diameter = 0; m_Diameter90 = 0; m_Radius = std::numeric_limits<unsigned int>::max(); m_Radius90 = std::numeric_limits<unsigned int>::max(); m_AverageEccentricity = 0.0; m_AverageEccentricity90 = 0.0; m_AveragePathLength = 0.0; //The size of the giant connected component so far. unsigned int giant_component_size = 0; VertexDescriptorType radius_src; //Loop over the vertices for( boost::tie(vi, vi_end) = boost::vertices( *(m_Network->GetBoostGraph()) ); vi!=vi_end; ++vi) { //We are going to start a BFS, initialize the neccessary //structures for that. Store the distances of nodes from the //source in distance vector. The maximum distance is stored in //max. The BFS will start from the node that vi is pointing, that //is the src is *vi. We also init the distance of the src node to //itself to 0. size gives the number of nodes discovered during //this BFS. std::vector<int> distances( m_NumberOfVertices ); int max_distance = 0; VertexDescriptorType src = *vi; distances[src] = 0; unsigned int size = 0; breadth_first_search(*(m_Network->GetBoostGraph()), src, visitor(all_pairs_shortest_recorder<NetworkType> (&distances[0], max_distance, size))); // vertex vi has eccentricity equal to max_distance m_VectorOfEccentrities[src] = max_distance; //check whether there is any change in the diameter or the radius. //note that the diameter we are calculating here is also the //diameter of the giant connected component! if(m_VectorOfEccentrities[src] > m_Diameter) { m_Diameter = m_VectorOfEccentrities[src]; } //The radius should be calculated on the largest connected //component, otherwise it is very likely that radius will be 1. //We change the value of the radius only if this is the giant //connected component so far. After all the eccentricities are //found we should loop over this connected component and find the //minimum eccentricity which is the radius. So we keep the src //node, so that we can find the connected component later on. if(size > giant_component_size) { giant_component_size = size; radius_src = src; } //Calculate in how many hops we can reach 90 percent of the //nodes. We store the number of hops we can reach in h hops in the //bucket vector. That is bucket[h] gives the number of nodes //reachable in exactly h hops. sum of bucket[i<h] gives the number //of nodes that are reachable in less than h hops. We also //calculate sum of the distances from this node to every single //other node in the graph. int reachable90 = std::ceil((double)size * 0.9); std::vector <int> bucket (max_distance+1); int counter = 0; for(unsigned int i=0; i<distances.size(); i++) { if(distances[i]>0) { bucket[distances[i]]++; m_VectorOfAveragePathLengths[src] += distances[i]; counter ++; } } if(counter > 0) { m_VectorOfAveragePathLengths[src] = m_VectorOfAveragePathLengths[src] / counter; } int eccentricity90 = 0; while(reachable90 > 0) { eccentricity90 ++; reachable90 = reachable90 - bucket[eccentricity90]; } // vertex vi has eccentricity90 equal to eccentricity90 m_VectorOfEccentrities90[src] = eccentricity90; if(m_VectorOfEccentrities90[src] > m_Diameter90) { m_Diameter90 = m_VectorOfEccentrities90[src]; } } //We are going to calculate the radius now. We stored the src node //that when we start a BFS gives the giant connected component, and //we have the eccentricities calculated. Iterate over the nodes of //this giant component and find the minimum eccentricity. std::vector<int> component( m_NumberOfVertices ); boost::connected_components( *(m_Network->GetBoostGraph()), &component[0]); for (unsigned int i=0; i<component.size(); i++) { //If we are in the same component and the radius is not the //minimum so far store the eccentricity as the radius. if( component[i] == component[radius_src]) { if(m_Radius > m_VectorOfEccentrities[i]) { m_Radius = m_VectorOfEccentrities[i]; } if(m_Radius90 > m_VectorOfEccentrities90[i]) { m_Radius90 = m_VectorOfEccentrities90[i]; } } } m_AverageEccentricity = std::accumulate(m_VectorOfEccentrities.begin(), m_VectorOfEccentrities.end(), 0.0) / m_NumberOfVertices; m_AverageEccentricity90 = std::accumulate(m_VectorOfEccentrities90.begin(), m_VectorOfEccentrities90.end(), 0.0) / m_NumberOfVertices; m_AveragePathLength = std::accumulate(m_VectorOfAveragePathLengths.begin(), m_VectorOfAveragePathLengths.end(), 0.0) / m_NumberOfVertices; //calculate Number of Central Points, nodes having eccentricity = radius. m_NumberOfCentralPoints = 0; for (boost::tie(vi, vi_end) = boost::vertices( *(m_Network->GetBoostGraph()) ); vi != vi_end; ++vi) { if(m_VectorOfEccentrities[*vi] == m_Radius) { m_NumberOfCentralPoints++; } } m_RatioOfCentralPoints = (double)m_NumberOfCentralPoints / m_NumberOfVertices; }
QDeclarativeItem* QmlWindowRenderer::createQmlItem( const QUrl& url ) { QDeclarativeComponent component( windowContext_->engine(), url ); QObject* qmlObject = component.create( windowContext_.get( )); return qobject_cast<QDeclarativeItem*>( qmlObject ); }
bool parseInput(std::string filename) { bool done = false; std::ifstream file(filename); std::string line; if(!file) { return false; } // done once line read equals 0 0 while(!done) { std::vector<Engineer> engineers; std::vector<Component> components; // read first line of file std::getline(file, line); std::vector<std::string> amounts = split_str(line, ' '); int nComponents = stoi(amounts.at(0)); int nEngineers = stoi(amounts.at(1)); int iterator = 0; // determine if end of file if(nComponents == 0 && nEngineers == 0) { done = true; } else { // populate components for(; iterator < nComponents; iterator++) { std::getline(file, line); // number of components in class std::vector<std::string> compKinds = split_str(line, ' '); int nComps = stoi(compKinds.at(0)); int nCompReviews = stoi(compKinds.at(1)); int compIter = 0; // create component and store in component array for(; compIter < nComps; compIter++) { Component component(nCompReviews); components.push_back(component); } } iterator = 0; for(; iterator < nEngineers; iterator++) { std::getline(file, line); // number of engineers in class std::vector<std::string> engKinds = split_str(line, ' '); int nEngs = stoi(engKinds.at(0)); int nEngReviews = stoi(engKinds.at(1)); int engIter = 0; // create engineer and store in component array for(; engIter < nEngs; engIter++) { Engineer engineer(nEngReviews); engineers.push_back(engineer); } } // log data std::cout << parseData(components, engineers) << std::endl; } } return true; }
void tst_QQuickAccessible::quickAttachedProperties() { { QQmlEngine engine; QQmlComponent component(&engine); component.setData("import QtQuick 2.0\nItem {\n" "}", QUrl()); QObject *object = component.create(); QVERIFY(object != 0); QObject *attachedObject = QQuickAccessibleAttached::attachedProperties(object); QCOMPARE(attachedObject, static_cast<QObject*>(0)); delete object; } // Attached property { QObject parent; QQuickAccessibleAttached *attachedObj = new QQuickAccessibleAttached(&parent); attachedObj->name(); QVariant pp = attachedObj->property("name"); QQmlEngine engine; QQmlComponent component(&engine); component.setData("import QtQuick 2.0\nItem {\n" "Accessible.role: Accessible.Button\n" "}", QUrl()); QObject *object = component.create(); QVERIFY(object != 0); QObject *attachedObject = QQuickAccessibleAttached::attachedProperties(object); QVERIFY(attachedObject); if (attachedObject) { QVariant p = attachedObject->property("role"); QCOMPARE(p.isNull(), false); QCOMPARE(p.toInt(), int(QAccessible::PushButton)); p = attachedObject->property("name"); QCOMPARE(p.isNull(), true); p = attachedObject->property("description"); QCOMPARE(p.isNull(), true); } delete object; } // Attached property { QQmlEngine engine; QQmlComponent component(&engine); component.setData("import QtQuick 2.0\nItem {\n" "Accessible.role: Accessible.Button\n" "Accessible.name: \"Donald\"\n" "Accessible.description: \"Duck\"\n" "}", QUrl()); QObject *object = component.create(); QVERIFY(object != 0); QObject *attachedObject = QQuickAccessibleAttached::attachedProperties(object); QVERIFY(attachedObject); if (attachedObject) { QVariant p = attachedObject->property("role"); QCOMPARE(p.isNull(), false); QCOMPARE(p.toInt(), int(QAccessible::PushButton)); p = attachedObject->property("name"); QCOMPARE(p.isNull(), false); QCOMPARE(p.toString(), QLatin1String("Donald")); p = attachedObject->property("description"); QCOMPARE(p.isNull(), false); QCOMPARE(p.toString(), QLatin1String("Duck")); } delete object; } QTestAccessibility::clearEvents(); }
void PluginCreator::runClicked() { log->clear(); QQmlEngine* qml = Ms::MScore::qml(); connect(qml, SIGNAL(warnings(const QList<QQmlError>&)), SLOT(qmlWarnings(const QList<QQmlError>&))); item = 0; QQmlComponent component(qml); component.setData(textEdit->toPlainText().toUtf8(), QUrl()); QObject* obj = component.create(); if (obj == 0) { msg("creating component failed\n"); foreach(QQmlError e, component.errors()) msg(QString(" line %1: %2\n").arg(e.line()).arg(e.description())); stop->setEnabled(false); return; } qInstallMsgHandler(qmlMsgHandler); stop->setEnabled(true); run->setEnabled(false); item = qobject_cast<QmlPlugin*>(obj); if (item->pluginType() == "dock" || item->pluginType() == "dialog") { view = new QQuickView(qml, 0); view->setTitle(item->menuPath().mid(item->menuPath().lastIndexOf(".") + 1)); view->setColor(QApplication::palette().color(QPalette::Window)); view->setResizeMode(QQuickView::SizeRootObjectToView); view->setWidth(item->width()); view->setHeight(item->height()); item->setParentItem(view->contentItem()); if (item->pluginType() == "dock") { dock = new QDockWidget("Plugin", 0); dock->setAttribute(Qt::WA_DeleteOnClose); dock->setWidget(QWidget::createWindowContainer(view)); dock->widget()->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding)); Qt::DockWidgetArea area = Qt::RightDockWidgetArea; if (item->dockArea() == "left") area = Qt::LeftDockWidgetArea; else if (item->dockArea() == "top") area = Qt::TopDockWidgetArea; else if (item->dockArea() == "bottom") area = Qt::BottomDockWidgetArea; addDockWidget(area, dock); connect(dock, SIGNAL(destroyed()), SLOT(closePlugin())); dock->widget()->setAttribute(Qt::WA_DeleteOnClose); } view->show(); view->raise(); connect(view, SIGNAL(destroyed()), SLOT(closePlugin())); } connect(qml, SIGNAL(quit()), SLOT(closePlugin())); if (mscore->currentScore() && item->pluginType() != "dock") mscore->currentScore()->startCmd(); item->runPlugin(); if (mscore->currentScore() && item->pluginType() != "dock") mscore->currentScore()->endCmd(); mscore->endCmd(); }
void FKServerComponent::guestConnection(FKConnector* connector){ connector->moveToThread(component()->thread()); if(!FK_THREAD_CALL_ARG(clientConnection,FKConnector*,connector)){ emit messageRequested(QString(tr("Unable add server guest connection"))); } }
void FKClientComponent::realmConnection(FKConnector* connector){ connector->moveToThread(component()->thread()); if(!FK_THREAD_CALL_ARG(realmConnection,FKConnector*,connector)){ emit messageRequested(QString(tr("Unable set realm connection for client"))); } }
void WebApplicationWindow::createAndSetup() { if (mTrustScope == TrustScopeSystem) { mUserScripts.append(QUrl("qrc:///qml/webos-api.js")); createDefaultExtensions(); } if (mWindowType == "dashboard") mLoadingAnimationDisabled = true; if (mHeadless) { qDebug() << __PRETTY_FUNCTION__ << "Creating application container for headless ..."; mEngine = new QQmlEngine; configureQmlEngine(); QQmlComponent component(mEngine, QUrl(QString("qrc:///qml/ApplicationContainer.qml"))); mRootItem = qobject_cast<QQuickItem*>(component.create()); } else { QQuickWebViewExperimental::setFlickableViewportEnabled(mApplication->desc().flickable()); mWindow = new QQuickView; mWindow->installEventFilter(this); mEngine = mWindow->engine(); configureQmlEngine(); connect(mWindow, &QObject::destroyed, [=](QObject *obj) { qDebug() << "Window destroyed"; }); mWindow->setColor(Qt::transparent); mWindow->reportContentOrientationChange(QGuiApplication::primaryScreen()->primaryOrientation()); mWindow->setSurfaceType(QSurface::OpenGLSurface); QSurfaceFormat surfaceFormat = mWindow->format(); surfaceFormat.setAlphaBufferSize(8); surfaceFormat.setRenderableType(QSurfaceFormat::OpenGLES); mWindow->setFormat(surfaceFormat); // make sure the platform window gets created to be able to set it's // window properties mWindow->create(); // set different information bits for our window setWindowProperty(QString("_LUNE_WINDOW_TYPE"), QVariant(mWindowType)); setWindowProperty(QString("_LUNE_WINDOW_PARENT_ID"), QVariant(mParentWindowId)); setWindowProperty(QString("_LUNE_WINDOW_LOADING_ANIMATION_DISABLED"), QVariant(mApplication->loadingAnimationDisabled())); setWindowProperty(QString("_LUNE_APP_ICON"), QVariant(mApplication->icon())); setWindowProperty(QString("_LUNE_APP_ID"), QVariant(mApplication->id())); connect(mWindow, SIGNAL(visibleChanged(bool)), this, SLOT(onVisibleChanged(bool))); QPlatformNativeInterface *nativeInterface = QGuiApplication::platformNativeInterface(); connect(nativeInterface, SIGNAL(windowPropertyChanged(QPlatformWindow*, const QString&)), this, SLOT(onWindowPropertyChanged(QPlatformWindow*, const QString&))); mWindow->setSource(QUrl(QString("qrc:///qml/ApplicationContainer.qml"))); mRootItem = mWindow->rootObject(); mWindow->resize(mSize); } }
void myLevelSystem::ProcessEntity(const tinyxml2::XMLNode* EntityNode) { const tinyxml2::XMLElement* entityElement = EntityNode->ToElement(); std::string entityId; float posx; float posy; float rot; float scaleX; float scaleY; bool canAdd = true; do { if (entityElement->Attribute("id") == NULL) { break; } if (entityElement->Attribute("x") == NULL) { break; } if (entityElement->Attribute("y") == NULL) { break; } if (entityElement->Attribute("rot") == NULL) { break; } if (entityElement->Attribute("scalex") == NULL) { break; } if (entityElement->Attribute("scaley") == NULL) { break; } entityId = std::string((entityElement->Attribute("id"))); posx = myMath::PixelsToMeters((float) atof(entityElement->Attribute("x"))); posy = myMath::PixelsToMeters((float) atof(entityElement->Attribute("y"))); rot = (float) atof(entityElement->Attribute("rot")); rot = myMath::DegreesToRadians(rot); scaleX = (float) atof(entityElement->Attribute("scalex")); scaleY = (float) atof(entityElement->Attribute("scaley")); std::shared_ptr<myEntity> entity(new myEntity(entityId, posx, posy, rot, scaleX, scaleY)); // Process Components for (const tinyxml2::XMLNode* componentNode = EntityNode->FirstChild(); componentNode; componentNode = componentNode->NextSibling()) { const tinyxml2::XMLElement* componentElement = componentNode->ToElement(); if (strcmp(componentElement->Name(), "Component") == 0) { std::string componentId; int type; bool enabled; do { if (componentElement->Attribute("id") == NULL) { break; } if (componentElement->Attribute("type") == NULL) { break; } if (componentElement->Attribute("enabled") == NULL) { break; } componentId = std::string(componentElement->Attribute("id")); type = atoi(componentElement->Attribute("type")); enabled = (atoi(componentElement->Attribute("enabled")) != 0); switch (type) { case myComponent::RENDER: { const tinyxml2::XMLElement* assetElement = componentNode->FirstChild()->ToElement(); std::string assetId(assetElement->Attribute("asset")); std::shared_ptr<myAsset> asset = GetAsset(assetId); switch (asset->type) { case myAsset::SPRITE: { myDebug::Log(myDebug::LOG_INFO, "Loaded:\n%s", asset->ToString().c_str()); std::shared_ptr<myRenderComponent> component(new myRenderComponent(componentId, std::static_pointer_cast < mySprite > (asset), enabled)); entity->AddComponent(component); } break; case myAsset::SPRITE_SHEET: { myDebug::Log(myDebug::LOG_INFO, "Loaded:\n%s", asset->ToString().c_str()); std::shared_ptr<myRenderComponent> component(new myRenderComponent(componentId, std::static_pointer_cast < mySpriteSheet > (asset), enabled)); entity->AddComponent(component); } break; } } break; case myComponent::AUDIO: break; case myComponent::PHYSICS: { const tinyxml2::XMLElement* physicsElement = componentNode->FirstChild()->ToElement(); unsigned int bodyType = atoi(physicsElement->Attribute("type")); float density = (float) atof(physicsElement->Attribute("density")); float friction = (float) atof(physicsElement->Attribute("friction")); float restitution = (float) atof(physicsElement->Attribute("restitution")); float gravityScale = (float) atof(physicsElement->Attribute("gravityScale")); bool allowSleep = (atoi(physicsElement->Attribute("allowSleep")) != 0); std::shared_ptr<myPhysicsComponent> component(new myPhysicsComponent(componentId, bodyType, enabled)); component->density = density; component->friction = friction; component->restitution = restitution; component->gravityScale = gravityScale; component->allowSleep = allowSleep; entity->AddComponent(component); } break; case myComponent::INPUT: { const tinyxml2::XMLElement* inputElement = componentNode->FirstChild()->ToElement(); std::shared_ptr<myInputComponent> component(new myInputComponent(componentId, enabled)); entity->AddComponent(component); } break; case myComponent::SCRIPT: { const tinyxml2::XMLElement* scriptElement = componentNode->FirstChild()->ToElement(); std::string filename(scriptElement->Attribute("filename")); std::shared_ptr<myScriptComponent> component(new myScriptComponent(componentId, filename, enabled)); entity->AddComponent(component); } } /*if (component) { entity->AddComponent(component); Debug::Log(Debug::LOG_INFO, "Added Component To: %s\n%s", entity->GetId().c_str(), component->ToString().c_str()); }*/ } while (0); } } // process components for (auto sharedEntity : _sharedEntities) { if (strcmp(entity->GetId().c_str(), sharedEntity->GetId().c_str()) == 0) { canAdd = false; } } if (canAdd) { myDebug::Log(myDebug::LOG_INFO, "Loaded:\n%s", entity->ToString().c_str()); _sharedEntities.push_back(entity); } else { myDebug::Log(myDebug::LOG_INFO, "Could Not Load:\n%s", entity->ToString().c_str()); } } while (0); }
bool OpenVRPlugin::init(QOpenGLExtraFunctions* f, QQmlEngine* qmlEngine) { Q_UNUSED(f) Q_INIT_RESOURCE(openvrplugin); if (!vr::VR_IsHmdPresent()) { qDebug("No HMD detected..."); return false; } /* This wil be inited on first usage. */ vrSystem = nullptr; mirrorShader = new QOpenGLShaderProgram; mirrorShader->addShaderFromSourceFile(QOpenGLShader::Vertex, ":/OpenVR/glsl/mirror.vsh"); mirrorShader->addShaderFromSourceFile(QOpenGLShader::Fragment, ":/OpenVR/glsl/mirror.fsh"); mirrorShader->link(); /* Bind so we set the texture sampler uniform values. */ mirrorShader->bind(); /* Left image is TEXTURE0. */ mirrorShader->setUniformValue("textureL", 0); /* Right image is TEXTURE1. */ mirrorShader->setUniformValue("textureR", 1); vrSceneShader = new QOpenGLShaderProgram; vrSceneShader->addShaderFromSourceFile(QOpenGLShader::Vertex, ":/OpenVR/glsl/vrscene.vsh"); vrSceneShader->addShaderFromSourceFile(QOpenGLShader::Fragment, ":/OpenVR/glsl/vrscene.fsh"); vrSceneShader->link(); /* Bind so we set the texture sampler uniform values. */ vrSceneShader->bind(); /* Left image is TEXTURE0. */ vrSceneShader->setUniformValue("textureL", 0); /* Right image is TEXTURE1. */ vrSceneShader->setUniformValue("textureR", 1); distortionShader = new QOpenGLShaderProgram; distortionShader->addShaderFromSourceFile(QOpenGLShader::Vertex, ":/OpenVR/glsl/distortion.vsh"); distortionShader->addShaderFromSourceFile(QOpenGLShader::Fragment, ":/OpenVR/glsl/distortion.fsh"); /* Make sure the attributes are bound correctly. */ distortionShader->bindAttributeLocation("position", 0); distortionShader->bindAttributeLocation("uvRedIn", 1); distortionShader->bindAttributeLocation("uvGreenIn", 2); distortionShader->bindAttributeLocation("uvBlueIn", 3); distortionShader->link(); /* Bind so we set the texture sampler uniform values. */ distortionShader->bind(); /* The source texture will be bound to TEXTURE0. */ distortionShader->setUniformValue("texture", 0); QQmlComponent component(qmlEngine); component.loadUrl(QUrl(QStringLiteral("qrc:/OpenVR/Config.qml"))); /* Wait for it to load... */ while(component.isLoading()); /* The program can't run if there was an error. */ if (component.isError()) { qDebug(qPrintable(component.errorString())); return false; } configMenu = qobject_cast<QQuickItem*>(component.create()); /* Critical error! abort! abort! */ if (configMenu == nullptr) return false; screenDistance = QQmlProperty(configMenu, "screenDistance"); screenHeight = QQmlProperty(configMenu, "screenHeight"); screenSize = QQmlProperty(configMenu, "screenSize"); curvedScreen = QQmlProperty(configMenu, "curvedScreen"); lockMouse = QQmlProperty(configMenu, "lockMouse"); screenDistance.connectNotifySignal(this, SLOT(updateScreen())); screenHeight.connectNotifySignal(this, SLOT(updateScreen())); screenSize.connectNotifySignal(this, SLOT(updateScreen())); curvedScreen.connectNotifySignal(this, SLOT(updateScreen())); qDebug("OpenVR plugin base inited."); return true; }
void complete_vehicle (game *g) { if (g->u.activity.values.size() < 7) { debugmsg ("Invalid activity ACT_VEHICLE values:%d", g->u.activity.values.size()); return; } vehicle *veh = g->m.veh_at (g->u.activity.values[0], g->u.activity.values[1]); if (!veh) { debugmsg ("Activity ACT_VEHICLE: vehicle not found"); return; } char cmd = (char) g->u.activity.index; int dx = g->u.activity.values[4]; int dy = g->u.activity.values[5]; int part = g->u.activity.values[6]; std::vector<component> tools; int welder_charges = ((it_tool *) g->itypes["welder"])->charges_per_use; itype_id itm; int partnum; item used_item; bool broken; int bigness; int dd = 2; switch (cmd) { case 'i': partnum = veh->install_part (dx, dy, (vpart_id) part); if(partnum < 0) debugmsg ("complete_vehicle install part fails dx=%d dy=%d id=%d", dx, dy, part); used_item = consume_vpart_item (g, (vpart_id) part); veh->get_part_properties_from_item(g, partnum, used_item); //transfer damage, etc. tools.push_back(component("welder", welder_charges)); tools.push_back(component("toolset", welder_charges/5)); g->consume_tools(tools); g->add_msg ("You install a %s into the %s.", vpart_list[part].name, veh->name.c_str()); g->u.practice (g->turn, "mechanics", vpart_list[part].difficulty * 5 + 20); break; case 'r': if (veh->parts[part].hp <= 0) { used_item = consume_vpart_item (g, veh->parts[part].id); tools.push_back(component("wrench", 1)); g->consume_tools(tools); tools.clear(); dd = 0; veh->insides_dirty = true; } tools.push_back(component("welder", welder_charges)); tools.push_back(component("toolset", welder_charges/5)); g->consume_tools(tools); veh->parts[part].hp = veh->part_info(part).durability; g->add_msg ("You repair the %s's %s.", veh->name.c_str(), veh->part_info(part).name); g->u.practice (g->turn, "mechanics", (vpart_list[part].difficulty + dd) * 5 + 20); break; case 'f': if (!g->pl_refill_vehicle(*veh, part, true)) debugmsg ("complete_vehicle refill broken"); g->pl_refill_vehicle(*veh, part); break; case 'o': for (int i = 0; i < veh->parts[part].items.size(); i++) g->m.add_item (g->u.posx, g->u.posy, veh->parts[part].items[i]); veh->parts[part].items.clear(); itm = veh->part_info(part).item; broken = veh->parts[part].hp <= 0; bigness = veh->parts[part].bigness; if (!broken){ itype* parttype = g->itypes[itm]; item tmp(parttype, g->turn); veh->give_part_properties_to_item(g, part, tmp); //transfer damage, etc. if(parttype->is_var_veh_part()){ // has bigness. tmp.bigness = bigness; } g->m.add_item(g->u.posx, g->u.posy, tmp); //else { // g->m.add_item (g->u.posx, g->u.posy, g->itypes[itm], g->turn); //} g->u.practice (g->turn, "mechanics", 2 * 5 + 20); } if (veh->parts.size() < 2) { g->add_msg ("You completely dismantle %s.", veh->name.c_str()); g->u.activity.type = ACT_NULL; g->m.destroy_vehicle (veh); } else { g->add_msg ("You remove %s%s from %s.", broken? "broken " : "", veh->part_info(part).name, veh->name.c_str()); veh->remove_part (part); } //break; default:; } }
PassOwnPtr<AudioSourceProvider> MediaStreamTrack::createWebAudioSource() { return MediaStreamCenter::instance().createWebAudioSourceFromMediaStreamTrack(component()); }
Partitioner::RegionStats * Partitioner::region_statistics(const ExtentMap &addresses) { RegionStats *stats = new_region_stats(); assert(stats!=NULL); size_t nbytes = addresses.size(); if (0==nbytes) return stats; stats->add_sample(RegionStats::RA_NBYTES, nbytes); ExtentMap not_addresses = addresses.invert<ExtentMap>(); Disassembler::AddressSet worklist; // addresses waiting to be disassembled recursively InstructionMap insns_found; // all the instructions we found herein ExtentMap insns_extent; // memory used by the instructions we've found ExtentMap pending = addresses; // addresses we haven't looked at yet /* Undirected local control flow graph used to count connected components */ typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> CFG; typedef boost::graph_traits<CFG>::vertex_descriptor CFGVertex; typedef std::map<rose_addr_t, CFGVertex> Addr2Vertex; CFG cfg; Addr2Vertex va2id; /* Statistics */ size_t nstarts=0; // number of times the recursive disassembler was started size_t nfails=0; // number of disassembler failures size_t noverlaps=0; // instructions overlapping with a previously found instruction size_t nincomplete=0; // number of instructions with unknown successors size_t nfallthrough=0; // number of branches to fall-through address within our "addresses" size_t ncalls=0; // number of function calls outside our "addresses" size_t nnoncalls=0; // number of branches to non-functions outside our "addresses" size_t ninternal=0; // number of non-fallthrough internal branches while (!pending.empty()) { rose_addr_t start_va = pending.min(); worklist.insert(start_va); ++nstarts; while (!worklist.empty()) { rose_addr_t va = *worklist.begin(); worklist.erase(worklist.begin()); /* Obtain (disassemble) the instruction and make sure it falls entirely within the "addresses" */ Instruction *insn = find_instruction(va); if (!insn) { ++nfails; pending.erase(Extent(va)); continue; } Extent ie(va, insn->get_size()); if (not_addresses.overlaps(ie)) { ++nfails; pending.erase(Extent(va)); continue; } /* The disassembler can also return an "unknown" instruction when failing, depending on how it is invoked. */ if (insn->node->is_unknown()) { ++nfails; pending.erase(Extent(va, insn->get_size())); continue; } insns_found.insert(std::make_pair(va, insn)); rose_addr_t fall_through_va = va + insn->get_size(); /* Does this instruction overlap with any we've already found? */ if (insns_extent.overlaps(ie)) ++noverlaps; pending.erase(Extent(va, insn->get_size())); insns_extent.insert(ie); /* Find instruction successors by looking only at the instruction itself. This is simpler, but less rigorous * method than finding successors a basic block at a time. For instance, we'll find both sides of a branch * instruction even if the more rigorous method determined that one side or the other is always taken. But this is * probably what we want here anyway for determining whether something looks like code. */ bool complete; Disassembler::AddressSet succs = insn->get_successors(&complete); if (!complete) ++nincomplete; /* Add instruction as vertex to CFG */ std::pair<Addr2Vertex::iterator, bool> inserted = va2id.insert(std::make_pair(va, va2id.size())); if (inserted.second) { CFGVertex vertex __attribute__((unused)) = add_vertex(cfg); assert(vertex==inserted.first->second); } /* Classify the various successors. */ for (Disassembler::AddressSet::const_iterator si=succs.begin(); si!=succs.end(); ++si) { rose_addr_t succ_va = *si; if (succ_va==fall_through_va) { ++nfallthrough; if (pending.find(succ_va)!=pending.end()) worklist.insert(succ_va); /* Add edge to CFG graph */ va2id.insert(std::make_pair(succ_va, va2id.size())); add_edge(va2id[va], va2id[succ_va], cfg); } else if (addresses.find(succ_va)==addresses.end()) { /* A non-fallthrough branch to something outside this memory region */ if (functions.find(succ_va)!=functions.end()) { /* A branch to a function entry point we've previously discovered. */ ++ncalls; } else { ++nnoncalls; } } else { /* A non-fallthrough branch to something in our address range. */ ++ninternal; if (pending.find(succ_va)!=pending.end()) worklist.insert(succ_va); /* Add edge to CFG graph */ va2id.insert(std::make_pair(succ_va, va2id.size())); add_edge(va2id[va], va2id[succ_va], cfg); } } } } /* Statistics */ stats->add_sample(RegionStats::RA_NFAILS, nfails); stats->add_sample(RegionStats::RA_NINSNS, insns_found.size()); stats->add_sample(RegionStats::RA_NOVERLAPS, noverlaps); stats->add_sample(RegionStats::RA_NSTARTS, nstarts); stats->add_sample(RegionStats::RA_NCOVERAGE, insns_extent.size()); stats->add_sample(RegionStats::RA_NINCOMPLETE, nincomplete); stats->add_sample(RegionStats::RA_NBRANCHES, ncalls+nnoncalls+ninternal); stats->add_sample(RegionStats::RA_NCALLS, ncalls); stats->add_sample(RegionStats::RA_NNONCALLS, nnoncalls); stats->add_sample(RegionStats::RA_NINTERNAL, ninternal); stats->add_sample(RegionStats::RA_NICFGEDGES, ninternal + nfallthrough); stats->add_sample(RegionStats::RA_NIUNIQUE, count_kinds(insns_found)); stats->add_sample(RegionStats::RA_NPRIV, count_privileged(insns_found)); stats->add_sample(RegionStats::RA_NFLOAT, count_floating_point(insns_found)); double regsz, regvar; stats->add_sample(RegionStats::RA_NREGREFS, count_registers(insns_found, ®sz, ®var)); stats->add_sample(RegionStats::RA_REGSZ, regsz); stats->add_sample(RegionStats::RA_REGVAR, regvar); /* Count the number of connected components in the undirected CFG */ if (!va2id.empty()) { std::vector<int> component(num_vertices(cfg)); stats->add_sample(RegionStats::RA_NCOMPS, connected_components(cfg, &component[0])); } stats->compute_ratios(); return stats; }
int internalMain(QGuiApplication *application) { QCoreApplication::setOrganizationName("QtProject"); QCoreApplication::setOrganizationDomain("qt-project.org"); QCoreApplication::setApplicationName("Qml2Puppet"); QCoreApplication::setApplicationVersion("1.0.0"); if (application->arguments().count() < 2 || (application->arguments().at(1) == "--readcapturedstream" && application->arguments().count() < 3)) { qDebug() << "Usage:\n"; qDebug() << "--test"; qDebug() << "--version"; qDebug() << "--readcapturedstream <stream file> [control stream file]"; return -1; } if (application->arguments().at(1) == "--readcapturedstream" && application->arguments().count() > 2) { QFileInfo inputStreamFileInfo(application->arguments().at(2)); if (!inputStreamFileInfo.exists()) { qDebug() << "Input stream does not exist:" << inputStreamFileInfo.absoluteFilePath(); return -1; } if (application->arguments().count() > 3) { QFileInfo controlStreamFileInfo(application->arguments().at(3)); if (!controlStreamFileInfo.exists()) { qDebug() << "Output stream does not exist:" << controlStreamFileInfo.absoluteFilePath(); return -1; } } } if (application->arguments().count() == 2 && application->arguments().at(1) == "--test") { qDebug() << QCoreApplication::applicationVersion(); QQmlEngine engine; QQmlComponent component(&engine); component.setData("import QtQuick 2.0\nItem {\n}\n", QUrl::fromLocalFile("test.qml")); QObject *object = component.create(); if (object) { qDebug() << "Basic QtQuick 2.0 working..."; } else { qDebug() << "Basic QtQuick 2.0 not working..."; qDebug() << component.errorString(); } delete object; return 0; } if (application->arguments().count() == 2 && application->arguments().at(1) == "--version") { std::cout << 2; return 0; } if (application->arguments().at(1) != "--readcapturedstream" && application->arguments().count() < 4) { qDebug() << "Wrong argument count: " << application->arguments().count(); return -1; } #ifdef ENABLE_QT_BREAKPAD const QString libexecPath = QCoreApplication::applicationDirPath() + '/' + RELATIVE_LIBEXEC_PATH; QtSystemExceptionHandler systemExceptionHandler(libexecPath); #endif new QmlDesigner::Qt5NodeInstanceClientProxy(application); #if defined(Q_OS_WIN) && defined(QT_NO_DEBUG) SetErrorMode(SEM_NOGPFAULTERRORBOX); //We do not want to see any message boxes #endif if (application->arguments().at(1) == "--readcapturedstream") return 0; return application->exec(); }
void processEvent(podio::EventStore& store, bool verboser, unsigned eventNum) { auto& failing = store.get<ExampleClusterCollection>("notthere"); if(failing.isValid() == true) { throw std::runtime_error("Collection 'notthere' should not be valid"); }; auto& strings = store.get<ExampleWithStringCollection>("strings"); if(strings.isValid()){ auto string = strings[0]; if (string.theString() != "SomeString") { throw std::runtime_error("Couldn't read string properly"); } } else { throw std::runtime_error("Collection 'strings' should be present."); } auto& clusters = store.get<ExampleClusterCollection>("clusters"); if(clusters.isValid()){ auto cluster = clusters[0]; for (auto i = cluster.Hits_begin(), end = cluster.Hits_end(); i!=end; ++i){ std::cout << " Referenced hit has an energy of " << i->energy() << std::endl; glob++; } } else { throw std::runtime_error("Collection 'clusters' should be present"); } auto& mcps = store.get<ExampleMCCollection>("mcparticles"); if( mcps.isValid() ){ // check that we can retrieve the correct parent daughter relation // set in write.cpp : // particle 0 has particles 2,3,4 and 5 as daughters: auto p = mcps[0] ; //-------- print relations for debugging: for( auto p : mcps ){ std::cout << " particle " << p.getObjectID().index << " has daughters: " ; for(auto it = p.daughters_begin(), end = p.daughters_end() ; it!=end ; ++it ){ std::cout << " " << it->getObjectID().index ; } std::cout << " and parents: " ; for(auto it = p.parents_begin(), end = p.parents_end() ; it!=end ; ++it ){ std::cout << " " << it->getObjectID().index ; } std::cout << std::endl ; } auto d0 = p.daughters(0) ; auto d1 = p.daughters(1) ; auto d2 = p.daughters(2) ; auto d3 = p.daughters(3) ; if( ! ( d0 == mcps[2] ) ) throw std::runtime_error(" error: 1. daughter of particle 0 is not particle 2 "); if( ! ( d1 == mcps[3] ) ) throw std::runtime_error(" error: 2. daughter of particle 0 is not particle 3 "); if( ! ( d2 == mcps[4] ) ) throw std::runtime_error(" error: 3. daughter of particle 0 is not particle 4 "); if( ! ( d3 == mcps[5] ) ) throw std::runtime_error(" error: 4. daughter of particle 0 is not particle 5 "); // particle 3 has particles 6,7,8 and 9 as daughters: p = mcps[3] ; d0 = p.daughters(0) ; d1 = p.daughters(1) ; d2 = p.daughters(2) ; d3 = p.daughters(3) ; if( ! ( d0 == mcps[6] ) ) throw std::runtime_error(" error: 1. daughter of particle 3 is not particle 6 "); if( ! ( d1 == mcps[7] ) ) throw std::runtime_error(" error: 2. daughter of particle 3 is not particle 7 "); if( ! ( d2 == mcps[8] ) ) throw std::runtime_error(" error: 3. daughter of particle 3 is not particle 8 "); if( ! ( d3 == mcps[9] ) ) throw std::runtime_error(" error: 4. daughter of particle 3 is not particle 9 "); } else { throw std::runtime_error("Collection 'mcparticles' should be present"); } //std::cout << "Fetching collection 'refs'" << std::endl; auto& refs = store.get<ExampleReferencingTypeCollection>("refs"); if(refs.isValid()){ auto ref = refs[0]; for (auto j = ref.Clusters_begin(), end = ref.Clusters_end(); j!=end; ++j){ for (auto i = j->Hits_begin(), end = j->Hits_end(); i!=end; ++i){ //std::cout << " Referenced object has an energy of " << i->energy() << std::endl; glob++; } } } else { throw std::runtime_error("Collection 'refs' should be present"); } //std::cout << "Fetching collection 'OneRelation'" << std::endl; auto& rels = store.get<ExampleWithOneRelationCollection>("OneRelation"); if(rels.isValid()) { //std::cout << "Referenced object has an energy of " << (*rels)[0].cluster().energy() << std::endl; glob++; } else { throw std::runtime_error("Collection 'OneRelation' should be present"); } // std::cout << "Fetching collection 'WithVectorMember'" << std::endl; auto& vecs = store.get<ExampleWithVectorMemberCollection>("WithVectorMember"); if(vecs.isValid()) { std::cout << vecs.size() << std::endl; for( auto item : vecs ) for (auto c = item.count_begin(), end = item.count_end(); c!=end; ++c){ std::cout << " Counter value " << (*c) << std::endl; glob++; } } else { throw std::runtime_error("Collection 'WithVectorMember' should be present"); } auto& comps = store.get<ExampleWithComponentCollection>("Component"); if (comps.isValid()) { auto comp = comps[0]; int a = comp.component().data.x + comp.component().data.z; } auto& arrays = store.get<ExampleWithArrayCollection>("arrays"); if (arrays.isValid() && arrays.size() != 0) { auto array = arrays[0]; if (array.myArray(1) != eventNum) { throw std::runtime_error("Array not properly set."); } if (array.arrayStruct().data.p.at(2) != 2*eventNum) { throw std::runtime_error("Array not properly set."); } if (array.structArray(0).x != eventNum) { throw std::runtime_error("Array of struct not properly set."); } } else { throw std::runtime_error("Collection 'arrays' should be present"); } auto& nmspaces = store.get<ex::ExampleWithARelationCollection>("WithNamespaceRelation"); auto& copies = store.get<ex::ExampleWithARelationCollection>("WithNamespaceRelationCopy"); auto& cpytest = store.create<ex::ExampleWithARelationCollection>("TestConstCopy"); if (nmspaces.isValid() && copies.isValid()) { for (int j = 0; j < nmspaces.size(); j++) { auto nmsp = nmspaces[j]; auto cpy = copies[j]; cpytest.push_back(nmsp.clone()); if (nmsp.ref().isAvailable()) { if (nmsp.ref().data().x != cpy.ref().data().x || nmsp.ref().data().y != cpy.ref().data().y) { throw std::runtime_error("Copied item has differing data in OneToOne referenced item."); } // check direct accessors of POD sub members if (nmsp.ref().x() != cpy.ref().x()) { throw std::runtime_error("Getting wrong values when using direct accessors for sub members."); } if (nmsp.number() != cpy.number()) { throw std::runtime_error("Copied item has differing member."); } if (!(nmsp.ref().getObjectID() == cpy.ref().getObjectID())) { throw std::runtime_error("Copied item has wrong OneToOne references."); } } auto cpy_it = cpy.refs_begin(); for (auto it = nmsp.refs_begin(); it != nmsp.refs_end(); ++it, ++cpy_it) { if (it->data().x != cpy_it->data().x || it->data().y != cpy_it->data().y) { throw std::runtime_error("Copied item has differing data in OneToMany referenced item."); } if (!(it->getObjectID() == cpy_it->getObjectID())) { throw std::runtime_error("Copied item has wrong OneToMany references."); } } } } else { throw std::runtime_error("Collection 'WithNamespaceRelation' and 'WithNamespaceRelationCopy' should be present"); } }
int main(int argc, char *argv[]) { QApplication app(argc, argv); app.setApplicationName ("QQStars"); app.setApplicationVersion ("1.0.0"); app.setOrganizationName ("雨后星辰"); app.setApplicationDisplayName ("星辰QQ"); QTranslator *translator = new QTranslator; translator->load (":/qt_zh_CN.qm"); QApplication::installTranslator (translator); QQmlApplicationEngine *engine = new QQmlApplicationEngine; engine->setNetworkAccessManagerFactory (new MyNetworkAccessManagerFactory());//给qml设置网络请求所用的类 qmlRegisterType<TextEditPlayGif>("MyTextEditPlugin", 1, 0, "TextEditPlayGif"); qmlRegisterType<MyWindow>("mywindow", 1,0, "MyQuickWindow"); qmlRegisterType<SystemTrayIcon>("mywindow", 1,0, "MySystemTrayIcon"); qmlRegisterType<MyMenu>("mywindow", 1,0, "MyMenu"); qmlRegisterType<MenuSeparator>("mywindow", 1,0, "MenuSeparator"); qmlRegisterType<MyMenuItem>("mywindow", 1,0, "MyMenuItem"); qmlRegisterType<MyShortcut>("utility", 1,0, "MyShortcut"); qmlRegisterType<DownloadImage>("utility", 1, 0, "DownloadImage"); qmlRegisterType<QQCommand>("qqstars", 1,0, "QQ"); qmlRegisterType<FriendInfo>("QQItemInfo", 1,0, "FriendInfo"); qmlRegisterType<GroupInfo>("QQItemInfo", 1,0, "GroupInfo"); qmlRegisterType<DiscuInfo>("QQItemInfo", 1,0, "DiscuInfo"); qmlRegisterType<QQItemInfo>("QQItemInfo", 1,0, "QQItemInfo"); qmlRegisterType<ChatMessageInfo>("QQItemInfo", 1, 0, "ChatMessageInfo"); qmlRegisterType<ChatMessageInfoList>("QQItemInfo", 1, 0, "ChatMessageInfoList"); qmlRegisterType<MyImage>("mywindow", 1,0, "MyImage"); qmlRegisterType<MySvgView>("mywindow", 1, 0, "SvgView"); qmlRegisterType<MyMessageBox>("mywindow", 1, 0, "MessageBox"); Utility *utility=Utility::createUtilityClass (); QNetworkRequest* request = utility->getHttpRequest ()->getNetworkRequest (); request->setRawHeader ("Referer", "http://d.web2.qq.com/proxy.html?v=20110331002&callback=1&id=2");//和腾讯服务器打交道需要设置这个 request->setHeader (QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); request = utility->getDownloadImage ()->getHttpRequest ()->getNetworkRequest (); request->setRawHeader ("Referer", "http://web2.qq.com/webqq.html");//需要设置这个,不然腾讯服务器不响应你的请求 request->setRawHeader ("Accept", "image/webp,*/*;q=0.8"); utility->initUtility (new QSettings, engine); QQmlComponent component0(engine, QUrl("qrc:/qml/Api/QQApi.qml")); QQCommand *qqapi = qobject_cast<QQCommand *>(component0.create ()); engine->rootContext ()->setContextProperty ("myqq", qqapi); QQmlComponent component(engine, QUrl("qrc:/qml/Utility/SystemTray.qml")); SystemTrayIcon *systemTray = qobject_cast<SystemTrayIcon *>(component.create ()); #ifdef Q_OS_WIN systemTray->setParent (Utility::createUtilityClass ());//不设置父对象会导致程序退出后托盘还存在的问题 #endif engine->rootContext ()->setContextProperty ("systemTray", systemTray);//将程序托盘注册过去 qqapi->loadLoginWindow ();//加载登录窗口 return app.exec(); }
void SpringEmbedderFR::call(GraphAttributes &AG) { const Graph &G = AG.constGraph(); if(G.empty()) return; // all edges straight-line AG.clearAllBends(); GraphCopy GC; GC.createEmpty(G); // compute connected component of G NodeArray<int> component(G); int numCC = connectedComponents(G,component); // intialize the array of lists of nodes contained in a CC Array<List<node> > nodesInCC(numCC); node v; forall_nodes(v,G) nodesInCC[component[v]].pushBack(v); EdgeArray<edge> auxCopy(G); Array<DPoint> boundingBox(numCC); int i; for(i = 0; i < numCC; ++i) { GC.initByNodes(nodesInCC[i],auxCopy); GraphCopyAttributes AGC(GC,AG); node vCopy; forall_nodes(vCopy, GC) { node vOrig = GC.original(vCopy); AGC.x(vCopy) = AG.x(vOrig); AGC.y(vCopy) = AG.y(vOrig); } // original if (initialize(GC, AGC) == true) { for(int i = 1; i <= m_iterations; i++) mainStep(GC, AGC); } cleanup(); // end original node vFirst = GC.firstNode(); double minX = AGC.x(vFirst), maxX = AGC.x(vFirst), minY = AGC.y(vFirst), maxY = AGC.y(vFirst); forall_nodes(vCopy,GC) { node v = GC.original(vCopy); AG.x(v) = AGC.x(vCopy); AG.y(v) = AGC.y(vCopy); if(AG.x(v)-AG.width (v)/2 < minX) minX = AG.x(v)-AG.width(v) /2; if(AG.x(v)+AG.width (v)/2 > maxX) maxX = AG.x(v)+AG.width(v) /2; if(AG.y(v)-AG.height(v)/2 < minY) minY = AG.y(v)-AG.height(v)/2; if(AG.y(v)+AG.height(v)/2 > maxY) maxY = AG.y(v)+AG.height(v)/2; }
void GEMLayout::call(GraphAttributes &AG) { const Graph &G = AG.constGraph(); if(G.empty()) return; OGDF_ASSERT(m_numberOfRounds >= 0); OGDF_ASSERT(DIsGreaterEqual(m_minimalTemperature,0)); OGDF_ASSERT(DIsGreaterEqual(m_initialTemperature,m_minimalTemperature)); OGDF_ASSERT(DIsGreaterEqual(m_gravitationalConstant,0)); OGDF_ASSERT(DIsGreaterEqual(m_desiredLength,0)); OGDF_ASSERT(DIsGreaterEqual(m_maximalDisturbance,0)); OGDF_ASSERT(DIsGreaterEqual(m_rotationAngle,0)); OGDF_ASSERT(DIsLessEqual(m_rotationAngle,pi / 2)); OGDF_ASSERT(DIsGreaterEqual(m_oscillationAngle,0)); OGDF_ASSERT(DIsLessEqual(m_oscillationAngle,pi / 2)); OGDF_ASSERT(DIsGreaterEqual(m_rotationSensitivity,0)); OGDF_ASSERT(DIsLessEqual(m_rotationSensitivity,1)); OGDF_ASSERT(DIsGreaterEqual(m_oscillationSensitivity,0)); OGDF_ASSERT(DIsLessEqual(m_oscillationSensitivity,1)); OGDF_ASSERT(m_attractionFormula == 1 || m_attractionFormula == 2); // all edges straight-line AG.clearAllBends(); GraphCopy GC; GC.createEmpty(G); // compute connected component of G NodeArray<int> component(G); int numCC = connectedComponents(G,component); // intialize the array of lists of nodes contained in a CC Array<List<node> > nodesInCC(numCC); node v; forall_nodes(v,G) nodesInCC[component[v]].pushBack(v); EdgeArray<edge> auxCopy(G); Array<DPoint> boundingBox(numCC); int i; for(i = 0; i < numCC; ++i) { GC.initByNodes(nodesInCC[i],auxCopy); GraphCopyAttributes AGC(GC,AG); node vCopy; forall_nodes(vCopy, GC) { node vOrig = GC.original(vCopy); AGC.x(vCopy) = AG.x(vOrig); AGC.y(vCopy) = AG.y(vOrig); } SList<node> permutation; node v; // initialize node data m_impulseX.init(GC,0); m_impulseY.init(GC,0); m_skewGauge.init(GC,0); m_localTemperature.init(GC,m_initialTemperature); // initialize other data m_globalTemperature = m_initialTemperature; m_barycenterX = 0; m_barycenterY = 0; forall_nodes(v,GC) { m_barycenterX += weight(v) * AGC.x(v); m_barycenterY += weight(v) * AGC.y(v); }
Type Foam::functionObjects::fieldValues::volRegion::processValues ( const Field<Type>& values, const scalarField& V, const scalarField& weightField ) const { Type result = Zero; switch (operation_) { case opSum: { result = gSum(values); break; } case opSumMag: { result = gSum(cmptMag(values)); break; } case opAverage: { result = gSum(values)/nCells_; break; } case opWeightedAverage: { result = gSum(weightField*values)/gSum(weightField); break; } case opVolAverage: { result = gSum(V*values)/volume_; break; } case opWeightedVolAverage: { result = gSum(weightField*V*values)/gSum(weightField*V); break; } case opVolIntegrate: { result = gSum(V*values); break; } case opMin: { result = gMin(values); break; } case opMax: { result = gMax(values); break; } case opCoV: { Type meanValue = gSum(values*V)/volume_; const label nComp = pTraits<Type>::nComponents; for (direction d=0; d<nComp; ++d) { scalarField vals(values.component(d)); scalar mean = component(meanValue, d); scalar& res = setComponent(result, d); res = sqrt(gSum(V*sqr(vals - mean))/volume_)/mean; } break; } case opNone: {} } return result; }
Type Foam::fieldValues::cellSource::processValues ( const Field<Type>& values, const scalarField& V, const scalarField& weightField ) const { Type result = pTraits<Type>::zero; switch (operation_) { case opSum: { result = sum(values); break; } case opSumMag: { result = sum(cmptMag(values)); break; } case opAverage: { result = sum(values)/values.size(); break; } case opWeightedAverage: { result = sum(weightField*values)/sum(weightField); break; } case opVolAverage: { result = sum(V*values)/sum(V); break; } case opWeightedVolAverage: { result = sum(weightField*V*values)/sum(weightField*V); break; } case opVolIntegrate: { result = sum(V*values); break; } case opMin: { result = min(values); break; } case opMax: { result = max(values); break; } case opCoV: { Type meanValue = sum(values*V)/sum(V); const label nComp = pTraits<Type>::nComponents; for (direction d=0; d<nComp; ++d) { scalarField vals(values.component(d)); scalar mean = component(meanValue, d); scalar& res = setComponent(result, d); res = sqrt(sum(V*sqr(vals - mean))/sum(V))/mean; } break; } default: { // Do nothing } } return result; }
void tst_QQmlEngineDebugService::initTestCase() { qmlRegisterType<NonScriptProperty>("Test", 1, 0, "NonScriptPropertyElement"); QTest::ignoreMessage(QtDebugMsg, "QML Debugger: Waiting for connection on port 3768..."); m_engine = new QQmlEngine(this); QList<QByteArray> qml; qml << "import QtQuick 2.0\n" "import Test 1.0\n" "Item {" "id: root\n" "width: 10; height: 20; scale: blueRect.scale;" "Rectangle { id: blueRect; width: 500; height: 600; color: \"blue\"; }" "Text { font.bold: true; color: blueRect.color; }" "MouseArea {" "onEntered: { console.log('hello') }" "}" "property variant varObj\n" "property variant varObjList: []\n" "property variant varObjMap\n" "property variant simpleVar: 10.05\n" "Component.onCompleted: {\n" "varObj = blueRect;\n" "var list = varObjList;\n" "list[0] = blueRect;\n" "varObjList = list;\n" "var map = new Object;\n" "map.rect = blueRect;\n" "varObjMap = map;\n" "}\n" "NonScriptPropertyElement {\n" "}\n" "}"; // add second component to test multiple root contexts qml << "import QtQuick 2.0\n" "Item {}"; // and a third to test methods qml << "import QtQuick 2.0\n" "Item {" "function myMethodNoArgs() { return 3; }\n" "function myMethod(a) { return a + 9; }\n" "function myMethodIndirect() { myMethod(3); }\n" "}"; // and a fourth to test states qml << "import QtQuick 2.0\n" "Rectangle {\n" "id:rootRect\n" "width:100\n" "states: [\n" "State {\n" "name:\"state1\"\n" "PropertyChanges {\n" "target:rootRect\n" "width:200\n" "}\n" "}\n" "]\n" "transitions: [\n" "Transition {\n" "from:\"*\"\n" "to:\"state1\"\n" "PropertyAnimation {\n" "target:rootRect\n" "property:\"width\"\n" "duration:100\n" "}\n" "}\n" "]\n" "}\n" ; for (int i=0; i<qml.count(); i++) { QQmlComponent component(m_engine); component.setData(qml[i], QUrl::fromLocalFile("")); QVERIFY(component.isReady()); // fails if bad syntax m_components << qobject_cast<QQuickItem*>(component.create()); } m_rootItem = qobject_cast<QQuickItem*>(m_components.first()); // add an extra context to test for multiple contexts QQmlContext *context = new QQmlContext(m_engine->rootContext(), this); context->setObjectName("tst_QQmlDebug_childContext"); m_conn = new QQmlDebugConnection(this); m_conn->connectToHost("127.0.0.1", 3768); bool ok = m_conn->waitForConnected(); QVERIFY(ok); QTRY_VERIFY(QQmlDebugService::hasDebuggingClient()); m_dbg = new QQmlEngineDebugClient(m_conn); QTRY_VERIFY(m_dbg->state() == QQmlEngineDebugClient::Enabled); }
std::shared_ptr<PlatformProcess> PlatformProcess::launchWorker( const std::string &exec_path, int argc, char **argv) { ::STARTUPINFOA si = {0}; ::PROCESS_INFORMATION pi = {0}; si.cb = sizeof(si); std::stringstream argv_stream; std::stringstream handle_stream; // The HANDLE exposed to the child process is currently limited to only having // SYNCHRONIZE and PROCESS_QUERY_LIMITED_INFORMATION capabilities. The // SYNCHRONIZE permissions allows for WaitForSingleObject. // PROCESS_QUERY_LIMITED_INFORMATION allows for the ability to use the // GetProcessId and GetExitCodeProcess API functions. HANDLE hLauncherProcess = ::OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, TRUE, GetCurrentProcessId()); if (hLauncherProcess == NULL) { return std::shared_ptr<PlatformProcess>(); } handle_stream << hLauncherProcess; std::string handle = handle_stream.str(); // In the POSIX version, the environment variable OSQUERY_WORKER is set to the // string form of the child process' process ID. However, this is not easily // doable on Windows. Since the value does not appear to be used by the rest // of osquery, we currently just set it to '1'. // // For the worker case, we also set another environment variable, // OSQUERY_LAUNCHER. OSQUERY_LAUNCHER stores the string form of a HANDLE to // the current process. This is mostly used for detecting the death of the // launcher process in WatcherWatcherRunner::start if (!setEnvVar("OSQUERY_WORKER", "1") || !setEnvVar("OSQUERY_LAUNCHER", handle.c_str())) { ::CloseHandle(hLauncherProcess); return std::shared_ptr<PlatformProcess>(); } // Since Windows does not accept a char * array for arguments, we have to // build one as a string. Therefore, we need to make sure that special // characters are not present that would obstruct the parsing of arguments. // For now, we strip out all double quotes. If the an entry in argv has // spaces, we will put double-quotes around the entry. // // NOTE: This is extremely naive and will break the moment complexities are // involved... Windows command line argument parsing is extremely // nitpicky and is different in behavior than POSIX argv parsing. // // We don't directly use argv.c_str() as the value for lpCommandLine in // CreateProcess since that argument requires a modifiable buffer. So, // instead, we off-load the contents of argv into a vector which will have its // backing memory as modifiable. for (size_t i = 0; i < argc; i++) { std::string component(argv[i]); if (component.find(" ") != std::string::npos) { boost::replace_all(component, "\"", "\\\""); argv_stream << "\"" << component << "\" "; } else { argv_stream << component << " "; } } std::string cmdline = argv_stream.str(); std::vector<char> mutable_argv(cmdline.begin(), cmdline.end()); mutable_argv.push_back('\0'); BOOL status = ::CreateProcessA(exec_path.c_str(), &mutable_argv[0], NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi); unsetEnvVar("OSQUERY_WORKER"); unsetEnvVar("OSQUERY_LAUNCHER"); ::CloseHandle(hLauncherProcess); if (!status) { return std::shared_ptr<PlatformProcess>(); } auto process = std::make_shared<PlatformProcess>(pi.hProcess); ::CloseHandle(pi.hThread); ::CloseHandle(pi.hProcess); return process; }
// get the name of the specified component const char *DrawMolecule::get_component_name(int ind) { DrawMolItem *rep = component(ind); if (!rep) return FALSE; return rep->name; }
void OptimalRanking::doCall( const Graph& G, NodeArray<int> &rank, EdgeArray<bool> &reversed, const EdgeArray<int> &length, const EdgeArray<int> &costOrig) { MinCostFlowReinelt mcf; // construct min-cost flow problem GraphCopy GC; GC.createEmpty(G); // compute connected component of G NodeArray<int> component(G); int numCC = connectedComponents(G,component); // intialize the array of lists of nodes contained in a CC Array<List<node> > nodesInCC(numCC); node v; forall_nodes(v,G) nodesInCC[component[v]].pushBack(v); EdgeArray<edge> auxCopy(G); rank.init(G); for(int i = 0; i < numCC; ++i) { GC.initByNodes(nodesInCC[i], auxCopy); makeLoopFree(GC); edge e; forall_edges(e,GC) if(reversed[GC.original(e)]) GC.reverseEdge(e); // special cases: if(GC.numberOfNodes() == 1) { rank[GC.original(GC.firstNode())] = 0; continue; } else if(GC.numberOfEdges() == 1) { e = GC.original(GC.firstEdge()); rank[e->source()] = 0; rank[e->target()] = length[e]; continue; } EdgeArray<int> lowerBound(GC,0); EdgeArray<int> upperBound(GC,mcf.infinity()); EdgeArray<int> cost(GC); NodeArray<int> supply(GC); forall_edges(e,GC) cost[e] = -length[GC.original(e)]; node v; forall_nodes(v,GC) { int s = 0; forall_adj_edges(e,v) { if(v == e->source()) s += costOrig[GC.original(e)]; else s -= costOrig[GC.original(e)]; } supply[v] = s; } OGDF_ASSERT(isAcyclic(GC) == true); // find min-cost flow EdgeArray<int> flow(GC); NodeArray<int> dual(GC); #ifdef OGDF_DEBUG bool feasible = #endif mcf.call(GC, lowerBound, upperBound, cost, supply, flow, dual); OGDF_ASSERT(feasible); forall_nodes(v,GC) rank[GC.original(v)] = dual[v]; }
void tst_qqmltranslation::translation() { QFETCH(QString, translation); QFETCH(QUrl, testFile); QFETCH(bool, verifyCompiledData); QTranslator translator; translator.load(translation, dataDirectory()); QCoreApplication::installTranslator(&translator); QQmlEngine engine; QQmlComponent component(&engine, testFile); QObject *object = component.create(); QVERIFY(object != 0); if (verifyCompiledData) { QQmlContext *context = qmlContext(object); QQmlEnginePrivate *engine = QQmlEnginePrivate::get(context->engine()); QQmlTypeData *typeData = engine->typeLoader.getType(context->baseUrl()); QQmlCompiledData *cdata = typeData->compiledData(); QVERIFY(cdata); QSet<QString> compiledTranslations; compiledTranslations << QStringLiteral("basic") << QStringLiteral("disambiguation") << QStringLiteral("singular") << QStringLiteral("plural"); const QV4::CompiledData::Unit *unit = cdata->compilationUnit->data; const QV4::CompiledData::Object *rootObject = unit->objectAt(unit->indexOfRootObject); const QV4::CompiledData::Binding *binding = rootObject->bindingTable(); for (quint32 i = 0; i < rootObject->nBindings; ++i, ++binding) { const QString propertyName = unit->stringAt(binding->propertyNameIndex); const bool expectCompiledTranslation = compiledTranslations.contains(propertyName); if (expectCompiledTranslation) { if (binding->type != QV4::CompiledData::Binding::Type_Translation) qDebug() << "binding for property" << propertyName << "is not a compiled translation"; QCOMPARE(binding->type, quint32(QV4::CompiledData::Binding::Type_Translation)); } else { if (binding->type == QV4::CompiledData::Binding::Type_Translation) qDebug() << "binding for property" << propertyName << "is not supposed to be a compiled translation"; QVERIFY(binding->type != QV4::CompiledData::Binding::Type_Translation); } } } QCOMPARE(object->property("basic").toString(), QLatin1String("bonjour")); QCOMPARE(object->property("basic2").toString(), QLatin1String("au revoir")); QCOMPARE(object->property("basic3").toString(), QLatin1String("bonjour")); QCOMPARE(object->property("disambiguation").toString(), QLatin1String("salut")); QCOMPARE(object->property("disambiguation2").toString(), QString::fromUtf8("\xc3\xa0 plus tard")); QCOMPARE(object->property("disambiguation3").toString(), QLatin1String("salut")); QCOMPARE(object->property("noop").toString(), QLatin1String("bonjour")); QCOMPARE(object->property("noop2").toString(), QLatin1String("au revoir")); QCOMPARE(object->property("singular").toString(), QLatin1String("1 canard")); QCOMPARE(object->property("singular2").toString(), QLatin1String("1 canard")); QCOMPARE(object->property("plural").toString(), QLatin1String("2 canards")); QCOMPARE(object->property("plural2").toString(), QLatin1String("2 canards")); QCoreApplication::removeTranslator(&translator); delete object; }
int main(int argc, char * argv[]){ /* первым делом создадим директорию для работы нашей проги */ pathDBfile = QDir::toNativeSeparators(QDir::homePath()) + separator + ".dplayer"; if (!QDir(pathDBfile).exists()) { qDebug() << "path programm not exists! Create..."; QDir().mkdir(pathDBfile); } /* вторым делом подготовим таблицы */ db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName(pathDBfile + separator + "dbplayer.db"); if (!db.open()) { QString message = db.lastError().text(); qDebug() << "DB error: " << message; } QSqlQuery a_query(db); QString str = "CREATE TABLE IF NOT EXISTS file (" "id integer PRIMARY KEY AUTOINCREMENT NOT NULL, " "name VARCHAR(255), " "create_date DATETIME" ");"; bool b = a_query.exec(str); if (!b) { QString message = db.lastError().text(); qDebug() << "DB Create table [file] error: " << message; } str = "CREATE TABLE IF NOT EXISTS conf (" "name VARCHAR(255) PRIMARY KEY NOT NULL, " "value VARCHAR(255) " ");"; b = a_query.exec(str); if (!b) { QString message = db.lastError().text(); qDebug() << "DB Create table [file] error: " << message; } db.close(); // закроем подключение к базе /* конец создания таблиц */ /* инициализируем гуи */ QGuiApplication app(argc, argv); QQmlEngine engine; QStringList dataList; dataList.append("Item 1"); dataList.append("Item 2"); dataList.append("Item 3"); dataList.append("Item 4"); //QQmlContext *ctxt = engine.rootContext(); engine.rootContext()->setContextProperty("myModel", QVariant::fromValue(dataList)); QQmlComponent component(&engine, QUrl(QStringLiteral("qrc:/main.qml"))); /* маппим объекты GML с нашими классами */ QObject * object = component.create(); watcherTxtDrive chekUSB; chekUSB.txtDrive = object->findChild<QObject *>("txtDrive"); chekUSB.txtMemo = object->findChild<QObject *>("txtMemo"); /* нужно просканировать наличие УЖЕ подключенных съемных дисков WIN32*/ QFileInfoList drivers = QDir::drives(); foreach(QFileInfo drive, drivers) { chekUSB.slotDeviceAdded(drive.absoluteFilePath()); }