예제 #1
0
void simplifyPFBlock(const Edges& toUnlink, const PFBlock& block, Blocks& simplifiedBlocks, Nodes& history) {
  // take a block, unlink some of the edges and
  // create smaller blocks or a simplified blocks
  // or if nothing has changed take a copy of the original block
  if (toUnlink.size() == 0) {
    // no change needed, just make a copy of block
    PFBlock newblock(block.elementIds(), block.edges(), simplifiedBlocks.size(), 's');  // will copy edges and ids
    PDebug::write("Made {}", newblock);
    auto id = newblock.id();
    simplifiedBlocks.emplace(id, std::move(newblock));
    // update history
    makeHistoryLinks(block.elementIds(), {id}, history);
  } else {
    Edges modifiedEdges;
    for (auto edge : block.edges()) {  // copying edges
      Edge e = edge.second;
      if (toUnlink.find(edge.first) != toUnlink.end()) {
        e.setLinked(false);
      }
      modifiedEdges.emplace(e.key(), e);
    }
    // create new blocks and add into simplifiedBlocks
    buildPFBlocks(block.elementIds(), modifiedEdges, 's', simplifiedBlocks, history);
  }
}
예제 #2
0
파일: block.cpp 프로젝트: asr1/xoreos-tools
static bool addBranchBlock(Blocks &blocks, Block &block,
                           const Instruction &branchDestination,
                           Block *&branchBlock, BlockEdgeType type) {

	/* Prepare to follow one branch of the path.
	   Returns true if this is a completely new path we haven't handled yet.
	   branchBlock will be filled with the block for the branch. */

	bool needAdd = false;

	// See if we have already handled this branch. If not, create a new block for it.
	branchBlock = const_cast<Block *>(branchDestination.block);
	if (!branchBlock) {
		blocks.push_back(Block(branchDestination.address));

		branchBlock = &blocks.back();
		needAdd     = true;
	}

	// Link the branch with its parent

	branchBlock->parents.push_back(&block);
	block.children.push_back(branchBlock);

	block.childrenTypes.push_back(type);

	return needAdd;
}
예제 #3
0
void puzzle_i()
{
    Blocks bs;
    Board board(5, 6);

    bs.push_back(&(*(new Block()))("***"));
    bs.push_back(&(*(new Block()))("***| *| *"));
    bs.push_back(&(*(new Block()))("**|**"));
    bs.push_back(&(*(new Block()))("*|**"));
    bs.push_back(&(*(new Block()))(" **| *|**"));
    bs.push_back(&(*(new Block()))("*|*"));
    bs.push_back(&(*(new Block()))("***|  *"));
    bs.push_back(&(*(new Block()))("*|**| *"));

    cout << "---------- Puzzle I ----------" << endl;

    if (!board.Unblock(bs))
    {
        cout << "No solution!" << endl;
    }

    for (auto i = bs.cbegin(); i != bs.cend(); i++)
    {
        delete (*i);
    }
}
예제 #4
0
// Start solving the problem.
bool Board::Unblock(Blocks bs)
{
    count_setblock = 0;
    count_checkblock = 0;
    count_setcell = 0;
    count_checkcell = 0;

    // Sort Blocks by block weight
    sort(bs.begin(), bs.end(), [](Block *a, Block *b)
    {
        return (a->weight > b->weight);
    });

    for (auto i = bs.cbegin(); i != bs.cend(); i++)
    {
        (*i)->Print("Block " + to_string(i - bs.cbegin()));
    }

    // Find solution
    bool result = RecursiveSetBlock(bs, 0);

    cout << "count_setblock   = " << count_setblock << endl
         << "count_checkblock = " << count_checkblock << endl
         << "count_setcell    = " << count_setcell << endl
         << "count_checkcell  = " << count_checkcell << endl;

    return result;
}
예제 #5
0
 ~CFGCalculator() {
   for(Blocks::iterator i = blocks_.begin();
       i != blocks_.end();
       i++) {
     delete i->second;
   }
 }
