void rotate(vector<int> &a) {
	a.insert(a.begin(), a[a.size()-1]);
	a.pop_back();
}
Example #2
0
    void loop()
    {
        size_t iter = 0;
        while( (!Lambda.empty()) && (iter < max_iter) )
        {
            if(verbosity >= 2)
                cout<<"Iteration: "<<iter<<endl;
            else if(verbosity == 1 && (iter%10)==0)
                cout<<"Iteration: "<<iter<<endl;

            Undefined u = Lambda.front();
            Lambda.pop();
            double energy2, m2, b2,min_m, min_b, min_energy;
            double energy3, m3, b3;
            //short_array min_x = minimizer->minimize( u.x_l, u.lambda, min_energy, min_m, min_b, true);

            short_array min_x = minimizer->minimize( u.x_l, u.lambda, min_energy, min_m, min_b, false);

            short_array x2 = minimizer->minimize( u.x_r, u.lambda, energy2, m2, b2, false);
            short_array x3 = minimizer->minimize( u.x_r, u.lambda, energy3, m3, b3, true);
            if(min_energy > energy2 && min_energy > energy3)
                e1++;
            else if( energy2 > energy3 && energy2 > min_energy)
                e2++;
            else if( energy3 > energy2 && energy3 > min_energy)
                e3++;

           
            if( energy2 < min_energy)
            {
                min_m = m2;
                min_b = b2;
                min_energy = energy2;
                min_x = x2;
            }

            if(energy3 < min_energy)
            {
                min_m = m3;
                min_b = b3;
                min_energy = energy3;
                min_x = x3;
            }

            //if( !compare( min_x, u.x_l, u.lambda) && !compare(min_x, u.x_r, u.lambda) )
            {
                LineSegment l( min_m, min_b, lambda_min, lambda_max, false );
                kmc.addLineSegment(l);
                if(verbosity >= 2)
                    cout<<"* Adding line segment: "<<l<<endl;
                int num_intersections = kmc.num_intersections;
                if( num_intersections > 1 && (kmc.intersecting_lambda[0] != kmc.intersecting_lambda[num_intersections -1] ) )
                { // had intersections
                    cout.precision(16);
                    if(verbosity >= 1)
                    {
                        cout<<"\t Had intersections at "<< kmc.intersecting_lambda[0]<<", "<<kmc.intersecting_lambda[num_intersections-1]<<endl; 
                        cout<<"\t\t Energies are: "<< fixed << kmc.intersecting_energies[0]<<", "<<fixed<<kmc.intersecting_energies[num_intersections-1]<<endl;
                    }
                    double lambda_l = kmc.intersecting_lambda[0];
                    double lambda_r = kmc.intersecting_lambda[num_intersections - 1];
                    int index_l = kmc.intersecting_indexes[0];
                    int index_r = kmc.intersecting_indexes[num_intersections - 1];
                    if(index_r - index_l > 1 )
                        labelings.erase( labelings.begin() + index_l + 1, labelings.begin() + index_r);
                    Undefined u1( lambda_l, labelings[index_l], min_x );
                    Undefined u2( lambda_r, labelings[index_r], min_x );
                    Lambda.push(u1);
                    Lambda.push(u2);

                    labelings.insert( labelings.begin() + index_l + 1, min_x);
                    
                }
            }
            //else
            //{
            //}

            iter++;
        }
        if(iter == max_iter)
            cout<<"Maximum number of iterations reached"<<endl;
        cout<<"Done in "<<iter<<" iterations."<<endl;
        cout<<KBCYN<<"[e1, e2, e3] = ["<<e1<<", "<<e2<<", "<<e3<<"]"<<KNRM<<endl;
        if(verbosity >= 1)
            cout<<kmc<<endl;
        if(verbosity >= 2)
        {
            /*cout<<"labelings:"<<endl;
            for(size_t i = 0; i < labelings.size(); i++)
            {
                cout<<labelings[i][0]<<" ";
            }
            cout<<endl;*/
        }
    }
Example #3
0
END_EXTERNC

