void TCartesianClassifier::domainHasChanged() { TEnumVariable *classV = mlnew TEnumVariable("new"); classVar = classV; mults = vector<int>(domain->attributes->size(), 0); TLimitsCounter counter(vector<int>(domain->attributes->size(), 0)); int mult = 1; vector<int>::reverse_iterator li(counter.limits.rbegin()); vector<int>::reverse_iterator mi(mults.rbegin()); for(TVarList::reverse_iterator vi(domain->attributes->rbegin()), ve(domain->attributes->rend()); vi!=ve; vi++) { if ((*vi)->varType!=TValue::INTVAR) raiseError("invalid attribute '%s' (discrete attributes expected)", (*vi)->get_name().c_str()); *li = (*vi)->noOfValues(); if (!*li) raiseError("invalid attribute '%s' (no values)", (*vi)->get_name().c_str()); (*(mi++)) = mult; mult *= *(li++); } counter.reset(); do { string val; TVarList::iterator vi(domain->attributes->begin()); ITERATE(TLimitsCounter, ci, counter) { if (val.length()) val+="_"; val += (*(vi++)).AS(TEnumVariable)->values->at(*ci); } classV->addValue(val); } while (counter.next()); }
Urho3D::Variant ToVariant(Variant* v) { if (!v) return Urho3D::Variant::EMPTY; switch(v->GetType()) { case Variant::INT: return Urho3D::Variant(v->Get<int>()); case Variant::BYTE: return Urho3D::Variant(v->Get<byte>()); case Variant::CHAR: return Urho3D::Variant(v->Get<char>()); case Variant::FLOAT: return Urho3D::Variant(v->Get<float>()); case Variant::SCRIPTINTERFACE: return Urho3D::Variant((void*)v->Get<ScriptInterface*>()); case Variant::STRING: return Urho3D::Variant(v->Get<String>().CString()); case Variant::VECTOR2: { Urho3D::Vector2 ve(v->Get<Vector2f>().x,v->Get<Vector2f>().y); return Urho3D::Variant(ve); } case Variant::VOIDPTR: return Urho3D::Variant(v->Get<void*>()); case Variant::WORD: return Urho3D::Variant(v->Get<word>()); case Variant::NONE: default: return Urho3D::Variant::EMPTY; } }
void System::addUserData( const string& ac, const string& humanName, const string& val, int prefLvl = 1, bool clobber = false ) { vector<DataItem*>::iterator i, end; for( i = mUserData.begin( ), end = mUserData.end( ); i != end; ++i ) { if( (*i)->ac == ac ) { if( clobber ) { (*i)->dataValue = val; } return; } } DataItem *d = new DataItem( ); if( d == NULL ) { VpdException ve( "Out of memory." ); throw ve; } d->ac = ac; d->humanName = humanName; d->setValue( val, prefLvl, __FILE__, __LINE__ ); mUserData.push_back( d ); }
void MainWindow::on_tableViewVerbs_doubleClicked(const QModelIndex &index) { //1. выбрать по индексу, какой глагол там был... //2. считать содержимое нулевого столбца (скрытого). //3. Открыть диалог. VerbEditor ve(verbsmodel->data(verbsmodel->index(index.row(),0)).toString(),&db,this); ve.exec(); reloadVerbsTable(); return; }
VpdRetriever::VpdRetriever( string envDir, string dbFileName ) throw( VpdException& ) { db = new VpdDbEnv( envDir, dbFileName, true ); if( db == NULL ) { Logger logger; logger.log( "Out of memory, failed to build VpdEnv.", LOG_ERR ); VpdException ve( "Out of memory, failed to build VpdEnv." ); throw ve; } }
void System::addDeviceSpecific( const string& ac, const string& humanName, const string& val, int lvl = 0 ) { DataItem *d = new DataItem( ); if( d == NULL ) { VpdException ve( "Out of memory." ); throw ve; } d->ac = ac; d->humanName = humanName; d->setValue( val, lvl, __FILE__, __LINE__ ); mDeviceSpecific.push_back( d ); }
System* VpdRetriever::getComponentTree( ) { System *root = db->fetch( ); if (root) buildSubTree( root ); else { Logger logger; logger.log( "Failed to fetch VPD DB, it may be corrupt.", LOG_ERR ); VpdException ve( "Failed to fetch VPD DB, it may be corrupt." ); throw ve; } return root; }
VpdRetriever::VpdRetriever( ) throw( VpdException& ) { struct stat vpd_stat,udev_stat; const string vpddb = VpdRetriever::DEFAULT_DIR + VpdRetriever::DEFAULT_FILE; const string udev_file = VpdRetriever::DEFAULT_DIR + VpdRetriever::UDEV_NOTIFY_FILE; Logger logger; int flag = 1; /* Check if stat is successful for UDEV_NOTIFY_FILE. */ if ( stat ( udev_file.c_str(), &udev_stat ) != 0 ) { logger.log( "libvpd: Unable to stat udev rule file, run.vpdupdate.", LOG_INFO ); } else { /* Find the modification time for default DB. */ if ( stat ( vpddb.c_str(), &vpd_stat ) != 0 ) { logger.log( "libvpd: Unable to stat vpd.db file.", LOG_INFO ); if ( errno == ENOENT ) vpd_stat.st_mtime = 0; else flag = 0; } if ( flag && ( udev_stat.st_mtime > vpd_stat.st_mtime ) ) { /* * This implies there were changes to devices on the system * after the VPD db was created/modified. So * run vpdupdate. */ logger.log( "libvpd: Running vpdupdate to update the default db.", LOG_INFO ); system( "vpdupdate >/dev/null 2>&1" ); } } db = new VpdDbEnv( VpdRetriever::DEFAULT_DIR, VpdRetriever::DEFAULT_FILE, true ); if( db == NULL ) { Logger logger; logger.log( "Out of memory, failed to build VpdEnv.", LOG_ERR ); VpdException ve( "Out of memory, failed to build VpdEnv." ); throw ve; } }
Span3d IsPtsSpan3d(const double* a, int n, double tolerance, double* deviation) { // returns a span3d if all points are within tolerance int np = n / 3; // number of points if(np < 2) return Span3d(); // Invalid span3d Point3d sp = Point3d(&a[0]); Point3d ep = Point3d(&a[n-3]); Line line = IsPtsLine(a, n, tolerance, deviation); if(line.ok) return Span3d(sp, ep); // it's a line *deviation = 0; // cumulative deviation Point3d mp = Point3d(&a[np / 2 * 3]); // mid point Plane plane(sp, mp, ep); if(plane.ok) { // plane of the arc is ok // calculate centre point Vector3d vs(mp, sp); vs.normalise(); Vector3d ve(mp, ep); ve.normalise(); Vector3d rs = vs ^ plane.normal; Vector3d re = ve ^ plane.normal; Line rsl(sp.Mid(mp), rs, false); Line rel(ep.Mid(mp), re, false); Point3d pc; Intof(rsl, rel, pc); double radius = pc.Dist(sp); // check other points on circle for(int i = 2; i < np - 1; i++) { Point3d p(&a[i*3]); double dp = fabs(plane.Dist(p)); double dr = fabs(p.Dist(pc) - radius); double tolerance = 10.0 * 1.0e-6; if(dp > tolerance || dr > tolerance) { return Span3d(); } } return Span3d(CW, plane.normal, sp, ep, pc); } return Span3d(); }
vector<vector<int>> threeSum(vector<int>& nums) { sort(nums.begin(),nums.end()); //vector<int> iterator::itr; vector<int>v(3); set< vector<int> > vec; int len=nums.size(); int sum=0; for(int i=0;i<len;i++) { //sum=nums[i]; int j=i+1; int k=len-1; while(j<k) { sum=-nums[i]; if(sum==nums[k]+nums[j]) { v[0]=nums[i]; v[1]=nums[j]; v[2]=nums[k]; vec.insert(v); while(j<k && nums[k]==nums[k-1]) k--; k--; while(j<k && nums[j]==nums[j+1]) j++; j++; } if(sum>nums[j]+nums[k]) j++; else if(sum<nums[j]+nums[k]) k--; } //vec.push_back(v); //v.clear(); } vector<vector<int> > ve(vec.begin(),vec.end()); return ve; }
void ProjectView::ProcessButtonMask(unsigned short mask,bool pressed) { if (!pressed) return ; FieldView::ProcessButtonMask(mask) ; if (mask&EPBM_R) { if (mask&EPBM_DOWN) { ViewType vt=VT_SONG; ViewEvent ve(VET_SWITCH_VIEW,&vt) ; SetChanged(); NotifyObservers(&ve) ; } } else { if (mask&EPBM_START) { Player *player=Player::GetInstance() ; player->OnStartButton(PM_SONG,viewData_->songX_,false,viewData_->songX_) ; } } ; } ;
Vector_3 Plasma::getCMVel(int comp){ int i; Vector_3 vi(0,0,0), ve(0,0,0); if(comp<0 || comp==0){ // ions if(!stable_ions){ for(i=0;i<ni;i++){ vi+=v[i]; } } } if(comp==0)return vi/ni; if(comp<0 || comp==1){ // electrons for(i=ni;i<n;i++){ ve+=v[i]; } } if(comp==1)return ve/ne; // full center-of-mass return (vi*mass+ve)/(ni*mass+ne); }
void Cylinder::getMappedCoords(const Point& intersectPoint, double& x, double &y) const { Point intersect = intersectPoint; intersect.rotate(_rotation, true); Point newPoint = intersect - _absolutePosition; Vector vn(0, 0, -1); Vector ve(1, 0, 0); y = -newPoint._z; newPoint.rotate(_rotation); newPoint.normalize(); double phi = acos(- (vn * newPoint)); double theta = (acos((newPoint * ve) / sin(phi))) / (2 * M_PI); vn *= ve; double y2; if (vn * newPoint > 0) y2 = theta; else y2 = 1 - theta; x = y2; }
void VpdRetriever::buildSubTree( Component* root ) { Component* leaf; const vector<string> children = root->getChildren( ); vector<string>::const_iterator i, end; end = children.end( ); for( i = children.begin( ); i != end; ++i ) { const string next = *i; leaf = db->fetch( next ); if( leaf == NULL ) { Logger logger; logger.log( "Failed to fetch requested item.", LOG_ERR ); VpdException ve( "Failed to fetch requested item." ); throw ve; } buildSubTree( leaf ); root->addLeaf( leaf ); } }
void ProjectView::OnLoadProject() { ViewEvent ve(VET_QUIT_PROJECT) ; SetChanged(); NotifyObservers(&ve) ; } ;
void TrajectoryGenerator::Set_CIRC(Pose3D StartPose, Pose3D ViaPose, Pose3D EndPose, double TotalTime , double AccelTime ) { MotionPose mPose; if(AccelTime >= TotalTime*0.5) { AccelTime = TotalTime*0.5; } int Er; mRobot->ComputeIK(StartPose, angleforplanning, *angleforplanning, &Er); mPose.StartPose = *angleforplanning; mRobot->ComputeIK(ViaPose, angleforplanning, *angleforplanning, &Er); mRobot->ComputeIK(EndPose, angleforplanning, *angleforplanning, &Er); mPose.EndPose = *angleforplanning; Pose3D SP, EP, VP; SP = StartPose; EP = EndPose; VP = ViaPose; mPose.StartPose3D = SP; mPose.EndPose3D = EP; mPose.ViaPose3D = VP; vecd vs(3); vs(0) = SP.x - VP.x; vs(1) = SP.y - VP.y; vs(2) = SP.z - VP.z; vecd ve(3); ve(0) = EP.x - VP.x; ve(1) = EP.y - VP.y; ve(2) = EP.z - VP.z; double p, q; p = ve.squaredNorm() * (vs.squaredNorm() - vs.dot(ve) ) / (2.0 * (vs.squaredNorm() * ve.squaredNorm() - vs.dot(ve) * vs.dot(ve) )); q = vs.squaredNorm() * (vs.dot(ve) - ve.squaredNorm() ) / (2.0 * (vs.dot(ve) * vs.dot(ve) - vs.squaredNorm() * ve.squaredNorm() )); vecd vc(3); vc = p*vs + q*ve; Position3D Center; Center.x = vc(0) + VP.x; Center.y = vc(1) + VP.y; Center.z = vc(2) + VP.z; mPose.CenterPosition = Center; PoseList.push_back(mPose); timeprofile mtime; vecd cs(3), cv(3), ce(3); cs(0) = SP.x - Center.x; cs(1) = SP.y - Center.y; cs(2) = SP.z - Center.z; cv(0) = VP.x - Center.x; cv(1) = VP.y - Center.y; cv(2) = VP.z - Center.z; ce(0) = EP.x - Center.x; ce(1) = EP.y - Center.y; ce(2) = EP.z - Center.z; mtime.distance1 = acos(cs.dot(cv) / ( cs.norm() * cv.norm() ) ); mtime.distance = mtime.distance1 + acos(cv.dot(ce) / ( cv.norm() * ce.norm() ) ); double V = mtime.distance/(TotalTime-AccelTime); double a = V/AccelTime; mtime.Method = Circular; mtime.ta = AccelTime; mtime.tc = TotalTime - 2 * AccelTime; mtime.td = AccelTime; mtime.totoaltime = TotalTime; mtime.a0[0] = 0.0; mtime.a1[0] = 0.0; mtime.a2[0] = 0.5*a; mtime.a0[1] = -0.5*a*AccelTime*AccelTime; mtime.a1[1] = V; mtime.a2[1] = 0.0; mtime.a0[2] = mtime.distance - 0.5*a*TotalTime*TotalTime; mtime.a1[2] = a*TotalTime; mtime.a2[2] = -0.5*a; mTF.push_back(mtime); mMF.push_back(mTF); mTF.clear(); }
PClassifier TTreeSplitConstructor_ExhaustiveBinary::operator()( PStringList &descriptions, PDiscDistribution &subsetSizes, float &quality, int &spentAttribute, PExampleGenerator gen, const int &weightID , PDomainContingency dcont, PDistribution apriorClass, const vector<bool> &candidates, PClassifier ) { checkProperty(measure); measure->checkClassTypeExc(gen->domain->classVar->varType); PIntList bestMapping; int wins, bestAttr; PVariable bvar; if (measure->needs==TMeasureAttribute::Generator) { bool cse = candidates.size()==0; bool haveCandidates = false; vector<bool> myCandidates; myCandidates.reserve(gen->domain->attributes->size()); vector<bool>::const_iterator ci(candidates.begin()), ce(candidates.end()); TVarList::const_iterator vi, ve(gen->domain->attributes->end()); for(vi = gen->domain->attributes->begin(); vi != ve; vi++) { bool co = (*vi)->varType == TValue::INTVAR && (!cse || (ci!=ce) && *ci); myCandidates.push_back(co); haveCandidates = haveCandidates || co; } if (!haveCandidates) return returnNothing(descriptions, subsetSizes, quality, spentAttribute); PDistribution thisSubsets; float thisQuality; wins = 0; int thisAttr = 0; int N = gen->numberOfExamples(); TSimpleRandomGenerator rgen(N); ci = myCandidates.begin(); for(vi = gen->domain->attributes->begin(); vi != ve; ci++, vi++, thisAttr++) { if (*ci) { thisSubsets = NULL; PIntList thisMapping = /*throughCont ? measure->bestBinarization(thisSubsets, thisQuality, *dci, dcont->classes, apriorClass, minSubset) : */measure->bestBinarization(thisSubsets, thisQuality, *vi, gen, apriorClass, weightID, minSubset); if (thisMapping && ( (!wins || (thisQuality>quality)) && ((wins=1)==1) || (thisQuality==quality) && rgen.randbool(++wins))) { bestAttr = thisAttr; quality = thisQuality; subsetSizes = thisSubsets; bestMapping = thisMapping; } } /*if (thoughCont) dci++; */ } if (!wins) return returnNothing(descriptions, subsetSizes, quality, spentAttribute); if (quality<worstAcceptable) return returnNothing(descriptions, subsetSizes, spentAttribute); if (subsetSizes && subsetSizes->variable) bvar = subsetSizes->variable; else { TEnumVariable *evar = mlnew TEnumVariable(""); evar->addValue("0"); evar->addValue("1"); bvar = evar; } } else { bool cse = candidates.size()==0; if (!cse && noCandidates(candidates)) return returnNothing(descriptions, subsetSizes, quality, spentAttribute); if (!dcont || dcont->classIsOuter) { dcont = PDomainContingency(mlnew TDomainContingency(gen, weightID)); // raiseWarningWho("TreeSplitConstructor_ExhaustiveBinary", "this class is not optimized for 'candidates' list and can be very slow"); } int N = gen ? gen->numberOfExamples() : -1; if (N<0) N = dcont->classes->cases; TSimpleRandomGenerator rgen(N); PDistribution classDistribution = dcont->classes; vector<bool>::const_iterator ci(candidates.begin()), ce(candidates.end()); TDiscDistribution *dis0, *dis1; TContDistribution *con0, *con1; int thisAttr = 0; bestAttr = -1; wins = 0; quality = 0.0; float leftExamples, rightExamples; TDomainContingency::iterator dci(dcont->begin()), dce(dcont->end()); for(; (cse || (ci!=ce)) && (dci!=dce); dci++, thisAttr++) { // We consider the attribute only if it is a candidate, discrete and has at least two values if ((cse || *(ci++)) && ((*dci)->outerVariable->varType==TValue::INTVAR) && ((*dci)->discrete->size()>=2)) { const TDistributionVector &distr = *(*dci)->discrete; if (distr.size()>16) raiseError("'%s' has more than 16 values, cannot exhaustively binarize", gen->domain->attributes->at(thisAttr)->get_name().c_str()); // If the attribute is binary, we check subsetSizes and assess the quality if they are OK if (distr.size()==2) { if ((distr.front()->abs<minSubset) || (distr.back()->abs<minSubset)) continue; // next attribute else { float thisMeas = measure->call(thisAttr, dcont, apriorClass); if ( ((!wins || (thisMeas>quality)) && ((wins=1)==1)) || ((thisMeas==quality) && rgen.randbool(++wins))) { bestAttr = thisAttr; quality = thisMeas; leftExamples = distr.front()->abs; rightExamples = distr.back()->abs; bestMapping = mlnew TIntList(2, 0); bestMapping->at(1) = 1; } continue; } } vector<int> valueIndices; int ind = 0; for(TDistributionVector::const_iterator dvi(distr.begin()), dve(distr.end()); (dvi!=dve); dvi++, ind++) if ((*dvi)->abs>0) valueIndices.push_back(ind); if (valueIndices.size()<2) continue; PContingency cont = prepareBinaryCheat(classDistribution, *dci, bvar, dis0, dis1, con0, con1); // A real job: go through all splits int binWins = 0; float binQuality = -1.0; float binLeftExamples = -1.0, binRightExamples = -1.0; // Selection: each element correspons to a value of the original attribute and is 1, if the value goes right // The first value always goes left (and has no corresponding bit in selection. TBoolCount selection(valueIndices.size()-1), bestSelection(0); // First for discrete classes if (dis0) { do { *dis0 = CAST_TO_DISCDISTRIBUTION(distr[valueIndices[0]]); *dis1 *= 0; vector<int>::const_iterator ii(valueIndices.begin()); ii++; for(TBoolCount::const_iterator bi(selection.begin()), be(selection.end()); bi!=be; bi++, ii++) *(*bi ? dis1 : dis0) += distr[*ii]; cont->outerDistribution->setint(0, dis0->abs); cont->outerDistribution->setint(1, dis1->abs); if ((dis0->abs < minSubset) || (dis1->abs < minSubset)) continue; // cannot split like that, to few examples in one of the branches float thisMeas = measure->operator()(cont, classDistribution, apriorClass); if ( ((!binWins) || (thisMeas>binQuality)) && ((binWins=1) ==1) || (thisMeas==binQuality) && rgen.randbool(++binWins)) { bestSelection = selection; binQuality = thisMeas; binLeftExamples = dis0->abs; binRightExamples = dis1->abs; } } while (selection.next()); } // And then exactly the same for continuous classes else { do { *con0 = CAST_TO_CONTDISTRIBUTION(distr[0]); *con1 = TContDistribution(); vector<int>::const_iterator ii(valueIndices.begin()); for(TBoolCount::const_iterator bi(selection.begin()), be(selection.end()); bi!=be; bi++, ii++) *(*bi ? con1 : con0) += distr[*ii]; if ((con0->abs<minSubset) || (con1->abs<minSubset)) continue; // cannot split like that, to few examples in one of the branches float thisMeas = measure->operator()(cont, classDistribution, apriorClass); if ( ((!binWins) || (thisMeas>binQuality)) && ((binWins=1) ==1) || (thisMeas==binQuality) && rgen.randbool(++binWins)) { bestSelection = selection; binQuality = thisMeas; binLeftExamples = con0->abs; binRightExamples = con1->abs; } } while (selection.next()); } if ( binWins && ( (!wins || (binQuality>quality)) && ((wins=1)==1) || (binQuality==quality) && rgen.randbool(++wins))) { bestAttr = thisAttr; quality = binQuality; leftExamples = binLeftExamples; rightExamples = binRightExamples; bestMapping = mlnew TIntList(distr.size(), -1); vector<int>::const_iterator ii = valueIndices.begin(); bestMapping->at(*(ii++)) = 0; ITERATE(TBoolCount, bi, bestSelection) bestMapping->at(*(ii++)) = *bi ? 1 : 0; } } } if (!wins) return returnNothing(descriptions, subsetSizes, quality, spentAttribute); subsetSizes = mlnew TDiscDistribution(); subsetSizes->addint(0, leftExamples); subsetSizes->addint(1, rightExamples); } PVariable attribute = gen->domain->attributes->at(bestAttr); if (attribute->noOfValues() == 2) { spentAttribute = bestAttr; descriptions = mlnew TStringList(attribute.AS(TEnumVariable)->values.getReference()); TClassifierFromVarFD *cfv = mlnew TClassifierFromVarFD(attribute, gen->domain, bestAttr, subsetSizes); cfv->transformUnknowns = false; return cfv; } string s0, s1; int ns0 = 0, ns1 = 0; TValue ev; attribute->firstValue(ev); PITERATE(TIntList, mi, bestMapping) { string str; attribute->val2str(ev, str); if (*mi==1) { s1 += string(ns1 ? ", " : "") + str; ns1++; } else if (*mi==0) { s0 += string(ns0 ? ", " : "") + str; ns0++; } attribute->nextValue(ev); }
PClassifier TTreeSplitConstructor_Combined::operator()( PStringList &descriptions, PDiscDistribution &subsetSizes, float &quality, int &spentAttribute, PExampleGenerator gen, const int &weightID , PDomainContingency dcont, PDistribution apriorClass, const vector<bool> &candidates, PClassifier nodeClassifier ) { checkProperty(discreteSplitConstructor); checkProperty(continuousSplitConstructor); vector<bool> discrete, continuous; bool cse = candidates.size()==0; vector<bool>::const_iterator ci(candidates.begin()), ce(candidates.end()); TVarList::const_iterator vi(gen->domain->attributes->begin()), ve(gen->domain->attributes->end()); for(; (cse || (ci!=ce)) && (vi!=ve); vi++) { if (cse || *(ci++)) if ((*vi)->varType == TValue::INTVAR) { discrete.push_back(true); continuous.push_back(false); continue; } else if ((*vi)->varType == TValue::FLOATVAR) { discrete.push_back(false); continuous.push_back(true); continue; } discrete.push_back(false); continuous.push_back(false); } float discQuality; PStringList discDescriptions; PDiscDistribution discSizes; int discSpent; PClassifier discSplit = discreteSplitConstructor->call(discDescriptions, discSizes, discQuality, discSpent, gen, weightID, dcont, apriorClass, discrete, nodeClassifier); float contQuality; PStringList contDescriptions; PDiscDistribution contSizes; int contSpent; PClassifier contSplit = continuousSplitConstructor->call(contDescriptions, contSizes, contQuality, contSpent, gen, weightID, dcont, apriorClass, continuous, nodeClassifier); int N = gen ? gen->numberOfExamples() : -1; if (N<0) N = dcont->classes->cases; if ( discSplit && ( !contSplit || (discQuality>contQuality) || (discQuality==contQuality) && (N%2>0))) { quality = discQuality; descriptions = discDescriptions; subsetSizes = discSizes; spentAttribute = discSpent; return discSplit; } else if (contSplit) { quality = contQuality; descriptions = contDescriptions; subsetSizes = contSizes; spentAttribute = contSpent; return contSplit; } else return returnNothing(descriptions, subsetSizes, quality, spentAttribute); }
/** * unpack does exactly the opposite from pack, it will take a data buffer * and load this object with the contents. If we need more data than the * size claims that we have, then we have a corrupt buffer and we will * throw an exception. */ void System::unpack( const void* payload ) { u32 size = 0, netOrder; char* packed = (char*) payload; char* next = packed;; string item; if( payload == NULL ) { // Rather than throwing an exception, this will just return, if NULL is handed in // this far there is nothing that we can do to stop program instability other // than refuse to mess with it. return; } // Load the size of the payload. (It is packed in network order) memcpy( &netOrder, next, sizeof( u32 ) ); size = ntohl( netOrder ); next += sizeof( u32 ); memcpy( &netOrder, next, sizeof( u32 ) ); mCPUCount = ntohl( netOrder ); next += sizeof( u32 ); mChildren = vector<string>( ); mDeviceSpecific = vector<DataItem*>( ); mIdNode = DataItem( next ); next += mIdNode.getPackedLength( ); if( next > packed + size ) { goto lderror; } mArch = DataItem( next ); next += mArch.getPackedLength( ); if( next > packed + size ) { goto lderror; } deviceTreeNode = DataItem( next ); next += deviceTreeNode.getPackedLength( ); if( next > packed + size ) { goto lderror; } mDescription = DataItem( next ); next += mDescription.getPackedLength( ); if( next > packed + size ) { goto lderror; } mBrand = DataItem( next ); next += mBrand.getPackedLength( ); if( next > packed + size ) { goto lderror; } mNodeName = DataItem( next ); next += mNodeName.getPackedLength( ); if( next > packed + size ) { goto lderror; } mOS = DataItem( next ); next += mOS.getPackedLength( ); if( next > packed + size ) { goto lderror; } mProcessorID = DataItem( next ); next += mProcessorID.getPackedLength( ); if( next > packed + size ) { goto lderror; } mMachineType = DataItem( next ); next += mMachineType.getPackedLength( ); if( next > packed + size ) { goto lderror; } mMachineModel = DataItem( next ); next += mMachineModel.getPackedLength( ); if( next > packed + size ) { goto lderror; } mFeatureCode = DataItem( next ); next += mFeatureCode.getPackedLength( ); if( next > packed + size ) { goto lderror; } mFlagField = DataItem( next ); next += mFlagField.getPackedLength( ); if( next > packed + size ) { goto lderror; } mRecordType = DataItem( next ); next += mRecordType.getPackedLength( ); if( next > packed + size ) { goto lderror; } mSerialNum1 = DataItem( next ); next += mSerialNum1.getPackedLength( ); if( next > packed + size ) { goto lderror; } mSerialNum2 = DataItem( next ); next += mSerialNum2.getPackedLength( ); if( next > packed + size ) { goto lderror; } mSUID = DataItem( next ); next += mSUID.getPackedLength( ); if( next > packed + size ) { goto lderror; } mKeywordVersion = DataItem( next ); next += mKeywordVersion.getPackedLength( ); if( next > packed + size ) { goto lderror; } mLocationCode = DataItem( next ); next += mLocationCode.getPackedLength( ); if( next > packed + size ) { goto lderror; } // Now onto the vectors, these should go much the same way that the packing // did. if( next == CHILD_START ) { next += CHILD_START.length( ) + 1; if( next > packed + size ) { goto lderror; } item = string( (char*)next ); while( CHILD_END != item ) { if( item != string( "" ) ) { string child = string( (char*)next ); mChildren.push_back( child ); next += item.length( ); } next++; item = string( (char*)next ); } next += CHILD_END.length( ) + 1; } if( DEVICE_START == next ) { next += DEVICE_START.length( ) + 1; if( next > packed + size ) { goto lderror; } item = string( (char*) next ); while( DEVICE_END != item ) { DataItem* d = new DataItem( next ); if ( d == NULL ) { VpdException ve( "Out of memory." ); throw ve; } next += d->getPackedLength( ); if( next > packed + size ) { delete ( d ); goto lderror; } mDeviceSpecific.push_back( d ); item = string( (char*)next ); } next += DEVICE_END.length( ) + 1; } if( USER_START == next ) { next += USER_START.length( ) + 1; if( next > packed + size ) { goto lderror; } item = string( (char*) next ); while( USER_END != item ) { DataItem* d = new DataItem( next ); if ( d == NULL ) { VpdException ve( "Out of memory." ); throw ve; } next += d->getPackedLength( ); if( next > packed + size ) { delete ( d ); goto lderror; } mDeviceSpecific.push_back( d ); item = string( (char*)next ); } } return; lderror: string message( "Component.unpack( ): Attempting to unpack corrupt buffer." ); Logger l; l.log( message, LOG_ERR ); VpdException ve( message ); throw ve; }
static void Test( ) { std::cout << std::endl << __FUNCTION__ << std::endl << std::endl; //VektorType v1((NUMERISCH)1,(NUMERISCH)2,(NUMERISCH)3); //VektorType v2((NUMERISCH)5,(NUMERISCH)7,(NUMERISCH)13); NUMERISCH ke[Dim] = { 1, 2 }; VektorType ve( ke ); std::cout << "\t" << ve << std::endl; NUMERISCH k1[Dim] = { 1, 2, 3 }; NUMERISCH k2[Dim] = { 5, 7, 13 }; NUMERISCH k3[Dim] = {-7, 8, 9 }; NUMERISCH k4[Dim] = { 6, 9, 16 }; VektorType v1( k1 ); VektorType v2( k2 ); std::cout << "\t" << (std::string) v1 << std::endl; std::cout << "\t" << v1 << std::endl; std::cout << "+\t" << v2 << std::endl; VektorType x = v1+v2; VektorType e( k4 ); std::cout << "=\t" << x << std::endl<< std::endl; assert( x == e ); v1 = VektorType( k1 ); v2 = VektorType( k3 ); std::cout << "\t" << v1 << std::endl; std::cout << "*\t" << v2 << std::endl; std::cout << "=\t" << v1*v2 << std::endl << std::endl; assert( v1*v2 == 36 ); VektorType c( v1 ); assert( c.id() != v1.id() ); assert( c == v1 ); try { std::cout << typeid( NUMERISCH ).name() << " x = vektor[-1]" << std::endl; NUMERISCH x = v1[-1]; assert( ! "Fehler erwartet!" ); } catch( const Fehler& e ) { std::cout << "Erwarteter Fehler: " << e.what() << std::endl; } try { std::cout << typeid( NUMERISCH ).name() << "vektor[-1] = 0" << std::endl; v1[-1] = 0; assert( ! "Fehler erwartet!" ); } catch( const Fehler& e ) { std::cout << "Erwarteter Fehler: " << e.what() << std::endl; } NUMERISCH f(2); VektorType vMul = v1 * f; NUMERISCH kMul[Dim] = { v1[0] * f, v1[1] * f, v1[2] * f }; std::cout << "\t" << v1 << std::endl; std::cout << "*\t" << f << std::endl; std::cout << "=\t" << v1*f << std::endl << std::endl; assert( v1*f == VektorType( kMul ) ); VektorType vDiv = v1 * f; NUMERISCH kDiv[Dim] = { v1[0] / f, v1[1] / f, v1[2] / f }; std::cout << "\t" << v1 << std::endl; std::cout << "/\t" << f << std::endl; std::cout << "=\t" << v1/f << std::endl << std::endl; assert( v1/f == VektorType( kDiv ) ); std::cout << __FUNCTION__ << " all test done. " << std::endl << std::endl; }
TEST(VectorEffects, UnknownBase) { VectorEffects ve(SetElem, Type::PtrToCell, Type::Int, Type::Obj); EXPECT_TEQ(Type::PtrToCell, ve.baseType); EXPECT_FALSE(ve.baseTypeChanged); EXPECT_TRUE(ve.baseValChanged); }
void rasterizer::draw_line(int x0, int y0, int x1, int y1, const zerging::color_rgba8 &c0, const zerging::color_rgba8 &c1) { int w = surface_->get_width(); int h = surface_->get_height(); if ((x0 < 0 || x0 > w) && (y0 < 0 || y0 > h) && (x1 < 0 || x1 > w) && (y1 < 0 || y1 > h)) { // out of screen space... return; } x0 = math::clamp<int>(x0, 0, w); y0 = math::clamp<int>(y0, 0, h); x1 = math::clamp<int>(x1, 0, w); y1 = math::clamp<int>(y1, 0, h); if (x0 == x1 && y0 == y1) { surface_->set_texel(x0, y0, 1, c1); return; } vec2 vs((float)x0, (float)y0); vec2 ve((float)x1, (float)y1); vec2 delta = ve - vs; auto func = [&](bool xmajor, int vmi, int vma, int vmt) { float delta_flag = 0.f; const vec2* start; const vec2* end; const color_rgba8* cs; const color_rgba8* ce; if (xmajor) { delta_flag = delta.x; } else { delta_flag = delta.y; } float diff_dir = math::abs(delta.x) > math::abs(delta.y) ? delta.x : delta.y; if (delta_flag < 0) { start = &ve; end = &vs; cs = &c1; ce = &c0; diff_dir = -diff_dir; } else { start = &vs; end = &ve; cs = &c0; ce = &c1; } float fs = 0.f, fe = 0.f; if (xmajor) { fs = start->x; fe = end->x; } else { fs = start->y; fe = end->y; } int is = (int)math::floor(fs + 0.5f); int ie = (int)math::floor(fe - 0.5f); is = math::clamp<int>(is, vmi, int(vma - 1)); ie = math::clamp<int>(ie, vmi, int(vma)); // set the attribute of start point float step = is + 0.5f - fs; vec2 output = *start + (*end - *start) * step / diff_dir; for (int i = is; i < ie; ++i) { float ot, dt; if (xmajor) { ot = output.y; dt = delta.y; } else { ot = output.x; dt = delta.x; } if (ot >= vmt) { if (dt > 0) break; continue; } if (ot < 0) { if (dt < 0) break; continue; } ++step; float st_dir = step / diff_dir; surface_->set_texel((size_t)output.x, (size_t)output.y, 1, lerp(*cs, *ce, st_dir)); output = *start + (*end - *start) * st_dir; } }; if (math::abs(delta.x) > math::abs(delta.y)) { func(true, vp_left_, vp_right_, vp_bottom_); } else { func(false, vp_top_, vp_bottom_, vp_right_); } }
TEST(VectorEffects, NonArrElem) { VectorEffects ve(SetElem, Type::PtrToDbl, Type::Int, Type::Obj); EXPECT_TEQ(Type::PtrToDbl, ve.baseType); EXPECT_FALSE(ve.baseTypeChanged); EXPECT_FALSE(ve.baseValChanged); }
double Trainer::earlyStopping(Optimizer& Optimizer, ErrorFunction& errFct, Array<double>& in, Array<double>& target, size_t validatonSize) { ValidationError ve(&errFct, &Optimizer, 1000, double(validatonSize)/100); return ve.error(model.getModel(), in, target); }
TEST(VectorEffects, BadArrayKey) { VectorEffects ve(SetElem, Type::PtrToArr, Type::Arr, Type::Int); EXPECT_TEQ(Type::PtrToArr, ve.baseType); EXPECT_FALSE(ve.baseTypeChanged); EXPECT_TRUE(ve.baseValChanged); }
void ProjectView::OnQuit() { ViewEvent ve(VET_QUIT_APP) ; SetChanged(); NotifyObservers(&ve) ; } ;
/** * pack serializes this object into the provided buffer (pack will allocate the * buffer) storing only the data fields (at the moment) and ignoring all the meta- * data within the DataItem object. The format for the packed object will be * direct strings seperated by '\0' charaters. If a given string field is empty * then there will be consectutive '\0' characters. Each of the vector fields will * be preceeded by ::listNameStart:: and followed by ::listNameEnd:: (e.g. the * children vector will be ::childrenStart::\0data\0data\0::childrenEnd::\0). */ unsigned int System::pack( void** buffer ) { u32 ret = getPackedSize( ), length; char* buf; buf = new char[ ret ]; if( buf == NULL ) { string message( "Component.pack( ): new call failed, out of memory." ); Logger l; l.log( message, LOG_ERR ); VpdException ve( message ); throw ve; } memset( buf, '\0', ret ); *buffer = (void*)buf; /* -----------------------------------------------------*/ /* ------------ Load up the buffer with data -----------*/ /* -----------------------------------------------------*/ // The first entry in our buffer is our length in network byte order u32 netOrder = htonl( ret ); memcpy( buf, &netOrder, sizeof( u32 ) ); buf += sizeof( u32 ); // Next is our system CPU count. netOrder = htonl( mCPUCount ); memcpy( buf, &netOrder, sizeof( u32 ) ); buf += sizeof( u32 ); // Pack the individual data items. length = mIdNode.pack( buf ); buf += length; length = mArch.pack( buf ); buf += length; length = deviceTreeNode.pack( buf ); buf += length; length = mDescription.pack( buf ); buf += length; length = mBrand.pack( buf ); buf += length; length = mNodeName.pack( buf ); buf += length; length = mOS.pack( buf ); buf += length; length = mProcessorID.pack( buf ); buf += length; length = mMachineType.pack( buf ); buf += length; length = mMachineModel.pack( buf ); buf += length; length = mFeatureCode.pack( buf ); buf += length; length = mFlagField.pack( buf ); buf += length; length = mRecordType.pack( buf ); buf += length; length = mSerialNum1.pack( buf ); buf += length; length = mSerialNum2.pack( buf ); buf += length; length = mSUID.pack( buf ); buf += length; length = mKeywordVersion.pack( buf ); buf += length; length = mLocationCode.pack( buf ); buf += length; // Pack the child vector. memcpy( buf, CHILD_START.c_str( ), CHILD_START.length( ) ); buf += CHILD_START.length( ); *buf = '\0'; buf++; vector<string>::iterator child, cEnd; vector<DataItem*>::iterator item, dEnd; for( child = mChildren.begin( ), cEnd = mChildren.end( ); child != cEnd; ++child ) { const char* str = (*child).c_str( ); int length = (*child).length( ); memcpy( buf, str, length ); buf+= length; *buf = '\0'; buf++; } memcpy( buf, CHILD_END.c_str( ), CHILD_END.length( ) ); buf += CHILD_END.length( ); *buf = '\0'; buf++; // Pack the Device Specific vector memcpy( buf, DEVICE_START.c_str( ), DEVICE_START.length( ) ); buf += DEVICE_START.length( ); *buf = '\0'; buf++; for( item = mDeviceSpecific.begin( ), dEnd = mDeviceSpecific.end( ); item != dEnd; ++item ) { length = (*item)->pack( buf ); buf+= length; } memcpy( buf, DEVICE_END.c_str( ), DEVICE_END.length( ) ); buf += DEVICE_END.length( ); *buf = '\0'; buf++; // Pack the User Data vector memcpy( buf, USER_START.c_str( ), USER_START.length( ) ); buf += USER_START.length( ); *buf = '\0'; buf++; for( item = mUserData.begin( ), dEnd = mUserData.end( ); item != dEnd; ++item ) { length = (*item)->pack( buf ); buf+= length; } memcpy( buf, USER_END.c_str( ), USER_END.length( ) ); buf += USER_END.length( ); *buf = '\0'; buf++; return ret; }
TEST(VectorEffects, NonObjProp) { VectorEffects ve(SetProp, Type::PtrToInt, Type::Str, Type::Dbl); EXPECT_TEQ(Type::PtrToInt, ve.baseType); EXPECT_FALSE(ve.baseTypeChanged); EXPECT_FALSE(ve.baseValChanged); }
int main(void) { out("starting ...\n"); std::cout << " MaxFlow " << std::endl; int N; //test cases scanf("%d\n", &N); out("N %d\n",N); int ord = 0; while(N-- > 0) { char * buff = NULL; graphtp g; size_t n; int m; //nodes scanf("%d\n", &m); out("m %d\n",m); int counter = 0; for(int i = 0; i < m; i++) { g.push_back(ve()); } out("size of g %d\n",g.size()); while(counter++ < m && getline(&buff, &n, stdin) != -1 ) { out("this is buff ='%s'\n", buff); char * tok = strtok(buff, " \n\t"); out("this is node ='%s'\n", tok); int nodefrom = atoi(tok); assert(nodefrom < m && "nodefrom is more than m"); if(tok == NULL) { printf("Error in input file"); exit(1); } tok = strtok(NULL, " \n\t"); while(tok > 0) { int nodeto = atoi(tok); if(nodeto < m) { out("red (node) tok='%s'\n", tok); } else { printf("ERROR: node %d outside of range (max %d)\n", nodeto,m); } tok = strtok(NULL, " \n\t"); if(tok == NULL) printf("ERROR: capacity must be given for each link \n"); float capacity = atof(tok); out("read (capacity) tok='%s'\n", tok); edge e; e.from = nodefrom; e.to = nodeto; e.flow = 0; e.capacity = capacity; e.backedge = false; g[nodefrom].push_back(e); out("inserting %d -> %d\n", nodefrom, nodeto); e.to = nodefrom; e.from = nodeto; e.backedge = true; g[nodeto].push_back(e); out("inserting %d -> %d\n", nodeto, nodefrom); tok = strtok(NULL, " \n\t"); } out("size of g %d\n",g.size()); } printf("Case %d:\n", ++ord); print_graph(g); MaxFlow(g, 0, g.size() - 1); printf("\n"); } return 0; }