예제 #6
0
파일: PatchMgr.C 프로젝트: Zirkon/dyninst
void PatchMgr::getBlockCandidates(Scope &scope, Point::Type types, Candidates &ret) {
   Blocks blocks;
   getBlocks(scope, blocks);
   for (Blocks::iterator iter = blocks.begin(); iter != blocks.end(); ++iter) {
      if (types & Point::BlockEntry) ret.push_back(Candidate(Location::Block(*iter), Point::BlockEntry));
      if (types & Point::BlockDuring) ret.push_back(Candidate(Location::Block(*iter), Point::BlockDuring));
      if (types & Point::BlockExit) ret.push_back(Candidate(Location::Block(*iter), Point::BlockExit));
   }
}
예제 #7
0
파일: block.cpp 프로젝트: asr1/xoreos-tools
void constructBlocks(Blocks &blocks, Instructions &instructions) {
	/* Create the first block containing the very first instruction in this script.
	 * Then follow the complete code flow from this instruction onwards. */

	assert(blocks.empty());
	if (instructions.empty())
		return;

	blocks.push_back(Block(instructions.front().address));
	constructBlocks(blocks, blocks.back(), instructions.front());
}
예제 #8
0
파일: PatchMgr.C 프로젝트: Zirkon/dyninst
void PatchMgr::getInsns(Scope &scope, Insns &insns) {
   Blocks blocks;
   getBlocks(scope, blocks);

   for (Blocks::iterator iter = blocks.begin(); iter != blocks.end(); ++iter) {
      PatchBlock::Insns tmp;
      (*iter)->getInsns(tmp);
      for (PatchBlock::Insns::iterator t = tmp.begin(); t != tmp.end(); ++t) {
         insns.push_back(InsnLoc_t(*iter, t->first, t->second));
      }
   }
}
예제 #9
0
void PFReconstructor::reconstruct() {
  // TODO sort m_blocks

  // simplify the blocks by editing the links
  // each track will end up linked to at most one hcal

  // sort the blocks by id to ensure match with python
  std::vector<IdType> blockids;
  std::vector<IdType> newblockids;

  Ids ids = m_pfEvent.mergedElementIds();

  // create the blocks of linked ids
  auto bBuilder = PFBlockBuilder(ids, m_pfEvent);
  m_blocks = bBuilder.blocks();

  for (const auto& b : m_blocks) {
    blockids.push_back(b.first);
  }
#if WITHSORT
  std::sort(blockids.begin(), blockids.end());
#endif
  // go through each block and see if it can be simplified
  // in some cases it will end up being split into smaller blocks
  // Note that the old block will be marked as disactivated
  for (auto bid : blockids) {
    // std::cout<<Id::pretty(bid)<< ":" << bid <<std::endl;
    Blocks newBlocks = simplifyBlock(bid);
    if (newBlocks.size() > 0) {
      for (auto& b : newBlocks) {
        IdType id = b.first;
        m_blocks.emplace(id, std::move(b.second));
        newblockids.push_back(b.first);
      }
    }
  }
  blockids.insert(std::end(blockids), std::begin(newblockids), std::end(newblockids));

  for (auto bid : blockids) {
    PFBlock& block = m_blocks.at(bid);
    if (block.isActive()) {  // when blocks are split the original gets deactivated
      PDebug::write("Processing {}", block);
      reconstructBlock(block);
    }
  }
  if (m_unused.size() > 0) {
    PDebug::write("unused elements ");
    for (auto u : m_unused)
      PDebug::write("{},", u);
    // TODO warning message
  }
}
예제 #10
0
template<int BlockSize> void compute(Blocks<BlockSize>& blocks)
{
  for(size_t i = 0 ; i < blocks.r.size(); ++i)
  {
    blocks.eval(i);
  }
}
예제 #11
0
void findDeadBlockEdges(Blocks &blocks) {
	/* Run through all blocks and find edges that are logically dead and will
	 * never be taken.
	 *
	 * Currently, this is limited to one special case that occurs in scripts
	 * compiled by the original BioWare NWScript compiler (at least in NWN and
	 * KotOR): short-circuiting in if (x || y) conditionals. The original BioWare
	 * compiler has a bug where it generates a JZ instead of a JMP, creating a
	 * true branch that will never be taken and effectively disabling short-
	 * circuiting. I.e. both x and y will always be evaluated; when x is true,
	 * y will still be evaluated afterwards.
	 *
	 * We use very simple pattern-matching here. This is enough to find most
	 * occurances of this case, but not all. */

	for (Blocks::iterator b = blocks.begin(); b != blocks.end(); ++b) {
		if (!isTopStackJumper(*b) || (b->instructions.size() != 2) || b->parents.empty())
			continue;

		/* Look through all parents of this block and make sure they fit the
		 * pattern as well. They also all need to jump to this block with the
		 * same branch edge (true or false). */
		size_t parentEdge = SIZE_MAX;
		for (std::vector<const Block *>::const_iterator p = b->parents.begin(); p != b->parents.end(); ++p) {
			if (!isTopStackJumper(**p, &*b, &parentEdge)) {
				parentEdge = SIZE_MAX;
				break;
			}
		}
		if (parentEdge == SIZE_MAX)
			continue;

		assert(parentEdge < 2);

		/* We have now established that
		 * 1) This block checks whether the top of the stack is == 0
		 * 2) All parent blocks check whether the top of the stack is == 0
		 * 3) All parent blocks jump with the same branch edge into this block
		 *
		 * Therefore, this block must also always follow the exact same edge.
		 * This means the other edge is logically dead. */

		b->childrenTypes[1 - parentEdge] = kBlockEdgeTypeDead;
	}
}
예제 #12
0
	void MarkBlockUsed( const SBlock& p_Block, unsigned int p_unWidth, unsigned int p_unHeight )
	{
		m_unFirstX += p_unWidth;
		if( m_unFirstX + p_unWidth >= m_unWidth )
		{
			m_unFirstX = 0;
			m_unFirstY += p_unHeight;
		}
		m_vecBlocks.push_back( p_Block );
	}
