Exemplo n.º 1
0
void gc(char b[]) {
  fc(b);
}
Exemplo n.º 2
0
    spark_pair_t create(spark_t effectType,osg::Transform* model)
    {
        static int count = 0; 
        osg::ref_ptr<SparkDrawable> spark = new SparkDrawable;
		osg::ref_ptr<osg::Geode>    geode = nullptr;

        // bool trackingModel = false;
        fire_creator fc(2.0);
        switch ( effectType )
        {
        case EXPLOSION:  // Explosion
            spark->setBaseSystemCreator( &createExplosion );
            spark->addParticleSystem();
            spark->setSortParticles( true );
            spark->addImage( "explosion", osgDB::readImageFile("data/explosion.bmp"), GL_ALPHA );
            spark->addImage( "flash"    , osgDB::readImageFile("data/flash.bmp")    , GL_RGB   );
            spark->addImage( "spark1"   , osgDB::readImageFile("data/spark1.bmp")   , GL_RGB   );
            spark->addImage( "spark2"   , osgDB::readImageFile("data/point.bmp")    , GL_ALPHA );
            spark->addImage( "wave"     , osgDB::readImageFile("data/wave.bmp")     , GL_RGBA  );
			geode = new osg::Geode;
            geode->setName("fxExplosion");
            break;
        case FIRE:  // Fire
            spark->setBaseSystemCreator( &fc.createFireSmoke );
            spark->addParticleSystem();
            spark->addImage( "fire"     , osgDB::readImageFile("data/fire2.bmp")    , GL_ALPHA );
            spark->addImage( "explosion", osgDB::readImageFile("data/explosion.bmp"), GL_ALPHA );
            spark->addImage( "smoke"    , osgDB::readImageFile("data/smoke_black.png"), GL_RGBA );
            geode = new SmokeNode;
            dynamic_cast<SmokeNode*>(geode.get())->setGravity(osg::Vec3f(1.0,1.0,0.05));
            geode->setName("fxFire");
            break;
        case RAIN:  // Rain
            spark->setBaseSystemCreator( &createRain, true );  // Must use the proto type directly
            spark->addImage( "waterdrops", osgDB::readImageFile("data/waterdrops.bmp"), GL_ALPHA );
			geode = new osg::Geode;
            geode->setName("fxRain");
            break;
        case SMOKE:  // Smoke
            spark->setBaseSystemCreator( &createSmoke );
            spark->addParticleSystem();
            spark->addImage( "smoke", osgDB::readImageFile("data/smoke_black.png"), GL_RGBA );
            //spark->addImage( "smoke", osgDB::readImageFile("data/fire2.bmp"), GL_RGBA );
			geode = new SmokeNode;
			dynamic_cast<SmokeNode*>(geode.get())->setGravity(osg::Vec3f(1.0,1.0,0.05));
            geode->setName("fxSmoke");
            ///trackingModel = true;
            break;
        case TEST:
            spark->setBaseSystemCreator( &createTest );
            spark->addParticleSystem();
			geode = new osg::Geode;
            geode->setName("fxTest");
            break;
        case SOMETHING:
            spark->setBaseSystemCreator( &createSomething);  // Must use the proto type directly
            spark->addImage( "waterdrops", osgDB::readImageFile("data/waterdrops.bmp"), GL_ALPHA );
            geode = new osg::Geode;
            geode->setName("fxRain");
            
            break;
        default:  // Simple
            spark->setBaseSystemCreator( &createSimpleSystem );
            spark->addParticleSystem();
            spark->addImage( "flare", osgDB::readImageFile("data/flare.bmp"), GL_ALPHA );
			geode = new osg::Geode;
            geode->setName("fxFlare");
            break;
        }

        geode->addDrawable( spark.get() );
        geode->getOrCreateStateSet()->setRenderingHint( osg::StateSet::TRANSPARENT_BIN );
        geode->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
		geode->getOrCreateStateSet()->setNestRenderBins(false);

        static osg::ref_ptr<SparkUpdatingHandler> handler = new SparkUpdatingHandler;
        handler->addSpark( spark.get() );
        
        if ( /*trackingModel*/model != nullptr )
        {
            handler->setTrackee( count, model );
        }
        
        count++;

        return spark_pair_t(geode.release(),handler.get());
    }