BEGIN_EXTERNC
static MI_Boolean ServerCallback(
    Selector* sel,
    Handler* handler,
    MI_Uint32 mask, 
    MI_Uint64 currentTimeUsec)
{
    char buf[BUFFER_SIZE];
    MI_Result r;
    size_t n = 0;

    sel=sel;
    currentTimeUsec = currentTimeUsec;
    s_srv_h = handler;

    // Process READ events.
    if (mask & SELECTOR_READ)
    {
        for (;;)
        {
            // Read request:
            n = 0;
            r = Sock_Read(handler->sock, buf, sizeof(buf), &n);
            s_srv_data.insert(s_srv_data.end(), buf, buf + n);

#if defined(TRACE_IO)
            printf("SERVER.READ[%u]\n", n);
#endif
            if (r == MI_RESULT_WOULD_BLOCK)
                break;

            TEST_ASSERT(r == MI_RESULT_OK);

            // Did client close connection?
            if (n == 0)
            {
                return MI_FALSE;
            }

            // Save incoming data.

            // Now solicit read and write events.
            handler->mask = SELECTOR_READ|SELECTOR_WRITE;
            //break;
                        
            // if event 'write' was already set and we have nothing to write
            // new event will never arrive
            // so we need to try to write data once it's available
            mask |= SELECTOR_WRITE;
        }
    }

    // Process WRITE events.
    if (mask & SELECTOR_WRITE)
    {
        for (;;)
        {
            n = 0;
            size_t m = 7 + (int)(rand() % 256);

            if (m >= s_srv_data.size())
                m = s_srv_data.size();

            // Write response:
            r = Sock_Write(handler->sock, &s_srv_data[0], m, &n);

            s_srv_data.erase(s_srv_data.begin(), s_srv_data.begin() + n);
#if defined(TRACE_IO)
            printf("SERVER.WRITE[%u]\n", n);
#endif
            if (s_srv_data.size() == 0)
            {
                /* Watch for read events (but not write events) */
                handler->mask = SELECTOR_READ;
                break;
            }

            if (r == MI_RESULT_WOULD_BLOCK)
                break;

            TEST_ASSERT(r == MI_RESULT_OK);

            //break;
        }
    }

    if (mask & SELECTOR_REMOVE)
    {
        r = Sock_Close(handler->sock);
        TEST_ASSERT(r == MI_RESULT_OK);
        s_done = true;
        PAL_Free(handler);
        handler = 0;
    }

    if (mask & SELECTOR_DESTROY)
    {
        if (handler)
        {
            Sock_Close(handler->sock);
            PAL_Free(handler);
        }
    }

    return MI_TRUE;
}
void ZeroSampleFiller::fill(const vector<double>& x, const vector<double>& y,
                            vector<double>& xFilled, vector<double>& yFilled,
                            size_t zeroSampleCount)
{
    if (x.size() != y.size())
        throw runtime_error("[ZeroSampleFiller::fill()] x and y arrays must be the same size");

    // adjacent samples are expected to be within this tolerance
    const static double EPSILON = 1e-5;

    // start with the original data
    xFilled.assign(x.begin(), x.end());
    yFilled.assign(y.begin(), y.end());

    // insert flanking zeros around non-zero data points
    bool wasInData = false;
    bool nowInData = false;
    for (int i=y.size()-1; i >= 0; --i)
    {
        nowInData = yFilled[i] > 0.0;
        if (nowInData && !wasInData)
        {
            // step forward to check for missing samples
            
            // at i==0, fudge the first order delta
            double firstOrderDelta = i < 1 ? xFilled[i+1] - xFilled[i]
                                           : xFilled[i] - xFilled[i-1];

            // at i==1 or when possibly between signals, assume no second order delta
            double secondOrderDelta = i < 2 || yFilled[i-1] == 0 ? 0 :
                                      firstOrderDelta - (xFilled[i-1] - xFilled[i-2]);
            double totalDelta = 0;
            for (int j=1; j <= (int) zeroSampleCount; ++j)
            {
                totalDelta += secondOrderDelta;
                double newX = xFilled[i+j-1] + firstOrderDelta + totalDelta;
                
                bool oob = i+j >= (int) y.size();

                // sampleDelta should never be less than negative firstOrderDelta
                double sampleDelta = oob ? 0 : xFilled[i+j] - newX;
                if (sampleDelta < -firstOrderDelta)
                    break;
                    //throw std::runtime_error("[ZeroSampleFiller::fill()] miscalculated sample rate");

                // if out of bounds or newX is a valid missing sample, insert a new zero point
                if (oob || sampleDelta > firstOrderDelta)
                {
                    xFilled.insert(xFilled.begin()+(i+j), newX);
                    yFilled.insert(yFilled.begin()+(i+j), 0.0);
                }
            }
        }
        wasInData = nowInData;
    }

    wasInData = false;
    for (int i=0, end=yFilled.size(); i < end; ++i, end=yFilled.size())
    {
        nowInData = yFilled[i] > 0.0;
        if (nowInData && !wasInData)
        {
            // step backward to check for missing samples

            // at i==end-1, fudge the first order delta
            double firstOrderDelta = i == end-1 ? xFilled[i] - xFilled[i-1]
                                                : xFilled[i+1] - xFilled[i];

            // at i==end-2 or when possibly between signals, assume no second order delta
            double secondOrderDelta = i == end-2 || yFilled[i+1] == 0 ? 0 :
                                      (xFilled[i+2] - xFilled[i+1]) - firstOrderDelta;
            double totalDelta = 0;
            for (int j=1; j <= (int) zeroSampleCount; ++j)
            {
                totalDelta += secondOrderDelta;
                double newX = (xFilled[i-j+1] - firstOrderDelta) - totalDelta;

                bool oob = i-j < 0;

                // xFilled[i-j] and newX should be nearly equal if they are the same sample

                // sampleDelta should never be greater than firstOrderDelta
                double sampleDelta = oob ? 0 : xFilled[i-j] - newX;
                if (sampleDelta > firstOrderDelta)
                    break;
                    //throw std::runtime_error("[ZeroSampleFiller::fill()] miscalculated sample rate");

                // if out of bounds or newX is a valid missing sample, insert a new zero point
                if (oob || sampleDelta <= -firstOrderDelta )
                {
                    xFilled.insert(xFilled.begin()+(i-j+1), newX);
                    yFilled.insert(yFilled.begin()+(i-j+1), 0.0);
                    ++i;
                }
            }
        }
        wasInData = nowInData;
    }
}
void addBoundaryWords(vector<string> &phrase)
{
  phrase.insert(phrase.begin(), "<s>");
  phrase.push_back("</s>");
}
Example #6
0
void GraphsListN::addGraph( vector< short unsigned int > iVertices, const vector< bool > &bVerticesLinkable, const unsigned int &iType, bool bSpherical, const short unsigned int &iVertexSupp1, const short unsigned int &iVertexSupp2, const unsigned int &iDataSupp )
{
	unsigned int short iTemp, i;
	
	if( bSpherical )
	{
		if( iType == 0 ) // An
		{
			// on veut une fois les A_n (et pas une fois pour chaque sens de lecture)
			if( iVertices.front( ) > iVertices.back( ) )
				reverse( iVertices.begin( ), iVertices.end( ) );
		}
		else if( iType == 1 ) // Bn
		{
			iVertices.push_back( iVertexSupp1 );
		}
		else if( iType == 3 ) // Dn
		{
			if( iVerticesCount > 4 )
			{
				iTemp = iVertices[ iVerticesCount - 2 ];
				iVertices[ iVerticesCount - 2 ] = min( iTemp, iVertexSupp1 );
				iVertices.push_back( max( iTemp, iVertexSupp1 ) );
			}
			else
			{
				if( iVertices[0] > iVertices[2] )
				{
					iTemp = iVertices[0];
					iVertices[0] = iVertices[2];
					iVertices[2] = iTemp;
				}
				
				if( iVertexSupp1 < iVertices[0] )
				{
					iVertices.push_back( iVertices[2] );
					iVertices[2] = iVertices[0];
					iVertices[0] = iVertexSupp1;
				}
				else if( iVertexSupp1 < iVertices[2] )
				{
					iVertices.push_back( iVertices[2] );
					iVertices[2] = iVertexSupp1;
				}
				else
					iVertices.push_back( iVertexSupp1 );
				
			}
		}
		else if( iType == 4 ) // En
		{
			if( iVerticesCount == 6 )
			{
				if( iVertices.front( ) > iVertices.back( ) )
					reverse( iVertices.begin( ), iVertices.end( ) );
			}
			iVertices.push_back( iVertexSupp1 );
		}
		else if( iType == 5 ) // Fn
		{
			iVertices.push_back( iVertexSupp1 );
			if( iVertices.front( ) > iVertices.back( ) )
				reverse( iVertices.begin( ), iVertices.end( ) );
		}
		else if( iType == 7 ) // Hn
		{
			iVertices.push_back( iVertexSupp1 );
		}
	}
	else
	{
		if( iType == 0 && iDataSupp )
		{
			int iMinIndex(0);
			unsigned int iMinValue( iVertices[0] );
			
			iVertices.push_back( iVertexSupp1 );
			vector< short unsigned int > iVerticesTemp( iVertices );
			
			// on répère le sommet avec l'indice le plus petit
			for( i = 1; i < iVerticesCount; i++ )
			{
				if( iVertices[i] < iMinValue )
				{
					iMinValue = iVertices[i];
					iMinIndex = i;
				}
			}
				
			// et le sens de parcours
			int iDirection( iVertices[ !iMinIndex ? (iVerticesCount - 1) : (iMinIndex - 1) ] > iVertices[ iMinIndex == (int)( iVerticesCount - 1 ) ? 0 : ( iMinIndex + 1 ) ] ? 1 : -1 );
			
			// on réordonne
			for( unsigned int j(0); j < iVerticesCount; j++ )
			{
				iVertices[j] = iVerticesTemp[iMinIndex];
				
				iMinIndex += iDirection;
				if( iMinIndex == -1 )
					iMinIndex = iVerticesCount - 1;
				else if( iMinIndex == (int)iVerticesCount )
					iMinIndex = 0;
			}
		}
		else if( iType == 1 ) // TBn
		{
			if( iVerticesCount == 4 ) // TB3
			{
				i = iVertices[1];
				iTemp = max( iVertices[0], iVertices[2] );
				iVertices[1] = min( iVertices[0], iVertices[2] ); 
				iVertices[2] = iTemp;
				iVertices[0] = i;
				
				iVertices.insert( iVertices.begin( ), iVertexSupp1 );
			}
			else // autres \tilde Bn
			{	
				iTemp = min( iVertices[ iVerticesCount - 3 ], iVertexSupp1 );
				iVertices.push_back( max( iVertices[ iVerticesCount - 3 ], iVertexSupp1 ) );
				iVertices[ iVerticesCount - 3 ] = iTemp;
				
				iVertices.insert( iVertices.begin( ), iVertexSupp2 );
			}
		}
		else if( iType == 2 ) // \tilde Cn
		{
			iVertices.insert( iVertices.begin( ), iVertexSupp1 );
			iVertices.push_back( iVertexSupp2 );
				
			if( iVertices[0] > iVertices[ iVerticesCount - 1 ] )
				reverse( iVertices.begin( ), iVertices.end( ) );
		}
		else if( iType == 3 ) // \tilde Dn
		{
			if( iVerticesCount >= 6 )
			{
				// le vecteur iVerticesBase contient la base (i.e. sans les 4 extrémités)
				#ifdef _MSC_VER
					vector< short unsigned int > iVerticesBase;
					iTemp = iVerticesCount - 3;
					for( i = 1; i < iTemp; i++ )
						iVerticesBase.push_back( iVertices[i] );
				#else
					vector< short unsigned int > iVerticesBase( iVertices.begin( ) + 1, iVertices.begin( ) + iVerticesCount - 3 ); // ne marche pas sous Visual Studio 2010 & 2012 malheureusement
				#endif

				// on regarde si on doit modifier l'ordre
				if( iVerticesBase[0] > iVerticesBase[ iVerticesCount - 5 ] )
				{
					reverse( iVerticesBase.begin( ), iVerticesBase.end( ) );
					
					// ajout des 4 extrémités
					iVerticesBase.push_back( min( iVertices[0], iVertexSupp1 ) );
					iVerticesBase.push_back( max( iVertices[0], iVertexSupp1 ) );
					iVerticesBase.insert( iVerticesBase.begin( ), max( iVertices[ iVerticesCount - 3 ], iVertexSupp2 ) );
					iVerticesBase.insert( iVerticesBase.begin( ), min( iVertices[ iVerticesCount - 3 ], iVertexSupp2 ) );
				}
				else
				{
					// ajout des 4 extrémités
					iVerticesBase.push_back( min( iVertices[ iVerticesCount - 3 ], iVertexSupp2 ) );
					iVerticesBase.push_back( max( iVertices[ iVerticesCount - 3 ], iVertexSupp2 ) );
					iVerticesBase.insert( iVerticesBase.begin( ), max( iVertices[0], iVertexSupp1 ) );
					iVerticesBase.insert( iVerticesBase.begin( ), min( iVertices[0], iVertexSupp1 ) );
				}

				iVertices = iVerticesBase;
			}
			else // le TD4, "+" est traité différemment
			{
				vector<short unsigned int> iVerticesTemp( 4, 0 );
				iVerticesTemp[0] = iVertices[0];
				iVerticesTemp[1] = iVertices[2];
				iVerticesTemp[2] = iVertexSupp1;
				iVerticesTemp[3] = iVertexSupp2;
				sort( iVerticesTemp.begin( ), iVerticesTemp.end( ) );
				iVerticesTemp.push_back( iVertices[1] );
				iVertices = iVerticesTemp;
			}
		}
		else if( iType == 4 ) // \tilde En
		{
			if( iVerticesCount == 7 ) // TE6
			{
				// TODO: refaire l'encodage de ce graphe et modifer la fonction bIsSubgraphOf_spherical_euclidean?
				vector< short unsigned int > iVerticesTemp;
				unsigned int iMin( min( min( iVertices[1], iVertices[3] ), iVertexSupp1 ) );
				
				if( iMin == iVertices[1] )
				{
					iVerticesTemp.push_back( iVertices[0] );
					iVerticesTemp.push_back( iVertices[1] );
					
					if( min( iVertices[3], iVertexSupp1 ) == iVertices[3] )
					{
						iVerticesTemp.push_back( iVertices[3] );
						iVerticesTemp.push_back( iVertices[4] );
						iVerticesTemp.push_back( iVertexSupp1 );
						iVerticesTemp.push_back( iVertexSupp2 );
					}
					else
					{
						iVerticesTemp.push_back( iVertexSupp1 );
						iVerticesTemp.push_back( iVertexSupp2 );
						iVerticesTemp.push_back( iVertices[3] );
						iVerticesTemp.push_back( iVertices[4] );
					}
				}
				else if( iMin == iVertices[3] )
				{
					iVerticesTemp.push_back( iVertices[4] );
					iVerticesTemp.push_back( iVertices[3] );
					
					if( min( iVertices[1], iVertexSupp1 ) == iVertices[1] )
					{
						iVerticesTemp.push_back( iVertices[1] );
						iVerticesTemp.push_back( iVertices[0] );
						iVerticesTemp.push_back( iVertexSupp1 );
						iVerticesTemp.push_back( iVertexSupp2 );
					}
					else
					{
						iVerticesTemp.push_back( iVertexSupp1 );
						iVerticesTemp.push_back( iVertexSupp2 );
						iVerticesTemp.push_back( iVertices[1] );
						iVerticesTemp.push_back( iVertices[0] );
					}
				}
				else
				{
					iVerticesTemp.push_back( iVertexSupp2 );
					iVerticesTemp.push_back( iVertexSupp1 );
					
					if( min( iVertices[1], iVertices[3] ) == iVertices[1] )
					{
						iVerticesTemp.push_back( iVertices[1] );
						iVerticesTemp.push_back( iVertices[0] );
						iVerticesTemp.push_back( iVertices[3] );
						iVerticesTemp.push_back( iVertices[4] );
					}
					else
					{
						iVerticesTemp.push_back( iVertices[3] );
						iVerticesTemp.push_back( iVertices[4] );
						iVerticesTemp.push_back( iVertices[1] );
						iVerticesTemp.push_back( iVertices[0] );
					}	
				}
				
				iVerticesTemp.push_back( iVertices[2] );
				iVertices = iVerticesTemp;
			}
			else if( iVerticesCount == 8  ) // TE7
			{
				if( iVertices.front( ) > iVertices.back( ) ) // la base du \tilde E7 est symétrique
					reverse( iVertices.begin( ), iVertices.end( ) );
				
				iVertices.push_back( iVertexSupp1 );
			}
			else // TE8
			{
				iVertices.push_back( iVertexSupp1 );
			}
		}
		else if( iType == 5 )
		{
			iVertices.push_back( iVertexSupp1 );
		}
		else if( iType == 6 && iDataSupp ) // \tilde G_2
		{
			iVertices.push_back( iVertexSupp1 );
		}
	}
	
	Graph g( iVertices, ptr_map_vertices_indexToLabel, bVerticesLinkable, iType, bSpherical, iDataSupp );

	auto it( lower_bound( graphs.begin(), graphs.end(), g ) );
	if( it == graphs.end() || !(*it == g) )
		graphs.insert( it, g );
}
Example #7
0
bool Realigner::addClippedBasesToTags(vector<CigarOp>& cigar_data, vector<MDelement>& MD_data, unsigned int nr_read_bases) const
{

  // Restore left end of cigar string incl. original soft clips
  vector<CigarOp>::const_iterator cigar_it = (clipped_anchors_.cigar_left.end()-1);
  if (cigar_it->Type == cigar_data.begin()->Type) {
    cigar_data.begin()->Length += cigar_it->Length;
    cigar_it--;
  } else if (cigar_data.begin()->Type == 'S') {
      if (verbose_)
        cout << "Error, invalid cigar: Soft clipping occurred after left anchor!" << endl;
      return false;
  }
  while (cigar_it > clipped_anchors_.cigar_left.begin()) {
    if (cigar_it->Length > 0)
      cigar_data.insert(cigar_data.begin(), *cigar_it);
    cigar_it--;
  }
  if (cigar_it == clipped_anchors_.cigar_left.begin() and cigar_it->Length > 0)
    cigar_data.insert(cigar_data.begin(), *cigar_it);

  // Restore right end of cigar string incl. original soft clips
  cigar_it = clipped_anchors_.cigar_right.end()-1;
  if (cigar_it->Type == (cigar_data.end()-1)->Type) {
    (cigar_data.end()-1)->Length += cigar_it->Length;
    cigar_it--;
  } else if ((cigar_data.end()-1)->Type == 'S') {
      if (verbose_)
        cout << "Error, invalid cigar: Soft clipping occurred before right anchor!" << endl;
      return false;
  }
  while (cigar_it > clipped_anchors_.cigar_right.begin()) {
    if (cigar_it->Length > 0)
      cigar_data.push_back(*cigar_it);
    cigar_it--;
  }
  if (cigar_it == clipped_anchors_.cigar_right.begin() and cigar_it->Length > 0)
    cigar_data.push_back(*cigar_it);

  // Restore left end of MD tag
  vector<MDelement>::const_iterator md_it = clipped_anchors_.md_left.end()-1;
  if (clipped_anchors_.md_left.size() > 0) {
    if (md_it->Type[0] != '=') {
      if (verbose_)
        cout << "Error, invalid md tag: Left clipping MD does not end with a match field!" << endl;
      return false;
    }
    MD_data.begin()->Length += md_it->Length;
    md_it--;
    while (md_it != (clipped_anchors_.md_left.begin()-1)) {
      MD_data.insert(MD_data.begin(), *md_it);
      md_it--;
    }
  }

  // Restore right end of MD tag
  if (clipped_anchors_.md_right.size() > 0) {
    md_it = clipped_anchors_.md_right.end()-1;
    if (md_it->Type[0] != '=') {
      if (verbose_)
        cout << "Error, invalid md tag: Right clipping MD does not end with a match field!" << endl;
      return false;
    }
    (MD_data.end()-1)->Length += md_it->Length;
    md_it--;
    while (md_it != (clipped_anchors_.md_right.begin()-1)) {
      MD_data.push_back(*md_it);
      md_it--;
    }
  }

  // Sanity check for newly created tag:
  unsigned int nr_bases = 0;
  for (cigar_it = cigar_data.begin(); cigar_it != cigar_data.end(); cigar_it++) {
    if (cigar_it->Type == 'S' or cigar_it->Type == 'M' or cigar_it->Type == 'I' or cigar_it->Type == '=' or cigar_it->Type == 'X')
      nr_bases += cigar_it->Length;
  }
  if (nr_bases != nr_read_bases) {
    if (verbose_)
      cout << "Warning: generated an erroneous cigar string. Not updating alignment." << endl;
    return false;
  }
  if (verbose_){
    cout << "New cigar tag:";
    for (vector<CigarOp>::const_iterator cigar = cigar_data.begin(); cigar != cigar_data.end(); ++cigar)
      cout << cigar->Length << cigar->Type;
    cout << endl << "New MD tag   : " << GetMDstring(MD_data) << endl;
  }

  return true;
}
bool InstructionContext::MakeExecutable(LPCTSTR szFile, const void* data, size_t dataSize, size_t dataSpaceSize)
{
    //////////////////////////////////////////////////////////////////////////
    // Finalizing code section

    { // safety net
        const BYTE exitCode[] = {
            0x31, 0xC9, 			//xor ecx, ecx
            0xFF, 0x15, 0, 0, 0, 0,	//call []
        };
        imports["kernel32.dll"]["ExitProcess"].push_back(section.size() + 4);
        section.insert(section.end(), std::begin(exitCode), std::end(exitCode));
    }

    const size_t codeEnd = section.size();

    section.push_back(0xCC);
    Align(section, 4, 0xCC);

    const size_t exceptionHandler = section.size();
    { // exception handler
        const BYTE exitCode[] = {
            0x48, 0x8D, 0x0D, 0x45, 0x57, 0x00, 0x00, //lea         rcx,[]  
            0xFF, 0x15, 0xFF, 0xA4, 0x00, 0x00,       //call        qword ptr []  
            0x31, 0xC9, 			//xor ecx, ecx
            0xFF, 0x15, 0, 0, 0, 0,	//call []
        };
        const size_t offset = section.size();
        imports["msvcrt.dll"]["printf"].push_back(offset + 9);
        imports["kernel32.dll"]["ExitProcess"].push_back(offset + 17);
        strings["Error: exception catched\n"].push_back(offset + 3);
        section.insert(section.end(), std::begin(exitCode), std::end(exitCode));
    }

    section.push_back(0xCC);
    Align(section, 4, 0xCC);

    // strings
    for (auto it(strings.begin()), itEnd(strings.end()); it != itEnd; ++it)
    {
        for each(auto offset in it->second)
        {
            uint32_t* pos = (uint32_t*) &section[offset];
            *pos = section.size() - sizeof(uint32_t) - offset;
        }
        BYTE* data = (BYTE*) it->first.c_str();
        section.insert(section.end(), data, data + it->first.length() + 1);
    }
    section.push_back(0);
    Align(section, 16, 0);

    // imports
    map<vector<size_t>*, size_t>  importNames;

    vector<IMAGE_IMPORT_DESCRIPTOR> importDescriptors(imports.size());

    auto itDescriptor = importDescriptors.begin();
    for (auto itModule(imports.begin()); itModule != imports.end(); ++itModule, ++itDescriptor)
    {
        for (auto it(itModule->second.begin()), itEnd(itModule->second.end()); it != itEnd; ++it)
        {
            importNames[&it->second] = SECTIONALIGN + section.size();

            section.push_back(0);
            section.push_back(0);
            BYTE* data = (BYTE*) it->first.c_str();
            section.insert(section.end(), data, data + it->first.length() + 1);
        }
    }
    Align(section, 16, 0);

    itDescriptor = importDescriptors.begin();
    for (auto itModule(imports.begin()); itModule != imports.end(); ++itModule, ++itDescriptor)
    {
        itDescriptor->OriginalFirstThunk = SECTIONALIGN + section.size();

        for (auto it(itModule->second.begin()), itEnd(itModule->second.end()); it != itEnd; ++it)
        {
            uint64_t th = importNames[&it->second];
            section.insert(section.end(), (BYTE*)&th, (BYTE*)(&th + 1));
        }

        section.insert(section.end(), sizeof(uint64_t), 0);
    }
    Align(section, 16, 0);

    itDescriptor = importDescriptors.begin();
    for (auto itModule(imports.begin()); itModule != imports.end(); ++itModule, ++itDescriptor)
    {
        itDescriptor->FirstThunk = SECTIONALIGN + section.size();

        for (auto it(itModule->second.begin()), itEnd(itModule->second.end()); it != itEnd; ++it)
        {

            for each(auto offset in it->second)
            {
                uint32_t* pos = (uint32_t*) &section[offset];
                *pos = section.size() - sizeof(uint32_t) - offset;
            }

            uint32_t th = importNames[&it->second];
            section.insert(section.end(), (BYTE*)&th, (BYTE*)(&th + 1));

            section.insert(section.end(), 4, 0);
        }
    }
    Align(section, 16, 0);

    itDescriptor = importDescriptors.begin();
    for (auto itModule(imports.begin()); itModule != imports.end(); ++itModule, ++itDescriptor)
    {
        itDescriptor->Name = SECTIONALIGN + section.size();
        BYTE* data = (BYTE*) itModule->first.c_str();
        section.insert(section.end(), data, data + itModule->first.length() + 1);
    }
    Align(section, 16, 0);

    // Exceptions
    UNWIND_INFO_ unwindInfo = {};
    unwindInfo.Ver3_Flags = 1 + (UNW_FLAG_EHANDLER << 3);
    const size_t unwindData = section.size();
    section.insert(section.end(), (BYTE*)&unwindInfo, (BYTE*)(&unwindInfo + 1));
    Align(section, 4, 0);
    uint64_t th = SECTIONALIGN + exceptionHandler;
    section.insert(section.end(), (BYTE*)&th, (BYTE*)(&th + 1));
    section.insert(section.end(), sizeof(uint64_t), 0);

    Align(section, 16, 0);

    RUNTIME_FUNCTION_ runtimeFunction = {};
    runtimeFunction.FunctionStart = SECTIONALIGN; // AddressOfEntryPoint
    runtimeFunction.FunctionEnd = SECTIONALIGN + codeEnd;
    runtimeFunction.UnwindInfo = SECTIONALIGN + unwindData;
    const size_t exceptionRuntimeFunction = section.size();
    section.insert(section.end(), (BYTE*)&runtimeFunction, (BYTE*)(&runtimeFunction + 1));

    Align(section, 16, 0);

    // Done with code section

    const size_t codeSectionSize = section.size() + importDescriptors.size() * sizeof(IMAGE_IMPORT_DESCRIPTOR);
    const size_t codeSectionVirtualSize = Align(codeSectionSize, SECTIONALIGN);

    // Data
    //dataMappings
    for (auto itMappings(dataMappings.begin()), itMappingsEnd(dataMappings.end())
        ; itMappings != itMappingsEnd
        ; ++itMappings)
    {
        for (auto it(itMappings->second.begin()), itEnd(itMappings->second.end()); it != itEnd; ++it)
        {
            const size_t dataOffset = codeSectionVirtualSize + it->first;
            for each(auto offset in it->second)
            {
                uint32_t* pos = (uint32_t*) &section[offset];
                *pos = dataOffset - sizeof(uint32_t) - offset - itMappings->first;
            }
        }
    }

    //////////////////////////////////////////////////////////////////////////
    // Preparing executable header structures

    Headers64 headers64 = {};

    headers64.dosHeader.e_magic = 'ZM';
    headers64.dosHeader.e_lfanew = offsetof(Headers64, ntHeaders);

    headers64.ntHeaders.Signature = 'EP';

    auto& fileHeader = headers64.ntHeaders.FileHeader;
    fileHeader.Machine = IMAGE_FILE_MACHINE_AMD64;
    fileHeader.NumberOfSections = NUMBEROFSECTIONS;
    fileHeader.SizeOfOptionalHeader = sizeof(headers64.ntHeaders.OptionalHeader);
    fileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_32BIT_MACHINE;

    auto& optionalHeader = headers64.ntHeaders.OptionalHeader;
    optionalHeader.Magic                 = IMAGE_NT_OPTIONAL_HDR64_MAGIC;

    //optionalHeader.AddressOfEntryPoint   = EntryPoint - IMAGEBASE;

    optionalHeader.ImageBase             = IMAGEBASE;
    optionalHeader.SectionAlignment      = SECTIONALIGN;
    optionalHeader.FileAlignment         = FILEALIGN;
    optionalHeader.MajorSubsystemVersion = 4;
    optionalHeader.SizeOfImage           = 2 * SECTIONALIGN;
    optionalHeader.SizeOfHeaders         = sizeof(Headers64);
    optionalHeader.Subsystem             = IMAGE_SUBSYSTEM_WINDOWS_CUI;
    optionalHeader.NumberOfRvaAndSizes   = 16;

    headers64.sectionHeaders[0].Misc.VirtualSize = SECTIONALIGN;
    headers64.sectionHeaders[0].VirtualAddress   = SECTIONALIGN;
    headers64.sectionHeaders[0].SizeOfRawData    = FILEALIGN;
    headers64.sectionHeaders[0].PointerToRawData = FILEALIGN;

    headers64.sectionHeaders[0].Characteristics  = IMAGE_SCN_MEM_EXECUTE;// | IMAGE_SCN_MEM_WRITE;

    headers64.sectionHeaders[1].Misc.VirtualSize = SECTIONALIGN;
    headers64.sectionHeaders[1].VirtualAddress   = SECTIONALIGN;
    headers64.sectionHeaders[1].SizeOfRawData    = FILEALIGN;
    headers64.sectionHeaders[1].PointerToRawData = FILEALIGN;

    headers64.sectionHeaders[1].Characteristics  = IMAGE_SCN_MEM_WRITE;

    optionalHeader.AddressOfEntryPoint   = SECTIONALIGN;// + section.size();

    optionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress 
        = section.size() + SECTIONALIGN;

    optionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION].VirtualAddress 
        = exceptionRuntimeFunction + SECTIONALIGN;
    optionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size = sizeof(RUNTIME_FUNCTION_);

    // Fixing sizes

    headers64.sectionHeaders[0].Misc.VirtualSize = codeSectionVirtualSize; //
    headers64.sectionHeaders[0].SizeOfRawData    = Align(codeSectionSize, FILEALIGN);

    headers64.sectionHeaders[1].VirtualAddress 
        = headers64.sectionHeaders[0].VirtualAddress + headers64.sectionHeaders[0].Misc.VirtualSize;
    headers64.sectionHeaders[1].PointerToRawData 
        = headers64.sectionHeaders[0].PointerToRawData + headers64.sectionHeaders[0].SizeOfRawData;

    assert(dataSize <= dataSpaceSize);
    headers64.sectionHeaders[1].Misc.VirtualSize = Align(REGISTER_TABLE_SIZE + dataSpaceSize, SECTIONALIGN); //
    headers64.sectionHeaders[1].SizeOfRawData    = (dataSize > 0) ? Align(REGISTER_TABLE_SIZE + dataSize, FILEALIGN) : 0;

    optionalHeader.SizeOfImage
        = SECTIONALIGN + headers64.sectionHeaders[0].Misc.VirtualSize + headers64.sectionHeaders[1].Misc.VirtualSize;

    //////////////////////////////////////////////////////////////////////////
    // Writing exe image

    HANDLE handle = CreateFile(
        szFile,
        GENERIC_WRITE,
        0,
        0,
        CREATE_ALWAYS,
        FILE_FLAG_SEQUENTIAL_SCAN,
        NULL);
    if (handle == INVALID_HANDLE_VALUE)
    {
        cerr << "Cannot create exe file.\n";
        return false;
    }

    LARGE_INTEGER size;
    size.QuadPart 
        = FILEALIGN + headers64.sectionHeaders[0].SizeOfRawData 
        + headers64.sectionHeaders[1].SizeOfRawData;
    SetFilePointerEx(handle, size, 0, FILE_BEGIN);
    SetEndOfFile(handle);
    SetFilePointer(handle, 0, 0, FILE_BEGIN);

    DWORD numberOfBytesWritten = 0;
    WriteFile(handle, &headers64, sizeof(headers64), &numberOfBytesWritten, NULL);

    SetFilePointer(handle, FILEALIGN, 0, FILE_BEGIN);
    WriteFile(handle, section.data(), section.size(), &numberOfBytesWritten, NULL); 
    WriteFile(
            handle, 
            importDescriptors.data(), 
            importDescriptors.size() * sizeof(IMAGE_IMPORT_DESCRIPTOR), 
            &numberOfBytesWritten, 
            NULL); 

    // handle data
    if (dataSize > 0)
    {
        SetFilePointer(handle, FILEALIGN + headers64.sectionHeaders[0].SizeOfRawData + REGISTER_TABLE_SIZE, 0, FILE_BEGIN);
        WriteFile(handle, data, dataSize, &numberOfBytesWritten, NULL);
    }

    CloseHandle(handle);

    return true;
}
Example #9
0
bool ReadStarRecord(istream& in)
{
    HipparcosStar star;
    char buf[HipStarRecordLength];

    in.read(buf, HipStarRecordLength);
    
    if (sscanf(buf + 2, "%d", &star.HIPCatalogNumber) != 1)
    {
        cout << "Error reading catalog number.\n";
        return false;
    }

    sscanf(buf + 390, "%d", &star.HDCatalogNumber);

    if (sscanf(buf + 41, "%f", &star.appMag) != 1)
    {
        cout << "Error reading magnitude.\n";
        return false;
    }

    if (sscanf(buf + 79, "%f", &star.parallax) != 1)
    {
        // cout << "Error reading parallax.\n";
    }

    bool coordReadError = false;
    if (sscanf(buf + 51, "%f", &star.ascension) != 1)
        coordReadError = true;
    if (sscanf(buf + 64, "%f", &star.declination) != 1)
        coordReadError = true;
    star.ascension = (float) (star.ascension * 24.0 / 360.0);

    // Read the lower resolution coordinates in hhmmss form if we failed
    // to read the coordinates in degrees.  Not sure why the high resolution
    // coordinates are occasionally missing . . .
    if (coordReadError)
    {
        int hh = 0;
        int mm = 0;
        float seconds;
        if (sscanf(buf + 17, "%d %d %f", &hh, &mm, &seconds) != 3)
        {
            cout << "Error reading ascension.\n";
            return false;
        }
        star.ascension = hh + (float) mm / 60.0f + (float) seconds / 3600.0f;
    
        char decSign;
        int deg;
        if (sscanf(buf + 29, "%c%d %d %f", &decSign, &deg, &mm, &seconds) != 4)
        {
            cout << "Error reading declination.\n";
            return false;
        }
        star.declination = deg + (float) mm / 60.0f + (float) seconds / 3600.0f;
        if (decSign == '-')
            star.declination = -star.declination;
    }

    char* spectralType = buf + 435;
    spectralType[12] = '\0';
    star.stellarClass = ParseStellarClass(spectralType);

    int asc = 0;
    int dec = 0;
    char decSign = ' ';
    if (sscanf(buf + 327, "%d%c%d", &asc, &decSign, &dec) == 3)
    {
        if (decSign == '-')
            dec = -dec;
        star.CCDMIdentifier = asc << 16 | (dec & 0xffff);

        int n = 1;
        sscanf(buf + 340, "%d", &n);
        star.starsWithCCDM = (uint8) n;
        sscanf(buf + 343, "%d", &n);
        star.nComponents = (uint8) n;
    }

    float parallaxError = 0.0f;
    if (sscanf(buf + 119, "%f", &parallaxError) != 0)
    {
        if (star.parallax < 0.0f || parallaxError / star.parallax > 1.0f)
            star.parallaxError = (int8) 255;
        else
            star.parallaxError = (int8) (parallaxError / star.parallax * 200);
    }
    
    stars.insert(stars.end(), star);

    return true;
}
Example #10
0
bool DevEffect::GetPrecompiledBinary(
		vector<char> &data, const char *id, const char *path, const char *bpath,
		vector<D3DXMACRO> &macros, byte hash[16], vector<byte> &bin)
{
	ID3DXEffectCompiler *fxc = NULL;
	ID3DXBuffer *binbuff = NULL;
	ID3DXBuffer *errors = NULL;


	if(_load_scrambled(bpath,*(vector<byte>*)&bin) && bin.size()>16)
	{
		if(memcmp(&bin[0],hash,16)==0)
		{
			bin.erase(bin.begin(),bin.begin()+16);
			return true;
		}
	}

	for(int pass=0;pass<2;pass++)
	{
		HRESULT r;
		bool error;
		
		if( pass == 0 )
		{
			r = D3DXCreateEffectCompiler(&data[0],(DWORD)data.size(),&macros[0],NULL,
					compile_flags,&fxc,&errors);
			error = !fxc;
		}
		else
		{
			r = fxc->CompileEffect(compile_flags,&binbuff,&errors);
			error = !binbuff;
		}

		if(FAILED(r) || errors || error)
		{
			if(errors)
			{
				last_error = format("%s:%s: %s",path,id,(char*)errors->GetBufferPointer());
				if(!(flags&FXF_NO_ERROR_POPUPS))
					if(MessageBox(NULL,last_error.c_str(),format("%s:%s",path,id).c_str(),MB_OKCANCEL)==IDCANCEL)
						ExitProcess(0);
				errors->Release();
				if(fxc) fxc->Release();
				if(binbuff) binbuff->Release();
				return false;
			}
			else
			{
				last_error = format("%s:%s: Unknown error!",path,id);
				if(!(flags&FXF_NO_ERROR_POPUPS))
					if(MessageBox(NULL,last_error.c_str(),format("%s:%s",path,id).c_str(),MB_OKCANCEL)==IDCANCEL)
						ExitProcess(0);
				if(fxc) fxc->Release();
				if(binbuff) binbuff->Release();
				return false;
			}
		}
	}

	bin.clear();
	bin.insert(bin.end(),hash,hash+16);
	bin.insert(bin.end(),(byte*)binbuff->GetBufferPointer(),((byte*)binbuff->GetBufferPointer())+binbuff->GetBufferSize());

	fxc->Release();
	binbuff->Release();

	_save_scrambled(bpath,bin);

	bin.erase(bin.begin(),bin.begin()+16);

	return true;
}
bool InstructionContext::AddInstruction(
    BYTE instruction, 
    signed char dst, 
    signed char src, 
    size_t instructionNumber,
    uint32_t dataSize)
{
    const size_t offset = section.size();
    trace("%4d ", instructionNumber);
    switch (instruction)
    {
    case 32:
        trace("NOP\n");
        break; // nop

    case 40: // IN reg read hexadecimal value from standard input, and store in registry reg reg <- stdin
        {
            trace("IN reg%d <- stdin\n", dst);
            VERIFY_REGISTER_IDX (dst);
            const BYTE scanCode[] = {
                0x48, 0x8D, 0x15, 0x18, 0x81, 0x00, 0x00, //lea         rdx,[]  
                0x48, 0x8D, 0x0D, 0x51, 0x57, 0x00, 0x00, //lea         rcx,[]  
                0xFF, 0x15, 0x0B, 0xA5, 0x00, 0x00,		  //call        qword ptr []  
                0x85, 0xC0,             //test        eax,eax  
                0x75, 0x15,             //jne
                0x48, 0x8D, 0x0D, 0x45, 0x57, 0x00, 0x00, //lea         rcx,[]  
                0xFF, 0x15, 0xFF, 0xA4, 0x00, 0x00,       //call        qword ptr []  
                0x31, 0xC9, 			//xor ecx, ecx
                0xFF, 0x15, 0, 0, 0, 0,	//call []
            };
            dataMappings[0][REGISTER_SIZE * dst].push_back(offset + 3);

            imports["msvcrt.dll"]["scanf"].push_back(offset + 16);
            strings["%I64X"].push_back(offset + 10);

            imports["msvcrt.dll"]["printf"].push_back(offset + 9 + 24);
            imports["kernel32.dll"]["ExitProcess"].push_back(offset + 17 + 24);
            strings["Error: Unable to read stdin\n"].push_back(offset + 3 + 24);

            section.insert(section.end(), std::begin(scanCode), std::end(scanCode));
        }
        break;

    case 41: // OUT reg write hexadecimal value in registry reg to standard output stdout <- reg
        {
            trace("OUT stdout <- reg%d\n", dst);
            VERIFY_REGISTER_IDX (dst);
            const BYTE printCode[] = {
                0x48, 0x8B, 0x15, 0x04, 0x81, 0x00, 0x00, //mov         rdx,qword ptr []  
                0x48, 0x8D, 0x0D, 0x45, 0x57, 0x00, 0x00, //lea         rcx,[]  
                0xFF, 0x15, 0xFF, 0xA4, 0x00, 0x00,       //call        qword ptr []  
            };
            imports["msvcrt.dll"]["printf"].push_back(offset + 16);
            strings["%016I64X\n"].push_back(offset + 10);
            dataMappings[0][REGISTER_SIZE * dst].push_back(offset + 3);
            section.insert(section.end(), std::begin(printCode), std::end(printCode));
        }
        break;

    case 48: // STORE reg1,reg2 store value of reg2 in memory cell pointed by reg1 [reg1] = reg2
        {
            trace("STORE [reg%d] = reg%d\n", dst, src);
            if (dataSize < REGISTER_SIZE)
            {
                cerr << "Error: dataSize is too small\n"; 
                return false;
            }
            VERIFY_REGISTER_IDX (src);
            VERIFY_REGISTER_IDX (dst);
            const BYTE code[] = {
                0x48, 0x8D, 0x05, 0x0D, 0x81, 0x00, 0x00, //lea         rax,[]  
                0x48, 0x8B, 0x0D, 0x0E, 0x85, 0x00, 0x00, //mov         rcx,qword ptr []

                0x48, 0x81, 0xF9, 0x10, 0x27, 0x00, 0x00, //cmp    rcx,0x2710
                0x7E, 0x15,                //jle

                0x48, 0x8D, 0x0D, 0x45, 0x57, 0x00, 0x00, //lea         rcx,[]  
                0xFF, 0x15, 0xFF, 0xA4, 0x00, 0x00,       //call        qword ptr []  
                0x31, 0xC9, 			//xor ecx, ecx
                0xFF, 0x15, 0, 0, 0, 0,	//call []

                0x48, 0x8B, 0x15, 0xFF, 0x84, 0x00, 0x00, //mov         rdx,qword ptr []  
                0x48, 0x89, 0x14, 0x08,                   //mov         qword ptr [rax+rcx],rdx  
            };
            dataMappings[0][REGISTER_TABLE_SIZE].push_back(offset + 3);
            dataMappings[0][REGISTER_SIZE * dst].push_back(offset + 10);

            imports["msvcrt.dll"]["printf"].push_back(offset + 9 + 23);
            imports["kernel32.dll"]["ExitProcess"].push_back(offset + 17 + 23);
            strings["Error: Runtime memory offset out of bounds\n"].push_back(offset + 3 + 23);

            dataMappings[0][REGISTER_SIZE * src].push_back(offset + 17 + 30);
            section.insert(section.end(), std::begin(code), std::end(code));
            uint32_t* pos = (uint32_t*) &section[offset + 17];
            *pos = dataSize - REGISTER_SIZE;
        }
        break;

    case 49: // LOAD reg1, reg2  load value from memory cell pointed by reg1 into register reg2 reg1 = [reg2]
        {
            trace("LOAD reg%d = [reg%d]\n", dst, src);
            if (dataSize < REGISTER_SIZE)
            {
                cerr << "Error: dataSize is too small\n"; 
                return false;
            }
            VERIFY_REGISTER_IDX (src);
            VERIFY_REGISTER_IDX (dst);
            const BYTE code[] = {
                0x48, 0x8D, 0x05, 0x0D, 0x81, 0x00, 0x00, //lea         rax,[]  
                0x48, 0x8B, 0x0D, 0x0E, 0x85, 0x00, 0x00, //mov         rcx,qword ptr []  

                0x48, 0x81, 0xF9, 0x10, 0x27, 0x00, 0x00, //cmp    rcx,0x2710
                0x7E, 0x15,                //jle

                0x48, 0x8D, 0x0D, 0x45, 0x57, 0x00, 0x00, //lea         rcx,[]  
                0xFF, 0x15, 0xFF, 0xA4, 0x00, 0x00,       //call        qword ptr []  
                0x31, 0xC9, 			//xor ecx, ecx
                0xFF, 0x15, 0, 0, 0, 0,	//call []

                0x48, 0x8B, 0x04, 0x08,                   //mov         rax,qword ptr [rax+rcx]  
                0x48, 0x89, 0x05, 0xFB, 0x84, 0x00, 0x00, //mov         qword ptr [],rax  
            };
            dataMappings[0][REGISTER_TABLE_SIZE].push_back(offset + 3);
            dataMappings[0][REGISTER_SIZE * src].push_back(offset + 10);

            imports["msvcrt.dll"]["printf"].push_back(offset + 9 + 23);
            imports["kernel32.dll"]["ExitProcess"].push_back(offset + 17 + 23);
            strings["Error: Runtime memory offset out of bounds\n"].push_back(offset + 3 + 23);

            dataMappings[0][REGISTER_SIZE * dst].push_back(offset + 21 + 30);
            section.insert(section.end(), std::begin(code), std::end(code));
            uint32_t* pos = (uint32_t*) &section[offset + 17];
            *pos = dataSize - REGISTER_SIZE;
        }
        break;

    case 50: // LDC reg, imm8 load 8-bit immediate value to reg reg = imm8 (unsigned)
        {
            const uint32_t imm = unsigned char(src);
            trace("LDC reg%d = %d\n", dst, imm);
            VERIFY_REGISTER_IDX (dst);
            const BYTE code[] = {
                0x48, 0xC7, 0x05, 0xDC, 0x66, 0x00, 0x00, //mov         qword ptr [value (140009558h)], ...  
            };
            dataMappings[4][REGISTER_SIZE * dst].push_back(offset + 3);
            section.insert(section.end(), std::begin(code), std::end(code));
            section.insert(section.end(), (const BYTE*)&imm, (const BYTE*)(&imm + 1));
        }
        break;

    case 64: // MOV reg1, reg2  copy value from register2 to register1 reg1 = reg2
        {
            trace("MOV reg%d = reg%d\n", dst, src);
            VERIFY_REGISTER_IDX (src);
            VERIFY_REGISTER_IDX (dst);
            const BYTE code[] = {
                0x48, 0x8B, 0x05, 0xD5, 0x66, 0x00, 0x00, //mov         rax,qword ptr []  
                0x48, 0x89, 0x05, 0xC6, 0x66, 0x00, 0x00, //mov         qword ptr [],rax  
            };
            dataMappings[0][REGISTER_SIZE * src].push_back(offset + 3);
            dataMappings[0][REGISTER_SIZE * dst].push_back(offset + 10);
            section.insert(section.end(), std::begin(code), std::end(code));
        }
        break;

    case 65: // ADD reg1, reg2 add value of reg2 to reg1, and save result in reg1 reg1 = reg1 + reg2
        {
            trace("ADD reg%d += reg%d\n", dst, src);
            VERIFY_REGISTER_IDX (src);
            VERIFY_REGISTER_IDX (dst);
            const BYTE code[] = {
                0x48, 0x8B, 0x05, 0xD5, 0x66, 0x00, 0x00, //mov         rax,qword ptr []  
                0x48, 0x8B, 0x0D, 0xC6, 0x66, 0x00, 0x00, //mov         rcx,qword ptr []  
                0x48, 0x03, 0xC8,                         //add         rcx,rax  
                0x48, 0x8B, 0xC1,                         //mov         rax,rcx  
                0x48, 0x89, 0x05, 0xB9, 0x66, 0x00, 0x00, //mov         qword ptr [],rax  
            };
            dataMappings[0][REGISTER_SIZE * src].push_back(offset + 3);
            dataMappings[0][REGISTER_SIZE * dst].push_back(offset + 10);
            dataMappings[0][REGISTER_SIZE * dst].push_back(offset + 23);
            section.insert(section.end(), std::begin(code), std::end(code));
        }
        break;

    case 66: // SUB reg1, reg2 subtract value of reg2 from reg1, and save result in reg1
        {
            trace("SUB reg%d -= reg%d\n", dst, src);
            VERIFY_REGISTER_IDX (src);
            VERIFY_REGISTER_IDX (dst);
            const BYTE code[] = {
                0x48, 0x8B, 0x05, 0xD5, 0x66, 0x00, 0x00, //mov         rax,qword ptr []  
                0x48, 0x8B, 0x0D, 0xC6, 0x66, 0x00, 0x00, //mov         rcx,qword ptr []  
                0x48, 0x2B, 0xC8,                         //sub         rcx,rax
                0x48, 0x8B, 0xC1,                         //mov         rax,rcx  
                0x48, 0x89, 0x05, 0xB9, 0x66, 0x00, 0x00, //mov         qword ptr [],rax  
            };
            dataMappings[0][REGISTER_SIZE * src].push_back(offset + 3);
            dataMappings[0][REGISTER_SIZE * dst].push_back(offset + 10);
            dataMappings[0][REGISTER_SIZE * dst].push_back(offset + 23);
            section.insert(section.end(), std::begin(code), std::end(code));
        }
        break;

    case 67: // MUL reg1, reg2 multiplies value of reg1 by value of reg2 and save result in reg1 reg1 = reg1 * reg2
        {
            trace("MUL reg%d *= reg%d\n", dst, src);
            VERIFY_REGISTER_IDX (src);
            VERIFY_REGISTER_IDX (dst);
            const BYTE code[] = {
                0x48, 0x8B, 0x05, 0x97, 0x66, 0x00, 0x00, //mov         rax,qword ptr []  
                0x48, 0x0F, 0xAF, 0x05, 0x97, 0x66, 0x00, 0x00, //imul  rax,qword ptr []  
                0x48, 0x89, 0x05, 0x88, 0x66, 0x00, 0x00, //mov         qword ptr [],rax  
            };
            dataMappings[0][REGISTER_SIZE * dst].push_back(offset + 3);
            dataMappings[0][REGISTER_SIZE * src].push_back(offset + 11);
            dataMappings[0][REGISTER_SIZE * dst].push_back(offset + 18);
            section.insert(section.end(), std::begin(code), std::end(code));
        }
        break;

    case 68: // DIV reg1, reg2 divides value of reg1 by value of reg2 and save result in reg1 reg1 = reg1 / reg2
        {
            trace("DIV reg%d /= reg%d\n", dst, src);
            VERIFY_REGISTER_IDX (src);
            VERIFY_REGISTER_IDX (dst);
            const BYTE code[] = {
                0x48, 0x8B, 0x05, 0x81, 0x66, 0x00, 0x00, //mov         rax,qword ptr []  
                0x48, 0x99,							      //cqo  
                0x48, 0xF7, 0x3D, 0x80, 0x66, 0x00, 0x00, //idiv        rax,qword ptr []  
                0x48, 0x89, 0x05, 0x71, 0x66, 0x00, 0x00, //mov         qword ptr [],rax  
            };
            dataMappings[0][REGISTER_SIZE * dst].push_back(offset + 3);
            dataMappings[0][REGISTER_SIZE * src].push_back(offset + 12);
            dataMappings[0][REGISTER_SIZE * dst].push_back(offset + 19);
            section.insert(section.end(), std::begin(code), std::end(code));
        }
        break;

    case 69: // MOD reg1, reg2 calculates reminder of division of reg1 by reg2 and save result in reg1 reg1 = reg1 % reg2
        {
            trace("MOD reg%d %%= reg%d\n", dst, src);
            VERIFY_REGISTER_IDX (src);
            VERIFY_REGISTER_IDX (dst);
            const BYTE code[] = {
                0x48, 0x8B, 0x05, 0x6A, 0x66, 0x00, 0x00, //mov         rax,qword ptr []  
                0x48, 0x99,					              //cqo  
                0x48, 0xF7, 0x3D, 0x69, 0x66, 0x00, 0x00, //idiv        rax,qword ptr []  
                0x48, 0x8B, 0xC2,						  //mov         rax,rdx  
                0x48, 0x89, 0x05, 0x57, 0x66, 0x00, 0x00, //mov         qword ptr [],rax  
            };
            dataMappings[0][REGISTER_SIZE * dst].push_back(offset + 3);
            dataMappings[0][REGISTER_SIZE * src].push_back(offset + 12);
            dataMappings[0][REGISTER_SIZE * dst].push_back(offset + 22);
            section.insert(section.end(), std::begin(code), std::end(code));
        }
        break;

    case 97: //JZ reg, imm8  if value of reg is zero, does relative jump. if reg1 == 0: IP = IP + imm8
        {
            trace("JZ reg%d, %d\n", dst, src + instructionNumber + 1);
            VERIFY_REGISTER_IDX (dst);
            const BYTE code[] = {
                0x48, 0x83, 0x3D, 0xCC, 0x66, 0x00, 0x00, 0x00, //cmp         qword ptr [],0  
                0x75, 0x05,							            //jne
                0xE9, 0x45, 0x01, 0x00, 0x00,                   //jmp         $
            };
            dataMappings[1][REGISTER_SIZE * dst].push_back(offset + 3);
            jumps[instructionNumber + src].push_back(offset + 11);
            section.insert(section.end(), std::begin(code), std::end(code));
        }
        break;

    case 98: //JL reg, imm8 if value of reg is less then zero, does relative jump. if reg1 < 0: IP = IP + imm8
        {
            trace("JL reg%d, %d\n", dst, src + instructionNumber + 1);
            VERIFY_REGISTER_IDX (dst);
            const BYTE code[] = {
                0x48, 0x83, 0x3D, 0xCC, 0x66, 0x00, 0x00, 0x00, //cmp         qword ptr [],0  
                0x7D, 0x05,							            //jge  
                0xE9, 0x45, 0x01, 0x00, 0x00,                   //jmp         $
            };
            dataMappings[1][REGISTER_SIZE * dst].push_back(offset + 3);
            jumps[instructionNumber + src].push_back(offset + 11);
            section.insert(section.end(), std::begin(code), std::end(code));
        }
        break;

    case 99: //JUMP imm16 unconditional relative jump by imm16. IP = IP + imm16
        {
            short imm16 = (short)MAKEWORD(dst, src);
            trace("JUMP %d\n", imm16 + instructionNumber + 1);

            const BYTE code[] = {
                0xE9, 0x45, 0x01, 0x00, 0x00,       //jmp         $
            };
            jumps[instructionNumber + imm16].push_back(offset + 1);
            section.insert(section.end(), std::begin(code), std::end(code));
        }
        break;

    case 100:	// CALL imm16 stores next instruction pointer on internal stack and jumps by imm16. 
                // save IP of next instruction to call stack JMP imm16
        {
            short imm16 = (short)MAKEWORD(dst, src);
            trace("CALL %d\n", imm16 + instructionNumber + 1);

            const BYTE code[] = {
                0xE8, 0x12, 0x00, 0x00, 0x00,       //call
            };
            jumps[instructionNumber + imm16].push_back(offset + 1);
            section.insert(section.end(), std::begin(code), std::end(code));
        }
        break;

    case 101:	//RET reads absolute instruction pointer from stack and jumps to it (returns to next instruction after corresponding CALL)
                // restore IP from call stack IP = saved_IP
        {
            trace("RET\n");
            section.push_back(0xC3); //                   ret
        }
        break;

    case 126: // HLT ends program, terminates execution
        {
            trace("HLT\n");
            const BYTE exitCode[] = {
                0x31, 0xC9, 			//xor ecx, ecx
                0xFF, 0x15, 0, 0, 0, 0,	//call []
            };
            imports["kernel32.dll"]["ExitProcess"].push_back(offset + 4);
            section.insert(section.end(), std::begin(exitCode), std::end(exitCode));
        }
        break;

    default:
        cerr << "Invalid instruction code.\n";
        return false;
    }

    return true;
}
Example #12
0
void CodeGenerator::appendVectors(vector<string>& v1, vector<string> v2)
{
    v1.reserve(v1.size() + v2.size());
    v1.insert(v1.end(), v2.begin(), v2.end());
}
void intersect2Dcurves(const ParamCurve* cv1, const ParamCurve* cv2, double epsge,
		       vector<pair<double,double> >& intersections,
		       vector<int>& pretopology,
		       vector<pair<pair<double,double>, pair<double,double> > >& int_crvs)
  //************************************************************************
  // 
  // Intersect two 2D spline curves. Collect intersection parameters
  // and pretopology information.
  //
  //***********************************************************************
{

  // First make sure that the curves are spline curves.
    ParamCurve* tmpcv1 = const_cast<ParamCurve*>(cv1);
    ParamCurve* tmpcv2 = const_cast<ParamCurve*>(cv2);
    SplineCurve* sc1 = tmpcv1->geometryCurve();
    SplineCurve* sc2 = tmpcv2->geometryCurve();
    if (sc1 == NULL || sc2 == NULL)
        THROW("ParamCurves doesn't have a spline representation.");

    MESSAGE_IF(cv1->dimension() != 2,
		"Dimension different from 2, pretopology not reliable.");

  // Make sisl curves and call sisl.
  SISLCurve *pc1 = Curve2SISL(*sc1, false);
  SISLCurve *pc2 = Curve2SISL(*sc2, false);

  int kntrack = 0;
  int trackflag = 0;  // Do not make tracks.
  SISLTrack **track =0;
  int knpt=0, kncrv=0;
  double *par1=0, *par2=0;
  int *pretop = 0;
  SISLIntcurve **vcrv = 0;
  int stat = 0;
  sh1857(pc1, pc2, 0.0, epsge, trackflag, &kntrack, &track,
	 &knpt, &par1, &par2, &pretop, &kncrv, &vcrv, &stat);

  ALWAYS_ERROR_IF(stat<0,"Error in intersection, code: " << stat);


  // Remember intersections points. 
  int ki;
  for (ki=0; ki<knpt; ki++)
    {
      intersections.push_back(std::make_pair(par1[ki],par2[ki]));
      pretopology.insert(pretopology.end(), pretop+4*ki, pretop+4*(ki+1));
    }

  // Remember intersection curves
  for (ki=0; ki<kncrv; ++ki)
    int_crvs.push_back(std::make_pair(std::make_pair(vcrv[ki]->epar1[0], vcrv[ki]->epar2[0]), 
				      std::make_pair(vcrv[ki]->epar1[vcrv[ki]->ipoint-1],
						     vcrv[ki]->epar2[vcrv[ki]->ipoint-1])));

  if (kncrv > 0)
    freeIntcrvlist(vcrv, kncrv);

  if (par1 != 0) free(par1);
  if (par2 != 0) free(par2);
  if (pc1 != 0) freeCurve(pc1);
  if (pc2 != 0) freeCurve(pc2);
  if (pretop != 0) free(pretop);

  delete sc1;
  delete sc2;
}
Example #14
0
int main(int argc, char *argv[]) {

  //get the initial coordinate positions
  for(int i = 0; i < argc; i++) {
    if(argv[i][0] == '+') {
      sscanf(argv[i], "+%d,%d,%d", &cur_file_posy, &cury, &curx);
    }
  }

  //create interrupt ^C to break
  signal(SIGINT, finish);

  //initialize library
  initscr();

  if(has_colors()) {
    start_color();
    init_pair(1, COLOR_GREEN, COLOR_BLACK);
    init_pair(2, COLOR_BLACK, COLOR_WHITE);
    attron(COLOR_PAIR(1));
  }

  //enable keyboard mapping
  keypad(stdscr, TRUE);

  //do not convert \n to \r\n
  nonl();

  //take input one character at a time and do not wait for \n
  cbreak();

  //disable automatic echo
  noecho();

  idlok(stdscr, TRUE);
  scrollok(stdscr, TRUE);

  //keep track of the current mode
  it_mode_t mode = mode_base;

  getmaxyx(stdscr, winy, winx);
  winy = winy - footer_height;

  //get the buffer_lines from the program string
  istringstream program_str_stream(program_str);
  string line;
  while(getline(program_str_stream, line)) {
    program_lines.push_back(line);
  }
  buffer_lines.insert(buffer_lines.begin(), program_lines.begin(), program_lines.end());

  //ensure our specified initial starting coordinates do not go past the max
  if(cur_file_posy > buffer_lines.size()-1) {
    cur_file_posy = buffer_lines.size()-1;
  }
  if(cury > cur_file_posy) {
    cury = cur_file_posy;
  }
  if(curx > buffer_lines[cur_file_posy].size()) {
    curx = buffer_lines[cur_file_posy].size();
  }

  //print the screen with the program string
  rewrite_buffer(cur_file_posy, curx, cury);

  //get the initial coordinate positions
  for(int i = 0; i < argc; i++) {
    string arg = argv[i];
    if(arg == "-r") {
      move(winy+1, 0);
      attron(COLOR_PAIR(2));
      addstr("REWRITE SUCCESS");
      attron(COLOR_PAIR(1));
      move(cury, curx);
    }
  }

  //infinitely loop over getting input
  int buffer_contents = it_buffer_program;
  for(;;) {
    getyx(stdscr, cury, curx);
    getmaxyx(stdscr, winy, winx);
    winy = winy - footer_height;

    switch(mode) {
      case mode_base: {
        int c = getch();

        //enter insert mode
        if(c == 'i') {
          if(buffer_contents == it_buffer_program) {
            mode = mode_insert;
          }
        }

        //quit
        else if(c == 'q') {
          finish(0);
        }

        //rewrite the program
        else if(c == 'w') {

          //save the buffer into the lines of the program
          program_lines.clear();
          program_lines.insert(program_lines.begin(), buffer_lines.begin(), buffer_lines.end());

          //recreate the program string
          program_str = "";
          for(auto line : program_lines) {
            program_str += line + '\n';
          }

          rewrite_program(program_str, &compile_output);

          //determine and show the result
          if(compile_output.size() > 0) {
            move(winy+1, 0);
            attron(COLOR_PAIR(2));
            addstr("REWRITE ERROR: type 'o' in command mode to see the output");
            attron(COLOR_PAIR(1));
            move(cury, curx);
          }
          else {
            move(winy+1, 0);
            addstr("REWRITE SUCCESS");
            move(cury, curx);
            string restart_str = "./it +" + to_string(cur_file_posy) + "," + to_string(cury) + "," + to_string(curx) + " -r";
            system(restart_str.c_str());
            finish(0);
          }
        }

        //show compile output
        else if(c == 'o') {

          if(buffer_contents == it_buffer_program) {
            program_lines.clear();
            program_lines.insert(program_lines.begin(), buffer_lines.begin(), buffer_lines.end());
            buffer_lines.clear();
            buffer_lines.insert(buffer_lines.begin(), compile_output.begin(), compile_output.end());
            buffer_contents = it_buffer_compile_output;

            pcury = cury;
            pcurx = curx;
            p_start_posy = cur_file_posy;
            rewrite_buffer(0, 0, 0);
          }
          else if(buffer_contents == it_buffer_compile_output) {
            buffer_lines.clear();
            buffer_lines.insert(buffer_lines.begin(), program_lines.begin(), program_lines.end());
            buffer_contents = it_buffer_program;

            cury = pcury;
            curx = pcurx;
            rewrite_buffer(p_start_posy, curx, cury);
          }
        }

        //save to file
        else if(c == 's') {
          FILE *fp = fopen("main.cpp", "w");
          for(auto line : buffer_lines) {
            string newline = line + "\n";
            fwrite(newline.c_str(), sizeof(char), newline.size(), fp);
          }
        }

        //move the cursor around with hjkl
        else if(c == 'h' || c == 'j' || c == 'k' || c == 'l') {

          //remove any messages
          move(winy+footer_height-1, 0);
          clrtoeol();

          if(c == 'h') {
            if(cur_file_posx > 0) {
              cur_file_posx = curx-1;
              curx = cur_file_posx;
            }
          }
          else if(c == 'j') {
            if(cury < min(winy-1, buffer_lines.size()-1)) {
              cur_file_posy++;
              cury++;
            }
            else if(cur_file_posy < buffer_lines.size()-1) {
              scroll(stdscr);
              cur_file_posy++;
              move(cury, 0);
              addstr(buffer_lines[cur_file_posy].c_str());
            }

            //ensure we are placed correctly on the x axis
            curx = cur_file_posx;
          }
          else if(c == 'k') {
            if(cury > 0) {
              cur_file_posy--;
              cury--;
            }
            else if(cur_file_posy > 0) {
              scrl(-1);
              cur_file_posy--;
              move(cury, 0);
              addstr(buffer_lines[cur_file_posy].c_str());
            }

            //clear the footer lines
            for(int i = winy; i < winy+footer_height; i++) {
              move(i, 0);
              clrtoeol();
            }

            //ensure we are placed correctly on the x axis
            curx = cur_file_posx;
          }
          else if(c == 'l') {
            if(curx < winx) {
              cur_file_posx = curx+1;
              curx = cur_file_posx;
            }
          }

          //restrict the cursor's x coordinate to the length of the string
          if(curx >= buffer_lines[cur_file_posy].size()) {
            curx = buffer_lines[cur_file_posy].size();
          }
          move(cury, curx);
        }

        break;
      }

      case mode_insert: {
        int c = getch();

        //go back to base mode
        if(c == 27) {
          mode = mode_base;
        }

        //handle newlines by scrolling up and splitting buffer_lines
        else if(c == '\r') {
          string line_start = buffer_lines[cur_file_posy].substr(0, curx);
          string line_end = buffer_lines[cur_file_posy].substr(curx, buffer_lines[cur_file_posy].size()-curx);

          //rewrite the current line
          buffer_lines[cur_file_posy] = line_start;
          clrtoeol();

          //add the new line
          buffer_lines.insert(buffer_lines.begin()+cur_file_posy+1, line_end);

          //reprint all the buffer_lines after
          for(int i = cur_file_posy+1; i < buffer_lines.size(); i++) {
            if(cury+i-cur_file_posy >= winy) {
              break;
            }
            move(cury+i-cur_file_posy, 0);
            clrtoeol();
            addstr(buffer_lines[i].c_str());
          }

          //move the cursor down the cursor
          cur_file_posy++;
          cury++;

          //scroll if the cursor passed the screen
          move(cury, 0);
          if(cury >= winy) {
            scroll(stdscr);
            cury = winy-1;
            move(cury, 0);
            addstr(buffer_lines[cur_file_posy].c_str());
            move(cury, 0);
          }
        }

        //delete or backspace
        else if(c == 127 || c == 8) {
          if(curx > 0) {
            string line = buffer_lines[cur_file_posy];
            buffer_lines[cur_file_posy] = line.substr(0, curx-1) + line.substr(curx, line.size()-curx);
            cur_file_posx--;
            curx--;
            move(cury, curx);
            delch();
          }
          else if(cur_file_posy > 0) {
            int new_posx = buffer_lines[cur_file_posy-1].size();
            string bigger_line = buffer_lines[cur_file_posy-1] + buffer_lines[cur_file_posy];
            buffer_lines[cur_file_posy-1] = bigger_line;
            buffer_lines.erase(buffer_lines.begin()+cur_file_posy);

            if(cury > 0) {

              //reprint all buffer_lines after
              for(int i = cur_file_posy-1; i < buffer_lines.size(); i++) {
                if(cury+i-cur_file_posy >= winy) {
                  break;
                }
                move(cury+i-cur_file_posy, 0);
                clrtoeol();
                addstr(buffer_lines[i].c_str());
              }

              //move the cursor
              cur_file_posy--;
              cury--;
              move(cury, new_posx);
              cur_file_posx = new_posx;
            }
            else {
              move(cury, 0);
              clrtoeol();
              addstr(buffer_lines[cur_file_posy].c_str());
              move(cury, new_posx);
              cur_file_posx = new_posx;
            }
          }
        }

        //regular character
        else {

          //add the character to the line
          string line_end = (char)c + buffer_lines[cur_file_posy].substr(curx, buffer_lines[cur_file_posy].size()-curx);
          buffer_lines[cur_file_posy] = buffer_lines[cur_file_posy].substr(0, curx) + line_end;
          move(cury, curx);
          addstr(line_end.c_str());

          curx++;
          cur_file_posx = curx;
          move(cury, curx);
        }

        break;
      }
    }
  }

  finish(0);

  return 0;
}
Example #15
0
//Subdivide the empty voxels into cells.
void PVSGenerator::generateCellsFromEmptyVoxelsUsingTiles( VoxelContainer& voxelContainer, vector<shared_ptr<Cell>>& cells ) const
{

	Point3i minVoxelPoint, maxVoxelPoint;

	int lastProgress = 0;
	int progress;
	int tileIndex;
	int expectedEmptyVoxels;
	int numberOfVoxelsInsideCell;
	int cellsCreated = 0;
	int cellsCreatedForTile = 0;
	int tilesProcessed=0;
	SceneTile* currentTile;
	
	try
	{
		//Process the SceneTiles in parallel. Each one has it's own collection of Cells and can read the voxel container concurrently.
		#pragma omp parallel for private(currentTile, tileIndex, expectedEmptyVoxels, minVoxelPoint, maxVoxelPoint, numberOfVoxelsInsideCell, cellsCreatedForTile ) shared(lastProgress, voxelContainer, cells, progress, cellsCreated, tilesProcessed)
		for( tileIndex = 0 ; tileIndex < (int) m_sceneTiles.size() ; ++tileIndex)
		{
			currentTile = (m_sceneTiles[tileIndex]).get();
			cellsCreatedForTile = 0;

			//How many empty voxels are we expecting to have in this tile.
			expectedEmptyVoxels = currentTile->getNumberOfVoxelsInside() - currentTile->getNumberOfSolidVoxelsInside();

			//If all the Tile is solid, don't generate a cell.
			if( expectedEmptyVoxels == 0 )
				continue;
		
			//Do while there are no pending empty voxels left in the tile
			while ( expectedEmptyVoxels > 0 )
			{

				//Take first seed voxel index.
				minVoxelPoint = maxVoxelPoint = findSeedPointInTile( *currentTile, voxelContainer );

				//Expand the cell until there is something that blocks the growth in that direction, then continue with the other directions.
				testExpansion( minVoxelPoint, maxVoxelPoint, VoxelContainer::POSITIVE_X, voxelContainer, *currentTile );
				testExpansion( minVoxelPoint, maxVoxelPoint, VoxelContainer::POSITIVE_Y, voxelContainer, *currentTile );
				testExpansion( minVoxelPoint, maxVoxelPoint, VoxelContainer::POSITIVE_Z, voxelContainer, *currentTile );
				testExpansion( minVoxelPoint, maxVoxelPoint, VoxelContainer::NEGATIVE_X, voxelContainer, *currentTile );
				testExpansion( minVoxelPoint, maxVoxelPoint, VoxelContainer::NEGATIVE_Y, voxelContainer, *currentTile );
				testExpansion( minVoxelPoint, maxVoxelPoint, VoxelContainer::NEGATIVE_Z, voxelContainer, *currentTile );
		
				//Calculate how many voxels are inside the cell found.
				numberOfVoxelsInsideCell = (maxVoxelPoint.x - minVoxelPoint.x + 1) * (maxVoxelPoint.y - minVoxelPoint.y + 1) * (maxVoxelPoint.z - minVoxelPoint.z + 1);

				//Expect less voxels to explore.
				expectedEmptyVoxels -= numberOfVoxelsInsideCell;

				//Create the cell and add it to the Tile.
				currentTile->addCell( shared_ptr<Cell>(new Cell(minVoxelPoint, maxVoxelPoint ) ));
				cellsCreatedForTile++;
			}

			//Show progress on the log.
			#pragma omp critical
			{
				tilesProcessed++;
				cellsCreated += cellsCreatedForTile;
				progress = (int) (((float)tilesProcessed / (float) m_sceneTiles.size()) * 100.0f);
				if( progress - lastProgress >= 10 )
				{
					std::stringstream str;
					str << "Tiles processed %: " << progress << " (" << cellsCreated << " cells)";
					Logger::Log( str.str() );
					lastProgress = progress; 
				}
			}

		}
	
		//With all the cells created in each Tile, merge them all into the unified cells vector.
		for( unsigned int tileIndex = 0 ; tileIndex < m_sceneTiles.size() ; ++tileIndex)
		{
			const vector<shared_ptr<Cell>>& tileCells = m_sceneTiles[tileIndex]->getCells();
			cells.insert( cells.end(), tileCells.begin(), tileCells.end() );
		}
	}catch( bad_alloc& ) {
		Logger::Log("Error allocating memory for Cells. Consider increasing the Max Cell size or increasing SceneTile size.");
		exit(1);
	}
}
Example #16
0
bool ReadComponentRecord(istream& in)
{
    HipparcosComponent component;
    char buf[HipComponentRecordLength];

    in.read(buf, HipComponentRecordLength);

    uint32 hip;
    if (sscanf(buf + 42, "%ud", &hip) != 1)
    {
        cout << "Missing HIP catalog number for component.\n";
        return false;
    }

    component.star = findStar(hip);
    if (component.star == NULL)
    {
        cout << "Nonexistent HIP catalog number for component.\n";
        return false;
    }

    if (sscanf(buf + 40, "%c", &component.componentID) != 1)
    {
        cout << "Missing component identifier.\n";
        return false;
    }

    if (sscanf(buf + 175, "%c", &component.refComponentID) != 1)
    {
        cout << "Error reading reference component.\n";
        return false;
    }
    if (component.refComponentID == ' ')
        component.refComponentID = component.componentID;

    // Read astrometric information
    if (sscanf(buf + 88, "%f", &component.ascension) != 1)
    {
        cout << "Missing ascension for component.\n";
        return false;
    }
    component.ascension = (float) (component.ascension * 24.0 / 360.0);

    if (sscanf(buf + 101, "%f", &component.declination) != 1)
    {
        cout << "Missing declination for component.\n";
        return false;
    }

    // Read photometric information
    if (sscanf(buf + 49, "%f", &component.appMag) != 1)
    {
        cout << "Missing magnitude for component.\n";
        return false;
    }

    // vMag and bMag may be necessary to guess the spectral type
    if (sscanf(buf + 62, "%f", &component.bMag) != 1 ||
        sscanf(buf + 69, "%f", &component.vMag) != 1)
    {
        component.bMag = component.vMag = component.appMag;
    }
    else
    {
        component.hasBV = true;
    }

    if (component.componentID != component.refComponentID)
    {
        if (sscanf(buf + 177, "%f", &component.positionAngle) != 1)
        {
            cout << "Missing position angle for component.\n";
            return false;
        }
        if (sscanf(buf + 185, "%f", &component.separation) != 1)
        {
            cout << "Missing separation for component.\n";
            return false;
        }
    }

    components.insert(components.end(), component);

    return true;
};
Example #17
0
// adjusts the allele to have a new start
// returns the ref/alt sequence obtained by subtracting length from the left end of the allele
void Allele::subtract(
        int subtractFromRefStart,
        int subtractFromRefEnd,
        string& substart,
        string& subend,
        vector<pair<int, string> >& cigarStart,
        vector<pair<int, string> >& cigarEnd,
        vector<short>& qsubstart,
        vector<short>& qsubend
    ) {

    substart.clear();
    subend.clear();
    cigarStart.clear();
    cigarEnd.clear();
    qsubstart.clear();
    qsubend.clear();

    // prepare to adjust cigar
    list<pair<int, string> > cigarL = splitCigarList(cigar);

    // walk the cigar string to determine where to make the left cut in the alternate sequence
    int subtractFromAltStart = 0;
    if (subtractFromRefStart) {
        int refbpstart = subtractFromRefStart;
        pair<int, string> c;
        while (!cigarL.empty()) {
            c = cigarL.front();
            cigarL.pop_front();
            char op = c.second[0];
            switch (op) {
                case 'M':
                case 'X':
                    refbpstart -= c.first;
                    subtractFromAltStart += c.first;
                    break;
                case 'I':
                    subtractFromAltStart += c.first;
                    break;
                case 'D':
                    refbpstart -= c.first;
                    break;
                default:
                    break;
            }

            cigarStart.push_back(c);

            if (refbpstart < 0) {
                // split/adjust the last cigar element
                cigarL.push_front(c);
                cigarL.front().first = -refbpstart;
                cigarStart.back().first += refbpstart;
                switch (op) {
                    case 'M':
                    case 'X':
                    case 'I':
                        subtractFromAltStart += refbpstart;
                        break;
                    case 'D':
                    default:
                        break;
                }
                break; // we're done
            }
        }
    }


    int subtractFromAltEnd = 0;
    // walk the cigar string to determine where to make the right cut in the alternate sequence
    if (subtractFromRefEnd) {
        int refbpend = subtractFromRefEnd;
        pair<int, string> c;
        while (!cigarL.empty() && refbpend > 0) {
            c = cigarL.back();
            cigarL.pop_back();
            char op = c.second[0];
            switch (op) {
                case 'M':
                case 'X':
                    subtractFromAltEnd += c.first;
                    refbpend -= c.first;
                    break;
                case 'I':
                    subtractFromAltEnd += c.first;
                    break;
                case 'D':
                    refbpend -= c.first;
                    break;
                default:
                    break;
            }

            cigarEnd.insert(cigarEnd.begin(), c);

            if (refbpend < 0) {
                // split/adjust the last cigar element
                cigarL.push_back(c);
                cigarL.back().first = -refbpend;
                cigarEnd.front().first += refbpend;
                switch (op) {
                    case 'M':
                    case 'X':
                    case 'I':
                        subtractFromAltEnd += refbpend;
                        break;
                    case 'D':
                    default:
                        break;
                }
                break; // drop out of loop, we're done
            }
        }
    }

    // adjust the alternateSequence
    substart = alternateSequence.substr(0, subtractFromAltStart);
    subend = alternateSequence.substr(alternateSequence.size() - subtractFromAltEnd, subtractFromAltEnd);
    alternateSequence.erase(0, subtractFromAltStart);
    alternateSequence.erase(alternateSequence.size() - subtractFromAltEnd, subtractFromAltEnd);

    // adjust the quality string
    qsubstart.insert(qsubstart.begin(), baseQualities.begin(), baseQualities.begin() + subtractFromAltStart);
    qsubend.insert(qsubend.begin(), baseQualities.begin() + baseQualities.size() - subtractFromAltEnd, baseQualities.end());
    baseQualities.erase(baseQualities.begin(), baseQualities.begin() + subtractFromAltStart);
    baseQualities.erase(baseQualities.begin() + baseQualities.size() - subtractFromAltEnd, baseQualities.end());

    // reset the cigar
    cigarL.erase(remove_if(cigarL.begin(), cigarL.end(), isEmptyCigarElement), cigarL.end());
    cigar = joinCigarList(cigarL);

    // reset the length
    length = alternateSequence.size();

    // update the type specification
    updateTypeAndLengthFromCigar();

    // adjust the position
    position += subtractFromRefStart; // assumes the first-base of the alleles is reference==, not ins

    //referenceLength -= subtractFromRefStart;
    //referenceLength -= subtractFromRefEnd;

    referenceLength = referenceLengthFromCigar();

}
Example #18
0
int main(int argc, char* argv[])
{
    assert(sizeof(StellarClass) == 2);

    // Read star records from the primary HIPPARCOS catalog
    {
        ifstream mainDatabase(MainDatabaseFile.c_str(), ios::in | ios::binary);
        if (!mainDatabase.good())
        {
            cout << "Error opening " << MainDatabaseFile << '\n';
            exit(1);
        }

        cout << "Reading HIPPARCOS data set.\n";
        while (mainDatabase.good())
        {
            ReadStarRecord(mainDatabase);
            if (stars.size() % 10000 == 0)
                cout << stars.size() << " records.\n";
        }
    }
    cout << "Read " << stars.size() << " stars from main database.\n";

    cout << "Adding the Sun...\n";
    stars.insert(stars.end(), TheSun());

    cout << "Sorting stars...\n";
    {
        starIndex.reserve(stars.size());
        for (vector<HipparcosStar>::iterator iter = stars.begin();
             iter != stars.end(); iter++)
        {
            starIndex.insert(starIndex.end(), iter);
        }

        HIPCatalogComparePredicate pred;

        // It may not even be necessary to sort the records, if the
        // HIPPARCOS catalog is strictly ordered by catalog number.  I'm not
        // sure about this however,
        random_shuffle(starIndex.begin(), starIndex.end());
        sort(starIndex.begin(), starIndex.end(), pred);
    }
        
    // Read component records
    {
        ifstream componentDatabase(ComponentDatabaseFile.c_str(),
                                   ios::in | ios::binary);
        if (!componentDatabase.good())
        {
            cout << "Error opening " << ComponentDatabaseFile << '\n';
            exit(1);
        }

        cout << "Reading HIPPARCOS component database.\n";
        while (componentDatabase.good())
        {
            ReadComponentRecord(componentDatabase);
        }
    }
    cout << "Read " << components.size() << " components.\n";

    {    
        int aComp = 0, bComp = 0, cComp = 0, dComp = 0, eComp = 0, otherComp = 0;
        int bvComp = 0;
        for (int i = 0; i < components.size(); i++)
        {
            switch (components[i].componentID)
            {
            case 'A':
                aComp++; break;
            case 'B':
                bComp++; break;
            case 'C':
                cComp++; break;
            case 'D':
                dComp++; break;
            case 'E':
                eComp++; break;
            default:
                otherComp++; break;
            }
            if (components[i].hasBV && components[i].componentID != 'A')
                bvComp++;
        }
        
        cout << "A:" << aComp << "  B:" << bComp << "  C:" << cComp << "  D:" << dComp << "  E:" << eComp << '\n';
        cout << "Components with B-V mag: " << bvComp << '\n';
    }

    cout << "Building catalog of multiple star systems.\n";
    BuildMultistarSystemCatalog();
    
    int nMultipleSystems = starSystems.size();
    cout << "Stars in multiple star systems: " << nMultipleSystems << '\n';

    ConstrainComponentParallaxes();

    CorrectErrors();

    // CreateCompanionList();
    cout << "Companion stars: " << companions.size() << '\n';
    cout << "Total stars: " << stars.size() + companions.size() << '\n';

    ShowStarsWithComponents();

    char* outputFile = "stars.dat";
    if (argc > 1)
        outputFile = argv[1];

    cout << "Writing processed star records to " << outputFile << '\n';
    ofstream out(outputFile, ios::out | ios::binary);
    if (!out.good())
    {
        cout << "Error opening " << outputFile << '\n';
        exit(1);
    }

    binwrite(out, stars.size() + companions.size());
    {
        vector<HipparcosStar>::iterator iter;
        for (iter = stars.begin(); iter != stars.end(); iter++)
            iter->write(out);
        for (iter = companions.begin(); iter != companions.end(); iter++)
            iter->write(out);
    }

#if 0
    char* hdOutputFile = "hdxref.dat";
    
    cout << "Writing out HD cross reference to " << hdOutputFile << '\n';
    ofstream hdout(hdOutputFile, ios::out | ios::binary);
    if (!out.good())
    {
        cout << "Error opening " << hdOutputFile << '\n';
        exit(1);
    }

    {
        int nHD = 0;
        vector<HipparcosStar>::iterator iter;
        for (iter = stars.begin(); iter != stars.end(); iter++)
        {
            if (iter->HDCatalogNumber != NullCatalogNumber)
                nHD++;
        }
        binwrite(hdout, nHD);

        cout << nHD << " stars have HD numbers.\n";
        
        for (iter = stars.begin(); iter != stars.end(); iter++)
        {
            if (iter->HDCatalogNumber != NullCatalogNumber)
            {
                binwrite(hdout, iter->HDCatalogNumber);
                binwrite(hdout, iter->HIPCatalogNumber);
            }
        }        
    }
#endif

    return 0;
}
Example #19
0
	bool LTKGrammar::replacePaths(string term,vector<vector<string> >& originalVector,vector<vector<string> >& replaceVector)
	{
		
		LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) <<"Entering LTKGrammar::replacePaths" <<endl;

		bool found=false;	//indicates whether is search term is found

		int iValue=0,jValue=0;	//indices whether the term is found

		bool checkedForRecursion=false;	

		int recursionCount=0;	//indicates how many times the term replacement happens

		while(true)
		{
			++recursionCount;

			if(recursionCount>150)
			{
				LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Cyclic dependency exists! Unable to find paths!" <<endl;
				throw LTKException(ECYCLIC_DEPENDENCY);
				return false;
			}
		
			bool foundTerm=false;

			//searching for the term in the paths determined so far			
			for(int i=iValue;i<originalVector.size();++i)
			{

				for(int j=0;j<originalVector[i].size();++j)
				{
					if(originalVector[i][j]==term)
					{
						iValue=i;
						jValue=j;
						if(!checkedForRecursion)
						{
							checkedForRecursion=true;
							for(int c=0;c<replaceVector.size();++c)
							{
								for(int d=0;d<replaceVector[c].size();++d)
								{
									if(replaceVector[c][d]==term)
									{
										LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Cyclic dependency exists! Unable to find paths!" <<endl;
										throw LTKException(ECYCLIC_DEPENDENCY);
										return false;
									}
								}
							}
						}
						originalVector[i].erase(originalVector[i].begin()+j);
						foundTerm=true;
						break;
					}
				}
				if(foundTerm)
				{
					break;
				}
			}
			if(foundTerm)	//Replacing the found term with its production values
			{
				originalVector.insert(originalVector.begin()+iValue+1,replaceVector.size()-1,*(originalVector.begin()+iValue));
							
				for(int k=iValue;k<(iValue+replaceVector.size());++k)
				{
					originalVector[k].insert(originalVector[k].begin()+jValue,replaceVector[k-iValue].begin(),replaceVector[k-iValue].end());

				}
				
				found=true;

				continue;
			}
			else
			{
				break;
			}
		}

		LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting LTKGrammar::replacePaths" <<endl;

		return found;
	}