예제 #13
0
	bool IsBlockFree( const SBlock& p_Block )const
	{
		unsigned int unRight = p_Block.m_unLeft + p_Block.m_unWidth;
		unsigned int unBottom = p_Block.m_unTop + p_Block.m_unHeight;

		if( unRight > m_unWidth || unBottom > m_unHeight )
		{
			return false;
		}

		Blocks::const_iterator IteEnd = m_vecBlocks.end();
		for( Blocks::const_iterator Ite = m_vecBlocks.begin();
			Ite != IteEnd; ++Ite )
		{
			if( Ite->m_unLeft < unRight && p_Block.m_unLeft < Ite->m_unLeft + Ite->m_unWidth 
				&& Ite->m_unTop < unBottom && p_Block.m_unTop < Ite->m_unTop + Ite->m_unHeight )
			{
				return false;
			}
		}
		return true;
	}
예제 #14
0
파일: PatchMgr.C 프로젝트: Zirkon/dyninst
void PatchMgr::getBlocks(Scope &scope, Blocks &blocks) {
   if (scope.wholeProgram) {
      const AddrSpace::ObjMap &objs = as()->objMap();
      for (AddrSpace::ObjMap::const_iterator iter = objs.begin(); iter != objs.end(); ++iter) {
         iter->second->blocks(std::back_inserter(blocks));
      }
   }
   else if (scope.obj) {
      scope.obj->blocks(std::back_inserter(blocks));
   }
   else if (scope.block) {
      blocks.push_back(scope.block);
   }
}
예제 #15
0
void solve() {
    int w = 0;
    int h = 0;
    int nBlocks = 0;
    cin >> w >> h >> nBlocks;
    Blocks blocks;
    blocks.resize(h + 1);
    for (int y = 0; y <= h; ++y) {
        blocks[y].resize(w + 1);
    }

    for (int i = 0; i < nBlocks; ++i) {
        int x = 0;
        int y = 0;
        cin >> x >> y;
        blocks[y][x] = true;
    }

    int nSolution = 0;
    uint nMinSolutionLength =  numeric_limits<unsigned long long>::max();
    travelse(0, 0, w, h, blocks, nSolution, 1, nMinSolutionLength);
    solutions.push_back(nSolution);
}
예제 #16
0
파일: Goomba.hpp 프로젝트: W0Z4/ProjetMario
	void isColl(Blocks& _block) {
		if (getBoundingBox().intersects(_block.getBoundingBox())) {
			cout << "col" << endl;
			_block.setColor(sf::Color::Red);
			if (_spriteG.getPosition().y <= _block.getBoundingBoxTop()) {//up
				canMoveUp = false;
				MarioJumping = false;
				if (_spriteG.getPosition().x - 2 < _block.getBoundingBoxLeft() - 12) {
					MarioJumping = true;
					canMoveRight = false;
				}
				else if (_spriteG.getPosition().x > _block.getBoundingBoxLeft() + 23) {
					MarioJumping = true;
					canMoveLeft = false;
				}
			}
			else if (_spriteG.getPosition().y  > _block.getBoundingBoxTop() - _block.getBoundingBoxHeight()) {
				_velocity.y = 5;
				MarioJumping = true;
			}
			else {

				if (_spriteG.getPosition().x < _block.getBoundingBoxLeft() - 12) {//Left

					canMoveLeft = false;
				}
				else if (_spriteG.getPosition().x > _block.getBoundingBoxLeft() + 23) {//right
					canMoveRight = false;
				}
			}
		}
		else {
			canMoveRight = true;
			canMoveLeft = true;
			canMoveUp = true;
			if (canMoveUp == true)
				_velocity.y += gravity;
		}
	}
