AnyType bernoulli_vector::run(AnyType & args)
{
    int dim = args[0].getAs<int>();
    double upper_val = args[1].getAs<double>();
    double lower_val = args[2].getAs<double>();
    double prob = args[3].getAs<double>();
    int seed = args[4].getAs<int>();

    if (dim < 1) {
        throw std::invalid_argument("invalid argument - dim should be positive");
    }
    if (prob > 1 || prob < 0) {
        throw std::invalid_argument("invalid argument - probability should be in [0,1]");
    }

    ColumnVector res(dim);
    boost::minstd_rand generator(seed);
    boost::bernoulli_distribution<> bn_dist(prob);
    boost::variate_generator<boost::minstd_rand&, boost::bernoulli_distribution<> > bn(generator, bn_dist);

    for (int i = 0; i < dim; i++) {
        res(i) = bn() ? upper_val : lower_val;
    }
    return res;
}
void insertar_arco(Grafo *        g,
		   const string & s1, 
		   const string & s2, 
		   const int &    i)
{
  Grafo::Node * src = bn(g, s1);
  Grafo::Node * tgt = bn(g, s2);

  g->insert_arc(src, tgt, i);
}
Exemple #3
0
std::unique_ptr<RSA_PrivateKey>
make_openssl_rsa_private_key(RandomNumberGenerator& rng, size_t rsa_bits)
   {
   if (rsa_bits > INT_MAX)
      throw Internal_Error("rsa_bits overflow");

   secure_vector<uint8_t> seed(BOTAN_SYSTEM_RNG_POLL_REQUEST);
   rng.randomize(seed.data(), seed.size());
   RAND_seed(seed.data(), seed.size());

   std::unique_ptr<BIGNUM, std::function<void (BIGNUM*)>> bn(BN_new(), BN_free);
   if(!bn)
      throw OpenSSL_Error("BN_new");
   if(!BN_set_word(bn.get(), RSA_F4))
      throw OpenSSL_Error("BN_set_word");

   std::unique_ptr<RSA, std::function<void (RSA*)>> rsa(RSA_new(), RSA_free);
   if(!rsa)
      throw OpenSSL_Error("RSA_new");
   if(!RSA_generate_key_ex(rsa.get(), rsa_bits, bn.get(), nullptr))
      throw OpenSSL_Error("RSA_generate_key_ex");

   uint8_t* der = nullptr;
   int bytes = i2d_RSAPrivateKey(rsa.get(), &der);
   if(bytes < 0)
      throw OpenSSL_Error("i2d_RSAPrivateKey");

   const secure_vector<uint8_t> keydata(der, der + bytes);
   memset(der, 0, bytes);
   free(der);
   return std::unique_ptr<Botan::RSA_PrivateKey>
      (new RSA_PrivateKey(AlgorithmIdentifier(), keydata));
   }