Example #20
0
void BackgroundUtil::AddBackgroundChange( vector<BackgroundChange> &vBackgroundChanges, BackgroundChange seg )
{
	vector<BackgroundChange>::iterator it;
	it = upper_bound( vBackgroundChanges.begin(), vBackgroundChanges.end(), seg, CompareBackgroundChanges );
	vBackgroundChanges.insert( it, seg );
}
void ClsMultiThread::FindSimilarKmer(map<string, St_KmerIndex>& mpCombine, vector<St_KmerInfo>& vKmerRegular)
{
    //1: Get the number of CPU
    string strNum = exec("nproc");
    if(strNum.substr(strNum.length()-1,1) == "\n")
        strNum = strNum.substr(0, strNum.length()-1);
    int iCpuNum = atoi(strNum.c_str());

    //2: Divid KmerRegular Table evenly by the number of cpu
    int iLen = ceil((float)vKmerRegular.size() / iCpuNum);
    vector<St_SimilarKmer> vSubGroupKmer;
    vSubGroupKmer.resize(iCpuNum);
    for(int i=0; i<iCpuNum; i++)
    {
        int iStart = i * iLen;
        int iEnd = (i+1)*iLen;
        if(iEnd < vKmerRegular.size())
            vSubGroupKmer[i].vRegKmer.insert(vSubGroupKmer[i].vRegKmer.end(),
                                             vKmerRegular.begin() + iStart, vKmerRegular.begin() + iEnd);
        else
            vSubGroupKmer[i].vRegKmer.insert(vSubGroupKmer[i].vRegKmer.end(),
                                             vKmerRegular.begin() + iStart,
                                             vKmerRegular.end());
        vSubGroupKmer[i].mpSuperKmer.insert(mpCombine.begin(), mpCombine.end());
    }

    //Create Threads
    int start_s = time(NULL);
    pthread_t tids[iCpuNum];
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

    for(int i=0; i<iCpuNum; i++)
    {
        int ret = pthread_create(&tids[i], &attr, ClsThreadFunc::SimilarDetect, (void*)&(vSubGroupKmer[i]));
        if(ret != 0)
            cout << "Thread error: " << ret << endl;
    }
    pthread_attr_destroy(&attr);

    void* status;
    for(int i=0; i<iCpuNum; i++)
    {
        int ret = pthread_join(tids[i], &status);
        if(ret != 0)
            cout << "Thread Error: " << ret << endl;
        else
            cout << "Thread Status: " << (long)status << endl;
    }
    //pthread_exit(NULL);
    int stop_s = time(NULL);
    double dRuningTime = difftime(stop_s, start_s);
    string strTimeFormat = ::GetHMSTimeFormat(dRuningTime);
    cout << "Running Time: " << strTimeFormat << endl;

    //Arrange the kmer
    for(map<string, St_KmerIndex>::iterator itr = mpCombine.begin(); itr != mpCombine.end(); itr++)
    {
        int iBase = itr->second.iCount;
        int iAccumulate = 0;
        for(vector<St_SimilarKmer>::iterator subItr = vSubGroupKmer.begin();
            subItr != vSubGroupKmer.end(); subItr++)
        {
            iAccumulate += subItr->mpSuperKmer[itr->first].iCount - iBase;
        }
        itr->second.iCount = iBase + iAccumulate;
    }
    //好折腾啊!!!!!!!!
    //2: 将剩下的没能归组的再进行合并,得到总的没有归组的kmer
    vKmerRegular.clear();
    for(vector<St_SimilarKmer>::iterator itr = vSubGroupKmer.begin();
        itr != vSubGroupKmer.end(); itr++)
    {
        vKmerRegular.insert(vKmerRegular.end(), itr->vRegKmer.begin(), itr->vRegKmer.end());
    }
}
bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType)
{
    CAutoBN_CTX pctx;
    CScript::const_iterator pc = script.begin();
    CScript::const_iterator pend = script.end();
    CScript::const_iterator pbegincodehash = script.begin();
    opcodetype opcode;
    valtype vchPushValue;
    vector<bool> vfExec;
    vector<valtype> altstack;
    if (script.size() > 10000)
        return false;
    int nOpCount = 0;


    try
    {
        while (pc < pend)
        {
            bool fExec = !count(vfExec.begin(), vfExec.end(), false);

            //
            // Read instruction
            //
            if (!script.GetOp(pc, opcode, vchPushValue))
                return false;
            if (vchPushValue.size() > 520)
                return false;
            if (opcode > OP_16 && ++nOpCount > 201)
                return false;

            if (opcode == OP_CAT ||
                opcode == OP_SUBSTR ||
                opcode == OP_LEFT ||
                opcode == OP_RIGHT ||
                opcode == OP_INVERT ||
                opcode == OP_AND ||
                opcode == OP_OR ||
                opcode == OP_XOR ||
                opcode == OP_2MUL ||
                opcode == OP_2DIV ||
                opcode == OP_MUL ||
                opcode == OP_DIV ||
                opcode == OP_MOD ||
                opcode == OP_LSHIFT ||
                opcode == OP_RSHIFT)
                return false;

            if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
                stack.push_back(vchPushValue);
            else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
            switch (opcode)
            {
                //
                // Push value
                //
                case OP_1NEGATE:
                case OP_1:
                case OP_2:
                case OP_3:
                case OP_4:
                case OP_5:
                case OP_6:
                case OP_7:
                case OP_8:
                case OP_9:
                case OP_10:
                case OP_11:
                case OP_12:
                case OP_13:
                case OP_14:
                case OP_15:
                case OP_16:
                {
                    // ( -- value)
                    CBigNum bn((int)opcode - (int)(OP_1 - 1));
                    stack.push_back(bn.getvch());
                }
                break;


                //
                // Control
                //
                case OP_NOP:
                case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
                case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
                break;

                case OP_IF:
                case OP_NOTIF:
                {
                    // <expression> if [statements] [else [statements]] endif
                    bool fValue = false;
                    if (fExec)
                    {
                        if (stack.size() < 1)
                            return false;
                        valtype& vch = stacktop(-1);
                        fValue = CastToBool(vch);
                        if (opcode == OP_NOTIF)
                            fValue = !fValue;
                        popstack(stack);
                    }
                    vfExec.push_back(fValue);
                }
                break;

                case OP_ELSE:
                {
                    if (vfExec.empty())
                        return false;
                    vfExec.back() = !vfExec.back();
                }
                break;

                case OP_ENDIF:
                {
                    if (vfExec.empty())
                        return false;
                    vfExec.pop_back();
                }
                break;

                case OP_VERIFY:
                {
                    // (true -- ) or
                    // (false -- false) and return
                    if (stack.size() < 1)
                        return false;
                    bool fValue = CastToBool(stacktop(-1));
                    if (fValue)
                        popstack(stack);
                    else
                        return false;
                }
                break;

                case OP_RETURN:
                {
                    return false;
                }
                break;


                //
                // Stack ops
                //
                case OP_TOALTSTACK:
                {
                    if (stack.size() < 1)
                        return false;
                    altstack.push_back(stacktop(-1));
                    popstack(stack);
                }
                break;

                case OP_FROMALTSTACK:
                {
                    if (altstack.size() < 1)
                        return false;
                    stack.push_back(altstacktop(-1));
                    popstack(altstack);
                }
                break;

                case OP_2DROP:
                {
                    // (x1 x2 -- )
                    if (stack.size() < 2)
                        return false;
                    popstack(stack);
                    popstack(stack);
                }
                break;

                case OP_2DUP:
                {
                    // (x1 x2 -- x1 x2 x1 x2)
                    if (stack.size() < 2)
                        return false;
                    valtype vch1 = stacktop(-2);
                    valtype vch2 = stacktop(-1);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                }
                break;

                case OP_3DUP:
                {
                    // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
                    if (stack.size() < 3)
                        return false;
                    valtype vch1 = stacktop(-3);
                    valtype vch2 = stacktop(-2);
                    valtype vch3 = stacktop(-1);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                    stack.push_back(vch3);
                }
                break;

                case OP_2OVER:
                {
                    // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
                    if (stack.size() < 4)
                        return false;
                    valtype vch1 = stacktop(-4);
                    valtype vch2 = stacktop(-3);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                }
                break;

                case OP_2ROT:
                {
                    // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
                    if (stack.size() < 6)
                        return false;
                    valtype vch1 = stacktop(-6);
                    valtype vch2 = stacktop(-5);
                    stack.erase(stack.end()-6, stack.end()-4);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                }
                break;

                case OP_2SWAP:
                {
                    // (x1 x2 x3 x4 -- x3 x4 x1 x2)
                    if (stack.size() < 4)
                        return false;
                    swap(stacktop(-4), stacktop(-2));
                    swap(stacktop(-3), stacktop(-1));
                }
                break;

                case OP_IFDUP:
                {
                    // (x - 0 | x x)
                    if (stack.size() < 1)
                        return false;
                    valtype vch = stacktop(-1);
                    if (CastToBool(vch))
                        stack.push_back(vch);
                }
                break;

                case OP_DEPTH:
                {
                    // -- stacksize
                    CBigNum bn(stack.size());
                    stack.push_back(bn.getvch());
                }
                break;

                case OP_DROP:
                {
                    // (x -- )
                    if (stack.size() < 1)
                        return false;
                    popstack(stack);
                }
                break;

                case OP_DUP:
                {
                    // (x -- x x)
                    if (stack.size() < 1)
                        return false;
                    valtype vch = stacktop(-1);
                    stack.push_back(vch);
                }
                break;

                case OP_NIP:
                {
                    // (x1 x2 -- x2)
                    if (stack.size() < 2)
                        return false;
                    stack.erase(stack.end() - 2);
                }
                break;

                case OP_OVER:
                {
                    // (x1 x2 -- x1 x2 x1)
                    if (stack.size() < 2)
                        return false;
                    valtype vch = stacktop(-2);
                    stack.push_back(vch);
                }
                break;

                case OP_PICK:
                case OP_ROLL:
                {
                    // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
                    // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
                    if (stack.size() < 2)
                        return false;
                    int n = CastToBigNum(stacktop(-1)).getint();
                    popstack(stack);
                    if (n < 0 || n >= stack.size())
                        return false;
                    valtype vch = stacktop(-n-1);
                    if (opcode == OP_ROLL)
                        stack.erase(stack.end()-n-1);
                    stack.push_back(vch);
                }
                break;

                case OP_ROT:
                {
                    // (x1 x2 x3 -- x2 x3 x1)
                    //  x2 x1 x3  after first swap
                    //  x2 x3 x1  after second swap
                    if (stack.size() < 3)
                        return false;
                    swap(stacktop(-3), stacktop(-2));
                    swap(stacktop(-2), stacktop(-1));
                }
                break;

                case OP_SWAP:
                {
                    // (x1 x2 -- x2 x1)
                    if (stack.size() < 2)
                        return false;
                    swap(stacktop(-2), stacktop(-1));
                }
                break;

                case OP_TUCK:
                {
                    // (x1 x2 -- x2 x1 x2)
                    if (stack.size() < 2)
                        return false;
                    valtype vch = stacktop(-1);
                    stack.insert(stack.end()-2, vch);
                }
                break;


                //
                // Splice ops
                //
                case OP_CAT:
                {
                    // (x1 x2 -- out)
                    if (stack.size() < 2)
                        return false;
                    valtype& vch1 = stacktop(-2);
                    valtype& vch2 = stacktop(-1);
                    vch1.insert(vch1.end(), vch2.begin(), vch2.end());
                    popstack(stack);
                    if (stacktop(-1).size() > 520)
                        return false;
                }
                break;

                case OP_SUBSTR:
                {
                    // (in begin size -- out)
                    if (stack.size() < 3)
                        return false;
                    valtype& vch = stacktop(-3);
                    int nBegin = CastToBigNum(stacktop(-2)).getint();
                    int nEnd = nBegin + CastToBigNum(stacktop(-1)).getint();
                    if (nBegin < 0 || nEnd < nBegin)
                        return false;
                    if (nBegin > vch.size())
                        nBegin = vch.size();
                    if (nEnd > vch.size())
                        nEnd = vch.size();
                    vch.erase(vch.begin() + nEnd, vch.end());
                    vch.erase(vch.begin(), vch.begin() + nBegin);
                    popstack(stack);
                    popstack(stack);
                }
                break;

                case OP_LEFT:
                case OP_RIGHT:
                {
                    // (in size -- out)
                    if (stack.size() < 2)
                        return false;
                    valtype& vch = stacktop(-2);
                    int nSize = CastToBigNum(stacktop(-1)).getint();
                    if (nSize < 0)
                        return false;
                    if (nSize > vch.size())
                        nSize = vch.size();
                    if (opcode == OP_LEFT)
                        vch.erase(vch.begin() + nSize, vch.end());
                    else
                        vch.erase(vch.begin(), vch.end() - nSize);
                    popstack(stack);
                }
                break;

                case OP_SIZE:
                {
                    // (in -- in size)
                    if (stack.size() < 1)
                        return false;
                    CBigNum bn(stacktop(-1).size());
                    stack.push_back(bn.getvch());
                }
                break;


                //
                // Bitwise logic
                //
                case OP_INVERT:
                {
                    // (in - out)
                    if (stack.size() < 1)
                        return false;
                    valtype& vch = stacktop(-1);
                    for (int i = 0; i < vch.size(); i++)
                        vch[i] = ~vch[i];
                }
                break;

                case OP_AND:
                case OP_OR:
                case OP_XOR:
                {
                    // (x1 x2 - out)
                    if (stack.size() < 2)
                        return false;
                    valtype& vch1 = stacktop(-2);
                    valtype& vch2 = stacktop(-1);
                    MakeSameSize(vch1, vch2);
                    if (opcode == OP_AND)
                    {
                        for (int i = 0; i < vch1.size(); i++)
                            vch1[i] &= vch2[i];
                    }
                    else if (opcode == OP_OR)
                    {
                        for (int i = 0; i < vch1.size(); i++)
                            vch1[i] |= vch2[i];
                    }
                    else if (opcode == OP_XOR)
                    {
                        for (int i = 0; i < vch1.size(); i++)
                            vch1[i] ^= vch2[i];
                    }
                    popstack(stack);
                }
                break;

                case OP_EQUAL:
                case OP_EQUALVERIFY:
                //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
                {
                    // (x1 x2 - bool)
                    if (stack.size() < 2)
                        return false;
                    valtype& vch1 = stacktop(-2);
                    valtype& vch2 = stacktop(-1);
                    bool fEqual = (vch1 == vch2);
                    // OP_NOTEQUAL is disabled because it would be too easy to say
                    // something like n != 1 and have some wiseguy pass in 1 with extra
                    // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
                    //if (opcode == OP_NOTEQUAL)
                    //    fEqual = !fEqual;
                    popstack(stack);
                    popstack(stack);
                    stack.push_back(fEqual ? vchTrue : vchFalse);
                    if (opcode == OP_EQUALVERIFY)
                    {
                        if (fEqual)
                            popstack(stack);
                        else
                            return false;
                    }
                }
                break;


                //
                // Numeric
                //
                case OP_1ADD:
                case OP_1SUB:
                case OP_2MUL:
                case OP_2DIV:
                case OP_NEGATE:
                case OP_ABS:
                case OP_NOT:
                case OP_0NOTEQUAL:
                {
                    // (in -- out)
                    if (stack.size() < 1)
                        return false;
                    CBigNum bn = CastToBigNum(stacktop(-1));
                    switch (opcode)
                    {
                    case OP_1ADD:       bn += bnOne; break;
                    case OP_1SUB:       bn -= bnOne; break;
                    case OP_2MUL:       bn <<= 1; break;
                    case OP_2DIV:       bn >>= 1; break;
                    case OP_NEGATE:     bn = -bn; break;
                    case OP_ABS:        if (bn < bnZero) bn = -bn; break;
                    case OP_NOT:        bn = (bn == bnZero); break;
                    case OP_0NOTEQUAL:  bn = (bn != bnZero); break;
                    default:            assert(!"invalid opcode"); break;
                    }
                    popstack(stack);
                    stack.push_back(bn.getvch());
                }
                break;

                case OP_ADD:
                case OP_SUB:
                case OP_MUL:
                case OP_DIV:
                case OP_MOD:
                case OP_LSHIFT:
                case OP_RSHIFT:
                case OP_BOOLAND:
                case OP_BOOLOR:
                case OP_NUMEQUAL:
                case OP_NUMEQUALVERIFY:
                case OP_NUMNOTEQUAL:
                case OP_LESSTHAN:
                case OP_GREATERTHAN:
                case OP_LESSTHANOREQUAL:
                case OP_GREATERTHANOREQUAL:
                case OP_MIN:
                case OP_MAX:
                {
                    // (x1 x2 -- out)
                    if (stack.size() < 2)
                        return false;
                    CBigNum bn1 = CastToBigNum(stacktop(-2));
                    CBigNum bn2 = CastToBigNum(stacktop(-1));
                    CBigNum bn;
                    switch (opcode)
                    {
                    case OP_ADD:
                        bn = bn1 + bn2;
                        break;

                    case OP_SUB:
                        bn = bn1 - bn2;
                        break;

                    case OP_MUL:
                        if (!BN_mul(&bn, &bn1, &bn2, pctx))
                            return false;
                        break;

                    case OP_DIV:
                        if (!BN_div(&bn, NULL, &bn1, &bn2, pctx))
                            return false;
                        break;

                    case OP_MOD:
                        if (!BN_mod(&bn, &bn1, &bn2, pctx))
                            return false;
                        break;

                    case OP_LSHIFT:
                        if (bn2 < bnZero || bn2 > CBigNum(2048))
                            return false;
                        bn = bn1 << bn2.getulong();
                        break;

                    case OP_RSHIFT:
                        if (bn2 < bnZero || bn2 > CBigNum(2048))
                            return false;
                        bn = bn1 >> bn2.getulong();
                        break;

                    case OP_BOOLAND:             bn = (bn1 != bnZero && bn2 != bnZero); break;
                    case OP_BOOLOR:              bn = (bn1 != bnZero || bn2 != bnZero); break;
                    case OP_NUMEQUAL:            bn = (bn1 == bn2); break;
                    case OP_NUMEQUALVERIFY:      bn = (bn1 == bn2); break;
                    case OP_NUMNOTEQUAL:         bn = (bn1 != bn2); break;
                    case OP_LESSTHAN:            bn = (bn1 < bn2); break;
                    case OP_GREATERTHAN:         bn = (bn1 > bn2); break;
                    case OP_LESSTHANOREQUAL:     bn = (bn1 <= bn2); break;
                    case OP_GREATERTHANOREQUAL:  bn = (bn1 >= bn2); break;
                    case OP_MIN:                 bn = (bn1 < bn2 ? bn1 : bn2); break;
                    case OP_MAX:                 bn = (bn1 > bn2 ? bn1 : bn2); break;
                    default:                     assert(!"invalid opcode"); break;
                    }
                    popstack(stack);
                    popstack(stack);
                    stack.push_back(bn.getvch());

                    if (opcode == OP_NUMEQUALVERIFY)
                    {
                        if (CastToBool(stacktop(-1)))
                            popstack(stack);
                        else
                            return false;
                    }
                }
                break;

                case OP_WITHIN:
                {
                    // (x min max -- out)
                    if (stack.size() < 3)
                        return false;
                    CBigNum bn1 = CastToBigNum(stacktop(-3));
                    CBigNum bn2 = CastToBigNum(stacktop(-2));
                    CBigNum bn3 = CastToBigNum(stacktop(-1));
                    bool fValue = (bn2 <= bn1 && bn1 < bn3);
                    popstack(stack);
                    popstack(stack);
                    popstack(stack);
                    stack.push_back(fValue ? vchTrue : vchFalse);
                }
                break;


                //
                // Crypto
                //
                case OP_RIPEMD160:
                case OP_SHA1:
                case OP_SHA256:
                case OP_HASH160:
                case OP_HASH256:
                {
                    // (in -- hash)
                    if (stack.size() < 1)
                        return false;
                    valtype& vch = stacktop(-1);
                    valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
                    if (opcode == OP_RIPEMD160)
                        RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
                    else if (opcode == OP_SHA1)
                        SHA1(&vch[0], vch.size(), &vchHash[0]);
                    else if (opcode == OP_SHA256)
                        SHA256(&vch[0], vch.size(), &vchHash[0]);
                    else if (opcode == OP_HASH160)
                    {
                        uint160 hash160 = Hash160(vch);
                        memcpy(&vchHash[0], &hash160, sizeof(hash160));
                    }
                    else if (opcode == OP_HASH256)
                    {
                        uint256 hash = Hash(vch.begin(), vch.end());
                        memcpy(&vchHash[0], &hash, sizeof(hash));
                    }
                    popstack(stack);
                    stack.push_back(vchHash);
                }
                break;

                case OP_CODESEPARATOR:
                {
                    // Hash starts after the code separator
                    pbegincodehash = pc;
                }
                break;

                case OP_CHECKSIG:
                case OP_CHECKSIGVERIFY:
                {
                    // (sig pubkey -- bool)
                    if (stack.size() < 2)
                        return false;

                    valtype& vchSig    = stacktop(-2);
                    valtype& vchPubKey = stacktop(-1);

                    ////// debug print
                    //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
                    //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");

                    // Subset of script starting at the most recent codeseparator
                    CScript scriptCode(pbegincodehash, pend);

                    // Drop the signature, since there's no way for a signature to sign itself
                    scriptCode.FindAndDelete(CScript(vchSig));

                    bool fSuccess = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);

                    popstack(stack);
                    popstack(stack);
                    stack.push_back(fSuccess ? vchTrue : vchFalse);
                    if (opcode == OP_CHECKSIGVERIFY)
                    {
                        if (fSuccess)
                            popstack(stack);
                        else
                            return false;
                    }
                }
                break;

                case OP_CHECKMULTISIG:
                case OP_CHECKMULTISIGVERIFY:
                {
                    // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)

                    int i = 1;
                    if (stack.size() < i)
                        return false;

                    int nKeysCount = CastToBigNum(stacktop(-i)).getint();
                    if (nKeysCount < 0 || nKeysCount > 20)
                        return false;
                    nOpCount += nKeysCount;
                    if (nOpCount > 201)
                        return false;
                    int ikey = ++i;
                    i += nKeysCount;
                    if (stack.size() < i)
                        return false;

                    int nSigsCount = CastToBigNum(stacktop(-i)).getint();
                    if (nSigsCount < 0 || nSigsCount > nKeysCount)
                        return false;
                    int isig = ++i;
                    i += nSigsCount;
                    if (stack.size() < i)
                        return false;

                    // Subset of script starting at the most recent codeseparator
                    CScript scriptCode(pbegincodehash, pend);

                    // Drop the signatures, since there's no way for a signature to sign itself
                    for (int k = 0; k < nSigsCount; k++)
                    {
                        valtype& vchSig = stacktop(-isig-k);
                        scriptCode.FindAndDelete(CScript(vchSig));
                    }

                    bool fSuccess = true;
                    while (fSuccess && nSigsCount > 0)
                    {
                        valtype& vchSig    = stacktop(-isig);
                        valtype& vchPubKey = stacktop(-ikey);

                        // Check signature
                        if (CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType))
                        {
                            isig++;
                            nSigsCount--;
                        }
                        ikey++;
                        nKeysCount--;

                        // If there are more signatures left than keys left,
                        // then too many signatures have failed
                        if (nSigsCount > nKeysCount)
                            fSuccess = false;
                    }

                    while (i-- > 0)
                        popstack(stack);
                    stack.push_back(fSuccess ? vchTrue : vchFalse);

                    if (opcode == OP_CHECKMULTISIGVERIFY)
                    {
                        if (fSuccess)
                            popstack(stack);
                        else
                            return false;
                    }
                }
                break;

                default:
                    return false;
            }

            // Size limits
            if (stack.size() + altstack.size() > 1000)
                return false;
        }
    }
    catch (...)
    {
        return false;
    }


    if (!vfExec.empty())
        return false;

    return true;
}
int LinesSampler::decodeRowCount(const int symbolsPerLine, vector<vector<int> > &detectedCodeWords, vector<int> &insertLinesAt)
{
    // Use the information in the first and last column to determin the number of rows and find more missing rows.
    // For missing rows insert blank space, so the error correction can try to fill them in.

    map<int, int> rowCountVotes;
    map<int, int> ecLevelVotes;
    map<int, int> rowNumberVotes;
    int lastRowNumber = -1;
    insertLinesAt.clear();

    for (int i = 0; i + 2 < (int)detectedCodeWords.size(); i += 3) {
        rowNumberVotes.clear();
        int firstCodewordDecodedLeft = -1;
        int secondCodewordDecodedLeft = -1;
        int thirdCodewordDecodedLeft = -1;
        int firstCodewordDecodedRight = -1;
        int secondCodewordDecodedRight = -1;
        int thirdCodewordDecodedRight = -1;

        if (detectedCodeWords[i][0] != 0) {
            firstCodewordDecodedLeft = BitMatrixParser::getCodeword(detectedCodeWords[i][0]);
        }
        if (detectedCodeWords[i + 1][0] != 0) {
            secondCodewordDecodedLeft = BitMatrixParser::getCodeword(detectedCodeWords[i + 1][0]);
        }
        if (detectedCodeWords[i + 2][0] != 0) {
            thirdCodewordDecodedLeft = BitMatrixParser::getCodeword(detectedCodeWords[i + 2][0]);
        }

        if (detectedCodeWords[i][detectedCodeWords[i].size() - 1] != 0) {
            firstCodewordDecodedRight = BitMatrixParser::getCodeword(detectedCodeWords[i][detectedCodeWords[i].size() - 1]);
        }
        if (detectedCodeWords[i + 1][detectedCodeWords[i + 1].size() - 1] != 0) {
            secondCodewordDecodedRight = BitMatrixParser::getCodeword(detectedCodeWords[i + 1][detectedCodeWords[i + 1].size() - 1]);
        }
        if (detectedCodeWords[i + 2][detectedCodeWords[i + 2].size() - 1] != 0) {
            thirdCodewordDecodedRight = BitMatrixParser::getCodeword(detectedCodeWords[i + 2][detectedCodeWords[i + 2].size() - 1]);
        }

        if (firstCodewordDecodedLeft != -1 && secondCodewordDecodedLeft != -1) {
            int leftRowCount = ((firstCodewordDecodedLeft % 30) * 3) + ((secondCodewordDecodedLeft % 30) % 3);
            int leftECLevel = (secondCodewordDecodedLeft % 30) / 3;

            rowCountVotes[leftRowCount] = rowCountVotes[leftRowCount] + 1;
            ecLevelVotes[leftECLevel] = ecLevelVotes[leftECLevel] + 1;
        }

        if (secondCodewordDecodedRight != -1 && thirdCodewordDecodedRight != -1) {
            int rightRowCount = ((secondCodewordDecodedRight % 30) * 3) + ((thirdCodewordDecodedRight % 30) % 3);
            int rightECLevel = (thirdCodewordDecodedRight % 30) / 3;

            rowCountVotes[rightRowCount] = rowCountVotes[rightRowCount] + 1;
            ecLevelVotes[rightECLevel] = ecLevelVotes[rightECLevel] + 1;
        }

        if (firstCodewordDecodedLeft != -1) {
            int rowNumber = firstCodewordDecodedLeft / 30;
            rowNumberVotes[rowNumber] = rowNumberVotes[rowNumber] + 1;
        }
        if (secondCodewordDecodedLeft != -1) {
            int rowNumber = secondCodewordDecodedLeft / 30;
            rowNumberVotes[rowNumber] = rowNumberVotes[rowNumber] + 1;
        }
        if (thirdCodewordDecodedLeft != -1) {
            int rowNumber = thirdCodewordDecodedLeft / 30;
            rowNumberVotes[rowNumber] = rowNumberVotes[rowNumber] + 1;
        }
        if (firstCodewordDecodedRight != -1) {
            int rowNumber = firstCodewordDecodedRight / 30;
            rowNumberVotes[rowNumber] = rowNumberVotes[rowNumber] + 1;
        }
        if (secondCodewordDecodedRight != -1) {
            int rowNumber = secondCodewordDecodedRight / 30;
            rowNumberVotes[rowNumber] = rowNumberVotes[rowNumber] + 1;
        }
        if (thirdCodewordDecodedRight != -1) {
            int rowNumber = thirdCodewordDecodedRight / 30;
            rowNumberVotes[rowNumber] = rowNumberVotes[rowNumber] + 1;
        }
        int rowNumber = getValueWithMaxVotes(rowNumberVotes).getVote();
        if (lastRowNumber + 1 < rowNumber) {
            for (int j = lastRowNumber + 1; j < rowNumber; j++) {
                insertLinesAt.push_back(i);
                insertLinesAt.push_back(i);
                insertLinesAt.push_back(i);
            }
        }
        lastRowNumber = rowNumber;
    }

    for (int i = 0; i < (int)insertLinesAt.size(); i++) {
        detectedCodeWords.insert(detectedCodeWords.begin() + insertLinesAt[i] + i, vector<int>(symbolsPerLine, 0));
    }

    int rowCount = getValueWithMaxVotes(rowCountVotes).getVote();
    // int ecLevel = getValueWithMaxVotes(ecLevelVotes);

#if PDF417_DIAG && OUTPUT_EC_LEVEL
    {
        cout << "EC Level: " << ecLevel << " (" << ((1 << (ecLevel + 1)) - 2) << " EC Codewords)" << endl;
    }
#endif
    rowCount += 1;
    return rowCount;
}
singleStepOutput simOneTimeStep( vector<int> lattice, vector<int> mrna, vector<int> unfoldedPos, vector<int> occupiedPos, vector<int> ribState, double alpha, double beta, vector<double> gamma, vector<int> delta, double refold, int w){
	vector<int> newLattice(lattice);
	
	// calculate total arrival rate
	int canEnter = initiateQ( lattice, w );
	double sumRates = 0;
	int sizeProp = occupiedPos.size() + 1;
	
	// does mRNA refold?
	for (int i=0; i < unfoldedPos.size(); ++i){
		if (refold <= ((double) rand() / (RAND_MAX))){
			mrna.at(unfoldedPos.at(i)) = 0;
		}
	}
	
	// now simulate 
	if ( canEnter == 1 ){
		sumRates += alpha;
	}
		
	for ( int j=0; j < occupiedPos.size(); ++j){
		if ( ribState.at(j) == 0 ) {
		//	cout << "i have no trna " << endl;
	//		cout << occupiedPos.at(j) << " " << ribState.at(j) << endl;
			sumRates += gamma.at(occupiedPos.at(j));
	//		sizeProp += 1;
		}
		else {
			double canMove = moveToRightQ( lattice, mrna, ribState.at(j), occupiedPos.at(j), w );
	//		cout << "can I move " << canMove << endl;
	//		cout << "lattice ";
	//		for (int i = 0; i <= lattice.size()-1; ++i){
	//			cout << lattice.at(i);
	//		}
			if ( occupiedPos.at(j) != lattice.size() - 1){
				sumRates += canMove*delta.at(occupiedPos.at(j));
			}
			else {
				if ( ribState.at(j) == 1 ) {
					sumRates += beta;
	//				sizeProp += 1;
				}
				else {
					sumRates += gamma.at(occupiedPos.at(j));
	//				sizeProp += 1;
				}
			}
		}
	}

	vector<double> prop(sizeProp,0); // propensity function
	
	// add on initiation
	if ( canEnter == 1 ) {
		prop.at(0) = alpha/sumRates;
	}
	else{
		prop.at(0) = 0;
	}
	// cumulative sum over elongation rates
	for ( int j = 0; j < occupiedPos.size(); ++j ){
		if ( occupiedPos.at(j) < lattice.size() - 1 ){
			if ( ribState.at(j) == 0 ) {
				prop.at(j+1) = prop.at(j) + gamma.at(occupiedPos.at(j))/sumRates;
			}
			else if ( ribState.at(j) == 1 ) {
				double canMove = moveToRightQ( lattice, mrna, ribState.at(j), occupiedPos.at(j), w );
					prop.at(j+1) = prop.at(j) + canMove*delta.at(occupiedPos.at(j))/sumRates;;
			}
		}
		else {
			if ( ribState.at(j) == 0 ) {
				prop.at(j+1) = prop.at(j) + gamma.at(occupiedPos.at(j))/sumRates;
			}
			else if ( ribState.at(j) == 1 ) {
				prop.at(j+1) = prop.at(j) + beta/sumRates;
			}
		}
	}

	// which ribosome will jump?

	double u = ((double) rand() / (RAND_MAX));
	int whichMove = 0;
	
	while ( prop.at(whichMove) < u ){
		whichMove++;
	}
	
//	cout << "ribosome " << whichMove << " moves" << endl;
	
	// now the jump! (or not)
	if ( whichMove == 0 ){
//		cout << "enter " << endl;
		newLattice.at(0) = 1;
		occupiedPos.insert(occupiedPos.begin(), 0);
		ribState.insert(ribState.begin(), 1);
	}
	else {
//		cout << "it is at " << occupiedPos.at(whichMove-1) << endl;
//		cout << "it is in state " << ribState.at(whichMove-1) << endl;
		if ( occupiedPos.at(whichMove-1) < lattice.size() - 1 ) {
			if ( ribState.at(whichMove-1) == 1 ) {
				newLattice.at(occupiedPos.at(whichMove-1)) = 0;
				mrna.at(occupiedPos.at(whichMove-1)) = 1;
				unfoldedPos.insert(unfoldedPos.begin(), whichMove-1);
				newLattice.at(occupiedPos.at(whichMove-1)+1) = 1;
				occupiedPos.at(whichMove-1) += 1;
				ribState.at(whichMove-1) = 0;
//				cout << "now it is at " << occupiedPos.at(whichMove-1) << endl;
//				cout << "see " << newLattice.at(occupiedPos.at(whichMove-1)) << endl;
//				cout << "it is at state " << ribState.at(whichMove-1) << endl;
			}
			else {
				ribState.at(whichMove-1) = 1;
			}
		}
		else if ( occupiedPos.at(whichMove-1) == lattice.size() - 1 )  {
			if ( ribState.at(whichMove-1) == 1 ){
				occupiedPos.pop_back();
				ribState.pop_back();
				newLattice.at( newLattice.size() - 1 ) = 0;
			}
			else {
//				cout << "i should come here " << endl;
				ribState.at(whichMove-1) = 1;
			}
		}
	}
			
	singleStepOutput result;
	result.lattice = newLattice;
	result.arrRate = sumRates;
	result.pos = occupiedPos;
	result.states = ribState;
	result.mrna = mrna;
	result.foldpos = unfoldedPos;
	
	return result;
	
}
    /**
     * Get the prediction response for the given image.
     * @param originImage image, which should be predicted
     * @param resultLayer the name of the result layer
     * @param dataLayer   the name of the data layer
     * @param predictions the predictions
     */
    void CaffeClassifier::predict(std::vector<cv::Mat>& originImages, std::vector<int> labels, string resultLayer,
                                  string dataLayer, vector<float> & predictions) {
        vector<Datum> vecDatum;

        for (int i = 0; i < originImages.size(); i++) {
            cv::Mat originImage = originImages[i];

            // resize image
            Mat image;
            if (originImage.cols != imageSize.width || originImage.rows != imageSize.height) {
                resize(originImage, image, imageSize);
//                std::cout << "Image does not have correct size. Exiting." << std::endl;
//                exit(99);
            } else
                image = originImage;

            // check channels
            if (channels != image.channels()) {
                cerr << "Error: the channel number of input image is invalid for CNN classifier!" << endl;
                exit(1);
            }

            // mat to datum
            Datum datum;
            CVMatToDatum(image, &datum);
            datum.set_label(labels[i]);
            vecDatum.push_back(datum);
            image.release();
        }

        // get the data layer
        const caffe::shared_ptr<MemoryDataLayer<float>> memDataLayer = boost::static_pointer_cast<MemoryDataLayer<float>> (caffeNet->layer_by_name(dataLayer));

        // push new image data
        memDataLayer->AddDatumVector(vecDatum);
        //memDataLayer->ExactNumBottomBlobs();

        // do forward pass
        vector<Blob<float>*> inputVec;
        caffeNet->Forward(inputVec);

        // get results
        const caffe::shared_ptr<Blob<float> > featureBlob = caffeNet->blob_by_name(resultLayer);
        int batchSize = featureBlob->num();
        int dimFeatures = featureBlob->count() / batchSize;
//        std::cout << "Batch size is " << batchSize << "/ dim features is " << dimFeatures << std::endl;

        // get output from each channel
        for (int n = 0; n < batchSize; ++n) {
            float* fs = featureBlob->mutable_cpu_data() + featureBlob->offset(n);
            if (sizeof(fs) > 0) {
                vector<float> feature_vector(fs, fs + dimFeatures);
                predictions.insert(predictions.end(), feature_vector.begin(), feature_vector.end());
            }
        }

        // release data
        // for (Datum d : vecDatum) {
        //     d.release_data();
        // }
    }