예제 #17
0
// This is the core solution
bool Board::RecursiveSetBlock(Blocks &bs, size_t block_index)
{
    Block* block = bs[block_index];

    size_t xmax = width - block->width;
    size_t ymax = height - block->height;

    for (size_t x = 0; x <= xmax; x++)
    {
        for (size_t y = 0; y <= ymax; y++)
        {
            // if there is a place for block, process.
            if (SetBlock(block, x, y))
            {
                // If the block is the last one, solution found.
                if (block_index == bs.size() - 1)
                {
                    cout << "Step: Put block " << block_index << " at [" << x << ", " << y << "]" << endl;
                    block->Print(width, height, x, y, "Block " + to_string(block_index));
                    return true;
                }

                // If not the last one, process other blocks.
                if (RecursiveSetBlock(bs, block_index + 1))
                {
                    // If all other blocks are positioned correctly, solution found.
                    cout << "Step: Put block " << block_index << " at [" << x << ", " << y << "]" << endl;
                    block->Print(width, height, x, y, "Block " + to_string(block_index));
                    return true;
                }
                else
                {
                    // If not able to found a solution for other blocks, rollback current block,
                    // and continually find next available position for current block.
                    ClearBlock(block, x, y);
                    continue;
                }
            }
        }
    }

    return false;
}
예제 #18
0
boost::shared_ptr<SegmentDescriptions>
LocalSegmentStore::getSegmentsByBlocks(
		const Blocks& blocks,
		Blocks&       missingBlocks,
		bool          /*readCosts*/) { // readCosts is ignored.

	boost::shared_ptr<SegmentDescriptions> _blocksSegments = boost::make_shared<SegmentDescriptions>();

	for (const Block& block : blocks) {
		std::map<Block, SegmentDescriptions>::const_iterator it = _segments.find(block);

		if (it == _segments.end())
			missingBlocks.add(block);
		else
			for (const SegmentDescription& segment : it->second)
				_blocksSegments->add(segment);
	}

	return _blocksSegments;
}
예제 #19
0
int main(int argc, char** argv)
{
	try {
		// init command line parser
		util::ProgramOptions::init(argc, argv);

		int stack_id = optionStackId.as<int>();
		std::string comp_dir = optionComponentDir.as<std::string>();
		std::string pg_host = optionPGHost.as<std::string>();
		std::string pg_user = optionPGUser.as<std::string>();
		std::string pg_pass = optionPGPassword.as<std::string>();
		std::string pg_dbase = optionPGDatabase.as<std::string>();


		std::cout << "Testing PostgreSQL stores with stack ID " << stack_id << std::endl;

		// init logger
		logger::LogManager::init();
		logger::LogManager::setGlobalLogLevel(logger::Debug);

		// create new project configuration
		ProjectConfiguration pc;
		pc.setBackendType(ProjectConfiguration::PostgreSql);
		StackDescription stack;
		stack.id = stack_id;
		pc.setCatmaidStack(Raw, stack);
		pc.setComponentDirectory(comp_dir);
		pc.setPostgreSqlHost(pg_host);
		pc.setPostgreSqlUser(pg_user);
		pc.setPostgreSqlPassword(pg_pass);
		pc.setPostgreSqlDatabase(pg_dbase);

		PostgreSqlSliceStore sliceStore(pc, Membrane);

		// Add first set of slices
		boost::shared_ptr<Slice> slice1 = createSlice(10, 0);
		boost::shared_ptr<Slice> slice2 = createSlice(10, 1);
		boost::shared_ptr<Slice> slice3 = createSlice(10, 2);

		Slices slices = Slices();
		slices.add(slice1);
		slices.add(slice2);
		slices.add(slice3);

		Block block(0, 0, 0);
		sliceStore.associateSlicesToBlock(slices, block);

		Blocks blocks;
		blocks.add(block);
		Blocks missingBlocks;

		boost::shared_ptr<Slices> retrievedSlices =
				sliceStore.getSlicesByBlocks(blocks, missingBlocks);

		// Create conflict set where each slice
		ConflictSet conflictSet1;
		conflictSet1.addSlice(slice1->hashValue());
		conflictSet1.addSlice(slice2->hashValue());
		conflictSet1.addSlice(slice3->hashValue());

		ConflictSets conflictSets;
		conflictSets.add(conflictSet1);

		sliceStore.associateConflictSetsToBlock(conflictSets, block);
		boost::shared_ptr<ConflictSets> retrievedConflictSets =
				sliceStore.getConflictSetsByBlocks(blocks, missingBlocks);
		for (const ConflictSet& cs : *retrievedConflictSets) {
			std::cout << "ConflictSet hash: " << hash_value(cs);

			for (const SliceHash& sh : cs.getSlices()) {
				std::cout << " Slice hash: " << sh;
			}

			std::cout << std::endl;
		}

		PostgreSqlSegmentStore segmentStore(pc, Membrane);
		util::box<unsigned int, 2> segmentBounds(0, 0, 0, 0);
		std::vector<double> segmentFeatures;
		segmentFeatures.push_back(0.0);
		segmentFeatures.push_back(1.0);
		segmentFeatures.push_back(2.0);
		SegmentDescription segment(0, segmentBounds);
		segment.addLeftSlice(slice1->hashValue());
		segment.addRightSlice(slice2->hashValue());
		segment.setFeatures(segmentFeatures);

		boost::shared_ptr<SegmentDescriptions> segments = boost::make_shared<SegmentDescriptions>();
		segments->add(segment);

		segmentStore.associateSegmentsToBlock(*segments, block);

		boost::shared_ptr<SegmentDescriptions> retrievedSegments =
				segmentStore.getSegmentsByBlocks(blocks, missingBlocks, false);

	} catch (boost::exception& e) {

		handleException(e, std::cerr);
	}
}
예제 #20
0
파일: main.cpp 프로젝트: mourisl/Rascaf
int main( int argc, char *argv[] )
{
	int i ;
	int ret ;

	Alignments alignments ;
	Alignments clippedAlignments ;
	Blocks blocks ;
	Genome genome ;
	char *genomeFile = NULL ;
	
	if ( argc < 2 )
	{
		printf( "%s", usage ) ;
		exit( 0 ) ;
	}

	minimumSupport = 2 ;
	minimumEffectiveLength = 200 ;
	kmerSize = 23 ;
	breakN = 1 ;
	minContigSize = 200 ;
	prefix = NULL ;
	VERBOSE = false ;
	outputConnectionSequence = false ;
	aggressiveMode = false ;

	for ( i = 1 ; i < argc ; ++i )
	{
		if ( !strcmp( "-b", argv[i] ) )
		{
			alignments.Open( argv[i + 1]) ;
			++i ;
		}
		else if ( !strcmp( "-o", argv[i] ) )
		{
			prefix = argv[i + 1] ;
			++i ;
		}
		else if ( !strcmp( "-f", argv[i] ) )
		{
			genomeFile = argv[i + 1] ;
			++i ;
		}
		else if ( !strcmp( "-ms", argv[i] ) )
		{
			minimumSupport = atoi( argv[i + 1] ) ;
			++i ;
		}
		else if ( !strcmp( "-ml", argv[i] ) )
		{
			minimumEffectiveLength = atoi( argv[i + 1] ) ;
			++i ;
		}
		else if ( !strcmp( "-k", argv[i] ) )
		{
			kmerSize = atoi( argv[i + 1] ) ;
			++i ;
		}
		else if ( !strcmp( "-breakN", argv[i] ) )
		{
			breakN = atoi( argv[i + 1] ) ;
			++i ;
		}
		else if ( !strcmp( "-minContigSize", argv[i] ) )
		{
			minContigSize = atoi( argv[i + 1] ) ;
			++i ;
		}
		else if ( !strcmp( "-v", argv[i] ) )
		{
			VERBOSE = true ;
		}
		else if ( !strcmp( "-cs", argv[i] ) )
		{
			outputConnectionSequence = true ;
		}
		/*else if ( !strcmp( "-aggressive", argv[i] ) )
		{
			aggressiveMode = true ;
		}*/
		else if ( !strcmp( "-bc", argv[i] ) )
		{
			// So far, assume the input is from BWA mem
			clippedAlignments.Open( argv[i + 1] ) ;
			clippedAlignments.SetAllowSupplementary( true ) ;
			++i ;
		}
		else
		{
			fprintf( stderr, "Unknown parameter: %s\n", argv[i] ) ;
			exit( 1 ) ;
		}
	}

	if ( !alignments.IsOpened() )
	{
		printf( "Must use -b to specify the bam file." ) ;
		return 0 ;
	}

	if ( prefix != NULL )
	{
		char buffer[255] ;
		sprintf( buffer, "%s.out", prefix ) ;
		fpOut = fopen( buffer, "w" ) ;
	}
	else
	{
		char buffer[255] ;
		prefix = strdup( "rascaf" ) ;
		sprintf( buffer, "%s.out", prefix ) ;
		fpOut = fopen( buffer, "w" ) ;
	}
	
	if ( genomeFile != NULL )
	{
		genome.Open( alignments, genomeFile ) ;
		alignments.Rewind() ;
	}

	if ( outputConnectionSequence == true && genomeFile == NULL )
	{
		fprintf( stderr, "Must use -f to specify assembly file when using -cs\n" ) ;	
		exit( EXIT_FAILURE ) ;
	}
	// 74619
	//printf( "%c\n", genome.GetNucleotide( 74619, 4 ) ) ;
	//exit(0) ;
	// Build the graph
	ret = blocks.BuildExonBlocks( alignments, genome ) ;
	alignments.Rewind() ;
	fprintf( stderr, "Found %d exon blocks.\n", ret ) ;
	if ( clippedAlignments.IsOpened() )
	{
		fprintf( stderr, "Extend exon blocks with clipped alignments.\n" ) ;
		Blocks extendBlocks ;
		extendBlocks.BuildExonBlocks( clippedAlignments, genome ) ;
		clippedAlignments.Rewind() ;

		ret = blocks.ExtendExonBlocks( extendBlocks ) ;
		fprintf( stderr, "Found %d exon blocks after extension.\n", ret ) ;
	}

	blocks.GetAlignmentsInfo( alignments ) ;
	alignments.Rewind() ;

	ret = blocks.BuildGeneBlocks( alignments, genome ) ;
	alignments.Rewind() ;
	fprintf( stderr, "Found %d gene blocks.\n", ret ) ;
	
	blocks.BuildGeneBlockGraph( alignments ) ;
	if ( clippedAlignments.IsOpened() )
	{
		blocks.AddGeneBlockGraphByClippedAlignments( clippedAlignments ) ; 
	}
	
	// Cleaning
	blocks.CleanGeneBlockGraph( alignments, genome ) ;

	// Scaffolding
	Scaffold scaffold( blocks, genome ) ;
	//scaffold.Init( blocks ) ;
	int componentCnt = scaffold.BuildComponent() ;
	fprintf( stderr, "Found %d non-trivial gene block components.\n", componentCnt ) ;
	// Possible for parallelization
	for ( i = 0 ; i < componentCnt ; ++i )
	{
		scaffold.ScaffoldComponent( i ) ;
	}
	
	scaffold.ScaffoldGenome() ;
	
	// Output the command line
	fprintf( fpOut, "command line: " ) ;
	char *fullpath = (char *)malloc( sizeof( char ) * 4096 ) ;
	for ( i = 0 ; i < argc ; ++i )
	{
		char c = ' ' ;
		if ( i == argc - 1 )
			c = '\n' ;
		if ( i > 0 && !strcmp( argv[i - 1], "-b" ) )
		{
			if ( realpath( argv[i], fullpath ) == NULL )
			{
				fprintf( stderr, "Failed to resolve the path of file %s.\n", argv[i] ) ;
				exit( 1 ) ;
			}
			fprintf( fpOut, "%s%c", fullpath, c ) ;
		}
		else if ( i > 0 && !strcmp( argv[i - 1], "-f" ) )
		{
			if ( realpath( argv[i], fullpath ) == NULL )
			{
				fprintf( stderr, "Failed to resolve the path of file %s.\n", argv[i] ) ;
				exit( 1 ) ;
			}
			fprintf( fpOut, "%s%c", fullpath, c ) ;
		}
		else
			fprintf( fpOut, "%s%c", argv[i], c ) ;
	}
	free( fullpath ) ;
	scaffold.Output( fpOut, alignments ) ;
	return 0 ;
}
예제 #21
0
int main() {
	int size = 9; // must be 11 or less
	Blocks * blocks = new Blocks(size);
	blocks->build();
}
예제 #22
0
파일: block.cpp 프로젝트: asr1/xoreos-tools
void findDeadBlockEdges(Blocks &blocks) {
	/* Run through all blocks and find edges that are logically dead and will
	 * never be taken.
	 *
	 * Currently, this is limited to one special case that occurs in scripts
	 * compiled by the original BioWare NWScript compiler (at least in NWN and
	 * KotOR): short-circuiting in if (x || y) conditionals. The original BioWare
	 * compiler has a bug where it generates a JZ instead of a JMP, creating a
	 * true branch that will never be taken and effectively disabling short-
	 * circuiting. I.e. both x and y will always be evaluated; when x is true,
	 * y will still be evaluated afterwards.
	 *
	 * We use very simple pattern-matching here. This is enough to find most
	 * occurrences of this case, but not all.
	 *
	 * For example, this is the control flow diagram for the bytecode, as
	 * compiled by the original BioWare compiler, for
	 *
	 * if ((global_variable == 1) || (global_variable == 3))
	 *
	 *        .
	 *        |
	 *        V
	 * .-------------------.
	 * | CPTOPBP -4 4      |
	 * | CONSTI 1          |
	 * | EQII              |
	 * | CPTOPSP -4 4      |
	 * | JZ                |
	 * '-------------------'
	 *  (true)|    |(false)
	 *        |    V (1)
	 *        | .--------------------.
	 *        | | CPTOPSP -4 4       |
	 *        | | JZ                 | (4)
	 *        | '--------------------'
	 *        |  (false)|     |(true)
	 *        |    (2)  |     |  (3)
	 *        V         V     |
	 * .-------------------.  |
	 * | CPTOPBP -4 4      |  |
	 * | CONSTI 3          |  |
	 * | EQII              |  |
	 * '-------------------'  |
	 *         |              |
	 *         V              |
	 * .-------------------.  |
	 * | LOGORII -4 4      |  |
	 * | JZ                |<-'
	 * '-------------------'
	 *  (true) |   |(false)
	 *         '   '
	 *
	 * "CPTOPSP -4 4" takes the top element on the stack and, without
	 * popping it, pushes it again onto the top, creating a duplicate.
	 *
	 * When taking the false branch at (1) (which means that the variable
	 * *is* equal to 1), we have already established that the top element
	 * on the stack (which is getting copied a few times, so it's not
	 * vanishing) is of a certain value. This means that the false branch
	 * at (2) has to be taken as well. The true branch at (3) can't ever
	 * be taken, and is therefore logically dead.
	 *
	 * Moreover, if the true branch at (3) would have been taken, this
	 * had resulted in a stack smash, because JZ consumes a stack element,
	 * and the LOGORII would now be one element short.
	 *
	 * Essentially, the whole block at (4) evaluates to a NOP.
	 *
	 * How this *should* have been compiled is thusly:
	 *
	 *        .
	 *        |
	 *        V
	 * .-------------------.
	 * | CPTOPBP -4 4      |
	 * | CONSTI 1          |
	 * | EQII              |
	 * | CPTOPSP -4 4      |
	 * | JZ                |
	 * '-------------------'
	 *  (true)|    |(false)
	 *        |    V
	 *        | .--------------------.
	 *        | | CPTOPSP -4 4       | (5)
	 *        | | JMP                |
	 *        | '--------------------'
	 *        |               |
	 *        |               |
	 *        V               |
	 * .-------------------.  |
	 * | CPTOPBP -4 4      |  |
	 * | CONSTI 3          |  |
	 * | EQII              |  |
	 * '-------------------'  |
	 *         |              |
	 *         V      (6)     |
	 * .-------------------.  |
	 * | LOGORII -4 4      |  |
	 * | JZ                |<-'
	 * '-------------------'
	 *  (true) |   |(false)
	 *         '   '
	 *
	 * In the block at (5), the top element is now copied, and the code
	 * jumps unconditionally to the LOGORII block at (6). In contrast
	 * to JZ, JMP does not pop an element from the stack. The LOGORII
	 * has enough elements to do its comparison.
	 *
	 * This is exactly what the OpenKnights compiler does. And this has
	 * been fixed by BioWare by the time of Neverwinter Nights 2 as well.
	 *
	 * The short-circuiting && construct does not seem to have this fault.
	 */

	for (Blocks::iterator b = blocks.begin(); b != blocks.end(); ++b) {
		if (!isTopStackJumper(*b) || (b->instructions.size() != 2) || b->parents.empty())
			continue;

		/* Look through all parents of this block and make sure they fit the
		 * pattern as well. They also all need to jump to this block with the
		 * same branch edge (true or false). */
		size_t parentEdge = SIZE_MAX;
		for (std::vector<const Block *>::const_iterator p = b->parents.begin(); p != b->parents.end(); ++p) {
			if (!isTopStackJumper(**p, &*b, &parentEdge)) {
				parentEdge = SIZE_MAX;
				break;
			}
		}
		if (parentEdge == SIZE_MAX)
			continue;

		assert(parentEdge < 2);

		/* We have now established that
		 * 1) This block checks whether the top of the stack is == 0
		 * 2) All parent blocks check whether the top of the stack is == 0
		 * 3) All parent blocks jump with the same branch edge into this block
		 *
		 * Therefore, this block must also always follow the exact same edge.
		 * This means the other edge is logically dead. */

		b->childrenTypes[1 - parentEdge] = kBlockEdgeTypeDead;
	}
}
예제 #23
0
 void addBlock(Block block) {
     blocks.push_back(block);
 }
