コード例 #1
0
bool RenderSVGResourceGradient::applyResource(RenderObject* object, RenderStyle* style, GraphicsContext*& context, unsigned short resourceMode)
{
    ASSERT(object);
    ASSERT(style);
    ASSERT(context);
    ASSERT(resourceMode != ApplyToDefaultMode);

    // Be sure to synchronize all SVG properties on the gradientElement _before_ processing any further.
    // Otherwhise the call to collectGradientAttributes() in createTileImage(), may cause the SVG DOM property
    // synchronization to kick in, which causes removeAllClientsFromCache() to be called, which in turn deletes our
    // GradientData object! Leaving out the line below will cause svg/dynamic-updates/SVG*GradientElement-svgdom* to crash.
    SVGGradientElement* gradientElement = static_cast<SVGGradientElement*>(node());
    if (!gradientElement)
        return false;

    gradientElement->updateAnimatedSVGAttribute(anyQName());

    if (!m_gradient.contains(object))
        m_gradient.set(object, new GradientData);

    GradientData* gradientData = m_gradient.get(object);

    bool isPaintingText = resourceMode & ApplyToTextMode;

    // Create gradient object
    if (!gradientData->gradient) {
        buildGradient(gradientData, gradientElement);

        // CG platforms will handle the gradient space transform for text after applying the
        // resource, so don't apply it here. For non-CG platforms, we want the text bounding
        // box applied to the gradient space transform now, so the gradient shader can use it.
#if PLATFORM(CG)
        if (gradientData->boundingBoxMode && !isPaintingText) {
#else
        if (gradientData->boundingBoxMode) {
#endif
            FloatRect objectBoundingBox = object->objectBoundingBox();
            gradientData->userspaceTransform.translate(objectBoundingBox.x(), objectBoundingBox.y());
            gradientData->userspaceTransform.scaleNonUniform(objectBoundingBox.width(), objectBoundingBox.height());
        }

        gradientData->userspaceTransform.multLeft(gradientData->transform);
        gradientData->gradient->setGradientSpaceTransform(gradientData->userspaceTransform);
    }

    if (!gradientData->gradient)
        return false;

    // Draw gradient
    context->save();

    if (isPaintingText) {
#if PLATFORM(CG)
        if (!createMaskAndSwapContextForTextGradient(context, m_savedContext, m_imageBuffer, object)) {
            context->restore();
            return false;
        }
#endif

        context->setTextDrawingMode(resourceMode & ApplyToFillMode ? cTextFill : cTextStroke);
    }

    const SVGRenderStyle* svgStyle = style->svgStyle();
    ASSERT(svgStyle);

    if (resourceMode & ApplyToFillMode) {
        context->setAlpha(svgStyle->fillOpacity());
        context->setFillGradient(gradientData->gradient);
        context->setFillRule(svgStyle->fillRule());
    } else if (resourceMode & ApplyToStrokeMode) {
        if (svgStyle->vectorEffect() == VE_NON_SCALING_STROKE)
            gradientData->gradient->setGradientSpaceTransform(transformOnNonScalingStroke(object, gradientData->userspaceTransform));
        context->setAlpha(svgStyle->strokeOpacity());
        context->setStrokeGradient(gradientData->gradient);
        SVGRenderSupport::applyStrokeStyleToContext(context, style, object);
    }

    return true;
}

void RenderSVGResourceGradient::postApplyResource(RenderObject* object, GraphicsContext*& context, unsigned short resourceMode)
{
    ASSERT(context);
    ASSERT(resourceMode != ApplyToDefaultMode);

    if (resourceMode & ApplyToTextMode) {
#if PLATFORM(CG)
        // CG requires special handling for gradient on text
        if (m_savedContext && m_gradient.contains(object)) {
            GradientData* gradientData = m_gradient.get(object);

            // Restore on-screen drawing context
            context = m_savedContext;
            m_savedContext = 0;

            FloatRect targetRect;
            gradientData->gradient->setGradientSpaceTransform(clipToTextMask(context, m_imageBuffer, targetRect, object, gradientData));
            context->setFillGradient(gradientData->gradient);

            context->fillRect(targetRect);
            m_imageBuffer.clear();
        }
#else
        UNUSED_PARAM(object);
#endif
    } else {
        if (resourceMode & ApplyToFillMode)
            context->fillPath();
        else if (resourceMode & ApplyToStrokeMode)
            context->strokePath();
    }

    context->restore();
}
コード例 #2
0
// TODO removeme
ossia::net::node_base& AreaComponent::thisNode() const
{
    return node();
}
コード例 #3
0
void RenderMediaControlTimelineContainer::layout()
{
    RenderFlexibleBox::layout();

    LayoutStateDisabler layoutStateDisabler(&view());
    MediaControlTimelineContainerElement* container = static_cast<MediaControlTimelineContainerElement*>(node());
    container->setTimeDisplaysHidden(width().toInt() < minWidthToDisplayTimeDisplays);
}
コード例 #4
0
// induce tail if necessary
Agedge_t *edge(char *tname, Agnode_t *h)
{
    return edge(node(agraphof(h), tname), h);
}
コード例 #5
0
// induce tail/head if necessary
Agedge_t *edge(Agraph_t *g, char *tname, char *hname)
{
    return edge(node(g, tname), node(g, hname));
}
コード例 #6
0
ファイル: FilePlaylistItem.cpp プロジェクト: DonCN/haiku
status_t
FilePlaylistItem::_RestoreFromTrash(vector<entry_ref>* refs,
	vector<BString>* namesInTrash)
{
	char trashPath[B_PATH_NAME_LENGTH];
	status_t err = find_directory(B_TRASH_DIRECTORY, (*refs)[0].device,
		false /*create it*/, trashPath, B_PATH_NAME_LENGTH);
	if (err != B_OK) {
		fprintf(stderr, "failed to find Trash: %s\n", strerror(err));
		return err;
	}
	
	for (vector<entry_ref>::size_type i = 0; i < refs->size(); i++) {
		// construct the entry to the file in the trash
		// TODO: BEntry(const BDirectory* directory, const char* path) is broken!
		//	BEntry entry(trashPath, (*namesInTrash)[i].String());
		BPath path(trashPath, (*namesInTrash)[i].String());
		BEntry entry(path.Path());
		err = entry.InitCheck();
		if (err != B_OK) {
			fprintf(stderr, "failed to init BEntry for %s: %s\n",
				(*namesInTrash)[i].String(), strerror(err));
			return err;
		}
		//entry.GetPath(&path);
		//printf("moving '%s'\n", path.Path());
	
		// construct the folder of the original entry_ref
		node_ref nodeRef;
		nodeRef.device = (*refs)[i].device;
		nodeRef.node = (*refs)[i].directory;
		BDirectory originalDir(&nodeRef);
		err = originalDir.InitCheck();
		if (err != B_OK) {
			fprintf(stderr, "failed to init original BDirectory for "
				"%s: %s\n", (*refs)[i].name, strerror(err));
			return err;
		}
	
		//path.SetTo(&originalDir, fItems[i].name);
		//printf("as '%s'\n", path.Path());
	
		// Reset the name here, the user may have already moved the entry
		// out of the trash via Tracker for example.
		(*namesInTrash)[i] = "";
	
		// Finally, move the entry back into the original folder
		err = entry.MoveTo(&originalDir, (*refs)[i].name);
		if (err != B_OK) {
			fprintf(stderr, "failed to restore entry from trash "
				"%s: %s\n", (*refs)[i].name, strerror(err));
			return err;
		}
	
		// Remove the attribute that helps Tracker restore the entry.
		BNode node(&entry);
		node.RemoveAttr("_trk/original_path");
	}

	return B_OK;
}
コード例 #7
0
ファイル: drawingcursor.cpp プロジェクト: kenhys/gecode
  void
  DrawingCursor::processCurrentNode(void) {
    Gist::VisualNode* n = node();
    double parentX = x - static_cast<double>(n->getOffset());
    double parentY = y - static_cast<double>(Layout::dist_y) + nodeWidth;
    if (!n->isRoot() &&
        (n->getParent(na)->getStatus() == STOP ||
         n->getParent(na)->getStatus() == UNSTOP) )
      parentY -= (nodeWidth-failedWidth)/2;

    double myx = x;
    double myy = y;

    if (n->getStatus() == STOP || n->getStatus() == UNSTOP)
      myy += (nodeWidth-failedWidth)/2;

    if (n != startNode()) {
      if (n->isOnPath())
        painter.setPen(Qt::red);
      else
        painter.setPen(Qt::black);
      // Here we use drawPath instead of drawLine in order to
      // workaround a strange redraw artefact on Windows
      QPainterPath path;
      path.moveTo(myx,myy);
      path.lineTo(parentX,parentY);
      painter.drawPath(path);
    }

    // draw shadow
    if (n->isMarked()) {
      painter.setBrush(Qt::gray);
      painter.setPen(Qt::NoPen);
      if (n->isHidden()) {
        QPointF points[3] = {QPointF(myx+shadowOffset,myy+shadowOffset),
                             QPointF(myx+nodeWidth+shadowOffset,
                                     myy+hiddenDepth+shadowOffset),
                             QPointF(myx-nodeWidth+shadowOffset,
                                     myy+hiddenDepth+shadowOffset),
                            };
        painter.drawConvexPolygon(points, 3);

      } else {
        switch (n->getStatus()) {
        case Gist::SOLVED:
          {
            QPointF points[4] = {QPointF(myx+shadowOffset,myy+shadowOffset),
                                 QPointF(myx+halfNodeWidth+shadowOffset,
                                         myy+halfNodeWidth+shadowOffset),
                                 QPointF(myx+shadowOffset,
                                         myy+nodeWidth+shadowOffset),
                                 QPointF(myx-halfNodeWidth+shadowOffset,
                                         myy+halfNodeWidth+shadowOffset)
                                };
            painter.drawConvexPolygon(points, 4);
          }
          break;
        case Gist::FAILED:
          painter.drawRect(myx-halfFailedWidth+shadowOffset,
                           myy+shadowOffset, failedWidth, failedWidth);
          break;
        case Gist::UNSTOP:
        case Gist::STOP:
          {
            QPointF points[8] = {QPointF(myx+shadowOffset-quarterFailedWidthF,
                                         myy+shadowOffset),
                                 QPointF(myx+shadowOffset+quarterFailedWidthF,
                                         myy+shadowOffset),
                                 QPointF(myx+shadowOffset+halfFailedWidth,
                                         myy+shadowOffset
                                            +quarterFailedWidthF),
                                 QPointF(myx+shadowOffset+halfFailedWidth,
                                         myy+shadowOffset+halfFailedWidth+
                                             quarterFailedWidthF),
                                 QPointF(myx+shadowOffset+quarterFailedWidthF,
                                         myy+shadowOffset+failedWidth),
                                 QPointF(myx+shadowOffset-quarterFailedWidthF,
                                         myy+shadowOffset+failedWidth),
                                 QPointF(myx+shadowOffset-halfFailedWidth,
                                         myy+shadowOffset+halfFailedWidth+
                                             quarterFailedWidthF),
                                 QPointF(myx+shadowOffset-halfFailedWidth,
                                         myy+shadowOffset
                                            +quarterFailedWidthF),
                                };
            painter.drawConvexPolygon(points, 8);
          }
          break;
        case Gist::BRANCH:
          painter.drawEllipse(myx-halfNodeWidth+shadowOffset,
                              myy+shadowOffset, nodeWidth, nodeWidth);
          break;
        case Gist::UNDETERMINED:
          painter.drawEllipse(myx-halfNodeWidth+shadowOffset,
                              myy+shadowOffset, nodeWidth, nodeWidth);
          break;
        }
      }
    }

    painter.setPen(Qt::SolidLine);
    if (n->isHidden()) {
      if (n->hasOpenChildren()) {
        QLinearGradient gradient(myx-nodeWidth,myy,
                                 myx+nodeWidth*1.3,myy+hiddenDepth*1.3);
        if (n->hasSolvedChildren()) {
          gradient.setColorAt(0, white);
          gradient.setColorAt(1, green);
        } else if (n->hasFailedChildren()) {
          gradient.setColorAt(0, white);
          gradient.setColorAt(1, red);          
        } else {
          gradient.setColorAt(0, white);
          gradient.setColorAt(1, QColor(0,0,0));
        }
        painter.setBrush(gradient);
      } else {
        if (n->hasSolvedChildren())
          painter.setBrush(QBrush(green));
        else
          painter.setBrush(QBrush(red));
      }
      
      QPointF points[3] = {QPointF(myx,myy),
                           QPointF(myx+nodeWidth,myy+hiddenDepth),
                           QPointF(myx-nodeWidth,myy+hiddenDepth),
                          };
      painter.drawConvexPolygon(points, 3);
    } else {
      switch (n->getStatus()) {
      case Gist::SOLVED:
        {
          if (n->isCurrentBest(curBest)) {
            painter.setBrush(QBrush(orange));
          } else {
            painter.setBrush(QBrush(green));
          }
          QPointF points[4] = {QPointF(myx,myy),
                               QPointF(myx+halfNodeWidth,myy+halfNodeWidth),
                               QPointF(myx,myy+nodeWidth),
                               QPointF(myx-halfNodeWidth,myy+halfNodeWidth)
                              };
          painter.drawConvexPolygon(points, 4);
        }
        break;
      case Gist::FAILED:
        painter.setBrush(QBrush(red));
        painter.drawRect(myx-halfFailedWidth, myy, failedWidth, failedWidth);
        break;
      case Gist::UNSTOP:
      case Gist::STOP:
        {
          painter.setBrush(n->getStatus() == STOP ? 
                           QBrush(red) : QBrush(green));
          QPointF points[8] = {QPointF(myx-quarterFailedWidthF,myy),
                               QPointF(myx+quarterFailedWidthF,myy),
                               QPointF(myx+halfFailedWidth,
                                       myy+quarterFailedWidthF),
                               QPointF(myx+halfFailedWidth,
                                       myy+halfFailedWidth+
                                           quarterFailedWidthF),
                               QPointF(myx+quarterFailedWidthF,
                                       myy+failedWidth),
                               QPointF(myx-quarterFailedWidthF,
                                       myy+failedWidth),
                               QPointF(myx-halfFailedWidth,
                                       myy+halfFailedWidth+
                                           quarterFailedWidthF),
                               QPointF(myx-halfFailedWidth,
                                       myy+quarterFailedWidthF),
                              };
          painter.drawConvexPolygon(points, 8);
        }
        break;
      case Gist::BRANCH:
        painter.setBrush(n->childrenLayoutIsDone() ? QBrush(blue) : 
                                                     QBrush(white));
        painter.drawEllipse(myx-halfNodeWidth, myy, nodeWidth, nodeWidth);
        break;
      case Gist::UNDETERMINED:
        painter.setBrush(Qt::white);
        painter.drawEllipse(myx-halfNodeWidth, myy, nodeWidth, nodeWidth);
        break;
      }
    }

    if (copies && (n->hasCopy() && !n->hasWorkingSpace())) {
     painter.setBrush(Qt::darkRed);
     painter.drawEllipse(myx, myy, 10.0, 10.0);
    }

    if (copies && n->hasWorkingSpace()) {
     painter.setBrush(Qt::darkYellow);
     painter.drawEllipse(myx, myy + 10.0, 10.0, 10.0);
    }

    if (n->isBookmarked()) {
     painter.setBrush(Qt::black);
     painter.drawEllipse(myx-10-0, myy, 10.0, 10.0);
    }

  }
コード例 #8
0
ファイル: Paladin.cpp プロジェクト: passick/Paladin
void
App::OpenFile(entry_ref ref, int32 line)
{
	if (!ref.name)
		return;
	
	BNode node(&ref);
	BString type;
	if (node.ReadAttrString("BEOS:TYPE",&type) != B_OK)
	{
		update_mime_info(BPath(&ref).Path(),0,0,1);
		node.ReadAttrString("BEOS:TYPE",&type);
	}
	
	if (type.CountChars() > 0)
	{
		if (type == PROJECT_MIME_TYPE || type.FindFirst("text/") != 0)
		{
			be_roster->Launch(&ref);
			return;
		}
	}
	else
	{
		BString extension = BPath(&ref).Path();
		int32 pos = extension.FindLast(".");
		if (pos >= 0)
		{
			extension = extension.String() + pos;
			if (extension.ICompare(".cpp") != 0 &&
				extension.ICompare(".h") != 0 &&
				extension.ICompare(".hpp") != 0 &&
				extension.ICompare(".c") != 0)
			{
				return;
			}
		}
	}
	
//	BMessage msg(B_REFS_RECEIVED);
	BMessage msg(PALEDIT_OPEN_FILE);
	msg.AddRef("refs",&ref);
	if (line >= 0)
		msg.AddInt32("line",line);
	
	if (be_roster->IsRunning(EDITOR_SIGNATURE))
	{
		BMessenger msgr(EDITOR_SIGNATURE);
		msgr.SendMessage(&msg);
	}
	else
	{
		DPath path(gAppPath.GetFolder());
		path.Append("PalEdit");
		
		entry_ref launchref;
		BEntry(path.GetFullPath()).GetRef(&launchref);
		
		if (be_roster->Launch(&launchref,&msg) != B_OK &&
			be_roster->Launch(EDITOR_SIGNATURE,&msg) != B_OK)
			be_roster->Launch(&ref);
	}
}
コード例 #9
0
bool RenderSVGResourceGradient::applyResource(RenderObject* object, RenderStyle* style, GraphicsContext*& context, unsigned short resourceMode)
{
    ASSERT(object);
    ASSERT(style);
    ASSERT(context);
    ASSERT(resourceMode != ApplyToDefaultMode);

    // Be sure to synchronize all SVG properties on the gradientElement _before_ processing any further.
    // Otherwhise the call to collectGradientAttributes() in createTileImage(), may cause the SVG DOM property
    // synchronization to kick in, which causes removeAllClientsFromCache() to be called, which in turn deletes our
    // GradientData object! Leaving out the line below will cause svg/dynamic-updates/SVG*GradientElement-svgdom* to crash.
    SVGGradientElement* gradientElement = toSVGGradientElement(node());
    if (!gradientElement)
        return false;

    if (m_shouldCollectGradientAttributes) {
        gradientElement->synchronizeAnimatedSVGAttribute(anyQName());
        if (!collectGradientAttributes(gradientElement))
            return false;

        m_shouldCollectGradientAttributes = false;
    }

    // Spec: When the geometry of the applicable element has no width or height and objectBoundingBox is specified,
    // then the given effect (e.g. a gradient or a filter) will be ignored.
    FloatRect objectBoundingBox = object->objectBoundingBox();
    if (gradientUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX && objectBoundingBox.isEmpty())
        return false;

    OwnPtr<GradientData>& gradientData = m_gradientMap.add(object, nullptr).iterator->value;
    if (!gradientData)
        gradientData = adoptPtr(new GradientData);

    bool isPaintingText = resourceMode & ApplyToTextMode;

    // Create gradient object
    if (!gradientData->gradient) {
        buildGradient(gradientData.get());

        // CG platforms will handle the gradient space transform for text after applying the
        // resource, so don't apply it here. For non-CG platforms, we want the text bounding
        // box applied to the gradient space transform now, so the gradient shader can use it.
#if USE(CG)
        if (gradientUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX && !objectBoundingBox.isEmpty() && !isPaintingText) {
#else
        if (gradientUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX && !objectBoundingBox.isEmpty()) {
#endif
            gradientData->userspaceTransform.translate(objectBoundingBox.x(), objectBoundingBox.y());
            gradientData->userspaceTransform.scaleNonUniform(objectBoundingBox.width(), objectBoundingBox.height());
        }

        AffineTransform gradientTransform;
        calculateGradientTransform(gradientTransform);

        gradientData->userspaceTransform *= gradientTransform;
        if (isPaintingText) {
            // Depending on font scaling factor, we may need to rescale the gradient here since
            // text painting removes the scale factor from the context.
            AffineTransform additionalTextTransform;
            if (shouldTransformOnTextPainting(object, additionalTextTransform))
                gradientData->userspaceTransform *= additionalTextTransform;
        }
        gradientData->gradient->setGradientSpaceTransform(gradientData->userspaceTransform);
    }

    if (!gradientData->gradient)
        return false;

    // Draw gradient
    context->save();

    if (isPaintingText) {
#if USE(CG)
        if (!createMaskAndSwapContextForTextGradient(context, m_savedContext, m_imageBuffer, object)) {
            context->restore();
            return false;
        }
#endif

        context->setTextDrawingMode(resourceMode & ApplyToFillMode ? TextModeFill : TextModeStroke);
    }

    const SVGRenderStyle* svgStyle = style->svgStyle();
    ASSERT(svgStyle);

    if (resourceMode & ApplyToFillMode) {
        context->setAlpha(svgStyle->fillOpacity());
        context->setFillGradient(gradientData->gradient);
        context->setFillRule(svgStyle->fillRule());
    } else if (resourceMode & ApplyToStrokeMode) {
        if (svgStyle->vectorEffect() == VE_NON_SCALING_STROKE)
            gradientData->gradient->setGradientSpaceTransform(transformOnNonScalingStroke(object, gradientData->userspaceTransform));
        context->setAlpha(svgStyle->strokeOpacity());
        context->setStrokeGradient(gradientData->gradient);
        SVGRenderSupport::applyStrokeStyleToContext(context, style, object);
    }

    return true;
}

void RenderSVGResourceGradient::postApplyResource(RenderObject* object, GraphicsContext*& context, unsigned short resourceMode, const Path* path, const RenderSVGShape* shape)
{
    ASSERT(context);
    ASSERT(resourceMode != ApplyToDefaultMode);

    if (resourceMode & ApplyToTextMode) {
#if USE(CG)
        // CG requires special handling for gradient on text
        GradientData* gradientData;
        if (m_savedContext && (gradientData = m_gradientMap.get(object))) {
            // Restore on-screen drawing context
            context = m_savedContext;
            m_savedContext = 0;

            AffineTransform gradientTransform;
            calculateGradientTransform(gradientTransform);

            FloatRect targetRect;
            gradientData->gradient->setGradientSpaceTransform(clipToTextMask(context, m_imageBuffer, targetRect, object, gradientUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX, gradientTransform));
            context->setFillGradient(gradientData->gradient);

            context->fillRect(targetRect);
            m_imageBuffer.clear();
        }
#else
        UNUSED_PARAM(object);
#endif
    } else {
        if (resourceMode & ApplyToFillMode) {
            if (path)
                context->fillPath(*path);
            else if (shape)
                shape->fillShape(context);
        }
        if (resourceMode & ApplyToStrokeMode) {
            if (path)
                context->strokePath(*path);
            else if (shape)
                shape->strokeShape(context);
        }
    }

    context->restore();
}
コード例 #10
0
ファイル: RenderPart.cpp プロジェクト: 3163504123/phantomjs
RenderBox* RenderPart::embeddedContentBox() const
{
    if (!node() || !widget() || !widget()->isFrameView())
        return 0;
    return toFrameView(widget())->embeddedContentBox();
}
コード例 #11
0
int main(int argc, char *argv[])
{
	cout << "Enter dimension" << endl;
	cin >> dim;
	//dim = 4;
	cout << "Enter number to generate partitions" << endl;
	cin >> num;
	//num = 20;

	//Initializing the array
	p[0] = node(dim);
	p[1] = node(dim);
	p[2] = node(dim);
	possible[0] = node(dim);
	possible[1] = node(dim);

	//Initializing possible with initial possible nodes
	int l=0; //Iterator
	for(int j=dim-1;j>=0;j--)
	{
		int *x = node(dim);
		x[j] = 1;
		delete [] possible[l];
		possible[l] = x;
		l++;
	}

	//Creating List object
	shared_ptr<List> initialList(new List());

	//Inserting 0 node
	initialList->insert_tail(node(dim));

	//pointer initialization
	d = NULL;
	a = NULL;

	//Initilization of results
	res[0] = 1;
	res[1] = 1;
	sum[0] = 0;
	sum[1] = 1;

	int start_s = clock();
	//The main call
	addpart(1,0,dim-1,initialList);
	int stop_s = clock();

	//Printing time
	cout << "Time : " << (stop_s - start_s)/(double)(CLOCKS_PER_SEC)*1000 << endl;

	//Deleting pointer a
	if(a!=NULL)
	{
		delete [] a;
	}

	//Deleting pointer d
	if(d!=NULL)
	{
		delete [] d;
	}

	//Result
	/*cout << "Result : " << endl;
	for(int j=0;j<=num;j++)
	{
		cout << "res["<<j<<"]" << ": " << res[j] << endl;
	}*/

	//Sum
	cout << "Sum : " << endl;

  for(int j=0;j<2000;j++)
	{
		if(j<=num)
		{
			cout << fixed << setprecision(0) << "sum["<<j<<"]" << ": " << sum[j] << endl;
		}

		//Deleting objects from the arrays
		if(p[j]!=NULL)
		{
			delete [] p[j];
		}

		if(possible[j]!=NULL)
		{
			delete [] possible[j];
		}
	}

	//Deleting List instance
  //delete initialList;
	
}
コード例 #12
0
void
ImageFilePanel::SelectionChanged()
{
    entry_ref ref;
    Rewind();

    if (GetNextSelectedRef(&ref) == B_OK) {
        BEntry entry(&ref);
        BNode node(&ref);
        fImageView->ClearViewBitmap();

        if (node.IsFile()) {
            BBitmap* bitmap = BTranslationUtils::GetBitmap(&ref);

            if (bitmap != NULL) {
                BRect dest(fImageView->Bounds());
                if (bitmap->Bounds().Width() > bitmap->Bounds().Height()) {
                    dest.InsetBy(0, (dest.Height() + 1
                                     - ((bitmap->Bounds().Height() + 1)
                                        / (bitmap->Bounds().Width() + 1)
                                        * (dest.Width() + 1))) / 2);
                } else {
                    dest.InsetBy((dest.Width() + 1
                                  - ((bitmap->Bounds().Width() + 1)
                                     / (bitmap->Bounds().Height() + 1)
                                     * (dest.Height() + 1))) / 2, 0);
                }
                fImageView->SetViewBitmap(bitmap, bitmap->Bounds(), dest,
                                          B_FOLLOW_LEFT | B_FOLLOW_TOP, 0);

                BString resolution;
                resolution << B_TRANSLATE("Resolution: ")
                           << (int)(bitmap->Bounds().Width() + 1)
                           << "x" << (int)(bitmap->Bounds().Height() + 1);
                fResolutionView->SetText(resolution.String());
                delete bitmap;

                BNodeInfo nodeInfo(&node);
                char type[B_MIME_TYPE_LENGTH];
                if (nodeInfo.GetType(type) == B_OK) {
                    BMimeType mimeType(type);
                    mimeType.GetShortDescription(type);
                    // if this fails, the MIME type will be displayed
                    fImageTypeView->SetText(type);
                } else {
                    BMimeType refType;
                    if (BMimeType::GuessMimeType(&ref, &refType) == B_OK) {
                        refType.GetShortDescription(type);
                        // if this fails, the MIME type will be displayed
                        fImageTypeView->SetText(type);
                    } else
                        fImageTypeView->SetText("");
                }
            }
        } else {
            fResolutionView->SetText("");
            fImageTypeView->SetText("");
        }
        fImageView->Invalidate();
        fResolutionView->Invalidate();
    }

    BFilePanel::SelectionChanged();
}
コード例 #13
0
HTMLMediaElement* RenderMedia::mediaElement() const
{ 
    return toMediaElement(node()); 
}
コード例 #14
0
void add(int u,int v,int len){
    G[u].push_back(node(v,len));
}
コード例 #15
0
LayoutUnit RenderTextControlMultiLine::computeControlHeight(LayoutUnit lineHeight, LayoutUnit nonContentHeight) const
{
    return lineHeight * static_cast<HTMLTextAreaElement*>(node())->rows() + nonContentHeight;
}
コード例 #16
0
TEST(AggregateTests, HashDistinctTest) {
  /*
   * SELECT d, a, b, c FROM table GROUP BY a, b, c, d;
   */

  const int tuple_count = TESTS_TUPLES_PER_TILEGROUP;

  // Create a table and wrap it in logical tiles
  auto &txn_manager = concurrency::TransactionManager::GetInstance();
  auto txn = txn_manager.BeginTransaction();
  auto txn_id = txn->GetTransactionId();
  std::unique_ptr<storage::DataTable> data_table(
      ExecutorTestsUtil::CreateTable(tuple_count, false));
  ExecutorTestsUtil::PopulateTable(txn, data_table.get(),
                                   2 * tuple_count, false,
                                   true,
                                   true);  // let it be random
  txn_manager.CommitTransaction();

  std::unique_ptr<executor::LogicalTile> source_logical_tile1(
      executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(0),
                                                  txn_id));

  std::unique_ptr<executor::LogicalTile> source_logical_tile2(
      executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(1),
                                                  txn_id));

  // (1-5) Setup plan node

  // 1) Set up group-by columns
  std::vector<oid_t> group_by_columns = {0, 1, 2, 3};

  // 2) Set up project info
  planner::ProjectInfo::DirectMapList direct_map_list = {
      {0, {0, 3}}, {1, {0, 0}}, {2, {0, 1}}, {3, {0, 2}}};
  auto proj_info = new planner::ProjectInfo(planner::ProjectInfo::TargetList(),
                                            std::move(direct_map_list));

  // 3) Set up unique aggregates (empty)
  std::vector<planner::AggregatePlan::AggTerm> agg_terms;

  // 4) Set up predicate (empty)
  expression::AbstractExpression* predicate = nullptr;

  // 5) Create output table schema
  auto data_table_schema = data_table.get()->GetSchema();
  std::vector<oid_t> set = {3, 0, 1, 2};
  std::vector<catalog::Column> columns;
  for (auto column_index : set) {
    columns.push_back(data_table_schema->GetColumn(column_index));
  }

  auto output_table_schema = new catalog::Schema(columns);

  // OK) Create the plan node
  planner::AggregatePlan node(proj_info, predicate, std::move(agg_terms),
                              std::move(group_by_columns), output_table_schema,
                              AGGREGATE_TYPE_HASH);

  // Create and set up executor
  auto txn2 = txn_manager.BeginTransaction();
  std::unique_ptr<executor::ExecutorContext> context(
      new executor::ExecutorContext(txn2));

  executor::AggregateExecutor executor(&node, context.get());
  MockExecutor child_executor;
  executor.AddChild(&child_executor);

  EXPECT_CALL(child_executor, DInit()).WillOnce(Return(true));

  EXPECT_CALL(child_executor, DExecute())
      .WillOnce(Return(true))
      .WillOnce(Return(true))
      .WillOnce(Return(false));

  EXPECT_CALL(child_executor, GetOutput())
      .WillOnce(Return(source_logical_tile1.release()))
      .WillOnce(Return(source_logical_tile2.release()));

  EXPECT_TRUE(executor.Init());

  EXPECT_TRUE(executor.Execute());
  txn_manager.CommitTransaction();

  /* Verify result */
  std::unique_ptr<executor::LogicalTile> result_tile(executor.GetOutput());
  EXPECT_TRUE(result_tile.get() != nullptr);

  for (auto tuple_id : *result_tile) {
    int colA = ValuePeeker::PeekAsInteger(result_tile->GetValue(tuple_id, 1));
    (void)colA;
  }
}
コード例 #17
0
ファイル: FilePlaylistItem.cpp プロジェクト: DonCN/haiku
status_t
FilePlaylistItem::_MoveIntoTrash(vector<entry_ref>* refs,
	vector<BString>* namesInTrash)
{
	char trashPath[B_PATH_NAME_LENGTH];
	status_t err = find_directory(B_TRASH_DIRECTORY, (*refs)[0].device,
		true /*create it*/, trashPath, B_PATH_NAME_LENGTH);
	if (err != B_OK) {
		fprintf(stderr, "failed to find Trash: %s\n", strerror(err));
		return err;
	}

	BDirectory trashDir(trashPath);
	err = trashDir.InitCheck();
	if (err != B_OK) {
		fprintf(stderr, "failed to init BDirectory for %s: %s\n",
			trashPath, strerror(err));
		return err;
	}

	for (vector<entry_ref>::size_type i = 0; i < refs->size(); i++) {
		BEntry entry(&(*refs)[i]);
		err = entry.InitCheck();
		if (err != B_OK) {
			fprintf(stderr, "failed to init BEntry for %s: %s\n",
				(*refs)[i].name, strerror(err));
			return err;
		}
	
		// Find a unique name for the entry in the trash
		(*namesInTrash)[i] = (*refs)[i].name;
		int32 uniqueNameIndex = 1;
		while (true) {
			BEntry test(&trashDir, (*namesInTrash)[i].String());
			if (!test.Exists())
				break;
			(*namesInTrash)[i] = (*refs)[i].name;
			(*namesInTrash)[i] << ' ' << uniqueNameIndex;
			uniqueNameIndex++;
		}
	
		// Remember the original path
		BPath originalPath;
		entry.GetPath(&originalPath);
	
		// Finally, move the entry into the trash
		err = entry.MoveTo(&trashDir, (*namesInTrash)[i].String());
		if (err != B_OK) {
			fprintf(stderr, "failed to move entry into trash %s: %s\n",
				trashPath, strerror(err));
			return err;
		}
	
		// Allow Tracker to restore this entry
		BNode node(&entry);
		BString originalPathString(originalPath.Path());
		node.WriteAttrString("_trk/original_path", &originalPathString);
	}

	return B_OK;
}
コード例 #18
0
TEST(AggregateTests, PlainSumCountDistinctTest) {
  /*
   * SELECT SUM(a), COUNT(b), COUNT(DISTINCT b) from table
   */
  const int tuple_count = TESTS_TUPLES_PER_TILEGROUP;

  // Create a table and wrap it in logical tiles
  auto &txn_manager = concurrency::TransactionManager::GetInstance();
  auto txn = txn_manager.BeginTransaction();
  auto txn_id = txn->GetTransactionId();

  std::unique_ptr<storage::DataTable> data_table(
      ExecutorTestsUtil::CreateTable(tuple_count, false));
  ExecutorTestsUtil::PopulateTable(txn, data_table.get(),
                                   2 * tuple_count, false,
                                   true, true);
  txn_manager.CommitTransaction();

  std::unique_ptr<executor::LogicalTile> source_logical_tile1(
      executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(0),
                                                  txn_id));

  std::unique_ptr<executor::LogicalTile> source_logical_tile2(
      executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(1),
                                                  txn_id));

  // (1-5) Setup plan node

  // 1) Set up group-by columns
  std::vector<oid_t> group_by_columns;

  // 2) Set up project info
  planner::ProjectInfo::DirectMapList direct_map_list = {
      {0, {1, 0}}, {1, {1, 1}}, {2, {1, 2}}};

  auto proj_info = new planner::ProjectInfo(planner::ProjectInfo::TargetList(),
                                            std::move(direct_map_list));

  // 3) Set up unique aggregates
  std::vector<planner::AggregatePlan::AggTerm> agg_terms;
  planner::AggregatePlan::AggTerm sumA(EXPRESSION_TYPE_AGGREGATE_SUM,
                                       expression::TupleValueFactory(0, 0),
                                       false);
  planner::AggregatePlan::AggTerm countB(EXPRESSION_TYPE_AGGREGATE_COUNT,
                                         expression::TupleValueFactory(0, 1),
                                         false);  // Flag distinct
  planner::AggregatePlan::AggTerm countDistinctB(
      EXPRESSION_TYPE_AGGREGATE_COUNT, expression::TupleValueFactory(0, 1),
      true);  // Flag distinct
  agg_terms.push_back(sumA);
  agg_terms.push_back(countB);
  agg_terms.push_back(countDistinctB);

  // 4) Set up predicate (empty)
  expression::AbstractExpression* predicate = nullptr;

  // 5) Create output table schema
  auto data_table_schema = data_table.get()->GetSchema();
  std::vector<oid_t> set = {0, 1, 1};
  std::vector<catalog::Column> columns;
  for (auto column_index : set) {
    columns.push_back(data_table_schema->GetColumn(column_index));
  }
  auto output_table_schema = new catalog::Schema(columns);

  // OK) Create the plan node
  planner::AggregatePlan node(proj_info, predicate, std::move(agg_terms),
                              std::move(group_by_columns), output_table_schema,
                              AGGREGATE_TYPE_PLAIN);

  // Create and set up executor
  auto txn2 = txn_manager.BeginTransaction();
  std::unique_ptr<executor::ExecutorContext> context(
      new executor::ExecutorContext(txn2));

  executor::AggregateExecutor executor(&node, context.get());
  MockExecutor child_executor;
  executor.AddChild(&child_executor);

  EXPECT_CALL(child_executor, DInit()).WillOnce(Return(true));

  EXPECT_CALL(child_executor, DExecute())
      .WillOnce(Return(true))
      .WillOnce(Return(true))
      .WillOnce(Return(false));

  EXPECT_CALL(child_executor, GetOutput())
      .WillOnce(Return(source_logical_tile1.release()))
      .WillOnce(Return(source_logical_tile2.release()));

  EXPECT_TRUE(executor.Init());

  EXPECT_TRUE(executor.Execute());

  txn_manager.CommitTransaction();

  /* Verify result */
  std::unique_ptr<executor::LogicalTile> result_tile(executor.GetOutput());
  EXPECT_TRUE(result_tile.get() != nullptr);
  EXPECT_TRUE(result_tile->GetValue(0, 0)
                  .OpEquals(ValueFactory::GetIntegerValue(50))
                  .IsTrue());
  EXPECT_TRUE(result_tile->GetValue(0, 1)
                  .OpEquals(ValueFactory::GetIntegerValue(10))
                  .IsTrue());

  EXPECT_TRUE(result_tile->GetValue(0, 2)
                  .OpLessThanOrEqual(ValueFactory::GetIntegerValue(3))
                  .IsTrue());
}
コード例 #19
0
// Main code:
int main(int argc,char* argv[])
{
	// The joint handles and proximity sensor handles are given in the argument list
	// (when V-REP launches this executable, V-REP will also provide the argument list)
	int leftMotorHandle;
	int rightMotorHandle;
	int sensorHandle;
	if (argc>=4)
	{
		leftMotorHandle=atoi(argv[1]);
		rightMotorHandle=atoi(argv[2]);
		sensorHandle=atoi(argv[3]);
	}
	else
	{
		printf("Indicate following arguments: 'leftMotorHandle rightMotorHandle sensorHandle'!\n");
		sleep(5000);
		return 0;
	}

	// Create a ROS node. The name has a random component: 
	int _argc = 0;
	char** _argv = NULL;
	struct timeval tv;
	unsigned int timeVal=0;
	if (gettimeofday(&tv,NULL)==0)
		timeVal=(tv.tv_sec*1000+tv.tv_usec/1000)&0x00ffffff;
	std::string nodeName("rosBubbleRob");
	std::string randId(boost::lexical_cast<std::string>(timeVal+int(999999.0f*(rand()/(float)RAND_MAX))));
	nodeName+=randId;		
	ros::init(_argc,_argv,nodeName.c_str());

	if(!ros::master::check())
		return(0);
	
	ros::NodeHandle node("~");	
	printf("rosBubbleRob just started with node name %s\n",nodeName.c_str());

	// 1. Let's subscribe to V-REP's info stream (that stream is the only one enabled by default,
	// and the only one that can run while no simulation is running):
	ros::Subscriber subInfo=node.subscribe("/vrep/info",1,infoCallback);

	// 2. Request V-REP to launch a publisher for the BubbleRob's proximity sensor:
	ros::ServiceClient client_enablePublisher=node.serviceClient<vrep_common::simRosEnablePublisher>("/vrep/simRosEnablePublisher");
	vrep_common::simRosEnablePublisher srv_enablePublisher;
	srv_enablePublisher.request.topicName="proxData"+randId; // the requested topic name
	srv_enablePublisher.request.queueSize=1; // the requested publisher queue size (on V-REP side)
	srv_enablePublisher.request.streamCmd=simros_strmcmd_read_proximity_sensor; // the requested publisher type
	srv_enablePublisher.request.auxInt1=sensorHandle; // some additional information the publisher needs (what proximity sensor)
    if ( client_enablePublisher.call(srv_enablePublisher)&&(srv_enablePublisher.response.effectiveTopicName.length()!=0) )
	{ 	// ok, the service call was ok, and the publisher was succesfully started on V-REP side
		// V-REP is now streaming the proximity sensor data!

		// 3. Let's subscribe to that proximity sensor data:
		std::string topicName("/vrep/");
		topicName+=srv_enablePublisher.response.effectiveTopicName; // Make sure to use the returned topic name, not the requested one (can be same)
		ros::Subscriber sub=node.subscribe(topicName.c_str(),1,sensorCallback);

		// 4. Let's tell V-REP to subscribe to the motor speed topic (publisher to that topic will be created further down):
		ros::ServiceClient client_enableSubscriber=node.serviceClient<vrep_common::simRosEnableSubscriber>("/vrep/simRosEnableSubscriber");
		vrep_common::simRosEnableSubscriber srv_enableSubscriber;

		srv_enableSubscriber.request.topicName="/"+nodeName+"/wheels"; // the topic name
		srv_enableSubscriber.request.queueSize=1; // the subscriber queue size (on V-REP side)
		srv_enableSubscriber.request.streamCmd=simros_strmcmd_set_joint_state; // the subscriber type
		if ( client_enableSubscriber.call(srv_enableSubscriber)&&(srv_enableSubscriber.response.subscriberID!=-1) )
		{	// ok, the service call was ok, and the subscriber was succesfully started on V-REP side
			// V-REP is now listening to the desired motor joint states

			// 5. Let's prepare a publisher of those motor speeds:
			ros::Publisher motorSpeedPub=node.advertise<vrep_common::JointSetStateData>("wheels",1);

			// 6. Finally we have the control loop:
			float driveBackStartTime=-99.0f;
			while (ros::ok()&&simulationRunning)
			{ // this is the control loop (very simple, just as an example)
				vrep_common::JointSetStateData motorSpeeds;
				float desiredLeftMotorSpeed;
				float desiredRightMotorSpeed;
				if (simulationTime-driveBackStartTime<3.0f)
				{ // driving backwards while slightly turning:
					desiredLeftMotorSpeed=-3.1415*0.5;
					desiredRightMotorSpeed=-3.1415*0.25;
				}
				else
				{ // going forward:
					desiredLeftMotorSpeed=3.1415;
					desiredRightMotorSpeed=3.1415;
					if (sensorTrigger)
						driveBackStartTime=simulationTime; // We detected something, and start the backward mode
					sensorTrigger=false;
				}

				// publish the motor speeds:
				motorSpeeds.handles.data.push_back(leftMotorHandle);
				motorSpeeds.handles.data.push_back(rightMotorHandle);
				motorSpeeds.setModes.data.push_back(2); // 2 is the speed mode
				motorSpeeds.setModes.data.push_back(2);
				motorSpeeds.values.data.push_back(desiredLeftMotorSpeed);
				motorSpeeds.values.data.push_back(desiredRightMotorSpeed);
				motorSpeedPub.publish(motorSpeeds);

				// handle ROS messages:
				ros::spinOnce();

				// sleep a bit:
				usleep(5000);
			}
		}
	}
	ros::shutdown();
	printf("rosBubbleRob just ended!\n");
	return(0);
}
コード例 #20
0
ファイル: b_plus_tree.cpp プロジェクト: AlecWong/DBSQL
void BPlusTree::_remove(Block blk, AttrType k) {
    Node node(blk);
    int i;
    
    std::cout << "BPlusTree::_remove == k " << k.datai << std::endl;
    std::cout << "BPlusTree::_remove == blk.pos " << blk.pos << std::endl;
    
    // delete the corresponding p, k at first
    for( i = 0; i < node.getKSize(); i++ ) {
        if( node.getK(i) == k ) {
            node.remove(k, node.getP(i), i);
            break;
        }
    }
    
    // then check whether the size of the node is too small
    bool isRootWithSoleChild =  node.isRoot() && !node.isLeaf() && node.getPSize() == 1;
    
    bool isNotRootAndTooSmall = ( node.isLeaf() && node.getKSize() < fanout / 2 ) || ( !node.isLeaf() && node.getKSize() < (fanout+1) / 2 );
    
    isNotRootAndTooSmall = isNotRootAndTooSmall && node.isRoot();
    
    
    if( isRootWithSoleChild ) { // If the root node has only one pointer after deletion, it is deleted and the sole child becomes the root.
        Block soleChildBlk;
        bufferManager->getBlock(filename, node.getP(0), soleChildBlk);
        Node soleChildNode(soleChildBlk);
        soleChildNode.setRoot(true);
        setRootNode(soleChildNode);
        setRootPos(soleChildBlk.getPos());
        soleChildNode.write2Blk(soleChildBlk, typeId, strLen, bufferManager);
        bufferManager->deleteBlock(blk);
        
        return;
    }
    else if( isNotRootAndTooSmall ) {
        Block parentBlk;
        Block siblingBlk;
        Node siblingNode;
        AttrType nk;
        
        std::cout << "isNotRootAndTooSmall" << std::endl;
        
        std::cout << "stk.top() = " << stk.top() << std::endl;
        
        stk.pop();
        
        std::cout << "parentBlk pos = " << stk.size() << std::endl;
        
        bufferManager->getBlock(filename, stk.top(), parentBlk);
        //stk.pop();
        Node parentNode(parentBlk);
        
        std::cout << "f**k" << std::endl;
        
        // find sibling
        bool isLeftSibling = true;
        int siblingPos;
        
        for( i = 0; i < parentNode.getPSize(); i++ ) {
            if( parentNode.getP(i) == blk.getPos() ) {
                if( i > 0 ) {
                    siblingPos = parentNode.getP(i-1);
                    nk = parentNode.getK(i);
                }
                else {
                    siblingPos = parentNode.getP(i+1);
                    nk = parentNode.getK(i);
                    isLeftSibling = false;
                }
                
                std::cout << "siblingPos " << siblingPos/BLOCK_SIZE << std::endl;
                
                bufferManager->getBlock(filename, siblingPos, siblingBlk);
                siblingNode.resetByBlock(siblingBlk);
                break;
            }
        }
        
        std::cout << "success up to now" << std::endl;
        
        
        
        // merge
        if( !isLeftSibling ) {
            std::swap(node, siblingNode);
            std::swap(blk, siblingBlk);
        }
        
        if( siblingNode.isLeaf() ) {
            siblingNode.popP();
        }
        else {
            siblingNode.appendK(nk);
        }
        
        for( i = 0; i < node.getPSize(); i++ ) {
            siblingNode.appendP(node.getP(i));
            if( i < node.getPSize() - 1 ) {
                siblingNode.appendK(node.getK(i));
            }
        }
        
        for( i = 0; i < siblingNode.getPSize(); i++ ) {
            std::cout << "siblingNode.getP[" << i << "] = " << siblingNode.getP(i) << std::endl;
        }
        
        for( i = 0; i < siblingNode.getKSize(); i++ ) {
            std::cout << "siblingNode.getK[" << i << "] = " << siblingNode.getK(i).datai << std::endl;
        }
        
        if( siblingNode.getPSize() <= fanout ) { // can be merged
            std::cout << "siblingNode.write2Blk -- siblingBlk.pos[] " << siblingBlk.pos << std::endl;
            
            
            
            // siblingNode.write2Blk(siblingBlk, typeId, strLen, bufferManager);
            // bufferManager->deleteBlock(blk);
            siblingNode.write2Blk(blk, typeId, strLen, bufferManager);
            bufferManager->deleteBlock(siblingBlk);
            
            
            _remove(parentBlk, nk);
        }
        else { // split
            Node n1(false, false), n2(false, false);
            
            for( i = 0; i < (siblingNode.getPSize() + 1) / 2 - 1; i++ ) {
                n1.appendK(siblingNode.getK(i));
                n1.appendP(siblingNode.getP(i));
            }
            
            n1.appendP(siblingNode.getP(i));
            for( i = (siblingNode.getPSize() + 1) / 2; i < (siblingNode.getPSize() + 1) / 2; i++ ) {
                n2.appendK(siblingNode.getK(i));
                n2.appendP(siblingNode.getP(i));
            }
            
            n2.appendP(siblingNode.getP(i));
            
            n1.write2Blk(siblingBlk, typeId, strLen, bufferManager);
            n2.write2Blk(blk, typeId, strLen, bufferManager);
            
            if( !isLeftSibling ) {
                std::swap(blk, siblingBlk);
            }
        }
    }
    else {
        node.write2Blk(blk, typeId, strLen, bufferManager);
    }
}
コード例 #21
0
int main(int argc, const char** argv)
{
    if (argc < 2)
    {
        std::cerr << "Usage: " << argv[0] << " <node-id>" << std::endl;
        return 1;
    }

    const int self_node_id = std::stoi(argv[1]);

    uavcan::Node<NodeMemoryPoolSize> node(getCanDriver(), getSystemClock());
    node.setNodeID(self_node_id);
    node.setName("org.uavcan.tutorial.configuree");

    const int node_start_res = node.start();
    if (node_start_res < 0)
    {
        throw std::runtime_error("Failed to start the node; error: " + std::to_string(node_start_res));
    }

    /*
     * This would be our configuration storage.
     */
    static struct Params
    {
        unsigned foo = 42;
        float bar = 0.123456F;
        double baz = 1e-5;
        std::string booz = "Hello world!";
    } configuration;

    /*
     * Now, we need to define some glue logic between the server (below) and our configuration storage (above).
     * This is done via the interface uavcan::IParamManager.
     */
    class : public uavcan::IParamManager
    {
        void getParamNameByIndex(Index index, Name& out_name) const override
        {
            if (index == 0) { out_name = "foo"; }
            if (index == 1) { out_name = "bar"; }
            if (index == 2) { out_name = "baz"; }
            if (index == 3) { out_name = "booz"; }
        }

        void assignParamValue(const Name& name, const Value& value) override
        {
            if (name == "foo")
            {
                /*
                 * Parameter "foo" is an integer, so we accept only integer values here.
                 */
                if (value.is(uavcan::protocol::param::Value::Tag::integer_value))
                {
                    configuration.foo = *value.as<uavcan::protocol::param::Value::Tag::integer_value>();
                }
            }
            else if (name == "bar")
            {
                /*
                 * Parameter "bar" is a floating point, so we accept only float values here.
                 */
                if (value.is(uavcan::protocol::param::Value::Tag::real_value))
                {
                    configuration.bar = *value.as<uavcan::protocol::param::Value::Tag::real_value>();
                }
            }
            else if (name == "baz")
            {
                /*
                 * Ditto
                 */
                if (value.is(uavcan::protocol::param::Value::Tag::real_value))
                {
                    configuration.baz = *value.as<uavcan::protocol::param::Value::Tag::real_value>();
                }
            }
            else if (name == "booz")
            {
                /*
                 * Parameter "booz" is a string, so we take only strings.
                 */
                if (value.is(uavcan::protocol::param::Value::Tag::string_value))
                {
                    configuration.booz = value.as<uavcan::protocol::param::Value::Tag::string_value>()->c_str();
                }
            }
            else
            {
                std::cout << "Can't assign parameter: " << name.c_str() << std::endl;
            }
        }

        void readParamValue(const Name& name, Value& out_value) const override
        {
            if (name == "foo")
            {
                out_value.to<uavcan::protocol::param::Value::Tag::integer_value>() = configuration.foo;
            }
            else if (name == "bar")
            {
                out_value.to<uavcan::protocol::param::Value::Tag::real_value>() = configuration.bar;
            }
            else if (name == "baz")
            {
                out_value.to<uavcan::protocol::param::Value::Tag::real_value>() = configuration.baz;
            }
            else if (name == "booz")
            {
                out_value.to<uavcan::protocol::param::Value::Tag::string_value>() = configuration.booz.c_str();
            }
            else
            {
                std::cout << "Can't read parameter: " << name.c_str() << std::endl;
            }
        }

        int saveAllParams() override
        {
            std::cout << "Save - this implementation does not require any action" << std::endl;
            return 0;     // Zero means that everything is fine.
        }

        int eraseAllParams() override
        {
            std::cout << "Erase - all params reset to default values" << std::endl;
            configuration = Params();
            return 0;
        }

        /**
         * Note that this method is optional. It can be left unimplemented.
         */
        void readParamDefaultMaxMin(const Name& name, Value& out_def,
                                    NumericValue& out_max, NumericValue& out_min) const override
        {
            if (name == "foo")
            {
                out_def.to<uavcan::protocol::param::Value::Tag::integer_value>() = Params().foo;
                out_max.to<uavcan::protocol::param::NumericValue::Tag::integer_value>() = 9000;
                out_min.to<uavcan::protocol::param::NumericValue::Tag::integer_value>() = 0;
            }
            else if (name == "bar")
            {
                out_def.to<uavcan::protocol::param::Value::Tag::real_value>() = Params().bar;
                out_max.to<uavcan::protocol::param::NumericValue::Tag::real_value>() = 1;
                out_min.to<uavcan::protocol::param::NumericValue::Tag::real_value>() = 0;
            }
            else if (name == "baz")
            {
                out_def.to<uavcan::protocol::param::Value::Tag::real_value>() = Params().baz;
                out_max.to<uavcan::protocol::param::NumericValue::Tag::real_value>() = 1;
                out_min.to<uavcan::protocol::param::NumericValue::Tag::real_value>() = 0;
            }
            else if (name == "booz")
            {
                out_def.to<uavcan::protocol::param::Value::Tag::string_value>() = Params().booz.c_str();
                std::cout << "Limits for 'booz' are not defined" << std::endl;
            }
            else
            {
                std::cout << "Can't read the limits for parameter: " << name.c_str() << std::endl;
            }
        }
    } param_manager;

    /*
     * Initializing the configuration server.
     * A pointer to the glue logic object is passed to the method start().
     */
    uavcan::ParamServer server(node);

    const int server_start_res = server.start(&param_manager);
    if (server_start_res < 0)
    {
        throw std::runtime_error("Failed to start ParamServer: " + std::to_string(server_start_res));
    }

    /*
     * Now, this node can be reconfigured via UAVCAN. Awesome.
     * Many embedded applications require a restart before the new configuration settings can
     * be applied, so it is highly recommended to also support the remote restart service.
     */
    class : public uavcan::IRestartRequestHandler
    {
        bool handleRestartRequest(uavcan::NodeID request_source) override
        {
            std::cout << "Got a remote restart request from " << int(request_source.get()) << std::endl;
            /*
             * We won't really restart, so return 'false'.
             * Returning 'true' would mean that we're going to restart for real.
             * Note that it is recognized that some nodes may not be able to respond to the
             * restart request (e.g. if they restart immediately from the service callback).
             */
            return false;
        }
    } restart_request_handler;

    /*
     * Installing the restart request handler.
     */
    node.setRestartRequestHandler(&restart_request_handler); // Done.

    /*
     * Running the node.
     */
    node.setModeOperational();
    while (true)
    {
        const int res = node.spin(uavcan::MonotonicDuration::getInfinite());
        if (res < 0)
        {
            std::cerr << "Transient failure: " << res << std::endl;
        }
    }
}
コード例 #22
0
ファイル: b_plus_tree.cpp プロジェクト: AlecWong/DBSQL
void BPlusTree::insert(const AttrType &k, int p) {
    int i;
    int blkPos = _findLeaf(k);
    
    std::cout << "insert blkPos" << blkPos/BLOCK_SIZE << std::endl;
    //system("pause");
    
    Block oldBlk;
    bufferManager->getBlock(filename, blkPos, oldBlk);
    Node node(oldBlk);
    
    // first insert k,p into the corresponding leaf node
    
    if( !node.getKSize() ) {
        node.appendK(k);
        node.appendP(p);
        node.appendP(-1); // has problem here
    } else {
        for( i = 0; i < node.getKSize(); i++ ) {
            
            if( k < node.getK(i) ) {
                node.insert(k, p, i);
                break;
            }
        }
        if( i == node.getKSize() ) {
            //std::cout << "k " << k.datai << std::endl;
            //std::cout << "node.getK(i) " << node.getK(i-1).datai << std::endl;
            node.insert(k, p, i);
        }
    }
    
    
    if( node.getKSize() < fanout ) {
        std::cout << " node.getKSize() < fanout " << std::endl;
        node.write2Blk(oldBlk, typeId, strLen, bufferManager);
    }
    else { // need to split
        Node n1(false, true), n2(false, true);
        Block newBlk = bufferManager->newBlock(filename);
        AttrType mid;
        
        n1.setRoot(node.isRoot());
        n2.setRoot(node.isRoot());
        
        n1.setLeaf(node.isLeaf());
        n2.setLeaf(node.isLeaf());
        
        for( i = 0; i < (fanout + 1) / 2; i++ ) {
            n1.appendK(node.getK(i));
            n1.appendP(node.getP(i));
        }
        n1.appendP(newBlk.pos); // here is problem!
        mid = node.getK(i);
        for( i = (fanout + 1) / 2; i < fanout; i++ ) {
            n2.appendK(node.getK(i));
            n2.appendP(node.getP(i));
        }
        n2.appendP(node.getP(i));
        
        n1.write2Blk(oldBlk, typeId, strLen, bufferManager);
        n2.write2Blk(newBlk, typeId, strLen, bufferManager);
        
        std::cout << "oldBlk " << oldBlk.pos/BLOCK_SIZE << std::endl;
        std::cout << "newBlk " << newBlk.pos/BLOCK_SIZE << std::endl;
        std::cout << "middata " << mid.datai << std::endl;
        
        _insertNewBlk(oldBlk, mid, newBlk);
    }
}
コード例 #23
0
// induce head if necessary
Agedge_t *edge(Agnode_t *t, char *hname)
{
    return edge(t, node(agraphof(t), hname));
}
コード例 #24
0
ファイル: find_grasps.cpp プロジェクト: Delft-APC/agile_grasp
int main(int argc, char** argv)
{
  // initialize ROS
  ros::init(argc, argv, "find_grasps");
  ros::NodeHandle node("~");
  
  GraspLocalizer::Parameters params;
  
  // camera transforms (poses)
  Eigen::Matrix4d base_tf, sqrt_tf;
  base_tf <<  0, 0.445417, 0.895323, 0.215, 
              1, 0, 0, -0.015, 
              0, 0.895323, -0.445417, 0.23, 
              0, 0, 0, 1;
  sqrt_tf <<  0.9366, -0.0162, 0.3500, -0.2863, 
              0.0151, 0.9999, 0.0058, 0.0058, 
              -0.3501, -0.0002, 0.9367, 0.0554, 
              0, 0, 0, 1;
  params.cam_tf_left_ = base_tf * sqrt_tf.inverse();
  params.cam_tf_right_ = base_tf * sqrt_tf;

  // read ROS parameters
  std::string cloud_topic;
  std::string cloud_frame;
  std::string svm_file_name;
  std::vector<double> workspace;
  std::vector<double> camera_pose;
  int cloud_type;
  bool parallel;

  node.param("parallel", parallel, true);
  node.param("cloud_topic", cloud_topic, CLOUD_TOPIC);
  node.param("cloud_frame", cloud_frame, CLOUD_FRAME);
  node.param("cloud_type", cloud_type, CLOUD_TYPE);
  node.param("svm_file_name", svm_file_name, SVM_FILE_NAME);
  node.param("num_threads", params.num_threads_, NUM_THREADS);
  node.param("num_samples", params.num_samples_, NUM_SAMPLES); 
  node.param("num_clouds", params.num_clouds_, NUM_CLOUDS);

  if (parallel) {
      double finger_width, hand_outer_diameter, hand_depth;
      node.param("finger_width", finger_width, FINGER_WIDTH);
      node.param("hand_outer_diameter", hand_outer_diameter, HAND_OUTER_DIAMETER);
      node.param("hand_depth", hand_depth, HAND_DEPTH);
      params.finger_hand_ = new ParallelHand(finger_width, hand_outer_diameter, hand_depth);
  }
  //TODO else

  node.param("init_bite", params.init_bite_, INIT_BITE);
  node.param("hand_height", params.hand_height_, HAND_HEIGHT);
  node.param("min_inliers", params.min_inliers_, MIN_HANDLE_INLIERS);
  node.getParam("workspace", workspace);
  node.getParam("camera_pose", camera_pose);
  node.param("plotting", params.plotting_mode_, 0);
  node.param("marker_lifetime", params.marker_lifetime_, 0.0);
  
  Eigen::Matrix4d R;
  for (int i=0; i < R.rows(); i++)
    R.row(i) << camera_pose[i*R.cols()], camera_pose[i*R.cols() + 1], camera_pose[i*R.cols() + 2], camera_pose[i*R.cols() + 3];  
    
  Eigen::VectorXd ws(6);
  ws << workspace[0], workspace[1], workspace[2], workspace[3], workspace[4], workspace[5];
  params.workspace_ = ws;
  
  std::cout << "-- Parameters --\n";
  std::cout << " Input\n";
  std::cout << "  cloud_topic: " << cloud_topic << "\n";
  std::cout << "  cloud_frame: " << cloud_frame << "\n";
  std::cout << "  cloud_type: " << CLOUD_TYPES[cloud_type] << "\n";
  std::cout << " Hand Search\n";  
  std::cout << "  workspace: " << ws.transpose() << "\n";
  std::cout << "  num_samples: " << params.num_samples_ << "\n";
  std::cout << "  num_threads: " << params.num_threads_ << "\n";
  std::cout << "  num_clouds: " << params.num_clouds_ << "\n";  
  std::cout << "  camera pose:\n" << R << std::endl;
  std::cout << " Robot Hand Model\n";
  //TODO: Make FingerGrasp printable.
 // std::cout << "  finger_width: " << params.finger_width_ << "\n";
 // std::cout << "  hand_outer_diameter: " << params.hand_outer_diameter_ << "\n";
 // std::cout << "  hand_depth: " << params.finger_width_ << "\n";
 // std::cout << "  init_bite: " << params.finger_width_ << "\n";
 // std::cout << "  hand_height: " << params.finger_width_ << "\n";
  std::cout << " Antipodal Grasps Prediction\n";
  std::cout << "  svm_file_name: " << svm_file_name << "\n";
  std::cout << " Handle Search\n";
  std::cout << "  min_inliers: " << params.min_inliers_ << "\n";
  std::cout << " Visualization\n";
  std::cout << "  plot_mode: " << PLOT_MODES[params.plotting_mode_] << "\n";
  std::cout << "  marker_lifetime: " << params.marker_lifetime_ << "\n";
  
  GraspLocalizer loc(node, cloud_topic, cloud_frame, cloud_type, svm_file_name, params);
  loc.localizeGrasps();
  
	return 0;
}
コード例 #25
0
 int testSQLiteDatabaseConnection()
 {
     SQLiteDatabaseConnection connection;
     QFile file("sqlitetest.db");
     
     std::cerr << "Removing database test file \"sqlitetest.db\"..." << std::endl;
     if (file.exists())
         file.remove();
     
     std::cerr << "Opening \"sqlitetest.db\"..." << std::endl;
     connection.open("sqlitetest.db");
     CHECK(connection.isDBOpen());
     
     std::cerr << "Closing database..." << std::endl;
     connection.close();
     CHECK(!connection.isDBOpen());
     
     std::cerr << "Reopening \"sqlitetest.db\"..." << std::endl;
     connection.open("sqlitetest.db");
     CHECK(connection.isDBOpen());
     
     RoutingNode node(25, 51.0, 7.0);
     std::cerr << "Save Node..." << std::endl;
     CHECK(connection.saveNode(node));
     node = RoutingNode(26, 51.5, 7.5);
     CHECK(connection.saveNode(node));
     CHECK(*connection.getNodeByID(26) == node);
     CHECK(*connection.getNodeByID(RoutingNode::convertIDToLongFormat(26)) == node);
     
     RoutingEdge edge(45, 25, 26);
     std::cerr << "Save Edge..." << std::endl;
     edge.setCycleBarrier(true);
     edge.setCyclewayType(5);
     CHECK(connection.saveEdge(edge, "Teststraße"));
     CHECK_EQ_TYPE(connection.getStreetName(edge), "Teststraße", QString);
     edge = RoutingEdge(46, 26, 25);
     CHECK(connection.saveEdge(edge));
     
     GPSPosition min(50.0, 6.0);
     GPSPosition max(52.0, 8.0);
     QVector<boost::shared_ptr<RoutingNode> > list = connection.getNodes(min, max);
     CHECK(!list.isEmpty());
     CHECK(list.size() == 2);
     
     std::cerr << "Node 0 from DB: " << *(list[0]) << std::endl;
     std::cerr << "Node 1 from DB: " << *(list[1]) << std::endl;
     CHECK((*list[0] == node) || (*list[1] == node));
     
     boost::minstd_rand generator(42u);
     boost::uniform_real<> uni_dist(50, 52);
     boost::variate_generator<boost::minstd_rand&, boost::uniform_real<> > uni(generator, uni_dist);
     
     std::cerr << "Inserting 10000 Nodes within one transaction..." << std::endl;
     bool successInsertManyNodes = true;
     CHECK(connection.beginTransaction());
     for (int i=0; i<10000; i++)
     {
         node = RoutingNode(i + 100, uni(), uni() - (51.0 - 7.0));
         successInsertManyNodes = successInsertManyNodes && connection.saveNode(node);
     }
     CHECK(successInsertManyNodes);
     CHECK(connection.endTransaction());
     std::cerr << "Hier erwartet: Resultcode 19 (-> Constraint failed)" << std::endl;
     CHECK(!connection.saveNode(node));
     
     boost::shared_ptr<RoutingEdge> dbEdge(connection.getEdgeByEdgeID(46));
     CHECK_EQ(edge, *dbEdge);
     
     QVector<boost::shared_ptr<RoutingEdge> > edgeList;
     edgeList = connection.getEdgesByStartNodeID(26);
     CHECK_EQ(edge, *edgeList[0]);
     edgeList = connection.getEdgesByStartNodeID(26);
     CHECK_EQ(edge, *edgeList[0]);
     
     edgeList = connection.getEdgesByEndNodeID(25);
     CHECK_EQ(edge, *edgeList[0]);
     edgeList = connection.getEdgesByEndNodeID(25);
     CHECK_EQ(edge, *edgeList[0]);
     
     
     std::cerr << "Inserting 10000 Edges within one transaction..." << std::endl;
     bool successInsertManyEdges = true;
     CHECK(connection.beginTransaction());
     for (int i=0; i<10000; i++)
     {
         edge = RoutingEdge(i + 100, i+99, i+100);
         successInsertManyEdges = successInsertManyEdges && connection.saveEdge(edge);
     }
     CHECK(successInsertManyEdges);
     CHECK(connection.endTransaction());
     std::cerr << "Hier erwartet: Resultcode 19 (-> Constraint failed)" << std::endl;
     CHECK(!connection.saveEdge(edge));
     
     
     edgeList = connection.getEdgesByStartNodeID(99);
     CHECK(!edgeList.isEmpty());
     edgeList = connection.getEdgesByStartNodeID(100);
     CHECK(!edgeList.isEmpty());
     
     CHECK(connection.beginTransaction());
     CHECK(connection.deleteEdge(99, 100));
     CHECK(connection.deleteEdge(100, 101));
     CHECK(connection.endTransaction());
     
     edgeList = connection.getEdgesByStartNodeID(99);
     CHECK(edgeList.isEmpty());
     edgeList = connection.getEdgesByStartNodeID(100);
     CHECK(edgeList.isEmpty());
     
     return EXIT_SUCCESS;
 }