Example #26
0
double Interpreter::evaluateInfix(vector<string> v) {
    //std::cout << "In postfix" << std::endl;
    printVector(v);
    //std::cout << "--------lol---------" << std::endl;
    stack<string> *operators = new stack<string>();
    stack<double> *doubles = new stack<double>();
    vector<string> *postfix = new vector<string>();

    v.push_back(")");
    v.insert(v.begin(), "(");

    for (; !v.empty();) {
        string element = v[0];
        if (isalpha(element.front())) {
            postfix->push_back(to_string(variableMap.at(element)));
        } else if (isNumber(element)) {
            postfix->push_back(element);
        } else if (element == "(") {
            operators->push(element);
        } else if (isOperator(element)) {
            for (; precedence(operators);) {
                postfix->push_back(operators->top());
                operators->pop();
            }
            operators->push(element);
        } else {
            while (operators->top() != "(") {
                postfix->push_back(operators->top());
                operators->pop();
            }

            operators->pop();
        }
        v.erase(v.begin());
    }
    // std::cout << "postfix : ";
    printVector(*postfix);
    while (!postfix->empty()) {
        if (isOperator(postfix->at(0))) {
            char x = postfix->front().front();
            double first = doubles->top();
            doubles->pop();
            double second = doubles->top();
            doubles->pop();
            double result;
            switch (x) {
                case '+':
                    result = second + first;
                    break;
                case '-':
                    result = second - first;
                    break;
                case '*':
                    result = second * first;
                    break;
                case '/':
                    result = second / first;
                    break;
            }
            doubles->push(result);
        } else {
            doubles->push(stod(postfix->at(0)));
        }

        //std::cout << "doubles : ";
        printStack(*doubles);
        postfix->erase(postfix->begin());
    }
    //  std::cout << "-------------------------" << std::endl;
    if (doubles->size() == 1) return doubles->top();
    else return NULL;
}
Example #27
0
BEGIN_EXTERNC
static MI_Boolean ClientCallback(
    Selector* sel,
    Handler* handler,
    MI_Uint32 mask, 
    MI_Uint64 currentTimeUsec)
{
    MI_Result r;

    sel=sel;
    currentTimeUsec = currentTimeUsec;
    s_cln_h = handler;

    /* Process write event */
    if (mask & SELECTOR_WRITE)
    {
        for (;;)
        {
            if (!s_cln_connected)
            {
                // Generate random data sequence.
                GenRandData(s_data);
                s_cln_out = s_data;

                // Watch for READ and WRITE events.
                handler->mask = SELECTOR_READ|SELECTOR_WRITE;

                s_cln_connected = true;
                //break;
            }

            // Write out data to server.
            if (s_cln_out.size())
            {
                size_t n = 0;
                size_t m = 7 + (int)(rand() % 256);

                if (m > s_cln_out.size())
                    m = s_cln_out.size();

                r = Sock_Write(handler->sock, &s_cln_out[0], m, &n);

                s_cln_out.erase(s_cln_out.begin(), s_cln_out.begin() + n);
#if defined(TRACE_IO)
                printf("CLIENT.WROTE[%u]\n", n);
#endif

                // If all data written, then quit watching for write.
                if (s_cln_out.size() == 0)
                {
                    handler->mask = SELECTOR_READ;
                }

                if (r == MI_RESULT_WOULD_BLOCK)
                    break;

                TEST_ASSERT(r == MI_RESULT_OK);
            }
            else
                break;
        }
    }

    /* Process read event */
    if (mask & SELECTOR_READ)
    {
        for (;;)
        {
            char buf[BUFFER_SIZE];
            size_t n = 0;

            r = Sock_Read(handler->sock, buf, sizeof(buf), &n);

            s_cln_in.insert(s_cln_in.end(), buf, buf + n);

#if defined(TRACE_IO)
            printf("CLIENT.READ[%u]\n", n);
#endif
            // All data has been written (check whether it is identical).
            if (s_cln_in.size() == s_data.size())
            {
                TEST_ASSERT(s_cln_in == s_data);
                return MI_FALSE;
            }

            if (r == MI_RESULT_WOULD_BLOCK)
                break;

            TEST_ASSERT(r == MI_RESULT_OK);


            break;
        }
    }

    if (mask & SELECTOR_REMOVE)
    {
        Sock_Close(handler->sock);
        PAL_Free(handler);
        handler = 0;
    }

    if (mask & SELECTOR_DESTROY)
    {
        if (handler)
        {
            Sock_Close(handler->sock);
            PAL_Free(handler);
        }
    }

    return MI_TRUE;
}
Example #28
0
  Figura(string descrip,string descrip2){
    vector <string> result;
    vector <string> result2;
    int x,y;

    descrip=descrip.substr(0,descrip.size()-1);
    descrip2=descrip2.substr(0,descrip2.size()-5);

    StringExplode(descrip, "{", &result);
    StringExplode(descrip2, "]", &result2);
     
    tam=0;
    for (int i = 0; i<result.size(); i++){
      tam++;
      result2[i]=result2[i].substr(2,result2[i].size());

      vector <string> datos;
      result[i]=result[i].substr(0,result[i].size()-2);
      StringExplode(result[i], " ", &datos);
      
      vector <string> puntos;
      datos[0]=datos[0].substr(1,datos[0].size()-1);
      StringExplode(datos[0], ",", &puntos);
      x = atoi(puntos[0].c_str() );
      y = atoi(puntos[1].c_str() );
            
      vector <string> caract;
      StringExplode(result2[i], ",", &caract);

      string conexion;
      string curvatura;
      string longitud;
      string convexidad;
      int con, cu, lo, co;

      conexion=caract[0];
      curvatura = caract[1];
      convexidad  = caract[3];
      longitud = caract[2];

      if (convexidad.compare("convex")==0){
	co=1;
      }
      else{
	co=0;
      }

      if (curvatura.compare("very_acute")==0){
	cu=1;
      }
      else if (curvatura.compare("acute")==0){
	cu=2;
      }
      else if (curvatura.compare("right")==0){
	cu=3;
      }
      else if (curvatura.compare("obtuse")==0){
	cu=4;
      }
      else if (curvatura.compare("very_obtuse")==0){
	cu=5;
      }
      else{
	cerr<<"Error curvatura desconocida"<<curvatura<<endl;
      }


      if (conexion.compare("line-line")==0){
	con=1;
      }
      else{
	con=0;
      }


      if (longitud.compare("msh")==0){
	lo=0;
      }
      else if (longitud.compare("hl")==0){
	lo=1;
      }
      else if (longitud.compare("qsh")==0){
	lo=2;
      }
      else if (longitud.compare("sl")==0){
	lo=3;
      }
      else if (longitud.compare("ql")==0){
	lo=4;
      }
      else if (longitud.compare("dl")==0){
	lo=5;
      }
      else if (longitud.compare("ml")==0){
	lo=6;
      }
      else{
	cerr<<"Error longitud desconocida:"<<longitud<<endl;
      }

      Vertice ver(x, y, con, cu, lo, co);
      vertices.push_back(ver);
    }


    int eje = 0;
    int min = vertices[0].pos->y;
    for (int i = 1; i< vertices.size(); i++){
      if (abs(vertices[eje].pos->y - vertices[i].pos->y) <= UMBRAL
	  && vertices[i].pos->x < vertices[eje].pos->x)
	eje = i;
    }
    
    Posicion peje (vertices[eje].pos->x, vertices[eje].pos->y);

    while (!vertices[0].pos->EsIgual(peje)){
      Vertice aux (vertices[tam-1].pos->x, vertices[tam-1].pos->y, vertices[tam-1].conexion, vertices[tam-1].curvatura, vertices[tam-1].longitud, vertices[tam-1].convexidad);
      vertices.pop_back();
      vector<Vertice>::iterator it;
      it=vertices.begin();
      vertices.insert(it, aux);
    }

  }
