bool PodSync::processOneItem( FileInfo *pSrcInfo, FileInfo *pDstInfo ) { FileInfo info; // Assume things are ok bool result = true; const char *srcFileName; srcFileName = basename( pSrcInfo->getName() ); // + 2 for the path separator and the final 0 char *dstFileName = new char[ strlen( pDstInfo->getName() ) + strlen( srcFileName ) + 2 ]; strcpy( dstFileName, pDstInfo->getName() ); strcat( dstFileName, "/" ); strcat( dstFileName, srcFileName ); rInfo( "Processing %s", pSrcInfo->getName() ); // Ok, destination does not exist, copy if( false == info.getInfo( dstFileName )) { if( false == pSrcInfo->isDir() ) { rInfo( "Copying %s to %s as it does not exist", pSrcInfo->getName(), dstFileName ) ; result = copy( pSrcInfo->getName(), dstFileName ); } else { // Current item in src is a dir, recurse const char *srcBaseName = basename( pSrcInfo->getName() ); char *pNewDst = new char[ strlen( pDstInfo->getName() ) + strlen( srcBaseName ) + 2 ]; strcpy( pNewDst, pDstInfo->getName() ); strcat( pNewDst, "/" ); strcat( pNewDst, srcBaseName ); performSync( pSrcInfo->getName(), pNewDst ); delete[] pNewDst; } } else { // Destination is older that source, copy if( info.getModificationTime() < pSrcInfo->getModificationTime() ) { rInfo( "Copying %s to %s as it is newer", pSrcInfo->getName(), dstFileName ) ; result = copy( pSrcInfo->getName(), dstFileName ); } else { rInfo( "Skipping %s as %s is up-to-date", pSrcInfo->getName(), dstFileName ) ; } } delete[] dstFileName; return result; }
void fill_simplex_set(const Delaunay3D& Dt, AlphaSimplex3D::SimplexSet& simplices) { // Compute all simplices with their alpha values and attachment information for(Cell_iterator cur = Dt.finite_cells_begin(); cur != Dt.finite_cells_end(); ++cur) simplices.insert(AlphaSimplex3D(*cur)); rInfo("Cells inserted"); for(Facet_iterator cur = Dt.finite_facets_begin(); cur != Dt.finite_facets_end(); ++cur) simplices.insert(AlphaSimplex3D(*cur, simplices, Dt)); rInfo("Facets inserted"); for(Edge_iterator cur = Dt.finite_edges_begin(); cur != Dt.finite_edges_end(); ++cur) simplices.insert(AlphaSimplex3D(*cur, simplices, Dt, Dt.incident_facets(*cur))); rInfo("Edges inserted"); for(Vertex_iterator cur = Dt.finite_vertices_begin(); cur != Dt.finite_vertices_end(); ++cur) simplices.insert(AlphaSimplex3D(*cur)); rInfo("Vertices inserted"); }
btRigidBody* Physics::CreateRigidBody( const float mass, const CIwFVec3 position, const CIwFVec3 rotation, btCollisionShape* shape ) { btRigidBody* rigidBody; btTransform startTransform; startTransform.setIdentity(); startTransform.setOrigin( btVector3( position.x, position.y, position.z ) ); btQuaternion q; CIwFVec3 rot = rotation * static_cast<float>( BPU_PI_180 ); EulerXYZToQuaternion( rot, q ); startTransform.setRotation( q ); bool isDynamic = ( mass != 0.f ); // Rigidbody is dynamic if and only if mass is non zero, otherwise static btVector3 localInertia( 0, 0, 0 ); if( isDynamic ) { shape->calculateLocalInertia( mass, localInertia ); } // Using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects #ifdef USE_MOTIONSTATE btDefaultMotionState* motionState = new btDefaultMotionState( startTransform ); btRigidBody::btRigidBodyConstructionInfo rInfo( mass, motionState, shape, localInertia ); rigidBody = new btRigidBody( rInfo ); #else rigidBody = new btRigidBody( mass, 0, shape, localInertia ); rigidBody->setWorldTransform( startTransform ); #endif m_dynamicsWorld->addRigidBody( rigidBody ); return rigidBody; }
/** * \brief Reads components parameters and checks set integrity before signaling the Worker thread to start running * There can be four (4) types of parameteres: * (1) Ice parameters * (2) Nexus (configuration) parameters * (3) Local component parameters read at start * (4) Local parameters read from other running component * */ void Monitor::initialize() { rInfo("Starting monitor ..."); initialTime=QTime::currentTime(); RoboCompCommonBehavior::ParameterList params; readConfig(params ); if(!sendParamsToWorker(params)) { rError("Error reading config parameters. Exiting"); killYourSelf(); } state = RoboCompCommonBehavior::Running; }
bool PodSync::doSync( void ) { bool result = true; const char *pDst = m_pConfig->getString( "destination_directory" ); const char *pSrc = m_pConfig->getString( "source_directory" ); if( 0 != pDst && 0 != pSrc ) { rInfo( "Performing sync from %s to %s", pSrc, pDst ); if( true == performSync( pSrc, pDst )) { rInfo( "Sync completed" ); } else { rWarning( "Sync failed" ); } } else { rWarning( "Bad config" ); result = false; } return result; }
bool SpecificWorker::setParams(RoboCompCommonBehavior::ParameterList params) { busParams.device = params["muecasJoint.Device"].value; busParams.numMotors = QString::fromStdString(params["muecasJoint.NumMotors"].value).toInt(); busParams.baudRate = QString::fromStdString(params["muecasJoint.BaudRate"].value).toInt(); busParams.basicPeriod = QString::fromStdString(params["muecasJoint.BasicPeriod"].value).toInt(); for (int i=0; i<busParams.numMotors; i++) { std::string s= QString::number(i).toStdString(); RoboCompJointMotor::MotorParams mpar; mpar.name = params["muecasJoint.Params_" + s +".name"].value; mpar.busId = QString::fromStdString(params["muecasJoint.Params_" + s +".busId"].value).toUShort(); mpar.invertedSign = QString::fromStdString(params["muecasJoint.Params_" + s +".invertedSign"].value).contains("true"); mpar.minPos = QString::fromStdString(params["muecasJoint.Params_" + s +".minPos"].value).toFloat(); mpar.maxPos = QString::fromStdString(params["muecasJoint.Params_" + s +".maxPos"].value).toFloat(); mpar.zeroPos = QString::fromStdString(params["muecasJoint.Params_" + s +".zeroPos"].value).toFloat(); mpar.maxVelocity = QString::fromStdString(params["muecasJoint.Params_" + s +".maxVelocity"].value).toFloat(); motorParamsList.push_back(mpar); QString name = QString::fromStdString(mpar.name); mParams[name] = mpar; name2id[name] = mpar.busId; //servos motorsName[name] = new Servo( mpar ); motorsId[mpar.busId] = motorsName[name]; //TODO: Revisar los parametros de cada motor //setMotorRanges(float step_range, float degrees_range, float speed_step_range, float max_speed_rads); motorsName[name]->setMotorRanges(200, 360.f,0,0); } //Creacion de acceso dispositivo device.setName (QString::fromStdString(busParams.device) ); device.setBaudRate ( QSerialPort::BAUD9600);//cambiar por valor leido de los parametros if ( device.open ( QIODevice::ReadWrite ) == false ) { rError("Failed to open: "+QString::fromStdString(busParams.device)); qFatal("Error opening device"); } rInfo("Device "+QString::fromStdString(busParams.device)+" is open"); timer.start(Period); return true; }
/** * Flush oldest blocks to disk */ int ABFile::flushBlocks() { int flushed = 0; // Comp cmp; //std::sort(blocks.begin(),blocks.end(),cmp); while (mBlocks.size() > maxblocks) { //remove last and write to disk. blockmap::iterator it = mBlocks.begin(); blockmap::iterator oldestblock = it; for (; it != mBlocks.end(); it++) { if (it->second->mLastUse < oldestblock->second->mLastUse) oldestblock = it; } Block *b = oldestblock->second; mBlocks.erase(oldestblock); if (b->mDirty) { rInfo("Flushing block %d", b->mBlockNr); b->write(); } delete b; flushed++; } return flushed; }
std::vector< std::shared_ptr<Carta::Lib::RegionInfo> > RegionCASA::_loadRegion( const QString & fname, std::shared_ptr<Carta::Lib::Image::ImageInterface> imagePtr ){ std::vector<std::shared_ptr<Carta::Lib::RegionInfo> > regionInfos; casa::String fileName( fname.toStdString().c_str() ); CCImageBase * base = dynamic_cast<CCImageBase*>( imagePtr.get() ); if ( base ){ Carta::Lib::Image::MetaDataInterface::SharedPtr metaPtr = base->metaData(); CCMetaDataInterface* metaData = dynamic_cast<CCMetaDataInterface*>(metaPtr.get()); if ( metaData ){ std::shared_ptr<casa::CoordinateSystem> cs = metaData->getCoordinateSystem(); std::vector < int > dimensions = imagePtr->dims(); int dimCount = dimensions.size(); casa::IPosition shape(dimCount); for ( int i = 0; i < dimCount; i++ ){ shape[i] = dimensions[i]; } casa::RegionTextList regionList( fileName, *cs.get(), shape ); casa::Vector<casa::AsciiAnnotationFileLine> aaregions = regionList.getLines(); int regionCount = aaregions.size(); for ( int i = 0; i < regionCount; i++ ){ if ( aaregions[i].getType() != casa::AsciiAnnotationFileLine::ANNOTATION ){ continue; } casa::CountedPtr<const casa::AnnotationBase> ann = aaregions[i].getAnnotationBase(); std::shared_ptr<Carta::Lib::RegionInfo> rInfo( new Carta::Lib::RegionInfo()); casa::Vector<casa::MDirection> directions = ann->getConvertedDirections(); casa::AnnotationBase::Direction points = ann->getDirections(); std::vector<std::pair<double,double> > corners = _getPixelVertices( points, *cs.get(), directions ); int annType = ann->getType(); switch( annType ){ case casa::AnnotationBase::RECT_BOX : { _addCorners( rInfo, corners ); rInfo->setRegionType( Carta::Lib::RegionInfo::RegionType::Polygon ); } break; case casa::AnnotationBase::ELLIPSE : { rInfo->setRegionType( Carta::Lib::RegionInfo::RegionType::Ellipse ); const casa::AnnEllipse* ellipse = dynamic_cast<const casa::AnnEllipse*>( ann.get() ); casa::Int directionIndex = cs->findCoordinate(casa::Coordinate::Type::DIRECTION ); casa::MDirection::Types csType = casa::MDirection::EXTRA; if ( directionIndex >= 0 ){ casa::DirectionCoordinate dCoord = cs->directionCoordinate(directionIndex); csType = dCoord.directionType(); } if ( csType == casa::MDirection::EXTRA ){ qWarning( "Unable to complete elliptical region, unspecified direction type."); continue; } // convert to the viewer's world coordinates... <mdirection> casa::MDirection dir_center = casa::MDirection::Convert(ellipse->getCenter( ), csType)(); casa::Vector<double> center = dir_center.getAngle("rad").getValue( ); // 90 deg around 0 & 180 deg const double major_radius = ellipse->getSemiMajorAxis().getValue("rad"); const double minor_radius = ellipse->getSemiMinorAxis().getValue("rad"); const double pos_angle = ellipse->getPositionAngle( ).getValue("deg"); const bool x_is_major = ((pos_angle > 45.0 && pos_angle < 135.0) || (pos_angle > 225.0 && pos_angle < 315.0)); const double xradius = (x_is_major ? major_radius : minor_radius); const double yradius = (x_is_major ? minor_radius : major_radius); casa::Vector<casa::Double> world0(2, 0); casa::Vector<casa::Double> world1(2, 0); world0[0] = center[0] - xradius; world0[1] = center[1] - yradius; world1[0] = center[0] + xradius; world1[1] = center[1] + yradius; casa::Vector<casa::Double> pixel0(2, 0); casa::Vector<casa::Double> pixel1(2, 0); std::vector<std::pair<double,double> > ellipseCorners(2); const casa::CoordinateSystem ellipsCoord = ellipse->getCsys(); bool firstConvert = ellipsCoord.directionCoordinate().toPixel( pixel0, world0 ); bool secondConvert = ellipsCoord.directionCoordinate().toPixel( pixel1, world1 ); if ( firstConvert && secondConvert ){ ellipseCorners[0] = std::pair<double,double>( pixel0[0], pixel0[1] ); ellipseCorners[1] = std::pair<double,double>( pixel1[0], pixel1[1] ); _addCorners( rInfo, ellipseCorners ); } else { qDebug() << "Problem storing ellipse corners: "<<ellipsCoord.errorMessage().c_str(); } } break; case casa::AnnotationBase::POLYGON : { _addCorners( rInfo, corners ); rInfo->setRegionType( Carta::Lib::RegionInfo::RegionType::Polygon ); } break; //Point???? case casa::AnnotationBase::SYMBOL : { _addCorners( rInfo, corners ); rInfo->setRegionType( Carta::Lib::RegionInfo::RegionType::Polygon ); } break; } regionInfos.push_back( rInfo ); } } } return regionInfos; }
/** * \brief Change configurations parameters to worker * @param l Configuration parameters list */ void Monitor::setParameterList(RoboCompCommonBehavior::ParameterList l) { rInfo("Changing configuration params"); sendParamsToWorker(l); }
bool copy(const char *i, const char *o, const struct stat *i_st, const struct stat *o_st) { Compress input(i_st, i); int i_fd = input.open(i, O_RDONLY); if (i_fd == -1) { rError("File (%s) cannot be opened! (%s)", i, strerror(errno)); return false; } if (input.isCompressed() == false) { rInfo(" Not compressed"); if (g_RawOutput) { rInfo(" Skipped"); // Input file is not compressed an user wants // to decomrpess file. Return now. input.release(i); return false; } } else { rInfo(" Compressed"); if (g_RawOutput) { } else { if (input.isCompressedOnlyWith(g_CompressionType)) { rInfo(" All blocks compressed with the same compression method"); // Input file is compressed only with // the same compression type as user wants. // Return now. input.release(i); return false; } rInfo(" Some block(s) compressed with different compression method than others"); } } Compress output(o_st, o); if (g_RawOutput) { output.setCompressed(false); } boost::scoped_array<char> buffer(new char[g_BufferedMemorySize]); int o_fd = output.open(o, O_WRONLY); if (o_fd == -1) { rError("File (%s) cannot be opened! (%s)", o, strerror(errno)); input.release(i); return false; } // Get the apparent input file size. struct stat st; int r = input.getattr(i, &st); if (r == -1) { rError("Cannot determine apparent size of input file (%s) (%s)", i, strerror(errno)); input.release(i); return false; } rInfo(" Processing"); for (off_t off = 0; off < st.st_size; off += g_BufferedMemorySize) { if (g_BreakFlag) { rWarning("Interrupted when processing file (%s)", i); rWarning("File is left untouched"); input.release(i); output.release(o); return false; } off_t r = input.read(buffer.get(), g_BufferedMemorySize, off); if (r == -1) { rError("Read failed! (offset: %lld, size: %lld)", (unsigned long long) off ,(unsigned long long) g_BufferedMemorySize); input.release(i); output.release(o); return false; } off_t rr = output.write(buffer.get(), r, off); if (rr != r) { rError("Write failed! (offset: %lld, size: %lld)", (unsigned long long) off , (unsigned long long) r); input.release(i); output.release(o); return false; } } // Remember extended attributes. FileRememberXattrs xattrs; xattrs.read(i_fd); xattrs.write(o_fd); input.release(i); output.release(o); return true; }
int compress(const char *i, const struct stat *i_st, int mode, struct FTW *n) { if (!((mode == FTW_F) && (S_ISREG(i_st->st_mode)))) return 0; fs::path input(i #if BOOST_VERSION <= 104600 , fs::native #endif ); fs::path input_directory(input.branch_path()); fs::path output(input_directory / "XXXXXX"); rInfo("Processing file (%s)", input.string().c_str()); // Remember times of the input file. struct stat stbuf; lstat(input.string().c_str(), &stbuf); int o_fd = mkstemp(const_cast<char *>(output.string().c_str())); if (o_fd < 0) { rError("Failed to create an temporary file in (%s) directory", input_directory.string().c_str()); return -1; } rInfo("Temporary file (%s)", output.string().c_str()); struct stat o_st; if (fstat(o_fd, &o_st) == -1) { rError("Failed to read stat of temporary file (%s)", output.string().c_str()); close(o_fd); return -1; } close(o_fd); if (!copy(i, output.string().c_str(), i_st, &o_st)) { unlink(output.string().c_str()); return -1; } if (rename(output.string().c_str(), i) == -1) { rError("Failed to rename temporary file (%s) to (%s) (%s)", output.string().c_str(), input.string().c_str(), strerror(errno)); return -1; } if (chmod(i, i_st->st_mode) == -1) { rError("Failed to change mode (%s) (%s)", input.string().c_str(), strerror(errno)); return -1; } // Write back original times. struct timespec times[2]; times[0].tv_sec = stbuf.st_atime; times[0].tv_nsec = stbuf.st_atim.tv_nsec; times[1].tv_sec = stbuf.st_mtime; times[1].tv_nsec = stbuf.st_mtim.tv_nsec; utimensat(AT_FDCWD, i, times, AT_SYMLINK_NOFOLLOW); return 0; }
bool PodSync::OnDriveInserted( char drive ) { rInfo( "Media detected %c", drive ); return doSync(); }
bool PodSync::performSync( const char *pSrc, const char *pDst ) { DirectoryEnum srcEnumerator; DirectoryEnum dstEnumerator; FileInfo srcInfo; FileInfo dstInfo; FileInfo *pSrcInfo = &srcInfo; bool result = false; // Check that source is valid if( false == srcInfo.getInfo( pSrc )) { rWarning( "Could not get info: %s", pSrc ); return false; } // Check that destination is valid if( false == dstInfo.getInfo( pDst )) { rWarning( "Could not get info: %s", pDst ); if( false == makeDirs( pDst )) { rError( "Could not create destination: %s", pDst ); return false; } else { if( false == dstInfo.getInfo( pDst )) { rError( "Could not get info: %s", pDst ); return false; } } } // Check that destination is a directory if( false == dstInfo.isDir() ) { rError( "%s is not a directory", pDst ); return false; } rInfo( "Source: %s", srcInfo.getName() ); if( true == srcInfo.isDir() ) { rInfo( "Enumerating %s", srcInfo.getName() ); // Skip . and .. srcEnumerator.findFirst( pSrc ); srcEnumerator.findNext(); pSrcInfo = srcEnumerator.findNext(); while( 0 != pSrcInfo ) { result = processOneItem( pSrcInfo, &dstInfo ); if( false == result ) { rError( "Sync %s failed", pSrcInfo->getName() ); } pSrcInfo = srcEnumerator.findNext(); } } else { result = processOneItem( pSrcInfo, &dstInfo ); } return result; }
// (recursive part of DetermineSCCs()) void ComputationNetwork::DetermineSCCsR(ComputationNodeBasePtr cur, list<ComputationNodeBasePtr>& sccStack, size_t& index, size_t& loopId) { assert(!cur->m_visited); // set the index (in order of visitation) cur->m_index = index; // TODO: can this be used as m_visitedOrder? cur->m_minIndex = index; // also set m_minIndex index++; cur->m_visited = true; sccStack.push_back(cur); cur->m_inStack = true; // set m_minIndex to min over m_lowLinks of children for (int i = 0; i < cur->GetNumInputs(); i++) { if (!cur->Input(i)->m_visited) { DetermineSCCsR(cur->Input(i), sccStack, index, loopId); cur->m_minIndex = min(cur->m_minIndex, cur->Input(i)->m_minIndex); } else if (cur->Input(i)->m_inStack) { cur->m_minIndex = min(cur->m_minIndex, cur->Input(i)->m_minIndex); } } // if we closed a loop then create an entry in m_allSEQNodes if (cur->m_minIndex == cur->m_index) // m_minIndex is still equal to m_index, as we set it at the start of this function: we closed a loop { // gather the list of all nodes in this loop vector<ComputationNodeBasePtr> nestedNodes; // TODO: build array first in a local array. Only if succeeds, then construct the node off it. SEQTraversalFlowControlNode rInfo(m_allSEQNodes.size() /*loopId*/, cur); for (;;) { ComputationNodeBasePtr w = sccStack.back(); sccStack.pop_back(); w->m_inStack = false; nestedNodes.push_back(w); if (w == cur) // hit our starting point: done break; } // insert loop into m_allSEQNodes if (nestedNodes.size() > 1) // non-looped nodes are detected here as loops of size 1 --skip those { // only add to the array if the loop is not already there // We end up producing the same loop multiple times because: // - FormRecurrentLoops() is called multiple times from different roots // - depth-first traversal might have led us to enter a loop multiple times? // TODO: Check whether this edge case of idempotence is done correctly: // - a recurrent loop with two delay nodes // - two root nodes // - the first root takes the first delay node's value, the second root that of the second delay node // I.e. the depth-first tree traversals enter the loop at two different places (m_sourceNode). // -> Are these two loops detected as identical? (determined by m_minIndex, but m_index depends on traversal from each root, so maybe not) bool bFound = false; // find a dup --TODO: check whether there is an STL algorithm for this for (const auto& iter2 : m_allSEQNodes) { if (iter2->m_sourceNode == cur) { bFound = true; break; } } if (!bFound) { #if 1 if (loopId != m_allSEQNodes.size()) LogicError("DetermineSCCsR(): inconsistent loopId (%d) vs. m_allSEQNodes.size() (%d)", (int) loopId, (int) m_allSEQNodes.size()); SEQTraversalFlowControlNode rInfo(m_allSEQNodes.size(), cur); #else assert(loopId == m_allSEQNodes.size()); // BUGBUG: Only true if all loops are shared among roots. Fix: use m_allSEQNodes.size() instead SEQTraversalFlowControlNode rInfo(loopId, cur); #endif // TODO: can we prove that 'cur' == nestedNodes.front()? If so, we won't need to store it separately. rInfo.m_nestedNodes = move(nestedNodes); // TODO: make these two part of the constructor rInfo.m_steppingDirection = DetermineLoopDirection(rInfo.m_nestedNodes); m_allSEQNodes.push_back(make_shared<SEQTraversalFlowControlNode>(move(rInfo))); loopId++; // and count it TODO: may be removed } } } }