template <class K> inline bool do_intersect(const Rectangle_2<K> &a, const Rectangle_2<K> &b)
{
    typedef typename K::Vector_2 Vector_2;
    typedef typename K::FT FT;
    Vector_2 an(a.normal());
    Vector_2 bn(b.normal());
    Vector_2 v(a.center()-b.center());

    FT det = abs(an.x()*bn.y()-an.y()*bn.x());
    FT dot = abs(an*bn);

    FT an2  = an.squared_length();
    FT br(abs(b.ratio()));
    FT ax0 = an*v;
    FT dax = dot+br*det+an2;
    if(ax0*ax0>=dax*dax) return false;

    FT ar(abs(a.ratio()));
    FT ay0 = an.x()*v.y()-an.y()*v.x();
    FT day = det+br*dot+ar*an2;
    if(ay0*ay0>=day*day) return false;

    FT bn2 = bn.squared_length();
    FT bx0 = bn*v;
    FT dbx = dot+ar*det+bn2;
    if(bx0*bx0>=dbx*dbx) return false;

    FT by0 = v.x()*bn.y()-v.y()*bn.x();
    FT dby = det+ar*dot+br*bn2;
    return(by0*by0<dby*dby);
}
static int generate_rsa_keypair(EVP_PKEY* pkey, const keymaster_rsa_keygen_params_t* rsa_params) {
    Unique_BIGNUM bn(BN_new());
    if (bn.get() == NULL) {
        logOpenSSLError("generate_rsa_keypair");
        return -1;
    }

    if (BN_set_word(bn.get(), rsa_params->public_exponent) == 0) {
        logOpenSSLError("generate_rsa_keypair");
        return -1;
    }

    /* initialize RSA */
    Unique_RSA rsa(RSA_new());
    if (rsa.get() == NULL) {
        logOpenSSLError("generate_rsa_keypair");
        return -1;
    }

    if (!RSA_generate_key_ex(rsa.get(), rsa_params->modulus_size, bn.get(), NULL) ||
        RSA_check_key(rsa.get()) < 0) {
        logOpenSSLError("generate_rsa_keypair");
        return -1;
    }

    if (EVP_PKEY_assign_RSA(pkey, rsa.get()) == 0) {
        logOpenSSLError("generate_rsa_keypair");
        return -1;
    }
    release_because_ownership_transferred(rsa);

    return 0;
}
Exemple #6
0
const BoxList
BoxLib::boxDiff (const Box& b1in,
		 const Box& b2)
{
   BL_ASSERT(b1in.sameType(b2));
  
   Box b1(b1in);
   BoxList b_list(b1.ixType());

   if ( !b2.contains(b1) )
   {
       if ( !b1.intersects(b2) )
       {
           b_list.push_back(b1);
       }
       else
       {
           const int* b2lo = b2.loVect();
           const int* b2hi = b2.hiVect();

           for (int i = BL_SPACEDIM-1; i >= 0; i--)
           {
               const int* b1lo = b1.loVect();
               const int* b1hi = b1.hiVect();

               if ((b1lo[i] < b2lo[i]) && (b2lo[i] <= b1hi[i]))
               {
                   Box bn(b1);
                   bn.setSmall(i,b1lo[i]);
                   bn.setBig(i,b2lo[i]-1);
                   b_list.push_back(bn);
                   b1.setSmall(i,b2lo[i]);
               }
               if ((b1lo[i] <= b2hi[i]) && (b2hi[i] < b1hi[i]))
               {
                   Box bn(b1);
                   bn.setSmall(i,b2hi[i]+1);
                   bn.setBig(i,b1hi[i]);
                   b_list.push_back(bn);
                   b1.setBig(i,b2hi[i]);
               }
           }
       }
   }
   return b_list;
}
static int openssl_generate_keypair(const keymaster_device_t* dev,
        const keymaster_keypair_t key_type, const void* key_params,
        uint8_t** keyBlob, size_t* keyBlobLength) {
    ssize_t privateLen, publicLen;

    if (key_type != TYPE_RSA) {
        ALOGW("Unsupported key type %d", key_type);
        return -1;
    } else if (key_params == NULL) {
        ALOGW("key_params == null");
        return -1;
    }

    keymaster_rsa_keygen_params_t* rsa_params = (keymaster_rsa_keygen_params_t*) key_params;

    Unique_BIGNUM bn(BN_new());
    if (bn.get() == NULL) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }

    if (BN_set_word(bn.get(), rsa_params->public_exponent) == 0) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }

    /* initialize RSA */
    Unique_RSA rsa(RSA_new());
    if (rsa.get() == NULL) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }

    if (!RSA_generate_key_ex(rsa.get(), rsa_params->modulus_size, bn.get(), NULL)
            || RSA_check_key(rsa.get()) < 0) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }

    /* assign to EVP */
    Unique_EVP_PKEY pkey(EVP_PKEY_new());
    if (pkey.get() == NULL) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }

    if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) == 0) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }
    OWNERSHIP_TRANSFERRED(rsa);

    if (wrap_key(pkey.get(), EVP_PKEY_RSA, keyBlob, keyBlobLength)) {
        return -1;
    }

    return 0;
}
Exemple #8
0
gnc_numeric
gnc_numeric_div(gnc_numeric a, gnc_numeric b,
                gint64 denom, gint how)
{
    if (gnc_numeric_check(a) || gnc_numeric_check(b))
    {
        return gnc_numeric_error(GNC_ERROR_ARG);
    }

    GncNumeric an (a), bn (b);
    GncDenom new_denom (an, bn, denom, how);
    if (new_denom.m_error)
        return gnc_numeric_error (new_denom.m_error);

    return static_cast<gnc_numeric>(an.div(bn, new_denom));
}
Exemple #9
0
int
gnc_numeric_compare(gnc_numeric a, gnc_numeric b)
{
    gint64 aa, bb;

    if (gnc_numeric_check(a) || gnc_numeric_check(b))
    {
        return 0;
    }

    if (a.denom == b.denom)
    {
        if (a.num == b.num) return 0;
        if (a.num > b.num) return 1;
        return -1;
    }

    GncNumeric an (a), bn (b);

    return (an.m_num * bn.m_den).cmp(bn.m_num * an.m_den);
}
Exemple #10
0
char *lire(t_g *s, int fd, char **line)
{
	if(s->an != NULL)
		{
			line[0] = ft_strjoin(line[0],s->an);
			s->an = NULL;
		}
	while ((s->ret = read(fd, s->buf,BUFF_SIZE)))
	{
		s->buf[s->ret] = '\0';
		line[0] = ft_strjoin(line[0], s->buf);
		if (ft_strchr(line[0], '\n'))
		{
			s->an = ft_strchr(line[0],'\n');
			s->an++;
			line[0] = ft_strsub(line[0], 0, bn(line[0]));
			return(line[0]);
		}
	}
	return(line[0]);
}
Exemple #11
0
	static BigNumber fromInteger(__int64 n) {

		unsigned char sz[22];
		if (n == 0) {
			return zero();
		}

		int index = 0;
		while (n > 0) {
			sz[index++] = n % 10;
			n /= 10;
		}

		BigNumber bn(index);
		bn.usedLength = index;

		for (int place = 0; place < index; place++) {
			bn.pb[place] = sz[place];
		}

		return bn;
	}