Exemplo n.º 3
0
size_t SimdFunctionArg::elements(void) const {
	SimdFunctionCallPtr fc(func());

	return fc->xContext()->interpreter().maxSamples();
}
void Foam::meshRefinement::findNearest
(
    const labelList& meshFaces,
    List<pointIndexHit>& nearestInfo,
    labelList& nearestSurface,
    labelList& nearestRegion,
    vectorField& nearestNormal
) const
{
    pointField fc(meshFaces.size());
    forAll(meshFaces, i)
    {
        fc[i] = mesh_.faceCentres()[meshFaces[i]];
    }

    const labelList allSurfaces(identity(surfaces_.surfaces().size()));

    surfaces_.findNearest
    (
        allSurfaces,
        fc,
        scalarField(fc.size(), sqr(GREAT)),    // sqr of attraction
        nearestSurface,
        nearestInfo
    );

    // Do normal testing per surface.
    nearestNormal.setSize(nearestInfo.size());
    nearestRegion.setSize(nearestInfo.size());

    forAll(allSurfaces, surfI)
    {
        DynamicList<pointIndexHit> localHits;

        forAll(nearestSurface, i)
        {
            if (nearestSurface[i] == surfI)
            {
                localHits.append(nearestInfo[i]);
            }
        }

        label geomI = surfaces_.surfaces()[surfI];

        pointField localNormals;
        surfaces_.geometry()[geomI].getNormal(localHits, localNormals);

        labelList localRegion;
        surfaces_.geometry()[geomI].getRegion(localHits, localRegion);

        label localI = 0;
        forAll(nearestSurface, i)
        {
            if (nearestSurface[i] == surfI)
            {
                nearestNormal[i] = localNormals[localI];
                nearestRegion[i] = localRegion[localI];
                localI++;
            }
        }
    }
FlyweightCharacter FlyweightCharacterAbstractBuilder::createFlyweightCharacter(
        unsigned short fontSizeIndex, unsigned short fontNameIndex, unsigned short positionInStream){
    FlyweightCharacter fc(fontSizeIndex, fontNameIndex, positionInStream);
    return fc;
}
Exemplo n.º 6
0
static void test_mg_stat(void) {
  static struct mg_context ctx;
  struct file file = STRUCT_FILE_INITIALIZER;
  ASSERT(!mg_stat(fc(&ctx), " does not exist ", &file));
}
Exemplo n.º 7
0
/**
 * Computes the solver string for a given cube.
 *
 * @param facelets
 *          is the cube definition string, see {@link Facelet} for the format.
 *
 * @param maxDepth
 *          defines the maximal allowed maneuver length. For random cubes, a maxDepth of 21 usually will return a
 *          solution in less than 0.5 seconds. With a maxDepth of 20 it takes a few seconds on average to find a
 *          solution, but it may take much longer for specific cubes.
 *
 *@param timeOut
 *          defines the maximum computing time of the method in seconds. If it does not return with a solution, it returns with
 *          an error code.
 *
 * @param useSeparator
 *          determines if a " . " separates the phase1 and phase2 parts of the solver string like in F' R B R L2 F .
 *          U2 U D for example.<br>
 * @return The solution string or an error code:<br>
 *         Error 1: There is not exactly one facelet of each colour<br>
 *         Error 2: Not all 12 edges exist exactly once<br>
 *         Error 3: Flip error: One edge has to be flipped<br>
 *         Error 4: Not all corners exist exactly once<br>
 *         Error 5: Twist error: One corner has to be twisted<br>
 *         Error 6: Parity error: Two corners or two edges have to be exchanged<br>
 *         Error 7: No solution exists for the given maxDepth<br>
 *         Error 8: Timeout, no solution within given time
 */
std::string Search::solution(std::string facelets, int maxDepth, long timeOut, bool useSeparator) {
    int s;

    // +++++++++++++++++++++check for wrong input +++++++++++++++++++++++++++++
    int count[6];
    for (int i = 0; i < 6; ++i)
        count[i] = 0;
    try {
        for (int i = 0; i < 54; i++)
            ++count[FaceCube::charToColor(facelets[i])];
    } catch (...) {
        return "Error 1";
    }
    for (int i = 0; i < 6; i++)
        if (count[i] != 9)
            return "Error 1";

    FaceCube fc(facelets);
    CubieCube cc(fc.toCubieCube());
    if ((s = cc.verify()) != 0) {
        char e[40];
        sprintf(e, "Error %d", abs(s));
        return e;
    }

    // +++++++++++++++++++++++ initialization +++++++++++++++++++++++++++++++++
    CoordCube c(cc);

    po[0] = 0;
    ax[0] = 0;
    flip[0] = c.flip;
    twist[0] = c.twist;
    parity[0] = c.parity;
    slice[0] = c.FRtoBR / 24;
    URFtoDLF[0] = c.URFtoDLF;
    FRtoBR[0] = c.FRtoBR;
    URtoUL[0] = c.URtoUL;
    UBtoDF[0] = c.UBtoDF;

    minDistPhase1[1] = 1;// else failure for depth=1, n=0
    int mv = 1, n = 0;
    bool busy = false; // gets set when a move is popped from the stack
    int depthPhase1 = 1;

    clock_t tStart = clock();
    timeOut *= CLOCKS_PER_SEC;

    // +++++++++++++++++++ Main loop ++++++++++++++++++++++++++++++++++++++++++
    do {
        /* Find the next node to test
         * This is an Iterative Deepening A* search (IDA*)
         * which means we are doing a depth first search over and over again
         * with increasing depth limit while pruning branches which would
         * give too many total moves.
         *
         * n is current depth
         * depthPhase1 is current max depth
         * minDistPhase1[n + 1] is the pruning value which gives a lower bound
         * on the moves necessary after the current move
         *
         * the sequence of moves are stored as ax[] and po[] which together represents each move.
         * ax[n] is the axis, 0 to 2
         * po[n] is the power, 1 to 15 (which combination of moves on the axis)
         */
        do { // loop for choice of node while busy
            if ((n + minDistPhase1[n + 1] < depthPhase1) && !busy) {
                // Dig deeper
                // Initialize next move, avoid previous axis
                if (ax[n] != 0)
                    ax[++n] = 0;
                else
                    ax[++n] = 1;
                po[n] = 1;
            } else if (++po[n] > 15) { // increment power
                do {// increment axis
                    if (++ax[n] > 2) {

                        if (clock() - tStart > timeOut)
                            return "Error 8";

                        if (n == 0) {
                            if (depthPhase1 >= maxDepth)
                                return "Error 7";
                            else {
                                // Start over with greater depth
                                depthPhase1++;
                                ax[n] = 0;
                                po[n] = 1;
                                busy = false;
                                break;
                            }
                        } else {
                            // Decrease current depth
                            n--;
                            busy = true;
                            break;
                        }

                    } else {
                        po[n] = 1;
                        busy = false;
                    }
                } while (n != 0 && (ax[n - 1] == ax[n]));
            } else
                busy = false;
        } while (busy);

        // +++++++++++++ compute new coordinates and new minDistPhase1 ++++++++++
        // if minDistPhase1 =0, the H subgroup is reached
        mv = 16 * ax[n] + po[n];
        if (mv > CoordCube::N_MOVE)
            printf("n: %d ax[n]: %d po[n]: %d mv: %d ", n, ax[n], po[n], mv);
        flip[n + 1] = CoordCube::flipMove[flip[n]][mv];
        twist[n + 1] = CoordCube::twistMove[twist[n]][mv];
        slice[n + 1] = CoordCube::FRtoBR_Move[slice[n] * 24][mv] / 24;
        minDistPhase1[n + 1] = std::max(CoordCube::getPruning(CoordCube::Slice_Flip_Prun, CoordCube::N_SLICE1 * flip[n + 1]
                + slice[n + 1]), CoordCube::getPruning(CoordCube::Slice_Twist_Prun, CoordCube::N_SLICE1 * twist[n + 1]
                + slice[n + 1]));
        // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

        if (minDistPhase1[n + 1] == 0 && n >= depthPhase1 - 5) {
            minDistPhase1[n + 1] = 10;// instead of 10 any value >5 is possible
            if (n == depthPhase1 - 1 && (s = totalDepth(depthPhase1, maxDepth)) >= 0) {
                if (s == depthPhase1
                        || (ax[depthPhase1 - 1] != ax[depthPhase1] && ax[depthPhase1 - 1] != ax[depthPhase1] + 3))
                    return useSeparator ? solutionToString(s, depthPhase1) : solutionToString(s);
            }

        }
    } while (true);
}
Exemplo n.º 8
0
const Result CtrlrWindows::exportWithDefaultPanel(CtrlrPanel*  panelToWrite, const bool isRestricted, const bool signPanel, RSAKey privateKey)
{
	if (panelToWrite == nullptr)
	{
		return (Result::fail("Windows Native: exportWithDefaultPanel got nullptr for panel"));
	}

	File	me = File::getSpecialLocation(File::currentExecutableFile);
	File	newMe;
	HANDLE	hResource;
	MemoryBlock panelExportData,panelResourcesData;
	MemoryBlock iconData(BinaryData::ico_midi_png, BinaryData::ico_midi_pngSize);

	FileChooser fc(CTRLR_NEW_INSTANCE_DIALOG_TITLE,
					me.getParentDirectory().getChildFile(File::createLegalFileName(panelToWrite->getProperty(Ids::name))).withFileExtension(me.getFileExtension()),
					"*"+me.getFileExtension(),
					panelToWrite->getOwner().getProperty(Ids::ctrlrNativeFileDialogs));

	if (fc.browseForFileToSave(true))
	{
		newMe = fc.getResult();

		if (!newMe.hasFileExtension(me.getFileExtension()))
		{
			newMe = newMe.withFileExtension(me.getFileExtension());
		}

		if (!me.copyFileTo (newMe))
		{
			return (Result::fail("Windows Native: exportMeWithNewResource can't copy \""+me.getFullPathName()+"\" to \""+newMe.getFullPathName()+"\""));
		}
	}
	else
	{
		return (Result::fail("Windows Native: exportMeWithNewResource \"Save file\" dialog failed"));
	}

	hResource = BeginUpdateResource(newMe.getFullPathName().toUTF8(), FALSE);

	if (hResource)
	{
		String error;

		if ( (error = CtrlrPanel::exportPanel (panelToWrite, File::nonexistent, newMe, &panelExportData, &panelResourcesData, isRestricted)) == String::empty)
		{
			if (	writeResource (hResource, MAKEINTRESOURCE(CTRLR_INTERNAL_PANEL_RESID), RT_RCDATA, panelExportData)
				&&	writeResource (hResource, MAKEINTRESOURCE(CTRLR_INTERNAL_RESOURCES_RESID), RT_RCDATA, panelResourcesData)
				)
			{
				EndUpdateResource(hResource, FALSE);
			}
			else
			{
				return (Result::fail("Windows Native: exportMeWithNewResource writeResource[panel] failed"));
			}

			if (isRestricted && privateKey != RSAKey())
			{
				/* Sign the panel */
				MemoryBlock signature = signData (panelResourcesData, privateKey);
			}
		}
		else
		{
			return (Result::fail("Windows Native: exportMeWithNewResource exportPanel error: \""+error+"\""));
		}

		return (Result::ok());
	}

	return (Result::fail("Windows Native: exportMeWithNewResource BeginUpdateResource failed"));
}
Exemplo n.º 9
0
bool UIComponent::perform(const InvocationInfo& info)
{

    switch (info.commandID)
    {
        case openConfiguration:
            {
                FileChooser fc("Choose a file to load...",
                               File::getCurrentWorkingDirectory(),
                               "*",
                               true);

                if (fc.browseForFileToOpen())
                {
                    currentConfigFile = fc.getResult();
                    sendActionMessage(getEditorViewport()->loadState(currentConfigFile));
                }
                else
                {
                    sendActionMessage("No configuration selected.");
                }

                break;
            }
        case saveConfiguration:
            {

                if (currentConfigFile.exists())
                {
                    sendActionMessage(getEditorViewport()->saveState(currentConfigFile));
                } else {
                    FileChooser fc("Choose the file name...",
                                   File::getCurrentWorkingDirectory(),
                                   "*",
                                   true);

                    if (fc.browseForFileToSave(true))
                    {
                        currentConfigFile = fc.getResult();
                        std::cout << currentConfigFile.getFileName() << std::endl;
                        sendActionMessage(getEditorViewport()->saveState(currentConfigFile));
                    }
                    else
                    {
                        sendActionMessage("No file chosen.");
                    }
                }

                break;
            }

        case saveConfigurationAs:
            {

                FileChooser fc("Choose the file name...",
                               File::getCurrentWorkingDirectory(),
                               "*",
                               true);

                if (fc.browseForFileToSave(true))
                {
                    currentConfigFile = fc.getResult();
                    std::cout << currentConfigFile.getFileName() << std::endl;
                    sendActionMessage(getEditorViewport()->saveState(currentConfigFile));
                }
                else
                {
                    sendActionMessage("No file chosen.");
                }

                break;
            }

        case reloadOnStartup:
            {
                mainWindow->shouldReloadOnStartup = !mainWindow->shouldReloadOnStartup;

            }
            break;

        case clearSignalChain:
        {
            getEditorViewport()->clearSignalChain();
            break;
        }

        case showHelp:
        {
            URL url = URL("https://open-ephys.atlassian.net/wiki/display/OEW/Open+Ephys+GUI");
            url.launchInDefaultBrowser();
            break;
        }

        case toggleProcessorList:
            processorList->toggleState();
            break;

        case toggleFileInfo:
            controlPanel->toggleState();
            break;

        case toggleSignalChain:
            editorViewportButton->toggleState();
            break;
            
        case resizeWindow:
            mainWindow->centreWithSize(800, 600);
            break;

        default:
            break;

    }

    return true;

}
Exemplo n.º 10
0
RcppExport SEXP benchmarkEvals(SEXP bmS, SEXP parS, SEXP funS, SEXP envS) {

    Rcpp::List bm(bmS);
    int nsim = Rcpp::as<int>(bm["nsim"]);

    long neval = 0;
    Rcpp::NumericVector x(parS);

    Timer t;
    double v1 = 0, v2 = 0, v3 = 0, v4 = 0, v5 = 0, v6 = 0;
    t.Start();
    for (int i=0; i<nsim; i++)
        v1 = evaluate1(&neval, x.begin(), x.size(), funS, envS);
    t.Stop();
    double t1 = t.ElapsedTime();

    t.Reset();
    neval = 0;
    t.Start();
    for (int i=0; i<nsim; i++)
        v2 = evaluate2(&neval, x.begin(), x.size(), funS, envS);
    t.Stop();
    double t2 = t.ElapsedTime();

    Rcpp::Function fun(funS);
    Rcpp::Environment env(envS);

    t.Reset();
    neval = 0;
    t.Start();
    for (int i=0; i<nsim; i++)
        v3 = evaluate3(&neval, x.begin(), x.size(), fun, env);
    t.Stop();
    double t3 = t.ElapsedTime();

    t.Reset();
    neval = 0;
    t.Start();
    for (int i=0; i<nsim; i++)
        v4 = evaluate4(&neval, x.begin(), x.size(), fun, env);
    t.Stop();
    double t4 = t.ElapsedTime();

    t.Reset();
    neval = 0;
    t.Start();
    for (int i=0; i<nsim; i++)
        v5 = evaluate5(neval, x, fun, env);
    t.Stop();
    double t5 = t.ElapsedTime();

    t.Reset();
    neval = 0;
    Rcpp::Function fc(fun);
    Rcpp::Environment en(env);
    t.Start();
    for (int i=0; i<nsim; i++)
        v6 = evaluate6(neval, x, fc, en);
    t.Stop();
    double t6 = t.ElapsedTime();

    return Rcpp::DataFrame::create(Rcpp::Named("times", Rcpp::NumericVector::create(t1, t2, t3, t4, t5, t6)),
                                   Rcpp::Named("values", Rcpp::NumericVector::create(v1, v2, v3, v4, v5, v6)));

}
Exemplo n.º 11
0
void DrawNode::drawPolygon(const Vec2* verts, int count, const Color4F& fillColor, float borderWidth, const Color4F& borderColor)
{
    CCASSERT(count >= 0, "invalid count value");
    
    Color4B fc(fillColor);
    Color4B bc(borderColor);
    
    bool outline = (borderColor.a > 0.0 && borderWidth > 0.0);
    
    for (int i = 0; i < count-2; ++i)
    {
        _vdTriangles->append<V2F_C4B_T2F>({verts[0],   fc, Tex2F()});
        _vdTriangles->append<V2F_C4B_T2F>({verts[i+1], fc, Tex2F()});
        _vdTriangles->append<V2F_C4B_T2F>({verts[i+2], fc, Tex2F()});
    }
    
    if (outline)
    {
        struct ExtrudeVerts {Vec2 offset, n;};
        auto extrude = (struct ExtrudeVerts*)CC_ALLOCA(sizeof(struct ExtrudeVerts)*count);
        memset(extrude, 0, sizeof(struct ExtrudeVerts)*count);
        
        for (auto i = 0; i < count; ++i)
        {
            Vec2 v0 = verts[(i-1+count)%count];
            Vec2 v1 = verts[i];
            Vec2 v2 = verts[(i+1)%count];
            
            Vec2 n1 = (v1 - v0).getPerp().getNormalized();
            Vec2 n2 = (v2 - v1).getPerp().getNormalized();
            
            Vec2 offset = (n1 + n2) * (1.f / (Vec2::dot(n1, n2) + 1.f));
            extrude[i] = {offset, n2};
        }
        
        for (auto i = 0; i < count; ++i)
        {
            int j = (i+1)%count;
            Vec2 v0 = verts[i];
            Vec2 v1 = verts[j];
            
            Vec2 n0 = extrude[i].n;
            
            Vec2 offset0 = extrude[i].offset;
            Vec2 offset1 = extrude[j].offset;
            
            Vec2 inner0 = v0 - offset0 * borderWidth;
            Vec2 inner1 = v1 - offset1 * borderWidth;
            Vec2 outer0 = v0 + offset0 * borderWidth;
            Vec2 outer1 = v1 + offset1 * borderWidth;
            
            _vdTriangles->append<V2F_C4B_T2F>({inner0, bc, -n0});
            _vdTriangles->append<V2F_C4B_T2F>({inner1, bc, -n0});
            _vdTriangles->append<V2F_C4B_T2F>({outer1, bc,  n0});
            
            _vdTriangles->append<V2F_C4B_T2F>({inner0, bc, -n0});
            _vdTriangles->append<V2F_C4B_T2F>({outer0, bc,  n0});
            _vdTriangles->append<V2F_C4B_T2F>({outer1, bc,  n0});
        }
    }
}
Exemplo n.º 12
0
void LocalH :: 
FindInnerBoxesRec2 (GradingBox * box,
		    class AdFront3 * adfront, 
		    ARRAY<Box3d> & faceboxes,
		    ARRAY<int> & faceinds, int nfinbox)
{
  if (!box) return;
  
  int i, j;
  
  GradingBox * father = box -> father;
  
  Point3d c(box->xmid[0], box->xmid[1], box->xmid[2]);
  Vec3d v(box->h2, box->h2, box->h2);
  Box3d boxc(c-v, c+v);

  Point3d fc(father->xmid[0], father->xmid[1], father->xmid[2]);
  Vec3d fv(father->h2, father->h2, father->h2);
  Box3d fboxc(fc-fv, fc+fv);

  Box3d boxcfc(c,fc);


  static ARRAY<int> faceused;
  static ARRAY<int> faceused2;
  static ARRAY<int> facenotused;

  faceused.SetSize(0);
  facenotused.SetSize(0);
  faceused2.SetSize(0);

  for (j = 1; j <= nfinbox; j++)
    {
      //      adfront->GetFaceBoundingBox (faceinds.Get(j), facebox);
      const Box3d & facebox = faceboxes.Get(faceinds.Get(j));
  
      if (boxc.Intersect (facebox))
	faceused.Append(faceinds.Get(j));
      else
	facenotused.Append(faceinds.Get(j));

      if (boxcfc.Intersect (facebox))
	faceused2.Append (faceinds.Get(j));
    }
  
  for (j = 1; j <= faceused.Size(); j++)
    faceinds.Elem(j) = faceused.Get(j);
  for (j = 1; j <= facenotused.Size(); j++)
    faceinds.Elem(j+faceused.Size()) = facenotused.Get(j);

  
  if (!father->flags.cutboundary)
    {
      box->flags.isinner = father->flags.isinner;
      box->flags.pinner = father->flags.pinner;
    }
  else
    {
      Point3d cf(father->xmid[0], father->xmid[1], father->xmid[2]);
      
      if (father->flags.isinner)
	box->flags.pinner = 1;
      else
	{
	  if (adfront->SameSide (c, cf, &faceused2))
	    box->flags.pinner = father->flags.pinner;
	  else
	    box->flags.pinner = 1 - father->flags.pinner;
	}
      
      if (box->flags.cutboundary)
	box->flags.isinner = 0;
      else
	box->flags.isinner = box->flags.pinner;
    }

  int nf = faceused.Size();
  for (i = 0; i < 8; i++)
    FindInnerBoxesRec2 (box->childs[i], adfront, faceboxes, faceinds, nf);
}
Exemplo n.º 13
0
void test_overload3() {

    std::cout << "\n";

    {
        A a;
        B b;
        C c;
        fc(a);
        fc(b);
        fc(c);
        fc(&a);
        fc(&b);
        fc(&c);
    }

    {
        const A a;
        const B b;
        const C c;
        fc(a);
        fc(b);
        fc(c);
        fc(&a);
        fc(&b);
        fc(&c);
    }
}
Exemplo n.º 14
0
void computeMaxDp(std::map<std::pair<int, int>, double>& maxDp,
                  const DeckConstPtr& deck,
                  EclipseStateConstPtr eclipseState,
                  const Grid& grid,
                  const BlackoilState& initialState,
                  const BlackoilPropertiesFromDeck& props,
                  const double gravity)
{

    const PhaseUsage& pu = props.phaseUsage();

    const auto& eqlnum = eclipseState->get3DProperties().getIntGridProperty("EQLNUM");
    const auto& eqlnumData = eqlnum.getData();

    const int numPhases = initialState.numPhases();
    const int numCells = UgGridHelpers::numCells(grid);
    const int numPvtRegions = deck->getKeyword("TABDIMS").getRecord(0).getItem("NTPVT").get< int >(0);

    // retrieve the minimum (residual!?) and the maximum saturations for all cells
    std::vector<double> minSat(numPhases*numCells);
    std::vector<double> maxSat(numPhases*numCells);
    std::vector<int> allCells(numCells);
    for (int cellIdx = 0; cellIdx < numCells; ++cellIdx) {
        allCells[cellIdx] = cellIdx;
    }
    props.satRange(numCells, allCells.data(), minSat.data(), maxSat.data());

    // retrieve the surface densities
    std::vector<std::vector<double> > surfaceDensity(numPvtRegions);
    const auto& densityKw = deck->getKeyword("DENSITY");
    for (int regionIdx = 0; regionIdx < numPvtRegions; ++regionIdx) {
        surfaceDensity[regionIdx].resize(numPhases);

        if (pu.phase_used[BlackoilPhases::Aqua]) {
            const int wpos = pu.phase_pos[BlackoilPhases::Aqua];
            surfaceDensity[regionIdx][wpos] =
                densityKw.getRecord(regionIdx).getItem("WATER").getSIDouble(0);
        }

        if (pu.phase_used[BlackoilPhases::Liquid]) {
            const int opos = pu.phase_pos[BlackoilPhases::Liquid];
            surfaceDensity[regionIdx][opos] =
                densityKw.getRecord(regionIdx).getItem("OIL").getSIDouble(0);
        }

        if (pu.phase_used[BlackoilPhases::Vapour]) {
            const int gpos = pu.phase_pos[BlackoilPhases::Vapour];
            surfaceDensity[regionIdx][gpos] =
                densityKw.getRecord(regionIdx).getItem("GAS").getSIDouble(0);
        }
    }

    // retrieve the PVT region of each cell. note that we need c++ instead of
    // Fortran indices.
    const int* gc = UgGridHelpers::globalCell(grid);
    std::vector<int> pvtRegion(numCells);
    const auto& cartPvtRegion = eclipseState->get3DProperties().getIntGridProperty("PVTNUM").getData();
    for (int cellIdx = 0; cellIdx < numCells; ++cellIdx) {
        const int cartCellIdx = gc ? gc[cellIdx] : cellIdx;
        pvtRegion[cellIdx] = std::max(0, cartPvtRegion[cartCellIdx] - 1);
    }

    // compute the initial "phase presence" of each cell (required to calculate
    // the inverse formation volume factors
    std::vector<PhasePresence> cond(numCells);
    for (int cellIdx = 0; cellIdx < numCells; ++cellIdx) {
        if (pu.phase_used[BlackoilPhases::Aqua]) {
            const double sw = initialState.saturation()[numPhases*cellIdx + pu.phase_pos[BlackoilPhases::Aqua]];
            if (sw > 0.0) {
                cond[cellIdx].setFreeWater();
            }
        }

        if (pu.phase_used[BlackoilPhases::Liquid]) {
            const double so = initialState.saturation()[numPhases*cellIdx + pu.phase_pos[BlackoilPhases::Liquid]];
            if (so > 0.0) {
                cond[cellIdx].setFreeOil();
            }
        }

        if (pu.phase_used[BlackoilPhases::Vapour]) {
            const double sg = initialState.saturation()[numPhases*cellIdx + pu.phase_pos[BlackoilPhases::Vapour]];
            if (sg > 0.0) {
                cond[cellIdx].setFreeGas();
            }
        }
    }

    // calculate the initial fluid densities for the gravity correction.
    std::vector<std::vector<double>> rho(numPhases);
    for (int phaseIdx = 0; phaseIdx < numPhases; ++phaseIdx) {
        rho[phaseIdx].resize(numCells);
    }

    // compute the capillary pressures of the active phases
    std::vector<double> capPress(numCells*numPhases);
    std::vector<int> cellIdxArray(numCells);
    for (int cellIdx = 0; cellIdx < numCells; ++ cellIdx) {
        cellIdxArray[cellIdx] = cellIdx;
    }
    props.capPress(numCells, initialState.saturation().data(), cellIdxArray.data(), capPress.data(), NULL);

    // compute the absolute pressure of each active phase: for some reason, E100
    // defines the capillary pressure for the water phase as p_o - p_w while it
    // uses p_g - p_o for the gas phase. (it would be more consistent to use the
    // oil pressure as reference for both the other phases.) probably this is
    // done to always have a positive number for the capillary pressure (as long
    // as the medium is hydrophilic)
    std::vector<std::vector<double> > phasePressure(numPhases);
    for (int phaseIdx = 0; phaseIdx < numPhases; ++phaseIdx) {
        phasePressure[phaseIdx].resize(numCells);
    }

    for (int cellIdx = 0; cellIdx < numCells; ++ cellIdx) {
        // we currently hard-code the oil phase as the reference phase!
        assert(pu.phase_used[BlackoilPhases::Liquid]);

        const int opos = pu.phase_pos[BlackoilPhases::Liquid];
        phasePressure[opos][cellIdx] = initialState.pressure()[cellIdx];

        if (pu.phase_used[BlackoilPhases::Aqua]) {
            const int wpos = pu.phase_pos[BlackoilPhases::Aqua];
            phasePressure[wpos][cellIdx] =
                initialState.pressure()[cellIdx]
                + (capPress[cellIdx*numPhases + opos] - capPress[cellIdx*numPhases + wpos]);
        }

        if (pu.phase_used[BlackoilPhases::Vapour]) {
            const int gpos = pu.phase_pos[BlackoilPhases::Vapour];
            phasePressure[gpos][cellIdx] =
                initialState.pressure()[cellIdx]
                + (capPress[cellIdx*numPhases + gpos] - capPress[cellIdx*numPhases + opos]);
        }
    }

    // calculate the densities of the active phases for each cell
    if (pu.phase_used[BlackoilPhases::Aqua]) {
        const int wpos = pu.phase_pos[BlackoilPhases::Aqua];
        const auto& pvtw = props.waterPvt();
        for (int cellIdx = 0; cellIdx < numCells; ++ cellIdx) {
            int pvtRegionIdx = pvtRegion[cellIdx];

            double T = initialState.temperature()[cellIdx];
            double p = phasePressure[wpos][cellIdx];
            double b = pvtw.inverseFormationVolumeFactor(pvtRegionIdx, T, p);

            rho[wpos][cellIdx] = surfaceDensity[pvtRegionIdx][wpos]*b;
        }
    }

    if (pu.phase_used[BlackoilPhases::Liquid]) {
        const int opos = pu.phase_pos[BlackoilPhases::Liquid];
        const auto& pvto = props.oilPvt();
        for (int cellIdx = 0; cellIdx < numCells; ++ cellIdx) {
            int pvtRegionIdx = pvtRegion[cellIdx];

            double T = initialState.temperature()[cellIdx];
            double p = phasePressure[opos][cellIdx];
            double Rs = initialState.gasoilratio()[cellIdx];
            double RsSat = pvto.saturatedGasDissolutionFactor(pvtRegionIdx, T, p);

            double b;
            if (Rs >= RsSat) {
                b = pvto.saturatedInverseFormationVolumeFactor(pvtRegionIdx, T, p);
            }
            else {
                b = pvto.inverseFormationVolumeFactor(pvtRegionIdx, T, p, Rs);
            }

            rho[opos][cellIdx] = surfaceDensity[pvtRegionIdx][opos]*b;
            if (pu.phase_used[BlackoilPhases::Vapour]) {
                int gpos = pu.phase_pos[BlackoilPhases::Vapour];
                rho[opos][cellIdx] += surfaceDensity[pvtRegionIdx][gpos]*Rs*b;
            }
        }
    }

    if (pu.phase_used[BlackoilPhases::Vapour]) {
        const int gpos = pu.phase_pos[BlackoilPhases::Vapour];
        const auto& pvtg = props.gasPvt();
        for (int cellIdx = 0; cellIdx < numCells; ++ cellIdx) {
            int pvtRegionIdx = pvtRegion[cellIdx];

            double T = initialState.temperature()[cellIdx];
            double p = phasePressure[gpos][cellIdx];
            double Rv = initialState.rv()[cellIdx];
            double RvSat = pvtg.saturatedOilVaporizationFactor(pvtRegionIdx, T, p);

            double b;
            if (Rv >= RvSat) {
                b = pvtg.saturatedInverseFormationVolumeFactor(pvtRegionIdx, T, p);
            }
            else {
                b = pvtg.inverseFormationVolumeFactor(pvtRegionIdx, T, p, Rv);
            }
            rho[gpos][cellIdx] = surfaceDensity[pvtRegionIdx][gpos]*b;
            if (pu.phase_used[BlackoilPhases::Liquid]) {
                int opos = pu.phase_pos[BlackoilPhases::Liquid];
                rho[gpos][cellIdx] += surfaceDensity[pvtRegionIdx][opos]*Rv*b;
            }
        }
    }

    // Calculate the maximum pressure potential difference between all PVT region
    // transitions of the initial solution.
    const int num_faces = UgGridHelpers::numFaces(grid);
    const auto& fc = UgGridHelpers::faceCells(grid);
    for (int face = 0; face < num_faces; ++face) {
        const int c1 = fc(face, 0);
        const int c2 = fc(face, 1);
        if (c1 < 0 || c2 < 0) {
            // Boundary face, skip this.
            continue;
        }
        const int gc1 = (gc == 0) ? c1 : gc[c1];
        const int gc2 = (gc == 0) ? c2 : gc[c2];
        const int eq1 = eqlnumData[gc1];
        const int eq2 = eqlnumData[gc2];

        if (eq1 == eq2) {
            // not an equilibration region boundary. skip this.
            continue;
        }

        // update the maximum pressure potential difference between the two
        // regions
        const auto barrierId = std::make_pair(std::min(eq1, eq2), std::max(eq1, eq2));
        if (maxDp.count(barrierId) == 0) {
            maxDp[barrierId] = 0.0;
        }

        for (int phaseIdx = 0; phaseIdx < numPhases; ++phaseIdx) {
            const double z1 = UgGridHelpers::cellCenterDepth(grid, c1);
            const double z2 = UgGridHelpers::cellCenterDepth(grid, c2);

            const double rhoAvg = (rho[phaseIdx][c1] + rho[phaseIdx][c2])/2;

            const double s1 = initialState.saturation()[numPhases*c1 + phaseIdx];
            const double s2 = initialState.saturation()[numPhases*c2 + phaseIdx];

            const double sResid1 = minSat[numPhases*c1 + phaseIdx];
            const double sResid2 = minSat[numPhases*c2 + phaseIdx];

            // compute gravity corrected pressure potentials at the average depth
            const double p1 = phasePressure[phaseIdx][c1];
            const double p2 = phasePressure[phaseIdx][c2] + rhoAvg*gravity*(z1 - z2);

            if ((p1 > p2 && s1 > sResid1) || (p2 > p1 && s2 > sResid2))
                maxDp[barrierId] = std::max(maxDp[barrierId], std::abs(p1 - p2));
        }
    }
}
Exemplo n.º 15
0
void digitsSPD(Int_t nevents, Int_t nfiles)
{

  TH1F * hadc = new TH1F ("hadc", "hadc",100, 0, 2);   
  TH1F * hadclog = new TH1F ("hadclog", "hadclog",100, -1, 1);   

  TDirectoryFile *tdf[100];      
  TDirectoryFile *tdfKine[100] ; 

  TTree *ttree[100];      
  TTree *ttreeKine[100];  


  TClonesArray *arr= NULL; // 

  //Run loader------------
  TString name;
  name = "galice.root";
  AliRunLoader* rlSig = AliRunLoader::Open(name.Data());

  // gAlice
  rlSig->LoadgAlice();
  gAlice = rlSig->GetAliRun();

  // Now load kinematics and event header
  rlSig->LoadKinematics();
  rlSig->LoadHeader();
  cout <<  rlSig->GetNumberOfEvents()<< endl;
  //----------------------

  
     //loop over events in the files
    for(Int_t event=0; event<nevents; event++){
      //printf("###event= %d\n", event + file*100);
      printf("###event= %d\n", event);

    tdf[event] = GetDirectory(event, "ITS", nfiles);
    if ( ! tdf[event] ) {
      cerr << "Event directory not found in " << nfiles <<  " files" << endl;
      exit(1);
    }      
    
      ttree[event] = (TTree*)tdf[event]->Get("TreeD");
          
      arr = NULL;
      ttree[event]->SetBranchAddress("ITSDigitsSPD", &arr);
   

      // Runloader -> gives particle Stack
      rlSig->GetEvent(event);
      AliStack * stack = rlSig->Stack(); 
      //stack->DumpPStack();


      // loop over tracks
      Int_t NumberPrim=0;
      for(Int_t iev=0; iev<ttree[event]->GetEntries(); iev++){
	ttree[event]->GetEntry(iev);

	
	for (Int_t j = 0; j < arr->GetEntries(); j++) {
	  AliITSdigit* digit = dynamic_cast<AliITSdigit*> (arr->At(j));
	  if (digit){
	    hadc->Fill(digit->GetSignal());
	    hadclog->Fill(TMath::Log10(digit->GetSignal()));
	
	  }
	}
      }

    }

  TFile fc("digits.ITS.SPD.root","RECREATE");
  fc.cd();
   
  hadc->Write();
  hadclog->Write();

  fc.Close();

}
Exemplo n.º 16
0
static void diff_save_tags(const base_object_t *obj, xmlNodePtr node) {
  diff_save_tags_functor fc(node);
  obj->tags.for_each(fc);
}
Exemplo n.º 17
0
int CreateMatricies(MPI_Comm comm,
		    int p, int q,
		    int bm, int bn, int bk,
		    int gm, int gn, int gk,
		    double *a, double *b, double *c,
		    double (*fa)(int i, int j),
		    double (*fb)(int i, int j),
		    double (*fc)(int i, int j)) {
  
  int rank, size;
  
  MPI_Comm_rank (comm, &rank);
  MPI_Comm_size (comm, &size);

  // Check that parameters form valid configuration
  assert(p*q == size);
  assert(gm % bm == 0);
  assert(gk % bk == 0);
  assert(gn % bn == 0);
  assert(bm % p == 0);
  assert(bn % q == 0);
  assert(bk % p == 0);
  assert(bk % q == 0);
  assert(bk / p == bk / q);

  int
    pm = bm / p,
    pn = bn / q,
    pk = bk / q;

  int
    m = gm / bm,
    n = gn / bn,
    k = gk / bk;

  int i, j, l;
  int pi, pj, pl;
  int bi, bj, bl;
  int gi, gj, gl;
  
  // Form A matrix
  for ( bi = 0; bi < m; bi++)
    for ( bl = 0; bl < k; bl++ ) {
      // Calculate processor location by column
      pi = rank % q;
      pl = rank / p;
      
      for ( i = 0; i < pm; i++ )
	for ( l = 0; l < pk; l++ )
	  {
	    gi = (bi * bm) + (pi * pm) + i;
	    gl = (bl * bk) + (pl * pk) + l;

	    a[(bi + bl * m) * (pm * pk) + (i + pm * l)] = fa(gi, gl);
	  }
    }

  // Form B matrix
  for ( bl = 0; bl < k; bl++)
    for ( bj = 0; bj < n; bj++ ) {
      // Calculate processor location by column
      pl = rank % q;
      pj = rank / p;
      
      for ( l = 0; l < pk; l++ )
	for ( j = 0; j < pn; j++ )
	  {
	    gl = (bl * bk) + (pl * pk) + l;
	    gj = (bj * bn) + (pj * pn) + j;

	    b[(bl + bj * k) * (pk * pn) + (l + pk * j)] = fb(gl, gj);
	  }
    }

  // Form C matrix
  for ( bi = 0; bi < m; bi++)
    for ( bj = 0; bj < n; bj++ ) {
      // Calculate processor location by column
      pi = rank % q;
      pj = rank / p;
      
      for ( i = 0; i < pm; i++ )
	for ( j = 0; j < pn; j++ )
	  {
	    gi = (bi * bm) + (pi * pm) + i;
	    gj = (bj * bn) + (pj * pn) + j;

	    c[(bi + bj * m) * (pm * pn) + (i + pm * j)] = fc(gi, gj);
	  }
    }

  return 0;
}
Exemplo n.º 18
0
void RGBMatrix::updateMapChannels(const RGBMap& map, const FixtureGroup* grp)
{
    uint fadeTime = (overrideFadeInSpeed() == defaultSpeed()) ? fadeInSpeed() : overrideFadeInSpeed();

    // Create/modify fade channels for ALL pixels in the color map.
    for (int y = 0; y < map.size(); y++)
    {
        for (int x = 0; x < map[y].size(); x++)
        {
            QLCPoint pt(x, y);
            GroupHead grpHead(grp->head(pt));
            Fixture* fxi = doc()->fixture(grpHead.fxi);
            if (fxi == NULL)
                continue;

            QLCFixtureHead head = fxi->head(grpHead.head);

            QVector <quint32> rgb = head.rgbChannels();
            QVector <quint32> cmy = head.cmyChannels();

            quint32 masterDim = fxi->masterIntensityChannel();
            quint32 headDim = head.channelNumber(QLCChannel::Intensity, QLCChannel::MSB);

            // Collect all dimmers that affect current head:
            // They are the master dimmer (affects whole fixture)
            // and per-head dimmer.
            //
            // If there are no RGB or CMY channels, the least important* dimmer channel
            // is used to create grayscale image.
            //
            // The rest of the dimmer channels are set to full if dimmer control is
            // enabled and target color is > 0 (see
            // http://www.qlcplus.org/forum/viewtopic.php?f=29&t=11090)
            //
            // Note: If there is only one head, and only one dimmer channel,
            // make it a master dimmer in fixture definition.
            //
            // *least important - per head dimmer if present,
            // otherwise per fixture dimmer if present
            QVector <quint32> dim;
            if (masterDim != QLCChannel::invalid())
                dim << masterDim;

            if (headDim != QLCChannel::invalid())
                dim << headDim;

            uint col = map[y][x];

            if (rgb.size() == 3)
            {
                // RGB color mixing
                {
                    FadeChannel fc(doc(), grpHead.fxi, rgb.at(0));
                    fc.setTarget(qRed(col));
                    insertStartValues(fc, fadeTime);
                    m_fader->add(fc);
                }

                {
                    FadeChannel fc(doc(), grpHead.fxi, rgb.at(1));
                    fc.setTarget(qGreen(col));
                    insertStartValues(fc, fadeTime);
                    m_fader->add(fc);
                }

                {
                    FadeChannel fc(doc(), grpHead.fxi, rgb.at(2));
                    fc.setTarget(qBlue(col));
                    insertStartValues(fc, fadeTime);
                    m_fader->add(fc);
                }
            }
            else if (cmy.size() == 3)
            {
                // CMY color mixing
                QColor cmyCol(col);

                {
                    FadeChannel fc(doc(), grpHead.fxi, cmy.at(0));
                    fc.setTarget(cmyCol.cyan());
                    insertStartValues(fc, fadeTime);
                    m_fader->add(fc);
                }

                {
                    FadeChannel fc(doc(), grpHead.fxi, cmy.at(1));
                    fc.setTarget(cmyCol.magenta());
                    insertStartValues(fc, fadeTime);
                    m_fader->add(fc);
                }

                {
                    FadeChannel fc(doc(), grpHead.fxi, cmy.at(2));
                    fc.setTarget(cmyCol.yellow());
                    insertStartValues(fc, fadeTime);
                    m_fader->add(fc);
                }
            }
            else if (!dim.empty())
            {
                // Set dimmer to value of the color (e.g. for PARs)
                FadeChannel fc(doc(), grpHead.fxi, dim.last());
                // the weights are taken from
                // https://en.wikipedia.org/wiki/YUV#SDTV_with_BT.601
                fc.setTarget(0.299 * qRed(col) + 0.587 * qGreen(col) + 0.114 * qBlue(col));
                insertStartValues(fc, fadeTime);
                m_fader->add(fc);
                dim.pop_back();
            }

            if (m_dimmerControl)
            {
                // Set the rest of the dimmer channels to full on
                foreach(quint32 ch, dim)
                {
                    FadeChannel fc(doc(), grpHead.fxi, ch);
                    fc.setTarget(col == 0 ? 0 : 255);
                    insertStartValues(fc, fadeTime);
                    m_fader->add(fc);
                }
            }
        }
    }
Exemplo n.º 19
0
void PaletteEditor::stopsChangedAction()
{
	static const int GradientBufferLastIdx = GradientBufferSize - 1;
	static const qreal dx  = 1.0 / GradientBufferSize;
	QSize s( m_gradientLabel->maximumSize() );
	QRect r( QPoint(0, 0), QSize(s.width(), (s.height() / 2.0 ) ) );
	QImage palette_image(s, QImage::Format_RGB32);
	QPainter painter(&palette_image);
	GradientStops stops(m_gradientStops->getStops());
	qStableSort(stops.begin(), stops.end(), GradientStop::lessThanGradientStopComparison);

	// now apply the ends and update the palette
	GradientStops ends( m_gradientEnds->getStops() );
	QGradient::Spread spread((QGradient::Spread)m_gradientSpreadGroup->checkedId());

	GradientStop n_stop(stops.first());
	QRgb ccolor = n_stop.second.rgba();
	for (int n = 0, fpos = n_stop.first * GradientBufferSize  ; n < fpos ; n++)
		m_gradient[qMin(n, GradientBufferLastIdx)] = ccolor;

	int last_stop_idx = stops.size() - 1;
	for (int begin_idx = 0; begin_idx < last_stop_idx ; begin_idx++)
	{
		GradientStop a = stops.at(begin_idx);
		GradientStop b = stops.at(begin_idx + 1);
		QColor ac = a.second;
		QColor bc = b.second;
		qreal d = ( b.first - a.first );
		qreal rdx, gdx, bdx, adx;
		if (b.colorspace == 0)
		{
			rdx = ( (bc.red()   - ac.red() )   / d ) * dx;
			gdx = ( (bc.green() - ac.green() ) / d ) * dx;
			bdx = ( (bc.blue()  - ac.blue() )  / d ) * dx;
			adx = ( (bc.alpha() - ac.alpha() ) / d ) * dx;
		}
		else
		{
			rdx = ( (bc.hue()        - ac.hue() )        / d ) * dx;
			gdx = ( (bc.saturation() - ac.saturation() ) / d ) * dx;
			bdx = ( (bc.value()      - ac.value() )      / d ) * dx;
			adx = ( (bc.alpha()      - ac.alpha() )      / d ) * dx;

			if (b.colorspace == 1)
			{
				if (rdx == 0.0)
					rdx = 180.0 / d * dx;
				else if (rdx < 0)
					rdx *= -1;
			}
			else
			{
				if (rdx == 0.0)
					rdx = -180.0 / d * dx;
				else if (rdx > 0)
					rdx *= -1;
			}
		}
		int n  = a.first * GradientBufferSize ;
		int nb = (int)(b.first * GradientBufferSize );
		for (int i = 0 ; n < nb ; i++, n++)
		{
			if (b.colorspace == 0)
			{
				m_gradient[n] = qRgba(
						qBound(0, (int)( ac.red()   + rdx * i + 0.5 ), 255),
						qBound(0, (int)( ac.green() + gdx * i + 0.5 ), 255),
						qBound(0, (int)( ac.blue()  + bdx * i + 0.5 ), 255),
						qBound(0, (int)( ac.alpha() + adx * i + 0.5 ), 255));
			}
			else
			{
				int h = (int)( ac.hue() + rdx * i + 0.5 );
				if (h < 0)
					h += 360;
				m_gradient[n] = QColor::fromHsv(h % 360,
						qBound(0, (int)( ac.saturation() + gdx * i + 0.5 ), 255),
						qBound(0, (int)( ac.value()  + bdx * i + 0.5 ), 255),
						qBound(0, (int)( ac.alpha() + adx * i + 0.5 ), 255)).rgba();
			}
		}
	}

	n_stop = stops.last();
	ccolor = n_stop.second.rgba();
	for (int n = n_stop.first * GradientBufferSize ; n < GradientBufferSize ; n++)
		m_gradient[n] = ccolor;

	qreal start(ends.at(0).first);
	qreal end(ends.at(1).first);
	int begin_idx = start * 256 ;
	int end_idx   = end   * 256 ;
	int ibuf_size = end_idx - begin_idx;
	flam3_palette_entry* ibuf = new flam3_palette_entry[ibuf_size]();

	// a very acute filter
	qreal c2 = 0.01;
	qreal c3 = 1.0;
	qreal c4 = 0.01;
	qreal norm = c2 + c3 + c4;
	qreal k = 0.0;
	qreal skip( (GradientBufferSize / 256.0) / qMax(qreal(1.0/GradientBufferSize), end - start) );
	for (int n = 0 ; n < ibuf_size ; n++, k += skip)
	{
		int j = k;
		QRgb a2( m_gradient[qBound(0, j + 0, GradientBufferLastIdx)] );
		QRgb a3( m_gradient[qMin(j + 1, GradientBufferLastIdx)] );
		QRgb a4( m_gradient[qMin(j + 2, GradientBufferLastIdx)] );

		ibuf[n].color[0] = (qRed(a2)*c2   + qRed(a3)*c3   + qRed(a4)*c4 )   / (norm * 255.);
		ibuf[n].color[1] = (qGreen(a2)*c2 + qGreen(a3)*c3 + qGreen(a4)*c4 ) / (norm * 255.);
		ibuf[n].color[2] = (qBlue(a2)*c2  + qBlue(a3)*c3  + qBlue(a4)*c4 )  / (norm * 255.);
		ibuf[n].color[3] = (qAlpha(a2)*c2 + qAlpha(a3)*c3 + qAlpha(a4)*c4 ) / (norm * 255.);
	}

	// update the gradient editor label
	painter.fillRect(QRect(QPoint(0,0), s), checkers);
	if (ibuf_size == 256)
	{
		for (int n = 0, h = s.height() ; n < 256 ; n++)
		{
			painter.setPen(QColor::fromRgbF(ibuf[n].color[0], ibuf[n].color[1], ibuf[n].color[2], ibuf[n].color[3]));
			painter.drawLine(n, 0, n, h);
		}
	}
	else
	{
		for (int n = 0, h = s.height(), j = 0 ; n < 256 ; n++, j += 4)
		{
			QRgb a2( m_gradient[qBound(0, j + 0, GradientBufferLastIdx)] );
			QRgb a3( m_gradient[qMin(j + 1, GradientBufferLastIdx)] );
			QRgb a4( m_gradient[qMin(j + 2, GradientBufferLastIdx)] );
			QRgb r((qRed(a2)*c2   + qRed(a3)*c3   + qRed(a4)*c4 )   / norm );
			QRgb g((qGreen(a2)*c2 + qGreen(a3)*c3 + qGreen(a4)*c4 ) / norm );
			QRgb b((qBlue(a2)*c2  + qBlue(a3)*c3  + qBlue(a4)*c4 )  / norm );
			QRgb a((qAlpha(a2)*c2 + qAlpha(a3)*c3 + qAlpha(a4)*c4 ) / norm );
			QColor c(r, g, b, a);
			painter.setPen(c);
			painter.drawLine(n, 0, n, h);
		}
	}
	m_gradientLabel->setPixmap(QPixmap::fromImage(palette_image));

	// Rescale the gradient colors into the palette with a simple filter
	if (spread == QGradient::PadSpread)
	{
		QRgb fc(m_gradient[0]);
		flam3_palette_entry e = { 0., { qRed(fc)/255., qGreen(fc)/255., qBlue(fc)/255., qAlpha(fc)/255. }};
		for (int n = 0 ; n < begin_idx ; n++)
			p[n] = e;

		for (int n = begin_idx, j = 0 ; n < end_idx ; n++, j++)
			p[n] = ibuf[j];

		fc = m_gradient[GradientBufferLastIdx];
		e = (flam3_palette_entry){ 1., { qRed(fc)/255., qGreen(fc)/ 255., qBlue(fc)/255., qAlpha(fc)/255. }};
		for (int n = end_idx ; n < 256 ; n++)
			p[n] = e;
	}
	else if (spread == QGradient::RepeatSpread)
	{
		for (int n = begin_idx, j = 0 ; n < 256 ; n++, j++)
			p[n] = ibuf[j % ibuf_size];
		for (int n = begin_idx - 1, j = ibuf_size * 4096 - 1 ; n >= 0 ; n--, j--)
			p[n] = ibuf[j % ibuf_size];
	}
	else if (spread == QGradient::ReflectSpread)
	{
		for (int n = begin_idx, j = 0, h = 4096*ibuf_size -1 ; n < begin_idx + ibuf_size ; n++, j++, h--)
		{
			for (int k = n, q = n + ibuf_size ; k < 256 ; k += 2*ibuf_size, q += 2*ibuf_size )
			{
				p[k] = ibuf[j % ibuf_size];
				if (q < 256)
					p[q] = ibuf[h % ibuf_size];
			}
		}
		for (int n = begin_idx - 1, j = ibuf_size * 4096 - 1, h = 0 ; n >= begin_idx - ibuf_size ; n--, j--, h++)
		{
			for (int k = n, q = n - ibuf_size ; k >= 0 ; k -= 2*ibuf_size, q -= 2*ibuf_size )
			{
				p[k] = ibuf[h % ibuf_size];
				if (q >= 0)
					p[q] = ibuf[j % ibuf_size];
			}
		}
	}
	delete[] ibuf;

	setPaletteView();
	emit paletteChanged();
}
Exemplo n.º 20
0
 fc operator-(const fc& o) const {
   return *this + fc(-1) * o;
 }
Exemplo n.º 21
0
int ProcessDifference()
{
	LPCSTR params = GetCommandLine();
	Flags32 _flags;
	_flags.zero();
	if(strstr(params,"-diff /?")){
		printf("HELP:\n");
		printf("xrCompress.exe -diff <new_data> <old_data> -out <diff_resulf> [options]\n");
		printf("<new_data>, <old_data> and <diff_resulf> values must be a folder name\n");
		printf("[options] are set of:\n");
		printf("-nofileage		do not perform file age checking\n");
		printf("-crc			do not perform crc32 checking\n");
		printf("-nobinary		do not perform binary content checking\n");
		printf("-nosize			do not perform file size checking\n");
		return 3;
	}

	CLocatorAPI* FS_new = NULL;
	CLocatorAPI* FS_old = NULL;
	

	xr_vector<char*>*	file_list_old		= NULL;
	xr_vector<char*>*	folder_list_old		= NULL;

	xr_vector<char*>*	file_list_new		= NULL;
	xr_vector<char*>*	folder_list_new		= NULL;

	sscanf					(strstr(params,"-diff ")+6,"%[^ ] ",new_folder);
	sscanf					(strstr(params,"-diff ")+6+xr_strlen(new_folder)+1,"%[^ ] ",old_folder);
	sscanf					(strstr(params,"-out ")+5,"%[^ ] ",target_folder);
	
	if(strstr(params,"-nofileage")){
		_flags.set(file_comparer::eDontCheckFileAge, TRUE);
	};
	if(strstr(params,"-nocrc")){
		_flags.set(file_comparer::eDontCheckCRC, TRUE);
	};
	if(strstr(params,"-nobinary")){
		_flags.set(file_comparer::eDontCheckBinary, TRUE);
	};
	if(strstr(params,"-nosize")){
		_flags.set(file_comparer::eDontCheckFileSize, TRUE);
	};

	FS_new = xr_new<CLocatorAPI>	();
	FS_new->_initialize(CLocatorAPI::flTargetFolderOnly,new_folder);
	file_list_new	= FS_new->file_list_open	("$target_folder$",FS_ListFiles);
	folder_list_new	= FS_new->file_list_open	("$target_folder$",FS_ListFolders);

	FS_old = xr_new<CLocatorAPI>	();
	FS_old->_initialize(CLocatorAPI::flTargetFolderOnly,old_folder);
	file_list_old	= FS_old->file_list_open	("$target_folder$",FS_ListFiles);
	folder_list_old	= FS_old->file_list_open	("$target_folder$",FS_ListFolders);

	xr_vector<LPCSTR> target_file_list;
	target_file_list.reserve(file_list_new->size());

	for(u32 i=0; i<file_list_new->size();++i){
		file_comparer fc(file_list_new->at(i),FS_new, FS_old,_flags);
		xr_vector<char*>::iterator it = std::find_if(file_list_old->begin(),file_list_old->end(),fc);
		if(it != file_list_old->end()){
			printf("skip file %s\n",file_list_new->at(i));
		}else
			target_file_list.push_back(file_list_new->at(i));
	}

	string_path out_path;
	for(u32 i=0; i<target_file_list.size();++i){
		LPCSTR fn = target_file_list[i];
		strconcat(out_path,target_folder,"\\",fn);
		VerifyPath(out_path);
		IReader* r = FS_new->r_open("$target_folder$",fn);
		IWriter* w = FS_old->w_open(out_path);
		w->w(r->pointer(),r->length());
		FS_new->r_close(r);
		FS_old->w_close(w);
	}


	FS_new->file_list_close(file_list_new);
	FS_new->file_list_close(folder_list_new);

	FS_old->file_list_close(file_list_old);
	FS_old->file_list_close(folder_list_old);

	xr_delete(FS_new);
	xr_delete(FS_old);

	return 0;
}
Exemplo n.º 22
0
 fc operator/(const fc& o) const {   
   return *this * fc(o.d, o.n);
 }
Exemplo n.º 23
0
int main(int argc, char *argv[]){
// code in the main program
char buf3[6];
char buf7[5];
char* cmd1[3];
char* cmd2[3];
cmd2[0] = buf3;
cmd2[1] = buf7;

strcpy(buf3, "hi");
strcpy(buf7, "ok");
char val[] = "ls|wc";
fa(buf3);
printf("fa(buf3) = %s\n", buf3);

fb(buf3);
printf("fb(buf3) = %s\n", buf3);

fc(buf3);
printf("fc(buf3) = %s\n", buf3);

fd(buf3);
printf("fd(buf3) = %s\n", buf3);

fe(buf3);
printf("fb(buf3) = %s\n", buf3);

fa(buf7);
printf("fa(buf7) = %s\n", buf7);

fb(buf7);
printf("fb(buf7) = %s\n", buf7);

fc(buf7);
printf("fc(buf7) = %s\n", buf7);

fd(buf7);
printf("fd(buf7) = %s\n", buf7);

fe(buf7);
printf("fb(buf7) = %s\n", buf7);

ff(cmd1, val);
printf("ff(cmd1[0], val) = %s\n", cmd1[0]);
printf("ff(cmd1, val) = %s\n", cmd1[1]);
fg(cmd1, val);
printf("fg(cmd1[0], val) = %s\n", cmd1[0]);
printf("fg(cmd1, val) = %s\n", cmd1[1]);
fh(cmd1, val);
printf("fh(cmd1[0], val) = %s\n", cmd1[0]);
printf("fh(cmd1, val) = %s\n", cmd1[1]);
fi(cmd1, val);
printf("fi(cmd1[0], val) = %s\n", cmd1[0]);
fj(cmd1, val);
printf("fj(cmd1[0], val) = %s\n", cmd1[0]);

ff(cmd2, val);
printf("ff(cmd2[0], val) = %s\n", cmd2[0]);
printf("ff(cmd2, val) = %s\n", cmd2[1]);
fg(cmd2, val);
printf("fg(cmd2[0], val) = %s\n", cmd2[0]);
printf("fg(cmd2, val) = %s\n", cmd2[1]);
fh(cmd2, val);
printf("fh(cmd2[0], val) = %s\n", cmd2[0]);
printf("fh(cmd2, val) = %s\n", cmd2[1]);
fi(cmd2, val);
printf("fi(cmd2[0], val) = %s\n", cmd2[0]);
fj(cmd2, val);
printf("fj(cmd2[0], val) = %s\n", cmd2[0]);

return 0;
}
Exemplo n.º 24
0
void captureFrames() {
    if (!stream1.isOpened()) {
        CV_Assert("T1 cam open failed");
    }

    if (isVideoCapture == true) {
        // resolutions 320, 240; 800, 448; 640, 480
        //stream1.set(CV_CAP_PROP_FRAME_WIDTH, 320); stream1.set(CV_CAP_PROP_FRAME_HEIGHT, 240);
        stream1.set(CV_CAP_PROP_FRAME_WIDTH, 640); stream1.set(CV_CAP_PROP_FRAME_HEIGHT, 480);
        //stream1.set(CV_CAP_PROP_FRAME_WIDTH, 1280); stream1.set(CV_CAP_PROP_FRAME_HEIGHT, 720);
    }

    if (isVideoCapture == false) {
        doLog(debug_t1_log, "debug_t1_log: T1 video capture %f %f %f\n", stream1.get(CV_CAP_PROP_FRAME_WIDTH), stream1.get(CV_CAP_PROP_FRAME_HEIGHT), stream1.get(CV_CAP_PROP_FPS));
        doLog(debug_t1_log, "debug_t1_log: CAP_PROP_FPS %f\n", stream1.get(CV_CAP_PROP_FPS));
        doLog(debug_t1_log, "debug_t1_log: CAP_PROP_FRAME_COUNT %f\n", stream1.get(CV_CAP_PROP_FRAME_COUNT));
    }

    cv::Mat frame;
    unsigned int frameNum = 0;
    //std::chrono::time_point<std::chrono::steady_clock> t1 = std::chrono::steady_clock::now();
    double prevFrameMs = 0;
    while (grabbing) {
#ifdef IS_TEST
//        while (canAdd != true && grabbing) {
//            std::this_thread::sleep_for(std::chrono::milliseconds(10));
//        }
#endif
        if(!(stream1.read(frame))) {
            doLog(debug_t1_log, "debug_t1_log: No captured frame, exiting!\n");
            finished = true;
            return;
        }

        long int listSize = frameList.size();
        doLog(debug_t1_log, "debug_t1_log: size %ld\n", frameList.size());

        if (listSize >= maxSize && disable_max_size != true) {
            doLog(debug_t1_log, "debug_t1_log: reached max size %d\n", maxSize);
            canAdd = false;
        }
        while (canAdd == false && grabbing) {
            doLog(debug_t1_log, "debug_t1_log: waiting...\n", frameList.size());
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
        }
        canAdd = true;
        double frameTimeMs;
        if (isVideoCapture == true) {
            long int ft = (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch())).count();
            frameTimeMs = (double) ft;
        } else {
            if (shouldUseAnnotTimestamps == true) {
                if (annotTimestampsMap.find((int)frameNum)!=annotTimestampsMap.end()) {
                    frameTimeMs = annotTimestampsMap[(int)frameNum];
                } else {
                    printf("missing framenum %d\n", (int)frameNum);
                    return;
                }
                
            } else {
                frameTimeMs = (double) stream1.get(CV_CAP_PROP_POS_MSEC);
            }
        }
        if (frameNum >= startingFrameNum) {
            FrameCarrier fc(frame.clone(), frameTimeMs, frameNum);
            frameList.push_back(fc);
            doLog(debug_t1_log, "debug_t1_log: F %d T %lf diff %lf\n", frameNum, frameTimeMs, frameTimeMs-prevFrameMs);
            prevFrameMs = frameTimeMs;
        }
        if (frameNum == endingFrameNum && endingFrameNum != 0) {
            doLog(debug_t1_log, "debug_t1_log: F %d T %lf  finished by endingFrameNum\n", frameNum, frameTimeMs);
            finished = true;
            return;
        }
        frameNum++;
    }
}
Exemplo n.º 25
0
Arquivo: 04.cpp Projeto: lgylo/CS
int main() {
	fc(1, 3);
	return 0;
}
Exemplo n.º 26
0
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  try
  {
    DDS::DomainParticipant_var participant1;
    DDS::DomainParticipant_var participant2;

    DDS::DomainParticipantFactory_var dpf = TheParticipantFactoryWithArgs(argc, argv);

    {
      OpenDDS::DCPS::TypeSupport_var typsup = new Xyz::FooTypeSupportImpl;

      Options configopt(argc, argv);
      Factory fc(configopt, typsup);

      Options plainopt;
      Factory fp(plainopt, typsup);

      DDS::DataWriterListener_var dwl1(new DataWriterListenerImpl);
      DDS::DataWriterListener_var dwl2(new DataWriterListenerImpl);

      if (configopt.collocation_str == "none")
      {
        participant1 = fc.participant(dpf);
        Pusher w(fc, dpf, participant1, dwl1);
        TEST_ASSERT(assert_supported(configopt, w.writer_));

        w.push(ACE_Time_Value(configopt.test_duration));
        if (!configopt.negotiated_str.empty())
        {
          TEST_ASSERT(assert_negotiated(configopt, w.writer_));
        }
      }
      else if (configopt.collocation_str == "process")
      {
        participant1 = fc.participant(dpf);
        Pusher w1(fc, dpf, participant1, dwl1);
//          TEST_ASSERT(wait_publication_matched_status(configopt, w1.writer_));

        participant2 = fp.participant(dpf);
        Pusher w2(fp, dpf, participant2, dwl2);
//          TEST_ASSERT(wait_publication_matched_status(configopt, w2.writer_));

        TEST_ASSERT(assert_supported(configopt, w1.writer_));
        if (configopt.entity_str == "none")
        {
          TEST_ASSERT(assert_supported(configopt, w2.writer_));
        }
        else
        {
          TEST_ASSERT(!assert_supported(configopt, w2.writer_));
          TEST_ASSERT(assert_supported(plainopt, w2.writer_));
        }

        w1.push(ACE_Time_Value(1));
        if (!configopt.negotiated_str.empty())
        {
          TEST_ASSERT(assert_negotiated(configopt, w1.writer_));
        }
      }
      else if (configopt.collocation_str == "participant")
      {
        participant1 = fc.participant(dpf);
        participant2 = participant1;

        DDS::Publisher_var publisher1(fc.publisher(participant1));
        Pusher w1(fc, dpf, participant1, publisher1, dwl1);

        DDS::Publisher_var publisher2(fp.publisher(participant2));
        Pusher w2(fp, dpf, participant2, publisher2, dwl2);

        TEST_ASSERT(assert_supported(configopt, w1.writer_));
        TEST_ASSERT(assert_supported(configopt, w2.writer_));

        w1.push(ACE_Time_Value(1));
        if (!configopt.negotiated_str.empty())
        {
          TEST_ASSERT(assert_negotiated(configopt, w1.writer_));
        }
      }
      else if (configopt.collocation_str == "pubsub")
      {
        participant1 = fc.participant(dpf);
        participant2 = participant1;
        DDS::Publisher_var publisher1(fc.publisher(participant1));
        DDS::Publisher_var publisher2(publisher1);

        Pusher w1(fc, dpf, participant1, publisher1, dwl1);
        Pusher w2(fp, dpf, participant2, publisher2, dwl2);

        TEST_ASSERT(assert_supported(configopt, w1.writer_));
        TEST_ASSERT(assert_supported(configopt, w2.writer_));

        w1.push(ACE_Time_Value(1));
        if (!configopt.negotiated_str.empty())
        {
          TEST_ASSERT(assert_negotiated(configopt, w1.writer_));
        }
      }

      if (configopt.collocation_str == "none")
      {
        TEST_ASSERT(assert_publication_matched(configopt, dwl1));
      }
      else if (configopt.collocation_str == "process")
      {
        TEST_ASSERT(assert_publication_matched(configopt, dwl1)
                    && assert_publication_matched(configopt, dwl2));
      }
      else if (configopt.collocation_str == "participant")
      {
        TEST_ASSERT(assert_publication_matched(configopt, dwl1)
                    && assert_publication_matched(configopt, dwl2));
      }
      else if (configopt.collocation_str == "pubsub")
      {
        TEST_ASSERT(assert_publication_matched(configopt, dwl1)
                    && assert_publication_matched(configopt, dwl2));
      }
    }
    // only want to clean up participant2 if it isn't just pointing to
    // participant1
    if (participant1.in() == participant2.in()) {
      participant2 = 0;
    }
    // Clean up
    if (participant1) {
      ACE_DEBUG((LM_INFO, ACE_TEXT("(%P|%t) deleting entities1\n")));
      participant1->delete_contained_entities();
      ACE_DEBUG((LM_INFO, ACE_TEXT("(%P|%t) deleting participant1\n")));
      dpf->delete_participant(participant1);
    }
    if (participant2) {
      ACE_DEBUG((LM_INFO, ACE_TEXT("(%P|%t) deleting entities2\n")));
      participant2->delete_contained_entities();
      ACE_DEBUG((LM_INFO, ACE_TEXT("(%P|%t) deleting participant2\n")));
      dpf->delete_participant(participant2);
    }
    ACE_DEBUG((LM_INFO, ACE_TEXT("(%P|%t) Shutting publisher down ...\n")));
    TheServiceParticipant->shutdown();
    ACE_DEBUG((LM_INFO, ACE_TEXT("(%P|%t) Publisher shutdown complete.\n")));
  }
  catch (char const *ex)
  {
    ACE_ERROR_RETURN((LM_ERROR,
                      ACE_TEXT("(%P|%t) Assertion failed.\n"), ex), -1);
  }
  catch (const CORBA::Exception& ex)
  {
    ex._tao_print_exception("Exception caught in main.cpp:");
    return 1;
  }
  catch (const std::runtime_error& rte)
  {
    ACE_ERROR_RETURN((LM_ERROR,
                      ACE_TEXT("(%P|%t) main() exception: %s\n"), rte.what()), -1);
  }

  ACE_ERROR_RETURN((LM_INFO,
                    ACE_TEXT("(%P|%t) done.\n")), 0);
}
Exemplo n.º 27
0
bool UIComponent::perform(const InvocationInfo& info)
{

    switch (info.commandID)
    {
        case openConfiguration:
            {
                FileChooser fc("Choose a file to load...",
                               File::getCurrentWorkingDirectory(),
                               "*",
                               true);

                if (fc.browseForFileToOpen())
                {
                    File currentFile = fc.getResult();
                    sendActionMessage(getEditorViewport()->loadState(currentFile));
                }
                else
                {
                    sendActionMessage("No configuration selected.");
                }

                break;
            }
        case saveConfiguration:
            {

                FileChooser fc("Choose the file to save...",
                               File::getCurrentWorkingDirectory(),
                               "*",
                               true);

                if (fc.browseForFileToSave(true))
                {
                    File currentFile = fc.getResult();
                    std::cout << currentFile.getFileName() << std::endl;
                    sendActionMessage(getEditorViewport()->saveState(currentFile));
                }
                else
                {
                    sendActionMessage("No file chosen.");
                }

                break;
            }
        case clearSignalChain:
            getEditorViewport()->clearSignalChain();
            break;

        case showHelp:
            std::cout << "SHOW ME SOME HELP!" << std::endl;
            break;

        case toggleProcessorList:
            processorList->toggleState();
            break;

        case toggleFileInfo:
            controlPanel->toggleState();
            break;

        case toggleSignalChain:
            editorViewportButton->toggleState();
            break;
            
        case resizeWindow:
            mainWindow->centreWithSize(800, 600);
            break;

        default:
            break;

    }

    return true;

}
Exemplo n.º 28
0
static void test_mg_fetch(void) {
  static const char *options[] = {
    "document_root", ".",
    "listening_ports", UNUSED_PORT,
    NULL,
  };
  char buf[2000], buf2[2000];
  int n, length;
  struct mg_context *ctx;
  struct mg_request_info ri;
  const char *tmp_file = "temporary_file_name_for_unit_test.txt";
  struct file file;
  FILE *fp;

  ASSERT((ctx = mg_start(event_handler, NULL, options)) != NULL);

  // Failed fetch, pass invalid URL
  ASSERT(mg_fetch(ctx, "localhost", tmp_file, buf, sizeof(buf), &ri) == NULL);
  ASSERT(mg_fetch(ctx, "localhost:" UNUSED_PORT, tmp_file,
                  buf, sizeof(buf), &ri) == NULL);
  ASSERT(mg_fetch(ctx, "http://$$$.$$$", tmp_file,
                  buf, sizeof(buf), &ri) == NULL);

  // Failed fetch, pass invalid file name
  ASSERT(mg_fetch(ctx, "http://localhost:" UNUSED_PORT "/data",
                  "/this/file/must/not/exist/ever",
                  buf, sizeof(buf), &ri) == NULL);

  // Successful fetch
  ASSERT((fp = mg_fetch(ctx, "http://localhost:" UNUSED_PORT "/data",
                        tmp_file, buf, sizeof(buf), &ri)) != NULL);
  ASSERT(ri.num_headers == 2);
  ASSERT(!strcmp(ri.request_method, "HTTP/1.1"));
  ASSERT(!strcmp(ri.uri, "200"));
  ASSERT(!strcmp(ri.http_version, "OK"));
  ASSERT((length = ftell(fp)) == (int) strlen(fetch_data));
  fseek(fp, 0, SEEK_SET);
  ASSERT(fread(buf2, 1, length, fp) == (size_t) length);
  ASSERT(memcmp(buf2, fetch_data, length) == 0);
  fclose(fp);

  // Fetch big file, mongoose.c
  ASSERT((fp = mg_fetch(ctx, "http://localhost:" UNUSED_PORT "/mongoose.c",
                        tmp_file, buf, sizeof(buf), &ri)) != NULL);
  ASSERT(mg_stat(fc(ctx), "mongoose.c", &file));
  ASSERT(file.size == ftell(fp));
  ASSERT(!strcmp(ri.request_method, "HTTP/1.1"));

  // Fetch nonexistent file, /blah
  ASSERT((fp = mg_fetch(ctx, "http://localhost:" UNUSED_PORT "/boo",
                        tmp_file, buf, sizeof(buf), &ri)) != NULL);
  ASSERT(!mg_strcasecmp(ri.uri, "404"));
  fclose(fp);

  // Fetch existing inmemory file
  ASSERT((fp = mg_fetch(ctx, "http://localhost:" UNUSED_PORT "/blah",
                        tmp_file, buf, sizeof(buf), &ri)) != NULL);
  ASSERT(!mg_strcasecmp(ri.uri, "200"));
  n = ftell(fp);
  fseek(fp, 0, SEEK_SET);
  printf("%s %d %d [%.*s]\n", __func__, n, (int) feof(fp), n, buf2);
  n = fread(buf2, 1, n, fp);
  printf("%s %d %d [%.*s]\n", __func__, n, (int) feof(fp), n, buf2);
  ASSERT((size_t) ftell(fp) == (size_t) strlen(inmemory_file_data));
  ASSERT(!memcmp(inmemory_file_data, buf2, ftell(fp)));
  fclose(fp);

  remove(tmp_file);
  mg_stop(ctx);
}
Exemplo n.º 29
0
void UploadWindow::handleCommand(int res)
{
	if (res == 1)
	{
		if (!smugMug.isUploading() || AlertWindow::showOkCancelBox(AlertWindow::InfoIcon, "Komodo Drop", 
			"There is an upload in progress, quit anyway?") == 1)
		{
			JUCEApplication::quit();
		}
	}
	else if (res == 2)
	{
		Settings::getInstance()->showSettingsDialog();
	}
	else if (res == 3)
	{
		AlertWindow::showMessageBox(AlertWindow::InfoIcon, "Komodo Drop " + JUCEApplication::getInstance()->getApplicationVersion(), 
			"Created By: Roland Rabien ([email protected])\nBased on JUCE (www.rawmaterialsoftware.com)");
	}
	else if (res == 4)
	{
		setVisible(!isVisible());
	}
	else if (res == 5)
	{
		if (!smugMug.isLoggedIn())
			smugMug.login(Settings::getInstance()->email, Settings::getInstance()->password);

		OwnedArray<Album> albums;
		smugMug.getAlbumList(albums);
		if (albums.size() > 0)
		{
			ComboBox* album = new ComboBox("");
			album->setSize(300, 26);
			album->setVisible(true);

			for (int i = 0; i < albums.size(); i++)
				album->addItem(albums[i]->getDisplayTitle(), i + 1);
			album->setSelectedItemIndex(0);
			
			AlertWindow aw("Komodo Drop", "Delete album:", AlertWindow::InfoIcon);
			aw.addCustomComponent(album);
			aw.addButton("ok", 1);
			aw.addButton("cancel", 2);

			if (aw.runModalLoop() == 1)
			{
				smugMug.deleteAlbum(albums[album->getSelectedId() - 1]->id);
			}
			delete album;
		}
	}
	else if (res == 6)
	{
		if (!smugMug.isLoggedIn())
			smugMug.login(Settings::getInstance()->email, Settings::getInstance()->password);

		OwnedArray<Category> categories;
		smugMug.getCategoryList(categories);
		if (categories.size())
		{
			ComboBox* cats = new ComboBox("");
			cats->setSize(300, 26);
			cats->setVisible(true);

			for (int i = 0; i < categories.size(); i++)
				cats->addItem(categories[i]->title, categories[i]->id + 1);
			cats->setSelectedItemIndex(0);
			
			AlertWindow aw("Komodo Drop", "Delete category:", AlertWindow::InfoIcon);
			aw.addCustomComponent(cats);
			aw.addButton("ok", 1);
			aw.addButton("cancel", 2);

			if (aw.runModalLoop() == 1)
			{
				smugMug.deleteCategory(cats->getSelectedId() - 1);
			}
			delete cats;
		}
	}
	else if (res == 7)
	{
		if (!smugMug.isLoggedIn())
			smugMug.login(Settings::getInstance()->email, Settings::getInstance()->password);

		OwnedArray<Category> categories;
		smugMug.getCategoryList(categories);

		OwnedArray<SubCategory> subCategories;
		smugMug.getSubCategoryList(subCategories);

		if (subCategories.size())
		{
			ComboBox* cats = new ComboBox("");
			cats->setSize(300, 26);
			cats->setVisible(true);

			for (int i = 0; i < subCategories.size(); i++)
			{
				int j;
				for (j = 0; j < categories.size(); j++)
				{
					if (categories[j]->id == subCategories[i]->parentId)
						break;
				}
				cats->addItem(categories[j]->title + " >> " + subCategories[i]->title, subCategories[i]->id + 1);
			}
			cats->setSelectedItemIndex(0);
			
			AlertWindow aw("Komodo Drop", "Delete sub category:", AlertWindow::InfoIcon);
			aw.addCustomComponent(cats);
			aw.addButton("ok", 1);
			aw.addButton("cancel", 2);

			if (aw.runModalLoop() == 1)
			{
				smugMug.deleteSubCategory(cats->getSelectedId() - 1);
			}
			delete cats;
		}
	}
	else if (res == 8)
	{
		if (!smugMug.isLoggedIn())
			smugMug.login(Settings::getInstance()->email, Settings::getInstance()->password);

			AlertWindow aw("Komodo Drop", "Create category:", AlertWindow::InfoIcon);
			aw.addTextEditor("name", "", "category name:");
			aw.addButton("ok", 1);
			aw.addButton("cancel", 2);

			if (aw.runModalLoop() == 1 && aw.getTextEditorContents("name").isNotEmpty())
			{
				smugMug.createCategory(aw.getTextEditorContents("name"));
			}
	}
	else if (res == 9)
	{
		if (!smugMug.isLoggedIn())
			smugMug.login(Settings::getInstance()->email, Settings::getInstance()->password);

		OwnedArray<Category> categories;
		smugMug.getCategoryList(categories);

		if (categories.size())
		{
			ComboBox* cats = new ComboBox("");
			cats->setSize(300, 26);
			cats->setVisible(true);

			for (int i = 0; i < categories.size(); i++)
				cats->addItem(categories[i]->title, categories[i]->id + 1);
			cats->setSelectedItemIndex(0);
			
			AlertWindow aw("Komodo Drop", "Create sub category:", AlertWindow::InfoIcon);
			aw.addCustomComponent(cats);
			aw.addTextEditor("name", "", "sub category name:");
			aw.addButton("ok", 1);
			aw.addButton("cancel", 2);

			if (aw.runModalLoop() == 1 && aw.getTextEditorContents("name").isNotEmpty())
			{
				smugMug.createSubCategory(cats->getSelectedId() - 1, aw.getTextEditorContents("name"));
			}
			delete cats;
		}
	}
	else if (res == 10)
	{
		smugMug.cancelUploads();
	}
	else if (res == 11)
	{
		FileChooser fc("Komodo Drop", File::getSpecialLocation(File::userDocumentsDirectory));
		if (fc.browseForMultipleFilesToOpen())
		{
			const Array<File>& files = fc.getResults();
			StringArray names;

			for (int i = 0; i < files.size(); i++)
				names.add(files[i].getFullPathName());

			filesDropped(names, 0, 0);
		}
	}
	else if (res == 12)
	{
		FileChooser fc("Komodo Drop", File::getSpecialLocation(File::userDocumentsDirectory));
		if (fc.browseForDirectory())
		{
			File dir = fc.getResult();

			Array<File> files;
			StringArray names;
			dir.findChildFiles(files, File::findFiles, false);

			for (int i = 0; i < files.size(); i++)
				names.add(files[i].getFullPathName());

			if (names.size())
				filesDropped(names, 0, 0);
		}
	}
	else if (res == 13)
	{
		FileChooser fc("Komodo Drop", File::getSpecialLocation(File::userDocumentsDirectory));
		if (fc.browseForDirectory())
		{
			File dir = fc.getResult();

			Array<File> files;
			StringArray names;
			dir.findChildFiles(files, File::findFiles, true);

			for (int i = 0; i < files.size(); i++)
				names.add(files[i].getFullPathName());

			if (names.size())
				filesDropped(names, 0, 0);
		}
	}
	else if (res == 19)
	{
		FileChooser fc("Komodo Drop", File::getSpecialLocation(File::userDocumentsDirectory));
		if (fc.browseForDirectory())
		{
			File dir = fc.getResult();
			
			Array<File> folders;
			dir.findChildFiles(folders, File::findDirectories, false);
			
			for (int i = 0; i < folders.size(); i++)
			{
				Array<File> files;
				folders[i].findChildFiles(files, File::findFiles, true);
				
				StringArray names;
				for (int j = 0; j < files.size(); j++)
					names.add(files[j].getFullPathName());
				
				if (names.size())
					filesDropped(names, 0, 0);
			}
		}		
	}
	else if (res == 14)
	{
		smugMug.showLogFile();
	}
	else if (res == 15)
	{
		smugMug.clearLogFile();
	}
	else if (res == 16)
	{
		if (!smugMug.isLoggedIn())
			smugMug.login(Settings::getInstance()->email, Settings::getInstance()->password);

		OwnedArray<Album> albums;
		smugMug.getAlbumList(albums);
		if (albums.size() > 0)
		{
			ComboBox* album = new ComboBox("");
			album->setSize(300, 26);
			album->setVisible(true);

			for (int i = 0; i < albums.size(); i++)
				album->addItem(albums[i]->getDisplayTitle(), i + 1);
			album->setSelectedItemIndex(0);
			
			AlertWindow aw("Komodo Drop", "Delete duplicate images from album:", AlertWindow::InfoIcon);
			aw.addCustomComponent(album);
			aw.addButton("ok", 1);
			aw.addButton("cancel", 2);

			if (aw.runModalLoop() == 1)
			{
				smugMug.deleteDuplicates(albums[album->getSelectedId() - 1]->id);
			}
			delete album;
		}
	}
	else if (res == 17)
	{
		smugMug.showQueue();
	}
	else if (res == 18)
	{
		if (!smugMug.isLoggedIn())
			smugMug.login(Settings::getInstance()->email, Settings::getInstance()->password);

		smugMug.showTopPhotos();
	}
}
Exemplo n.º 30
0
int main(void)
{
	struct sa x = { 14 },*y = &x;
	/* exec sql begin declare section */
		 
		 
		 
		 
		 
		 
		 

		 
		 
		 
		  /* = 1L */ 
	
#line 60 "init.pgc"
 int a = ( int ) 2 ;
 
#line 61 "init.pgc"
 int b = 2 + 2 ;
 
#line 62 "init.pgc"
 int b2 = ( 14 * 7 ) ;
 
#line 63 "init.pgc"
 int d = x . member ;
 
#line 64 "init.pgc"
 int g = fb ( 2 ) ;
 
#line 65 "init.pgc"
 int i = 3 ^ 1 ;
 
#line 66 "init.pgc"
 int j = 1 ? 1 : 2 ;
 
#line 68 "init.pgc"
 int e = y -> member ;
 
#line 69 "init.pgc"
 int c = 10 >> 2 ;
 
#line 70 "init.pgc"
 bool h = 2 || 1 ;
 
#line 71 "init.pgc"
 long iay ;
/* exec sql end declare section */
#line 72 "init.pgc"


	int f=fa();

#ifdef _cplusplus
	/* exec sql begin declare section */
	  /* compile error */
	
#line 78 "init.pgc"
 int k = N : : i ;
/* exec sql end declare section */
#line 79 "init.pgc"

#endif

	ECPGdebug(1, stderr);

	printf("%d %d %d %d %d %d %d %d %d %d %d\n", a, b, b2, c, d, e, f, g, h, i, j);
	iay = 0;
	printf("%ld\n", iay);
	/* exec sql whenever sqlerror  do fa ( ) ; */
#line 87 "init.pgc"

	{ ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select now ( )", ECPGt_EOIT, ECPGt_EORT);
#line 88 "init.pgc"

if (sqlca.sqlcode < 0) fa ( );}
#line 88 "init.pgc"

	/* exec sql whenever sqlerror  do fb ( 20 ) ; */
#line 89 "init.pgc"

	{ ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select now ( )", ECPGt_EOIT, ECPGt_EORT);
#line 90 "init.pgc"

if (sqlca.sqlcode < 0) fb ( 20 );}
#line 90 "init.pgc"

	/* exec sql whenever sqlerror  do fc ( \"50\" ) ; */
#line 91 "init.pgc"

	{ ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select now ( )", ECPGt_EOIT, ECPGt_EORT);
#line 92 "init.pgc"

if (sqlca.sqlcode < 0) fc ( "50" );}
#line 92 "init.pgc"

	/* exec sql whenever sqlerror  do fd ( \"50\" , 1 ) ; */
#line 93 "init.pgc"

	{ ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select now ( )", ECPGt_EOIT, ECPGt_EORT);
#line 94 "init.pgc"

if (sqlca.sqlcode < 0) fd ( "50" , 1 );}
#line 94 "init.pgc"

	/* exec sql whenever sqlerror  do fe ( ENUM0 ) ; */
#line 95 "init.pgc"

	{ ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select now ( )", ECPGt_EOIT, ECPGt_EORT);
#line 96 "init.pgc"

if (sqlca.sqlcode < 0) fe ( ENUM0 );}
#line 96 "init.pgc"

	/* exec sql whenever sqlerror  do sqlnotice ( NULL , 0 ) ; */
#line 97 "init.pgc"

	{ ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select now ( )", ECPGt_EOIT, ECPGt_EORT);
#line 98 "init.pgc"

if (sqlca.sqlcode < 0) sqlnotice ( NULL , 0 );}
#line 98 "init.pgc"

	return 0;
}