コード例 #26
0
RenderTextControlMultiLine::~RenderTextControlMultiLine()
{
    if (node() && node()->inDocument())
        static_cast<HTMLTextAreaElement*>(node())->rendererWillBeDestroyed();
}
コード例 #27
0
 Trie(){
     nodes.push_back(node());
 }
コード例 #28
0
LayoutUnit RenderTextControlMultiLine::preferredContentWidth(float charWidth) const
{
    int factor = static_cast<HTMLTextAreaElement*>(node())->cols();
    return static_cast<LayoutUnit>(ceilf(charWidth * factor)) + scrollbarThickness();
}
コード例 #29
0
ファイル: defines.hpp プロジェクト: x37v/datajockey
 static Node encode(const QString& rhs) {
   Node node(rhs.toStdString());
   return node;
 }
コード例 #30
0
void CNcdServerReportManager::NodeSetAsInstalledRequestL( MCatalogsBaseMessage& aMessage )
    {
    HBufC8* input = HBufC8::NewLC( aMessage.InputLength() );
    TPtr8 inputPtr = input->Des();
    aMessage.ReadInput( inputPtr );
    RDesReadStream inputStream( *input );
    CleanupClosePushL( inputStream );

    TInt errorCode( inputStream.ReadInt32L() );
    CNcdNodeIdentifier* identifier( CNcdNodeIdentifier::NewLC( inputStream ) );

    CNcdReportManager& reportManager( ReportManagerL( aMessage ) );
    CNcdNode& node( Provider().NodeManager().NodeL( *identifier ) ); 
    CNcdNodeMetaData& metaData( node.NodeMetaDataL() );
    
    TNcdReportStatusInfo info( ENcdReportCreate, errorCode );
    // Use the node identifier to identify the content in install report.
    // Node id uniquely identifies the node that contains contents
    // that will be installed. One node may contains multiple contents but
    // they are all thought as one bundle, in one operation. Also, notice that 
    // multiple nodes can contain same metadata and same content.
    TNcdReportId reportId = 
        reportManager.RegisterInstallL( 
            identifier->NodeId(),
            metaData.Identifier(),
            info,
            metaData.Identifier().ServerUri(),
            metaData.Identifier().NodeNameSpace() );

    // Set access point for report.
    UpdateInstallReportAccessPointL( aMessage.Session().Context().FamilyId(),
                                     reportId,
                                     node,
                                     metaData,
                                     reportManager,
                                     HttpSessionL( aMessage.Session().Context() ) );    

    // Set the final success information directly into the report instead of
    // reporting other install statuses here.
    TNcdReportStatus status( ENcdReportSuccess );
    if ( errorCode == KErrNone )
        {
        status = ENcdReportSuccess;
        }
    else if ( errorCode == KErrCancel )
        {
        status = ENcdReportCancel;
        }
    else 
        {
        status = ENcdReportFail;
        }
    
    // Create the status info object with the given info.
    info.iStatus = status;
    info.iErrorCode = errorCode;
    
    reportManager.ReportInstallStatusL(
            reportId,
            info );
    
    CleanupStack::PopAndDestroy( identifier );
    CleanupStack::PopAndDestroy( &inputStream );
    CleanupStack::PopAndDestroy( input );

    aMessage.CompleteAndRelease( KErrNone );    
    }