Exemple #12
0
int get_next_line(int const fd, char **line)
{
	static t_g *s;

	if((fd < 0 || fd > 100) || line == NULL || fd == 42)
		return (-1);
	if(!s)
	{
		s = malloc(sizeof(t_g));
		s->an = NULL;
	}
	line[0] = ft_strnew(1);
	if (s->an)
	{
		if(ft_strchr(s->an, '\n'))
		{
			line[0] = ft_strsub(s->an, 0, bn(s->an));
			s->an  = ft_strchr(s->an, '\n');
			s->an++;
			if (*s->an == '\0')
			{
				s->an = NULL;
				free(s->an);
				return (1);
			}
			else
				return (1);
		}
	}

	line[0] = lire(s, fd, &line[0]);
	if(line[0][0] == '\0' && s->ret == 0)
		return (0);
	else
		return (1);
}
void
TestLimiterNode() {
    int out_int;
    tbb::flow::graph g;
    tbb::flow::limiter_node<int> ln(g,1);
    REMARK("Testing limiter_node: preds and succs");
    ASSERT(ln.decrement.my_predecessor_count == 0, "error in pred count");
    ASSERT(ln.decrement.my_initial_predecessor_count == 0, "error in initial pred count");
    ASSERT(ln.decrement.my_current_count == 0, "error in current count");
    ASSERT(ln.init_decrement_predecessors == 0, "error in decrement predecessors");
    ASSERT(ln.my_threshold == 1, "error in my_threshold");
    tbb::flow::queue_node<int> inq(g);
    tbb::flow::queue_node<int> outq(g);
    tbb::flow::broadcast_node<tbb::flow::continue_msg> bn(g);

    tbb::flow::make_edge(inq,ln);
    tbb::flow::make_edge(ln,outq);
    tbb::flow::make_edge(bn,ln.decrement);

    g.wait_for_all();
    ASSERT(!(ln.my_successors.empty()),"successors empty after make_edge");
    ASSERT(ln.my_predecessors.empty(), "input edge reversed");
    inq.try_put(1);
    g.wait_for_all();
    ASSERT(outq.try_get(out_int) && out_int == 1, "limiter_node didn't pass first value");
    ASSERT(ln.my_predecessors.empty(), "input edge reversed");
    inq.try_put(2);
    g.wait_for_all();
    ASSERT(!outq.try_get(out_int), "limiter_node incorrectly passed second input");
    ASSERT(!ln.my_predecessors.empty(), "input edge to limiter_node not reversed");
    bn.try_put(tbb::flow::continue_msg());
    g.wait_for_all();
    ASSERT(outq.try_get(out_int) && out_int == 2, "limiter_node didn't pass second value");
    g.wait_for_all();
    ASSERT(!ln.my_predecessors.empty(), "input edge was reversed(after try_get())");
    g.reset();
    ASSERT(ln.my_predecessors.empty(), "input edge not reset");
    inq.try_put(3);
    g.wait_for_all();
    ASSERT(outq.try_get(out_int) && out_int == 3, "limiter_node didn't pass third value");

    REMARK(" rf_clear_edges");
    // currently the limiter_node will not pass another message
    g.reset(tbb::flow::rf_clear_edges);
    ASSERT(ln.decrement.my_predecessor_count == 0, "error in pred count");
    ASSERT(ln.decrement.my_initial_predecessor_count == 0, "error in initial pred count");
    ASSERT(ln.decrement.my_current_count == 0, "error in current count");
    ASSERT(ln.init_decrement_predecessors == 0, "error in decrement predecessors");
    ASSERT(ln.my_threshold == 1, "error in my_threshold");
    ASSERT(ln.my_predecessors.empty(), "preds not reset(rf_clear_edges)");
    ASSERT(ln.my_successors.empty(), "preds not reset(rf_clear_edges)");
    ASSERT(inq.my_successors.empty(), "Arc not removed on reset(rf_clear_edges)");
    ASSERT(inq.my_successors.empty(), "Arc not removed on reset(rf_clear_edges)");
    ASSERT(bn.my_successors.empty(), "control edge not removed on reset(rf_clear_edges)");
    tbb::flow::make_edge(inq,ln);
    tbb::flow::make_edge(ln,outq);
    inq.try_put(4);
    inq.try_put(5);
    g.wait_for_all();
    ASSERT(outq.try_get(out_int),"missing output after reset(rf_clear_edges)");
    ASSERT(out_int == 4, "input incorrect (4)");
    bn.try_put(tbb::flow::continue_msg());
    g.wait_for_all();
    ASSERT(!outq.try_get(out_int),"second output incorrectly passed (rf_clear_edges)");
    REMARK(" done\n");
}
Exemple #14
0
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;
                    }
                    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;
                    }
                    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;
}
Exemple #15
0
int main()
{

    Bayes bn(4, 2); //constract a bayes network with 4 featuers and 2 classes


    std::vector<double> FV(4);

    //Class 0
    FV[0] = 752; FV[1] = 265; FV[2] = 700; FV[3] = 271; bn.learn(FV, 0u);
    FV[0] = 895; FV[1] = 355; FV[2] = 812; FV[3] = 288; bn.learn(FV, 0u);
    FV[0] = 893; FV[1] = 352; FV[2] = 790; FV[3] = 298; bn.learn(FV, 0u);
    FV[0] = 814; FV[1] = 326; FV[2] = 790; FV[3] = 296; bn.learn(FV, 0u);
    FV[0] = 532; FV[1] = 405; FV[2] = 750; FV[3] = 401; bn.learn(FV, 0u);
    FV[0] = 532; FV[1] = 405; FV[2] = 750; FV[3] = 401; bn.learn(FV, 0u);
    FV[0] = 478; FV[1] = 385; FV[2] = 750; FV[3] = 394; bn.learn(FV, 0u);
    FV[0] = 532; FV[1] = 405; FV[2] = 750; FV[3] = 401; bn.learn(FV, 0u);
    FV[0] = 565; FV[1] = 47 ; FV[2] = 710; FV[3] = 142; bn.learn(FV, 0u);
    FV[0] = 689; FV[1] = 127; FV[2] = 955; FV[3] = 162; bn.learn(FV, 0u);

    //Class 1
    FV[0] = 576; FV[1] = 726; FV[2] = 287; FV[3] =719; bn.learn(FV, 1);
    FV[0] = 718; FV[1] = 783; FV[2] = 300; FV[3] =536; bn.learn(FV, 1);
    FV[0] = 859; FV[1] = 724; FV[2] = 270; FV[3] =480; bn.learn(FV, 1);
    FV[0] = 839; FV[1] = 512; FV[2] = 246; FV[3] =657; bn.learn(FV, 1);
    FV[0] = 746; FV[1] = 343; FV[2] = 250; FV[3] =710; bn.learn(FV, 1);
    FV[0] = 660; FV[1] = 527; FV[2] = 272; FV[3] =763; bn.learn(FV, 1);
    FV[0] = 704; FV[1] = 621; FV[2] = 263; FV[3] =713; bn.learn(FV, 1);
    FV[0] = 684; FV[1] = 836; FV[2] = 287; FV[3] =213; bn.learn(FV, 1);
    FV[0] = 678; FV[1] = 800; FV[2] = 377; FV[3] =220; bn.learn(FV, 1);
    FV[0] = 624; FV[1] = 697; FV[2] = 494; FV[3] =238; bn.learn(FV, 1);


    LINFO("Class 0");
    for(uint i=0; i<bn.getNumFeatures(); i++)
      LINFO("Feature %i: mean %f, stddevSq %f", i, bn.getMean(0, i), bn.getStdevSq(0, i));

    LINFO("Class 1");
    for(uint i=0; i<bn.getNumFeatures(); i++)
      LINFO("Feature %i: mean %f, stddevSq %f", i, bn.getMean(1, i), bn.getStdevSq(1, i));

    LINFO("Class 0 frq %i prob %f", bn.getClassFreq(0), bn.getClassProb(0));
    LINFO("Class 1 frq %i prob %f", bn.getClassFreq(1), bn.getClassProb(1));


    //New FV to classify
    FV[0] = 750; FV[1] = 269; FV[2] = 720; FV[3] = 291;
    int cls = bn.classify(FV); //classify a given FV
    LINFO("FV1 belongs to class %i", cls);

    FV[0] = 458; FV[1] = 381; FV[2] = 350; FV[3] = 392;
    cls = bn.classify(FV); //classify a given FV
    LINFO("FV2 belongs to class %i", cls);


    bn.save("Bayes.net");

    bn.load("Bayes.net");

    LINFO("Class 0");
    for(uint i=0; i<bn.getNumFeatures(); i++)
      LINFO("Feature %i: mean %f, stddevSq %f", i, bn.getMean(0, i), bn.getStdevSq(0, i));

    LINFO("Class 1");
    for(uint i=0; i<bn.getNumFeatures(); i++)
      LINFO("Feature %i: mean %f, stddevSq %f", i, bn.getMean(1, i), bn.getStdevSq(1, i));

    LINFO("Class 0 frq %i prob %f", bn.getClassFreq(0), bn.getClassProb(0));
    LINFO("Class 1 frq %i prob %f", bn.getClassFreq(1), bn.getClassProb(1));


    //New FV to classify
    FV[0] = 750; FV[1] = 269; FV[2] = 720; FV[3] = 291;
    cls = bn.classify(FV); //classify a given FV
    LINFO("FV1 belongs to class %i", cls);

    FV[0] = 458; FV[1] = 381; FV[2] = 350; FV[3] = 392;
    cls = bn.classify(FV); //classify a given FV
    LINFO("FV2 belongs to class %i", cls);
}
Exemple #16
0
int
gagb()
{
	int             money;
	char            genbuf[200], buf[80];
	char            ans[5] = "";
	/* ±¶ÂÊ        0  1   2   3   4   5   6   7   8   9   10 */
	float           bet[11] = {0, 100, 50, 10, 3, 1.5, 1.2, 0.9, 0.8, 0.5, 0.1};
	int             a, b, c, count;

	modify_user_mode(M_XAXB);
	srandom(time(0));
	money = get_money(0,"game/gagb.welcome");
	if(!money) return 0;
	move(6, 0);
	prints("%s", MSG_SEPERATOR);
	move(17, 0);
	prints("%s", MSG_SEPERATOR);

	do {
		itoa(random() % 10000, ans);
		for (a = 0; a < 3; a++)
			for (b = a + 1; b < 4; b++)
				if (ans[a] == ans[b])
					ans[0] = 0;
	} while (!ans[0]);

	for (count = 1; count < 11; count++) {
		do {
			getdata(5, 0, "Çë²Â[q - Í˳ö] ¡ú ", genbuf, 5, DOECHO, YEA);
			if (!strcmp(genbuf, "Good")) {
				prints("[%s]", ans);
				sprintf(genbuf,"²ÂÊý×Ö×÷±×, ÏÂ×¢ %d Ôª", money);
				gamelog(genbuf);
				igetch();
			}
			if ( genbuf[0] == 'q' || genbuf[0] == 'Q' ) {
				sprintf(buf,"·ÅÆú²Â²â, ¿Û³ýѹע½ð¶î %d Ôª.", money);
				gamelog(buf);
				return;
			}
			c = atoi(genbuf);
			itoa(c, genbuf);
			for (a = 0; a < 3; a++)
				for (b = a + 1; b < 4; b++)
					if (genbuf[a] == genbuf[b])
						genbuf[0] = 0;
			if (!genbuf[0]) {
				move ( 18,3 );
				prints("ÊäÈëÊý×ÖÓÐÎÊÌâ!!");
				pressanykey();
				move ( 18,3 );
				prints("                ");
			}
		} while (!genbuf[0]);
		move(count + 6, 0);
		prints("  µÚ %2d ´Î£º %s  ->  %dA %dB ", count, genbuf, an(genbuf, ans), bn(genbuf, ans));
		if (an(genbuf, ans) == 4)
			break;
	}

	if (count > 10) {
		sprintf(buf, "ÄãÊäÁËßÏ£¡ÕýÈ·´ð°¸ÊÇ %s£¬Ï´ÎÔÙ¼ÓÓÍ°É!!", ans);
		sprintf(genbuf,"¿ÉÁ¯Ã»²Âµ½£¬ÊäÁË %d Ôª£¡", money);
		gamelog(genbuf);
	} else {
		int             oldmoney = money;
		money *= bet[count];
		inmoney(money);
		if (money - oldmoney > 0)
			sprintf(buf, "¹§Ï²£¡×ܹ²²ÂÁË %d ´Î£¬¾»×¬½±½ð %d Ôª", count, money - oldmoney);
		else if (money - oldmoney == 0)
			sprintf(buf, "°¦¡«¡«×ܹ²²ÂÁË %d ´Î£¬Ã»ÊäûӮ£¡", count);
		else
			sprintf(buf, "°¡¡«¡«×ܹ²²ÂÁË %d ´Î£¬ÅâÇ® %d Ôª£¡", count, oldmoney - money);
	}
	gamelog(buf);
	move(22, 0);
        clrtobot();
	prints(buf);
	pressanykey();
	return 0;
}
Exemple #17
0
int main()
{
    const std::chrono::system_clock::time_point start =
        std::chrono::system_clock::now();

    std::array<std::array<bool, width>, height> space{};
    std::mt19937 mt(10);
    std::bernoulli_distribution bn(0.5);
    std::uniform_real_distribution<Real> uni(0., 1.);

    for(auto outer = space.begin(); outer < space.end(); ++outer)
        for(auto iter = outer->begin(); iter != outer->end(); ++iter)
            *iter = bn(mt);

    std::array<std::array<Real, width>, height> random{};
    std::array<char, (width+1) * height + 1> format;
    for(std::size_t i=0; i<height; ++i)
        format[(width+1)*i+width] = '\n';
    format[(width+1)*height] = '\0';

    std::size_t t = 0;

    const std::chrono::system_clock::time_point start_time =
        std::chrono::system_clock::now();
    while(t < 100)
    {
        for(auto outer = random.begin(); outer < random.end(); ++outer)
            for(auto iter = outer->begin(); iter != outer->end(); ++iter)
                *iter = uni(mt);

#pragma omp parallel
{
#pragma omp for schedule(guided)
        for(std::size_t i=0; i<height; ++i)
        {
            if(i % 2 == 0)
                for(std::size_t j=0; j<width; j+=2)
                    step(space, i, j, random[i][j]);
            else
                for(std::size_t j=1; j<width; j+=2)
                    step(space, i, j, random[i][j]);
        }

#pragma omp for schedule(guided)
        for(std::size_t i=0; i<height; ++i)
        {
            if(i % 2 == 0)
                for(std::size_t j=1; j<width; j+=2)
                    step(space, i, j, random[i][j]);
            else
                for(std::size_t j=0; j<width; j+=2)
                    step(space, i, j, random[i][j]);
        }

}//parallel

        for(std::size_t i=0; i<height; ++i)
            for(std::size_t j=0; j<width; ++j)
                format[(width+1) * i + j] = space[i][j]+48;
        puts(format.data());
        ++t;
    }

    const std::chrono::system_clock::time_point end =
        std::chrono::system_clock::now();

    const auto whole_time =
        std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
    const auto time_integral =
        std::chrono::duration_cast<std::chrono::milliseconds>(end - start_time);

    std::cerr << "time(include initialization): " << whole_time.count() << " ms" << std::endl;
    std::cerr << "time(only time integration) : " << time_integral.count() << " ms" << std::endl;

    return EXIT_SUCCESS;
}
void tst_QGeometryData::appendVertexNormal()
{
    QVector3D a(1.1, 1.2, 1.3);
    QVector3D b(2.1, 2.2, 2.3);
    QVector3D c(3.1, 3.2, 3.3);
    QVector3D d(4.1, 4.2, 4.3);
    QVector3D an(5.1, 5.2, 5.3);
    QVector3D bn(6.1, 6.2, 6.3);
    QVector3D cn(7.1, 7.2, 7.3);
    QVector3D dn(8.1, 8.2, 8.3);
    {
        QGeometryData data;
        data.appendVertex(a);
        data.appendNormal(an);
        QCOMPARE(data.count(), 1);
        QCOMPARE(data.fields(), QGL::fieldMask(QGL::Position) | QGL::fieldMask(QGL::Normal));
        QCOMPARE(data.vertices().count(), 1);
        QCOMPARE(data.vertices().at(0), a);
    }
    {
        QGeometryData data;
        data.appendVertex(a, b);
        data.appendNormal(an, bn);
        QCOMPARE(data.count(), 2);
        QCOMPARE(data.fields(), QGL::fieldMask(QGL::Position) | QGL::fieldMask(QGL::Normal));
        QCOMPARE(data.vertices().count(), 2);
        QCOMPARE(data.vertices().at(0), a);
        QCOMPARE(data.vertex(1), b);
        QCOMPARE(data.normals().count(), 2);
        QCOMPARE(data.normal(0), an);
        QCOMPARE(data.normals().at(1), bn);
    }
    {
        QGeometryData data;
        data.appendVertex(a, b, c);
        data.appendNormal(an, bn, cn);
        QCOMPARE(data.count(), 3);
        QCOMPARE(data.fields(), QGL::fieldMask(QGL::Position) | QGL::fieldMask(QGL::Normal));
        QCOMPARE(data.vertices().count(), 3);
        QCOMPARE(data.vertices().at(0), a);
        QCOMPARE(data.vertices().at(1), b);
        QCOMPARE(data.vertices().at(2), c);
        QCOMPARE(data.normals().count(), 3);
        QCOMPARE(data.normal(0), an);
        QCOMPARE(data.normals().at(1), bn);
        QCOMPARE(data.normal(2), cn);
    }
    {
        QGeometryData data;
        data.appendVertex(a, b, c, d);
        data.appendNormal(an, bn, cn, dn);
        QCOMPARE(data.count(), 4);
        QCOMPARE(data.fields(), QGL::fieldMask(QGL::Position) | QGL::fieldMask(QGL::Normal));
        QCOMPARE(data.vertices().count(), 4);
        QCOMPARE(data.vertices().at(0), a);
        QCOMPARE(data.vertices().at(1), b);
        QCOMPARE(data.vertices().at(2), c);
        QCOMPARE(data.vertices().at(3), d);
        QCOMPARE(data.normals().count(), 4);
        QCOMPARE(data.normals().at(0), an);
        QCOMPARE(data.normals().at(1), bn);
        QCOMPARE(data.normals().at(2), cn);
        QCOMPARE(data.normals().at(3), dn);
    }
    {
        QGeometryData data;
        data.appendVertex(a, b, c, d);
        data.appendNormal(an, bn, cn, dn);
        data.appendVertex(a, b, c, d);
        data.appendNormal(an, bn, cn, dn);
        data.appendVertex(a);
        data.appendNormal(an);
        QCOMPARE(data.count(), 9);
        QCOMPARE(data.fields(), QGL::fieldMask(QGL::Position) | QGL::fieldMask(QGL::Normal));
        QCOMPARE(data.vertices().count(), 9);
        QCOMPARE(data.vertices().at(0), a);
        QCOMPARE(data.vertices().at(1), b);
        QCOMPARE(data.vertices().at(5), b);
        QCOMPARE(data.vertices().at(8), a);
        QCOMPARE(data.normals().count(), 9);
        QCOMPARE(data.normals().at(0), an);
        QCOMPARE(data.normals().at(1), bn);
        QCOMPARE(data.normals().at(5), bn);
        QCOMPARE(data.normals().at(8), an);
    }
}
Exemple #19
0
/** write cbf file
 *
 * @param filename the filename to write the cbf to
 * @param data iterator to the data that should be written
 * @param shape the shape of the image
 *
 * @author Stephan Kassemeyer
 */