예제 #24
0
/**
* Unpause par2-files
* returns true, if the files with required number of blocks were unpaused,
* or false if there are no more files in queue for this collection or not enough blocks.
* special case: returns true if there are any unpaused par2-files in the queue regardless
* of the amount of blocks; this is to keep par-checker wait for download completion.
*/
bool ParCoordinator::RequestMorePars(NZBInfo* pNZBInfo, const char* szParFilename, int iBlockNeeded, int* pBlockFound)
{
	DownloadQueue* pDownloadQueue = DownloadQueue::Lock();
	
	Blocks blocks;
	blocks.clear();
	int iBlockFound = 0;
    int iCurBlockFound = 0;

	FindPars(pDownloadQueue, pNZBInfo, szParFilename, &blocks, true, true, &iCurBlockFound);
    iBlockFound += iCurBlockFound;
	if (iBlockFound < iBlockNeeded)
	{
		FindPars(pDownloadQueue, pNZBInfo, szParFilename, &blocks, true, false, &iCurBlockFound);
        iBlockFound += iCurBlockFound;
	}
	if (iBlockFound < iBlockNeeded)
	{
		FindPars(pDownloadQueue, pNZBInfo, szParFilename, &blocks, false, false, &iCurBlockFound);
        iBlockFound += iCurBlockFound;
	}

	if (iBlockFound >= iBlockNeeded)
	{
		// 1. first unpause all files with par-blocks less or equal iBlockNeeded
		// starting from the file with max block count.
		// if par-collection was built exponentially and all par-files present,
		// this step selects par-files with exact number of blocks we need.
		while (iBlockNeeded > 0)
		{               
			BlockInfo* pBestBlockInfo = NULL;
			for (Blocks::iterator it = blocks.begin(); it != blocks.end(); it++)
			{
				BlockInfo* pBlockInfo = *it;
				if (pBlockInfo->m_iBlockCount <= iBlockNeeded &&
				   (!pBestBlockInfo || pBestBlockInfo->m_iBlockCount < pBlockInfo->m_iBlockCount))
				{
					pBestBlockInfo = pBlockInfo;
				}
			}
			if (pBestBlockInfo)
			{
				if (pBestBlockInfo->m_pFileInfo->GetPaused())
				{
					m_ParChecker.PrintMessage(Message::mkInfo, "Unpausing %s%c%s for par-recovery", pNZBInfo->GetName(), (int)PATH_SEPARATOR, pBestBlockInfo->m_pFileInfo->GetFilename());
					pBestBlockInfo->m_pFileInfo->SetPaused(false);
					pBestBlockInfo->m_pFileInfo->SetExtraPriority(true);
				}
				iBlockNeeded -= pBestBlockInfo->m_iBlockCount;
				blocks.remove(pBestBlockInfo);
				delete pBestBlockInfo;
			}
			else
			{
				break;
			}
		}
			
		// 2. then unpause other files
		// this step only needed if the par-collection was built not exponentially 
		// or not all par-files present (or some of them were corrupted)
		// this step is not optimal, but we hope, that the first step will work good 
		// in most cases and we will not need the second step often
		while (iBlockNeeded > 0)
		{
			BlockInfo* pBlockInfo = blocks.front();
			if (pBlockInfo->m_pFileInfo->GetPaused())
			{
				m_ParChecker.PrintMessage(Message::mkInfo, "Unpausing %s%c%s for par-recovery", pNZBInfo->GetName(), (int)PATH_SEPARATOR, pBlockInfo->m_pFileInfo->GetFilename());
				pBlockInfo->m_pFileInfo->SetPaused(false);
				pBlockInfo->m_pFileInfo->SetExtraPriority(true);
			}
			iBlockNeeded -= pBlockInfo->m_iBlockCount;
		}
	}

	bool bHasUnpausedParFiles = false;
	for (FileList::iterator it = pNZBInfo->GetFileList()->begin(); it != pNZBInfo->GetFileList()->end(); it++)
	{
		FileInfo* pFileInfo = *it;
		if (pFileInfo->GetParFile() && !pFileInfo->GetPaused())
		{
			bHasUnpausedParFiles = true;
			break;
		}
	}

	DownloadQueue::Unlock();

	if (pBlockFound)
	{
		*pBlockFound = iBlockFound;
	}

	for (Blocks::iterator it = blocks.begin(); it != blocks.end(); it++)
	{
		delete *it;
	}
	blocks.clear();

	bool bOK = iBlockNeeded <= 0 || bHasUnpausedParFiles;

	return bOK;
}
예제 #25
0
void AbstractAligner::change_blocks_impl(Blocks& blocks) const {
    std::sort(blocks.begin(), blocks.end(), BlockSquareLess());
}
예제 #26
0
 CFGBlock* find_block(int ip) {
   Blocks::iterator i = blocks_.find(ip);
   if(i == blocks_.end()) return 0;
   return i->second;
 }
예제 #27
0
BlkModel::BlkModel(const BlkModel& rhs) {
	Blocks blocks = const_cast<BlkModel&>(rhs).blocks();
	for (Blocks::iterator it = blocks.begin(); it != blocks.end(); ++it)
		addBlock(it->first, it->second);
}