Example #29
0
// Encrypt data in vector
void RC5Simple::RC5_Encrypt(vector<unsigned char> &in, vector<unsigned char> &out)
{
 // Clear output vector
 out.clear();


 // No crypt null data
 if(in.size()==0) return;

 
 // Save input data size
 unsigned int clean_data_size=in.size();
 RC5_LOG(( "Input data size: %d\n", clean_data_size ));


 // IV block
 unsigned char iv[RC5_BLOCK_LEN];
 for(int i=0; i<RC5_BLOCK_LEN; i++)
  iv[i]=(unsigned char)RC5_Rand(0, 0xFF);


 // Block with data size
 unsigned char data_size[RC5_BLOCK_LEN];

 for(int i=0; i<RC5_BLOCK_LEN; i++)
  {
   data_size[i]=RC5_GetByteFromInt( clean_data_size, i );
   RC5_LOG(( "Data size byte %d: %.2X\n", i, data_size[i] ));
  }


 // Insert data size to begin data
 in.insert( in.begin(), RC5_BLOCK_LEN, 0);
 for(int i=0; i<RC5_BLOCK_LEN; i++)
  in[i]=data_size[i];


 // Align end of data to block size
 int last_unalign_len=clean_data_size%RC5_BLOCK_LEN;
 RC5_LOG(( "Last unalign len: %d\n", last_unalign_len ));

 if(last_unalign_len>0)
  {
   // Add random data to end for align to block size
   for(int i=0; i<(RC5_BLOCK_LEN-last_unalign_len); i++)
    {
     RC5_LOG(( "Add byte: %d\n", i ));
     in.push_back( (unsigned char)RC5_Rand(0, 0xFF) );
    }
  }

 #if RC5_ENABLE_DEBUG_PRINT==1
  RC5_LOG(( "Data size after crypt setup: %d\n", in.size() ));
  RC5_LOG(( "Plain byte after crypt setup: " ));
  for(int i=0; i<in.size(); i++)
   RC5_LOG(( "%.2X ", in[i] ));
  RC5_LOG(( "\n" ));
 #endif


 // ------  
 // Encode
 // ------  

 // Create cell in output vector
 out.resize(in.size()+RC5_BLOCK_LEN, 0);


 // Save start IV to first block in output data
 for(int i=0; i<RC5_BLOCK_LEN; i++)
  out[i]=iv[i];


 // Set secret key for encrypt
 RC5_Setup(rc5_key);


 // Encode by blocks
 unsigned int block=0;
 while( (RC5_BLOCK_LEN*(block+1))<=in.size() )
  {
   unsigned int shift=block*RC5_BLOCK_LEN;

   // Temp input buffer for dont modify input data
   unsigned char temp_in[RC5_BLOCK_LEN];

   // XOR block with current IV
   for(int i=0; i<RC5_BLOCK_LEN; i++)
    temp_in[i]=in[shift+i] ^ iv[i];

   RC5_TWORD temp_word_1;
   RC5_TWORD temp_word_2;
   RC5_TWORD pt[RC5_WORDS_IN_BLOCK];
   RC5_TWORD ct[RC5_WORDS_IN_BLOCK];

   RC5_LOG(( "Block num %d, shift %d\n", block, shift ));

   temp_word_1=RC5_GetWordFromByte(temp_in[0],
                                   temp_in[1],
                                   temp_in[2],
                                   temp_in[3]);

   temp_word_2=RC5_GetWordFromByte(temp_in[RC5_WORD_LEN+0],
                                   temp_in[RC5_WORD_LEN+1],
                                   temp_in[RC5_WORD_LEN+2],
                                   temp_in[RC5_WORD_LEN+3]);

   pt[0]=temp_word_1; 
   pt[1]=temp_word_2;


   // Encode
   RC5_EncryptBlock(pt, ct);


   #if RC5_ENABLE_DEBUG_PRINT==1
    RC5_LOG(( "Pt %.8X, %.8X\n", pt[0], pt[1] ));
    RC5_LOG(( "Ct %.8X, %.8X\n", ct[0], ct[1] ));
   #endif

   // Save crypt data
   for(int i=0; i<RC5_WORD_LEN; i++)
    {
     // Save crypt data with shift to RC5_BLOCK_LEN
     // btw. in first block putted IV 
     out[RC5_BLOCK_LEN+shift+i]=RC5_GetByteFromWord(ct[0], i);
     out[RC5_BLOCK_LEN+shift+RC5_WORD_LEN+i]=RC5_GetByteFromWord(ct[1], i);
    }


   // Generate next IV for Cipher Block Chaining (CBC)
   for(int i=0; i<RC5_BLOCK_LEN; i++)
    iv[i]=out[RC5_BLOCK_LEN+shift+i];


   block++;
  }


 // Cleaning IV
 for(int i=0; i<RC5_BLOCK_LEN; i++)
  iv[i]=0;


 // -----------------------------------
 // Return input vector to firsted data
 // -----------------------------------

 // Clear input vector from service data
 in.erase(in.begin(), in.begin()+RC5_BLOCK_LEN);

 // Remove from input vector last random byte for aligning
 if(in.size()>clean_data_size)
  in.erase(in.begin()+clean_data_size, in.end());

}
Example #30
0
File: CNTK.cpp Project: AltasK/CNTK
static void Append(vector<wstring>& toWhat, const WHAT& what)
{
    toWhat.insert(toWhat.end(), what.begin(), what.end());
}