inline
void write(const std::string &filename, std::vector<float>::const_iterator data,
           const std::pair<int,int>& shape)
{
  const int nx = shape.first;
  const int ny = shape.second;

  /** cbf parameters: */
  int IOBUFSIZ = 4096;
  char MARKBYTE[4] = {static_cast<char>(0x0C),
                      static_cast<char>(0x01A),
                      static_cast<char>(0x004),
                      static_cast<char>(0x0D5)};

  /** create the cbf file */
  std::ofstream cbf_file;
  cbf_file.open(filename.c_str(), std::ios::out|std::ios::binary);

  /**  find out length of the compressed array: */
  int nbytes = 0;
  int pixvalue = 0;
  int diff;
  int absdiff;
  for (int iadr=0; iadr<nx*ny; ++iadr)
  {
    diff = ((int) data[iadr]) - pixvalue;
    pixvalue = (int) data[iadr];
    absdiff = abs(diff);
    ++nbytes;
    if (absdiff < 128)
      continue;
    nbytes += 2;
    if (absdiff < 32768)
      continue;
    nbytes += 4;
  }

  QString fn(QString::fromStdString(filename));
  QString bn(QFileInfo(fn).fileName());
  std::string fbn(bn.toStdString());

  /** write image header */
  cbf_file << "###CBF: Generated by CASS " << VERSION << "\r\n";
  cbf_file << "" << "\r\n";
  cbf_file << fbn << "\r\n";
  cbf_file << "" << "\r\n";
  cbf_file << "_array_data.header_convention \"XDS special\"" << "\r\n";
  cbf_file << "_array_data.header_contents" << "\r\n";
  cbf_file << ";" << "\r\n";
  cbf_file << ";" << "\r\n";
  cbf_file << "" << "\r\n";
  cbf_file << "_array_data.data" << "\r\n";
  cbf_file << ";" << "\r\n";
  cbf_file << "--CIF-BINARY-FORMAT-SECTION--" << "\r\n";
  cbf_file << "Content-Type: application/octet-stream;" << "\r\n";
  cbf_file << "     conversions=\"x-CBF_BYTE_OFFSET\"" << "\r\n";
  cbf_file << "Content-Transfer-Encoding: BINARY" << "\r\n";
  cbf_file << "X-Binary-Size:" << nbytes << "\r\n";
  cbf_file << "X-Binary-ID: 1" << "\r\n";
  cbf_file << "X-Binary-Element-Type: \"signed 32-bit integer\"" << "\r\n";
  cbf_file << "X-Binary-Element-Byte-Order: LITTLE_ENDIAN" << "\r\n";
  cbf_file << "X-Binary-Number-of-Elements: " << nx*ny << "\r\n";
  cbf_file << "X-Binary-Size-Fastest-Dimension: " << nx << "\r\n";
  cbf_file << "X-Binary-Size-Second-Dimension: " << ny << "\r\n";
  cbf_file << "X-Binary-Size-Padding: " << IOBUFSIZ-1 << "\r\n";
  cbf_file << "" << "\r\n";
  cbf_file << MARKBYTE[0] << MARKBYTE[1] << MARKBYTE[2] << MARKBYTE[3];


  // determine endianness
  int step, first2, last2, first4, last4;
  union
  {
    uint32_t ii;
    char cc[4];
  }
  bint = {0x01020304};
  if (bint.cc[0] == 1)
  {
    // big endian
    step = -1;
    first2=1; last2=0;
    first4=3; last4=0;
  }
  else
  {
    // little endian
    step = 1;
    first2=0; last2=1;
    first4=0; last4=3;
  }

  /** write histogram data
   * compress image using the byte offset method and save as octet stream
   */
  pixvalue = 0;

  signed char onebyte[1];
  signed char twobytes[2];
  signed char fourbytes[4];
  int shortint;

  for (int iadr=0; iadr<nx*ny; ++iadr)
  {
    diff = ((int) data[iadr]) - pixvalue;
    absdiff = abs(diff);
    pixvalue = (int)data[iadr];

    onebyte[0] = -128;
    if (absdiff < 128)
      onebyte[0] = diff;
    cbf_file << onebyte[0];
    if (absdiff < 128)
      continue;

    shortint = -32768;
    if (absdiff < 32768)
      shortint = diff;
    *((char*)(&twobytes)+0) = *((char*)(&shortint)+0);
    *((char*)(&twobytes)+1) = *((char*)(&shortint)+1);

    for (int ii=first2; ii!=last2+step; ii+=step)
      cbf_file << twobytes[ii];
    if (absdiff < 32768)
      continue;

    *((char*)(&fourbytes)+0) = *((char*)(&diff)+0);
    *((char*)(&fourbytes)+1) = *((char*)(&diff)+1);
    *((char*)(&fourbytes)+2) = *((char*)(&diff)+2);
    *((char*)(&fourbytes)+3) = *((char*)(&diff)+3);

    for (int ii=first4; ii!=last4+step; ii+=step)
      cbf_file << fourbytes[ii];
  }

  /** terminate image data part and pad last record of file with zeros:*/
  cbf_file << "--CIF-BINARY-FORMAT-SECTION----";
  cbf_file << ";";

  char zerobyte;
  zerobyte = 0;
  for (int ii=0; ii<IOBUFSIZ; ++ii)
    cbf_file << zerobyte;

  cbf_file.close();
}
Exemple #20
0
Point Gerade::Schnitt(Gerade &G)
{
  //neuer Ansatz
	  Matrix An(2,2,Null);
	  Matrix xn;
	  Matrix bn(2,1,Null);
      
	  Point G1O;
	  G1O=(*this).get_O(); //Ortsvektor
	  Point G1R;
	  G1R=(*this).get_R(); //Richtungsvektor
	  Point G2O;
	  G2O=G.get_O(); //Ortsvektor
	  Point G2R;
	  G2R=G.get_R(); //Richtungsvektor
	  
	  double x1n= G1R.get_X()*G1R.get_X()+G1R.get_Y()*G1R.get_Y()+G1R.get_Z()*G1R.get_Z();
	  double x2n=-G1R.get_X()*G2R.get_X()-G1R.get_Y()*G2R.get_Y()-G1R.get_Z()*G2R.get_Z();
	  double x3n= G1R.get_X()*G2R.get_X()+G1R.get_Y()*G2R.get_Y()+G1R.get_Z()*G2R.get_Z();
	  double x4n=-G2R.get_X()*G2R.get_X()-G2R.get_Y()*G2R.get_Y()-G2R.get_Z()*G2R.get_Z();

	  An(0,0)=x1n;
	  An(0,1)=x2n;

	  An(1,0)=x3n;
	  An(1,1)=x4n;

	  double b1n=-G1O.get_X()*G1R.get_X()+G2O.get_X()*G1R.get_X()
		         -G1O.get_Y()*G1R.get_Y()+G2O.get_Y()*G1R.get_Y()
				 -G1O.get_Z()*G1R.get_Z()+G2O.get_Z()*G1R.get_Z();

	  double b2n=-G1O.get_X()*G2R.get_X()+G2O.get_X()*G2R.get_X()
		         -G1O.get_Y()*G2R.get_Y()+G2O.get_Y()*G2R.get_Y()
				 -G1O.get_Z()*G2R.get_Z()+G2O.get_Z()*G2R.get_Z();
  
	  bn(0,0)=b1n;
	  bn(1,0)=b2n;

	  xn=An.MatInvert().MatMult( bn );
 
	  Point Sn,S1n,S2n;
	  S1n = (*this).get_O().Add( (*this).get_R().MultS(  xn(0,0) ) );
      S2n =       G.get_O().Add(       G.get_R().MultS(  xn(1,0) ) );

	  Sn.set_X( (S1n.get_X()+S2n.get_X())/2.0);
	  Sn.set_Y( (S1n.get_Y()+S2n.get_Y())/2.0);
	  Sn.set_Z( (S1n.get_Z()+S2n.get_Z())/2.0);

	  Sn.set_dX( (S1n.get_X()-S2n.get_X())/2.0);
	  Sn.set_dY( (S1n.get_Y()-S2n.get_Y())/2.0);
	  Sn.set_dZ( (S1n.get_Z()-S2n.get_Z())/2.0);
	  
  //Gleichnugssystem Ax=b
	  Matrix A(2,2,Null);
	  Matrix x;
	  Matrix b(2,1,Null);
   /*
	  Point G1O;
	  G1O=(*this).getO(); //Ortsvektor
	  Point G1R;
	  G1R=(*this).getR(); //Richtungsvektor
	  Point G2O;
	  G2O=G.getO(); //Ortsvektor
	  Point G2R;
	  G2R=G.getR(); //Richtungsvektor
*/
	  double x1=G1R.get_X();
	  double x2=(-1)*G2R.get_X();
	  double x3=G1R.get_Y();
	  double x4=(-1)*G2R.get_Y();

	  A(0,0)=x1;
	  A(0,1)=x2;

	  A(1,0)=x3;
	  A(1,1)=x4;

	  double b1=G2O.get_X()-G1O.get_X();
	  double b2=G2O.get_Y()-G1O.get_Y();
  
	  b(0,0)=b1;
	  b(1,0)=b2;

	  x=A.MatInvert().MatMult( b );
 
	  Point S,S1,S2;
	  S1 = (*this).get_O().Add( (*this).get_R().MultS(  x(0,0) ) );
      S2 =       G.get_O().Add(       G.get_R().MultS(  x(1,0) ) );

	  S.set_X( (S1.get_X()+S2.get_X())/2.0);
	  S.set_Y( (S1.get_Y()+S2.get_Y())/2.0);
	  S.set_Z( (S1.get_Z()+S2.get_Z())/2.0);

	  S.set_dX( (S1.get_X()-S2.get_X())/2.0);
	  S.set_dY( (S1.get_Y()-S2.get_Y())/2.0);
	  S.set_dZ( (S1.get_Z()-S2.get_Z())/2.0);

 return Sn;
}
Exemple #21
0
  void
  BoolExpr::NNF::rel(Home home, IntConLevel icl) const {
    switch (t) {
    case NT_VAR:
      Gecode::rel(home, u.a.x->x, IRT_EQ, u.a.neg ? 0 : 1);
      break;
    case NT_RLIN:
      u.a.x->rl.post(home, !u.a.neg, icl);
      break;
#ifdef GECODE_HAS_SET_VARS
    case NT_RSET:
      u.a.x->rs.post(home, !u.a.neg);
      break;
#endif
    case NT_MISC:
      {
        BoolVar b(home,!u.a.neg,!u.a.neg);
        u.a.x->m->post(home, b, false, icl);
      }
      break;
    case NT_AND:
      u.b.l->rel(home, icl);
      u.b.r->rel(home, icl);
      break;
    case NT_OR:
      {
        BoolVarArgs bp(p), bn(n);
        int ip=0, in=0;
        post(home, NT_OR, bp, bn, ip, in, icl);
        clause(home, BOT_OR, bp, bn, 1);
      }
      break;
    case NT_EQV:
      if (u.b.l->t==NT_VAR && u.b.r->t==NT_RLIN) {
        u.b.r->u.a.x->rl.post(home, u.b.l->u.a.x->x,
                              u.b.l->u.a.neg==u.b.r->u.a.neg, icl);
      } else if (u.b.r->t==NT_VAR && u.b.l->t==NT_RLIN) {
        u.b.l->u.a.x->rl.post(home, u.b.r->u.a.x->x,
                              u.b.l->u.a.neg==u.b.r->u.a.neg, icl);
      } else if (u.b.l->t==NT_RLIN) {
        u.b.l->u.a.x->rl.post(home, u.b.r->expr(home,icl),
                              !u.b.l->u.a.neg,icl);
      } else if (u.b.r->t==NT_RLIN) {
        u.b.r->u.a.x->rl.post(home, u.b.l->expr(home,icl),
                              !u.b.r->u.a.neg,icl);
#ifdef GECODE_HAS_SET_VARS
      } else if (u.b.l->t==NT_VAR && u.b.r->t==NT_RSET) {
        u.b.r->u.a.x->rs.post(home, u.b.l->u.a.x->x,
                              u.b.l->u.a.neg==u.b.r->u.a.neg);
      } else if (u.b.r->t==NT_VAR && u.b.l->t==NT_RSET) {
        u.b.l->u.a.x->rs.post(home, u.b.r->u.a.x->x,
                              u.b.l->u.a.neg==u.b.r->u.a.neg);
      } else if (u.b.l->t==NT_RSET) {
        u.b.l->u.a.x->rs.post(home, u.b.r->expr(home,icl),
                              !u.b.l->u.a.neg);
      } else if (u.b.r->t==NT_RSET) {
        u.b.r->u.a.x->rs.post(home, u.b.l->expr(home,icl),
                              !u.b.r->u.a.neg);
#endif
      } else {
        Gecode::rel(home, expr(home, icl), IRT_EQ, 1);
      }
      break;
    default:
      GECODE_NEVER;
    }
  }
Exemple #22
0
template<typename PointInT> pcl::nurbs::NurbsSurface
pcl::nurbs::NurbsFitter<PointInT>::grow (float max_dist, float max_angle, unsigned min_length, unsigned max_length)
{
  unsigned num_bnd = this->nurbs_data_.boundary_param.size ();

  if (num_bnd == 0)
    throw std::runtime_error ("[NurbsFitter::grow] No boundary given.");

  if ((unsigned)this->nurbs_data_.boundary.size () != num_bnd)
  {
    printf ("[NurbsFitter::grow] %u %u\n", (unsigned)this->nurbs_data_.boundary.size (), num_bnd);
    throw std::runtime_error ("[NurbsFitter::grow] size of boundary and boundary parameters do not match.");
  }

  if (this->boundary_indices_->indices.size () != num_bnd)
  {
    printf ("[NurbsFitter::grow] %u %u\n", (unsigned)this->boundary_indices_->indices.size (), num_bnd);
    throw std::runtime_error ("[NurbsFitter::grow] size of boundary indices and boundary parameters do not match.");
  }

  float angle = cos (max_angle);
  unsigned bnd_moved (0);

  for (unsigned i = 0; i < num_bnd; i++)
  {
    vec3 r (0.0, 0.0, 0.0), tu (0.0, 0.0, 0.0), tv (0.0, 0.0, 0.0), n (0.0, 0.0, 0.0), bn (0.0, 0.0, 0.0);
    double u = this->nurbs_data_.boundary_param[i] (0);
    double v = this->nurbs_data_.boundary_param[i] (1);

    // Evaluate point and tangents
    nurbs_surface_.evaluate (u, v, r, tu, tv);

    n = tu.cross (tv);
    n.normalize ();

    // calculate boundary normal (pointing outward)
    double eps = 0.00000001;

    if (u < eps)
      bn = n.cross (tv);
    if (u > 1.0 - eps)
      bn = -n.cross (tv);
    if (v < eps)
      bn = -n.cross (tu);
    if (v > 1.0 - eps)
      bn = n.cross (tu);

    bn.normalize ();

    Eigen::Vector3d e (r (0) + bn (0) * max_dist, r (1) + bn (1) * max_dist, r (2) + bn (2) * max_dist);

    // Project into image plane
    Eigen::Vector2d ri = this->project (r);
    Eigen::Vector2d ei = this->project (e);
    Eigen::Vector2d bni = ei - ri;
    bni.normalize ();

    // search for valid points along boundary normal in image space
    float max_dist_sq = max_dist * max_dist;
    bool valid = false;
    PointInT point = cloud_->at (this->boundary_indices_->indices[i]);
    for (unsigned j = min_length; j < max_length; j++)
    {
      int col = static_cast<int> (ri (0) + bni (0) * j);
      int row = static_cast<int> (ri (1) + bni (1) * j);

      if (row >= int (cloud_->height) || row < 0)
      {
        j = max_length;
        break;
      }
      if (col >= int (cloud_->width) || col < 0)
      {
        j = max_length;
        break;
      }

      unsigned idx = row * cloud_->width + col;

      const PointInT &pt = cloud_->at (idx);
      if (!pcl_isnan (pt.x) && !pcl_isnan (pt.y) && !pcl_isnan (pt.z))
      {

        // distance requirement
        Eigen::Vector3d d (pt.x - r (0), pt.y - r (1), pt.z - r (2));
        if (d.dot (d) < max_dist_sq)
        {
          d.normalize ();
          if (std::abs (d.dot (bn)) > (angle))
          {
            valid = true;
            point = pt;
          } // dot
        } // max_dist
      } // isnan
    } // j

      // if valid point found, add current boundary point to interior points and move boundary
    if (valid)
    {
      this->nurbs_data_.interior.push_back (this->nurbs_data_.boundary[i]);
      this->nurbs_data_.boundary[i] (0) = point.x;
      this->nurbs_data_.boundary[i] (1) = point.y;
      this->nurbs_data_.boundary[i] (2) = point.z;
      ++bnd_moved;
    }

  } // i

  computeInterior (nurbs_surface_);

  double int_err (0.0);
  double div_err = 1.0 / nurbs_data_.interior_error.size ();
  for (unsigned i = 0; i < nurbs_data_.interior_error.size (); i++)
  {
    int_err += (nurbs_data_.interior_error[i] * div_err);
  }

  printf ("[NurbsFitter::grow] average interior error: %e\n", int_err);

  return (nurbs_surface_);
}
Exemple #23
0
	static BigNumber zeroWithLength(int n) {
		BigNumber bn(n);
		return n;
	}
Exemple #24
0
Vector Helice::b(float u) const                     //Vector binormal unitario en u
{
	Vector a(-sin(u*dPI),0.0,-cos(u*dPI));
	Vector bn(glm::cross(t(u),a));
	return glm::normalize(bn);
}
Exemple #25
0
  BoolVar
  BoolExpr::NNF::expr(Home home, IntConLevel icl) const {
    if ((t == NT_VAR) && !u.a.neg)
      return u.a.x->x;
    BoolVar b(home,0,1);
    switch (t) {
    case NT_VAR:
      assert(u.a.neg);
      Gecode::rel(home, u.a.x->x, IRT_NQ, b);
      break;
    case NT_RLIN:
      u.a.x->rl.post(home, b, !u.a.neg, icl);
      break;
#ifdef GECODE_HAS_SET_VARS
    case NT_RSET:
      u.a.x->rs.post(home, b, !u.a.neg);
      break;
#endif
    case NT_MISC:
      u.a.x->m->post(home, b, !u.a.neg, icl);
      break;
    case NT_AND:
      {
        BoolVarArgs bp(p), bn(n);
        int ip=0, in=0;
        post(home, NT_AND, bp, bn, ip, in, icl);
        clause(home, BOT_AND, bp, bn, b);
      }
      break;
    case NT_OR:
      {
        BoolVarArgs bp(p), bn(n);
        int ip=0, in=0;
        post(home, NT_OR, bp, bn, ip, in, icl);
        clause(home, BOT_OR, bp, bn, b);
      }
      break;
    case NT_EQV:
      {
        bool n = false;
        BoolVar l;
        if (u.b.l->t == NT_VAR) {
          l = u.b.l->u.a.x->x;
          if (u.b.l->u.a.neg) n = !n;
        } else {
          l = u.b.l->expr(home,icl);
        }
        BoolVar r;
        if (u.b.r->t == NT_VAR) {
          r = u.b.r->u.a.x->x;
          if (u.b.r->u.a.neg) n = !n;
        } else {
          r = u.b.r->expr(home,icl);
        }
        Gecode::rel(home, l, n ? BOT_XOR : BOT_EQV, r, b, icl);
      }
      break;
    default:
      GECODE_NEVER;
    }
    return b;
  }